]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Правки ревью origin/feature_fomichev_erp-487_add_admin_position_dictionary
authorVladimir Fomichev <vladimir.fomichev@erp-flowers.ru>
Mon, 10 Nov 2025 15:15:40 +0000 (18:15 +0300)
committerVladimir Fomichev <vladimir.fomichev@erp-flowers.ru>
Mon, 10 Nov 2025 15:15:40 +0000 (18:15 +0300)
erp24/migrations/m251201_120000_replace_salary_with_monthly_and_daily_in_employee_position.php
erp24/migrations/m251201_120001_add_employee_position_id_to_employee_payment.php
erp24/records/Admin.php
erp24/records/EmployeePayment.php
erp24/records/EmployeePosition.php
erp24/services/SalarySyncService.php

index 8a812f8a5ab460c15bbcfe8664ad413890d3433c..74b9f1c293f2455922b6f3363812c00f8f799749 100644 (file)
@@ -11,24 +11,32 @@ class m251201_120000_replace_salary_with_monthly_and_daily_in_employee_position
      */
     public function safeUp()
     {
-        $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+        $transaction = $this->db->beginTransaction();
+        try {
+            $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
 
-        // Добавляем поле monthly_salary
-        if (isset($tableSchema) && !isset($tableSchema->columns['monthly_salary'])) {
-            $this->addColumn(self::TABLE_NAME, 'monthly_salary', $this->decimal(10, 2)->null()->comment('Месячный оклад'));
-        }
+            // Добавляем поле monthly_salary
+            if (isset($tableSchema) && !isset($tableSchema->columns['monthly_salary'])) {
+                $this->addColumn(self::TABLE_NAME, 'monthly_salary', $this->decimal(10, 2)->null()->comment('Месячный оклад'));
+            }
 
-        // Добавляем поле daily_payment
-        if (isset($tableSchema) && !isset($tableSchema->columns['daily_payment'])) {
-            $this->addColumn(self::TABLE_NAME, 'daily_payment', $this->decimal(10, 2)->null()->comment('Подневная оплата'));
-        }
+            // Добавляем поле daily_payment
+            if (isset($tableSchema) && !isset($tableSchema->columns['daily_payment'])) {
+                $this->addColumn(self::TABLE_NAME, 'daily_payment', $this->decimal(10, 2)->null()->comment('Подневная оплата'));
+            }
 
-        // Переносим данные из salary в monthly_salary, если salary существует
-        if (isset($tableSchema) && isset($tableSchema->columns['salary'])) {
-            $this->execute("UPDATE " . self::TABLE_NAME . " SET monthly_salary = salary WHERE salary IS NOT NULL AND monthly_salary IS NULL");
-            
-            // Удаляем старое поле salary
-            $this->dropColumn(self::TABLE_NAME, 'salary');
+            // Переносим данные из salary в monthly_salary, если salary существует
+            if (isset($tableSchema) && isset($tableSchema->columns['salary'])) {
+                $this->execute("UPDATE " . self::TABLE_NAME . " SET monthly_salary = salary WHERE salary IS NOT NULL AND monthly_salary IS NULL");
+                
+                // Удаляем старое поле salary
+                $this->dropColumn(self::TABLE_NAME, 'salary');
+            }
+
+            $transaction->commit();
+        } catch (\Exception $e) {
+            $transaction->rollBack();
+            throw $e;
         }
     }
 
@@ -37,24 +45,32 @@ class m251201_120000_replace_salary_with_monthly_and_daily_in_employee_position
      */
     public function safeDown()
     {
-        $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
-
-        // Восстанавливаем поле salary
-        if (isset($tableSchema) && !isset($tableSchema->columns['salary'])) {
-            $this->addColumn(self::TABLE_NAME, 'salary', $this->integer()->null()->comment('Зарплата'));
-            
-            // Переносим данные обратно из monthly_salary в salary
-            $this->execute("UPDATE " . self::TABLE_NAME . " SET salary = CAST(monthly_salary AS INTEGER) WHERE monthly_salary IS NOT NULL");
-        }
+        $transaction = $this->db->beginTransaction();
+        try {
+            $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
 
-        // Удаляем поле daily_payment
-        if (isset($tableSchema) && isset($tableSchema->columns['daily_payment'])) {
-            $this->dropColumn(self::TABLE_NAME, 'daily_payment');
-        }
+            // Восстанавливаем поле salary
+            if (isset($tableSchema) && !isset($tableSchema->columns['salary'])) {
+                $this->addColumn(self::TABLE_NAME, 'salary', $this->integer()->null()->comment('Зарплата'));
+                
+                // Переносим данные обратно из monthly_salary в salary
+                $this->execute("UPDATE " . self::TABLE_NAME . " SET salary = CAST(monthly_salary AS INTEGER) WHERE monthly_salary IS NOT NULL");
+            }
+
+            // Удаляем поле daily_payment
+            if (isset($tableSchema) && isset($tableSchema->columns['daily_payment'])) {
+                $this->dropColumn(self::TABLE_NAME, 'daily_payment');
+            }
+
+            // Удаляем поле monthly_salary
+            if (isset($tableSchema) && isset($tableSchema->columns['monthly_salary'])) {
+                $this->dropColumn(self::TABLE_NAME, 'monthly_salary');
+            }
 
-        // Удаляем поле monthly_salary
-        if (isset($tableSchema) && isset($tableSchema->columns['monthly_salary'])) {
-            $this->dropColumn(self::TABLE_NAME, 'monthly_salary');
+            $transaction->commit();
+        } catch (\Exception $e) {
+            $transaction->rollBack();
+            throw $e;
         }
     }
 }
index 9191d175fbc84e82d04cdba6520ecdd2b4a4065e..d352407fa15f86011f44f17fe6d70adddc35d54c 100644 (file)
@@ -11,29 +11,37 @@ class m251201_120001_add_employee_position_id_to_employee_payment extends Migrat
      */
     public function safeUp()
     {
-        $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
-
-        // Добавляем поле employee_position_id
-        if (isset($tableSchema) && !isset($tableSchema->columns['employee_position_id'])) {
-            $this->addColumn(self::TABLE_NAME, 'employee_position_id', $this->integer()->null()->comment('ID должности из employee_position'));
-            
-            // Добавляем внешний ключ
-            $this->addForeignKey(
-                'fk-employee_payment-employee_position_id',
-                self::TABLE_NAME,
-                'employee_position_id',
-                'erp24.employee_position',
-                'id',
-                'SET NULL',
-                'CASCADE'
-            );
-            
-            // Добавляем индекс для улучшения производительности
-            $this->createIndex(
-                'idx-employee_payment-employee_position_id',
-                self::TABLE_NAME,
-                'employee_position_id'
-            );
+        $transaction = $this->db->beginTransaction();
+        try {
+            $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+
+            // Добавляем поле employee_position_id
+            if (isset($tableSchema) && !isset($tableSchema->columns['employee_position_id'])) {
+                $this->addColumn(self::TABLE_NAME, 'employee_position_id', $this->integer()->null()->comment('ID должности из employee_position'));
+                
+                // Добавляем внешний ключ
+                $this->addForeignKey(
+                    'fk-employee_payment-employee_position_id',
+                    self::TABLE_NAME,
+                    'employee_position_id',
+                    'erp24.employee_position',
+                    'id',
+                    'SET NULL',
+                    'CASCADE'
+                );
+                
+                // Добавляем индекс для улучшения производительности
+                $this->createIndex(
+                    'idx-employee_payment-employee_position_id',
+                    self::TABLE_NAME,
+                    'employee_position_id'
+                );
+            }
+
+            $transaction->commit();
+        } catch (\Exception $e) {
+            $transaction->rollBack();
+            throw $e;
         }
     }
 
@@ -42,21 +50,29 @@ class m251201_120001_add_employee_position_id_to_employee_payment extends Migrat
      */
     public function safeDown()
     {
-        $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+        $transaction = $this->db->beginTransaction();
+        try {
+            $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
 
-        // Удаляем индекс
-        if (isset($tableSchema) && isset($tableSchema->columns['employee_position_id'])) {
-            $this->dropIndex('idx-employee_payment-employee_position_id', self::TABLE_NAME);
-        }
+            // Удаляем индекс
+            if (isset($tableSchema) && isset($tableSchema->columns['employee_position_id'])) {
+                $this->dropIndex('idx-employee_payment-employee_position_id', self::TABLE_NAME);
+            }
 
-        // Удаляем внешний ключ
-        if (isset($tableSchema) && isset($tableSchema->columns['employee_position_id'])) {
-            $this->dropForeignKey('fk-employee_payment-employee_position_id', self::TABLE_NAME);
-        }
+            // Удаляем внешний ключ
+            if (isset($tableSchema) && isset($tableSchema->columns['employee_position_id'])) {
+                $this->dropForeignKey('fk-employee_payment-employee_position_id', self::TABLE_NAME);
+            }
+
+            // Удаляем поле employee_position_id
+            if (isset($tableSchema) && isset($tableSchema->columns['employee_position_id'])) {
+                $this->dropColumn(self::TABLE_NAME, 'employee_position_id');
+            }
 
-        // Удаляем поле employee_position_id
-        if (isset($tableSchema) && isset($tableSchema->columns['employee_position_id'])) {
-            $this->dropColumn(self::TABLE_NAME, 'employee_position_id');
+            $transaction->commit();
+        } catch (\Exception $e) {
+            $transaction->rollBack();
+            throw $e;
         }
     }
 }
index d493b0860dcd961d01b7fc12594fde42adbe7b74..65f295a0248789282efbbe14d99237e2b406dbca 100755 (executable)
@@ -4,6 +4,7 @@ declare(strict_types = 1);
 namespace yii_app\records;
 
 use svay\FaceDetector;
+use Yii;
 use yii\base\NotSupportedException;
 use yii\db\ActiveQueryInterface;
 use yii\db\ActiveRecord;
@@ -778,10 +779,19 @@ class Admin extends ActiveRecord implements IdentityInterface
             $oldPositionId = $changedAttributes['employee_position_id'] ?? null;
             $newPositionId = $this->employee_position_id;
 
-            // Если должность была добавлена или изменена
-            if ($newPositionId && ($oldPositionId != $newPositionId || $insert)) {
-                $syncService = new SalarySyncService();
-                $syncService->createPaymentFromPosition($this->id);
+            // Если должность была добавлена или изменена, и сотрудник не уволен
+            if ($newPositionId && ($oldPositionId != $newPositionId || $insert) && $this->group_id != AdminGroup::GROUP_FIRED) {
+                try {
+                    $syncService = new SalarySyncService();
+                    $result = $syncService->createPaymentFromPosition($this->id);
+                    
+                    if ($result) {
+                        Yii::info("Автоматически создана запись EmployeePayment для admin_id={$this->id}, position_id={$newPositionId}", 'salary-sync');
+                    }
+                } catch (\Exception $e) {
+                    Yii::error("Ошибка автоматической синхронизации оклада для admin_id={$this->id}: " . $e->getMessage(), 'salary-sync');
+                    // Не бросаем исключение, чтобы не прервать сохранение Admin
+                }
             }
         }
     }
index 04c57f9ae83b9ed030ef8f859351a85da07d8276..17817732324f66e134eb79ec8c4036540680e2eb 100755 (executable)
@@ -94,7 +94,7 @@ class EmployeePayment extends \yii\db\ActiveRecord
     public function beforeValidate()
     {
         if (get_called_class() === self::class) {
-            $this->creator_id = $_SESSION['admin_id'] ?? null;
+            $this->creator_id = Yii::$app->user->id ?? null;
             if ($this->admin) {
                 $this->admin_group_id = $this->admin->group_id;
                 // Автоматически заполняем employee_position_id из Admin, если не заполнено
index 3697ab15724163e21a60a878e8d3c97b5cc69510..dc29f5378f41e76bfb15b41cbad3a52c83b8ba98 100755 (executable)
@@ -155,9 +155,18 @@ class EmployeePosition extends \yii\db\ActiveRecord
 
         // Если оклады изменились и они заполнены, синхронизируем для всех сотрудников
         if ($salaryChanged && $this->monthly_salary !== null && $this->daily_payment !== null) {
-            $syncService = new SalarySyncService();
-            $creatorId = $this->updated_by ?? $_SESSION['admin_id'] ?? null;
-            $syncService->syncEmployeesByPosition($this->id, $creatorId);
+            try {
+                $syncService = new SalarySyncService();
+                $creatorId = $this->updated_by ?? Yii::$app->user->id ?? null;
+                $result = $syncService->syncEmployeesByPosition($this->id, $creatorId);
+                
+                if ($result['success']) {
+                    Yii::info("Автоматическая синхронизация окладов для должности ID={$this->id}: {$result['message']}", 'salary-sync');
+                }
+            } catch (\Exception $e) {
+                Yii::error("Ошибка автоматической синхронизации окладов для должности ID={$this->id}: " . $e->getMessage(), 'salary-sync');
+                // Не бросаем исключение, чтобы не прервать сохранение EmployeePosition
+            }
         }
     }
 }
index ab3a5b3c67a9c64f0ac040aad10fa6d3b73a1829..6512ec6c4c1b2f5fb6561de858a20f48e663ebce 100644 (file)
@@ -23,7 +23,7 @@ class SalarySyncService
     public function syncAllEmployeesFromPositions($creatorId = null): array
     {
         if ($creatorId === null) {
-            $creatorId = $_SESSION['admin_id'] ?? null;
+            $creatorId = Yii::$app->user->id ?? null;
         }
 
         if (!$creatorId) {
@@ -121,7 +121,7 @@ class SalarySyncService
     public function createPaymentFromPosition($adminId, $creatorId = null, $date = null): ?EmployeePayment
     {
         if ($creatorId === null) {
-            $creatorId = $_SESSION['admin_id'] ?? null;
+            $creatorId = Yii::$app->user->id ?? null;
         }
 
         if (!$creatorId) {
@@ -178,7 +178,7 @@ class SalarySyncService
     public function syncEmployeesByPosition($positionId, $creatorId = null): array
     {
         if ($creatorId === null) {
-            $creatorId = $_SESSION['admin_id'] ?? null;
+            $creatorId = Yii::$app->user->id ?? null;
         }
 
         if (!$creatorId) {