OrderView.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Models;
  3. use App\Models\Scopes\YearScope;
  4. use Illuminate\Database\Eloquent\Attributes\ScopedBy;
  5. use Illuminate\Database\Eloquent\Casts\Attribute;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Database\Eloquent\SoftDeletes;
  8. #[ScopedBy([YearScope::class])]
  9. class OrderView extends Model
  10. {
  11. use SoftDeletes;
  12. const DEFAULT_SORT_BY = 'created_at';
  13. protected $table = 'orders_view';
  14. protected $fillable = [
  15. 'year',
  16. 'name',
  17. 'user_id',
  18. 'district_id',
  19. 'area_id',
  20. 'object_address',
  21. 'object_type_id',
  22. 'comment',
  23. 'installation_date',
  24. 'ready_date',
  25. 'brigadier_id',
  26. 'order_status_id',
  27. 'tg_group_name',
  28. 'tg_group_link',
  29. 'ready_to_mount',
  30. 'user_name',
  31. 'district_name',
  32. 'area_name',
  33. 'object_type_name',
  34. 'brigadier_name',
  35. 'order_status_name',
  36. 'products_total',
  37. ];
  38. public $appends = ['common_name', 'move_maf_name', 'products_with_count'];
  39. public function commonName(): Attribute
  40. {
  41. return Attribute::make(
  42. get: fn($value) => (string) $this->object_address . ', ' . $this->area_name . ', ' . $this->district_name,
  43. );
  44. }
  45. public function moveMafName(): Attribute
  46. {
  47. return Attribute::make(
  48. get: fn ($value) => trim($this->common_name . ($this->name ? ' | ' . $this->name : '')),
  49. );
  50. }
  51. public function productsWithCount(): Attribute
  52. {
  53. $products = ProductSKU::query()->where('order_id', $this->id)->get(); //$this->products_sku;
  54. $ret = [];
  55. foreach ($products as $product) {
  56. if(isset($ret[$product->product->id])) {
  57. $ret[$product->product->id]['count'] += 1;
  58. } else {
  59. $ret[$product->product->id] = [
  60. 'name' => $product->product->article,
  61. 'count' => 1,
  62. ];
  63. }
  64. if($product->maf_order?->order_number) {
  65. $ret[$product->product->id]['order_numbers'][] = $product->maf_order?->order_number;
  66. }
  67. }
  68. $s = '';
  69. $openTag = '<div>';
  70. $closeTag = '</div>';
  71. foreach ($ret as $product) {
  72. $order_numbers = (isset($product['order_numbers'])) ? ' (' . implode(', ', array_unique($product['order_numbers'])) . ')' : '';
  73. $s .= $openTag . $product['name'] . ' - ' . $product['count'] . $order_numbers . $closeTag;
  74. }
  75. return Attribute::make(
  76. get: fn($value) => (string) $s,
  77. );
  78. }
  79. }