SparePart.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. <?php
  2. namespace App\Models;
  3. use App\Helpers\Price;
  4. use Illuminate\Database\Eloquent\Casts\Attribute;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  7. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  8. use Illuminate\Database\Eloquent\Relations\HasMany;
  9. use Illuminate\Database\Eloquent\SoftDeletes;
  10. class SparePart extends Model
  11. {
  12. use SoftDeletes;
  13. const DEFAULT_SORT_BY = 'article';
  14. protected $fillable = [
  15. // БЕЗ year! Каталог общий для всех лет
  16. 'article',
  17. 'used_in_maf',
  18. 'product_id',
  19. 'note',
  20. 'purchase_price',
  21. 'customer_price',
  22. 'expertise_price',
  23. 'tsn_number',
  24. 'pricing_code',
  25. 'min_stock',
  26. ];
  27. protected $appends = [
  28. 'purchase_price',
  29. 'customer_price',
  30. 'expertise_price',
  31. 'purchase_price_txt',
  32. 'customer_price_txt',
  33. 'expertise_price_txt',
  34. 'image',
  35. 'quantity_without_docs',
  36. 'quantity_with_docs',
  37. 'total_quantity',
  38. 'tsn_number_description',
  39. 'pricing_code_description',
  40. ];
  41. // Аксессоры для цен (копейки -> рубли)
  42. protected function purchasePrice(): Attribute
  43. {
  44. return Attribute::make(
  45. get: fn($value) => $value ? $value / 100 : null,
  46. set: fn($value) => $value ? round($value * 100) : null,
  47. );
  48. }
  49. protected function customerPrice(): Attribute
  50. {
  51. return Attribute::make(
  52. get: fn($value) => $value ? $value / 100 : null,
  53. set: fn($value) => $value ? round($value * 100) : null,
  54. );
  55. }
  56. protected function expertisePrice(): Attribute
  57. {
  58. return Attribute::make(
  59. get: fn($value) => $value ? $value / 100 : null,
  60. set: fn($value) => $value ? round($value * 100) : null,
  61. );
  62. }
  63. // Текстовое представление цен
  64. protected function purchasePriceTxt(): Attribute
  65. {
  66. return Attribute::make(
  67. get: fn() => isset($this->attributes['purchase_price']) && $this->attributes['purchase_price'] !== null
  68. ? Price::format($this->attributes['purchase_price'] / 100)
  69. : '-',
  70. );
  71. }
  72. protected function customerPriceTxt(): Attribute
  73. {
  74. return Attribute::make(
  75. get: fn() => isset($this->attributes['customer_price']) && $this->attributes['customer_price'] !== null
  76. ? Price::format($this->attributes['customer_price'] / 100)
  77. : '-',
  78. );
  79. }
  80. protected function expertisePriceTxt(): Attribute
  81. {
  82. return Attribute::make(
  83. get: fn() => isset($this->attributes['expertise_price']) && $this->attributes['expertise_price'] !== null
  84. ? Price::format($this->attributes['expertise_price'] / 100)
  85. : '-',
  86. );
  87. }
  88. // Атрибут для картинки
  89. public function image(): Attribute
  90. {
  91. $path = '';
  92. if (file_exists(public_path() . '/images/spare_parts/' . $this->article . '.jpg')) {
  93. $path = url('/images/spare_parts/' . $this->article . '.jpg');
  94. }
  95. return Attribute::make(get: fn() => $path);
  96. }
  97. // Отношения
  98. public function product(): BelongsTo
  99. {
  100. return $this->belongsTo(Product::class);
  101. }
  102. public function orders(): HasMany
  103. {
  104. return $this->hasMany(SparePartOrder::class);
  105. }
  106. public function reclamations(): BelongsToMany
  107. {
  108. return $this->belongsToMany(Reclamation::class, 'reclamation_spare_part')
  109. ->withPivot('quantity', 'with_documents')
  110. ->withTimestamps();
  111. }
  112. // ВЫЧИСЛЯЕМЫЕ ПОЛЯ (с учетом текущего года!)
  113. // Примечание: YearScope автоматически применяется к SparePartOrder,
  114. // поэтому явный фильтр по году НЕ нужен
  115. public function getQuantityWithoutDocsAttribute(): int
  116. {
  117. return (int) ($this->orders()
  118. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  119. ->where('with_documents', false)
  120. ->sum('remaining_quantity') ?? 0);
  121. }
  122. public function getQuantityWithDocsAttribute(): int
  123. {
  124. return (int) ($this->orders()
  125. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  126. ->where('with_documents', true)
  127. ->sum('remaining_quantity') ?? 0);
  128. }
  129. public function getTotalQuantityAttribute(): int
  130. {
  131. // Общее количество — сумма всех остатков на складе за текущий год,
  132. // независимо от наличия документов
  133. return (int) ($this->orders()
  134. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  135. ->sum('remaining_quantity') ?? 0);
  136. }
  137. // Методы проверки
  138. public function hasCriticalShortage(): bool
  139. {
  140. return $this->quantity_without_docs < 0 || $this->quantity_with_docs < 0;
  141. }
  142. public function isBelowMinStock(): bool
  143. {
  144. return $this->total_quantity < $this->min_stock && $this->total_quantity >= 0;
  145. }
  146. // Расшифровки из справочника
  147. protected function tsnNumberDescription(): Attribute
  148. {
  149. return Attribute::make(
  150. get: fn() => PricingCode::getTsnDescription($this->tsn_number)
  151. );
  152. }
  153. protected function pricingCodeDescription(): Attribute
  154. {
  155. return Attribute::make(
  156. get: fn() => PricingCode::getPricingCodeDescription($this->pricing_code)
  157. );
  158. }
  159. }