table.blade.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. <div class="table-responsive js-main-table-scroll">
  2. <div class="table-buttons py-2 bg-primary rounded-start d-flex flex-column ">
  3. <button type="button" class="btn btn-sm text-white" data-bs-toggle="modal"
  4. data-bs-target="#table_{{ $id }}_modal_search">
  5. <i class="bi bi-search-heart @if(request()->has('s')) text-danger @endif"></i>
  6. </button>
  7. <button type="button" class="btn btn-sm text-white " data-bs-toggle="modal"
  8. data-bs-target="#table_{{ $id }}_modal_filters">
  9. <i class="bi bi-funnel-fill @if(request()->has('filters')) text-danger @endif"></i>
  10. </button>
  11. <button type="button" class="btn btn-sm text-white " data-bs-toggle="modal"
  12. data-bs-target="#table_{{ $id }}_modal_settings">
  13. <i class="bi bi-gear-fill"></i>
  14. </button>
  15. </div>
  16. <table class="table table-interactive table-initial-hidden" id="tbl" data-table-name="{{ $id }}">
  17. <thead class="table-head-shadow">
  18. <tr>
  19. @if($selectable ?? false)
  20. <th scope="col" class="bg-primary-subtle text-center" data-no-row-select>
  21. <input type="checkbox" class="form-check-input js-table-select-all"
  22. aria-label="Выбрать все строки на странице">
  23. </th>
  24. @endif
  25. @foreach($header as $headerName => $headerTitle)
  26. @php
  27. $normalizedHeaderName = str_replace('_txt', '', $headerName);
  28. $isCurrentSortColumn = $headerName === $sortBy || $normalizedHeaderName === $sortBy;
  29. @endphp
  30. <th scope="col" class="bg-primary-subtle column_{{ $headerName }}">
  31. <div class="d-flex align-items-center justify-content-between">
  32. <div class="@if($headerName !== 'actions') cursor-pointer sort-by-column @endif" data-name="{{ $headerName }}">
  33. {{ $headerTitle }}
  34. </div>
  35. <div class="text-center mx-1 @if($headerName !== 'actions') cursor-pointer @endif" data-name="{{ $headerName }}">
  36. @if($headerName !== 'actions' && $isCurrentSortColumn)
  37. @if($orderBy === 'asc')
  38. <i class="bi bi-arrow-down-square-fill text-primary"></i>
  39. @else
  40. <i class="bi bi-arrow-up-square-fill text-primary"></i>
  41. @endif
  42. @endif
  43. </div>
  44. @if(($enableColumnFilters ?? true) && $headerName !== 'image' && $headerName !== 'actions')
  45. @php
  46. $filters = $filters ?? [];
  47. $ranges = $ranges ?? [];
  48. $dates = $dates ?? [];
  49. $type = null;
  50. $data = (array_merge($filters, $ranges, $dates))[$headerName] ?? null;
  51. if (isset($filters[$headerName])) {
  52. $type = 'filters';
  53. } elseif (isset($ranges[$headerName])) {
  54. // В фильтрах заголовка всегда показываем список фактических значений.
  55. $type = 'filters';
  56. } elseif (isset($dates[$headerName])) {
  57. $type = 'filters';
  58. }
  59. @endphp
  60. <div class="text-end cursor-pointer dropdown" data-bs-auto-close="outside" aria-expanded="false">
  61. <i
  62. data-bs-auto-close="outside"
  63. aria-expanded="false"
  64. data-bs-toggle="dropdown"
  65. class="dropdown-toggle bi
  66. @if(isset(request()->filters[$headerName]) ||
  67. isset(request()->filters[$headerName . '_from']) ||
  68. isset(request()->filters[$headerName . '_to']) ||
  69. isset(request()->filters[str_replace('_txt', '', $headerName) . '_from']) ||
  70. isset(request()->filters[str_replace('_txt', '', $headerName) . '_to'])
  71. )
  72. bi-funnel-fill text-danger
  73. @else
  74. bi-funnel
  75. @endif
  76. " id="{{$headerName}}"></i>
  77. @include('partials.newFilterElement', ['id' => $headerName, 'data' => $data, 'type' => $type, 'table' => $id, 'isSort' => $isCurrentSortColumn, '$orderBy' => $orderBy])
  78. </div>
  79. @endif
  80. </div>
  81. </th>
  82. @endforeach
  83. </tr>
  84. </thead>
  85. <tbody>
  86. @foreach($strings as $string)
  87. @php
  88. $rowId = $string->id ?? null;
  89. $rowAnchor = $rowId ? 'row-' . $rowId : null;
  90. $rowHref = null;
  91. if (isset($routeName) && $rowId && !empty($nav ?? null)) {
  92. $rowHref = route($routeName, [$string->id, 'nav' => $nav]);
  93. }
  94. @endphp
  95. <tr
  96. @if($rowAnchor) id="{{ $rowAnchor }}" data-row-id="{{ $rowId }}" @endif
  97. @if($rowHref) data-row-href="{{ $rowHref }}" @endif
  98. @if($id === 'notifications')
  99. data-notification-id="{{ $string->id }}"
  100. data-notification-read="{{ $string->isRead() ? '1' : '0' }}"
  101. data-read-class="{{ match($string->type) { 'reclamation' => 'notification-read-reclamation', 'platform' => 'notification-read-platform', 'schedule' => 'notification-read-schedule', default => 'notification-read-platform' } }}"
  102. class="{{ $string->isRead() ? match($string->type) { 'reclamation' => 'notification-read-reclamation', 'platform' => 'notification-read-platform', 'schedule' => 'notification-read-schedule', default => 'notification-read-platform' } : 'notification-unread' }}"
  103. @endif
  104. >
  105. @if($selectable ?? false)
  106. <td class="align-middle text-center" data-no-row-select>
  107. <input type="checkbox"
  108. class="form-check-input js-table-row-select"
  109. value="{{ $rowId }}"
  110. aria-label="Выбрать строку {{ $rowId }}">
  111. </td>
  112. @endif
  113. @foreach($header as $headerName => $headerTitle)
  114. <td class="column_{{$headerName}} align-middle"
  115. >
  116. @if(str_contains($headerName, '-'))
  117. @php
  118. list($rel, $field) = explode('-', $headerName);
  119. @endphp
  120. @if(isset($string->$rel->$field))
  121. @if(str_ends_with($field, '_id'))
  122. @php
  123. $relation = \Illuminate\Support\Str::camel(str_replace('_id', '', $field));
  124. @endphp
  125. {!! $string->$rel->$relation?->name; !!}
  126. @else
  127. @if(str_contains($field, 'image') && $string->$rel->$field)
  128. <a href="{{ $string->$rel->$field }}" data-toggle="lightbox"
  129. data-gallery="photos" data-size="fullscreen">
  130. <img src="{{ $string->$rel->$field }}" alt="" class="img-thumbnail maf-img">
  131. </a>
  132. @else
  133. {!! $string->$rel->$field !!}
  134. @endif
  135. @endif
  136. @else
  137. <ul class="small mb-0 list-group list-group-flush bg-secondary">
  138. @foreach($string->$rel ?? [] as $item)
  139. <li class="list-group-item py-0 bg-body-secondary">
  140. {!! $item->$field !!}
  141. </li>
  142. @endforeach
  143. </ul>
  144. @endif
  145. @elseif(str_ends_with($headerName, '_id'))
  146. @php
  147. $relation = \Illuminate\Support\Str::camel(str_replace('_id', '', $headerName));
  148. @endphp
  149. @if($headerName == 'order_status_id')
  150. <div class="badge fs-5 text-bg-{{ App\Models\Order::STATUS_COLOR[$string->order_status_id] }}">{{ $string->$relation?->name }}</div>
  151. @else
  152. {!! $string->$relation?->name; !!}
  153. @endif
  154. @elseif($id === 'product_sku' && in_array($headerName, ['rfid', 'factory_number', 'manufacture_date', 'statement_number', 'statement_date', 'upd_number'], true))
  155. @if(canUpdateField('maf', $headerName))
  156. <input
  157. type="{{ str_ends_with($headerName, '_date') ? 'date' : 'text' }}"
  158. class="form-control form-control-sm inline-product-sku-field"
  159. data-url="{{ route('product_sku.inline-update', $string->id) }}"
  160. data-field="{{ $headerName }}"
  161. value="{{ $string->$headerName }}"
  162. >
  163. @elseif(str_ends_with($headerName, '_date') && ($string->$headerName))
  164. {{ \App\Helpers\DateHelper::getHumanDate($string->$headerName, true) }}
  165. @else
  166. <p title="{{ $string->$headerName }}">
  167. {{ \Illuminate\Support\Str::words($string->$headerName, config('app.words_in_table_cell_limit'), ' ...') }}
  168. </p>
  169. @endif
  170. @elseif(str_ends_with($headerName, '_date') && ($string->$headerName))
  171. {{ \App\Helpers\DateHelper::getHumanDate($string->$headerName, true) }}
  172. @elseif(str_contains($headerName, 'image') && $string->$headerName)
  173. <a href="{{ $string->$headerName }}" data-toggle="lightbox" data-gallery="photos"
  174. data-size="fullscreen">
  175. <img src="{{ $string->$headerName }}" alt="" class="img-thumbnail maf-img">
  176. </a>
  177. @elseif(str_contains($headerName, 'order_status_name'))
  178. <select name="order_status_name" data-order-id="{{ $string->id }}" @disabled(!hasPermission('orders.update')) class="change-order-status form-control form-control-sm" >
  179. @foreach($statuses as $statusId => $statusName)
  180. <option value="{{ $statusId }}" @selected($statusName == $string->$headerName)>{{ $statusName }}</option>
  181. @endforeach
  182. </select>
  183. @elseif($id === 'reclamations' && $headerName === 'status_name')
  184. <select name="status_id"
  185. data-reclamation-id="{{ $string->id }}"
  186. data-url="{{ route('reclamations.update-status', $string->id) }}"
  187. @disabled(!hasPermission('orders.update'))
  188. class="change-reclamation-status form-control form-control-sm">
  189. @foreach($statuses as $statusId => $statusName)
  190. <option value="{{ $statusId }}" @selected($statusId == $string->status_id)>{{ $statusName }}</option>
  191. @endforeach
  192. </select>
  193. @elseif($id === 'schedule_orders' && $headerName === 'status_name')
  194. <span class="badge text-bg-{{ $string->status->color() }}">
  195. {{ $string->status_name }}
  196. </span>
  197. @elseif($headerName === 'tsn_number' && $string->$headerName)
  198. <span data-bs-toggle="tooltip"
  199. data-bs-placement="top"
  200. title="{{ $string->tsn_number_description ?? 'Нет расшифровки' }}"
  201. class="tooltip-help">
  202. {{ $string->$headerName }}
  203. </span>
  204. @elseif($headerName === 'pricing_code' && $string->$headerName)
  205. <span data-bs-toggle="tooltip"
  206. data-bs-placement="top"
  207. title="{{ $string->pricing_code_description ?? 'Нет расшифровки' }}"
  208. class="tooltip-help">
  209. {{ $string->$headerName }}
  210. </span>
  211. @elseif($headerName === 'pricing_codes_list' && $string->pricingCodes->count() > 0)
  212. @foreach($string->pricingCodes as $pricingCode)
  213. <span data-bs-toggle="tooltip"
  214. data-bs-placement="top"
  215. title="{{ $pricingCode->description ?? 'Нет расшифровки' }}"
  216. class="tooltip-help">
  217. {{ $pricingCode->code }}
  218. </span>@if(!$loop->last)<br>@endif
  219. @endforeach
  220. @elseif($id === 'pricing_codes' && $headerName === 'type')
  221. @if($string->type === 'tsn_number')
  222. <span class="badge bg-info">№ по ТСН</span>
  223. @else
  224. <span class="badge bg-primary">Шифр расценки</span>
  225. @endif
  226. @elseif($id === 'pricing_codes' && $headerName === 'description')
  227. @if(hasPermission('pricing_codes.update'))
  228. <div class="d-flex justify-content-between align-items-center">
  229. <span class="description-text-{{ $string->id }}">{{ $string->description }}</span>
  230. <button type="button" class="btn btn-sm btn-link edit-description"
  231. data-id="{{ $string->id }}"
  232. data-description="{{ $string->description }}">
  233. <i class="bi bi-pencil"></i>
  234. </button>
  235. </div>
  236. <form action="{{ route('pricing_codes.update', $string) }}" method="POST" class="edit-form-{{ $string->id }} is-hidden">
  237. @csrf
  238. @method('PUT')
  239. <div class="input-group input-group-sm">
  240. <input type="text" name="description" class="form-control" value="{{ $string->description }}">
  241. <button type="submit" class="btn btn-success">Сохранить</button>
  242. <button type="button" class="btn btn-secondary cancel-edit" data-id="{{ $string->id }}">Отмена</button>
  243. </div>
  244. </form>
  245. @else
  246. {{ $string->description }}
  247. @endif
  248. @elseif($id === 'pricing_codes' && $headerName === 'actions')
  249. @if(hasPermission('pricing_codes.delete'))
  250. <form action="{{ route('pricing_codes.destroy', $string) }}" method="POST" class="d-inline js-confirm-submit"
  251. data-confirm-message="Удалить код {{ $string->code }}?">
  252. @csrf
  253. @method('DELETE')
  254. <button type="submit" class="btn btn-sm btn-danger">Удалить</button>
  255. </form>
  256. @endif
  257. @elseif($id === 'contractor_prices' && $headerName === 'status_name')
  258. @if($string->available)
  259. <span class="badge text-bg-success">Доступен</span>
  260. @else
  261. <span class="badge text-bg-warning">МАФ недоступен</span>
  262. @endif
  263. @elseif($id === 'contractor_prices' && $headerName === 'actions')
  264. <button
  265. type="button"
  266. class="btn btn-sm btn-outline-primary edit-price"
  267. data-bs-toggle="modal"
  268. data-bs-target="#editPriceModal"
  269. data-product-id="{{ $string->product_id }}"
  270. data-article="{{ $string->article }}"
  271. data-name="{{ e($string->name_in_spec) }}"
  272. data-price="{{ $string->installation_price }}"
  273. >
  274. Изменить
  275. </button>
  276. @elseif($id === 'notifications' && $headerName === 'type')
  277. <span class="badge text-bg-{{ \App\Models\UserNotification::TYPE_COLORS[$string->type] ?? 'secondary' }}">{{ $string->type_name }}</span>
  278. @elseif($id === 'notifications' && $headerName === 'event')
  279. {{ $string->event_name }}
  280. @elseif($id === 'notifications' && $headerName === 'message')
  281. {!! $string->message_html ?: e($string->message) !!}
  282. @elseif($id === 'notifications' && $headerName === 'read_at')
  283. @if($string->read_at)
  284. {{ $string->read_at->format('d.m.Y H:i') }}
  285. @else
  286. <span class="text-muted">—</span>
  287. @endif
  288. @elseif($id === 'notifications' && $headerName === 'created_at')
  289. {{ $string->created_at?->format('d.m.Y H:i') }}
  290. @elseif($id === 'users' && $headerName === 'role')
  291. {{ \App\Models\Role::NAMES[$string->role] ?? $string->role }}
  292. @elseif($headerName === 'actions' && isset($routeName) && isset($string->id))
  293. <a href="{{ route($routeName, $string->id) }}" class="btn btn-sm btn-outline-primary">
  294. Редактировать
  295. </a>
  296. @else
  297. <p title="{!! $string->$headerName !!}">
  298. {!! \Illuminate\Support\Str::words($string->$headerName, config('app.words_in_table_cell_limit'), ' ...') !!}
  299. </p>
  300. @endif
  301. </td>
  302. @endforeach
  303. </tr>
  304. @endforeach
  305. </tbody>
  306. </table>
  307. </div>
  308. <!-- Модальное окно настроек таблицы -->
  309. <div class="modal fade" id="table_{{ $id }}_modal_settings" tabindex="-1" aria-labelledby="table_{{ $id }}_modal_settings_label"
  310. aria-hidden="true">
  311. <div class="modal-dialog modal-fullscreen-sm-down">
  312. <div class="modal-content">
  313. <div class="modal-header">
  314. <h1 class="modal-title fs-5" id="table_{{ $id }}_modal_settings_label">Выбор отображаемых колонок</h1>
  315. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
  316. </div>
  317. <div class="modal-body">
  318. @foreach($header as $headerName => $headerTitle)
  319. <div>
  320. <label class="me-3"><input type="checkbox" checked="checked" data-name="{{ $headerName }}"
  321. class="toggle-column checkbox-{{ $headerName }}"> {{ $headerTitle }}
  322. </label>
  323. </div>
  324. @endforeach
  325. </div>
  326. <div class="modal-footer">
  327. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
  328. </div>
  329. </div>
  330. </div>
  331. </div>
  332. <!-- Модальное окно фильтров -->
  333. <div class="modal fade" id="table_{{ $id }}_modal_filters" tabindex="-1" aria-labelledby="table_{{ $id }}_modal_filters_label"
  334. aria-hidden="true">
  335. <div class="modal-dialog modal-fullscreen-sm-down modal-lg">
  336. <div class="modal-content">
  337. <div class="modal-header">
  338. <h1 class="modal-title fs-5" id="table_{{ $id }}_modal_filters_label">Фильтры по колонкам таблицы</h1>
  339. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
  340. </div>
  341. <div class="modal-body">
  342. <form class="filters">
  343. @if(isset($filters) && is_array($filters))
  344. @foreach($filters as $filterName => $filter)
  345. @php $filter['values'] = ['' => ''] + $filter['values'] @endphp
  346. @include('partials.select', [
  347. 'name' => 'filters[' . $filterName . ']',
  348. 'title' => $filter['title'],
  349. 'options' => $filter['values'],
  350. 'value' => request()->filters[$filterName] ?? '',
  351. ])
  352. @endforeach
  353. @endif
  354. @if(isset($ranges) && is_array($ranges))
  355. @foreach($ranges as $rangeName => $range)
  356. @include('partials.input', [
  357. 'name' => 'filters[' . $rangeName . '_from]',
  358. 'type' => 'number',
  359. 'title' => $range['title'] . ' с:',
  360. 'min' => $range['min'],
  361. 'max' => $range['max'],
  362. 'value' => request()->filters[$rangeName . '_from'] ?? '', // $range['min']
  363. ])
  364. @include('partials.input', [
  365. 'name' => 'filters[' . $rangeName . '_to]',
  366. 'type' => 'number',
  367. 'title' => ' по:',
  368. 'min' => $range['min'],
  369. 'max' => $range['max'],
  370. 'value' => request()->filters[$rangeName . '_to'] ?? '', // $range['max']
  371. ])
  372. @endforeach
  373. @endif
  374. @if(isset($dates) && is_array($dates))
  375. @foreach($dates as $rangeName => $range)
  376. @include('partials.input', [
  377. 'name' => 'filters[' . $rangeName . '_from]',
  378. 'type' => 'date',
  379. 'title' => $range['title'] . ' с:',
  380. 'min' => $range['min'],
  381. 'max' => $range['max'],
  382. 'value' => request()->filters[$rangeName . '_from'] ?? '',
  383. ])
  384. @include('partials.input', [
  385. 'name' => 'filters[' . $rangeName . '_to]',
  386. 'type' => 'date',
  387. 'title' => $range['title'] . ' по:',
  388. 'min' => $range['min'],
  389. 'max' => $range['max'],
  390. 'value' => request()->filters[$rangeName . '_to'] ?? '',
  391. ])
  392. @endforeach
  393. @endif
  394. </form>
  395. </div>
  396. <div class="modal-footer">
  397. <button type="button" class="btn btn-primary accept-filters" data-bs-dismiss="modal">Применить</button>
  398. <button type="button" class="btn btn-outline-secondary reset-filters" data-bs-dismiss="modal">Сбросить
  399. </button>
  400. </div>
  401. </div>
  402. </div>
  403. </div>
  404. <!-- Модальное окно поиска -->
  405. <div class="modal fade" id="table_{{ $id }}_modal_search" tabindex="-1" aria-labelledby="table_{{ $id }}_modal_search_label"
  406. aria-hidden="true">
  407. <div class="modal-dialog modal-fullscreen-sm-down modal-lg">
  408. <div class="modal-content">
  409. <div class="modal-header">
  410. <h1 class="modal-title fs-5" id="table_{{ $id }}_modal_search_label">Поиск</h1>
  411. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
  412. </div>
  413. <div class="modal-body">
  414. <div>
  415. Поиск ведётся по следующим колонкам:
  416. <span class="fst-italic">
  417. @foreach($searchFields as $searchField)
  418. {{ $header[$searchField] ?? $searchField }}
  419. @if(!$loop->last)
  420. ,
  421. @endif
  422. @endforeach
  423. </span>
  424. </div>
  425. <form class="search-form">
  426. @include('partials.input', [
  427. 'name' => 's',
  428. 'title' => 'Поиск',
  429. 'placeholder' => 'что ищем?',
  430. 'value' => request()->s ?? '',
  431. ])
  432. </form>
  433. </div>
  434. <div class="modal-footer">
  435. <button type="button" class="btn btn-primary accept-search" data-bs-dismiss="modal">Найти</button>
  436. <button type="button" class="btn btn-outline-secondary reset-search" data-bs-dismiss="modal">Сбросить
  437. </button>
  438. </div>
  439. </div>
  440. </div>
  441. </div>
  442. @push('scripts')
  443. <script type="module">
  444. // Ждём загрузки jQuery через Vite
  445. function waitForJQuery(callback) {
  446. if (typeof window.$ !== 'undefined') {
  447. callback();
  448. } else {
  449. setTimeout(() => waitForJQuery(callback), 50);
  450. }
  451. }
  452. waitForJQuery(function () {
  453. // on page load set column visible
  454. let tbl = $('#tbl');
  455. let tableName = tbl.attr('data-table-name');
  456. let tables = JSON.parse(localStorage.getItem('table_' + tableName));
  457. // on first load create tables object
  458. if (!tables) {
  459. tables = {};
  460. }
  461. // hide disabled columns
  462. $.each(tables, function (colName, colStatus) {
  463. if (!colStatus) {
  464. $('.checkbox-' + colName).attr('checked', false);
  465. $('.column_' + colName).hide();
  466. }
  467. });
  468. // highlight search text
  469. let searchText = $('.search-form input').val();
  470. if (searchText !== '') {
  471. let innerHTML = tbl.html();
  472. let index = innerHTML.indexOf(searchText);
  473. if (index >= 0) {
  474. innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + searchText.length) + "</span>" + innerHTML.substring(index + searchText.length);
  475. tbl.html(innerHTML);
  476. }
  477. }
  478. $('.table').fadeIn();
  479. function isRowActionTarget(target) {
  480. return $(target).closest('a, button, input, select, textarea, label, .dropdown, [data-bs-toggle], [data-no-row-select]').length > 0;
  481. }
  482. function openRow($row, newTab = false) {
  483. const href = $row.data('row-href');
  484. if (!href) {
  485. return;
  486. }
  487. selectRow($row, false);
  488. if (newTab) {
  489. window.open(href, '_blank');
  490. } else {
  491. window.location.href = href;
  492. }
  493. }
  494. function selectRow($row, updateHash = true) {
  495. if (!$row || !$row.length) {
  496. return;
  497. }
  498. $row.closest('tbody').find('tr.is-selected').removeClass('is-selected');
  499. $row.addClass('is-selected');
  500. if (updateHash) {
  501. const rowId = $row.data('row-id');
  502. if (rowId) {
  503. const hash = '#row-' + rowId;
  504. const newUrl = window.location.pathname + window.location.search + hash;
  505. history.replaceState(null, '', newUrl);
  506. if (tableName) {
  507. localStorage.setItem('table_last_row_' + tableName, String(rowId));
  508. }
  509. }
  510. }
  511. }
  512. $(document).on('click', '.table-interactive tbody tr', function (e) {
  513. if (isRowActionTarget(e.target)) {
  514. return;
  515. }
  516. const $row = $(this);
  517. // На десктопах с Ctrl открываем в новой вкладке сразу по одиночному клику
  518. const isTouchDevice = window.matchMedia('(pointer: coarse)').matches || ('ontouchstart' in window);
  519. if (!isTouchDevice && (e.ctrlKey || e.metaKey)) {
  520. openRow($row, true);
  521. return;
  522. }
  523. selectRow($row);
  524. // На мобильных dblclick часто не срабатывает, поэтому поддерживаем двойной тап.
  525. if (!isTouchDevice) {
  526. return;
  527. }
  528. const now = Date.now();
  529. const rowKey = String($row.data('row-id') ?? $row.data('row-href') ?? '');
  530. const lastTapAt = Number($row.data('last-tap-at') ?? 0);
  531. const lastTapKey = String($row.data('last-tap-key') ?? '');
  532. if (lastTapAt && (now - lastTapAt) < 450 && rowKey && lastTapKey === rowKey) {
  533. openRow($row);
  534. $row.removeData('last-tap-at').removeData('last-tap-key');
  535. return;
  536. }
  537. $row.data('last-tap-at', now);
  538. $row.data('last-tap-key', rowKey);
  539. });
  540. $(document).on('dblclick', '.table-interactive tbody tr', function (e) {
  541. if (isRowActionTarget(e.target)) {
  542. return;
  543. }
  544. openRow($(this), e.ctrlKey || e.metaKey);
  545. });
  546. $('.toggle-column').on('change', function () {
  547. let columnName = $(this).attr('data-name');
  548. let columnStatus = $(this).is(':checked');
  549. // save column status
  550. tables[columnName] = columnStatus;
  551. localStorage.setItem('table_' + tableName, JSON.stringify(tables));
  552. // show or hide column
  553. if (columnStatus) {
  554. $('.column_' + columnName).show('fast');
  555. } else {
  556. $('.column_' + columnName).hide('fast');
  557. }
  558. });
  559. $('.sort-by-column').on('click', function () {
  560. let columnName = $(this).attr('data-name');
  561. let currentUrl = new URL(document.location.href);
  562. let currentColumnName = currentUrl.searchParams.get('sortBy');
  563. currentUrl.searchParams.set('sortBy', columnName);
  564. if ((currentColumnName !== columnName) || (currentUrl.searchParams.has('order'))) {
  565. currentUrl.searchParams.delete('order');
  566. } else {
  567. currentUrl.searchParams.set('order', 'desc');
  568. }
  569. document.location.href = currentUrl.href;
  570. });
  571. $('.accept-filters').on('click', function () {
  572. let filters = $('.filters').serializeArray();
  573. let currentUrl = new URL(document.location.href);
  574. $.each(filters, function (id, filter) {
  575. if (filter.value !== '') {
  576. currentUrl.searchParams.set(filter.name, filter.value);
  577. } else {
  578. currentUrl.searchParams.delete(filter.name);
  579. }
  580. });
  581. currentUrl.searchParams.delete('page');
  582. document.location.href = currentUrl.href;
  583. });
  584. $('.reset-filters').on('click', function () {
  585. let filters = $('.filters').serializeArray();
  586. let currentUrl = new URL(document.location.href);
  587. $.each(filters, function (id, filter) {
  588. currentUrl.searchParams.delete(filter.name);
  589. });
  590. currentUrl.searchParams.delete('page');
  591. document.location.href = currentUrl.href;
  592. });
  593. $('.accept-search').on('click', function () {
  594. let s = $('.search-form input').val();
  595. let currentUrl = new URL(document.location.href);
  596. if (s !== '') {
  597. currentUrl.searchParams.set('s', s);
  598. } else {
  599. currentUrl.searchParams.delete('s');
  600. }
  601. currentUrl.searchParams.delete('page');
  602. document.location.href = currentUrl.href;
  603. });
  604. $('.reset-search').on('click', function () {
  605. let currentUrl = new URL(document.location.href);
  606. currentUrl.searchParams.delete('s');
  607. currentUrl.searchParams.delete('page');
  608. document.location.href = currentUrl.href;
  609. });
  610. $('.change-order-status').on('focus', function () {
  611. $(this).data('previous-value', $(this).val());
  612. });
  613. $('.change-order-status').on('change', function () {
  614. let $select = $(this);
  615. let orderStatusId = $select.val();
  616. let orderId = $select.attr('data-order-id');
  617. let previousValue = $select.data('previous-value');
  618. $.post(
  619. '{{ route('order.update') }}',
  620. {
  621. '_token' : '{{ csrf_token() }}',
  622. id: orderId,
  623. order_status_id: orderStatusId
  624. },
  625. function () {
  626. $select.data('previous-value', orderStatusId);
  627. $('.alerts').append(
  628. '<div class="main-alert alert alert-success" role="alert">Обновлён статус площадки!</div>'
  629. );
  630. setTimeout(function () {
  631. $('.main-alert').fadeTo(2000, 500).slideUp(500, function () {
  632. $(".main-alert").slideUp(500);
  633. })
  634. }, 3000);
  635. }
  636. ).fail(function (xhr) {
  637. if (previousValue !== undefined) {
  638. $select.val(previousValue);
  639. }
  640. let errorText = xhr.responseJSON?.message || 'Не удалось обновить статус площадки!';
  641. $('.alerts').append(
  642. '<div class="main-alert alert alert-danger" role="alert">' + errorText + '</div>'
  643. );
  644. setTimeout(function () {
  645. $('.main-alert').fadeTo(2000, 500).slideUp(500, function () {
  646. $(".main-alert").slideUp(500);
  647. })
  648. }, 3000);
  649. });
  650. });
  651. $('.change-reclamation-status').on('change', function () {
  652. let statusId = $(this).val();
  653. let url = $(this).attr('data-url');
  654. $.post(
  655. url,
  656. {
  657. '_token' : '{{ csrf_token() }}',
  658. status_id: statusId
  659. },
  660. function () {
  661. $('.alerts').append(
  662. '<div class="main-alert alert alert-success" role="alert">Обновлён статус рекламации!</div>'
  663. );
  664. setTimeout(function () {
  665. $('.main-alert').fadeTo(2000, 500).slideUp(500, function () {
  666. $(".main-alert").slideUp(500);
  667. })
  668. }, 3000);
  669. }
  670. );
  671. });
  672. $('.inline-product-sku-field').on('focus', function () {
  673. $(this).data('previous-value', $(this).val());
  674. });
  675. $('.inline-product-sku-field').on('blur', function () {
  676. let $input = $(this);
  677. let value = $input.val();
  678. let previousValue = $input.data('previous-value');
  679. if (value === previousValue) {
  680. return;
  681. }
  682. $input.prop('disabled', true);
  683. $.post(
  684. $input.attr('data-url'),
  685. {
  686. '_token' : '{{ csrf_token() }}',
  687. field: $input.attr('data-field'),
  688. value: value
  689. },
  690. function (response) {
  691. $input.data('previous-value', response.value ?? '');
  692. $input.val(response.value ?? '');
  693. $('.alerts').append(
  694. '<div class="main-alert alert alert-success" role="alert">Поле МАФ обновлено!</div>'
  695. );
  696. setTimeout(function () {
  697. $('.main-alert').fadeTo(2000, 500).slideUp(500, function () {
  698. $(".main-alert").slideUp(500);
  699. })
  700. }, 3000);
  701. }
  702. ).fail(function (xhr) {
  703. if (previousValue !== undefined) {
  704. $input.val(previousValue);
  705. }
  706. let errorText = xhr.responseJSON?.message || 'Не удалось обновить поле МАФ!';
  707. $('.alerts').append(
  708. '<div class="main-alert alert alert-danger" role="alert">' + errorText + '</div>'
  709. );
  710. setTimeout(function () {
  711. $('.main-alert').fadeTo(2000, 500).slideUp(500, function () {
  712. $(".main-alert").slideUp(500);
  713. })
  714. }, 3000);
  715. }).always(function () {
  716. $input.prop('disabled', false);
  717. });
  718. });
  719. function updateMainTableScrollHeight() {
  720. const tableScrollElement = document.querySelector('.js-main-table-scroll');
  721. if (!tableScrollElement) {
  722. return;
  723. }
  724. const tableTop = tableScrollElement.getBoundingClientRect().top;
  725. const bottomGap = 16;
  726. let paginationHeight = 0;
  727. const paginationRow = document.querySelector('.pagination')?.closest('.row');
  728. if (paginationRow) {
  729. paginationHeight = paginationRow.getBoundingClientRect().height + 8;
  730. }
  731. const maxHeight = Math.max(180, window.innerHeight - tableTop - paginationHeight - bottomGap);
  732. tableScrollElement.style.maxHeight = maxHeight + 'px';
  733. }
  734. $(document).ready(function () {
  735. updateMainTableScrollHeight();
  736. window.addEventListener('resize', updateMainTableScrollHeight);
  737. // Инициализация tooltips для полей tsn_number и pricing_code
  738. const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
  739. const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
  740. const hash = window.location.hash;
  741. if (hash && hash.startsWith('#row-')) {
  742. const $row = $(hash);
  743. if ($row.length) {
  744. selectRow($row, false);
  745. $row[0].scrollIntoView({block: 'center'});
  746. const rowId = $row.data('row-id');
  747. if (rowId && tableName) {
  748. localStorage.setItem('table_last_row_' + tableName, String(rowId));
  749. }
  750. return;
  751. }
  752. }
  753. if (tableName) {
  754. const storedRowId = localStorage.getItem('table_last_row_' + tableName);
  755. if (storedRowId) {
  756. const $storedRow = $('#row-' + storedRowId);
  757. if ($storedRow.length) {
  758. selectRow($storedRow, false);
  759. $storedRow[0].scrollIntoView({block: 'center'});
  760. }
  761. }
  762. }
  763. });
  764. }); // end waitForJQuery
  765. </script>
  766. @endpush