ImportReclamationsService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. <?php
  2. namespace App\Services;
  3. use App\Helpers\DateHelper;
  4. use App\Models\Import;
  5. use App\Models\Order;
  6. use App\Models\Product;
  7. use App\Models\ProductSKU;
  8. use App\Models\Reclamation;
  9. use Illuminate\Support\Str;
  10. class ImportReclamationsService extends ImportBaseService
  11. {
  12. const HEADERS = [
  13. 'Округ' => 'districts.name',
  14. 'Район' => 'areas.name',
  15. 'Адрес' => 'orders.object_address',
  16. 'Артикул' => 'products.article',
  17. 'Тип' => 'products.nomenclature_number',
  18. 'RFID' => 'products_sku.rfid',
  19. 'Гарантии' => 'reclamations.guarantee',
  20. 'Что сделано' => 'reclamations.whats_done',
  21. 'Дата создания' => 'reclamations.create_date',
  22. 'Дата начала работ' => 'reclamations.start_work_date',
  23. 'Дата завершения работ' => 'reclamations.finish_date',
  24. 'Год поставки МАФ' => 'orders.year',
  25. 'Причина' => 'reclamations.reason',
  26. 'Статус' => 'reclamation_statuses.name',
  27. 'Комментарий' => 'reclamations.comment',
  28. ];
  29. public function __construct(Import $import)
  30. {
  31. parent::__construct($import);
  32. $this->headers = self::HEADERS;
  33. }
  34. public function handle(): bool
  35. {
  36. if(!$this->prepare()) {
  37. return false;
  38. }
  39. $strNumber = 0;
  40. $result = [
  41. 'reclamationsCreated' => 0,
  42. 'mafAttached' => 0,
  43. ];
  44. $errors = [
  45. 'district_not_found' => [],
  46. 'area_not_found' => [],
  47. 'status_not_found' => [],
  48. 'order_not_found' => [],
  49. 'product_not_found' => [],
  50. 'sku_not_found' => [],
  51. 'exceptions' => [],
  52. ];
  53. foreach ($this->rowIterator as $row) {
  54. $r = $this->rowToArray($row);
  55. $strNumber++;
  56. if(1 === $strNumber) {
  57. echo $this->import->log('Skip headers Row: ' . $strNumber);
  58. continue;
  59. }
  60. try {
  61. $logMessage = "Row $strNumber: " . $r['orders.object_address'] . ". ";
  62. $year = (int)$r['orders.year'];
  63. // округ
  64. // if (!($districtId = $this->findId('districts.shortname', $r['districts.name'] ?? ''))) {
  65. // $errors['district_not_found'][] = $strNumber;
  66. // continue;
  67. // }
  68. // район
  69. // if (!($areaId = $this->findId('areas.name', $r['areas.name']))) {
  70. // $errors['area_not_found'][] = $strNumber;
  71. // continue;
  72. // }
  73. // manager
  74. $userId = config('app.default_maf_order_user_id');
  75. // status
  76. if (!($statusId = $this->findId('reclamation_statuses.name', $r['reclamation_statuses.name']))) {
  77. $errors['status_not_found'][] = $strNumber;
  78. continue;
  79. }
  80. // order
  81. // $order = Order::query()
  82. // ->withoutGlobalScopes()
  83. // ->where('year', $year)
  84. // ->where('object_address', $r['orders.object_address'])
  85. // ->first();
  86. // if (!$order) {
  87. // echo $this->import->log('Order NOT FOUND: ' . $r['orders.object_address'], 'WARNING');
  88. // $errors['order_not_found'][] = $strNumber;
  89. // continue;
  90. // } else {
  91. // $logMessage .= 'Found order: ' . $order->object_address . ". ";
  92. // }
  93. // product
  94. // $product = Product::query()
  95. // ->withoutGlobalScopes()
  96. // ->where('year', $year)
  97. // ->where('nomenclature_number', $r['products.nomenclature_number'])
  98. // ->first();
  99. // if (!$product) {
  100. // echo $this->import->log('Product not found: ' . $r['products.nomenclature_number'], 'WARNING');
  101. // $errors['product_not_found'][] = $strNumber;
  102. // continue;
  103. // }
  104. $rfid = Str::replace(' ', '', $r['products_sku.rfid']);
  105. // check maf with this nomenclature number in order
  106. $productSKU = ProductSKU::query()
  107. ->withoutGlobalScopes()
  108. // ->where('year', $year)
  109. // ->where('product_id', $product->id)
  110. // ->where('order_id', $order->id)
  111. ->where('rfid', $rfid)
  112. ->first();
  113. if (!$productSKU) {
  114. echo $this->import->log('SKU not found: ' . $r['products.nomenclature_number'] . '(RFID: ' . $r['products_sku.rfid'] . ')', 'WARNING');
  115. $errors['sku_not_found'][] = $strNumber;
  116. continue;
  117. }
  118. $order = Order::query()->withoutGlobalScopes()->where('id', $productSKU->order_id)->first();
  119. $createDate = ($r['reclamations.create_date']) ? DateHelper::excelDateToISODate($r['reclamations.create_date']) : null;
  120. $finishDate = ($r['reclamations.finish_date']) ? DateHelper::excelDateToISODate($r['reclamations.finish_date']) : null;
  121. $startWorkDate = ($r['reclamations.start_work_date']) ? DateHelper::excelDateToISODate($r['reclamations.start_work_date']) : null;
  122. // reclamation
  123. $reclamation = Reclamation::query()
  124. ->where('order_id', $order->id)
  125. ->where('status_id', $statusId)
  126. ->where('create_date', $createDate)
  127. ->where('finish_date', $finishDate)
  128. ->where('start_work_date', $startWorkDate)
  129. ->where('reason', $r['reclamations.reason'])
  130. ->where('whats_done', $r['reclamations.whats_done'])
  131. ->where('guarantee', $r['reclamations.guarantee'])
  132. ->first();
  133. if (!$reclamation) {
  134. $reclamation = Reclamation::query()
  135. ->create([
  136. 'order_id' => $order->id,
  137. 'user_id' => $userId,
  138. 'status_id' => $statusId,
  139. 'create_date' => $createDate,
  140. 'finish_date' => $finishDate,
  141. 'reason' => $r['reclamations.reason'],
  142. 'guarantee' => $r['reclamations.guarantee'],
  143. 'whats_done' => $r['reclamations.whats_done'],
  144. 'start_work_date' => $startWorkDate,
  145. 'comment' => $r['reclamations.comment'],
  146. ]);
  147. $logMessage .= 'Reclamation created: ' . $r['orders.object_address'] . ". ";
  148. $result['reclamationsCreated']++;
  149. } else {
  150. $logMessage .= 'Reclamation found: ' . $r['orders.object_address']. ". ";
  151. }
  152. if (!$reclamation->skus->contains($productSKU)) {
  153. $reclamation->skus()->syncWithoutDetaching($productSKU->id);
  154. $logMessage .= 'Attached MAF to reclamation, maf_id: ' . $productSKU->id . ". ";
  155. $result['mafAttached']++;
  156. } else {
  157. $logMessage .= 'MAF already attached!';
  158. }
  159. echo $this->import->log($logMessage);
  160. } catch(\Exception $e) {
  161. echo $this->import->log($e->getMessage(), 'WARNING');
  162. $errors['exceptions'][] = $strNumber;
  163. }
  164. }
  165. echo $this->import->log(print_r($result, true));
  166. // Резюме по ошибкам
  167. $totalErrors = array_sum(array_map('count', $errors));
  168. if ($totalErrors > 0) {
  169. echo $this->import->log('--- РЕЗЮМЕ ПО ОШИБКАМ ---');
  170. if (count($errors['district_not_found']) > 0) {
  171. $rows = implode(', ', $errors['district_not_found']);
  172. echo $this->import->log("Округ не найден: " . count($errors['district_not_found']) . " ({$rows})", 'WARNING');
  173. }
  174. if (count($errors['area_not_found']) > 0) {
  175. $rows = implode(', ', $errors['area_not_found']);
  176. echo $this->import->log("Район не найден: " . count($errors['area_not_found']) . " ({$rows})", 'WARNING');
  177. }
  178. if (count($errors['status_not_found']) > 0) {
  179. $rows = implode(', ', $errors['status_not_found']);
  180. echo $this->import->log("Статус не найден: " . count($errors['status_not_found']) . " ({$rows})", 'WARNING');
  181. }
  182. if (count($errors['order_not_found']) > 0) {
  183. $rows = implode(', ', $errors['order_not_found']);
  184. echo $this->import->log("Заказ не найден: " . count($errors['order_not_found']) . " ({$rows})", 'WARNING');
  185. }
  186. if (count($errors['product_not_found']) > 0) {
  187. $rows = implode(', ', $errors['product_not_found']);
  188. echo $this->import->log("Товар не найден: " . count($errors['product_not_found']) . " ({$rows})", 'WARNING');
  189. }
  190. if (count($errors['sku_not_found']) > 0) {
  191. $rows = implode(', ', $errors['sku_not_found']);
  192. echo $this->import->log("МАФ (SKU) не найден: " . count($errors['sku_not_found']) . " ({$rows})", 'WARNING');
  193. }
  194. if (count($errors['exceptions']) > 0) {
  195. $rows = implode(', ', $errors['exceptions']);
  196. echo $this->import->log("Исключения: " . count($errors['exceptions']) . " ({$rows})", 'WARNING');
  197. }
  198. echo $this->import->log("Всего ошибок: {$totalErrors}", 'WARNING');
  199. } else {
  200. echo $this->import->log('Импорт завершён без ошибок');
  201. }
  202. $this->import->status = 'DONE';
  203. $this->import->save();
  204. return true;
  205. }
  206. }