ScheduleController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. // create all records in schedule
  142. $order = Order::query()
  143. ->where('id', $validated['order_id'])
  144. ->first();
  145. $errors = [];
  146. if(!$order->brigadier_id) $errors[] = 'Не указан бригадир!';
  147. if(!$order->installation_date) $errors[] = 'Не указана дата монтажа!';
  148. if(!$order->install_days) $errors[] = 'Не указан срок монтажа!';
  149. $errors = array_merge($errors, $order->getMountStatusErrors());
  150. if($errors) {
  151. return redirect()->route('order.show', $order->id)->with(['danger' => $errors]);
  152. }
  153. // delete all auto schedules for this order
  154. if(isset($validated['delete_old_records'])) {
  155. Schedule::query()
  156. ->where('order_id', $validated['order_id'])
  157. ->where('source', 'Площадки')
  158. ->where('manual', false)
  159. ->delete();
  160. }
  161. if(empty($validated['skus'])) {
  162. foreach ($order->products_sku as $psku)
  163. $validated['skus'][] = $psku->id;
  164. }
  165. $mafs = [];
  166. foreach ($validated['skus'] as $skuId) {
  167. $sku = ProductSKU::query()->where('id', $skuId)->first();
  168. if(!isset($mafs[$sku->product->article])) {
  169. $mafs[$sku->product->article] = 1;
  170. } else {
  171. $mafs[$sku->product->article] += 1;
  172. }
  173. }
  174. $mafsText = '';
  175. $mafsCount = 0;
  176. foreach ($mafs as $article => $count) {
  177. $mafsText .= $article . ' - ' . $count . "\r\n";
  178. $mafsCount += $count;
  179. }
  180. $first = true;
  181. for ($iDays = 1; $iDays < $order->install_days + 1; $iDays++) {
  182. $instDate = date('Y-m-d', strtotime('+' . $iDays - 1 . ' days', strtotime($order->installation_date)));
  183. $schedule = Schedule::query()
  184. ->create([
  185. 'order_id' => $validated['order_id'],
  186. 'address_code' => $validated['order_id'],
  187. 'source' => 'Площадки',
  188. 'installation_date' => $instDate,
  189. 'manual' => false,
  190. 'district_id' => $order->district_id,
  191. 'area_id' => $order->area_id,
  192. 'object_address' => $order->object_address,
  193. 'object_type' => $order->objectType->name,
  194. 'mafs' => $mafsText,
  195. 'mafs_count' => $mafsCount,
  196. 'brigadier_id' => $order->brigadier_id,
  197. 'comment' => $validated['comment'] ?? null,
  198. ]);
  199. if($first && isset($validated['send_notifications'])) {
  200. $first = false;
  201. $notificationService->notifyScheduleAdded($schedule->fresh(['brigadier']), auth()->user());
  202. }
  203. }
  204. return redirect()->route('schedule.index');
  205. }
  206. public function createFromReclamation(CreateScheduleFromReclamationRequest $request, NotificationService $notificationService)
  207. {
  208. $validated = $request->validated();
  209. // delete all auto schedules for this order
  210. if(isset($validated['delete_old_records'])) {
  211. Schedule::query()
  212. ->where('address_code', 'РЕКЛ-' . $validated['reclamation_id'])
  213. ->where('source', 'Рекламации')
  214. ->where('manual', false)
  215. ->delete();
  216. }
  217. $reclamation = Reclamation::query()
  218. ->where('id', $validated['reclamation_id'])
  219. ->first();
  220. $order = $reclamation->order;
  221. $scheduleComment = $this->buildScheduleCommentFromReclamation($reclamation);
  222. $mafs = [];
  223. if(empty($validated['skus'])) {
  224. foreach ($reclamation->skus as $sku)
  225. if(!isset($mafs[$sku->product->article])) {
  226. $mafs[$sku->product->article] = 1;
  227. } else {
  228. $mafs[$sku->product->article] += 1;
  229. }
  230. }
  231. $mafsCount = 0;
  232. $mafsText = '';
  233. foreach ($mafs as $article => $count) {
  234. $mafsCount += $count;
  235. $mafsText .= $article . ' - ' . $count . "\r\n";
  236. }
  237. $first = true;
  238. for ($iDays = 1; $iDays < $reclamation->work_days + 1; $iDays++) {
  239. $instDate = date('Y-m-d', strtotime('+' . $iDays - 1 . ' days', strtotime($reclamation->start_work_date)));
  240. $schedule = Schedule::query()
  241. ->create([
  242. 'order_id' => $order->id,
  243. 'address_code' => 'РЕКЛ-' . $validated['reclamation_id'],
  244. 'source' => 'Рекламации',
  245. 'installation_date' => $instDate,
  246. 'manual' => false,
  247. 'district_id' => $order->district_id,
  248. 'area_id' => $order->area_id,
  249. 'object_address' => $order->object_address,
  250. 'object_type' => $reclamation->reason,
  251. 'mafs' => $mafsText,
  252. 'mafs_count' => $mafsCount,
  253. 'brigadier_id' => $reclamation->brigadier_id,
  254. 'comment' => $scheduleComment,
  255. ]);
  256. if($first && isset($validated['send_notifications'])) {
  257. $first = false;
  258. $notificationService->notifyScheduleAdded($schedule->fresh(['brigadier']), auth()->user());
  259. }
  260. }
  261. return redirect()->route('schedule.index');
  262. }
  263. private function buildScheduleCommentFromReclamation(Reclamation $reclamation): string
  264. {
  265. $guarantee = trim((string) $reclamation->guarantee);
  266. $parts = $reclamation->sparePartReservations()
  267. ->whereIn('status', ['active', 'issued'])
  268. ->with(['sparePart:id,article', 'sparePartOrder:id,order_number'])
  269. ->orderBy('created_at')
  270. ->get()
  271. ->map(static function ($reservation): ?string {
  272. $article = trim((string) $reservation->sparePart?->article);
  273. if ($article === '') {
  274. return null;
  275. }
  276. $orderNumber = $reservation->sparePartOrder?->display_order_number ?? '-';
  277. return $article . ' - ' . $orderNumber;
  278. })
  279. ->filter()
  280. ->values();
  281. $lines = array_filter([
  282. $guarantee !== '' ? $guarantee : null,
  283. $parts->isNotEmpty()
  284. ? 'Используемые детали: ' . $parts->implode(', ') . '.'
  285. : null,
  286. ]);
  287. return implode(PHP_EOL, $lines);
  288. }
  289. public function update(UpdateScheduleRequest $request, NotificationService $notificationService)
  290. {
  291. $validated = $request->validated();
  292. if(isset($validated['id'])) {
  293. Schedule::query()
  294. ->where('id', $validated['id'])
  295. ->update($validated);
  296. $schedule = Schedule::query()->find($validated['id']);
  297. } else {
  298. $schedule = Schedule::query()
  299. ->create([
  300. 'address_code' => $validated['address_code'] ?? '-',
  301. 'installation_date' => $validated['installation_date'],
  302. 'manual' => true,
  303. 'district_id' => $validated['district_id'],
  304. 'area_id' => $validated['area_id'],
  305. 'object_address' => $validated['object_address'],
  306. 'object_type' => $validated['object_type'],
  307. 'mafs' => $validated['mafs'],
  308. 'mafs_count' => $validated['mafs_count'],
  309. 'brigadier_id' => $validated['brigadier_id'],
  310. 'comment' => $validated['comment'],
  311. 'transport' => $validated['transport'] ?? null,
  312. 'admin_comment' => $validated['admin_comment'] ?? null,
  313. ]);
  314. $notificationService->notifyScheduleAdded($schedule->fresh(['brigadier']), auth()->user());
  315. }
  316. return redirect()->back();
  317. }
  318. public function delete(Schedule $schedule)
  319. {
  320. $schedule->delete();
  321. return redirect()->back();
  322. }
  323. public function export(ExportScheduleRequest $request)
  324. {
  325. $startDate = $request->validated()['start_date'];
  326. $endDate = $request->validated()['end_date'];
  327. $schedules = Schedule::query()
  328. ->where('installation_date', '>=', $startDate)
  329. ->where('installation_date', '<=', $endDate)
  330. ->orderBy('installation_date')
  331. ->orderBy('brigadier_id')
  332. ->get();
  333. ExportScheduleJob::dispatch($schedules, $request->user()->id);
  334. return redirect()->route('schedule.index', [
  335. 'week' => (int) $request->validated()['week'],
  336. 'year' => (int) $request->input('year', date('Y')),
  337. ])
  338. ->with(['success' => 'Задача генерации графика создана!']);
  339. }
  340. private function filterSchedulesForCurrentUser(Collection $schedules): Collection
  341. {
  342. if (!hasRole(Role::BRIGADIER)) {
  343. return $schedules;
  344. }
  345. $brigadierSchedules = $schedules
  346. ->where('brigadier_id', auth()->id())
  347. ->values();
  348. if ($brigadierSchedules->isEmpty()) {
  349. return $brigadierSchedules;
  350. }
  351. $visibleOrderIds = Order::query()
  352. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  353. ->whereIn('id', $brigadierSchedules->pluck('order_id')->filter()->unique()->all())
  354. ->where('brigadier_id', auth()->id())
  355. ->whereIn('order_status_id', Order::visibleStatusIdsForBrigadier())
  356. ->pluck('id')
  357. ->all();
  358. $reclamationIds = $brigadierSchedules
  359. ->filter(fn (Schedule $schedule) => $schedule->source === 'Рекламации')
  360. ->map(fn (Schedule $schedule) => $this->extractReclamationId((string)$schedule->address_code))
  361. ->filter()
  362. ->unique()
  363. ->values();
  364. $visibleReclamationIds = Reclamation::query()
  365. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  366. ->whereIn('id', $reclamationIds->all())
  367. ->where('brigadier_id', auth()->id())
  368. ->whereIn('status_id', Reclamation::visibleStatusIdsForBrigadier())
  369. ->pluck('id')
  370. ->all();
  371. return $brigadierSchedules
  372. ->filter(function (Schedule $schedule) use ($visibleOrderIds, $visibleReclamationIds) {
  373. if ($schedule->source === 'Площадки') {
  374. return in_array((int)$schedule->order_id, $visibleOrderIds, true);
  375. }
  376. if ($schedule->source === 'Рекламации') {
  377. return in_array($this->extractReclamationId((string)$schedule->address_code), $visibleReclamationIds, true);
  378. }
  379. return true;
  380. })
  381. ->values();
  382. }
  383. private function buildScheduleStatusMap($schedules): array
  384. {
  385. $statusMap = [];
  386. $orderIds = [];
  387. $reclamationScheduleIds = [];
  388. foreach ($schedules as $schedule) {
  389. $statusMap[$schedule->id] = [
  390. 'name' => '-',
  391. 'color' => 'secondary',
  392. ];
  393. if ($schedule->source === 'Площадки' && $schedule->order_id) {
  394. $orderIds[] = (int)$schedule->order_id;
  395. continue;
  396. }
  397. if ($schedule->source === 'Рекламации') {
  398. $reclamationId = $this->extractReclamationId((string)$schedule->address_code);
  399. if ($reclamationId) {
  400. $reclamationScheduleIds[$reclamationId][] = $schedule->id;
  401. }
  402. }
  403. }
  404. if ($orderIds) {
  405. $orderStatuses = Order::query()
  406. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  407. ->whereIn('id', array_unique($orderIds))
  408. ->pluck('order_status_id', 'id')
  409. ->all();
  410. foreach ($schedules as $schedule) {
  411. if ($schedule->source !== 'Площадки' || !$schedule->order_id) {
  412. continue;
  413. }
  414. $statusId = $orderStatuses[(int)$schedule->order_id] ?? null;
  415. if ($statusId) {
  416. $statusMap[$schedule->id] = [
  417. 'name' => Order::STATUS_NAMES[$statusId] ?? '-',
  418. 'color' => Order::STATUS_COLOR[$statusId] ?: 'secondary',
  419. ];
  420. }
  421. }
  422. }
  423. if ($reclamationScheduleIds) {
  424. $reclamationStatuses = Reclamation::query()
  425. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  426. ->whereIn('id', array_keys($reclamationScheduleIds))
  427. ->pluck('status_id', 'id')
  428. ->all();
  429. foreach ($reclamationScheduleIds as $reclamationId => $scheduleIds) {
  430. $statusId = $reclamationStatuses[$reclamationId] ?? null;
  431. $statusName = $statusId ? (Reclamation::STATUS_NAMES[$statusId] ?? '-') : '-';
  432. $statusColor = $statusId ? (ReclamationStatus::STATUS_COLOR[$statusId] ?? 'secondary') : 'secondary';
  433. foreach ($scheduleIds as $scheduleId) {
  434. $statusMap[$scheduleId] = [
  435. 'name' => $statusName,
  436. 'color' => $statusColor,
  437. ];
  438. }
  439. }
  440. }
  441. return $statusMap;
  442. }
  443. private function extractReclamationId(string $addressCode): ?int
  444. {
  445. if (preg_match('/^РЕКЛ-(\d+)$/u', $addressCode, $matches)) {
  446. return (int)$matches[1];
  447. }
  448. return null;
  449. }
  450. }