GenerateDocumentsService.php 33 KB

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