ScheduleController.php 16 KB

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