table.blade.php 43 KB

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