ExportYearDataService.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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::withoutGlobalScopes()
  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::withoutGlobalScopes()
  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::withoutGlobalScopes()
  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::withoutGlobalScopes()
  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::withoutGlobalScopes()
  297. ->withTrashed()
  298. ->where('year', $this->year)
  299. ->pluck('id');
  300. $reclamations = Reclamation::whereIn('order_id', $orderIds)
  301. ->with(['order', 'user', 'brigadier', 'status'])
  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', 'reason', 'guarantee', 'whats_done', 'create_date',
  310. 'finish_date', 'start_work_date', 'work_days', 'brigadier_id',
  311. 'brigadier_name', 'comment', 'created_at', 'updated_at'
  312. ];
  313. $this->writeRow($sheet, 1, $headers);
  314. $row = 2;
  315. foreach ($reclamations as $reclamation) {
  316. $this->writeRow($sheet, $row, [
  317. $reclamation->id,
  318. $reclamation->order_id,
  319. $reclamation->order?->object_address,
  320. $reclamation->user_id,
  321. $reclamation->user?->name,
  322. $reclamation->status_id,
  323. $reclamation->status?->name,
  324. $reclamation->reason,
  325. $reclamation->guarantee,
  326. $reclamation->whats_done,
  327. $reclamation->create_date,
  328. $reclamation->finish_date,
  329. $reclamation->start_work_date,
  330. $reclamation->work_days,
  331. $reclamation->brigadier_id,
  332. $reclamation->brigadier?->name,
  333. $reclamation->comment,
  334. $reclamation->created_at?->toIso8601String(),
  335. $reclamation->updated_at?->toIso8601String(),
  336. ]);
  337. $row++;
  338. }
  339. // Лист 2: ReclamationDetails
  340. $sheet2 = $spreadsheet->createSheet();
  341. $sheet2->setTitle('ReclamationDetails');
  342. $headers2 = ['id', 'reclamation_id', 'name', 'quantity', 'created_at', 'updated_at'];
  343. $this->writeRow($sheet2, 1, $headers2);
  344. $reclamationIds = $reclamations->pluck('id');
  345. $details = ReclamationDetail::whereIn('reclamation_id', $reclamationIds)->get();
  346. $row = 2;
  347. $detailsCount = 0;
  348. foreach ($details as $detail) {
  349. $this->writeRow($sheet2, $row, [
  350. $detail->id,
  351. $detail->reclamation_id,
  352. $detail->name,
  353. $detail->quantity,
  354. $detail->created_at?->toIso8601String(),
  355. $detail->updated_at?->toIso8601String(),
  356. ]);
  357. $row++;
  358. $detailsCount++;
  359. }
  360. // Лист 3: ReclamationSKU (many-to-many)
  361. $sheet3 = $spreadsheet->createSheet();
  362. $sheet3->setTitle('ReclamationSKU');
  363. $headers3 = ['reclamation_id', 'product_sku_id'];
  364. $this->writeRow($sheet3, 1, $headers3);
  365. $skuRelations = DB::table('reclamation_product_sku')
  366. ->whereIn('reclamation_id', $reclamationIds)
  367. ->get();
  368. $row = 2;
  369. foreach ($skuRelations as $relation) {
  370. $this->writeRow($sheet3, $row, [
  371. $relation->reclamation_id,
  372. $relation->product_sku_id,
  373. ]);
  374. $row++;
  375. }
  376. $writer = new Xlsx($spreadsheet);
  377. $writer->save($this->dataDir . '/reclamations.xlsx');
  378. $this->stats['reclamations'] = $reclamations->count();
  379. $this->stats['reclamation_details'] = $detailsCount;
  380. }
  381. private function exportSchedules(): void
  382. {
  383. $orderIds = Order::withoutGlobalScopes()
  384. ->withTrashed()
  385. ->where('year', $this->year)
  386. ->pluck('id');
  387. $schedules = Schedule::whereIn('order_id', $orderIds)
  388. ->with(['district', 'area', 'brigadier'])
  389. ->get();
  390. $spreadsheet = new Spreadsheet();
  391. $sheet = $spreadsheet->getActiveSheet();
  392. $sheet->setTitle('Schedules');
  393. $headers = [
  394. 'id', 'installation_date', 'address_code', 'manual', 'source', 'order_id',
  395. 'district_id', 'district_shortname', 'area_id', 'area_name', 'object_address',
  396. 'object_type', 'mafs', 'mafs_count', 'brigadier_id', 'brigadier_name',
  397. 'comment', 'created_at', 'updated_at'
  398. ];
  399. $this->writeRow($sheet, 1, $headers);
  400. $row = 2;
  401. foreach ($schedules as $schedule) {
  402. $this->writeRow($sheet, $row, [
  403. $schedule->id,
  404. $schedule->installation_date,
  405. $schedule->address_code,
  406. $schedule->manual,
  407. $schedule->source,
  408. $schedule->order_id,
  409. $schedule->district_id,
  410. $schedule->district?->shortname,
  411. $schedule->area_id,
  412. $schedule->area?->name,
  413. $schedule->object_address,
  414. $schedule->object_type,
  415. $schedule->mafs,
  416. $schedule->mafs_count,
  417. $schedule->brigadier_id,
  418. $schedule->brigadier?->name,
  419. $schedule->comment,
  420. $schedule->created_at?->toIso8601String(),
  421. $schedule->updated_at?->toIso8601String(),
  422. ]);
  423. $row++;
  424. }
  425. $writer = new Xlsx($spreadsheet);
  426. $writer->save($this->dataDir . '/schedules.xlsx');
  427. $this->stats['schedules'] = $schedules->count();
  428. }
  429. private function exportContracts(): void
  430. {
  431. $contracts = Contract::where('year', $this->year)->get();
  432. $spreadsheet = new Spreadsheet();
  433. $sheet = $spreadsheet->getActiveSheet();
  434. $sheet->setTitle('Contracts');
  435. $headers = ['id', 'contract_number', 'contract_date', 'created_at', 'updated_at'];
  436. $this->writeRow($sheet, 1, $headers);
  437. $row = 2;
  438. foreach ($contracts as $contract) {
  439. $this->writeRow($sheet, $row, [
  440. $contract->id,
  441. $contract->contract_number,
  442. $contract->contract_date,
  443. $contract->created_at?->toIso8601String(),
  444. $contract->updated_at?->toIso8601String(),
  445. ]);
  446. $row++;
  447. }
  448. $writer = new Xlsx($spreadsheet);
  449. $writer->save($this->dataDir . '/contracts.xlsx');
  450. $this->stats['contracts'] = $contracts->count();
  451. }
  452. private function exportTtn(): void
  453. {
  454. $ttns = Ttn::where('year', $this->year)->with('file')->get();
  455. $spreadsheet = new Spreadsheet();
  456. $sheet = $spreadsheet->getActiveSheet();
  457. $sheet->setTitle('Ttn');
  458. $headers = [
  459. 'id', 'ttn_number', 'ttn_number_suffix', 'order_number', 'order_date',
  460. 'order_sum', 'skus', 'file_path', 'created_at', 'updated_at'
  461. ];
  462. $this->writeRow($sheet, 1, $headers);
  463. $row = 2;
  464. foreach ($ttns as $ttn) {
  465. $filePath = '';
  466. if ($ttn->file_id && $ttn->file) {
  467. $filePath = $this->mapFileToArchive($ttn->file, 'ttn');
  468. }
  469. $this->writeRow($sheet, $row, [
  470. $ttn->id,
  471. $ttn->ttn_number,
  472. $ttn->ttn_number_suffix,
  473. $ttn->order_number,
  474. $ttn->order_date,
  475. $ttn->order_sum,
  476. $ttn->skus,
  477. $filePath,
  478. $ttn->created_at?->toIso8601String(),
  479. $ttn->updated_at?->toIso8601String(),
  480. ]);
  481. $row++;
  482. }
  483. $writer = new Xlsx($spreadsheet);
  484. $writer->save($this->dataDir . '/ttn.xlsx');
  485. $this->stats['ttn'] = $ttns->count();
  486. }
  487. private function copyFilesAndExportPivots(): void
  488. {
  489. $orderIds = Order::withoutGlobalScopes()
  490. ->withTrashed()
  491. ->where('year', $this->year)
  492. ->pluck('id');
  493. $reclamationIds = Reclamation::whereIn('order_id', $orderIds)->pluck('id');
  494. $spreadsheet = new Spreadsheet();
  495. $hasSheets = false;
  496. // Order photos
  497. if ($this->exportPivotSheet($spreadsheet, 'order_photo', 'order_id', $orderIds, 'orders', 'photos', !$hasSheets)) {
  498. $hasSheets = true;
  499. }
  500. // Order documents
  501. if ($this->exportPivotSheet($spreadsheet, 'order_document', 'order_id', $orderIds, 'orders', 'documents', !$hasSheets)) {
  502. $hasSheets = true;
  503. }
  504. // Order statements
  505. if ($this->exportPivotSheet($spreadsheet, 'order_statement', 'order_id', $orderIds, 'orders', 'statements', !$hasSheets)) {
  506. $hasSheets = true;
  507. }
  508. // Reclamation photos before
  509. if ($this->exportPivotSheet($spreadsheet, 'reclamation_photo_before', 'reclamation_id', $reclamationIds, 'reclamations', 'photos_before', !$hasSheets)) {
  510. $hasSheets = true;
  511. }
  512. // Reclamation photos after
  513. if ($this->exportPivotSheet($spreadsheet, 'reclamation_photo_after', 'reclamation_id', $reclamationIds, 'reclamations', 'photos_after', !$hasSheets)) {
  514. $hasSheets = true;
  515. }
  516. // Reclamation documents
  517. if ($this->exportPivotSheet($spreadsheet, 'reclamation_document', 'reclamation_id', $reclamationIds, 'reclamations', 'documents', !$hasSheets)) {
  518. $hasSheets = true;
  519. }
  520. // Reclamation acts
  521. if ($this->exportPivotSheet($spreadsheet, 'reclamation_act', 'reclamation_id', $reclamationIds, 'reclamations', 'acts', !$hasSheets)) {
  522. $hasSheets = true;
  523. }
  524. // Если ничего не экспортировано, создаём пустой лист
  525. if (!$hasSheets) {
  526. $sheet = $spreadsheet->getActiveSheet();
  527. $sheet->setTitle('empty');
  528. $sheet->setCellValue('A1', 'No pivot data');
  529. }
  530. $writer = new Xlsx($spreadsheet);
  531. $writer->save($this->dataDir . '/pivot_tables.xlsx');
  532. // Копируем все файлы из fileMapping
  533. $this->copyMappedFiles();
  534. }
  535. private function exportPivotSheet(
  536. Spreadsheet $spreadsheet,
  537. string $tableName,
  538. string $foreignKey,
  539. Collection $ids,
  540. string $entityFolder,
  541. string $fileSubfolder,
  542. bool $isFirstSheet
  543. ): bool {
  544. $records = DB::table($tableName)
  545. ->whereIn($foreignKey, $ids)
  546. ->get();
  547. if ($records->isEmpty()) {
  548. return false;
  549. }
  550. if ($isFirstSheet) {
  551. $sheet = $spreadsheet->getActiveSheet();
  552. } else {
  553. $sheet = $spreadsheet->createSheet();
  554. }
  555. $sheet->setTitle($tableName);
  556. $headers = [$foreignKey, 'file_id', 'file_archive_path'];
  557. $this->writeRow($sheet, 1, $headers);
  558. $row = 2;
  559. foreach ($records as $record) {
  560. $file = File::find($record->file_id);
  561. $archivePath = '';
  562. if ($file) {
  563. $entityId = $record->$foreignKey;
  564. $archivePath = $this->mapFileToArchive(
  565. $file,
  566. "{$entityFolder}/{$entityId}/{$fileSubfolder}"
  567. );
  568. }
  569. $this->writeRow($sheet, $row, [
  570. $record->$foreignKey,
  571. $record->file_id,
  572. $archivePath,
  573. ]);
  574. $row++;
  575. }
  576. return true;
  577. }
  578. private function mapFileToArchive(File $file, string $subPath): string
  579. {
  580. if (isset($this->fileMapping[$file->id])) {
  581. return $this->fileMapping[$file->id]['archive_path'];
  582. }
  583. $extension = pathinfo($file->original_name ?? '', PATHINFO_EXTENSION);
  584. $safeName = Str::slug(pathinfo($file->original_name ?? 'file', PATHINFO_FILENAME));
  585. if (empty($safeName)) {
  586. $safeName = 'file';
  587. }
  588. $archivePath = "files/{$subPath}/{$file->id}_{$safeName}.{$extension}";
  589. $this->fileMapping[$file->id] = [
  590. 'archive_path' => $archivePath,
  591. 'storage_path' => $file->path,
  592. 'original_name' => $file->original_name,
  593. 'mime_type' => $file->mime_type,
  594. ];
  595. return $archivePath;
  596. }
  597. private function copyMappedFiles(): void
  598. {
  599. $filesCount = 0;
  600. foreach ($this->fileMapping as $fileId => $fileData) {
  601. $storagePath = $fileData['storage_path'];
  602. $archivePath = $fileData['archive_path'];
  603. if ($storagePath && Storage::disk('public')->exists($storagePath)) {
  604. $targetPath = $this->tempDir . '/' . $archivePath;
  605. $targetDir = dirname($targetPath);
  606. if (!is_dir($targetDir)) {
  607. mkdir($targetDir, 0755, true);
  608. }
  609. $content = Storage::disk('public')->get($storagePath);
  610. file_put_contents($targetPath, $content);
  611. $filesCount++;
  612. }
  613. }
  614. $this->stats['files'] = $filesCount;
  615. }
  616. private function createManifest(): void
  617. {
  618. $manifest = [
  619. 'version' => '1.0',
  620. 'exported_at' => now()->toIso8601String(),
  621. 'year' => $this->year,
  622. 'exported_by_user_id' => $this->userId,
  623. 'stats' => $this->stats,
  624. ];
  625. file_put_contents(
  626. $this->tempDir . '/manifest.json',
  627. json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  628. );
  629. }
  630. private function createArchive(): string
  631. {
  632. $archiveName = "year_data_{$this->year}_" . date('Y-m-d_His') . '.zip';
  633. $archivePath = storage_path('app/public/export/' . $archiveName);
  634. // Создаем директорию если не существует
  635. $exportDir = storage_path('app/public/export');
  636. if (!is_dir($exportDir)) {
  637. mkdir($exportDir, 0755, true);
  638. }
  639. $zip = new ZipArchive();
  640. if ($zip->open($archivePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
  641. throw new Exception("Не удалось создать ZIP архив");
  642. }
  643. $files = new RecursiveIteratorIterator(
  644. new RecursiveDirectoryIterator($this->tempDir),
  645. RecursiveIteratorIterator::LEAVES_ONLY
  646. );
  647. foreach ($files as $file) {
  648. if ($file->isDir()) {
  649. continue;
  650. }
  651. $filePath = $file->getRealPath();
  652. $relativePath = substr($filePath, strlen($this->tempDir) + 1);
  653. $zip->addFile($filePath, $relativePath);
  654. }
  655. $zip->close();
  656. // Создаем запись File в БД
  657. File::create([
  658. 'user_id' => $this->userId,
  659. 'original_name' => $archiveName,
  660. 'mime_type' => 'application/zip',
  661. 'path' => 'export/' . $archiveName,
  662. 'link' => url('/storage/export/' . $archiveName),
  663. ]);
  664. // Возвращаем только имя файла (фронтенд добавляет /storage/export/ сам)
  665. return $archiveName;
  666. }
  667. private function cleanupTempDirectory(): void
  668. {
  669. if (is_dir($this->tempDir)) {
  670. $this->deleteDirectory($this->tempDir);
  671. }
  672. }
  673. private function deleteDirectory(string $dir): void
  674. {
  675. if (!is_dir($dir)) {
  676. return;
  677. }
  678. $files = array_diff(scandir($dir), ['.', '..']);
  679. foreach ($files as $file) {
  680. $path = $dir . '/' . $file;
  681. is_dir($path) ? $this->deleteDirectory($path) : unlink($path);
  682. }
  683. rmdir($dir);
  684. }
  685. public function getStats(): array
  686. {
  687. return $this->stats;
  688. }
  689. }