ImportOrdersService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <?php
  2. namespace App\Services;
  3. use App\Helpers\DateHelper;
  4. use App\Models\Import;
  5. use App\Models\MafOrder;
  6. use App\Models\Order;
  7. use App\Models\Product;
  8. use App\Models\ProductSKU;
  9. use Exception;
  10. class ImportOrdersService extends ImportBaseService
  11. {
  12. const HEADERS = [
  13. 'Округ' => 'districts.name',
  14. 'Район' => 'areas.name',
  15. 'Название площадки' => 'orders.name',
  16. 'Адрес объекта' => 'orders.object_address',
  17. 'Тип объекта' => 'object_types.name',
  18. 'Артикул' => 'products.article',
  19. 'Номер номенклатуры' => 'products.nomenclature_number',
  20. 'Габаритные размеры' => 'products.sizes',
  21. 'RFID' => 'products_sku.rfid',
  22. 'Наименование производителя' => 'products.manufacturer_name',
  23. 'Наименование по ТЗ' => 'products.name_tz',
  24. 'Тип по тз' => 'products.type_tz',
  25. 'ТИП' => 'products.type',
  26. 'Цена товара' => 'products.product_price',
  27. 'Цена установки' => 'products.installation_price',
  28. 'Итоговая цена' => 'products.total_price',
  29. 'Примечание' => 'products.note',
  30. 'Год установки' => 'orders.year',
  31. 'Номер заказа МАФ' => 'maf_orders.order_number',
  32. '№ Ведомости' => 'products_sku.statement_number',
  33. 'Дата ведомости' => 'products_sku.statement_date',
  34. '№УПД' => 'products_sku.upd_number',
  35. 'Статус' => 'order_statuses.name',
  36. 'Комментарий' => 'orders.comment',
  37. 'Менеджер' => 'users.name',
  38. 'Номер фабрики' => 'products_sku.factory_number',
  39. 'Дата пр-ва' => 'products_sku.manufacture_date',
  40. 'Срок эксплуатации (месяцев)' => 'products.service_life',
  41. '№ сертификата' => 'products.certificate_number',
  42. 'Дата выдачи' => 'products.certificate_date',
  43. 'Орган сертификации' => 'products.certificate_issuer',
  44. 'ТИП (Декларация/Сертификат/Отказное)' => 'products.certificate_type',
  45. // заголовки из файла для проверки и маппинга
  46. ];
  47. public function __construct(Import $import)
  48. {
  49. parent::__construct($import);
  50. $this->headers = self::HEADERS;
  51. }
  52. public function handle(): bool
  53. {
  54. try {
  55. $this->import->log('Reading file...');
  56. $this->readFile();
  57. } catch (Exception $exception){
  58. $this->import->log($exception->getMessage(), 'ERROR');
  59. $this->import->status = 'ERROR';
  60. $this->import->save();
  61. return false;
  62. }
  63. try {
  64. $this->import->log('Checking headers...');
  65. $headers = $this->rowToArray($this->rowIterator->current());
  66. if (!$this->checkHeaders(array_values($headers))) {
  67. throw new Exception("Invalid headers");
  68. }
  69. } catch (Exception $exception){
  70. $this->import->log($exception->getMessage(), 'ERROR');
  71. $this->import->status = 'ERROR';
  72. $this->import->save();
  73. return false;
  74. }
  75. $this->rowIterator->next();
  76. $strNumber = 0;
  77. $result = [
  78. 'productsCreated' => 0,
  79. 'ordersCreated' => 0,
  80. 'mafOrdersCreated' => 0,
  81. 'productsSkuCreated' => 0,
  82. ];
  83. foreach($this->rowIterator as $row){
  84. $strNumber++;
  85. $r = $this->rowToArray($row);
  86. if($strNumber === 1) {
  87. echo $this->import->log('Skip headers Row: ' . $strNumber);
  88. continue;
  89. }
  90. echo $this->import->log("Row $strNumber: " . $r['orders.object_address']);
  91. $year = (int) $r['orders.year'];
  92. // округ
  93. if(!($districtId = $this->findId('districts.shortname', $r['districts.name']))) {
  94. continue;
  95. }
  96. // район
  97. if(!($areaId = $this->findId('areas.name', $r['areas.name']))) {
  98. continue;
  99. }
  100. // manager
  101. if(!($userId = $this->findId('users.name', $r['users.name']))) {
  102. continue;
  103. }
  104. // object_type
  105. if(!($objectTypeId = $this->findId('object_types.name', $r['object_types.name']))) {
  106. continue;
  107. }
  108. // order_statuses.name
  109. if(!($orderStatusId = $this->findId('order_statuses.name', $r['order_statuses.name']))) {
  110. continue;
  111. }
  112. // product
  113. $product = Product::query()
  114. ->where('year', $year)
  115. ->where('nomenclature_number', $r['products.nomenclature_number'])
  116. ->first();
  117. if(!$product) {
  118. $product = Product::query()
  119. ->create([
  120. 'year' => $year,
  121. 'article' => $r['products.article'],
  122. 'nomenclature_number' => $r['products.nomenclature_number'],
  123. 'manufacturer_name' => $r['products.manufacturer_name'],
  124. 'name_tz' => $r['products.name_tz'],
  125. 'type' => $r['products.type'],
  126. 'type_tz' => $r['products.type_tz'],
  127. 'product_price' => $r['products.product_price'],
  128. 'installation_price' => $r['products.installation_price'],
  129. 'total_price' => $r['products.total_price'],
  130. 'note' => $r['products.note'],
  131. 'service_life' => $r['products.service_life'],
  132. 'certificate_number' => $r['products.certificate_number'],
  133. 'certificate_date' => is_int($r['products.certificate_date']) ? DateHelper::excelDateToISODate($r['products.certificate_date']) : null,
  134. 'certificate_issuer' => $r['products.certificate_issuer'],
  135. 'certificate_type' => $r['products.certificate_type'],
  136. 'sizes' => $r['products.sizes'],
  137. 'unit' => 'шт.',
  138. 'passport_name' => $r['products.manufacturer_name'],
  139. 'statement_name' => $r['products.name_tz'],
  140. 'manufacturer' => 'Наш двор',
  141. ]);
  142. echo $this->import->log('Created product: ' . $product->name_tz);
  143. $result['productsCreated'] += 1;
  144. } else {
  145. echo $this->import->log('Found product: ' . $product->name_tz);
  146. }
  147. // order
  148. $order = Order::query()
  149. ->where('year', $year)
  150. ->where('object_address', $r['orders.object_address'])
  151. ->first();
  152. if(!$order) {
  153. $order = Order::query()
  154. ->create([
  155. 'year' => $year,
  156. 'name' => $r['orders.object_address'],
  157. 'user_id' => $userId,
  158. 'district_id' => $districtId,
  159. 'area_id' => $areaId,
  160. 'object_address' => $r['orders.object_address'],
  161. 'object_type_id' => $objectTypeId,
  162. 'comment' => $r['orders.comment'],
  163. 'order_status_id' => $orderStatusId,
  164. 'tg_group_name' => '/' . $r['districts.name'] . ' ' . $r['orders.object_address'] . ' (' . $r['areas.name'] . ')' . ' - ' . $r['users.name'],
  165. 'tg_group_link' => '',
  166. ]);
  167. echo $this->import->log('Created order: ' . $order->object_address);
  168. $result['ordersCreated'] += 1;
  169. } else {
  170. echo $this->import->log('Found order: ' . $order->object_address);
  171. }
  172. // maf order
  173. if ($r['maf_orders.order_number'] != '') {
  174. $mafOrder = MafOrder::query()
  175. ->where('year', $year)
  176. ->where('product_id', $product->id)
  177. ->where('order_number', $r['maf_orders.order_number'])
  178. ->first();
  179. if(!$mafOrder) {
  180. $mafOrder = MafOrder::query()
  181. ->create([
  182. 'year' => $year,
  183. 'order_number' => $r['maf_orders.order_number'],
  184. 'user_id' => config('app.default_maf_order_user_id'),
  185. 'status' => 'на складе',
  186. 'product_id' => $product->id,
  187. 'quantity' => 1,
  188. 'in_stock' => 0,
  189. ]);
  190. echo $this->import->log('Created maf order: ' . $mafOrder->order_number);
  191. $result['mafOrdersCreated'] += 1;
  192. } else {
  193. echo $this->import->log('Found maf order: ' . $mafOrder->order_number);
  194. $mafOrder->quantity += 1;
  195. $mafOrder->save();
  196. echo $this->import->log('Incremented maf order: ' . $mafOrder->quantity);
  197. }
  198. } else {
  199. $mafOrder = null;
  200. }
  201. // search rfid in products_sku
  202. $manufacture_date = is_int($r['products_sku.manufacture_date']) ? DateHelper::excelDateToISODate($r['products_sku.manufacture_date']) : null;
  203. $statement_date = is_int($r['products_sku.statement_date']) ? DateHelper::excelDateToISODate($r['products_sku.statement_date']) : null;
  204. $productSKU = ProductSKU::query()
  205. ->where('year', $year)
  206. ->where('rfid', $r['products_sku.rfid'])
  207. ->where('product_id', $product->id)
  208. ->where('order_id', $order->id)
  209. ->where('maf_order_id', $mafOrder?->id)
  210. ->where('factory_number', $r['products_sku.factory_number'])
  211. ->where('statement_number', $r['products_sku.statement_number'])
  212. ->where('upd_number', $r['products_sku.upd_number'])
  213. ->where('statement_date', $statement_date)
  214. ->where('manufacture_date', $manufacture_date)
  215. ->first();
  216. // dd($productSKU->toRawSql());
  217. if($productSKU) {
  218. echo $this->import->log('Found product with rfid: ' . $productSKU->rfid . ' Skip.');
  219. continue;
  220. } else {
  221. $productSKU = ProductSKU::query()->create([
  222. 'year' => $year,
  223. 'product_id' => $product->id,
  224. 'order_id' => $order->id,
  225. 'maf_order_id' => $mafOrder?->id,
  226. 'status' => ($mafOrder?->id) ? 'отгружен' : 'требуется',
  227. 'rfid' => $r['products_sku.rfid'],
  228. 'factory_number' => $r['products_sku.factory_number'],
  229. 'manufacture_date' => $manufacture_date,
  230. 'statement_number' => $r['products_sku.statement_number'],
  231. 'statement_date' => $statement_date,
  232. 'upd_number' => $r['products_sku.upd_number'],
  233. ]);
  234. $result['productsSkuCreated'] += 1;
  235. echo $this->import->log('Created product sku: ' . $productSKU->id);
  236. }
  237. }
  238. echo $this->import->log(print_r($result, true));
  239. $this->import->status = 'DONE';
  240. $this->import->save();
  241. return true;
  242. }
  243. }