瀏覽代碼

create zip archives

Alexander Musikhin 7 月之前
父節點
當前提交
938e1ed192
共有 4 個文件被更改,包括 119 次插入3 次删除
  1. 16 2
      app/Jobs/GenerateInstallationPack.php
  2. 60 0
      app/Services/FileService.php
  3. 41 0
      app/Services/GenerateDocumentsService.php
  4. 2 1
      composer.json

+ 16 - 2
app/Jobs/GenerateInstallationPack.php

@@ -2,9 +2,13 @@
 
 namespace App\Jobs;
 
+use App\Events\SendWebSocketMessageEvent;
 use App\Models\Order;
+use App\Services\GenerateDocumentsService;
+use Exception;
 use Illuminate\Contracts\Queue\ShouldQueue;
 use Illuminate\Foundation\Queue\Queueable;
+use Illuminate\Support\Facades\Log;
 
 class GenerateInstallationPack implements ShouldQueue
 {
@@ -13,7 +17,7 @@ class GenerateInstallationPack implements ShouldQueue
     /**
      * Create a new job instance.
      */
-    public function __construct(private readonly Order $order)
+    public function __construct(private readonly Order $order, private readonly int $userId)
     {
         //
     }
@@ -23,6 +27,16 @@ class GenerateInstallationPack implements ShouldQueue
      */
     public function handle(): void
     {
-        // generate pack
+        try {
+            $link = (new GenerateDocumentsService())->generateInstallationPack($this->order, $this->userId);
+            Log::info('Generate installation pack finished!');
+            event(new SendWebSocketMessageEvent('Пакет документов для монтажа готов!', $this->userId, ['success' => true, 'link' => $link]));
+        } catch (Exception $e) {
+            Log::info('Generate installation pack failed! ' . $e->getMessage());
+            event(new SendWebSocketMessageEvent('Ошибка создания покета документов для монтажа! ', $this->userId, ['error' => $e->getMessage()]));
+        }
+
+
+
     }
 }

+ 60 - 0
app/Services/FileService.php

@@ -3,7 +3,11 @@
 namespace App\Services;
 
 use App\Models\File;
+use Exception;
 use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
+use RecursiveIteratorIterator;
+use ZipArchive;
 
 class FileService
 {
@@ -23,4 +27,60 @@ class FileService
             'mime_type' => $file->getClientMimeType(),
         ]);
     }
+
+
+    /**
+     * @param string $path
+     * @param string $archiveName
+     * @param int|null $userId
+     * @param bool $deleteSourceFiles
+     * @return File
+     * @throws Exception
+     */
+    public function createZipArchive(string $path, string $archiveName, int $userId = null, bool $deleteSourceFiles = false): File
+    {
+
+        if (!($tempFile = tempnam(sys_get_temp_dir(), Str::random()))) {
+            throw new Exception('Cant create temporary file!');
+        }
+        var_dump(storage_path('app/public/' . $path));
+
+        $zip = new ZipArchive();
+        $fullPath = storage_path('app/public/' . $path);
+        $zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
+        $files = new RecursiveIteratorIterator(
+            new \RecursiveDirectoryIterator($fullPath),
+            RecursiveIteratorIterator::LEAVES_ONLY
+        );
+        foreach ($files as $file) {
+            if(!$file->isDir()) {
+                // Get real and relative path for current file
+                $filePath = $file->getRealPath();
+                var_dump($filePath);
+                $relativePath = substr($filePath, strlen($fullPath) + 1);
+                var_dump($relativePath);
+                // Add current file to archive
+                $zip->addFile($filePath, $relativePath);
+                if($deleteSourceFiles) {
+                    Storage::disk($file->disk)->delete($file->path);
+                    $file->delete();
+                }
+            }
+        }
+        $zip->close();
+        $fileModel = File::query()->updateOrCreate([
+            'link' => url('/storage/') . '/' . $path . '/' .$archiveName,
+            'path' => $path . '/' .$archiveName,
+            'user_id' => $userId ?? auth()->user()->id,
+            'original_name' => $archiveName,
+            'mime_type' => 'application/zip',
+        ]);
+        $contents = file_get_contents($tempFile);
+        Storage::disk('public')->put($path . '/../' .$archiveName, $contents);
+        unlink($tempFile);
+
+        return $fileModel;
+    }
+
+
 }

+ 41 - 0
app/Services/GenerateDocumentsService.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Services;
+
+use App\Models\Order;
+use Exception;
+use Illuminate\Support\Facades\Storage;
+
+class GenerateDocumentsService
+{
+    /**
+     * @param Order $order
+     * @param int $userId
+     * @return string
+     * @throws Exception
+     */
+    public function generateInstallationPack(Order $order, int $userId): string
+    {
+        $products_sku = $order->products_sku;
+        $articles = [];
+        Storage::disk('public')->makeDirectory('orders/' . $order->id . '/installation/Схемы сборки');
+        foreach ($products_sku as $sku) {
+            if(!in_array($sku->product->article, $articles)) {
+                $articles[] = $sku->product->article;
+                // find and copy scheme files to installation directory
+                // ...
+            }
+
+            // generate xlsx order file
+            // ...
+
+            // create zip archive
+            $fileModel = (new FileService())->createZipArchive('orders/' . $order->id . '/installation', 'Installation-' . $order->id . '.zip', $userId);
+
+            // create link
+            return $fileModel->link;
+
+
+        }
+    }
+}

+ 2 - 1
composer.json

@@ -11,7 +11,8 @@
         "laravel/tinker": "^2.9",
         "laravel/ui": "^4.6",
         "phpoffice/phpspreadsheet": "^3.6",
-        "predis/predis": "^2.3"
+        "predis/predis": "^2.3",
+        "ext-zip": "*"
     },
     "require-dev": {
         "fakerphp/faker": "^1.23",