Order.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. namespace App\Models;
  3. use App\Helpers\Price;
  4. use App\Jobs\GenerateInstallationPack;
  5. use App\Models\Dictionary\Area;
  6. use App\Models\Dictionary\District;
  7. use App\Models\Scopes\YearScope;
  8. use Illuminate\Database\Eloquent\Attributes\ScopedBy;
  9. use Illuminate\Database\Eloquent\Casts\Attribute;
  10. use Illuminate\Database\Eloquent\Factories\HasFactory;
  11. use Illuminate\Database\Eloquent\Model;
  12. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  13. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  14. use Illuminate\Database\Eloquent\Relations\HasMany;
  15. use Illuminate\Database\Eloquent\Relations\HasManyThrough;
  16. use Illuminate\Database\Eloquent\SoftDeletes;
  17. use Illuminate\Support\Facades\DB;
  18. #[ScopedBy([YearScope::class])]
  19. class Order extends Model
  20. {
  21. use HasFactory, SoftDeletes;
  22. const DEFAULT_SORT_BY = 'created_at';
  23. const STATUS_NEW = 1;
  24. const STATUS_NOT_READY = 2;
  25. const STATUS_READY_NO_MAF = 3;
  26. const STATUS_READY_TO_MOUNT = 4;
  27. const STATUS_IN_MOUNT = 5;
  28. const STATUS_DUTY = 6;
  29. const STATUS_READY_TO_HAND_OVER = 7;
  30. const STATUS_NOT_HANDED_OVER_WITH_NOTES = 8;
  31. const STATUS_HANDED_OVER_WITH_NOTES = 9;
  32. const STATUS_HANDED_OVER = 10;
  33. const STATUS_NO_MAF = 11;
  34. const STATUS_PROBLEM = 12;
  35. //ПЛ не готова; ПЛ готова нет МАФ; Готов к монтажу; В монтаже; Долг;Готов к сдаче;Не сдан, замечания;Сдан с замечаниями;Сдан;Проблема
  36. const STATUS_NAMES = [
  37. self::STATUS_NEW => 'Новая',
  38. self::STATUS_NOT_READY => 'Не готова',
  39. self::STATUS_READY_NO_MAF => 'Готова, нет МАФ',
  40. self::STATUS_READY_TO_MOUNT => 'Готова к монтажу',
  41. self::STATUS_IN_MOUNT => 'В монтаже',
  42. self::STATUS_DUTY => 'Долг',
  43. self::STATUS_READY_TO_HAND_OVER => 'Готова к сдаче',
  44. self::STATUS_NOT_HANDED_OVER_WITH_NOTES => 'Не сдана, замечания',
  45. self::STATUS_HANDED_OVER_WITH_NOTES => 'Сдана с замечаниями',
  46. self::STATUS_HANDED_OVER => 'Сдана',
  47. self::STATUS_NO_MAF => 'Отсутствуют МАФ',
  48. self::STATUS_PROBLEM => 'Проблема',
  49. ];
  50. const STATUS_COLOR = [
  51. self::STATUS_NEW => 'dark',
  52. self::STATUS_NOT_READY => 'dark',
  53. self::STATUS_READY_NO_MAF => 'light',
  54. self::STATUS_READY_TO_MOUNT => 'primary',
  55. self::STATUS_IN_MOUNT => 'info',
  56. self::STATUS_DUTY => 'warning',
  57. self::STATUS_READY_TO_HAND_OVER => 'primary',
  58. self::STATUS_NOT_HANDED_OVER_WITH_NOTES => 'warning',
  59. self::STATUS_HANDED_OVER_WITH_NOTES => 'info',
  60. self::STATUS_HANDED_OVER => 'success',
  61. self::STATUS_NO_MAF => 'secondary',
  62. self::STATUS_PROBLEM => 'danger',
  63. ];
  64. public const BRIGADIER_HIDDEN_STATUS_IDS = [
  65. self::STATUS_HANDED_OVER,
  66. ];
  67. // set year attribute to current selected year
  68. protected static function boot(): void
  69. {
  70. parent::boot();
  71. static::creating(function($attributes) {
  72. if(!isset($attributes->year)) {
  73. $attributes->year = year();
  74. }
  75. });
  76. }
  77. protected $fillable = [
  78. 'year',
  79. 'name',
  80. 'user_id',
  81. 'district_id',
  82. 'area_id',
  83. 'object_address',
  84. 'object_type_id',
  85. 'comment',
  86. 'installation_date',
  87. 'ready_date',
  88. 'brigadier_id',
  89. 'order_status_id',
  90. 'tg_group_name',
  91. 'tg_group_link',
  92. 'ready_to_mount',
  93. 'install_days',
  94. ];
  95. public $appends = ['common_name', 'move_maf_name', 'products_with_count'];
  96. public function products_sku(): HasMany
  97. {
  98. return $this->hasMany(ProductSKU::class, 'order_id', 'id');
  99. }
  100. public function products(): HasManyThrough
  101. {
  102. return $this->hasManyThrough(
  103. Product::class,
  104. ProductSKU::class,
  105. 'order_id',
  106. 'id',
  107. 'id',
  108. 'product_id');
  109. }
  110. public function user(): BelongsTo
  111. {
  112. return $this->belongsTo(User::class, 'user_id', 'id');
  113. }
  114. public function district(): BelongsTo
  115. {
  116. return $this->belongsTo(District::class);
  117. }
  118. public function area(): BelongsTo
  119. {
  120. return $this->belongsTo(Area::class);
  121. }
  122. public function objectType(): BelongsTo
  123. {
  124. return $this->belongsTo(ObjectType::class);
  125. }
  126. public function brigadier(): BelongsTo
  127. {
  128. return $this->belongsTo(User::class, 'brigadier_id', 'id');
  129. }
  130. public function orderStatus(): BelongsTo
  131. {
  132. return $this->belongsTo(OrderStatus::class);
  133. }
  134. public function photos(): BelongsToMany
  135. {
  136. return $this->belongsToMany(File::class, 'order_photo');
  137. }
  138. public function documents(): BelongsToMany
  139. {
  140. return $this->belongsToMany(File::class, 'order_document');
  141. }
  142. public function statements(): BelongsToMany
  143. {
  144. return $this->belongsToMany(File::class, 'order_statement');
  145. }
  146. public function reclamations(): HasMany
  147. {
  148. return $this->hasMany(Reclamation::class);
  149. }
  150. public function chatMessages(): HasMany
  151. {
  152. return $this->hasMany(ChatMessage::class)->orderBy('created_at');
  153. }
  154. public static function visibleStatusIdsForBrigadier(): array
  155. {
  156. return array_values(array_diff(
  157. array_keys(self::STATUS_NAMES),
  158. self::BRIGADIER_HIDDEN_STATUS_IDS,
  159. ));
  160. }
  161. public function getNeeds(): array
  162. {
  163. $needs = [];
  164. foreach ($this->products_sku as $sku) {
  165. if($sku->maf_order) continue;
  166. $needs[$sku->product_id]['needs'] = (isset($needs[$sku->product_id])) ? $needs[$sku->product_id]['needs'] + 1 : 1;
  167. }
  168. foreach ($needs as $productId => $quantity) {
  169. $needs[$productId]['sku'] = MafOrder::query()
  170. ->where('maf_orders.product_id', $productId)
  171. ->sum('maf_orders.in_stock');
  172. }
  173. return $needs;
  174. }
  175. public function recalculateReadyToMount(): void
  176. {
  177. $result = true;
  178. foreach ($this->getNeeds() as $need) {
  179. if($need['sku'] < $need['needs']) {
  180. $result = false;
  181. break;
  182. }
  183. }
  184. $this->update(['ready_to_mount' => ($result) ? 'Да' : 'Нет']);
  185. }
  186. public function autoChangeStatus(): void
  187. {
  188. if(($this->products_sku->count() < 1)
  189. && ($this->order_status_id !== self::STATUS_NEW)
  190. ) {
  191. $this->update(['order_status_id' => self::STATUS_NO_MAF]);
  192. return;
  193. }
  194. if(($this->order_status_id === self::STATUS_READY_TO_MOUNT)
  195. && ($this->brigadier_id !== null)
  196. && ($this->installation_date !== null)
  197. ) {
  198. if ($this->canBeMovedToMountStatus()) {
  199. $this->update(['order_status_id' => self::STATUS_IN_MOUNT]);
  200. }
  201. }
  202. }
  203. public function commonName(): Attribute
  204. {
  205. return Attribute::make(
  206. get: fn($value) => (string) $this->object_address . ', ' . $this->area->name . ', ' . $this->district->shortname,
  207. );
  208. }
  209. public function moveMafName(): Attribute
  210. {
  211. return Attribute::make(
  212. get: fn ($value) => trim($this->common_name . ($this->name ? ' | ' . $this->name : '')),
  213. );
  214. }
  215. public function productsWithCount(): Attribute
  216. {
  217. $products = $this->products_sku;
  218. $ret = [];
  219. foreach ($products as $product) {
  220. if(isset($ret[$product->product->id])) {
  221. $ret[$product->product->id]['count'] += 1;
  222. } else {
  223. $ret[$product->product->id] = [
  224. 'name' => $product->product->article,
  225. 'count' => 1,
  226. ];
  227. }
  228. if($product->maf_order?->order_number) {
  229. $ret[$product->product->id]['order_numbers'][] = $product->maf_order?->order_number;
  230. }
  231. }
  232. $s = '';
  233. $openTag = '<div>';
  234. $closeTag = '</div>';
  235. foreach ($ret as $product) {
  236. $order_numbers = (isset($product['order_numbers'])) ? ' (' . implode(', ', array_unique($product['order_numbers'])) . ')' : '';
  237. $s .= $openTag . $product['name'] . ' - ' . $product['count'] . $order_numbers . $closeTag;
  238. }
  239. return Attribute::make(
  240. get: fn($value) => (string) $s,
  241. );
  242. }
  243. public function isAllMafConnected(): array
  244. {
  245. $errors = [];
  246. foreach($this->products_sku as $sku) {
  247. $orderNumber = trim((string) ($sku->maf_order?->order_number ?? ''));
  248. if($sku->maf_order_id && $orderNumber !== '') continue;
  249. $errors[] = 'МАФ ' . $sku->product->article . 'не имеет номера заказа МАФ!';
  250. }
  251. return $errors;
  252. }
  253. public function getMountStatusErrors(): array
  254. {
  255. foreach ($this->products_sku as $sku) {
  256. $orderNumber = trim((string) ($sku->maf_order?->order_number ?? ''));
  257. if ($sku->maf_order_id !== null && $orderNumber !== '') {
  258. continue;
  259. }
  260. return ['МАФ не привязан к заказу'];
  261. }
  262. return [];
  263. }
  264. public function canBeMovedToMountStatus(): bool
  265. {
  266. return $this->getMountStatusErrors() === [];
  267. }
  268. public function canCreateHandover(): array
  269. {
  270. $errors = [];
  271. if($this->photos->count() === 0) $errors[] = 'Не загружены фотографии!';
  272. foreach($this->products_sku as $sku) {
  273. if($sku->maf_order_id === null) $errors[] = 'МАФ ' . $sku->product->article . ' не имеет номера заказа!';
  274. if($sku->passport_id === null) $errors[] = 'МАФ ' . $sku->product->article . ' не загружен паспорт!';
  275. if($sku->rfid === null) $errors[] = 'МАФ ' . $sku->product->article . ' не имеет номера заказа!';
  276. if($sku->manufacture_date === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет даты производства!';
  277. if($sku->factory_number === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет заводского номера!';
  278. if($sku->product->passport_name === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет паспорта!';
  279. if($sku->product->statement_name === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет ведомости!';
  280. if($sku->product->certificate_id === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет сертификата!';
  281. if($sku->product->service_life === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет срока эксплуатации!';
  282. if($sku->product->certificate_number === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет номера сертификата!';
  283. if($sku->product->certificate_date === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет даты сертификата!';
  284. if($sku->product->certificate_issuer === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет орана выпустившего сертификат!';
  285. if($sku->product->certificate_type === null) $errors[] = 'МАФ ' . $sku->product->article . ' нет типа сертификата!';
  286. }
  287. return $errors;
  288. }
  289. }