--- /dev/null
+<?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;
+ }
+}
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;