| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986 |
- @extends('layouts.app')
- @section('content')
- <div class="container-fluid">
- <div class="row">
- <div class="col-12">
- <div class="row mb-2">
- <div class="col-6">
- <h2>{{ $spare_part ? 'Редактирование запчасти' : 'Создание запчасти' }}</h2>
- </div>
- <div class="col-6 text-end">
- @if($spare_part && hasRole('admin'))
- <button class="btn btn-sm text-success" onclick="$('#upl-image').trigger('click');"><i class="bi bi-plus-circle-fill"></i> Загрузить изображение</button>
- <form action="{{ route('spare_parts.upload_image', ['sparePart' => $spare_part]) }}" class="visually-hidden" method="POST" enctype="multipart/form-data">
- @csrf
- <input type="file" name="image" onchange="$(this).parent().submit()" required id="upl-image" accept="image/*" />
- </form>
- @endif
- </div>
- </div>
- <form action="{{ $spare_part ? route('spare_parts.update', $spare_part) : route('spare_parts.store') }}"
- method="POST">
- @csrf
- @if($spare_part)
- @method('PUT')
- @endif
- <input type="hidden" name="previous_url" value="{{ $previous_url ?? url()->previous() }}">
- <div class="row">
- {{-- Левая колонка --}}
- <div class="col-md-6">
- @if($spare_part && $spare_part->image)
- <div class="mb-3">
- <img src="{{ $spare_part->image }}" alt="{{ $spare_part->article }}" class="img-fluid" style="max-width: 200px;">
- </div>
- @endif
- <div class="mb-3">
- <label for="article" class="form-label">Артикул <span class="text-danger">*</span></label>
- <input type="text"
- class="form-control"
- id="article"
- name="article"
- value="{{ old('article', $spare_part->article ?? '') }}"
- {{ hasRole('admin') ? '' : 'readonly' }}
- required>
- </div>
- <div class="mb-3">
- <label for="used_in_maf" class="form-label">Где используется</label>
- <input type="text"
- class="form-control"
- id="used_in_maf"
- name="used_in_maf"
- value="{{ old('used_in_maf', $spare_part->used_in_maf ?? '') }}"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- </div>
- <div class="mb-3">
- <label for="note" class="form-label">Примечание</label>
- <textarea class="form-control"
- id="note"
- name="note"
- rows="3"
- {{ hasRole('admin') ? '' : 'readonly' }}>{{ old('note', $spare_part->note ?? '') }}</textarea>
- </div>
- </div>
- {{-- Правая колонка --}}
- <div class="col-md-6">
- @if(hasRole('admin'))
- <div class="mb-3">
- <label for="purchase_price" class="form-label">Цена закупки (руб.)</label>
- <input type="number"
- class="form-control"
- id="purchase_price"
- name="purchase_price"
- step="0.01"
- value="{{ old('purchase_price', $spare_part->purchase_price ?? '') }}">
- </div>
- @endif
- <div class="mb-3">
- <label for="customer_price" class="form-label">Цена для заказчика (руб.)</label>
- <input type="number"
- class="form-control"
- id="customer_price"
- name="customer_price"
- step="0.01"
- value="{{ old('customer_price', $spare_part->customer_price ?? '') }}"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- </div>
- <div class="mb-3">
- <label for="expertise_price" class="form-label">Цена экспертизы (руб.)</label>
- <input type="number"
- class="form-control"
- id="expertise_price"
- name="expertise_price"
- step="0.01"
- value="{{ old('expertise_price', $spare_part->expertise_price ?? '') }}"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- </div>
- <div class="mb-3">
- <label for="tsn_number" class="form-label">№ по ТСН</label>
- <div class="row">
- <div class="col-md-5 position-relative">
- <input type="text"
- class="form-control"
- id="tsn_number"
- name="tsn_number"
- value="{{ old('tsn_number', $spare_part->tsn_number ?? '') }}"
- autocomplete="off"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- <div class="autocomplete-dropdown" id="tsn_number_dropdown"></div>
- </div>
- <div class="col-md-7">
- <input type="text"
- class="form-control"
- id="tsn_number_description"
- name="tsn_number_description"
- placeholder="Расшифровка"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- </div>
- </div>
- <div class="form-text" id="tsn_number_hint"></div>
- </div>
- <div class="mb-3">
- <label class="form-label">Шифр расценки и коды ресурсов</label>
- <div id="pricing_codes_container">
- @php
- $existingCodes = old('pricing_codes', $spare_part ? $spare_part->pricingCodes->pluck('code')->toArray() : []);
- @endphp
- @forelse($existingCodes as $index => $code)
- <div class="pricing-code-row row mb-2" data-index="{{ $index }}">
- <div class="col-md-5 position-relative">
- <input type="text"
- class="form-control pricing-code-input"
- name="pricing_codes[]"
- value="{{ $code }}"
- autocomplete="off"
- placeholder="Код"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- <div class="autocomplete-dropdown pricing-code-dropdown"></div>
- </div>
- <div class="col-md-5">
- <input type="text"
- class="form-control pricing-code-description-input"
- name="pricing_codes_descriptions[]"
- placeholder="Расшифровка"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- </div>
- <div class="col-md-2">
- @if(hasRole('admin'))
- <button type="button" class="btn btn-outline-danger btn-remove-pricing-code" title="Удалить">
- <i class="bi bi-trash"></i>
- </button>
- @endif
- </div>
- <div class="col-12"><div class="form-text pricing-code-hint"></div></div>
- </div>
- @empty
- <div class="pricing-code-row row mb-2" data-index="0">
- <div class="col-md-5 position-relative">
- <input type="text"
- class="form-control pricing-code-input"
- name="pricing_codes[]"
- value=""
- autocomplete="off"
- placeholder="Код"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- <div class="autocomplete-dropdown pricing-code-dropdown"></div>
- </div>
- <div class="col-md-5">
- <input type="text"
- class="form-control pricing-code-description-input"
- name="pricing_codes_descriptions[]"
- placeholder="Расшифровка"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- </div>
- <div class="col-md-2">
- @if(hasRole('admin'))
- <button type="button" class="btn btn-outline-danger btn-remove-pricing-code" title="Удалить">
- <i class="bi bi-trash"></i>
- </button>
- @endif
- </div>
- <div class="col-12"><div class="form-text pricing-code-hint"></div></div>
- </div>
- @endforelse
- </div>
- @if(hasRole('admin'))
- <button type="button" class="btn btn-sm btn-outline-primary" id="btn_add_pricing_code">
- <i class="bi bi-plus-circle"></i> Добавить код
- </button>
- @endif
- </div>
- <div class="mb-3">
- <label for="min_stock" class="form-label">Минимальный остаток</label>
- <input type="number"
- class="form-control"
- id="min_stock"
- name="min_stock"
- value="{{ old('min_stock', $spare_part->min_stock ?? 0) }}"
- {{ hasRole('admin') ? '' : 'readonly' }}>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-12">
- @if(hasRole('admin'))
- <button type="submit" class="btn btn-success">Сохранить</button>
- @endif
- <a href="{{ $previous_url ?? route('spare_parts.index') }}" class="btn btn-secondary">Назад</a>
- @if($spare_part && hasRole('admin'))
- <button type="button" class="btn btn-danger float-end" data-bs-toggle="modal" data-bs-target="#deleteModal">
- Удалить
- </button>
- @endif
- </div>
- </div>
- </form>
- @if($spare_part)
- <hr class="my-4">
- {{-- Остатки --}}
- <div class="row mb-4">
- <div class="col-12">
- <h4>Остатки</h4>
- <div class="table-responsive">
- <table class="table table-sm table-bordered">
- <thead class="table-light">
- <tr>
- <th></th>
- <th class="text-center">Без документов</th>
- <th class="text-center">С документами</th>
- <th class="text-center">Всего</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>Физический остаток</td>
- <td class="text-center">{{ $spare_part->physical_stock_without_docs }}</td>
- <td class="text-center">{{ $spare_part->physical_stock_with_docs }}</td>
- <td class="text-center fw-bold">{{ $spare_part->total_physical_stock }}</td>
- </tr>
- <tr class="table-warning">
- <td>Зарезервировано</td>
- <td class="text-center">{{ $spare_part->reserved_without_docs }}</td>
- <td class="text-center">{{ $spare_part->reserved_with_docs }}</td>
- <td class="text-center fw-bold">{{ $spare_part->total_reserved }}</td>
- </tr>
- <tr class="table-success">
- <td>Свободный остаток</td>
- <td class="text-center">{{ $spare_part->free_stock_without_docs }}</td>
- <td class="text-center">{{ $spare_part->free_stock_with_docs }}</td>
- <td class="text-center fw-bold">{{ $spare_part->total_free_stock }}</td>
- </tr>
- @if($spare_part->min_stock > 0)
- <tr class="@if($spare_part->total_free_stock < $spare_part->min_stock) table-danger @endif">
- <td>Минимальный остаток</td>
- <td colspan="3" class="text-center">{{ $spare_part->min_stock }}</td>
- </tr>
- @endif
- </tbody>
- </table>
- </div>
- </div>
- </div>
- {{-- Активные резервы --}}
- @php
- $activeReservations = $spare_part->reservations()
- ->where('status', \App\Models\Reservation::STATUS_ACTIVE)
- ->with('reclamation', 'sparePartOrder')
- ->orderByDesc('created_at')
- ->get();
- @endphp
- @if($activeReservations->count() > 0)
- <div class="row mb-4">
- <div class="col-12">
- <h4>Активные резервы <span class="badge bg-warning">{{ $activeReservations->count() }}</span></h4>
- <div class="table-responsive">
- <table class="table table-sm table-striped">
- <thead>
- <tr>
- <th>Рекламация</th>
- <th>Партия</th>
- <th class="text-center">Кол-во</th>
- <th class="text-center">С док.</th>
- <th>Дата</th>
- </tr>
- </thead>
- <tbody>
- @foreach($activeReservations as $reservation)
- <tr>
- <td>
- @if($reservation->reclamation)
- <a href="{{ route('reclamations.show', $reservation->reclamation->id) }}">
- #{{ $reservation->reclamation->id }}
- </a>
- @else
- -
- @endif
- </td>
- <td>
- @if($reservation->sparePartOrder)
- <a href="{{ route('spare_part_orders.show', $reservation->sparePartOrder->id) }}">
- #{{ $reservation->sparePartOrder->id }}
- </a>
- @else
- -
- @endif
- </td>
- <td class="text-center">{{ $reservation->reserved_qty }}</td>
- <td class="text-center">
- @if($reservation->with_documents)
- <i class="bi bi-check-circle text-success"></i>
- @else
- <i class="bi bi-x-circle text-muted"></i>
- @endif
- </td>
- <td>{{ $reservation->created_at->format('d.m.Y H:i') }}</td>
- </tr>
- @endforeach
- </tbody>
- </table>
- </div>
- </div>
- </div>
- @endif
- {{-- Открытые дефициты --}}
- @php
- $openShortages = $spare_part->shortages()
- ->where('status', \App\Models\Shortage::STATUS_OPEN)
- ->with('reclamation')
- ->orderByDesc('created_at')
- ->get();
- @endphp
- @if($openShortages->count() > 0)
- <div class="row mb-4">
- <div class="col-12">
- <h4 class="text-danger">Открытые дефициты <span class="badge bg-danger">{{ $openShortages->count() }}</span></h4>
- <div class="table-responsive">
- <table class="table table-sm table-danger">
- <thead>
- <tr>
- <th>Рекламация</th>
- <th class="text-center">Требуется</th>
- <th class="text-center">Зарезервировано</th>
- <th class="text-center">Не хватает</th>
- <th class="text-center">С док.</th>
- <th>Дата</th>
- </tr>
- </thead>
- <tbody>
- @foreach($openShortages as $shortage)
- <tr>
- <td>
- @if($shortage->reclamation)
- <a href="{{ route('reclamations.show', $shortage->reclamation->id) }}">
- #{{ $shortage->reclamation->id }}
- </a>
- @else
- -
- @endif
- </td>
- <td class="text-center">{{ $shortage->required_qty }}</td>
- <td class="text-center">{{ $shortage->reserved_qty }}</td>
- <td class="text-center fw-bold">{{ $shortage->missing_qty }}</td>
- <td class="text-center">
- @if($shortage->with_documents)
- <i class="bi bi-check-circle text-success"></i>
- @else
- <i class="bi bi-x-circle text-muted"></i>
- @endif
- </td>
- <td>{{ $shortage->created_at->format('d.m.Y H:i') }}</td>
- </tr>
- @endforeach
- </tbody>
- </table>
- </div>
- </div>
- </div>
- @endif
- {{-- Партии (заказы) на складе --}}
- @php
- $ordersInStock = $spare_part->orders()
- ->where('status', \App\Models\SparePartOrder::STATUS_IN_STOCK)
- ->where('available_qty', '>', 0)
- ->orderByDesc('created_at')
- ->get();
- @endphp
- @if($ordersInStock->count() > 0)
- <div class="row mb-4">
- <div class="col-12">
- <h4>Партии на складе <span class="badge bg-info">{{ $ordersInStock->count() }}</span></h4>
- <div class="table-responsive">
- <table class="table table-sm table-striped">
- <thead>
- <tr>
- <th>ID</th>
- <th>Источник</th>
- <th class="text-center">Остаток</th>
- <th class="text-center">С док.</th>
- <th>Дата поступления</th>
- </tr>
- </thead>
- <tbody>
- @foreach($ordersInStock as $order)
- <tr>
- <td>
- <a href="{{ route('spare_part_orders.show', $order->id) }}">#{{ $order->id }}</a>
- </td>
- <td>{{ $order->source_text ?: '-' }}</td>
- <td class="text-center">{{ $order->available_qty }}</td>
- <td class="text-center">
- @if($order->with_documents)
- <i class="bi bi-check-circle text-success"></i>
- @else
- <i class="bi bi-x-circle text-muted"></i>
- @endif
- </td>
- <td>{{ $order->updated_at->format('d.m.Y') }}</td>
- </tr>
- @endforeach
- </tbody>
- </table>
- </div>
- </div>
- </div>
- @endif
- {{-- История движений --}}
- @php
- $movements = $spare_part->movements()
- ->with('user', 'sparePartOrder')
- ->orderByDesc('created_at')
- ->limit(50)
- ->get();
- @endphp
- <div class="row mb-4">
- <div class="col-12">
- <h4>История движений <span class="badge bg-secondary">{{ $spare_part->movements()->count() }}</span></h4>
- @if($movements->count() > 0)
- <div class="table-responsive">
- <table class="table table-sm table-striped">
- <thead>
- <tr>
- <th>Дата</th>
- <th>Тип</th>
- <th>Партия</th>
- <th class="text-center">Кол-во</th>
- <th class="text-center">С док.</th>
- <th>Примечание</th>
- <th>Пользователь</th>
- </tr>
- </thead>
- <tbody>
- @foreach($movements as $movement)
- <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">
- <td>{{ $movement->created_at->format('d.m.Y H:i') }}</td>
- <td>{{ $movement->type_name }}</td>
- <td>
- @if($movement->sparePartOrder)
- <a href="{{ route('spare_part_orders.show', $movement->sparePartOrder->id) }}">#{{ $movement->sparePartOrder->id }}</a>
- @else
- -
- @endif
- </td>
- <td class="text-center">{{ $movement->qty }}</td>
- <td class="text-center">
- @if($movement->with_documents)
- <i class="bi bi-check-circle text-success"></i>
- @else
- <i class="bi bi-x-circle text-muted"></i>
- @endif
- </td>
- <td>
- {{ $movement->note }}
- @if($movement->source_type === 'reclamation' && $movement->source_id)
- <br><small><a href="{{ route('reclamations.show', $movement->source_id) }}">Рекламация #{{ $movement->source_id }}</a></small>
- @endif
- </td>
- <td>{{ $movement->user->name ?? '-' }}</td>
- </tr>
- @endforeach
- </tbody>
- </table>
- </div>
- @if($spare_part->movements()->count() > 50)
- <p class="text-muted">Показаны последние 50 движений из {{ $spare_part->movements()->count() }}</p>
- @endif
- @else
- <p class="text-muted">Движений пока нет</p>
- @endif
- </div>
- </div>
- @endif
- </div>
- </div>
- </div>
- @if($spare_part && hasRole('admin'))
- {{-- Модальное окно удаления --}}
- <div class="modal fade" id="deleteModal" tabindex="-1">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <h5 class="modal-title">Подтверждение удаления</h5>
- <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
- </div>
- <div class="modal-body">
- Вы действительно хотите удалить запчасть "{{ $spare_part->article }}"?
- </div>
- <div class="modal-footer">
- <form action="{{ route('spare_parts.destroy', $spare_part) }}" method="POST">
- @csrf
- @method('DELETE')
- <button type="submit" class="btn btn-danger">Удалить</button>
- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
- </form>
- </div>
- </div>
- </div>
- </div>
- @endif
- @push('scripts')
- <style>
- .autocomplete-dropdown {
- position: absolute;
- top: 100%;
- left: 0;
- right: 0;
- z-index: 1050;
- background: white;
- border: 1px solid #dee2e6;
- border-top: none;
- border-radius: 0 0 .375rem .375rem;
- max-height: 250px;
- overflow-y: auto;
- display: none;
- box-shadow: 0 4px 6px rgba(0,0,0,.1);
- }
- .autocomplete-dropdown .autocomplete-item {
- padding: 8px 12px;
- cursor: pointer;
- border-bottom: 1px solid #f0f0f0;
- }
- .autocomplete-dropdown .autocomplete-item:last-child {
- border-bottom: none;
- }
- .autocomplete-dropdown .autocomplete-item:hover,
- .autocomplete-dropdown .autocomplete-item.active {
- background-color: #e9ecef;
- }
- .autocomplete-dropdown .autocomplete-item .code {
- font-weight: 600;
- color: #495057;
- }
- .autocomplete-dropdown .autocomplete-item .description {
- font-size: 0.875em;
- color: #6c757d;
- }
- </style>
- <script>
- function waitForJQuery(callback) {
- if (typeof $ !== 'undefined') {
- callback();
- } else {
- setTimeout(function() { waitForJQuery(callback); }, 50);
- }
- }
- waitForJQuery(function() {
- $(document).ready(function() {
- @if(hasRole('admin'))
- //console.log('Autocomplete init started');
- // Общая функция для инициализации автокомплита
- function initAutocomplete(inputId, dropdownId, descriptionId, hintId, type) {
- const $input = $('#' + inputId);
- const $dropdown = $('#' + dropdownId);
- const $description = $('#' + descriptionId);
- const $hint = $('#' + hintId);
- let currentFocus = -1;
- let searchTimeout;
- //console.log('Init autocomplete for:', inputId, $input.length);
- // Обработка ввода
- $input.on('input', function() {
- const query = $(this).val().trim();
- clearTimeout(searchTimeout);
- //console.log('Input event:', inputId, query);
- if (query.length > 0) {
- searchTimeout = setTimeout(function() {
- // Поиск вариантов для автокомплита
- $.get('{{ route('pricing_codes.search') }}', {
- type: type,
- query: query
- }).done(function(data) {
- //console.log('Search result:', data);
- showDropdown(data, query);
- }).fail(function(xhr) {
- console.error('Search error:', xhr.status, xhr.responseText);
- });
- // Проверка точного соответствия для расшифровки
- $.get('{{ route('pricing_codes.get_description') }}', {
- type: type,
- code: query
- }).done(function(data) {
- // console.log('Description result:', data);
- if (data.description) {
- $description.val(data.description);
- $description.prop('readonly', true);
- $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
- } else {
- $description.val('');
- $description.prop('readonly', false);
- $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
- }
- }).fail(function(xhr) {
- console.error('Description error:', xhr.status, xhr.responseText);
- });
- }, 200);
- } else {
- $dropdown.hide();
- $description.val('');
- $description.prop('readonly', false);
- $hint.text('');
- }
- });
- // Показать выпадающий список
- function showDropdown(items, query) {
- $dropdown.empty();
- currentFocus = -1;
- if (items.length === 0) {
- $dropdown.hide();
- return;
- }
- items.forEach(function(item, index) {
- const $item = $('<div class="autocomplete-item"></div>');
- const highlightedCode = highlightMatch(item.code, query);
- const highlightedDesc = item.description ? highlightMatch(item.description, query) : '';
- $item.html('<div class="code">' + highlightedCode + '</div>' +
- (item.description ? '<div class="description">' + highlightedDesc + '</div>' : ''));
- $item.data('code', item.code);
- $item.data('description', item.description || '');
- $item.on('click', function() {
- selectItem($(this));
- });
- $dropdown.append($item);
- });
- $dropdown.show();
- }
- // Подсветка совпадения
- function highlightMatch(text, query) {
- if (!text || !query) return text || '';
- const regex = new RegExp('(' + escapeRegex(query) + ')', 'gi');
- return text.replace(regex, '<strong>$1</strong>');
- }
- function escapeRegex(str) {
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- }
- // Выбор элемента
- function selectItem($item) {
- $input.val($item.data('code'));
- $description.val($item.data('description'));
- $description.prop('readonly', true);
- $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
- $dropdown.hide();
- }
- // Навигация клавиатурой
- $input.on('keydown', function(e) {
- const $items = $dropdown.find('.autocomplete-item');
- if (e.keyCode === 40) { // Стрелка вниз
- e.preventDefault();
- currentFocus++;
- if (currentFocus >= $items.length) currentFocus = 0;
- setActive($items);
- } else if (e.keyCode === 38) { // Стрелка вверх
- e.preventDefault();
- currentFocus--;
- if (currentFocus < 0) currentFocus = $items.length - 1;
- setActive($items);
- } else if (e.keyCode === 13) { // Enter
- e.preventDefault();
- if (currentFocus > -1 && $items.length > 0) {
- selectItem($items.eq(currentFocus));
- }
- } else if (e.keyCode === 27) { // Escape
- $dropdown.hide();
- }
- });
- function setActive($items) {
- $items.removeClass('active');
- if (currentFocus >= 0 && currentFocus < $items.length) {
- $items.eq(currentFocus).addClass('active');
- }
- }
- // Закрытие при клике вне
- $(document).on('click', function(e) {
- if (!$(e.target).closest('#' + inputId + ', #' + dropdownId).length) {
- $dropdown.hide();
- }
- });
- // При фокусе показать список если есть значение
- $input.on('focus', function() {
- const query = $(this).val().trim();
- if (query.length > 0) {
- $.get('{{ route('pricing_codes.search') }}', {
- type: type,
- query: query
- }, function(data) {
- showDropdown(data, query);
- });
- }
- });
- }
- // Инициализация автокомплитов
- initAutocomplete('tsn_number', 'tsn_number_dropdown', 'tsn_number_description', 'tsn_number_hint', 'tsn_number');
- // Загрузка расшифровок при открытии страницы
- function loadInitialDescription(inputId, descriptionId, hintId, type) {
- const code = $('#' + inputId).val().trim();
- if (code.length > 0) {
- $.get('{{ route('pricing_codes.get_description') }}', {
- type: type,
- code: code
- }).done(function(data) {
- if (data.description) {
- $('#' + descriptionId).val(data.description);
- $('#' + descriptionId).prop('readonly', true);
- $('#' + hintId).html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
- } else {
- $('#' + descriptionId).prop('readonly', false);
- $('#' + hintId).html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
- }
- }).fail(function(xhr) {
- console.error('Initial description error:', xhr.status, xhr.responseText);
- });
- }
- }
- loadInitialDescription('tsn_number', 'tsn_number_description', 'tsn_number_hint', 'tsn_number');
- // Функционал множественных шифров расценки
- function initPricingCodeAutocomplete($row) {
- const $input = $row.find('.pricing-code-input');
- const $dropdown = $row.find('.pricing-code-dropdown');
- const $description = $row.find('.pricing-code-description-input');
- const $hint = $row.find('.pricing-code-hint');
- let currentFocus = -1;
- let searchTimeout;
- $input.on('input', function() {
- const query = $(this).val().trim();
- clearTimeout(searchTimeout);
- if (query.length > 0) {
- searchTimeout = setTimeout(function() {
- $.get('{{ route('pricing_codes.search') }}', {
- type: 'pricing_code',
- query: query
- }).done(function(data) {
- showDropdownPricing($dropdown, data, query, $input, $description, $hint);
- });
- $.get('{{ route('pricing_codes.get_description') }}', {
- type: 'pricing_code',
- code: query
- }).done(function(data) {
- if (data.description) {
- $description.val(data.description);
- $description.prop('readonly', true);
- $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
- } else {
- $description.val('');
- $description.prop('readonly', false);
- $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
- }
- });
- }, 200);
- } else {
- $dropdown.hide();
- $description.val('');
- $description.prop('readonly', false);
- $hint.text('');
- }
- });
- $input.on('focus', function() {
- const query = $(this).val().trim();
- if (query.length > 0) {
- $.get('{{ route('pricing_codes.search') }}', {
- type: 'pricing_code',
- query: query
- }, function(data) {
- showDropdownPricing($dropdown, data, query, $input, $description, $hint);
- });
- }
- });
- $input.on('keydown', function(e) {
- const $items = $dropdown.find('.autocomplete-item');
- if (e.keyCode === 40) {
- e.preventDefault();
- currentFocus++;
- if (currentFocus >= $items.length) currentFocus = 0;
- $items.removeClass('active');
- if (currentFocus >= 0) $items.eq(currentFocus).addClass('active');
- } else if (e.keyCode === 38) {
- e.preventDefault();
- currentFocus--;
- if (currentFocus < 0) currentFocus = $items.length - 1;
- $items.removeClass('active');
- if (currentFocus >= 0) $items.eq(currentFocus).addClass('active');
- } else if (e.keyCode === 13) {
- e.preventDefault();
- if (currentFocus > -1 && $items.length > 0) {
- $items.eq(currentFocus).trigger('click');
- }
- } else if (e.keyCode === 27) {
- $dropdown.hide();
- }
- });
- $(document).on('click', function(e) {
- if (!$(e.target).closest($row).length) {
- $dropdown.hide();
- }
- });
- }
- function showDropdownPricing($dropdown, items, query, $input, $description, $hint) {
- $dropdown.empty();
- if (items.length === 0) {
- $dropdown.hide();
- return;
- }
- items.forEach(function(item) {
- const $item = $('<div class="autocomplete-item"></div>');
- const highlightedCode = highlightMatchPricing(item.code, query);
- const highlightedDesc = item.description ? highlightMatchPricing(item.description, query) : '';
- $item.html('<div class="code">' + highlightedCode + '</div>' +
- (item.description ? '<div class="description">' + highlightedDesc + '</div>' : ''));
- $item.data('code', item.code);
- $item.data('description', item.description || '');
- $item.on('click', function() {
- $input.val($(this).data('code'));
- $description.val($(this).data('description'));
- $description.prop('readonly', true);
- $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
- $dropdown.hide();
- });
- $dropdown.append($item);
- });
- $dropdown.show();
- }
- function highlightMatchPricing(text, query) {
- if (!text || !query) return text || '';
- const regex = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
- return text.replace(regex, '<strong>$1</strong>');
- }
- function loadInitialPricingCodeDescription($row) {
- const code = $row.find('.pricing-code-input').val().trim();
- const $description = $row.find('.pricing-code-description-input');
- const $hint = $row.find('.pricing-code-hint');
- if (code.length > 0) {
- $.get('{{ route('pricing_codes.get_description') }}', {
- type: 'pricing_code',
- code: code
- }).done(function(data) {
- if (data.description) {
- $description.val(data.description);
- $description.prop('readonly', true);
- $hint.html('<i class="bi bi-check-circle text-success"></i> Код найден в справочнике');
- } else {
- $description.prop('readonly', false);
- $hint.html('<i class="bi bi-plus-circle text-primary"></i> Новый код - заполните расшифровку');
- }
- });
- }
- }
- // Инициализация существующих строк
- $('.pricing-code-row').each(function() {
- initPricingCodeAutocomplete($(this));
- loadInitialPricingCodeDescription($(this));
- });
- // Добавление новой строки
- $('#btn_add_pricing_code').on('click', function() {
- const $container = $('#pricing_codes_container');
- const newIndex = $container.find('.pricing-code-row').length;
- const $newRow = $(`
- <div class="pricing-code-row row mb-2" data-index="${newIndex}">
- <div class="col-md-5 position-relative">
- <input type="text"
- class="form-control pricing-code-input"
- name="pricing_codes[]"
- value=""
- autocomplete="off"
- placeholder="Код">
- <div class="autocomplete-dropdown pricing-code-dropdown"></div>
- </div>
- <div class="col-md-5">
- <input type="text"
- class="form-control pricing-code-description-input"
- name="pricing_codes_descriptions[]"
- placeholder="Расшифровка">
- </div>
- <div class="col-md-2">
- <button type="button" class="btn btn-outline-danger btn-remove-pricing-code" title="Удалить">
- <i class="bi bi-trash"></i>
- </button>
- </div>
- <div class="col-12"><div class="form-text pricing-code-hint"></div></div>
- </div>
- `);
- $container.append($newRow);
- initPricingCodeAutocomplete($newRow);
- $newRow.find('.pricing-code-input').focus();
- });
- // Удаление строки
- $(document).on('click', '.btn-remove-pricing-code', function() {
- const $container = $('#pricing_codes_container');
- if ($container.find('.pricing-code-row').length > 1) {
- $(this).closest('.pricing-code-row').remove();
- } else {
- // Если осталась одна строка, просто очищаем её
- const $row = $(this).closest('.pricing-code-row');
- $row.find('.pricing-code-input').val('');
- $row.find('.pricing-code-description-input').val('').prop('readonly', false);
- $row.find('.pricing-code-hint').text('');
- }
- });
- @endif
- });
- });
- </script>
- @endpush
- @endsection
|