SparePart.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. ];
  64. // Аксессоры для цен (копейки -> рубли)
  65. protected function purchasePrice(): Attribute
  66. {
  67. return Attribute::make(
  68. get: fn($value) => $value === null ? null : $value / 100,
  69. set: fn($value) => $value === null || $value === '' ? null : round($value * 100),
  70. );
  71. }
  72. protected function customerPrice(): Attribute
  73. {
  74. return Attribute::make(
  75. get: fn($value) => $value === null ? null : $value / 100,
  76. set: fn($value) => $value === null || $value === '' ? null : round($value * 100),
  77. );
  78. }
  79. protected function expertisePrice(): Attribute
  80. {
  81. return Attribute::make(
  82. get: fn($value) => $value === null ? null : $value / 100,
  83. set: fn($value) => $value === null || $value === '' ? null : round($value * 100),
  84. );
  85. }
  86. // Текстовое представление цен
  87. protected function purchasePriceTxt(): Attribute
  88. {
  89. return Attribute::make(
  90. get: fn() => isset($this->attributes['purchase_price']) && $this->attributes['purchase_price'] !== null
  91. ? Price::format($this->attributes['purchase_price'] / 100)
  92. : '-',
  93. );
  94. }
  95. protected function customerPriceTxt(): Attribute
  96. {
  97. return Attribute::make(
  98. get: fn() => isset($this->attributes['customer_price']) && $this->attributes['customer_price'] !== null
  99. ? Price::format($this->attributes['customer_price'] / 100)
  100. : '-',
  101. );
  102. }
  103. protected function expertisePriceTxt(): Attribute
  104. {
  105. return Attribute::make(
  106. get: fn() => isset($this->attributes['expertise_price']) && $this->attributes['expertise_price'] !== null
  107. ? Price::format($this->attributes['expertise_price'] / 100)
  108. : '-',
  109. );
  110. }
  111. // Атрибут для картинки
  112. public function image(): Attribute
  113. {
  114. $article = $this->article;
  115. $cacheKey = 'spare_part_image:' . $article;
  116. $path = Cache::remember($cacheKey, 3600, function () use ($article) {
  117. $dir = public_path('images/spare_parts');
  118. $pattern = $dir . '/' . glob_safe($article) . '*.*';
  119. $files = glob($pattern, GLOB_NOSORT);
  120. if (empty($files)) {
  121. return '';
  122. }
  123. $filename = basename($files[0]);
  124. return url('/images/spare_parts/' . rawurlencode($filename));
  125. });
  126. return Attribute::make(get: fn() => $path);
  127. }
  128. // ========== ОТНОШЕНИЯ ==========
  129. public function product(): BelongsTo
  130. {
  131. return $this->belongsTo(Product::class);
  132. }
  133. public function orders(): HasMany
  134. {
  135. return $this->hasMany(SparePartOrder::class);
  136. }
  137. public function reclamations(): BelongsToMany
  138. {
  139. return $this->belongsToMany(Reclamation::class, 'reclamation_spare_part')
  140. ->withPivot('quantity', 'with_documents', 'status', 'reserved_qty', 'issued_qty')
  141. ->withTimestamps();
  142. }
  143. public function pricingCodes(): BelongsToMany
  144. {
  145. return $this->belongsToMany(PricingCode::class, 'spare_part_pricing_code')
  146. ->withTimestamps();
  147. }
  148. public function reservations(): HasMany
  149. {
  150. return $this->hasMany(Reservation::class);
  151. }
  152. public function shortages(): HasMany
  153. {
  154. return $this->hasMany(Shortage::class);
  155. }
  156. public function movements(): HasMany
  157. {
  158. return $this->hasMany(InventoryMovement::class);
  159. }
  160. // ========== ВЫЧИСЛЯЕМЫЕ ПОЛЯ ОСТАТКОВ ==========
  161. /**
  162. * Физический остаток БЕЗ документов
  163. */
  164. public function getPhysicalStockWithoutDocsAttribute(): int
  165. {
  166. return (int) ($this->orders()
  167. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  168. ->where('with_documents', false)
  169. ->sum('available_qty') ?? 0);
  170. }
  171. /**
  172. * Физический остаток С документами
  173. */
  174. public function getPhysicalStockWithDocsAttribute(): int
  175. {
  176. return (int) ($this->orders()
  177. ->where('status', SparePartOrder::STATUS_IN_STOCK)
  178. ->where('with_documents', true)
  179. ->sum('available_qty') ?? 0);
  180. }
  181. /**
  182. * Зарезервировано БЕЗ документов
  183. */
  184. public function getReservedWithoutDocsAttribute(): int
  185. {
  186. return (int) (Reservation::query()
  187. ->where('spare_part_id', $this->id)
  188. ->where('with_documents', false)
  189. ->where('status', Reservation::STATUS_ACTIVE)
  190. ->sum('reserved_qty') ?? 0);
  191. }
  192. /**
  193. * Зарезервировано С документами
  194. */
  195. public function getReservedWithDocsAttribute(): int
  196. {
  197. return (int) (Reservation::query()
  198. ->where('spare_part_id', $this->id)
  199. ->where('with_documents', true)
  200. ->where('status', Reservation::STATUS_ACTIVE)
  201. ->sum('reserved_qty') ?? 0);
  202. }
  203. /**
  204. * Свободный остаток БЕЗ документов
  205. */
  206. public function getFreeStockWithoutDocsAttribute(): int
  207. {
  208. return $this->physical_stock_without_docs - $this->reserved_without_docs;
  209. }
  210. /**
  211. * Свободный остаток С документами
  212. */
  213. public function getFreeStockWithDocsAttribute(): int
  214. {
  215. return $this->physical_stock_with_docs - $this->reserved_with_docs;
  216. }
  217. /**
  218. * Общий физический остаток
  219. */
  220. public function getTotalPhysicalStockAttribute(): int
  221. {
  222. return $this->physical_stock_without_docs + $this->physical_stock_with_docs;
  223. }
  224. /**
  225. * Общее зарезервировано
  226. */
  227. public function getTotalReservedAttribute(): int
  228. {
  229. return $this->reserved_without_docs + $this->reserved_with_docs;
  230. }
  231. /**
  232. * Общий свободный остаток
  233. */
  234. public function getTotalFreeStockAttribute(): int
  235. {
  236. return $this->total_physical_stock - $this->total_reserved;
  237. }
  238. // ========== ОБРАТНАЯ СОВМЕСТИМОСТЬ ==========
  239. // Старые атрибуты для совместимости с существующим кодом
  240. public function getQuantityWithoutDocsAttribute(): int
  241. {
  242. return $this->free_stock_without_docs;
  243. }
  244. public function getQuantityWithDocsAttribute(): int
  245. {
  246. return $this->free_stock_with_docs;
  247. }
  248. public function getTotalQuantityAttribute(): int
  249. {
  250. return $this->total_free_stock;
  251. }
  252. // ========== МЕТОДЫ ПРОВЕРКИ ==========
  253. /**
  254. * Есть ли открытые дефициты?
  255. */
  256. public function hasOpenShortages(): bool
  257. {
  258. return $this->shortages()->open()->exists();
  259. }
  260. /**
  261. * Количество в открытых дефицитах
  262. */
  263. public function getOpenShortagesQtyAttribute(): int
  264. {
  265. return (int) ($this->shortages()->open()->sum('missing_qty') ?? 0);
  266. }
  267. /**
  268. * Ниже минимального остатка?
  269. */
  270. public function isBelowMinStock(): bool
  271. {
  272. return $this->total_free_stock < $this->min_stock;
  273. }
  274. /**
  275. * @deprecated Используйте hasOpenShortages()
  276. */
  277. public function hasCriticalShortage(): bool
  278. {
  279. return $this->hasOpenShortages();
  280. }
  281. // ========== РАСШИФРОВКИ ==========
  282. protected function tsnNumberDescription(): Attribute
  283. {
  284. return Attribute::make(
  285. get: fn() => PricingCode::getTsnDescription($this->tsn_number)
  286. );
  287. }
  288. protected function pricingCodeDescription(): Attribute
  289. {
  290. return Attribute::make(
  291. get: function () {
  292. $codes = $this->pricingCodes;
  293. if ($codes->isEmpty()) {
  294. return null;
  295. }
  296. return $codes->map(fn($code) => $code->code . ($code->description ? ': ' . $code->description : ''))->implode("\n");
  297. }
  298. );
  299. }
  300. public function getPricingCodesListAttribute(): string
  301. {
  302. return $this->pricingCodes->pluck('code')->implode(', ');
  303. }
  304. // ========== ВСПОМОГАТЕЛЬНЫЕ МЕТОДЫ ==========
  305. /**
  306. * Получить свободный остаток для конкретного типа документов
  307. */
  308. public function getFreeStock(bool $withDocuments): int
  309. {
  310. return $withDocuments
  311. ? $this->free_stock_with_docs
  312. : $this->free_stock_without_docs;
  313. }
  314. /**
  315. * Получить физический остаток для конкретного типа документов
  316. */
  317. public function getPhysicalStock(bool $withDocuments): int
  318. {
  319. return $withDocuments
  320. ? $this->physical_stock_with_docs
  321. : $this->physical_stock_without_docs;
  322. }
  323. /**
  324. * Получить зарезервировано для конкретного типа документов
  325. */
  326. public function getReserved(bool $withDocuments): int
  327. {
  328. return $withDocuments
  329. ? $this->reserved_with_docs
  330. : $this->reserved_without_docs;
  331. }
  332. }