OrderView.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. ];
  37. public $appends = ['common_name', 'move_maf_name', 'products_with_count'];
  38. public function commonName(): Attribute
  39. {
  40. return Attribute::make(
  41. get: fn($value) => (string) $this->object_address . ', ' . $this->area_name . ', ' . $this->district_name,
  42. );
  43. }
  44. public function moveMafName(): Attribute
  45. {
  46. return Attribute::make(
  47. get: fn ($value) => trim($this->common_name . ($this->name ? ' | ' . $this->name : '')),
  48. );
  49. }
  50. public function productsWithCount(): Attribute
  51. {
  52. $products = ProductSKU::query()->where('order_id', $this->id)->get(); //$this->products_sku;
  53. $ret = [];
  54. foreach ($products as $product) {
  55. if(isset($ret[$product->product->id])) {
  56. $ret[$product->product->id]['count'] += 1;
  57. } else {
  58. $ret[$product->product->id] = [
  59. 'name' => $product->product->article,
  60. 'count' => 1,
  61. ];
  62. }
  63. if($product->maf_order?->order_number) {
  64. $ret[$product->product->id]['order_numbers'][] = $product->maf_order?->order_number;
  65. }
  66. }
  67. $s = '';
  68. $openTag = '<div>';
  69. $closeTag = '</div>';
  70. foreach ($ret as $product) {
  71. $order_numbers = (isset($product['order_numbers'])) ? ' (' . implode(', ', array_unique($product['order_numbers'])) . ')' : '';
  72. $s .= $openTag . $product['name'] . ' - ' . $product['count'] . $order_numbers . $closeTag;
  73. }
  74. return Attribute::make(
  75. get: fn($value) => (string) $s,
  76. );
  77. }
  78. }