ScheduleController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. foreach ($result as $schedule) {
  60. $schedules[$schedule->installation_date][] = $schedule;
  61. }
  62. $this->data['schedules'] = $schedules;
  63. $monthParam = $request->get('month');
  64. $monthNumber = (int)date('m');
  65. if (is_string($monthParam)) {
  66. if (preg_match('/^(0[1-9]|1[0-2])$/', $monthParam)) {
  67. $monthNumber = (int)$monthParam;
  68. } elseif (preg_match('/^(\\d{4})-(0[1-9]|1[0-2])$/', $monthParam, $matches)) {
  69. $this->data['scheduleYear'] = (int)$matches[1];
  70. $monthNumber = (int)$matches[2];
  71. }
  72. }
  73. $monthStart = Carbon::createFromDate($this->data['scheduleYear'], $monthNumber, 1)->startOfMonth();
  74. $monthEnd = $monthStart->copy()->endOfMonth();
  75. $gridStart = $monthStart->copy()->startOfWeek(Carbon::MONDAY);
  76. $gridEnd = $monthEnd->copy()->endOfWeek(Carbon::SUNDAY);
  77. $cursor = $gridStart->copy();
  78. $monthDays = [];
  79. while ($cursor->lte($gridEnd)) {
  80. $monthDays[] = [
  81. 'date' => $cursor->toDateString(),
  82. 'day' => (int)$cursor->format('j'),
  83. 'week' => (int)$cursor->isoWeek(),
  84. 'weekYear' => (int)$cursor->isoWeekYear(),
  85. 'inMonth' => $cursor->month === $monthStart->month,
  86. 'isToday' => $cursor->isToday(),
  87. ];
  88. $cursor->addDay();
  89. }
  90. $monthSchedules = Schedule::query()
  91. ->whereBetween('installation_date', [$monthStart->toDateString(), $monthEnd->toDateString()])
  92. ->with(['brigadier'])
  93. ->get();
  94. $monthScheduleColors = [];
  95. $monthBrigadierLegend = [];
  96. foreach ($monthSchedules as $schedule) {
  97. $date = $schedule->installation_date;
  98. $brigadierId = $schedule->brigadier_id ?? 0;
  99. if (!isset($monthScheduleColors[$date])) {
  100. $monthScheduleColors[$date] = [];
  101. }
  102. if (!isset($monthScheduleColors[$date][$brigadierId])) {
  103. $monthScheduleColors[$date][$brigadierId] = [
  104. 'color' => $schedule->brigadier?->color ?? '#cccccc',
  105. 'name' => $schedule->brigadier?->name ?? '',
  106. ];
  107. }
  108. if (!isset($monthBrigadierLegend[$brigadierId])) {
  109. $monthBrigadierLegend[$brigadierId] = [
  110. 'color' => $schedule->brigadier?->color ?? '#cccccc',
  111. 'name' => $schedule->brigadier?->name ?? '',
  112. ];
  113. }
  114. }
  115. foreach ($monthScheduleColors as $date => $colors) {
  116. $monthScheduleColors[$date] = array_values($colors);
  117. }
  118. $this->data['monthGrid'] = array_chunk($monthDays, 7);
  119. $this->data['monthLabel'] = $monthStart->isoFormat('MMMM YYYY');
  120. $this->data['monthNumber'] = $monthNumber;
  121. $this->data['monthPrev'] = $monthStart->copy()->subMonth()->format('Y-m');
  122. $this->data['monthNext'] = $monthStart->copy()->addMonth()->format('Y-m');
  123. $this->data['monthValue'] = $monthStart->format('Y-m');
  124. $this->data['monthScheduleColors'] = $monthScheduleColors;
  125. $this->data['monthBrigadierLegend'] = array_values($monthBrigadierLegend);
  126. return view('schedule.index', $this->data);
  127. }
  128. public function createFromOrder(CreateScheduleFromOrderRequest $request)
  129. {
  130. $validated = $request->validated();
  131. // delete all auto schedules for this order
  132. if(isset($validated['delete_old_records'])) {
  133. Schedule::query()
  134. ->where('order_id', $validated['order_id'])
  135. ->where('source', 'Площадки')
  136. ->where('manual', false)
  137. ->delete();
  138. }
  139. // create all records in schedule
  140. $order = Order::query()
  141. ->where('id', $validated['order_id'])
  142. ->first();
  143. $errors = [];
  144. if(!$order->brigadier_id) $errors[] = 'Не указан бригадир!';
  145. if(!$order->installation_date) $errors[] = 'Не указана дата монтажа!';
  146. if(!$order->install_days) $errors[] = 'Не указан срок монтажа!';
  147. if($errors) {
  148. return redirect()->route('order.show', $order->id)->with(['danger' => $errors]);
  149. }
  150. if(empty($validated['skus'])) {
  151. foreach ($order->products_sku as $psku)
  152. $validated['skus'][] = $psku->id;
  153. }
  154. $mafs = [];
  155. foreach ($validated['skus'] as $skuId) {
  156. $sku = ProductSKU::query()->where('id', $skuId)->first();
  157. if(!isset($mafs[$sku->product->article])) {
  158. $mafs[$sku->product->article] = 1;
  159. } else {
  160. $mafs[$sku->product->article] += 1;
  161. }
  162. }
  163. $mafsText = '';
  164. $mafsCount = 0;
  165. foreach ($mafs as $article => $count) {
  166. $mafsText .= $article . ' - ' . $count . "\r\n";
  167. $mafsCount += $count;
  168. }
  169. $first = true;
  170. for ($iDays = 1; $iDays < $order->install_days + 1; $iDays++) {
  171. $instDate = date('Y-m-d', strtotime('+' . $iDays - 1 . ' days', strtotime($order->installation_date)));
  172. $schedule = Schedule::query()
  173. ->create([
  174. 'order_id' => $validated['order_id'],
  175. 'address_code' => $validated['order_id'],
  176. 'source' => 'Площадки',
  177. 'installation_date' => $instDate,
  178. 'manual' => false,
  179. 'district_id' => $order->district_id,
  180. 'area_id' => $order->area_id,
  181. 'object_address' => $order->object_address,
  182. 'object_type' => $order->objectType->name,
  183. 'mafs' => $mafsText,
  184. 'mafs_count' => $mafsCount,
  185. 'brigadier_id' => $order->brigadier_id,
  186. 'comment' => $validated['comment'],
  187. ]);
  188. if($first && isset($validated['send_notifications'])) {
  189. $first = false;
  190. NotifyOrderInScheduleJob::dispatch($schedule);
  191. }
  192. }
  193. return redirect()->route('schedule.index');
  194. }
  195. public function createFromReclamation(CreateScheduleFromReclamationRequest $request)
  196. {
  197. $validated = $request->validated();
  198. // delete all auto schedules for this order
  199. if(isset($validated['delete_old_records'])) {
  200. Schedule::query()
  201. ->where('address_code', 'РЕКЛ-' . $validated['reclamation_id'])
  202. ->where('source', 'Рекламации')
  203. ->where('manual', false)
  204. ->delete();
  205. }
  206. $reclamation = Reclamation::query()
  207. ->where('id', $validated['reclamation_id'])
  208. ->first();
  209. $order = $reclamation->order;
  210. $mafs = [];
  211. if(empty($validated['skus'])) {
  212. foreach ($reclamation->skus as $sku)
  213. if(!isset($mafs[$sku->product->article])) {
  214. $mafs[$sku->product->article] = 1;
  215. } else {
  216. $mafs[$sku->product->article] += 1;
  217. }
  218. }
  219. $mafsCount = 0;
  220. $mafsText = '';
  221. foreach ($mafs as $article => $count) {
  222. $mafsCount += $count;
  223. $mafsText .= $article . ' - ' . $count . "\r\n";
  224. }
  225. $first = true;
  226. for ($iDays = 1; $iDays < $reclamation->work_days + 1; $iDays++) {
  227. $instDate = date('Y-m-d', strtotime('+' . $iDays - 1 . ' days', strtotime($reclamation->start_work_date)));
  228. $schedule = Schedule::query()
  229. ->create([
  230. 'order_id' => $order->id,
  231. 'address_code' => 'РЕКЛ-' . $validated['reclamation_id'],
  232. 'source' => 'Рекламации',
  233. 'installation_date' => $instDate,
  234. 'manual' => false,
  235. 'district_id' => $order->district_id,
  236. 'area_id' => $order->area_id,
  237. 'object_address' => $order->object_address,
  238. 'object_type' => $reclamation->reason,
  239. 'mafs' => $mafsText,
  240. 'mafs_count' => $mafsCount,
  241. 'brigadier_id' => $reclamation->brigadier_id,
  242. 'comment' => $reclamation->guarantee,
  243. ]);
  244. if($first && isset($validated['send_notifications'])) {
  245. $first = false;
  246. NotifyOrderInScheduleJob::dispatch($schedule);
  247. }
  248. }
  249. return redirect()->route('schedule.index');
  250. }
  251. public function update(UpdateScheduleRequest $request)
  252. {
  253. $validated = $request->validated();
  254. if(isset($validated['id'])) {
  255. Schedule::query()
  256. ->where('id', $validated['id'])
  257. ->update($validated);
  258. $schedule = Schedule::query()->find($validated['id']);
  259. } else {
  260. $schedule = Schedule::query()
  261. ->create([
  262. 'address_code' => $validated['address_code'] ?? '-',
  263. 'installation_date' => $validated['installation_date'],
  264. 'manual' => true,
  265. 'district_id' => $validated['district_id'],
  266. 'area_id' => $validated['area_id'],
  267. 'object_address' => $validated['object_address'],
  268. 'object_type' => $validated['object_type'],
  269. 'mafs' => $validated['mafs'],
  270. 'mafs_count' => $validated['mafs_count'],
  271. 'brigadier_id' => $validated['brigadier_id'],
  272. 'comment' => $validated['comment'],
  273. 'transport' => $validated['transport'] ?? null,
  274. 'admin_comment' => $validated['admin_comment'] ?? null,
  275. ]);
  276. }
  277. NotifyOrderInScheduleJob::dispatch($schedule);
  278. return redirect()->back();
  279. }
  280. public function delete(Schedule $schedule)
  281. {
  282. $schedule->delete();
  283. return redirect()->back();
  284. }
  285. public function export(ExportScheduleRequest $request)
  286. {
  287. $startDate = $request->validated()['start_date'];
  288. $endDate = $request->validated()['end_date'];
  289. $schedules = Schedule::query()
  290. ->where('installation_date', '>=', $startDate)
  291. ->where('installation_date', '<=', $endDate)
  292. ->orderBy('installation_date')
  293. ->orderBy('brigadier_id')
  294. ->get();
  295. ExportScheduleJob::dispatch($schedules, $request->user()->id);
  296. return redirect()->route('schedule.index', [
  297. 'week' => (int) $request->validated()['week'],
  298. 'year' => (int) $request->input('year', date('Y')),
  299. ])
  300. ->with(['success' => 'Задача генерации графика создана!']);
  301. }
  302. }