edit.blade.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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" style="max-width: 200px;">
  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. <style>
  519. .autocomplete-dropdown {
  520. position: absolute;
  521. top: 100%;
  522. left: 0;
  523. right: 0;
  524. z-index: 1050;
  525. background: white;
  526. border: 1px solid #dee2e6;
  527. border-top: none;
  528. border-radius: 0 0 .375rem .375rem;
  529. max-height: 250px;
  530. overflow-y: auto;
  531. display: none;
  532. box-shadow: 0 4px 6px rgba(0,0,0,.1);
  533. }
  534. .autocomplete-dropdown .autocomplete-item {
  535. padding: 8px 12px;
  536. cursor: pointer;
  537. border-bottom: 1px solid #f0f0f0;
  538. }
  539. .autocomplete-dropdown .autocomplete-item:last-child {
  540. border-bottom: none;
  541. }
  542. .autocomplete-dropdown .autocomplete-item:hover,
  543. .autocomplete-dropdown .autocomplete-item.active {
  544. background-color: #e9ecef;
  545. }
  546. .autocomplete-dropdown .autocomplete-item .code {
  547. font-weight: 600;
  548. color: #495057;
  549. }
  550. .autocomplete-dropdown .autocomplete-item .description {
  551. font-size: 0.875em;
  552. color: #6c757d;
  553. }
  554. </style>
  555. <script>
  556. function waitForJQuery(callback) {
  557. if (typeof $ !== 'undefined') {
  558. callback();
  559. } else {
  560. setTimeout(function() { waitForJQuery(callback); }, 50);
  561. }
  562. }
  563. waitForJQuery(function() {
  564. $(document).ready(function() {
  565. @if(hasRole('admin'))
  566. //console.log('Autocomplete init started');
  567. // Общая функция для инициализации автокомплита
  568. function initAutocomplete(inputId, dropdownId, descriptionId, hintId, type) {
  569. const $input = $('#' + inputId);
  570. const $dropdown = $('#' + dropdownId);
  571. const $description = $('#' + descriptionId);
  572. const $hint = $('#' + hintId);
  573. let currentFocus = -1;
  574. let searchTimeout;
  575. //console.log('Init autocomplete for:', inputId, $input.length);
  576. // Обработка ввода
  577. $input.on('input', function() {
  578. const query = $(this).val().trim();
  579. clearTimeout(searchTimeout);
  580. //console.log('Input event:', inputId, query);
  581. if (query.length > 0) {
  582. searchTimeout = setTimeout(function() {
  583. // Поиск вариантов для автокомплита
  584. $.get('{{ route('pricing_codes.search') }}', {
  585. type: type,
  586. query: query
  587. }).done(function(data) {
  588. //console.log('Search result:', data);
  589. showDropdown(data, query);
  590. }).fail(function(xhr) {
  591. console.error('Search error:', xhr.status, xhr.responseText);
  592. });
  593. // Проверка точного соответствия для расшифровки
  594. $.get('{{ route('pricing_codes.get_description') }}', {
  595. type: type,
  596. code: query
  597. }).done(function(data) {
  598. // console.log('Description result:', data);
  599. if (data.description) {
  600. $description.val(data.description);
  601. $description.prop('readonly', true);
  602. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  603. } else {
  604. $description.val('');
  605. $description.prop('readonly', false);
  606. $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  607. }
  608. }).fail(function(xhr) {
  609. console.error('Description error:', xhr.status, xhr.responseText);
  610. });
  611. }, 200);
  612. } else {
  613. $dropdown.hide();
  614. $description.val('');
  615. $description.prop('readonly', false);
  616. $hint.text('');
  617. }
  618. });
  619. // Показать выпадающий список
  620. function showDropdown(items, query) {
  621. $dropdown.empty();
  622. currentFocus = -1;
  623. if (items.length === 0) {
  624. $dropdown.hide();
  625. return;
  626. }
  627. items.forEach(function(item, index) {
  628. const $item = $('<div class="autocomplete-item"></div>');
  629. const highlightedCode = highlightMatch(item.code, query);
  630. const highlightedDesc = item.description ? highlightMatch(item.description, query) : '';
  631. $item.html('<div class="code">' + highlightedCode + '</div>' +
  632. (item.description ? '<div class="description">' + highlightedDesc + '</div>' : ''));
  633. $item.data('code', item.code);
  634. $item.data('description', item.description || '');
  635. $item.on('click', function() {
  636. selectItem($(this));
  637. });
  638. $dropdown.append($item);
  639. });
  640. $dropdown.show();
  641. }
  642. // Подсветка совпадения
  643. function highlightMatch(text, query) {
  644. if (!text || !query) return text || '';
  645. const regex = new RegExp('(' + escapeRegex(query) + ')', 'gi');
  646. return text.replace(regex, '<strong>$1</strong>');
  647. }
  648. function escapeRegex(str) {
  649. return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  650. }
  651. // Выбор элемента
  652. function selectItem($item) {
  653. $input.val($item.data('code'));
  654. $description.val($item.data('description'));
  655. $description.prop('readonly', true);
  656. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  657. $dropdown.hide();
  658. }
  659. // Навигация клавиатурой
  660. $input.on('keydown', function(e) {
  661. const $items = $dropdown.find('.autocomplete-item');
  662. if (e.keyCode === 40) { // Стрелка вниз
  663. e.preventDefault();
  664. currentFocus++;
  665. if (currentFocus >= $items.length) currentFocus = 0;
  666. setActive($items);
  667. } else if (e.keyCode === 38) { // Стрелка вверх
  668. e.preventDefault();
  669. currentFocus--;
  670. if (currentFocus < 0) currentFocus = $items.length - 1;
  671. setActive($items);
  672. } else if (e.keyCode === 13) { // Enter
  673. e.preventDefault();
  674. if (currentFocus > -1 && $items.length > 0) {
  675. selectItem($items.eq(currentFocus));
  676. }
  677. } else if (e.keyCode === 27) { // Escape
  678. $dropdown.hide();
  679. }
  680. });
  681. function setActive($items) {
  682. $items.removeClass('active');
  683. if (currentFocus >= 0 && currentFocus < $items.length) {
  684. $items.eq(currentFocus).addClass('active');
  685. }
  686. }
  687. // Закрытие при клике вне
  688. $(document).on('click', function(e) {
  689. if (!$(e.target).closest('#' + inputId + ', #' + dropdownId).length) {
  690. $dropdown.hide();
  691. }
  692. });
  693. // При фокусе показать список если есть значение
  694. $input.on('focus', function() {
  695. const query = $(this).val().trim();
  696. if (query.length > 0) {
  697. $.get('{{ route('pricing_codes.search') }}', {
  698. type: type,
  699. query: query
  700. }, function(data) {
  701. showDropdown(data, query);
  702. });
  703. }
  704. });
  705. }
  706. // Инициализация автокомплитов
  707. initAutocomplete('tsn_number', 'tsn_number_dropdown', 'tsn_number_description', 'tsn_number_hint', 'tsn_number');
  708. // Загрузка расшифровок при открытии страницы
  709. function loadInitialDescription(inputId, descriptionId, hintId, type) {
  710. const code = $('#' + inputId).val().trim();
  711. if (code.length > 0) {
  712. $.get('{{ route('pricing_codes.get_description') }}', {
  713. type: type,
  714. code: code
  715. }).done(function(data) {
  716. if (data.description) {
  717. $('#' + descriptionId).val(data.description);
  718. $('#' + descriptionId).prop('readonly', true);
  719. $('#' + hintId).html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  720. } else {
  721. $('#' + descriptionId).prop('readonly', false);
  722. $('#' + hintId).html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  723. }
  724. }).fail(function(xhr) {
  725. console.error('Initial description error:', xhr.status, xhr.responseText);
  726. });
  727. }
  728. }
  729. loadInitialDescription('tsn_number', 'tsn_number_description', 'tsn_number_hint', 'tsn_number');
  730. // Функционал множественных шифров расценки
  731. function initPricingCodeAutocomplete($row) {
  732. const $input = $row.find('.pricing-code-input');
  733. const $dropdown = $row.find('.pricing-code-dropdown');
  734. const $description = $row.find('.pricing-code-description-input');
  735. const $hint = $row.find('.pricing-code-hint');
  736. let currentFocus = -1;
  737. let searchTimeout;
  738. $input.on('input', function() {
  739. const query = $(this).val().trim();
  740. clearTimeout(searchTimeout);
  741. if (query.length > 0) {
  742. searchTimeout = setTimeout(function() {
  743. $.get('{{ route('pricing_codes.search') }}', {
  744. type: 'pricing_code',
  745. query: query
  746. }).done(function(data) {
  747. showDropdownPricing($dropdown, data, query, $input, $description, $hint);
  748. });
  749. $.get('{{ route('pricing_codes.get_description') }}', {
  750. type: 'pricing_code',
  751. code: query
  752. }).done(function(data) {
  753. if (data.description) {
  754. $description.val(data.description);
  755. $description.prop('readonly', true);
  756. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  757. } else {
  758. $description.val('');
  759. $description.prop('readonly', false);
  760. $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  761. }
  762. });
  763. }, 200);
  764. } else {
  765. $dropdown.hide();
  766. $description.val('');
  767. $description.prop('readonly', false);
  768. $hint.text('');
  769. }
  770. });
  771. $input.on('focus', function() {
  772. const query = $(this).val().trim();
  773. if (query.length > 0) {
  774. $.get('{{ route('pricing_codes.search') }}', {
  775. type: 'pricing_code',
  776. query: query
  777. }, function(data) {
  778. showDropdownPricing($dropdown, data, query, $input, $description, $hint);
  779. });
  780. }
  781. });
  782. $input.on('keydown', function(e) {
  783. const $items = $dropdown.find('.autocomplete-item');
  784. if (e.keyCode === 40) {
  785. e.preventDefault();
  786. currentFocus++;
  787. if (currentFocus >= $items.length) currentFocus = 0;
  788. $items.removeClass('active');
  789. if (currentFocus >= 0) $items.eq(currentFocus).addClass('active');
  790. } else if (e.keyCode === 38) {
  791. e.preventDefault();
  792. currentFocus--;
  793. if (currentFocus < 0) currentFocus = $items.length - 1;
  794. $items.removeClass('active');
  795. if (currentFocus >= 0) $items.eq(currentFocus).addClass('active');
  796. } else if (e.keyCode === 13) {
  797. e.preventDefault();
  798. if (currentFocus > -1 && $items.length > 0) {
  799. $items.eq(currentFocus).trigger('click');
  800. }
  801. } else if (e.keyCode === 27) {
  802. $dropdown.hide();
  803. }
  804. });
  805. $(document).on('click', function(e) {
  806. if (!$(e.target).closest($row).length) {
  807. $dropdown.hide();
  808. }
  809. });
  810. }
  811. function showDropdownPricing($dropdown, items, query, $input, $description, $hint) {
  812. $dropdown.empty();
  813. if (items.length === 0) {
  814. $dropdown.hide();
  815. return;
  816. }
  817. items.forEach(function(item) {
  818. const $item = $('<div class="autocomplete-item"></div>');
  819. const highlightedCode = highlightMatchPricing(item.code, query);
  820. const highlightedDesc = item.description ? highlightMatchPricing(item.description, query) : '';
  821. $item.html('<div class="code">' + highlightedCode + '</div>' +
  822. (item.description ? '<div class="description">' + highlightedDesc + '</div>' : ''));
  823. $item.data('code', item.code);
  824. $item.data('description', item.description || '');
  825. $item.on('click', function() {
  826. $input.val($(this).data('code'));
  827. $description.val($(this).data('description'));
  828. $description.prop('readonly', true);
  829. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  830. $dropdown.hide();
  831. });
  832. $dropdown.append($item);
  833. });
  834. $dropdown.show();
  835. }
  836. function highlightMatchPricing(text, query) {
  837. if (!text || !query) return text || '';
  838. const regex = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
  839. return text.replace(regex, '<strong>$1</strong>');
  840. }
  841. function loadInitialPricingCodeDescription($row) {
  842. const code = $row.find('.pricing-code-input').val().trim();
  843. const $description = $row.find('.pricing-code-description-input');
  844. const $hint = $row.find('.pricing-code-hint');
  845. if (code.length > 0) {
  846. $.get('{{ route('pricing_codes.get_description') }}', {
  847. type: 'pricing_code',
  848. code: code
  849. }).done(function(data) {
  850. if (data.description) {
  851. $description.val(data.description);
  852. $description.prop('readonly', true);
  853. $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
  854. } else {
  855. $description.prop('readonly', false);
  856. $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
  857. }
  858. });
  859. }
  860. }
  861. // Инициализация существующих строк
  862. $('.pricing-code-row').each(function() {
  863. initPricingCodeAutocomplete($(this));
  864. loadInitialPricingCodeDescription($(this));
  865. });
  866. // Добавление новой строки
  867. $('#btn_add_pricing_code').on('click', function() {
  868. const $container = $('#pricing_codes_container');
  869. const newIndex = $container.find('.pricing-code-row').length;
  870. const $newRow = $(`
  871. <div class="pricing-code-row row mb-2" data-index="${newIndex}">
  872. <div class="col-md-5 position-relative">
  873. <input type="text"
  874. class="form-control pricing-code-input"
  875. name="pricing_codes[]"
  876. value=""
  877. autocomplete="off"
  878. placeholder="Код">
  879. <div class="autocomplete-dropdown pricing-code-dropdown"></div>
  880. </div>
  881. <div class="col-md-5">
  882. <input type="text"
  883. class="form-control pricing-code-description-input"
  884. name="pricing_codes_descriptions[]"
  885. placeholder="Расшифровка">
  886. </div>
  887. <div class="col-md-2">
  888. <button type="button" class="btn btn-outline-danger btn-remove-pricing-code" title="Удалить">
  889. <i class="bi bi-trash"></i>
  890. </button>
  891. </div>
  892. <div class="col-12"><div class="form-text pricing-code-hint"></div></div>
  893. </div>
  894. `);
  895. $container.append($newRow);
  896. initPricingCodeAutocomplete($newRow);
  897. $newRow.find('.pricing-code-input').focus();
  898. });
  899. // Удаление строки
  900. $(document).on('click', '.btn-remove-pricing-code', function() {
  901. const $container = $('#pricing_codes_container');
  902. if ($container.find('.pricing-code-row').length > 1) {
  903. $(this).closest('.pricing-code-row').remove();
  904. } else {
  905. // Если осталась одна строка, просто очищаем её
  906. const $row = $(this).closest('.pricing-code-row');
  907. $row.find('.pricing-code-input').val('');
  908. $row.find('.pricing-code-description-input').val('').prop('readonly', false);
  909. $row.find('.pricing-code-hint').text('');
  910. }
  911. });
  912. @endif
  913. });
  914. });
  915. </script>
  916. @endpush
  917. @endsection