SparePartOrder.php 7.1 KB

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