edit.blade.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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-6">
  8. <h2>{{ $spare_part ? 'Редактирование запчасти' : 'Создание запчасти' }}</h2>
  9. </div>
  10. <div class="col-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') ? '' : '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') ? '' : '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') ? '' : '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') ? '' : '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') ? '' : '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') ? '' : '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') ? '' : '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') ? '' : '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') ? '' : 'readonly' }}>
  144. </div>
  145. <div class="col-md-2">
  146. @if(hasRole('admin'))
  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') ? '' : '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') ? '' : 'readonly' }}>
  172. </div>
  173. <div class="col-md-2">
  174. @if(hasRole('admin'))
  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'))
  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') ? '' : 'readonly' }}>
  198. </div>
  199. </div>
  200. </div>
  201. <div class="row">
  202. <div class="col-12">
  203. @if(hasRole('admin'))
  204. <button type="submit" class="btn btn-success">Сохранить</button>
  205. @endif
  206. <a href="{{ $previous_url ?? route('spare_parts.index') }}" class="btn btn-secondary">Назад</a>
  207. @if($spare_part && hasRole('admin'))
  208. <button type="button" class="btn 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. <tr class="table-success">
  245. <td>Свободный остаток</td>
  246. <td class="text-center">{{ $spare_part->free_stock_without_docs }}</td>
  247. <td class="text-center">{{ $spare_part->free_stock_with_docs }}</td>
  248. <td class="text-center fw-bold">{{ $spare_part->total_free_stock }}</td>
  249. </tr>
  250. @if($spare_part->min_stock > 0)
  251. <tr class="@if($spare_part->total_free_stock < $spare_part->min_stock) table-danger @endif">
  252. <td>Минимальный остаток</td>
  253. <td colspan="3" class="text-center">{{ $spare_part->min_stock }}</td>
  254. </tr>
  255. @endif
  256. </tbody>
  257. </table>
  258. </div>
  259. </div>
  260. </div>
  261. {{-- Активные резервы --}}
  262. @php
  263. $activeReservations = $spare_part->reservations()
  264. ->where('status', \App\Models\Reservation::STATUS_ACTIVE)
  265. ->with('reclamation', 'sparePartOrder')
  266. ->orderByDesc('created_at')
  267. ->get();
  268. @endphp
  269. @if($activeReservations->count() > 0)
  270. <div class="row mb-4">
  271. <div class="col-12">
  272. <h4>Активные резервы <span class="badge bg-warning">{{ $activeReservations->count() }}</span></h4>
  273. <div class="table-responsive">
  274. <table class="table table-sm table-striped">
  275. <thead>
  276. <tr>
  277. <th>Рекламация</th>
  278. <th>Партия</th>
  279. <th class="text-center">Кол-во</th>
  280. <th class="text-center">С док.</th>
  281. <th>Дата</th>
  282. </tr>
  283. </thead>
  284. <tbody>
  285. @foreach($activeReservations as $reservation)
  286. <tr>
  287. <td>
  288. @if($reservation->reclamation)
  289. <a href="{{ route('reclamations.show', $reservation->reclamation->id) }}">
  290. #{{ $reservation->reclamation->id }}
  291. </a>
  292. @else
  293. -
  294. @endif
  295. </td>
  296. <td>
  297. @if($reservation->sparePartOrder)
  298. <a href="{{ route('spare_part_orders.show', $reservation->sparePartOrder->id) }}">
  299. #{{ $reservation->sparePartOrder->id }}
  300. </a>
  301. @else
  302. -
  303. @endif
  304. </td>
  305. <td class="text-center">{{ $reservation->reserved_qty }}</td>
  306. <td class="text-center">
  307. @if($reservation->with_documents)
  308. <i class="bi bi-check-circle text-success"></i>
  309. @else
  310. <i class="bi bi-x-circle text-muted"></i>
  311. @endif
  312. </td>
  313. <td>{{ $reservation->created_at->format('d.m.Y H:i') }}</td>
  314. </tr>
  315. @endforeach
  316. </tbody>
  317. </table>
  318. </div>
  319. </div>
  320. </div>
  321. @endif
  322. {{-- Открытые дефициты --}}
  323. @php
  324. $openShortages = $spare_part->shortages()
  325. ->where('status', \App\Models\Shortage::STATUS_OPEN)
  326. ->with('reclamation')
  327. ->orderByDesc('created_at')
  328. ->get();
  329. @endphp
  330. @if($openShortages->count() > 0)
  331. <div class="row mb-4">
  332. <div class="col-12">
  333. <h4 class="text-danger">Открытые дефициты <span class="badge bg-danger">{{ $openShortages->count() }}</span></h4>
  334. <div class="table-responsive">
  335. <table class="table table-sm table-danger">
  336. <thead>
  337. <tr>
  338. <th>Рекламация</th>
  339. <th class="text-center">Требуется</th>
  340. <th class="text-center">Зарезервировано</th>
  341. <th class="text-center">Не хватает</th>
  342. <th class="text-center">С док.</th>
  343. <th>Дата</th>
  344. </tr>
  345. </thead>
  346. <tbody>
  347. @foreach($openShortages as $shortage)
  348. <tr>
  349. <td>
  350. @if($shortage->reclamation)
  351. <a href="{{ route('reclamations.show', $shortage->reclamation->id) }}">
  352. #{{ $shortage->reclamation->id }}
  353. </a>
  354. @else
  355. -
  356. @endif
  357. </td>
  358. <td class="text-center">{{ $shortage->required_qty }}</td>
  359. <td class="text-center">{{ $shortage->reserved_qty }}</td>
  360. <td class="text-center fw-bold">{{ $shortage->missing_qty }}</td>
  361. <td class="text-center">
  362. @if($shortage->with_documents)
  363. <i class="bi bi-check-circle text-success"></i>
  364. @else
  365. <i class="bi bi-x-circle text-muted"></i>
  366. @endif
  367. </td>
  368. <td>{{ $shortage->created_at->format('d.m.Y H:i') }}</td>
  369. </tr>
  370. @endforeach
  371. </tbody>
  372. </table>
  373. </div>
  374. </div>
  375. </div>
  376. @endif
  377. {{-- Партии (заказы) на складе --}}
  378. @php
  379. $ordersInStock = $spare_part->orders()
  380. ->where('status', \App\Models\SparePartOrder::STATUS_IN_STOCK)
  381. ->where('available_qty', '>', 0)
  382. ->orderByDesc('created_at')
  383. ->get();
  384. @endphp
  385. @if($ordersInStock->count() > 0)
  386. <div class="row mb-4">
  387. <div class="col-12">
  388. <h4>Партии на складе <span class="badge bg-info">{{ $ordersInStock->count() }}</span></h4>
  389. <div class="table-responsive">
  390. <table class="table table-sm table-striped">
  391. <thead>
  392. <tr>
  393. <th>ID</th>
  394. <th>Источник</th>
  395. <th class="text-center">Остаток</th>
  396. <th class="text-center">С док.</th>
  397. <th>Дата поступления</th>
  398. </tr>
  399. </thead>
  400. <tbody>
  401. @foreach($ordersInStock as $order)
  402. <tr>
  403. <td>
  404. <a href="{{ route('spare_part_orders.show', $order->id) }}">#{{ $order->id }}</a>
  405. </td>
  406. <td>{{ $order->source_text ?: '-' }}</td>
  407. <td class="text-center">{{ $order->available_qty }}</td>
  408. <td class="text-center">
  409. @if($order->with_documents)
  410. <i class="bi bi-check-circle text-success"></i>
  411. @else
  412. <i class="bi bi-x-circle text-muted"></i>
  413. @endif
  414. </td>
  415. <td>{{ $order->updated_at->format('d.m.Y') }}</td>
  416. </tr>
  417. @endforeach
  418. </tbody>
  419. </table>
  420. </div>
  421. </div>
  422. </div>
  423. @endif
  424. {{-- История движений --}}
  425. @php
  426. $movements = $spare_part->movements()
  427. ->with('user', 'sparePartOrder')
  428. ->orderByDesc('created_at')
  429. ->limit(50)
  430. ->get();
  431. @endphp
  432. <div class="row mb-4">
  433. <div class="col-12">
  434. <h4>История движений <span class="badge bg-secondary">{{ $spare_part->movements()->count() }}</span></h4>
  435. @if($movements->count() > 0)
  436. <div class="table-responsive">
  437. <table class="table table-sm table-striped">
  438. <thead>
  439. <tr>
  440. <th>Дата</th>
  441. <th>Тип</th>
  442. <th>Партия</th>
  443. <th class="text-center">Кол-во</th>
  444. <th class="text-center">С док.</th>
  445. <th>Примечание</th>
  446. <th>Пользователь</th>
  447. </tr>
  448. </thead>
  449. <tbody>
  450. @foreach($movements as $movement)
  451. <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">
  452. <td>{{ $movement->created_at->format('d.m.Y H:i') }}</td>
  453. <td>{{ $movement->type_name }}</td>
  454. <td>
  455. @if($movement->sparePartOrder)
  456. <a href="{{ route('spare_part_orders.show', $movement->sparePartOrder->id) }}">#{{ $movement->sparePartOrder->id }}</a>
  457. @else
  458. -
  459. @endif
  460. </td>
  461. <td class="text-center">{{ $movement->qty }}</td>
  462. <td class="text-center">
  463. @if($movement->with_documents)
  464. <i class="bi bi-check-circle text-success"></i>
  465. @else
  466. <i class="bi bi-x-circle text-muted"></i>
  467. @endif
  468. </td>
  469. <td>
  470. {{ $movement->note }}
  471. @if($movement->source_type === 'reclamation' && $movement->source_id)
  472. <br><small><a href="{{ route('reclamations.show', $movement->source_id) }}">Рекламация #{{ $movement->source_id }}</a></small>
  473. @endif
  474. </td>
  475. <td>{{ $movement->user->name ?? '-' }}</td>
  476. </tr>
  477. @endforeach
  478. </tbody>
  479. </table>
  480. </div>
  481. @if($spare_part->movements()->count() > 50)
  482. <p class="text-muted">Показаны последние 50 движений из {{ $spare_part->movements()->count() }}</p>
  483. @endif
  484. @else
  485. <p class="text-muted">Движений пока нет</p>
  486. @endif
  487. </div>
  488. </div>
  489. @endif
  490. </div>
  491. </div>
  492. </div>
  493. @if($spare_part && hasRole('admin'))
  494. {{-- Модальное окно удаления --}}
  495. <div class="modal fade" id="deleteModal" tabindex="-1">
  496. <div class="modal-dialog">
  497. <div class="modal-content">
  498. <div class="modal-header">
  499. <h5 class="modal-title">Подтверждение удаления</h5>
  500. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  501. </div>
  502. <div class="modal-body">
  503. Вы действительно хотите удалить запчасть "{{ $spare_part->article }}"?
  504. </div>
  505. <div class="modal-footer">
  506. <form action="{{ route('spare_parts.destroy', $spare_part) }}" method="POST">
  507. @csrf
  508. @method('DELETE')
  509. <button type="submit" class="btn btn-danger">Удалить</button>
  510. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
  511. </form>
  512. </div>
  513. </div>
  514. </div>
  515. </div>
  516. @endif
  517. @push('scripts')
  518. <script>
  519. function waitForJQuery(callback) {
  520. if (typeof $ !== 'undefined') {
  521. callback();
  522. } else {
  523. setTimeout(function() { waitForJQuery(callback); }, 50);
  524. }
  525. }
  526. waitForJQuery(function() {
  527. $(document).ready(function() {
  528. @if(hasRole('admin'))
  529. //console.log('Autocomplete init started');
  530. // Общая функция для инициализации автокомплита
  531. function initAutocomplete(inputId, dropdownId, descriptionId, hintId, type) {
  532. const $input = $('#' + inputId);
  533. const $dropdown = $('#' + dropdownId);
  534. const $description = $('#' + descriptionId);
  535. const $hint = $('#' + hintId);
  536. let currentFocus = -1;
  537. let searchTimeout;
  538. //console.log('Init autocomplete for:', inputId, $input.length);
  539. // Обработка ввода
  540. $input.on('input', function() {
  541. const query = $(this).val().trim();
  542. clearTimeout(searchTimeout);
  543. //console.log('Input event:', inputId, query);
  544. if (query.length > 0) {
  545. searchTimeout = setTimeout(function() {
  546. // Поиск вариантов для автокомплита
  547. $.get('{{ route('pricing_codes.search') }}', {
  548. type: type,
  549. query: query
  550. }).done(function(data) {
  551. //console.log('Search result:', data);
  552. showDropdown(data, query);
  553. }).fail(function(xhr) {
  554. console.error('Search error:', xhr.status, xhr.responseText);
  555. });
  556. // Проверка точного соответствия для расшифровки
  557. $.get('{{ route('pricing_codes.get_description') }}', {
  558. type: type,
  559. code: query
  560. }).done(function(data) {
  561. // console.log('Description result:', data);
  562. if (data.description) {
  563. $description.val(data.description);
  564. $description.prop('readonly', true);
  565. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  566. } else {
  567. $description.val('');
  568. $description.prop('readonly', false);
  569. $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  570. }
  571. }).fail(function(xhr) {
  572. console.error('Description error:', xhr.status, xhr.responseText);
  573. });
  574. }, 200);
  575. } else {
  576. $dropdown.hide();
  577. $description.val('');
  578. $description.prop('readonly', false);
  579. $hint.text('');
  580. }
  581. });
  582. // Показать выпадающий список
  583. function showDropdown(items, query) {
  584. $dropdown.empty();
  585. currentFocus = -1;
  586. if (items.length === 0) {
  587. $dropdown.hide();
  588. return;
  589. }
  590. items.forEach(function(item, index) {
  591. const $item = $('<div class="autocomplete-item"></div>');
  592. const highlightedCode = highlightMatch(item.code, query);
  593. const highlightedDesc = item.description ? highlightMatch(item.description, query) : '';
  594. $item.html('<div class="code">' + highlightedCode + '</div>' +
  595. (item.description ? '<div class="description">' + highlightedDesc + '</div>' : ''));
  596. $item.data('code', item.code);
  597. $item.data('description', item.description || '');
  598. $item.on('click', function() {
  599. selectItem($(this));
  600. });
  601. $dropdown.append($item);
  602. });
  603. $dropdown.show();
  604. }
  605. // Подсветка совпадения
  606. function highlightMatch(text, query) {
  607. if (!text || !query) return text || '';
  608. const regex = new RegExp('(' + escapeRegex(query) + ')', 'gi');
  609. return text.replace(regex, '<strong>$1</strong>');
  610. }
  611. function escapeRegex(str) {
  612. return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  613. }
  614. // Выбор элемента
  615. function selectItem($item) {
  616. $input.val($item.data('code'));
  617. $description.val($item.data('description'));
  618. $description.prop('readonly', true);
  619. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  620. $dropdown.hide();
  621. }
  622. // Навигация клавиатурой
  623. $input.on('keydown', function(e) {
  624. const $items = $dropdown.find('.autocomplete-item');
  625. if (e.keyCode === 40) { // Стрелка вниз
  626. e.preventDefault();
  627. currentFocus++;
  628. if (currentFocus >= $items.length) currentFocus = 0;
  629. setActive($items);
  630. } else if (e.keyCode === 38) { // Стрелка вверх
  631. e.preventDefault();
  632. currentFocus--;
  633. if (currentFocus < 0) currentFocus = $items.length - 1;
  634. setActive($items);
  635. } else if (e.keyCode === 13) { // Enter
  636. e.preventDefault();
  637. if (currentFocus > -1 && $items.length > 0) {
  638. selectItem($items.eq(currentFocus));
  639. }
  640. } else if (e.keyCode === 27) { // Escape
  641. $dropdown.hide();
  642. }
  643. });
  644. function setActive($items) {
  645. $items.removeClass('active');
  646. if (currentFocus >= 0 && currentFocus < $items.length) {
  647. $items.eq(currentFocus).addClass('active');
  648. }
  649. }
  650. // Закрытие при клике вне
  651. $(document).on('click', function(e) {
  652. if (!$(e.target).closest('#' + inputId + ', #' + dropdownId).length) {
  653. $dropdown.hide();
  654. }
  655. });
  656. // При фокусе показать список если есть значение
  657. $input.on('focus', function() {
  658. const query = $(this).val().trim();
  659. if (query.length > 0) {
  660. $.get('{{ route('pricing_codes.search') }}', {
  661. type: type,
  662. query: query
  663. }, function(data) {
  664. showDropdown(data, query);
  665. });
  666. }
  667. });
  668. }
  669. // Инициализация автокомплитов
  670. initAutocomplete('tsn_number', 'tsn_number_dropdown', 'tsn_number_description', 'tsn_number_hint', 'tsn_number');
  671. // Загрузка расшифровок при открытии страницы
  672. function loadInitialDescription(inputId, descriptionId, hintId, type) {
  673. const code = $('#' + inputId).val().trim();
  674. if (code.length > 0) {
  675. $.get('{{ route('pricing_codes.get_description') }}', {
  676. type: type,
  677. code: code
  678. }).done(function(data) {
  679. if (data.description) {
  680. $('#' + descriptionId).val(data.description);
  681. $('#' + descriptionId).prop('readonly', true);
  682. $('#' + hintId).html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  683. } else {
  684. $('#' + descriptionId).prop('readonly', false);
  685. $('#' + hintId).html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  686. }
  687. }).fail(function(xhr) {
  688. console.error('Initial description error:', xhr.status, xhr.responseText);
  689. });
  690. }
  691. }
  692. loadInitialDescription('tsn_number', 'tsn_number_description', 'tsn_number_hint', 'tsn_number');
  693. // Функционал множественных шифров расценки
  694. function initPricingCodeAutocomplete($row) {
  695. const $input = $row.find('.pricing-code-input');
  696. const $dropdown = $row.find('.pricing-code-dropdown');
  697. const $description = $row.find('.pricing-code-description-input');
  698. const $hint = $row.find('.pricing-code-hint');
  699. let currentFocus = -1;
  700. let searchTimeout;
  701. $input.on('input', function() {
  702. const query = $(this).val().trim();
  703. clearTimeout(searchTimeout);
  704. if (query.length > 0) {
  705. searchTimeout = setTimeout(function() {
  706. $.get('{{ route('pricing_codes.search') }}', {
  707. type: 'pricing_code',
  708. query: query
  709. }).done(function(data) {
  710. showDropdownPricing($dropdown, data, query, $input, $description, $hint);
  711. });
  712. $.get('{{ route('pricing_codes.get_description') }}', {
  713. type: 'pricing_code',
  714. code: query
  715. }).done(function(data) {
  716. if (data.description) {
  717. $description.val(data.description);
  718. $description.prop('readonly', true);
  719. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  720. } else {
  721. $description.val('');
  722. $description.prop('readonly', false);
  723. $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  724. }
  725. });
  726. }, 200);
  727. } else {
  728. $dropdown.hide();
  729. $description.val('');
  730. $description.prop('readonly', false);
  731. $hint.text('');
  732. }
  733. });
  734. $input.on('focus', function() {
  735. const query = $(this).val().trim();
  736. if (query.length > 0) {
  737. $.get('{{ route('pricing_codes.search') }}', {
  738. type: 'pricing_code',
  739. query: query
  740. }, function(data) {
  741. showDropdownPricing($dropdown, data, query, $input, $description, $hint);
  742. });
  743. }
  744. });
  745. $input.on('keydown', function(e) {
  746. const $items = $dropdown.find('.autocomplete-item');
  747. if (e.keyCode === 40) {
  748. e.preventDefault();
  749. currentFocus++;
  750. if (currentFocus >= $items.length) currentFocus = 0;
  751. $items.removeClass('active');
  752. if (currentFocus >= 0) $items.eq(currentFocus).addClass('active');
  753. } else if (e.keyCode === 38) {
  754. e.preventDefault();
  755. currentFocus--;
  756. if (currentFocus < 0) currentFocus = $items.length - 1;
  757. $items.removeClass('active');
  758. if (currentFocus >= 0) $items.eq(currentFocus).addClass('active');
  759. } else if (e.keyCode === 13) {
  760. e.preventDefault();
  761. if (currentFocus > -1 && $items.length > 0) {
  762. $items.eq(currentFocus).trigger('click');
  763. }
  764. } else if (e.keyCode === 27) {
  765. $dropdown.hide();
  766. }
  767. });
  768. $(document).on('click', function(e) {
  769. if (!$(e.target).closest($row).length) {
  770. $dropdown.hide();
  771. }
  772. });
  773. }
  774. function showDropdownPricing($dropdown, items, query, $input, $description, $hint) {
  775. $dropdown.empty();
  776. if (items.length === 0) {
  777. $dropdown.hide();
  778. return;
  779. }
  780. items.forEach(function(item) {
  781. const $item = $('<div class="autocomplete-item"></div>');
  782. const highlightedCode = highlightMatchPricing(item.code, query);
  783. const highlightedDesc = item.description ? highlightMatchPricing(item.description, query) : '';
  784. $item.html('<div class="code">' + highlightedCode + '</div>' +
  785. (item.description ? '<div class="description">' + highlightedDesc + '</div>' : ''));
  786. $item.data('code', item.code);
  787. $item.data('description', item.description || '');
  788. $item.on('click', function() {
  789. $input.val($(this).data('code'));
  790. $description.val($(this).data('description'));
  791. $description.prop('readonly', true);
  792. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  793. $dropdown.hide();
  794. });
  795. $dropdown.append($item);
  796. });
  797. $dropdown.show();
  798. }
  799. function highlightMatchPricing(text, query) {
  800. if (!text || !query) return text || '';
  801. const regex = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
  802. return text.replace(regex, '<strong>$1</strong>');
  803. }
  804. function loadInitialPricingCodeDescription($row) {
  805. const code = $row.find('.pricing-code-input').val().trim();
  806. const $description = $row.find('.pricing-code-description-input');
  807. const $hint = $row.find('.pricing-code-hint');
  808. if (code.length > 0) {
  809. $.get('{{ route('pricing_codes.get_description') }}', {
  810. type: 'pricing_code',
  811. code: code
  812. }).done(function(data) {
  813. if (data.description) {
  814. $description.val(data.description);
  815. $description.prop('readonly', true);
  816. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  817. } else {
  818. $description.prop('readonly', false);
  819. $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  820. }
  821. });
  822. }
  823. }
  824. // Инициализация существующих строк
  825. $('.pricing-code-row').each(function() {
  826. initPricingCodeAutocomplete($(this));
  827. loadInitialPricingCodeDescription($(this));
  828. });
  829. // Добавление новой строки
  830. $('#btn_add_pricing_code').on('click', function() {
  831. const $container = $('#pricing_codes_container');
  832. const newIndex = $container.find('.pricing-code-row').length;
  833. const $newRow = $(`
  834. <div class="pricing-code-row row mb-2" data-index="${newIndex}">
  835. <div class="col-md-5 position-relative">
  836. <input type="text"
  837. class="form-control pricing-code-input"
  838. name="pricing_codes[]"
  839. value=""
  840. autocomplete="off"
  841. placeholder="Код">
  842. <div class="autocomplete-dropdown pricing-code-dropdown"></div>
  843. </div>
  844. <div class="col-md-5">
  845. <input type="text"
  846. class="form-control pricing-code-description-input"
  847. name="pricing_codes_descriptions[]"
  848. placeholder="Расшифровка">
  849. </div>
  850. <div class="col-md-2">
  851. <button type="button" class="btn btn-outline-danger btn-remove-pricing-code" title="Удалить">
  852. <i class="bi bi-trash"></i>
  853. </button>
  854. </div>
  855. <div class="col-12"><div class="form-text pricing-code-hint"></div></div>
  856. </div>
  857. `);
  858. $container.append($newRow);
  859. initPricingCodeAutocomplete($newRow);
  860. $newRow.find('.pricing-code-input').focus();
  861. });
  862. // Удаление строки
  863. $(document).on('click', '.btn-remove-pricing-code', function() {
  864. const $container = $('#pricing_codes_container');
  865. if ($container.find('.pricing-code-row').length > 1) {
  866. $(this).closest('.pricing-code-row').remove();
  867. } else {
  868. // Если осталась одна строка, просто очищаем её
  869. const $row = $(this).closest('.pricing-code-row');
  870. $row.find('.pricing-code-input').val('');
  871. $row.find('.pricing-code-description-input').val('').prop('readonly', false);
  872. $row.find('.pricing-code-hint').text('');
  873. }
  874. });
  875. @endif
  876. });
  877. });
  878. </script>
  879. @endpush
  880. @endsection