From: Vladimir Fomichev Date: Wed, 6 Aug 2025 10:00:54 +0000 (+0300) Subject: Перезапись данных X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=3c312b4dec394b53cf72a8f095cf243487269171;p=erp24_rep%2Fyii-erp24%2F.git Перезапись данных --- diff --git a/erp24/controllers/Products1cNomenclatureActualityController.php b/erp24/controllers/Products1cNomenclatureActualityController.php index 55a2d1f6..4ca22482 100644 --- a/erp24/controllers/Products1cNomenclatureActualityController.php +++ b/erp24/controllers/Products1cNomenclatureActualityController.php @@ -258,27 +258,74 @@ class Products1cNomenclatureActualityController extends Controller $userId = Yii::$app->user->id; $createdAt = date('Y-m-d H:i:s'); - $rows = []; + $toInsert = []; + $toDeactivate = []; + + $existingActives = Products1cNomenclatureActuality::find() + ->where(['guid' => $productIds, 'active' => 1]) + ->indexBy('guid') + ->all(); + foreach ($productIds as $pid) { - $rows[] = [ - 'guid' => $pid, - 'date_from' => $from, - 'date_to' => $to, - 'active' => 1, - 'created_at' => $createdAt, - 'created_by' => $userId, - ]; + $needNewRecord = true; + + if (isset($existingActives[$pid])) { + $existing = $existingActives[$pid]; + + if ($existing->date_from == $from && $existing->date_to == $to) { + $needNewRecord = false; + } else { + $toDeactivate[] = $existing->id; + } + } + + if ($needNewRecord) { + $toInsert[] = [ + 'guid' => $pid, + 'date_from' => $from, + 'date_to' => $to, + 'active' => 1, + 'created_at' => $createdAt, + 'created_by' => $userId, + ]; + } } - Yii::$app->db->createCommand() - ->batchInsert( - Products1cNomenclatureActuality::tableName(), - ['guid','date_from','date_to','active','created_at','created_by'], - $rows - ) - ->execute(); + $transaction = Yii::$app->db->beginTransaction(); + try { + if (!empty($toDeactivate)) { + Products1cNomenclatureActuality::updateAll( + [ + 'active' => 0, + 'updated_at' => $createdAt, + 'updated_by' => $userId, + ], + ['id' => $toDeactivate] + ); + } + + if (!empty($toInsert)) { + Yii::$app->db->createCommand() + ->batchInsert( + Products1cNomenclatureActuality::tableName(), + ['guid','date_from','date_to','active','created_at','created_by'], + $toInsert + ) + ->execute(); + } - Yii::$app->session->setFlash('success', 'Таблица актуальности заполнена.'); + $transaction->commit(); + + $message = 'Таблица актуальности обновлена. '; + $message .= 'Добавлено: ' . count($toInsert) . '; '; + $message .= 'Деактивировано: ' . count($toDeactivate); + + Yii::$app->session->setFlash('success', $message); + + } catch (\Exception $e) { + $transaction->rollBack(); + Yii::$app->session->setFlash('error', 'Ошибка: ' . $e->getMessage()); + } return $this->render('add-activity', [ 'historyDays' => $historyDays, 'intervalMonths' => $intervalMonths,