/
ProductBackendController.php
405 lines (348 loc) · 12.5 KB
/
ProductBackendController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
75
76
77
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
247
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<?php
/**
* Class ProductBackendController
*/
class ProductBackendController extends yupe\components\controllers\BackController
{
/**
* @var ProductRepository
*/
protected $productRepository;
/**
*
*/
public function init()
{
$this->productRepository = Yii::app()->getComponent('productRepository');
parent::init();
}
/**
* @return array
*/
public function actions()
{
return [
'inline' => [
'class' => 'yupe\components\actions\YInLineEditAction',
'model' => 'Product',
'validAttributes' => [
'status',
'in_stock',
'price',
'discount_price',
'sku',
'type_id',
'quantity',
],
],
'sortable' => [
'class' => 'yupe\components\actions\SortAction',
'model' => 'Product',
],
];
}
/**
* @return array
*/
public function accessRules()
{
return [
['allow', 'roles' => ['admin'],],
['allow', 'actions' => ['index'], 'roles' => ['Store.ProductBackend.Index'],],
['allow', 'actions' => ['view'], 'roles' => ['Store.ProductBackend.View'],],
['allow', 'actions' => ['create', 'copy'], 'roles' => ['Store.ProductBackend.Create'],],
[
'allow',
'actions' => ['update', 'inline', 'sortable', 'deleteImage'],
'roles' => ['Store.ProductBackend.Update'],
],
['allow', 'actions' => ['delete', 'multiaction'], 'roles' => ['Store.ProductBackend.Delete'],],
[
'allow',
'actions' => ['typeAttributes'],
'roles' => ['Store.ProductBackend.Create', 'Store.ProductBackend.Update'],
],
[
'allow',
'actions' => ['typeAttributesForm'],
'roles' => ['Store.ProductBackend.Create', 'Store.ProductBackend.Update'],
],
[
'allow',
'actions' => ['variantRow'],
'roles' => ['Store.ProductBackend.Create', 'Store.ProductBackend.Update'],
],
['deny',],
];
}
/**
* Отображает товар по указанному идентификатору
* @param integer $id Идентификатор товар для отображения
*/
public function actionView($id)
{
$this->render('view', ['model' => $this->loadModel($id)]);
}
/**
* Создает новую модель товара.
* Если создание прошло успешно - перенаправляет на просмотр.
*/
public function actionCreate()
{
$model = new Product();
if (Yii::app()->getRequest()->getIsPostRequest() && Yii::app()->getRequest()->getPost('Product')) {
$attributes = Yii::app()->getRequest()->getPost('Product');
$typeAttributes = Yii::app()->getRequest()->getPost('Attribute', []);
$variants = Yii::app()->getRequest()->getPost('ProductVariant', []);
$categories = Yii::app()->getRequest()->getPost('categories', []);
if ($model->saveData($attributes, $typeAttributes, $variants, $categories)) {
$this->updateProductImages($model);
$this->uploadAttributesFiles($model);
Yii::app()->getUser()->setFlash(
yupe\widgets\YFlashMessages::SUCCESS_MESSAGE,
Yii::t('StoreModule.store', 'Record was created!')
);
$this->redirect(
(array)Yii::app()->getRequest()->getPost(
'submit-type',
['create']
)
);
} else {
Yii::app()->getUser()->setFlash(
yupe\widgets\YFlashMessages::ERROR_MESSAGE,
Yii::t('StoreModule.store', 'Failed to save product!')
);
}
}
$this->render(
'create',
[
'model' => $model,
'imageGroup' => ImageGroup::model(),
]
);
}
/**
* Редактирование товара.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
if (Yii::app()->getRequest()->getIsPostRequest() && Yii::app()->getRequest()->getPost('Product')) {
$attributes = Yii::app()->getRequest()->getPost('Product');
$typeAttributes = Yii::app()->getRequest()->getPost('Attribute', []);
$variants = Yii::app()->getRequest()->getPost('ProductVariant', []);
$categories = Yii::app()->getRequest()->getPost('categories', []);
if ($model->saveData($attributes, $typeAttributes, $variants, $categories)) {
$this->updateProductImages($model);
$this->uploadAttributesFiles($model);
Yii::app()->getUser()->setFlash(
yupe\widgets\YFlashMessages::SUCCESS_MESSAGE,
Yii::t('StoreModule.store', 'Record was updated!')
);
if (!isset($_POST['submit-type'])) {
$this->redirect(['update', 'id' => $model->id]);
} else {
$this->redirect([$_POST['submit-type']]);
}
} else {
Yii::app()->getUser()->setFlash(
yupe\widgets\YFlashMessages::ERROR_MESSAGE,
Yii::t('StoreModule.store', 'Failed to save product!')
);
}
}
$searchModel = new ProductSearch('search');
$searchModel->unsetAttributes();
$searchModel->setAttributes(
Yii::app()->getRequest()->getQuery('ProductSearch')
);
$this->render(
'update',
[
'model' => $model,
'searchModel' => $searchModel,
'imageGroup' => ImageGroup::model(),
]
);
}
/**
* @param $model
*/
protected function uploadAttributesFiles($model)
{
if (!empty($_FILES['Attribute']['name'])) {
foreach ($_FILES['Attribute']['name'] as $key => $file) {
$value = AttributeValue::model()->find('product_id = :product AND attribute_id = :attribute', [
':product' => $model->id,
':attribute' => $key,
]);
$value = $value ?: new AttributeValue();
$value->setAttributes([
'product_id' => $model->id,
'attribute_id' => $key,
]);
$value->addFileInstanceName('Attribute['.$key.'][name]');
if (false === $value->save()) {
Yii::app()->getUser()->setFlash(\yupe\widgets\YFlashMessages::ERROR_MESSAGE,
Yii::t('StoreModule.store', 'Error uploading some files...'));
}
}
}
}
/**
* @param Product $product
*/
protected function updateProductImages(Product $product)
{
if (Yii::app()->getRequest()->getPost('ProductImage')) {
foreach (Yii::app()->getRequest()->getPost('ProductImage') as $key => $val) {
$productImage = ProductImage::model()->findByPk($key);
if (null === $productImage) {
$productImage = new ProductImage();
$productImage->product_id = $product->id;
$productImage->addFileInstanceName('ProductImage['.$key.'][name]');
}
$productImage->setAttributes($_POST['ProductImage'][$key]);
if (false === $productImage->save()) {
Yii::app()->getUser()->setFlash(\yupe\widgets\YFlashMessages::ERROR_MESSAGE,
Yii::t('StoreModule.store', 'Error uploading some images...'));
}
}
}
}
/**
* @throws CHttpException
*/
public function actionDeleteImage()
{
if (Yii::app()->getRequest()->getIsPostRequest() && Yii::app()->getRequest()->getIsAjaxRequest()) {
$id = (int)Yii::app()->getRequest()->getPost('id');
$model = ProductImage::model()->findByPk($id);
if (null !== $model && $model->delete()) {
Yii::app()->ajax->success();
}
}
throw new CHttpException(404);
}
/**
* Удаяет модель товара из базы.
* Если удаление прошло успешно - возвращется в index
* @param integer $id идентификатор товара, который нужно удалить
* @throws CHttpException
*/
public function actionDelete($id)
{
if (Yii::app()->getRequest()->getIsPostRequest()) {
$this->loadModel($id)->delete();
Yii::app()->getUser()->setFlash(
yupe\widgets\YFlashMessages::SUCCESS_MESSAGE,
Yii::t('StoreModule.store', 'Record was removed!')
);
if (!isset($_GET['ajax'])) {
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : ['index']);
}
} else {
throw new CHttpException(400, Yii::t('StoreModule.store', 'Unknown request. Don\'t repeat it please!'));
}
}
/**
* Управление товарами.
*/
public function actionIndex()
{
$model = new Product('search');
$model->unsetAttributes();
if (Yii::app()->getRequest()->getQuery('Product')) {
$model->setAttributes(
Yii::app()->getRequest()->getQuery('Product')
);
}
$this->render('index', ['model' => $model]);
}
/**
* @param $id
* @return Product
* @throws CHttpException
*/
public function loadModel($id)
{
$model = Product::model()->with('images')->findByPk($id);
if ($model === null) {
throw new CHttpException(404, Yii::t('StoreModule.store', 'Page not found!'));
}
return $model;
}
/**
* @param $id
* @throws CException
* @throws CHttpException
*/
public function actionTypeAttributesForm($id)
{
$type = Type::model()->findByPk($id);
if (null === $type) {
throw new CHttpException(404);
}
$this->renderPartial('_attribute_form', ['groups' => $type->getAttributeGroups(), 'model' => new Product()]);
}
/**
* @param $id
* @throws CException
*/
public function actionVariantRow($id)
{
$variant = new ProductVariant();
$variant->setAttributes(
[
'attribute_id' => (int)$id,
]
);
$this->renderPartial('_variant_row', ['variant' => $variant]);
}
/**
* @param $id
* @throws CHttpException
*/
public function actionTypeAttributes($id)
{
$type = Type::model()->findByPk($id);
if (null === $type) {
throw new CHttpException(404);
}
$types = [];
$noSupported = [Attribute::TYPE_FILE, Attribute::TYPE_TEXT, Attribute::TYPE_CHECKBOX_LIST];
foreach ($type->typeAttributes as $attr) {
if (in_array($attr->type, $noSupported)) {
continue;
}
if ($attr->type == Attribute::TYPE_DROPDOWN) {
$types[] = array_merge($attr->attributes, ['options' => $attr->options]);
} else {
if (in_array($attr->type, [Attribute::TYPE_CHECKBOX, Attribute::TYPE_SHORT_TEXT])) {
$types[] = array_merge($attr->attributes, ['options' => []]);
} else {
$types[] = $attr->attributes;
}
}
}
Yii::app()->ajax->raw($types);
}
/**
*
*/
public function actionCopy()
{
if ($data = Yii::app()->getRequest()->getPost('items')) {
foreach ($data as $id) {
$model = Product::model()->findByPk($id);
if ($model) {
$model->copy();
}
}
Yii::app()->ajax->success();
}
}
}