use yii\data\ArrayDataProvider;
use yii\db\Expression;
use yii\db\Query;
+use yii_app\helpers\DataHelper;
use yii_app\models\FlowwowOrdersForm;
+use yii_app\records\MarketplaceOrderDelivery;
+use yii_app\records\MarketplaceOrderItems;
use yii_app\records\MarketplaceOrders;
use yii_app\records\MarketplaceOrdersSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
+use yii_app\records\MarketplaceOrderStatusHistory;
+use yii_app\records\MarketplaceOrderStatusTypes;
+use yii_app\records\MarketplaceStore;
+use yii_app\records\PricesDynamic;
+use yii_app\records\Products1c;
use yii_app\services\MarketplaceService;
/**
]);
}
+ /**
+ * Создаёт тестовый заказ Flowwow с одним случайным товаром из products_1c
+ */
+ public function actionCreateTestOrder()
+ {
+ $mp = Yii::$app->request->post('marketplace', null);
+
+ $product = Products1c::find()
+ ->where(['tip' => 'products', 'type' => 'Маркетплейсы'])
+ ->orderBy('RANDOM()')
+ ->one();
+
+ if (!$product) {
+ Yii::$app->session->setFlash('error', 'Не найден ни один товар в products_1c.');
+ return $this->redirect(['index']);
+ }
+ $priceRecord = PricesDynamic::find()
+ ->where([
+ 'product_id' => $product->id,
+ 'active' => 1,
+ 'region_id' => 52,
+ ])
+ ->orderBy(['date_from' => SORT_DESC])
+ ->one();
+
+ $price = $priceRecord ? $priceRecord->price : 0;
+
+ $orderNumber = mt_rand(10_000_000, 99_999_999);
+ $now = date('Y-m-d H:i:s');
+ if ($mp == 1) {
+
+
+ $orderDetails = [
+ 'number' => $orderNumber,
+ 'date' => $now,
+ 'items' => [[
+ 'id' => $product->id,
+ 'name' => $product->name,
+ 'articule' => $product->articule,
+ 'count' => 1,
+ 'price' => $price,
+ ]],
+ 'deliverySum' => 0,
+ 'totalSum' => $price,
+ 'buyerItemsTotal' => $price,
+ 'buyerTotal' => $price,
+ 'buyerItemsTotalBeforeDiscount' => $price,
+ 'buyerTotalBeforeDiscount' => $price,
+ 'paymentType' => 'PREPAID',
+ 'paymentMethod' => 'UNKNOWN',
+ 'fake' => true,
+ ];
+
+ // 4) Создаём модель заказа
+ $m = new MarketplaceOrders();
+ $m->marketplace_order_id = (string)$orderNumber;
+ $m->marketplace_id = 1;
+ $m->marketplace_name = 'ФлауВау';
+ // Статусы PROCESSING / STARTED
+ $status = MarketplaceOrderStatusTypes::findOne(['code' => 'PROCESSING']);
+ $substatus = MarketplaceOrderStatusTypes::findOne(['code' => 'STARTED']);
+ if (!$status) {
+ $status = new MarketplaceOrderStatusTypes(['code' => 'PROCESSING']);
+ $status->save(false);
+ }
+ if (!$substatus) {
+ $substatus = new MarketplaceOrderStatusTypes(['code' => 'STARTED']);
+ $substatus->save(false);
+ }
+ $m->status_id = $status->id;
+ $m->substatus_id = $substatus->id;
+ $m->creation_date = $now;
+ $m->updated_at = $now;
+ $m->total = $orderDetails['totalSum'];
+ $m->delivery_total = $orderDetails['deliverySum'];
+ $m->buyer_total_before_discount = $orderDetails['buyerTotalBeforeDiscount'];
+ $m->tax_system = 'UNKNOWN';
+ $m->payment_type = $orderDetails['paymentType'];
+ $m->payment_method = $orderDetails['paymentMethod'];
+ $m->fake = 1;
+ $m->raw_data = json_encode($orderDetails, JSON_UNESCAPED_UNICODE);
+
+ $m->warehouse_guid = '206008';
+ $m->store_id = 4;
+ $m->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_ERP;
+ $m->guid = DataHelper::createGuidMy('08');
+
+ if ($m->save()) {
+
+ MarketplaceService::createOrUpdateStatusHistory($m->id, $status->id, $substatus->id, $orderDetails);
+ MarketplaceService::saveOrderItems($orderDetails, $m->id, $m->warehouse_guid);
+
+ Yii::$app->session->setFlash('success', "Тестовый заказ Flowwow #{$orderNumber} создан");
+ } else {
+ Yii::$app->session->setFlash(
+ 'error',
+ 'Ошибка создания тестового заказа: ' . json_encode($m->getErrors(), JSON_UNESCAPED_UNICODE)
+ );
+ }
+
+ return $this->redirect(['index']);
+ }
+ if ($mp == 2) {
+
+ $raw = [
+ "id" => $orderNumber,
+ "status" => "PROCESSING",
+ "substatus" => "STARTED",
+ "creationDate" => $now,
+ "updatedAt" => $now,
+ "currency" => "RUR",
+ "itemsTotal" => $price,
+ "deliveryTotal" => 0,
+ "buyerItemsTotal" => $price,
+ "buyerTotal" => $price,
+ "buyerItemsTotalBeforeDiscount" => $price,
+ "buyerTotalBeforeDiscount" => $price,
+ "paymentType" => "PREPAID",
+ "paymentMethod" => "YANDEX",
+ "fake" => true,
+ "items" => [
+ [
+ "id" => $product->id,
+ "offerId" => $product->articule,
+ "offerName" => "Букет из 35 тюльпанов микс",
+ "price" => $price,
+ "buyerPrice" => $price,
+ "buyerPriceBeforeDiscount" => $price,
+ "priceBeforeDiscount" => $price,
+ "count" => 1,
+ "vat" => "VAT_05",
+ "shopSku" => $product->articule,
+ "subsidy" => 1090,
+ ],
+ ],
+ "delivery" => [
+ "type" => "DELIVERY",
+ "serviceName" => "Доставка",
+ "partnerType" => "YANDEX_MARKET",
+ "address" => [
+ "country" => "Россия",
+ "postcode" => "603105",
+ "city" => "Нижний Новгород",
+ "street" => "Агрономическая улица",
+ "house" => "136",
+ "entrance" => "4",
+ "floor" => "9",
+ "apartment" => "153",
+ "gps" => ["latitude" => 56.30095, "longitude" => 44.02491],
+ ],
+ "dates" => [
+ "fromDate" => "07-03-2025",
+ "toDate" => "07-03-2025",
+ "fromTime" => "18:30:00",
+ "toTime" => "20:00:00",
+ ],
+ "courier" => [
+ "fullName" => "Русановская Есения Алексеевна",
+ "phone" => "+79587265749",
+ "phoneExt" => "91098",
+ "vehicleNumber" => "Е507ХН152",
+ "vehicleDescription" => "Chevrolet Aveo чёрный",
+ ],
+ ],
+ "buyer" => ["type" => "PERSON"],
+ "notes" => "Звоните хотя бы за час",
+ "taxSystem" => "USN_MINUS_COST",
+ "cancelRequested" => false,
+ ];
+
+ $m = new MarketplaceOrders();
+ $m->marketplace_order_id = (string)$orderNumber;
+ $m->marketplace_id = 2;
+ $m->marketplace_name = 'ЯндексМаркет';
+ $m->creation_date = date('Y-m-d H:i:s', strtotime($raw['creationDate']));
+ $m->updated_at = date('Y-m-d H:i:s', strtotime($raw['updatedAt']));
+ $m->total = $raw['buyerTotal'];
+ $m->delivery_total = $raw['deliveryTotal'];
+ $m->buyer_total_before_discount = $raw['buyerTotalBeforeDiscount'];
+ $m->tax_system = $raw['taxSystem'];
+ $m->payment_type = $raw['paymentType'];
+ $m->payment_method = $raw['paymentMethod'];
+ $m->cancel_requested = (int)$raw['cancelRequested'];
+ $m->fake = 1;
+ $m->raw_data = json_encode($raw, JSON_UNESCAPED_UNICODE);
+ $m->guid = DataHelper::createGuidMy('08');
+ $m->warehouse_guid = '109969229';
+ $m->store_id = 4;
+ // статус PROCESSING/STARTED
+ $status = MarketplaceOrderStatusTypes::findOne(['code' => 'PROCESSING'])
+ ?: (new MarketplaceOrderStatusTypes(['code' => 'PROCESSING']))->save(false) && MarketplaceOrderStatusTypes::findOne('PROCESSING');
+ $substatus = MarketplaceOrderStatusTypes::findOne(['code' => 'STARTED'])
+ ?: (new MarketplaceOrderStatusTypes(['code' => 'STARTED']))->save(false) && MarketplaceOrderStatusTypes::findOne('STARTED');
+
+ $m->status_id = $status->id;
+ $m->substatus_id = $substatus->id;
+ $m->status_1c = MarketplaceOrders::STATUSES_1C_CREATED_IN_ERP;
+
+ if (!$m->save()) {
+ Yii::$app->session->setFlash('error', 'Ошибка создания Яндекс-заказа: '
+ . json_encode($m->getErrors(), JSON_UNESCAPED_UNICODE));
+ return $this->redirect(['index']);
+ }
+
+
+ $hist = new MarketplaceOrderStatusHistory();
+ $hist->order_id = $m->id;
+ $hist->status_id = $status->id;
+ $hist->substatus_id = $substatus->id;
+ $hist->active = 1;
+ $hist->initiator = 'ERP';
+ $hist->date_from = date('Y-m-d H:i:s');
+ $hist->date_end = '2100-01-01 00:00:00';
+ $hist->save(false);
+
+ $d = $raw['delivery'];
+ $del = new MarketplaceOrderDelivery();
+ $del->order_id = $m->id;
+ $del->type = $d['type'];
+ $del->service_name = $d['serviceName'];
+ $del->partner_type = $d['partnerType'] ?? $d['deliveryPartnerType'] ?? null;
+
+ $addr = $d['address'];
+ $del->country = $addr['country'];
+ $del->postcode = $addr['postcode'] ?? null;
+ $del->city = $addr['city'];
+ $del->street = $addr['street'];
+ $del->house = $addr['house'];
+ $del->apartment = $addr['apartment'] ?? null;
+ $del->latitude = $addr['gps']['latitude'] ?? null;
+ $del->longitude = $addr['gps']['longitude'] ?? null;
+
+ $del->delivery_start = date('Y-m-d H:i:s', strtotime("{$d['dates']['fromDate']} {$d['dates']['fromTime']}"));
+ $del->delivery_end = date('Y-m-d H:i:s', strtotime("{$d['dates']['toDate']} {$d['dates']['toTime']}"));
+
+ $cour = $d['courier'];
+ $del->courier_full_name = $cour['fullName'];
+ $del->courier_phone = $cour['phone'];
+ $del->courier_extension = $cour['phoneExt'] ?? $cour['phoneExtension'] ?? null;
+ $del->courier_vehicle_number = $cour['vehicleNumber'];
+ $del->courier_vehicle_description = $cour['vehicleDescription'];
+ $del->save();
+
+
+ foreach ($raw['items'] as $it) {
+ $oi = new MarketplaceOrderItems();
+ $oi->order_id = $m->id;
+ $oi->external_item_id = (int)$it['id'];
+ $oi->offer_id = $it['offerId'];
+ $oi->offer_name = $it['offerName'];
+ $oi->price = $it['price'];
+ $oi->buyer_price = $it['buyerPrice'];
+ $oi->buyer_price_before_discount = $it['buyerPriceBeforeDiscount'];
+ $oi->price_before_discount = $it['priceBeforeDiscount'];
+ $oi->count = $it['count'];
+ $oi->vat = $it['vat'];
+ $oi->shop_sku = $it['shopSku'];
+ $oi->subsidy = $it['subsidy'] ?? 0;
+ $oi->partner_warehouse_id = $m->warehouse_guid;
+ $oi->promos = null;
+ $oi->subsidies = null;
+ if (!$oi->save())
+ {
+ Yii::error('Ошибка сохранения' . json_encode($oi->getErrors(), JSON_UNESCAPED_UNICODE), 'Не выбран маркетплейс.');
+ }
+
+ }
+
+ Yii::$app->session->setFlash('success', "Тестовый заказ Яндекс.Маркет #{$orderNumber} создан");
+ return $this->redirect(['index']);
+ }
+
+ Yii::$app->session->setFlash('warning', 'Не выбран маркетплейс.');
+ return $this->redirect(['index']);
+
+ }
+
/**
* Displays a single MarketplaceOrders model.
* @param int $id ID заказа