ImportReclamationsServiceTest.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?php
  2. namespace Tests\Unit\Services\Import;
  3. use App\Models\Import;
  4. use App\Models\Order;
  5. use App\Models\Product;
  6. use App\Models\ProductSKU;
  7. use App\Models\Reclamation;
  8. use App\Models\ReclamationStatus;
  9. use App\Models\ReclamationType;
  10. use App\Models\User;
  11. use App\Services\ImportReclamationsService;
  12. use Illuminate\Foundation\Testing\RefreshDatabase;
  13. use Illuminate\Support\Facades\Storage;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
  16. use Tests\TestCase;
  17. class ImportReclamationsServiceTest extends TestCase
  18. {
  19. use RefreshDatabase;
  20. protected $seed = true;
  21. private array $tempFiles = [];
  22. protected function tearDown(): void
  23. {
  24. foreach ($this->tempFiles as $path) {
  25. if (file_exists($path)) {
  26. unlink($path);
  27. }
  28. }
  29. parent::tearDown();
  30. }
  31. // -------------------------------------------------------------------------
  32. // Helper: create xlsx file with reclamation headers and optional data rows,
  33. // upload it to Storage::disk('upload') and return the Import model.
  34. // -------------------------------------------------------------------------
  35. private function createImportWithFile(array $dataRows = [], ?array $customHeaders = null): Import
  36. {
  37. $import = Import::factory()->create([
  38. 'type' => 'reclamations',
  39. 'filename' => 'test_reclamations_' . uniqid() . '.xlsx',
  40. 'status' => 'new',
  41. ]);
  42. $tempPath = $this->buildXlsxFile($customHeaders ?? array_keys(ImportReclamationsService::HEADERS), $dataRows);
  43. Storage::fake('upload');
  44. Storage::disk('upload')->put($import->filename, file_get_contents($tempPath));
  45. return $import;
  46. }
  47. private function buildXlsxFile(array $headers, array $dataRows): string
  48. {
  49. $spreadsheet = new Spreadsheet();
  50. $sheet = $spreadsheet->getActiveSheet();
  51. // Write headers in row 1
  52. foreach ($headers as $colIdx => $header) {
  53. $sheet->setCellValue(chr(65 + $colIdx) . '1', $header);
  54. }
  55. // Write data rows starting from row 2
  56. foreach ($dataRows as $rowIdx => $row) {
  57. foreach ($row as $colIdx => $value) {
  58. $sheet->setCellValue(chr(65 + $colIdx) . ($rowIdx + 2), $value);
  59. }
  60. }
  61. $path = sys_get_temp_dir() . '/test_reclamations_' . uniqid() . '.xlsx';
  62. (new XlsxWriter($spreadsheet))->save($path);
  63. $this->tempFiles[] = $path;
  64. return $path;
  65. }
  66. // -------------------------------------------------------------------------
  67. // Tests
  68. // -------------------------------------------------------------------------
  69. /**
  70. * When the file does not exist in the upload disk, prepare() should fail
  71. * and handle() must return false.
  72. */
  73. public function test_handle_returns_false_when_file_not_found(): void
  74. {
  75. Storage::fake('upload');
  76. $import = Import::factory()->create([
  77. 'type' => 'reclamations',
  78. 'filename' => 'nonexistent_file_' . uniqid() . '.xlsx',
  79. 'status' => 'new',
  80. ]);
  81. $service = new ImportReclamationsService($import);
  82. $result = $service->handle();
  83. $this->assertFalse($result);
  84. }
  85. /**
  86. * A file that exists but has wrong column headers must cause prepare() to
  87. * throw "Invalid headers", so handle() returns false.
  88. */
  89. public function test_handle_returns_false_with_wrong_headers(): void
  90. {
  91. $import = $this->createImportWithFile([], ['Wrong', 'Headers', 'Here']);
  92. $service = new ImportReclamationsService($import);
  93. $result = $service->handle();
  94. $this->assertFalse($result);
  95. }
  96. /**
  97. * Correct headers, one data row, but the status name in the row does not
  98. * match any row in reclamation_statuses → the row is skipped with
  99. * status_not_found, but handle() still returns true (processing completes).
  100. */
  101. public function test_handle_returns_false_when_status_not_found(): void
  102. {
  103. $import = $this->createImportWithFile([
  104. [
  105. 'Округ ЦАО', // Округ
  106. 'Тверской', // Район
  107. 'ул. Тестовая, 1', // Адрес
  108. 'ART-001', // Артикул
  109. '1.01.01', // Тип
  110. 'RFID-UNKNOWN-999', // RFID
  111. 'Нет', // Гарантии
  112. 'Покраска', // Что сделано
  113. 45000, // Дата создания (excel serial)
  114. 45001, // Дата начала работ
  115. 45002, // Дата завершения работ
  116. 2024, // Год поставки МАФ
  117. 'Вандализм', // Причина
  118. 'НесуществующийСтатус', // Статус
  119. '', // Комментарий
  120. ],
  121. ]);
  122. $service = new ImportReclamationsService($import);
  123. // handle() returns true (the import ran), but the row was skipped
  124. $result = $service->handle();
  125. $this->assertTrue($result);
  126. $this->assertDatabaseMissing('reclamations', ['reason' => 'Вандализм']);
  127. }
  128. /**
  129. * Full happy path: a ProductSKU with a known RFID exists, the status
  130. * exists in the DB (seeded), the import creates a Reclamation and attaches
  131. * the SKU to it.
  132. */
  133. public function test_handle_creates_reclamation_when_sku_found(): void
  134. {
  135. // ReclamationStatus is seeded via $seed = true (ReclamationStatusSeeder).
  136. $status = ReclamationStatus::query()->first();
  137. $this->assertNotNull($status, 'ReclamationStatusSeeder must create at least one status');
  138. // Create a user and set it as the default MAF order user to avoid FK errors
  139. $user = User::factory()->create();
  140. \App\Models\Setting::set(
  141. \App\Models\Setting::KEY_DEFAULT_MAF_ORDER_USER_ID,
  142. $user->id
  143. );
  144. $order = Order::factory()->create(['year' => (int) date('Y')]);
  145. $product = Product::factory()->create(['year' => (int) date('Y')]);
  146. $rfid = 'RFID-TEST-' . uniqid();
  147. $sku = ProductSKU::factory()->create([
  148. 'rfid' => $rfid,
  149. 'order_id' => $order->id,
  150. 'product_id' => $product->id,
  151. 'year' => (int) date('Y'),
  152. ]);
  153. $import = $this->createImportWithFile([
  154. [
  155. 'Округ ЦАО', // Округ
  156. 'Тверской', // Район
  157. 'ул. Тестовая, 1', // Адрес
  158. 'ART-001', // Артикул
  159. '1.01.01', // Тип
  160. $rfid, // RFID
  161. 'Нет', // Гарантии
  162. 'Покраска', // Что сделано
  163. 46023, // Дата создания (2026-01-01 в Excel serial)
  164. 46024, // Дата начала работ (2026-01-02)
  165. 46054, // Дата завершения работ (2026-02-01)
  166. (int) date('Y'), // Год поставки МАФ
  167. 'Вандализм', // Причина
  168. $status->name, // Статус
  169. 'Тест комментарий',// Комментарий
  170. ],
  171. ]);
  172. $service = new ImportReclamationsService($import);
  173. $result = $service->handle();
  174. $this->assertTrue($result);
  175. $this->assertDatabaseHas('reclamations', [
  176. 'order_id' => $order->id,
  177. 'reclamation_type_id' => ReclamationType::idForCode(ReclamationType::CODE_DKR),
  178. 'status_id' => $status->id,
  179. 'reason' => 'Вандализм',
  180. ]);
  181. }
  182. /**
  183. * When the RFID in the row does not match any ProductSKU the row is
  184. * logged with sku_not_found and skipped; handle() still returns true.
  185. */
  186. public function test_handle_skips_row_when_sku_not_found(): void
  187. {
  188. $status = ReclamationStatus::query()->first();
  189. $this->assertNotNull($status);
  190. $import = $this->createImportWithFile([
  191. [
  192. 'Округ ЦАО',
  193. 'Тверской',
  194. 'ул. Тестовая, 1',
  195. 'ART-001',
  196. '1.01.01',
  197. 'RFID-DOES-NOT-EXIST-' . uniqid(), // unknown RFID
  198. 'Нет',
  199. 'Покраска',
  200. '',
  201. '',
  202. '',
  203. (int) date('Y'),
  204. 'Вандализм',
  205. $status->name,
  206. '',
  207. ],
  208. ]);
  209. $service = new ImportReclamationsService($import);
  210. $result = $service->handle();
  211. $this->assertTrue($result);
  212. $this->assertDatabaseMissing('reclamations', ['reason' => 'Вандализм']);
  213. }
  214. /**
  215. * A file that contains only the header row (no data rows) should be
  216. * processed successfully and return true.
  217. */
  218. public function test_handle_returns_true_with_empty_data_rows(): void
  219. {
  220. $import = $this->createImportWithFile([]);
  221. $service = new ImportReclamationsService($import);
  222. $result = $service->handle();
  223. $this->assertTrue($result);
  224. }
  225. }