SparePartOrder.php 7.4 KB

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