SparePartOrder.php 7.3 KB

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