]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
ERP-256 Сделать отправку документов Пересортица в 1с
authormarina <m.zozirova@gmail.com>
Wed, 18 Dec 2024 08:30:47 +0000 (11:30 +0300)
committermarina <m.zozirova@gmail.com>
Wed, 18 Dec 2024 08:30:47 +0000 (11:30 +0300)
erp24/api2/controllers/DataController.php
erp24/controllers/ShiftTransferController.php
erp24/migrations/m241218_073127_add_new_column_on_replacement_invoice.php [new file with mode: 0644]
erp24/records/EqualizationRemains.php
erp24/records/ReplacementInvoice.php
erp24/records/ReplacementInvoiceProducts.php
erp24/records/StoreBalance.php
erp24/records/TimetableFactModel.php

index ade8e3603b75390cb564fa9bd699724864081fd1..dc730b9b1f822e1443939754aa9fe9bde60d44df 100644 (file)
@@ -20,6 +20,7 @@ use yii_app\records\CreateChecks;
 use yii_app\records\CreateChecks2;
 use yii_app\records\CreateChecksBags;
 use yii_app\records\EmployeeOnShift;
+use yii_app\records\EqualizationRemains;
 use yii_app\records\ExportImportTable;
 use yii_app\records\Incoming;
 use yii_app\records\IncomingItems;
@@ -31,10 +32,13 @@ use yii_app\records\PricesZakup;
 use yii_app\records\Products1cPropType;
 use yii_app\records\Products1c;
 use yii_app\records\Products1cAdditionalCharacteristics;
+use yii_app\records\ReplacementInvoice;
+use yii_app\records\ReplacementInvoiceProducts;
 use yii_app\records\Sales;
 use yii_app\records\SalesItems;
 use yii_app\records\SalesProducts;
 use yii_app\records\SelfCostProduct;
+
 //use yii_app\records\SalesProductsUpdate;
 use yii_app\records\SalesUpdate;
 use yii_app\records\Terminals;
@@ -47,15 +51,18 @@ use yii_app\records\WriteOffsProductsErp;
 use yii_app\services\InfoLogService;
 use yii_app\services\LogService;
 
-class DataController extends BaseController {
+class DataController extends BaseController
+{
 
     const OUT_DIR =
 //        __DIR__ . "/../json";
-    //    "/www/api2/json";
-    "/var/www/erp24/api2/json";
+        //    "/www/api2/json";
+        "/var/www/erp24/api2/json";
+
 //          "/var/www/www-root/data/www/api.bazacvetov24.ru/data/json";
 
-    public function actionRequest() {
+    public function actionRequest()
+    {
         Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
 
         $request = Yii::$app->request->getRawBody();
@@ -149,13 +156,22 @@ class DataController extends BaseController {
                 $mess['create_employee'] = $createEmployeeArray;
             }
 
+            $replacementInvoiceArray = $this->getResortingDoc();
+            $replacementInvoice = $replacementInvoiceArray['replacementInvoice'];
+            $replacementInvoiceResult = $replacementInvoiceArray['replacementInvoiceResult'];
+            $replacementInvoiceIds = $replacementInvoiceArray['replacementInvoiceIds'];
+
+            if (!empty($replacementInvoiceResult)) {
+                $mess['create_write_ons'] = $replacementInvoiceResult;
+            }
+
 //            $mess['delete_employee'] = [
 //                ['id' => '06202309-2808-0427-d4c9-100030128795'],
 //                ['id' => '06202309-2855-0215-4f5d-100043236389']
 //            ];
 
         } catch (Exception $e) {
-            file_put_contents(self::OUT_DIR . '/request_error.txt', PHP_EOL . date("d.m.Y H:i:s",time()). $e->getMessage(), FILE_APPEND);
+            file_put_contents(self::OUT_DIR . '/request_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage(), FILE_APPEND);
         } finally {
             $jsonArray = [];
             $apiCron = ApiCron::find()->where(['status' => 0])->orderBy(['date' => SORT_ASC])->one();
@@ -195,6 +211,9 @@ class DataController extends BaseController {
                 if (!empty($waybillIncomingIds) && !empty($waybillIncoming)) {
                     $this->getWaybillIncomingSetStatusSend($waybillIncomingIds);
                 }
+                if (!empty($replacementInvoiceIds) && !empty($replacementInvoice)) {
+                    $this->getReplacementInvoiceSetStatusSend($replacementInvoiceIds);
+                }
                 $json = json_encode($mess, JSON_UNESCAPED_UNICODE);
             }
 //
@@ -215,7 +234,8 @@ class DataController extends BaseController {
         return $this->asJson(json_decode($json, true));
     }
 
-    private function getWriteOffsSetStatusSend($writeOffIds) {
+    private function getWriteOffsSetStatusSend($writeOffIds)
+    {
         try {
             $writeOffsErp = WriteOffsErp::find()->where(['in', 'id', $writeOffIds])->all();
             foreach ($writeOffsErp as $writeOffsErpElem) {
@@ -228,11 +248,12 @@ class DataController extends BaseController {
                 }
             }
         } catch (Exception $e3) {
-            file_put_contents(self::OUT_DIR . '/log_created_write_offs_erp_error.txt', PHP_EOL . date("d.m.Y H:i:s",time()). $e3->getMessage(), FILE_APPEND);
+            file_put_contents(self::OUT_DIR . '/log_created_write_offs_erp_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e3->getMessage(), FILE_APPEND);
         }
     }
 
-    private function getWaybillIncomingSetStatusSend($waybillIncomingIds) {
+    private function getWaybillIncomingSetStatusSend($waybillIncomingIds)
+    {
         try {
             $waybillIncoming = WaybillIncoming::find()->where(['in', 'id', $waybillIncomingIds])->all();
             foreach ($waybillIncoming as $waybillIncomingElem) {
@@ -244,11 +265,28 @@ class DataController extends BaseController {
                 }
             }
         } catch (Exception $e3) {
-            file_put_contents(self::OUT_DIR . '/log_created_waybill_incoming_error.txt', PHP_EOL . date("d.m.Y H:i:s",time()). $e3->getMessage(), FILE_APPEND);
+            file_put_contents(self::OUT_DIR . '/log_created_waybill_incoming_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e3->getMessage(), FILE_APPEND);
+        }
+    }
+
+    private function getReplacementInvoiceSetStatusSend($replacementInvoiceIds)
+    {
+        try {
+            $replacementInvoice = ReplacementInvoice::find()->where(['in', 'id', $replacementInvoiceIds])->all();
+            foreach ($replacementInvoice as $replacementInvoiceElem) {
+                $replacementInvoiceElem->status = WriteOffsErp::STATUS_SEND;
+                $replacementInvoiceElem->send_at = date('Y-m-d H:i:s');
+                $replacementInvoiceElem->save();
+                if ($replacementInvoiceElem->getErrors()) {
+                    LogService::apiErrorLog(json_encode(["error_id" => 2.5, "error" => $replacementInvoiceElem->getErrors()], JSON_UNESCAPED_UNICODE));
+                }
+            }
+        } catch (Exception $e3) {
+            file_put_contents(self::OUT_DIR . '/log_created_waybill_incoming_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e3->getMessage(), FILE_APPEND);
         }
     }
 
-    private function getWriteOffsDoc() : array
+    private function getWriteOffsDoc(): array
     {
         $writeOff = [];
         $writeOffIds = [];
@@ -293,7 +331,7 @@ class DataController extends BaseController {
                     $writeOffProducts[$product['write_offs_erp_id']][] = [
                         'product_id' => $product['product_id'],
 //                        'color' => '',
-                        'quantity' => (string) $product['quantity'],
+                        'quantity' => (string)$product['quantity'],
                         'price' => $product['price'],
                     ];
                 }
@@ -323,7 +361,7 @@ class DataController extends BaseController {
             }
 
         } catch (Exception $e3) {
-            file_put_contents(self::OUT_DIR . '/log_created_write_offs_erp_error.txt', PHP_EOL . date("d.m.Y H:i:s",time()). $e3->getMessage(). ' file: '. $e3->getFile() . ' line: '. $e3->getLine(), FILE_APPEND);
+            file_put_contents(self::OUT_DIR . '/log_created_write_offs_erp_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e3->getMessage() . ' file: ' . $e3->getFile() . ' line: ' . $e3->getLine(), FILE_APPEND);
         }
 
         return [
@@ -335,7 +373,8 @@ class DataController extends BaseController {
         ];
     }
 
-    private function getWaybillIncomingDoc() : array {
+    private function getWaybillIncomingDoc(): array
+    {
         $waybillIncoming = [];
         $waybillIncomingIds = [];
         $waybillIncomingResult = [];
@@ -371,7 +410,7 @@ class DataController extends BaseController {
                 foreach ($products as $product) {
                     $waybillIncomingProducts[$product['waybill_incoming_id']][] = [
                         'product_id' => $product['product_id'],
-                        'quantity' => (string) $product['product_count'],
+                        'quantity' => (string)$product['product_count'],
                         'price' => $product['product_price'],
                     ];
                 }
@@ -401,13 +440,91 @@ class DataController extends BaseController {
             }
 
         } catch (Exception $e3) {
-            file_put_contents(self::OUT_DIR . '/log_created_waybill_incoming_error.txt', PHP_EOL . date("d.m.Y H:i:s",time()). $e3->getMessage(). ' file: '. $e3->getFile() . ' line: '. $e3->getLine(), FILE_APPEND);
+            file_put_contents(self::OUT_DIR . '/log_created_waybill_incoming_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e3->getMessage() . ' file: ' . $e3->getFile() . ' line: ' . $e3->getLine(), FILE_APPEND);
         }
 
         return compact('waybillIncoming', 'waybillIncomingIds');
     }
 
-    private function getCreateEmployee() : array {
+
+    private function getResortingDoc(): array
+    {
+        $replacementInvoice = [];
+        $replacementInvoicesIds = [];
+        $replacementInvoiceResult = [];
+
+        try {
+            $replacementInvoice = ReplacementInvoice::find()
+                ->select(['id', 'guid', 'shift_transfer_id', 'store_guid', 'number', 'date', 'comment', 'quantity', 'summ'])
+                ->andWhere(['status' => WriteOffsErp::STATUS_CONFIRM])
+                ->indexBy('id')
+                ->asArray()
+                ->all();
+
+            if (!empty($replacementInvoice)) {
+                $replacementInvoicesIds = array_column($replacementInvoice, 'id');
+                $shiftTransferIds = array_column($replacementInvoice, 'shift_transfer_id');
+
+                $products = EqualizationRemains::find()
+                    ->where(['in', 'shift_transfer_id', $shiftTransferIds])
+                    ->asArray()
+                    ->all();
+
+                $replacementInvoiceProducts = [];
+
+                foreach ($products as $product) {
+                    $replacementInvoiceProducts[$product['']][] = [
+                        'product_id' => $product->product_id,
+                        'color' => Products1cAdditionalCharacteristics::findOne([
+                                'property_id' => '5880b25c-809f-11ef-84ea-ac1f6b1b7573',
+                                'product_id' => $product->product_id])->value ?? '',
+                        'price' => $product->product_price,
+                        'new_product_id' => $product->product_replacement_id,
+                        'new_color' => Products1cAdditionalCharacteristics::findOne([
+                                'property_id' => '5880b25c-809f-11ef-84ea-ac1f6b1b7573',
+                                'product_id' => $product->product_replacement_id])->value ?? '',
+                        'new_price' => $product->product_replacement_price,
+                        'quantity' => $product->product_replacement_count,
+                    ];
+                }
+
+                $replacementInvoiceTemp = $replacementInvoice;
+                foreach ($replacementInvoiceTemp as $key => $row) {
+                    $replacementInvoiceProductsRow = [];
+                    if (!isset($replacementInvoice[$key]['items'])) {
+                        $replacementInvoice[$key]['items'] = [];
+                    }
+                    if (array_key_exists($row['id'], $replacementInvoiceProducts)) {
+                        $replacementInvoiceProductsRow = $replacementInvoiceProducts[$row['id']];
+                    }
+                    if (!empty($replacementInvoiceProductsRow)) {
+                        $replacementInvoice[$key]['items'][] = $replacementInvoiceProductsRow;
+                    }
+                }
+
+                foreach ($replacementInvoice as $row) {
+                    $replacementInvoiceResult[] = [
+                        'id' => $row['guid'],
+                        'store_id' => $row['store_guid'],
+                        'type' => 'ревизия при передаче смены',
+                        'cause' => 'Документ пересортицы при передаче смены в ERP ' . $row['number'],
+                        'items' => $row['items'],
+                        'summ' => $row['summ'],
+                        'comment' => $row['comment'],
+                    ];
+                }
+            }
+
+        } catch (Exception $e3) {
+            file_put_contents(self::OUT_DIR . '/log_created_replacement_invoice_error.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e3->getMessage() . ' file: ' . $e3->getFile() . ' line: ' . $e3->getLine(), FILE_APPEND);
+        }
+
+        return compact('replacementInvoice', 'replacementInvoicesIds', 'replacementInvoiceResult');
+    }
+
+
+    private function getCreateEmployee(): array
+    {
         $employeeOnShiftArray = EmployeeOnShift::find()
             ->where([
                 'status' => EmployeeOnShift::STATUS_ACCEPT,
@@ -449,7 +566,8 @@ class DataController extends BaseController {
         return $result;
     }
 
-    public function actionUpload() {
+    public function actionUpload()
+    {
         set_time_limit(600);
         file_put_contents(self::OUT_DIR . '/a2_upload_in.json', PHP_EOL . date('Y-m-d H:i:s') . ' ', FILE_APPEND | LOCK_EX);
 
@@ -483,7 +601,7 @@ class DataController extends BaseController {
             $mess = [];
             if (!empty($result['error'])) {
                 file_put_contents(self::OUT_DIR . '/error_upload.txt',
-                    PHP_EOL . json_encode($result["error"],JSON_UNESCAPED_UNICODE), FILE_APPEND);
+                    PHP_EOL . json_encode($result["error"], JSON_UNESCAPED_UNICODE), FILE_APPEND);
             }
             $mess["result"] = true;
             $checks_dell = "";
@@ -648,7 +766,7 @@ class DataController extends BaseController {
 //                    if (!empty($arr["name"]) && in_array($arr["name"][0], ['ь', 'Ь', 'ъ', 'Ъ'])) { // Не вносим номенклатуру, помеченную на удаление
 //                        continue;
 //                    }
-                    $components = !empty($arr["components"]) ? json_encode($arr["components"],JSON_UNESCAPED_UNICODE) : ""; // Пустые компоненты не надо разворачивать в json объект
+                    $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;
@@ -725,8 +843,8 @@ class DataController extends BaseController {
                                 $propertyType->name = $characteristic["name"];
                                 if (!$propertyType->save()) {
                                     LogService::apiErrorLog(json_encode(["error_id" => 8.1,
-                                                                        "error" => $propertyType->getErrors()],
-                                                                        JSON_UNESCAPED_UNICODE));
+                                        "error" => $propertyType->getErrors()],
+                                        JSON_UNESCAPED_UNICODE));
                                     continue;
                                 }
                             }
@@ -766,7 +884,7 @@ class DataController extends BaseController {
                     if ($paymentTypes->getErrors()) {
                         LogService::apiErrorLog(json_encode(
                             ["error_id" => 9,
-                            "error" => $paymentTypes->getErrors()],
+                                "error" => $paymentTypes->getErrors()],
                             JSON_UNESCAPED_UNICODE
                         ));
                     }
@@ -793,7 +911,7 @@ class DataController extends BaseController {
                     self::OUT_DIR . '/created_write_offs_upload_'
                     . date("Y_m_d") . '.json',
                     PHP_EOL
-                    . json_encode($result["created_write_offs"],JSON_UNESCAPED_UNICODE),
+                    . json_encode($result["created_write_offs"], JSON_UNESCAPED_UNICODE),
                     FILE_APPEND
                 );
                 foreach ($result["created_write_offs"] as $arr) {
@@ -876,7 +994,7 @@ class DataController extends BaseController {
                                 LogService::apiErrorLog(
                                     json_encode(
                                         ["error_id" => 11,
-                                        "error" => $writeOffsErp->getErrors()],
+                                            "error" => $writeOffsErp->getErrors()],
                                         JSON_UNESCAPED_UNICODE
                                     )
                                 );
@@ -901,8 +1019,8 @@ class DataController extends BaseController {
                 }
             }
 
-           if (!empty($result['write_offs'])) {
-                if (!empty($start_time)  and !empty($end_time)) {
+            if (!empty($result['write_offs'])) {
+                if (!empty($start_time) and !empty($end_time)) {
                     if ($update) {
                         WriteOffs::deleteAll(['and', ['>=', 'date', $start_time], ['<=', 'date', $end_time]]);
                     }
@@ -925,7 +1043,7 @@ class DataController extends BaseController {
                         }
                     }
 
-                    file_put_contents(self::OUT_DIR . '/write_offs.json', PHP_EOL . json_encode($result["write_offs"],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) {
@@ -944,14 +1062,14 @@ class DataController extends BaseController {
                     $writeOffs2->type = $arr["type"];
                     $writeOffs2->cause = $arr["cause"] ?? "";
                     $writeOffs2->comment = $arr["comment"] ?? "";
-                    $writeOffs2->items = json_encode($arr["items"],JSON_UNESCAPED_UNICODE);
+                    $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()], JSON_UNESCAPED_UNICODE));
                     }
 
-                    foreach ($arr["items"]  as $j2 => $mass2) {
+                    foreach ($arr["items"] as $j2 => $mass2) {
                         $writeOffsProducts = WriteOffsProducts::findOne([
                             'write_offs_id' => $arr["id"],
                             'product_id' => $mass2['product_id'],
@@ -1060,13 +1178,13 @@ class DataController extends BaseController {
                 }
             }
 
-            if (!empty($checks_dell) and !empty($start_time)  and !empty($end_time)) {
+            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);
+                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 = [];
@@ -1074,7 +1192,7 @@ class DataController extends BaseController {
                 $matrixProductsIds = SalaryHelper::getMatrixProductsIds();
             }
 
-           if (!empty($result['checks']) && count($result['checks']) < 1000) {
+            if (!empty($result['checks']) && count($result['checks']) < 1000) {
 
                 foreach ($result["checks"] as $arr) {
 
@@ -1199,7 +1317,7 @@ class DataController extends BaseController {
                         $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->delivery_date = date('Y-m-d', strtotime($arr['delivery_date'] ?? ''));
                         $sales2->pickup = $arr['pickup'] ?? false;
                         $sales2->save();
                         if ($sales2->getErrors()) {
@@ -1303,17 +1421,17 @@ class DataController extends BaseController {
                 }
             } elseif (!empty($result['checks'])) {
                 file_put_contents(self::OUT_DIR . '/error_upload.txt',
-                    PHP_EOL . "elseif" , FILE_APPEND);
+                    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);
+                        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');
+                        InfoLogService::setInfoLog(__FILE__, __LINE__, $errorString, 'error_id_25_m_st');
                     }
                 }
             }
@@ -1358,7 +1476,7 @@ class DataController extends BaseController {
                         }
                         try {
                             $pricesDynamic = PricesDynamic::find()->where(['product_id' => $idp])->andWhere(['active' => '1'])->orderBy(['id' => SORT_DESC])->one();
-                            $price = round($price,2);
+                            $price = round($price, 2);
                             // если нет записи или цена изменилась то вносим запись в БД
                             if ($pricesDynamic and $pricesDynamic->price != $price) {
                                 $pricesDynamic->active = 0;
@@ -1368,7 +1486,7 @@ class DataController extends BaseController {
                                     LogService::apiErrorLog(json_encode(["error_id" => 28, "error" => $pricesDynamic->getErrors()], JSON_UNESCAPED_UNICODE));
                                 }
                             }
-                            if (!$pricesDynamic  or ($pricesDynamic and $pricesDynamic->price != $price)) {
+                            if (!$pricesDynamic or ($pricesDynamic and $pricesDynamic->price != $price)) {
                                 $pricesDynamic2 = new PricesDynamic;
                                 $pricesDynamic2->product_id = $idp;
                                 $pricesDynamic2->price = $price;
@@ -1381,7 +1499,7 @@ class DataController extends BaseController {
                                 }
                             }
                         } 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);
+                            file_put_contents(self::OUT_DIR . '/log_prices_dinamics.txt', PHP_EOL . date("d.m.Y H:i:s", time()) . $e->getMessage(), FILE_APPEND);
                         }
                     }
                 }
@@ -1398,12 +1516,14 @@ class DataController extends BaseController {
                             if ($priceZakup->getErrors()) {
                                 LogService::apiErrorLog(json_encode(["error_id" => 30, "error" => $priceZakup->getErrors()], JSON_UNESCAPED_UNICODE));
                             }
-                        } catch (Exception $e) {}
+                        } 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) { }
+                        try {
+                            file_put_contents(self::OUT_DIR . '/price_purchese.txt', PHP_EOL . "$idp=" . $price, FILE_APPEND);
+                        } catch (Exception $e) {
+                        }
                     }
                 }
             }
@@ -1411,7 +1531,7 @@ class DataController extends BaseController {
             if (!empty($result['created_checks'])) {
                 foreach ($result["created_checks"] as $idp => $arr2) {
                     if (!empty($arr2["error"])) { // Если есть ошибки
-                         // // обновляем GUID на новый
+                        // // обновляем GUID на новый
 //                        try {
 //                            $createChecks = CreateChecks::find()->select(['order_id'])->where(['check_id' => $arr2["id"]])->one();
 //                            if ($createChecks) {
@@ -1433,7 +1553,7 @@ class DataController extends BaseController {
 //                            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"];
+                        $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
@@ -1515,7 +1635,7 @@ class DataController extends BaseController {
             }
 
         } catch (Exception $e) {
-            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);
+            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);
         } finally {
             LogService::apiDataLogs(1, json_encode($mess, JSON_UNESCAPED_UNICODE), $requestIdText);
         }
@@ -1541,7 +1661,7 @@ class DataController extends BaseController {
         return $pay_arr;
     }
 
-     private function getSalesDate($checks, $update): array
+    private function getSalesDate($checks, $update): array
     {
         $admins = $this->getEntityByType('admin');
 
@@ -1705,12 +1825,14 @@ class DataController extends BaseController {
         return $result;
     }
 
-    private function getEntityByType($entity = 'city_store') {
+    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) {
+    private function deleteSales($ids, $update)
+    {
         if (!empty($ids)) {
             SalesUpdate::deleteAll(['in', 'id', $ids]);
 //            SalesProductsUpdate::deleteAll(['in', 'check_id', $ids]);
@@ -1722,7 +1844,8 @@ class DataController extends BaseController {
         }
     }
 
-    private function setSales($values) {
+    private function setSales($values)
+    {
         $columns = [
             'phone',
             'id',
@@ -1751,7 +1874,8 @@ class DataController extends BaseController {
         $this->insertDataSales($values, 'sales', $columns);
     }
 
-    private function setSalesProducts($values) {
+    private function setSalesProducts($values)
+    {
         $columns = [
             'type_id',
             'check_id',
@@ -1769,7 +1893,8 @@ class DataController extends BaseController {
         $this->insertDataSales($values, 'sales_products', $columns);
     }
 
-    private function setSalesProductsComponents($values) {
+    private function setSalesProductsComponents($values)
+    {
         $columns = [
             'type_id',
             'check_id',
@@ -1860,7 +1985,8 @@ class DataController extends BaseController {
 //    }
 
 
-    private function setSelfCostUpdate($values) {
+    private function setSelfCostUpdate($values)
+    {
         $columns = [
 
             'date',
@@ -1871,31 +1997,30 @@ class DataController extends BaseController {
         ];
 
 
-
         $this->insertDataSales($values, 'self_cost_product', $columns, 4000);
     }
 
 
+    private function insertDataSales($values, $tableName, $columns, $chunks = 1000)
+    {
+        $chunkValues = array_chunk($values, $chunks);
 
-    private function insertDataSales($values, $tableName, $columns, $chunks = 1000 ) {
-    $chunkValues = array_chunk($values, $chunks);
-
-    foreach ($chunkValues as $key => $rows) {
+        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));
+            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));
 
+            }
         }
     }
-    }
 }
index 05fa0bb82a4136f7f6709c6a96a00019afe03ef7..63e7333f73e87139b1dd3174c97e48cdd2ab6623 100644 (file)
@@ -29,6 +29,7 @@ use yii_app\records\ShiftTransfer;
 use yii_app\records\StoreBalance;
 use yii_app\records\WaybillIncoming;
 use yii_app\records\WaybillWriteOffs;
+use yii_app\records\WriteOffsErp;
 use yii_app\services\TaskService;
 
 class ShiftTransferController extends Controller
@@ -299,6 +300,9 @@ class ShiftTransferController extends Controller
                 StoreBalance::setData($model);
             } elseif ($action === 'save') {
                 $model->updateAttributes(['status_id' => ShiftTransfer::STATUS_ID_READY_TO_ACCEPT]);
+                WaybillIncoming::updateAll(['status' => WriteOffsErp::STATUS_CONFIRM], ['shift_transfer_id' => $id]);
+                WaybillWriteOffs::updateAll(['status' => WriteOffsErp::STATUS_CONFIRM], ['shift_transfer_id' => $id]);
+                ReplacementInvoice::updateAll(['status' => WriteOffsErp::STATUS_CONFIRM], ['shift_transfer_id' => $id]);
             } elseif ($action == 'recalculate') {
                 EqualizationRemains::setData($model);
                 Yii::$app->session->setFlash('success', 'Таблица замен успешно перерасчитана');
diff --git a/erp24/migrations/m241218_073127_add_new_column_on_replacement_invoice.php b/erp24/migrations/m241218_073127_add_new_column_on_replacement_invoice.php
new file mode 100644 (file)
index 0000000..fdc011e
--- /dev/null
@@ -0,0 +1,51 @@
+<?php
+
+use yii\db\Migration;
+
+/**
+ * Class m241218_073127_add_new_column_on_replacement_invoice
+ */
+class m241218_073127_add_new_column_on_replacement_invoice extends Migration
+{
+    public function safeUp()
+    {
+        if ($this->db->getTableSchema('erp24.replacement_invoice', true)->getColumn('shift_transfer_id') == null) {
+            $this->addColumn('erp24.replacement_invoice', 'shift_transfer_id',  $this->integer()->comment('ID записи передачи смены'));
+        }
+
+        if ($this->db->getTableSchema('erp24.replacement_invoice', true)->getColumn('quantity') == null) {
+            $this->addColumn('erp24.replacement_invoice', 'quantity',  $this->float()->comment('Количество'));
+        }
+
+        if ($this->db->getTableSchema('erp24.replacement_invoice', true)->getColumn('summ') == null) {
+            $this->addColumn('erp24.replacement_invoice', 'summ',  $this->float()->comment('Сумма розничная'));
+        }
+
+        if ($this->db->getTableSchema('erp24.replacement_invoice', true)->getColumn('summ_self_cost') == null) {
+            $this->addColumn('erp24.replacement_invoice', 'summ_self_cost', $this->float()->comment('Сумма себестоимости'));
+        }
+
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function safeDown()
+    {
+        if ($this->db->getTableSchema('erp24.equalization_remains', true)->getColumn('shift_transfer_id') !== null) {
+            $this->dropColumn('erp24.replacement_invoice', 'shift_transfer_id');
+        }
+
+        if ($this->db->getTableSchema('erp24.replacement_invoice', true)->getColumn('quantity') !== null) {
+            $this->dropColumn('erp24.replacement_invoice', 'quantity');
+        }
+
+        if ($this->db->getTableSchema('erp24.replacement_invoice', true)->getColumn('summ') !== null) {
+            $this->dropColumn('erp24.replacement_invoice', 'summ');
+        }
+
+        if ($this->db->getTableSchema('erp24.replacement_invoice', true)->getColumn('summ_self_cost') !== null) {
+            $this->dropColumn('erp24.replacement_invoice', 'summ_self_cost');
+        }
+    }
+}
index eedbebf3fa6bdabc61c020400a88be99cf04ae81..8ecaa3f47899503cab5555ff72cce35f5f1c223d 100644 (file)
@@ -6,6 +6,7 @@ use Yii;
 use yii\behaviors\BlameableBehavior;
 use yii\behaviors\TimestampBehavior;
 use yii\data\ActiveDataProvider;
+use yii\db\Exception;
 use yii\db\Expression;
 use yii\helpers\ArrayHelper;
 
@@ -131,11 +132,10 @@ class EqualizationRemains extends \yii\db\ActiveRecord
                 'balance_self_cost' => $er['balance_self_cost'],
             ]);
 
-            if ($equalizationRemain->validate()) {
+            try {
                 $equalizationRemain->save();
-            } else {
-                var_dump($equalizationRemain->errors);
-                die();
+            } catch (\Exception $exception) {
+                throw new Exception($exception);
             }
         }
     }
index 996de30f0e03469bccd81a0119756aef22ef89e1..7510c55e02f8116159e25e6bfb0f9b2614d4f9af 100644 (file)
@@ -5,6 +5,7 @@ namespace yii_app\records;
 use Yii;
 use yii\behaviors\BlameableBehavior;
 use yii\behaviors\TimestampBehavior;
+use yii\db\Exception;
 use yii\db\Expression;
 use yii_app\helpers\DataHelper;
 
@@ -13,6 +14,7 @@ use yii_app\helpers\DataHelper;
  *
  * @property int $id ID
  * @property string $guid GUID документа для 1c
+ * @property int|null $shift_transfer_id ID записи передачи смены
  * @property int $status Статус документа
  * @property int $created_admin_id Создан пользователем
  * @property int|null $updated_admin_id Изменён пользователем
@@ -23,13 +25,15 @@ use yii_app\helpers\DataHelper;
  * @property string|null $number_1c Название документа в 1с
  * @property string $date Дата документа
  * @property string|null $comment Комментарий
+ * @property float $quantity Количество
+ * @property float $summ Сумма розничная
+ * @property float|null $summ_self_cost Сумма себестоимости
  * @property string $created_at Дата создания
  * @property string|null $updated_at Дата обновления
  * @property string|null $send_at Дата отправления в 1с
  */
 class ReplacementInvoice extends \yii\db\ActiveRecord
 {
-    public const REPLACEMENT_ACTIONS = 2;
     /**
      * {@inheritdoc}
      */
@@ -63,7 +67,7 @@ class ReplacementInvoice extends \yii\db\ActiveRecord
         return [
             [['guid', 'created_admin_id', 'store_id', 'store_guid', 'date', 'created_at'], 'required'],
             [['status', 'created_admin_id', 'updated_admin_id', 'confirm_admin_id', 'store_id'], 'default', 'value' => null],
-            [['status', 'created_admin_id', 'updated_admin_id', 'confirm_admin_id', 'store_id'], 'integer'],
+            [['status', 'created_admin_id', 'updated_admin_id', 'confirm_admin_id', 'store_id', 'quantity', 'summ', 'summ_self_cost', 'shift_transfer_id'], 'integer'],
             [['date', 'created_at', 'updated_at', 'send_at'], 'safe'],
             [['comment'], 'string'],
             [['guid', 'store_guid', 'number', 'number_1c'], 'string', 'max' => 100],
@@ -78,7 +82,8 @@ class ReplacementInvoice extends \yii\db\ActiveRecord
         $model = new self();
         $model->setAttributes([
             'guid' => $guid,
-            'status' => self::REPLACEMENT_ACTIONS,
+            'shift_transfer_id' => $shiftTransfer->id,
+            'status' => WriteOffsErp::STATUS_CREATED,
             'created_admin_id' => $shiftTransfer->end_shift_admin_id,
             'updated_admin_id' => $shiftTransfer->start_shift_admin_id,
             'confirm_admin_id' => $shiftTransfer->start_shift_admin_id,
@@ -89,12 +94,31 @@ class ReplacementInvoice extends \yii\db\ActiveRecord
             'created_at' => $shiftTransfer->date_start
         ]);
 
-        if ($model->validate()) {
+        try {
             $model->save();
-            $model->updateAttributes(['number' => 'ЕРП_ПС_' . date("Y-m-d_H-i") . '_' .$model->id]);
+            $model->updateAttributes(['number' => 'ЕРП_ПС_' . date("Y-m-d_H-i") . '_' . $model->id]);
+
             ReplacementInvoiceProducts::setData($model, $shiftTransfer);
-        } else {
-            var_dump($model->getErrors());
+
+            $summaries = ReplacementInvoiceProducts::find()
+                ->andWhere(['replacement_invoice_id' => $model->id])
+                ->select([
+                    'total_product_count' => 'sum(product_count)',
+                    'total_summ' => 'sum(summ)',
+                    'total_summ_self_cost' => 'sum(summ_self_cost)'
+                ])
+                ->asArray()
+                ->one();
+
+            if ($summaries) {
+                $model->updateAttributes([
+                    'quantity' => $summaries['total_product_count'],
+                    'summ' => $summaries['total_summ'],
+                    'summ_self_cost' => $summaries['total_summ_self_cost']
+                ]);
+            }
+        } catch (\Exception $exception) {
+            throw new \Exception($exception);
         }
     }
 
@@ -106,6 +130,7 @@ class ReplacementInvoice extends \yii\db\ActiveRecord
         return [
             'id' => 'ID',
             'guid' => 'GUID',
+            'shift_transfer_id' => 'ID записи передачи смены',
             'status' => 'Статус',
             'created_admin_id' => 'ID администратора (создатель)',
             'updated_admin_id' => 'ID администратора (редактировавший)',
@@ -115,6 +140,9 @@ class ReplacementInvoice extends \yii\db\ActiveRecord
             'number' => 'Номер',
             'number_1c' => 'Номер 1C',
             'date' => 'Дата',
+            'quantity' => 'Количество',
+            'summ' => 'Сумма розничная',
+            'summ_self_cost' => 'Сумма себестоимости',
             'comment' => 'Комментарий',
             'created_at' => 'Дата создания',
             'updated_at' => 'Дата обновления',
index 4f1194e494b2819d13aa214988cbef41368073e9..f6bf3555c4dad76d90117c6a6fac0aada54a20aa 100644 (file)
@@ -5,6 +5,7 @@ namespace yii_app\records;
 use Yii;
 use yii\behaviors\BlameableBehavior;
 use yii\behaviors\TimestampBehavior;
+use yii\db\Exception;
 use yii\db\Expression;
 
 /**
@@ -111,10 +112,11 @@ class ReplacementInvoiceProducts extends \yii\db\ActiveRecord
                 'updated_admin_id' => $equalizationRemain->updated_by,
             ]);
 
-            if ($expending->validate() && $incoming->validate()) {
-                $expending->save() && $incoming->save();
-            } else {
-                var_dump($expending->getErrors(), $incoming->getErrors());
+            try {
+                $expending->save();
+                $incoming->save();
+            } catch (\Exception $exception) {
+                throw new Exception($exception);
             }
         }
     }
index 6a8d88a1baf727b10f5b7b4ad80b70394121445b..307430619b00aebc1f22cf8c5974880e365a681c 100644 (file)
@@ -3,6 +3,7 @@
 namespace yii_app\records;
 
 use Yii;
+use yii\db\Exception;
 
 /**
  * This is the model class for table "store_balance".
@@ -77,10 +78,11 @@ class StoreBalance extends \yii\db\ActiveRecord
             'replace_articule' => $articule,
             'type_id' => self::REPLACEMENT_ACTIONS,
         ]);
-        if ($model->validate()) {
+
+        try {
             $model->save();
-        } else {
-            var_dump($model->errors);
+        } catch (\Exception $exception) {
+            throw new Exception($exception);
         }
     }
 
index 33af9f50dea488373859f3a53eab7bab19718d7c..ed2f2140d6b1b8ca748cdc910351e9ce2bbc836b 100644 (file)
@@ -92,7 +92,11 @@ class TimetableFactModel extends ActiveRecord
             [['checkin_start_id', 'checkin_end_id'], 'exist', 'targetClass' => AdminCheckin::class, 'targetAttribute' => 'id', 'skipOnEmpty' => true],
             [['admin_id', 'admin_id_add'], 'exist', 'targetClass' => Admin::class, 'targetAttribute' => 'id', 'skipOnEmpty' => true],
             [['store_id'], 'exist', 'targetClass' => CityStore::class, 'targetAttribute' => 'id', 'skipOnEmpty' => true],
-            [['time_start', 'time_end'], 'date', 'format' => 'HH:mm:ss'],
+            ['time_end', function($attribute) {
+                if (strtotime($this->$attribute) - strtotime($this->time_start) < 120) {
+                    $this->addError($attribute, 'Интервал между сменами должен быть не менее 2 минут.');
+                }
+            }],
 //            [['work_time'], 'number', 'min' => 0, 'max' => 24],
             [['comment'], 'string'],
             [['comment'], 'default', 'value' => null],
@@ -160,11 +164,9 @@ class TimetableFactModel extends ActiveRecord
         $model->is_opening = $is_start;
         $model->is_close = !$is_start;
 
-        if ($model->validate()) {
+        try {
             $model->save();
-        }
-
-        if ($model->getErrors()) {
+        } catch (\Exception $exception) {
             throw new \Exception($model->getErrors());
         }
     }