SparePartOrder.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. /**
  133. * Сколько зарезервировано из этой партии
  134. */
  135. public function getReservedQtyAttribute(): int
  136. {
  137. return (int) ($this->reservations()
  138. ->where('status', Reservation::STATUS_ACTIVE)
  139. ->sum('reserved_qty') ?? 0);
  140. }
  141. /**
  142. * Свободно для резервирования (физический остаток минус активные резервы)
  143. */
  144. public function getFreeQtyAttribute(): int
  145. {
  146. return max(0, $this->available_qty - $this->reserved_qty);
  147. }
  148. /**
  149. * Сколько было списано (через движения issue)
  150. */
  151. public function getIssuedQtyAttribute(): int
  152. {
  153. return (int) ($this->movements()
  154. ->where('movement_type', InventoryMovement::TYPE_ISSUE)
  155. ->sum('qty') ?? 0);
  156. }
  157. // ========== МЕТОДЫ ==========
  158. /**
  159. * Можно ли зарезервировать указанное количество?
  160. */
  161. public function canReserve(int $quantity): bool
  162. {
  163. return $this->free_qty >= $quantity;
  164. }
  165. /**
  166. * Проверка статуса
  167. */
  168. public function isInStock(): bool
  169. {
  170. return $this->status === self::STATUS_IN_STOCK;
  171. }
  172. public function isOrdered(): bool
  173. {
  174. return $this->status === self::STATUS_ORDERED;
  175. }
  176. public function isShipped(): bool
  177. {
  178. return $this->status === self::STATUS_SHIPPED;
  179. }
  180. // ========== ОБРАТНАЯ СОВМЕСТИМОСТЬ ==========
  181. /**
  182. * @deprecated Поле переименовано в available_qty
  183. */
  184. public function getRemainingQuantityAttribute(): int
  185. {
  186. return $this->available_qty;
  187. }
  188. /**
  189. * @deprecated Используйте SparePartIssueService::issue()
  190. */
  191. public function shipQuantity(int $quantity, string $note, ?int $reclamationId = null, ?int $userId = null): bool
  192. {
  193. // Оставляем для обратной совместимости, но рекомендуется использовать сервис
  194. if ($quantity > $this->available_qty) {
  195. return false;
  196. }
  197. $this->available_qty -= $quantity;
  198. $this->save();
  199. // Создаём движение для аудита
  200. InventoryMovement::create([
  201. 'spare_part_order_id' => $this->id,
  202. 'spare_part_id' => $this->spare_part_id,
  203. 'qty' => $quantity,
  204. 'movement_type' => InventoryMovement::TYPE_ISSUE,
  205. 'source_type' => $reclamationId ? InventoryMovement::SOURCE_RECLAMATION : InventoryMovement::SOURCE_MANUAL,
  206. 'source_id' => $reclamationId,
  207. 'with_documents' => $this->with_documents,
  208. 'user_id' => $userId ?? auth()->id(),
  209. 'note' => $note,
  210. ]);
  211. return true;
  212. }
  213. }