$monthEnd = date("Y-m-t 23:59:59", strtotime($year . '-' . $month . '-1'));
$motivations = Motivation::find()->where(['year' => $year, 'month' => $month])->indexBy('store_id')->all();
- $motivationValueGroup = MotivationValueGroup::find()->where(['alias' => 'fact'])->one();
$exportImportTables = ExportImportTable::find()->select(['export_val', 'entity_id'])->where(['entity' => 'city_store',
'entity_id' => array_keys($motivations), 'export_id' => 1])->indexBy('entity_id')->all();
/** @var $exportImportTables ExportImportTable[] */
foreach ($exportImportTables as $store_id => $store_guid) {
if (isset($motivations[$store_id])) {
- $writeOffs = WriteOffs::find()->select(['sum(summ) as total', 'type'])
+ $writeOffs = WriteOffs::find()->alias('wo')->select(['wo.type', 'wo.date', 'wop.product_id', 'wop.quantity'])
+ ->rightJoin('write_offs_products wop', 'wop.write_offs_id = wo.id')
+ ->where(['between', 'wo.date', $monthStart, $monthEnd])
+ ->andWhere(['wo.store_id' => $store_guid])
+ ->asArray()->all();
+
+ $selfCostProduct = SelfCostProduct::find()->select(['price', 'product_guid', 'date'])
->where(['between', 'date', $monthStart, $monthEnd])
- ->andWhere(['store_id' => $store_guid])
- ->groupBy(['type'])
- ->indexBy('type')
+ ->andWhere(['store_id' => $store_id])
->asArray()->all();
+
+ $selfCostProductMap = [];
+ foreach ($selfCostProduct as $scp) {
+ $selfCostProductMap[$scp['date']][$scp['product_guid']] = floatval($scp['price']);
+ }
+
foreach (MotivationCostsItem::writeOffsToMotivationItemArray() as $key => $motivationItemType) {
- $data = $writeOffs[$key] ?? [];
+ $sum = 0;
+ foreach($writeOffs as $data) {
+ if (($data['type'] ?? '') == $key) {
+ $sum += ($selfCostProductMap[date("Y-m-d", strtotime($data['date']))][$data['product_id']] ?? 0)
+ * ($data['quantity'] ?? 0);
+ }
+ }
+
$motivationCostsItem = MotivationCostsItem::find()->where(['name' => $motivationItemType])->one();
/** @var $motivationCostsItem MotivationCostsItem */
$correction = self::getMotivationValue($motivations[$store_id]->id, 8, $motivationCostsItem->code);
- $motivationValue = MotivationValue::find()->where(['motivation_id' => $motivations[$store_id]->id,
- 'motivation_group_id' => $motivationValueGroup->id, 'value_id' => $motivationCostsItem->code])->one();
- if (!$motivationValue) {
- $motivationValue = new MotivationValue;
- $motivationValue->motivation_id = $motivations[$store_id]->id;
- $motivationValue->motivation_group_id = $motivationValueGroup->id;
- $motivationValue->value_id = $motivationCostsItem->code;
- $motivationValue->value_type = $motivationCostsItem->data_type;
- }
- $motivationValue->value_float = ($data['total'] ?? 0) + $correction;
- $motivationValue->save();
- if ($motivationValue->getErrors()) {
- throw new \Exception(Json::encode($motivationValue->getErrors()));
- }
+ self::saveOrUpdateMotivationValue($motivations[$store_id]->id, 'fact',
+ $motivationCostsItem->code, 'float', $sum + $correction);
}
}
}