GenerateDocumentsService.php 29 KB

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