ScheduleController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Helpers\DateHelper;
  4. use App\Http\Requests\CreateScheduleFromOrderRequest;
  5. use App\Http\Requests\CreateScheduleFromReclamationRequest;
  6. use App\Http\Requests\ExportScheduleRequest;
  7. use App\Http\Requests\UpdateScheduleRequest;
  8. use App\Jobs\ExportScheduleJob;
  9. use App\Models\Dictionary\Area;
  10. use App\Models\Dictionary\District;
  11. use App\Models\Order;
  12. use App\Models\ProductSKU;
  13. use App\Models\Reclamation;
  14. use App\Models\ReclamationStatus;
  15. use App\Models\Role;
  16. use App\Models\Schedule;
  17. use App\Models\User;
  18. use App\Services\NotificationService;
  19. use Illuminate\Database\Eloquent\Builder;
  20. use Illuminate\Support\Collection;
  21. use Illuminate\Http\Request;
  22. use Illuminate\Support\Carbon;
  23. class ScheduleController extends Controller
  24. {
  25. protected array $data = [
  26. 'active' => 'schedule',
  27. 'title' => 'График монтажей',
  28. 'id' => 'schedule',
  29. ];
  30. public function index(Request $request)
  31. {
  32. $this->data['districts'] = District::query()->get()->pluck('name', 'id');
  33. $this->data['areas'] = Area::query()->get()->pluck('name', 'id');
  34. $this->data['brigadiers'] = User::query()
  35. ->where('role', Role::BRIGADIER)
  36. ->when(hasRole(Role::BRIGADIER), fn (Builder $query) => $query->whereKey(auth()->id()))
  37. ->get()
  38. ->pluck('name', 'id');
  39. $this->data['scheduleYear'] = (int)$request->get('year', date('Y'));
  40. if ($this->data['scheduleYear'] < 2000 || $this->data['scheduleYear'] > 2100) {
  41. $this->data['scheduleYear'] = (int)date('Y');
  42. }
  43. $tab = $request->get('tab', 'week');
  44. $this->data['activeTab'] = in_array($tab, ['week', 'month'], true) ? $tab : 'week';
  45. $this->data['weekNumber'] = $request->get('week' ,date('W'));
  46. $weekDates = [
  47. 'mon' => DateHelper::getDateOfWeek($this->data['scheduleYear'], $this->data['weekNumber']),
  48. 'tue' => DateHelper::getDateOfWeek($this->data['scheduleYear'], $this->data['weekNumber'], 2),
  49. 'wed' => DateHelper::getDateOfWeek($this->data['scheduleYear'], $this->data['weekNumber'], 3),
  50. 'thu' => DateHelper::getDateOfWeek($this->data['scheduleYear'], $this->data['weekNumber'], 4),
  51. 'fri' => DateHelper::getDateOfWeek($this->data['scheduleYear'], $this->data['weekNumber'], 5),
  52. 'sat' => DateHelper::getDateOfWeek($this->data['scheduleYear'], $this->data['weekNumber'], 6),
  53. 'sun' => DateHelper::getDateOfWeek($this->data['scheduleYear'], $this->data['weekNumber'], 7),
  54. ];
  55. $this->data['weekDates'] = $weekDates;
  56. $schedules = [];
  57. foreach ($weekDates as $date) {
  58. $schedules[$date] = null;
  59. }
  60. $result = Schedule::query()
  61. ->whereBetween('installation_date', [$weekDates['mon'], $weekDates['sun']])
  62. ->when(hasRole(Role::BRIGADIER), fn (Builder $query) => $query->where('brigadier_id', auth()->id()))
  63. ->with(['brigadier', 'district', 'area'])
  64. ->get();
  65. $result = $this->filterSchedulesForCurrentUser($result);
  66. $this->data['scheduleStatusMap'] = $this->buildScheduleStatusMap($result);
  67. foreach ($result as $schedule) {
  68. $schedules[$schedule->installation_date][] = $schedule;
  69. }
  70. $this->data['schedules'] = $schedules;
  71. $monthParam = $request->get('month');
  72. $monthNumber = (int)date('m');
  73. if (is_string($monthParam)) {
  74. if (preg_match('/^(0[1-9]|1[0-2])$/', $monthParam)) {
  75. $monthNumber = (int)$monthParam;
  76. } elseif (preg_match('/^(\\d{4})-(0[1-9]|1[0-2])$/', $monthParam, $matches)) {
  77. $this->data['scheduleYear'] = (int)$matches[1];
  78. $monthNumber = (int)$matches[2];
  79. }
  80. }
  81. $monthStart = Carbon::createFromDate($this->data['scheduleYear'], $monthNumber, 1)->startOfMonth();
  82. $monthEnd = $monthStart->copy()->endOfMonth();
  83. $gridStart = $monthStart->copy()->startOfWeek(Carbon::MONDAY);
  84. $gridEnd = $monthEnd->copy()->endOfWeek(Carbon::SUNDAY);
  85. $cursor = $gridStart->copy();
  86. $monthDays = [];
  87. while ($cursor->lte($gridEnd)) {
  88. $monthDays[] = [
  89. 'date' => $cursor->toDateString(),
  90. 'day' => (int)$cursor->format('j'),
  91. 'week' => (int)$cursor->isoWeek(),
  92. 'weekYear' => (int)$cursor->isoWeekYear(),
  93. 'inMonth' => $cursor->month === $monthStart->month,
  94. 'isToday' => $cursor->isToday(),
  95. ];
  96. $cursor->addDay();
  97. }
  98. $monthSchedules = Schedule::query()
  99. ->whereBetween('installation_date', [$monthStart->toDateString(), $monthEnd->toDateString()])
  100. ->when(hasRole(Role::BRIGADIER), fn (Builder $query) => $query->where('brigadier_id', auth()->id()))
  101. ->with(['brigadier'])
  102. ->get();
  103. $monthSchedules = $this->filterSchedulesForCurrentUser($monthSchedules);
  104. $monthScheduleColors = [];
  105. $monthBrigadierLegend = [];
  106. foreach ($monthSchedules as $schedule) {
  107. $date = $schedule->installation_date;
  108. $brigadierId = $schedule->brigadier_id ?? 0;
  109. if (!isset($monthScheduleColors[$date])) {
  110. $monthScheduleColors[$date] = [];
  111. }
  112. if (!isset($monthScheduleColors[$date][$brigadierId])) {
  113. $monthScheduleColors[$date][$brigadierId] = [
  114. 'color' => $schedule->brigadier?->color ?? '#cccccc',
  115. 'name' => $schedule->brigadier?->name ?? '',
  116. ];
  117. }
  118. if (!isset($monthBrigadierLegend[$brigadierId])) {
  119. $monthBrigadierLegend[$brigadierId] = [
  120. 'color' => $schedule->brigadier?->color ?? '#cccccc',
  121. 'name' => $schedule->brigadier?->name ?? '',
  122. ];
  123. }
  124. }
  125. foreach ($monthScheduleColors as $date => $colors) {
  126. $monthScheduleColors[$date] = array_values($colors);
  127. }
  128. $this->data['monthGrid'] = array_chunk($monthDays, 7);
  129. $this->data['monthLabel'] = $monthStart->isoFormat('MMMM YYYY');
  130. $this->data['monthNumber'] = $monthNumber;
  131. $this->data['monthPrev'] = $monthStart->copy()->subMonth()->format('Y-m');
  132. $this->data['monthNext'] = $monthStart->copy()->addMonth()->format('Y-m');
  133. $this->data['monthValue'] = $monthStart->format('Y-m');
  134. $this->data['monthScheduleColors'] = $monthScheduleColors;
  135. $this->data['monthBrigadierLegend'] = array_values($monthBrigadierLegend);
  136. return view('schedule.index', $this->data);
  137. }
  138. public function createFromOrder(CreateScheduleFromOrderRequest $request, NotificationService $notificationService)
  139. {
  140. $validated = $request->validated();
  141. // delete all auto schedules for this order
  142. if(isset($validated['delete_old_records'])) {
  143. Schedule::query()
  144. ->where('order_id', $validated['order_id'])
  145. ->where('source', 'Площадки')
  146. ->where('manual', false)
  147. ->delete();
  148. }
  149. // create all records in schedule
  150. $order = Order::query()
  151. ->where('id', $validated['order_id'])
  152. ->first();
  153. $errors = [];
  154. if(!$order->brigadier_id) $errors[] = 'Не указан бригадир!';
  155. if(!$order->installation_date) $errors[] = 'Не указана дата монтажа!';
  156. if(!$order->install_days) $errors[] = 'Не указан срок монтажа!';
  157. if($errors) {
  158. return redirect()->route('order.show', $order->id)->with(['danger' => $errors]);
  159. }
  160. if(empty($validated['skus'])) {
  161. foreach ($order->products_sku as $psku)
  162. $validated['skus'][] = $psku->id;
  163. }
  164. $mafs = [];
  165. foreach ($validated['skus'] as $skuId) {
  166. $sku = ProductSKU::query()->where('id', $skuId)->first();
  167. if(!isset($mafs[$sku->product->article])) {
  168. $mafs[$sku->product->article] = 1;
  169. } else {
  170. $mafs[$sku->product->article] += 1;
  171. }
  172. }
  173. $mafsText = '';
  174. $mafsCount = 0;
  175. foreach ($mafs as $article => $count) {
  176. $mafsText .= $article . ' - ' . $count . "\r\n";
  177. $mafsCount += $count;
  178. }
  179. $first = true;
  180. for ($iDays = 1; $iDays < $order->install_days + 1; $iDays++) {
  181. $instDate = date('Y-m-d', strtotime('+' . $iDays - 1 . ' days', strtotime($order->installation_date)));
  182. $schedule = Schedule::query()
  183. ->create([
  184. 'order_id' => $validated['order_id'],
  185. 'address_code' => $validated['order_id'],
  186. 'source' => 'Площадки',
  187. 'installation_date' => $instDate,
  188. 'manual' => false,
  189. 'district_id' => $order->district_id,
  190. 'area_id' => $order->area_id,
  191. 'object_address' => $order->object_address,
  192. 'object_type' => $order->objectType->name,
  193. 'mafs' => $mafsText,
  194. 'mafs_count' => $mafsCount,
  195. 'brigadier_id' => $order->brigadier_id,
  196. 'comment' => $validated['comment'],
  197. ]);
  198. if($first && isset($validated['send_notifications'])) {
  199. $first = false;
  200. $notificationService->notifyScheduleAdded($schedule->fresh(['brigadier']), auth()->user());
  201. }
  202. }
  203. return redirect()->route('schedule.index');
  204. }
  205. public function createFromReclamation(CreateScheduleFromReclamationRequest $request, NotificationService $notificationService)
  206. {
  207. $validated = $request->validated();
  208. // delete all auto schedules for this order
  209. if(isset($validated['delete_old_records'])) {
  210. Schedule::query()
  211. ->where('address_code', 'РЕКЛ-' . $validated['reclamation_id'])
  212. ->where('source', 'Рекламации')
  213. ->where('manual', false)
  214. ->delete();
  215. }
  216. $reclamation = Reclamation::query()
  217. ->where('id', $validated['reclamation_id'])
  218. ->first();
  219. $order = $reclamation->order;
  220. $scheduleComment = $this->buildScheduleCommentFromReclamation($reclamation);
  221. $mafs = [];
  222. if(empty($validated['skus'])) {
  223. foreach ($reclamation->skus as $sku)
  224. if(!isset($mafs[$sku->product->article])) {
  225. $mafs[$sku->product->article] = 1;
  226. } else {
  227. $mafs[$sku->product->article] += 1;
  228. }
  229. }
  230. $mafsCount = 0;
  231. $mafsText = '';
  232. foreach ($mafs as $article => $count) {
  233. $mafsCount += $count;
  234. $mafsText .= $article . ' - ' . $count . "\r\n";
  235. }
  236. $first = true;
  237. for ($iDays = 1; $iDays < $reclamation->work_days + 1; $iDays++) {
  238. $instDate = date('Y-m-d', strtotime('+' . $iDays - 1 . ' days', strtotime($reclamation->start_work_date)));
  239. $schedule = Schedule::query()
  240. ->create([
  241. 'order_id' => $order->id,
  242. 'address_code' => 'РЕКЛ-' . $validated['reclamation_id'],
  243. 'source' => 'Рекламации',
  244. 'installation_date' => $instDate,
  245. 'manual' => false,
  246. 'district_id' => $order->district_id,
  247. 'area_id' => $order->area_id,
  248. 'object_address' => $order->object_address,
  249. 'object_type' => $reclamation->reason,
  250. 'mafs' => $mafsText,
  251. 'mafs_count' => $mafsCount,
  252. 'brigadier_id' => $reclamation->brigadier_id,
  253. 'comment' => $scheduleComment,
  254. ]);
  255. if($first && isset($validated['send_notifications'])) {
  256. $first = false;
  257. $notificationService->notifyScheduleAdded($schedule->fresh(['brigadier']), auth()->user());
  258. }
  259. }
  260. return redirect()->route('schedule.index');
  261. }
  262. private function buildScheduleCommentFromReclamation(Reclamation $reclamation): string
  263. {
  264. $guarantee = trim((string) $reclamation->guarantee);
  265. $parts = $reclamation->sparePartReservations()
  266. ->whereIn('status', ['active', 'issued'])
  267. ->with(['sparePart:id,article', 'sparePartOrder:id,order_number'])
  268. ->orderBy('created_at')
  269. ->get()
  270. ->map(static function ($reservation): ?string {
  271. $article = trim((string) $reservation->sparePart?->article);
  272. if ($article === '') {
  273. return null;
  274. }
  275. $orderNumber = $reservation->sparePartOrder?->display_order_number ?? '-';
  276. return $article . ' - ' . $orderNumber;
  277. })
  278. ->filter()
  279. ->values();
  280. $lines = array_filter([
  281. $guarantee !== '' ? $guarantee : null,
  282. $parts->isNotEmpty()
  283. ? 'Используемые детали: ' . $parts->implode(', ') . '.'
  284. : null,
  285. ]);
  286. return implode(PHP_EOL, $lines);
  287. }
  288. public function update(UpdateScheduleRequest $request, NotificationService $notificationService)
  289. {
  290. $validated = $request->validated();
  291. if(isset($validated['id'])) {
  292. Schedule::query()
  293. ->where('id', $validated['id'])
  294. ->update($validated);
  295. $schedule = Schedule::query()->find($validated['id']);
  296. } else {
  297. $schedule = Schedule::query()
  298. ->create([
  299. 'address_code' => $validated['address_code'] ?? '-',
  300. 'installation_date' => $validated['installation_date'],
  301. 'manual' => true,
  302. 'district_id' => $validated['district_id'],
  303. 'area_id' => $validated['area_id'],
  304. 'object_address' => $validated['object_address'],
  305. 'object_type' => $validated['object_type'],
  306. 'mafs' => $validated['mafs'],
  307. 'mafs_count' => $validated['mafs_count'],
  308. 'brigadier_id' => $validated['brigadier_id'],
  309. 'comment' => $validated['comment'],
  310. 'transport' => $validated['transport'] ?? null,
  311. 'admin_comment' => $validated['admin_comment'] ?? null,
  312. ]);
  313. $notificationService->notifyScheduleAdded($schedule->fresh(['brigadier']), auth()->user());
  314. }
  315. return redirect()->back();
  316. }
  317. public function delete(Schedule $schedule)
  318. {
  319. $schedule->delete();
  320. return redirect()->back();
  321. }
  322. public function export(ExportScheduleRequest $request)
  323. {
  324. $startDate = $request->validated()['start_date'];
  325. $endDate = $request->validated()['end_date'];
  326. $schedules = Schedule::query()
  327. ->where('installation_date', '>=', $startDate)
  328. ->where('installation_date', '<=', $endDate)
  329. ->orderBy('installation_date')
  330. ->orderBy('brigadier_id')
  331. ->get();
  332. ExportScheduleJob::dispatch($schedules, $request->user()->id);
  333. return redirect()->route('schedule.index', [
  334. 'week' => (int) $request->validated()['week'],
  335. 'year' => (int) $request->input('year', date('Y')),
  336. ])
  337. ->with(['success' => 'Задача генерации графика создана!']);
  338. }
  339. private function filterSchedulesForCurrentUser(Collection $schedules): Collection
  340. {
  341. if (!hasRole(Role::BRIGADIER)) {
  342. return $schedules;
  343. }
  344. $brigadierSchedules = $schedules
  345. ->where('brigadier_id', auth()->id())
  346. ->values();
  347. if ($brigadierSchedules->isEmpty()) {
  348. return $brigadierSchedules;
  349. }
  350. $visibleOrderIds = Order::query()
  351. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  352. ->whereIn('id', $brigadierSchedules->pluck('order_id')->filter()->unique()->all())
  353. ->where('brigadier_id', auth()->id())
  354. ->whereIn('order_status_id', Order::visibleStatusIdsForBrigadier())
  355. ->pluck('id')
  356. ->all();
  357. $reclamationIds = $brigadierSchedules
  358. ->filter(fn (Schedule $schedule) => $schedule->source === 'Рекламации')
  359. ->map(fn (Schedule $schedule) => $this->extractReclamationId((string)$schedule->address_code))
  360. ->filter()
  361. ->unique()
  362. ->values();
  363. $visibleReclamationIds = Reclamation::query()
  364. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  365. ->whereIn('id', $reclamationIds->all())
  366. ->where('brigadier_id', auth()->id())
  367. ->whereIn('status_id', Reclamation::visibleStatusIdsForBrigadier())
  368. ->pluck('id')
  369. ->all();
  370. return $brigadierSchedules
  371. ->filter(function (Schedule $schedule) use ($visibleOrderIds, $visibleReclamationIds) {
  372. if ($schedule->source === 'Площадки') {
  373. return in_array((int)$schedule->order_id, $visibleOrderIds, true);
  374. }
  375. if ($schedule->source === 'Рекламации') {
  376. return in_array($this->extractReclamationId((string)$schedule->address_code), $visibleReclamationIds, true);
  377. }
  378. return true;
  379. })
  380. ->values();
  381. }
  382. private function buildScheduleStatusMap($schedules): array
  383. {
  384. $statusMap = [];
  385. $orderIds = [];
  386. $reclamationScheduleIds = [];
  387. foreach ($schedules as $schedule) {
  388. $statusMap[$schedule->id] = [
  389. 'name' => '-',
  390. 'color' => 'secondary',
  391. ];
  392. if ($schedule->source === 'Площадки' && $schedule->order_id) {
  393. $orderIds[] = (int)$schedule->order_id;
  394. continue;
  395. }
  396. if ($schedule->source === 'Рекламации') {
  397. $reclamationId = $this->extractReclamationId((string)$schedule->address_code);
  398. if ($reclamationId) {
  399. $reclamationScheduleIds[$reclamationId][] = $schedule->id;
  400. }
  401. }
  402. }
  403. if ($orderIds) {
  404. $orderStatuses = Order::query()
  405. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  406. ->whereIn('id', array_unique($orderIds))
  407. ->pluck('order_status_id', 'id')
  408. ->all();
  409. foreach ($schedules as $schedule) {
  410. if ($schedule->source !== 'Площадки' || !$schedule->order_id) {
  411. continue;
  412. }
  413. $statusId = $orderStatuses[(int)$schedule->order_id] ?? null;
  414. if ($statusId) {
  415. $statusMap[$schedule->id] = [
  416. 'name' => Order::STATUS_NAMES[$statusId] ?? '-',
  417. 'color' => Order::STATUS_COLOR[$statusId] ?: 'secondary',
  418. ];
  419. }
  420. }
  421. }
  422. if ($reclamationScheduleIds) {
  423. $reclamationStatuses = Reclamation::query()
  424. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  425. ->whereIn('id', array_keys($reclamationScheduleIds))
  426. ->pluck('status_id', 'id')
  427. ->all();
  428. foreach ($reclamationScheduleIds as $reclamationId => $scheduleIds) {
  429. $statusId = $reclamationStatuses[$reclamationId] ?? null;
  430. $statusName = $statusId ? (Reclamation::STATUS_NAMES[$statusId] ?? '-') : '-';
  431. $statusColor = $statusId ? (ReclamationStatus::STATUS_COLOR[$statusId] ?? 'secondary') : 'secondary';
  432. foreach ($scheduleIds as $scheduleId) {
  433. $statusMap[$scheduleId] = [
  434. 'name' => $statusName,
  435. 'color' => $statusColor,
  436. ];
  437. }
  438. }
  439. }
  440. return $statusMap;
  441. }
  442. private function extractReclamationId(string $addressCode): ?int
  443. {
  444. if (preg_match('/^РЕКЛ-(\d+)$/u', $addressCode, $matches)) {
  445. return (int)$matches[1];
  446. }
  447. return null;
  448. }
  449. }