ScheduleController.php 13 KB

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