ScheduleController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. $mafs = [];
  221. if(empty($validated['skus'])) {
  222. foreach ($reclamation->skus as $sku)
  223. if(!isset($mafs[$sku->product->article])) {
  224. $mafs[$sku->product->article] = 1;
  225. } else {
  226. $mafs[$sku->product->article] += 1;
  227. }
  228. }
  229. $mafsCount = 0;
  230. $mafsText = '';
  231. foreach ($mafs as $article => $count) {
  232. $mafsCount += $count;
  233. $mafsText .= $article . ' - ' . $count . "\r\n";
  234. }
  235. $first = true;
  236. for ($iDays = 1; $iDays < $reclamation->work_days + 1; $iDays++) {
  237. $instDate = date('Y-m-d', strtotime('+' . $iDays - 1 . ' days', strtotime($reclamation->start_work_date)));
  238. $schedule = Schedule::query()
  239. ->create([
  240. 'order_id' => $order->id,
  241. 'address_code' => 'РЕКЛ-' . $validated['reclamation_id'],
  242. 'source' => 'Рекламации',
  243. 'installation_date' => $instDate,
  244. 'manual' => false,
  245. 'district_id' => $order->district_id,
  246. 'area_id' => $order->area_id,
  247. 'object_address' => $order->object_address,
  248. 'object_type' => $reclamation->reason,
  249. 'mafs' => $mafsText,
  250. 'mafs_count' => $mafsCount,
  251. 'brigadier_id' => $reclamation->brigadier_id,
  252. 'comment' => $reclamation->guarantee,
  253. ]);
  254. if($first && isset($validated['send_notifications'])) {
  255. $first = false;
  256. $notificationService->notifyScheduleAdded($schedule->fresh(['brigadier']), auth()->user());
  257. }
  258. }
  259. return redirect()->route('schedule.index');
  260. }
  261. public function update(UpdateScheduleRequest $request, NotificationService $notificationService)
  262. {
  263. $validated = $request->validated();
  264. if(isset($validated['id'])) {
  265. Schedule::query()
  266. ->where('id', $validated['id'])
  267. ->update($validated);
  268. $schedule = Schedule::query()->find($validated['id']);
  269. } else {
  270. $schedule = Schedule::query()
  271. ->create([
  272. 'address_code' => $validated['address_code'] ?? '-',
  273. 'installation_date' => $validated['installation_date'],
  274. 'manual' => true,
  275. 'district_id' => $validated['district_id'],
  276. 'area_id' => $validated['area_id'],
  277. 'object_address' => $validated['object_address'],
  278. 'object_type' => $validated['object_type'],
  279. 'mafs' => $validated['mafs'],
  280. 'mafs_count' => $validated['mafs_count'],
  281. 'brigadier_id' => $validated['brigadier_id'],
  282. 'comment' => $validated['comment'],
  283. 'transport' => $validated['transport'] ?? null,
  284. 'admin_comment' => $validated['admin_comment'] ?? null,
  285. ]);
  286. $notificationService->notifyScheduleAdded($schedule->fresh(['brigadier']), auth()->user());
  287. }
  288. return redirect()->back();
  289. }
  290. public function delete(Schedule $schedule)
  291. {
  292. $schedule->delete();
  293. return redirect()->back();
  294. }
  295. public function export(ExportScheduleRequest $request)
  296. {
  297. $startDate = $request->validated()['start_date'];
  298. $endDate = $request->validated()['end_date'];
  299. $schedules = Schedule::query()
  300. ->where('installation_date', '>=', $startDate)
  301. ->where('installation_date', '<=', $endDate)
  302. ->orderBy('installation_date')
  303. ->orderBy('brigadier_id')
  304. ->get();
  305. ExportScheduleJob::dispatch($schedules, $request->user()->id);
  306. return redirect()->route('schedule.index', [
  307. 'week' => (int) $request->validated()['week'],
  308. 'year' => (int) $request->input('year', date('Y')),
  309. ])
  310. ->with(['success' => 'Задача генерации графика создана!']);
  311. }
  312. private function filterSchedulesForCurrentUser(Collection $schedules): Collection
  313. {
  314. if (!hasRole(Role::BRIGADIER)) {
  315. return $schedules;
  316. }
  317. $brigadierSchedules = $schedules
  318. ->where('brigadier_id', auth()->id())
  319. ->values();
  320. if ($brigadierSchedules->isEmpty()) {
  321. return $brigadierSchedules;
  322. }
  323. $visibleOrderIds = Order::query()
  324. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  325. ->whereIn('id', $brigadierSchedules->pluck('order_id')->filter()->unique()->all())
  326. ->where('brigadier_id', auth()->id())
  327. ->whereIn('order_status_id', Order::visibleStatusIdsForBrigadier())
  328. ->pluck('id')
  329. ->all();
  330. $reclamationIds = $brigadierSchedules
  331. ->filter(fn (Schedule $schedule) => $schedule->source === 'Рекламации')
  332. ->map(fn (Schedule $schedule) => $this->extractReclamationId((string)$schedule->address_code))
  333. ->filter()
  334. ->unique()
  335. ->values();
  336. $visibleReclamationIds = Reclamation::query()
  337. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  338. ->whereIn('id', $reclamationIds->all())
  339. ->where('brigadier_id', auth()->id())
  340. ->whereIn('status_id', Reclamation::visibleStatusIdsForBrigadier())
  341. ->pluck('id')
  342. ->all();
  343. return $brigadierSchedules
  344. ->filter(function (Schedule $schedule) use ($visibleOrderIds, $visibleReclamationIds) {
  345. if ($schedule->source === 'Площадки') {
  346. return in_array((int)$schedule->order_id, $visibleOrderIds, true);
  347. }
  348. if ($schedule->source === 'Рекламации') {
  349. return in_array($this->extractReclamationId((string)$schedule->address_code), $visibleReclamationIds, true);
  350. }
  351. return true;
  352. })
  353. ->values();
  354. }
  355. private function buildScheduleStatusMap($schedules): array
  356. {
  357. $statusMap = [];
  358. $orderIds = [];
  359. $reclamationScheduleIds = [];
  360. foreach ($schedules as $schedule) {
  361. $statusMap[$schedule->id] = [
  362. 'name' => '-',
  363. 'color' => 'secondary',
  364. ];
  365. if ($schedule->source === 'Площадки' && $schedule->order_id) {
  366. $orderIds[] = (int)$schedule->order_id;
  367. continue;
  368. }
  369. if ($schedule->source === 'Рекламации') {
  370. $reclamationId = $this->extractReclamationId((string)$schedule->address_code);
  371. if ($reclamationId) {
  372. $reclamationScheduleIds[$reclamationId][] = $schedule->id;
  373. }
  374. }
  375. }
  376. if ($orderIds) {
  377. $orderStatuses = Order::query()
  378. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  379. ->whereIn('id', array_unique($orderIds))
  380. ->pluck('order_status_id', 'id')
  381. ->all();
  382. foreach ($schedules as $schedule) {
  383. if ($schedule->source !== 'Площадки' || !$schedule->order_id) {
  384. continue;
  385. }
  386. $statusId = $orderStatuses[(int)$schedule->order_id] ?? null;
  387. if ($statusId) {
  388. $statusMap[$schedule->id] = [
  389. 'name' => Order::STATUS_NAMES[$statusId] ?? '-',
  390. 'color' => Order::STATUS_COLOR[$statusId] ?: 'secondary',
  391. ];
  392. }
  393. }
  394. }
  395. if ($reclamationScheduleIds) {
  396. $reclamationStatuses = Reclamation::query()
  397. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  398. ->whereIn('id', array_keys($reclamationScheduleIds))
  399. ->pluck('status_id', 'id')
  400. ->all();
  401. foreach ($reclamationScheduleIds as $reclamationId => $scheduleIds) {
  402. $statusId = $reclamationStatuses[$reclamationId] ?? null;
  403. $statusName = $statusId ? (Reclamation::STATUS_NAMES[$statusId] ?? '-') : '-';
  404. $statusColor = $statusId ? (ReclamationStatus::STATUS_COLOR[$statusId] ?? 'secondary') : 'secondary';
  405. foreach ($scheduleIds as $scheduleId) {
  406. $statusMap[$scheduleId] = [
  407. 'name' => $statusName,
  408. 'color' => $statusColor,
  409. ];
  410. }
  411. }
  412. }
  413. return $statusMap;
  414. }
  415. private function extractReclamationId(string $addressCode): ?int
  416. {
  417. if (preg_match('/^РЕКЛ-(\d+)$/u', $addressCode, $matches)) {
  418. return (int)$matches[1];
  419. }
  420. return null;
  421. }
  422. }