SparePartOrder.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  6. use Illuminate\Database\Eloquent\Relations\HasMany;
  7. use Illuminate\Database\Eloquent\Relations\MorphTo;
  8. use Illuminate\Database\Eloquent\SoftDeletes;
  9. /**
  10. * Партия запчастей (заказ/поступление).
  11. *
  12. * Представляет физическое поступление запчастей на склад.
  13. * Поле available_qty всегда >= 0 (enforced CHECK constraint).
  14. *
  15. * Жизненный цикл:
  16. * 1. ordered - заказано у поставщика
  17. * 2. in_stock - получено на склад
  18. * 3. shipped - полностью отгружено (available_qty = 0)
  19. */
  20. class SparePartOrder extends Model
  21. {
  22. use HasFactory, SoftDeletes;
  23. const STATUS_ORDERED = 'ordered';
  24. const STATUS_IN_STOCK = 'in_stock';
  25. const STATUS_SHIPPED = 'shipped';
  26. const STATUS_NAMES = [
  27. self::STATUS_ORDERED => 'Заказано',
  28. self::STATUS_IN_STOCK => 'На складе',
  29. self::STATUS_SHIPPED => 'Отгружено',
  30. ];
  31. const DEFAULT_SORT_BY = 'created_at';
  32. protected $fillable = [
  33. 'spare_part_id',
  34. 'order_number',
  35. 'source_text',
  36. 'sourceable_id',
  37. 'sourceable_type',
  38. 'status',
  39. 'ordered_quantity',
  40. 'available_qty',
  41. 'with_documents',
  42. 'note',
  43. 'user_id',
  44. ];
  45. protected $casts = [
  46. 'with_documents' => 'boolean',
  47. 'ordered_quantity' => 'integer',
  48. 'available_qty' => 'integer',
  49. ];
  50. protected static function boot(): void
  51. {
  52. parent::boot();
  53. static::creating(function ($model) {
  54. if (!isset($model->available_qty)) {
  55. $model->available_qty = $model->ordered_quantity;
  56. }
  57. });
  58. // Автосмена статуса при полной отгрузке
  59. static::updating(function ($model) {
  60. if ($model->available_qty === 0 && $model->status === self::STATUS_IN_STOCK) {
  61. $model->status = self::STATUS_SHIPPED;
  62. }
  63. });
  64. }
  65. // ========== ОТНОШЕНИЯ ==========
  66. public function sparePart(): BelongsTo
  67. {
  68. return $this->belongsTo(SparePart::class);
  69. }
  70. public function user(): BelongsTo
  71. {
  72. return $this->belongsTo(User::class);
  73. }
  74. public function sourceable(): MorphTo
  75. {
  76. return $this->morphTo();
  77. }
  78. /**
  79. * Резервы из этой партии
  80. */
  81. public function reservations(): HasMany
  82. {
  83. return $this->hasMany(Reservation::class, 'spare_part_order_id');
  84. }
  85. /**
  86. * Движения по этой партии
  87. */
  88. public function movements(): HasMany
  89. {
  90. return $this->hasMany(InventoryMovement::class, 'spare_part_order_id');
  91. }
  92. /**
  93. * @deprecated Используйте movements()
  94. */
  95. public function shipments(): HasMany
  96. {
  97. return $this->hasMany(SparePartOrderShipment::class);
  98. }
  99. // ========== SCOPES ==========
  100. public function scopeInStock($query)
  101. {
  102. return $query->where('status', self::STATUS_IN_STOCK);
  103. }
  104. public function scopeWithAvailable($query)
  105. {
  106. return $query->where('available_qty', '>', 0);
  107. }
  108. public function scopeWithDocuments($query, bool $withDocs = true)
  109. {
  110. return $query->where('with_documents', $withDocs);
  111. }
  112. public function scopeForSparePart($query, int $sparePartId)
  113. {
  114. return $query->where('spare_part_id', $sparePartId);
  115. }
  116. /**
  117. * Партии доступные для резервирования (FIFO)
  118. */
  119. public function scopeAvailableForReservation($query, int $sparePartId, bool $withDocuments)
  120. {
  121. return $query->where('spare_part_id', $sparePartId)
  122. ->where('with_documents', $withDocuments)
  123. ->where('status', self::STATUS_IN_STOCK)
  124. ->where('available_qty', '>', 0)
  125. ->orderBy('created_at', 'asc');
  126. }
  127. // ========== ВЫЧИСЛЯЕМЫЕ ПОЛЯ ==========
  128. public function getStatusNameAttribute(): string
  129. {
  130. return self::STATUS_NAMES[$this->status] ?? $this->status;
  131. }
  132. public function getDisplayOrderNumberAttribute(): string
  133. {
  134. $orderNumber = trim((string) ($this->order_number ?? ''));
  135. return $orderNumber !== '' ? $orderNumber : '#' . $this->id;
  136. }
  137. /**
  138. * Сколько зарезервировано из этой партии
  139. */
  140. public function getReservedQtyAttribute(): int
  141. {
  142. return (int) ($this->reservations()
  143. ->where('status', Reservation::STATUS_ACTIVE)
  144. ->sum('reserved_qty') ?? 0);
  145. }
  146. /**
  147. * Свободно для резервирования (физический остаток минус активные резервы)
  148. */
  149. public function getFreeQtyAttribute(): int
  150. {
  151. return max(0, $this->available_qty - $this->reserved_qty);
  152. }
  153. /**
  154. * Сколько было списано (через движения issue)
  155. */
  156. public function getIssuedQtyAttribute(): int
  157. {
  158. return (int) ($this->movements()
  159. ->where('movement_type', InventoryMovement::TYPE_ISSUE)
  160. ->sum('qty') ?? 0);
  161. }
  162. // ========== МЕТОДЫ ==========
  163. /**
  164. * Можно ли зарезервировать указанное количество?
  165. */
  166. public function canReserve(int $quantity): bool
  167. {
  168. return $this->free_qty >= $quantity;
  169. }
  170. /**
  171. * Проверка статуса
  172. */
  173. public function isInStock(): bool
  174. {
  175. return $this->status === self::STATUS_IN_STOCK;
  176. }
  177. public function isOrdered(): bool
  178. {
  179. return $this->status === self::STATUS_ORDERED;
  180. }
  181. public function isShipped(): bool
  182. {
  183. return $this->status === self::STATUS_SHIPPED;
  184. }
  185. // ========== ОБРАТНАЯ СОВМЕСТИМОСТЬ ==========
  186. /**
  187. * @deprecated Поле переименовано в available_qty
  188. */
  189. public function getRemainingQuantityAttribute(): int
  190. {
  191. return $this->available_qty;
  192. }
  193. /**
  194. * @deprecated Используйте SparePartIssueService::issue()
  195. */
  196. public function shipQuantity(int $quantity, string $note, ?int $reclamationId = null, ?int $userId = null): bool
  197. {
  198. // Оставляем для обратной совместимости, но рекомендуется использовать сервис
  199. if ($quantity > $this->available_qty) {
  200. return false;
  201. }
  202. $this->available_qty -= $quantity;
  203. $this->save();
  204. // Создаём движение для аудита
  205. InventoryMovement::create([
  206. 'spare_part_order_id' => $this->id,
  207. 'spare_part_id' => $this->spare_part_id,
  208. 'qty' => $quantity,
  209. 'movement_type' => InventoryMovement::TYPE_ISSUE,
  210. 'source_type' => $reclamationId ? InventoryMovement::SOURCE_RECLAMATION : InventoryMovement::SOURCE_MANUAL,
  211. 'source_id' => $reclamationId,
  212. 'with_documents' => $this->with_documents,
  213. 'user_id' => $userId ?? auth()->id(),
  214. 'note' => $note,
  215. ]);
  216. return true;
  217. }
  218. }