/
delphin
/
CatRW
Обзор
Документация
Войти
/
delphin
/
CatRW
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
api/ModelSubtypeService.php
298 строк
12 KB
delphin
start project
02 мар 2026, 09:14
Верифицирован
02 мар 2026, 09:14
4b0ee03
Код
Авторство
О чём код?
<?php // /api/ModelSubtypeService.php - СЕРВИС ПОДТИПОВ МОДЕЛЕЙ class ModelSubtypeService { // Получить все подтипы public static function getAll($typeCode = null) { try { if ($typeCode) { return Database::select( "SELECT ms.*, mt.code as type_code FROM model_subtypes ms LEFT JOIN model_types mt ON ms.type_code = mt.code WHERE ms.type_code = :typeCode ORDER BY ms.code", [':typeCode' => $typeCode] ); } else { return Database::select( "SELECT ms.*, mt.code as type_code FROM model_subtypes ms LEFT JOIN model_types mt ON ms.type_code = mt.code ORDER BY ms.type_code, ms.code" ); } } catch (Exception $e) { error_log("ModelSubtypeService::getAll error: " . $e->getMessage()); return []; } } // Получить один подтип public static function get($code) { try { return Database::selectOne( "SELECT ms.*, mt.code as type_code FROM model_subtypes ms LEFT JOIN model_types mt ON ms.type_code = mt.code WHERE ms.code = :code", [':code' => $code] ); } catch (Exception $e) { error_log("ModelSubtypeService::get error for code '$code': " . $e->getMessage()); return null; } } // Добавить подтип public static function add($data) { try { if (empty($data['code'])) { throw new Exception("Код обязателен"); } if (empty($data['type_code'])) { throw new Exception("Код типа обязателен"); } // Проверяем существование типа $type = Database::selectOne( "SELECT code FROM model_types WHERE code = ?", [$data['type_code']] ); if (!$type) { throw new Exception("Тип модели не найден"); } // Проверка уникальности $existing = Database::selectOne( "SELECT code FROM model_subtypes WHERE code = ?", [$data['code']] ); if ($existing) { throw new Exception("Подтип с таким кодом уже существует"); } // Очистка данных $cleanData = [ 'code' => trim($data['code']), 'type_code' => trim($data['type_code']) ]; return Database::insert('model_subtypes', $cleanData); } catch (Exception $e) { error_log("ModelSubtypeService::add error: " . $e->getMessage()); throw $e; } } // Обновить подтип (только код или тип) public static function update($oldCode, $data) { try { error_log("=== ModelSubtypeService::update() START ==="); error_log("Updating model subtype from code: $oldCode"); error_log("Data: " . print_r($data, true)); // Проверяем существование $subtype = self::get($oldCode); if (!$subtype) { error_log("ERROR: Model subtype not found code: $oldCode"); throw new Exception("Подтип модели не найден"); } $newCode = !empty($data['code']) ? trim($data['code']) : $oldCode; $newTypeCode = !empty($data['type_code']) ? trim($data['type_code']) : $subtype['type_code']; // Если ничего не меняем if ($newCode === $oldCode && $newTypeCode === $subtype['type_code']) { throw new Exception("Нет изменений для обновления"); } // Проверяем уникальность нового кода (если меняем) if ($newCode !== $oldCode) { $existing = Database::selectOne( "SELECT code FROM model_subtypes WHERE code = :code AND code != :oldCode", [':code' => $newCode, ':oldCode' => $oldCode] ); if ($existing) { throw new Exception("Подтип с таким кодом уже существует"); } // Проверяем, есть ли модели этого подтипа $modelsCount = Database::selectOne( "SELECT COUNT(*) as cnt FROM catalog_models WHERE subtype_code = :code", [':code' => $oldCode] ); if ($modelsCount && $modelsCount['cnt'] > 0) { throw new Exception("Нельзя изменить код: есть модели этого подтипа"); } } // Если меняем тип - проверяем существование нового типа if ($newTypeCode !== $subtype['type_code']) { $typeExists = Database::selectOne( "SELECT code FROM model_types WHERE code = :code", [':code' => $newTypeCode] ); if (!$typeExists) { error_log("ERROR: New type not found"); throw new Exception("Тип модели не найден"); } } // Обновляем данные $cleanData = [ 'code' => $newCode, 'type_code' => $newTypeCode ]; error_log("Clean data for update: " . print_r($cleanData, true)); $result = Database::update( 'model_subtypes', $cleanData, 'code = :oldCode', ['oldCode' => $oldCode] ); error_log("Update result: $result rows affected"); error_log("=== ModelSubtypeService::update() SUCCESS ==="); return $result; } catch (Exception $e) { error_log("ModelSubtypeService::update ERROR: " . $e->getMessage()); throw $e; } } // Удалить подтип public static function delete($code) { try { error_log("ModelSubtypeService::delete called for code: " . $code); // 1. Проверяем существование подтипа $subtype = self::get($code); if (!$subtype) { throw new Exception("Подтип модели '$code' не найден"); } error_log("Subtype found: " . $subtype['code']); // 2. Проверяем, есть ли модели этого подтипа $modelsCount = Database::selectOne( "SELECT COUNT(*) as cnt FROM catalog_models WHERE subtype_code = :code", [':code' => $code] ); error_log("Models count: " . ($modelsCount['cnt'] ?? 0)); if ($modelsCount && $modelsCount['cnt'] > 0) { throw new Exception("Нельзя удалить подтип: есть модели этого подтипа"); } // 3. Удаляем подтип error_log("Deleting model subtype from database..."); $result = Database::delete('model_subtypes', 'code = :code', [':code' => $code]); error_log("Database delete result: " . $result . " rows affected"); return [ 'type' => 'deleted', 'message' => 'Подтип модели удалён' ]; } catch (Exception $e) { error_log("ModelSubtypeService::delete ERROR for code '$code': " . $e->getMessage()); throw $e; } } // Поиск public static function search($query, $typeCode = null) { try { if (empty($query)) { return $typeCode ? self::getAll($typeCode) : self::getAll(); } $searchPattern = "%" . $query . "%"; if ($typeCode) { return Database::select( "SELECT ms.*, mt.code as type_code FROM model_subtypes ms LEFT JOIN model_types mt ON ms.type_code = mt.code WHERE ms.type_code = ? AND ms.code LIKE ? ORDER BY ms.code", [$typeCode, $searchPattern] ); } else { return Database::select( "SELECT ms.*, mt.code as type_code FROM model_subtypes ms LEFT JOIN model_types mt ON ms.type_code = mt.code WHERE ms.code LIKE ? OR mt.code LIKE ? ORDER BY ms.type_code, ms.code", [$searchPattern, $searchPattern] ); } } catch (Exception $e) { error_log("ModelSubtypeService::search error for query '$query': " . $e->getMessage()); return []; } } // Получить статистику public static function getStats($code = null) { try { if ($code) { // Статистика для конкретного подтипа $result = Database::selectOne(" SELECT (SELECT COUNT(*) FROM catalog_models WHERE subtype_code = :code) as models_count ", [':code' => $code]); return [ 'models_count' => $result['models_count'] ?? 0 ]; } else { // Общая статистика $result = Database::selectOne(" SELECT COUNT(*) as total, COUNT(DISTINCT type_code) as types_count FROM model_subtypes "); return [ 'total' => $result['total'] ?? 0, 'types_count' => $result['types_count'] ?? 0 ]; } } catch (Exception $e) { error_log("ModelSubtypeService::getStats error: " . $e->getMessage()); return $code ? ['models_count' => 0] : ['total' => 0, 'types_count' => 0]; } } // Получить подтипы для типа public static function getByType($typeCode) { try { return Database::select( "SELECT * FROM model_subtypes WHERE type_code = :typeCode ORDER BY code", [':typeCode' => $typeCode] ); } catch (Exception $e) { error_log("ModelSubtypeService::getByType error for type '$typeCode': " . $e->getMessage()); return []; } } } ?>