]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
[ERP-482] Создание списка вложений из списаний старше двух месяцев origin/feature_filippov_erp-482_make_old_file_wr_off_list
authorAleksey Filippov <Aleksey.Filippov@erp-flowers.ru>
Tue, 14 Oct 2025 11:52:20 +0000 (14:52 +0300)
committerAleksey Filippov <Aleksey.Filippov@erp-flowers.ru>
Tue, 14 Oct 2025 11:52:20 +0000 (14:52 +0300)
erp24/commands/WriteOffsAttachmentsController.php [new file with mode: 0644]
erp24/records/WriteOffsErp.php

diff --git a/erp24/commands/WriteOffsAttachmentsController.php b/erp24/commands/WriteOffsAttachmentsController.php
new file mode 100644 (file)
index 0000000..a81a043
--- /dev/null
@@ -0,0 +1,78 @@
+<?php
+
+namespace yii_app\commands;
+
+use Yii;
+use yii\console\Controller;
+use yii\console\ExitCode;
+use yii_app\records\WriteOffsErp;
+
+class WriteOffsAttachmentsController extends Controller
+{
+    /**
+     * Экспортирует вложения всех документов старше одного месяца в JSON-файл в runtime.
+     * Пример запуска: php yii write-offs-attachments/export-old
+     * Файл: runtime/attachments_older_than_month_YYYYmmdd_His.json
+     */
+    public function actionExportOld(): int
+    {
+        $data = [
+            'generated_at' => date('Y-m-d H:i:s'),
+            'border_date' => date('Y-m-d H:i:s', strtotime('-2 month')),
+            'items' => WriteOffsErp::getAttachmentsOlderThanMonth(),
+        ];
+
+        $dir = Yii::getAlias('@runtime');
+        $stamp = date('Ymd_His');
+        $filename = 'attachments_older_than_month_' . $stamp . '.json';
+        $filePath = rtrim($dir, '/') . '/' . $filename;
+
+        $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
+        $result = @file_put_contents($filePath, $json);
+        if ($result === false) {
+            $this->stderr("Не удалось записать файл: {$filePath}\n");
+            return ExitCode::UNSPECIFIED_ERROR;
+        }
+
+        $this->stdout("Сохранено: {$filePath}\n");
+
+        // Сохраняем отдельный файл со списком путей (url) вложений
+        $paths = [];
+        foreach (($data['items'] ?? []) as $item) {
+            foreach (($item['attachments'] ?? []) as $attachment) {
+                if (!empty($attachment['url'])) {
+                    $paths[] = $attachment['url'];
+                }
+            }
+        }
+
+        $pathsFilename = 'old_files.txt';
+        $pathsFilePath = rtrim($dir, '/') . '/' . $pathsFilename;
+        $pathsContent = implode(PHP_EOL, $paths) . PHP_EOL;
+        $pathsResult = @file_put_contents($pathsFilePath, $pathsContent);
+        if ($pathsResult === false) {
+            $this->stderr("Не удалось записать файл путей: {$pathsFilePath}\n");
+        } else {
+            $this->stdout("Сохранено (пути): {$pathsFilePath}\n");
+        }
+
+        return ExitCode::OK;
+    }
+
+    /**
+     * Выводит на экран список вложений всех документов старше одного месяца.
+     * Пример запуска: php yii write-offs-attachments/print-old
+     */
+    public function actionPrintOld(): int
+    {
+        $data = [
+//            'generated_at' => date('Y-m-d H:i:s'),
+//            'border_date' => date('Y-m-d H:i:s', strtotime('-1 month')),
+            'items' => WriteOffsErp::getAttachmentsOlderThanMonthList(),
+        ];
+
+        $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
+        $this->stdout($json . "\n");
+        return ExitCode::OK;
+    }
+}
index 60b07e96fa4832c944a8742a22ace5b28085e226..32b8ccfab623da672680e1b3a0a501c1e7aa69ba 100644 (file)
@@ -782,6 +782,115 @@ class WriteOffsErp extends \yii\db\ActiveRecord
         return $images;
     }
 
+    /**
+     * Формирует список всех вложений (изображения + видео) документа.
+     * Возвращает простой массив с элементами вида:
+     * [
+     *   'type' => 'image'|'video',
+     *   'product_item_id' => int|null,
+     *   'url' => string,
+     *   'thumb' => string|null,
+     *   'name' => string|null,
+     *   'mime' => string|null
+     * ]
+     */
+    public function getAttachments(): array
+    {
+        $attachments = [];
+
+        // Изображения, привязанные через image_document_link к строкам документа
+        $imagesLinks = $this->getImagesWriteOffsErp()->all();
+        foreach ($imagesLinks as $link) {
+            $image = \yii_app\records\Images::findOne(['id' => $link->image_id]);
+            if (!$image) {
+                continue;
+            }
+            $url = File::src($image->filename, 'images');
+            // $thumb = null;
+            // if (!empty($image->size)) {
+            //     $thumb = '/' . File::getResizedImageByName($image->filename, 100, 100);
+            // }
+
+            $attachments[] = [
+                'type' => 'image',
+                'product_item_id' => $link->document_item_id,
+                'url' => $url,
+                // 'thumb' => $thumb,
+                'name' => File::getRealName($link->image_id),
+                'mime' => $image->type,
+            ];
+        }
+
+        // Видео, привязанные к строкам списания через files (entity WRITE_OFFS_VIDEO)
+        $items = $this->getWriteOffsProductsErps()->all();
+        foreach ($items as $item) {
+            $video = $item->video ?? null;
+            if ($video) {
+                $attachments[] = [
+                    'type' => 'video',
+                    'product_item_id' => $item->id,
+                    'url' => $video->url,
+                    'thumb' => null,
+                    'name' => null,
+                    'mime' => $video->file_type,
+                ];
+            }
+        }
+
+        return $attachments;
+    }
+
+    /**
+     * Возвращает вложения для всех документов, дата которых старше одного месяца.
+     * Можно передать свою граничную дату в $borderDate (формат Y-m-d или Y-m-d H:i:s).
+     * Структура ответа: массив элементов с ключами document_id, date, attachments.
+     */
+    public static function getAttachmentsOlderThanMonth(?string $borderDate = null): array
+    {
+        $borderDate = $borderDate ?: date('Y-m-d H:i:s', strtotime('-2 month'));
+
+        $docs = self::find()
+            ->andWhere(['status' => self::STATUS_CREATED_1C])
+            ->andWhere(['<', 'date', $borderDate])
+            ->all();
+
+        $result = [];
+        foreach ($docs as $doc) {
+            $result[] = [
+                'document_id' => $doc->id,
+                'date' => $doc->getDate(),
+                'attachments' => $doc->getAttachments(),
+            ];
+        }
+
+        return $result;
+    }
+
+
+
+    /**
+     * Возвращает вложения для всех документов, дата которых старше одного месяца.
+     * Можно передать свою граничную дату в $borderDate (формат Y-m-d или Y-m-d H:i:s).
+     * Структура ответа: массив элементов с ключами document_id, date, attachments.
+     */
+    public static function getAttachmentsOlderThanMonthList(?string $borderDate = null): array
+    {
+        $borderDate = $borderDate ?: date('Y-m-d H:i:s', strtotime('-2 month'));
+
+        $docs = self::find()
+            ->andWhere(['status' => self::STATUS_CREATED_1C])
+            ->andWhere(['<', 'date', $borderDate])
+            ->all();
+
+        $result = [];
+        foreach ($docs as $doc) {
+            $linksRow = $doc->getAttachments();
+            $result[] = $linksRow;
+        }
+
+        return $result;
+    }
+
     public static function isManager(int $storeId) : bool
     {
         $adminId = Yii::$app->user->id;