GenerateDocumentsServiceTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <?php
  2. namespace Tests\Unit\Services;
  3. use App\Models\Contract;
  4. use App\Models\File;
  5. use App\Models\Order;
  6. use App\Models\Product;
  7. use App\Models\ProductSKU;
  8. use App\Models\Reclamation;
  9. use App\Models\Ttn;
  10. use App\Models\User;
  11. use App\Services\GenerateDocumentsService;
  12. use Illuminate\Foundation\Testing\RefreshDatabase;
  13. use Illuminate\Support\Facades\Storage;
  14. use Tests\TestCase;
  15. use ZipArchive;
  16. class GenerateDocumentsServiceTest extends TestCase
  17. {
  18. use RefreshDatabase;
  19. protected $seed = true;
  20. private GenerateDocumentsService $service;
  21. protected function setUp(): void
  22. {
  23. parent::setUp();
  24. $this->service = new GenerateDocumentsService();
  25. }
  26. protected function tearDown(): void
  27. {
  28. unset($this->service);
  29. gc_collect_cycles();
  30. parent::tearDown();
  31. }
  32. // ==================== Constants ====================
  33. public function test_service_has_correct_filename_constants(): void
  34. {
  35. $this->assertEquals('Монтаж ', GenerateDocumentsService::INSTALL_FILENAME);
  36. $this->assertEquals('Сдача ', GenerateDocumentsService::HANDOVER_FILENAME);
  37. $this->assertEquals('Рекламация ', GenerateDocumentsService::RECLAMATION_FILENAME);
  38. }
  39. // ==================== generateFilePack ====================
  40. public function test_generate_file_pack_creates_zip_archive(): void
  41. {
  42. // This test uses real storage because FileService uses storage_path()
  43. // which doesn't work with Storage::fake()
  44. $user = User::factory()->create();
  45. // Create test directory and files
  46. $testDir = 'test_' . uniqid();
  47. Storage::disk('public')->makeDirectory($testDir);
  48. Storage::disk('public')->put($testDir . '/test1.jpg', 'test content 1');
  49. Storage::disk('public')->put($testDir . '/test2.jpg', 'test content 2');
  50. // Create file records
  51. $file1 = File::factory()->create([
  52. 'user_id' => $user->id,
  53. 'original_name' => 'test1.jpg',
  54. 'path' => $testDir . '/test1.jpg',
  55. ]);
  56. $file2 = File::factory()->create([
  57. 'user_id' => $user->id,
  58. 'original_name' => 'test2.jpg',
  59. 'path' => $testDir . '/test2.jpg',
  60. ]);
  61. $files = collect([$file1, $file2]);
  62. // Act
  63. $result = $this->service->generateFilePack($files, $user->id, 'test_pack');
  64. // Assert
  65. $this->assertInstanceOf(File::class, $result);
  66. $this->assertStringContainsString('test_pack', $result->original_name);
  67. $this->assertStringContainsString('.zip', $result->original_name);
  68. // Cleanup
  69. Storage::disk('public')->deleteDirectory($testDir);
  70. if ($result->path) {
  71. Storage::disk('public')->delete($result->path);
  72. }
  73. }
  74. public function test_generate_file_pack_handles_empty_collection(): void
  75. {
  76. $user = User::factory()->create();
  77. $files = collect([]);
  78. // Empty collection should throw an exception or return File with empty zip
  79. // This tests the edge case behavior
  80. try {
  81. $result = $this->service->generateFilePack($files, $user->id, 'empty_pack');
  82. // If it succeeds, verify the result
  83. $this->assertInstanceOf(File::class, $result);
  84. // Cleanup
  85. if ($result->path) {
  86. Storage::disk('public')->delete($result->path);
  87. }
  88. } catch (\Exception $e) {
  89. // Empty collection may cause errors in zip creation
  90. $this->assertTrue(true);
  91. }
  92. }
  93. // ==================== Integration tests with templates ====================
  94. // Note: These tests require Excel templates to be present
  95. public function test_generate_installation_pack_creates_directories(): void
  96. {
  97. // Skip if templates don't exist
  98. if (!file_exists('./templates/OrderForMount.xlsx')) {
  99. $this->markTestSkipped('Excel template OrderForMount.xlsx not found');
  100. }
  101. $user = User::factory()->create();
  102. $product = Product::factory()->create();
  103. $order = Order::factory()->create();
  104. ProductSKU::factory()->create([
  105. 'order_id' => $order->id,
  106. 'product_id' => $product->id,
  107. ]);
  108. // Act
  109. try {
  110. $result = $this->service->generateInstallationPack($order, $user->id);
  111. // Assert
  112. $this->assertIsString($result);
  113. // Cleanup
  114. Storage::disk('public')->deleteDirectory('orders/' . $order->id);
  115. } catch (\Exception $e) {
  116. // Expected if FileService or templates fail
  117. $this->assertTrue(true);
  118. }
  119. }
  120. public function test_generate_handover_pack_requires_order_with_skus(): void
  121. {
  122. // Skip if templates don't exist
  123. if (!file_exists('./templates/Statement.xlsx')) {
  124. $this->markTestSkipped('Excel template Statement.xlsx not found');
  125. }
  126. Storage::fake('public');
  127. $user = User::factory()->create();
  128. $product = Product::factory()->create();
  129. $order = Order::factory()->create();
  130. // Create contract for the year
  131. Contract::factory()->create([
  132. 'year' => $order->year,
  133. 'contract_number' => 'TEST-001',
  134. 'contract_date' => now(),
  135. ]);
  136. ProductSKU::factory()->create([
  137. 'order_id' => $order->id,
  138. 'product_id' => $product->id,
  139. 'rfid' => 'TEST-RFID-001',
  140. 'factory_number' => 'FN-001',
  141. ]);
  142. // Act
  143. try {
  144. $result = $this->service->generateHandoverPack($order, $user->id);
  145. $this->assertIsString($result);
  146. } catch (\Exception $e) {
  147. // Expected if templates or dependencies fail
  148. $this->assertTrue(true);
  149. }
  150. }
  151. public function test_generate_handover_pack_handles_many_large_related_files_and_cleans_tmp(): void
  152. {
  153. foreach (['./templates/Statement.xlsx', './templates/QualityDeclaration.xlsx', './templates/Inventory.xlsx', './templates/Passport.xlsx'] as $template) {
  154. if (!file_exists($template)) {
  155. $this->markTestSkipped('Excel template ' . basename($template) . ' not found');
  156. }
  157. }
  158. $user = User::factory()->create();
  159. $order = Order::factory()->create([
  160. 'object_address' => 'г Москва, тестовый объект для большого пакета',
  161. 'name' => 'Большой тестовый пакет сдачи',
  162. ]);
  163. Contract::factory()->create([
  164. 'year' => $order->year,
  165. 'contract_number' => 'LOAD-001',
  166. 'contract_date' => now(),
  167. ]);
  168. $createdPaths = [];
  169. $generatedArchivePath = null;
  170. $photoIds = [];
  171. $documentIds = [];
  172. try {
  173. for ($index = 1; $index <= 50; $index++) {
  174. $path = "orders/{$order->id}/photo/load-photo-{$index}.jpg";
  175. $this->putLargePublicFile($path, 2 * 1024 * 1024);
  176. $createdPaths[] = $path;
  177. $photo = File::factory()->image()->create([
  178. 'user_id' => $user->id,
  179. 'original_name' => "load-photo-{$index}.jpg",
  180. 'path' => $path,
  181. 'link' => url('/storage/' . $path),
  182. 'mime_type' => 'image/jpeg',
  183. ]);
  184. $photoIds[] = $photo->id;
  185. }
  186. for ($index = 1; $index <= 8; $index++) {
  187. $path = "orders/{$order->id}/document/load-document-{$index}.pdf";
  188. $this->putLargePublicFile($path, 2 * 1024 * 1024);
  189. $createdPaths[] = $path;
  190. $document = File::factory()->pdf()->create([
  191. 'user_id' => $user->id,
  192. 'original_name' => "load-document-{$index}.pdf",
  193. 'path' => $path,
  194. 'link' => url('/storage/' . $path),
  195. 'mime_type' => 'application/pdf',
  196. ]);
  197. $documentIds[] = $document->id;
  198. }
  199. $order->photos()->syncWithoutDetaching($photoIds);
  200. $order->documents()->syncWithoutDetaching($documentIds);
  201. for ($index = 1; $index <= 12; $index++) {
  202. $certificatePath = "tests/handover-large/certificates/certificate-{$index}.pdf";
  203. $passportPath = "tests/handover-large/passports/passport-{$index}.pdf";
  204. $this->putLargePublicFile($certificatePath, 2 * 1024 * 1024);
  205. $this->putLargePublicFile($passportPath, 2 * 1024 * 1024);
  206. $createdPaths[] = $certificatePath;
  207. $createdPaths[] = $passportPath;
  208. $certificate = File::factory()->pdf()->create([
  209. 'user_id' => $user->id,
  210. 'original_name' => "certificate-{$index}.pdf",
  211. 'path' => $certificatePath,
  212. 'link' => url('/storage/' . $certificatePath),
  213. 'mime_type' => 'application/pdf',
  214. ]);
  215. $passport = File::factory()->pdf()->create([
  216. 'user_id' => $user->id,
  217. 'original_name' => "passport-{$index}.pdf",
  218. 'path' => $passportPath,
  219. 'link' => url('/storage/' . $passportPath),
  220. 'mime_type' => 'application/pdf',
  221. ]);
  222. $product = Product::factory()->create([
  223. 'year' => $order->year,
  224. 'article' => 'LOAD-MAF-' . $index,
  225. 'passport_name' => 'Паспортное имя МАФ ' . $index,
  226. 'statement_name' => 'Ведомость МАФ ' . $index,
  227. 'certificate_id' => $certificate->id,
  228. 'certificate_number' => 'CERT-' . $index,
  229. 'service_life' => 84,
  230. ]);
  231. ProductSKU::factory()->create([
  232. 'year' => $order->year,
  233. 'order_id' => $order->id,
  234. 'product_id' => $product->id,
  235. 'passport_id' => $passport->id,
  236. 'rfid' => 'LOAD-RFID-' . $index,
  237. 'factory_number' => 'LOAD-FN-' . $index,
  238. 'manufacture_date' => now()->subDays($index)->format('Y-m-d'),
  239. ]);
  240. }
  241. $link = $this->service->generateHandoverPack($order->fresh(), $user->id);
  242. $this->assertNotSame('', $link);
  243. $this->assertStringContainsString('/storage/orders/' . $order->id . '/', $link);
  244. $this->assertFalse(Storage::disk('public')->exists("orders/{$order->id}/tmp"));
  245. $generatedArchive = File::query()
  246. ->where('is_generated', true)
  247. ->where('path', 'like', "orders/{$order->id}/%.zip")
  248. ->firstOrFail();
  249. $generatedArchivePath = $generatedArchive->path;
  250. Storage::disk('public')->assertExists($generatedArchivePath);
  251. $this->assertGreaterThan(100 * 1024 * 1024, filesize(Storage::disk('public')->path($generatedArchivePath)));
  252. $zip = new ZipArchive();
  253. $this->assertTrue($zip->open(Storage::disk('public')->path($generatedArchivePath)));
  254. try {
  255. $this->assertGreaterThanOrEqual(78, $zip->numFiles);
  256. $this->assertNotFalse($zip->locateName('ФОТО ПСТ/load-photo-1.jpg'));
  257. $this->assertNotFalse($zip->locateName('СЕРТИФИКАТ/certificate-1.pdf'));
  258. $this->assertNotFalse($zip->locateName('ПАСПОРТ/Паспорт LOAD-FN-1 арт. LOAD-MAF-1.pdf'));
  259. $this->assertNotFalse($zip->locateName('1.Ведомость.xlsx'));
  260. $this->assertNotFalse($zip->locateName('2.Декларация качества.xlsx'));
  261. $this->assertNotFalse($zip->locateName('3.Опись.xlsx'));
  262. } finally {
  263. $zip->close();
  264. }
  265. } finally {
  266. Storage::disk('public')->deleteDirectory("orders/{$order->id}/tmp");
  267. if ($generatedArchivePath) {
  268. Storage::disk('public')->delete($generatedArchivePath);
  269. }
  270. foreach ($createdPaths as $path) {
  271. Storage::disk('public')->delete($path);
  272. }
  273. Storage::disk('public')->deleteDirectory("orders/{$order->id}/photo");
  274. Storage::disk('public')->deleteDirectory("orders/{$order->id}/document");
  275. Storage::disk('public')->deleteDirectory('tests/handover-large');
  276. }
  277. }
  278. public function test_generate_reclamation_pack_creates_documents(): void
  279. {
  280. // Skip if templates don't exist
  281. if (!file_exists('./templates/ReclamationOrder.xlsx')) {
  282. $this->markTestSkipped('Excel template ReclamationOrder.xlsx not found');
  283. }
  284. Storage::fake('public');
  285. $user = User::factory()->create();
  286. $product = Product::factory()->create();
  287. $order = Order::factory()->create();
  288. $reclamation = Reclamation::factory()->create([
  289. 'order_id' => $order->id,
  290. 'create_date' => now(),
  291. 'finish_date' => now()->addDays(30),
  292. ]);
  293. // Create contract for the year
  294. Contract::factory()->create([
  295. 'year' => $order->year,
  296. ]);
  297. $sku = ProductSKU::factory()->create([
  298. 'order_id' => $order->id,
  299. 'product_id' => $product->id,
  300. ]);
  301. $reclamation->skus()->attach($sku->id);
  302. // Act
  303. try {
  304. $result = $this->service->generateReclamationPack($reclamation, $user->id);
  305. $this->assertIsString($result);
  306. } catch (\Exception $e) {
  307. // Expected if PdfConverterClient or templates fail
  308. $this->assertTrue(true);
  309. }
  310. }
  311. private function putLargePublicFile(string $path, int $bytes): void
  312. {
  313. Storage::disk('public')->makeDirectory(dirname($path));
  314. $handle = fopen(Storage::disk('public')->path($path), 'wb');
  315. if ($handle === false) {
  316. $this->fail('Cannot create test file: ' . $path);
  317. }
  318. try {
  319. $remaining = $bytes;
  320. while ($remaining > 0) {
  321. $chunkSize = min($remaining, 256 * 1024);
  322. fwrite($handle, random_bytes($chunkSize));
  323. $remaining -= $chunkSize;
  324. }
  325. } finally {
  326. fclose($handle);
  327. }
  328. }
  329. public function test_generate_ttn_pack_uses_departure_date_and_address_in_filename(): void
  330. {
  331. if (!file_exists('./templates/Ttn.xlsx')) {
  332. $this->markTestSkipped('Excel template Ttn.xlsx not found');
  333. }
  334. $user = User::factory()->create();
  335. $product = Product::factory()->create([
  336. 'weight' => 10,
  337. 'volume' => 2,
  338. 'places' => 3,
  339. ]);
  340. $order = Order::factory()->create([
  341. 'object_address' => 'г Москва, ул Ангарская, д 51 к 2',
  342. 'installation_date' => '2026-04-01',
  343. ]);
  344. $sku = ProductSKU::factory()->create([
  345. 'order_id' => $order->id,
  346. 'product_id' => $product->id,
  347. ]);
  348. $ttn = Ttn::query()->create([
  349. 'year' => 2026,
  350. 'ttn_number' => 12,
  351. 'ttn_number_suffix' => 'И',
  352. 'order_number' => 'З-77',
  353. 'order_date' => '2026-04-05',
  354. 'departure_date' => '2026-04-08',
  355. 'order_sum' => '1000',
  356. 'skus' => json_encode([$sku->id], JSON_THROW_ON_ERROR),
  357. ]);
  358. $link = $this->service->generateTtnPack($ttn, $user->id);
  359. $file = File::query()->findOrFail($ttn->fresh()->file_id);
  360. $expectedName = 'ТН №12 от 8 апреля 2026 (г Москва, ул Ангарская, д 51 к 2).xlsx';
  361. $this->assertIsString($link);
  362. $this->assertSame($expectedName, $file->original_name);
  363. $this->assertStringContainsString('/storage/', $link);
  364. Storage::disk('public')->delete('ttn/2026/' . $expectedName);
  365. }
  366. }