ImportReclamationsService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. $productSKU = ProductSKU::query()
  115. ->where('year', $year)
  116. ->where('product_id', $product->id)
  117. ->where('order_id', $order->id)
  118. ->first();
  119. }
  120. if (!$productSKU) {
  121. echo $this->import->log('SKU not found: ' . $r['products.nomenclature_number'], 'WARNING');
  122. $errors['sku_not_found'][] = $strNumber;
  123. continue;
  124. }
  125. $createDate = ($r['reclamations.create_date']) ? DateHelper::excelDateToISODate($r['reclamations.create_date']) : null;
  126. $finishDate = ($r['reclamations.finish_date']) ? DateHelper::excelDateToISODate($r['reclamations.finish_date']) : null;
  127. $startWorkDate = ($r['reclamations.start_work_date']) ? DateHelper::excelDateToISODate($r['reclamations.start_work_date']) : null;
  128. // reclamation
  129. $reclamation = Reclamation::query()
  130. ->where('order_id', $order->id)
  131. ->where('status_id', $statusId)
  132. ->where('create_date', $createDate)
  133. ->where('finish_date', $finishDate)
  134. ->where('start_work_date', $startWorkDate)
  135. ->where('reason', $r['reclamations.reason'])
  136. ->where('whats_done', $r['reclamations.whats_done'])
  137. ->where('guarantee', $r['reclamations.guarantee'])
  138. ->first();
  139. if (!$reclamation) {
  140. $reclamation = Reclamation::query()
  141. ->create([
  142. 'order_id' => $order->id,
  143. 'user_id' => $userId,
  144. 'status_id' => $statusId,
  145. 'create_date' => $createDate,
  146. 'finish_date' => $finishDate,
  147. 'reason' => $r['reclamations.reason'],
  148. 'guarantee' => $r['reclamations.guarantee'],
  149. 'whats_done' => $r['reclamations.whats_done'],
  150. 'start_work_date' => $startWorkDate,
  151. 'comment' => $r['reclamations.comment'],
  152. ]);
  153. $logMessage .= 'Reclamation created: ' . $r['orders.object_address'] . ". ";
  154. $result['reclamationsCreated']++;
  155. } else {
  156. $logMessage .= 'Reclamation found: ' . $r['orders.object_address']. ". ";
  157. }
  158. if (!$reclamation->skus->contains($productSKU)) {
  159. $reclamation->skus()->syncWithoutDetaching($productSKU->id);
  160. $logMessage .= 'Attached MAF to reclamation, maf_id: ' . $productSKU->id . ". ";
  161. $result['mafAttached']++;
  162. } else {
  163. $logMessage .= 'MAF already attached!';
  164. }
  165. echo $this->import->log($logMessage);
  166. } catch(\Exception $e) {
  167. echo $this->import->log($e->getMessage(), 'WARNING');
  168. $errors['exceptions'][] = $strNumber;
  169. }
  170. }
  171. echo $this->import->log(print_r($result, true));
  172. // Резюме по ошибкам
  173. $totalErrors = array_sum(array_map('count', $errors));
  174. if ($totalErrors > 0) {
  175. echo $this->import->log('--- РЕЗЮМЕ ПО ОШИБКАМ ---');
  176. if (count($errors['district_not_found']) > 0) {
  177. $rows = implode(', ', $errors['district_not_found']);
  178. echo $this->import->log("Округ не найден: " . count($errors['district_not_found']) . " ({$rows})", 'WARNING');
  179. }
  180. if (count($errors['area_not_found']) > 0) {
  181. $rows = implode(', ', $errors['area_not_found']);
  182. echo $this->import->log("Район не найден: " . count($errors['area_not_found']) . " ({$rows})", 'WARNING');
  183. }
  184. if (count($errors['status_not_found']) > 0) {
  185. $rows = implode(', ', $errors['status_not_found']);
  186. echo $this->import->log("Статус не найден: " . count($errors['status_not_found']) . " ({$rows})", 'WARNING');
  187. }
  188. if (count($errors['order_not_found']) > 0) {
  189. $rows = implode(', ', $errors['order_not_found']);
  190. echo $this->import->log("Заказ не найден: " . count($errors['order_not_found']) . " ({$rows})", 'WARNING');
  191. }
  192. if (count($errors['product_not_found']) > 0) {
  193. $rows = implode(', ', $errors['product_not_found']);
  194. echo $this->import->log("Товар не найден: " . count($errors['product_not_found']) . " ({$rows})", 'WARNING');
  195. }
  196. if (count($errors['sku_not_found']) > 0) {
  197. $rows = implode(', ', $errors['sku_not_found']);
  198. echo $this->import->log("МАФ (SKU) не найден: " . count($errors['sku_not_found']) . " ({$rows})", 'WARNING');
  199. }
  200. if (count($errors['exceptions']) > 0) {
  201. $rows = implode(', ', $errors['exceptions']);
  202. echo $this->import->log("Исключения: " . count($errors['exceptions']) . " ({$rows})", 'WARNING');
  203. }
  204. echo $this->import->log("Всего ошибок: {$totalErrors}", 'WARNING');
  205. } else {
  206. echo $this->import->log('Импорт завершён без ошибок');
  207. }
  208. $this->import->status = 'DONE';
  209. $this->import->save();
  210. return true;
  211. }
  212. }