ImportCommonCatalogService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Services\Import;
  4. use App\Models\CommonCatalogItem;
  5. use App\Models\File;
  6. use App\Models\Import;
  7. use App\Models\User;
  8. use App\Services\Access\AccessService;
  9. use App\Services\Export\ExportCommonCatalogService;
  10. use App\Services\FileService;
  11. use Illuminate\Support\Facades\Storage;
  12. use Illuminate\Support\Facades\Validator;
  13. use Illuminate\Support\Str;
  14. use PhpOffice\PhpSpreadsheet\Cell\Cell;
  15. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  16. use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
  18. use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
  19. use RuntimeException;
  20. use Throwable;
  21. class ImportCommonCatalogService
  22. {
  23. public function __construct(
  24. private readonly Import $import,
  25. private readonly int $userId,
  26. ) {}
  27. public function handle(): bool
  28. {
  29. try {
  30. $path = Storage::disk('upload')->path((string) $this->import->filename);
  31. $spreadsheet = (new Xlsx)->load($path);
  32. $sheet = $spreadsheet->getActiveSheet();
  33. $this->assertHeaders(
  34. $sheet->rangeToArray('A1:AD1', null, true, true, false)[0],
  35. $sheet->rangeToArray('A2:AD2', null, true, true, false)[0],
  36. );
  37. $drawings = $this->drawingsByRow($sheet->getDrawingCollection());
  38. $articleCounts = $this->articleCounts($sheet);
  39. $user = User::query()->findOrFail($this->userId);
  40. $access = app(AccessService::class);
  41. $created = 0;
  42. $updated = 0;
  43. $errors = 0;
  44. for ($row = 3; $row <= $sheet->getHighestDataRow(); $row++) {
  45. $article = $this->stringValue($sheet->getCell("A{$row}")->getFormattedValue());
  46. if ($article === null) {
  47. continue;
  48. }
  49. $data = [
  50. 'article' => $article,
  51. 'calculator_name' => $this->stringValue($sheet->getCell("B{$row}")->getValue()),
  52. 'kind' => $this->stringValue($sheet->getCell("C{$row}")->getValue()),
  53. 'dimension_length' => $this->dimensionValue($sheet->getCell("D{$row}")),
  54. 'dimension_width' => $this->dimensionValue($sheet->getCell("E{$row}")),
  55. 'dimension_height' => $this->dimensionValue($sheet->getCell("F{$row}")),
  56. 'site_length' => $this->dimensionValue($sheet->getCell("G{$row}")),
  57. 'site_width' => $this->dimensionValue($sheet->getCell("H{$row}")),
  58. 'fall_height' => $this->numericValue($sheet->getCell("I{$row}")->getCalculatedValue()),
  59. 'additional_info' => $this->stringValue($sheet->getCell("J{$row}")->getValue()),
  60. 'dimension_unit' => $this->stringValue($sheet->getCell("K{$row}")->getValue()),
  61. 'weight' => $this->numericValue($sheet->getCell("L{$row}")->getCalculatedValue()),
  62. 'volume' => $this->numericValue($sheet->getCell("M{$row}")->getCalculatedValue()),
  63. 'places' => $this->integerValue($sheet->getCell("N{$row}")->getCalculatedValue()),
  64. 'composition' => $this->stringValue($sheet->getCell("O{$row}")->getValue()),
  65. 'age_group' => $this->stringValue($sheet->getCell("P{$row}")->getFormattedValue()),
  66. 'max_users' => $this->integerValue($sheet->getCell("Q{$row}")->getCalculatedValue()),
  67. 'unit' => $this->stringValue($sheet->getCell("R{$row}")->getValue()),
  68. 'series' => $this->stringValue($sheet->getCell("T{$row}")->getValue()),
  69. 'trademark' => $this->stringValue($sheet->getCell("U{$row}")->getValue()),
  70. 'calculator_enabled' => $this->booleanValue($sheet->getCell("V{$row}")->getValue()),
  71. 'builders_price' => $this->numericValue($sheet->getCell("W{$row}")->getCalculatedValue()),
  72. 'wholesale_price' => $this->numericValue($sheet->getCell("X{$row}")->getCalculatedValue()),
  73. 'recommended_price' => $this->numericValue($sheet->getCell("Y{$row}")->getCalculatedValue()),
  74. 'retail_price' => $this->numericValue($sheet->getCell("Z{$row}")->getCalculatedValue()),
  75. 'project_price' => $this->numericValue($sheet->getCell("AA{$row}")->getCalculatedValue()),
  76. 'project_with_installation_price' => $this->numericValue($sheet->getCell("AB{$row}")->getCalculatedValue()),
  77. 'pik_price' => $this->numericValue($sheet->getCell("AC{$row}")->getCalculatedValue()),
  78. 'recommended_plus_10_price' => $this->numericValue($sheet->getCell("AD{$row}")->getCalculatedValue()),
  79. ];
  80. $data = $access->filterWritableData($user, 'common-catalog', $data);
  81. $validator = Validator::make($data, $this->rules());
  82. if ($validator->fails()) {
  83. $errors++;
  84. $this->import->log(
  85. "Строка {$row}: ".implode(' ', $validator->errors()->all()),
  86. 'WARNING',
  87. );
  88. continue;
  89. }
  90. $validated = $validator->validated();
  91. $item = $this->findExistingItem(
  92. $article,
  93. $validated['calculator_name'],
  94. $articleCounts[$article] ?? 1,
  95. );
  96. if ($item) {
  97. $item->update($validated);
  98. $updated++;
  99. } else {
  100. $item = CommonCatalogItem::query()->create($validated);
  101. $created++;
  102. }
  103. if (isset($drawings[$row])) {
  104. try {
  105. $this->replaceImage($item, $drawings[$row]);
  106. } catch (Throwable $exception) {
  107. $errors++;
  108. $this->import->log(
  109. "Строка {$row}: изображение не импортировано ({$exception->getMessage()}).",
  110. 'WARNING',
  111. );
  112. }
  113. }
  114. }
  115. $this->import->log("Создано: {$created}; обновлено: {$updated}; ошибок: {$errors}.");
  116. $this->import->status = 'DONE';
  117. $this->import->save();
  118. $spreadsheet->disconnectWorksheets();
  119. return true;
  120. } catch (Throwable $exception) {
  121. $this->import->log($exception->getMessage(), 'ERROR');
  122. $this->import->status = 'ERROR';
  123. $this->import->save();
  124. throw $exception;
  125. }
  126. }
  127. private function assertHeaders(array $headers, array $subheaders): void
  128. {
  129. $actual = array_map($this->normalizeHeader(...), $headers);
  130. $expected = array_map($this->normalizeHeader(...), ExportCommonCatalogService::HEADERS);
  131. $actualSubheaders = array_map($this->normalizeHeader(...), $subheaders);
  132. $expectedSubheaders = array_map($this->normalizeHeader(...), ExportCommonCatalogService::SUBHEADERS);
  133. if ($actual !== $expected || $actualSubheaders !== $expectedSubheaders) {
  134. throw new RuntimeException('Некорректные заголовки файла общего каталога. Используйте утверждённый формат.');
  135. }
  136. }
  137. private function articleCounts(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet): array
  138. {
  139. $counts = [];
  140. for ($row = 3; $row <= $sheet->getHighestDataRow(); $row++) {
  141. $article = $this->stringValue($sheet->getCell("A{$row}")->getFormattedValue());
  142. if ($article !== null) {
  143. $counts[$article] = ($counts[$article] ?? 0) + 1;
  144. }
  145. }
  146. return $counts;
  147. }
  148. private function findExistingItem(
  149. string $article,
  150. ?string $name,
  151. int $sourceOccurrences,
  152. ): ?CommonCatalogItem {
  153. $exact = CommonCatalogItem::query()
  154. ->where('article', $article)
  155. ->where('calculator_name', $name)
  156. ->first();
  157. if ($exact) {
  158. return $exact;
  159. }
  160. if ($sourceOccurrences !== 1) {
  161. return null;
  162. }
  163. $items = CommonCatalogItem::query()
  164. ->where('article', $article)
  165. ->limit(2)
  166. ->get();
  167. return $items->count() === 1 ? $items->first() : null;
  168. }
  169. /** @param iterable<BaseDrawing> $drawings */
  170. private function drawingsByRow(iterable $drawings): array
  171. {
  172. $result = [];
  173. foreach ($drawings as $drawing) {
  174. if (preg_match('/^S(\d+)$/i', $drawing->getCoordinates(), $matches) === 1) {
  175. $result[(int) $matches[1]] = $drawing;
  176. }
  177. }
  178. return $result;
  179. }
  180. private function replaceImage(CommonCatalogItem $item, BaseDrawing $drawing): void
  181. {
  182. [$contents, $mimeType, $extension] = $this->drawingContents($drawing);
  183. $relativePath = "common_catalog/items/{$item->id}/image/".Str::uuid().".{$extension}";
  184. Storage::disk('public')->put($relativePath, $contents);
  185. $newImage = File::query()->create([
  186. 'user_id' => $this->userId,
  187. 'original_name' => "{$item->article}.{$extension}",
  188. 'mime_type' => $mimeType,
  189. 'path' => $relativePath,
  190. 'link' => url('/storage/'.$relativePath),
  191. ]);
  192. app(FileService::class)->ensureThumbnail($newImage);
  193. $oldImage = $item->imageFile;
  194. $item->update(['image_file_id' => $newImage->id]);
  195. if ($oldImage) {
  196. app(FileService::class)->deleteFileWithThumbnail($oldImage);
  197. $oldImage->delete();
  198. }
  199. }
  200. private function drawingContents(BaseDrawing $drawing): array
  201. {
  202. if ($drawing instanceof MemoryDrawing) {
  203. ob_start();
  204. ($drawing->getRenderingFunction())($drawing->getImageResource());
  205. $contents = ob_get_clean();
  206. $mimeType = $drawing->getMimeType();
  207. } elseif ($drawing instanceof Drawing) {
  208. $contents = file_get_contents($drawing->getPath());
  209. $mimeType = $this->mimeType($contents ?: '');
  210. } else {
  211. throw new RuntimeException('Неподдерживаемый формат изображения.');
  212. }
  213. if (! is_string($contents) || $contents === '') {
  214. throw new RuntimeException('Пустое изображение.');
  215. }
  216. $extension = match ($mimeType) {
  217. 'image/jpeg' => 'jpg',
  218. 'image/png' => 'png',
  219. 'image/webp' => 'webp',
  220. default => throw new RuntimeException("Неподдерживаемый MIME-тип {$mimeType}"),
  221. };
  222. return [$contents, $mimeType, $extension];
  223. }
  224. private function mimeType(string $contents): string
  225. {
  226. $info = new \finfo(FILEINFO_MIME_TYPE);
  227. return (string) $info->buffer($contents);
  228. }
  229. private function normalizeHeader(mixed $value): string
  230. {
  231. return trim((string) preg_replace('/\s+/u', ' ', (string) $value));
  232. }
  233. private function stringValue(mixed $value): ?string
  234. {
  235. $value = trim((string) $value);
  236. return $value === '' ? null : $value;
  237. }
  238. private function numericValue(mixed $value): int|float|string|null
  239. {
  240. $value = $this->stringValue($value);
  241. if ($value === null) {
  242. return null;
  243. }
  244. return str_replace([' ', ','], ['', '.'], $value);
  245. }
  246. private function dimensionValue(Cell $cell): ?string
  247. {
  248. $calculated = $cell->getCalculatedValue();
  249. if (is_int($calculated) || is_float($calculated)) {
  250. return rtrim(rtrim(number_format((float) $calculated, 10, '.', ''), '0'), '.');
  251. }
  252. return $this->stringValue($cell->getFormattedValue());
  253. }
  254. private function integerValue(mixed $value): int|string|null
  255. {
  256. $value = $this->numericValue($value);
  257. if ($value === null) {
  258. return null;
  259. }
  260. return is_numeric($value) ? (int) $value : (string) $value;
  261. }
  262. private function booleanValue(mixed $value): bool|string|null
  263. {
  264. $value = $this->stringValue($value);
  265. if ($value === null) {
  266. return null;
  267. }
  268. return match (mb_strtolower($value)) {
  269. 'да', 'yes', '1' => true,
  270. 'нет', 'no', '0' => false,
  271. default => $value,
  272. };
  273. }
  274. private function rules(): array
  275. {
  276. return [
  277. 'article' => ['required', 'string', 'max:100'],
  278. 'calculator_name' => ['nullable', 'string', 'max:255'],
  279. 'kind' => ['nullable', 'string', 'max:255'],
  280. 'dimension_length' => ['nullable', 'string', 'max:255'],
  281. 'dimension_width' => ['nullable', 'string', 'max:255'],
  282. 'dimension_height' => ['nullable', 'string', 'max:255'],
  283. 'site_length' => ['nullable', 'string', 'max:255'],
  284. 'site_width' => ['nullable', 'string', 'max:255'],
  285. 'fall_height' => ['nullable', 'numeric', 'min:0'],
  286. 'additional_info' => ['nullable', 'string'],
  287. 'dimension_unit' => ['nullable', 'string', 'max:50'],
  288. 'weight' => ['nullable', 'numeric', 'min:0'],
  289. 'volume' => ['nullable', 'numeric', 'min:0'],
  290. 'places' => ['nullable', 'integer', 'min:0'],
  291. 'composition' => ['nullable', 'string'],
  292. 'age_group' => ['nullable', 'string', 'max:100'],
  293. 'max_users' => ['nullable', 'integer', 'min:0'],
  294. 'unit' => ['nullable', 'string', 'max:50'],
  295. 'series' => ['nullable', 'string', 'max:255'],
  296. 'trademark' => ['nullable', 'string', 'max:255'],
  297. 'calculator_enabled' => ['nullable', 'boolean'],
  298. 'builders_price' => ['nullable', 'numeric', 'min:0'],
  299. 'wholesale_price' => ['nullable', 'numeric', 'min:0'],
  300. 'recommended_price' => ['nullable', 'numeric', 'min:0'],
  301. 'retail_price' => ['nullable', 'numeric', 'min:0'],
  302. 'project_price' => ['nullable', 'numeric', 'min:0'],
  303. 'project_with_installation_price' => ['nullable', 'numeric', 'min:0'],
  304. 'pik_price' => ['nullable', 'numeric', 'min:0'],
  305. 'recommended_plus_10_price' => ['nullable', 'numeric', 'min:0'],
  306. ];
  307. }
  308. }