From: Vladimir Fomichev Date: Wed, 15 Oct 2025 11:20:39 +0000 (+0300) Subject: Добавление в очередь X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=e1d00f8a5d0cabe3a81d0f7436ff7576f2b529a7;p=erp24_rep%2Fyii-erp24%2F.git Добавление в очередь --- diff --git a/erp24/api2/controllers/DataController.php b/erp24/api2/controllers/DataController.php index d8c49c1c..921dad87 100644 --- a/erp24/api2/controllers/DataController.php +++ b/erp24/api2/controllers/DataController.php @@ -9,6 +9,7 @@ use yii\helpers\ArrayHelper; use yii\helpers\Json; use yii_app\helpers\ClientHelper; use yii_app\helpers\SalaryHelper; +use yii_app\jobs\SendRequestUploadDataToJob; use yii_app\records\Admin; use yii_app\records\AdminGroup; use yii_app\records\AnalystsBusinessOperations; @@ -989,1548 +990,3062 @@ class DataController extends BaseController PHP_EOL . 'result empty', FILE_APPEND); return $this->asJson(['error' => ['code' => 400, 'message' => 'result empty']]); } - $mess['request'] = $result; - $requestIdText = ''; - if (!empty($result["request_id"])) { - $requestIdText = $result["request_id"]; - $fl = "request_id_" . $result["request_id"]; - } else { - $fl = time(); - } - //InfoLogService::setInfoLog(__FILE__, __LINE__, 'upload_' . $fl . '.json' , 'info_id_25_1'); - - file_put_contents(self::OUT_DIR . '/upload_' . $fl . '.json', PHP_EOL . $request); - - try { - - if (!empty($result['error'])) { - file_put_contents(self::OUT_DIR . '/error_upload.txt', - PHP_EOL . json_encode($result["error"], JSON_UNESCAPED_UNICODE), FILE_APPEND); - } - $mess["result"] = true; - $checks_dell = ""; - $requestId = time(); - if (array_key_exists("request_id", $result) && !empty($result["request_id"])) { - $requestId = $result["request_id"]; - } - $type_price = "Розничная цена"; - - if (!empty($requestId)) { - $apiCron = ApiCron::find()->select(['json_post'])->where(['request_id' => $requestId])->one(); - if ($apiCron) { - $jsn = json_decode($apiCron->json_post, true, 512, JSON_UNESCAPED_UNICODE); - $start_time = $jsn["checks"]["start_time"] ?? date('Y-m-d 00:00:00', time() - 3 * 86400); - $end_time = $jsn["checks"]["end_time"] ?? date('Y-m-d 00:00:00', time()); - $checks_dell = $jsn["checks_dell"] ?? ""; - $type_price = $jsn["prices"]["type_price"] ?? "Розничная цена"; - - ApiCron::updateAll(['status' => 1, 'date_up' => date('Y-m-d H:i:s')], - ['and', ['status' => 0], ['request_id' => $requestId]]); - -// file_put_contents(self::OUT_DIR . '/request_api_cron.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . "request_id=$requestId $start_time - $end_time ", FILE_APPEND); - } - } - - if (!empty($result['stores'])) { - $products1cByTip = Products1c::find() - ->select(['id', 'tip']) - ->andWhere(['tip' => ['kkms', 'terminals', 'city_store']]) - ->groupBy(['tip', 'id']) - ->asArray() - ->all(); - $products1cByTipMap = []; - foreach ($products1cByTip as $item) { - $products1cByTipMap[$item['tip']][] = $item['id']; - } - $existTerminals = Terminals::find() - ->indexBy('id') - ->asArray() - ->column(); - - foreach ($result['stores'] as $gi => $arr) { - if (!in_array($arr["id"], $products1cByTipMap['city_store'])) { - $products1c = new Products1c; - $products1c->id = $arr["id"]; - $products1c->tip = 'city_store'; - $products1c->name = $arr["name"]; - $products1c->code = $arr["code"]; - $products1c->save(); - if ($products1c->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 2, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } - - if ($arr["terminals"]) { - $k = 0; - foreach ($arr["terminals"] as $gi2 => $arr2) { - if (!in_array($arr2['id'], $products1cByTipMap['terminals'])) { - $products1c2 = new Products1c; - $products1c2->id = $arr2['id']; - $products1c2->tip = 'terminals'; - $products1c2->name = $arr2["name"]; - $products1c2->code = $arr2["code"]; - $products1c2->save(); - if ($products1c2->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 3, "error" => $products1c2->getErrors()], JSON_UNESCAPED_UNICODE)); - Yii::error(''); - } - } +// $mess['request'] = $result; +// $requestIdText = ''; +// if (!empty($result["request_id"])) { +// $requestIdText = $result["request_id"]; +// $fl = "request_id_" . $result["request_id"]; +// } else { +// $fl = time(); +// } +// //InfoLogService::setInfoLog(__FILE__, __LINE__, 'upload_' . $fl . '.json' , 'info_id_25_1'); +// +// file_put_contents(self::OUT_DIR . '/upload_' . $fl . '.json', PHP_EOL . $request); +// +// try { +// +// if (!empty($result['error'])) { +// file_put_contents(self::OUT_DIR . '/error_upload.txt', +// PHP_EOL . json_encode($result["error"], JSON_UNESCAPED_UNICODE), FILE_APPEND); +// } +// $mess["result"] = true; +// $checks_dell = ""; +// $requestId = time(); +// if (array_key_exists("request_id", $result) && !empty($result["request_id"])) { +// $requestId = $result["request_id"]; +// } +// $type_price = "Розничная цена"; +// +// if (!empty($requestId)) { +// $apiCron = ApiCron::find()->select(['json_post'])->where(['request_id' => $requestId])->one(); +// if ($apiCron) { +// $jsn = json_decode($apiCron->json_post, true, 512, JSON_UNESCAPED_UNICODE); +// $start_time = $jsn["checks"]["start_time"] ?? date('Y-m-d 00:00:00', time() - 3 * 86400); +// $end_time = $jsn["checks"]["end_time"] ?? date('Y-m-d 00:00:00', time()); +// $checks_dell = $jsn["checks_dell"] ?? ""; +// $type_price = $jsn["prices"]["type_price"] ?? "Розничная цена"; +// +// ApiCron::updateAll(['status' => 1, 'date_up' => date('Y-m-d H:i:s')], +// ['and', ['status' => 0], ['request_id' => $requestId]]); +// +//// file_put_contents(self::OUT_DIR . '/request_api_cron.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . "request_id=$requestId $start_time - $end_time ", FILE_APPEND); +// } +// } +// +// if (!empty($result['stores'])) { +// $products1cByTip = Products1c::find() +// ->select(['id', 'tip']) +// ->andWhere(['tip' => ['kkms', 'terminals', 'city_store']]) +// ->groupBy(['tip', 'id']) +// ->asArray() +// ->all(); +// $products1cByTipMap = []; +// foreach ($products1cByTip as $item) { +// $products1cByTipMap[$item['tip']][] = $item['id']; +// } +// $existTerminals = Terminals::find() +// ->indexBy('id') +// ->asArray() +// ->column(); +// +// foreach ($result['stores'] as $gi => $arr) { +// if (!in_array($arr["id"], $products1cByTipMap['city_store'])) { +// $products1c = new Products1c; +// $products1c->id = $arr["id"]; +// $products1c->tip = 'city_store'; +// $products1c->name = $arr["name"]; +// $products1c->code = $arr["code"]; +// $products1c->save(); +// if ($products1c->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 2, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// +// if ($arr["terminals"]) { +// $k = 0; +// foreach ($arr["terminals"] as $gi2 => $arr2) { +// if (!in_array($arr2['id'], $products1cByTipMap['terminals'])) { +// $products1c2 = new Products1c; +// $products1c2->id = $arr2['id']; +// $products1c2->tip = 'terminals'; +// $products1c2->name = $arr2["name"]; +// $products1c2->code = $arr2["code"]; +// $products1c2->save(); +// if ($products1c2->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 3, "error" => $products1c2->getErrors()], JSON_UNESCAPED_UNICODE)); +// Yii::error(''); +// } +// } +// +// if (!in_array($arr2['id'], $existTerminals)) { +// $terminal = new Terminals; +// $terminal->id = $arr2["id"]; +// $terminal->name = $arr2["name"]; +// $terminal->code = $arr2["code"]; +// $terminal->store_id = $arr["id"]; +// $terminal->date = date('Y-m-d H:i:s'); +// $terminal->posit = $k; +// $terminal->save(); +// if ($terminal->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 4, "error" => $terminal->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// $k++; +// } +// } +// +// if ($arr['kkms']) { +// foreach ($arr["kkms"] as $gi2 => $arr2) { +// if (!in_array($arr2['id'], $products1cByTipMap['kkms'])) { +// $products1c3 = new Products1c; +// $products1c3->id = $arr2["id"]; +// $products1c3->tip = 'kkms'; +// $products1c3->name = $arr2["name"]; +// $products1c3->code = $arr2["code"]; +// $products1c3->save(); +// if ($products1c3->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 5, "error" => $products1c3->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// } +// } +// } +// if (!empty($result['self_cost'])) { +// $storeMap = []; +// +// $cityStoreIds = CityStore::find()->select('id')->column(); +// +// // Получаем соответствия export_val => entity_id из таблицы ExportImportTable +// $exportImportRecords = ExportImportTable::find() +// ->select(['entity_id', 'export_val']) +// ->where(['entity_id' => $cityStoreIds, 'entity' => 'city_store', 'export_id' => 1]) +// ->all(); +// +// // Создаем справочник +// foreach ($exportImportRecords as $record) { +// $storeMap[$record->export_val] = $record->entity_id; +// } +// +// $values = []; +// +// foreach ($result['self_cost'] as $selfCost) { +// $storeId = $storeMap[$selfCost['store_id']] ?? null; +// if (!$storeId) { +// continue; +// } +// +// +// // Удаляем старые данные +// SelfCostProduct::deleteAll(['date' => $selfCost['date'], 'store_id' => $storeId]); +// +// foreach ($selfCost['items'] as $item) { +// $values[] = [ +// 'date' => $selfCost['date'], +// 'store_id' => $storeId, +// 'product_guid' => $item['product_id'], +// 'price' => $item['price'], +// 'updated_at' => date('Y-m-d H:i:s') +// ]; +// } +// } +// +// if (!empty($values)) { +// $this->setSelfCostUpdate($values); +// SelfCostProductDinamicService::UpdateResult($values); +// } +// } +// +// +// if (!empty($result['sellers'])) { +// Products1c::deleteAll(['tip' => 'admin']); +// +// foreach ($result["sellers"] as $gi => $arr) { +// EmployeeOnShift::updateAll(['status_source' => EmployeeOnShift::STATUS_SOURCE_CREATED_IN_1C], ['guid' => $arr['id']]); +// $products1c4 = new Products1c; +// $products1c4->id = $arr["id"]; +// $products1c4->tip = 'admin'; +// $products1c4->name = $arr["name"]; +// $products1c4->code = $arr["code"] ?? ''; +// $products1c4->parent_id = $arr["parent_id"] ?? ''; +// $products1c4->save(); +// if ($products1c4->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 6, "error" => $products1c4->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// +// if (!empty($result["nomenclature"]["groups"])) { +// Products1c::deleteAll(['tip' => 'products_group']); +// foreach ($result["nomenclature"]["groups"] as $gi => $arr) { +// $products1c5 = new Products1c; +// $products1c5->id = $arr["id"]; +// $products1c5->tip = 'products_group'; +// $products1c5->name = $arr["name"]; +// $products1c5->code = $arr["code"] ?? ''; +// $products1c5->articule = $arr["articule"] ?? ''; +// $products1c5->parent_id = $arr["parent_id"] ?? '0'; +// $products1c5->save(); +// if ($products1c5->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 7, "error" => $products1c5->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// if (!empty($result["nomenclature"]["elements"])) { +//// Products1c::deleteAll(['and', ['tip' => 'products'], ['view' => 0]]); +// $bouquets = BouquetComposition::find()->select('guid')->column(); +// foreach ($result["nomenclature"]["elements"] as $gi => $arr) { +//// if (!empty($arr["name"]) && in_array($arr["name"][0], ['ь', 'Ь', 'ъ', 'Ъ'])) { // Не вносим номенклатуру, помеченную на удаление +//// continue; +//// } +// $components = !empty($arr["components"]) ? json_encode($arr["components"], JSON_UNESCAPED_UNICODE) : ""; // Пустые компоненты не надо разворачивать в json объект +// $products1c6 = Products1c::find()->where(['id' => $arr["id"]])->one(); +// if (!$products1c6) { +// $products1c6 = new Products1c; +// $products1c6->id = $arr["id"]; +// $products1c6->tip = 'products'; +// } +// $products1c6->name = $arr["name"]; +// $products1c6->code = $arr["code"]; +// $products1c6->type = $arr["type"]; +// $products1c6->articule = $arr["articule"]; +// $products1c6->parent_id = $arr["parent_id"]; +// $products1c6->view = $arr["view"]; +// $products1c6->components = $components; +// $products1c6->save(); +// if ($products1c6->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 8, "error" => $products1c6->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// +// if(!empty($arr["components"])) { +// if(!in_array($arr["id"], $bouquets)) { +// $newBouquetComp = new BouquetComposition(); +// $newBouquetComp->guid = $arr["id"]; +// $newBouquetComp->name = $arr["name"]; +// $newBouquetComp->status = 1; +// $newBouquetComp->matrix_type_id = 1; +// $newBouquetComp->created_by = Admin::getAdminAgentId() ?: null; +// if(!$newBouquetComp->save()) { +// LogService::apiErrorLog(json_encode(["error_id" => 8.1, "error" => $newBouquetComp->getErrors()], JSON_UNESCAPED_UNICODE)); +// } else { +// foreach ($arr["components"] as $guid => $quantity) { +// $newBouquetCompProd = new BouquetCompositionProducts(); +// $newBouquetCompProd->bouquet_id = $newBouquetComp->id; +// $newBouquetCompProd->product_guid = $guid; +// $newBouquetCompProd->count = $quantity; +// $newBouquetCompProd->created_by = Admin::getAdminAgentId() ?: null; +// if(!$newBouquetCompProd->save()) { +// LogService::apiErrorLog(json_encode(["error_id" => 8.2, "error" => $newBouquetCompProd->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +//// $costModels = []; +//// foreach (BouquetComposition::getRegions() as $region_id) { +//// $costModels[$region_id] = $newBouquetComp->getCostModel($region_id, array_keys($arr["components"]), true); +//// } +//// if(empty($costModels)) { +//// LogService::apiErrorLog(json_encode(["error_id" => 8.3, "error" => "Стоимость и цена не подсчитаны"], JSON_UNESCAPED_UNICODE)); +//// } +//// $bouquetTypeHistory = new BouquetCompositionMatrixTypeHistory(); +//// $bouquetTypeHistory->bouquet_id = $newBouquetComp->id; +//// $bouquetTypeHistory->matrix_type_id = 1; +//// $bouquetTypeHistory->created_by = Admin::getAdminAgentId() ?: null; +//// $bouquetTypeHistory->is_active = 1; +//// $bouquetTypeHistory->date_from = date('Y-m-d H:i:s'); +//// if(!$bouquetTypeHistory->save()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 8.4, "error" => $bouquetTypeHistory->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +// } +// } +// } +// +// foreach ($arr as $key => $property) { +// if (!in_array($key, Products1c::PRODUCT1C_FIELDS)) { +// if (empty($property)) continue; +// $propertyType = Products1cPropType::findOne(['id' => $key]); +// if (!$propertyType) { +// $propertyType = new Products1cPropType(); +// $propertyType->id = $key; +// $propertyType->name = $key; +// if (!$propertyType->save()) { +// LogService::apiErrorLog(json_encode(["error_id" => 8.1, +// "error" => $propertyType->getErrors()], +// JSON_UNESCAPED_UNICODE)); +// continue; +// } +// } +// $additionalCharacteristic = Products1cAdditionalCharacteristics::findOne([ +// 'product_id' => $arr["id"], +// 'property_id' => $key +// ]); +// if (!$additionalCharacteristic && !empty($property)) { +// $additionalCharacteristic = new Products1cAdditionalCharacteristics(); +// $additionalCharacteristic->product_id = $arr["id"]; +// $additionalCharacteristic->property_id = $key; +// } +// $additionalCharacteristic->value = $property; +// if (!$additionalCharacteristic->save()) { +// LogService::apiErrorLog(json_encode(["error_id" => 8.2, +// "error" => $additionalCharacteristic->getErrors()], +// JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// +// if (!empty($arr["AdditionCharacteristics"])) { +// $passedCharacteristics = array_column($arr["AdditionCharacteristics"], null, "id"); +// $currentCharacteristics = Products1cAdditionalCharacteristics::find() +// ->where(['product_id' => $arr["id"]]) +// ->indexBy('property_id') +// ->all(); +// +// foreach ($currentCharacteristics as $propertyId => $currentCharacteristic) { +// if (!isset($passedCharacteristics[$propertyId])) { +// if (!$currentCharacteristic->delete()) { +// LogService::apiErrorLog(json_encode([ +// "error_id" => 8.39, +// "error" => $currentCharacteristic->getErrors() +// ], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// +// foreach ($arr["AdditionCharacteristics"] as $characteristic) { +// $propertyType = Products1cPropType::findOne(['id' => $characteristic["id"]]); +// if (!$propertyType) { +// $propertyType = new Products1cPropType(); +// $propertyType->id = $characteristic["id"]; +// $propertyType->name = $characteristic["name"]; +// if (!$propertyType->save()) { +// LogService::apiErrorLog(json_encode(["error_id" => 8.1, +// "error" => $propertyType->getErrors()], +// JSON_UNESCAPED_UNICODE)); +// continue; +// } +// } +// +// $additionalCharacteristic = Products1cAdditionalCharacteristics::findOne([ +// 'product_id' => $arr["id"], +// 'property_id' => $characteristic["id"] +// ]); +// +// if (!$additionalCharacteristic) { +// $additionalCharacteristic = new Products1cAdditionalCharacteristics(); +// $additionalCharacteristic->product_id = $arr["id"]; +// $additionalCharacteristic->property_id = $characteristic["id"]; +// } +// +// $additionalCharacteristic->value = $characteristic["value_name"]; +// if (!$additionalCharacteristic->save()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 8.2, "error" => $additionalCharacteristic->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// } +// if ( +// !empty($arr["type"]) +// && str_starts_with($arr["type"], '[') +// && str_ends_with($arr["type"], ']') +// ) { +// // return [$arr["type"]]; +// $product1cNomenclature = Products1cNomenclature::find()->where(['id' => $arr["id"]])->one(); +// if (!$product1cNomenclature) { +// $product1cNomenclature = new Products1cNomenclature(); +// $product1cNomenclature->id = $arr["id"]; +// } +// $typeNomenclature = rtrim(ltrim($arr["type"], '['), ']'); +// $typeArr = explode("/", $typeNomenclature); +// $category = $typeArr[0]; +// $subcategory = $typeArr[1] ?? null; +// $product1cNomenclature->name = $arr["name"]; +// $product1cNomenclature->location = $arr["type"]; +// $product1cNomenclature->type_num = $typeNomenclature; +// $product1cNomenclature->category = $category; +// $product1cNomenclature->subcategory = $subcategory; +// $characteristics = Products1cAdditionalCharacteristics::find() +// ->select(['property_id', 'value']) +// ->where(['product_id' => $arr["id"]]) +// ->indexBy(['property_id']) +// ->asArray() +// ->all(); +// +// $propTypes = array_keys($characteristics); +// $propertyNames = Products1cPropType::find() +// ->select(['id','name']) +// ->where(['id' => $propTypes]) +// ->indexBy('id') +// ->asArray() +// ->all(); +// $characteristicsValues = []; +// +// foreach ($propertyNames as $propertyId => $property) { +// if (isset($characteristics[$propertyId])) { +// $characteristicsValues[$property['name']] = $characteristics[$propertyId]['value']; +// } +// } +// +// $sizeValue = 0; +// if (isset($characteristicsValues['size']) && intval($characteristicsValues['size'])) { +// $sizeValue = intval($characteristicsValues['size']); +// } +// if (isset($characteristicsValues['размер']) && intval($characteristicsValues['размер'])) { +// $sizeValue = intval($characteristicsValues['размер']); +// } +// +// $speciesValue = null; +// if (isset($characteristicsValues['species']) && !empty($characteristicsValues['species'])) { +// $speciesValue = $characteristicsValues['species']; +// } +// if (isset($characteristicsValues['вид']) && !empty($characteristicsValues['вид'])) { +// $speciesValue = $characteristicsValues['вид']; +// } +// +// $sortValue = null; +// if (isset($characteristicsValues['sort']) && !empty($characteristicsValues['sort'])) { +// $sortValue = $characteristicsValues['sort']; +// } +// if (isset($characteristicsValues['сорт']) && !empty($characteristicsValues['сорт'])) { +// $sortValue = $characteristicsValues['сорт']; +// } +// +// $typeValue = null; +// if (isset($characteristicsValues['type']) && !empty($characteristicsValues['type'])) { +// $typeValue = $characteristicsValues['type']; +// } +// if (isset($characteristicsValues['тип']) && !empty($characteristicsValues['тип'])) { +// $typeValue = $characteristicsValues['тип']; +// } +// +// $measureValue = null; +// if (isset($characteristicsValues['measure']) && !empty($characteristicsValues['measure'])) { +// $measureValue = $characteristicsValues['measure']; +// } +// +// $colorValue = null; +// if (isset($characteristicsValues['color']) && !empty($characteristicsValues['color'])) { +// $colorValue = $characteristicsValues['color']; +// } +// if (isset($characteristicsValues['цвет']) && !empty($characteristicsValues['цвет'])) { +// $colorValue = $characteristicsValues['цвет']; +// } +// +// $product1cNomenclature->species = $speciesValue; +// $product1cNomenclature->sort = $sortValue; +// $product1cNomenclature->type = $typeValue; +// $product1cNomenclature->size = $sizeValue; +// $product1cNomenclature->measure = $measureValue; +// $product1cNomenclature->color = $colorValue; +// +// if (!$product1cNomenclature->save()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 8.3, "error" => $product1cNomenclature->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// } +// } +// +// if (!empty($result['payment_types'])) { +// foreach ($result["payment_types"] as $gi => $arr) { +// $paymentTypes = PaymentTypes::findOne(['id' => $arr['id']]) ?? new PaymentTypes(); +// $paymentTypes->id = $arr['id']; +// $paymentTypes->code = $arr['code']; +// $paymentTypes->name = $arr['name']; +// $paymentTypes->save(); +// if ($paymentTypes->getErrors()) { +// LogService::apiErrorLog(json_encode( +// ["error_id" => 9, +// "error" => $paymentTypes->getErrors()], +// JSON_UNESCAPED_UNICODE +// )); +// } +// +// $products1c7 = Products1c::findOne(['id' => $arr["id"]]) ?? new Products1c(); +// $products1c7->id = $arr["id"]; +// $products1c7->tip = 'payment_types'; +// $products1c7->name = $arr["name"]; +// $products1c7->code = $arr["code"]; +// $products1c7->save(); +// if ($products1c7->getErrors()) { +// LogService::apiErrorLog(json_encode( +// ["error_id" => 10, "error" => $products1c7->getErrors()], +// JSON_UNESCAPED_UNICODE +// )); +// } +// } +// } +// +// if (!empty($result['created_write_offs'])) { +// $productsNames = Products1c::getNamesByTip('products'); +// +// file_put_contents( +// self::OUT_DIR . '/created_write_offs_upload_' +// . date("Y_m_d") . '.json', +// PHP_EOL +// . json_encode($result["created_write_offs"], JSON_UNESCAPED_UNICODE), +// FILE_APPEND +// ); +// foreach ($result["created_write_offs"] as $arr) { +// if (!empty($arr["id"])) { +// $writeOffsErp = WriteOffsErp::find()->where(['guid' => $arr["id"]])->one(); +// if (empty($writeOffsErp)) { +// $waybillWriteOffsErp = WaybillWriteOffs::find()->where(['guid' => $arr["id"]])->one(); +// } +// } +// +// if (!empty($writeOffsErp) || !empty($waybillWriteOffsErp)) { +// if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { +// $errorText = ''; +// if (!empty($arr["errors"])) { +// //"errors": [ +// //{ +// //"error": "Ошибка преобразования ИД документа", +// //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", +// //"error_json": [ +// //{ +// //"field": "id", +// //"error": "Документ с данным ИД уже записан в системе" +// //} +// // +// +// foreach ($arr["errors"] as $errorRow) { +// if (!empty($errorRow['error'])) { +// $errorText .= $errorRow['error']; +// +// $errorText .= ' ,' . $errorRow['error_description']; +// if (!empty($errorRow['error_json'])) { +// foreach ($errorRow['error_json'] as $errorJsonRow) { +// $errorText .= ' , поле: ' . $errorJsonRow['field']; +// $errorText .= ' , ошибка: ' . $errorJsonRow['error']; +// } +// } +// } +// +// if (!empty($errorRow["errors_items"])) { +// foreach ($errorRow["errors_items"] as $errorDopRow) { +// //"errors_items": [ +// //{ +// //"error_dop": "Ошибка проверки количества номенклатуры", +// //"field": "quantity", +// //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", +// //"error": "У данной позиции запрещён ввод дробного значения!" +// //}, +// // +// // +// $productName = $errorDopRow['product_id']; +// +// if (array_key_exists($errorDopRow['product_id'], $productsNames)) { +// $productName = $productsNames[$errorDopRow['product_id']]; +// } +// +// $errorText .= ' ' . $errorDopRow['error_dop']; +// $errorText .= ' , поле: ' . $errorDopRow['field']; +// $errorText .= ' , товар: ' . $productName; +// $errorText .= ' , ошибка: ' . $errorDopRow['error']; +// } +// } +// } +// } +// if (!empty($writeOffsErp)) { +// /** @var WriteOffsErp $writeOffsErp */ +// $writeOffsErp->status = WriteOffsErp::STATUS_ERROR_1C; +// $writeOffsErp->error_text = $errorText; +// $writeOffsErp->save(); +// if ($writeOffsErp->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 11.1, "error" => $writeOffsErp->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// if (!empty($waybillWriteOffsErp)) { +// /** @var WaybillWriteOffs $waybillWriteOffsErp */ +// $waybillWriteOffsErp->status = WriteOffsErp::STATUS_ERROR_1C; +// $waybillWriteOffsErp->error_text = $errorText; +// $waybillWriteOffsErp->save(); +// if ($waybillWriteOffsErp->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 11.2, "error" => $waybillWriteOffsErp->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// +// } else { +// if (!empty($writeOffsErp)) { +// /** @var WriteOffsErp $writeOffsErp */ +// $writeOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; +// $writeOffsErp->number_1c = $arr["number"] ?? ''; +// $writeOffsErp->save(); +// if ($writeOffsErp->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// [ +// "error_id" => 11.3, +// "error" => $writeOffsErp->getErrors() +// ], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// if (!empty($waybillWriteOffsErp) && isset($arr["held"]) && $arr["held"]) { +// /** @var WaybillWriteOffs $waybillWriteOffsErp */ +// $waybillWriteOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; +// $waybillWriteOffsErp->name_1c = $arr["name"] ?? ''; +// $waybillWriteOffsErp->save(); +// if ($waybillWriteOffsErp->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// [ +// "error_id" => 11.4, +// "error" => $waybillWriteOffsErp->getErrors() +// ], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// +// } +// } +// } +// } +// +// if (!empty($result['created_write_ons'])) { +// $productsNames = Products1c::getNamesByTip('products'); +// file_put_contents( +// self::OUT_DIR . '/created_write_ons_upload_' +// . date("Y_m_d") . '.json', +// PHP_EOL +// . json_encode($result["created_write_ons"], JSON_UNESCAPED_UNICODE), +// FILE_APPEND +// ); +// foreach ($result["created_write_ons"] as $arr) { +// if (!empty($arr["id"])) { +// $waybillIncoming = WaybillIncoming::find()->where(['guid' => $arr["id"]])->one(); +// } +// +// if (!empty($waybillIncoming)) { +// if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { +// $errorText = ''; +// if (!empty($arr["errors"])) { +// //"errors": [ +// //{ +// //"error": "Ошибка преобразования ИД документа", +// //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", +// //"error_json": [ +// //{ +// //"field": "id", +// //"error": "Документ с данным ИД уже записан в системе" +// //} +// // +// +// foreach ($arr["errors"] as $errorRow) { +// if (!empty($errorRow['error'])) { +// $errorText .= $errorRow['error']; +// +// $errorText .= ' ,' . $errorRow['error_description']; +// if (!empty($errorRow['error_json'])) { +// foreach ($errorRow['error_json'] as $errorJsonRow) { +// $errorText .= ' , поле: ' . $errorJsonRow['field']; +// $errorText .= ' , ошибка: ' . $errorJsonRow['error']; +// } +// } +// } +// +// if (!empty($errorRow["errors_items"])) { +// foreach ($errorRow["errors_items"] as $errorDopRow) { +// //"errors_items": [ +// //{ +// //"error_dop": "Ошибка проверки количества номенклатуры", +// //"field": "quantity", +// //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", +// //"error": "У данной позиции запрещён ввод дробного значения!" +// //}, +// // +// // +// $productName = $errorDopRow['product_id']; +// +// if (array_key_exists($errorDopRow['product_id'], $productsNames)) { +// $productName = $productsNames[$errorDopRow['product_id']]; +// } +// +// $errorText .= ' ' . $errorDopRow['error_dop']; +// $errorText .= ' , поле: ' . $errorDopRow['field']; +// $errorText .= ' , товар: ' . $productName; +// $errorText .= ' , ошибка: ' . $errorDopRow['error']; +// } +// } +// } +// } +// +// /** @var WaybillIncoming $waybillIncoming */ +// $waybillIncoming->status = WriteOffsErp::STATUS_ERROR_1C; +// $waybillIncoming->error_text = $errorText; +// $waybillIncoming->save(); +// if ($waybillIncoming->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 11.5, "error" => $waybillIncoming->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } else { +// if (isset($arr["held"]) && $arr["held"]) { +// /** @var WaybillIncoming $waybillIncoming */ +// $waybillIncoming->status = WriteOffsErp::STATUS_CREATED_1C; +// $waybillIncoming->number_1c = $arr["name"] ?? ''; +// $waybillIncoming->save(); +// if ($waybillIncoming->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 11.55, "error" => $waybillIncoming->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// } +// } +// } +// } +// +// if (!empty($result['created_resortings'])) { +// $productsNames = Products1c::getNamesByTip('products'); +// file_put_contents( +// self::OUT_DIR . '/created_resortings_upload_' +// . date("Y_m_d") . '.json', +// PHP_EOL +// . json_encode($result["created_resortings"], JSON_UNESCAPED_UNICODE), +// FILE_APPEND +// ); +// foreach ($result["created_resortings"] as $arr) { +// if (!empty($arr["id"])) { +// $replacementInvoice = ReplacementInvoice::findOne(['guid' => $arr["id"]]); +// } +// +// if (!empty($replacementInvoice)) { +// if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { +// $errorText = ''; +// if (!empty($arr["errors"])) { +// foreach ($arr["errors"] as $errorRow) { +// if (!empty($errorRow['error'])) { +// $errorText .= $errorRow['error']; +// +// $errorText .= ' ,' . $errorRow['error_description']; +// if (!empty($errorRow['error_json'])) { +// foreach ($errorRow['error_json'] as $errorJsonRow) { +// $errorText .= ' , поле: ' . $errorJsonRow['field']; +// $errorText .= ' , ошибка: ' . $errorJsonRow['error']; +// } +// } +// } +// +// if (!empty($errorRow["errors_items"])) { +// foreach ($errorRow["errors_items"] as $errorDopRow) { +// $productName = $errorDopRow['product_id']; +// +// if (array_key_exists($errorDopRow['product_id'], $productsNames)) { +// $productName = $productsNames[$errorDopRow['product_id']]; +// } +// +// $errorText .= ' ' . $errorDopRow['error_dop']; +// $errorText .= ' , поле: ' . $errorDopRow['field']; +// $errorText .= ' , товар: ' . $productName; +// $errorText .= ' , ошибка: ' . $errorDopRow['error']; +// } +// } +// } +// } +// +// /** @var ReplacementInvoice $replacementInvoice */ +// $replacementInvoice->status = WriteOffsErp::STATUS_ERROR_1C; +// $replacementInvoice->error_text = $errorText; +// $replacementInvoice->save(); +// if ($replacementInvoice->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 4.555, "error" => $replacementInvoice->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// +// } else { +// if (isset($arr["held"]) && $arr["held"]) { +// /** @var ReplacementInvoice $replacementInvoice */ +// $replacementInvoice->status = WriteOffsErp::STATUS_CREATED_1C; +// $replacementInvoice->number_1c = $arr["name"] ?? ''; +// $replacementInvoice->save(); +// if ($replacementInvoice->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 4.55, "error" => $replacementInvoice->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// } +// } +// } +// } +// +// $update = false; +// if (!empty($start_time) && !empty($end_time)) { +// $start_time_unix = strtotime($start_time); +// $startMonth = date("Y-m-01"); +// $end_time_unix = strtotime($end_time); +// if ( +// $startMonth <= (date("Y-m-d", strtotime($start_time))) +// || +// ($end_time_unix < (time() - 90 * 86400)) +// ) { +// $update = true; +// } +// } +// +// if (!empty($result['write_offs'])) { +// if (!empty($start_time) and !empty($end_time)) { +// if ($update) { +// WriteOffs::deleteAll(['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); +// } +// } +// +// foreach ($result["write_offs"] as $gi => $arr) { +// if (!empty($arr["error"])) { +// file_put_contents(self::OUT_DIR . '/created_write_offs_erp_error.txt', PHP_EOL . " " . $arr["id"] . " error=" . $arr["error"], FILE_APPEND); +// } +// +// if (empty($arr["error"]) && !empty($arr["id"])) { +// $writeOffsErp = WriteOffsErp::find()->where(['guid' => $arr["id"]])->one(); +// if ($writeOffsErp) { +// $writeOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; +// $writeOffsErp->number_1c = $arr["number"]; +// $writeOffsErp->save(); +// if ($writeOffsErp->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 11.6, "error" => $writeOffsErp->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } else { +// $waybillWriteOffsErp = WaybillWriteOffs::find()->where(['guid' => $arr["id"]])->one(); +// if ($waybillWriteOffsErp) { +// $waybillWriteOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; +// $waybillWriteOffsErp->number_1c = $arr["number"]; +// $waybillWriteOffsErp->save(); +// if ($waybillWriteOffsErp->getErrors()) { +// LogService::apiErrorLog( +// json_encode(["error_id" => 11.7, "error" => $waybillWriteOffsErp->getErrors()], +// JSON_UNESCAPED_UNICODE) +// ); +// } +// } +// } +// } +// +//// file_put_contents(self::OUT_DIR . '/write_offs.json', PHP_EOL . json_encode($result["write_offs"], JSON_UNESCAPED_UNICODE)); +// +// $writeOffs = WriteOffs::find()->where(['id' => $arr["id"]])->one(); +// if ($writeOffs) { +// $writeOffs->delete(); +// } +// WriteOffsProducts::deleteAll(['write_offs_id' => $arr["id"]]); +// +// $writeOffs2 = new WriteOffs; +// $writeOffs2->id = $arr["id"]; +// $writeOffs2->status_id = 1; +// $writeOffs2->write_downs = '1c'; +// $writeOffs2->store_id = $arr["store_id"]; +// $writeOffs2->number = $arr["number"]; +// $writeOffs2->date = $arr["date"]; +// $writeOffs2->based_on = $arr["based_on"] ?? ""; +// $typeIndex = strpos($arr["type"], "_"); +// $writeOffs2->type = $typeIndex === false ? $arr['type'] : substr($arr["type"], $typeIndex + 1); +// $writeOffs2->cause = $arr["cause"] ?? ""; +// $writeOffs2->comment = $arr["comment"] ?? ""; +// $writeOffs2->items = json_encode($arr["items"], JSON_UNESCAPED_UNICODE); +// $writeOffs2->summ = $arr["summ"]; +// $writeOffs2->save(); +// if ($writeOffs2->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 12, "error" => $writeOffs2->getErrors(), "number" => $arr["number"]], JSON_UNESCAPED_UNICODE)); +// } +// +// foreach ($arr["items"] as $j2 => $mass2) { +// $writeOffsProducts = WriteOffsProducts::findOne([ +// 'write_offs_id' => $arr["id"], +// 'product_id' => $mass2['product_id'], +// ]) ?? new WriteOffsProducts(); +// $writeOffsProducts->write_offs_id = $arr["id"]; +// $writeOffsProducts->date = $arr["date"]; +// $writeOffsProducts->product_id = $mass2['product_id']; +// $writeOffsProducts->color = $mass2["color"]; +// $writeOffsProducts->quantity = ceil($mass2["quantity"]); +// $writeOffsProducts->summ = $mass2["summ"]; +// $writeOffsProducts->price = $mass2["price"]; +// $writeOffsProducts->price_retail = 0; +// $writeOffsProducts->summ_retail = 0; +// $writeOffsProducts->save(); +// if ($writeOffsProducts->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 13, "error" => $writeOffsProducts->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// } +// +// if (!empty($result['counteragents'])) { +// foreach ($result["counteragents"] as $gi => $arr) { +// $arr["is_group"] = $arr["is_group"] ? 1 : 0; +// $products1c = new Products1c; +// $products1c->id = $arr["id"]; +// $products1c->tip = 'counteragents'; +// $products1c->name = $arr["name"]; +// $products1c->code = $arr["inn"]; +// $products1c->parent_id = $arr["parent_id"]; +// $products1c->view = $arr["is_group"]; +// $products1c->save(); +// if ($products1c->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 14, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// +// if (!empty($result['incomings'])) { +// foreach ($result["incomings"] as $gi => $arr) { +// $incoming = Incoming::find()->where(['id' => $arr['id']])->one(); +// if (!$incoming) { +// $incoming = new Incoming; +// $incoming->id = $arr["id"]; +// $incoming->store_id = $arr["store_id"]; +// $incoming->counteragent_id = $arr["counteragent_id"]; +// $incoming->number = $arr["number"]; +// $incoming->date = $arr["date"]; +// $incoming->comment = $arr["comment"] ?? ''; +// $incoming->items = empty($arr["items"]) ? '[]' : json_encode($arr["items"], JSON_UNESCAPED_UNICODE); +// $incoming->is_discrepancies = (int)$arr["is_discrepancies"]; +// $incoming->supplier_items = empty($arr["supplier_items"]) ? '[]' : json_encode($arr["supplier_items"], JSON_UNESCAPED_UNICODE); +// $incoming->payments = empty($arr["payments"]) ? '[]' : json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); +// $incoming->summ = $arr["summ"]; +// $incoming->save(); +// } +// if ($incoming->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 15, "error" => $incoming->getErrors()], JSON_UNESCAPED_UNICODE)); +// } else { +// try { +// $json = Json::decode($incoming->items); +// IncomingItems::deleteAll(['incoming_id' => $incoming->id]); +// foreach ($json as $item) { +// $incomingItem = new IncomingItems; +// $incomingItem->incoming_id = $incoming->id; +// $incomingItem->product_id = $item['product_id']; +// $incomingItem->color = $item['color']; +// $incomingItem->quantity = $item['quantity']; +// $incomingItem->price = $item['price']; +// $incomingItem->vat_rate = $item['vat_rate']; +// $incomingItem->vat_amount = $item['vat_amount']; +// $incomingItem->summ = $item['summ']; +// $incomingItem->save(); +// if ($incomingItem->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 15.2, "error" => $incomingItem->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } catch (Exception $jex) { +// LogService::apiErrorLog(json_encode(["error_id" => 15.3, "error" => "items has no json format"], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// } +// +// if (!empty($result['cashes'])) { +// foreach ($result["cashes"] as $gi => $arr) { +// $products1c = new Products1c; +// $products1c->id = $arr["id"]; +// $products1c->tip = 'cashes'; +// $products1c->name = $arr["name"]; +// $products1c->code = $arr["store_id"]; +// $products1c->save(); +// if ($products1c->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 16, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// $cashes = new Cashes; +// $cashes->id = $arr["id"]; +// $cashes->store_id = $arr["store_id"]; +// $cashes->kkm_id = $arr["kkm_id"]; +// $cashes->name = $arr["name"]; +// $cashes->is_central = $arr["is_central"]; +// $cashes->save(); +// if ($cashes->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 17, "error" => $cashes->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// +// if (!empty($checks_dell) and !empty($start_time) and !empty($end_time)) { +// if ($update) { +// Sales::updateAll(['operation' => 'Удален'], ['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); +// } +//// SalesUpdate::updateAll(['operation' => 'Удален'], ['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); +// +// file_put_contents(self::OUT_DIR . '/check_dell.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . " regquest_id=$requestId Удаление $start_time - $end_time ", FILE_APPEND); +// } +// +// $matrixProductsIds = []; +// if (!empty($result['checks'])) { +// $matrixProductsIds = SalaryHelper::getMatrixProductsIds(); +// } +// +// if (!empty($result['checks'])) { +// foreach ($result["checks"] as $index => $arr) { +// if (!isset($arr["marketplace_order_id"])) { +// continue; +// } +// $marketplaceOrder = MarketplaceOrders::findOne(['guid' => $arr["marketplace_order_id"]]); +// if (!empty($arr['error'])) { +// $txt = date("d.m.Y H:i:s", time()) . " $index СОЗДАНИЕ ЧЕКА ОШИБКА id=" . $arr["id"] . " " . $arr["error"]; +// file_put_contents(self::OUT_DIR . '/log_check_error.txt', PHP_EOL . $txt, FILE_APPEND); +// $marketplaceOrder->error_text = "ОШИБКА ЧЕКА" . $arr["id"] . "для заказа id=" . $marketplaceOrder->marketplace_order_id . " " . $arr["error"]; +// $marketplaceOrder->save(); +// if ($marketplaceOrder->getErrors()) { +// Yii::error('Ошибка сохранения ошибки заказа ' . json_encode($marketplaceOrder->getErrors(), JSON_UNESCAPED_UNICODE)); +// LogService::apiErrorLog(json_encode(["error_id" => 17.2, "error" => $marketplaceOrder->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// continue; +// } +// $check = CreateChecks::find() +// ->where(['check_id' => $arr["id"]]) +// ->andWhere(['order_guid' => $arr["marketplace_order_id"]]) +// ->andWhere(['status' => 0])->one(); +// if(!$check) { +// continue; +// } +// $check->status = 1; +// $check->name = $arr["number"] . " от " . $arr["date"]; +// $check->guid = $arr["id"]; +// $check->date_up = date('Y-m-d H:i:s'); +// $check->held = 1; +// $check->save(); +// if ($check->getErrors()) { +// Yii::error('Ошибка обновления чека ' . json_encode($check->getErrors(), JSON_UNESCAPED_UNICODE)); +// LogService::apiErrorLog(json_encode(["error_id" => 17.3, "error" => $check->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// +// if (!empty($result['checks']) && count($result['checks']) < 1000) { +// +// foreach ($result["checks"] as $arr) { +// +// $check_id = $arr["id"]; +// if ($arr["seller_id"] == '00000000-0000-0000-0000-000000000000') { +// $arr["seller_id"] = "NULL"; +// } +// +// $pay_arr = $this->getPayArr($arr["payments"]); +// +// $store_id = ClientHelper::getExportId($arr["store_id"], "city_store", 1); +//// $admin_id = ClientHelper::getExportId($arr["seller_id"], "admin", 1); +// $exportImportTable = ExportImportTable::find()->select(['entity_id'])->where(['entity' => 'admin']) +// ->andWhere(['export_id' => 1])->andWhere(['export_val' => $arr["seller_id"]])->all(); +// $exportImportTableIds = ArrayHelper::getColumn($exportImportTable, 'entity_id'); +// $admin = Admin::find()->where(['in', 'id', $exportImportTableIds])->andWhere(['>', 'group_id', 0])->one(); +// $admin_id = $admin->id ?? 0; +// +// //удаляем чеки и товары в чеках +// $saleUpdate = SalesUpdate::find()->where(['id' => $arr["id"]])->one(); +// if ($saleUpdate) { +// $saleUpdate->delete(); +// } +//// SalesProductsUpdate::deleteAll(['check_id' => $arr["id"]]); +// +// if ($update) { +// $sales = Sales::find()->where(['id' => $arr["id"]])->one(); +// if ($sales) { +// $sales->delete(); +// } +// SalesItems::deleteAll(['check_id' => $arr["id"]]); +// SalesProducts::deleteAll(['check_id' => $arr["id"]]); +// } +// +// // проверяем стутс чека - вносим только Архивные и пробитые +//// if (!empty($arr["status"])) { +//// $salesUpdate = new SalesUpdate; +//// $salesUpdate->phone = empty($arr["client_phone"]) ? 0 : (int)$arr["client_phone"]; +//// $salesUpdate->id = $arr["id"]; +//// $salesUpdate->store_id = $store_id; +//// $salesUpdate->store_id_1c = $arr["store_id"]; +//// $salesUpdate->seller_id = $arr["seller_id"]; +//// $salesUpdate->admin_id = $admin_id; +//// $salesUpdate->operation = $arr["type"]; +//// $salesUpdate->number = $arr["number"]; +//// $salesUpdate->date = $arr["date"]; +//// $salesUpdate->summ = $arr["summ"]; +//// $salesUpdate->status = $arr["status"]; +//// $salesUpdate->sales_check = $arr["sales_check"] ?? 'NULL'; +//// $salesUpdate->payments = json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); +//// $salesUpdate->pay_arr = implode(",", $pay_arr); +//// $salesUpdate->order_id = $arr["order_id"] ?? ''; +//// $salesUpdate->terminal = $arr["terminal"] ?? 'NULL'; +//// $salesUpdate->terminal_id = $arr["terminal_id"] ?? 'NULL'; +//// $salesUpdate->date_up = date('Y-m-d H:i:s'); +//// $salesUpdate->skidka = $arr["discount"] ?? 0; +//// $salesUpdate->kkm_id = $arr["kkm_id"] ?? ''; // Пустая строка по умолчанию не может быть +//// $salesUpdate->held = 0; // ??? +//// $salesUpdate->save(); +//// if ($salesUpdate->getErrors()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 18, "error" => $salesUpdate->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +// +//// $amount = 0; +////// $items_arr = []; +//// foreach ($arr["items"] as $itemid => $arr2) { +//// if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { +//// $arr2["seller_id"] = "NULL"; +//// } +//// $saleProductsUpdate = new SalesProductsUpdate; +//// $saleProductsUpdate->type_id = 1; +//// $saleProductsUpdate->check_id = $check_id; +//// $saleProductsUpdate->product_id = $arr2["product_id"]; +//// $saleProductsUpdate->seller_id = $arr2["seller_id"]; +//// $saleProductsUpdate->quantity = $arr2["quantity"]; +//// $saleProductsUpdate->price = $arr2["price"]; +//// $saleProductsUpdate->summ = $arr2["summ"]; +//// $saleProductsUpdate->discount = $arr2["discount"]; +//// $saleProductsUpdate->color = $arr2["color"] ?? ''; // ??? +//// $saleProductsUpdate->component_parent_id = ''; // ??? +//// $saleProductsUpdate->save(); +//// if ($saleProductsUpdate->getErrors()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 19, "error" => $saleProductsUpdate->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +//// if (!empty($arr2["components"])) { +//// foreach ($arr2["components"] as $compID => $comp) { +//// $saleProductsUpdate2 = new SalesProductsUpdate; +//// $saleProductsUpdate2->type_id = 3; +//// $saleProductsUpdate2->check_id = $check_id; +//// $saleProductsUpdate2->product_id = $comp["product_id"]; +//// $saleProductsUpdate2->seller_id = $arr2["seller_id"]; +//// $saleProductsUpdate2->quantity = $comp["quantity"]; +//// $saleProductsUpdate2->color = $comp["color"]; +//// $saleProductsUpdate2->component_parent_id = $arr2["product_id"]; +//// $saleProductsUpdate2->save(); +//// if ($saleProductsUpdate2->getErrors()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 20, "error" => $saleProductsUpdate2->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +//// } +//// } +//// } +//// } +// +// if ($update) { +// $sales2 = new Sales; +// $sales2->phone = $arr["client_phone"] ?? 0; +// $sales2->id = $arr["id"]; +// $sales2->store_id = $store_id; +// $sales2->store_id_1c = $arr["store_id"]; +// $sales2->seller_id = $arr["seller_id"]; +// $sales2->admin_id = $admin_id; +// $sales2->operation = $arr["type"]; +// $sales2->number = $arr["number"]; +// $sales2->date = $arr["date"]; +// $sales2->summ = $arr["summ"]; +// $sales2->status = $arr["status"]; +// $sales2->sales_check = $arr["sales_check"] ?? ''; +// $sales2->payments = json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); +// $sales2->pay_arr = implode(",", $pay_arr); +// $sales2->order_id = trim($arr["order_id"] ?? ''); +// $sales2->terminal = $arr["terminal"] ?? ''; +// $sales2->terminal_id = $arr["terminal_id"] ?? ''; +// $sales2->date_up = date('Y-m-d H:i:s'); +// $sales2->skidka = $arr["discount"] ?? '0'; +// $sales2->delivery_date = date('Y-m-d', strtotime($arr['delivery_date'] ?? '')); +// $sales2->pickup = $arr['pickup'] ?? false; +// $sales2->save(); +// if ($sales2->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 21, "error" => $sales2->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// +// // Обновляем данные в очереди на создание чеков +// CreateChecks::updateAll(['status' => 1], ['check_id' => $arr["id"]]); +// +// // позиции в чеке +// $amount = 0; +//// $items_arr = []; +// $productsInfos = []; +// foreach ($arr["items"] as $itemid => $arr2) { +// if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { +// $arr2["seller_id"] = null; +// } +// $saleProducts = new SalesProducts; +// $saleProducts->type_id = 1; +// $saleProducts->check_id = $check_id; +// $saleProducts->product_id = $arr2["product_id"]; +// $saleProducts->seller_id = $arr2["seller_id"]; +// $saleProducts->quantity = $arr2["quantity"]; +// $saleProducts->price = $arr2["price"]; +// $saleProducts->summ = $arr2["summ"]; +// $saleProducts->discount = $arr2["discount"]; +// $saleProducts->color = $arr2["color"]; +// $saleProducts->assemble_id = !empty($arr2["assemble_id"]) && $arr2["assemble_id"] != '00000000-0000-0000-0000-000000000000' ? $arr2["assemble_id"] : null; +// $saleProducts->save(); +// if ($saleProducts->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 22, "error" => $saleProducts->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// $assemble = Assemblies::find()->where(['guid' => $saleProducts->assemble_id])->one(); +// if ($assemble) { +// if (in_array($saleProducts->product_id, $matrixProductsIds)) { +// $productsInfos[$assemble->id] = ($productsInfos[$assemble->id] ?? 0) + $saleProducts->summ; +// } +// $assemble->date_close = $sales2->date; +// $assemble->check_id = $sales2->id; +// if ($arr["type"] == 'Продажа') { +// $assemble->status_id = 1; +// } elseif ($arr["type"] == 'Возврат') { +// $assemble->status_id = 2; +// $assemble->with_return = 1; +// } +// $assemble->save(); +// if ($assemble->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 22.2, "error" => $assemble->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// +// if (!empty($arr2["components"])) { +// foreach ($arr2["components"] as $compID => $comp) { +// $saleProducts2 = new SalesProducts; +// $saleProducts2->type_id = 3; +// $saleProducts2->check_id = $check_id; +// $saleProducts2->product_id = $comp["product_id"]; +// $saleProducts2->seller_id = $arr2["seller_id"]; +// $saleProducts2->quantity = $comp["quantity"]; +// $saleProducts2->color = $comp["color"]; +// $saleProducts2->component_parent_id = $arr2["product_id"]; +// $saleProducts2->price = 0; // ??? +// $saleProducts2->discount = 0; // ??? +// $saleProducts2->summ = 0; // ??? +// $saleProducts2->save(); +// if ($saleProducts2->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 23, "error" => $saleProducts2->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +//// $salesItems = new SalesItems; +//// $salesItems->lid_id = empty($arr["order_id"]) ? 0 : $arr["order_id"]; +//// $salesItems->check_id = $check_id; +//// $salesItems->phone = $arr["client_phone"] ?? 0; +//// $salesItems->id_1c = $arr2["product_id"]; +//// $salesItems->seller_id = $arr2["seller_id"]; +//// $salesItems->kol = $arr2["quantity"]; +//// $salesItems->color_id = $arr2["color_id"] ?? 0; +//// $salesItems->summa = $arr2["summ"]; +//// $salesItems->date = date('Y-m-d H:i:s'); +//// $salesItems->skidka = $arr2["discount"]; +//// $salesItems->store_id = 0; // ??? +//// $salesItems->store_id_1c = ''; // ??? +//// $salesItems->admin_id = 0; // ??? +//// $salesItems->item_id = 0; // ??? +//// $salesItems->complect_id = 0; // ??? +//// $salesItems->name = ''; // ??? +//// $salesItems->referal_id = 0; // ??? +//// $salesItems->vozvrat = 0; // ??? +//// $salesItems->save(); +//// if ($salesItems->getErrors()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 24, "error" => $salesItems->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +//// $amount = $amount + $arr2["price"] * $arr2["quantity"]; +//// $items_arr[] = ["product_id" => $arr2["product_id"], "seller_id" => $arr2["seller_id"], "quantity" => $arr2["quantity"], "summ" => $arr2["summ"], "discount" => $arr2["discount"]]; +// } +// foreach ($productsInfos as $assemble_id => $summ) { +// Assemblies::updateAll(['summ_matrix' => $summ], ['id' => $assemble_id]); +// } +// } +// } +// } elseif (!empty($result['checks'])) { +// file_put_contents(self::OUT_DIR . '/error_upload.txt', +// PHP_EOL . "elseif", FILE_APPEND); +// $dataArrayValues = $this->getSalesDate($result["checks"], $update); +// +// foreach ($dataArrayValues as $keyMethodName => $rowValue) { +// file_put_contents(self::OUT_DIR . '/error_upload.txt', +// PHP_EOL . $keyMethodName, FILE_APPEND); +// try { +// $this->$keyMethodName($rowValue, $update); +// } catch (Exception $e) { +// $errorString = substr($e->getMessage(), 0, 2000); +// InfoLogService::setInfoLog(__FILE__, __LINE__, $errorString, 'error_id_25_m_st'); +// } +// } +// } +// +// if (!empty($result['balances'])) { +// foreach ($result["balances"] as $std => $arr) { +// Balances::deleteAll(['store_id' => $std]); +// foreach ($arr as $pid => $arr2) { +// $balances = new Balances; +// $balances->store_id = $std; +// $balances->product_id = $pid; +// $balances->quantity = $arr2[0]; +// $balances->reserv = $arr2[1]; +// $balances->save(); +// if ($balances->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 26, "error" => $balances->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// } +// +// if (!empty($result['prices'])) { +// foreach ($result["prices"] as $idp => $price) { +// if ( +// !empty($price) +// && +// in_array( +// $type_price, +// array_keys(Prices::REGION_TYPE_PRICES) +// ) +// ) { +// $region_id = Prices::REGION_TYPE_PRICES[$type_price]; +// Prices::deleteAll(['product_id' => $idp]); +// $price1 = new Prices; +// $price1->product_id = $idp; +// $price1->price = $price; +// $price1->save(); +// if ($price1->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 27, "error" => $price1->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// PricesRegion::deleteAll(['product_id' => $idp, 'region_id' => $region_id]); +// $priceRegion = new PricesRegion; +// $priceRegion->product_id = $idp; +// $priceRegion->region_id = $region_id; +// $priceRegion->price = $price; +// $priceRegion->save(); +// if ($priceRegion->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 27.5, "error" => $priceRegion->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// try { +// $pricesDynamic = PricesDynamic::find()->where(['product_id' => $idp, 'region_id' => $region_id])->andWhere(['active' => '1'])->orderBy(['id' => SORT_DESC])->one(); +// $price = round($price, 2); +// // если нет записи или цена изменилась то вносим запись в БД +// if ($pricesDynamic and $pricesDynamic->price != $price) { +// $pricesDynamic->active = 0; +// $pricesDynamic->date_to = date('Y-m-d H:i:s'); +// $pricesDynamic->save(); +// if ($pricesDynamic->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 28, "error" => $pricesDynamic->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// if (!$pricesDynamic or ($pricesDynamic and ($pricesDynamic->price != $price || $pricesDynamic->region_id != $region_id))) { +// $pricesDynamic2 = new PricesDynamic; +// $pricesDynamic2->product_id = $idp; +// $pricesDynamic2->price = $price; +// $pricesDynamic2->date_from = date('Y-m-d H:i:s'); +// $pricesDynamic2->date_to = '2100-01-01 00:00:00'; +// $pricesDynamic2->active = 1; +// $pricesDynamic2->region_id = $region_id; +// $pricesDynamic2->save(); +// if ($pricesDynamic2->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 29, "error" => $pricesDynamic2->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } catch (Exception $e) { +// file_put_contents(self::OUT_DIR . '/log_prices_dinamics.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage(), FILE_APPEND); +// } +// } +// } +// } +// +// if (!empty($result['prices'])) { +// foreach ($result["prices"] as $idp => $price) { +// if (!empty($price) and $type_price == "Закупочная цена руб.") { +// try { +// $priceZakup = new PricesZakup; +// $priceZakup->product_id = $idp; +// $priceZakup->price = $price; +// $priceZakup->save(); +// if ($priceZakup->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 30, "error" => $priceZakup->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } catch (Exception $e) { +// } +// } +// if (!empty($price) and $type_price == "Себестоимость") { +// try { +// file_put_contents(self::OUT_DIR . '/price_purchese.txt', PHP_EOL . "$idp=" . $price, FILE_APPEND); +// } catch (Exception $e) { +// } +// } +// } +// } +// +// if (!empty($result['created_checks'])) { +// foreach ($result["created_checks"] as $idp => $arr2) { +// if (!empty($arr2["error"])) { // Если есть ошибки +// // // обновляем GUID на новый +//// try { +//// $createChecks = CreateChecks::find()->select(['order_id'])->where(['check_id' => $arr2["id"]])->one(); +//// if ($createChecks) { +//// $lid_id = $createChecks->order_id; +//// $guid_new = \yii_app\controllers\crud\UniversalCatalogController::create_guid_my_old("01", $lid_id); +//// $createChecks2 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->andWhere(['!=', 'check_id', '0']) +//// ->andWhere(['status' => '0'])->andWhere(['held' => '0'])->one(); +//// if ($createChecks2) { +//// $createChecks2->check_id = $guid_new; +//// $createChecks2->save(); +//// if ($createChecks2->getErrors()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 32, "error" => $createChecks2->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +//// } +//// } else { +//// LogService::apiErrorLog(json_encode(["error_id" => 31, "error" => 'no create_checks with check_id=' . $arr2["id"]], JSON_UNESCAPED_UNICODE)); +//// } +//// } catch (Exception $e) { +//// file_put_contents(self::OUT_DIR . '/log_created_check_error.txt', PHP_EOL . date("d.m.Y H:i:s",time()). $e->getMessage(), FILE_APPEND); +//// } +// +// $txt = date("d.m.Y H:i:s", time()) . " $idp СОЗДАНИЕ ЧЕКА ОШИБКА id=" . $arr2["id"] . " " . $arr2["error"]; +// file_put_contents(self::OUT_DIR . '/log_created_check_error.txt', PHP_EOL . $txt, FILE_APPEND); +// } else { // Если ошибок нет +// if (/* $arr2["held"] == true and */ !empty($arr2["name"]) and !empty($arr2["id"])) { // Если заполнен name b id +//// $createChecksBags = CreateChecksBags::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]])->orderBy(['id' => SORT_DESC])->one(); +//// if ($createChecksBags) { +//// $createChecksBags->guid = $arr2["guid"]; +//// $createChecksBags->name = $arr2["name"]; +//// $createChecksBags->held = $arr2["held"]; +//// $createChecksBags->status = '1'; +//// $createChecksBags->date_up = date('Y-m-d H:I:s'); +//// $createChecksBags->save(); +//// if ($createChecksBags->getErrors()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 33, "error" => $createChecksBags->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +//// } +// // Обновляем данные в очереди на создание чеков +// CreateChecks::updateAll([ +// 'status' => 1, +// 'guid' => $arr2["id"], +// 'date_up' => date('Y-m-d H:i:s'), +// 'name' => $arr2["name"], +// 'held' => isset($arr2["held"]) ? $arr2["held"] : 0 +// ], ['check_id' => $arr2["id"]]); +//// $createChecks3 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->orderBy(['id' => SORT_DESC])->one(); +//// if ($createChecks3) { +//// $createChecks3->guid = $arr2["id"]; +//// $createChecks3->name = $arr2["name"]; +//// $createChecks3->held = isset($arr2["held"]) ? ($arr2["held"] ? 1 : 0) : 0; +//// $createChecks3->status = '1'; +//// $createChecks3->date_up = date('Y-m-d H:i:s'); +//// $createChecks3->save(); +//// if ($createChecks3->getErrors()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 34, "error" => $createChecks3->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +//// } +//// $createChecks4 = CreateChecks2::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]])->orderBy(['id' => SORT_DESC])->one(); +//// if ($createChecks4) { +//// $createChecks4->name = $arr2["name"]; +//// $createChecks4->held = $arr2["held"]; +//// $createChecks4->status = '1'; +//// $createChecks4->date_up = date('Y-m-d H:I:s'); +//// $createChecks4->save(); +//// if ($createChecks4->getErrors()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 35, "error" => $createChecks4->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +//// } +//// $createChecks5 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]]) +//// ->andWhere(['type' => 'Возврат'])->orderBy(['id' => SORT_DESC])->one(); +//// if ($createChecks5) { +//// $createChecks5->held = $arr2["held"]; +//// $createChecks5->status = '1'; +//// $createChecks5->date_up = date('Y-m-d H:I:s'); +//// $createChecks5->save(); +//// if ($createChecks5->getErrors()) { +//// LogService::apiErrorLog(json_encode(["error_id" => 35, "error" => $createChecks5->getErrors()], JSON_UNESCAPED_UNICODE)); +//// } +//// } +// // прикрепляем чек к заказу +// $ordersAmo = OrdersAmo::find()->where(['id' => $arr2["order_id"]])->one(); +// if ($ordersAmo) { +// $ordersAmo->check_id_arr = $arr2["id"]; +// $ordersAmo->save(false); +// if ($ordersAmo->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 36, "error" => $ordersAmo->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// +// // обращаемся к старой базе данных базацветов_24 +// // ??? +// } +// } +// } +// } +// +// if (!empty($result['created_employee'])) { +// foreach ($result['created_employee'] as $arr) { +// EmployeeOnShift::updateAll(['status_source' => EmployeeOnShift::STATUS_SOURCE_CREATED_IN_1C], ['guid' => $arr['id']]); +// } +// } +// +// if (!empty($result['marketplace_orders'])) { +// foreach ($result["marketplace_orders"] as $mpOrder) { +// $updateResult = self::changeMarketplaceOrderStatusFrom1C($mpOrder); //изменение статусов +// if ($updateResult['status'] == 'error') { +// LogService::apiErrorLog(json_encode(["error_id" => 40, "error" => $updateResult['message']], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// +//// +// $mess["request_id"] = "" . time(); +// +// if (!empty($result['created_orders'])) { +// $mess['line'][] = __LINE__; +// $mess["created_orders"] = $result['created_orders']; +// $productsNames = Products1c::getNamesByTip('products'); +// foreach ($result['created_orders'] as $arr) { +// $marketplaceOrders = null; +// $marketplaceOrdersGuidArr = []; +// if (!empty($arr["id"])) { +// $marketplaceOrders = MarketplaceOrders::find()->where(['guid' => $arr["id"]])->one(); +// if ($marketplaceOrders && $marketplaceOrders->guid) { +// $marketplaceOrdersGuidArr[] = $marketplaceOrders->guid; +// } +// } +// if (!empty($marketplaceOrders)) { +// /** @var MarketplaceOrders $marketplaceOrders */ +// $mess['line'][] = __LINE__; +// if (!empty($arr["errors"]) || !empty($arr["error"]) || !empty($arr["errors_items"])) { +// $errorText = ''; +// if (!empty($arr["errors"])) { +// //"errors": [ +// //{ +// //"error": "Ошибка преобразования ИД документа", +// //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", +// //"error_json": [ +// //{ +// //"field": "id", +// //"error": "Документ с данным ИД уже записан в системе" +// //} +// // +// +// foreach ($arr["errors"] as $errorRow) { +// if (!empty($errorRow['error'])) { +// $errorText .= $errorRow['error']; +// +// $errorText .= ' ,' . $errorRow['error_description']; +// if (!empty($errorRow['error_json'])) { +// foreach ($errorRow['error_json'] as $errorJsonRow) { +// $errorText .= ' , поле: ' . $errorJsonRow['field']; +// $errorText .= ' , ошибка: ' . $errorJsonRow['error']; +// } +// } +// } +// +// if (!empty($errorRow["errors_items"])) { +// foreach ($errorRow["errors_items"] as $errorDopRow) { +// //"errors_items": [ +// //{ +// //"error_dop": "Ошибка проверки количества номенклатуры", +// //"field": "quantity", +// //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", +// //"error": "У данной позиции запрещён ввод дробного значения!" +// //}, +// // +// // +// $productName = $errorDopRow['product_id']; +// +// if (array_key_exists($errorDopRow['product_id'], $productsNames)) { +// $productName = $productsNames[$errorDopRow['product_id']]; +// } +// +// $errorText .= ' ' . $errorDopRow['error_dop']; +// $errorText .= ' , поле: ' . $errorDopRow['field']; +// $errorText .= ' , товар: ' . $productName; +// $errorText .= ' , ошибка: ' . $errorDopRow['error']; +// } +// } +// } +// } +// +// if (!empty($arr["error"])) { +// //"error": "Ошибка преобразования ИД документа", +// //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", +// $errorText .= $arr["error"]; +// $errorText .= ' ,' . $arr['error_description']; +// } +// +// $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; +// $marketplaceOrders->error_text = $errorText; +// $marketplaceOrders->save(); +// if ($marketplaceOrders->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } else { +// $mess['line'][] = __LINE__; +// if (isset($arr["held"]) && $arr["held"]) { +// $mess['line'][] = __LINE__; +// $marketplaceOrders->number_1c = $arr["number"] ?? ''; +// $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_1C; +// $marketplaceOrders->save(); +// if ($marketplaceOrders->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 42, "error" => $marketplaceOrders->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// } +// } +// } +// +// $now = time(); +// $sendedOrders = MarketplaceOrders::find() +// ->where(['status_1c' => MarketplaceOrders::STATUSES_1C_SENDED_TO_1C]) +// ->andWhere(['not in', 'guid', $marketplaceOrdersGuidArr]) +// ->all(); +// foreach ($sendedOrders as $order) { +// $sentAt = strtotime($order->sent_1c_at ?? '2025-07-01 00:00:00'); +// $attempts = (int)$order->attempts_number; +// if (($now - $sentAt) > 300) { +// if ($attempts < 4) { +// $order->sent_1c_at = null; +// $order->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_ERP; +// $order->save(); +// } else { +// $order->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; +// $order->error_text = 'Превышено число попыток отправки в 1С.'; +// $order->save(); +// +// LogService::apiErrorLog(json_encode([ +// "error_id" => 43, +// "error" => "Превышено число попыток отправки в 1С " . $order->guid, +// ], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// +// } +// +// if (!empty($result['analysts_business_operations'])) { +// $existingOperations = AnalystsBusinessOperations::find() +// ->indexBy('id') +// ->asArray() +// ->all(); +// $existingTypes = AnalystsBusinessOperationsTypes::find() +// ->indexBy('code') +// ->asArray() +// ->all(); +// foreach ($result["analysts_business_operations"] as $operation) { +// if (!in_array($operation['id'], array_keys($existingOperations))) { +// $newOperation = new AnalystsBusinessOperations(); +// $newOperation->id = $operation['id']; +// $newOperation->name = $operation['name']; +// $newOperation->type = (int)$operation['type']; +// $newOperation->active = 1; +// if (!in_array((int)$operation['type'], array_column($existingTypes, 'code'))) { +// $newType = new AnalystsBusinessOperationsTypes(); +// $newType->code = (int)$operation['type']; +// $newType->name = null; +// $newType->alias = null; +// $newType->created_at = date('Y-m-d H:i:s'); +// $newType->created_by = 1409; +// if ($newType->save()) { +// $newOperation->type_id = $newType->id; +// } else { +// $newOperation->type_id = null; +// Yii::error('Ошибка сохранение типа ' . json_encode($newType->getErrors(), JSON_UNESCAPED_UNICODE), __METHOD__ ); +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 44.1, "error" => $newType->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } else { +// $newOperation->type_id = $existingTypes[$operation['type']]['id']; +// } +// $newOperation->created_at = date('Y-m-d H:i:s'); +// if (!$newOperation->save()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 44.2, "error" => $newOperation->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// +// } else { +// if ($existingOperations[$operation['id']]['type'] !== (int)$operation['type']) { +// $oldOperation = AnalystsBusinessOperations::findOne($operation['id']); +// if (!in_array((int)$operation['type'], array_column($existingTypes, 'code'))) { +// $newType = new AnalystsBusinessOperationsTypes(); +// $newType->code = (int)$operation['type']; +// $newType->name = null; +// $newType->alias = null; +// $newType->created_at = date('Y-m-d H:i:s'); +// $newType->created_by = 1409; +// if ($newType->save()) { +// $oldOperation->type = (int)$operation['type']; +// $oldOperation->type_id = $newType->id; +// if (!$oldOperation->save()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 44.3, "error" => $oldOperation->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } else { +// Yii::error('Ошибка сохранение типа ' . json_encode($newType->getErrors(), JSON_UNESCAPED_UNICODE), __METHOD__ ); +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 44.4, "error" => $oldOperation->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } else { +// $oldOperation->type = (int)$operation['type']; +// $oldOperation->type_id = AnalystsBusinessOperationsTypes::find()->where(['code' => (int)$operation['type']])->one()->id; +// if (!$oldOperation->save()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 44.5, "error" => $oldOperation->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// } +// } +// +// } +// } +// if (!empty($result['cancelled_orders'])) { +// foreach ($result['cancelled_orders'] as $arr) { +// $marketplaceOrders = null; +// $marketplaceOrdersGuidArr = []; +// +// $marketplaceOrders = MarketplaceOrders::find()->where(['guid' => $arr])->one(); +// $marketplaceOrdersGuidArr[] = $marketplaceOrders->guid; +// +// if (!empty($marketplaceOrders)) { +// /** @var MarketplaceOrders $marketplaceOrders */ +// +// if (!empty($arr["errors"]) || !empty($arr["error"]) || !empty($arr["errors_items"])) { +// $errorText = ''; +// if (!empty($arr["errors"])) { +// +// +// foreach ($arr["errors"] as $errorRow) { +// if (!empty($errorRow['error'])) { +// $errorText .= $errorRow['error']; +// +// $errorText .= ' ,' . $errorRow['error_description']; +// if (!empty($errorRow['error_json'])) { +// foreach ($errorRow['error_json'] as $errorJsonRow) { +// $errorText .= ' , поле: ' . $errorJsonRow['field']; +// $errorText .= ' , ошибка: ' . $errorJsonRow['error']; +// } +// } +// } +// } +// } +// +// if (!empty($arr["error"])) { +// //"error": "Ошибка преобразования ИД документа", +// //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", +// $errorText .= $arr["error"]; +// $errorText .= ' ,' . $arr['error_description']; +// } +// +// $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; +// $marketplaceOrders->error_text = $errorText; +// $marketplaceOrders->save(); +// if ($marketplaceOrders->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } else { +// $marketplaceOrders->cancelled_order_sent = MarketplaceOrders::STATUSES_1C_CANCELLED_ORDER_SENT_IN_1C; +// $marketplaceOrders->save(); +// if ($marketplaceOrders->getErrors()) { +// LogService::apiErrorLog( +// json_encode( +// ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], +// JSON_UNESCAPED_UNICODE +// ) +// ); +// } +// } +// } +// } +// +// +// +// } +// +// $mess['line'][] = __LINE__; +// } catch (Exception $e) { +// LogService::apiDataLogs(1, json_encode($mess, JSON_UNESCAPED_UNICODE), $requestIdText); +// file_put_contents(self::OUT_DIR . '/log_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage() . " " . $e->getLine(), FILE_APPEND); +// Yii::error('Ошибка upload - блок catch '. json_encode($e->getMessage() . " " . $e->getLine(), JSON_UNESCAPED_UNICODE)); +// LogService::apiErrorLog(json_encode([ +// "error_id" => 45, +// "error" => "Ошибка загрузки " . $e->getMessage() . " " . $e->getLine(), +// ], JSON_UNESCAPED_UNICODE)); +// } finally { +// LogService::apiDataLogs(1, json_encode($mess, JSON_UNESCAPED_UNICODE), $requestIdText); +// } + + Yii::$app->queue->push(new SendRequestUploadDataToJob(['decodingResult' => $result])); - if (!in_array($arr2['id'], $existTerminals)) { - $terminal = new Terminals; - $terminal->id = $arr2["id"]; - $terminal->name = $arr2["name"]; - $terminal->code = $arr2["code"]; - $terminal->store_id = $arr["id"]; - $terminal->date = date('Y-m-d H:i:s'); - $terminal->posit = $k; - $terminal->save(); - if ($terminal->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 4, "error" => $terminal->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } - $k++; - } - } + return $this->asJson(['response' => true]); + } - if ($arr['kkms']) { - foreach ($arr["kkms"] as $gi2 => $arr2) { - if (!in_array($arr2['id'], $products1cByTipMap['kkms'])) { - $products1c3 = new Products1c; - $products1c3->id = $arr2["id"]; - $products1c3->tip = 'kkms'; - $products1c3->name = $arr2["name"]; - $products1c3->code = $arr2["code"]; - $products1c3->save(); - if ($products1c3->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 5, "error" => $products1c3->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } - } - } + private function getPayArr($arrPayments): array + { + $pay_arr = array(); + if (!empty($arrPayments)) { + foreach ($arrPayments as $tp) { + if ($tp["type"] == "Наличные") { + $pay_arr[] = 1; + } elseif ($tp['type'] == 'QR код') { + $pay_arr[] = 3; + } else { + $pay_arr[] = 2; } } - if (!empty($result['self_cost'])) { - $storeMap = []; - - $cityStoreIds = CityStore::find()->select('id')->column(); - - // Получаем соответствия export_val => entity_id из таблицы ExportImportTable - $exportImportRecords = ExportImportTable::find() - ->select(['entity_id', 'export_val']) - ->where(['entity_id' => $cityStoreIds, 'entity' => 'city_store', 'export_id' => 1]) - ->all(); - - // Создаем справочник - foreach ($exportImportRecords as $record) { - $storeMap[$record->export_val] = $record->entity_id; - } - - $values = []; - - foreach ($result['self_cost'] as $selfCost) { - $storeId = $storeMap[$selfCost['store_id']] ?? null; - if (!$storeId) { - continue; - } - - - // Удаляем старые данные - SelfCostProduct::deleteAll(['date' => $selfCost['date'], 'store_id' => $storeId]); - - foreach ($selfCost['items'] as $item) { - $values[] = [ - 'date' => $selfCost['date'], - 'store_id' => $storeId, - 'product_guid' => $item['product_id'], - 'price' => $item['price'], - 'updated_at' => date('Y-m-d H:i:s') - ]; - } - } + } - if (!empty($values)) { - $this->setSelfCostUpdate($values); - SelfCostProductDinamicService::UpdateResult($values); - } - } + return $pay_arr; + } + private function getSalesDate($checks, $update): array + { + $admins = $this->getEntityByType('admin'); - if (!empty($result['sellers'])) { - Products1c::deleteAll(['tip' => 'admin']); + $adminsIds = array_column($admins, 'entity_id'); + $adminsValue = array_column($admins, 'export_val'); - foreach ($result["sellers"] as $gi => $arr) { - EmployeeOnShift::updateAll(['status_source' => EmployeeOnShift::STATUS_SOURCE_CREATED_IN_1C], ['guid' => $arr['id']]); - $products1c4 = new Products1c; - $products1c4->id = $arr["id"]; - $products1c4->tip = 'admin'; - $products1c4->name = $arr["name"]; - $products1c4->code = $arr["code"] ?? ''; - $products1c4->parent_id = $arr["parent_id"] ?? ''; - $products1c4->save(); - if ($products1c4->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 6, "error" => $products1c4->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } - } + $adminsGuidIds = array_combine($adminsValue, $adminsIds); + $adminsIdsGuid = array_combine($adminsIds, $adminsValue); - if (!empty($result["nomenclature"]["groups"])) { - Products1c::deleteAll(['tip' => 'products_group']); - foreach ($result["nomenclature"]["groups"] as $gi => $arr) { - $products1c5 = new Products1c; - $products1c5->id = $arr["id"]; - $products1c5->tip = 'products_group'; - $products1c5->name = $arr["name"]; - $products1c5->code = $arr["code"] ?? ''; - $products1c5->articule = $arr["articule"] ?? ''; - $products1c5->parent_id = $arr["parent_id"] ?? '0'; - $products1c5->save(); - if ($products1c5->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 7, "error" => $products1c5->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } - } - if (!empty($result["nomenclature"]["elements"])) { -// Products1c::deleteAll(['and', ['tip' => 'products'], ['view' => 0]]); - $bouquets = BouquetComposition::find()->select('guid')->column(); - foreach ($result["nomenclature"]["elements"] as $gi => $arr) { -// if (!empty($arr["name"]) && in_array($arr["name"][0], ['ь', 'Ь', 'ъ', 'Ъ'])) { // Не вносим номенклатуру, помеченную на удаление -// continue; -// } - $components = !empty($arr["components"]) ? json_encode($arr["components"], JSON_UNESCAPED_UNICODE) : ""; // Пустые компоненты не надо разворачивать в json объект - $products1c6 = Products1c::find()->where(['id' => $arr["id"]])->one(); - if (!$products1c6) { - $products1c6 = new Products1c; - $products1c6->id = $arr["id"]; - $products1c6->tip = 'products'; - } - $products1c6->name = $arr["name"]; - $products1c6->code = $arr["code"]; - $products1c6->type = $arr["type"]; - $products1c6->articule = $arr["articule"]; - $products1c6->parent_id = $arr["parent_id"]; - $products1c6->view = $arr["view"]; - $products1c6->components = $components; - $products1c6->save(); - if ($products1c6->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 8, "error" => $products1c6->getErrors()], JSON_UNESCAPED_UNICODE)); - } + $stores = $this->getEntityByType(); - if(!empty($arr["components"])) { - if(!in_array($arr["id"], $bouquets)) { - $newBouquetComp = new BouquetComposition(); - $newBouquetComp->guid = $arr["id"]; - $newBouquetComp->name = $arr["name"]; - $newBouquetComp->status = 1; - $newBouquetComp->matrix_type_id = 1; - $newBouquetComp->created_by = Admin::getAdminAgentId() ?: null; - if(!$newBouquetComp->save()) { - LogService::apiErrorLog(json_encode(["error_id" => 8.1, "error" => $newBouquetComp->getErrors()], JSON_UNESCAPED_UNICODE)); - } else { - foreach ($arr["components"] as $guid => $quantity) { - $newBouquetCompProd = new BouquetCompositionProducts(); - $newBouquetCompProd->bouquet_id = $newBouquetComp->id; - $newBouquetCompProd->product_guid = $guid; - $newBouquetCompProd->count = $quantity; - $newBouquetCompProd->created_by = Admin::getAdminAgentId() ?: null; - if(!$newBouquetCompProd->save()) { - LogService::apiErrorLog(json_encode(["error_id" => 8.2, "error" => $newBouquetCompProd->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } -// $costModels = []; -// foreach (BouquetComposition::getRegions() as $region_id) { -// $costModels[$region_id] = $newBouquetComp->getCostModel($region_id, array_keys($arr["components"]), true); -// } -// if(empty($costModels)) { -// LogService::apiErrorLog(json_encode(["error_id" => 8.3, "error" => "Стоимость и цена не подсчитаны"], JSON_UNESCAPED_UNICODE)); -// } -// $bouquetTypeHistory = new BouquetCompositionMatrixTypeHistory(); -// $bouquetTypeHistory->bouquet_id = $newBouquetComp->id; -// $bouquetTypeHistory->matrix_type_id = 1; -// $bouquetTypeHistory->created_by = Admin::getAdminAgentId() ?: null; -// $bouquetTypeHistory->is_active = 1; -// $bouquetTypeHistory->date_from = date('Y-m-d H:i:s'); -// if(!$bouquetTypeHistory->save()) { -// LogService::apiErrorLog(json_encode(["error_id" => 8.4, "error" => $bouquetTypeHistory->getErrors()], JSON_UNESCAPED_UNICODE)); -// } - } - } - } + $storesIds = array_column($stores, 'entity_id'); + $storesValue = array_column($stores, 'export_val'); - foreach ($arr as $key => $property) { - if (!in_array($key, Products1c::PRODUCT1C_FIELDS)) { - if (empty($property)) continue; - $propertyType = Products1cPropType::findOne(['id' => $key]); - if (!$propertyType) { - $propertyType = new Products1cPropType(); - $propertyType->id = $key; - $propertyType->name = $key; - if (!$propertyType->save()) { - LogService::apiErrorLog(json_encode(["error_id" => 8.1, - "error" => $propertyType->getErrors()], - JSON_UNESCAPED_UNICODE)); - continue; - } - } - $additionalCharacteristic = Products1cAdditionalCharacteristics::findOne([ - 'product_id' => $arr["id"], - 'property_id' => $key - ]); - if (!$additionalCharacteristic && !empty($property)) { - $additionalCharacteristic = new Products1cAdditionalCharacteristics(); - $additionalCharacteristic->product_id = $arr["id"]; - $additionalCharacteristic->property_id = $key; - } - $additionalCharacteristic->value = $property; - if (!$additionalCharacteristic->save()) { - LogService::apiErrorLog(json_encode(["error_id" => 8.2, - "error" => $additionalCharacteristic->getErrors()], - JSON_UNESCAPED_UNICODE)); - } - } - } + $storesGuidIds = array_combine($storesValue, $storesIds); + $storesIdsGuid = array_combine($storesIds, $storesValue); - if (!empty($arr["AdditionCharacteristics"])) { - $passedCharacteristics = array_column($arr["AdditionCharacteristics"], null, "id"); - $currentCharacteristics = Products1cAdditionalCharacteristics::find() - ->where(['product_id' => $arr["id"]]) - ->indexBy('property_id') - ->all(); + $checksIdsPrepared = array_column($checks, 'id'); - foreach ($currentCharacteristics as $propertyId => $currentCharacteristic) { - if (!isset($passedCharacteristics[$propertyId])) { - if (!$currentCharacteristic->delete()) { - LogService::apiErrorLog(json_encode([ - "error_id" => 8.39, - "error" => $currentCharacteristic->getErrors() - ], JSON_UNESCAPED_UNICODE)); - } - } - } + $checksIds = array_unique($checksIdsPrepared); - foreach ($arr["AdditionCharacteristics"] as $characteristic) { - $propertyType = Products1cPropType::findOne(['id' => $characteristic["id"]]); - if (!$propertyType) { - $propertyType = new Products1cPropType(); - $propertyType->id = $characteristic["id"]; - $propertyType->name = $characteristic["name"]; - if (!$propertyType->save()) { - LogService::apiErrorLog(json_encode(["error_id" => 8.1, - "error" => $propertyType->getErrors()], - JSON_UNESCAPED_UNICODE)); - continue; - } - } + $checksValues = []; + $salesProducts = []; + $salesItems = []; + $salesProductsComponents = []; - $additionalCharacteristic = Products1cAdditionalCharacteristics::findOne([ - 'product_id' => $arr["id"], - 'property_id' => $characteristic["id"] - ]); + foreach ($checks as $arr) { + $check_id = $arr["id"]; - if (!$additionalCharacteristic) { - $additionalCharacteristic = new Products1cAdditionalCharacteristics(); - $additionalCharacteristic->product_id = $arr["id"]; - $additionalCharacteristic->property_id = $characteristic["id"]; - } + if (array_key_exists($arr["store_id"], $storesGuidIds)) { + $store_id = $storesGuidIds[$arr["store_id"]]; + } + if (array_key_exists($arr["seller_id"], $adminsGuidIds)) { + $admin_id = $adminsGuidIds[$arr["seller_id"]]; + } - $additionalCharacteristic->value = $characteristic["value_name"]; - if (!$additionalCharacteristic->save()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 8.2, "error" => $additionalCharacteristic->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } - } - if ( - !empty($arr["type"]) - && str_starts_with($arr["type"], '[') - && str_ends_with($arr["type"], ']') - ) { - // return [$arr["type"]]; - $product1cNomenclature = Products1cNomenclature::find()->where(['id' => $arr["id"]])->one(); - if (!$product1cNomenclature) { - $product1cNomenclature = new Products1cNomenclature(); - $product1cNomenclature->id = $arr["id"]; - } - $typeNomenclature = rtrim(ltrim($arr["type"], '['), ']'); - $typeArr = explode("/", $typeNomenclature); - $category = $typeArr[0]; - $subcategory = $typeArr[1] ?? null; - $product1cNomenclature->name = $arr["name"]; - $product1cNomenclature->location = $arr["type"]; - $product1cNomenclature->type_num = $typeNomenclature; - $product1cNomenclature->category = $category; - $product1cNomenclature->subcategory = $subcategory; - $characteristics = Products1cAdditionalCharacteristics::find() - ->select(['property_id', 'value']) - ->where(['product_id' => $arr["id"]]) - ->indexBy(['property_id']) - ->asArray() - ->all(); + $pay_arr = $this->getPayArr($arr["payments"]); - $propTypes = array_keys($characteristics); - $propertyNames = Products1cPropType::find() - ->select(['id','name']) - ->where(['id' => $propTypes]) - ->indexBy('id') - ->asArray() - ->all(); - $characteristicsValues = []; + if (empty($store_id)) { + continue; + } - foreach ($propertyNames as $propertyId => $property) { - if (isset($characteristics[$propertyId])) { - $characteristicsValues[$property['name']] = $characteristics[$propertyId]['value']; - } - } + $date_up = date("Y-m-d H:i:s"); + $date = date("Y-m-d H:i:s"); - $sizeValue = 0; - if (isset($characteristicsValues['size']) && intval($characteristicsValues['size'])) { - $sizeValue = intval($characteristicsValues['size']); - } - if (isset($characteristicsValues['размер']) && intval($characteristicsValues['размер'])) { - $sizeValue = intval($characteristicsValues['размер']); - } + $purchaseItemsArray = []; - $speciesValue = null; - if (isset($characteristicsValues['species']) && !empty($characteristicsValues['species'])) { - $speciesValue = $characteristicsValues['species']; - } - if (isset($characteristicsValues['вид']) && !empty($characteristicsValues['вид'])) { - $speciesValue = $characteristicsValues['вид']; - } + // позиции в чеке + $amount = 0; + $items_arr = []; + foreach ($arr["items"] as $itemid => $arr2) { + if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { + $arr2["seller_id"] = null; + } - $sortValue = null; - if (isset($characteristicsValues['sort']) && !empty($characteristicsValues['sort'])) { - $sortValue = $characteristicsValues['sort']; - } - if (isset($characteristicsValues['сорт']) && !empty($characteristicsValues['сорт'])) { - $sortValue = $characteristicsValues['сорт']; - } + $purchaseItemsRow = 0; + if (!empty($arr2["purchase_price"]) && !empty($arr2["quantity"])) { + $purchaseItemsRow = $arr2["purchase_price"] * $arr2["quantity"]; + } - $typeValue = null; - if (isset($characteristicsValues['type']) && !empty($characteristicsValues['type'])) { - $typeValue = $characteristicsValues['type']; - } - if (isset($characteristicsValues['тип']) && !empty($characteristicsValues['тип'])) { - $typeValue = $characteristicsValues['тип']; - } + $purchaseItemsArray[] = $purchaseItemsRow; - $measureValue = null; - if (isset($characteristicsValues['measure']) && !empty($characteristicsValues['measure'])) { - $measureValue = $characteristicsValues['measure']; - } + $salesProducts[] = [ + 'type_id' => '1', // type_id, + 'check_id' => $check_id, // check_id, + 'product_id' => $arr2["product_id"], // product_id, + 'seller_id' => $arr2["seller_id"], // seller_id, + 'quantity' => $arr2["quantity"], // quantity, + 'price' => $arr2["price"], // price, + 'summ' => $arr2["summ"], // summ, + 'purchase_price' => $arr2["purchase_price"] ?? 0, // purchase_price, + 'purchase_sum' => $purchaseItemsRow, // purchase_sum, + 'discount' => $arr2["discount"], // discount, + 'color' => $arr2["color"] // color + ]; - $colorValue = null; - if (isset($characteristicsValues['color']) && !empty($characteristicsValues['color'])) { - $colorValue = $characteristicsValues['color']; - } - if (isset($characteristicsValues['цвет']) && !empty($characteristicsValues['цвет'])) { - $colorValue = $characteristicsValues['цвет']; - } + $log[$arr["id"]][$itemid] = $arr2; - $product1cNomenclature->species = $speciesValue; - $product1cNomenclature->sort = $sortValue; - $product1cNomenclature->type = $typeValue; - $product1cNomenclature->size = $sizeValue; - $product1cNomenclature->measure = $measureValue; - $product1cNomenclature->color = $colorValue; + if (!empty($arr2["components"])) { + foreach ($arr2["components"] as $compID => $comp) { + $salesProductsComponents[] = + [ + 'type_id' => '3', // type_id + 'check_id' => $check_id, // check_id + 'product_id' => $comp["product_id"], // product_id + 'seller_id' => $arr2["seller_id"], // seller_id + 'quantity' => $comp["quantity"], // quantity + 'color' => $comp["color"], // color + 'component_parent_id' => $arr2["product_id"], // component_parent_id + 'price' => 0, // price, + 'discount' => 0, // discount, + 'summ' => 0, // summ, + ]; - if (!$product1cNomenclature->save()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 8.3, "error" => $product1cNomenclature->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } + $salesItems[] = [ + 'lid_id' => $arr["order_id"], // lid_id + 'check_id' => $check_id, // check_id + 'phone' => $arr["client_phone"] ?? null, // phone + 'id_1c' => $arr2["product_id"], // id_1c + 'seller_id' => $arr2["seller_id"], // seller_id + 'kol' => $arr2["quantity"], // kol + 'color_id' => $arr2["color_id"] ?? 0, // color_id + 'summa' => $arr2["summ"], // summa + 'skidka' => $arr2["discount"], // skidka + 'date' => $date, // date + ]; } } } - if (!empty($result['payment_types'])) { - foreach ($result["payment_types"] as $gi => $arr) { - $paymentTypes = PaymentTypes::findOne(['id' => $arr['id']]) ?? new PaymentTypes(); - $paymentTypes->id = $arr['id']; - $paymentTypes->code = $arr['code']; - $paymentTypes->name = $arr['name']; - $paymentTypes->save(); - if ($paymentTypes->getErrors()) { - LogService::apiErrorLog(json_encode( - ["error_id" => 9, - "error" => $paymentTypes->getErrors()], - JSON_UNESCAPED_UNICODE - )); - } + $purchaseItemsSum = array_sum($purchaseItemsArray); + + $checksValues[] = [ + 'phone' => $arr["client_phone"] ?? null, // phone, + 'id' => $arr["id"], // id, + 'store_id' => $store_id, // store_id, + 'store_id_1c' => $arr["store_id"], // store_id_1c, + 'seller_id' => $arr["seller_id"], // seller_id, + 'admin_id' => $admin_id, // admin_id, + 'operation' => $arr["type"], // operation, + 'number' => $arr["number"], // number, + 'date' => $arr["date"], // date, + 'summ' => $arr["summ"], // summ, + 'purchase_sum' => $purchaseItemsSum ?? 0, // purchase_sum, + 'status' => $arr["status"], // status, + 'sales_check' => $arr["sales_check"] ?? '', // sales_check, + 'payments' => json_encode($arr["payments"], JSON_UNESCAPED_UNICODE), // payments, + 'pay_arr' => implode(",", $pay_arr), // pay_arr, + 'order_id' => trim($arr["order_id"]), // order_id, + 'terminal' => $arr["terminal"] ?? '', // terminal, + 'kkm_id' => $arr["kkm_id"] ?? '', // terminal, + 'terminal_id' => $arr["terminal_id"] ?? '', // terminal_id, + 'skidka' => $arr["discount"] ?? 0, // skidka + 'date_up' => $date_up, // date_up + 'held' => 0, + ]; + + } + + $result = []; + + $updateSalesMain = [ + 'deleteSales' => $checksIds, +// 'setSalesUpdate' => $checksValues, + //'setSalesProductsUpdate' => $salesProducts, +// 'setSalesProductsComponentsUpdate' => $salesProductsComponents, + ]; + + $result = array_merge($result, $updateSalesMain); + + if ($update) { + $updateSalesPart = [ + 'setSales' => $checksValues, + 'setSalesProducts' => $salesProducts, + 'setSalesProductsComponents' => $salesProductsComponents, +// 'setSalesItems' => $salesItems, + ]; + $result = array_merge($result, $updateSalesPart); + } + + return $result; + } - $products1c7 = Products1c::findOne(['id' => $arr["id"]]) ?? new Products1c(); - $products1c7->id = $arr["id"]; - $products1c7->tip = 'payment_types'; - $products1c7->name = $arr["name"]; - $products1c7->code = $arr["code"]; - $products1c7->save(); - if ($products1c7->getErrors()) { - LogService::apiErrorLog(json_encode( - ["error_id" => 10, "error" => $products1c7->getErrors()], - JSON_UNESCAPED_UNICODE - )); - } - } + private function getEntityByType($entity = 'city_store') + { + return ExportImportTable::find()->select(['entity_id', 'export_val'])->where(['entity' => $entity]) + ->andWhere(['export_id' => 1])->andWhere(['!=', 'export_val', ''])->asArray()->all(); + } + + private function deleteSales($ids, $update) + { + if (!empty($ids)) { + SalesUpdate::deleteAll(['in', 'id', $ids]); +// SalesProductsUpdate::deleteAll(['in', 'check_id', $ids]); + if ($update) { + Sales::deleteAll(['in', 'id', $ids]); + SalesItems::deleteAll(['in', 'check_id', $ids]); + SalesProducts::deleteAll(['in', 'check_id', $ids]); } + } + } - if (!empty($result['created_write_offs'])) { - $productsNames = Products1c::getNamesByTip('products'); + private function setSales($values) + { + $columns = [ + 'phone', + 'id', + 'store_id', + 'store_id_1c', + 'seller_id', + 'admin_id', + 'operation', + 'number', + 'date', + 'summ', + 'purchase_sum', + 'status', + 'sales_check', + 'payments', + 'pay_arr', + 'order_id', + 'terminal', + 'kkm_id', + 'terminal_id', + 'skidka', + 'date_up', + 'held', + ]; - file_put_contents( - self::OUT_DIR . '/created_write_offs_upload_' - . date("Y_m_d") . '.json', - PHP_EOL - . json_encode($result["created_write_offs"], JSON_UNESCAPED_UNICODE), - FILE_APPEND - ); - foreach ($result["created_write_offs"] as $arr) { - if (!empty($arr["id"])) { - $writeOffsErp = WriteOffsErp::find()->where(['guid' => $arr["id"]])->one(); - if (empty($writeOffsErp)) { - $waybillWriteOffsErp = WaybillWriteOffs::find()->where(['guid' => $arr["id"]])->one(); - } - } + $this->insertDataSales($values, 'sales', $columns); + } - if (!empty($writeOffsErp) || !empty($waybillWriteOffsErp)) { - if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { - $errorText = ''; - if (!empty($arr["errors"])) { - //"errors": [ - //{ - //"error": "Ошибка преобразования ИД документа", - //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", - //"error_json": [ - //{ - //"field": "id", - //"error": "Документ с данным ИД уже записан в системе" - //} - // + private function setSalesProducts($values) + { + $columns = [ + 'type_id', + 'check_id', + 'product_id', + 'seller_id', + 'quantity', + 'price', + 'summ', + 'purchase_price', + 'purchase_sum', + 'discount', + 'color' + ]; - foreach ($arr["errors"] as $errorRow) { - if (!empty($errorRow['error'])) { - $errorText .= $errorRow['error']; + $this->insertDataSales($values, 'sales_products', $columns); + } - $errorText .= ' ,' . $errorRow['error_description']; - if (!empty($errorRow['error_json'])) { - foreach ($errorRow['error_json'] as $errorJsonRow) { - $errorText .= ' , поле: ' . $errorJsonRow['field']; - $errorText .= ' , ошибка: ' . $errorJsonRow['error']; - } - } - } + private function setSalesProductsComponents($values) + { + $columns = [ + 'type_id', + 'check_id', + 'product_id', + 'seller_id', + 'quantity', + 'color', + 'component_parent_id', + 'price', + 'discount', + 'summ', + ]; - if (!empty($errorRow["errors_items"])) { - foreach ($errorRow["errors_items"] as $errorDopRow) { - //"errors_items": [ - //{ - //"error_dop": "Ошибка проверки количества номенклатуры", - //"field": "quantity", - //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", - //"error": "У данной позиции запрещён ввод дробного значения!" - //}, - // - // - $productName = $errorDopRow['product_id']; + $this->insertDataSales($values, 'sales_products', $columns); + } - if (array_key_exists($errorDopRow['product_id'], $productsNames)) { - $productName = $productsNames[$errorDopRow['product_id']]; - } +// private function setSalesItems($values) { +// $columns = [ +// 'lid_id', +// 'check_id', +// 'phone', +// 'id_1c', +// 'seller_id', +// 'kol', +// 'color_id', +// 'summa', +// 'skidka', +// 'date' +// ]; +// +// $this->insertDataSales($values, 'sales_items', $columns); +// } - $errorText .= ' ' . $errorDopRow['error_dop']; - $errorText .= ' , поле: ' . $errorDopRow['field']; - $errorText .= ' , товар: ' . $productName; - $errorText .= ' , ошибка: ' . $errorDopRow['error']; - } - } - } - } - if (!empty($writeOffsErp)) { - /** @var WriteOffsErp $writeOffsErp */ - $writeOffsErp->status = WriteOffsErp::STATUS_ERROR_1C; - $writeOffsErp->error_text = $errorText; - $writeOffsErp->save(); - if ($writeOffsErp->getErrors()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 11.1, "error" => $writeOffsErp->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } - if (!empty($waybillWriteOffsErp)) { - /** @var WaybillWriteOffs $waybillWriteOffsErp */ - $waybillWriteOffsErp->status = WriteOffsErp::STATUS_ERROR_1C; - $waybillWriteOffsErp->error_text = $errorText; - $waybillWriteOffsErp->save(); - if ($waybillWriteOffsErp->getErrors()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 11.2, "error" => $waybillWriteOffsErp->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } +// private function setSalesUpdate($values) { +// $columns = [ +// 'phone', +// 'id', +// 'store_id', +// 'store_id_1c', +// 'seller_id', +// 'admin_id', +// 'operation', +// 'number', +// 'date', +// 'summ', +// 'status', +// 'sales_check', +// 'payments', +// 'pay_arr', +// 'order_id', +// 'terminal', +// 'terminal_id', +// 'skidka', +// 'date_up' +// ]; +// +// $this->insertDataSales($values, 'sales_update', $columns); +// } + +// private function setSalesProductsUpdate($values) { +// $columns = [ +// 'type_id', +// 'check_id', +// 'product_id', +// 'seller_id', +// 'quantity', +// 'price', +// 'summ', +// 'discount', +// 'color' +// ]; +// +// $this->insertDataSales($values, 'sales_products_update', $columns); +// } - } else { - if (!empty($writeOffsErp)) { - /** @var WriteOffsErp $writeOffsErp */ - $writeOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; - $writeOffsErp->number_1c = $arr["number"] ?? ''; - $writeOffsErp->save(); - if ($writeOffsErp->getErrors()) { - LogService::apiErrorLog( - json_encode( - [ - "error_id" => 11.3, - "error" => $writeOffsErp->getErrors() - ], - JSON_UNESCAPED_UNICODE - ) - ); - } - } - if (!empty($waybillWriteOffsErp) && isset($arr["held"]) && $arr["held"]) { - /** @var WaybillWriteOffs $waybillWriteOffsErp */ - $waybillWriteOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; - $waybillWriteOffsErp->name_1c = $arr["name"] ?? ''; - $waybillWriteOffsErp->save(); - if ($waybillWriteOffsErp->getErrors()) { - LogService::apiErrorLog( - json_encode( - [ - "error_id" => 11.4, - "error" => $waybillWriteOffsErp->getErrors() - ], - JSON_UNESCAPED_UNICODE - ) - ); - } - } +// private function setSalesProductsComponentsUpdate($values) { +// $columns = [ +// 'type_id', +// 'check_id', +// 'product_id', +// 'seller_id', +// 'quantity', +// 'color', +// 'component_parent_id' +// ]; +// +// $this->insertDataSales($values, 'sales_products_update', $columns); +// } - } - } - } - } - if (!empty($result['created_write_ons'])) { - $productsNames = Products1c::getNamesByTip('products'); - file_put_contents( - self::OUT_DIR . '/created_write_ons_upload_' - . date("Y_m_d") . '.json', - PHP_EOL - . json_encode($result["created_write_ons"], JSON_UNESCAPED_UNICODE), - FILE_APPEND - ); - foreach ($result["created_write_ons"] as $arr) { - if (!empty($arr["id"])) { - $waybillIncoming = WaybillIncoming::find()->where(['guid' => $arr["id"]])->one(); - } + private function setSelfCostUpdate($values) + { + $columns = [ - if (!empty($waybillIncoming)) { - if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { - $errorText = ''; - if (!empty($arr["errors"])) { - //"errors": [ - //{ - //"error": "Ошибка преобразования ИД документа", - //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", - //"error_json": [ - //{ - //"field": "id", - //"error": "Документ с данным ИД уже записан в системе" - //} - // + 'date', + 'store_id', + 'product_guid', + 'price', + 'updated_at' + ]; - foreach ($arr["errors"] as $errorRow) { - if (!empty($errorRow['error'])) { - $errorText .= $errorRow['error']; - $errorText .= ' ,' . $errorRow['error_description']; - if (!empty($errorRow['error_json'])) { - foreach ($errorRow['error_json'] as $errorJsonRow) { - $errorText .= ' , поле: ' . $errorJsonRow['field']; - $errorText .= ' , ошибка: ' . $errorJsonRow['error']; - } - } - } + $this->insertDataSales($values, 'self_cost_product', $columns, 4000); + } - if (!empty($errorRow["errors_items"])) { - foreach ($errorRow["errors_items"] as $errorDopRow) { - //"errors_items": [ - //{ - //"error_dop": "Ошибка проверки количества номенклатуры", - //"field": "quantity", - //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", - //"error": "У данной позиции запрещён ввод дробного значения!" - //}, - // - // - $productName = $errorDopRow['product_id']; - if (array_key_exists($errorDopRow['product_id'], $productsNames)) { - $productName = $productsNames[$errorDopRow['product_id']]; - } + private function insertDataSales($values, $tableName, $columns, $chunks = 1000) - $errorText .= ' ' . $errorDopRow['error_dop']; - $errorText .= ' , поле: ' . $errorDopRow['field']; - $errorText .= ' , товар: ' . $productName; - $errorText .= ' , ошибка: ' . $errorDopRow['error']; - } - } - } - } + { + $chunkValues = array_chunk($values, $chunks); - /** @var WaybillIncoming $waybillIncoming */ - $waybillIncoming->status = WriteOffsErp::STATUS_ERROR_1C; - $waybillIncoming->error_text = $errorText; - $waybillIncoming->save(); - if ($waybillIncoming->getErrors()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 11.5, "error" => $waybillIncoming->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } else { - if (isset($arr["held"]) && $arr["held"]) { - /** @var WaybillIncoming $waybillIncoming */ - $waybillIncoming->status = WriteOffsErp::STATUS_CREATED_1C; - $waybillIncoming->number_1c = $arr["name"] ?? ''; - $waybillIncoming->save(); - if ($waybillIncoming->getErrors()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 11.55, "error" => $waybillIncoming->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } - } + foreach ($chunkValues as $key => $rows) { + + try { + $transaction = \Yii::$app->db->beginTransaction(); + Yii::$app->db->createCommand()->batchInsert($tableName, $columns, $rows)->execute(); + $transaction->commit(); + } catch (Exception $e) { + $errorString = substr($e->getMessage(), 0, 2000); + file_put_contents(self::OUT_DIR . '/error_upload.txt', + PHP_EOL . $errorString, FILE_APPEND + ); + $transaction->rollBack(); + InfoLogService::setInfoLog(__FILE__, __LINE__, $tableName, 'error_id_25'); + InfoLogService::setInfoLog(__FILE__, __LINE__, $errorString, 'error_id_25_22'); + LogService::apiErrorLog(json_encode(["error_id" => 25, "error" => $errorString], JSON_UNESCAPED_UNICODE) + ); + } + } + } + + private function getMarketplaceStatuses() + { + $marketplaces = [ + MarketplaceOrder1cStatuses::GUID_FLOWWOW => "ФлауВау", + MarketplaceOrder1cStatuses::GUID_YANDEXMARKET => "ЯндексМаркет" + ]; + $data = []; + foreach ($marketplaces as $marketplaceGuid => $marketplaceName) { + $statuses = MarketplaceOrder1cStatuses::find()->where(['marketplace_id' => MarketplaceOrder1cStatuses::guid2id()[$marketplaceGuid]]) + ->orderBy(['posit' => SORT_ASC])->all(); + $statusesData = []; + foreach ($statuses as $status) { + /* @var $status MarketplaceOrder1cStatuses */ + $relftions = $status->relationsFrom; + $relationsToSend = []; + foreach ($relftions as $relation) { + $statusTo = MarketplaceOrder1cStatuses::find()->where(['id' => $relation['status_id_to']])->one(); + if(!$statusTo) { + continue; } + $relationsToSend[] = + $statusTo->status_id; } + $statusesData [] = [ + 'index_number' => $status->posit, + 'status_name' => $status->status, + 'allowed_reserve' => $status->allowed_reserve, + 'allowed_closing' => $status->allowed_closing, + 'hint' => $status->status_instruction, + 'status_id' => $status->status_id, + 'allowed_statuses' => $relationsToSend + ]; } - - if (!empty($result['created_resortings'])) { - $productsNames = Products1c::getNamesByTip('products'); - file_put_contents( - self::OUT_DIR . '/created_resortings_upload_' - . date("Y_m_d") . '.json', - PHP_EOL - . json_encode($result["created_resortings"], JSON_UNESCAPED_UNICODE), - FILE_APPEND - ); - foreach ($result["created_resortings"] as $arr) { - if (!empty($arr["id"])) { - $replacementInvoice = ReplacementInvoice::findOne(['guid' => $arr["id"]]); - } + $data[] = [ + 'id' => $marketplaceGuid, + 'name' => $marketplaceName, + 'statuses' => $statusesData + ]; + } + return $data; + } + + public static function changeMarketplaceOrderStatusFrom1C($mpOrder) + { + $result = null; + if (!$mpOrder['status']) { + $result['message'] = 'Статус не передан'; + $result['status'] = 'error'; + return $result; + } + // статусы маркетплейса + $statuses = MarketplaceOrderStatusTypes::find() + ->select(['id', 'code']) + ->indexBy('code') + ->asArray() + ->all(); + $cancelledStatusId = $statuses[MarketplaceOrderStatusTypes::CANSELLED_CODE]['id']; + $readyStatusId = $statuses[MarketplaceOrderStatusTypes::READY_CODE]['id']; + $deliveredStatusId = $statuses['DELIVERED']['id']; + $status = $mpOrder['status']; + $marketplaceOrder = MarketplaceOrders::find() + ->where(['guid' => $mpOrder['id']]) + // ->andWhere(['<>', 'status_id', $cancelledStatusId]) + ->one(); + + if ($marketplaceOrder) { + /** @var $marketplaceOrder MarketplaceOrders */ + $debug = false; + if ($marketplaceOrder->fake == 1) { + $debug = true; + } + $marketplaceId = $marketplaceOrder->marketplace_id; + $cancelledStatusesCode = MarketplaceOrder1cStatuses::find() + ->select(['status_id']) + ->where(['marketplace_id' => $marketplaceId]) + ->andWhere(['order_status_id' => $cancelledStatusId]) + ->scalar(); - if (!empty($replacementInvoice)) { - if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { - $errorText = ''; - if (!empty($arr["errors"])) { - foreach ($arr["errors"] as $errorRow) { - if (!empty($errorRow['error'])) { - $errorText .= $errorRow['error']; + $statusId1C = MarketplaceOrder1cStatuses::find() + ->where(['marketplace_id' => $marketplaceId]) + ->andWhere(['status_id' => $status]) + ->one(); - $errorText .= ' ,' . $errorRow['error_description']; - if (!empty($errorRow['error_json'])) { - foreach ($errorRow['error_json'] as $errorJsonRow) { - $errorText .= ' , поле: ' . $errorJsonRow['field']; - $errorText .= ' , ошибка: ' . $errorJsonRow['error']; - } - } - } + if ($marketplaceOrder->status_id === $cancelledStatusId && $status !== $cancelledStatusesCode) { + $result['message'] = 'Заказ отменен ' . $mpOrder['id'];; + $result['status'] = 'cancelled_order'; + return $result; + } - if (!empty($errorRow["errors_items"])) { - foreach ($errorRow["errors_items"] as $errorDopRow) { - $productName = $errorDopRow['product_id']; + $statuses1cWithCancelledId = ArrayHelper::getColumn(MarketplaceOrder1cStatuses::find() + ->select(['status_id']) + ->where(['order_status_id' => $cancelledStatusId]) + ->asArray() + ->all(), 'status_id'); + $statuses1cToChangeYandexMarketFakeOrderId = ArrayHelper::getColumn(MarketplaceOrder1cStatuses::find() + ->select(['status_id']) + ->where(['order_status_id' => $cancelledStatusId]) + ->orWhere(['order_substatus_id' => $readyStatusId]) + ->andWhere(['marketplace_id' => 2]) + ->asArray() + ->all(), 'status_id'); + $statuses = ArrayHelper::map($statuses, 'code', 'id'); + $statusCodes = array_unique(array_keys($statuses)); - if (array_key_exists($errorDopRow['product_id'], $productsNames)) { - $productName = $productsNames[$errorDopRow['product_id']]; - } - $errorText .= ' ' . $errorDopRow['error_dop']; - $errorText .= ' , поле: ' . $errorDopRow['field']; - $errorText .= ' , товар: ' . $productName; - $errorText .= ' , ошибка: ' . $errorDopRow['error']; - } - } - } - } + if (empty($statusId1C)) { + $mess["result"] = 'error'; + $mess["message_order"] = "Статус не найден"; + $errorJson = json_encode($mess, JSON_UNESCAPED_UNICODE); + LogService::apiLogs(1, $errorJson); + Yii::error('Ошибка: такого статуса не существует' . $status, __METHOD__); + return $errorJson; + } - /** @var ReplacementInvoice $replacementInvoice */ - $replacementInvoice->status = WriteOffsErp::STATUS_ERROR_1C; - $replacementInvoice->error_text = $errorText; - $replacementInvoice->save(); - if ($replacementInvoice->getErrors()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 4.555, "error" => $replacementInvoice->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } + // Проверяем, если заказ уже имеет статус CANCELLED или DELIVERED, то не меняем статусы + if ($marketplaceOrder->status_id === $cancelledStatusId || $marketplaceOrder->status_id === $deliveredStatusId) { + $result['status'] = 'no_change'; + $result['message'] = 'Заказ уже имеет финальный статус (CANCELLED или DELIVERED) ' . $mpOrder['id']; + return $result; + } - } else { - if (isset($arr["held"]) && $arr["held"]) { - /** @var ReplacementInvoice $replacementInvoice */ - $replacementInvoice->status = WriteOffsErp::STATUS_CREATED_1C; - $replacementInvoice->number_1c = $arr["name"] ?? ''; - $replacementInvoice->save(); - if ($replacementInvoice->getErrors()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 4.55, "error" => $replacementInvoice->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } + // Получаем статусы МП по статусу 1С + /** @var $status MarketplaceOrderStatusTypes */ + /** @var $substatus MarketplaceOrderStatusTypes */ + $status = $statusId1C->orderStatus; + $substatus = $statusId1C->orderSubstatus; + + if ( + in_array($statusId1C->status_id, $statuses1cToChangeYandexMarketFakeOrderId) && + $marketplaceOrder->marketplace_id == MarketplaceStore::YANDEX_WAREHOUSE_ID + ) { + if (!$debug) { + $updateResult = MarketplaceService::updateOrderStatus( + $marketplaceOrder->warehouse_guid, + $marketplaceOrder->marketplace_order_id, + $status->code, + $substatus->code + ); + if (!$updateResult && $marketplaceOrder->fake == 1) { + if ($status->id && $substatus->id) { + $marketplaceOrder->status_id = $status->id; + $marketplaceOrder->substatus_id = $substatus->id; } } } - } - $update = false; - if (!empty($start_time) && !empty($end_time)) { - $start_time_unix = strtotime($start_time); - $startMonth = date("Y-m-01"); - $end_time_unix = strtotime($end_time); - if ( - $startMonth <= (date("Y-m-d", strtotime($start_time))) - || - ($end_time_unix < (time() - 90 * 86400)) - ) { - $update = true; + } else { + if ($status->id && $substatus->id) { + $marketplaceOrder->status_id = $status->id; + $marketplaceOrder->substatus_id = $substatus->id; } } + if (in_array($statusId1C->status_id, $statuses1cWithCancelledId)) { + $marketplaceOrder->cancelled_order_source = '1c'; + $marketplaceOrder->cancelled_order_date = date('Y-m-d H:m:s'); + } + $marketplaceOrder->status_processing_1c = $statusId1C->id; + $marketplaceOrder->seller_id = $mpOrder['seller_id'] ?? null; + $marketplaceOrder->number_1c = $mpOrder['number'] ?? null; - if (!empty($result['write_offs'])) { - if (!empty($start_time) and !empty($end_time)) { - if ($update) { - WriteOffs::deleteAll(['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); - } - } - foreach ($result["write_offs"] as $gi => $arr) { - if (!empty($arr["error"])) { - file_put_contents(self::OUT_DIR . '/created_write_offs_erp_error.txt', PHP_EOL . " " . $arr["id"] . " error=" . $arr["error"], FILE_APPEND); - } + if ($marketplaceOrder->save()) { + // Обновляем историю статусов + MarketplaceService::createOrUpdateStatusHistory($marketplaceOrder->id, $status->id, $substatus->id, [ + 'date' => date('Y-m-d H:i:s') + ]); + $result['status'] = 'success'; + $result['message'] = 'Статус обновлен'; + } else { + Yii::error('Ошибка сохранения: ' . Json::encode($marketplaceOrder->getErrors(), JSON_UNESCAPED_UNICODE)); + $result['status'] = 'error'; + $result['message'] = $marketplaceOrder->getErrors(); + } + } else { + $result['message'] = 'Заказ не найден ' . $mpOrder['id'];; + $result['status'] = 'not_found'; + } - if (empty($arr["error"]) && !empty($arr["id"])) { - $writeOffsErp = WriteOffsErp::find()->where(['guid' => $arr["id"]])->one(); - if ($writeOffsErp) { - $writeOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; - $writeOffsErp->number_1c = $arr["number"]; - $writeOffsErp->save(); - if ($writeOffsErp->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 11.6, "error" => $writeOffsErp->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } else { - $waybillWriteOffsErp = WaybillWriteOffs::find()->where(['guid' => $arr["id"]])->one(); - if ($waybillWriteOffsErp) { - $waybillWriteOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; - $waybillWriteOffsErp->number_1c = $arr["number"]; - $waybillWriteOffsErp->save(); - if ($waybillWriteOffsErp->getErrors()) { - LogService::apiErrorLog( - json_encode(["error_id" => 11.7, "error" => $waybillWriteOffsErp->getErrors()], - JSON_UNESCAPED_UNICODE) - ); - } - } - } - } + return $result; + } -// file_put_contents(self::OUT_DIR . '/write_offs.json', PHP_EOL . json_encode($result["write_offs"], JSON_UNESCAPED_UNICODE)); + public function processingUpload($result) + { + $request = json_encode($result, JSON_UNESCAPED_UNICODE); + $mess['request'] = $result; + $requestIdText = ''; + if (!empty($result["request_id"])) { + $requestIdText = $result["request_id"]; + $fl = "request_id_" . $result["request_id"]; + } else { + $fl = time(); + } + //InfoLogService::setInfoLog(__FILE__, __LINE__, 'upload_' . $fl . '.json' , 'info_id_25_1'); - $writeOffs = WriteOffs::find()->where(['id' => $arr["id"]])->one(); - if ($writeOffs) { - $writeOffs->delete(); - } - WriteOffsProducts::deleteAll(['write_offs_id' => $arr["id"]]); + file_put_contents(self::OUT_DIR . '/upload_' . $fl . '.json', PHP_EOL . $request); - $writeOffs2 = new WriteOffs; - $writeOffs2->id = $arr["id"]; - $writeOffs2->status_id = 1; - $writeOffs2->write_downs = '1c'; - $writeOffs2->store_id = $arr["store_id"]; - $writeOffs2->number = $arr["number"]; - $writeOffs2->date = $arr["date"]; - $writeOffs2->based_on = $arr["based_on"] ?? ""; - $typeIndex = strpos($arr["type"], "_"); - $writeOffs2->type = $typeIndex === false ? $arr['type'] : substr($arr["type"], $typeIndex + 1); - $writeOffs2->cause = $arr["cause"] ?? ""; - $writeOffs2->comment = $arr["comment"] ?? ""; - $writeOffs2->items = json_encode($arr["items"], JSON_UNESCAPED_UNICODE); - $writeOffs2->summ = $arr["summ"]; - $writeOffs2->save(); - if ($writeOffs2->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 12, "error" => $writeOffs2->getErrors(), "number" => $arr["number"]], JSON_UNESCAPED_UNICODE)); - } + try { + + if (!empty($result['error'])) { + file_put_contents(self::OUT_DIR . '/error_upload.txt', + PHP_EOL . json_encode($result["error"], JSON_UNESCAPED_UNICODE), FILE_APPEND); + } + $mess["result"] = true; + $checks_dell = ""; + $requestId = time(); + if (array_key_exists("request_id", $result) && !empty($result["request_id"])) { + $requestId = $result["request_id"]; + } + $type_price = "Розничная цена"; + + if (!empty($requestId)) { + $apiCron = ApiCron::find()->select(['json_post'])->where(['request_id' => $requestId])->one(); + if ($apiCron) { + $jsn = json_decode($apiCron->json_post, true, 512, JSON_UNESCAPED_UNICODE); + $start_time = $jsn["checks"]["start_time"] ?? date('Y-m-d 00:00:00', time() - 3 * 86400); + $end_time = $jsn["checks"]["end_time"] ?? date('Y-m-d 00:00:00', time()); + $checks_dell = $jsn["checks_dell"] ?? ""; + $type_price = $jsn["prices"]["type_price"] ?? "Розничная цена"; + + ApiCron::updateAll(['status' => 1, 'date_up' => date('Y-m-d H:i:s')], + ['and', ['status' => 0], ['request_id' => $requestId]]); - foreach ($arr["items"] as $j2 => $mass2) { - $writeOffsProducts = WriteOffsProducts::findOne([ - 'write_offs_id' => $arr["id"], - 'product_id' => $mass2['product_id'], - ]) ?? new WriteOffsProducts(); - $writeOffsProducts->write_offs_id = $arr["id"]; - $writeOffsProducts->date = $arr["date"]; - $writeOffsProducts->product_id = $mass2['product_id']; - $writeOffsProducts->color = $mass2["color"]; - $writeOffsProducts->quantity = ceil($mass2["quantity"]); - $writeOffsProducts->summ = $mass2["summ"]; - $writeOffsProducts->price = $mass2["price"]; - $writeOffsProducts->price_retail = 0; - $writeOffsProducts->summ_retail = 0; - $writeOffsProducts->save(); - if ($writeOffsProducts->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 13, "error" => $writeOffsProducts->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } +// file_put_contents(self::OUT_DIR . '/request_api_cron.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . "request_id=$requestId $start_time - $end_time ", FILE_APPEND); } } - if (!empty($result['counteragents'])) { - foreach ($result["counteragents"] as $gi => $arr) { - $arr["is_group"] = $arr["is_group"] ? 1 : 0; - $products1c = new Products1c; - $products1c->id = $arr["id"]; - $products1c->tip = 'counteragents'; - $products1c->name = $arr["name"]; - $products1c->code = $arr["inn"]; - $products1c->parent_id = $arr["parent_id"]; - $products1c->view = $arr["is_group"]; - $products1c->save(); - if ($products1c->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 14, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); - } + if (!empty($result['stores'])) { + $products1cByTip = Products1c::find() + ->select(['id', 'tip']) + ->andWhere(['tip' => ['kkms', 'terminals', 'city_store']]) + ->groupBy(['tip', 'id']) + ->asArray() + ->all(); + $products1cByTipMap = []; + foreach ($products1cByTip as $item) { + $products1cByTipMap[$item['tip']][] = $item['id']; } - } + $existTerminals = Terminals::find() + ->indexBy('id') + ->asArray() + ->column(); - if (!empty($result['incomings'])) { - foreach ($result["incomings"] as $gi => $arr) { - $incoming = Incoming::find()->where(['id' => $arr['id']])->one(); - if (!$incoming) { - $incoming = new Incoming; - $incoming->id = $arr["id"]; - $incoming->store_id = $arr["store_id"]; - $incoming->counteragent_id = $arr["counteragent_id"]; - $incoming->number = $arr["number"]; - $incoming->date = $arr["date"]; - $incoming->comment = $arr["comment"] ?? ''; - $incoming->items = empty($arr["items"]) ? '[]' : json_encode($arr["items"], JSON_UNESCAPED_UNICODE); - $incoming->is_discrepancies = (int)$arr["is_discrepancies"]; - $incoming->supplier_items = empty($arr["supplier_items"]) ? '[]' : json_encode($arr["supplier_items"], JSON_UNESCAPED_UNICODE); - $incoming->payments = empty($arr["payments"]) ? '[]' : json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); - $incoming->summ = $arr["summ"]; - $incoming->save(); + foreach ($result['stores'] as $gi => $arr) { + if (!in_array($arr["id"], $products1cByTipMap['city_store'])) { + $products1c = new Products1c; + $products1c->id = $arr["id"]; + $products1c->tip = 'city_store'; + $products1c->name = $arr["name"]; + $products1c->code = $arr["code"]; + $products1c->save(); + if ($products1c->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 2, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); + } } - if ($incoming->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 15, "error" => $incoming->getErrors()], JSON_UNESCAPED_UNICODE)); - } else { - try { - $json = Json::decode($incoming->items); - IncomingItems::deleteAll(['incoming_id' => $incoming->id]); - foreach ($json as $item) { - $incomingItem = new IncomingItems; - $incomingItem->incoming_id = $incoming->id; - $incomingItem->product_id = $item['product_id']; - $incomingItem->color = $item['color']; - $incomingItem->quantity = $item['quantity']; - $incomingItem->price = $item['price']; - $incomingItem->vat_rate = $item['vat_rate']; - $incomingItem->vat_amount = $item['vat_amount']; - $incomingItem->summ = $item['summ']; - $incomingItem->save(); - if ($incomingItem->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 15.2, "error" => $incomingItem->getErrors()], JSON_UNESCAPED_UNICODE)); + + if ($arr["terminals"]) { + $k = 0; + foreach ($arr["terminals"] as $gi2 => $arr2) { + if (!in_array($arr2['id'], $products1cByTipMap['terminals'])) { + $products1c2 = new Products1c; + $products1c2->id = $arr2['id']; + $products1c2->tip = 'terminals'; + $products1c2->name = $arr2["name"]; + $products1c2->code = $arr2["code"]; + $products1c2->save(); + if ($products1c2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 3, "error" => $products1c2->getErrors()], JSON_UNESCAPED_UNICODE)); + Yii::error(''); } } - } catch (Exception $jex) { - LogService::apiErrorLog(json_encode(["error_id" => 15.3, "error" => "items has no json format"], JSON_UNESCAPED_UNICODE)); + + if (!in_array($arr2['id'], $existTerminals)) { + $terminal = new Terminals; + $terminal->id = $arr2["id"]; + $terminal->name = $arr2["name"]; + $terminal->code = $arr2["code"]; + $terminal->store_id = $arr["id"]; + $terminal->date = date('Y-m-d H:i:s'); + $terminal->posit = $k; + $terminal->save(); + if ($terminal->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 4, "error" => $terminal->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + $k++; } } - } - } - if (!empty($result['cashes'])) { - foreach ($result["cashes"] as $gi => $arr) { - $products1c = new Products1c; - $products1c->id = $arr["id"]; - $products1c->tip = 'cashes'; - $products1c->name = $arr["name"]; - $products1c->code = $arr["store_id"]; - $products1c->save(); - if ($products1c->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 16, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); - } - $cashes = new Cashes; - $cashes->id = $arr["id"]; - $cashes->store_id = $arr["store_id"]; - $cashes->kkm_id = $arr["kkm_id"]; - $cashes->name = $arr["name"]; - $cashes->is_central = $arr["is_central"]; - $cashes->save(); - if ($cashes->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 17, "error" => $cashes->getErrors()], JSON_UNESCAPED_UNICODE)); + if ($arr['kkms']) { + foreach ($arr["kkms"] as $gi2 => $arr2) { + if (!in_array($arr2['id'], $products1cByTipMap['kkms'])) { + $products1c3 = new Products1c; + $products1c3->id = $arr2["id"]; + $products1c3->tip = 'kkms'; + $products1c3->name = $arr2["name"]; + $products1c3->code = $arr2["code"]; + $products1c3->save(); + if ($products1c3->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 5, "error" => $products1c3->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } } } } + if (!empty($result['self_cost'])) { + $storeMap = []; - if (!empty($checks_dell) and !empty($start_time) and !empty($end_time)) { - if ($update) { - Sales::updateAll(['operation' => 'Удален'], ['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); - } -// SalesUpdate::updateAll(['operation' => 'Удален'], ['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); + $cityStoreIds = CityStore::find()->select('id')->column(); - file_put_contents(self::OUT_DIR . '/check_dell.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . " regquest_id=$requestId Удаление $start_time - $end_time ", FILE_APPEND); - } + // Получаем соответствия export_val => entity_id из таблицы ExportImportTable + $exportImportRecords = ExportImportTable::find() + ->select(['entity_id', 'export_val']) + ->where(['entity_id' => $cityStoreIds, 'entity' => 'city_store', 'export_id' => 1]) + ->all(); - $matrixProductsIds = []; - if (!empty($result['checks'])) { - $matrixProductsIds = SalaryHelper::getMatrixProductsIds(); - } + // Создаем справочник + foreach ($exportImportRecords as $record) { + $storeMap[$record->export_val] = $record->entity_id; + } - if (!empty($result['checks'])) { - foreach ($result["checks"] as $index => $arr) { - if (!isset($arr["marketplace_order_id"])) { - continue; - } - $marketplaceOrder = MarketplaceOrders::findOne(['guid' => $arr["marketplace_order_id"]]); - if (!empty($arr['error'])) { - $txt = date("d.m.Y H:i:s", time()) . " $index СОЗДАНИЕ ЧЕКА ОШИБКА id=" . $arr["id"] . " " . $arr["error"]; - file_put_contents(self::OUT_DIR . '/log_check_error.txt', PHP_EOL . $txt, FILE_APPEND); - $marketplaceOrder->error_text = "ОШИБКА ЧЕКА" . $arr["id"] . "для заказа id=" . $marketplaceOrder->marketplace_order_id . " " . $arr["error"]; - $marketplaceOrder->save(); - if ($marketplaceOrder->getErrors()) { - Yii::error('Ошибка сохранения ошибки заказа ' . json_encode($marketplaceOrder->getErrors(), JSON_UNESCAPED_UNICODE)); - LogService::apiErrorLog(json_encode(["error_id" => 17.2, "error" => $marketplaceOrder->getErrors()], JSON_UNESCAPED_UNICODE)); - } + $values = []; + + foreach ($result['self_cost'] as $selfCost) { + $storeId = $storeMap[$selfCost['store_id']] ?? null; + if (!$storeId) { continue; } - $check = CreateChecks::find() - ->where(['check_id' => $arr["id"]]) - ->andWhere(['order_guid' => $arr["marketplace_order_id"]]) - ->andWhere(['status' => 0])->one(); - if(!$check) { - continue; + + + // Удаляем старые данные + SelfCostProduct::deleteAll(['date' => $selfCost['date'], 'store_id' => $storeId]); + + foreach ($selfCost['items'] as $item) { + $values[] = [ + 'date' => $selfCost['date'], + 'store_id' => $storeId, + 'product_guid' => $item['product_id'], + 'price' => $item['price'], + 'updated_at' => date('Y-m-d H:i:s') + ]; } - $check->status = 1; - $check->name = $arr["number"] . " от " . $arr["date"]; - $check->guid = $arr["id"]; - $check->date_up = date('Y-m-d H:i:s'); - $check->held = 1; - $check->save(); - if ($check->getErrors()) { - Yii::error('Ошибка обновления чека ' . json_encode($check->getErrors(), JSON_UNESCAPED_UNICODE)); - LogService::apiErrorLog(json_encode(["error_id" => 17.3, "error" => $check->getErrors()], JSON_UNESCAPED_UNICODE)); + } + + if (!empty($values)) { + $this->setSelfCostUpdate($values); + SelfCostProductDinamicService::UpdateResult($values); + } + } + + + if (!empty($result['sellers'])) { + Products1c::deleteAll(['tip' => 'admin']); + + foreach ($result["sellers"] as $gi => $arr) { + EmployeeOnShift::updateAll(['status_source' => EmployeeOnShift::STATUS_SOURCE_CREATED_IN_1C], ['guid' => $arr['id']]); + $products1c4 = new Products1c; + $products1c4->id = $arr["id"]; + $products1c4->tip = 'admin'; + $products1c4->name = $arr["name"]; + $products1c4->code = $arr["code"] ?? ''; + $products1c4->parent_id = $arr["parent_id"] ?? ''; + $products1c4->save(); + if ($products1c4->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 6, "error" => $products1c4->getErrors()], JSON_UNESCAPED_UNICODE)); } } } - if (!empty($result['checks']) && count($result['checks']) < 1000) { - - foreach ($result["checks"] as $arr) { - - $check_id = $arr["id"]; - if ($arr["seller_id"] == '00000000-0000-0000-0000-000000000000') { - $arr["seller_id"] = "NULL"; + if (!empty($result["nomenclature"]["groups"])) { + Products1c::deleteAll(['tip' => 'products_group']); + foreach ($result["nomenclature"]["groups"] as $gi => $arr) { + $products1c5 = new Products1c; + $products1c5->id = $arr["id"]; + $products1c5->tip = 'products_group'; + $products1c5->name = $arr["name"]; + $products1c5->code = $arr["code"] ?? ''; + $products1c5->articule = $arr["articule"] ?? ''; + $products1c5->parent_id = $arr["parent_id"] ?? '0'; + $products1c5->save(); + if ($products1c5->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 7, "error" => $products1c5->getErrors()], JSON_UNESCAPED_UNICODE)); } - - $pay_arr = $this->getPayArr($arr["payments"]); - - $store_id = ClientHelper::getExportId($arr["store_id"], "city_store", 1); -// $admin_id = ClientHelper::getExportId($arr["seller_id"], "admin", 1); - $exportImportTable = ExportImportTable::find()->select(['entity_id'])->where(['entity' => 'admin']) - ->andWhere(['export_id' => 1])->andWhere(['export_val' => $arr["seller_id"]])->all(); - $exportImportTableIds = ArrayHelper::getColumn($exportImportTable, 'entity_id'); - $admin = Admin::find()->where(['in', 'id', $exportImportTableIds])->andWhere(['>', 'group_id', 0])->one(); - $admin_id = $admin->id ?? 0; - - //удаляем чеки и товары в чеках - $saleUpdate = SalesUpdate::find()->where(['id' => $arr["id"]])->one(); - if ($saleUpdate) { - $saleUpdate->delete(); + } + } + if (!empty($result["nomenclature"]["elements"])) { +// Products1c::deleteAll(['and', ['tip' => 'products'], ['view' => 0]]); + $bouquets = BouquetComposition::find()->select('guid')->column(); + foreach ($result["nomenclature"]["elements"] as $gi => $arr) { +// if (!empty($arr["name"]) && in_array($arr["name"][0], ['ь', 'Ь', 'ъ', 'Ъ'])) { // Не вносим номенклатуру, помеченную на удаление +// continue; +// } + $components = !empty($arr["components"]) ? json_encode($arr["components"], JSON_UNESCAPED_UNICODE) : ""; // Пустые компоненты не надо разворачивать в json объект + $products1c6 = Products1c::find()->where(['id' => $arr["id"]])->one(); + if (!$products1c6) { + $products1c6 = new Products1c; + $products1c6->id = $arr["id"]; + $products1c6->tip = 'products'; } -// SalesProductsUpdate::deleteAll(['check_id' => $arr["id"]]); - - if ($update) { - $sales = Sales::find()->where(['id' => $arr["id"]])->one(); - if ($sales) { - $sales->delete(); - } - SalesItems::deleteAll(['check_id' => $arr["id"]]); - SalesProducts::deleteAll(['check_id' => $arr["id"]]); + $products1c6->name = $arr["name"]; + $products1c6->code = $arr["code"]; + $products1c6->type = $arr["type"]; + $products1c6->articule = $arr["articule"]; + $products1c6->parent_id = $arr["parent_id"]; + $products1c6->view = $arr["view"]; + $products1c6->components = $components; + $products1c6->save(); + if ($products1c6->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 8, "error" => $products1c6->getErrors()], JSON_UNESCAPED_UNICODE)); } - // проверяем стутс чека - вносим только Архивные и пробитые -// if (!empty($arr["status"])) { -// $salesUpdate = new SalesUpdate; -// $salesUpdate->phone = empty($arr["client_phone"]) ? 0 : (int)$arr["client_phone"]; -// $salesUpdate->id = $arr["id"]; -// $salesUpdate->store_id = $store_id; -// $salesUpdate->store_id_1c = $arr["store_id"]; -// $salesUpdate->seller_id = $arr["seller_id"]; -// $salesUpdate->admin_id = $admin_id; -// $salesUpdate->operation = $arr["type"]; -// $salesUpdate->number = $arr["number"]; -// $salesUpdate->date = $arr["date"]; -// $salesUpdate->summ = $arr["summ"]; -// $salesUpdate->status = $arr["status"]; -// $salesUpdate->sales_check = $arr["sales_check"] ?? 'NULL'; -// $salesUpdate->payments = json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); -// $salesUpdate->pay_arr = implode(",", $pay_arr); -// $salesUpdate->order_id = $arr["order_id"] ?? ''; -// $salesUpdate->terminal = $arr["terminal"] ?? 'NULL'; -// $salesUpdate->terminal_id = $arr["terminal_id"] ?? 'NULL'; -// $salesUpdate->date_up = date('Y-m-d H:i:s'); -// $salesUpdate->skidka = $arr["discount"] ?? 0; -// $salesUpdate->kkm_id = $arr["kkm_id"] ?? ''; // Пустая строка по умолчанию не может быть -// $salesUpdate->held = 0; // ??? -// $salesUpdate->save(); -// if ($salesUpdate->getErrors()) { -// LogService::apiErrorLog(json_encode(["error_id" => 18, "error" => $salesUpdate->getErrors()], JSON_UNESCAPED_UNICODE)); -// } - -// $amount = 0; -//// $items_arr = []; -// foreach ($arr["items"] as $itemid => $arr2) { -// if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { -// $arr2["seller_id"] = "NULL"; -// } -// $saleProductsUpdate = new SalesProductsUpdate; -// $saleProductsUpdate->type_id = 1; -// $saleProductsUpdate->check_id = $check_id; -// $saleProductsUpdate->product_id = $arr2["product_id"]; -// $saleProductsUpdate->seller_id = $arr2["seller_id"]; -// $saleProductsUpdate->quantity = $arr2["quantity"]; -// $saleProductsUpdate->price = $arr2["price"]; -// $saleProductsUpdate->summ = $arr2["summ"]; -// $saleProductsUpdate->discount = $arr2["discount"]; -// $saleProductsUpdate->color = $arr2["color"] ?? ''; // ??? -// $saleProductsUpdate->component_parent_id = ''; // ??? -// $saleProductsUpdate->save(); -// if ($saleProductsUpdate->getErrors()) { -// LogService::apiErrorLog(json_encode(["error_id" => 19, "error" => $saleProductsUpdate->getErrors()], JSON_UNESCAPED_UNICODE)); -// } -// if (!empty($arr2["components"])) { -// foreach ($arr2["components"] as $compID => $comp) { -// $saleProductsUpdate2 = new SalesProductsUpdate; -// $saleProductsUpdate2->type_id = 3; -// $saleProductsUpdate2->check_id = $check_id; -// $saleProductsUpdate2->product_id = $comp["product_id"]; -// $saleProductsUpdate2->seller_id = $arr2["seller_id"]; -// $saleProductsUpdate2->quantity = $comp["quantity"]; -// $saleProductsUpdate2->color = $comp["color"]; -// $saleProductsUpdate2->component_parent_id = $arr2["product_id"]; -// $saleProductsUpdate2->save(); -// if ($saleProductsUpdate2->getErrors()) { -// LogService::apiErrorLog(json_encode(["error_id" => 20, "error" => $saleProductsUpdate2->getErrors()], JSON_UNESCAPED_UNICODE)); -// } + if(!empty($arr["components"])) { + if(!in_array($arr["id"], $bouquets)) { + $newBouquetComp = new BouquetComposition(); + $newBouquetComp->guid = $arr["id"]; + $newBouquetComp->name = $arr["name"]; + $newBouquetComp->status = 1; + $newBouquetComp->matrix_type_id = 1; + $newBouquetComp->created_by = Admin::getAdminAgentId() ?: null; + if(!$newBouquetComp->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.1, "error" => $newBouquetComp->getErrors()], JSON_UNESCAPED_UNICODE)); + } else { + foreach ($arr["components"] as $guid => $quantity) { + $newBouquetCompProd = new BouquetCompositionProducts(); + $newBouquetCompProd->bouquet_id = $newBouquetComp->id; + $newBouquetCompProd->product_guid = $guid; + $newBouquetCompProd->count = $quantity; + $newBouquetCompProd->created_by = Admin::getAdminAgentId() ?: null; + if(!$newBouquetCompProd->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.2, "error" => $newBouquetCompProd->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } +// $costModels = []; +// foreach (BouquetComposition::getRegions() as $region_id) { +// $costModels[$region_id] = $newBouquetComp->getCostModel($region_id, array_keys($arr["components"]), true); // } -// } -// } -// } - - if ($update) { - $sales2 = new Sales; - $sales2->phone = $arr["client_phone"] ?? 0; - $sales2->id = $arr["id"]; - $sales2->store_id = $store_id; - $sales2->store_id_1c = $arr["store_id"]; - $sales2->seller_id = $arr["seller_id"]; - $sales2->admin_id = $admin_id; - $sales2->operation = $arr["type"]; - $sales2->number = $arr["number"]; - $sales2->date = $arr["date"]; - $sales2->summ = $arr["summ"]; - $sales2->status = $arr["status"]; - $sales2->sales_check = $arr["sales_check"] ?? ''; - $sales2->payments = json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); - $sales2->pay_arr = implode(",", $pay_arr); - $sales2->order_id = trim($arr["order_id"] ?? ''); - $sales2->terminal = $arr["terminal"] ?? ''; - $sales2->terminal_id = $arr["terminal_id"] ?? ''; - $sales2->date_up = date('Y-m-d H:i:s'); - $sales2->skidka = $arr["discount"] ?? '0'; - $sales2->delivery_date = date('Y-m-d', strtotime($arr['delivery_date'] ?? '')); - $sales2->pickup = $arr['pickup'] ?? false; - $sales2->save(); - if ($sales2->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 21, "error" => $sales2->getErrors()], JSON_UNESCAPED_UNICODE)); +// if(empty($costModels)) { +// LogService::apiErrorLog(json_encode(["error_id" => 8.3, "error" => "Стоимость и цена не подсчитаны"], JSON_UNESCAPED_UNICODE)); +// } +// $bouquetTypeHistory = new BouquetCompositionMatrixTypeHistory(); +// $bouquetTypeHistory->bouquet_id = $newBouquetComp->id; +// $bouquetTypeHistory->matrix_type_id = 1; +// $bouquetTypeHistory->created_by = Admin::getAdminAgentId() ?: null; +// $bouquetTypeHistory->is_active = 1; +// $bouquetTypeHistory->date_from = date('Y-m-d H:i:s'); +// if(!$bouquetTypeHistory->save()) { +// LogService::apiErrorLog(json_encode(["error_id" => 8.4, "error" => $bouquetTypeHistory->getErrors()], JSON_UNESCAPED_UNICODE)); +// } + } } + } - // Обновляем данные в очереди на создание чеков - CreateChecks::updateAll(['status' => 1], ['check_id' => $arr["id"]]); - - // позиции в чеке - $amount = 0; -// $items_arr = []; - $productsInfos = []; - foreach ($arr["items"] as $itemid => $arr2) { - if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { - $arr2["seller_id"] = null; - } - $saleProducts = new SalesProducts; - $saleProducts->type_id = 1; - $saleProducts->check_id = $check_id; - $saleProducts->product_id = $arr2["product_id"]; - $saleProducts->seller_id = $arr2["seller_id"]; - $saleProducts->quantity = $arr2["quantity"]; - $saleProducts->price = $arr2["price"]; - $saleProducts->summ = $arr2["summ"]; - $saleProducts->discount = $arr2["discount"]; - $saleProducts->color = $arr2["color"]; - $saleProducts->assemble_id = !empty($arr2["assemble_id"]) && $arr2["assemble_id"] != '00000000-0000-0000-0000-000000000000' ? $arr2["assemble_id"] : null; - $saleProducts->save(); - if ($saleProducts->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 22, "error" => $saleProducts->getErrors()], JSON_UNESCAPED_UNICODE)); - } - $assemble = Assemblies::find()->where(['guid' => $saleProducts->assemble_id])->one(); - if ($assemble) { - if (in_array($saleProducts->product_id, $matrixProductsIds)) { - $productsInfos[$assemble->id] = ($productsInfos[$assemble->id] ?? 0) + $saleProducts->summ; - } - $assemble->date_close = $sales2->date; - $assemble->check_id = $sales2->id; - if ($arr["type"] == 'Продажа') { - $assemble->status_id = 1; - } elseif ($arr["type"] == 'Возврат') { - $assemble->status_id = 2; - $assemble->with_return = 1; - } - $assemble->save(); - if ($assemble->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 22.2, "error" => $assemble->getErrors()], JSON_UNESCAPED_UNICODE)); + foreach ($arr as $key => $property) { + if (!in_array($key, Products1c::PRODUCT1C_FIELDS)) { + if (empty($property)) continue; + $propertyType = Products1cPropType::findOne(['id' => $key]); + if (!$propertyType) { + $propertyType = new Products1cPropType(); + $propertyType->id = $key; + $propertyType->name = $key; + if (!$propertyType->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.1, + "error" => $propertyType->getErrors()], + JSON_UNESCAPED_UNICODE)); + continue; } } + $additionalCharacteristic = Products1cAdditionalCharacteristics::findOne([ + 'product_id' => $arr["id"], + 'property_id' => $key + ]); + if (!$additionalCharacteristic && !empty($property)) { + $additionalCharacteristic = new Products1cAdditionalCharacteristics(); + $additionalCharacteristic->product_id = $arr["id"]; + $additionalCharacteristic->property_id = $key; + } + $additionalCharacteristic->value = $property; + if (!$additionalCharacteristic->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.2, + "error" => $additionalCharacteristic->getErrors()], + JSON_UNESCAPED_UNICODE)); + } + } + } - if (!empty($arr2["components"])) { - foreach ($arr2["components"] as $compID => $comp) { - $saleProducts2 = new SalesProducts; - $saleProducts2->type_id = 3; - $saleProducts2->check_id = $check_id; - $saleProducts2->product_id = $comp["product_id"]; - $saleProducts2->seller_id = $arr2["seller_id"]; - $saleProducts2->quantity = $comp["quantity"]; - $saleProducts2->color = $comp["color"]; - $saleProducts2->component_parent_id = $arr2["product_id"]; - $saleProducts2->price = 0; // ??? - $saleProducts2->discount = 0; // ??? - $saleProducts2->summ = 0; // ??? - $saleProducts2->save(); - if ($saleProducts2->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 23, "error" => $saleProducts2->getErrors()], JSON_UNESCAPED_UNICODE)); - } + if (!empty($arr["AdditionCharacteristics"])) { + $passedCharacteristics = array_column($arr["AdditionCharacteristics"], null, "id"); + $currentCharacteristics = Products1cAdditionalCharacteristics::find() + ->where(['product_id' => $arr["id"]]) + ->indexBy('property_id') + ->all(); + + foreach ($currentCharacteristics as $propertyId => $currentCharacteristic) { + if (!isset($passedCharacteristics[$propertyId])) { + if (!$currentCharacteristic->delete()) { + LogService::apiErrorLog(json_encode([ + "error_id" => 8.39, + "error" => $currentCharacteristic->getErrors() + ], JSON_UNESCAPED_UNICODE)); } } -// $salesItems = new SalesItems; -// $salesItems->lid_id = empty($arr["order_id"]) ? 0 : $arr["order_id"]; -// $salesItems->check_id = $check_id; -// $salesItems->phone = $arr["client_phone"] ?? 0; -// $salesItems->id_1c = $arr2["product_id"]; -// $salesItems->seller_id = $arr2["seller_id"]; -// $salesItems->kol = $arr2["quantity"]; -// $salesItems->color_id = $arr2["color_id"] ?? 0; -// $salesItems->summa = $arr2["summ"]; -// $salesItems->date = date('Y-m-d H:i:s'); -// $salesItems->skidka = $arr2["discount"]; -// $salesItems->store_id = 0; // ??? -// $salesItems->store_id_1c = ''; // ??? -// $salesItems->admin_id = 0; // ??? -// $salesItems->item_id = 0; // ??? -// $salesItems->complect_id = 0; // ??? -// $salesItems->name = ''; // ??? -// $salesItems->referal_id = 0; // ??? -// $salesItems->vozvrat = 0; // ??? -// $salesItems->save(); -// if ($salesItems->getErrors()) { -// LogService::apiErrorLog(json_encode(["error_id" => 24, "error" => $salesItems->getErrors()], JSON_UNESCAPED_UNICODE)); -// } -// $amount = $amount + $arr2["price"] * $arr2["quantity"]; -// $items_arr[] = ["product_id" => $arr2["product_id"], "seller_id" => $arr2["seller_id"], "quantity" => $arr2["quantity"], "summ" => $arr2["summ"], "discount" => $arr2["discount"]]; - } - foreach ($productsInfos as $assemble_id => $summ) { - Assemblies::updateAll(['summ_matrix' => $summ], ['id' => $assemble_id]); } - } - } - } elseif (!empty($result['checks'])) { - file_put_contents(self::OUT_DIR . '/error_upload.txt', - PHP_EOL . "elseif", FILE_APPEND); - $dataArrayValues = $this->getSalesDate($result["checks"], $update); - foreach ($dataArrayValues as $keyMethodName => $rowValue) { - file_put_contents(self::OUT_DIR . '/error_upload.txt', - PHP_EOL . $keyMethodName, FILE_APPEND); - try { - $this->$keyMethodName($rowValue, $update); - } catch (Exception $e) { - $errorString = substr($e->getMessage(), 0, 2000); - InfoLogService::setInfoLog(__FILE__, __LINE__, $errorString, 'error_id_25_m_st'); - } - } - } + foreach ($arr["AdditionCharacteristics"] as $characteristic) { + $propertyType = Products1cPropType::findOne(['id' => $characteristic["id"]]); + if (!$propertyType) { + $propertyType = new Products1cPropType(); + $propertyType->id = $characteristic["id"]; + $propertyType->name = $characteristic["name"]; + if (!$propertyType->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.1, + "error" => $propertyType->getErrors()], + JSON_UNESCAPED_UNICODE)); + continue; + } + } - if (!empty($result['balances'])) { - foreach ($result["balances"] as $std => $arr) { - Balances::deleteAll(['store_id' => $std]); - foreach ($arr as $pid => $arr2) { - $balances = new Balances; - $balances->store_id = $std; - $balances->product_id = $pid; - $balances->quantity = $arr2[0]; - $balances->reserv = $arr2[1]; - $balances->save(); - if ($balances->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 26, "error" => $balances->getErrors()], JSON_UNESCAPED_UNICODE)); + $additionalCharacteristic = Products1cAdditionalCharacteristics::findOne([ + 'product_id' => $arr["id"], + 'property_id' => $characteristic["id"] + ]); + + if (!$additionalCharacteristic) { + $additionalCharacteristic = new Products1cAdditionalCharacteristics(); + $additionalCharacteristic->product_id = $arr["id"]; + $additionalCharacteristic->property_id = $characteristic["id"]; + } + + $additionalCharacteristic->value = $characteristic["value_name"]; + if (!$additionalCharacteristic->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 8.2, "error" => $additionalCharacteristic->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } } } - } - } - - if (!empty($result['prices'])) { - foreach ($result["prices"] as $idp => $price) { if ( - !empty($price) - && - in_array( - $type_price, - array_keys(Prices::REGION_TYPE_PRICES) - ) + !empty($arr["type"]) + && str_starts_with($arr["type"], '[') + && str_ends_with($arr["type"], ']') ) { - $region_id = Prices::REGION_TYPE_PRICES[$type_price]; - Prices::deleteAll(['product_id' => $idp]); - $price1 = new Prices; - $price1->product_id = $idp; - $price1->price = $price; - $price1->save(); - if ($price1->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 27, "error" => $price1->getErrors()], JSON_UNESCAPED_UNICODE)); - } - PricesRegion::deleteAll(['product_id' => $idp, 'region_id' => $region_id]); - $priceRegion = new PricesRegion; - $priceRegion->product_id = $idp; - $priceRegion->region_id = $region_id; - $priceRegion->price = $price; - $priceRegion->save(); - if ($priceRegion->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 27.5, "error" => $priceRegion->getErrors()], JSON_UNESCAPED_UNICODE)); + // return [$arr["type"]]; + $product1cNomenclature = Products1cNomenclature::find()->where(['id' => $arr["id"]])->one(); + if (!$product1cNomenclature) { + $product1cNomenclature = new Products1cNomenclature(); + $product1cNomenclature->id = $arr["id"]; } - try { - $pricesDynamic = PricesDynamic::find()->where(['product_id' => $idp, 'region_id' => $region_id])->andWhere(['active' => '1'])->orderBy(['id' => SORT_DESC])->one(); - $price = round($price, 2); - // если нет записи или цена изменилась то вносим запись в БД - if ($pricesDynamic and $pricesDynamic->price != $price) { - $pricesDynamic->active = 0; - $pricesDynamic->date_to = date('Y-m-d H:i:s'); - $pricesDynamic->save(); - if ($pricesDynamic->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 28, "error" => $pricesDynamic->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } - if (!$pricesDynamic or ($pricesDynamic and ($pricesDynamic->price != $price || $pricesDynamic->region_id != $region_id))) { - $pricesDynamic2 = new PricesDynamic; - $pricesDynamic2->product_id = $idp; - $pricesDynamic2->price = $price; - $pricesDynamic2->date_from = date('Y-m-d H:i:s'); - $pricesDynamic2->date_to = '2100-01-01 00:00:00'; - $pricesDynamic2->active = 1; - $pricesDynamic2->region_id = $region_id; - $pricesDynamic2->save(); - if ($pricesDynamic2->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 29, "error" => $pricesDynamic2->getErrors()], JSON_UNESCAPED_UNICODE)); - } + $typeNomenclature = rtrim(ltrim($arr["type"], '['), ']'); + $typeArr = explode("/", $typeNomenclature); + $category = $typeArr[0]; + $subcategory = $typeArr[1] ?? null; + $product1cNomenclature->name = $arr["name"]; + $product1cNomenclature->location = $arr["type"]; + $product1cNomenclature->type_num = $typeNomenclature; + $product1cNomenclature->category = $category; + $product1cNomenclature->subcategory = $subcategory; + $characteristics = Products1cAdditionalCharacteristics::find() + ->select(['property_id', 'value']) + ->where(['product_id' => $arr["id"]]) + ->indexBy(['property_id']) + ->asArray() + ->all(); + + $propTypes = array_keys($characteristics); + $propertyNames = Products1cPropType::find() + ->select(['id','name']) + ->where(['id' => $propTypes]) + ->indexBy('id') + ->asArray() + ->all(); + $characteristicsValues = []; + + foreach ($propertyNames as $propertyId => $property) { + if (isset($characteristics[$propertyId])) { + $characteristicsValues[$property['name']] = $characteristics[$propertyId]['value']; } - } catch (Exception $e) { - file_put_contents(self::OUT_DIR . '/log_prices_dinamics.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage(), FILE_APPEND); + } + + $sizeValue = 0; + if (isset($characteristicsValues['size']) && intval($characteristicsValues['size'])) { + $sizeValue = intval($characteristicsValues['size']); + } + if (isset($characteristicsValues['размер']) && intval($characteristicsValues['размер'])) { + $sizeValue = intval($characteristicsValues['размер']); + } + + $speciesValue = null; + if (isset($characteristicsValues['species']) && !empty($characteristicsValues['species'])) { + $speciesValue = $characteristicsValues['species']; + } + if (isset($characteristicsValues['вид']) && !empty($characteristicsValues['вид'])) { + $speciesValue = $characteristicsValues['вид']; + } + + $sortValue = null; + if (isset($characteristicsValues['sort']) && !empty($characteristicsValues['sort'])) { + $sortValue = $characteristicsValues['sort']; + } + if (isset($characteristicsValues['сорт']) && !empty($characteristicsValues['сорт'])) { + $sortValue = $characteristicsValues['сорт']; + } + + $typeValue = null; + if (isset($characteristicsValues['type']) && !empty($characteristicsValues['type'])) { + $typeValue = $characteristicsValues['type']; + } + if (isset($characteristicsValues['тип']) && !empty($characteristicsValues['тип'])) { + $typeValue = $characteristicsValues['тип']; + } + + $measureValue = null; + if (isset($characteristicsValues['measure']) && !empty($characteristicsValues['measure'])) { + $measureValue = $characteristicsValues['measure']; + } + + $colorValue = null; + if (isset($characteristicsValues['color']) && !empty($characteristicsValues['color'])) { + $colorValue = $characteristicsValues['color']; + } + if (isset($characteristicsValues['цвет']) && !empty($characteristicsValues['цвет'])) { + $colorValue = $characteristicsValues['цвет']; + } + + $product1cNomenclature->species = $speciesValue; + $product1cNomenclature->sort = $sortValue; + $product1cNomenclature->type = $typeValue; + $product1cNomenclature->size = $sizeValue; + $product1cNomenclature->measure = $measureValue; + $product1cNomenclature->color = $colorValue; + + if (!$product1cNomenclature->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 8.3, "error" => $product1cNomenclature->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); } } } } - if (!empty($result['prices'])) { - foreach ($result["prices"] as $idp => $price) { - if (!empty($price) and $type_price == "Закупочная цена руб.") { - try { - $priceZakup = new PricesZakup; - $priceZakup->product_id = $idp; - $priceZakup->price = $price; - $priceZakup->save(); - if ($priceZakup->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 30, "error" => $priceZakup->getErrors()], JSON_UNESCAPED_UNICODE)); - } - } catch (Exception $e) { - } + if (!empty($result['payment_types'])) { + foreach ($result["payment_types"] as $gi => $arr) { + $paymentTypes = PaymentTypes::findOne(['id' => $arr['id']]) ?? new PaymentTypes(); + $paymentTypes->id = $arr['id']; + $paymentTypes->code = $arr['code']; + $paymentTypes->name = $arr['name']; + $paymentTypes->save(); + if ($paymentTypes->getErrors()) { + LogService::apiErrorLog(json_encode( + ["error_id" => 9, + "error" => $paymentTypes->getErrors()], + JSON_UNESCAPED_UNICODE + )); } - if (!empty($price) and $type_price == "Себестоимость") { - try { - file_put_contents(self::OUT_DIR . '/price_purchese.txt', PHP_EOL . "$idp=" . $price, FILE_APPEND); - } catch (Exception $e) { - } + + $products1c7 = Products1c::findOne(['id' => $arr["id"]]) ?? new Products1c(); + $products1c7->id = $arr["id"]; + $products1c7->tip = 'payment_types'; + $products1c7->name = $arr["name"]; + $products1c7->code = $arr["code"]; + $products1c7->save(); + if ($products1c7->getErrors()) { + LogService::apiErrorLog(json_encode( + ["error_id" => 10, "error" => $products1c7->getErrors()], + JSON_UNESCAPED_UNICODE + )); } } } - if (!empty($result['created_checks'])) { - foreach ($result["created_checks"] as $idp => $arr2) { - if (!empty($arr2["error"])) { // Если есть ошибки - // // обновляем GUID на новый -// try { -// $createChecks = CreateChecks::find()->select(['order_id'])->where(['check_id' => $arr2["id"]])->one(); -// if ($createChecks) { -// $lid_id = $createChecks->order_id; -// $guid_new = \yii_app\controllers\crud\UniversalCatalogController::create_guid_my_old("01", $lid_id); -// $createChecks2 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->andWhere(['!=', 'check_id', '0']) -// ->andWhere(['status' => '0'])->andWhere(['held' => '0'])->one(); -// if ($createChecks2) { -// $createChecks2->check_id = $guid_new; -// $createChecks2->save(); -// if ($createChecks2->getErrors()) { -// LogService::apiErrorLog(json_encode(["error_id" => 32, "error" => $createChecks2->getErrors()], JSON_UNESCAPED_UNICODE)); -// } -// } -// } else { -// LogService::apiErrorLog(json_encode(["error_id" => 31, "error" => 'no create_checks with check_id=' . $arr2["id"]], JSON_UNESCAPED_UNICODE)); -// } -// } catch (Exception $e) { -// file_put_contents(self::OUT_DIR . '/log_created_check_error.txt', PHP_EOL . date("d.m.Y H:i:s",time()). $e->getMessage(), FILE_APPEND); -// } + if (!empty($result['created_write_offs'])) { + $productsNames = Products1c::getNamesByTip('products'); - $txt = date("d.m.Y H:i:s", time()) . " $idp СОЗДАНИЕ ЧЕКА ОШИБКА id=" . $arr2["id"] . " " . $arr2["error"]; - file_put_contents(self::OUT_DIR . '/log_created_check_error.txt', PHP_EOL . $txt, FILE_APPEND); - } else { // Если ошибок нет - if (/* $arr2["held"] == true and */ !empty($arr2["name"]) and !empty($arr2["id"])) { // Если заполнен name b id -// $createChecksBags = CreateChecksBags::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]])->orderBy(['id' => SORT_DESC])->one(); -// if ($createChecksBags) { -// $createChecksBags->guid = $arr2["guid"]; -// $createChecksBags->name = $arr2["name"]; -// $createChecksBags->held = $arr2["held"]; -// $createChecksBags->status = '1'; -// $createChecksBags->date_up = date('Y-m-d H:I:s'); -// $createChecksBags->save(); -// if ($createChecksBags->getErrors()) { -// LogService::apiErrorLog(json_encode(["error_id" => 33, "error" => $createChecksBags->getErrors()], JSON_UNESCAPED_UNICODE)); -// } -// } - // Обновляем данные в очереди на создание чеков - CreateChecks::updateAll([ - 'status' => 1, - 'guid' => $arr2["id"], - 'date_up' => date('Y-m-d H:i:s'), - 'name' => $arr2["name"], - 'held' => isset($arr2["held"]) ? $arr2["held"] : 0 - ], ['check_id' => $arr2["id"]]); -// $createChecks3 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->orderBy(['id' => SORT_DESC])->one(); -// if ($createChecks3) { -// $createChecks3->guid = $arr2["id"]; -// $createChecks3->name = $arr2["name"]; -// $createChecks3->held = isset($arr2["held"]) ? ($arr2["held"] ? 1 : 0) : 0; -// $createChecks3->status = '1'; -// $createChecks3->date_up = date('Y-m-d H:i:s'); -// $createChecks3->save(); -// if ($createChecks3->getErrors()) { -// LogService::apiErrorLog(json_encode(["error_id" => 34, "error" => $createChecks3->getErrors()], JSON_UNESCAPED_UNICODE)); -// } -// } -// $createChecks4 = CreateChecks2::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]])->orderBy(['id' => SORT_DESC])->one(); -// if ($createChecks4) { -// $createChecks4->name = $arr2["name"]; -// $createChecks4->held = $arr2["held"]; -// $createChecks4->status = '1'; -// $createChecks4->date_up = date('Y-m-d H:I:s'); -// $createChecks4->save(); -// if ($createChecks4->getErrors()) { -// LogService::apiErrorLog(json_encode(["error_id" => 35, "error" => $createChecks4->getErrors()], JSON_UNESCAPED_UNICODE)); -// } -// } -// $createChecks5 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]]) -// ->andWhere(['type' => 'Возврат'])->orderBy(['id' => SORT_DESC])->one(); -// if ($createChecks5) { -// $createChecks5->held = $arr2["held"]; -// $createChecks5->status = '1'; -// $createChecks5->date_up = date('Y-m-d H:I:s'); -// $createChecks5->save(); -// if ($createChecks5->getErrors()) { -// LogService::apiErrorLog(json_encode(["error_id" => 35, "error" => $createChecks5->getErrors()], JSON_UNESCAPED_UNICODE)); -// } -// } - // прикрепляем чек к заказу - $ordersAmo = OrdersAmo::find()->where(['id' => $arr2["order_id"]])->one(); - if ($ordersAmo) { - $ordersAmo->check_id_arr = $arr2["id"]; - $ordersAmo->save(false); - if ($ordersAmo->getErrors()) { - LogService::apiErrorLog(json_encode(["error_id" => 36, "error" => $ordersAmo->getErrors()], JSON_UNESCAPED_UNICODE)); + file_put_contents( + self::OUT_DIR . '/created_write_offs_upload_' + . date("Y_m_d") . '.json', + PHP_EOL + . json_encode($result["created_write_offs"], JSON_UNESCAPED_UNICODE), + FILE_APPEND + ); + foreach ($result["created_write_offs"] as $arr) { + if (!empty($arr["id"])) { + $writeOffsErp = WriteOffsErp::find()->where(['guid' => $arr["id"]])->one(); + if (empty($writeOffsErp)) { + $waybillWriteOffsErp = WaybillWriteOffs::find()->where(['guid' => $arr["id"]])->one(); + } + } + + if (!empty($writeOffsErp) || !empty($waybillWriteOffsErp)) { + if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { + $errorText = ''; + if (!empty($arr["errors"])) { + //"errors": [ + //{ + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + //"error_json": [ + //{ + //"field": "id", + //"error": "Документ с данным ИД уже записан в системе" + //} + // + + foreach ($arr["errors"] as $errorRow) { + if (!empty($errorRow['error'])) { + $errorText .= $errorRow['error']; + + $errorText .= ' ,' . $errorRow['error_description']; + if (!empty($errorRow['error_json'])) { + foreach ($errorRow['error_json'] as $errorJsonRow) { + $errorText .= ' , поле: ' . $errorJsonRow['field']; + $errorText .= ' , ошибка: ' . $errorJsonRow['error']; + } + } + } + + if (!empty($errorRow["errors_items"])) { + foreach ($errorRow["errors_items"] as $errorDopRow) { + //"errors_items": [ + //{ + //"error_dop": "Ошибка проверки количества номенклатуры", + //"field": "quantity", + //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", + //"error": "У данной позиции запрещён ввод дробного значения!" + //}, + // + // + $productName = $errorDopRow['product_id']; + + if (array_key_exists($errorDopRow['product_id'], $productsNames)) { + $productName = $productsNames[$errorDopRow['product_id']]; + } + + $errorText .= ' ' . $errorDopRow['error_dop']; + $errorText .= ' , поле: ' . $errorDopRow['field']; + $errorText .= ' , товар: ' . $productName; + $errorText .= ' , ошибка: ' . $errorDopRow['error']; + } + } + } + } + if (!empty($writeOffsErp)) { + /** @var WriteOffsErp $writeOffsErp */ + $writeOffsErp->status = WriteOffsErp::STATUS_ERROR_1C; + $writeOffsErp->error_text = $errorText; + $writeOffsErp->save(); + if ($writeOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 11.1, "error" => $writeOffsErp->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + if (!empty($waybillWriteOffsErp)) { + /** @var WaybillWriteOffs $waybillWriteOffsErp */ + $waybillWriteOffsErp->status = WriteOffsErp::STATUS_ERROR_1C; + $waybillWriteOffsErp->error_text = $errorText; + $waybillWriteOffsErp->save(); + if ($waybillWriteOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 11.2, "error" => $waybillWriteOffsErp->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); } } - // обращаемся к старой базе данных базацветов_24 - // ??? - } - } - } - } - - if (!empty($result['created_employee'])) { - foreach ($result['created_employee'] as $arr) { - EmployeeOnShift::updateAll(['status_source' => EmployeeOnShift::STATUS_SOURCE_CREATED_IN_1C], ['guid' => $arr['id']]); - } - } + } else { + if (!empty($writeOffsErp)) { + /** @var WriteOffsErp $writeOffsErp */ + $writeOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; + $writeOffsErp->number_1c = $arr["number"] ?? ''; + $writeOffsErp->save(); + if ($writeOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode( + [ + "error_id" => 11.3, + "error" => $writeOffsErp->getErrors() + ], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + if (!empty($waybillWriteOffsErp) && isset($arr["held"]) && $arr["held"]) { + /** @var WaybillWriteOffs $waybillWriteOffsErp */ + $waybillWriteOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; + $waybillWriteOffsErp->name_1c = $arr["name"] ?? ''; + $waybillWriteOffsErp->save(); + if ($waybillWriteOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode( + [ + "error_id" => 11.4, + "error" => $waybillWriteOffsErp->getErrors() + ], + JSON_UNESCAPED_UNICODE + ) + ); + } + } - if (!empty($result['marketplace_orders'])) { - foreach ($result["marketplace_orders"] as $mpOrder) { - $updateResult = $this->changeMarketplaceOrderStatusFrom1C($mpOrder); //изменение статусов - if ($updateResult['status'] == 'error') { - LogService::apiErrorLog(json_encode(["error_id" => 40, "error" => $updateResult['message']], JSON_UNESCAPED_UNICODE)); + } } } } -// - $mess["request_id"] = "" . time(); - - if (!empty($result['created_orders'])) { - $mess['line'][] = __LINE__; - $mess["created_orders"] = $result['created_orders']; + if (!empty($result['created_write_ons'])) { $productsNames = Products1c::getNamesByTip('products'); - foreach ($result['created_orders'] as $arr) { - $marketplaceOrders = null; - $marketplaceOrdersGuidArr = []; + file_put_contents( + self::OUT_DIR . '/created_write_ons_upload_' + . date("Y_m_d") . '.json', + PHP_EOL + . json_encode($result["created_write_ons"], JSON_UNESCAPED_UNICODE), + FILE_APPEND + ); + foreach ($result["created_write_ons"] as $arr) { if (!empty($arr["id"])) { - $marketplaceOrders = MarketplaceOrders::find()->where(['guid' => $arr["id"]])->one(); - if ($marketplaceOrders && $marketplaceOrders->guid) { - $marketplaceOrdersGuidArr[] = $marketplaceOrders->guid; - } + $waybillIncoming = WaybillIncoming::find()->where(['guid' => $arr["id"]])->one(); } - if (!empty($marketplaceOrders)) { - /** @var MarketplaceOrders $marketplaceOrders */ - $mess['line'][] = __LINE__; - if (!empty($arr["errors"]) || !empty($arr["error"]) || !empty($arr["errors_items"])) { + + if (!empty($waybillIncoming)) { + if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { $errorText = ''; if (!empty($arr["errors"])) { - //"errors": [ - //{ - //"error": "Ошибка преобразования ИД документа", - //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", - //"error_json": [ - //{ - //"field": "id", - //"error": "Документ с данным ИД уже записан в системе" - //} - // + //"errors": [ + //{ + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + //"error_json": [ + //{ + //"field": "id", + //"error": "Документ с данным ИД уже записан в системе" + //} + // foreach ($arr["errors"] as $errorRow) { if (!empty($errorRow['error'])) { @@ -2547,15 +4062,15 @@ class DataController extends BaseController if (!empty($errorRow["errors_items"])) { foreach ($errorRow["errors_items"] as $errorDopRow) { - //"errors_items": [ - //{ - //"error_dop": "Ошибка проверки количества номенклатуры", - //"field": "quantity", - //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", - //"error": "У данной позиции запрещён ввод дробного значения!" - //}, - // - // + //"errors_items": [ + //{ + //"error_dop": "Ошибка проверки количества номенклатуры", + //"field": "quantity", + //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", + //"error": "У данной позиции запрещён ввод дробного значения!" + //}, + // + // $productName = $errorDopRow['product_id']; if (array_key_exists($errorDopRow['product_id'], $productsNames)) { @@ -2571,157 +4086,28 @@ class DataController extends BaseController } } - if (!empty($arr["error"])) { - //"error": "Ошибка преобразования ИД документа", - //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", - $errorText .= $arr["error"]; - $errorText .= ' ,' . $arr['error_description']; - } - - $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; - $marketplaceOrders->error_text = $errorText; - $marketplaceOrders->save(); - if ($marketplaceOrders->getErrors()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } else { - $mess['line'][] = __LINE__; - if (isset($arr["held"]) && $arr["held"]) { - $mess['line'][] = __LINE__; - $marketplaceOrders->number_1c = $arr["number"] ?? ''; - $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_1C; - $marketplaceOrders->save(); - if ($marketplaceOrders->getErrors()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 42, "error" => $marketplaceOrders->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } - } - } - } - - $now = time(); - $sendedOrders = MarketplaceOrders::find() - ->where(['status_1c' => MarketplaceOrders::STATUSES_1C_SENDED_TO_1C]) - ->andWhere(['not in', 'guid', $marketplaceOrdersGuidArr]) - ->all(); - foreach ($sendedOrders as $order) { - $sentAt = strtotime($order->sent_1c_at ?? '2025-07-01 00:00:00'); - $attempts = (int)$order->attempts_number; - if (($now - $sentAt) > 300) { - if ($attempts < 4) { - $order->sent_1c_at = null; - $order->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_ERP; - $order->save(); - } else { - $order->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; - $order->error_text = 'Превышено число попыток отправки в 1С.'; - $order->save(); - - LogService::apiErrorLog(json_encode([ - "error_id" => 43, - "error" => "Превышено число попыток отправки в 1С " . $order->guid, - ], JSON_UNESCAPED_UNICODE)); - } - } - } - - } - - if (!empty($result['analysts_business_operations'])) { - $existingOperations = AnalystsBusinessOperations::find() - ->indexBy('id') - ->asArray() - ->all(); - $existingTypes = AnalystsBusinessOperationsTypes::find() - ->indexBy('code') - ->asArray() - ->all(); - foreach ($result["analysts_business_operations"] as $operation) { - if (!in_array($operation['id'], array_keys($existingOperations))) { - $newOperation = new AnalystsBusinessOperations(); - $newOperation->id = $operation['id']; - $newOperation->name = $operation['name']; - $newOperation->type = (int)$operation['type']; - $newOperation->active = 1; - if (!in_array((int)$operation['type'], array_column($existingTypes, 'code'))) { - $newType = new AnalystsBusinessOperationsTypes(); - $newType->code = (int)$operation['type']; - $newType->name = null; - $newType->alias = null; - $newType->created_at = date('Y-m-d H:i:s'); - $newType->created_by = 1409; - if ($newType->save()) { - $newOperation->type_id = $newType->id; - } else { - $newOperation->type_id = null; - Yii::error('Ошибка сохранение типа ' . json_encode($newType->getErrors(), JSON_UNESCAPED_UNICODE), __METHOD__ ); - LogService::apiErrorLog( - json_encode( - ["error_id" => 44.1, "error" => $newType->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } else { - $newOperation->type_id = $existingTypes[$operation['type']]['id']; - } - $newOperation->created_at = date('Y-m-d H:i:s'); - if (!$newOperation->save()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 44.2, "error" => $newOperation->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - - } else { - if ($existingOperations[$operation['id']]['type'] !== (int)$operation['type']) { - $oldOperation = AnalystsBusinessOperations::findOne($operation['id']); - if (!in_array((int)$operation['type'], array_column($existingTypes, 'code'))) { - $newType = new AnalystsBusinessOperationsTypes(); - $newType->code = (int)$operation['type']; - $newType->name = null; - $newType->alias = null; - $newType->created_at = date('Y-m-d H:i:s'); - $newType->created_by = 1409; - if ($newType->save()) { - $oldOperation->type = (int)$operation['type']; - $oldOperation->type_id = $newType->id; - if (!$oldOperation->save()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 44.3, "error" => $oldOperation->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } else { - Yii::error('Ошибка сохранение типа ' . json_encode($newType->getErrors(), JSON_UNESCAPED_UNICODE), __METHOD__ ); - LogService::apiErrorLog( - json_encode( - ["error_id" => 44.4, "error" => $oldOperation->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); - } - } else { - $oldOperation->type = (int)$operation['type']; - $oldOperation->type_id = AnalystsBusinessOperationsTypes::find()->where(['code' => (int)$operation['type']])->one()->id; - if (!$oldOperation->save()) { + /** @var WaybillIncoming $waybillIncoming */ + $waybillIncoming->status = WriteOffsErp::STATUS_ERROR_1C; + $waybillIncoming->error_text = $errorText; + $waybillIncoming->save(); + if ($waybillIncoming->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 11.5, "error" => $waybillIncoming->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + if (isset($arr["held"]) && $arr["held"]) { + /** @var WaybillIncoming $waybillIncoming */ + $waybillIncoming->status = WriteOffsErp::STATUS_CREATED_1C; + $waybillIncoming->number_1c = $arr["name"] ?? ''; + $waybillIncoming->save(); + if ($waybillIncoming->getErrors()) { LogService::apiErrorLog( json_encode( - ["error_id" => 44.5, "error" => $oldOperation->getErrors()], + ["error_id" => 11.55, "error" => $waybillIncoming->getErrors()], JSON_UNESCAPED_UNICODE ) ); @@ -2729,25 +4115,27 @@ class DataController extends BaseController } } } - } } - if (!empty($result['cancelled_orders'])) { - foreach ($result['cancelled_orders'] as $arr) { - $marketplaceOrders = null; - $marketplaceOrdersGuidArr = []; - - $marketplaceOrders = MarketplaceOrders::find()->where(['guid' => $arr])->one(); - $marketplaceOrdersGuidArr[] = $marketplaceOrders->guid; - if (!empty($marketplaceOrders)) { - /** @var MarketplaceOrders $marketplaceOrders */ + if (!empty($result['created_resortings'])) { + $productsNames = Products1c::getNamesByTip('products'); + file_put_contents( + self::OUT_DIR . '/created_resortings_upload_' + . date("Y_m_d") . '.json', + PHP_EOL + . json_encode($result["created_resortings"], JSON_UNESCAPED_UNICODE), + FILE_APPEND + ); + foreach ($result["created_resortings"] as $arr) { + if (!empty($arr["id"])) { + $replacementInvoice = ReplacementInvoice::findOne(['guid' => $arr["id"]]); + } - if (!empty($arr["errors"]) || !empty($arr["error"]) || !empty($arr["errors_items"])) { + if (!empty($replacementInvoice)) { + if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { $errorText = ''; if (!empty($arr["errors"])) { - - foreach ($arr["errors"] as $errorRow) { if (!empty($errorRow['error'])) { $errorText .= $errorRow['error']; @@ -2760,623 +4148,1066 @@ class DataController extends BaseController } } } - } - } - if (!empty($arr["error"])) { - //"error": "Ошибка преобразования ИД документа", - //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", - $errorText .= $arr["error"]; - $errorText .= ' ,' . $arr['error_description']; + if (!empty($errorRow["errors_items"])) { + foreach ($errorRow["errors_items"] as $errorDopRow) { + $productName = $errorDopRow['product_id']; + + if (array_key_exists($errorDopRow['product_id'], $productsNames)) { + $productName = $productsNames[$errorDopRow['product_id']]; + } + + $errorText .= ' ' . $errorDopRow['error_dop']; + $errorText .= ' , поле: ' . $errorDopRow['field']; + $errorText .= ' , товар: ' . $productName; + $errorText .= ' , ошибка: ' . $errorDopRow['error']; + } + } + } } - $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; - $marketplaceOrders->error_text = $errorText; - $marketplaceOrders->save(); - if ($marketplaceOrders->getErrors()) { + /** @var ReplacementInvoice $replacementInvoice */ + $replacementInvoice->status = WriteOffsErp::STATUS_ERROR_1C; + $replacementInvoice->error_text = $errorText; + $replacementInvoice->save(); + if ($replacementInvoice->getErrors()) { LogService::apiErrorLog( json_encode( - ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], + ["error_id" => 4.555, "error" => $replacementInvoice->getErrors()], JSON_UNESCAPED_UNICODE ) ); } + } else { - $marketplaceOrders->cancelled_order_sent = MarketplaceOrders::STATUSES_1C_CANCELLED_ORDER_SENT_IN_1C; - $marketplaceOrders->save(); - if ($marketplaceOrders->getErrors()) { - LogService::apiErrorLog( - json_encode( - ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], - JSON_UNESCAPED_UNICODE - ) - ); + if (isset($arr["held"]) && $arr["held"]) { + /** @var ReplacementInvoice $replacementInvoice */ + $replacementInvoice->status = WriteOffsErp::STATUS_CREATED_1C; + $replacementInvoice->number_1c = $arr["name"] ?? ''; + $replacementInvoice->save(); + if ($replacementInvoice->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 4.55, "error" => $replacementInvoice->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } } } } } - - - } - $mess['line'][] = __LINE__; - } catch (Exception $e) { - LogService::apiDataLogs(1, json_encode($mess, JSON_UNESCAPED_UNICODE), $requestIdText); - file_put_contents(self::OUT_DIR . '/log_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage() . " " . $e->getLine(), FILE_APPEND); - Yii::error('Ошибка upload - блок catch '. json_encode($e->getMessage() . " " . $e->getLine(), JSON_UNESCAPED_UNICODE)); - LogService::apiErrorLog(json_encode([ - "error_id" => 45, - "error" => "Ошибка загрузки " . $e->getMessage() . " " . $e->getLine(), - ], JSON_UNESCAPED_UNICODE)); - } finally { - LogService::apiDataLogs(1, json_encode($mess, JSON_UNESCAPED_UNICODE), $requestIdText); - } - - return $this->asJson(['response' => true]); - } - - private function getPayArr($arrPayments): array - { - $pay_arr = array(); - if (!empty($arrPayments)) { - foreach ($arrPayments as $tp) { - if ($tp["type"] == "Наличные") { - $pay_arr[] = 1; - } elseif ($tp['type'] == 'QR код') { - $pay_arr[] = 3; - } else { - $pay_arr[] = 2; + $update = false; + if (!empty($start_time) && !empty($end_time)) { + $start_time_unix = strtotime($start_time); + $startMonth = date("Y-m-01"); + $end_time_unix = strtotime($end_time); + if ( + $startMonth <= (date("Y-m-d", strtotime($start_time))) + || + ($end_time_unix < (time() - 90 * 86400)) + ) { + $update = true; } } - } - - return $pay_arr; - } - - private function getSalesDate($checks, $update): array - { - $admins = $this->getEntityByType('admin'); - - $adminsIds = array_column($admins, 'entity_id'); - $adminsValue = array_column($admins, 'export_val'); - - $adminsGuidIds = array_combine($adminsValue, $adminsIds); - $adminsIdsGuid = array_combine($adminsIds, $adminsValue); - - $stores = $this->getEntityByType(); - - $storesIds = array_column($stores, 'entity_id'); - $storesValue = array_column($stores, 'export_val'); - - $storesGuidIds = array_combine($storesValue, $storesIds); - $storesIdsGuid = array_combine($storesIds, $storesValue); - $checksIdsPrepared = array_column($checks, 'id'); + if (!empty($result['write_offs'])) { + if (!empty($start_time) and !empty($end_time)) { + if ($update) { + WriteOffs::deleteAll(['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); + } + } - $checksIds = array_unique($checksIdsPrepared); + foreach ($result["write_offs"] as $gi => $arr) { + if (!empty($arr["error"])) { + file_put_contents(self::OUT_DIR . '/created_write_offs_erp_error.txt', PHP_EOL . " " . $arr["id"] . " error=" . $arr["error"], FILE_APPEND); + } - $checksValues = []; - $salesProducts = []; - $salesItems = []; - $salesProductsComponents = []; + if (empty($arr["error"]) && !empty($arr["id"])) { + $writeOffsErp = WriteOffsErp::find()->where(['guid' => $arr["id"]])->one(); + if ($writeOffsErp) { + $writeOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; + $writeOffsErp->number_1c = $arr["number"]; + $writeOffsErp->save(); + if ($writeOffsErp->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 11.6, "error" => $writeOffsErp->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } else { + $waybillWriteOffsErp = WaybillWriteOffs::find()->where(['guid' => $arr["id"]])->one(); + if ($waybillWriteOffsErp) { + $waybillWriteOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; + $waybillWriteOffsErp->number_1c = $arr["number"]; + $waybillWriteOffsErp->save(); + if ($waybillWriteOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode(["error_id" => 11.7, "error" => $waybillWriteOffsErp->getErrors()], + JSON_UNESCAPED_UNICODE) + ); + } + } + } + } - foreach ($checks as $arr) { - $check_id = $arr["id"]; +// file_put_contents(self::OUT_DIR . '/write_offs.json', PHP_EOL . json_encode($result["write_offs"], JSON_UNESCAPED_UNICODE)); - if (array_key_exists($arr["store_id"], $storesGuidIds)) { - $store_id = $storesGuidIds[$arr["store_id"]]; - } - if (array_key_exists($arr["seller_id"], $adminsGuidIds)) { - $admin_id = $adminsGuidIds[$arr["seller_id"]]; - } + $writeOffs = WriteOffs::find()->where(['id' => $arr["id"]])->one(); + if ($writeOffs) { + $writeOffs->delete(); + } + WriteOffsProducts::deleteAll(['write_offs_id' => $arr["id"]]); - $pay_arr = $this->getPayArr($arr["payments"]); + $writeOffs2 = new WriteOffs; + $writeOffs2->id = $arr["id"]; + $writeOffs2->status_id = 1; + $writeOffs2->write_downs = '1c'; + $writeOffs2->store_id = $arr["store_id"]; + $writeOffs2->number = $arr["number"]; + $writeOffs2->date = $arr["date"]; + $writeOffs2->based_on = $arr["based_on"] ?? ""; + $typeIndex = strpos($arr["type"], "_"); + $writeOffs2->type = $typeIndex === false ? $arr['type'] : substr($arr["type"], $typeIndex + 1); + $writeOffs2->cause = $arr["cause"] ?? ""; + $writeOffs2->comment = $arr["comment"] ?? ""; + $writeOffs2->items = json_encode($arr["items"], JSON_UNESCAPED_UNICODE); + $writeOffs2->summ = $arr["summ"]; + $writeOffs2->save(); + if ($writeOffs2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 12, "error" => $writeOffs2->getErrors(), "number" => $arr["number"]], JSON_UNESCAPED_UNICODE)); + } - if (empty($store_id)) { - continue; + foreach ($arr["items"] as $j2 => $mass2) { + $writeOffsProducts = WriteOffsProducts::findOne([ + 'write_offs_id' => $arr["id"], + 'product_id' => $mass2['product_id'], + ]) ?? new WriteOffsProducts(); + $writeOffsProducts->write_offs_id = $arr["id"]; + $writeOffsProducts->date = $arr["date"]; + $writeOffsProducts->product_id = $mass2['product_id']; + $writeOffsProducts->color = $mass2["color"]; + $writeOffsProducts->quantity = ceil($mass2["quantity"]); + $writeOffsProducts->summ = $mass2["summ"]; + $writeOffsProducts->price = $mass2["price"]; + $writeOffsProducts->price_retail = 0; + $writeOffsProducts->summ_retail = 0; + $writeOffsProducts->save(); + if ($writeOffsProducts->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 13, "error" => $writeOffsProducts->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } } - $date_up = date("Y-m-d H:i:s"); - $date = date("Y-m-d H:i:s"); - - $purchaseItemsArray = []; - - // позиции в чеке - $amount = 0; - $items_arr = []; - foreach ($arr["items"] as $itemid => $arr2) { - if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { - $arr2["seller_id"] = null; + if (!empty($result['counteragents'])) { + foreach ($result["counteragents"] as $gi => $arr) { + $arr["is_group"] = $arr["is_group"] ? 1 : 0; + $products1c = new Products1c; + $products1c->id = $arr["id"]; + $products1c->tip = 'counteragents'; + $products1c->name = $arr["name"]; + $products1c->code = $arr["inn"]; + $products1c->parent_id = $arr["parent_id"]; + $products1c->view = $arr["is_group"]; + $products1c->save(); + if ($products1c->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 14, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); + } } + } - $purchaseItemsRow = 0; - if (!empty($arr2["purchase_price"]) && !empty($arr2["quantity"])) { - $purchaseItemsRow = $arr2["purchase_price"] * $arr2["quantity"]; + if (!empty($result['incomings'])) { + foreach ($result["incomings"] as $gi => $arr) { + $incoming = Incoming::find()->where(['id' => $arr['id']])->one(); + if (!$incoming) { + $incoming = new Incoming; + $incoming->id = $arr["id"]; + $incoming->store_id = $arr["store_id"]; + $incoming->counteragent_id = $arr["counteragent_id"]; + $incoming->number = $arr["number"]; + $incoming->date = $arr["date"]; + $incoming->comment = $arr["comment"] ?? ''; + $incoming->items = empty($arr["items"]) ? '[]' : json_encode($arr["items"], JSON_UNESCAPED_UNICODE); + $incoming->is_discrepancies = (int)$arr["is_discrepancies"]; + $incoming->supplier_items = empty($arr["supplier_items"]) ? '[]' : json_encode($arr["supplier_items"], JSON_UNESCAPED_UNICODE); + $incoming->payments = empty($arr["payments"]) ? '[]' : json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); + $incoming->summ = $arr["summ"]; + $incoming->save(); + } + if ($incoming->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 15, "error" => $incoming->getErrors()], JSON_UNESCAPED_UNICODE)); + } else { + try { + $json = Json::decode($incoming->items); + IncomingItems::deleteAll(['incoming_id' => $incoming->id]); + foreach ($json as $item) { + $incomingItem = new IncomingItems; + $incomingItem->incoming_id = $incoming->id; + $incomingItem->product_id = $item['product_id']; + $incomingItem->color = $item['color']; + $incomingItem->quantity = $item['quantity']; + $incomingItem->price = $item['price']; + $incomingItem->vat_rate = $item['vat_rate']; + $incomingItem->vat_amount = $item['vat_amount']; + $incomingItem->summ = $item['summ']; + $incomingItem->save(); + if ($incomingItem->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 15.2, "error" => $incomingItem->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } catch (Exception $jex) { + LogService::apiErrorLog(json_encode(["error_id" => 15.3, "error" => "items has no json format"], JSON_UNESCAPED_UNICODE)); + } + } } + } - $purchaseItemsArray[] = $purchaseItemsRow; + if (!empty($result['cashes'])) { + foreach ($result["cashes"] as $gi => $arr) { + $products1c = new Products1c; + $products1c->id = $arr["id"]; + $products1c->tip = 'cashes'; + $products1c->name = $arr["name"]; + $products1c->code = $arr["store_id"]; + $products1c->save(); + if ($products1c->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 16, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); + } + $cashes = new Cashes; + $cashes->id = $arr["id"]; + $cashes->store_id = $arr["store_id"]; + $cashes->kkm_id = $arr["kkm_id"]; + $cashes->name = $arr["name"]; + $cashes->is_central = $arr["is_central"]; + $cashes->save(); + if ($cashes->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 17, "error" => $cashes->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } - $salesProducts[] = [ - 'type_id' => '1', // type_id, - 'check_id' => $check_id, // check_id, - 'product_id' => $arr2["product_id"], // product_id, - 'seller_id' => $arr2["seller_id"], // seller_id, - 'quantity' => $arr2["quantity"], // quantity, - 'price' => $arr2["price"], // price, - 'summ' => $arr2["summ"], // summ, - 'purchase_price' => $arr2["purchase_price"] ?? 0, // purchase_price, - 'purchase_sum' => $purchaseItemsRow, // purchase_sum, - 'discount' => $arr2["discount"], // discount, - 'color' => $arr2["color"] // color - ]; + if (!empty($checks_dell) and !empty($start_time) and !empty($end_time)) { + if ($update) { + Sales::updateAll(['operation' => 'Удален'], ['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); + } +// SalesUpdate::updateAll(['operation' => 'Удален'], ['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); - $log[$arr["id"]][$itemid] = $arr2; + file_put_contents(self::OUT_DIR . '/check_dell.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . " regquest_id=$requestId Удаление $start_time - $end_time ", FILE_APPEND); + } - if (!empty($arr2["components"])) { - foreach ($arr2["components"] as $compID => $comp) { - $salesProductsComponents[] = - [ - 'type_id' => '3', // type_id - 'check_id' => $check_id, // check_id - 'product_id' => $comp["product_id"], // product_id - 'seller_id' => $arr2["seller_id"], // seller_id - 'quantity' => $comp["quantity"], // quantity - 'color' => $comp["color"], // color - 'component_parent_id' => $arr2["product_id"], // component_parent_id - 'price' => 0, // price, - 'discount' => 0, // discount, - 'summ' => 0, // summ, - ]; + $matrixProductsIds = []; + if (!empty($result['checks'])) { + $matrixProductsIds = SalaryHelper::getMatrixProductsIds(); + } - $salesItems[] = [ - 'lid_id' => $arr["order_id"], // lid_id - 'check_id' => $check_id, // check_id - 'phone' => $arr["client_phone"] ?? null, // phone - 'id_1c' => $arr2["product_id"], // id_1c - 'seller_id' => $arr2["seller_id"], // seller_id - 'kol' => $arr2["quantity"], // kol - 'color_id' => $arr2["color_id"] ?? 0, // color_id - 'summa' => $arr2["summ"], // summa - 'skidka' => $arr2["discount"], // skidka - 'date' => $date, // date - ]; + if (!empty($result['checks'])) { + foreach ($result["checks"] as $index => $arr) { + if (!isset($arr["marketplace_order_id"])) { + continue; + } + $marketplaceOrder = MarketplaceOrders::findOne(['guid' => $arr["marketplace_order_id"]]); + if (!empty($arr['error'])) { + $txt = date("d.m.Y H:i:s", time()) . " $index СОЗДАНИЕ ЧЕКА ОШИБКА id=" . $arr["id"] . " " . $arr["error"]; + file_put_contents(self::OUT_DIR . '/log_check_error.txt', PHP_EOL . $txt, FILE_APPEND); + $marketplaceOrder->error_text = "ОШИБКА ЧЕКА" . $arr["id"] . "для заказа id=" . $marketplaceOrder->marketplace_order_id . " " . $arr["error"]; + $marketplaceOrder->save(); + if ($marketplaceOrder->getErrors()) { + Yii::error('Ошибка сохранения ошибки заказа ' . json_encode($marketplaceOrder->getErrors(), JSON_UNESCAPED_UNICODE)); + LogService::apiErrorLog(json_encode(["error_id" => 17.2, "error" => $marketplaceOrder->getErrors()], JSON_UNESCAPED_UNICODE)); + } + continue; + } + $check = CreateChecks::find() + ->where(['check_id' => $arr["id"]]) + ->andWhere(['order_guid' => $arr["marketplace_order_id"]]) + ->andWhere(['status' => 0])->one(); + if(!$check) { + continue; + } + $check->status = 1; + $check->name = $arr["number"] . " от " . $arr["date"]; + $check->guid = $arr["id"]; + $check->date_up = date('Y-m-d H:i:s'); + $check->held = 1; + $check->save(); + if ($check->getErrors()) { + Yii::error('Ошибка обновления чека ' . json_encode($check->getErrors(), JSON_UNESCAPED_UNICODE)); + LogService::apiErrorLog(json_encode(["error_id" => 17.3, "error" => $check->getErrors()], JSON_UNESCAPED_UNICODE)); } } } - $purchaseItemsSum = array_sum($purchaseItemsArray); + if (!empty($result['checks']) && count($result['checks']) < 1000) { - $checksValues[] = [ - 'phone' => $arr["client_phone"] ?? null, // phone, - 'id' => $arr["id"], // id, - 'store_id' => $store_id, // store_id, - 'store_id_1c' => $arr["store_id"], // store_id_1c, - 'seller_id' => $arr["seller_id"], // seller_id, - 'admin_id' => $admin_id, // admin_id, - 'operation' => $arr["type"], // operation, - 'number' => $arr["number"], // number, - 'date' => $arr["date"], // date, - 'summ' => $arr["summ"], // summ, - 'purchase_sum' => $purchaseItemsSum ?? 0, // purchase_sum, - 'status' => $arr["status"], // status, - 'sales_check' => $arr["sales_check"] ?? '', // sales_check, - 'payments' => json_encode($arr["payments"], JSON_UNESCAPED_UNICODE), // payments, - 'pay_arr' => implode(",", $pay_arr), // pay_arr, - 'order_id' => trim($arr["order_id"]), // order_id, - 'terminal' => $arr["terminal"] ?? '', // terminal, - 'kkm_id' => $arr["kkm_id"] ?? '', // terminal, - 'terminal_id' => $arr["terminal_id"] ?? '', // terminal_id, - 'skidka' => $arr["discount"] ?? 0, // skidka - 'date_up' => $date_up, // date_up - 'held' => 0, - ]; + foreach ($result["checks"] as $arr) { - } + $check_id = $arr["id"]; + if ($arr["seller_id"] == '00000000-0000-0000-0000-000000000000') { + $arr["seller_id"] = "NULL"; + } - $result = []; + $pay_arr = $this->getPayArr($arr["payments"]); - $updateSalesMain = [ - 'deleteSales' => $checksIds, -// 'setSalesUpdate' => $checksValues, - //'setSalesProductsUpdate' => $salesProducts, -// 'setSalesProductsComponentsUpdate' => $salesProductsComponents, - ]; + $store_id = ClientHelper::getExportId($arr["store_id"], "city_store", 1); +// $admin_id = ClientHelper::getExportId($arr["seller_id"], "admin", 1); + $exportImportTable = ExportImportTable::find()->select(['entity_id'])->where(['entity' => 'admin']) + ->andWhere(['export_id' => 1])->andWhere(['export_val' => $arr["seller_id"]])->all(); + $exportImportTableIds = ArrayHelper::getColumn($exportImportTable, 'entity_id'); + $admin = Admin::find()->where(['in', 'id', $exportImportTableIds])->andWhere(['>', 'group_id', 0])->one(); + $admin_id = $admin->id ?? 0; - $result = array_merge($result, $updateSalesMain); + //удаляем чеки и товары в чеках + $saleUpdate = SalesUpdate::find()->where(['id' => $arr["id"]])->one(); + if ($saleUpdate) { + $saleUpdate->delete(); + } +// SalesProductsUpdate::deleteAll(['check_id' => $arr["id"]]); - if ($update) { - $updateSalesPart = [ - 'setSales' => $checksValues, - 'setSalesProducts' => $salesProducts, - 'setSalesProductsComponents' => $salesProductsComponents, -// 'setSalesItems' => $salesItems, - ]; - $result = array_merge($result, $updateSalesPart); - } + if ($update) { + $sales = Sales::find()->where(['id' => $arr["id"]])->one(); + if ($sales) { + $sales->delete(); + } + SalesItems::deleteAll(['check_id' => $arr["id"]]); + SalesProducts::deleteAll(['check_id' => $arr["id"]]); + } - return $result; - } + // проверяем стутс чека - вносим только Архивные и пробитые +// if (!empty($arr["status"])) { +// $salesUpdate = new SalesUpdate; +// $salesUpdate->phone = empty($arr["client_phone"]) ? 0 : (int)$arr["client_phone"]; +// $salesUpdate->id = $arr["id"]; +// $salesUpdate->store_id = $store_id; +// $salesUpdate->store_id_1c = $arr["store_id"]; +// $salesUpdate->seller_id = $arr["seller_id"]; +// $salesUpdate->admin_id = $admin_id; +// $salesUpdate->operation = $arr["type"]; +// $salesUpdate->number = $arr["number"]; +// $salesUpdate->date = $arr["date"]; +// $salesUpdate->summ = $arr["summ"]; +// $salesUpdate->status = $arr["status"]; +// $salesUpdate->sales_check = $arr["sales_check"] ?? 'NULL'; +// $salesUpdate->payments = json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); +// $salesUpdate->pay_arr = implode(",", $pay_arr); +// $salesUpdate->order_id = $arr["order_id"] ?? ''; +// $salesUpdate->terminal = $arr["terminal"] ?? 'NULL'; +// $salesUpdate->terminal_id = $arr["terminal_id"] ?? 'NULL'; +// $salesUpdate->date_up = date('Y-m-d H:i:s'); +// $salesUpdate->skidka = $arr["discount"] ?? 0; +// $salesUpdate->kkm_id = $arr["kkm_id"] ?? ''; // Пустая строка по умолчанию не может быть +// $salesUpdate->held = 0; // ??? +// $salesUpdate->save(); +// if ($salesUpdate->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 18, "error" => $salesUpdate->getErrors()], JSON_UNESCAPED_UNICODE)); +// } - private function getEntityByType($entity = 'city_store') - { - return ExportImportTable::find()->select(['entity_id', 'export_val'])->where(['entity' => $entity]) - ->andWhere(['export_id' => 1])->andWhere(['!=', 'export_val', ''])->asArray()->all(); - } +// $amount = 0; +//// $items_arr = []; +// foreach ($arr["items"] as $itemid => $arr2) { +// if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { +// $arr2["seller_id"] = "NULL"; +// } +// $saleProductsUpdate = new SalesProductsUpdate; +// $saleProductsUpdate->type_id = 1; +// $saleProductsUpdate->check_id = $check_id; +// $saleProductsUpdate->product_id = $arr2["product_id"]; +// $saleProductsUpdate->seller_id = $arr2["seller_id"]; +// $saleProductsUpdate->quantity = $arr2["quantity"]; +// $saleProductsUpdate->price = $arr2["price"]; +// $saleProductsUpdate->summ = $arr2["summ"]; +// $saleProductsUpdate->discount = $arr2["discount"]; +// $saleProductsUpdate->color = $arr2["color"] ?? ''; // ??? +// $saleProductsUpdate->component_parent_id = ''; // ??? +// $saleProductsUpdate->save(); +// if ($saleProductsUpdate->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 19, "error" => $saleProductsUpdate->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// if (!empty($arr2["components"])) { +// foreach ($arr2["components"] as $compID => $comp) { +// $saleProductsUpdate2 = new SalesProductsUpdate; +// $saleProductsUpdate2->type_id = 3; +// $saleProductsUpdate2->check_id = $check_id; +// $saleProductsUpdate2->product_id = $comp["product_id"]; +// $saleProductsUpdate2->seller_id = $arr2["seller_id"]; +// $saleProductsUpdate2->quantity = $comp["quantity"]; +// $saleProductsUpdate2->color = $comp["color"]; +// $saleProductsUpdate2->component_parent_id = $arr2["product_id"]; +// $saleProductsUpdate2->save(); +// if ($saleProductsUpdate2->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 20, "error" => $saleProductsUpdate2->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// } +// } - private function deleteSales($ids, $update) - { - if (!empty($ids)) { - SalesUpdate::deleteAll(['in', 'id', $ids]); -// SalesProductsUpdate::deleteAll(['in', 'check_id', $ids]); - if ($update) { - Sales::deleteAll(['in', 'id', $ids]); - SalesItems::deleteAll(['in', 'check_id', $ids]); - SalesProducts::deleteAll(['in', 'check_id', $ids]); - } - } - } + if ($update) { + $sales2 = new Sales; + $sales2->phone = $arr["client_phone"] ?? 0; + $sales2->id = $arr["id"]; + $sales2->store_id = $store_id; + $sales2->store_id_1c = $arr["store_id"]; + $sales2->seller_id = $arr["seller_id"]; + $sales2->admin_id = $admin_id; + $sales2->operation = $arr["type"]; + $sales2->number = $arr["number"]; + $sales2->date = $arr["date"]; + $sales2->summ = $arr["summ"]; + $sales2->status = $arr["status"]; + $sales2->sales_check = $arr["sales_check"] ?? ''; + $sales2->payments = json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); + $sales2->pay_arr = implode(",", $pay_arr); + $sales2->order_id = trim($arr["order_id"] ?? ''); + $sales2->terminal = $arr["terminal"] ?? ''; + $sales2->terminal_id = $arr["terminal_id"] ?? ''; + $sales2->date_up = date('Y-m-d H:i:s'); + $sales2->skidka = $arr["discount"] ?? '0'; + $sales2->delivery_date = date('Y-m-d', strtotime($arr['delivery_date'] ?? '')); + $sales2->pickup = $arr['pickup'] ?? false; + $sales2->save(); + if ($sales2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 21, "error" => $sales2->getErrors()], JSON_UNESCAPED_UNICODE)); + } - private function setSales($values) - { - $columns = [ - 'phone', - 'id', - 'store_id', - 'store_id_1c', - 'seller_id', - 'admin_id', - 'operation', - 'number', - 'date', - 'summ', - 'purchase_sum', - 'status', - 'sales_check', - 'payments', - 'pay_arr', - 'order_id', - 'terminal', - 'kkm_id', - 'terminal_id', - 'skidka', - 'date_up', - 'held', - ]; + // Обновляем данные в очереди на создание чеков + CreateChecks::updateAll(['status' => 1], ['check_id' => $arr["id"]]); - $this->insertDataSales($values, 'sales', $columns); - } + // позиции в чеке + $amount = 0; +// $items_arr = []; + $productsInfos = []; + foreach ($arr["items"] as $itemid => $arr2) { + if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { + $arr2["seller_id"] = null; + } + $saleProducts = new SalesProducts; + $saleProducts->type_id = 1; + $saleProducts->check_id = $check_id; + $saleProducts->product_id = $arr2["product_id"]; + $saleProducts->seller_id = $arr2["seller_id"]; + $saleProducts->quantity = $arr2["quantity"]; + $saleProducts->price = $arr2["price"]; + $saleProducts->summ = $arr2["summ"]; + $saleProducts->discount = $arr2["discount"]; + $saleProducts->color = $arr2["color"]; + $saleProducts->assemble_id = !empty($arr2["assemble_id"]) && $arr2["assemble_id"] != '00000000-0000-0000-0000-000000000000' ? $arr2["assemble_id"] : null; + $saleProducts->save(); + if ($saleProducts->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 22, "error" => $saleProducts->getErrors()], JSON_UNESCAPED_UNICODE)); + } + $assemble = Assemblies::find()->where(['guid' => $saleProducts->assemble_id])->one(); + if ($assemble) { + if (in_array($saleProducts->product_id, $matrixProductsIds)) { + $productsInfos[$assemble->id] = ($productsInfos[$assemble->id] ?? 0) + $saleProducts->summ; + } + $assemble->date_close = $sales2->date; + $assemble->check_id = $sales2->id; + if ($arr["type"] == 'Продажа') { + $assemble->status_id = 1; + } elseif ($arr["type"] == 'Возврат') { + $assemble->status_id = 2; + $assemble->with_return = 1; + } + $assemble->save(); + if ($assemble->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 22.2, "error" => $assemble->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } - private function setSalesProducts($values) - { - $columns = [ - 'type_id', - 'check_id', - 'product_id', - 'seller_id', - 'quantity', - 'price', - 'summ', - 'purchase_price', - 'purchase_sum', - 'discount', - 'color' - ]; + if (!empty($arr2["components"])) { + foreach ($arr2["components"] as $compID => $comp) { + $saleProducts2 = new SalesProducts; + $saleProducts2->type_id = 3; + $saleProducts2->check_id = $check_id; + $saleProducts2->product_id = $comp["product_id"]; + $saleProducts2->seller_id = $arr2["seller_id"]; + $saleProducts2->quantity = $comp["quantity"]; + $saleProducts2->color = $comp["color"]; + $saleProducts2->component_parent_id = $arr2["product_id"]; + $saleProducts2->price = 0; // ??? + $saleProducts2->discount = 0; // ??? + $saleProducts2->summ = 0; // ??? + $saleProducts2->save(); + if ($saleProducts2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 23, "error" => $saleProducts2->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } +// $salesItems = new SalesItems; +// $salesItems->lid_id = empty($arr["order_id"]) ? 0 : $arr["order_id"]; +// $salesItems->check_id = $check_id; +// $salesItems->phone = $arr["client_phone"] ?? 0; +// $salesItems->id_1c = $arr2["product_id"]; +// $salesItems->seller_id = $arr2["seller_id"]; +// $salesItems->kol = $arr2["quantity"]; +// $salesItems->color_id = $arr2["color_id"] ?? 0; +// $salesItems->summa = $arr2["summ"]; +// $salesItems->date = date('Y-m-d H:i:s'); +// $salesItems->skidka = $arr2["discount"]; +// $salesItems->store_id = 0; // ??? +// $salesItems->store_id_1c = ''; // ??? +// $salesItems->admin_id = 0; // ??? +// $salesItems->item_id = 0; // ??? +// $salesItems->complect_id = 0; // ??? +// $salesItems->name = ''; // ??? +// $salesItems->referal_id = 0; // ??? +// $salesItems->vozvrat = 0; // ??? +// $salesItems->save(); +// if ($salesItems->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 24, "error" => $salesItems->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// $amount = $amount + $arr2["price"] * $arr2["quantity"]; +// $items_arr[] = ["product_id" => $arr2["product_id"], "seller_id" => $arr2["seller_id"], "quantity" => $arr2["quantity"], "summ" => $arr2["summ"], "discount" => $arr2["discount"]]; + } + foreach ($productsInfos as $assemble_id => $summ) { + Assemblies::updateAll(['summ_matrix' => $summ], ['id' => $assemble_id]); + } + } + } + } elseif (!empty($result['checks'])) { + file_put_contents(self::OUT_DIR . '/error_upload.txt', + PHP_EOL . "elseif", FILE_APPEND); + $dataArrayValues = $this->getSalesDate($result["checks"], $update); - $this->insertDataSales($values, 'sales_products', $columns); - } + foreach ($dataArrayValues as $keyMethodName => $rowValue) { + file_put_contents(self::OUT_DIR . '/error_upload.txt', + PHP_EOL . $keyMethodName, FILE_APPEND); + try { + $this->$keyMethodName($rowValue, $update); + } catch (Exception $e) { + $errorString = substr($e->getMessage(), 0, 2000); + InfoLogService::setInfoLog(__FILE__, __LINE__, $errorString, 'error_id_25_m_st'); + } + } + } - private function setSalesProductsComponents($values) - { - $columns = [ - 'type_id', - 'check_id', - 'product_id', - 'seller_id', - 'quantity', - 'color', - 'component_parent_id', - 'price', - 'discount', - 'summ', - ]; + if (!empty($result['balances'])) { + foreach ($result["balances"] as $std => $arr) { + Balances::deleteAll(['store_id' => $std]); + foreach ($arr as $pid => $arr2) { + $balances = new Balances; + $balances->store_id = $std; + $balances->product_id = $pid; + $balances->quantity = $arr2[0]; + $balances->reserv = $arr2[1]; + $balances->save(); + if ($balances->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 26, "error" => $balances->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } + } - $this->insertDataSales($values, 'sales_products', $columns); - } + if (!empty($result['prices'])) { + foreach ($result["prices"] as $idp => $price) { + if ( + !empty($price) + && + in_array( + $type_price, + array_keys(Prices::REGION_TYPE_PRICES) + ) + ) { + $region_id = Prices::REGION_TYPE_PRICES[$type_price]; + Prices::deleteAll(['product_id' => $idp]); + $price1 = new Prices; + $price1->product_id = $idp; + $price1->price = $price; + $price1->save(); + if ($price1->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 27, "error" => $price1->getErrors()], JSON_UNESCAPED_UNICODE)); + } + PricesRegion::deleteAll(['product_id' => $idp, 'region_id' => $region_id]); + $priceRegion = new PricesRegion; + $priceRegion->product_id = $idp; + $priceRegion->region_id = $region_id; + $priceRegion->price = $price; + $priceRegion->save(); + if ($priceRegion->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 27.5, "error" => $priceRegion->getErrors()], JSON_UNESCAPED_UNICODE)); + } + try { + $pricesDynamic = PricesDynamic::find()->where(['product_id' => $idp, 'region_id' => $region_id])->andWhere(['active' => '1'])->orderBy(['id' => SORT_DESC])->one(); + $price = round($price, 2); + // если нет записи или цена изменилась то вносим запись в БД + if ($pricesDynamic and $pricesDynamic->price != $price) { + $pricesDynamic->active = 0; + $pricesDynamic->date_to = date('Y-m-d H:i:s'); + $pricesDynamic->save(); + if ($pricesDynamic->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 28, "error" => $pricesDynamic->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + if (!$pricesDynamic or ($pricesDynamic and ($pricesDynamic->price != $price || $pricesDynamic->region_id != $region_id))) { + $pricesDynamic2 = new PricesDynamic; + $pricesDynamic2->product_id = $idp; + $pricesDynamic2->price = $price; + $pricesDynamic2->date_from = date('Y-m-d H:i:s'); + $pricesDynamic2->date_to = '2100-01-01 00:00:00'; + $pricesDynamic2->active = 1; + $pricesDynamic2->region_id = $region_id; + $pricesDynamic2->save(); + if ($pricesDynamic2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 29, "error" => $pricesDynamic2->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } catch (Exception $e) { + file_put_contents(self::OUT_DIR . '/log_prices_dinamics.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage(), FILE_APPEND); + } + } + } + } -// private function setSalesItems($values) { -// $columns = [ -// 'lid_id', -// 'check_id', -// 'phone', -// 'id_1c', -// 'seller_id', -// 'kol', -// 'color_id', -// 'summa', -// 'skidka', -// 'date' -// ]; -// -// $this->insertDataSales($values, 'sales_items', $columns); -// } + if (!empty($result['prices'])) { + foreach ($result["prices"] as $idp => $price) { + if (!empty($price) and $type_price == "Закупочная цена руб.") { + try { + $priceZakup = new PricesZakup; + $priceZakup->product_id = $idp; + $priceZakup->price = $price; + $priceZakup->save(); + if ($priceZakup->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 30, "error" => $priceZakup->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } catch (Exception $e) { + } + } + if (!empty($price) and $type_price == "Себестоимость") { + try { + file_put_contents(self::OUT_DIR . '/price_purchese.txt', PHP_EOL . "$idp=" . $price, FILE_APPEND); + } catch (Exception $e) { + } + } + } + } -// private function setSalesUpdate($values) { -// $columns = [ -// 'phone', -// 'id', -// 'store_id', -// 'store_id_1c', -// 'seller_id', -// 'admin_id', -// 'operation', -// 'number', -// 'date', -// 'summ', -// 'status', -// 'sales_check', -// 'payments', -// 'pay_arr', -// 'order_id', -// 'terminal', -// 'terminal_id', -// 'skidka', -// 'date_up' -// ]; -// -// $this->insertDataSales($values, 'sales_update', $columns); -// } + if (!empty($result['created_checks'])) { + foreach ($result["created_checks"] as $idp => $arr2) { + if (!empty($arr2["error"])) { // Если есть ошибки + // // обновляем GUID на новый +// try { +// $createChecks = CreateChecks::find()->select(['order_id'])->where(['check_id' => $arr2["id"]])->one(); +// if ($createChecks) { +// $lid_id = $createChecks->order_id; +// $guid_new = \yii_app\controllers\crud\UniversalCatalogController::create_guid_my_old("01", $lid_id); +// $createChecks2 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->andWhere(['!=', 'check_id', '0']) +// ->andWhere(['status' => '0'])->andWhere(['held' => '0'])->one(); +// if ($createChecks2) { +// $createChecks2->check_id = $guid_new; +// $createChecks2->save(); +// if ($createChecks2->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 32, "error" => $createChecks2->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } else { +// LogService::apiErrorLog(json_encode(["error_id" => 31, "error" => 'no create_checks with check_id=' . $arr2["id"]], JSON_UNESCAPED_UNICODE)); +// } +// } catch (Exception $e) { +// file_put_contents(self::OUT_DIR . '/log_created_check_error.txt', PHP_EOL . date("d.m.Y H:i:s",time()). $e->getMessage(), FILE_APPEND); +// } -// private function setSalesProductsUpdate($values) { -// $columns = [ -// 'type_id', -// 'check_id', -// 'product_id', -// 'seller_id', -// 'quantity', -// 'price', -// 'summ', -// 'discount', -// 'color' -// ]; -// -// $this->insertDataSales($values, 'sales_products_update', $columns); -// } + $txt = date("d.m.Y H:i:s", time()) . " $idp СОЗДАНИЕ ЧЕКА ОШИБКА id=" . $arr2["id"] . " " . $arr2["error"]; + file_put_contents(self::OUT_DIR . '/log_created_check_error.txt', PHP_EOL . $txt, FILE_APPEND); + } else { // Если ошибок нет + if (/* $arr2["held"] == true and */ !empty($arr2["name"]) and !empty($arr2["id"])) { // Если заполнен name b id +// $createChecksBags = CreateChecksBags::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]])->orderBy(['id' => SORT_DESC])->one(); +// if ($createChecksBags) { +// $createChecksBags->guid = $arr2["guid"]; +// $createChecksBags->name = $arr2["name"]; +// $createChecksBags->held = $arr2["held"]; +// $createChecksBags->status = '1'; +// $createChecksBags->date_up = date('Y-m-d H:I:s'); +// $createChecksBags->save(); +// if ($createChecksBags->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 33, "error" => $createChecksBags->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } + // Обновляем данные в очереди на создание чеков + CreateChecks::updateAll([ + 'status' => 1, + 'guid' => $arr2["id"], + 'date_up' => date('Y-m-d H:i:s'), + 'name' => $arr2["name"], + 'held' => isset($arr2["held"]) ? $arr2["held"] : 0 + ], ['check_id' => $arr2["id"]]); +// $createChecks3 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->orderBy(['id' => SORT_DESC])->one(); +// if ($createChecks3) { +// $createChecks3->guid = $arr2["id"]; +// $createChecks3->name = $arr2["name"]; +// $createChecks3->held = isset($arr2["held"]) ? ($arr2["held"] ? 1 : 0) : 0; +// $createChecks3->status = '1'; +// $createChecks3->date_up = date('Y-m-d H:i:s'); +// $createChecks3->save(); +// if ($createChecks3->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 34, "error" => $createChecks3->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// $createChecks4 = CreateChecks2::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]])->orderBy(['id' => SORT_DESC])->one(); +// if ($createChecks4) { +// $createChecks4->name = $arr2["name"]; +// $createChecks4->held = $arr2["held"]; +// $createChecks4->status = '1'; +// $createChecks4->date_up = date('Y-m-d H:I:s'); +// $createChecks4->save(); +// if ($createChecks4->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 35, "error" => $createChecks4->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// $createChecks5 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]]) +// ->andWhere(['type' => 'Возврат'])->orderBy(['id' => SORT_DESC])->one(); +// if ($createChecks5) { +// $createChecks5->held = $arr2["held"]; +// $createChecks5->status = '1'; +// $createChecks5->date_up = date('Y-m-d H:I:s'); +// $createChecks5->save(); +// if ($createChecks5->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 35, "error" => $createChecks5->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } + // прикрепляем чек к заказу + $ordersAmo = OrdersAmo::find()->where(['id' => $arr2["order_id"]])->one(); + if ($ordersAmo) { + $ordersAmo->check_id_arr = $arr2["id"]; + $ordersAmo->save(false); + if ($ordersAmo->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 36, "error" => $ordersAmo->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } -// private function setSalesProductsComponentsUpdate($values) { -// $columns = [ -// 'type_id', -// 'check_id', -// 'product_id', -// 'seller_id', -// 'quantity', -// 'color', -// 'component_parent_id' -// ]; -// -// $this->insertDataSales($values, 'sales_products_update', $columns); -// } + // обращаемся к старой базе данных базацветов_24 + // ??? + } + } + } + } + if (!empty($result['created_employee'])) { + foreach ($result['created_employee'] as $arr) { + EmployeeOnShift::updateAll(['status_source' => EmployeeOnShift::STATUS_SOURCE_CREATED_IN_1C], ['guid' => $arr['id']]); + } + } - private function setSelfCostUpdate($values) - { - $columns = [ + if (!empty($result['marketplace_orders'])) { + foreach ($result["marketplace_orders"] as $mpOrder) { + $updateResult = self::changeMarketplaceOrderStatusFrom1C($mpOrder); //изменение статусов + if ($updateResult['status'] == 'error') { + LogService::apiErrorLog(json_encode(["error_id" => 40, "error" => $updateResult['message']], JSON_UNESCAPED_UNICODE)); + } + } + } - 'date', - 'store_id', - 'product_guid', - 'price', - 'updated_at' - ]; +// + $mess["request_id"] = "" . time(); + if (!empty($result['created_orders'])) { + $mess['line'][] = __LINE__; + $mess["created_orders"] = $result['created_orders']; + $productsNames = Products1c::getNamesByTip('products'); + foreach ($result['created_orders'] as $arr) { + $marketplaceOrders = null; + $marketplaceOrdersGuidArr = []; + if (!empty($arr["id"])) { + $marketplaceOrders = MarketplaceOrders::find()->where(['guid' => $arr["id"]])->one(); + if ($marketplaceOrders && $marketplaceOrders->guid) { + $marketplaceOrdersGuidArr[] = $marketplaceOrders->guid; + } + } + if (!empty($marketplaceOrders)) { + /** @var MarketplaceOrders $marketplaceOrders */ + $mess['line'][] = __LINE__; + if (!empty($arr["errors"]) || !empty($arr["error"]) || !empty($arr["errors_items"])) { + $errorText = ''; + if (!empty($arr["errors"])) { + //"errors": [ + //{ + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + //"error_json": [ + //{ + //"field": "id", + //"error": "Документ с данным ИД уже записан в системе" + //} + // - $this->insertDataSales($values, 'self_cost_product', $columns, 4000); - } + foreach ($arr["errors"] as $errorRow) { + if (!empty($errorRow['error'])) { + $errorText .= $errorRow['error']; + $errorText .= ' ,' . $errorRow['error_description']; + if (!empty($errorRow['error_json'])) { + foreach ($errorRow['error_json'] as $errorJsonRow) { + $errorText .= ' , поле: ' . $errorJsonRow['field']; + $errorText .= ' , ошибка: ' . $errorJsonRow['error']; + } + } + } - private function insertDataSales($values, $tableName, $columns, $chunks = 1000) + if (!empty($errorRow["errors_items"])) { + foreach ($errorRow["errors_items"] as $errorDopRow) { + //"errors_items": [ + //{ + //"error_dop": "Ошибка проверки количества номенклатуры", + //"field": "quantity", + //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", + //"error": "У данной позиции запрещён ввод дробного значения!" + //}, + // + // + $productName = $errorDopRow['product_id']; - { - $chunkValues = array_chunk($values, $chunks); + if (array_key_exists($errorDopRow['product_id'], $productsNames)) { + $productName = $productsNames[$errorDopRow['product_id']]; + } - foreach ($chunkValues as $key => $rows) { + $errorText .= ' ' . $errorDopRow['error_dop']; + $errorText .= ' , поле: ' . $errorDopRow['field']; + $errorText .= ' , товар: ' . $productName; + $errorText .= ' , ошибка: ' . $errorDopRow['error']; + } + } + } + } - try { - $transaction = \Yii::$app->db->beginTransaction(); - Yii::$app->db->createCommand()->batchInsert($tableName, $columns, $rows)->execute(); - $transaction->commit(); - } catch (Exception $e) { - $errorString = substr($e->getMessage(), 0, 2000); - file_put_contents(self::OUT_DIR . '/error_upload.txt', - PHP_EOL . $errorString, FILE_APPEND - ); - $transaction->rollBack(); - InfoLogService::setInfoLog(__FILE__, __LINE__, $tableName, 'error_id_25'); - InfoLogService::setInfoLog(__FILE__, __LINE__, $errorString, 'error_id_25_22'); - LogService::apiErrorLog(json_encode(["error_id" => 25, "error" => $errorString], JSON_UNESCAPED_UNICODE) - ); - } - } - } + if (!empty($arr["error"])) { + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + $errorText .= $arr["error"]; + $errorText .= ' ,' . $arr['error_description']; + } - private function getMarketplaceStatuses() - { - $marketplaces = [ - MarketplaceOrder1cStatuses::GUID_FLOWWOW => "ФлауВау", - MarketplaceOrder1cStatuses::GUID_YANDEXMARKET => "ЯндексМаркет" - ]; - $data = []; - foreach ($marketplaces as $marketplaceGuid => $marketplaceName) { - $statuses = MarketplaceOrder1cStatuses::find()->where(['marketplace_id' => MarketplaceOrder1cStatuses::guid2id()[$marketplaceGuid]]) - ->orderBy(['posit' => SORT_ASC])->all(); - $statusesData = []; - foreach ($statuses as $status) { - /* @var $status MarketplaceOrder1cStatuses */ - $relftions = $status->relationsFrom; - $relationsToSend = []; - foreach ($relftions as $relation) { - $statusTo = MarketplaceOrder1cStatuses::find()->where(['id' => $relation['status_id_to']])->one(); - if(!$statusTo) { - continue; + $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; + $marketplaceOrders->error_text = $errorText; + $marketplaceOrders->save(); + if ($marketplaceOrders->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + $mess['line'][] = __LINE__; + if (isset($arr["held"]) && $arr["held"]) { + $mess['line'][] = __LINE__; + $marketplaceOrders->number_1c = $arr["number"] ?? ''; + $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_1C; + $marketplaceOrders->save(); + if ($marketplaceOrders->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 42, "error" => $marketplaceOrders->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + } } - $relationsToSend[] = - $statusTo->status_id; } - $statusesData [] = [ - 'index_number' => $status->posit, - 'status_name' => $status->status, - 'allowed_reserve' => $status->allowed_reserve, - 'allowed_closing' => $status->allowed_closing, - 'hint' => $status->status_instruction, - 'status_id' => $status->status_id, - 'allowed_statuses' => $relationsToSend - ]; - } - $data[] = [ - 'id' => $marketplaceGuid, - 'name' => $marketplaceName, - 'statuses' => $statusesData - ]; - } - return $data; - } - public function changeMarketplaceOrderStatusFrom1C($mpOrder) - { - $result = null; - if (!$mpOrder['status']) { - $result['message'] = 'Статус не передан'; - $result['status'] = 'error'; - return $result; - } - // статусы маркетплейса - $statuses = MarketplaceOrderStatusTypes::find() - ->select(['id', 'code']) - ->indexBy('code') - ->asArray() - ->all(); - $cancelledStatusId = $statuses[MarketplaceOrderStatusTypes::CANSELLED_CODE]['id']; - $readyStatusId = $statuses[MarketplaceOrderStatusTypes::READY_CODE]['id']; - $deliveredStatusId = $statuses['DELIVERED']['id']; - $status = $mpOrder['status']; - $marketplaceOrder = MarketplaceOrders::find() - ->where(['guid' => $mpOrder['id']]) - // ->andWhere(['<>', 'status_id', $cancelledStatusId]) - ->one(); + $now = time(); + $sendedOrders = MarketplaceOrders::find() + ->where(['status_1c' => MarketplaceOrders::STATUSES_1C_SENDED_TO_1C]) + ->andWhere(['not in', 'guid', $marketplaceOrdersGuidArr]) + ->all(); + foreach ($sendedOrders as $order) { + $sentAt = strtotime($order->sent_1c_at ?? '2025-07-01 00:00:00'); + $attempts = (int)$order->attempts_number; + if (($now - $sentAt) > 300) { + if ($attempts < 4) { + $order->sent_1c_at = null; + $order->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_ERP; + $order->save(); + } else { + $order->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; + $order->error_text = 'Превышено число попыток отправки в 1С.'; + $order->save(); + + LogService::apiErrorLog(json_encode([ + "error_id" => 43, + "error" => "Превышено число попыток отправки в 1С " . $order->guid, + ], JSON_UNESCAPED_UNICODE)); + } + } + } - if ($marketplaceOrder) { - /** @var $marketplaceOrder MarketplaceOrders */ - $debug = false; - if ($marketplaceOrder->fake == 1) { - $debug = true; } - $marketplaceId = $marketplaceOrder->marketplace_id; - $cancelledStatusesCode = MarketplaceOrder1cStatuses::find() - ->select(['status_id']) - ->where(['marketplace_id' => $marketplaceId]) - ->andWhere(['order_status_id' => $cancelledStatusId]) - ->scalar(); - $statusId1C = MarketplaceOrder1cStatuses::find() - ->where(['marketplace_id' => $marketplaceId]) - ->andWhere(['status_id' => $status]) - ->one(); + if (!empty($result['analysts_business_operations'])) { + $existingOperations = AnalystsBusinessOperations::find() + ->indexBy('id') + ->asArray() + ->all(); + $existingTypes = AnalystsBusinessOperationsTypes::find() + ->indexBy('code') + ->asArray() + ->all(); + foreach ($result["analysts_business_operations"] as $operation) { + if (!in_array($operation['id'], array_keys($existingOperations))) { + $newOperation = new AnalystsBusinessOperations(); + $newOperation->id = $operation['id']; + $newOperation->name = $operation['name']; + $newOperation->type = (int)$operation['type']; + $newOperation->active = 1; + if (!in_array((int)$operation['type'], array_column($existingTypes, 'code'))) { + $newType = new AnalystsBusinessOperationsTypes(); + $newType->code = (int)$operation['type']; + $newType->name = null; + $newType->alias = null; + $newType->created_at = date('Y-m-d H:i:s'); + $newType->created_by = 1409; + if ($newType->save()) { + $newOperation->type_id = $newType->id; + } else { + $newOperation->type_id = null; + Yii::error('Ошибка сохранение типа ' . json_encode($newType->getErrors(), JSON_UNESCAPED_UNICODE), __METHOD__ ); + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.1, "error" => $newType->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + $newOperation->type_id = $existingTypes[$operation['type']]['id']; + } + $newOperation->created_at = date('Y-m-d H:i:s'); + if (!$newOperation->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.2, "error" => $newOperation->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } - if ($marketplaceOrder->status_id === $cancelledStatusId && $status !== $cancelledStatusesCode) { - $result['message'] = 'Заказ отменен ' . $mpOrder['id'];; - $result['status'] = 'cancelled_order'; - return $result; + } else { + if ($existingOperations[$operation['id']]['type'] !== (int)$operation['type']) { + $oldOperation = AnalystsBusinessOperations::findOne($operation['id']); + if (!in_array((int)$operation['type'], array_column($existingTypes, 'code'))) { + $newType = new AnalystsBusinessOperationsTypes(); + $newType->code = (int)$operation['type']; + $newType->name = null; + $newType->alias = null; + $newType->created_at = date('Y-m-d H:i:s'); + $newType->created_by = 1409; + if ($newType->save()) { + $oldOperation->type = (int)$operation['type']; + $oldOperation->type_id = $newType->id; + if (!$oldOperation->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.3, "error" => $oldOperation->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + Yii::error('Ошибка сохранение типа ' . json_encode($newType->getErrors(), JSON_UNESCAPED_UNICODE), __METHOD__ ); + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.4, "error" => $oldOperation->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + $oldOperation->type = (int)$operation['type']; + $oldOperation->type_id = AnalystsBusinessOperationsTypes::find()->where(['code' => (int)$operation['type']])->one()->id; + if (!$oldOperation->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.5, "error" => $oldOperation->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + } + } + + } } + if (!empty($result['cancelled_orders'])) { + foreach ($result['cancelled_orders'] as $arr) { + $marketplaceOrders = null; + $marketplaceOrdersGuidArr = []; - $statuses1cWithCancelledId = ArrayHelper::getColumn(MarketplaceOrder1cStatuses::find() - ->select(['status_id']) - ->where(['order_status_id' => $cancelledStatusId]) - ->asArray() - ->all(), 'status_id'); - $statuses1cToChangeYandexMarketFakeOrderId = ArrayHelper::getColumn(MarketplaceOrder1cStatuses::find() - ->select(['status_id']) - ->where(['order_status_id' => $cancelledStatusId]) - ->orWhere(['order_substatus_id' => $readyStatusId]) - ->andWhere(['marketplace_id' => 2]) - ->asArray() - ->all(), 'status_id'); - $statuses = ArrayHelper::map($statuses, 'code', 'id'); - $statusCodes = array_unique(array_keys($statuses)); + $marketplaceOrders = MarketplaceOrders::find()->where(['guid' => $arr])->one(); + $marketplaceOrdersGuidArr[] = $marketplaceOrders->guid; + if (!empty($marketplaceOrders)) { + /** @var MarketplaceOrders $marketplaceOrders */ - if (empty($statusId1C)) { - $mess["result"] = 'error'; - $mess["message_order"] = "Статус не найден"; - $errorJson = json_encode($mess, JSON_UNESCAPED_UNICODE); - LogService::apiLogs(1, $errorJson); - Yii::error('Ошибка: такого статуса не существует' . $status, __METHOD__); - return $errorJson; - } + if (!empty($arr["errors"]) || !empty($arr["error"]) || !empty($arr["errors_items"])) { + $errorText = ''; + if (!empty($arr["errors"])) { - // Проверяем, если заказ уже имеет статус CANCELLED или DELIVERED, то не меняем статусы - if ($marketplaceOrder->status_id === $cancelledStatusId || $marketplaceOrder->status_id === $deliveredStatusId) { - $result['status'] = 'no_change'; - $result['message'] = 'Заказ уже имеет финальный статус (CANCELLED или DELIVERED) ' . $mpOrder['id']; - return $result; - } - // Получаем статусы МП по статусу 1С - /** @var $status MarketplaceOrderStatusTypes */ - /** @var $substatus MarketplaceOrderStatusTypes */ - $status = $statusId1C->orderStatus; - $substatus = $statusId1C->orderSubstatus; + foreach ($arr["errors"] as $errorRow) { + if (!empty($errorRow['error'])) { + $errorText .= $errorRow['error']; - if ( - in_array($statusId1C->status_id, $statuses1cToChangeYandexMarketFakeOrderId) && - $marketplaceOrder->marketplace_id == MarketplaceStore::YANDEX_WAREHOUSE_ID - ) { - if (!$debug) { - $updateResult = MarketplaceService::updateOrderStatus( - $marketplaceOrder->warehouse_guid, - $marketplaceOrder->marketplace_order_id, - $status->code, - $substatus->code - ); - if (!$updateResult && $marketplaceOrder->fake == 1) { - if ($status->id && $substatus->id) { - $marketplaceOrder->status_id = $status->id; - $marketplaceOrder->substatus_id = $substatus->id; + $errorText .= ' ,' . $errorRow['error_description']; + if (!empty($errorRow['error_json'])) { + foreach ($errorRow['error_json'] as $errorJsonRow) { + $errorText .= ' , поле: ' . $errorJsonRow['field']; + $errorText .= ' , ошибка: ' . $errorJsonRow['error']; + } + } + } + } + } + + if (!empty($arr["error"])) { + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + $errorText .= $arr["error"]; + $errorText .= ' ,' . $arr['error_description']; + } + + $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; + $marketplaceOrders->error_text = $errorText; + $marketplaceOrders->save(); + if ($marketplaceOrders->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + $marketplaceOrders->cancelled_order_sent = MarketplaceOrders::STATUSES_1C_CANCELLED_ORDER_SENT_IN_1C; + $marketplaceOrders->save(); + if ($marketplaceOrders->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } } } } - } else { - if ($status->id && $substatus->id) { - $marketplaceOrder->status_id = $status->id; - $marketplaceOrder->substatus_id = $substatus->id; - } - } - if (in_array($statusId1C->status_id, $statuses1cWithCancelledId)) { - $marketplaceOrder->cancelled_order_source = '1c'; - $marketplaceOrder->cancelled_order_date = date('Y-m-d H:m:s'); - } - $marketplaceOrder->status_processing_1c = $statusId1C->id; - $marketplaceOrder->seller_id = $mpOrder['seller_id'] ?? null; - $marketplaceOrder->number_1c = $mpOrder['number'] ?? null; - if ($marketplaceOrder->save()) { - // Обновляем историю статусов - MarketplaceService::createOrUpdateStatusHistory($marketplaceOrder->id, $status->id, $substatus->id, [ - 'date' => date('Y-m-d H:i:s') - ]); - $result['status'] = 'success'; - $result['message'] = 'Статус обновлен'; - } else { - Yii::error('Ошибка сохранения: ' . Json::encode($marketplaceOrder->getErrors(), JSON_UNESCAPED_UNICODE)); - $result['status'] = 'error'; - $result['message'] = $marketplaceOrder->getErrors(); } - } else { - $result['message'] = 'Заказ не найден ' . $mpOrder['id'];; - $result['status'] = 'not_found'; - } - return $result; + $mess['line'][] = __LINE__; + } catch (Exception $e) { + LogService::apiDataLogs(1, json_encode($mess, JSON_UNESCAPED_UNICODE), $requestIdText); + file_put_contents(self::OUT_DIR . '/log_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage() . " " . $e->getLine(), FILE_APPEND); + Yii::error('Ошибка upload - блок catch '. json_encode($e->getMessage() . " " . $e->getLine(), JSON_UNESCAPED_UNICODE)); + LogService::apiErrorLog(json_encode([ + "error_id" => 45, + "error" => "Ошибка загрузки " . $e->getMessage() . " " . $e->getLine(), + ], JSON_UNESCAPED_UNICODE)); + } finally { + LogService::apiDataLogs(1, json_encode($mess, JSON_UNESCAPED_UNICODE), $requestIdText); + } } } diff --git a/erp24/jobs/SendRequestUploadDataToJob.php b/erp24/jobs/SendRequestUploadDataToJob.php new file mode 100644 index 00000000..9cbf0121 --- /dev/null +++ b/erp24/jobs/SendRequestUploadDataToJob.php @@ -0,0 +1,26 @@ +decodingResult; + + $result = UploadService::processingUpload($request); + + } + + + + +} diff --git a/erp24/services/UploadService.php b/erp24/services/UploadService.php new file mode 100644 index 00000000..1713bb71 --- /dev/null +++ b/erp24/services/UploadService.php @@ -0,0 +1,2337 @@ +select(['json_post'])->where(['request_id' => $requestId])->one(); + if ($apiCron) { + $jsn = json_decode($apiCron->json_post, true, 512, JSON_UNESCAPED_UNICODE); + $start_time = $jsn["checks"]["start_time"] ?? date('Y-m-d 00:00:00', time() - 3 * 86400); + $end_time = $jsn["checks"]["end_time"] ?? date('Y-m-d 00:00:00', time()); + $checks_dell = $jsn["checks_dell"] ?? ""; + $type_price = $jsn["prices"]["type_price"] ?? "Розничная цена"; + + ApiCron::updateAll(['status' => 1, 'date_up' => date('Y-m-d H:i:s')], + ['and', ['status' => 0], ['request_id' => $requestId]]); + +// file_put_contents(self::OUT_DIR . '/request_api_cron.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . "request_id=$requestId $start_time - $end_time ", FILE_APPEND); + } + } + + if (!empty($result['stores'])) { + $products1cByTip = Products1c::find() + ->select(['id', 'tip']) + ->andWhere(['tip' => ['kkms', 'terminals', 'city_store']]) + ->groupBy(['tip', 'id']) + ->asArray() + ->all(); + $products1cByTipMap = []; + foreach ($products1cByTip as $item) { + $products1cByTipMap[$item['tip']][] = $item['id']; + } + $existTerminals = Terminals::find() + ->indexBy('id') + ->asArray() + ->column(); + + foreach ($result['stores'] as $gi => $arr) { + if (!in_array($arr["id"], $products1cByTipMap['city_store'])) { + $products1c = new Products1c; + $products1c->id = $arr["id"]; + $products1c->tip = 'city_store'; + $products1c->name = $arr["name"]; + $products1c->code = $arr["code"]; + $products1c->save(); + if ($products1c->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 2, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + + if ($arr["terminals"]) { + $k = 0; + foreach ($arr["terminals"] as $gi2 => $arr2) { + if (!in_array($arr2['id'], $products1cByTipMap['terminals'])) { + $products1c2 = new Products1c; + $products1c2->id = $arr2['id']; + $products1c2->tip = 'terminals'; + $products1c2->name = $arr2["name"]; + $products1c2->code = $arr2["code"]; + $products1c2->save(); + if ($products1c2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 3, "error" => $products1c2->getErrors()], JSON_UNESCAPED_UNICODE)); + Yii::error(''); + } + } + + if (!in_array($arr2['id'], $existTerminals)) { + $terminal = new Terminals; + $terminal->id = $arr2["id"]; + $terminal->name = $arr2["name"]; + $terminal->code = $arr2["code"]; + $terminal->store_id = $arr["id"]; + $terminal->date = date('Y-m-d H:i:s'); + $terminal->posit = $k; + $terminal->save(); + if ($terminal->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 4, "error" => $terminal->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + $k++; + } + } + + if ($arr['kkms']) { + foreach ($arr["kkms"] as $gi2 => $arr2) { + if (!in_array($arr2['id'], $products1cByTipMap['kkms'])) { + $products1c3 = new Products1c; + $products1c3->id = $arr2["id"]; + $products1c3->tip = 'kkms'; + $products1c3->name = $arr2["name"]; + $products1c3->code = $arr2["code"]; + $products1c3->save(); + if ($products1c3->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 5, "error" => $products1c3->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } + } + } + } + if (!empty($result['self_cost'])) { + $storeMap = []; + + $cityStoreIds = CityStore::find()->select('id')->column(); + + // Получаем соответствия export_val => entity_id из таблицы ExportImportTable + $exportImportRecords = ExportImportTable::find() + ->select(['entity_id', 'export_val']) + ->where(['entity_id' => $cityStoreIds, 'entity' => 'city_store', 'export_id' => 1]) + ->all(); + + // Создаем справочник + foreach ($exportImportRecords as $record) { + $storeMap[$record->export_val] = $record->entity_id; + } + + $values = []; + + foreach ($result['self_cost'] as $selfCost) { + $storeId = $storeMap[$selfCost['store_id']] ?? null; + if (!$storeId) { + continue; + } + + + // Удаляем старые данные + SelfCostProduct::deleteAll(['date' => $selfCost['date'], 'store_id' => $storeId]); + + foreach ($selfCost['items'] as $item) { + $values[] = [ + 'date' => $selfCost['date'], + 'store_id' => $storeId, + 'product_guid' => $item['product_id'], + 'price' => $item['price'], + 'updated_at' => date('Y-m-d H:i:s') + ]; + } + } + + if (!empty($values)) { + self::setSelfCostUpdate($values); + SelfCostProductDinamicService::UpdateResult($values); + } + } + + + if (!empty($result['sellers'])) { + Products1c::deleteAll(['tip' => 'admin']); + + foreach ($result["sellers"] as $gi => $arr) { + EmployeeOnShift::updateAll(['status_source' => EmployeeOnShift::STATUS_SOURCE_CREATED_IN_1C], ['guid' => $arr['id']]); + $products1c4 = new Products1c; + $products1c4->id = $arr["id"]; + $products1c4->tip = 'admin'; + $products1c4->name = $arr["name"]; + $products1c4->code = $arr["code"] ?? ''; + $products1c4->parent_id = $arr["parent_id"] ?? ''; + $products1c4->save(); + if ($products1c4->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 6, "error" => $products1c4->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } + + if (!empty($result["nomenclature"]["groups"])) { + Products1c::deleteAll(['tip' => 'products_group']); + foreach ($result["nomenclature"]["groups"] as $gi => $arr) { + $products1c5 = new Products1c; + $products1c5->id = $arr["id"]; + $products1c5->tip = 'products_group'; + $products1c5->name = $arr["name"]; + $products1c5->code = $arr["code"] ?? ''; + $products1c5->articule = $arr["articule"] ?? ''; + $products1c5->parent_id = $arr["parent_id"] ?? '0'; + $products1c5->save(); + if ($products1c5->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 7, "error" => $products1c5->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } + if (!empty($result["nomenclature"]["elements"])) { +// Products1c::deleteAll(['and', ['tip' => 'products'], ['view' => 0]]); + $bouquets = BouquetComposition::find()->select('guid')->column(); + foreach ($result["nomenclature"]["elements"] as $gi => $arr) { +// if (!empty($arr["name"]) && in_array($arr["name"][0], ['ь', 'Ь', 'ъ', 'Ъ'])) { // Не вносим номенклатуру, помеченную на удаление +// continue; +// } + $components = !empty($arr["components"]) ? json_encode($arr["components"], JSON_UNESCAPED_UNICODE) : ""; // Пустые компоненты не надо разворачивать в json объект + $products1c6 = Products1c::find()->where(['id' => $arr["id"]])->one(); + if (!$products1c6) { + $products1c6 = new Products1c; + $products1c6->id = $arr["id"]; + $products1c6->tip = 'products'; + } + $products1c6->name = $arr["name"]; + $products1c6->code = $arr["code"]; + $products1c6->type = $arr["type"]; + $products1c6->articule = $arr["articule"]; + $products1c6->parent_id = $arr["parent_id"]; + $products1c6->view = $arr["view"]; + $products1c6->components = $components; + $products1c6->save(); + if ($products1c6->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 8, "error" => $products1c6->getErrors()], JSON_UNESCAPED_UNICODE)); + } + + if(!empty($arr["components"])) { + if(!in_array($arr["id"], $bouquets)) { + $newBouquetComp = new BouquetComposition(); + $newBouquetComp->guid = $arr["id"]; + $newBouquetComp->name = $arr["name"]; + $newBouquetComp->status = 1; + $newBouquetComp->matrix_type_id = 1; + $newBouquetComp->created_by = Admin::getAdminAgentId() ?: null; + if(!$newBouquetComp->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.1, "error" => $newBouquetComp->getErrors()], JSON_UNESCAPED_UNICODE)); + } else { + foreach ($arr["components"] as $guid => $quantity) { + $newBouquetCompProd = new BouquetCompositionProducts(); + $newBouquetCompProd->bouquet_id = $newBouquetComp->id; + $newBouquetCompProd->product_guid = $guid; + $newBouquetCompProd->count = $quantity; + $newBouquetCompProd->created_by = Admin::getAdminAgentId() ?: null; + if(!$newBouquetCompProd->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.2, "error" => $newBouquetCompProd->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } +// $costModels = []; +// foreach (BouquetComposition::getRegions() as $region_id) { +// $costModels[$region_id] = $newBouquetComp->getCostModel($region_id, array_keys($arr["components"]), true); +// } +// if(empty($costModels)) { +// LogService::apiErrorLog(json_encode(["error_id" => 8.3, "error" => "Стоимость и цена не подсчитаны"], JSON_UNESCAPED_UNICODE)); +// } +// $bouquetTypeHistory = new BouquetCompositionMatrixTypeHistory(); +// $bouquetTypeHistory->bouquet_id = $newBouquetComp->id; +// $bouquetTypeHistory->matrix_type_id = 1; +// $bouquetTypeHistory->created_by = Admin::getAdminAgentId() ?: null; +// $bouquetTypeHistory->is_active = 1; +// $bouquetTypeHistory->date_from = date('Y-m-d H:i:s'); +// if(!$bouquetTypeHistory->save()) { +// LogService::apiErrorLog(json_encode(["error_id" => 8.4, "error" => $bouquetTypeHistory->getErrors()], JSON_UNESCAPED_UNICODE)); +// } + } + } + } + + foreach ($arr as $key => $property) { + if (!in_array($key, Products1c::PRODUCT1C_FIELDS)) { + if (empty($property)) continue; + $propertyType = Products1cPropType::findOne(['id' => $key]); + if (!$propertyType) { + $propertyType = new Products1cPropType(); + $propertyType->id = $key; + $propertyType->name = $key; + if (!$propertyType->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.1, + "error" => $propertyType->getErrors()], + JSON_UNESCAPED_UNICODE)); + continue; + } + } + $additionalCharacteristic = Products1cAdditionalCharacteristics::findOne([ + 'product_id' => $arr["id"], + 'property_id' => $key + ]); + if (!$additionalCharacteristic && !empty($property)) { + $additionalCharacteristic = new Products1cAdditionalCharacteristics(); + $additionalCharacteristic->product_id = $arr["id"]; + $additionalCharacteristic->property_id = $key; + } + $additionalCharacteristic->value = $property; + if (!$additionalCharacteristic->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.2, + "error" => $additionalCharacteristic->getErrors()], + JSON_UNESCAPED_UNICODE)); + } + } + } + + if (!empty($arr["AdditionCharacteristics"])) { + $passedCharacteristics = array_column($arr["AdditionCharacteristics"], null, "id"); + $currentCharacteristics = Products1cAdditionalCharacteristics::find() + ->where(['product_id' => $arr["id"]]) + ->indexBy('property_id') + ->all(); + + foreach ($currentCharacteristics as $propertyId => $currentCharacteristic) { + if (!isset($passedCharacteristics[$propertyId])) { + if (!$currentCharacteristic->delete()) { + LogService::apiErrorLog(json_encode([ + "error_id" => 8.39, + "error" => $currentCharacteristic->getErrors() + ], JSON_UNESCAPED_UNICODE)); + } + } + } + + foreach ($arr["AdditionCharacteristics"] as $characteristic) { + $propertyType = Products1cPropType::findOne(['id' => $characteristic["id"]]); + if (!$propertyType) { + $propertyType = new Products1cPropType(); + $propertyType->id = $characteristic["id"]; + $propertyType->name = $characteristic["name"]; + if (!$propertyType->save()) { + LogService::apiErrorLog(json_encode(["error_id" => 8.1, + "error" => $propertyType->getErrors()], + JSON_UNESCAPED_UNICODE)); + continue; + } + } + + $additionalCharacteristic = Products1cAdditionalCharacteristics::findOne([ + 'product_id' => $arr["id"], + 'property_id' => $characteristic["id"] + ]); + + if (!$additionalCharacteristic) { + $additionalCharacteristic = new Products1cAdditionalCharacteristics(); + $additionalCharacteristic->product_id = $arr["id"]; + $additionalCharacteristic->property_id = $characteristic["id"]; + } + + $additionalCharacteristic->value = $characteristic["value_name"]; + if (!$additionalCharacteristic->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 8.2, "error" => $additionalCharacteristic->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + } + if ( + !empty($arr["type"]) + && str_starts_with($arr["type"], '[') + && str_ends_with($arr["type"], ']') + ) { + // return [$arr["type"]]; + $product1cNomenclature = Products1cNomenclature::find()->where(['id' => $arr["id"]])->one(); + if (!$product1cNomenclature) { + $product1cNomenclature = new Products1cNomenclature(); + $product1cNomenclature->id = $arr["id"]; + } + $typeNomenclature = rtrim(ltrim($arr["type"], '['), ']'); + $typeArr = explode("/", $typeNomenclature); + $category = $typeArr[0]; + $subcategory = $typeArr[1] ?? null; + $product1cNomenclature->name = $arr["name"]; + $product1cNomenclature->location = $arr["type"]; + $product1cNomenclature->type_num = $typeNomenclature; + $product1cNomenclature->category = $category; + $product1cNomenclature->subcategory = $subcategory; + $characteristics = Products1cAdditionalCharacteristics::find() + ->select(['property_id', 'value']) + ->where(['product_id' => $arr["id"]]) + ->indexBy(['property_id']) + ->asArray() + ->all(); + + $propTypes = array_keys($characteristics); + $propertyNames = Products1cPropType::find() + ->select(['id','name']) + ->where(['id' => $propTypes]) + ->indexBy('id') + ->asArray() + ->all(); + $characteristicsValues = []; + + foreach ($propertyNames as $propertyId => $property) { + if (isset($characteristics[$propertyId])) { + $characteristicsValues[$property['name']] = $characteristics[$propertyId]['value']; + } + } + + $sizeValue = 0; + if (isset($characteristicsValues['size']) && intval($characteristicsValues['size'])) { + $sizeValue = intval($characteristicsValues['size']); + } + if (isset($characteristicsValues['размер']) && intval($characteristicsValues['размер'])) { + $sizeValue = intval($characteristicsValues['размер']); + } + + $speciesValue = null; + if (isset($characteristicsValues['species']) && !empty($characteristicsValues['species'])) { + $speciesValue = $characteristicsValues['species']; + } + if (isset($characteristicsValues['вид']) && !empty($characteristicsValues['вид'])) { + $speciesValue = $characteristicsValues['вид']; + } + + $sortValue = null; + if (isset($characteristicsValues['sort']) && !empty($characteristicsValues['sort'])) { + $sortValue = $characteristicsValues['sort']; + } + if (isset($characteristicsValues['сорт']) && !empty($characteristicsValues['сорт'])) { + $sortValue = $characteristicsValues['сорт']; + } + + $typeValue = null; + if (isset($characteristicsValues['type']) && !empty($characteristicsValues['type'])) { + $typeValue = $characteristicsValues['type']; + } + if (isset($characteristicsValues['тип']) && !empty($characteristicsValues['тип'])) { + $typeValue = $characteristicsValues['тип']; + } + + $measureValue = null; + if (isset($characteristicsValues['measure']) && !empty($characteristicsValues['measure'])) { + $measureValue = $characteristicsValues['measure']; + } + + $colorValue = null; + if (isset($characteristicsValues['color']) && !empty($characteristicsValues['color'])) { + $colorValue = $characteristicsValues['color']; + } + if (isset($characteristicsValues['цвет']) && !empty($characteristicsValues['цвет'])) { + $colorValue = $characteristicsValues['цвет']; + } + + $product1cNomenclature->species = $speciesValue; + $product1cNomenclature->sort = $sortValue; + $product1cNomenclature->type = $typeValue; + $product1cNomenclature->size = $sizeValue; + $product1cNomenclature->measure = $measureValue; + $product1cNomenclature->color = $colorValue; + + if (!$product1cNomenclature->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 8.3, "error" => $product1cNomenclature->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + } + } + + if (!empty($result['payment_types'])) { + foreach ($result["payment_types"] as $gi => $arr) { + $paymentTypes = PaymentTypes::findOne(['id' => $arr['id']]) ?? new PaymentTypes(); + $paymentTypes->id = $arr['id']; + $paymentTypes->code = $arr['code']; + $paymentTypes->name = $arr['name']; + $paymentTypes->save(); + if ($paymentTypes->getErrors()) { + LogService::apiErrorLog(json_encode( + ["error_id" => 9, + "error" => $paymentTypes->getErrors()], + JSON_UNESCAPED_UNICODE + )); + } + + $products1c7 = Products1c::findOne(['id' => $arr["id"]]) ?? new Products1c(); + $products1c7->id = $arr["id"]; + $products1c7->tip = 'payment_types'; + $products1c7->name = $arr["name"]; + $products1c7->code = $arr["code"]; + $products1c7->save(); + if ($products1c7->getErrors()) { + LogService::apiErrorLog(json_encode( + ["error_id" => 10, "error" => $products1c7->getErrors()], + JSON_UNESCAPED_UNICODE + )); + } + } + } + + if (!empty($result['created_write_offs'])) { + $productsNames = Products1c::getNamesByTip('products'); + + file_put_contents( + self::OUT_DIR . '/created_write_offs_upload_' + . date("Y_m_d") . '.json', + PHP_EOL + . json_encode($result["created_write_offs"], JSON_UNESCAPED_UNICODE), + FILE_APPEND + ); + foreach ($result["created_write_offs"] as $arr) { + if (!empty($arr["id"])) { + $writeOffsErp = WriteOffsErp::find()->where(['guid' => $arr["id"]])->one(); + if (empty($writeOffsErp)) { + $waybillWriteOffsErp = WaybillWriteOffs::find()->where(['guid' => $arr["id"]])->one(); + } + } + + if (!empty($writeOffsErp) || !empty($waybillWriteOffsErp)) { + if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { + $errorText = ''; + if (!empty($arr["errors"])) { + //"errors": [ + //{ + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + //"error_json": [ + //{ + //"field": "id", + //"error": "Документ с данным ИД уже записан в системе" + //} + // + + foreach ($arr["errors"] as $errorRow) { + if (!empty($errorRow['error'])) { + $errorText .= $errorRow['error']; + + $errorText .= ' ,' . $errorRow['error_description']; + if (!empty($errorRow['error_json'])) { + foreach ($errorRow['error_json'] as $errorJsonRow) { + $errorText .= ' , поле: ' . $errorJsonRow['field']; + $errorText .= ' , ошибка: ' . $errorJsonRow['error']; + } + } + } + + if (!empty($errorRow["errors_items"])) { + foreach ($errorRow["errors_items"] as $errorDopRow) { + //"errors_items": [ + //{ + //"error_dop": "Ошибка проверки количества номенклатуры", + //"field": "quantity", + //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", + //"error": "У данной позиции запрещён ввод дробного значения!" + //}, + // + // + $productName = $errorDopRow['product_id']; + + if (array_key_exists($errorDopRow['product_id'], $productsNames)) { + $productName = $productsNames[$errorDopRow['product_id']]; + } + + $errorText .= ' ' . $errorDopRow['error_dop']; + $errorText .= ' , поле: ' . $errorDopRow['field']; + $errorText .= ' , товар: ' . $productName; + $errorText .= ' , ошибка: ' . $errorDopRow['error']; + } + } + } + } + if (!empty($writeOffsErp)) { + /** @var WriteOffsErp $writeOffsErp */ + $writeOffsErp->status = WriteOffsErp::STATUS_ERROR_1C; + $writeOffsErp->error_text = $errorText; + $writeOffsErp->save(); + if ($writeOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 11.1, "error" => $writeOffsErp->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + if (!empty($waybillWriteOffsErp)) { + /** @var WaybillWriteOffs $waybillWriteOffsErp */ + $waybillWriteOffsErp->status = WriteOffsErp::STATUS_ERROR_1C; + $waybillWriteOffsErp->error_text = $errorText; + $waybillWriteOffsErp->save(); + if ($waybillWriteOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 11.2, "error" => $waybillWriteOffsErp->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + + } else { + if (!empty($writeOffsErp)) { + /** @var WriteOffsErp $writeOffsErp */ + $writeOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; + $writeOffsErp->number_1c = $arr["number"] ?? ''; + $writeOffsErp->save(); + if ($writeOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode( + [ + "error_id" => 11.3, + "error" => $writeOffsErp->getErrors() + ], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + if (!empty($waybillWriteOffsErp) && isset($arr["held"]) && $arr["held"]) { + /** @var WaybillWriteOffs $waybillWriteOffsErp */ + $waybillWriteOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; + $waybillWriteOffsErp->name_1c = $arr["name"] ?? ''; + $waybillWriteOffsErp->save(); + if ($waybillWriteOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode( + [ + "error_id" => 11.4, + "error" => $waybillWriteOffsErp->getErrors() + ], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + + } + } + } + } + + if (!empty($result['created_write_ons'])) { + $productsNames = Products1c::getNamesByTip('products'); + file_put_contents( + self::OUT_DIR . '/created_write_ons_upload_' + . date("Y_m_d") . '.json', + PHP_EOL + . json_encode($result["created_write_ons"], JSON_UNESCAPED_UNICODE), + FILE_APPEND + ); + foreach ($result["created_write_ons"] as $arr) { + if (!empty($arr["id"])) { + $waybillIncoming = WaybillIncoming::find()->where(['guid' => $arr["id"]])->one(); + } + + if (!empty($waybillIncoming)) { + if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { + $errorText = ''; + if (!empty($arr["errors"])) { + //"errors": [ + //{ + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + //"error_json": [ + //{ + //"field": "id", + //"error": "Документ с данным ИД уже записан в системе" + //} + // + + foreach ($arr["errors"] as $errorRow) { + if (!empty($errorRow['error'])) { + $errorText .= $errorRow['error']; + + $errorText .= ' ,' . $errorRow['error_description']; + if (!empty($errorRow['error_json'])) { + foreach ($errorRow['error_json'] as $errorJsonRow) { + $errorText .= ' , поле: ' . $errorJsonRow['field']; + $errorText .= ' , ошибка: ' . $errorJsonRow['error']; + } + } + } + + if (!empty($errorRow["errors_items"])) { + foreach ($errorRow["errors_items"] as $errorDopRow) { + //"errors_items": [ + //{ + //"error_dop": "Ошибка проверки количества номенклатуры", + //"field": "quantity", + //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", + //"error": "У данной позиции запрещён ввод дробного значения!" + //}, + // + // + $productName = $errorDopRow['product_id']; + + if (array_key_exists($errorDopRow['product_id'], $productsNames)) { + $productName = $productsNames[$errorDopRow['product_id']]; + } + + $errorText .= ' ' . $errorDopRow['error_dop']; + $errorText .= ' , поле: ' . $errorDopRow['field']; + $errorText .= ' , товар: ' . $productName; + $errorText .= ' , ошибка: ' . $errorDopRow['error']; + } + } + } + } + + /** @var WaybillIncoming $waybillIncoming */ + $waybillIncoming->status = WriteOffsErp::STATUS_ERROR_1C; + $waybillIncoming->error_text = $errorText; + $waybillIncoming->save(); + if ($waybillIncoming->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 11.5, "error" => $waybillIncoming->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + if (isset($arr["held"]) && $arr["held"]) { + /** @var WaybillIncoming $waybillIncoming */ + $waybillIncoming->status = WriteOffsErp::STATUS_CREATED_1C; + $waybillIncoming->number_1c = $arr["name"] ?? ''; + $waybillIncoming->save(); + if ($waybillIncoming->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 11.55, "error" => $waybillIncoming->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + } + } + } + } + + if (!empty($result['created_resortings'])) { + $productsNames = Products1c::getNamesByTip('products'); + file_put_contents( + self::OUT_DIR . '/created_resortings_upload_' + . date("Y_m_d") . '.json', + PHP_EOL + . json_encode($result["created_resortings"], JSON_UNESCAPED_UNICODE), + FILE_APPEND + ); + foreach ($result["created_resortings"] as $arr) { + if (!empty($arr["id"])) { + $replacementInvoice = ReplacementInvoice::findOne(['guid' => $arr["id"]]); + } + + if (!empty($replacementInvoice)) { + if (!empty($arr["errors"]) || !empty($arr["errors_items"])) { + $errorText = ''; + if (!empty($arr["errors"])) { + foreach ($arr["errors"] as $errorRow) { + if (!empty($errorRow['error'])) { + $errorText .= $errorRow['error']; + + $errorText .= ' ,' . $errorRow['error_description']; + if (!empty($errorRow['error_json'])) { + foreach ($errorRow['error_json'] as $errorJsonRow) { + $errorText .= ' , поле: ' . $errorJsonRow['field']; + $errorText .= ' , ошибка: ' . $errorJsonRow['error']; + } + } + } + + if (!empty($errorRow["errors_items"])) { + foreach ($errorRow["errors_items"] as $errorDopRow) { + $productName = $errorDopRow['product_id']; + + if (array_key_exists($errorDopRow['product_id'], $productsNames)) { + $productName = $productsNames[$errorDopRow['product_id']]; + } + + $errorText .= ' ' . $errorDopRow['error_dop']; + $errorText .= ' , поле: ' . $errorDopRow['field']; + $errorText .= ' , товар: ' . $productName; + $errorText .= ' , ошибка: ' . $errorDopRow['error']; + } + } + } + } + + /** @var ReplacementInvoice $replacementInvoice */ + $replacementInvoice->status = WriteOffsErp::STATUS_ERROR_1C; + $replacementInvoice->error_text = $errorText; + $replacementInvoice->save(); + if ($replacementInvoice->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 4.555, "error" => $replacementInvoice->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + + } else { + if (isset($arr["held"]) && $arr["held"]) { + /** @var ReplacementInvoice $replacementInvoice */ + $replacementInvoice->status = WriteOffsErp::STATUS_CREATED_1C; + $replacementInvoice->number_1c = $arr["name"] ?? ''; + $replacementInvoice->save(); + if ($replacementInvoice->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 4.55, "error" => $replacementInvoice->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + } + } + } + } + + $update = false; + if (!empty($start_time) && !empty($end_time)) { + $start_time_unix = strtotime($start_time); + $startMonth = date("Y-m-01"); + $end_time_unix = strtotime($end_time); + if ( + $startMonth <= (date("Y-m-d", strtotime($start_time))) + || + ($end_time_unix < (time() - 90 * 86400)) + ) { + $update = true; + } + } + + if (!empty($result['write_offs'])) { + if (!empty($start_time) and !empty($end_time)) { + if ($update) { + WriteOffs::deleteAll(['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); + } + } + + foreach ($result["write_offs"] as $gi => $arr) { + if (!empty($arr["error"])) { + file_put_contents(self::OUT_DIR . '/created_write_offs_erp_error.txt', PHP_EOL . " " . $arr["id"] . " error=" . $arr["error"], FILE_APPEND); + } + + if (empty($arr["error"]) && !empty($arr["id"])) { + $writeOffsErp = WriteOffsErp::find()->where(['guid' => $arr["id"]])->one(); + if ($writeOffsErp) { + $writeOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; + $writeOffsErp->number_1c = $arr["number"]; + $writeOffsErp->save(); + if ($writeOffsErp->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 11.6, "error" => $writeOffsErp->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } else { + $waybillWriteOffsErp = WaybillWriteOffs::find()->where(['guid' => $arr["id"]])->one(); + if ($waybillWriteOffsErp) { + $waybillWriteOffsErp->status = WriteOffsErp::STATUS_CREATED_1C; + $waybillWriteOffsErp->number_1c = $arr["number"]; + $waybillWriteOffsErp->save(); + if ($waybillWriteOffsErp->getErrors()) { + LogService::apiErrorLog( + json_encode(["error_id" => 11.7, "error" => $waybillWriteOffsErp->getErrors()], + JSON_UNESCAPED_UNICODE) + ); + } + } + } + } + +// file_put_contents(self::OUT_DIR . '/write_offs.json', PHP_EOL . json_encode($result["write_offs"], JSON_UNESCAPED_UNICODE)); + + $writeOffs = WriteOffs::find()->where(['id' => $arr["id"]])->one(); + if ($writeOffs) { + $writeOffs->delete(); + } + WriteOffsProducts::deleteAll(['write_offs_id' => $arr["id"]]); + + $writeOffs2 = new WriteOffs; + $writeOffs2->id = $arr["id"]; + $writeOffs2->status_id = 1; + $writeOffs2->write_downs = '1c'; + $writeOffs2->store_id = $arr["store_id"]; + $writeOffs2->number = $arr["number"]; + $writeOffs2->date = $arr["date"]; + $writeOffs2->based_on = $arr["based_on"] ?? ""; + $typeIndex = strpos($arr["type"], "_"); + $writeOffs2->type = $typeIndex === false ? $arr['type'] : substr($arr["type"], $typeIndex + 1); + $writeOffs2->cause = $arr["cause"] ?? ""; + $writeOffs2->comment = $arr["comment"] ?? ""; + $writeOffs2->items = json_encode($arr["items"], JSON_UNESCAPED_UNICODE); + $writeOffs2->summ = $arr["summ"]; + $writeOffs2->save(); + if ($writeOffs2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 12, "error" => $writeOffs2->getErrors(), "number" => $arr["number"]], JSON_UNESCAPED_UNICODE)); + } + + foreach ($arr["items"] as $j2 => $mass2) { + $writeOffsProducts = WriteOffsProducts::findOne([ + 'write_offs_id' => $arr["id"], + 'product_id' => $mass2['product_id'], + ]) ?? new WriteOffsProducts(); + $writeOffsProducts->write_offs_id = $arr["id"]; + $writeOffsProducts->date = $arr["date"]; + $writeOffsProducts->product_id = $mass2['product_id']; + $writeOffsProducts->color = $mass2["color"]; + $writeOffsProducts->quantity = ceil($mass2["quantity"]); + $writeOffsProducts->summ = $mass2["summ"]; + $writeOffsProducts->price = $mass2["price"]; + $writeOffsProducts->price_retail = 0; + $writeOffsProducts->summ_retail = 0; + $writeOffsProducts->save(); + if ($writeOffsProducts->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 13, "error" => $writeOffsProducts->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } + } + + if (!empty($result['counteragents'])) { + foreach ($result["counteragents"] as $gi => $arr) { + $arr["is_group"] = $arr["is_group"] ? 1 : 0; + $products1c = new Products1c; + $products1c->id = $arr["id"]; + $products1c->tip = 'counteragents'; + $products1c->name = $arr["name"]; + $products1c->code = $arr["inn"]; + $products1c->parent_id = $arr["parent_id"]; + $products1c->view = $arr["is_group"]; + $products1c->save(); + if ($products1c->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 14, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } + + if (!empty($result['incomings'])) { + foreach ($result["incomings"] as $gi => $arr) { + $incoming = Incoming::find()->where(['id' => $arr['id']])->one(); + if (!$incoming) { + $incoming = new Incoming; + $incoming->id = $arr["id"]; + $incoming->store_id = $arr["store_id"]; + $incoming->counteragent_id = $arr["counteragent_id"]; + $incoming->number = $arr["number"]; + $incoming->date = $arr["date"]; + $incoming->comment = $arr["comment"] ?? ''; + $incoming->items = empty($arr["items"]) ? '[]' : json_encode($arr["items"], JSON_UNESCAPED_UNICODE); + $incoming->is_discrepancies = (int)$arr["is_discrepancies"]; + $incoming->supplier_items = empty($arr["supplier_items"]) ? '[]' : json_encode($arr["supplier_items"], JSON_UNESCAPED_UNICODE); + $incoming->payments = empty($arr["payments"]) ? '[]' : json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); + $incoming->summ = $arr["summ"]; + $incoming->save(); + } + if ($incoming->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 15, "error" => $incoming->getErrors()], JSON_UNESCAPED_UNICODE)); + } else { + try { + $json = Json::decode($incoming->items); + IncomingItems::deleteAll(['incoming_id' => $incoming->id]); + foreach ($json as $item) { + $incomingItem = new IncomingItems; + $incomingItem->incoming_id = $incoming->id; + $incomingItem->product_id = $item['product_id']; + $incomingItem->color = $item['color']; + $incomingItem->quantity = $item['quantity']; + $incomingItem->price = $item['price']; + $incomingItem->vat_rate = $item['vat_rate']; + $incomingItem->vat_amount = $item['vat_amount']; + $incomingItem->summ = $item['summ']; + $incomingItem->save(); + if ($incomingItem->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 15.2, "error" => $incomingItem->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } catch (Exception $jex) { + LogService::apiErrorLog(json_encode(["error_id" => 15.3, "error" => "items has no json format"], JSON_UNESCAPED_UNICODE)); + } + } + } + } + + if (!empty($result['cashes'])) { + foreach ($result["cashes"] as $gi => $arr) { + $products1c = new Products1c; + $products1c->id = $arr["id"]; + $products1c->tip = 'cashes'; + $products1c->name = $arr["name"]; + $products1c->code = $arr["store_id"]; + $products1c->save(); + if ($products1c->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 16, "error" => $products1c->getErrors()], JSON_UNESCAPED_UNICODE)); + } + $cashes = new Cashes; + $cashes->id = $arr["id"]; + $cashes->store_id = $arr["store_id"]; + $cashes->kkm_id = $arr["kkm_id"]; + $cashes->name = $arr["name"]; + $cashes->is_central = $arr["is_central"]; + $cashes->save(); + if ($cashes->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 17, "error" => $cashes->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } + + if (!empty($checks_dell) and !empty($start_time) and !empty($end_time)) { + if ($update) { + Sales::updateAll(['operation' => 'Удален'], ['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); + } +// SalesUpdate::updateAll(['operation' => 'Удален'], ['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]); + + file_put_contents(self::OUT_DIR . '/check_dell.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . " regquest_id=$requestId Удаление $start_time - $end_time ", FILE_APPEND); + } + + $matrixProductsIds = []; + if (!empty($result['checks'])) { + $matrixProductsIds = SalaryHelper::getMatrixProductsIds(); + } + + if (!empty($result['checks'])) { + foreach ($result["checks"] as $index => $arr) { + if (!isset($arr["marketplace_order_id"])) { + continue; + } + $marketplaceOrder = MarketplaceOrders::findOne(['guid' => $arr["marketplace_order_id"]]); + if (!empty($arr['error'])) { + $txt = date("d.m.Y H:i:s", time()) . " $index СОЗДАНИЕ ЧЕКА ОШИБКА id=" . $arr["id"] . " " . $arr["error"]; + file_put_contents(self::OUT_DIR . '/log_check_error.txt', PHP_EOL . $txt, FILE_APPEND); + $marketplaceOrder->error_text = "ОШИБКА ЧЕКА" . $arr["id"] . "для заказа id=" . $marketplaceOrder->marketplace_order_id . " " . $arr["error"]; + $marketplaceOrder->save(); + if ($marketplaceOrder->getErrors()) { + Yii::error('Ошибка сохранения ошибки заказа ' . json_encode($marketplaceOrder->getErrors(), JSON_UNESCAPED_UNICODE)); + LogService::apiErrorLog(json_encode(["error_id" => 17.2, "error" => $marketplaceOrder->getErrors()], JSON_UNESCAPED_UNICODE)); + } + continue; + } + $check = CreateChecks::find() + ->where(['check_id' => $arr["id"]]) + ->andWhere(['order_guid' => $arr["marketplace_order_id"]]) + ->andWhere(['status' => 0])->one(); + if(!$check) { + continue; + } + $check->status = 1; + $check->name = $arr["number"] . " от " . $arr["date"]; + $check->guid = $arr["id"]; + $check->date_up = date('Y-m-d H:i:s'); + $check->held = 1; + $check->save(); + if ($check->getErrors()) { + Yii::error('Ошибка обновления чека ' . json_encode($check->getErrors(), JSON_UNESCAPED_UNICODE)); + LogService::apiErrorLog(json_encode(["error_id" => 17.3, "error" => $check->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } + + if (!empty($result['checks']) && count($result['checks']) < 1000) { + + foreach ($result["checks"] as $arr) { + + $check_id = $arr["id"]; + if ($arr["seller_id"] == '00000000-0000-0000-0000-000000000000') { + $arr["seller_id"] = "NULL"; + } + + $pay_arr = self::getPayArr($arr["payments"]); + + $store_id = ClientHelper::getExportId($arr["store_id"], "city_store", 1); +// $admin_id = ClientHelper::getExportId($arr["seller_id"], "admin", 1); + $exportImportTable = ExportImportTable::find()->select(['entity_id'])->where(['entity' => 'admin']) + ->andWhere(['export_id' => 1])->andWhere(['export_val' => $arr["seller_id"]])->all(); + $exportImportTableIds = ArrayHelper::getColumn($exportImportTable, 'entity_id'); + $admin = Admin::find()->where(['in', 'id', $exportImportTableIds])->andWhere(['>', 'group_id', 0])->one(); + $admin_id = $admin->id ?? 0; + + //удаляем чеки и товары в чеках + $saleUpdate = SalesUpdate::find()->where(['id' => $arr["id"]])->one(); + if ($saleUpdate) { + $saleUpdate->delete(); + } +// SalesProductsUpdate::deleteAll(['check_id' => $arr["id"]]); + + if ($update) { + $sales = Sales::find()->where(['id' => $arr["id"]])->one(); + if ($sales) { + $sales->delete(); + } + SalesItems::deleteAll(['check_id' => $arr["id"]]); + SalesProducts::deleteAll(['check_id' => $arr["id"]]); + } + + // проверяем стутс чека - вносим только Архивные и пробитые +// if (!empty($arr["status"])) { +// $salesUpdate = new SalesUpdate; +// $salesUpdate->phone = empty($arr["client_phone"]) ? 0 : (int)$arr["client_phone"]; +// $salesUpdate->id = $arr["id"]; +// $salesUpdate->store_id = $store_id; +// $salesUpdate->store_id_1c = $arr["store_id"]; +// $salesUpdate->seller_id = $arr["seller_id"]; +// $salesUpdate->admin_id = $admin_id; +// $salesUpdate->operation = $arr["type"]; +// $salesUpdate->number = $arr["number"]; +// $salesUpdate->date = $arr["date"]; +// $salesUpdate->summ = $arr["summ"]; +// $salesUpdate->status = $arr["status"]; +// $salesUpdate->sales_check = $arr["sales_check"] ?? 'NULL'; +// $salesUpdate->payments = json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); +// $salesUpdate->pay_arr = implode(",", $pay_arr); +// $salesUpdate->order_id = $arr["order_id"] ?? ''; +// $salesUpdate->terminal = $arr["terminal"] ?? 'NULL'; +// $salesUpdate->terminal_id = $arr["terminal_id"] ?? 'NULL'; +// $salesUpdate->date_up = date('Y-m-d H:i:s'); +// $salesUpdate->skidka = $arr["discount"] ?? 0; +// $salesUpdate->kkm_id = $arr["kkm_id"] ?? ''; // Пустая строка по умолчанию не может быть +// $salesUpdate->held = 0; // ??? +// $salesUpdate->save(); +// if ($salesUpdate->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 18, "error" => $salesUpdate->getErrors()], JSON_UNESCAPED_UNICODE)); +// } + +// $amount = 0; +//// $items_arr = []; +// foreach ($arr["items"] as $itemid => $arr2) { +// if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { +// $arr2["seller_id"] = "NULL"; +// } +// $saleProductsUpdate = new SalesProductsUpdate; +// $saleProductsUpdate->type_id = 1; +// $saleProductsUpdate->check_id = $check_id; +// $saleProductsUpdate->product_id = $arr2["product_id"]; +// $saleProductsUpdate->seller_id = $arr2["seller_id"]; +// $saleProductsUpdate->quantity = $arr2["quantity"]; +// $saleProductsUpdate->price = $arr2["price"]; +// $saleProductsUpdate->summ = $arr2["summ"]; +// $saleProductsUpdate->discount = $arr2["discount"]; +// $saleProductsUpdate->color = $arr2["color"] ?? ''; // ??? +// $saleProductsUpdate->component_parent_id = ''; // ??? +// $saleProductsUpdate->save(); +// if ($saleProductsUpdate->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 19, "error" => $saleProductsUpdate->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// if (!empty($arr2["components"])) { +// foreach ($arr2["components"] as $compID => $comp) { +// $saleProductsUpdate2 = new SalesProductsUpdate; +// $saleProductsUpdate2->type_id = 3; +// $saleProductsUpdate2->check_id = $check_id; +// $saleProductsUpdate2->product_id = $comp["product_id"]; +// $saleProductsUpdate2->seller_id = $arr2["seller_id"]; +// $saleProductsUpdate2->quantity = $comp["quantity"]; +// $saleProductsUpdate2->color = $comp["color"]; +// $saleProductsUpdate2->component_parent_id = $arr2["product_id"]; +// $saleProductsUpdate2->save(); +// if ($saleProductsUpdate2->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 20, "error" => $saleProductsUpdate2->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } +// } +// } + + if ($update) { + $sales2 = new Sales; + $sales2->phone = $arr["client_phone"] ?? 0; + $sales2->id = $arr["id"]; + $sales2->store_id = $store_id; + $sales2->store_id_1c = $arr["store_id"]; + $sales2->seller_id = $arr["seller_id"]; + $sales2->admin_id = $admin_id; + $sales2->operation = $arr["type"]; + $sales2->number = $arr["number"]; + $sales2->date = $arr["date"]; + $sales2->summ = $arr["summ"]; + $sales2->status = $arr["status"]; + $sales2->sales_check = $arr["sales_check"] ?? ''; + $sales2->payments = json_encode($arr["payments"], JSON_UNESCAPED_UNICODE); + $sales2->pay_arr = implode(",", $pay_arr); + $sales2->order_id = trim($arr["order_id"] ?? ''); + $sales2->terminal = $arr["terminal"] ?? ''; + $sales2->terminal_id = $arr["terminal_id"] ?? ''; + $sales2->date_up = date('Y-m-d H:i:s'); + $sales2->skidka = $arr["discount"] ?? '0'; + $sales2->delivery_date = date('Y-m-d', strtotime($arr['delivery_date'] ?? '')); + $sales2->pickup = $arr['pickup'] ?? false; + $sales2->save(); + if ($sales2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 21, "error" => $sales2->getErrors()], JSON_UNESCAPED_UNICODE)); + } + + // Обновляем данные в очереди на создание чеков + CreateChecks::updateAll(['status' => 1], ['check_id' => $arr["id"]]); + + // позиции в чеке + $amount = 0; +// $items_arr = []; + $productsInfos = []; + foreach ($arr["items"] as $itemid => $arr2) { + if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { + $arr2["seller_id"] = null; + } + $saleProducts = new SalesProducts; + $saleProducts->type_id = 1; + $saleProducts->check_id = $check_id; + $saleProducts->product_id = $arr2["product_id"]; + $saleProducts->seller_id = $arr2["seller_id"]; + $saleProducts->quantity = $arr2["quantity"]; + $saleProducts->price = $arr2["price"]; + $saleProducts->summ = $arr2["summ"]; + $saleProducts->discount = $arr2["discount"]; + $saleProducts->color = $arr2["color"]; + $saleProducts->assemble_id = !empty($arr2["assemble_id"]) && $arr2["assemble_id"] != '00000000-0000-0000-0000-000000000000' ? $arr2["assemble_id"] : null; + $saleProducts->save(); + if ($saleProducts->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 22, "error" => $saleProducts->getErrors()], JSON_UNESCAPED_UNICODE)); + } + $assemble = Assemblies::find()->where(['guid' => $saleProducts->assemble_id])->one(); + if ($assemble) { + if (in_array($saleProducts->product_id, $matrixProductsIds)) { + $productsInfos[$assemble->id] = ($productsInfos[$assemble->id] ?? 0) + $saleProducts->summ; + } + $assemble->date_close = $sales2->date; + $assemble->check_id = $sales2->id; + if ($arr["type"] == 'Продажа') { + $assemble->status_id = 1; + } elseif ($arr["type"] == 'Возврат') { + $assemble->status_id = 2; + $assemble->with_return = 1; + } + $assemble->save(); + if ($assemble->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 22.2, "error" => $assemble->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + + if (!empty($arr2["components"])) { + foreach ($arr2["components"] as $compID => $comp) { + $saleProducts2 = new SalesProducts; + $saleProducts2->type_id = 3; + $saleProducts2->check_id = $check_id; + $saleProducts2->product_id = $comp["product_id"]; + $saleProducts2->seller_id = $arr2["seller_id"]; + $saleProducts2->quantity = $comp["quantity"]; + $saleProducts2->color = $comp["color"]; + $saleProducts2->component_parent_id = $arr2["product_id"]; + $saleProducts2->price = 0; // ??? + $saleProducts2->discount = 0; // ??? + $saleProducts2->summ = 0; // ??? + $saleProducts2->save(); + if ($saleProducts2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 23, "error" => $saleProducts2->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } +// $salesItems = new SalesItems; +// $salesItems->lid_id = empty($arr["order_id"]) ? 0 : $arr["order_id"]; +// $salesItems->check_id = $check_id; +// $salesItems->phone = $arr["client_phone"] ?? 0; +// $salesItems->id_1c = $arr2["product_id"]; +// $salesItems->seller_id = $arr2["seller_id"]; +// $salesItems->kol = $arr2["quantity"]; +// $salesItems->color_id = $arr2["color_id"] ?? 0; +// $salesItems->summa = $arr2["summ"]; +// $salesItems->date = date('Y-m-d H:i:s'); +// $salesItems->skidka = $arr2["discount"]; +// $salesItems->store_id = 0; // ??? +// $salesItems->store_id_1c = ''; // ??? +// $salesItems->admin_id = 0; // ??? +// $salesItems->item_id = 0; // ??? +// $salesItems->complect_id = 0; // ??? +// $salesItems->name = ''; // ??? +// $salesItems->referal_id = 0; // ??? +// $salesItems->vozvrat = 0; // ??? +// $salesItems->save(); +// if ($salesItems->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 24, "error" => $salesItems->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// $amount = $amount + $arr2["price"] * $arr2["quantity"]; +// $items_arr[] = ["product_id" => $arr2["product_id"], "seller_id" => $arr2["seller_id"], "quantity" => $arr2["quantity"], "summ" => $arr2["summ"], "discount" => $arr2["discount"]]; + } + foreach ($productsInfos as $assemble_id => $summ) { + Assemblies::updateAll(['summ_matrix' => $summ], ['id' => $assemble_id]); + } + } + } + } elseif (!empty($result['checks'])) { + file_put_contents(self::OUT_DIR . '/error_upload.txt', + PHP_EOL . "elseif", FILE_APPEND); + $dataArrayValues = self::getSalesDate($result["checks"], $update); + + foreach ($dataArrayValues as $keyMethodName => $rowValue) { + file_put_contents(self::OUT_DIR . '/error_upload.txt', + PHP_EOL . $keyMethodName, FILE_APPEND); + try { + self::$keyMethodName($rowValue, $update); + } catch (Exception $e) { + $errorString = substr($e->getMessage(), 0, 2000); + InfoLogService::setInfoLog(__FILE__, __LINE__, $errorString, 'error_id_25_m_st'); + } + } + } + + if (!empty($result['balances'])) { + foreach ($result["balances"] as $std => $arr) { + Balances::deleteAll(['store_id' => $std]); + foreach ($arr as $pid => $arr2) { + $balances = new Balances; + $balances->store_id = $std; + $balances->product_id = $pid; + $balances->quantity = $arr2[0]; + $balances->reserv = $arr2[1]; + $balances->save(); + if ($balances->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 26, "error" => $balances->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } + } + + if (!empty($result['prices'])) { + foreach ($result["prices"] as $idp => $price) { + if ( + !empty($price) + && + in_array( + $type_price, + array_keys(Prices::REGION_TYPE_PRICES) + ) + ) { + $region_id = Prices::REGION_TYPE_PRICES[$type_price]; + Prices::deleteAll(['product_id' => $idp]); + $price1 = new Prices; + $price1->product_id = $idp; + $price1->price = $price; + $price1->save(); + if ($price1->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 27, "error" => $price1->getErrors()], JSON_UNESCAPED_UNICODE)); + } + PricesRegion::deleteAll(['product_id' => $idp, 'region_id' => $region_id]); + $priceRegion = new PricesRegion; + $priceRegion->product_id = $idp; + $priceRegion->region_id = $region_id; + $priceRegion->price = $price; + $priceRegion->save(); + if ($priceRegion->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 27.5, "error" => $priceRegion->getErrors()], JSON_UNESCAPED_UNICODE)); + } + try { + $pricesDynamic = PricesDynamic::find()->where(['product_id' => $idp, 'region_id' => $region_id])->andWhere(['active' => '1'])->orderBy(['id' => SORT_DESC])->one(); + $price = round($price, 2); + // если нет записи или цена изменилась то вносим запись в БД + if ($pricesDynamic and $pricesDynamic->price != $price) { + $pricesDynamic->active = 0; + $pricesDynamic->date_to = date('Y-m-d H:i:s'); + $pricesDynamic->save(); + if ($pricesDynamic->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 28, "error" => $pricesDynamic->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + if (!$pricesDynamic or ($pricesDynamic and ($pricesDynamic->price != $price || $pricesDynamic->region_id != $region_id))) { + $pricesDynamic2 = new PricesDynamic; + $pricesDynamic2->product_id = $idp; + $pricesDynamic2->price = $price; + $pricesDynamic2->date_from = date('Y-m-d H:i:s'); + $pricesDynamic2->date_to = '2100-01-01 00:00:00'; + $pricesDynamic2->active = 1; + $pricesDynamic2->region_id = $region_id; + $pricesDynamic2->save(); + if ($pricesDynamic2->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 29, "error" => $pricesDynamic2->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + } catch (Exception $e) { + file_put_contents(self::OUT_DIR . '/log_prices_dinamics.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage(), FILE_APPEND); + } + } + } + } + + if (!empty($result['prices'])) { + foreach ($result["prices"] as $idp => $price) { + if (!empty($price) and $type_price == "Закупочная цена руб.") { + try { + $priceZakup = new PricesZakup; + $priceZakup->product_id = $idp; + $priceZakup->price = $price; + $priceZakup->save(); + if ($priceZakup->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 30, "error" => $priceZakup->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } catch (Exception $e) { + } + } + if (!empty($price) and $type_price == "Себестоимость") { + try { + file_put_contents(self::OUT_DIR . '/price_purchese.txt', PHP_EOL . "$idp=" . $price, FILE_APPEND); + } catch (Exception $e) { + } + } + } + } + + if (!empty($result['created_checks'])) { + foreach ($result["created_checks"] as $idp => $arr2) { + if (!empty($arr2["error"])) { // Если есть ошибки + // // обновляем GUID на новый +// try { +// $createChecks = CreateChecks::find()->select(['order_id'])->where(['check_id' => $arr2["id"]])->one(); +// if ($createChecks) { +// $lid_id = $createChecks->order_id; +// $guid_new = \yii_app\controllers\crud\UniversalCatalogController::create_guid_my_old("01", $lid_id); +// $createChecks2 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->andWhere(['!=', 'check_id', '0']) +// ->andWhere(['status' => '0'])->andWhere(['held' => '0'])->one(); +// if ($createChecks2) { +// $createChecks2->check_id = $guid_new; +// $createChecks2->save(); +// if ($createChecks2->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 32, "error" => $createChecks2->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// } else { +// LogService::apiErrorLog(json_encode(["error_id" => 31, "error" => 'no create_checks with check_id=' . $arr2["id"]], JSON_UNESCAPED_UNICODE)); +// } +// } catch (Exception $e) { +// file_put_contents(self::OUT_DIR . '/log_created_check_error.txt', PHP_EOL . date("d.m.Y H:i:s",time()). $e->getMessage(), FILE_APPEND); +// } + + $txt = date("d.m.Y H:i:s", time()) . " $idp СОЗДАНИЕ ЧЕКА ОШИБКА id=" . $arr2["id"] . " " . $arr2["error"]; + file_put_contents(self::OUT_DIR . '/log_created_check_error.txt', PHP_EOL . $txt, FILE_APPEND); + } else { // Если ошибок нет + if (/* $arr2["held"] == true and */ !empty($arr2["name"]) and !empty($arr2["id"])) { // Если заполнен name b id +// $createChecksBags = CreateChecksBags::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]])->orderBy(['id' => SORT_DESC])->one(); +// if ($createChecksBags) { +// $createChecksBags->guid = $arr2["guid"]; +// $createChecksBags->name = $arr2["name"]; +// $createChecksBags->held = $arr2["held"]; +// $createChecksBags->status = '1'; +// $createChecksBags->date_up = date('Y-m-d H:I:s'); +// $createChecksBags->save(); +// if ($createChecksBags->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 33, "error" => $createChecksBags->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } + // Обновляем данные в очереди на создание чеков + CreateChecks::updateAll([ + 'status' => 1, + 'guid' => $arr2["id"], + 'date_up' => date('Y-m-d H:i:s'), + 'name' => $arr2["name"], + 'held' => isset($arr2["held"]) ? $arr2["held"] : 0 + ], ['check_id' => $arr2["id"]]); +// $createChecks3 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->orderBy(['id' => SORT_DESC])->one(); +// if ($createChecks3) { +// $createChecks3->guid = $arr2["id"]; +// $createChecks3->name = $arr2["name"]; +// $createChecks3->held = isset($arr2["held"]) ? ($arr2["held"] ? 1 : 0) : 0; +// $createChecks3->status = '1'; +// $createChecks3->date_up = date('Y-m-d H:i:s'); +// $createChecks3->save(); +// if ($createChecks3->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 34, "error" => $createChecks3->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// $createChecks4 = CreateChecks2::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]])->orderBy(['id' => SORT_DESC])->one(); +// if ($createChecks4) { +// $createChecks4->name = $arr2["name"]; +// $createChecks4->held = $arr2["held"]; +// $createChecks4->status = '1'; +// $createChecks4->date_up = date('Y-m-d H:I:s'); +// $createChecks4->save(); +// if ($createChecks4->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 35, "error" => $createChecks4->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } +// $createChecks5 = CreateChecks::find()->where(['check_id' => $arr2["id"]])->andWhere(['order_id' => $arr2["order_id"]]) +// ->andWhere(['type' => 'Возврат'])->orderBy(['id' => SORT_DESC])->one(); +// if ($createChecks5) { +// $createChecks5->held = $arr2["held"]; +// $createChecks5->status = '1'; +// $createChecks5->date_up = date('Y-m-d H:I:s'); +// $createChecks5->save(); +// if ($createChecks5->getErrors()) { +// LogService::apiErrorLog(json_encode(["error_id" => 35, "error" => $createChecks5->getErrors()], JSON_UNESCAPED_UNICODE)); +// } +// } + // прикрепляем чек к заказу + $ordersAmo = OrdersAmo::find()->where(['id' => $arr2["order_id"]])->one(); + if ($ordersAmo) { + $ordersAmo->check_id_arr = $arr2["id"]; + $ordersAmo->save(false); + if ($ordersAmo->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 36, "error" => $ordersAmo->getErrors()], JSON_UNESCAPED_UNICODE)); + } + } + + // обращаемся к старой базе данных базацветов_24 + // ??? + } + } + } + } + + if (!empty($result['created_employee'])) { + foreach ($result['created_employee'] as $arr) { + EmployeeOnShift::updateAll(['status_source' => EmployeeOnShift::STATUS_SOURCE_CREATED_IN_1C], ['guid' => $arr['id']]); + } + } + + if (!empty($result['marketplace_orders'])) { + foreach ($result["marketplace_orders"] as $mpOrder) { + $updateResult = self::changeMarketplaceOrderStatusFrom1C($mpOrder); //изменение статусов + if ($updateResult['status'] == 'error') { + LogService::apiErrorLog(json_encode(["error_id" => 40, "error" => $updateResult['message']], JSON_UNESCAPED_UNICODE)); + } + } + } + +// + $mess["request_id"] = "" . time(); + + if (!empty($result['created_orders'])) { + $mess['line'][] = __LINE__; + $mess["created_orders"] = $result['created_orders']; + $productsNames = Products1c::getNamesByTip('products'); + foreach ($result['created_orders'] as $arr) { + $marketplaceOrders = null; + $marketplaceOrdersGuidArr = []; + if (!empty($arr["id"])) { + $marketplaceOrders = MarketplaceOrders::find()->where(['guid' => $arr["id"]])->one(); + if ($marketplaceOrders && $marketplaceOrders->guid) { + $marketplaceOrdersGuidArr[] = $marketplaceOrders->guid; + } + } + if (!empty($marketplaceOrders)) { + /** @var MarketplaceOrders $marketplaceOrders */ + $mess['line'][] = __LINE__; + if (!empty($arr["errors"]) || !empty($arr["error"]) || !empty($arr["errors_items"])) { + $errorText = ''; + if (!empty($arr["errors"])) { + //"errors": [ + //{ + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + //"error_json": [ + //{ + //"field": "id", + //"error": "Документ с данным ИД уже записан в системе" + //} + // + + foreach ($arr["errors"] as $errorRow) { + if (!empty($errorRow['error'])) { + $errorText .= $errorRow['error']; + + $errorText .= ' ,' . $errorRow['error_description']; + if (!empty($errorRow['error_json'])) { + foreach ($errorRow['error_json'] as $errorJsonRow) { + $errorText .= ' , поле: ' . $errorJsonRow['field']; + $errorText .= ' , ошибка: ' . $errorJsonRow['error']; + } + } + } + + if (!empty($errorRow["errors_items"])) { + foreach ($errorRow["errors_items"] as $errorDopRow) { + //"errors_items": [ + //{ + //"error_dop": "Ошибка проверки количества номенклатуры", + //"field": "quantity", + //"product_id": "bdd17587-09d8-11e5-bd74-1c6f659fb563", + //"error": "У данной позиции запрещён ввод дробного значения!" + //}, + // + // + $productName = $errorDopRow['product_id']; + + if (array_key_exists($errorDopRow['product_id'], $productsNames)) { + $productName = $productsNames[$errorDopRow['product_id']]; + } + + $errorText .= ' ' . $errorDopRow['error_dop']; + $errorText .= ' , поле: ' . $errorDopRow['field']; + $errorText .= ' , товар: ' . $productName; + $errorText .= ' , ошибка: ' . $errorDopRow['error']; + } + } + } + } + + if (!empty($arr["error"])) { + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + $errorText .= $arr["error"]; + $errorText .= ' ,' . $arr['error_description']; + } + + $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; + $marketplaceOrders->error_text = $errorText; + $marketplaceOrders->save(); + if ($marketplaceOrders->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + $mess['line'][] = __LINE__; + if (isset($arr["held"]) && $arr["held"]) { + $mess['line'][] = __LINE__; + $marketplaceOrders->number_1c = $arr["number"] ?? ''; + $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_1C; + $marketplaceOrders->save(); + if ($marketplaceOrders->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 42, "error" => $marketplaceOrders->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + } + } + } + + $now = time(); + $sendedOrders = MarketplaceOrders::find() + ->where(['status_1c' => MarketplaceOrders::STATUSES_1C_SENDED_TO_1C]) + ->andWhere(['not in', 'guid', $marketplaceOrdersGuidArr]) + ->all(); + foreach ($sendedOrders as $order) { + $sentAt = strtotime($order->sent_1c_at ?? '2025-07-01 00:00:00'); + $attempts = (int)$order->attempts_number; + if (($now - $sentAt) > 300) { + if ($attempts < 4) { + $order->sent_1c_at = null; + $order->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_ERP; + $order->save(); + } else { + $order->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; + $order->error_text = 'Превышено число попыток отправки в 1С.'; + $order->save(); + + LogService::apiErrorLog(json_encode([ + "error_id" => 43, + "error" => "Превышено число попыток отправки в 1С " . $order->guid, + ], JSON_UNESCAPED_UNICODE)); + } + } + } + + } + + if (!empty($result['analysts_business_operations'])) { + $existingOperations = AnalystsBusinessOperations::find() + ->indexBy('id') + ->asArray() + ->all(); + $existingTypes = AnalystsBusinessOperationsTypes::find() + ->indexBy('code') + ->asArray() + ->all(); + foreach ($result["analysts_business_operations"] as $operation) { + if (!in_array($operation['id'], array_keys($existingOperations))) { + $newOperation = new AnalystsBusinessOperations(); + $newOperation->id = $operation['id']; + $newOperation->name = $operation['name']; + $newOperation->type = (int)$operation['type']; + $newOperation->active = 1; + if (!in_array((int)$operation['type'], array_column($existingTypes, 'code'))) { + $newType = new AnalystsBusinessOperationsTypes(); + $newType->code = (int)$operation['type']; + $newType->name = null; + $newType->alias = null; + $newType->created_at = date('Y-m-d H:i:s'); + $newType->created_by = 1409; + if ($newType->save()) { + $newOperation->type_id = $newType->id; + } else { + $newOperation->type_id = null; + Yii::error('Ошибка сохранение типа ' . json_encode($newType->getErrors(), JSON_UNESCAPED_UNICODE), __METHOD__ ); + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.1, "error" => $newType->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + $newOperation->type_id = $existingTypes[$operation['type']]['id']; + } + $newOperation->created_at = date('Y-m-d H:i:s'); + if (!$newOperation->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.2, "error" => $newOperation->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + + } else { + if ($existingOperations[$operation['id']]['type'] !== (int)$operation['type']) { + $oldOperation = AnalystsBusinessOperations::findOne($operation['id']); + if (!in_array((int)$operation['type'], array_column($existingTypes, 'code'))) { + $newType = new AnalystsBusinessOperationsTypes(); + $newType->code = (int)$operation['type']; + $newType->name = null; + $newType->alias = null; + $newType->created_at = date('Y-m-d H:i:s'); + $newType->created_by = 1409; + if ($newType->save()) { + $oldOperation->type = (int)$operation['type']; + $oldOperation->type_id = $newType->id; + if (!$oldOperation->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.3, "error" => $oldOperation->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + Yii::error('Ошибка сохранение типа ' . json_encode($newType->getErrors(), JSON_UNESCAPED_UNICODE), __METHOD__ ); + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.4, "error" => $oldOperation->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + $oldOperation->type = (int)$operation['type']; + $oldOperation->type_id = AnalystsBusinessOperationsTypes::find()->where(['code' => (int)$operation['type']])->one()->id; + if (!$oldOperation->save()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 44.5, "error" => $oldOperation->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + } + } + + } + } + if (!empty($result['cancelled_orders'])) { + foreach ($result['cancelled_orders'] as $arr) { + $marketplaceOrders = null; + $marketplaceOrdersGuidArr = []; + + $marketplaceOrders = MarketplaceOrders::find()->where(['guid' => $arr])->one(); + $marketplaceOrdersGuidArr[] = $marketplaceOrders->guid; + + if (!empty($marketplaceOrders)) { + /** @var MarketplaceOrders $marketplaceOrders */ + + if (!empty($arr["errors"]) || !empty($arr["error"]) || !empty($arr["errors_items"])) { + $errorText = ''; + if (!empty($arr["errors"])) { + + + foreach ($arr["errors"] as $errorRow) { + if (!empty($errorRow['error'])) { + $errorText .= $errorRow['error']; + + $errorText .= ' ,' . $errorRow['error_description']; + if (!empty($errorRow['error_json'])) { + foreach ($errorRow['error_json'] as $errorJsonRow) { + $errorText .= ' , поле: ' . $errorJsonRow['field']; + $errorText .= ' , ошибка: ' . $errorJsonRow['error']; + } + } + } + } + } + + if (!empty($arr["error"])) { + //"error": "Ошибка преобразования ИД документа", + //"error_description": "ИД документа 01202307-2705-1039-09bc-100015809667 уже записан в системе", + $errorText .= $arr["error"]; + $errorText .= ' ,' . $arr['error_description']; + } + + $marketplaceOrders->status_1c = MarketplaceOrders::STATUSES_1C_ERROR_1C; + $marketplaceOrders->error_text = $errorText; + $marketplaceOrders->save(); + if ($marketplaceOrders->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } else { + $marketplaceOrders->cancelled_order_sent = MarketplaceOrders::STATUSES_1C_CANCELLED_ORDER_SENT_IN_1C; + $marketplaceOrders->save(); + if ($marketplaceOrders->getErrors()) { + LogService::apiErrorLog( + json_encode( + ["error_id" => 41, "error" => $marketplaceOrders->getErrors()], + JSON_UNESCAPED_UNICODE + ) + ); + } + } + } + } + + + + } + + $mess['line'][] = __LINE__; + } catch (Exception $e) { + LogService::apiDataLogs(1, json_encode($mess, JSON_UNESCAPED_UNICODE), $requestIdText); + file_put_contents(self::OUT_DIR . '/log_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage() . " " . $e->getLine(), FILE_APPEND); + Yii::error('Ошибка upload - блок catch '. json_encode($e->getMessage() . " " . $e->getLine(), JSON_UNESCAPED_UNICODE)); + LogService::apiErrorLog(json_encode([ + "error_id" => 45, + "error" => "Ошибка загрузки " . $e->getMessage() . " " . $e->getLine(), + ], JSON_UNESCAPED_UNICODE)); + } finally { + LogService::apiDataLogs(1, json_encode($mess, JSON_UNESCAPED_UNICODE), $requestIdText); + } + + return true; + } + + public static function setSelfCostUpdate($values) + { + $columns = [ + + 'date', + 'store_id', + 'product_guid', + 'price', + 'updated_at' + ]; + + + self::insertDataSales($values, 'self_cost_product', $columns, 4000); + } + + + public static function insertDataSales($values, $tableName, $columns, $chunks = 1000) + + { + $chunkValues = array_chunk($values, $chunks); + + foreach ($chunkValues as $key => $rows) { + + try { + $transaction = \Yii::$app->db->beginTransaction(); + Yii::$app->db->createCommand()->batchInsert($tableName, $columns, $rows)->execute(); + $transaction->commit(); + } catch (Exception $e) { + $errorString = substr($e->getMessage(), 0, 2000); + file_put_contents(self::OUT_DIR . '/error_upload.txt', + PHP_EOL . $errorString, FILE_APPEND + ); + $transaction->rollBack(); + InfoLogService::setInfoLog(__FILE__, __LINE__, $tableName, 'error_id_25'); + InfoLogService::setInfoLog(__FILE__, __LINE__, $errorString, 'error_id_25_22'); + LogService::apiErrorLog(json_encode(["error_id" => 25, "error" => $errorString], JSON_UNESCAPED_UNICODE) + ); + } + } + } + + public static function getPayArr($arrPayments): array + { + $pay_arr = array(); + if (!empty($arrPayments)) { + foreach ($arrPayments as $tp) { + if ($tp["type"] == "Наличные") { + $pay_arr[] = 1; + } elseif ($tp['type'] == 'QR код') { + $pay_arr[] = 3; + } else { + $pay_arr[] = 2; + } + } + } + + return $pay_arr; + } + + public static function getSalesDate($checks, $update): array + { + $admins = self::getEntityByType('admin'); + + $adminsIds = array_column($admins, 'entity_id'); + $adminsValue = array_column($admins, 'export_val'); + + $adminsGuidIds = array_combine($adminsValue, $adminsIds); + $adminsIdsGuid = array_combine($adminsIds, $adminsValue); + + $stores = self::getEntityByType(); + + $storesIds = array_column($stores, 'entity_id'); + $storesValue = array_column($stores, 'export_val'); + + $storesGuidIds = array_combine($storesValue, $storesIds); + $storesIdsGuid = array_combine($storesIds, $storesValue); + + $checksIdsPrepared = array_column($checks, 'id'); + + $checksIds = array_unique($checksIdsPrepared); + + $checksValues = []; + $salesProducts = []; + $salesItems = []; + $salesProductsComponents = []; + + foreach ($checks as $arr) { + $check_id = $arr["id"]; + + if (array_key_exists($arr["store_id"], $storesGuidIds)) { + $store_id = $storesGuidIds[$arr["store_id"]]; + } + if (array_key_exists($arr["seller_id"], $adminsGuidIds)) { + $admin_id = $adminsGuidIds[$arr["seller_id"]]; + } + + $pay_arr = self::getPayArr($arr["payments"]); + + if (empty($store_id)) { + continue; + } + + $date_up = date("Y-m-d H:i:s"); + $date = date("Y-m-d H:i:s"); + + $purchaseItemsArray = []; + + // позиции в чеке + $amount = 0; + $items_arr = []; + foreach ($arr["items"] as $itemid => $arr2) { + if ($arr2["seller_id"] == '00000000-0000-0000-0000-000000000000') { + $arr2["seller_id"] = null; + } + + $purchaseItemsRow = 0; + if (!empty($arr2["purchase_price"]) && !empty($arr2["quantity"])) { + $purchaseItemsRow = $arr2["purchase_price"] * $arr2["quantity"]; + } + + $purchaseItemsArray[] = $purchaseItemsRow; + + $salesProducts[] = [ + 'type_id' => '1', // type_id, + 'check_id' => $check_id, // check_id, + 'product_id' => $arr2["product_id"], // product_id, + 'seller_id' => $arr2["seller_id"], // seller_id, + 'quantity' => $arr2["quantity"], // quantity, + 'price' => $arr2["price"], // price, + 'summ' => $arr2["summ"], // summ, + 'purchase_price' => $arr2["purchase_price"] ?? 0, // purchase_price, + 'purchase_sum' => $purchaseItemsRow, // purchase_sum, + 'discount' => $arr2["discount"], // discount, + 'color' => $arr2["color"] // color + ]; + + $log[$arr["id"]][$itemid] = $arr2; + + if (!empty($arr2["components"])) { + foreach ($arr2["components"] as $compID => $comp) { + $salesProductsComponents[] = + [ + 'type_id' => '3', // type_id + 'check_id' => $check_id, // check_id + 'product_id' => $comp["product_id"], // product_id + 'seller_id' => $arr2["seller_id"], // seller_id + 'quantity' => $comp["quantity"], // quantity + 'color' => $comp["color"], // color + 'component_parent_id' => $arr2["product_id"], // component_parent_id + 'price' => 0, // price, + 'discount' => 0, // discount, + 'summ' => 0, // summ, + ]; + + $salesItems[] = [ + 'lid_id' => $arr["order_id"], // lid_id + 'check_id' => $check_id, // check_id + 'phone' => $arr["client_phone"] ?? null, // phone + 'id_1c' => $arr2["product_id"], // id_1c + 'seller_id' => $arr2["seller_id"], // seller_id + 'kol' => $arr2["quantity"], // kol + 'color_id' => $arr2["color_id"] ?? 0, // color_id + 'summa' => $arr2["summ"], // summa + 'skidka' => $arr2["discount"], // skidka + 'date' => $date, // date + ]; + } + } + } + + $purchaseItemsSum = array_sum($purchaseItemsArray); + + $checksValues[] = [ + 'phone' => $arr["client_phone"] ?? null, // phone, + 'id' => $arr["id"], // id, + 'store_id' => $store_id, // store_id, + 'store_id_1c' => $arr["store_id"], // store_id_1c, + 'seller_id' => $arr["seller_id"], // seller_id, + 'admin_id' => $admin_id, // admin_id, + 'operation' => $arr["type"], // operation, + 'number' => $arr["number"], // number, + 'date' => $arr["date"], // date, + 'summ' => $arr["summ"], // summ, + 'purchase_sum' => $purchaseItemsSum ?? 0, // purchase_sum, + 'status' => $arr["status"], // status, + 'sales_check' => $arr["sales_check"] ?? '', // sales_check, + 'payments' => json_encode($arr["payments"], JSON_UNESCAPED_UNICODE), // payments, + 'pay_arr' => implode(",", $pay_arr), // pay_arr, + 'order_id' => trim($arr["order_id"]), // order_id, + 'terminal' => $arr["terminal"] ?? '', // terminal, + 'kkm_id' => $arr["kkm_id"] ?? '', // terminal, + 'terminal_id' => $arr["terminal_id"] ?? '', // terminal_id, + 'skidka' => $arr["discount"] ?? 0, // skidka + 'date_up' => $date_up, // date_up + 'held' => 0, + ]; + + } + + $result = []; + + $updateSalesMain = [ + 'deleteSales' => $checksIds, +// 'setSalesUpdate' => $checksValues, + //'setSalesProductsUpdate' => $salesProducts, +// 'setSalesProductsComponentsUpdate' => $salesProductsComponents, + ]; + + $result = array_merge($result, $updateSalesMain); + + if ($update) { + $updateSalesPart = [ + 'setSales' => $checksValues, + 'setSalesProducts' => $salesProducts, + 'setSalesProductsComponents' => $salesProductsComponents, +// 'setSalesItems' => $salesItems, + ]; + $result = array_merge($result, $updateSalesPart); + } + + return $result; + } + + public static function getEntityByType($entity = 'city_store') + { + return ExportImportTable::find()->select(['entity_id', 'export_val'])->where(['entity' => $entity]) + ->andWhere(['export_id' => 1])->andWhere(['!=', 'export_val', ''])->asArray()->all(); + } + + public static function deleteSales($ids, $update) + { + if (!empty($ids)) { + SalesUpdate::deleteAll(['in', 'id', $ids]); +// SalesProductsUpdate::deleteAll(['in', 'check_id', $ids]); + if ($update) { + Sales::deleteAll(['in', 'id', $ids]); + SalesItems::deleteAll(['in', 'check_id', $ids]); + SalesProducts::deleteAll(['in', 'check_id', $ids]); + } + } + } + + public static function setSales($values) + { + $columns = [ + 'phone', + 'id', + 'store_id', + 'store_id_1c', + 'seller_id', + 'admin_id', + 'operation', + 'number', + 'date', + 'summ', + 'purchase_sum', + 'status', + 'sales_check', + 'payments', + 'pay_arr', + 'order_id', + 'terminal', + 'kkm_id', + 'terminal_id', + 'skidka', + 'date_up', + 'held', + ]; + + self::insertDataSales($values, 'sales', $columns); + } + + public static function setSalesProducts($values) + { + $columns = [ + 'type_id', + 'check_id', + 'product_id', + 'seller_id', + 'quantity', + 'price', + 'summ', + 'purchase_price', + 'purchase_sum', + 'discount', + 'color' + ]; + + self::insertDataSales($values, 'sales_products', $columns); + } + + public static function setSalesProductsComponents($values) + { + $columns = [ + 'type_id', + 'check_id', + 'product_id', + 'seller_id', + 'quantity', + 'color', + 'component_parent_id', + 'price', + 'discount', + 'summ', + ]; + + self::insertDataSales($values, 'sales_products', $columns); + } + + public static function changeMarketplaceOrderStatusFrom1C($mpOrder) + { + $result = null; + if (!$mpOrder['status']) { + $result['message'] = 'Статус не передан'; + $result['status'] = 'error'; + return $result; + } + // статусы маркетплейса + $statuses = MarketplaceOrderStatusTypes::find() + ->select(['id', 'code']) + ->indexBy('code') + ->asArray() + ->all(); + $cancelledStatusId = $statuses[MarketplaceOrderStatusTypes::CANSELLED_CODE]['id']; + $readyStatusId = $statuses[MarketplaceOrderStatusTypes::READY_CODE]['id']; + $deliveredStatusId = $statuses['DELIVERED']['id']; + $status = $mpOrder['status']; + $marketplaceOrder = MarketplaceOrders::find() + ->where(['guid' => $mpOrder['id']]) + // ->andWhere(['<>', 'status_id', $cancelledStatusId]) + ->one(); + + if ($marketplaceOrder) { + /** @var $marketplaceOrder MarketplaceOrders */ + $debug = false; + if ($marketplaceOrder->fake == 1) { + $debug = true; + } + $marketplaceId = $marketplaceOrder->marketplace_id; + $cancelledStatusesCode = MarketplaceOrder1cStatuses::find() + ->select(['status_id']) + ->where(['marketplace_id' => $marketplaceId]) + ->andWhere(['order_status_id' => $cancelledStatusId]) + ->scalar(); + + $statusId1C = MarketplaceOrder1cStatuses::find() + ->where(['marketplace_id' => $marketplaceId]) + ->andWhere(['status_id' => $status]) + ->one(); + + if ($marketplaceOrder->status_id === $cancelledStatusId && $status !== $cancelledStatusesCode) { + $result['message'] = 'Заказ отменен ' . $mpOrder['id'];; + $result['status'] = 'cancelled_order'; + return $result; + } + + $statuses1cWithCancelledId = ArrayHelper::getColumn(MarketplaceOrder1cStatuses::find() + ->select(['status_id']) + ->where(['order_status_id' => $cancelledStatusId]) + ->asArray() + ->all(), 'status_id'); + $statuses1cToChangeYandexMarketFakeOrderId = ArrayHelper::getColumn(MarketplaceOrder1cStatuses::find() + ->select(['status_id']) + ->where(['order_status_id' => $cancelledStatusId]) + ->orWhere(['order_substatus_id' => $readyStatusId]) + ->andWhere(['marketplace_id' => 2]) + ->asArray() + ->all(), 'status_id'); + $statuses = ArrayHelper::map($statuses, 'code', 'id'); + $statusCodes = array_unique(array_keys($statuses)); + + + if (empty($statusId1C)) { + $mess["result"] = 'error'; + $mess["message_order"] = "Статус не найден"; + $errorJson = json_encode($mess, JSON_UNESCAPED_UNICODE); + LogService::apiLogs(1, $errorJson); + Yii::error('Ошибка: такого статуса не существует' . $status, __METHOD__); + return $errorJson; + } + + // Проверяем, если заказ уже имеет статус CANCELLED или DELIVERED, то не меняем статусы + if ($marketplaceOrder->status_id === $cancelledStatusId || $marketplaceOrder->status_id === $deliveredStatusId) { + $result['status'] = 'no_change'; + $result['message'] = 'Заказ уже имеет финальный статус (CANCELLED или DELIVERED) ' . $mpOrder['id']; + return $result; + } + + // Получаем статусы МП по статусу 1С + /** @var $status MarketplaceOrderStatusTypes */ + /** @var $substatus MarketplaceOrderStatusTypes */ + $status = $statusId1C->orderStatus; + $substatus = $statusId1C->orderSubstatus; + + if ( + in_array($statusId1C->status_id, $statuses1cToChangeYandexMarketFakeOrderId) && + $marketplaceOrder->marketplace_id == MarketplaceStore::YANDEX_WAREHOUSE_ID + ) { + if (!$debug) { + $updateResult = MarketplaceService::updateOrderStatus( + $marketplaceOrder->warehouse_guid, + $marketplaceOrder->marketplace_order_id, + $status->code, + $substatus->code + ); + if (!$updateResult && $marketplaceOrder->fake == 1) { + if ($status->id && $substatus->id) { + $marketplaceOrder->status_id = $status->id; + $marketplaceOrder->substatus_id = $substatus->id; + } + } + } + + } else { + if ($status->id && $substatus->id) { + $marketplaceOrder->status_id = $status->id; + $marketplaceOrder->substatus_id = $substatus->id; + } + } + if (in_array($statusId1C->status_id, $statuses1cWithCancelledId)) { + $marketplaceOrder->cancelled_order_source = '1c'; + $marketplaceOrder->cancelled_order_date = date('Y-m-d H:m:s'); + } + $marketplaceOrder->status_processing_1c = $statusId1C->id; + $marketplaceOrder->seller_id = $mpOrder['seller_id'] ?? null; + $marketplaceOrder->number_1c = $mpOrder['number'] ?? null; + + + if ($marketplaceOrder->save()) { + // Обновляем историю статусов + MarketplaceService::createOrUpdateStatusHistory($marketplaceOrder->id, $status->id, $substatus->id, [ + 'date' => date('Y-m-d H:i:s') + ]); + $result['status'] = 'success'; + $result['message'] = 'Статус обновлен'; + } else { + Yii::error('Ошибка сохранения: ' . Json::encode($marketplaceOrder->getErrors(), JSON_UNESCAPED_UNICODE)); + $result['status'] = 'error'; + $result['message'] = $marketplaceOrder->getErrors(); + } + } else { + $result['message'] = 'Заказ не найден ' . $mpOrder['id'];; + $result['status'] = 'not_found'; + } + + return $result; + } +} \ No newline at end of file