]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Изменение таблиц и добавление элементов и доставок
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 20 Feb 2025 09:49:52 +0000 (12:49 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 20 Feb 2025 09:49:52 +0000 (12:49 +0300)
20 files changed:
erp24/api2/controllers/YandexMarketController.php
erp24/controllers/MarketplaceOrderItemsController.php [new file with mode: 0644]
erp24/migrations/m250219_062708_create_marketplace_orders_table.php
erp24/migrations/m250219_081610_create_marketplace_order_status_types_table.php
erp24/migrations/m250219_081716_create_marketplace_order_status_history_table.php
erp24/migrations/m250219_082141_create_marketplace_order_delivery_table.php
erp24/migrations/m250220_084832_create_marketplace_order_items_table.php [new file with mode: 0644]
erp24/records/MarketplaceOrderDelivery.php
erp24/records/MarketplaceOrderItems.php [new file with mode: 0644]
erp24/records/MarketplaceOrderItemsSearch.php [new file with mode: 0644]
erp24/records/MarketplaceOrderStatusHistory.php
erp24/records/MarketplaceOrderStatusTypes.php
erp24/records/MarketplaceOrders.php
erp24/records/MarketplaceOrdersSearch.php
erp24/views/marketplace-order-items/_search.php [new file with mode: 0644]
erp24/views/marketplace-order-items/index.php [new file with mode: 0644]
erp24/views/marketplace-order-items/view.php [new file with mode: 0644]
erp24/views/marketplace-orders/_search.php
erp24/views/marketplace-orders/index.php
erp24/views/marketplace-orders/view.php

index a065e0f4e8518322ad760851d05cd2c1981346f8..760c07964b899baca6c589c9816f489039360ac8 100644 (file)
@@ -10,6 +10,8 @@ use OpenAPI\Client\Api;
 use OpenAPI\Client\Model;
 use GuzzleHttp;
 use yii\web\Response;
+use yii_app\records\MarketplaceOrderDelivery;
+use yii_app\records\MarketplaceOrderItems;
 use yii_app\records\MarketplaceOrders;
 use yii_app\records\MarketplaceOrderStatusHistory;
 use yii_app\records\MarketplaceOrderStatusTypes;
@@ -183,7 +185,7 @@ class YandexMarketController extends Controller
             ->select(['warehouse_guid'])
             ->where(['warehouse_id' => 2])
             ->column();
-        
+
         $statuses = MarketplaceOrderStatusTypes::find()
             ->select(['id', 'code'])
             ->indexBy('code')
@@ -191,7 +193,7 @@ class YandexMarketController extends Controller
 
         $statuses = ArrayHelper::map($statuses, 'code', 'id');
         $statusCodes = array_unique(array_keys($statuses));
-       // var_dump($statusCodes);die();
+        // var_dump($statusCodes);die();
 
 
         $apiInstance = new Api\OrdersApi(new GuzzleHttp\Client(), $config);
@@ -206,10 +208,9 @@ class YandexMarketController extends Controller
 
             $orders = $result[0]->getOrders();
             foreach ($orders as $order) {
-              //  var_dump($statusCodes);die();
-                // Установка и сохранение статусов
                 $status = $statuses[$order->getStatus()] ?? null;
                 $substatus = $statuses[$order->getSubstatus()] ?? null;
+
                 if (!in_array($order->getStatus(), $statusCodes)) {
                     $newStatus = new MarketplaceOrderStatusTypes();
                     $newStatus->code = $order->getStatus();
@@ -218,61 +219,39 @@ class YandexMarketController extends Controller
                         $statusCodes[] = $order->getStatus();
                         $statuses[$order->getStatus()] = $newStatus->id;
                     } else {
-                        Yii::error('Ошибка сохранения' . json_encode($newStatus->getErrors(), JSON_UNESCAPED_UNICODE));
+                        Yii::error(
+                            'Ошибка сохранения статуса: ' . json_encode($newStatus->getErrors(), JSON_UNESCAPED_UNICODE)
+                        );
                     }
                 }
+
                 if (!in_array($order->getSubstatus(), $statusCodes)) {
                     $newSubstatus = new MarketplaceOrderStatusTypes();
                     $newSubstatus->code = $order->getSubstatus();
                     if ($newSubstatus->save()) {
                         $substatus = $newSubstatus->id;
                         $statusCodes[] = $order->getSubstatus();
-                        $statuses[$order->getSubstatus()] = $newStatus->id;
+                        $statuses[$order->getSubstatus()] = $newSubstatus->id;
                     } else {
-                        Yii::error('Ошибка сохранения' . json_encode($newSubstatus->getErrors(), JSON_UNESCAPED_UNICODE));
+                        Yii::error(
+                            'Ошибка сохранения подстатуса: ' . json_encode(
+                                $newSubstatus->getErrors(),
+                                JSON_UNESCAPED_UNICODE
+                            )
+                        );
                     }
                 }
-                $marketplaceOrder = MarketplaceOrders::find()->where(['marketplace_id' => (string)$order->getId()])->one();
-                
-                if (!empty($marketplaceOrder)) {
-                    $statusHistoryRecord = MarketplaceOrderStatusHistory::find()
-                        ->where(['id' => $marketplaceOrder->status_history_id])
-                        ->one();
-                    if(!empty($statusHistoryRecord) && ($statusHistoryRecord->status_id !== $status || $statusHistoryRecord->substatus_id !== $substatus)) {
-                        $statusHistoryRecord->active = 0;
-                        $statusHistoryRecord->date_to = date();
-                        $statusHistoryRecord->save();
 
-                        $newStatusHistoryRecord = new MarketplaceOrderStatusHistory();
-                        $newStatusHistoryRecord->order_id = $marketplaceOrder->id;
-                        $newStatusHistoryRecord->status_id = (int)$status;
-                        $newStatusHistoryRecord->substatus_id = (int)$substatus;
-                        $newStatusHistoryRecord->active = 1;
-                        $newStatusHistoryRecord->initiator = "ERP";
-                        $newStatusHistoryRecord->date_from = date();
-                        $newStatusHistoryRecord->date_end = date('Y-m-d H:i:s',strtotime("2100-01-01"));
-                        if (!$newStatusHistoryRecord->save()) {
-                            Yii::error('Ошибка сохранения' . json_encode($newStatusHistoryRecord->getErrors(), JSON_UNESCAPED_UNICODE));
-                        } else {
-                            $marketplaceOrder->status_history_id = $newStatusHistoryRecord->id;
-                        }
-                        }
-                } else {
+                $newRawData = json_encode($order);
+                $marketplaceOrder = MarketplaceOrders::find()
+                    ->where(['marketplace_order_id' => (string)$order->getId()])
+                    ->one();
+
+                if (!$marketplaceOrder) {
                     $marketplaceOrder = new MarketplaceOrders();
-                    $marketplaceOrder->marketplace_id = (string)$order->getId();
-                    //var_dump((int)$order->getCancelRequested()); die();
-                    $creationDate = strtotime($order->getCreationDate());
-                    if ($creationDate !== false) {
-                        $marketplaceOrder->creation_date = date('Y-m-d H:i:s', $creationDate);
-                    } else {
-                        Yii::error("Неверный формат даты: " . $order->getCreationDate());
-                    }
-                    $updatedAt = strtotime($order->getUpdatedAt());
-                    if ($updatedAt !== false) {
-                        $marketplaceOrder->updated_at = date('Y-m-d H:i:s', $updatedAt);
-                    } else {
-                        Yii::error("Неверный формат даты: " . $order->getUpdatedAt());
-                    }
+                    $marketplaceOrder->marketplace_order_id = (string)$order->getId();
+                    $marketplaceOrder->creation_date = date('Y-m-d H:i:s', strtotime($order->getCreationDate()));
+                    $marketplaceOrder->updated_at = date('Y-m-d H:i:s', strtotime($order->getUpdatedAt()));
                     $marketplaceOrder->total = $order->getBuyerTotal();
                     $marketplaceOrder->delivery_total = $order->getDeliveryTotal();
                     $marketplaceOrder->buyer_total_before_discount = $order->getBuyerTotalBeforeDiscount();
@@ -280,16 +259,17 @@ class YandexMarketController extends Controller
                     $marketplaceOrder->payment_type = $order->getPaymentType();
                     $marketplaceOrder->payment_method = $order->getPaymentMethod();
                     $marketplaceOrder->cancel_requested = (int)$order->getCancelRequested();
-                    $marketplaceOrder->store_id = (string)$campaignId;
-                    $marketplaceOrder->raw_data = json_encode($order);
 
-                    if (!$marketplaceOrder->save()) {
-                        Yii::error(
-                            "Ошибка сохранения заказа с marketplace_id: " . $order->getId() . ". Ошибки: " . json_encode(
-                                $marketplaceOrder->getErrors(), JSON_UNESCAPED_UNICODE
-                            )
-                        );
-                    } else {
+                    $warehouseGuid = (string)$campaignId;
+                    $store = MarketplaceStore::findOne(['warehouse_guid' => $warehouseGuid]);
+                    $marketplaceOrder->store_id = $store ? $store->store_id : null;
+                    $marketplaceOrder->warehouse_guid = $warehouseGuid;
+
+                    $marketplaceOrder->status_id = (int)$status;
+                    $marketplaceOrder->substatus_id = (int)$substatus;
+                    $marketplaceOrder->raw_data = $newRawData;
+
+                    if ($marketplaceOrder->save()) {
                         $newStatusHistoryRecord = new MarketplaceOrderStatusHistory();
                         $newStatusHistoryRecord->order_id = $marketplaceOrder->id;
                         $newStatusHistoryRecord->status_id = (int)$status;
@@ -297,19 +277,253 @@ class YandexMarketController extends Controller
                         $newStatusHistoryRecord->active = 1;
                         $newStatusHistoryRecord->initiator = "ERP";
                         $newStatusHistoryRecord->date_from = date('Y-m-d H:i:s');
-                        $newStatusHistoryRecord->date_end = date('Y-m-d H:i:s',strtotime("2100-01-01"));
+                        $newStatusHistoryRecord->date_end = '2100-01-01 00:00:00';
+
                         if (!$newStatusHistoryRecord->save()) {
-                            Yii::error('Ошибка сохранения' . json_encode($newStatusHistoryRecord->getErrors(), JSON_UNESCAPED_UNICODE));
-                        } else {
-                            $marketplaceOrder->status_history_id = $newStatusHistoryRecord->id;
-                            if (!$marketplaceOrder->save()) {
+                            Yii::error(
+                                'Ошибка сохранения истории: ' . json_encode(
+                                    $newStatusHistoryRecord->getErrors(),
+                                    JSON_UNESCAPED_UNICODE
+                                )
+                            );
+                        }
+
+
+                        $delivery = $order->getDelivery();
+                        if ($delivery) {
+                            $deliveryModel = new MarketplaceOrderDelivery();
+                            $deliveryModel->order_id = $marketplaceOrder->id;
+                            $deliveryModel->type = $delivery->getType();
+                            $deliveryModel->service_name = $delivery->getServiceName();
+                            $deliveryModel->partner_type = $delivery->getDeliveryPartnerType();
+
+                            $address = $delivery->getAddress();
+                            if ($address) {
+                                $deliveryModel->country = $address->getCountry();
+                                $deliveryModel->postcode = $address->getPostcode();
+                                $deliveryModel->city = $address->getCity();
+                                $deliveryModel->street = $address->getStreet();
+                                $deliveryModel->house = $address->getHouse();
+                                $deliveryModel->apartment = $address->getApartment();
+                                $deliveryModel->latitude = $address->getGps()->getLatitude();
+                                $deliveryModel->longitude = $address->getGps()->getLongitude();
+                            }
+
+                            $dates = $delivery->getDates();
+                            if ($dates) {
+                                $deliveryModel->delivery_start = date(
+                                    'Y-m-d H:i:s',
+                                    strtotime($dates->getFromDate() . ' ' . $dates->getFromTime())
+                                );
+                                $deliveryModel->delivery_end = date(
+                                    'Y-m-d H:i:s',
+                                    strtotime($dates->getToDate() . ' ' . $dates->getToTime())
+                                );
+                            }
+
+                            $courier = $delivery->getCourier();
+                            if ($courier) {
+                                $deliveryModel->courier_full_name = $courier->getFullName();
+                                $deliveryModel->courier_phone = $courier->getPhone();
+                                $deliveryModel->courier_extension = $courier->getPhoneExtension();
+                                $deliveryModel->courier_vehicle_number = $courier->getVehicleNumber();
+                                $deliveryModel->courier_vehicle_description = $courier->getVehicleDescription();
+                            }
+
+                            if (!$deliveryModel->save()) {
                                 Yii::error(
-                                    "Ошибка сохранения заказа с marketplace_id: " . $order->getId() . ". Ошибки: " . json_encode(
-                                        $marketplaceOrder->getErrors(), JSON_UNESCAPED_UNICODE
+                                    'Ошибка сохранения доставки: ' . json_encode(
+                                        $deliveryModel->getErrors(),
+                                        JSON_UNESCAPED_UNICODE
                                     )
                                 );
                             }
                         }
+
+                        $items = $order->getItems();
+                        if (!empty($items)) {
+                            foreach ($items as $item) {
+                                $orderItem = new MarketplaceOrderItems();
+                                $orderItem->order_id = $marketplaceOrder->id;
+                                $orderItem->external_item_id = $item->getId();
+                                $orderItem->offer_id = $item->getOfferId();
+                                $orderItem->offer_name = $item->getOfferName();
+                                $orderItem->price = $item->getPrice();
+                                $orderItem->buyer_price = $item->getBuyerPrice();
+                                $orderItem->buyer_price_before_discount = $item->getBuyerPriceBeforeDiscount();
+                                $orderItem->price_before_discount = $item->getPriceBeforeDiscount();
+                                $orderItem->count = $item->getCount();
+                                $orderItem->vat = $item->getVat();
+                                $orderItem->shop_sku = $item->getShopSku();
+                                $orderItem->subsidy = $item->getSubsidy();
+                                $orderItem->partner_warehouse_id = $item->getPartnerWarehouseId();
+                                $orderItem->promos = json_encode($item->getPromos());
+                                $orderItem->subsidies = json_encode($item->getSubsidies());
+
+                                if (!$orderItem->save()) {
+                                    Yii::error(
+                                        'Ошибка сохранения элемента заказа: ' . json_encode(
+                                            $orderItem->getErrors(),
+                                            JSON_UNESCAPED_UNICODE
+                                        )
+                                    );
+                                }
+                            }
+                        }
+                    } else {
+                        Yii::error(
+                            'Ошибка сохранения заказа: ' . json_encode(
+                                $marketplaceOrder->getErrors(),
+                                JSON_UNESCAPED_UNICODE
+                            )
+                        );
+                    }
+                } else {
+                    if ($newRawData !== $marketplaceOrder->raw_data) {
+                        $marketplaceOrder->updated_at = date('Y-m-d H:i:s', strtotime($order->getUpdatedAt()));
+                        $marketplaceOrder->total = $order->getBuyerTotal();
+                        $marketplaceOrder->delivery_total = $order->getDeliveryTotal();
+                        $marketplaceOrder->buyer_total_before_discount = $order->getBuyerTotalBeforeDiscount();
+                        $marketplaceOrder->tax_system = $order->getTaxSystem();
+                        $marketplaceOrder->payment_type = $order->getPaymentType();
+                        $marketplaceOrder->payment_method = $order->getPaymentMethod();
+                        $marketplaceOrder->cancel_requested = (int)$order->getCancelRequested();
+                        $marketplaceOrder->raw_data = $newRawData;
+
+                        $statusHistoryRecord = MarketplaceOrderStatusHistory::find()
+                            ->where(['order_id' => $marketplaceOrder->id])
+                            ->one();
+                        if (
+                            (!empty($statusHistoryRecord)) &&
+                            ($statusHistoryRecord->status_id !== $status
+                                || $statusHistoryRecord->substatus_id !== $substatus)
+                        ) {
+                            $statusHistoryRecord->active = 0;
+                            $statusHistoryRecord->date_to = date();
+                            $statusHistoryRecord->save();
+
+                            $newStatusHistoryRecord = new MarketplaceOrderStatusHistory();
+                            $newStatusHistoryRecord->order_id = $marketplaceOrder->id;
+                            $newStatusHistoryRecord->status_id = (int)$status;
+                            $newStatusHistoryRecord->substatus_id = (int)$substatus;
+                            $newStatusHistoryRecord->active = 1;
+                            $newStatusHistoryRecord->initiator = "ERP";
+                            $newStatusHistoryRecord->date_from = date('Y-m-d H:i:s');
+                            $newStatusHistoryRecord->date_end = date('Y-m-d H:i:s', strtotime("2100-01-01"));
+                            if (!$newStatusHistoryRecord->save()) {
+                                Yii::error(
+                                    'Ошибка сохранения' . json_encode(
+                                        $newStatusHistoryRecord->getErrors(),
+                                        JSON_UNESCAPED_UNICODE
+                                    )
+                                );
+                            }
+                        }
+                        $marketplaceOrder->status_id = (int)$status;
+                        $marketplaceOrder->substatus_id = (int)$substatus;
+                        $marketplaceOrder->updated_at = date('Y-m-d H:i:s', strtotime($order->getUpdatedAt()));
+                        $marketplaceOrder->save();
+
+                        $newItems = $order->getItems();
+                        $existingItems = MarketplaceOrderItems::find()->where(['order_id' => $marketplaceOrder->id])
+                            ->all();
+
+                        if (count($existingItems) !== count($newItems)) {
+                            MarketplaceOrderItems::deleteAll(['order_id' => $marketplaceOrder->id]);
+                            foreach ($newItems as $item) {
+                                $orderItem = new MarketplaceOrderItems();
+                                $orderItem->order_id = $marketplaceOrder->id;
+                                $orderItem->external_item_id = $item->getId();
+                                $orderItem->offer_id = $item->getOfferId();
+                                $orderItem->offer_name = $item->getOfferName();
+                                $orderItem->price = $item->getPrice();
+                                $orderItem->buyer_price = $item->getBuyerPrice();
+                                $orderItem->buyer_price_before_discount = $item->getBuyerPriceBeforeDiscount();
+                                $orderItem->price_before_discount = $item->getPriceBeforeDiscount();
+                                $orderItem->count = $item->getCount();
+                                $orderItem->vat = $item->getVat();
+                                $orderItem->shop_sku = $item->getShopSku();
+                                $orderItem->subsidy = $item->getSubsidy();
+                                $orderItem->partner_warehouse_id = $item->getPartnerWarehouseId();
+                                $orderItem->promos = json_encode($item->getPromos());
+                                $orderItem->subsidies = json_encode($item->getSubsidies());
+
+                                if (!$orderItem->save()) {
+                                    Yii::error(
+                                        'Ошибка сохранения элемента заказа: ' . json_encode(
+                                            $orderItem->getErrors(),
+                                            JSON_UNESCAPED_UNICODE
+                                        )
+                                    );
+                                }
+                            }
+                        } else {
+                            foreach ($newItems as $item) {
+                                $orderItem = MarketplaceOrderItems::findOne([
+                                    'order_id' => $marketplaceOrder->id,
+                                    'external_item_id' => $item->getId()
+                                ]);
+                                if ($orderItem) {
+                                    $updateNeeded = false;
+                                    $fields = [
+                                        'offer_id' => $item->getOfferId(),
+                                        'offer_name' => $item->getOfferName(),
+                                        'price' => $item->getPrice(),
+                                        'buyer_price' => $item->getBuyerPrice(),
+                                        'buyer_price_before_discount' => $item->getBuyerPriceBeforeDiscount(),
+                                        'price_before_discount' => $item->getPriceBeforeDiscount(),
+                                        'count' => $item->getCount(),
+                                        'vat' => $item->getVat(),
+                                        'shop_sku' => $item->getShopSku(),
+                                        'subsidy' => $item->getSubsidy(),
+                                        'partner_warehouse_id' => $item->getPartnerWarehouseId(),
+                                        'promos' => json_encode($item->getPromos()),
+                                        'subsidies' => json_encode($item->getSubsidies()),
+                                    ];
+
+                                    foreach ($fields as $attr => $value) {
+                                        if ($orderItem->$attr != $value) {
+                                            $orderItem->$attr = $value;
+                                            $updateNeeded = true;
+                                        }
+                                    }
+                                    if ($updateNeeded && !$orderItem->save()) {
+                                        Yii::error(
+                                            'Ошибка обновления элемента заказа: ' . json_encode(
+                                                $orderItem->getErrors(),
+                                                JSON_UNESCAPED_UNICODE
+                                            )
+                                        );
+                                    }
+                                } else {
+                                    $orderItem = new MarketplaceOrderItems();
+                                    $orderItem->order_id = $marketplaceOrder->id;
+                                    $orderItem->external_item_id = $item->getId();
+                                    $orderItem->offer_id = $item->getOfferId();
+                                    $orderItem->offer_name = $item->getOfferName();
+                                    $orderItem->price = $item->getPrice();
+                                    $orderItem->buyer_price = $item->getBuyerPrice();
+                                    $orderItem->buyer_price_before_discount = $item->getBuyerPriceBeforeDiscount();
+                                    $orderItem->price_before_discount = $item->getPriceBeforeDiscount();
+                                    $orderItem->count = $item->getCount();
+                                    $orderItem->vat = $item->getVat();
+                                    $orderItem->shop_sku = $item->getShopSku();
+                                    $orderItem->subsidy = $item->getSubsidy();
+                                    $orderItem->partner_warehouse_id = $item->getPartnerWarehouseId();
+                                    $orderItem->promos = json_encode($item->getPromos());
+                                    $orderItem->subsidies = json_encode($item->getSubsidies());
+
+                                    if (!$orderItem->save()) {
+                                        Yii::error(
+                                            'Ошибка сохранения нового элемента заказа: ' . json_encode(
+                                                $orderItem->getErrors(),
+                                                JSON_UNESCAPED_UNICODE
+                                            )
+                                        );
+                                    }
+                                }
+                            }
+                        }
                     }
                 }
             }
diff --git a/erp24/controllers/MarketplaceOrderItemsController.php b/erp24/controllers/MarketplaceOrderItemsController.php
new file mode 100644 (file)
index 0000000..d9ff24f
--- /dev/null
@@ -0,0 +1,134 @@
+<?php
+
+namespace app\controllers;
+
+use yii_app\records\MarketplaceOrderItems;
+use yii_app\records\MarketplaceOrderItemsSearch;
+use yii\web\Controller;
+use yii\web\NotFoundHttpException;
+use yii\filters\VerbFilter;
+
+/**
+ * MarketplaceOrderItemsController implements the CRUD actions for MarketplaceOrderItems model.
+ */
+class MarketplaceOrderItemsController extends Controller
+{
+    /**
+     * @inheritDoc
+     */
+    public function behaviors()
+    {
+        return array_merge(
+            parent::behaviors(),
+            [
+                'verbs' => [
+                    'class' => VerbFilter::className(),
+                    'actions' => [
+                        'delete' => ['POST'],
+                    ],
+                ],
+            ]
+        );
+    }
+
+    /**
+     * Lists all MarketplaceOrderItems models.
+     *
+     * @return string
+     */
+    public function actionIndex()
+    {
+        $searchModel = new MarketplaceOrderItemsSearch();
+        $dataProvider = $searchModel->search($this->request->queryParams);
+
+        return $this->render('index', [
+            'searchModel' => $searchModel,
+            'dataProvider' => $dataProvider,
+        ]);
+    }
+
+    /**
+     * Displays a single MarketplaceOrderItems model.
+     * @param int $id ID
+     * @return string
+     * @throws NotFoundHttpException if the model cannot be found
+     */
+    public function actionView($id)
+    {
+        return $this->render('view', [
+            'model' => $this->findModel($id),
+        ]);
+    }
+
+    /**
+     * Creates a new MarketplaceOrderItems model.
+     * If creation is successful, the browser will be redirected to the 'view' page.
+     * @return string|\yii\web\Response
+     */
+    public function actionCreate()
+    {
+        $model = new MarketplaceOrderItems();
+
+        if ($this->request->isPost) {
+            if ($model->load($this->request->post()) && $model->save()) {
+                return $this->redirect(['view', 'id' => $model->id]);
+            }
+        } else {
+            $model->loadDefaultValues();
+        }
+
+        return $this->render('create', [
+            'model' => $model,
+        ]);
+    }
+
+    /**
+     * Updates an existing MarketplaceOrderItems model.
+     * If update is successful, the browser will be redirected to the 'view' page.
+     * @param int $id ID
+     * @return string|\yii\web\Response
+     * @throws NotFoundHttpException if the model cannot be found
+     */
+    public function actionUpdate($id)
+    {
+        $model = $this->findModel($id);
+
+        if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
+            return $this->redirect(['view', 'id' => $model->id]);
+        }
+
+        return $this->render('update', [
+            'model' => $model,
+        ]);
+    }
+
+    /**
+     * Deletes an existing MarketplaceOrderItems model.
+     * If deletion is successful, the browser will be redirected to the 'index' page.
+     * @param int $id ID
+     * @return \yii\web\Response
+     * @throws NotFoundHttpException if the model cannot be found
+     */
+    public function actionDelete($id)
+    {
+        $this->findModel($id)->delete();
+
+        return $this->redirect(['index']);
+    }
+
+    /**
+     * Finds the MarketplaceOrderItems model based on its primary key value.
+     * If the model is not found, a 404 HTTP exception will be thrown.
+     * @param int $id ID
+     * @return MarketplaceOrderItems the loaded model
+     * @throws NotFoundHttpException if the model cannot be found
+     */
+    protected function findModel($id)
+    {
+        if (($model = MarketplaceOrderItems::findOne(['id' => $id])) !== null) {
+            return $model;
+        }
+
+        throw new NotFoundHttpException('The requested page does not exist.');
+    }
+}
index a54bd4f4f6e062ae4e5f7b75727bd7e6dcd9d28e..f99e930735a8bf020041f0716f63a24da9a48be1 100644 (file)
@@ -17,9 +17,13 @@ class m250219_062708_create_marketplace_orders_table extends Migration
         if (!isset($tableSchema)) {
             $this->createTable(self::TABLE_NAME, [
                 'id' => $this->bigPrimaryKey()->comment('ID заказа'),
-                'marketplace_id' => $this->string(64)->notNull()->unique()->comment('ID заказа в системе маркетплейса'),
-                'store_id' => $this->string(36)->comment('Идентификатор склада/магазина'),
-                'status_history_id' => $this->bigInteger()->comment('Ссылка на текущий активный статус'),
+                'marketplace_order_id' => $this->string(64)->notNull()
+                    ->unique()
+                    ->comment('ID заказа в системе маркетплейса'),
+                'store_id' => $this->integer()->comment('Идентификатор магазина'),
+                'status_id' => $this->integer()->notNull()->comment('Ссылка на тип статуса'),
+                'substatus_id' => $this->integer()->notNull()->comment('Ссылка на подстатус'),
+                'warehouse_guid' => $this->string(36)->comment('Идентификатор магазина'),
                 'creation_date' => $this->dateTime()->notNull()->comment('Дата создания заказа'),
                 'updated_at' => $this->dateTime()->notNull()->comment('Время последнего обновления'),
                 'total' => $this->decimal(15, 2)->notNull()->comment('Итоговая сумма к оплате'),
index 7ed87fb106d793491c7204f9d02588ace354782f..f62aff5582648eadc5e4f467b9aa21dc121cdf43 100644 (file)
@@ -15,7 +15,7 @@ class m250219_081610_create_marketplace_order_status_types_table extends Migrati
         if (!isset($tableSchema)) {
             $this->createTable(self::TABLE_NAME, [
                 'id' => $this->primaryKey()->comment('ID статуса'),
-                'code' => $this->string(64)->notNull()->comment('Код статуса'),
+                'code' => $this->string(64)->notNull()->unique()->comment('Код статуса'),
                 'name' => $this->string(255)->null()->comment('Название статуса'),
                 'description' => $this->string()->null()->comment('Описание статуса'),
             ]);
index 664e9d390098b3d75867d4693d65cef91b3d41b7..96b495f01bada82ed3e5c060bc8893cd5b6f4e0b 100644 (file)
@@ -23,36 +23,6 @@ class m250219_081716_create_marketplace_order_status_history_table extends Migra
                 'date_end' => $this->dateTime()->null()->comment('Дата и время окончания активности'),
                 'initiator' => $this->text()->comment('Инициатор изменения'),
             ]);
-
-            $this->addForeignKey(
-                'fk_order_status_history_order',
-                self::TABLE_NAME,
-                'order_id',
-                'marketplace_orders',
-                'id',
-                'SET NULL',
-                'CASCADE'
-            );
-
-            $this->addForeignKey(
-                'fk_order_status_history_status',
-                self::TABLE_NAME,
-                'status_id',
-                'marketplace_order_status_types',
-                'id',
-                'RESTRICT',
-                'CASCADE'
-            );
-
-            $this->addForeignKey(
-                'fk_order_status_history_substatus',
-                self::TABLE_NAME,
-                'substatus_id',
-                'marketplace_order_status_types',
-                'id',
-                'SET NULL',
-                'CASCADE'
-            );
         }
     }
 
index 6c1e0f1845075d564ad7c4bb415678bdc75e6b57..cd4547f8e430ecd79f835d850297bba200515c61 100644 (file)
@@ -20,7 +20,7 @@ class m250219_082141_create_marketplace_order_delivery_table extends Migration
                 'service_name' => $this->string(64)->notNull()->comment('Название службы доставки'),
                 'partner_type' => $this->string(32)->notNull()->comment('Тип партнера доставки'),
                 'country' => $this->string(64)->notNull()->comment('Страна'),
-                'postcode' => $this->string(16)->notNull()->comment('Индекс'),
+                'postcode' => $this->string(16)->null()->comment('Индекс'),
                 'city' => $this->string(128)->notNull()->comment('Город'),
                 'street' => $this->string(255)->notNull()->comment('Улица'),
                 'house' => $this->string(16)->notNull()->comment('Дом'),
@@ -35,16 +35,6 @@ class m250219_082141_create_marketplace_order_delivery_table extends Migration
                 'courier_vehicle_number' => $this->string(32)->null()->comment('Номер автомобиля курьера'),
                 'courier_vehicle_description' => $this->string(255)->null()->comment('Описание автомобиля курьера'),
             ]);
-
-            $this->addForeignKey(
-                'fk_order_delivery_order',
-                self::TABLE_NAME,
-                'order_id',
-                'marketplace_orders',
-                'id',
-                'SET NULL',
-                'CASCADE'
-            );
         }
     }
 
diff --git a/erp24/migrations/m250220_084832_create_marketplace_order_items_table.php b/erp24/migrations/m250220_084832_create_marketplace_order_items_table.php
new file mode 100644 (file)
index 0000000..f8c3827
--- /dev/null
@@ -0,0 +1,50 @@
+<?php
+
+use yii\db\Migration;
+
+/**
+ * Handles the creation of table `{{%marketplace_order_items}}`.
+ */
+class m250220_084832_create_marketplace_order_items_table extends Migration
+{
+    const TABLE_NAME = 'erp24.marketplace_order_items';
+    /**
+     * {@inheritdoc}
+     */
+    public function safeUp()
+    {
+        $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+        if (!isset($tableSchema)) {
+            $this->createTable(self::TABLE_NAME, [
+            'id' => $this->primaryKey(),
+            'order_id' => $this->integer()->notNull()->comment('Ссылка на заказ'),
+            'external_item_id' => $this->bigInteger()->notNull()->comment('ID элемента заказа из API'),
+            'offer_id' => $this->string(64)->notNull()->comment('ID предложения'),
+            'offer_name' => $this->string()->notNull()->comment('Название предложения'),
+            'price' => $this->decimal(10, 2)->notNull()->comment('Цена'),
+            'buyer_price' => $this->decimal(10, 2)->notNull()->comment('Цена для покупателя'),
+            'buyer_price_before_discount' => $this->decimal(10, 2)->notNull()->comment('Цена для покупателя до скидки'),
+            'price_before_discount' => $this->decimal(10, 2)->notNull()->comment('Цена до скидки'),
+            'count' => $this->integer()->notNull()->comment('Количество'),
+            'vat' => $this->string(32)->notNull()->comment('НДС'),
+            'shop_sku' => $this->string(64)->notNull()->comment('SKU магазина'),
+            'subsidy' => $this->decimal(10, 2)->notNull()->comment('Субсидия'),
+            'partner_warehouse_id' => $this->string(64)->notNull()->comment('ID склада партнёра'),
+            'promos' => $this->text()->comment('Промо скидки в формате JSON'),
+            'subsidies' => $this->text()->comment('Субсидии в формате JSON'),
+            ]);
+        }
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function safeDown()
+    {
+        $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+
+        if (isset($tableSchema)) {
+            $this->dropTable(self::TABLE_NAME);
+        }
+    }
+}
index 2562101ce5c49a6a07acd3fc9f1522964a8de685..06061e12fcb8f86f4829847e2d10877123a32c30 100644 (file)
@@ -13,7 +13,7 @@ use Yii;
  * @property string $service_name Название службы доставки
  * @property string $partner_type Тип партнера доставки
  * @property string $country Страна
- * @property string $postcode Индекс
+ * @property string|null $postcode Индекс
  * @property string $city Город
  * @property string $street Улица
  * @property string $house Дом
@@ -27,8 +27,6 @@ use Yii;
  * @property string|null $courier_extension Дополнительный номер курьера
  * @property string|null $courier_vehicle_number Номер автомобиля курьера
  * @property string|null $courier_vehicle_description Описание автомобиля курьера
- *
- * @property MarketplaceOrders $order
  */
 class MarketplaceOrderDelivery extends \yii\db\ActiveRecord
 {
@@ -48,8 +46,8 @@ class MarketplaceOrderDelivery extends \yii\db\ActiveRecord
     public function rules()
     {
         return [
-            [['apartment', 'delivery_start', 'delivery_end', 'courier_full_name', 'courier_phone', 'courier_extension', 'courier_vehicle_number', 'courier_vehicle_description'], 'default', 'value' => null],
-            [['order_id', 'type', 'service_name', 'partner_type', 'country', 'postcode', 'city', 'street', 'house', 'latitude', 'longitude'], 'required'],
+            [['postcode', 'apartment', 'delivery_start', 'delivery_end', 'courier_full_name', 'courier_phone', 'courier_extension', 'courier_vehicle_number', 'courier_vehicle_description'], 'default', 'value' => null],
+            [['order_id', 'type', 'service_name', 'partner_type', 'country', 'city', 'street', 'house', 'latitude', 'longitude'], 'required'],
             [['order_id'], 'default', 'value' => null],
             [['order_id'], 'integer'],
             [['latitude', 'longitude'], 'number'],
@@ -59,7 +57,6 @@ class MarketplaceOrderDelivery extends \yii\db\ActiveRecord
             [['postcode', 'house', 'apartment', 'courier_extension'], 'string', 'max' => 16],
             [['city'], 'string', 'max' => 128],
             [['street', 'courier_full_name', 'courier_vehicle_description'], 'string', 'max' => 255],
-            [['order_id'], 'exist', 'skipOnError' => true, 'targetClass' => MarketplaceOrders::class, 'targetAttribute' => ['order_id' => 'id']],
         ];
     }
 
@@ -92,14 +89,4 @@ class MarketplaceOrderDelivery extends \yii\db\ActiveRecord
         ];
     }
 
-    /**
-     * Gets query for [[Order]].
-     *
-     * @return \yii\db\ActiveQuery
-     */
-    public function getOrder()
-    {
-        return $this->hasOne(MarketplaceOrders::class, ['id' => 'order_id']);
-    }
-
 }
diff --git a/erp24/records/MarketplaceOrderItems.php b/erp24/records/MarketplaceOrderItems.php
new file mode 100644 (file)
index 0000000..26b56b8
--- /dev/null
@@ -0,0 +1,82 @@
+<?php
+
+namespace yii_app\records;
+
+use Yii;
+
+/**
+ * This is the model class for table "marketplace_order_items".
+ *
+ * @property int $id
+ * @property int $order_id Ссылка на заказ
+ * @property int $external_item_id ID элемента заказа из API
+ * @property string $offer_id ID предложения
+ * @property string $offer_name Название предложения
+ * @property float $price Цена
+ * @property float $buyer_price Цена для покупателя
+ * @property float $buyer_price_before_discount Цена для покупателя до скидки
+ * @property float $price_before_discount Цена до скидки
+ * @property int $count Количество
+ * @property string $vat НДС
+ * @property string $shop_sku SKU магазина
+ * @property float $subsidy Субсидия
+ * @property string $partner_warehouse_id ID склада партнёра
+ * @property string|null $promos Промо скидки в формате JSON
+ * @property string|null $subsidies Субсидии в формате JSON
+ */
+class MarketplaceOrderItems extends \yii\db\ActiveRecord
+{
+
+
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return 'marketplace_order_items';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['promos', 'subsidies'], 'default', 'value' => null],
+            [['order_id', 'external_item_id', 'offer_id', 'offer_name', 'price', 'buyer_price', 'buyer_price_before_discount', 'price_before_discount', 'count', 'vat', 'shop_sku', 'subsidy', 'partner_warehouse_id'], 'required'],
+            [['order_id', 'external_item_id', 'count'], 'default', 'value' => null],
+            [['order_id', 'external_item_id', 'count'], 'integer'],
+            [['price', 'buyer_price', 'buyer_price_before_discount', 'price_before_discount', 'subsidy'], 'number'],
+            [['promos', 'subsidies'], 'string'],
+            [['offer_id', 'shop_sku', 'partner_warehouse_id'], 'string', 'max' => 64],
+            [['offer_name'], 'string', 'max' => 255],
+            [['vat'], 'string', 'max' => 32],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'id' => 'ID',
+            'order_id' => 'Ссылка на заказ',
+            'external_item_id' => 'ID элемента заказа из API',
+            'offer_id' => 'ID предложения',
+            'offer_name' => 'Название предложения',
+            'price' => 'Цена',
+            'buyer_price' => 'Цена для покупателя',
+            'buyer_price_before_discount' => 'Цена для покупателя до скидки',
+            'price_before_discount' => 'Цена до скидки',
+            'count' => 'Количество',
+            'vat' => 'НДС',
+            'shop_sku' => 'SKU магазина',
+            'subsidy' => 'Субсидия',
+            'partner_warehouse_id' => 'ID склада партнёра',
+            'promos' => 'Промо скидки в формате JSON',
+            'subsidies' => 'Субсидии в формате JSON',
+        ];
+    }
+
+}
diff --git a/erp24/records/MarketplaceOrderItemsSearch.php b/erp24/records/MarketplaceOrderItemsSearch.php
new file mode 100644 (file)
index 0000000..4f2617a
--- /dev/null
@@ -0,0 +1,84 @@
+<?php
+
+namespace yii_app\records;
+
+use yii\base\Model;
+use yii\data\ActiveDataProvider;
+use yii_app\records\MarketplaceOrderItems;
+
+/**
+ * MarketplaceOrderItemsSearch represents the model behind the search form of `yii_app\records\MarketplaceOrderItems`.
+ */
+class MarketplaceOrderItemsSearch extends MarketplaceOrderItems
+{
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['id', 'order_id', 'external_item_id', 'count'], 'integer'],
+            [['offer_id', 'offer_name', 'vat', 'shop_sku', 'partner_warehouse_id', 'promos', 'subsidies'], 'safe'],
+            [['price', 'buyer_price', 'buyer_price_before_discount', 'price_before_discount', 'subsidy'], 'number'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function scenarios()
+    {
+        // bypass scenarios() implementation in the parent class
+        return Model::scenarios();
+    }
+
+    /**
+     * Creates data provider instance with search query applied
+     *
+     * @param array $params
+     * @param string|null $formName Form name to be used into `->load()` method.
+     *
+     * @return ActiveDataProvider
+     */
+    public function search($params, $formName = null)
+    {
+        $query = MarketplaceOrderItems::find();
+
+        // add conditions that should always apply here
+
+        $dataProvider = new ActiveDataProvider([
+            'query' => $query,
+        ]);
+
+        $this->load($params, $formName);
+
+        if (!$this->validate()) {
+            // uncomment the following line if you do not want to return any records when validation fails
+            // $query->where('0=1');
+            return $dataProvider;
+        }
+
+        // grid filtering conditions
+        $query->andFilterWhere([
+            'id' => $this->id,
+            'order_id' => $this->order_id,
+            'external_item_id' => $this->external_item_id,
+            'price' => $this->price,
+            'buyer_price' => $this->buyer_price,
+            'buyer_price_before_discount' => $this->buyer_price_before_discount,
+            'price_before_discount' => $this->price_before_discount,
+            'count' => $this->count,
+            'subsidy' => $this->subsidy,
+        ]);
+
+        $query->andFilterWhere(['ilike', 'offer_id', $this->offer_id])
+            ->andFilterWhere(['ilike', 'offer_name', $this->offer_name])
+            ->andFilterWhere(['ilike', 'vat', $this->vat])
+            ->andFilterWhere(['ilike', 'shop_sku', $this->shop_sku])
+            ->andFilterWhere(['ilike', 'partner_warehouse_id', $this->partner_warehouse_id])
+            ->andFilterWhere(['ilike', 'promos', $this->promos])
+            ->andFilterWhere(['ilike', 'subsidies', $this->subsidies]);
+
+        return $dataProvider;
+    }
+}
index 91230b82fab61ff6c655366720000a2213236c0e..25212740ebf48978b41d13e47f85568ed22ec60e 100644 (file)
@@ -15,10 +15,6 @@ use Yii;
  * @property string $date_from Дата и время начала активности
  * @property string|null $date_end Дата и время окончания активности
  * @property string|null $initiator Инициатор изменения
- *
- * @property MarketplaceOrders $order
- * @property MarketplaceOrderStatusTypes $status
- * @property MarketplaceOrderStatusTypes $substatus
  */
 class MarketplaceOrderStatusHistory extends \yii\db\ActiveRecord
 {
@@ -45,9 +41,6 @@ class MarketplaceOrderStatusHistory extends \yii\db\ActiveRecord
             [['order_id', 'status_id', 'substatus_id', 'active'], 'integer'],
             [['date_from', 'date_end'], 'safe'],
             [['initiator'], 'string'],
-            [['status_id'], 'exist', 'skipOnError' => true, 'targetClass' => MarketplaceOrderStatusTypes::class, 'targetAttribute' => ['status_id' => 'id']],
-            [['substatus_id'], 'exist', 'skipOnError' => true, 'targetClass' => MarketplaceOrderStatusTypes::class, 'targetAttribute' => ['substatus_id' => 'id']],
-            [['order_id'], 'exist', 'skipOnError' => true, 'targetClass' => MarketplaceOrders::class, 'targetAttribute' => ['order_id' => 'id']],
         ];
     }
 
@@ -68,34 +61,4 @@ class MarketplaceOrderStatusHistory extends \yii\db\ActiveRecord
         ];
     }
 
-    /**
-     * Gets query for [[Order]].
-     *
-     * @return \yii\db\ActiveQuery
-     */
-    public function getOrder()
-    {
-        return $this->hasOne(MarketplaceOrders::class, ['id' => 'order_id']);
-    }
-
-    /**
-     * Gets query for [[Status]].
-     *
-     * @return \yii\db\ActiveQuery
-     */
-    public function getStatus()
-    {
-        return $this->hasOne(MarketplaceOrderStatusTypes::class, ['id' => 'status_id']);
-    }
-
-    /**
-     * Gets query for [[Substatus]].
-     *
-     * @return \yii\db\ActiveQuery
-     */
-    public function getSubstatus()
-    {
-        return $this->hasOne(MarketplaceOrderStatusTypes::class, ['id' => 'substatus_id']);
-    }
-
 }
index 94076309cd9f500e257a217bf1ca994d34f71bc4..ceb8bb2222d18ba44b88d30680d9cba1d1e0e616 100644 (file)
@@ -11,9 +11,6 @@ use Yii;
  * @property string $code Код статуса
  * @property string|null $name Название статуса
  * @property string|null $description Описание статуса
- *
- * @property MarketplaceOrderStatusHistory[] $marketplaceOrderStatusHistories
- * @property MarketplaceOrderStatusHistory[] $marketplaceOrderStatusHistories0
  */
 class MarketplaceOrderStatusTypes extends \yii\db\ActiveRecord
 {
@@ -37,6 +34,7 @@ class MarketplaceOrderStatusTypes extends \yii\db\ActiveRecord
             [['code'], 'required'],
             [['code'], 'string', 'max' => 64],
             [['name', 'description'], 'string', 'max' => 255],
+            [['code'], 'unique'],
         ];
     }
 
@@ -53,24 +51,4 @@ class MarketplaceOrderStatusTypes extends \yii\db\ActiveRecord
         ];
     }
 
-    /**
-     * Gets query for [[MarketplaceOrderStatusHistories]].
-     *
-     * @return \yii\db\ActiveQuery
-     */
-    public function getMarketplaceOrderStatusHistories()
-    {
-        return $this->hasMany(MarketplaceOrderStatusHistory::class, ['status_id' => 'id']);
-    }
-
-    /**
-     * Gets query for [[MarketplaceOrderStatusHistories0]].
-     *
-     * @return \yii\db\ActiveQuery
-     */
-    public function getMarketplaceOrderStatusHistories0()
-    {
-        return $this->hasMany(MarketplaceOrderStatusHistory::class, ['substatus_id' => 'id']);
-    }
-
 }
index 626c5e60e5e72b76119a4f2b91ce7aea45f94329..eda6edf3ae6489e36e51a2107d273ae66f66b0ba 100644 (file)
@@ -8,9 +8,11 @@ use Yii;
  * This is the model class for table "marketplace_orders".
  *
  * @property int $id ID заказа
- * @property string $marketplace_id ID заказа в системе маркетплейса
- * @property string|null $store_id Идентификатор склада/магазина
- * @property int|null $status_history_id Ссылка на текущий активный статус
+ * @property string $marketplace_order_id ID заказа в системе маркетплейса
+ * @property int|null $store_id Идентификатор магазина
+ * @property int $status_id Ссылка на тип статуса
+ * @property int $substatus_id Ссылка на подстатус
+ * @property string|null $warehouse_guid Идентификатор магазина
  * @property string $creation_date Дата создания заказа
  * @property string $updated_at Время последнего обновления
  * @property float $total Итоговая сумма к оплате
@@ -23,9 +25,6 @@ use Yii;
  * @property string|null $raw_data Полный сырой ответ API
  * @property string|null $guid GUID заказа в 1С
  * @property int|null $status_1c Статус заказа в 1С
- *
- * @property MarketplaceOrderDelivery[] $marketplaceOrderDeliveries
- * @property MarketplaceOrderStatusHistory[] $marketplaceOrderStatusHistories
  */
 class MarketplaceOrders extends \yii\db\ActiveRecord
 {
@@ -45,19 +44,19 @@ class MarketplaceOrders extends \yii\db\ActiveRecord
     public function rules()
     {
         return [
-            [['store_id', 'status_history_id', 'raw_data', 'guid'], 'default', 'value' => null],
+            [['store_id', 'warehouse_guid', 'raw_data', 'guid'], 'default', 'value' => null],
             [['cancel_requested'], 'default', 'value' => 0],
             [['status_1c'], 'default', 'value' => 1],
-            [['marketplace_id', 'creation_date', 'updated_at', 'total', 'delivery_total', 'buyer_total_before_discount', 'tax_system', 'payment_type', 'payment_method'], 'required'],
-            [['status_history_id', 'cancel_requested', 'status_1c'], 'default', 'value' => null],
-            [['status_history_id', 'cancel_requested', 'status_1c'], 'integer'],
+            [['marketplace_order_id', 'status_id', 'substatus_id', 'creation_date', 'updated_at', 'total', 'delivery_total', 'buyer_total_before_discount', 'tax_system', 'payment_type', 'payment_method'], 'required'],
+            [['store_id', 'status_id', 'substatus_id', 'cancel_requested', 'status_1c'], 'default', 'value' => null],
+            [['store_id', 'status_id', 'substatus_id', 'cancel_requested', 'status_1c'], 'integer'],
             [['creation_date', 'updated_at'], 'safe'],
             [['total', 'delivery_total', 'buyer_total_before_discount'], 'number'],
             [['raw_data'], 'string'],
-            [['marketplace_id'], 'string', 'max' => 64],
-            [['store_id', 'guid'], 'string', 'max' => 36],
+            [['marketplace_order_id'], 'string', 'max' => 64],
+            [['warehouse_guid', 'guid'], 'string', 'max' => 36],
             [['tax_system', 'payment_type', 'payment_method'], 'string', 'max' => 32],
-            [['marketplace_id'], 'unique'],
+            [['marketplace_order_id'], 'unique'],
         ];
     }
 
@@ -68,9 +67,11 @@ class MarketplaceOrders extends \yii\db\ActiveRecord
     {
         return [
             'id' => 'ID заказа',
-            'marketplace_id' => 'ID заказа в системе маркетплейса',
-            'store_id' => 'Идентификатор склада/магазина',
-            'status_history_id' => 'Ссылка на текущий активный статус',
+            'marketplace_order_id' => 'ID заказа в системе маркетплейса',
+            'store_id' => 'Идентификатор магазина',
+            'status_id' => 'Ссылка на тип статуса',
+            'substatus_id' => 'Ссылка на подстатус',
+            'warehouse_guid' => 'Идентификатор магазина',
             'creation_date' => 'Дата создания заказа',
             'updated_at' => 'Время последнего обновления',
             'total' => 'Итоговая сумма к оплате',
@@ -86,24 +87,4 @@ class MarketplaceOrders extends \yii\db\ActiveRecord
         ];
     }
 
-    /**
-     * Gets query for [[MarketplaceOrderDeliveries]].
-     *
-     * @return \yii\db\ActiveQuery
-     */
-    public function getMarketplaceOrderDeliveries()
-    {
-        return $this->hasMany(MarketplaceOrderDelivery::class, ['order_id' => 'id']);
-    }
-
-    /**
-     * Gets query for [[MarketplaceOrderStatusHistories]].
-     *
-     * @return \yii\db\ActiveQuery
-     */
-    public function getMarketplaceOrderStatusHistories()
-    {
-        return $this->hasMany(MarketplaceOrderStatusHistory::class, ['order_id' => 'id']);
-    }
-
 }
index 2f0a0f857629cf9f1c5592d937f6aa6c112c3600..c1fa088db3437d0e5dac7e2a85b227d9a60207e6 100644 (file)
@@ -17,8 +17,8 @@ class MarketplaceOrdersSearch extends MarketplaceOrders
     public function rules()
     {
         return [
-            [['id', 'status_history_id', 'cancel_requested', 'status_1c'], 'integer'],
-            [['marketplace_id', 'store_id', 'creation_date', 'updated_at', 'tax_system', 'payment_type', 'payment_method', 'raw_data', 'guid'], 'safe'],
+            [['id', 'store_id', 'status_id', 'substatus_id', 'cancel_requested', 'status_1c'], 'integer'],
+            [['marketplace_order_id', 'warehouse_guid', 'creation_date', 'updated_at', 'tax_system', 'payment_type', 'payment_method', 'raw_data', 'guid'], 'safe'],
             [['total', 'delivery_total', 'buyer_total_before_discount'], 'number'],
         ];
     }
@@ -61,7 +61,9 @@ class MarketplaceOrdersSearch extends MarketplaceOrders
         // grid filtering conditions
         $query->andFilterWhere([
             'id' => $this->id,
-            'status_history_id' => $this->status_history_id,
+            'store_id' => $this->store_id,
+            'status_id' => $this->status_id,
+            'substatus_id' => $this->substatus_id,
             'creation_date' => $this->creation_date,
             'updated_at' => $this->updated_at,
             'total' => $this->total,
@@ -71,8 +73,8 @@ class MarketplaceOrdersSearch extends MarketplaceOrders
             'status_1c' => $this->status_1c,
         ]);
 
-        $query->andFilterWhere(['ilike', 'marketplace_id', $this->marketplace_id])
-            ->andFilterWhere(['ilike', 'store_id', $this->store_id])
+        $query->andFilterWhere(['ilike', 'marketplace_order_id', $this->marketplace_order_id])
+            ->andFilterWhere(['ilike', 'warehouse_guid', $this->warehouse_guid])
             ->andFilterWhere(['ilike', 'tax_system', $this->tax_system])
             ->andFilterWhere(['ilike', 'payment_type', $this->payment_type])
             ->andFilterWhere(['ilike', 'payment_method', $this->payment_method])
diff --git a/erp24/views/marketplace-order-items/_search.php b/erp24/views/marketplace-order-items/_search.php
new file mode 100644 (file)
index 0000000..1491d22
--- /dev/null
@@ -0,0 +1,57 @@
+<?php
+
+use yii\helpers\Html;
+use yii\widgets\ActiveForm;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\MarketplaceOrderItemsSearch $model */
+/** @var yii\widgets\ActiveForm $form */
+?>
+
+<div class="marketplace-order-items-search">
+
+    <?php $form = ActiveForm::begin([
+        'action' => ['index'],
+        'method' => 'get',
+    ]); ?>
+
+    <?= $form->field($model, 'id') ?>
+
+    <?= $form->field($model, 'order_id') ?>
+
+    <?= $form->field($model, 'external_item_id') ?>
+
+    <?= $form->field($model, 'offer_id') ?>
+
+    <?= $form->field($model, 'offer_name') ?>
+
+    <?php // echo $form->field($model, 'price') ?>
+
+    <?php // echo $form->field($model, 'buyer_price') ?>
+
+    <?php // echo $form->field($model, 'buyer_price_before_discount') ?>
+
+    <?php // echo $form->field($model, 'price_before_discount') ?>
+
+    <?php // echo $form->field($model, 'count') ?>
+
+    <?php // echo $form->field($model, 'vat') ?>
+
+    <?php // echo $form->field($model, 'shop_sku') ?>
+
+    <?php // echo $form->field($model, 'subsidy') ?>
+
+    <?php // echo $form->field($model, 'partner_warehouse_id') ?>
+
+    <?php // echo $form->field($model, 'promos') ?>
+
+    <?php // echo $form->field($model, 'subsidies') ?>
+
+    <div class="form-group">
+        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
+        <?= Html::resetButton('Reset', ['class' => 'btn btn-outline-secondary']) ?>
+    </div>
+
+    <?php ActiveForm::end(); ?>
+
+</div>
diff --git a/erp24/views/marketplace-order-items/index.php b/erp24/views/marketplace-order-items/index.php
new file mode 100644 (file)
index 0000000..9473145
--- /dev/null
@@ -0,0 +1,58 @@
+<?php
+
+use yii_app\records\MarketplaceOrderItems;
+use yii\helpers\Html;
+use yii\helpers\Url;
+use yii\grid\ActionColumn;
+use yii\grid\GridView;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\MarketplaceOrderItemsSearch $searchModel */
+/** @var yii\data\ActiveDataProvider $dataProvider */
+
+$this->title = 'Marketplace Order Items';
+$this->params['breadcrumbs'][] = $this->title;
+?>
+<div class="marketplace-order-items-index">
+
+    <h1><?= Html::encode($this->title) ?></h1>
+
+    <p>
+        <?= Html::a('Create Marketplace Order Items', ['create'], ['class' => 'btn btn-success']) ?>
+    </p>
+
+    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>
+
+    <?= GridView::widget([
+        'dataProvider' => $dataProvider,
+        'filterModel' => $searchModel,
+        'columns' => [
+            ['class' => 'yii\grid\SerialColumn'],
+
+            'id',
+            'order_id',
+            'external_item_id',
+            'offer_id',
+            'offer_name',
+            //'price',
+            //'buyer_price',
+            //'buyer_price_before_discount',
+            //'price_before_discount',
+            //'count',
+            //'vat',
+            //'shop_sku',
+            //'subsidy',
+            //'partner_warehouse_id',
+            //'promos:ntext',
+            //'subsidies:ntext',
+            [
+                'class' => ActionColumn::className(),
+                'urlCreator' => function ($action, MarketplaceOrderItems $model, $key, $index, $column) {
+                    return Url::toRoute([$action, 'id' => $model->id]);
+                 }
+            ],
+        ],
+    ]); ?>
+
+
+</div>
diff --git a/erp24/views/marketplace-order-items/view.php b/erp24/views/marketplace-order-items/view.php
new file mode 100644 (file)
index 0000000..fc19e38
--- /dev/null
@@ -0,0 +1,51 @@
+<?php
+
+use yii\helpers\Html;
+use yii\widgets\DetailView;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\MarketplaceOrderItems $model */
+
+$this->title = $model->id;
+$this->params['breadcrumbs'][] = ['label' => 'Marketplace Order Items', 'url' => ['index']];
+$this->params['breadcrumbs'][] = $this->title;
+\yii\web\YiiAsset::register($this);
+?>
+<div class="marketplace-order-items-view">
+
+    <h1><?= Html::encode($this->title) ?></h1>
+
+    <p>
+        <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
+        <?= Html::a('Delete', ['delete', 'id' => $model->id], [
+            'class' => 'btn btn-danger',
+            'data' => [
+                'confirm' => 'Are you sure you want to delete this item?',
+                'method' => 'post',
+            ],
+        ]) ?>
+    </p>
+
+    <?= DetailView::widget([
+        'model' => $model,
+        'attributes' => [
+            'id',
+            'order_id',
+            'external_item_id',
+            'offer_id',
+            'offer_name',
+            'price',
+            'buyer_price',
+            'buyer_price_before_discount',
+            'price_before_discount',
+            'count',
+            'vat',
+            'shop_sku',
+            'subsidy',
+            'partner_warehouse_id',
+            'promos:ntext',
+            'subsidies:ntext',
+        ],
+    ]) ?>
+
+</div>
index 6765db5ed8839226f127db4df46bfcea508a9989..29c17ad7af9c70426e7e12c29d8bfda77e07a89f 100644 (file)
@@ -17,13 +17,17 @@ use yii\widgets\ActiveForm;
 
     <?= $form->field($model, 'id') ?>
 
-    <?= $form->field($model, 'marketplace_id') ?>
+    <?= $form->field($model, 'marketplace_order_id') ?>
 
     <?= $form->field($model, 'store_id') ?>
 
-    <?= $form->field($model, 'status_history_id') ?>
+    <?= $form->field($model, 'status_id') ?>
 
-    <?= $form->field($model, 'creation_date') ?>
+    <?= $form->field($model, 'substatus_id') ?>
+
+    <?php // echo $form->field($model, 'warehouse_guid') ?>
+
+    <?php // echo $form->field($model, 'creation_date') ?>
 
     <?php // echo $form->field($model, 'updated_at') ?>
 
index 6702300fc9edace946f28c6e62e4cf2fcb7c86f1..c842bdf46efb3e120b9a3368f3140f285ea11084 100644 (file)
@@ -30,10 +30,12 @@ $this->params['breadcrumbs'][] = $this->title;
             ['class' => 'yii\grid\SerialColumn'],
 
             'id',
-            'marketplace_id',
+            'marketplace_order_id',
             'store_id',
-            'status_history_id',
-            'creation_date',
+            'status_id',
+            'substatus_id',
+            //'warehouse_guid',
+            //'creation_date',
             //'updated_at',
             //'total',
             //'delivery_total',
index 9781711b9836b218e8f99e9a1b49e23b78b88838..9afbae359f15ede62a7a83d9c1fd06a7899ca486 100644 (file)
@@ -30,9 +30,11 @@ $this->params['breadcrumbs'][] = $this->title;
         'model' => $model,
         'attributes' => [
             'id',
-            'marketplace_id',
+            'marketplace_order_id',
             'store_id',
-            'status_history_id',
+            'status_id',
+            'substatus_id',
+            'warehouse_guid',
             'creation_date',
             'updated_at',
             'total',