Completed
Push — master ( 0d4988...d79a7d )
by Alexey
05:18
created

Ecommerce::getItemsParams()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 1
eloc 8
nc 1
nop 1
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
    {
15
        App::$primary->view->customAsset('js', '/moduleAsset/Ecommerce/js/cart.js');
16
    }
17
18
    public function getPayTypeHandlers($forSelect = false)
19
    {
20
        if (!$forSelect) {
21
            return $this->getSnippets('payTypeHandler');
22
        }
23
        $handlers = ['' => 'Не выбрано'];
24
        foreach ($this->getSnippets('payTypeHandler') as $key => $handler) {
25
            if (empty($handler)) {
26
                continue;
27
            }
28
            $handlers[$key] = $handler['name'];
29
        }
30
        return $handlers;
31
    }
32
33
    public function cartPayRecive($data)
34
    {
35
        $cart = Ecommerce\Cart::get($data['pay']->data);
36
        if ($cart) {
37
            $payed = true;
38
            foreach ($cart->pays as $pay) {
39
                if ($pay->pay_status_id != 2) {
40
                    $payed = false;
41
                    break;
42
                }
43
            }
44
            $cart->payed = $payed;
45
            $cart->save();
46
        }
47
    }
48
49 View Code Duplication
    public function parseFields($data, $cart)
50
    {
51
        $fields = \Ecommerce\UserAdds\Field::getList();
52
        $name = '';
53
        foreach ($fields as $field) {
54
            if ($field->save && !empty($data[$field->id])) {
55
                $name .= htmlspecialchars($data[$field->id]) . ' ';
56
            }
57
        }
58
        $name = trim($name);
59
60
        $userAdds = Ecommerce\UserAdds::get([['user_id', $cart->user->id], ['name', $name]]);
61
        if (!$userAdds) {
62
            $userAdds = new Ecommerce\UserAdds();
63
            $userAdds->user_id = $cart->user->id;
64
            $userAdds->name = $name;
65
            $userAdds->save();
66
            foreach ($fields as $field) {
67
                if (!$field->save) {
68
                    continue;
69
                }
70
                $userAddsValue = new Ecommerce\UserAdds\Value();
71
                $userAddsValue->value = htmlspecialchars($data[$field->id]);
72
                $userAddsValue->useradds_field_id = $field->id;
73
                $userAddsValue->useradds_id = $userAdds->id;
74
                $userAddsValue->save();
75
            }
76
        }
77
        $user = \Users\User::get($cart->user_id);
78
        foreach ($fields as $field) {
79
            $info = new \Ecommerce\Cart\Info();
80
            $info->name = $field->name;
81
            $info->value = htmlspecialchars($data[$field->id]);
82
            $info->useradds_field_id = $field->id;
83
            $info->cart_id = $cart->id;
84
            $info->save();
85
            $relations = [];
86
            if ($field->userfield) {
87
                if (strpos($field->userfield, ':')) {
88
                    $path = explode(':', $field->userfield);
89
                    if (!$user->{$path[0]}->{$path[1]}) {
90
                        $user->{$path[0]}->{$path[1]} = $info->value;
91
                        $relations[$path[0]] = $path[0];
92
                    }
93
                } else {
94
                    if (!$user->{$field->userfield}) {
95
                        $user->{$field->userfield} = $info->value;
96
                    }
97
                }
98
            }
99
            foreach ($relations as $rel) {
100
                $user->$rel->save();
101
            }
102
            $user->save();
103
        }
104
        return $userAdds;
105
    }
106
107 View Code Duplication
    public function parseDeliveryFields($data, $cart, $fields)
108
    {
109
        $name = '';
110
        foreach ($fields as $field) {
111
            if ($field->save && !empty($data[$field->id])) {
112
                $name .= htmlspecialchars($data[$field->id]) . ' ';
113
            }
114
        }
115
        $name = trim($name);
116
117
        $save = Ecommerce\Delivery\Save::get([['user_id', $cart->user->id], ['name', $name]]);
118
        if (!$save) {
119
            $save = new Ecommerce\Delivery\Save();
120
            $save->user_id = $cart->user->id;
121
            $save->name = $name;
122
            $save->save();
123
            foreach ($fields as $field) {
124
                if (!$field->save) {
125
                    continue;
126
                }
127
                $saveValue = new Ecommerce\Delivery\Value();
128
                $saveValue->value = htmlspecialchars($data[$field->id]);
129
                $saveValue->delivery_field_id = $field->id;
130
                $saveValue->delivery_save_id = $save->id;
131
                $saveValue->save();
132
            }
133
        }
134
        $user = \Users\User::get($cart->user_id);
135
        foreach ($fields as $field) {
136
            $info = new \Ecommerce\Cart\DeliveryInfo();
137
            $info->name = $field->name;
138
            $info->value = htmlspecialchars($data[$field->id]);
139
            $info->delivery_field_id = $field->id;
140
            $info->cart_id = $cart->id;
141
            $info->save();
142
            $relations = [];
143
            if ($field->userfield) {
144
                if (strpos($field->userfield, ':')) {
145
                    $path = explode(':', $field->userfield);
146
                    if (!$user->{$path[0]}->{$path[1]}) {
147
                        $user->{$path[0]}->{$path[1]} = $info->value;
148
                        $relations[$path[0]] = $path[0];
149
                    }
150
                } else {
151
                    if (!$user->{$field->userfield}) {
152
                        $user->{$field->userfield} = $info->value;
153
                    }
154
                }
155
            }
156
            foreach ($relations as $rel) {
157
                $user->$rel->save();
158
            }
159
            $user->save();
160
        }
161
        return $save;
162
    }
163
164
    public function getCurCart($create = true)
1 ignored issue
show
Coding Style introduced by
getCurCart uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
165
    {
166
        $cart = false;
167
        if (!empty($_SESSION['cart']['cart_id'])) {
168
            $cart = Ecommerce\Cart::get((int) $_SESSION['cart']['cart_id']);
169
        }
170
        if (!$cart && $create) {
171
            $cart = new Ecommerce\Cart();
172
            $cart->cart_status_id = 1;
173
            $cart->user_id = Users\User::$cur->id;
174
            $userCard = \Ecommerce\Card\Item::get(\Users\User::$cur->id, 'user_id');
175
            if ($userCard) {
176
                $cart->card_item_id = $userCard->id;
177
            }
178
            $cart->save();
179
            $_SESSION['cart']['cart_id'] = $cart->id;
180
        }
181
        return $cart;
182
    }
183
184
    public function parseOptions($options = [])
185
    {
186
        $selectOptions = [
187
            'where' => !empty($options['where']) ? $options['where'] : [],
188
            'distinct' => false,
189
            'join' => [],
190
            'order' => [],
191
            'start' => isset($options['start']) ? (int) $options['start'] : 0,
192
            'key' => isset($options['key']) ? $options['key'] : null,
193
            'limit' => !empty($options['count']) ? (int) $options['count'] : 0,
194
        ];
195
        if (!empty($options['sort']) && is_array($options['sort'])) {
196
            foreach ($options['sort'] as $col => $direction) {
197
                switch ($col) {
198
                    case 'price':
199
                        $selectOptions['order'][] = [Ecommerce\Item\Offer\Price::colPrefix() . 'price', strtolower($direction) == 'desc' ? 'desc' : 'asc'];
200
                        break;
201 View Code Duplication
                    case 'name':
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...
202
                        $selectOptions['order'][] = ['name', strtolower($direction) == 'desc' ? 'desc' : 'asc'];
203
                        break;
204 View Code Duplication
                    case 'sales':
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...
205
                        $selectOptions['order'][] = ['sales', strtolower($direction) == 'desc' ? 'desc' : 'asc'];
206
                        break;
207 View Code Duplication
                    case 'weight':
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...
208
                        $selectOptions['order'][] = ['weight', strtolower($direction) == 'desc' ? 'desc' : 'asc'];
209
                        break;
210
                }
211
            }
212
        }
213
        $selectOptions['where'][] = ['deleted', 0];
214
        if (empty($this->config['view_empty_image'])) {
215
            $selectOptions['where'][] = ['image_file_id', 0, '!='];
216
        }
217
        if (!empty($this->config['view_filter'])) {
218
            if (!empty($this->config['view_filter']['options'])) {
219
                foreach ($this->config['view_filter']['options'] as $optionId => $optionValue) {
220
                    $selectOptions['join'][] = [Ecommerce\Item\Param::table(), Ecommerce\Item::index() . ' = ' . 'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . Ecommerce\Item::index() . ' AND ' .
221
                        'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . Ecommerce\Item\Option::index() . ' = "' . (int) $optionId . '" AND ' .
222
                        'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . 'value = "' . (int) $optionValue . '"',
223
                        'inner', 'option' . $optionId];
224
                }
225
            }
226
        }
227
        //filters
228
        if (!empty($options['filters'])) {
229
            foreach ($options['filters'] as $col => $filter) {
230
                switch ($col) {
231
                    case 'price':
232 View Code Duplication
                        if (!empty($filter['min'])) {
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...
233
                            $selectOptions['where'][] = [Ecommerce\Item\Offer\Price::colPrefix() . 'price', (float) $filter['min'], '>='];
234
                        }
235 View Code Duplication
                        if (!empty($filter['max'])) {
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...
236
                            $selectOptions['where'][] = [Ecommerce\Item\Offer\Price::colPrefix() . 'price', (float) $filter['max'], '<='];
237
                        }
238
                        break;
239
                    case 'options':
240
                        foreach ($filter as $optionId => $optionValue) {
241
                            $selectOptions['join'][] = [Ecommerce\Item\Param::table(), Ecommerce\Item::index() . ' = ' . 'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . Ecommerce\Item::index() . ' AND ' .
242
                                'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . Ecommerce\Item\Option::index() . ' = "' . (int) $optionId . '" AND ' .
243
                                'option' . $optionId . '.' . Ecommerce\Item\Param::colPrefix() . 'value = "' . (int) $optionValue . '"',
244
                                'inner', 'option' . $optionId];
245
                        }
246
                        break;
247
                }
248
            }
249
        }
250
        //parents
251
        if (!empty($options['parent']) && strpos($options['parent'], ',') !== false) {
252
            $first = true;
253
            $where = [];
254
            foreach (explode(',', $options['parent']) as $categoryId) {
255
                if (!$categoryId) {
256
                    continue;
257
                }
258
                $category = \Ecommerce\Category::get($categoryId);
259
                $where[] = ['tree_path', $category->tree_path . (int) $categoryId . '/%', 'LIKE', $first ? 'AND' : 'OR'];
260
                $first = false;
261
            }
262
            $selectOptions['where'][] = $where;
263
        } elseif (!empty($options['parent'])) {
264
            $category = \Ecommerce\Category::get($options['parent']);
265
            $selectOptions['where'][] = ['tree_path', $category->tree_path . (int) $options['parent'] . '/%', 'LIKE'];
266
        }
267
268
        //search
269
        if (!empty($options['search'])) {
270
            $searchStr = preg_replace('![^A-zА-я0-9 ]!iSu', ' ', $options['search']);
271
            $searchArr = [];
272
            foreach (explode(' ', $searchStr) as $part) {
273
                $part = trim($part);
274
                if ($part && strlen($part) > 2) {
275
                    $searchArr[] = ['search_index', '%' . $part . '%', 'LIKE'];
276
                }
277
            }
278
            if (!empty($searchArr)) {
279
                $selectOptions['where'][] = $searchArr;
280
            }
281
        }
282
        if (empty($this->config['view_empty_warehouse'])) {
283
            $selectOptions['where'][] = [
284
                '(
285
          (SELECT COALESCE(sum(`' . \Ecommerce\Item\Offer\Warehouse::colPrefix() . 'count`),0) 
286
            FROM ' . \App::$cur->db->table_prefix . \Ecommerce\Item\Offer\Warehouse::table() . ' iciw 
287
            WHERE iciw.' . \Ecommerce\Item\Offer\Warehouse::colPrefix() . \Ecommerce\Item\Offer::index() . ' = ' . \Ecommerce\Item\Offer::index() . '
288
            )
289
          -
290
          (SELECT COALESCE(sum(' . \Ecommerce\Warehouse\Block::colPrefix() . 'count) ,0)
291
            FROM ' . \App::$cur->db->table_prefix . \Ecommerce\Warehouse\Block::table() . ' iewb
292
            inner JOIN ' . \App::$cur->db->table_prefix . \Ecommerce\Cart::table() . ' icc ON icc.' . \Ecommerce\Cart::index() . ' = iewb.' . \Ecommerce\Warehouse\Block::colPrefix() . \Ecommerce\Cart::index() . ' AND (
293
                (`' . \Ecommerce\Cart::colPrefix() . 'warehouse_block` = 1 and `' . \Ecommerce\Cart::colPrefix() . 'cart_status_id` in(2,3,6)) ||
294
                (`' . \Ecommerce\Cart::colPrefix() . \Ecommerce\Cart\Status::index() . '` in(0,1) and `' . \Ecommerce\Cart::colPrefix() . 'date_last_activ` >=subdate(now(),INTERVAL 30 MINUTE))
295
            )
296
            WHERE iewb.' . \Ecommerce\Warehouse\Block::colPrefix() . \Ecommerce\Item\Offer::index() . ' = ' . \Ecommerce\Item\Offer::index() . ')
297
          )',
298
                0,
299
                '>'
300
            ];
301
        }
302
303
304
        $selectOptions['join'][] = [Ecommerce\Item\Offer::table(), Ecommerce\Item::index() . ' = ' . Ecommerce\Item\Offer::colPrefix() . Ecommerce\Item::index(), 'inner'];
305
        $selectOptions['join'][] = [Ecommerce\Item\Offer\Price::table(),
306
            Ecommerce\Item\Offer::index() . ' = ' . Ecommerce\Item\Offer\Price::colPrefix() . Ecommerce\Item\Offer::index() . ' and ' . Ecommerce\Item\Offer\Price::colPrefix() . 'price>0', 'inner'];
307
        $selectOptions['join'][] = [
308
            Ecommerce\Item\Offer\Price\Type::table(), Ecommerce\Item\Offer\Price::colPrefix() . Ecommerce\Item\Offer\Price\Type::index() . ' = ' . Ecommerce\Item\Offer\Price\Type::index() .
309
            ' and (' . Ecommerce\Item\Offer\Price\Type::colPrefix() . 'roles="" || ' . Ecommerce\Item\Offer\Price\Type::colPrefix() . 'roles LIKE "%|' . \Users\User::$cur->role_id . '|%")'
310
        ];
311
        $selectOptions['where'][] = [
312
            [Ecommerce\Item\Offer\Price::colPrefix() . Ecommerce\Item\Offer\Price\Type::index(), 0],
313
            [Ecommerce\Item\Offer\Price\Type::index(), 0, '>', 'OR']
314
        ];
315
316
317
318
        $selectOptions['group'] = Ecommerce\Item::index();
319
320
        return $selectOptions;
321
    }
322
323
    /**
324
     * Getting items params with params
325
     * 
326
     * @param array $params
327
     * @return array
328
     */
329
    public function getItemsParams($params = [])
330
    {
331
        $selectOptions = $this->parseOptions($params);
332
        $items = Ecommerce\Item::getList($selectOptions);
333
        $items = Ecommerce\Item\Param::getList([
334
                    'where' => ['item_id', array_keys($items), 'IN'],
335
                    'join' => [[Ecommerce\Item\Option::table(), Ecommerce\Item\Option::index() . ' = ' . \Ecommerce\Item\Param::colPrefix() .Ecommerce\Item\Option::index(). ' and ' . \Ecommerce\Item\Option::colPrefix() . 'searchable = 1', 'inner']],
336
                    'distinct' => \Ecommerce\Item\Option::index()
337
        ]);
338
        return $items;
339
    }
340
341
    /**
342
     * Getting items with params
343
     * 
344
     * @param array $params
345
     * @return array
346
     */
347
    public function getItems($params = [])
348
    {
349
        $selectOptions = $this->parseOptions($params);
350
        $items = Ecommerce\Item::getList($selectOptions);
351
        return $items;
352
    }
353
354
    /**
355
     * Return count of items with params
356
     * 
357
     * @param array $params
358
     * @return int
359
     */
360
    public function getItemsCount($params = [])
361
    {
362
        $selectOptions = $this->parseOptions($params);
363
        $selectOptions['distinct'] = \Ecommerce\Item::index();
364
        $counts = Ecommerce\Item::getCount($selectOptions);
365
        if (is_array($counts)) {
366
            $sum = 0;
367
            foreach ($counts as $count) {
368
                $sum +=$count['count'];
369
            }
370
            return $sum;
371
        }
372
        return $counts;
373
    }
374
375 View Code Duplication
    public function viewsCategoryList($inherit = true)
376
    {
377
        $return = [];
378
        if ($inherit) {
379
            $return['inherit'] = 'Как у родителя';
380
        }
381
        $return['itemList'] = 'Список товаров';
382
        $conf = App::$primary->view->template->config;
383
        if (!empty($conf['files']['modules']['Ecommerce'])) {
384
            foreach ($conf['files']['modules']['Ecommerce'] as $file) {
385
                if ($file['type'] == 'Category') {
386
                    $return[$file['file']] = $file['name'];
387
                }
388
            }
389
        }
390
        return $return;
391
    }
392
393 View Code Duplication
    public function templatesCategoryList()
394
    {
395
        $return = [
396
            'inherit' => 'Как у родителя',
397
            'current' => 'Текущая тема'
398
        ];
399
400
        $conf = App::$primary->view->template->config;
401
402
        if (!empty($conf['files']['aditionTemplateFiels'])) {
403
            foreach ($conf['files']['aditionTemplateFiels'] as $file) {
404
                $return[$file['file']] = '- ' . $file['name'];
405
            }
406
        }
407
        return $return;
408
    }
409
410
    public function cartStatusDetector($event)
411
    {
412
        $cart = $event['eventObject'];
413
        if (!empty($cart->_changedParams['cart_cart_status_id'])) {
414
            $cart->date_status = date('Y-m-d H:i:s');
415
            $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]);
416
            $event->save();
417
418
            $prev_status_id = $cart->_changedParams['cart_cart_status_id'];
419
            $now_status_id = $cart->cart_status_id;
420
421
            $status = Ecommerce\Cart\Status::getList(['where' => ['id', implode(',', [$prev_status_id, $now_status_id]), 'IN']]);
422
423
            $prefix = isset(App::$cur->ecommerce->config['orderPrefix']) ? $config = App::$cur->ecommerce->config['orderPrefix'] : '';
424
            \App::$cur->users->AddUserActivity($cart->user_id, 3, "Статус вашего заказа номер {$prefix}{$cart->id} изменился с {$status[$prev_status_id]->name} на {$status[$now_status_id]->name}");
425
426
            if ($cart->cart_status_id == 5) {
427
                Inji::$inst->event('ecommerceCartClosed', $cart);
428
            }
429
        }
430
    }
431
432
    public function cardTrigger($event)
433
    {
434
        $cart = $event['eventObject'];
435
        if ($cart->card) {
436
            $sum = 0;
437
            foreach ($cart->cartItems as $cartItem) {
438
                $sum += $cartItem->final_price * $cartItem->count;
439
            }
440
            $cardItemHistory = new Ecommerce\Card\Item\History();
441
            $cardItemHistory->amount = $sum;
442
            $cardItemHistory->card_item_id = $cart->card_item_id;
443
            $cardItemHistory->save();
444
            $cart->card->sum += $sum;
445
            $cart->card->save();
446
        }
447
    }
448
449
    public function bonusTrigger($event)
450
    {
451
        $cart = $event['eventObject'];
452
        foreach ($cart->cartItems as $cartItem) {
453
            foreach ($cartItem->price->offer->bonuses as $bonus) {
454
                if ($bonus->limited && $bonus->left <= 0) {
455
                    continue;
456
                } elseif ($bonus->limited && $bonus->left > 0) {
457
                    $bonus->left -= 1;
458
                    $bonus->save();
459
                }
460
                switch ($bonus->type) {
461
                    case'currency':
0 ignored issues
show
Coding Style introduced by
As per coding-style, case should be followed by a single space.

As per the PSR-2 coding standard, there must be a space after the case keyword, instead of the test immediately following it.

switch (true) {
    case!isset($a):  //wrong
        doSomething();
        break;
    case !isset($b):  //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
462
                        $currency = \Money\Currency::get($bonus->value);
463
                        $wallets = App::$cur->money->getUserWallets($cart->user->id);
464
                        $wallets[$currency->id]->diff($bonus->count, 'Бонус за покупку');
465
                        break;
466
                }
467
            }
468
        }
469
    }
470
471
}
472