Product.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Models;
  3. use App\Helpers\Price;
  4. use App\Models\Scopes\YearScope;
  5. use Illuminate\Database\Eloquent\Attributes\ScopedBy;
  6. use Illuminate\Database\Eloquent\Casts\Attribute;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  9. use Illuminate\Database\Eloquent\SoftDeletes;
  10. use Illuminate\Support\Facades\DB;
  11. #[ScopedBy([YearScope::class])]
  12. class Product extends Model
  13. {
  14. use SoftDeletes;
  15. const DEFAULT_SORT_BY = 'article';
  16. protected $fillable = [
  17. 'year',
  18. 'article',
  19. 'name_tz',
  20. 'type_tz',
  21. 'nomenclature_number',
  22. 'sizes',
  23. 'manufacturer',
  24. 'unit',
  25. 'type',
  26. 'product_price',
  27. 'installation_price',
  28. 'total_price',
  29. 'manufacturer_name',
  30. 'note',
  31. ];
  32. protected $appends = ['product_price', 'installation_price', 'total_price',
  33. 'product_price_txt', 'installation_price_txt', 'total_price_txt',];
  34. protected function productPrice(): Attribute
  35. {
  36. return Attribute::make(
  37. get: fn(int $value) => (float) $value / 100,
  38. set: fn (float $value) => (int) ($value * 100),
  39. );
  40. }
  41. protected function installationPrice(): Attribute
  42. {
  43. return Attribute::make(
  44. get: fn(int $value) => (float) $value / 100,
  45. set: fn (float $value) => (int) ($value * 100),
  46. );
  47. }
  48. protected function totalPrice(): Attribute
  49. {
  50. return Attribute::make(
  51. get: fn(int $value) => (float) $value / 100,
  52. set: fn (float $value) => (int) ($value * 100),
  53. );
  54. }
  55. public function productPriceTxt(): Attribute
  56. {
  57. return Attribute::make(
  58. get: fn($value) => Price::format($this->product_price),
  59. );
  60. }
  61. public function installationPriceTxt(): Attribute
  62. {
  63. return Attribute::make(
  64. get: fn($value) => Price::format($this->installation_price),
  65. );
  66. }
  67. protected function totalPriceTxt(): Attribute
  68. {
  69. return Attribute::make(
  70. get: fn($value) => Price::format($this->total_price),
  71. );
  72. }
  73. public function commonName(): Attribute
  74. {
  75. return Attribute::make(
  76. get: fn($value) => $this->article . ', №' . $this->nomenclature_number,
  77. // get: fn($value) => (string) $this->name_tz . ' (арт.' . $this->article . ', №' . $this->nomenclature_number . ', ' . $this->year . 'г, ' . $this->product_price_txt . ')',
  78. );
  79. }
  80. /**
  81. * @return BelongsToMany
  82. */
  83. public function orders(): BelongsToMany
  84. {
  85. return $this->belongsToMany(Order::class, 'products_sku', 'order_id', 'product_id');
  86. }
  87. }