SparePartController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Requests\StoreSparePartRequest;
  4. use App\Jobs\Export\ExportSparePartsJob;
  5. use App\Jobs\Import\ImportSparePartsJob;
  6. use App\Models\Import;
  7. use App\Models\SparePart;
  8. use App\Models\SparePartsView;
  9. use Illuminate\Http\RedirectResponse;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Cache;
  13. use Illuminate\Support\Facades\File;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Storage;
  16. use Illuminate\Support\Str;
  17. use League\CommonMark\Extension\HeadingPermalink\HeadingPermalinkExtension;
  18. class SparePartController extends Controller
  19. {
  20. protected array $data = [
  21. 'active' => 'spare_parts',
  22. 'title' => 'Каталог запчастей',
  23. 'id' => 'spare_parts',
  24. 'header' => [
  25. 'image' => 'Картинка',
  26. 'id' => 'ID',
  27. 'article' => 'Артикул',
  28. 'used_in_maf' => 'Где используется',
  29. 'quantity_without_docs' => 'Кол-во без док',
  30. 'quantity_with_docs' => 'Кол-во с док',
  31. 'total_quantity' => 'Кол-во общее',
  32. 'note' => 'Примечание',
  33. 'customer_price_txt' => 'Цена для заказчика',
  34. 'expertise_price_txt' => 'Цена экспертизы',
  35. 'tsn_number' => '№ по ТСН',
  36. 'pricing_codes_list' => 'Шифр расценки и коды ресурсов',
  37. 'min_stock' => 'Минимальный остаток',
  38. ],
  39. 'searchFields' => [
  40. 'article',
  41. 'used_in_maf',
  42. 'note',
  43. 'tsn_number',
  44. ],
  45. 'routeName' => 'spare_parts.show',
  46. ];
  47. public function index(Request $request)
  48. {
  49. session(['gp_spare_parts' => $request->query()]);
  50. $nav = $this->startNavigationContext($request);
  51. $model = new SparePartsView();
  52. // Для админа добавляем колонку цены закупки
  53. if ($request->user()?->hasPermission('spare_parts.purchase_price.view')) {
  54. $this->data['header'] = array_merge(
  55. array_slice($this->data['header'], 0, 8, true),
  56. ['purchase_price_txt' => 'Цена закупки'],
  57. array_slice($this->data['header'], 8, null, true)
  58. );
  59. }
  60. // Фильтры
  61. $this->createFilters($model, 'used_in_maf');
  62. $this->data['filters']['customer_price_txt'] = [
  63. 'title' => $this->data['header']['customer_price_txt'],
  64. 'values' => [],
  65. ];
  66. $this->data['filters']['expertise_price_txt'] = [
  67. 'title' => $this->data['header']['expertise_price_txt'],
  68. 'values' => [],
  69. ];
  70. $this->data['filters']['pricing_codes_list'] = [
  71. 'title' => $this->data['header']['pricing_codes_list'],
  72. 'values' => [],
  73. ];
  74. if ($request->user()?->hasPermission('spare_parts.purchase_price.view')) {
  75. $this->data['filters']['purchase_price_txt'] = [
  76. 'title' => $this->data['header']['purchase_price_txt'],
  77. 'values' => [],
  78. ];
  79. }
  80. // Запрос
  81. $q = $model::query()->with('pricingCodes');
  82. $this->acceptFilters($q, $request);
  83. $this->acceptSearch($q, $request);
  84. $this->setSortAndOrderBy($model, $request);
  85. if ($request->get('sortBy') === 'pricing_codes_list') {
  86. $this->data['sortBy'] = 'pricing_codes_list';
  87. $q->orderBy(
  88. DB::table('spare_part_pricing_code as sppc')
  89. ->join('pricing_codes as pc', 'pc.id', '=', 'sppc.pricing_code_id')
  90. ->selectRaw('MIN(pc.code)')
  91. ->whereColumn('sppc.spare_part_id', 'spare_parts_view.id'),
  92. $this->data['orderBy'] ?? 'asc'
  93. )->orderBy('id', $this->data['orderBy'] ?? 'asc');
  94. } else {
  95. $this->applyStableSorting($q);
  96. }
  97. $this->data['spare_parts'] = $q->paginate($this->data['per_page'])->withQueryString();
  98. $this->data['strings'] = $this->data['spare_parts'];
  99. $this->data['tab'] = 'catalog';
  100. $this->data['nav'] = $nav;
  101. return view('spare_parts.index', $this->data);
  102. }
  103. public function show(Request $request, SparePart $sparePart)
  104. {
  105. $nav = $this->resolveNavToken($request);
  106. $this->rememberNavigation($request, $nav);
  107. $this->data['nav'] = $nav;
  108. $this->data['back_url'] = $this->navigationBackUrl(
  109. $request,
  110. $nav,
  111. route('spare_parts.index', session('gp_spare_parts'))
  112. );
  113. $this->data['spare_part'] = $sparePart;
  114. return view('spare_parts.edit', $this->data);
  115. }
  116. public function help()
  117. {
  118. $this->data['active'] = 'spare_parts_help';
  119. $this->data['title'] = 'Справка по модулю «Запчасти»';
  120. $markdownPath = base_path('docs/spare-parts.md');
  121. $markdown = File::exists($markdownPath) ? File::get($markdownPath) : '# Справка не найдена';
  122. $this->data['helpContent'] = Str::markdown($markdown, [
  123. 'heading_permalink' => [
  124. 'html_class' => 'heading-permalink',
  125. 'id_prefix' => '',
  126. 'fragment_prefix' => '',
  127. 'insert' => 'none',
  128. 'apply_id_to_heading' => true,
  129. 'min_heading_level' => 1,
  130. 'max_heading_level' => 6,
  131. 'symbol' => '',
  132. ],
  133. ], [
  134. new HeadingPermalinkExtension(),
  135. ]);
  136. $this->data['tab'] = 'help';
  137. return view('spare_parts.index', $this->data);
  138. }
  139. public function create(Request $request)
  140. {
  141. $nav = $this->resolveNavToken($request);
  142. $this->rememberNavigation($request, $nav);
  143. $this->data['nav'] = $nav;
  144. $this->data['back_url'] = $this->navigationBackUrl(
  145. $request,
  146. $nav,
  147. route('spare_parts.index', session('gp_spare_parts'))
  148. );
  149. $this->data['spare_part'] = null;
  150. return view('spare_parts.edit', $this->data);
  151. }
  152. public function store(StoreSparePartRequest $request): RedirectResponse
  153. {
  154. $sparePart = SparePart::create($request->validated());
  155. $this->syncPricingCodes($sparePart, $request);
  156. $nav = $this->resolveNavToken($request);
  157. $backUrl = $this->navigationParentUrl(
  158. $nav,
  159. route('spare_parts.index', session('gp_spare_parts'))
  160. );
  161. return redirect()->to($backUrl)->with(['success' => 'Запчасть успешно создана!']);
  162. }
  163. public function update(StoreSparePartRequest $request, SparePart $sparePart): RedirectResponse
  164. {
  165. $sparePart->update($request->validated());
  166. $this->syncPricingCodes($sparePart, $request);
  167. $nav = $this->resolveNavToken($request);
  168. $backUrl = $this->navigationParentUrl(
  169. $nav,
  170. route('spare_parts.index', session('gp_spare_parts'))
  171. );
  172. return redirect()->to($backUrl)->with(['success' => 'Запчасть успешно обновлена!']);
  173. }
  174. protected function syncPricingCodes(SparePart $sparePart, StoreSparePartRequest $request): void
  175. {
  176. $codes = $request->input('pricing_codes', []);
  177. $descriptions = $request->input('pricing_codes_descriptions', []);
  178. $pricingCodeIds = [];
  179. foreach ($codes as $index => $code) {
  180. $code = trim($code);
  181. if (empty($code)) {
  182. continue;
  183. }
  184. $description = trim($descriptions[$index] ?? '');
  185. // Находим или создаём PricingCode
  186. $pricingCode = \App\Models\PricingCode::where('type', \App\Models\PricingCode::TYPE_PRICING_CODE)
  187. ->where('code', $code)
  188. ->first();
  189. if ($pricingCode) {
  190. // Обновляем расшифровку, если предоставлена
  191. if ($description && $description !== $pricingCode->description) {
  192. $pricingCode->update(['description' => $description]);
  193. }
  194. } else {
  195. // Создаём новый код
  196. $pricingCode = \App\Models\PricingCode::create([
  197. 'type' => \App\Models\PricingCode::TYPE_PRICING_CODE,
  198. 'code' => $code,
  199. 'description' => $description ?: null,
  200. ]);
  201. }
  202. $pricingCodeIds[] = $pricingCode->id;
  203. }
  204. // Синхронизируем связи
  205. $sparePart->pricingCodes()->sync($pricingCodeIds);
  206. }
  207. public function destroy(SparePart $sparePart): RedirectResponse
  208. {
  209. // Проверка на наличие заказов
  210. if ($sparePart->orders()->count() > 0) {
  211. return redirect()->route('spare_parts.index', session('gp_spare_parts'))
  212. ->with(['error' => 'Невозможно удалить запчасть, т.к. для неё есть заказы!']);
  213. }
  214. $sparePart->delete();
  215. return redirect()->route('spare_parts.index', session('gp_spare_parts'))
  216. ->with(['success' => 'Запчасть успешно удалена!']);
  217. }
  218. public function export(Request $request): RedirectResponse
  219. {
  220. // Запускаем Job для экспорта
  221. ExportSparePartsJob::dispatch(auth()->id());
  222. Log::info('ExportSparePartsJob created!');
  223. return redirect()->route('spare_parts.index', session('gp_spare_parts'))
  224. ->with(['success' => 'Задача экспорта успешно создана!']);
  225. }
  226. public function import(Request $request): RedirectResponse
  227. {
  228. $request->validate([
  229. 'file' => 'required|mimes:xlsx,xls|max:10240',
  230. ]);
  231. try {
  232. // Сохраняем временный файл
  233. $file = $request->file('file');
  234. $tempPath = $file->storeAs('temp/imports', 'spare_parts_import_' . time() . '.xlsx');
  235. $fullPath = Storage::path($tempPath);
  236. // Создаём запись импорта
  237. $import = Import::create([
  238. 'user_id' => auth()->id(),
  239. 'type' => 'spare_parts',
  240. 'status' => Import::STATUS_PENDING,
  241. 'file_path' => $tempPath,
  242. 'original_filename' => $file->getClientOriginalName(),
  243. ]);
  244. // Запускаем Job для импорта
  245. ImportSparePartsJob::dispatch($fullPath, auth()->id(), $import->id);
  246. Log::info('ImportSparePartsJob created!', ['import_id' => $import->id]);
  247. return redirect()->route('spare_parts.index', session('gp_spare_parts'))
  248. ->with(['success' => 'Задача импорта успешно создана! Следите за статусом в разделе импорта.']);
  249. } catch (\Exception $e) {
  250. Log::error('Ошибка создания задачи импорта: ' . $e->getMessage());
  251. return redirect()->route('spare_parts.index', session('gp_spare_parts'))
  252. ->with(['error' => 'Ошибка импорта: ' . $e->getMessage()]);
  253. }
  254. }
  255. public function uploadImage(Request $request, SparePart $sparePart): RedirectResponse
  256. {
  257. $request->validate([
  258. 'image' => 'required|image|mimes:jpeg,jpg,png|max:2048',
  259. ]);
  260. if ($request->hasFile('image')) {
  261. $image = $request->file('image');
  262. $filename = $sparePart->article . '.jpg';
  263. // Создаём директорию если её нет
  264. $directory = public_path('images/spare_parts');
  265. if (!file_exists($directory)) {
  266. mkdir($directory, 0755, true);
  267. }
  268. // Сохраняем изображение
  269. $image->move($directory, $filename);
  270. Cache::forget('spare_part_image:' . $sparePart->article);
  271. return $this->redirectToSparePartShow($request, $sparePart)
  272. ->with(['success' => 'Изображение успешно загружено!']);
  273. }
  274. return $this->redirectToSparePartShow($request, $sparePart)
  275. ->with(['error' => 'Ошибка загрузки изображения!']);
  276. }
  277. /**
  278. * API метод для поиска запчастей (autocomplete)
  279. */
  280. public function search(Request $request)
  281. {
  282. $query = $request->get('query', '');
  283. $spareParts = SparePart::query()
  284. ->where(function ($q) use ($query) {
  285. $q->where('article', 'LIKE', '%' . $query . '%')
  286. ->orWhere('note', 'LIKE', '%' . $query . '%');
  287. })
  288. ->orderBy('article')
  289. ->limit(20)
  290. ->get(['id', 'article', 'note']);
  291. return response()->json($spareParts);
  292. }
  293. private function redirectToSparePartShow(Request $request, SparePart $sparePart): RedirectResponse
  294. {
  295. $nav = $this->resolveNavToken($request);
  296. return redirect()->route('spare_parts.show', $this->withNav(['sparePart' => $sparePart], $nav));
  297. }
  298. }