SparePart.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <?php
  2. namespace App\Models;
  3. use App\Helpers\Price;
  4. use Illuminate\Database\Eloquent\Casts\Attribute;
  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\BelongsToMany;
  9. use Illuminate\Database\Eloquent\Relations\HasMany;
  10. use Illuminate\Database\Eloquent\SoftDeletes;
  11. use Illuminate\Support\Facades\Cache;
  12. /**
  13. * Каталог запчастей — СПРАВОЧНИК.
  14. *
  15. * ВАЖНО: Эта модель НЕ хранит остатки!
  16. * Остатки рассчитываются на основе:
  17. * - SparePartOrder.available_qty (физический остаток)
  18. * - Reservation (активные резервы)
  19. *
  20. * Свободный остаток = Физический - Зарезервировано
  21. */
  22. class SparePart extends Model
  23. {
  24. use HasFactory, SoftDeletes;
  25. const DEFAULT_SORT_BY = 'article';
  26. protected $fillable = [
  27. // БЕЗ year! Каталог общий для всех лет
  28. 'article',
  29. 'used_in_maf',
  30. 'product_id',
  31. 'note',
  32. 'purchase_price',
  33. 'customer_price',
  34. 'expertise_price',
  35. 'tsn_number',
  36. 'min_stock',
  37. ];
  38. /**
  39. * Атрибуты для автоматической сериализации.
  40. *
  41. * ВАЖНО: Подробные остатки (physical_stock_*, reserved_*, free_stock_*) НЕ включены сюда,
  42. * т.к. согласно спецификации каталог не хранит остатки.
  43. * Для получения детальных остатков используйте SparePartInventoryService::getStockInfo()
  44. * или явно вызывайте соответствующие аксессоры.
  45. *
  46. * Атрибуты quantity_* оставлены для обратной совместимости с UI.
  47. */
  48. protected $appends = [
  49. 'purchase_price',
  50. 'customer_price',
  51. 'expertise_price',
  52. 'purchase_price_txt',
  53. 'customer_price_txt',
  54. 'expertise_price_txt',
  55. 'image',
  56. 'tsn_number_description',
  57. 'pricing_code_description',
  58. 'pricing_codes_list',
  59. // Обратная совместимость для UI (отображаются как свободный остаток)
  60. 'quantity_without_docs',
  61. 'quantity_with_docs',
  62. 'total_quantity',
  63. 'ordered_without_docs',
  64. 'ordered_with_docs',
  65. 'total_ordered',
  66. ];
  67. // Аксессоры для цен (копейки -> рубли)
  68. protected function purchasePrice(): Attribute
  69. {
  70. return Attribute::make(
  71. get: fn($value) => $value === null ? null : $value / 100,
  72. set: fn($value) => $value === null || $value === '' ? null : round($value * 100),
  73. );
  74. }
  75. protected function customerPrice(): Attribute
  76. {
  77. return Attribute::make(
  78. get: fn($value) => $value === null ? null : $value / 100,
  79. set: fn($value) => $value === null || $value === '' ? null : round($value * 100),
  80. );
  81. }
  82. protected function expertisePrice(): Attribute
  83. {
  84. return Attribute::make(
  85. get: fn($value) => $value === null ? null : $value / 100,
  86. set: fn($value) => $value === null || $value === '' ? null : round($value * 100),
  87. );
  88. }
  89. // Текстовое представление цен
  90. protected function purchasePriceTxt(): Attribute
  91. {
  92. return Attribute::make(
  93. get: fn() => isset($this->attributes['purchase_price']) && $this->attributes['purchase_price'] !== null
  94. ? Price::format($this->attributes['purchase_price'] / 100)
  95. : '-',
  96. );
  97. }
  98. protected function customerPriceTxt(): Attribute
  99. {
  100. return Attribute::make(
  101. get: fn() => isset($this->attributes['customer_price']) && $this->attributes['customer_price'] !== null
  102. ? Price::format($this->attributes['customer_price'] / 100)
  103. : '-',
  104. );
  105. }
  106. protected function expertisePriceTxt(): Attribute
  107. {
  108. return Attribute::make(
  109. get: fn() => isset($this->attributes['expertise_price']) && $this->attributes['expertise_price'] !== null
  110. ? Price::format($this->attributes['expertise_price'] / 100)
  111. : '-',
  112. );
  113. }
  114. // Атрибут для картинки
  115. public function image(): Attribute
  116. {
  117. $article = $this->article;
  118. $cacheKey = 'spare_part_image:' . $article;
  119. $path = Cache::remember($cacheKey, 3600, function () use ($article) {
  120. $dir = public_path('images/spare_parts');
  121. $pattern = $dir . '/' . glob_safe($article) . '*.*';
  122. $files = glob($pattern, GLOB_NOSORT);
  123. if (empty($files)) {
  124. return '';
  125. }
  126. $filename = basename($files[0]);
  127. return url('/images/spare_parts/' . rawurlencode($filename));
  128. });
  129. return Attribute::make(get: fn() => $path);
  130. }
  131. // ========== ОТНОШЕНИЯ ==========
  132. public function product(): BelongsTo
  133. {
  134. return $this->belongsTo(Product::class);
  135. }
  136. public function orders(): HasMany
  137. {
  138. return $this->hasMany(SparePartOrder::class);
  139. }
  140. public function reclamations(): BelongsToMany
  141. {
  142. return $this->belongsToMany(Reclamation::class, 'reclamation_spare_part')
  143. ->withPivot('quantity', 'with_documents', 'status', 'reserved_qty', 'issued_qty')
  144. ->withTimestamps();
  145. }
  146. public function pricingCodes(): BelongsToMany
  147. {
  148. return $this->belongsToMany(PricingCode::class, 'spare_part_pricing_code')
  149. ->withTimestamps();
  150. }
  151. public function reservations(): HasMany
  152. {
  153. return $this->hasMany(Reservation::class);
  154. }
  155. public function shortages(): HasMany
  156. {
  157. return $this->hasMany(Shortage::class);
  158. }
  159. public function movements(): HasMany
  160. {
  161. return $this->hasMany(InventoryMovement::class);
  162. }
  163. // ========== ВЫЧИСЛЯЕМЫЕ ПОЛЯ ОСТАТКОВ ==========
  164. /**
  165. * Физический остаток БЕЗ документов
  166. */
  167. public function getPhysicalStockWithoutDocsAttribute(): int
  168. {
  169. return (int) ($this->orders()
  170. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  171. ->where('with_documents', false)
  172. ->sum('available_qty') ?? 0);
  173. }
  174. /**
  175. * Физический остаток С документами
  176. */
  177. public function getPhysicalStockWithDocsAttribute(): int
  178. {
  179. return (int) ($this->orders()
  180. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  181. ->where('with_documents', true)
  182. ->sum('available_qty') ?? 0);
  183. }
  184. /**
  185. * Зарезервировано БЕЗ документов
  186. */
  187. public function getReservedWithoutDocsAttribute(): int
  188. {
  189. return (int) (Reservation::query()
  190. ->where('spare_part_id', $this->id)
  191. ->where('with_documents', false)
  192. ->where('status', Reservation::STATUS_ACTIVE)
  193. ->sum('reserved_qty') ?? 0);
  194. }
  195. /**
  196. * Зарезервировано С документами
  197. */
  198. public function getReservedWithDocsAttribute(): int
  199. {
  200. return (int) (Reservation::query()
  201. ->where('spare_part_id', $this->id)
  202. ->where('with_documents', true)
  203. ->where('status', Reservation::STATUS_ACTIVE)
  204. ->sum('reserved_qty') ?? 0);
  205. }
  206. /**
  207. * Свободный остаток БЕЗ документов
  208. */
  209. public function getFreeStockWithoutDocsAttribute(): int
  210. {
  211. return $this->physical_stock_without_docs - $this->reserved_without_docs;
  212. }
  213. /**
  214. * Свободный остаток С документами
  215. */
  216. public function getFreeStockWithDocsAttribute(): int
  217. {
  218. return $this->physical_stock_with_docs - $this->reserved_with_docs;
  219. }
  220. /**
  221. * Общий физический остаток
  222. */
  223. public function getTotalPhysicalStockAttribute(): int
  224. {
  225. return $this->physical_stock_without_docs + $this->physical_stock_with_docs;
  226. }
  227. /**
  228. * Общее зарезервировано
  229. */
  230. public function getTotalReservedAttribute(): int
  231. {
  232. return $this->reserved_without_docs + $this->reserved_with_docs;
  233. }
  234. public function getOrderedWithoutDocsAttribute(): int
  235. {
  236. return (int) ($this->orders()
  237. ->where('status', SparePartOrder::STATUS_ORDERED)
  238. ->where('with_documents', false)
  239. ->sum('ordered_quantity') ?? 0);
  240. }
  241. public function getOrderedWithDocsAttribute(): int
  242. {
  243. return (int) ($this->orders()
  244. ->where('status', SparePartOrder::STATUS_ORDERED)
  245. ->where('with_documents', true)
  246. ->sum('ordered_quantity') ?? 0);
  247. }
  248. public function getTotalOrderedAttribute(): int
  249. {
  250. return $this->ordered_without_docs + $this->ordered_with_docs;
  251. }
  252. /**
  253. * Общий свободный остаток
  254. */
  255. public function getTotalFreeStockAttribute(): int
  256. {
  257. return $this->total_physical_stock - $this->total_reserved;
  258. }
  259. // ========== ОБРАТНАЯ СОВМЕСТИМОСТЬ ==========
  260. // Старые атрибуты для совместимости с существующим кодом
  261. public function getQuantityWithoutDocsAttribute(): int
  262. {
  263. return $this->free_stock_without_docs;
  264. }
  265. public function getQuantityWithDocsAttribute(): int
  266. {
  267. return $this->free_stock_with_docs;
  268. }
  269. public function getTotalQuantityAttribute(): int
  270. {
  271. return $this->total_free_stock;
  272. }
  273. // ========== МЕТОДЫ ПРОВЕРКИ ==========
  274. /**
  275. * Есть ли открытые дефициты?
  276. */
  277. public function hasOpenShortages(): bool
  278. {
  279. return $this->shortages()->open()->exists();
  280. }
  281. /**
  282. * Количество в открытых дефицитах
  283. */
  284. public function getOpenShortagesQtyAttribute(): int
  285. {
  286. return (int) ($this->shortages()->open()->sum('missing_qty') ?? 0);
  287. }
  288. /**
  289. * Ниже минимального остатка?
  290. */
  291. public function isBelowMinStock(): bool
  292. {
  293. return $this->total_free_stock < $this->min_stock;
  294. }
  295. /**
  296. * @deprecated Используйте hasOpenShortages()
  297. */
  298. public function hasCriticalShortage(): bool
  299. {
  300. return $this->hasOpenShortages();
  301. }
  302. // ========== РАСШИФРОВКИ ==========
  303. protected function tsnNumberDescription(): Attribute
  304. {
  305. return Attribute::make(
  306. get: fn() => PricingCode::getTsnDescription($this->tsn_number)
  307. );
  308. }
  309. protected function pricingCodeDescription(): Attribute
  310. {
  311. return Attribute::make(
  312. get: function () {
  313. $codes = $this->pricingCodes;
  314. if ($codes->isEmpty()) {
  315. return null;
  316. }
  317. return $codes->map(fn($code) => $code->code . ($code->description ? ': ' . $code->description : ''))->implode("\n");
  318. }
  319. );
  320. }
  321. public function getPricingCodesListAttribute(): string
  322. {
  323. return $this->pricingCodes->pluck('code')->implode(', ');
  324. }
  325. // ========== ВСПОМОГАТЕЛЬНЫЕ МЕТОДЫ ==========
  326. /**
  327. * Получить свободный остаток для конкретного типа документов
  328. */
  329. public function getFreeStock(bool $withDocuments): int
  330. {
  331. return $withDocuments
  332. ? $this->free_stock_with_docs
  333. : $this->free_stock_without_docs;
  334. }
  335. /**
  336. * Получить физический остаток для конкретного типа документов
  337. */
  338. public function getPhysicalStock(bool $withDocuments): int
  339. {
  340. return $withDocuments
  341. ? $this->physical_stock_with_docs
  342. : $this->physical_stock_without_docs;
  343. }
  344. /**
  345. * Получить зарезервировано для конкретного типа документов
  346. */
  347. public function getReserved(bool $withDocuments): int
  348. {
  349. return $withDocuments
  350. ? $this->reserved_with_docs
  351. : $this->reserved_without_docs;
  352. }
  353. }