StockOrder.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Models;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  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\SoftDeletes;
  9. class StockOrder extends Model
  10. {
  11. use HasFactory, SoftDeletes;
  12. public const STATUS_ORDERED = 'ordered';
  13. public const STATUS_IN_STOCK = 'in_stock';
  14. public const STATUS_SHIPPED = 'shipped';
  15. public const STATUS_NAMES = [
  16. self::STATUS_ORDERED => 'Заказан',
  17. self::STATUS_IN_STOCK => 'На складе',
  18. self::STATUS_SHIPPED => 'Отгружено',
  19. ];
  20. protected $fillable = [
  21. 'common_catalog_item_id',
  22. 'order_number',
  23. 'status',
  24. 'ordered_quantity',
  25. 'available_quantity',
  26. 'note',
  27. 'user_id',
  28. ];
  29. protected function casts(): array
  30. {
  31. return [
  32. 'common_catalog_item_id' => 'integer',
  33. 'ordered_quantity' => 'integer',
  34. 'available_quantity' => 'integer',
  35. 'user_id' => 'integer',
  36. ];
  37. }
  38. public function item(): BelongsTo
  39. {
  40. return $this->belongsTo(CommonCatalogItem::class, 'common_catalog_item_id');
  41. }
  42. public function user(): BelongsTo
  43. {
  44. return $this->belongsTo(User::class);
  45. }
  46. public function reservations(): HasMany
  47. {
  48. return $this->hasMany(StockReservation::class);
  49. }
  50. public function movements(): HasMany
  51. {
  52. return $this->hasMany(StockMovement::class);
  53. }
  54. public function getStatusNameAttribute(): string
  55. {
  56. return self::STATUS_NAMES[$this->status] ?? $this->status;
  57. }
  58. public function getReservedQuantityAttribute(): int
  59. {
  60. if (array_key_exists('active_reservations_sum_quantity', $this->attributes)) {
  61. return (int) $this->attributes['active_reservations_sum_quantity'];
  62. }
  63. return (int) $this->reservations()->active()->sum('quantity');
  64. }
  65. public function getFreeQuantityAttribute(): int
  66. {
  67. return max(0, $this->available_quantity - $this->reserved_quantity);
  68. }
  69. }