edit.blade.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. @extends('layouts.app')
  2. @section('content')
  3. <div class="container-fluid">
  4. <div class="row">
  5. <div class="col-12">
  6. <div class="row mb-2">
  7. <div class="col-md-6">
  8. <h3>{{ $spare_part ? 'Редактирование запчасти' : 'Создание запчасти' }}</h3>
  9. </div>
  10. <div class="col-md-6 text-end">
  11. @if($spare_part && hasRole('admin'))
  12. <button class="btn btn-sm text-success" onclick="$('#upl-image').trigger('click');"><i class="bi bi-plus-circle-fill"></i> Загрузить изображение</button>
  13. <form action="{{ route('spare_parts.upload_image', ['sparePart' => $spare_part]) }}" class="visually-hidden" method="POST" enctype="multipart/form-data">
  14. @csrf
  15. <input type="file" name="image" onchange="$(this).parent().submit()" required id="upl-image" accept="image/*" />
  16. </form>
  17. @endif
  18. </div>
  19. </div>
  20. <form action="{{ $spare_part ? route('spare_parts.update', $spare_part) : route('spare_parts.store') }}"
  21. method="POST">
  22. @csrf
  23. @if($spare_part)
  24. @method('PUT')
  25. @endif
  26. <input type="hidden" name="previous_url" value="{{ $previous_url ?? url()->previous() }}">
  27. <div class="row">
  28. {{-- Левая колонка --}}
  29. <div class="col-md-6">
  30. @if($spare_part && $spare_part->image)
  31. <div class="mb-3">
  32. <img src="{{ $spare_part->image }}" alt="{{ $spare_part->article }}" class="img-fluid img-max-200">
  33. </div>
  34. @endif
  35. <div class="mb-3">
  36. <label for="article" class="form-label">Артикул <span class="text-danger">*</span></label>
  37. <input type="text"
  38. class="form-control"
  39. id="article"
  40. name="article"
  41. value="{{ old('article', $spare_part->article ?? '') }}"
  42. {{ hasRole('admin,manager') ? '' : 'readonly' }}
  43. required>
  44. </div>
  45. <div class="mb-3">
  46. <label for="used_in_maf" class="form-label">Где используется</label>
  47. <input type="text"
  48. class="form-control"
  49. id="used_in_maf"
  50. name="used_in_maf"
  51. value="{{ old('used_in_maf', $spare_part->used_in_maf ?? '') }}"
  52. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  53. </div>
  54. <div class="mb-3">
  55. <label for="note" class="form-label">Примечание</label>
  56. <textarea class="form-control"
  57. id="note"
  58. name="note"
  59. rows="3"
  60. {{ hasRole('admin,manager') ? '' : 'readonly' }}>{{ old('note', $spare_part->note ?? '') }}</textarea>
  61. </div>
  62. </div>
  63. {{-- Правая колонка --}}
  64. <div class="col-md-6">
  65. @if(hasRole('admin'))
  66. <div class="mb-3">
  67. <label for="purchase_price" class="form-label">Цена закупки (руб.)</label>
  68. <input type="number"
  69. class="form-control"
  70. id="purchase_price"
  71. name="purchase_price"
  72. step="0.01"
  73. value="{{ old('purchase_price', $spare_part->purchase_price ?? '') }}">
  74. </div>
  75. @endif
  76. <div class="mb-3">
  77. <label for="customer_price" class="form-label">Цена для заказчика (руб.)</label>
  78. <input type="number"
  79. class="form-control"
  80. id="customer_price"
  81. name="customer_price"
  82. step="0.01"
  83. value="{{ old('customer_price', $spare_part->customer_price ?? '') }}"
  84. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  85. </div>
  86. <div class="mb-3">
  87. <label for="expertise_price" class="form-label">Цена экспертизы (руб.)</label>
  88. <input type="number"
  89. class="form-control"
  90. id="expertise_price"
  91. name="expertise_price"
  92. step="0.01"
  93. value="{{ old('expertise_price', $spare_part->expertise_price ?? '') }}"
  94. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  95. </div>
  96. <div class="mb-3">
  97. <label for="tsn_number" class="form-label">№ по ТСН</label>
  98. <div class="row">
  99. <div class="col-md-5 position-relative">
  100. <input type="text"
  101. class="form-control"
  102. id="tsn_number"
  103. name="tsn_number"
  104. value="{{ old('tsn_number', $spare_part->tsn_number ?? '') }}"
  105. autocomplete="off"
  106. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  107. <div class="autocomplete-dropdown" id="tsn_number_dropdown"></div>
  108. </div>
  109. <div class="col-md-7">
  110. <input type="text"
  111. class="form-control"
  112. id="tsn_number_description"
  113. name="tsn_number_description"
  114. placeholder="Расшифровка"
  115. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  116. </div>
  117. </div>
  118. <div class="form-text" id="tsn_number_hint"></div>
  119. </div>
  120. <div class="mb-3">
  121. <label class="form-label">Шифр расценки и коды ресурсов</label>
  122. <div id="pricing_codes_container">
  123. @php
  124. $existingCodes = old('pricing_codes', $spare_part ? $spare_part->pricingCodes->pluck('code')->toArray() : []);
  125. @endphp
  126. @forelse($existingCodes as $index => $code)
  127. <div class="pricing-code-row row mb-2" data-index="{{ $index }}">
  128. <div class="col-md-5 position-relative">
  129. <input type="text"
  130. class="form-control pricing-code-input"
  131. name="pricing_codes[]"
  132. value="{{ $code }}"
  133. autocomplete="off"
  134. placeholder="Код"
  135. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  136. <div class="autocomplete-dropdown pricing-code-dropdown"></div>
  137. </div>
  138. <div class="col-md-5">
  139. <input type="text"
  140. class="form-control pricing-code-description-input"
  141. name="pricing_codes_descriptions[]"
  142. placeholder="Расшифровка"
  143. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  144. </div>
  145. <div class="col-md-2">
  146. @if(hasRole('admin,manager'))
  147. <button type="button" class="btn btn-outline-danger btn-remove-pricing-code" title="Удалить">
  148. <i class="bi bi-trash"></i>
  149. </button>
  150. @endif
  151. </div>
  152. <div class="col-12"><div class="form-text pricing-code-hint"></div></div>
  153. </div>
  154. @empty
  155. <div class="pricing-code-row row mb-2" data-index="0">
  156. <div class="col-md-5 position-relative">
  157. <input type="text"
  158. class="form-control pricing-code-input"
  159. name="pricing_codes[]"
  160. value=""
  161. autocomplete="off"
  162. placeholder="Код"
  163. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  164. <div class="autocomplete-dropdown pricing-code-dropdown"></div>
  165. </div>
  166. <div class="col-md-5">
  167. <input type="text"
  168. class="form-control pricing-code-description-input"
  169. name="pricing_codes_descriptions[]"
  170. placeholder="Расшифровка"
  171. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  172. </div>
  173. <div class="col-md-2">
  174. @if(hasRole('admin,manager'))
  175. <button type="button" class="btn btn-outline-danger btn-remove-pricing-code" title="Удалить">
  176. <i class="bi bi-trash"></i>
  177. </button>
  178. @endif
  179. </div>
  180. <div class="col-12"><div class="form-text pricing-code-hint"></div></div>
  181. </div>
  182. @endforelse
  183. </div>
  184. @if(hasRole('admin,manager'))
  185. <button type="button" class="btn btn-sm btn-outline-primary" id="btn_add_pricing_code">
  186. <i class="bi bi-plus-circle"></i> Добавить код
  187. </button>
  188. @endif
  189. </div>
  190. <div class="mb-3">
  191. <label for="min_stock" class="form-label">Минимальный остаток</label>
  192. <input type="number"
  193. class="form-control"
  194. id="min_stock"
  195. name="min_stock"
  196. value="{{ old('min_stock', $spare_part->min_stock ?? 0) }}"
  197. {{ hasRole('admin,manager') ? '' : 'readonly' }}>
  198. </div>
  199. </div>
  200. </div>
  201. <div class="row">
  202. <div class="col-12">
  203. @if(hasRole('admin,manager'))
  204. <button type="submit" class="btn btn-sm btn-success">Сохранить</button>
  205. @endif
  206. <a href="{{ $previous_url ?? route('spare_parts.index') }}" class="btn btn-sm btn-secondary">Назад</a>
  207. @if($spare_part && hasRole('admin'))
  208. <button type="button" class="btn btn-sm btn-danger float-end" data-bs-toggle="modal" data-bs-target="#deleteModal">
  209. Удалить
  210. </button>
  211. @endif
  212. </div>
  213. </div>
  214. </form>
  215. @if($spare_part)
  216. <hr class="my-4">
  217. {{-- Остатки --}}
  218. <div class="row mb-4">
  219. <div class="col-12">
  220. <h4>Остатки</h4>
  221. <div class="table-responsive">
  222. <table class="table table-sm table-bordered">
  223. <thead class="table-light">
  224. <tr>
  225. <th></th>
  226. <th class="text-center">Без документов</th>
  227. <th class="text-center">С документами</th>
  228. <th class="text-center">Всего</th>
  229. </tr>
  230. </thead>
  231. <tbody>
  232. <tr>
  233. <td>Физический остаток</td>
  234. <td class="text-center">{{ $spare_part->physical_stock_without_docs }}</td>
  235. <td class="text-center">{{ $spare_part->physical_stock_with_docs }}</td>
  236. <td class="text-center fw-bold">{{ $spare_part->total_physical_stock }}</td>
  237. </tr>
  238. <tr class="table-warning">
  239. <td>Зарезервировано</td>
  240. <td class="text-center">{{ $spare_part->reserved_without_docs }}</td>
  241. <td class="text-center">{{ $spare_part->reserved_with_docs }}</td>
  242. <td class="text-center fw-bold">{{ $spare_part->total_reserved }}</td>
  243. </tr>
  244. @if($spare_part->min_stock > 0)
  245. <tr class="@if($spare_part->total_free_stock < $spare_part->min_stock) table-danger @endif">
  246. <td>Минимальный остаток</td>
  247. <td colspan="3" class="text-center">{{ $spare_part->min_stock }}</td>
  248. </tr>
  249. @endif
  250. <tr class="table-info">
  251. <td>Заказано</td>
  252. <td class="text-center">{{ $spare_part->ordered_without_docs }}</td>
  253. <td class="text-center">{{ $spare_part->ordered_with_docs }}</td>
  254. <td class="text-center fw-bold">{{ $spare_part->total_ordered }}</td>
  255. </tr>
  256. <tr class="table-success">
  257. <td>Свободный остаток</td>
  258. <td class="text-center">{{ $spare_part->free_stock_without_docs }}</td>
  259. <td class="text-center">{{ $spare_part->free_stock_with_docs }}</td>
  260. <td class="text-center fw-bold">{{ $spare_part->total_free_stock }}</td>
  261. </tr>
  262. </tbody>
  263. </table>
  264. </div>
  265. </div>
  266. </div>
  267. {{-- Активные резервы --}}
  268. @php
  269. $activeReservations = $spare_part->reservations()
  270. ->where('status', \App\Models\Reservation::STATUS_ACTIVE)
  271. ->with('reclamation', 'sparePartOrder')
  272. ->orderByDesc('created_at')
  273. ->get();
  274. @endphp
  275. @if($activeReservations->count() > 0)
  276. <div class="row mb-4">
  277. <div class="col-12">
  278. <h4>Активные резервы <span class="badge bg-warning">{{ $activeReservations->count() }}</span></h4>
  279. <div class="table-responsive">
  280. <table class="table table-sm table-striped">
  281. <thead>
  282. <tr>
  283. <th>Рекламация</th>
  284. <th>Партия</th>
  285. <th class="text-center">Кол-во</th>
  286. <th class="text-center">С док.</th>
  287. <th>Дата</th>
  288. </tr>
  289. </thead>
  290. <tbody>
  291. @foreach($activeReservations as $reservation)
  292. <tr>
  293. <td>
  294. @if($reservation->reclamation)
  295. <a href="{{ route('reclamations.show', $reservation->reclamation->id) }}">
  296. #{{ $reservation->reclamation->id }}
  297. </a>
  298. @else
  299. -
  300. @endif
  301. </td>
  302. <td>
  303. @if($reservation->sparePartOrder)
  304. <a href="{{ route('spare_part_orders.show', $reservation->sparePartOrder->id) }}">
  305. #{{ $reservation->sparePartOrder->id }}
  306. </a>
  307. @else
  308. -
  309. @endif
  310. </td>
  311. <td class="text-center">{{ $reservation->reserved_qty }}</td>
  312. <td class="text-center">
  313. @if($reservation->with_documents)
  314. <i class="bi bi-check-circle text-success"></i>
  315. @else
  316. <i class="bi bi-x-circle text-muted"></i>
  317. @endif
  318. </td>
  319. <td>{{ $reservation->created_at->format('d.m.Y H:i') }}</td>
  320. </tr>
  321. @endforeach
  322. </tbody>
  323. </table>
  324. </div>
  325. </div>
  326. </div>
  327. @endif
  328. {{-- Открытые дефициты --}}
  329. @php
  330. $openShortages = $spare_part->shortages()
  331. ->where('status', \App\Models\Shortage::STATUS_OPEN)
  332. ->with('reclamation')
  333. ->orderByDesc('created_at')
  334. ->get();
  335. @endphp
  336. @if($openShortages->count() > 0)
  337. <div class="row mb-4">
  338. <div class="col-12">
  339. <h4 class="text-danger">Открытые дефициты <span class="badge bg-danger">{{ $openShortages->count() }}</span></h4>
  340. <div class="table-responsive">
  341. <table class="table table-sm table-danger">
  342. <thead>
  343. <tr>
  344. <th>Рекламация</th>
  345. <th class="text-center">Требуется</th>
  346. <th class="text-center">Зарезервировано</th>
  347. <th class="text-center">Не хватает</th>
  348. <th class="text-center">С док.</th>
  349. <th>Дата</th>
  350. </tr>
  351. </thead>
  352. <tbody>
  353. @foreach($openShortages as $shortage)
  354. <tr>
  355. <td>
  356. @if($shortage->reclamation)
  357. <a href="{{ route('reclamations.show', $shortage->reclamation->id) }}">
  358. #{{ $shortage->reclamation->id }}
  359. </a>
  360. @else
  361. -
  362. @endif
  363. </td>
  364. <td class="text-center">{{ $shortage->required_qty }}</td>
  365. <td class="text-center">{{ $shortage->reserved_qty }}</td>
  366. <td class="text-center fw-bold">{{ $shortage->missing_qty }}</td>
  367. <td class="text-center">
  368. @if($shortage->with_documents)
  369. <i class="bi bi-check-circle text-success"></i>
  370. @else
  371. <i class="bi bi-x-circle text-muted"></i>
  372. @endif
  373. </td>
  374. <td>{{ $shortage->created_at->format('d.m.Y H:i') }}</td>
  375. </tr>
  376. @endforeach
  377. </tbody>
  378. </table>
  379. </div>
  380. </div>
  381. </div>
  382. @endif
  383. {{-- Партии (заказы) на складе --}}
  384. @php
  385. $ordersInStock = $spare_part->orders()
  386. ->where('status', \App\Models\SparePartOrder::STATUS_IN_STOCK)
  387. ->where('available_qty', '>', 0)
  388. ->orderByDesc('created_at')
  389. ->get();
  390. @endphp
  391. @if($ordersInStock->count() > 0)
  392. <div class="row mb-4">
  393. <div class="col-12">
  394. <h4>Партии на складе <span class="badge bg-info">{{ $ordersInStock->count() }}</span></h4>
  395. <div class="table-responsive">
  396. <table class="table table-sm table-striped">
  397. <thead>
  398. <tr>
  399. <th>ID</th>
  400. <th>Номер заказа</th>
  401. <th class="text-center">Остаток</th>
  402. <th class="text-center">С док.</th>
  403. <th>Дата поступления</th>
  404. </tr>
  405. </thead>
  406. <tbody>
  407. @foreach($ordersInStock as $order)
  408. <tr>
  409. <td>
  410. <a href="{{ route('spare_part_orders.show', $order->id) }}">#{{ $order->id }}</a>
  411. </td>
  412. <td>{{ $order->display_order_number }}</td>
  413. <td class="text-center">{{ $order->available_qty }}</td>
  414. <td class="text-center">
  415. @if($order->with_documents)
  416. <i class="bi bi-check-circle text-success"></i>
  417. @else
  418. <i class="bi bi-x-circle text-muted"></i>
  419. @endif
  420. </td>
  421. <td>{{ $order->updated_at->format('d.m.Y') }}</td>
  422. </tr>
  423. @endforeach
  424. </tbody>
  425. </table>
  426. </div>
  427. </div>
  428. </div>
  429. @endif
  430. {{-- История движений --}}
  431. @php
  432. $movements = $spare_part->movements()
  433. ->with('user', 'sparePartOrder')
  434. ->orderByDesc('created_at')
  435. ->limit(50)
  436. ->get();
  437. @endphp
  438. <div class="row mb-4">
  439. <div class="col-12">
  440. <h4>История движений <span class="badge bg-secondary">{{ $spare_part->movements()->count() }}</span></h4>
  441. @if($movements->count() > 0)
  442. <div class="table-responsive">
  443. <table class="table table-sm table-striped">
  444. <thead>
  445. <tr>
  446. <th>Дата</th>
  447. <th>Тип</th>
  448. <th>Номер заказа</th>
  449. <th class="text-center">Кол-во</th>
  450. <th class="text-center">С док.</th>
  451. <th>Примечание</th>
  452. <th>Пользователь</th>
  453. </tr>
  454. </thead>
  455. <tbody>
  456. @foreach($movements as $movement)
  457. <tr class="@if($movement->movement_type === 'issue') table-danger @elseif($movement->movement_type === 'reserve') table-warning @elseif($movement->movement_type === 'receipt') table-success @elseif($movement->movement_type === 'reserve_cancel') table-info @endif">
  458. <td>{{ $movement->created_at->format('d.m.Y H:i') }}</td>
  459. <td>{{ $movement->type_name }}</td>
  460. <td>
  461. @if($movement->sparePartOrder)
  462. <a href="{{ route('spare_part_orders.show', $movement->sparePartOrder->id) }}">{{ $movement->sparePartOrder->display_order_number }}</a>
  463. @else
  464. -
  465. @endif
  466. </td>
  467. <td class="text-center">{{ $movement->qty }}</td>
  468. <td class="text-center">
  469. @if($movement->with_documents)
  470. <i class="bi bi-check-circle text-success"></i>
  471. @else
  472. <i class="bi bi-x-circle text-muted"></i>
  473. @endif
  474. </td>
  475. <td>
  476. {{ $movement->note }}
  477. @if($movement->source_type === 'reclamation' && $movement->source_id)
  478. <br><small><a href="{{ route('reclamations.show', $movement->source_id) }}">Рекламация #{{ $movement->source_id }}</a></small>
  479. @endif
  480. </td>
  481. <td>{{ $movement->user->name ?? '-' }}</td>
  482. </tr>
  483. @endforeach
  484. </tbody>
  485. </table>
  486. </div>
  487. @if($spare_part->movements()->count() > 50)
  488. <p class="text-muted">Показаны последние 50 движений из {{ $spare_part->movements()->count() }}</p>
  489. @endif
  490. @else
  491. <p class="text-muted">Движений пока нет</p>
  492. @endif
  493. </div>
  494. </div>
  495. @endif
  496. </div>
  497. </div>
  498. </div>
  499. @if($spare_part && hasRole('admin'))
  500. {{-- Модальное окно удаления --}}
  501. <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteSparePartModalLabel" aria-hidden="true">
  502. <div class="modal-dialog">
  503. <div class="modal-content">
  504. <div class="modal-header">
  505. <h1 class="modal-title fs-5" id="deleteSparePartModalLabel">Подтверждение удаления</h1>
  506. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  507. </div>
  508. <div class="modal-body">
  509. Вы действительно хотите удалить запчасть "{{ $spare_part->article }}"?
  510. </div>
  511. <div class="modal-footer">
  512. <form action="{{ route('spare_parts.destroy', $spare_part) }}" method="POST">
  513. @csrf
  514. @method('DELETE')
  515. <button type="submit" class="btn btn-danger">Удалить</button>
  516. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
  517. </form>
  518. </div>
  519. </div>
  520. </div>
  521. </div>
  522. @endif
  523. @push('scripts')
  524. <script>
  525. function waitForJQuery(callback) {
  526. if (typeof $ !== 'undefined') {
  527. callback();
  528. } else {
  529. setTimeout(function() { waitForJQuery(callback); }, 50);
  530. }
  531. }
  532. waitForJQuery(function() {
  533. $(document).ready(function() {
  534. @if(hasRole('admin'))
  535. //console.log('Autocomplete init started');
  536. // Общая функция для инициализации автокомплита
  537. function initAutocomplete(inputId, dropdownId, descriptionId, hintId, type) {
  538. const $input = $('#' + inputId);
  539. const $dropdown = $('#' + dropdownId);
  540. const $description = $('#' + descriptionId);
  541. const $hint = $('#' + hintId);
  542. let currentFocus = -1;
  543. let searchTimeout;
  544. //console.log('Init autocomplete for:', inputId, $input.length);
  545. // Обработка ввода
  546. $input.on('input', function() {
  547. const query = $(this).val().trim();
  548. clearTimeout(searchTimeout);
  549. //console.log('Input event:', inputId, query);
  550. if (query.length > 0) {
  551. searchTimeout = setTimeout(function() {
  552. // Поиск вариантов для автокомплита
  553. $.get('{{ route('pricing_codes.search') }}', {
  554. type: type,
  555. query: query
  556. }).done(function(data) {
  557. //console.log('Search result:', data);
  558. showDropdown(data, query);
  559. }).fail(function(xhr) {
  560. console.error('Search error:', xhr.status, xhr.responseText);
  561. });
  562. // Проверка точного соответствия для расшифровки
  563. $.get('{{ route('pricing_codes.get_description') }}', {
  564. type: type,
  565. code: query
  566. }).done(function(data) {
  567. // console.log('Description result:', data);
  568. if (data.description) {
  569. $description.val(data.description);
  570. $description.prop('readonly', true);
  571. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  572. } else {
  573. $description.val('');
  574. $description.prop('readonly', false);
  575. $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  576. }
  577. }).fail(function(xhr) {
  578. console.error('Description error:', xhr.status, xhr.responseText);
  579. });
  580. }, 200);
  581. } else {
  582. $dropdown.hide();
  583. $description.val('');
  584. $description.prop('readonly', false);
  585. $hint.text('');
  586. }
  587. });
  588. // Показать выпадающий список
  589. function showDropdown(items, query) {
  590. $dropdown.empty();
  591. currentFocus = -1;
  592. if (items.length === 0) {
  593. $dropdown.hide();
  594. return;
  595. }
  596. items.forEach(function(item, index) {
  597. const $item = $('<div class="autocomplete-item"></div>');
  598. const highlightedCode = highlightMatch(item.code, query);
  599. const highlightedDesc = item.description ? highlightMatch(item.description, query) : '';
  600. $item.html('<div class="code">' + highlightedCode + '</div>' +
  601. (item.description ? '<div class="description">' + highlightedDesc + '</div>' : ''));
  602. $item.data('code', item.code);
  603. $item.data('description', item.description || '');
  604. $item.on('click', function() {
  605. selectItem($(this));
  606. });
  607. $dropdown.append($item);
  608. });
  609. $dropdown.show();
  610. }
  611. // Подсветка совпадения
  612. function highlightMatch(text, query) {
  613. if (!text || !query) return text || '';
  614. const regex = new RegExp('(' + escapeRegex(query) + ')', 'gi');
  615. return text.replace(regex, '<strong>$1</strong>');
  616. }
  617. function escapeRegex(str) {
  618. return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  619. }
  620. // Выбор элемента
  621. function selectItem($item) {
  622. $input.val($item.data('code'));
  623. $description.val($item.data('description'));
  624. $description.prop('readonly', true);
  625. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  626. $dropdown.hide();
  627. }
  628. // Навигация клавиатурой
  629. $input.on('keydown', function(e) {
  630. const $items = $dropdown.find('.autocomplete-item');
  631. if (e.keyCode === 40) { // Стрелка вниз
  632. e.preventDefault();
  633. currentFocus++;
  634. if (currentFocus >= $items.length) currentFocus = 0;
  635. setActive($items);
  636. } else if (e.keyCode === 38) { // Стрелка вверх
  637. e.preventDefault();
  638. currentFocus--;
  639. if (currentFocus < 0) currentFocus = $items.length - 1;
  640. setActive($items);
  641. } else if (e.keyCode === 13) { // Enter
  642. e.preventDefault();
  643. if (currentFocus > -1 && $items.length > 0) {
  644. selectItem($items.eq(currentFocus));
  645. }
  646. } else if (e.keyCode === 27) { // Escape
  647. $dropdown.hide();
  648. }
  649. });
  650. function setActive($items) {
  651. $items.removeClass('active');
  652. if (currentFocus >= 0 && currentFocus < $items.length) {
  653. $items.eq(currentFocus).addClass('active');
  654. }
  655. }
  656. // Закрытие при клике вне
  657. $(document).on('click', function(e) {
  658. if (!$(e.target).closest('#' + inputId + ', #' + dropdownId).length) {
  659. $dropdown.hide();
  660. }
  661. });
  662. // При фокусе показать список если есть значение
  663. $input.on('focus', function() {
  664. const query = $(this).val().trim();
  665. if (query.length > 0) {
  666. $.get('{{ route('pricing_codes.search') }}', {
  667. type: type,
  668. query: query
  669. }, function(data) {
  670. showDropdown(data, query);
  671. });
  672. }
  673. });
  674. }
  675. // Инициализация автокомплитов
  676. initAutocomplete('tsn_number', 'tsn_number_dropdown', 'tsn_number_description', 'tsn_number_hint', 'tsn_number');
  677. // Загрузка расшифровок при открытии страницы
  678. function loadInitialDescription(inputId, descriptionId, hintId, type) {
  679. const code = $('#' + inputId).val().trim();
  680. if (code.length > 0) {
  681. $.get('{{ route('pricing_codes.get_description') }}', {
  682. type: type,
  683. code: code
  684. }).done(function(data) {
  685. if (data.description) {
  686. $('#' + descriptionId).val(data.description);
  687. $('#' + descriptionId).prop('readonly', true);
  688. $('#' + hintId).html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  689. } else {
  690. $('#' + descriptionId).prop('readonly', false);
  691. $('#' + hintId).html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  692. }
  693. }).fail(function(xhr) {
  694. console.error('Initial description error:', xhr.status, xhr.responseText);
  695. });
  696. }
  697. }
  698. loadInitialDescription('tsn_number', 'tsn_number_description', 'tsn_number_hint', 'tsn_number');
  699. // Функционал множественных шифров расценки
  700. function initPricingCodeAutocomplete($row) {
  701. const $input = $row.find('.pricing-code-input');
  702. const $dropdown = $row.find('.pricing-code-dropdown');
  703. const $description = $row.find('.pricing-code-description-input');
  704. const $hint = $row.find('.pricing-code-hint');
  705. let currentFocus = -1;
  706. let searchTimeout;
  707. $input.on('input', function() {
  708. const query = $(this).val().trim();
  709. clearTimeout(searchTimeout);
  710. if (query.length > 0) {
  711. searchTimeout = setTimeout(function() {
  712. $.get('{{ route('pricing_codes.search') }}', {
  713. type: 'pricing_code',
  714. query: query
  715. }).done(function(data) {
  716. showDropdownPricing($dropdown, data, query, $input, $description, $hint);
  717. });
  718. $.get('{{ route('pricing_codes.get_description') }}', {
  719. type: 'pricing_code',
  720. code: query
  721. }).done(function(data) {
  722. if (data.description) {
  723. $description.val(data.description);
  724. $description.prop('readonly', true);
  725. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  726. } else {
  727. $description.val('');
  728. $description.prop('readonly', false);
  729. $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  730. }
  731. });
  732. }, 200);
  733. } else {
  734. $dropdown.hide();
  735. $description.val('');
  736. $description.prop('readonly', false);
  737. $hint.text('');
  738. }
  739. });
  740. $input.on('focus', function() {
  741. const query = $(this).val().trim();
  742. if (query.length > 0) {
  743. $.get('{{ route('pricing_codes.search') }}', {
  744. type: 'pricing_code',
  745. query: query
  746. }, function(data) {
  747. showDropdownPricing($dropdown, data, query, $input, $description, $hint);
  748. });
  749. }
  750. });
  751. $input.on('keydown', function(e) {
  752. const $items = $dropdown.find('.autocomplete-item');
  753. if (e.keyCode === 40) {
  754. e.preventDefault();
  755. currentFocus++;
  756. if (currentFocus >= $items.length) currentFocus = 0;
  757. $items.removeClass('active');
  758. if (currentFocus >= 0) $items.eq(currentFocus).addClass('active');
  759. } else if (e.keyCode === 38) {
  760. e.preventDefault();
  761. currentFocus--;
  762. if (currentFocus < 0) currentFocus = $items.length - 1;
  763. $items.removeClass('active');
  764. if (currentFocus >= 0) $items.eq(currentFocus).addClass('active');
  765. } else if (e.keyCode === 13) {
  766. e.preventDefault();
  767. if (currentFocus > -1 && $items.length > 0) {
  768. $items.eq(currentFocus).trigger('click');
  769. }
  770. } else if (e.keyCode === 27) {
  771. $dropdown.hide();
  772. }
  773. });
  774. $(document).on('click', function(e) {
  775. if (!$(e.target).closest($row).length) {
  776. $dropdown.hide();
  777. }
  778. });
  779. }
  780. function showDropdownPricing($dropdown, items, query, $input, $description, $hint) {
  781. $dropdown.empty();
  782. if (items.length === 0) {
  783. $dropdown.hide();
  784. return;
  785. }
  786. items.forEach(function(item) {
  787. const $item = $('<div class="autocomplete-item"></div>');
  788. const highlightedCode = highlightMatchPricing(item.code, query);
  789. const highlightedDesc = item.description ? highlightMatchPricing(item.description, query) : '';
  790. $item.html('<div class="code">' + highlightedCode + '</div>' +
  791. (item.description ? '<div class="description">' + highlightedDesc + '</div>' : ''));
  792. $item.data('code', item.code);
  793. $item.data('description', item.description || '');
  794. $item.on('click', function() {
  795. $input.val($(this).data('code'));
  796. $description.val($(this).data('description'));
  797. $description.prop('readonly', true);
  798. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  799. $dropdown.hide();
  800. });
  801. $dropdown.append($item);
  802. });
  803. $dropdown.show();
  804. }
  805. function highlightMatchPricing(text, query) {
  806. if (!text || !query) return text || '';
  807. const regex = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
  808. return text.replace(regex, '<strong>$1</strong>');
  809. }
  810. function loadInitialPricingCodeDescription($row) {
  811. const code = $row.find('.pricing-code-input').val().trim();
  812. const $description = $row.find('.pricing-code-description-input');
  813. const $hint = $row.find('.pricing-code-hint');
  814. if (code.length > 0) {
  815. $.get('{{ route('pricing_codes.get_description') }}', {
  816. type: 'pricing_code',
  817. code: code
  818. }).done(function(data) {
  819. if (data.description) {
  820. $description.val(data.description);
  821. $description.prop('readonly', true);
  822. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  823. } else {
  824. $description.prop('readonly', false);
  825. $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  826. }
  827. });
  828. }
  829. }
  830. // Инициализация существующих строк
  831. $('.pricing-code-row').each(function() {
  832. initPricingCodeAutocomplete($(this));
  833. loadInitialPricingCodeDescription($(this));
  834. });
  835. // Добавление новой строки
  836. $('#btn_add_pricing_code').on('click', function() {
  837. const $container = $('#pricing_codes_container');
  838. const newIndex = $container.find('.pricing-code-row').length;
  839. const $newRow = $(`
  840. <div class="pricing-code-row row mb-2" data-index="${newIndex}">
  841. <div class="col-md-5 position-relative">
  842. <input type="text"
  843. class="form-control pricing-code-input"
  844. name="pricing_codes[]"
  845. value=""
  846. autocomplete="off"
  847. placeholder="Код">
  848. <div class="autocomplete-dropdown pricing-code-dropdown"></div>
  849. </div>
  850. <div class="col-md-5">
  851. <input type="text"
  852. class="form-control pricing-code-description-input"
  853. name="pricing_codes_descriptions[]"
  854. placeholder="Расшифровка">
  855. </div>
  856. <div class="col-md-2">
  857. <button type="button" class="btn btn-outline-danger btn-remove-pricing-code" title="Удалить">
  858. <i class="bi bi-trash"></i>
  859. </button>
  860. </div>
  861. <div class="col-12"><div class="form-text pricing-code-hint"></div></div>
  862. </div>
  863. `);
  864. $container.append($newRow);
  865. initPricingCodeAutocomplete($newRow);
  866. $newRow.find('.pricing-code-input').focus();
  867. });
  868. // Удаление строки
  869. $(document).on('click', '.btn-remove-pricing-code', function() {
  870. const $container = $('#pricing_codes_container');
  871. if ($container.find('.pricing-code-row').length > 1) {
  872. $(this).closest('.pricing-code-row').remove();
  873. } else {
  874. // Если осталась одна строка, просто очищаем её
  875. const $row = $(this).closest('.pricing-code-row');
  876. $row.find('.pricing-code-input').val('');
  877. $row.find('.pricing-code-description-input').val('').prop('readonly', false);
  878. $row.find('.pricing-code-hint').text('');
  879. }
  880. });
  881. @endif
  882. });
  883. });
  884. </script>
  885. @endpush
  886. @endsection