ScheduleController.php 16 KB

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