ExportYearDataService.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. <?php
  2. namespace App\Services\Export;
  3. use App\Models\Contract;
  4. use App\Models\File;
  5. use App\Models\MafOrder;
  6. use App\Models\Order;
  7. use App\Models\Product;
  8. use App\Models\ProductSKU;
  9. use App\Models\Reclamation;
  10. use App\Models\ReclamationDetail;
  11. use App\Models\Schedule;
  12. use App\Models\Ttn;
  13. use Exception;
  14. use Illuminate\Support\Collection;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Storage;
  17. use Illuminate\Support\Str;
  18. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  19. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  20. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  21. use RecursiveDirectoryIterator;
  22. use RecursiveIteratorIterator;
  23. use ZipArchive;
  24. class ExportYearDataService
  25. {
  26. private string $tempDir;
  27. private string $dataDir;
  28. private string $filesDir;
  29. private array $stats = [];
  30. private array $fileMapping = []; // file_id => archive_path
  31. public function __construct(
  32. private readonly int $year,
  33. private readonly int $userId,
  34. ) {}
  35. public function handle(): string
  36. {
  37. $this->prepareTempDirectories();
  38. try {
  39. // Экспорт данных в Excel
  40. $this->exportProducts();
  41. $this->exportMafOrders();
  42. $this->exportOrders();
  43. $this->exportProductsSku();
  44. $this->exportReclamations();
  45. $this->exportSchedules();
  46. $this->exportContracts();
  47. $this->exportTtn();
  48. // Копирование файлов и создание pivot таблицы
  49. $this->copyFilesAndExportPivots();
  50. // Создание манифеста
  51. $this->createManifest();
  52. // Создание ZIP архива
  53. $archivePath = $this->createArchive();
  54. return $archivePath;
  55. } finally {
  56. // Очистка временной директории
  57. $this->cleanupTempDirectory();
  58. }
  59. }
  60. private function prepareTempDirectories(): void
  61. {
  62. $this->tempDir = storage_path('app/temp/export_year_' . $this->year . '_' . Str::random(8));
  63. $this->dataDir = $this->tempDir . '/data';
  64. $this->filesDir = $this->tempDir . '/files';
  65. if (!is_dir($this->dataDir)) {
  66. mkdir($this->dataDir, 0755, true);
  67. }
  68. if (!is_dir($this->filesDir)) {
  69. mkdir($this->filesDir, 0755, true);
  70. }
  71. }
  72. /**
  73. * Записывает строку данных в лист Excel
  74. */
  75. private function writeRow($sheet, int $row, array $data): void
  76. {
  77. $col = 1;
  78. foreach ($data as $value) {
  79. $cellAddress = Coordinate::stringFromColumnIndex($col) . $row;
  80. $sheet->setCellValue($cellAddress, $value);
  81. $col++;
  82. }
  83. }
  84. private function exportProducts(): void
  85. {
  86. $products = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  87. ->withTrashed()
  88. ->where('year', $this->year)
  89. ->with('certificate')
  90. ->cursor();
  91. $spreadsheet = new Spreadsheet();
  92. $sheet = $spreadsheet->getActiveSheet();
  93. $sheet->setTitle('Products');
  94. // Заголовки
  95. $headers = [
  96. 'id', 'article', 'name_tz', 'type_tz', 'nomenclature_number', 'sizes',
  97. 'manufacturer', 'unit', 'type', 'product_price', 'installation_price',
  98. 'total_price', 'manufacturer_name', 'note', 'passport_name', 'statement_name',
  99. 'service_life', 'certificate_number', 'certificate_date', 'certificate_issuer',
  100. 'certificate_type', 'weight', 'volume', 'places', 'certificate_file',
  101. 'created_at', 'updated_at', 'deleted_at'
  102. ];
  103. $this->writeRow($sheet, 1, $headers);
  104. $row = 2;
  105. $count = 0;
  106. foreach ($products as $product) {
  107. $certificatePath = '';
  108. if ($product->certificate_id && $product->certificate) {
  109. $certificatePath = $this->mapFileToArchive($product->certificate, 'products/certificates');
  110. }
  111. $this->writeRow($sheet, $row, [
  112. $product->id,
  113. $product->article,
  114. $product->name_tz,
  115. $product->type_tz,
  116. $product->nomenclature_number,
  117. $product->sizes,
  118. $product->manufacturer,
  119. $product->unit,
  120. $product->type,
  121. $product->getRawOriginal('product_price'),
  122. $product->getRawOriginal('installation_price'),
  123. $product->getRawOriginal('total_price'),
  124. $product->manufacturer_name,
  125. $product->note,
  126. $product->passport_name,
  127. $product->statement_name,
  128. $product->service_life,
  129. $product->certificate_number,
  130. $product->certificate_date,
  131. $product->certificate_issuer,
  132. $product->certificate_type,
  133. $product->weight,
  134. $product->volume,
  135. $product->places,
  136. $certificatePath,
  137. $product->created_at?->toIso8601String(),
  138. $product->updated_at?->toIso8601String(),
  139. $product->deleted_at?->toIso8601String(),
  140. ]);
  141. $row++;
  142. $count++;
  143. }
  144. $writer = new Xlsx($spreadsheet);
  145. $writer->save($this->dataDir . '/products.xlsx');
  146. $this->stats['products'] = $count;
  147. }
  148. private function exportMafOrders(): void
  149. {
  150. $mafOrders = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  151. ->withTrashed()
  152. ->where('year', $this->year)
  153. ->with(['user', 'product'])
  154. ->cursor();
  155. $spreadsheet = new Spreadsheet();
  156. $sheet = $spreadsheet->getActiveSheet();
  157. $sheet->setTitle('MafOrders');
  158. $headers = [
  159. 'id', 'order_number', 'status', 'user_id', 'user_name', 'product_id',
  160. 'product_nomenclature', 'quantity', 'in_stock', 'created_at', 'updated_at', 'deleted_at'
  161. ];
  162. $this->writeRow($sheet, 1, $headers);
  163. $row = 2;
  164. $count = 0;
  165. foreach ($mafOrders as $mafOrder) {
  166. $this->writeRow($sheet, $row, [
  167. $mafOrder->id,
  168. $mafOrder->order_number,
  169. $mafOrder->status,
  170. $mafOrder->user_id,
  171. $mafOrder->user?->name,
  172. $mafOrder->product_id,
  173. $mafOrder->product?->nomenclature_number,
  174. $mafOrder->quantity,
  175. $mafOrder->in_stock,
  176. $mafOrder->created_at?->toIso8601String(),
  177. $mafOrder->updated_at?->toIso8601String(),
  178. $mafOrder->deleted_at?->toIso8601String(),
  179. ]);
  180. $row++;
  181. $count++;
  182. }
  183. $writer = new Xlsx($spreadsheet);
  184. $writer->save($this->dataDir . '/maf_orders.xlsx');
  185. $this->stats['maf_orders'] = $count;
  186. }
  187. private function exportOrders(): void
  188. {
  189. $orders = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  190. ->withTrashed()
  191. ->where('year', $this->year)
  192. ->with(['user', 'district', 'area', 'objectType', 'brigadier', 'orderStatus'])
  193. ->cursor();
  194. $spreadsheet = new Spreadsheet();
  195. $sheet = $spreadsheet->getActiveSheet();
  196. $sheet->setTitle('Orders');
  197. $headers = [
  198. 'id', 'name', 'user_id', 'user_name', 'district_id', 'district_shortname',
  199. 'area_id', 'area_name', 'object_address', 'object_type_id', 'object_type_name',
  200. 'comment', 'installation_date', 'ready_date', 'brigadier_id', 'brigadier_name',
  201. 'order_status_id', 'order_status_name', 'tg_group_name', 'tg_group_link',
  202. 'ready_to_mount', 'install_days', 'created_at', 'updated_at', 'deleted_at'
  203. ];
  204. $this->writeRow($sheet, 1, $headers);
  205. $row = 2;
  206. $count = 0;
  207. foreach ($orders as $order) {
  208. $this->writeRow($sheet, $row, [
  209. $order->id,
  210. $order->name,
  211. $order->user_id,
  212. $order->user?->name,
  213. $order->district_id,
  214. $order->district?->shortname,
  215. $order->area_id,
  216. $order->area?->name,
  217. $order->object_address,
  218. $order->object_type_id,
  219. $order->objectType?->name,
  220. $order->comment,
  221. $order->installation_date,
  222. $order->ready_date,
  223. $order->brigadier_id,
  224. $order->brigadier?->name,
  225. $order->order_status_id,
  226. $order->orderStatus?->name,
  227. $order->tg_group_name,
  228. $order->tg_group_link,
  229. $order->ready_to_mount,
  230. $order->install_days,
  231. $order->created_at?->toIso8601String(),
  232. $order->updated_at?->toIso8601String(),
  233. $order->deleted_at?->toIso8601String(),
  234. ]);
  235. $row++;
  236. $count++;
  237. }
  238. $writer = new Xlsx($spreadsheet);
  239. $writer->save($this->dataDir . '/orders.xlsx');
  240. $this->stats['orders'] = $count;
  241. }
  242. private function exportProductsSku(): void
  243. {
  244. $skus = ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  245. ->withTrashed()
  246. ->where('year', $this->year)
  247. ->with(['product', 'order', 'maf_order', 'passport'])
  248. ->cursor();
  249. $spreadsheet = new Spreadsheet();
  250. $sheet = $spreadsheet->getActiveSheet();
  251. $sheet->setTitle('ProductsSKU');
  252. $headers = [
  253. 'id', 'product_id', 'product_nomenclature', 'order_id', 'order_address',
  254. 'maf_order_id', 'maf_order_number', 'status', 'rfid', 'factory_number',
  255. 'manufacture_date', 'statement_number', 'statement_date', 'upd_number',
  256. 'comment', 'passport_file', 'created_at', 'updated_at', 'deleted_at'
  257. ];
  258. $this->writeRow($sheet, 1, $headers);
  259. $row = 2;
  260. $count = 0;
  261. foreach ($skus as $sku) {
  262. $passportPath = '';
  263. if ($sku->passport_id && $sku->passport) {
  264. $passportPath = $this->mapFileToArchive($sku->passport, 'products_sku/passports');
  265. }
  266. $this->writeRow($sheet, $row, [
  267. $sku->id,
  268. $sku->product_id,
  269. $sku->product?->nomenclature_number,
  270. $sku->order_id,
  271. $sku->order?->object_address,
  272. $sku->maf_order_id,
  273. $sku->maf_order?->order_number,
  274. $sku->status,
  275. $sku->rfid,
  276. $sku->factory_number,
  277. $sku->manufacture_date,
  278. $sku->statement_number,
  279. $sku->statement_date,
  280. $sku->upd_number,
  281. $sku->comment,
  282. $passportPath,
  283. $sku->created_at?->toIso8601String(),
  284. $sku->updated_at?->toIso8601String(),
  285. $sku->deleted_at?->toIso8601String(),
  286. ]);
  287. $row++;
  288. $count++;
  289. }
  290. $writer = new Xlsx($spreadsheet);
  291. $writer->save($this->dataDir . '/products_sku.xlsx');
  292. $this->stats['products_sku'] = $count;
  293. }
  294. private function exportReclamations(): void
  295. {
  296. $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  297. ->withTrashed()
  298. ->where('year', $this->year)
  299. ->pluck('id');
  300. $reclamations = Reclamation::whereIn('order_id', $orderIds)
  301. ->with(['order', 'user', 'brigadier', 'status', 'reclamationType'])
  302. ->get();
  303. $spreadsheet = new Spreadsheet();
  304. // Лист 1: Reclamations
  305. $sheet = $spreadsheet->getActiveSheet();
  306. $sheet->setTitle('Reclamations');
  307. $headers = [
  308. 'id', 'order_id', 'order_address', 'user_id', 'user_name', 'status_id',
  309. 'status_name', 'reclamation_type_code', 'reclamation_type_name',
  310. 'reason', 'guarantee', 'whats_done', 'create_date',
  311. 'finish_date', 'start_work_date', 'work_days', 'brigadier_id',
  312. 'brigadier_name', 'comment', 'created_at', 'updated_at'
  313. ];
  314. $this->writeRow($sheet, 1, $headers);
  315. $row = 2;
  316. foreach ($reclamations as $reclamation) {
  317. $this->writeRow($sheet, $row, [
  318. $reclamation->id,
  319. $reclamation->order_id,
  320. $reclamation->order?->object_address,
  321. $reclamation->user_id,
  322. $reclamation->user?->name,
  323. $reclamation->status_id,
  324. $reclamation->status?->name,
  325. $reclamation->reclamationType?->code,
  326. $reclamation->reclamationType?->name,
  327. $reclamation->reason,
  328. $reclamation->guarantee,
  329. $reclamation->whats_done,
  330. $reclamation->create_date,
  331. $reclamation->finish_date,
  332. $reclamation->start_work_date,
  333. $reclamation->work_days,
  334. $reclamation->brigadier_id,
  335. $reclamation->brigadier?->name,
  336. $reclamation->comment,
  337. $reclamation->created_at?->toIso8601String(),
  338. $reclamation->updated_at?->toIso8601String(),
  339. ]);
  340. $row++;
  341. }
  342. // Лист 2: ReclamationDetails
  343. $sheet2 = $spreadsheet->createSheet();
  344. $sheet2->setTitle('ReclamationDetails');
  345. $headers2 = ['id', 'reclamation_id', 'name', 'quantity', 'created_at', 'updated_at'];
  346. $this->writeRow($sheet2, 1, $headers2);
  347. $reclamationIds = $reclamations->pluck('id');
  348. $details = ReclamationDetail::whereIn('reclamation_id', $reclamationIds)->get();
  349. $row = 2;
  350. $detailsCount = 0;
  351. foreach ($details as $detail) {
  352. $this->writeRow($sheet2, $row, [
  353. $detail->id,
  354. $detail->reclamation_id,
  355. $detail->name,
  356. $detail->quantity,
  357. $detail->created_at?->toIso8601String(),
  358. $detail->updated_at?->toIso8601String(),
  359. ]);
  360. $row++;
  361. $detailsCount++;
  362. }
  363. // Лист 3: ReclamationSKU (many-to-many)
  364. $sheet3 = $spreadsheet->createSheet();
  365. $sheet3->setTitle('ReclamationSKU');
  366. $headers3 = ['reclamation_id', 'product_sku_id'];
  367. $this->writeRow($sheet3, 1, $headers3);
  368. $skuRelations = DB::table('reclamation_product_sku')
  369. ->whereIn('reclamation_id', $reclamationIds)
  370. ->get();
  371. $row = 2;
  372. foreach ($skuRelations as $relation) {
  373. $this->writeRow($sheet3, $row, [
  374. $relation->reclamation_id,
  375. $relation->product_sku_id,
  376. ]);
  377. $row++;
  378. }
  379. $writer = new Xlsx($spreadsheet);
  380. $writer->save($this->dataDir . '/reclamations.xlsx');
  381. $this->stats['reclamations'] = $reclamations->count();
  382. $this->stats['reclamation_details'] = $detailsCount;
  383. }
  384. private function exportSchedules(): void
  385. {
  386. $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  387. ->withTrashed()
  388. ->where('year', $this->year)
  389. ->pluck('id');
  390. $schedules = Schedule::whereIn('order_id', $orderIds)
  391. ->with(['district', 'area', 'brigadier'])
  392. ->get();
  393. $spreadsheet = new Spreadsheet();
  394. $sheet = $spreadsheet->getActiveSheet();
  395. $sheet->setTitle('Schedules');
  396. $headers = [
  397. 'id', 'installation_date', 'address_code', 'manual', 'source', 'order_id',
  398. 'district_id', 'district_shortname', 'area_id', 'area_name', 'object_address',
  399. 'object_type', 'mafs', 'mafs_count', 'brigadier_id', 'brigadier_name',
  400. 'comment', 'created_at', 'updated_at'
  401. ];
  402. $this->writeRow($sheet, 1, $headers);
  403. $row = 2;
  404. foreach ($schedules as $schedule) {
  405. $this->writeRow($sheet, $row, [
  406. $schedule->id,
  407. $schedule->installation_date,
  408. $schedule->address_code,
  409. $schedule->manual,
  410. $schedule->source,
  411. $schedule->order_id,
  412. $schedule->district_id,
  413. $schedule->district?->shortname,
  414. $schedule->area_id,
  415. $schedule->area?->name,
  416. $schedule->object_address,
  417. $schedule->object_type,
  418. $schedule->mafs,
  419. $schedule->mafs_count,
  420. $schedule->brigadier_id,
  421. $schedule->brigadier?->name,
  422. $schedule->comment,
  423. $schedule->created_at?->toIso8601String(),
  424. $schedule->updated_at?->toIso8601String(),
  425. ]);
  426. $row++;
  427. }
  428. $writer = new Xlsx($spreadsheet);
  429. $writer->save($this->dataDir . '/schedules.xlsx');
  430. $this->stats['schedules'] = $schedules->count();
  431. }
  432. private function exportContracts(): void
  433. {
  434. $contracts = Contract::where('year', $this->year)->get();
  435. $spreadsheet = new Spreadsheet();
  436. $sheet = $spreadsheet->getActiveSheet();
  437. $sheet->setTitle('Contracts');
  438. $headers = ['id', 'contract_number', 'contract_date', 'created_at', 'updated_at'];
  439. $this->writeRow($sheet, 1, $headers);
  440. $row = 2;
  441. foreach ($contracts as $contract) {
  442. $this->writeRow($sheet, $row, [
  443. $contract->id,
  444. $contract->contract_number,
  445. $contract->contract_date,
  446. $contract->created_at?->toIso8601String(),
  447. $contract->updated_at?->toIso8601String(),
  448. ]);
  449. $row++;
  450. }
  451. $writer = new Xlsx($spreadsheet);
  452. $writer->save($this->dataDir . '/contracts.xlsx');
  453. $this->stats['contracts'] = $contracts->count();
  454. }
  455. private function exportTtn(): void
  456. {
  457. $ttns = Ttn::where('year', $this->year)->with('file')->get();
  458. $spreadsheet = new Spreadsheet();
  459. $sheet = $spreadsheet->getActiveSheet();
  460. $sheet->setTitle('Ttn');
  461. $headers = [
  462. 'id', 'ttn_number', 'ttn_number_suffix', 'order_number', 'order_date',
  463. 'departure_date', 'order_sum', 'skus', 'file_path', 'created_at', 'updated_at'
  464. ];
  465. $this->writeRow($sheet, 1, $headers);
  466. $row = 2;
  467. foreach ($ttns as $ttn) {
  468. $filePath = '';
  469. if ($ttn->file_id && $ttn->file) {
  470. $filePath = $this->mapFileToArchive($ttn->file, 'ttn');
  471. }
  472. $this->writeRow($sheet, $row, [
  473. $ttn->id,
  474. $ttn->ttn_number,
  475. $ttn->ttn_number_suffix,
  476. $ttn->order_number,
  477. $ttn->order_date,
  478. $ttn->departure_date,
  479. $ttn->order_sum,
  480. $ttn->skus,
  481. $filePath,
  482. $ttn->created_at?->toIso8601String(),
  483. $ttn->updated_at?->toIso8601String(),
  484. ]);
  485. $row++;
  486. }
  487. $writer = new Xlsx($spreadsheet);
  488. $writer->save($this->dataDir . '/ttn.xlsx');
  489. $this->stats['ttn'] = $ttns->count();
  490. }
  491. private function copyFilesAndExportPivots(): void
  492. {
  493. $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  494. ->withTrashed()
  495. ->where('year', $this->year)
  496. ->pluck('id');
  497. $reclamationIds = Reclamation::whereIn('order_id', $orderIds)->pluck('id');
  498. $spreadsheet = new Spreadsheet();
  499. $hasSheets = false;
  500. // Order photos
  501. if ($this->exportPivotSheet($spreadsheet, 'order_photo', 'order_id', $orderIds, 'orders', 'photos', !$hasSheets)) {
  502. $hasSheets = true;
  503. }
  504. // Order documents
  505. if ($this->exportPivotSheet($spreadsheet, 'order_document', 'order_id', $orderIds, 'orders', 'documents', !$hasSheets)) {
  506. $hasSheets = true;
  507. }
  508. // Order statements
  509. if ($this->exportPivotSheet($spreadsheet, 'order_statement', 'order_id', $orderIds, 'orders', 'statements', !$hasSheets)) {
  510. $hasSheets = true;
  511. }
  512. // Reclamation photos before
  513. if ($this->exportPivotSheet($spreadsheet, 'reclamation_photo_before', 'reclamation_id', $reclamationIds, 'reclamations', 'photos_before', !$hasSheets)) {
  514. $hasSheets = true;
  515. }
  516. // Reclamation photos after
  517. if ($this->exportPivotSheet($spreadsheet, 'reclamation_photo_after', 'reclamation_id', $reclamationIds, 'reclamations', 'photos_after', !$hasSheets)) {
  518. $hasSheets = true;
  519. }
  520. // Reclamation documents
  521. if ($this->exportPivotSheet($spreadsheet, 'reclamation_document', 'reclamation_id', $reclamationIds, 'reclamations', 'documents', !$hasSheets)) {
  522. $hasSheets = true;
  523. }
  524. // Reclamation acts
  525. if ($this->exportPivotSheet($spreadsheet, 'reclamation_act', 'reclamation_id', $reclamationIds, 'reclamations', 'acts', !$hasSheets)) {
  526. $hasSheets = true;
  527. }
  528. // Если ничего не экспортировано, создаём пустой лист
  529. if (!$hasSheets) {
  530. $sheet = $spreadsheet->getActiveSheet();
  531. $sheet->setTitle('empty');
  532. $sheet->setCellValue('A1', 'No pivot data');
  533. }
  534. $writer = new Xlsx($spreadsheet);
  535. $writer->save($this->dataDir . '/pivot_tables.xlsx');
  536. // Копируем все файлы из fileMapping
  537. $this->copyMappedFiles();
  538. }
  539. private function exportPivotSheet(
  540. Spreadsheet $spreadsheet,
  541. string $tableName,
  542. string $foreignKey,
  543. Collection $ids,
  544. string $entityFolder,
  545. string $fileSubfolder,
  546. bool $isFirstSheet
  547. ): bool {
  548. $records = DB::table($tableName)
  549. ->whereIn($foreignKey, $ids)
  550. ->get();
  551. if ($records->isEmpty()) {
  552. return false;
  553. }
  554. if ($isFirstSheet) {
  555. $sheet = $spreadsheet->getActiveSheet();
  556. } else {
  557. $sheet = $spreadsheet->createSheet();
  558. }
  559. $sheet->setTitle($tableName);
  560. $headers = [$foreignKey, 'file_id', 'file_archive_path'];
  561. $this->writeRow($sheet, 1, $headers);
  562. $row = 2;
  563. foreach ($records as $record) {
  564. $file = File::find($record->file_id);
  565. $archivePath = '';
  566. if ($file) {
  567. $entityId = $record->$foreignKey;
  568. $archivePath = $this->mapFileToArchive(
  569. $file,
  570. "{$entityFolder}/{$entityId}/{$fileSubfolder}"
  571. );
  572. }
  573. $this->writeRow($sheet, $row, [
  574. $record->$foreignKey,
  575. $record->file_id,
  576. $archivePath,
  577. ]);
  578. $row++;
  579. }
  580. return true;
  581. }
  582. private function mapFileToArchive(File $file, string $subPath): string
  583. {
  584. if (isset($this->fileMapping[$file->id])) {
  585. return $this->fileMapping[$file->id]['archive_path'];
  586. }
  587. $extension = pathinfo($file->original_name ?? '', PATHINFO_EXTENSION);
  588. $safeName = Str::slug(pathinfo($file->original_name ?? 'file', PATHINFO_FILENAME));
  589. if (empty($safeName)) {
  590. $safeName = 'file';
  591. }
  592. $archivePath = "files/{$subPath}/{$file->id}_{$safeName}.{$extension}";
  593. $this->fileMapping[$file->id] = [
  594. 'archive_path' => $archivePath,
  595. 'storage_path' => $file->path,
  596. 'original_name' => $file->original_name,
  597. 'mime_type' => $file->mime_type,
  598. ];
  599. return $archivePath;
  600. }
  601. private function copyMappedFiles(): void
  602. {
  603. $filesCount = 0;
  604. foreach ($this->fileMapping as $fileId => $fileData) {
  605. $storagePath = $fileData['storage_path'];
  606. $archivePath = $fileData['archive_path'];
  607. if ($storagePath && Storage::disk('public')->exists($storagePath)) {
  608. $targetPath = $this->tempDir . '/' . $archivePath;
  609. $targetDir = dirname($targetPath);
  610. if (!is_dir($targetDir)) {
  611. mkdir($targetDir, 0755, true);
  612. }
  613. $content = Storage::disk('public')->get($storagePath);
  614. file_put_contents($targetPath, $content);
  615. $filesCount++;
  616. }
  617. }
  618. $this->stats['files'] = $filesCount;
  619. }
  620. private function createManifest(): void
  621. {
  622. $manifest = [
  623. 'version' => '1.0',
  624. 'exported_at' => now()->toIso8601String(),
  625. 'year' => $this->year,
  626. 'exported_by_user_id' => $this->userId,
  627. 'stats' => $this->stats,
  628. ];
  629. file_put_contents(
  630. $this->tempDir . '/manifest.json',
  631. json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  632. );
  633. }
  634. private function createArchive(): string
  635. {
  636. $archiveName = "year_data_{$this->year}_" . date('Y-m-d_His') . '.zip';
  637. $archivePath = storage_path('app/public/export/' . $archiveName);
  638. // Создаем директорию если не существует
  639. $exportDir = storage_path('app/public/export');
  640. if (!is_dir($exportDir)) {
  641. mkdir($exportDir, 0755, true);
  642. }
  643. $zip = new ZipArchive();
  644. if ($zip->open($archivePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
  645. throw new Exception("Не удалось создать ZIP архив");
  646. }
  647. $files = new RecursiveIteratorIterator(
  648. new RecursiveDirectoryIterator($this->tempDir),
  649. RecursiveIteratorIterator::LEAVES_ONLY
  650. );
  651. foreach ($files as $file) {
  652. if ($file->isDir()) {
  653. continue;
  654. }
  655. $filePath = $file->getRealPath();
  656. $relativePath = substr($filePath, strlen($this->tempDir) + 1);
  657. $zip->addFile($filePath, $relativePath);
  658. }
  659. $zip->close();
  660. // Создаем запись File в БД
  661. File::create([
  662. 'user_id' => $this->userId,
  663. 'original_name' => $archiveName,
  664. 'mime_type' => 'application/zip',
  665. 'path' => 'export/' . $archiveName,
  666. 'link' => url('/storage/export/' . $archiveName),
  667. ]);
  668. // Возвращаем только имя файла (фронтенд добавляет /storage/export/ сам)
  669. return $archiveName;
  670. }
  671. private function cleanupTempDirectory(): void
  672. {
  673. if (is_dir($this->tempDir)) {
  674. $this->deleteDirectory($this->tempDir);
  675. }
  676. }
  677. private function deleteDirectory(string $dir): void
  678. {
  679. if (!is_dir($dir)) {
  680. return;
  681. }
  682. $files = array_diff(scandir($dir), ['.', '..']);
  683. foreach ($files as $file) {
  684. $path = $dir . '/' . $file;
  685. is_dir($path) ? $this->deleteDirectory($path) : unlink($path);
  686. }
  687. rmdir($dir);
  688. }
  689. public function getStats(): array
  690. {
  691. return $this->stats;
  692. }
  693. }