Test Failed
Push — master ( 455e4b...89dfd0 )
by Alexey
07:06 queued 02:50
created

Ecommerce::sitemap()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

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

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
439
            $payTypes[$className] = $className::$name;
440
        }
441
        return $payTypes;
442
    }
443
}