GenerateDocumentsService.php 29 KB

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