SparePart.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. 'min_stock',
  25. ];
  26. protected $appends = [
  27. 'purchase_price',
  28. 'customer_price',
  29. 'expertise_price',
  30. 'purchase_price_txt',
  31. 'customer_price_txt',
  32. 'expertise_price_txt',
  33. 'image',
  34. 'quantity_without_docs',
  35. 'quantity_with_docs',
  36. 'total_quantity',
  37. 'tsn_number_description',
  38. 'pricing_code_description',
  39. 'pricing_codes_list',
  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. public function pricingCodes(): BelongsToMany
  113. {
  114. return $this->belongsToMany(PricingCode::class, 'spare_part_pricing_code')
  115. ->withTimestamps();
  116. }
  117. // ВЫЧИСЛЯЕМЫЕ ПОЛЯ (с учетом текущего года!)
  118. // Примечание: YearScope автоматически применяется к SparePartOrder,
  119. // поэтому явный фильтр по году НЕ нужен
  120. public function getQuantityWithoutDocsAttribute(): int
  121. {
  122. return (int) ($this->orders()
  123. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  124. ->where('with_documents', false)
  125. ->sum('remaining_quantity') ?? 0);
  126. }
  127. public function getQuantityWithDocsAttribute(): int
  128. {
  129. return (int) ($this->orders()
  130. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  131. ->where('with_documents', true)
  132. ->sum('remaining_quantity') ?? 0);
  133. }
  134. public function getTotalQuantityAttribute(): int
  135. {
  136. // Общее количество — сумма всех остатков на складе за текущий год,
  137. // независимо от наличия документов
  138. return (int) ($this->orders()
  139. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  140. ->sum('remaining_quantity') ?? 0);
  141. }
  142. // Методы проверки
  143. public function hasCriticalShortage(): bool
  144. {
  145. return $this->quantity_without_docs < 0 || $this->quantity_with_docs < 0;
  146. }
  147. public function isBelowMinStock(): bool
  148. {
  149. return $this->total_quantity < $this->min_stock && $this->total_quantity >= 0;
  150. }
  151. // Расшифровки из справочника
  152. protected function tsnNumberDescription(): Attribute
  153. {
  154. return Attribute::make(
  155. get: fn() => PricingCode::getTsnDescription($this->tsn_number)
  156. );
  157. }
  158. protected function pricingCodeDescription(): Attribute
  159. {
  160. return Attribute::make(
  161. get: function () {
  162. $codes = $this->pricingCodes;
  163. if ($codes->isEmpty()) {
  164. return null;
  165. }
  166. return $codes->map(fn($code) => $code->code . ($code->description ? ': ' . $code->description : ''))->implode("\n");
  167. }
  168. );
  169. }
  170. public function getPricingCodesListAttribute(): string
  171. {
  172. return $this->pricingCodes->pluck('code')->implode(', ');
  173. }
  174. }