| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260 |
- <?php
- namespace App\Models;
- use App\Models\Scopes\YearScope;
- use Illuminate\Database\Eloquent\Attributes\ScopedBy;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
- use Illuminate\Database\Eloquent\Relations\HasMany;
- use Illuminate\Database\Eloquent\Relations\MorphTo;
- use Illuminate\Database\Eloquent\SoftDeletes;
- /**
- * Партия запчастей (заказ/поступление).
- *
- * Представляет физическое поступление запчастей на склад.
- * Поле available_qty всегда >= 0 (enforced CHECK constraint).
- *
- * Жизненный цикл:
- * 1. ordered - заказано у поставщика
- * 2. in_stock - получено на склад
- * 3. shipped - полностью отгружено (available_qty = 0)
- */
- #[ScopedBy([YearScope::class])]
- class SparePartOrder extends Model
- {
- use HasFactory, SoftDeletes;
- const STATUS_ORDERED = 'ordered';
- const STATUS_IN_STOCK = 'in_stock';
- const STATUS_SHIPPED = 'shipped';
- const STATUS_NAMES = [
- self::STATUS_ORDERED => 'Заказано',
- self::STATUS_IN_STOCK => 'На складе',
- self::STATUS_SHIPPED => 'Отгружено',
- ];
- const DEFAULT_SORT_BY = 'created_at';
- protected $fillable = [
- 'year',
- 'spare_part_id',
- 'source_text',
- 'sourceable_id',
- 'sourceable_type',
- 'status',
- 'ordered_quantity',
- 'available_qty',
- 'with_documents',
- 'note',
- 'user_id',
- ];
- protected $casts = [
- 'with_documents' => 'boolean',
- 'ordered_quantity' => 'integer',
- 'available_qty' => 'integer',
- 'year' => 'integer',
- ];
- protected static function boot(): void
- {
- parent::boot();
- static::creating(function ($model) {
- if (!isset($model->year)) {
- $model->year = year();
- }
- if (!isset($model->available_qty)) {
- $model->available_qty = $model->ordered_quantity;
- }
- });
- // Автосмена статуса при полной отгрузке
- static::updating(function ($model) {
- if ($model->available_qty === 0 && $model->status === self::STATUS_IN_STOCK) {
- $model->status = self::STATUS_SHIPPED;
- }
- });
- }
- // ========== ОТНОШЕНИЯ ==========
- public function sparePart(): BelongsTo
- {
- return $this->belongsTo(SparePart::class);
- }
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
- public function sourceable(): MorphTo
- {
- return $this->morphTo();
- }
- /**
- * Резервы из этой партии
- */
- public function reservations(): HasMany
- {
- return $this->hasMany(Reservation::class, 'spare_part_order_id');
- }
- /**
- * Движения по этой партии
- */
- public function movements(): HasMany
- {
- return $this->hasMany(InventoryMovement::class, 'spare_part_order_id');
- }
- /**
- * @deprecated Используйте movements()
- */
- public function shipments(): HasMany
- {
- return $this->hasMany(SparePartOrderShipment::class);
- }
- // ========== SCOPES ==========
- public function scopeInStock($query)
- {
- return $query->where('status', self::STATUS_IN_STOCK);
- }
- public function scopeWithAvailable($query)
- {
- return $query->where('available_qty', '>', 0);
- }
- public function scopeWithDocuments($query, bool $withDocs = true)
- {
- return $query->where('with_documents', $withDocs);
- }
- public function scopeForSparePart($query, int $sparePartId)
- {
- return $query->where('spare_part_id', $sparePartId);
- }
- /**
- * Партии доступные для резервирования (FIFO)
- */
- public function scopeAvailableForReservation($query, int $sparePartId, bool $withDocuments)
- {
- return $query->where('spare_part_id', $sparePartId)
- ->where('with_documents', $withDocuments)
- ->where('status', self::STATUS_IN_STOCK)
- ->where('available_qty', '>', 0)
- ->orderBy('created_at', 'asc');
- }
- // ========== ВЫЧИСЛЯЕМЫЕ ПОЛЯ ==========
- public function getStatusNameAttribute(): string
- {
- return self::STATUS_NAMES[$this->status] ?? $this->status;
- }
- /**
- * Сколько зарезервировано из этой партии
- */
- public function getReservedQtyAttribute(): int
- {
- return (int) ($this->reservations()
- ->where('status', Reservation::STATUS_ACTIVE)
- ->sum('reserved_qty') ?? 0);
- }
- /**
- * Свободно для резервирования (физический остаток минус активные резервы)
- */
- public function getFreeQtyAttribute(): int
- {
- return max(0, $this->available_qty - $this->reserved_qty);
- }
- /**
- * Сколько было списано (через движения issue)
- */
- public function getIssuedQtyAttribute(): int
- {
- return (int) ($this->movements()
- ->where('movement_type', InventoryMovement::TYPE_ISSUE)
- ->sum('qty') ?? 0);
- }
- // ========== МЕТОДЫ ==========
- /**
- * Можно ли зарезервировать указанное количество?
- */
- public function canReserve(int $quantity): bool
- {
- return $this->free_qty >= $quantity;
- }
- /**
- * Проверка статуса
- */
- public function isInStock(): bool
- {
- return $this->status === self::STATUS_IN_STOCK;
- }
- public function isOrdered(): bool
- {
- return $this->status === self::STATUS_ORDERED;
- }
- public function isShipped(): bool
- {
- return $this->status === self::STATUS_SHIPPED;
- }
- // ========== ОБРАТНАЯ СОВМЕСТИМОСТЬ ==========
- /**
- * @deprecated Поле переименовано в available_qty
- */
- public function getRemainingQuantityAttribute(): int
- {
- return $this->available_qty;
- }
- /**
- * @deprecated Используйте SparePartIssueService::issue()
- */
- public function shipQuantity(int $quantity, string $note, ?int $reclamationId = null, ?int $userId = null): bool
- {
- // Оставляем для обратной совместимости, но рекомендуется использовать сервис
- if ($quantity > $this->available_qty) {
- return false;
- }
- $this->available_qty -= $quantity;
- $this->save();
- // Создаём движение для аудита
- InventoryMovement::create([
- 'spare_part_order_id' => $this->id,
- 'spare_part_id' => $this->spare_part_id,
- 'qty' => $quantity,
- 'movement_type' => InventoryMovement::TYPE_ISSUE,
- 'source_type' => $reclamationId ? InventoryMovement::SOURCE_RECLAMATION : InventoryMovement::SOURCE_MANUAL,
- 'source_id' => $reclamationId,
- 'with_documents' => $this->with_documents,
- 'user_id' => $userId ?? auth()->id(),
- 'note' => $note,
- ]);
- return true;
- }
- }
|