Blame view

models/ProductVariant.php 17.9 KB
2f25da09   Yarik   first commit
1
2
3
4
  <?php
      
      namespace artweb\artbox\ecommerce\models;
      
8a7e6ecf   Yarik   Namespaces
5
6
7
      use artweb\artbox\behaviors\MultipleImgBehavior;
      use artweb\artbox\behaviors\SaveMultipleFileBehavior;
      use artweb\artbox\language\behaviors\LanguageBehavior;
b044365b   Administrator   add variantSku
8
      use frontend\models\Catalog;
2f25da09   Yarik   first commit
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
      use Yii;
      use yii\base\InvalidParamException;
      use yii\db\ActiveQuery;
      use yii\db\ActiveRecord;
      use yii\web\Request;
      
      /**
       * This is the model class for table "product_variant".
       *
       * @property integer              $id
       * @property integer              $product_id
       * @property integer              $remote_id
       * @property string               $sku
       * @property double               $price
       * @property double               $price_old
       * @property double               $stock
       * @property integer              $product_unit_id
       * @property string               $fullname
       * @property TaxOption[]          $options
8b83e9d1   Administrator   add variantSku
28
29
       * @property TaxGroup[]           $groups
       * @property TaxOption[]          $filterOptions
2f25da09   Yarik   first commit
30
31
32
33
34
35
36
37
38
39
40
       * @property ProductUnit          $productUnit
       * @property Product              $product
       * @property Category[]           $categories
       * @property Category             $category
       * @property TaxOption[]          $filters
       * @property ProductStock[]       $productStocks
       * @property int                  $quantity
       * @property ProductStock[]       $variantStocks
       * @property Stock[]              $stocks
       * @property TaxGroup[]           $properties
       * @property TaxGroup[]           $taxGroupsByLevel
42883b83   Alexey Boroda   -Order form beta ...
41
       * @property string               $size
d4272254   Alexey Boroda   -Feed and it git ...
42
       * @property string               $imageUrl
2f25da09   Yarik   first commit
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
       *       * From language behavior *
       * @property ProductVariantLang   $lang
       * @property ProductVariantLang[] $langs
       * @property ProductVariantLang   $objectLang
       * @property string               $ownerKey
       * @property string               $langKey
       * @property ProductVariantLang[] $modelLangs
       * @property bool                 $transactionStatus
       * @method string           getOwnerKey()
       * @method void             setOwnerKey( string $value )
       * @method string           getLangKey()
       * @method void             setLangKey( string $value )
       * @method ActiveQuery      getLangs()
       * @method ActiveQuery      getLang( integer $language_id )
       * @method ProductVariantLang[]    generateLangs()
       * @method void             loadLangs( Request $request )
       * @method bool             linkLangs()
       * @method bool             saveLangs()
       * @method bool             getTransactionStatus()
       *       * End language behavior *
       *       * From multipleImage behavior
       * @property ProductImage         $image
       * @property ProductImage[]       $images
       * @property array                $imagesConfig
       * @method ActiveQuery getImage()
       * @method ActiveQuery getImages()
       * @method array getImagesConfig()
       * @method array getImagesHTML( string $preset )
       *       * End multipleImage behavior
       */
      class ProductVariant extends ActiveRecord
      {
2b315849   Alexey Boroda   -Product card (wi...
75
76
          
          public $customOption = [];
8b83e9d1   Administrator   add variantSku
77
  
2f25da09   Yarik   first commit
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
          /**
           * @var int[] $options
           */
          private $options;
          
          /** @var array $_images */
          public $imagesUpload = [];
          
          /**
           * @var array $stocks
           */
          protected $stocks = [];
          
          /**
           * @inheritdoc
           */
          public static function tableName()
          {
              return 'product_variant';
          }
          
          public function behaviors()
          {
              return [
                  'language'      => [
                      'class' => LanguageBehavior::className(),
                  ],
                  'images'        => [
                      'class'     => SaveMultipleFileBehavior::className(),
                      'name'      => 'imagesUpload',
                      'directory' => 'products',
                      'column'    => 'image',
                      'links'     => [
42883b83   Alexey Boroda   -Order form beta ...
111
112
                          'product_id' => 'product_id',
                          'id'         => 'product_variant_id',
2f25da09   Yarik   first commit
113
114
115
116
117
118
119
120
121
122
123
                      ],
                      'model'     => ProductImage::className(),
                  ],
                  'multipleImage' => [
                      'class'  => MultipleImgBehavior::className(),
                      'links'  => [
                          'product_variant_id' => 'id',
                      ],
                      'model'  => ProductImage::className(),
                      'config' => [
                          'caption'       => 'image',
2b315849   Alexey Boroda   -Product card (wi...
124
                          'delete_action' => 'variant/delete-image',
2f25da09   Yarik   first commit
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
                          'id'            => 'id',
                      ],
                  ],
              ];
          }
          
          /**
           * @inheritdoc
           */
          public function rules()
          {
              return [
                  [
                      [
                          'product_id',
                          'product_unit_id',
                      ],
                      'required',
                  ],
                  [
                      [
                          'product_id',
                          'product_unit_id',
                      ],
                      'integer',
                  ],
                  [
                      [
                          'price',
                          'price_old',
                          'stock',
                      ],
                      'number',
                  ],
                  [
                      [
                          'sku',
                      ],
                      'string',
                      'max' => 255,
                  ],
                  [
                      [
                          'options',
                      ],
                      'safe',
                  ],
                  [
                      [ 'product_unit_id' ],
                      'exist',
                      'skipOnError'     => true,
                      'targetClass'     => ProductUnit::className(),
                      'targetAttribute' => [ 'product_unit_id' => 'id' ],
                  ],
                  [
                      [ 'product_id' ],
                      'exist',
                      'skipOnError'     => true,
                      'targetClass'     => Product::className(),
                      'targetAttribute' => [ 'product_id' => 'id' ],
                  ],
              ];
          }
          
          /**
           * @inheritdoc
           */
          public function attributeLabels()
          {
              return [
                  'id'              => Yii::t('product', 'Product Variant ID'),
                  'product_id'      => Yii::t('product', 'Product ID'),
                  'sku'             => Yii::t('product', 'Sku'),
                  'price'           => Yii::t('product', 'Price'),
                  'price_old'       => Yii::t('product', 'Price Old'),
                  'stock'           => Yii::t('product', 'Stock'),
                  'product_unit_id' => Yii::t('product', 'Product Unit ID'),
                  'stock_caption'   => Yii::t('product', 'Stock'),
                  'image'           => Yii::t('product', 'Image'),
                  'images'          => Yii::t('product', 'Images'),
              ];
          }
          
          /**
           * @return \yii\db\ActiveQuery
           */
          public function getProductUnit()
          {
              return $this->hasOne(ProductUnit::className(), [ 'id' => 'product_unit_id' ]);
          }
          
          /**
           * @return \yii\db\ActiveQuery
           */
          public function getProduct()
          {
              return $this->hasOne(Product::className(), [ 'id' => 'product_id' ]);
          }
          
          /**
           * @return \yii\db\ActiveQuery
           */
          public function getProductStocks()
          {
              return $this->hasMany(ProductStock::className(), [ 'product_variant_id' => 'id' ]);
          }
          
          /**
           * Get qunatity for current ProductVariant
           * If $recalculate set to true will recalculate stock via product_stock table
           *
           * @param bool $recalculate
           *
           * @return int
           */
          public function getQuantity(bool $recalculate = false): int
          {
              if (!$recalculate) {
                  return $this->stock;
              } else {
                  $quantity = $this->getProductStocks()
                                   ->sum('quantity');
42883b83   Alexey Boroda   -Order form beta ...
247
                  if (empty($quantity)) {
2f25da09   Yarik   first commit
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
                      $this->stock = 0;
                  } else {
                      $this->stock = (int) $quantity;
                  }
                  $this->save(false, [ 'stock' ]);
                  return $this->stock;
              }
          }
          
          /**
           * Get ProductStocks query woth preloaded Stocks for current ProductVariant
           * **Used in dynamic fields in product variant form**
           *
           * @return ActiveQuery
           */
          public function getVariantStocks()
          {
              return $this->getProductStocks()
                          ->joinWith('stock');
          }
          
          /**
           * @return ActiveQuery
           */
          public function getStocks()
          {
              return $this->hasMany(Stock::className(), [ 'id' => 'stock_id' ])
                          ->via('productStocks');
          }
          
          /**
           * @return ActiveQuery
           */
          public function getOptions()
          {
              return $this->hasMany(TaxOption::className(), [ 'id' => 'option_id' ])
                          ->viaTable('product_variant_option', [ 'product_variant_id' => 'id' ]);
          }
8b83e9d1   Administrator   add variantSku
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
  
          /**
           * Get TaxGroup for current Product
           *
           * @return ActiveQuery
           */
          public function getGroups()
          {
              return $this->hasMany(TaxGroup::className(), [ 'id' => 'tax_group_id' ])
                  ->via('options');
          }
  
          /**
           * Get TaxOptions query for current ProductVariant that will by used in filter
           *
           * @return ActiveQuery
           */
          public function getFilterOptions()
          {
              return $this->getOptions()
                  ->joinWith(['lang','taxGroup'])
                  ->where(['is_filter' => true]);
          }
  
2b315849   Alexey Boroda   -Product card (wi...
310
311
312
313
314
315
316
317
318
319
          /**
           * Get one variant's option whith needed conditions, or random if condition is empty
           *
           * @param array $conditions
           *
           * @return ActiveQuery
           */
          public function getOption(array $conditions = [])
          {
              $query = $this->hasOne(TaxOption::className(), [ 'id' => 'option_id' ])
42883b83   Alexey Boroda   -Order form beta ...
320
321
322
                            ->viaTable('product_variant_option', [ 'product_variant_id' => 'id' ]);
              foreach ($conditions as $condition) {
                  if (!empty($condition) && is_array($condition)) {
2b315849   Alexey Boroda   -Product card (wi...
323
324
325
326
327
328
                      $query->andFilterWhere($condition);
                  }
              }
              
              return $query;
          }
2f25da09   Yarik   first commit
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
          
          /**
           * Get TaxOptions with preloaded TaxGroups for current ProductVariant
           *
           * @return ActiveQuery
           */
          public function getFilters()
          {
              return $this->getOptions()
                          ->joinWith('taxGroup.lang')
                          ->joinWith('lang');
          }
          
          /**
           * Get Product title concanated with current ProductVariant title
           *
           * @return string
           */
          public function getFullname(): string
          {
              return $this->product->lang->title . ' ' . $this->lang->title;
          }
          
          /**
           * Set Options to override previous
           *
           * @param int[] $values
           */
          public function setOptions($values)
          {
              $this->options = $values;
          }
8b83e9d1   Administrator   add variantSku
361
  
2f25da09   Yarik   first commit
362
363
364
          /**
           * Get all TaxGroups for current ProductVariant filled with $customOptions that satisfy current ProductVariant
           *
2b315849   Alexey Boroda   -Product card (wi...
365
366
367
           * @param array $conditions
           *
           * @return \artweb\artbox\ecommerce\models\TaxGroup[]
2f25da09   Yarik   first commit
368
           */
2b315849   Alexey Boroda   -Product card (wi...
369
          public function getProperties(array $conditions = [])
2f25da09   Yarik   first commit
370
371
372
373
374
375
376
377
378
379
          {
              $groups = $options = [];
              foreach ($this->getOptions()
                            ->with('lang')
                            ->all() as $option) {
                  /**
                   * @var TaxOption $option
                   */
                  $options[ $option->tax_group_id ][] = $option;
              }
2b315849   Alexey Boroda   -Product card (wi...
380
              $query = TaxGroup::find()
2f25da09   Yarik   first commit
381
382
                               ->where([ 'tax_group.id' => array_keys($options) ])
                               ->orderBy([ 'sort' => SORT_ASC ])
2b315849   Alexey Boroda   -Product card (wi...
383
384
385
386
387
388
389
                               ->with('lang');
              
              if (!empty($conditions)) {
                  foreach ($conditions as $condition) {
                      $query->andFilterWhere($condition);
                  }
              }
42883b83   Alexey Boroda   -Order form beta ...
390
              foreach ($query->all() as $group) {
2f25da09   Yarik   first commit
391
                  /**
65f5712c   Administrator   select characteri...
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
                   * @var TaxGroup $group
                   */
                  if (!empty($options[ $group->id ])) {
                      $group->customOptions = $options[ $group->id ];
                      $groups[] = $group;
                  }
              }
              return $groups;
          }
  
          /**
           * Get characteristic from TaxGroups for current ProductVariant filled with $customOptions that satisfy current Product
           *
           * @return TaxGroup[]
           */
          public function getCharacteristic(): array
          {
              $groups = $options = [];
              foreach ($this->getOptions()
                           ->with('lang')
                           ->all() as $option) {
                  /**
                   * @var TaxOption $option
                   */
                  $options[ $option[ 'tax_group_id' ] ][] = $option;
              }
              foreach (TaxGroup::find()
                           ->where(['is_menu'=>true])
                           ->andWhere([ 'id' => array_keys($options) ])
                           ->with('lang')
                           ->all() as $group) {
                  /**
2f25da09   Yarik   first commit
424
425
                   * @var TaxGroup $group
                   */
42883b83   Alexey Boroda   -Order form beta ...
426
                  if (!empty($options[ $group->id ])) {
2f25da09   Yarik   first commit
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
                      $group->customOptions = $options[ $group->id ];
                      $groups[] = $group;
                  }
              }
              return $groups;
          }
          
          /**
           * Set stocks to override existing in product_stock table
           *
           * @param mixed $stocks
           */
          public function setStocks($stocks)
          {
              $this->stocks = (array) $stocks;
          }
          
          /**
           * @return ActiveQuery
           */
          public function getCategory()
          {
              return $this->hasOne(Category::className(), [ 'id' => 'category_id' ])
                          ->viaTable('product_category', [ 'product_id' => 'product_id' ]);
          }
          
          /**
           * @return ActiveQuery
           */
          public function getCategories()
          {
              return $this->hasMany(Category::className(), [ 'id' => 'category_id' ])
                          ->viaTable('product_category', [ 'product_id' => 'product_id' ]);
          }
          
          /**
           * Get TaxGroups query for current ProductVariant according to level
           * * 0 - Product Tax Groups
           * * 1 - ProductVariant Tax Groups
           *
           * @param int $level
           *
           * @return ActiveQuery
           * @throws InvalidParamException
           */
          public function getTaxGroupsByLevel(int $level = 0)
          {
              return $this->product->getTaxGroupsByLevel($level);
          }
          
          public function afterSave($insert, $changedAttributes)
          {
              parent::afterSave($insert, $changedAttributes);
4775a528   Administrator   site map
480
481
482
  
              Catalog::addRecord($this->product);
  
42883b83   Alexey Boroda   -Order form beta ...
483
              if (!empty($this->options)) {
2f25da09   Yarik   first commit
484
485
486
487
488
489
490
                  $options = TaxOption::findAll($this->options);
                  $this->unlinkAll('options', true);
                  foreach ($options as $option) {
                      $this->link('options', $option);
                  }
              }
              
42883b83   Alexey Boroda   -Order form beta ...
491
              if (!empty($this->stocks)) {
2f25da09   Yarik   first commit
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
                  ProductStock::deleteAll([ 'product_variant_id' => $this->id ]);
                  foreach ($this->stocks as $id => $quantity) {
                      /**
                       * @var ProductStock $productStock
                       */
                      $productStock = ProductStock::find()
                                                  ->where(
                                                      [
                                                          'product_variant_id' => $this->id,
                                                          'stock_id'           => $id,
                                                      ]
                                                  )
                                                  ->one();
                      $productStock->quantity = $quantity;
                      $productStock->save();
                  }
              }
          }
8b83e9d1   Administrator   add variantSku
510
  
42883b83   Alexey Boroda   -Order form beta ...
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
          /**
           * @return string
           */
          public function getSize()
          {
              $option = $this->getOptions()
                             ->with('lang')
                             ->joinWith('group')
                             ->where(
                                 [
                                     'tax_group.position' => 1,
                                 ]
                             )
                             ->one();
              if (empty($option)) {
                  return '';
              } else {
                  return $option->lang->value;
              }
          }
b044365b   Administrator   add variantSku
531
532
533
534
  
          public function beforeSave($insert)
          {
              if (parent::beforeSave($insert)) {
4775a528   Administrator   site map
535
  
b044365b   Administrator   add variantSku
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
                  return true;
              } else {
                  return false;
              }
          }
  
          public function beforeDelete()
          {
              if (parent::beforeDelete()) {
                  Catalog::deleteRecord($this->product);
                  return true;
              } else {
                  return false;
              }
          }
2f25da09   Yarik   first commit
551
      }