GenerateDocumentsService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. <?php
  2. namespace App\Services;
  3. use App\Helpers\CountHelper;
  4. use App\Helpers\DateHelper;
  5. use App\Helpers\ExcelHelper;
  6. use App\Models\Contract;
  7. use App\Models\File;
  8. use App\Models\Order;
  9. use App\Models\ProductSKU;
  10. use App\Models\Reclamation;
  11. use App\Models\Setting;
  12. use App\Models\Ttn;
  13. use App\Models\User;
  14. use Exception;
  15. use Illuminate\Support\Collection;
  16. use Illuminate\Support\Facades\Storage;
  17. use Illuminate\Support\Str;
  18. use PhpOffice\PhpSpreadsheet\IOFactory;
  19. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  20. use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
  21. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  22. class GenerateDocumentsService
  23. {
  24. const INSTALL_FILENAME = 'Монтаж ';
  25. const HANDOVER_FILENAME = 'Сдача ';
  26. const RECLAMATION_FILENAME = 'Рекламация ';
  27. /**
  28. * @param Order $order
  29. * @param int $userId
  30. * @return string
  31. * @throws Exception
  32. */
  33. public function generateInstallationPack(Order $order, int $userId): string
  34. {
  35. $techDocsPath = public_path('/images/tech-docs/');
  36. $order = Order::query()
  37. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  38. ->whereKey($order->id)
  39. ->where('year', $order->year)
  40. ->with('documents')
  41. ->firstOrFail();
  42. $products_sku = $order->products_sku()
  43. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  44. ->where('year', $order->year)
  45. ->get();
  46. $order->setRelation('products_sku', $products_sku);
  47. $articles = [];
  48. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp/Схемы сборки/');
  49. foreach ($products_sku as $sku) {
  50. if (!in_array($sku->product->article, $articles)) {
  51. $articles[] = $sku->product->article;
  52. // find and copy scheme files to installation directory
  53. if (file_exists($techDocsPath . $sku->product->article . '/')) {
  54. foreach (Storage::disk('base')->allFiles('public/images/tech-docs/' . $sku->product->article) as $p) {
  55. $content = Storage::disk('base')->get($p);
  56. Storage::disk('public')->put('orders/' . $order->id . '/tmp/Схемы сборки/' . basename($p), $content);
  57. }
  58. }
  59. }
  60. }
  61. $orderDocumentsDir = 'orders/' . $order->id . '/tmp/Документы площадки';
  62. foreach ($order->documents as $document) {
  63. if ($this->shouldSkipArchiveDocument($document)) {
  64. continue;
  65. }
  66. $this->copyFileToDir($document->path, $orderDocumentsDir, $document->original_name);
  67. }
  68. // generate xlsx order file
  69. $this->generateOrderForMount($order);
  70. // create zip archive
  71. $fileModel = (new FileService())->createZipArchive('orders/' . $order->id . '/tmp', self::INSTALL_FILENAME . fileName($order->common_name) . '.zip', $userId);
  72. // remove temp files
  73. Storage::disk('public')->deleteDirectory('orders/' . $order->id . '/tmp');
  74. $order->documents()->syncWithoutDetaching($fileModel);
  75. // return link
  76. return $fileModel?->link ?? '';
  77. }
  78. private function generateOrderForMount(Order $order): void
  79. {
  80. $inputFileType = 'Xlsx'; // Xlsx - Xml - Ods - Slk - Gnumeric - Csv
  81. $inputFileName = './templates/OrderForMount.xlsx';
  82. $reader = IOFactory::createReader($inputFileType);
  83. $spreadsheet = $reader->load($inputFileName);
  84. $sheet = $spreadsheet->getActiveSheet();
  85. // менеджер
  86. $sheet->setCellValue('F8', $order->user->name);
  87. $sheet->setCellValue('X8', $order->user->phone);
  88. // округ и район
  89. $sheet->setCellValue('L10', $order->district->shortname);
  90. $sheet->setCellValue('W10', $order->area->name);
  91. if ($order->area->responsible) {
  92. // ответственный
  93. $sheet->setCellValue('C12', $order->area->responsible?->name
  94. . ', ' . $order->area->responsible?->phone . ', ' . $order->area->responsible?->post);
  95. } else {
  96. $sheet->setCellValue('C12', '');
  97. }
  98. // адрес
  99. $sheet->setCellValue('L14', $order->object_address);
  100. $str = Str::replace('<div>', '', $order->products_with_count);
  101. $str = Str::replace('</div>', "\n", $str);
  102. // дата монтажа
  103. $installationDate = ($order->installation_date) ? DateHelper::getHumanDate($order->installation_date, true) : '';
  104. $sheet->setCellValue('L15', $installationDate);
  105. // мафы
  106. $sheet->setCellValue('G33', Str::trim($str));
  107. //
  108. $fileName = 'Заявка на монтаж - ' . fileName($order->object_address) . '.xlsx';
  109. $writer = new Xlsx($spreadsheet);
  110. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp');
  111. $writer->save(storage_path('app/public/orders/') . $order->id . '/tmp/' . $fileName);
  112. }
  113. /**
  114. * @throws Exception
  115. */
  116. public function generateHandoverPack(Order $order, int $userId): string
  117. {
  118. $productsSku = $order->products_sku()
  119. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  120. ->where('year', $order->year)
  121. ->get();
  122. $order->setRelation('products_sku', $productsSku);
  123. $articles = [];
  124. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp/ПАСПОРТ/');
  125. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp/СЕРТИФИКАТ/');
  126. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp/ФОТО ПСТ/');
  127. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp/ФОТО ТН/');
  128. // copy app photos
  129. foreach ($order->photos as $photo) {
  130. $from = $photo->path;
  131. $to = 'orders/' . $order->id . '/tmp/ФОТО ПСТ/' . $photo->original_name;
  132. if (!Storage::disk('public')->exists($to)) {
  133. Storage::disk('public')->copy($from, $to);
  134. }
  135. }
  136. foreach ($productsSku as $sku) {
  137. // copy certificates
  138. if ($sku->product->certificate_id) {
  139. $from = $sku->product->certificate->path;
  140. $to = 'orders/' . $order->id . '/tmp/СЕРТИФИКАТ/' . $sku->product->certificate->original_name;
  141. if (!Storage::disk('public')->exists($to)) {
  142. Storage::disk('public')->copy($from, $to);
  143. }
  144. }
  145. // copy passport
  146. if ($sku->passport_id) {
  147. $from = $sku->passport->path;
  148. $to = 'orders/' . $order->id . '/tmp/ПАСПОРТ/';
  149. if (!Storage::disk('public')->exists($to . $sku->passport->original_name)) {
  150. $f = Storage::disk('public')->get($from);
  151. $ext = \File::extension($sku->passport->original_name);
  152. $targetName = $to . 'Паспорт ' . $sku->factory_number . ' арт. ' . $sku->product->article . '.' . $ext;
  153. Storage::disk('public')->put($targetName, $f);
  154. }
  155. }
  156. }
  157. // generate xlsx order files
  158. $this->generateStatement($order);
  159. $this->generateQualityDeclaration($order);
  160. $this->generateInventory($order);
  161. $this->generatePassport($order);
  162. // create zip archive
  163. $fileModel = (new FileService())->createZipArchive('orders/' . $order->id . '/tmp', self::HANDOVER_FILENAME . fileName($order->common_name) . '.zip', $userId);
  164. // remove temp files
  165. Storage::disk('public')->deleteDirectory('orders/' . $order->id . '/tmp');
  166. $order->documents()->syncWithoutDetaching($fileModel);
  167. // return link
  168. return $fileModel?->link ?? '';
  169. }
  170. private function generateStatement(Order $order): void
  171. {
  172. $inputFileType = 'Xlsx';
  173. $inputFileName = './templates/Statement.xlsx';
  174. $reader = IOFactory::createReader($inputFileType);
  175. $spreadsheet = $reader->load($inputFileName);
  176. $sheet = $spreadsheet->getActiveSheet();
  177. $contract = Contract::query()->where('contracts.year', $order->year)->first();
  178. $contract_number = $contract->contract_number ?? 'заполнить договор за ' . $order->year . ' год!';
  179. $contract_date = DateHelper::getHumanDate($contract->contract_date ?? '1970-01-01', true);
  180. $s = 'по Договору №' . $contract_number . ' от ' . $contract_date . ' г. Между ГБУ "Мосремонт" и ООО "НАШ ДВОР-СТ"';
  181. $sheet->setCellValue('B5', $s);
  182. // менеджер
  183. $sheet->setCellValue('G21', $order->user->name);
  184. // округ и район
  185. $sheet->setCellValue('C6', $order->district->shortname);
  186. $sheet->setCellValue('F6', $order->area->name);
  187. $i = 9; // start of table
  188. $nn = 1; // string number
  189. foreach ($order->products_sku as $sku) {
  190. if ($nn > 1) { // inset row
  191. $sheet->insertNewRowBefore($i);
  192. }
  193. $sheet->setCellValue('A' . $i, $nn++);
  194. $sheet->setCellValue('B' . $i, $sku->product->statement_name);
  195. $sheet->setCellValue('C' . $i, $sku->product->passport_name);
  196. $sheet->setCellValue('D' . $i, 'шт');
  197. $sheet->setCellValue('E' . $i, '1');
  198. $sheet->setCellValue('F' . $i, $order->name);
  199. $sheet->setCellValue('G' . $i, $sku->factory_number);
  200. $sheet->setCellValue('H' . $i++, $sku->rfid);
  201. }
  202. // save file
  203. $fileName = '1.Ведомость.xlsx';
  204. $writer = new Xlsx($spreadsheet);
  205. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp');
  206. $writer->save(storage_path('app/public/orders/') . $order->id . '/tmp/' . $fileName);
  207. }
  208. private function generateQualityDeclaration(Order $order): void
  209. {
  210. $rowsPerDeclaration = 57;
  211. $inputFileType = 'Xlsx';
  212. $inputFileName = './templates/QualityDeclaration.xlsx';
  213. $reader = IOFactory::createReader($inputFileType);
  214. $spreadsheet = $reader->load($inputFileName);
  215. $sheet = $spreadsheet->getActiveSheet();
  216. $sheet->getPageSetup()->setFitToWidth(1);
  217. $sheet->getPageSetup()->setFitToHeight(0);
  218. $address = 'г. Москва, ' . $order->district->shortname . ', район ' . $order->area->name . ', по адресу: ' . (filled(trim((string) $order->name)) ? $order->name : $order->object_address);
  219. $i = 1; // start of table
  220. $n = 1;
  221. foreach ($order->products_sku as $sku) {
  222. if ($n++ > 1) {
  223. $range = 'A' . $i . ':I' . ($i + $rowsPerDeclaration - 1);
  224. $i += $rowsPerDeclaration;
  225. ExcelHelper::copyRows($sheet, $range, 'A' . $i);
  226. $sheet->setBreak('A' . ($i - 1), Worksheet::BREAK_ROW);
  227. // add header img
  228. $drawing = new Drawing();
  229. $drawing->setName('Header');
  230. $drawing->setDescription('Header');
  231. $drawing->setPath('templates/header.png');
  232. $drawing->setCoordinates('A' . $i);
  233. $drawing->setOffsetX(16);
  234. $drawing->setOffsetY(8);
  235. $drawing->setResizeProportional(true);
  236. $drawing->setWidth(680);
  237. $drawing->setWorksheet($sheet);
  238. }
  239. // document date?
  240. $sheet->setCellValue('A' . ($i + 7), DateHelper::getHumanDate(date('Y-m-d'), true));
  241. $sheet->setCellValue('B' . ($i + 16), $sku->product->passport_name);
  242. $sheet->setCellValue('C' . ($i + 18), $sku->rfid);
  243. $sheet->setCellValue('C' . ($i + 20), $address);
  244. }
  245. $sheet->getPageSetup()->setPrintArea('A1:I' . ($i + $rowsPerDeclaration - 1));
  246. // save file
  247. $fileName = '2.Декларация качества.xlsx';
  248. $writer = new Xlsx($spreadsheet);
  249. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp');
  250. $writer->save(storage_path('app/public/orders/') . $order->id . '/tmp/' . $fileName);
  251. }
  252. private function generateInventory(Order $order): void
  253. {
  254. $inputFileType = 'Xlsx';
  255. $inputFileName = './templates/Inventory.xlsx';
  256. $reader = IOFactory::createReader($inputFileType);
  257. $spreadsheet = $reader->load($inputFileName);
  258. $sheet = $spreadsheet->getActiveSheet();
  259. $address = 'Округ: ' . $order->district->shortname . ' Район ' . $order->area->name;
  260. $sheet->setCellValue('C4', $order->name);
  261. $sheet->setCellValue('C5', $address);
  262. $sheet->setCellValue('C13', $order->user->name);
  263. $i = 8; // start of table
  264. $n = 1;
  265. foreach ($order->products_sku as $sku) {
  266. if ($n++ > 1) {
  267. $sheet->insertNewRowBefore($i + 3, 3);
  268. $range = 'A' . $i . ':E' . $i + 2;
  269. $i = $i + 3;
  270. ExcelHelper::copyRows($sheet, $range, 'A' . $i);
  271. }
  272. $sheet->setCellValue('A' . $i, $n - 1);
  273. $sheet->setCellValue('B' . $i, $sku->product->passport_name);
  274. $sheet->setCellValue('B' . $i + 2, $sku->rfid);
  275. }
  276. // save file
  277. $fileName = '3.Опись.xlsx';
  278. $writer = new Xlsx($spreadsheet);
  279. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp');
  280. $writer->save(storage_path('app/public/orders/') . $order->id . '/tmp/' . $fileName);
  281. }
  282. private function generatePassport(Order $order): void
  283. {
  284. $inputFileType = 'Xlsx';
  285. $inputFileName = './templates/Passport.xlsx';
  286. $reader = IOFactory::createReader($inputFileType);
  287. $spreadsheet = $reader->load($inputFileName);
  288. $sheet = $spreadsheet->getActiveSheet();
  289. $i = 3; // start of table
  290. $n = 1;
  291. foreach ($order->products_sku as $sku) {
  292. if ($n++ > 1) {
  293. $sheet->insertNewRowBefore($i + 1, 1);
  294. $range = 'A' . $i . ':J' . $i;
  295. $i++;
  296. ExcelHelper::copyRows($sheet, $range, 'A' . $i);
  297. }
  298. $sheet->setCellValue('A' . $i, $n - 1);
  299. $sheet->setCellValue('B' . $i, $sku->product->passport_name);
  300. $sheet->setCellValue('C' . $i, $sku->product->type_tz);
  301. $sheet->setCellValue('D' . $i, $sku->rfid);
  302. $sheet->setCellValue('E' . $i, $sku->product->certificate_number);
  303. $sheet->setCellValue('G' . $i, $sku->factory_number);
  304. $sheet->setCellValue('H' . $i, DateHelper::getHumanDate($sku->manufacture_date, true));
  305. $sheet->setCellValue('J' . $i, $sku->product->service_life ?? 84);
  306. }
  307. // save file
  308. $fileName = '4.Паспорт объекта - ' . fileName($order->object_address) . '.xlsx';
  309. $writer = new Xlsx($spreadsheet);
  310. Storage::disk('public')->makeDirectory('orders/' . $order->id . '/tmp');
  311. $writer->save(storage_path('app/public/orders/') . $order->id . '/tmp/' . $fileName);
  312. }
  313. /**
  314. * @param Reclamation $reclamation
  315. * @param int $userId
  316. * @return string
  317. * @throws Exception
  318. */
  319. public function generateReclamationPack(Reclamation $reclamation, int $userId): string
  320. {
  321. $reclamation->loadMissing([
  322. 'order',
  323. 'photos_before',
  324. 'documents',
  325. 'skus.product',
  326. ]);
  327. $baseDir = 'reclamations/' . $reclamation->id . '/tmp/' . fileName($reclamation->order->object_address);
  328. $photosDir = $baseDir . '/ФОТО НАРУШЕНИЯ';
  329. Storage::disk('public')->makeDirectory($photosDir);
  330. // copy photos
  331. foreach ($reclamation->photos_before as $photo) {
  332. $from = $photo->path;
  333. $to = $photosDir . '/' . $photo->original_name;
  334. if (!Storage::disk('public')->exists($to)) {
  335. Storage::disk('public')->copy($from, $to);
  336. }
  337. }
  338. foreach ($reclamation->documents as $document) {
  339. if ($this->shouldSkipArchiveDocument($document)) {
  340. continue;
  341. }
  342. $this->copyFileToDir($document->path, $baseDir, $document->original_name);
  343. }
  344. // create xls and pdf
  345. $this->generateReclamationOrder($reclamation);
  346. $this->generateReclamationAct($reclamation);
  347. $this->generateReclamationGuarantee($reclamation);
  348. // create zip archive
  349. $fileModel = (new FileService())->createZipArchive('reclamations/' . $reclamation->id . '/tmp', self::RECLAMATION_FILENAME . fileName($reclamation->order->object_address) . '.zip', $userId);
  350. // remove temp files
  351. Storage::disk('public')->deleteDirectory('reclamations/' . $reclamation->id . '/tmp');
  352. $reclamation->documents()->syncWithoutDetaching($fileModel);
  353. // return link
  354. return $fileModel?->link ?? '';
  355. }
  356. /**
  357. * @throws Exception
  358. */
  359. public function generateReclamationPaymentPack(Reclamation $reclamation, int $userId): string
  360. {
  361. $reclamation->loadMissing([
  362. 'order.statements',
  363. 'documents',
  364. 'acts',
  365. 'photos_before',
  366. 'photos_after',
  367. ]);
  368. $tmpRoot = 'reclamations/' . $reclamation->id . '/tmp';
  369. $baseDir = $tmpRoot . '/Пакет документов на оплату - ' . fileName($reclamation->order->object_address);
  370. $beforeDir = $baseDir . '/Фотографии проблемы';
  371. $afterDir = $baseDir . '/Фотографии после устранения';
  372. Storage::disk('public')->makeDirectory($beforeDir);
  373. Storage::disk('public')->makeDirectory($afterDir);
  374. $this->copyPhotosWithEmptyFallback($reclamation->photos_before, $beforeDir);
  375. $this->copyPhotosWithEmptyFallback($reclamation->photos_after, $afterDir);
  376. foreach ($reclamation->documents as $document) {
  377. if ($this->shouldSkipDocumentForPaymentPack($document)) {
  378. continue;
  379. }
  380. $this->copyFileToDir($document->path, $baseDir, $document->original_name);
  381. }
  382. foreach ($reclamation->acts as $act) {
  383. $this->copyFileToDir($act->path, $baseDir, $act->original_name);
  384. }
  385. foreach ($reclamation->order?->statements ?? [] as $statement) {
  386. $this->copyFileToDir($statement->path, $baseDir, $statement->original_name);
  387. }
  388. $archiveName = 'Пакет документов на оплату - ' . fileName($reclamation->order->object_address) . '.zip';
  389. $fileModel = (new FileService())->createZipArchive($tmpRoot, $archiveName, $userId);
  390. Storage::disk('public')->deleteDirectory($tmpRoot);
  391. $reclamation->documents()->syncWithoutDetaching($fileModel);
  392. return $fileModel?->link ?? '';
  393. }
  394. /**
  395. * @throws Exception
  396. */
  397. private function generateReclamationOrder(Reclamation $reclamation): void
  398. {
  399. $inputFileType = 'Xlsx';
  400. $inputFileName = './templates/ReclamationOrder.xlsx';
  401. $reader = IOFactory::createReader($inputFileType);
  402. $spreadsheet = $reader->load($inputFileName);
  403. $sheet = $spreadsheet->getActiveSheet();
  404. $articles = [];
  405. foreach ($reclamation->skus as $p) {
  406. $articles[] = $p->product->article;
  407. }
  408. $sheet->setCellValue('J4', DateHelper::getHumanDate($reclamation->create_date, true));
  409. $sheet->setCellValue('L10', $reclamation->order->common_name);
  410. $sheet->setCellValue('L11', $reclamation->order->area?->responsible?->name);
  411. $sheet->setCellValue('W11', $reclamation->order->area?->responsible?->phone);
  412. $sheet->setCellValue('L12', $reclamation->order->year);
  413. $sheet->setCellValue('G13', $reclamation->guarantee);
  414. $sheet->setCellValue('G14', implode(', ', $articles));
  415. $sheet->setCellValue('Y15', DateHelper::getHumanDate($reclamation->finish_date, true));
  416. $sheet->setCellValue('U20', DateHelper::getHumanDate($reclamation->create_date, true));
  417. // save file
  418. $fileName = 'Монтажная заявка - ' . fileName($reclamation->order->object_address) . '.xlsx';
  419. $writer = new Xlsx($spreadsheet);
  420. $fd = 'reclamations/' . $reclamation->id . '/tmp/' . fileName($reclamation->order->object_address);
  421. Storage::disk('public')->makeDirectory($fd);
  422. $fp = storage_path('app/public/reclamations/') . $reclamation->id . '/tmp/' . fileName($reclamation->order->object_address) . '/' . $fileName;
  423. Storage::disk('public')->delete($fd . '/' . $fileName);
  424. $writer->save($fp);
  425. PdfConverterClient::convert($fp);
  426. }
  427. /**
  428. * @throws Exception
  429. */
  430. private function generateReclamationAct(Reclamation $reclamation): void
  431. {
  432. $inputFileType = 'Xlsx';
  433. $inputFileName = './templates/ReclamationAct.xlsx';
  434. $reader = IOFactory::createReader($inputFileType);
  435. $spreadsheet = $reader->load($inputFileName);
  436. $sheet = $spreadsheet->getActiveSheet();
  437. $representativeId = Setting::getInt(Setting::KEY_RECLAMATION_ACT_REPRESENTATIVE_USER_ID);
  438. if ($representativeId) {
  439. $representative = User::query()->withTrashed()->find($representativeId);
  440. if ($representative) {
  441. $sheet->setCellValue('A14', 'службы сервиса ' . $representative->name);
  442. }
  443. }
  444. $mafs = [];
  445. foreach ($reclamation->skus as $p) {
  446. $mafs[] = $p->product->passport_name . ', тип ' . $p->product->nomenclature_number;
  447. }
  448. $sheet->setCellValue('A17', $reclamation->order->object_address);
  449. $sheet->setCellValue('A22', implode('; ', $mafs));
  450. $sheet->setCellValue('A27', $reclamation->whats_done . ' (' . $reclamation->reason . ')');
  451. $i = 24;
  452. $n = 1;
  453. foreach ($reclamation->skus as $p) {
  454. if ($n++ > 1) {
  455. $i++;
  456. $sheet->insertNewRowBefore($i, 1);
  457. $range = 'D' . $i . ':I' . $i;
  458. $sheet->mergeCells($range);
  459. }
  460. $sheet->setCellValue('D' . $i, $p->rfid);
  461. }
  462. // save file
  463. $fileName = 'Акт - ' . fileName($reclamation->order->object_address) . '.xlsx';
  464. $writer = new Xlsx($spreadsheet);
  465. $fd = 'reclamations/' . $reclamation->id . '/tmp/' . fileName($reclamation->order->object_address);
  466. Storage::disk('public')->makeDirectory($fd);
  467. $fp = storage_path('app/public/reclamations/') . $reclamation->id . '/tmp/' . fileName($reclamation->order->object_address) . '/' . $fileName;
  468. Storage::disk('public')->delete($fd . '/' . $fileName);
  469. $writer->save($fp);
  470. PdfConverterClient::convert($fp);
  471. }
  472. /**
  473. * @throws Exception
  474. */
  475. private function generateReclamationGuarantee(Reclamation $reclamation): void
  476. {
  477. $inputFileType = 'Xlsx';
  478. $inputFileName = './templates/ReclamationGuarantee.xlsx';
  479. $reader = IOFactory::createReader($inputFileType);
  480. $spreadsheet = $reader->load($inputFileName);
  481. $sheet = $spreadsheet->getActiveSheet();
  482. $mafs = [];
  483. foreach ($reclamation->skus as $p) {
  484. $mafs[] = 'Тип ' . $p->product->nomenclature_number . ' (' . $p->product->passport_name . ')' ;
  485. }
  486. $contract = Contract::query()->where('contracts.year', $reclamation->order->year)->first();
  487. $text = "ООО «НАШ ДВОР-СТ» в рамках обязательств по Договору №{$contract?->contract_number}" .
  488. " от " . DateHelper::getHumanDate($contract?->contract_date ?? '1970-01-01', true) .
  489. " г. на выполнение комплекса работ по поставке, монтажу устанавливаемых на городских территориях малых архитектурных форм гарантирует " .
  490. $reclamation->guarantee . " на оборудовании «" . implode('; ', $mafs) .
  491. "» установленному по адресу г. Москва, " . $reclamation->order->object_address . " в срок до " .
  492. DateHelper::getHumanDate($reclamation->finish_date, true). " г. в связи с отсутствием детали в наличии и ее производством.";
  493. $sheet->setCellValue('B9', $reclamation->id);
  494. $sheet->setCellValue('D9', DateHelper::getHumanDate($reclamation->create_date, true));
  495. $sheet->setCellValue('A19', $text);
  496. // save file
  497. $fileName = 'Гарантийное письмо - ' . fileName($reclamation->order->object_address) . '.xlsx';
  498. $writer = new Xlsx($spreadsheet);
  499. $fd = 'reclamations/' . $reclamation->id . '/tmp/' . fileName($reclamation->order->object_address);
  500. Storage::disk('public')->makeDirectory($fd);
  501. $fp = storage_path('app/public/reclamations/') . $reclamation->id . '/tmp/' . fileName($reclamation->order->object_address) . '/' . $fileName;
  502. Storage::disk('public')->delete($fd . '/' . $fileName);
  503. $writer->save($fp);
  504. PdfConverterClient::convert($fp);
  505. }
  506. public function generateFilePack(Collection $files, int $userId, string $name = 'files'): \App\Models\File
  507. {
  508. $dir = Str::random(2);
  509. Storage::disk('public')->makeDirectory('files/' . $dir . '/tmp/');
  510. // copy files
  511. foreach ($files as $file) {
  512. $from = $file->path;
  513. $to = 'files/' . $dir . '/tmp/' . $file->original_name;
  514. if (!Storage::disk('public')->exists($to)) {
  515. Storage::disk('public')->copy($from, $to);
  516. }
  517. }
  518. // create zip archive
  519. $fileModel = (new FileService())->createZipArchive('files/' . $dir . '/tmp', $name .'_' . date('Y-m-d_h-i-s') . '.zip', $userId);
  520. // remove temp files
  521. Storage::disk('public')->deleteDirectory('files/' . $dir . '/tmp');
  522. // return link
  523. return $fileModel;
  524. }
  525. private function copyPhotosWithEmptyFallback(Collection $photos, string $targetDir): void
  526. {
  527. if ($photos->isEmpty()) {
  528. Storage::disk('public')->put(
  529. $targetDir . '/empty.txt',
  530. 'Данный файл создан для возможности создания пустой папки в архиве'
  531. );
  532. return;
  533. }
  534. foreach ($photos as $photo) {
  535. $this->copyFileToDir($photo->path, $targetDir, $photo->original_name);
  536. }
  537. }
  538. private function shouldSkipDocumentForPaymentPack($file): bool
  539. {
  540. return $this->shouldSkipArchiveDocument($file);
  541. }
  542. private function shouldSkipArchiveDocument($file): bool
  543. {
  544. if (!$file) {
  545. return true;
  546. }
  547. $fileName = Str::lower((string)$file->original_name);
  548. $mimeType = Str::lower((string)$file->mime_type);
  549. $archiveSuffixes = [
  550. '.zip',
  551. '.rar',
  552. '.7z',
  553. '.tar',
  554. '.tar.gz',
  555. '.tgz',
  556. '.tar.bz2',
  557. '.tbz2',
  558. '.bz2',
  559. '.tar.xz',
  560. '.txz',
  561. '.xz',
  562. ];
  563. if (Str::endsWith($fileName, $archiveSuffixes)) {
  564. return true;
  565. }
  566. if (str_contains($mimeType, 'zip') || str_contains($mimeType, 'compressed') || str_contains($mimeType, '7z') || str_contains($mimeType, 'rar')) {
  567. return true;
  568. }
  569. return false;
  570. }
  571. private function copyFileToDir(string $fromPath, string $targetDir, string $originalName): void
  572. {
  573. if (!Storage::disk('public')->exists($fromPath)) {
  574. return;
  575. }
  576. $safeName = $this->uniqueFileName($targetDir, $originalName);
  577. $to = $targetDir . '/' . $safeName;
  578. if (!Storage::disk('public')->exists($to)) {
  579. Storage::disk('public')->copy($fromPath, $to);
  580. }
  581. }
  582. private function uniqueFileName(string $dir, string $name): string
  583. {
  584. $base = pathinfo($name, PATHINFO_FILENAME);
  585. $ext = pathinfo($name, PATHINFO_EXTENSION);
  586. $extPart = $ext ? '.' . $ext : '';
  587. $candidate = $base . $extPart;
  588. $counter = 1;
  589. while (Storage::disk('public')->exists($dir . '/' . $candidate)) {
  590. $candidate = $base . ' (' . $counter . ')' . $extPart;
  591. $counter++;
  592. }
  593. return $candidate;
  594. }
  595. public function generateTtnPack(Ttn $ttn, int $userId): string
  596. {
  597. $skus = ProductSKU::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->whereIn('id', json_decode($ttn->skus))->get();
  598. $volume = $weight = $places = 0;
  599. foreach ($skus as $sku) {
  600. if(!isset($order)) {
  601. $order = $sku->order;
  602. }
  603. $volume += $sku->product->volume;
  604. $weight += $sku->product->weight;
  605. $places += $sku->product->places;
  606. }
  607. $departureDate = $ttn->departure_date ?? $order->installation_date;
  608. $installationDate = $departureDate ? DateHelper::getHumanDate($departureDate, true) : '-';
  609. $ttnNumber = ($ttn->ttn_number_suffix) ? $ttn->ttn_number . '-' . $ttn->ttn_number_suffix : $ttn->ttn_number;
  610. $inputFileType = 'Xlsx';
  611. $inputFileName = './templates/Ttn.xlsx';
  612. $reader = IOFactory::createReader($inputFileType);
  613. $spreadsheet = $reader->load($inputFileName);
  614. $sheet = $spreadsheet->getActiveSheet();
  615. $sheet->setCellValue('D8', $installationDate);
  616. $sheet->setCellValue('R8', $ttnNumber);
  617. $sheet->setCellValue('AF8', DateHelper::getHumanDate($ttn->order_date, true));
  618. $sheet->setCellValue('AT8', $ttn->order_number);
  619. $sheet->setCellValue('B19', $order->object_address ?? '');
  620. $sheet->setCellValue('AD22', CountHelper::humanCount($places, 'место', 'места', 'мест') . ', способ упаковки: поддон, ящик, картон, полиэтилен');
  621. $sheet->setCellValue('B24', $weight . ' кг, ' . $volume . ' м.куб');
  622. $sheet->setCellValue('B36', $installationDate);
  623. $sheet->setCellValue('AB57', $installationDate . ' 8-00');
  624. $sheet->setCellValue('B59', $installationDate . ' 8-10');
  625. $sheet->setCellValue('AB59', $installationDate . ' 8-40');
  626. $sheet->setCellValue('B61', $weight . ' кг');
  627. $sheet->setCellValue('B63', CountHelper::humanCount($places, 'место', 'места', 'мест'));
  628. $sheet->setCellValue('B75', $order->object_address ?? '');
  629. $sheet->setCellValue('AB75', $installationDate);
  630. $sheet->setCellValue('B77', $installationDate);
  631. $sheet->setCellValue('AB77', $installationDate);
  632. $sheet->setCellValue('AB79', CountHelper::humanCount($places, 'место', 'места', 'мест'));
  633. $sheet->setCellValue('B81', $weight . ' кг');
  634. $sheet->setCellValue('B83', $order->brigadier?->name ?? '');
  635. $sheet->setCellValue('B89', $ttn->order_sum);
  636. $sheet->setCellValue('AD89', $ttn->order_sum);
  637. $sheet->setCellValue('AS89', $ttn->order_sum);
  638. // save file
  639. $addressSuffix = trim((string) ($order->object_address ?? ''));
  640. $safeAddressSuffix = str_replace(['\\', '/', ':', '*', '?', '"', '<', '>', '|'], ' ', $addressSuffix);
  641. $fileName = 'ТН №' . $ttn->ttn_number . ' от ' . DateHelper::getHumanDate($departureDate ?? $ttn->order_date);
  642. if ($safeAddressSuffix !== '') {
  643. $fileName .= ' (' . preg_replace('/\s+/', ' ', $safeAddressSuffix) . ')';
  644. }
  645. $fileName .= '.xlsx';
  646. $writer = new Xlsx($spreadsheet);
  647. $fd = 'ttn/' . $ttn->year;
  648. Storage::disk('public')->makeDirectory($fd);
  649. $fp = storage_path('app/public/ttn/') . $ttn->year . '/' . $fileName;
  650. Storage::disk('public')->delete($fd . '/' . $fileName);
  651. $writer->save($fp);
  652. $fileModel = File::query()->updateOrCreate([
  653. 'link' => url('/storage/') . '/ttn/' . $ttn->year . '/' .$fileName,
  654. 'path' => $fp . '/' .$fileName,
  655. 'user_id' => $userId,
  656. 'original_name' => $fileName,
  657. 'mime_type' => 'application/xlsx',
  658. ]);
  659. $ttn->file_id = $fileModel->id;
  660. $ttn->save();
  661. $order->documents()->attach($fileModel->id);
  662. return $fileModel->link ?? '';
  663. }
  664. }