SparePartReservationService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. <?php
  2. namespace App\Services;
  3. use App\Models\InventoryMovement;
  4. use App\Models\ReclamationSparePart;
  5. use App\Models\Reservation;
  6. use App\Models\Shortage;
  7. use App\Models\SparePart;
  8. use App\Models\SparePartOrder;
  9. use Illuminate\Support\Collection;
  10. use Illuminate\Support\Facades\DB;
  11. /**
  12. * Сервис резервирования запчастей.
  13. *
  14. * Реализует алгоритм резервирования с учётом:
  15. * - FIFO по партиям (первыми резервируются старые поступления)
  16. * - Разделения по типу документов (with_documents)
  17. * - Создания дефицитов при нехватке
  18. */
  19. class SparePartReservationService
  20. {
  21. /**
  22. * Результат резервирования
  23. */
  24. public function __construct(
  25. private readonly ShortageService $shortageService
  26. ) {}
  27. /**
  28. * Зарезервировать запчасть для рекламации
  29. *
  30. * @param int $sparePartId ID запчасти
  31. * @param int $quantity Требуемое количество
  32. * @param bool $withDocuments С документами или без
  33. * @param int $reclamationId ID рекламации
  34. * @return ReservationResult
  35. */
  36. public function reserve(
  37. int $sparePartId,
  38. int $quantity,
  39. bool $withDocuments,
  40. int $reclamationId
  41. ): ReservationResult {
  42. return DB::transaction(function () use ($sparePartId, $quantity, $withDocuments, $reclamationId) {
  43. $sparePart = SparePart::findOrFail($sparePartId);
  44. // 1. Расчёт свободного остатка
  45. $physicalStock = SparePartOrder::query()
  46. ->where('spare_part_id', $sparePartId)
  47. ->where('with_documents', $withDocuments)
  48. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  49. ->sum('available_qty');
  50. $activeReserves = Reservation::query()
  51. ->where('spare_part_id', $sparePartId)
  52. ->where('with_documents', $withDocuments)
  53. ->where('status', Reservation::STATUS_ACTIVE)
  54. ->sum('reserved_qty');
  55. $freeStock = $physicalStock - $activeReserves;
  56. // 2. Определение сколько можем зарезервировать
  57. $canReserve = min($quantity, max(0, $freeStock));
  58. $missing = $quantity - $canReserve;
  59. $reservations = collect();
  60. $shortage = null;
  61. // 3. Резервирование доступного количества (FIFO по партиям)
  62. if ($canReserve > 0) {
  63. $remainingToReserve = $canReserve;
  64. $orders = SparePartOrder::query()
  65. ->where('spare_part_id', $sparePartId)
  66. ->where('with_documents', $withDocuments)
  67. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  68. ->where('available_qty', '>', 0)
  69. ->orderBy('created_at', 'asc')
  70. ->lockForUpdate()
  71. ->get();
  72. foreach ($orders as $order) {
  73. if ($remainingToReserve <= 0) break;
  74. // Сколько уже зарезервировано из этой партии
  75. $alreadyReserved = Reservation::query()
  76. ->where('spare_part_order_id', $order->id)
  77. ->where('status', Reservation::STATUS_ACTIVE)
  78. ->sum('reserved_qty');
  79. $freeInOrder = $order->available_qty - $alreadyReserved;
  80. $toReserve = min($remainingToReserve, $freeInOrder);
  81. if ($toReserve > 0) {
  82. // Создаём движение типа reserve
  83. $movement = InventoryMovement::create([
  84. 'spare_part_order_id' => $order->id,
  85. 'spare_part_id' => $sparePartId,
  86. 'qty' => $toReserve,
  87. 'movement_type' => InventoryMovement::TYPE_RESERVE,
  88. 'source_type' => InventoryMovement::SOURCE_RECLAMATION,
  89. 'source_id' => $reclamationId,
  90. 'with_documents' => $withDocuments,
  91. 'user_id' => auth()->id(),
  92. 'note' => "Резервирование для рекламации #{$reclamationId}",
  93. ]);
  94. // Создаём резерв
  95. $reservation = Reservation::create([
  96. 'spare_part_id' => $sparePartId,
  97. 'spare_part_order_id' => $order->id,
  98. 'reclamation_id' => $reclamationId,
  99. 'reserved_qty' => $toReserve,
  100. 'with_documents' => $withDocuments,
  101. 'status' => Reservation::STATUS_ACTIVE,
  102. 'movement_id' => $movement->id,
  103. ]);
  104. $reservations->push($reservation);
  105. $remainingToReserve -= $toReserve;
  106. }
  107. }
  108. }
  109. // 4. Создание дефицита при нехватке
  110. if ($missing > 0) {
  111. $shortage = Shortage::create([
  112. 'spare_part_id' => $sparePartId,
  113. 'reclamation_id' => $reclamationId,
  114. 'with_documents' => $withDocuments,
  115. 'required_qty' => $quantity,
  116. 'reserved_qty' => $canReserve,
  117. 'missing_qty' => $missing,
  118. 'status' => Shortage::STATUS_OPEN,
  119. 'note' => "Дефицит при резервировании для рекламации #{$reclamationId}",
  120. ]);
  121. }
  122. return new ReservationResult(
  123. reserved: $canReserve,
  124. missing: $missing,
  125. reservations: $reservations,
  126. shortage: $shortage
  127. );
  128. });
  129. }
  130. /**
  131. * Отменить резервы для рекламации
  132. *
  133. * @param int $reclamationId ID рекламации
  134. * @param int|null $sparePartId ID запчасти (опционально, если нужно отменить для конкретной)
  135. * @param bool|null $withDocuments Тип документов (опционально)
  136. * @return int Количество отменённых единиц
  137. */
  138. public function cancelForReclamation(
  139. int $reclamationId,
  140. ?int $sparePartId = null,
  141. ?bool $withDocuments = null
  142. ): int {
  143. return DB::transaction(function () use ($reclamationId, $sparePartId, $withDocuments) {
  144. $query = Reservation::query()
  145. ->where('reclamation_id', $reclamationId)
  146. ->where('status', Reservation::STATUS_ACTIVE);
  147. if ($sparePartId !== null) {
  148. $query->where('spare_part_id', $sparePartId);
  149. }
  150. if ($withDocuments !== null) {
  151. $query->where('with_documents', $withDocuments);
  152. }
  153. $reservations = $query->lockForUpdate()->get();
  154. $totalCancelled = 0;
  155. foreach ($reservations as $reservation) {
  156. $this->cancelReservation($reservation, "Отмена резерва для рекламации #{$reclamationId}");
  157. $totalCancelled += $reservation->reserved_qty;
  158. }
  159. // Также закрываем связанные дефициты
  160. $shortageQuery = Shortage::query()
  161. ->where('reclamation_id', $reclamationId)
  162. ->where('status', Shortage::STATUS_OPEN);
  163. if ($sparePartId !== null) {
  164. $shortageQuery->where('spare_part_id', $sparePartId);
  165. }
  166. if ($withDocuments !== null) {
  167. $shortageQuery->where('with_documents', $withDocuments);
  168. }
  169. $shortageQuery->update(['status' => Shortage::STATUS_CLOSED]);
  170. return $totalCancelled;
  171. });
  172. }
  173. /**
  174. * Отменить конкретный резерв
  175. */
  176. public function cancelReservation(Reservation $reservation, string $reason = ''): bool
  177. {
  178. if (!$reservation->isActive()) {
  179. return false;
  180. }
  181. return DB::transaction(function () use ($reservation, $reason) {
  182. $reservation->status = Reservation::STATUS_CANCELLED;
  183. $reservation->save();
  184. // Создаём движение отмены
  185. InventoryMovement::create([
  186. 'spare_part_order_id' => $reservation->spare_part_order_id,
  187. 'spare_part_id' => $reservation->spare_part_id,
  188. 'qty' => $reservation->reserved_qty,
  189. 'movement_type' => InventoryMovement::TYPE_RESERVE_CANCEL,
  190. 'source_type' => InventoryMovement::SOURCE_RECLAMATION,
  191. 'source_id' => $reservation->reclamation_id,
  192. 'with_documents' => $reservation->with_documents,
  193. 'user_id' => auth()->id(),
  194. 'note' => $reason,
  195. ]);
  196. return true;
  197. });
  198. }
  199. /**
  200. * Изменить количество резерва для рекламации
  201. *
  202. * @param int $reclamationId ID рекламации
  203. * @param int $sparePartId ID запчасти
  204. * @param bool $withDocuments Тип документов
  205. * @param int $newQuantity Новое требуемое количество
  206. * @return ReservationResult
  207. */
  208. public function adjustReservation(
  209. int $reclamationId,
  210. int $sparePartId,
  211. bool $withDocuments,
  212. int $newQuantity
  213. ): ReservationResult {
  214. return DB::transaction(function () use ($reclamationId, $sparePartId, $withDocuments, $newQuantity) {
  215. // Получаем текущие резервы
  216. $currentReserved = Reservation::query()
  217. ->where('reclamation_id', $reclamationId)
  218. ->where('spare_part_id', $sparePartId)
  219. ->where('with_documents', $withDocuments)
  220. ->where('status', Reservation::STATUS_ACTIVE)
  221. ->sum('reserved_qty');
  222. $diff = $newQuantity - $currentReserved;
  223. if ($diff > 0) {
  224. // Нужно дорезервировать
  225. return $this->reserve($sparePartId, $diff, $withDocuments, $reclamationId);
  226. } elseif ($diff < 0) {
  227. // Нужно освободить часть резерва
  228. $toRelease = abs($diff);
  229. $released = 0;
  230. // Освобождаем в обратном порядке FIFO (сначала новые)
  231. $reservations = Reservation::query()
  232. ->where('reclamation_id', $reclamationId)
  233. ->where('spare_part_id', $sparePartId)
  234. ->where('with_documents', $withDocuments)
  235. ->where('status', Reservation::STATUS_ACTIVE)
  236. ->orderBy('created_at', 'desc')
  237. ->lockForUpdate()
  238. ->get();
  239. foreach ($reservations as $reservation) {
  240. if ($released >= $toRelease) break;
  241. $releaseFromThis = min($toRelease - $released, $reservation->reserved_qty);
  242. if ($releaseFromThis === $reservation->reserved_qty) {
  243. // Отменяем весь резерв
  244. $this->cancelReservation($reservation, "Уменьшение резерва");
  245. } else {
  246. // Частичная отмена — создаём новый резерв на остаток
  247. $reservation->reserved_qty -= $releaseFromThis;
  248. $reservation->save();
  249. // Движение частичной отмены
  250. InventoryMovement::create([
  251. 'spare_part_order_id' => $reservation->spare_part_order_id,
  252. 'spare_part_id' => $sparePartId,
  253. 'qty' => $releaseFromThis,
  254. 'movement_type' => InventoryMovement::TYPE_RESERVE_CANCEL,
  255. 'source_type' => InventoryMovement::SOURCE_RECLAMATION,
  256. 'source_id' => $reclamationId,
  257. 'with_documents' => $withDocuments,
  258. 'user_id' => auth()->id(),
  259. 'note' => "Частичная отмена резерва",
  260. ]);
  261. }
  262. $released += $releaseFromThis;
  263. }
  264. // Обновляем дефицит если есть
  265. $shortage = Shortage::query()
  266. ->where('reclamation_id', $reclamationId)
  267. ->where('spare_part_id', $sparePartId)
  268. ->where('with_documents', $withDocuments)
  269. ->where('status', Shortage::STATUS_OPEN)
  270. ->first();
  271. if ($shortage) {
  272. $shortage->required_qty = $newQuantity;
  273. $shortage->recalculate();
  274. }
  275. // Пересчитываем фактически зарезервированное количество после изменений
  276. $actualReserved = Reservation::query()
  277. ->where('reclamation_id', $reclamationId)
  278. ->where('spare_part_id', $sparePartId)
  279. ->where('with_documents', $withDocuments)
  280. ->where('status', Reservation::STATUS_ACTIVE)
  281. ->sum('reserved_qty');
  282. return new ReservationResult(
  283. reserved: (int) $actualReserved,
  284. missing: max(0, $newQuantity - $actualReserved),
  285. reservations: collect(),
  286. shortage: $shortage
  287. );
  288. }
  289. // diff = 0, ничего не делаем
  290. return new ReservationResult(
  291. reserved: $currentReserved,
  292. missing: 0,
  293. reservations: collect(),
  294. shortage: null
  295. );
  296. });
  297. }
  298. /**
  299. * Получить все активные резервы для рекламации
  300. */
  301. public function getReservationsForReclamation(int $reclamationId): Collection
  302. {
  303. return Reservation::query()
  304. ->where('reclamation_id', $reclamationId)
  305. ->where('status', Reservation::STATUS_ACTIVE)
  306. ->with(['sparePart', 'sparePartOrder'])
  307. ->get();
  308. }
  309. public function reassignReservationToSelectedOrder(
  310. Reservation $reservation,
  311. int $selectedOrderId
  312. ): Reservation {
  313. if (!$reservation->isActive()) {
  314. throw new \InvalidArgumentException('Резерв не активен, перенос невозможен');
  315. }
  316. return DB::transaction(function () use ($reservation, $selectedOrderId) {
  317. $reservation = Reservation::query()->lockForUpdate()->findOrFail($reservation->id);
  318. $selectedOrder = SparePartOrder::query()->lockForUpdate()->findOrFail($selectedOrderId);
  319. if (!$reservation->isActive()) {
  320. throw new \InvalidArgumentException('Резерв не активен, перенос невозможен');
  321. }
  322. if ((int) $reservation->spare_part_order_id === $selectedOrderId) {
  323. return $reservation;
  324. }
  325. if ((int) $selectedOrder->spare_part_id !== (int) $reservation->spare_part_id) {
  326. throw new \InvalidArgumentException('Выбран заказ другой запчасти');
  327. }
  328. if ((bool) $selectedOrder->with_documents !== (bool) $reservation->with_documents) {
  329. throw new \InvalidArgumentException('Выбран заказ с другим признаком документов');
  330. }
  331. if ($selectedOrder->status !== SparePartOrder::STATUS_IN_STOCK) {
  332. throw new \InvalidArgumentException('Резервирование возможно только на партии на складе');
  333. }
  334. $alreadyReservedOnSelected = Reservation::query()
  335. ->where('spare_part_order_id', $selectedOrder->id)
  336. ->where('status', Reservation::STATUS_ACTIVE)
  337. ->sum('reserved_qty');
  338. $freeQty = max(0, (int) $selectedOrder->available_qty - (int) $alreadyReservedOnSelected);
  339. if ($freeQty < 1) {
  340. throw new \RuntimeException('В выбранном заказе нет доступного остатка');
  341. }
  342. $requestedQty = (int) $reservation->reserved_qty;
  343. $reassignedQty = min($requestedQty, $freeQty);
  344. $this->cancelReservation($reservation, 'Перенос резерва на другой заказ');
  345. $reserveMovement = InventoryMovement::create([
  346. 'spare_part_order_id' => $selectedOrder->id,
  347. 'spare_part_id' => $reservation->spare_part_id,
  348. 'qty' => $reassignedQty,
  349. 'movement_type' => InventoryMovement::TYPE_RESERVE,
  350. 'source_type' => InventoryMovement::SOURCE_RECLAMATION,
  351. 'source_id' => $reservation->reclamation_id,
  352. 'with_documents' => $reservation->with_documents,
  353. 'user_id' => auth()->id(),
  354. 'note' => "Перенос резерва на заказ #{$selectedOrder->id}",
  355. ]);
  356. $selectedReservation = Reservation::create([
  357. 'spare_part_id' => $reservation->spare_part_id,
  358. 'spare_part_order_id' => $selectedOrder->id,
  359. 'reclamation_id' => $reservation->reclamation_id,
  360. 'reserved_qty' => $reassignedQty,
  361. 'with_documents' => $reservation->with_documents,
  362. 'status' => Reservation::STATUS_ACTIVE,
  363. 'movement_id' => $reserveMovement->id,
  364. ]);
  365. if ($reassignedQty < $requestedQty) {
  366. $this->reassignRemainingQuantity(
  367. $reservation,
  368. $reassignedQty,
  369. $requestedQty - $reassignedQty
  370. );
  371. } else {
  372. $this->syncPivotRowForReservation($selectedReservation);
  373. }
  374. return $selectedReservation;
  375. });
  376. }
  377. public function syncPivotRowForReservation(Reservation $reservation): void
  378. {
  379. $row = ReclamationSparePart::query()
  380. ->where('reclamation_id', $reservation->reclamation_id)
  381. ->where('spare_part_id', $reservation->spare_part_id)
  382. ->where('with_documents', $reservation->with_documents)
  383. ->orderBy('id')
  384. ->first();
  385. if (!$row) {
  386. return;
  387. }
  388. $activeQty = (int) Reservation::query()
  389. ->where('reclamation_id', $reservation->reclamation_id)
  390. ->where('spare_part_id', $reservation->spare_part_id)
  391. ->where('with_documents', $reservation->with_documents)
  392. ->where('status', Reservation::STATUS_ACTIVE)
  393. ->sum('reserved_qty');
  394. $issuedQty = (int) Reservation::query()
  395. ->where('reclamation_id', $reservation->reclamation_id)
  396. ->where('spare_part_id', $reservation->spare_part_id)
  397. ->where('with_documents', $reservation->with_documents)
  398. ->where('status', Reservation::STATUS_ISSUED)
  399. ->sum('reserved_qty');
  400. $row->update([
  401. 'reserved_qty' => $activeQty,
  402. 'issued_qty' => min($row->quantity, $issuedQty),
  403. 'status' => $issuedQty >= $row->quantity
  404. ? 'issued'
  405. : ($activeQty > 0 ? 'reserved' : 'pending'),
  406. ]);
  407. }
  408. private function reassignRemainingQuantity(
  409. Reservation $reservation,
  410. int $reservedQty,
  411. int $remainingQty
  412. ): void {
  413. $row = ReclamationSparePart::query()
  414. ->where('reclamation_id', $reservation->reclamation_id)
  415. ->where('spare_part_id', $reservation->spare_part_id)
  416. ->where('with_documents', $reservation->with_documents)
  417. ->where('quantity', '>=', $reservation->reserved_qty)
  418. ->orderBy('id')
  419. ->first();
  420. if (!$row) {
  421. return;
  422. }
  423. $row->update([
  424. 'quantity' => $reservedQty,
  425. 'reserved_qty' => $reservedQty,
  426. 'issued_qty' => 0,
  427. 'status' => 'reserved',
  428. ]);
  429. $remainingReservationResult = $this->reserve(
  430. $reservation->spare_part_id,
  431. $remainingQty,
  432. $reservation->with_documents,
  433. $reservation->reclamation_id
  434. );
  435. if ($remainingReservationResult->reserved > 0) {
  436. ReclamationSparePart::query()->create([
  437. 'reclamation_id' => $row->reclamation_id,
  438. 'spare_part_id' => $row->spare_part_id,
  439. 'quantity' => $remainingReservationResult->reserved,
  440. 'with_documents' => $row->with_documents,
  441. 'status' => 'reserved',
  442. 'reserved_qty' => $remainingReservationResult->reserved,
  443. 'issued_qty' => 0,
  444. ]);
  445. }
  446. if ($remainingReservationResult->missing > 0) {
  447. ReclamationSparePart::query()->create([
  448. 'reclamation_id' => $row->reclamation_id,
  449. 'spare_part_id' => $row->spare_part_id,
  450. 'quantity' => $remainingReservationResult->missing,
  451. 'with_documents' => $row->with_documents,
  452. 'status' => 'pending',
  453. 'reserved_qty' => 0,
  454. 'issued_qty' => 0,
  455. ]);
  456. }
  457. }
  458. }
  459. /**
  460. * Результат операции резервирования
  461. */
  462. class ReservationResult
  463. {
  464. public function __construct(
  465. public readonly int $reserved,
  466. public readonly int $missing,
  467. public readonly Collection $reservations,
  468. public readonly ?Shortage $shortage
  469. ) {}
  470. public function isFullyReserved(): bool
  471. {
  472. return $this->missing === 0;
  473. }
  474. public function hasShortage(): bool
  475. {
  476. return $this->shortage !== null;
  477. }
  478. public function getTotalRequested(): int
  479. {
  480. return $this->reserved + $this->missing;
  481. }
  482. }