ImportOrdersServiceTest.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. namespace Tests\Unit\Services;
  3. use App\Models\Dictionary\Area;
  4. use App\Models\Dictionary\District;
  5. use App\Models\Import;
  6. use App\Models\MafOrder;
  7. use App\Models\ObjectType;
  8. use App\Models\Order;
  9. use App\Models\OrderStatus;
  10. use App\Models\Product;
  11. use App\Models\ProductSKU;
  12. use App\Models\User;
  13. use App\Services\ImportOrdersService;
  14. use Illuminate\Foundation\Testing\RefreshDatabase;
  15. use Illuminate\Support\Facades\Storage;
  16. use Tests\TestCase;
  17. class ImportOrdersServiceTest extends TestCase
  18. {
  19. use RefreshDatabase;
  20. protected $seed = true;
  21. private string $testFilePath = 'tests/fixtures/test_orders_import.xlsx';
  22. protected function setUp(): void
  23. {
  24. parent::setUp();
  25. // Copy test file to upload storage if it exists
  26. if (file_exists(base_path($this->testFilePath))) {
  27. Storage::disk('upload')->put(
  28. 'test_orders_import.xlsx',
  29. file_get_contents(base_path($this->testFilePath))
  30. );
  31. }
  32. }
  33. protected function tearDown(): void
  34. {
  35. Storage::disk('upload')->delete('test_orders_import.xlsx');
  36. parent::tearDown();
  37. }
  38. private function createReferenceData(): array
  39. {
  40. $district = District::factory()->create(['name' => 'ЦАО', 'shortname' => 'ЦАО']);
  41. $area = Area::factory()->create(['name' => 'Тверской', 'district_id' => $district->id]);
  42. $user = User::factory()->create(['name' => 'Тест Менеджер']);
  43. $objectType = ObjectType::factory()->create(['name' => 'Детская площадка']);
  44. $orderStatus = OrderStatus::firstOrCreate(['name' => 'Новый']);
  45. // Create a user for MAF orders and set it in settings to avoid FK errors
  46. $mafUser = User::factory()->create(['name' => 'MAF User']);
  47. \App\Models\Setting::set(
  48. \App\Models\Setting::KEY_DEFAULT_MAF_ORDER_USER_ID,
  49. $mafUser->id
  50. );
  51. return compact('district', 'area', 'user', 'objectType', 'orderStatus');
  52. }
  53. private function hasTestFile(): bool
  54. {
  55. return file_exists(base_path($this->testFilePath));
  56. }
  57. // ==================== Constants ====================
  58. public function test_service_has_headers_mapping(): void
  59. {
  60. $this->assertIsArray(ImportOrdersService::HEADERS);
  61. $this->assertArrayHasKey('Округ', ImportOrdersService::HEADERS);
  62. $this->assertArrayHasKey('Район', ImportOrdersService::HEADERS);
  63. $this->assertArrayHasKey('Адрес объекта', ImportOrdersService::HEADERS);
  64. $this->assertArrayHasKey('Артикул', ImportOrdersService::HEADERS);
  65. $this->assertArrayHasKey('Год установки', ImportOrdersService::HEADERS);
  66. }
  67. public function test_headers_mapping_contains_required_fields(): void
  68. {
  69. $headers = ImportOrdersService::HEADERS;
  70. // Order fields
  71. $this->assertEquals('orders.name', $headers['Название площадки']);
  72. $this->assertEquals('orders.object_address', $headers['Адрес объекта']);
  73. $this->assertEquals('orders.year', $headers['Год установки']);
  74. // Product fields
  75. $this->assertEquals('products.article', $headers['Артикул']);
  76. $this->assertEquals('products.nomenclature_number', $headers['Номер номенклатуры']);
  77. // References
  78. $this->assertEquals('districts.name', $headers['Округ']);
  79. $this->assertEquals('areas.name', $headers['Район']);
  80. $this->assertEquals('users.name', $headers['Менеджер']);
  81. }
  82. // ==================== Service instantiation ====================
  83. public function test_service_can_be_instantiated(): void
  84. {
  85. $import = Import::factory()->create();
  86. $service = new ImportOrdersService($import);
  87. $this->assertInstanceOf(ImportOrdersService::class, $service);
  88. }
  89. // ==================== Handle method (requires Excel file) ====================
  90. public function test_handle_returns_false_when_file_not_found(): void
  91. {
  92. $import = Import::factory()->create([
  93. 'filename' => 'non_existent_file.xlsx',
  94. 'status' => 'PENDING',
  95. ]);
  96. $service = new ImportOrdersService($import);
  97. $result = $service->handle();
  98. $this->assertFalse($result);
  99. $import->refresh();
  100. $this->assertEquals('ERROR', $import->status);
  101. }
  102. // ==================== Integration tests ====================
  103. public function test_import_creates_order_from_valid_row(): void
  104. {
  105. if (!$this->hasTestFile()) {
  106. $this->markTestSkipped('Requires valid Excel test file at ' . $this->testFilePath);
  107. }
  108. $this->createReferenceData();
  109. $import = Import::factory()->create([
  110. 'filename' => 'test_orders_import.xlsx',
  111. 'status' => 'PENDING',
  112. ]);
  113. $initialOrderCount = Order::withoutGlobalScopes()->count();
  114. $initialProductCount = Product::withoutGlobalScopes()->count();
  115. $service = new ImportOrdersService($import);
  116. $result = $service->handle();
  117. $this->assertTrue($result);
  118. $import->refresh();
  119. $this->assertEquals('DONE', $import->status);
  120. // Should create 2 orders (rows 1,2 same address; row 5 different address; row 3 skipped; row 4 duplicate)
  121. $this->assertGreaterThan($initialOrderCount, Order::withoutGlobalScopes()->count());
  122. // Should create products
  123. $this->assertGreaterThan($initialProductCount, Product::withoutGlobalScopes()->count());
  124. // Verify order created with correct address
  125. $this->assertDatabaseHas('orders', [
  126. 'object_address' => 'ул. Тестовая, д. 1',
  127. 'year' => 2025,
  128. ]);
  129. }
  130. public function test_import_creates_product_when_not_exists(): void
  131. {
  132. if (!$this->hasTestFile()) {
  133. $this->markTestSkipped('Requires valid Excel test file at ' . $this->testFilePath);
  134. }
  135. $this->createReferenceData();
  136. $import = Import::factory()->create([
  137. 'filename' => 'test_orders_import.xlsx',
  138. 'status' => 'PENDING',
  139. ]);
  140. // Verify no products with test nomenclature exist
  141. $this->assertDatabaseMissing('products', ['nomenclature_number' => 'NOM-001']);
  142. $service = new ImportOrdersService($import);
  143. $service->handle();
  144. // Verify product was created
  145. $this->assertDatabaseHas('products', [
  146. 'nomenclature_number' => 'NOM-001',
  147. 'article' => 'ART-001',
  148. 'year' => 2025,
  149. ]);
  150. }
  151. public function test_import_skips_row_when_district_not_found(): void
  152. {
  153. if (!$this->hasTestFile()) {
  154. $this->markTestSkipped('Requires valid Excel test file at ' . $this->testFilePath);
  155. }
  156. $this->createReferenceData();
  157. $import = Import::factory()->create([
  158. 'filename' => 'test_orders_import.xlsx',
  159. 'status' => 'PENDING',
  160. ]);
  161. $service = new ImportOrdersService($import);
  162. $service->handle();
  163. // Row 3 has invalid district "НЕСУЩЕСТВУЮЩИЙ_ОКРУГ" - should be skipped
  164. $this->assertDatabaseMissing('orders', [
  165. 'object_address' => 'ул. Ошибочная, д. 999',
  166. ]);
  167. }
  168. public function test_import_increments_maf_order_quantity(): void
  169. {
  170. if (!$this->hasTestFile()) {
  171. $this->markTestSkipped('Requires valid Excel test file at ' . $this->testFilePath);
  172. }
  173. $this->createReferenceData();
  174. $import = Import::factory()->create([
  175. 'filename' => 'test_orders_import.xlsx',
  176. 'status' => 'PENDING',
  177. ]);
  178. $service = new ImportOrdersService($import);
  179. $service->handle();
  180. // Rows 1 and 2 have same MAF order number "MAF-001"
  181. // Should create one maf_order with quantity = 2
  182. $mafOrder = MafOrder::withoutGlobalScopes()
  183. ->where('order_number', 'MAF-001')
  184. ->where('year', 2025)
  185. ->first();
  186. $this->assertNotNull($mafOrder);
  187. $this->assertEquals(2, $mafOrder->quantity);
  188. }
  189. public function test_import_skips_duplicate_product_sku(): void
  190. {
  191. if (!$this->hasTestFile()) {
  192. $this->markTestSkipped('Requires valid Excel test file at ' . $this->testFilePath);
  193. }
  194. $this->createReferenceData();
  195. $import = Import::factory()->create([
  196. 'filename' => 'test_orders_import.xlsx',
  197. 'status' => 'PENDING',
  198. ]);
  199. $service = new ImportOrdersService($import);
  200. $service->handle();
  201. // Row 4 is duplicate of Row 1 (same RFID, product, order, maf, factory_number, etc.)
  202. // Should only have 1 SKU with RFID-001
  203. $skuCount = ProductSKU::withoutGlobalScopes()
  204. ->where('rfid', 'RFID-001')
  205. ->where('year', 2025)
  206. ->count();
  207. $this->assertEquals(1, $skuCount);
  208. }
  209. public function test_import_creates_product_sku_without_maf(): void
  210. {
  211. if (!$this->hasTestFile()) {
  212. $this->markTestSkipped('Requires valid Excel test file at ' . $this->testFilePath);
  213. }
  214. $this->createReferenceData();
  215. $import = Import::factory()->create([
  216. 'filename' => 'test_orders_import.xlsx',
  217. 'status' => 'PENDING',
  218. ]);
  219. $service = new ImportOrdersService($import);
  220. $service->handle();
  221. // Row 5 has no MAF order - should create SKU with status "требуется"
  222. $sku = ProductSKU::withoutGlobalScopes()
  223. ->where('rfid', 'RFID-004')
  224. ->where('year', 2025)
  225. ->first();
  226. $this->assertNotNull($sku);
  227. $this->assertNull($sku->maf_order_id);
  228. $this->assertEquals('требуется', $sku->status);
  229. }
  230. }