Test Failed
Push — master ( ab6225...0b6844 )
by Alexey
05:32
created

Ecommerce::getCurCart()   D

Complexity

Conditions 9
Paths 18

Size

Total Lines 26
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 20
nc 18
nop 1
dl 0
loc 26
rs 4.909
c 0
b 0
f 0
ccs 0
cts 15
cp 0
crap 90
1
<?php
2
3
/**
4
 * Ecommerce module
5
 *
6
 * @author Alexey Krupskiy <[email protected]>
7
 * @link http://inji.ru/
8
 * @copyright 2015 Alexey Krupskiy
9
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
10
 */
11
12
class Ecommerce extends Module {
13
14
    public function init() {
15
        App::$primary->view->customAsset('js', '/moduleAsset/Ecommerce/js/cart.js');
16
        if (class_exists('Users\User') && Users\User::$cur->id) {
17
            $favs = !empty($_COOKIE['ecommerce_favitems']) ? json_decode($_COOKIE['ecommerce_favitems'], true) : [];
18
            if ($favs) {
19
                foreach ($favs as $itemId) {
20
                    $fav = \Ecommerce\Favorite::get([['user_id', Users\User::$cur->id], ['item_id', (int) $itemId]]);
21
                    if (!$fav) {
22
                        $item = \Ecommerce\Item::get((int) $itemId);
23
                        if ($item) {
24
                            $fav = new \Ecommerce\Favorite([
25
                                'user_id' => Users\User::$cur->id,
26
                                'item_id' => $itemId
27
                            ]);
28
                            $fav->save();
29
                        }
30
                    }
31
                }
32
                if (!headers_sent()) {
33
                    setcookie("ecommerce_favitems", json_encode([]), time() + 360000, "/");
34
                }
35
            }
36
        }
37
    }
38
39
    public function getPayTypeHandlers($forSelect = false) {
40
        if (!$forSelect) {
41
            return $this->getSnippets('payTypeHandler');
42
        }
43
        $handlers = ['' => 'Не выбрано'];
44
        foreach ($this->getSnippets('payTypeHandler') as $key => $handler) {
45
            if (empty($handler)) {
46
                continue;
47
            }
48
            $handlers[$key] = $handler['name'];
49
        }
50
        return $handlers;
51
    }
52
53
    public function cartPayRecive($data) {
54
        $cart = Ecommerce\Cart::get($data['pay']->data);
55
        if ($cart) {
56
            $payed = true;
57
            foreach ($cart->pays as $pay) {
58
                if ($pay->pay_status_id != 2) {
59
                    $payed = false;
60
                    break;
61
                }
62
            }
63
            $cart->payed = $payed;
64
            $cart->save();
65
        }
66
    }
67
68
    /**
69
     * @param array $data
70
     * @param \Ecommerce\Cart $cart
71
     * @return bool|\Ecommerce\UserAdds
72
     */
73 View Code Duplication
    public function parseFields($data, $cart) {
74
        $user = \Users\User::get($cart->user_id);
75
        $fields = \Ecommerce\UserAdds\Field::getList();
76
        if ($user) {
77
            $name = '';
78
            foreach ($fields as $field) {
79
                if ($field->save && isset($data[$field->id])) {
80
                    $name .= htmlspecialchars($data[$field->id]) . ' ';
81
                }
82
            }
83
            $name = trim($name);
84
85
            $userAdds = Ecommerce\UserAdds::get([['user_id', $cart->user->id], ['name', $name]]);
86
            if (!$userAdds) {
87
                $userAdds = new Ecommerce\UserAdds();
88
                $userAdds->user_id = $cart->user->id;
89
                $userAdds->name = $name;
90
                $userAdds->save();
91
            }
92
            foreach ($fields as $field) {
93
                if (!$field->save) {
94
                    continue;
95
                }
96
                if (isset($data[$field->id])) {
97
                    $value = htmlspecialchars($data[$field->id]);
98
                    if (!isset($userAdds->values[$field->id])) {
99
                        $userAddsValue = new Ecommerce\UserAdds\Value();
100
                        $userAddsValue->value = $value;
101
                        $userAddsValue->useradds_field_id = $field->id;
102
                        $userAddsValue->useradds_id = $userAdds->id;
103
                        $userAddsValue->save();
104
                    } else {
105
                        $userAddsValue = $userAdds->values[$field->id];
106
                        $userAddsValue->value = $value;
107
                        $userAddsValue->save();
108
                    }
109
                }
110
            }
111
        }
112
113
        foreach ($fields as $field) {
114
            if (isset($data[$field->id])) {
115
                $value = htmlspecialchars($data[$field->id]);
116
                if (!isset($cart->infos[$field->id])) {
117
                    $info = new \Ecommerce\Cart\Info();
118
                    $info->name = $field->name;
119
                    $info->value = $value;
120
                    $info->useradds_field_id = $field->id;
121
                    $info->cart_id = $cart->id;
122
                    $info->save();
123
                } else {
124
                    $info = $cart->infos[$field->id];
125
                    $info->value = $value;
126
                    $info->save();
127
                }
128
            }
129
            if (isset($info) && $user && $field->userfield) {
130
                $relations = [];
131
                if (strpos($field->userfield, ':')) {
132
                    $path = explode(':', $field->userfield);
133
                    if (!$user->{$path[0]}->{$path[1]}) {
134
                        $user->{$path[0]}->{$path[1]} = $info->value;
135
                        $relations[$path[0]] = $path[0];
136
                    }
137
                } else {
138
                    if (!$user->{$field->userfield}) {
139
                        $user->{$field->userfield} = $info->value;
140
                    }
141
                }
142
143
                foreach ($relations as $rel) {
144
                    $user->$rel->save();
145
                }
146
                $user->save();
147
            }
148
        }
149
        return isset($userAdds) ? $userAdds : false;
150
    }
151
152
    /**
153
     * @param array $data
154
     * @param \Ecommerce\Cart $cart
155
     * @param \Ecommerce\Delivery\Field[] $fields
156
     * @return bool|\Ecommerce\Delivery\Save
157
     */
158 View Code Duplication
    public function parseDeliveryFields($data, $cart, $fields) {
159
        $user = \Users\User::get($cart->user_id);
160
        if ($user) {
161
            $name = '';
162
            foreach ($fields as $field) {
163
                if ($field->save && isset($data[$field->id])) {
164
                    $name .= htmlspecialchars($data[$field->id]) . ' ';
165
                }
166
            }
167
            $name = trim($name);
168
169
            $save = Ecommerce\Delivery\Save::get([['user_id', $cart->user->id], ['name', $name]]);
170
            if (!$save) {
171
                $save = new Ecommerce\Delivery\Save();
172
                $save->user_id = $cart->user->id;
173
                $save->name = $name;
174
                $save->save();
175
            }
176
            foreach ($fields as $field) {
177
                if (!$field->save) {
178
                    continue;
179
                }
180
                if (isset($data[$field->id])) {
181
                    $value = htmlspecialchars($data[$field->id]);
182
                    if (!isset($save->values[$field->id])) {
183
                        $saveValue = new Ecommerce\Delivery\Value();
184
                        $saveValue->value = $value;
185
                        $saveValue->delivery_field_id = $field->id;
186
                        $saveValue->delivery_save_id = $save->id;
187
                        $saveValue->save();
188
                    } else {
189
                        $saveValue = $save->values[$field->id];
190
                        $saveValue->value = $value;
191
                        $saveValue->save();
192
                    }
193
                }
194
            }
195
        }
196
        foreach ($fields as $field) {
197
            if (isset($data[$field->id])) {
198
                $value = htmlspecialchars($data[$field->id]);
199
                if (!isset($cart->deliveryInfos[$field->id])) {
200
                    $info = new \Ecommerce\Cart\DeliveryInfo();
201
                    $info->name = $field->name;
202
                    $info->value = $value;
203
                    $info->delivery_field_id = $field->id;
204
                    $info->cart_id = $cart->id;
205
                    $info->save();
206
                } else {
207
                    $info = $cart->deliveryInfos[$field->id];
208
                    $info->value = $value;
209
                    $info->save();
210
                }
211
            }
212
213
            if (isset($info) && $user && $field->userfield) {
214
                $relations = [];
215
                if (strpos($field->userfield, ':')) {
216
                    $path = explode(':', $field->userfield);
217
                    if (!$user->{$path[0]}->{$path[1]}) {
218
                        $user->{$path[0]}->{$path[1]} = $info->value;
219
                        $relations[$path[0]] = $path[0];
220
                    }
221
                } else {
222
                    if (!$user->{$field->userfield}) {
223
                        $user->{$field->userfield} = $info->value;
224
                    }
225
                }
226
                foreach ($relations as $rel) {
227
                    $user->$rel->save();
228
                }
229
                $user->save();
230
            }
231
        }
232
        return isset($save) ? $save : false;
233
    }
234
235
    /**
236
     * @param bool $create
237
     * @return \Ecommerce\Cart
238
     */
239
    public function getCurCart($create = true) {
240
        $cart = false;
241
        if (!empty($_SESSION['cart']['cart_id'])) {
242
            $cart = Ecommerce\Cart::get((int) $_SESSION['cart']['cart_id']);
0 ignored issues
show
Bug Compatibility introduced by
The expression \Ecommerce\Cart::get((in...ON['cart']['cart_id']); of type boolean|Model adds the type boolean to the return on line 263 which is incompatible with the return type documented by Ecommerce::getCurCart of type Ecommerce\Cart.
Loading history...
243
            if ($cart->checkPrices()) {
244
                $cart->save();
245
            }
246
        }
247
        if (!$cart && $create) {
248
            $cart = new Ecommerce\Cart();
249
            $cart->cart_status_id = 1;
250
            $cart->user_id = Users\User::$cur->id;
251
            $userCard = \Ecommerce\Card\Item::get(\Users\User::$cur->id, 'user_id');
252
            if ($userCard) {
253
                $cart->card_item_id = $userCard->id;
254
            }
255
            $cart->save();
256
            $_SESSION['cart']['cart_id'] = $cart->id;
257
        }
258
        $defaultDelivery = \Ecommerce\Delivery::get(1, 'default');
259
        if ($cart && $defaultDelivery && !$cart->delivery_id) {
260
            $cart->delivery_id = $defaultDelivery->id;
261
            $cart->save();
262
        }
263
        return $cart;
264
    }
265
266
    /**
267
     * Getting items params with params
268
     *
269
     * @param array $params
270
     * @return array
271
     */
272
    public function getItemsParams($params = [], $saveFilterOptions = []) {
273
        $filtersOptions = !empty($params['filters']['options']) ? $params['filters']['options'] : [];
274
        $params['filters'] = [];
275
        foreach ($filtersOptions as $optionId => $filter) {
276
            if (in_array($optionId, $saveFilterOptions)) {
277
                $params['filters']['options'][$optionId] = $filter;
278
            }
279
        }
280
        $selectOptions = Ecommerce\OptionsParser::parse($params);
281
        $selectOptions['array'] = true;
282
        $items = Ecommerce\Item::getList($selectOptions);
283
        if (!$items) {
284
            return [];
285
        }
286
        $cols = array_keys(App::$cur->db->getTableCols(\Ecommerce\Item\Option::table()));
287
        $cols[] = \Ecommerce\Item\Param::colPrefix() . \Ecommerce\Item::index();
288
        $selectOptions = ['where' => ['view', 1],
289
            'join' => [
290
                [Ecommerce\Item\Param::table(), \Ecommerce\Item\Option::index() . ' = ' . Ecommerce\Item\Param::colPrefix() . \Ecommerce\Item\Option::index() . ' and ' . Ecommerce\Item\Param::colPrefix() . Ecommerce\Item::index() . ' IN (' . implode(',', array_keys($items)) . ')', 'inner'],
291
            ],
292
            'distinct' => true,
293
            'cols' => implode(',', $cols)
294
        ];
295
        $options = Ecommerce\Item\Option::getList($selectOptions);
296
        return $options;
297
    }
298
299
    /**
300
     * Getting items with params
301
     *
302
     * @param array $params
303
     * @return array
304
     */
305
    public function getItems($params = []) {
306
        $selectOptions = Ecommerce\OptionsParser::parse($params);
307
        $items = Ecommerce\Item::getList($selectOptions);
308
        return $items;
309
    }
310
311
    /**
312
     * Return count of items with params
313
     *
314
     * @param array $params
315
     * @return int
316
     */
317
    public function getItemsCount($params = []) {
318
        $selectOptions = Ecommerce\OptionsParser::parse($params);
319
        $selectOptions['distinct'] = \Ecommerce\Item::index();
320
        $counts = Ecommerce\Item::getCount($selectOptions);
321
        if (is_array($counts)) {
322
            $sum = 0;
323
            foreach ($counts as $count) {
324
                $sum += $count['count'];
325
            }
326
            return $sum;
327
        }
328
        return $counts;
329
    }
330
331 View Code Duplication
    public function viewsCategoryList($inherit = true) {
332
        $return = [];
333
        if ($inherit) {
334
            $return['inherit'] = 'Как у родителя';
335
        }
336
        $return['itemList'] = 'Список товаров';
337
        $conf = App::$primary->view->template->config;
338
        if (!empty($conf['files']['modules']['Ecommerce'])) {
339
            foreach ($conf['files']['modules']['Ecommerce'] as $file) {
340
                if ($file['type'] == 'Category') {
341
                    $return[$file['file']] = $file['name'];
342
                }
343
            }
344
        }
345
        return $return;
346
    }
347
348 View Code Duplication
    public function templatesCategoryList() {
349
        $return = [
350
            'inherit' => 'Как у родителя',
351
            'current' => 'Текущая тема'
352
        ];
353
354
        $conf = App::$primary->view->template->config;
355
356
        if (!empty($conf['files']['aditionTemplateFiels'])) {
357
            foreach ($conf['files']['aditionTemplateFiels'] as $file) {
358
                $return[$file['file']] = '- ' . $file['name'];
359
            }
360
        }
361
        return $return;
362
    }
363
364
    public function cartStatusDetector($event) {
365
        $cart = $event['eventObject'];
366
        if (!empty($cart->_changedParams['cart_cart_status_id'])) {
367
            $cart->date_status = date('Y-m-d H:i:s');
368
            $event = new Ecommerce\Cart\Event(['cart_id' => $cart->id, 'user_id' => \Users\User::$cur->id, 'cart_event_type_id' => 5, 'info' => $cart->cart_status_id]);
369
            $event->save();
370
371
            $prev_status_id = $cart->_changedParams['cart_cart_status_id'];
372
            $now_status_id = $cart->cart_status_id;
373
374
            $status = Ecommerce\Cart\Status::getList(['where' => ['id', implode(',', [$prev_status_id, $now_status_id]), 'IN']]);
375
376
            $prefix = isset(App::$cur->ecommerce->config['orderPrefix']) ? $config = App::$cur->ecommerce->config['orderPrefix'] : '';
377
            \App::$cur->users->AddUserActivity($cart->user_id, 3, "Статус вашего заказа номер {$prefix}{$cart->id} изменился с {$status[$prev_status_id]->name} на {$status[$now_status_id]->name}");
378
379
            if ($cart->cart_status_id == 5) {
380
                Inji::$inst->event('ecommerceCartClosed', $cart);
381
            }
382
        }
383
        return $cart;
384
    }
385
386
    public function cardTrigger($event) {
387
        $cart = $event['eventObject'];
388
        if ($cart->card) {
389
            $sum = 0;
390
            foreach ($cart->cartItems as $cartItem) {
391
                $sum += $cartItem->final_price * $cartItem->count;
392
            }
393
            $cardItemHistory = new Ecommerce\Card\Item\History();
394
            $cardItemHistory->amount = $sum;
395
            $cardItemHistory->card_item_id = $cart->card_item_id;
396
            $cardItemHistory->save();
397
            $cart->card->sum += $sum;
398
            $cart->card->save();
399
        }
400
        return $cart;
401
    }
402
403
    public function bonusTrigger($event) {
404
        $cart = $event['eventObject'];
405
        foreach ($cart->cartItems as $cartItem) {
406
            foreach ($cartItem->price->offer->bonuses as $bonus) {
407
                if ($bonus->limited && $bonus->left <= 0) {
408
                    continue;
409
                } elseif ($bonus->limited && $bonus->left > 0) {
410
                    $bonus->left -= 1;
411
                    $bonus->save();
412
                }
413
                switch ($bonus->type) {
414
                    case 'currency':
415
                        $currency = \Money\Currency::get($bonus->value);
416
                        $wallets = App::$cur->money->getUserWallets($cart->user->id);
417
                        $wallets[$currency->id]->diff($bonus->count, 'Бонус за покупку');
418
                        break;
419
                }
420
            }
421
        }
422
        return $cart;
423
    }
424
425
    public function sitemap() {
426
        $map = [];
427
        $zeroItems = \Ecommerce\Item::getList(['where' => ['category_id', 0], 'array' => true, 'cols' => ['item_id', 'item_name']]);
428
        foreach ($zeroItems as $item) {
429
            $map[] = [
430
                'name' => $item['item_name'],
431
                'url' => [
432
                    'loc' => (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . INJI_DOMAIN_NAME . '/ecommerce/view/' . $item['item_id']
433
                ],
434
            ];
435
        }
436
437
        $categorys = \Ecommerce\Category::getList(['where' => ['parent_id', 0]]);
438
        $scan = function ($category, $scan) {
439
            $map = [];
440
441
            foreach ($category->items(['array' => true, 'cols' => ['item_id', 'item_name']]) as $item) {
442
                $map[] = [
443
                    'name' => $item['item_name'],
444
                    'url' => [
445
                        'loc' => (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . INJI_DOMAIN_NAME . '/ecommerce/view/' . $item['item_id']
446
                    ],
447
                ];
448
            }
449
            foreach ($category->catalogs as $child) {
450
                $map = array_merge($map, $scan($child, $scan));
451
            }
452
            return $map;
453
        };
454
        foreach ($categorys as $category) {
455
            $map = array_merge($map, $scan($category, $scan));
456
        }
457
        return $map;
458
    }
459
460
    public function getFavoriteCount() {
461
        if (Users\User::$cur->id) {
462
            return \Ecommerce\Favorite::getCount(['user_id', Users\User::$cur->id]);
463 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
464
            $favs = !empty($_COOKIE['ecommerce_favitems']) ? json_decode($_COOKIE['ecommerce_favitems'], true) : [];
465
            return count($favs);
466
        }
467
    }
468
469
    public function siteSearch($search) {
470
        //items pages
471
        $count = $this->getItemsCount([
472
            'search' => trim($search),
473
        ]);
474
        //items
475
        $items = $this->getItems([
476
            'start' => 0,
477
            'count' => 10,
478
            'search' => trim($search),
479
        ]);
480
        $searchResult = [];
481
        foreach ($items as $item) {
482
            $details = '<div>';
483
            if ($item->image) {
484
                $details .= "<img style='margin-right:10px;margin-bottom:10px;' class='pull-left' src ='" . Statics::file($item->image->path, '70x70', 'q') . "' />";
485
            }
486
            $details .= '<b>' . $item->category->name . '</b><br />';
487
            $shortdes = mb_substr($item->description, 0, 200);
488
            $shortdes = mb_substr($shortdes, 0, mb_strrpos($shortdes, ' '));
489
            $details .= $shortdes;
490
            if (mb_strlen($item->description) > $shortdes) {
491
                $details .= '...';
492
            }
493
            $details .= '<div class="clearfix"></div> </div>';
494
            $searchResult[] = [
495
                'title' => $item->name(),
496
                'details' => $details,
497
                'href' => '/ecommerce/view/' . $item->id
498
            ];
499
        }
500
        return ['name' => 'Онлайн магазин', 'count' => $count, 'result' => $searchResult, 'detailSearch' => '/ecommerce/itemList?search=' . $search];
501
    }
502
503
    public function priceTypes() {
504
        $payTypes = ['custom' => 'Настраиваемая стоимость'];
505
        foreach ($this->getObjects('Ecommerce\\DeliveryHelper') as $className) {
506
            $payTypes[$className] = $className::$name;
507
        }
508
        return $payTypes;
509
    }
510
}