Yii::error("Ошибка при расчёте прогноза: " . $e->getMessage(), __METHOD__);
continue;
}
+ $writeOffsForecastMap = [];
+ foreach ($writeOffsForecast as $itemForecast) {
+ $itemWeek = $itemForecast['week'];
+ $itemGuid = $itemForecast['product_id'];
+ $writeoffsForecast = $itemForecast['forecast'];
+ $writeOffsForecastMap[$itemWeek][$itemGuid] = $writeoffsForecast;
+
+ }
+ $existingRecords = [];
+ $records = Autoplannogramma::find()
+ ->where([
+ 'month' => $month,
+ 'year' => $year,
+ 'store_id' => $store->id,
+ ])
+ ->andWhere(['week' => array_unique(array_column($forecast, 'week'))])
+ ->all();
+
+ foreach ($records as $record) {
+ $existingRecords[$record->week . '_' . $record->product_id] = $record;
+ }
foreach ($forecast as $item) {
- $model = new Autoplannogramma();
- $model->month = $month;
- $model->year = $year;
- $model->week = $item['week'];
- $model->product_id = $item['product_id'];
- $model->store_id = $item['store_id'];
- $model->quantity = $item['forecast_week_pieces'];
- $model->quantity_forecast = $item['forecast_week_pieces'];
- $model->is_archive = false;
- $model->capacity_type = 1;
- if (isset($writeOffsForecastMap[$item['week']]) && isset($writeOffsForecastMap[$item['week']][$item['product_id']])) {
- $model->writeoffs_forecast = $writeOffsForecastMap[$item['week']][$item['product_id']];
- } else {
- $model->writeoffs_forecast = 0;
+ $key = $item['week'] . '_' . $item['product_id'];
+ $model = $existingRecords[$key] ?? null;
+ $this->stderr(implode("\n", $item), BaseConsole::FG_GREEN);
+ if (!$model) {
+ $model = new Autoplannogramma();
+ $model->month = $month;
+ $model->year = $year;
+ $model->week = $item['week'];
+ $model->product_id = $item['product_id'];
+ $model->store_id = $item['store_id'];
+ $model->is_archive = false;
+ $model->capacity_type = 1;
+ $model->quantity = $item['forecast_week_pieces'];
++ if (isset($writeOffsForecastMap[$item['week']]) && isset($writeOffsForecastMap[$item['week']][$item['product_id']])) {
++ $model->writeoffs_forecast = $writeOffsForecastMap[$item['week']][$item['product_id']];
++ } else {
++ $model->writeoffs_forecast = 0;
++ }
+ }
+
++
++
+ $needsUpdate = $model->quantity_forecast != $item['forecast_week_pieces'];
+
+ if ($needsUpdate) {
+ $model->quantity_forecast = $item['forecast_week_pieces'];
}
if (!$model->save()) {