$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,