Test Failed
Push — master ( cf7a15...101480 )
by Alexey
05:05
created

CartController::deleteItemAction()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 18
nc 4
nop 0
dl 0
loc 22
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Ecommerce Cart app controller
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 CartController extends Controller {
12
13
    public function indexAction() {
14
        $cart = '';
15
        $deliverys = \Ecommerce\Delivery::getList(['where' => ['disabled', 0], 'order' => ['weight', 'ASC']]);
16
        $payTypes = \Ecommerce\PayType::getList(['order' => ['weight', 'ASC']]);
17
        if (!empty($_SESSION['cart']['cart_id'])) {
18
            $cart = Ecommerce\Cart::get($_SESSION['cart']['cart_id']);
19
            if (!empty($_POST)) {
20
                $error = false;
21
                if (!Users\User::$cur->id) {
22
                    $user_id = $this->Users->registration($_POST, true);
23
                    if (!$user_id) {
24
                        $error = true;
25
                    } else {
26
                        $user = Users\User::get($user_id);
27
                    }
28
                } else {
29
                    $user = Users\User::$cur;
30
                }
31
                $ids = [];
32
                if (!empty($_POST['cartItems'])) {
33
                    foreach ($_POST['cartItems'] as $cartItemId => $cartItemCont) {
34
                        $cartItem = \Ecommerce\Cart\Item::get((int)$cartItemId);
35
                        if (!$cartItem) {
36
                            continue;
37
                        }
38
                        if ($cartItem->cart_id != $cart->id) {
39
                            continue;
40
                        }
41
                        $count = (float)$cartItemCont;
42
                        if ($count < 0.001) {
43
                            $count = 1;
44
                        }
45
                        $cartItem->count = $count;
46
                        $cartItem->save();
47
                        $ids[] = $cartItemId;
48
                    }
49
                }
50
                foreach ($cart->cartItems as $cartItem) {
51
                    if (!in_array($cartItem->id, $ids)) {
52
                        $cartItem->delete();
53
                    }
54
                }
55
                $cart = Ecommerce\Cart::get($cart->id);
56
                if (!$cart->cartItems) {
57
                    $error = true;
58
                }
59
                if (empty($this->module->config['sell_over_warehouse'])) {
60
                    foreach ($cart->cartItems as $cartitem) {
61
                        $warecount = $cartitem->price->offer->warehouseCount($cart->id);
62
                        if ($cartitem->count > $warecount) {
63
                            $error = true;
64
                            Msg::add('Вы заказали <b>' . $cartitem->item->name . '</b> больше чем есть на складе. на складе: <b>' . $warecount . '</b>', 'danger');
65
                        }
66
                    }
67
                }
68
                if ($deliverys && empty($deliverys[$_POST['delivery']])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deliverys of type Model[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
69
                    $error = 1;
70
                    Msg::add('Выберите способ доставки', 'danger');
71
                } elseif ($deliverys && !empty($deliverys[$_POST['delivery']])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deliverys of type Model[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
72
                    $cart->delivery_id = $_POST['delivery'];
73
                    foreach ($deliverys[$cart->delivery_id]->fields as $field) {
74 View Code Duplication
                        if (empty($_POST['deliveryFields'][$field->id]) && $field->required) {
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...
75
                            $error = 1;
76
                            Msg::add('Вы не указали: ' . $field->name, 'danger');
77
                        }
78
                    }
79
                }
80
                if ($payTypes && (empty($_POST['payType']) || empty($payTypes[$_POST['payType']]))) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $payTypes of type Model[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
81
                    $error = 1;
82
                    Msg::add('Выберите способ оплаты', 'danger');
83
                } elseif ($payTypes && !empty($payTypes[$_POST['payType']])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $payTypes of type Model[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
84
                    $payType = $payTypes[$_POST['payType']];
85
                    $cart->paytype_id = $payType->id;
86
                } else {
87
                    $payType = null;
88
                }
89
                foreach (\Ecommerce\UserAdds\Field::getList() as $field) {
90 View Code Duplication
                    if (empty($_POST['userAdds']['fields'][$field->id]) && $field->required) {
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...
91
                        $error = 1;
92
                        Msg::add('Вы не указали: ' . $field->name, 'danger');
93
                    }
94
                }
95
                if (!empty($_POST['discounts']['card_item_id'])) {
96
                    $userCard = \Ecommerce\Card\Item::get((int)$_POST['discounts']['card_item_id']);
97
                    if (!$userCard) {
98
                        $error = true;
99
                        Msg::add('Такой карты не существует', 'danger');
100
                    } elseif ($userCard->user_id != $user->id) {
101
                        $error = true;
102
                        Msg::add('Это не ваша карта', 'danger');
103
                    } else {
104
                        $cart->card_item_id = $userCard->id;
105
                    }
106
                }
107
                $cart->save();
108
                if (!$error && !empty($_POST['action']) && $_POST['action'] = 'order') {
109
                    $cart->user_id = $user->user_id;
110
                    $this->module->parseFields($_POST['userAdds']['fields'], $cart);
111
                    if ($deliverys && !empty($deliverys[$cart->delivery_id]) && !empty($_POST['deliveryFields'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deliverys of type Model[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
112
                        $this->module->parseDeliveryFields($_POST['deliveryFields'], $cart, $deliverys[$cart->delivery_id]->fields);
113
                    }
114
                    $cart->cart_status_id = 2;
115
                    $cart->comment = !empty($_POST['comment']) ? htmlspecialchars($_POST['comment']) : '';
116
                    $cart->date_status = date('Y-m-d H:i:s');
117
                    $cart->complete_data = date('Y-m-d H:i:s');
118
                    $cart->warehouse_block = 1;
119
                    $cart->save();
120
121
                    $cart = \Ecommerce\Cart::get($cart->id);
122
                    foreach ($cart->cartItems as $cartItem) {
123
                        $cartItem->discount = $cartItem->discount();
124
                        $cartItem->final_price = $cartItem->price->price - $cartItem->discount;
125
                        $cartItem->save();
126
                    }
127
                    $cart = \Ecommerce\Cart::get($cart->id);
128
                    if (!empty(\App::$cur->ecommerce->config['notify_mail'])) {
129
                        $text = 'Перейдите в админ панель чтобы просмотреть новый заказ <a href = "http://' . idn_to_utf8(INJI_DOMAIN_NAME) . '/admin/ecommerce/Cart">Админ панель</a>';
130
                        $title = 'Новый заказ в интернет магазине на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME);
131
                        \Tools::sendMail('noreply@' . INJI_DOMAIN_NAME, \App::$cur->ecommerce->config['notify_mail'], $title, $text);
132
                    }
133
                    if ($this->notifications) {
134
                        $notification = new Notifications\Notification();
135
                        $notification->name = 'Новый заказ в интернет магазине на сайте ' . idn_to_utf8(INJI_DOMAIN_NAME);
136
                        $notification->text = 'Перейдите в админ панель чтобы просмотреть новый заказ';
137
                        $notification->chanel_id = $this->notifications->getChanel('Ecommerce-orders')->id;
138
                        $notification->save();
139
                    }
140
                    $handlers = $this->ecommerce->getSnippets('payTypeHandler');
141
                    $redirect = ['/ecommerce/cart/success'];
142
                    if ($payType && !empty($handlers[$payType->handler]['handler'])) {
143
                        $newRedirect = $handlers[$payType->handler]['handler']($cart);
144
                        if (!empty($newRedirect)) {
145
                            $redirect = $newRedirect;
146
                        }
147
                    }
148
                    unset($_SESSION['cart']['cart_id']);
149
                    call_user_func_array(['Tools', 'redirect'], $redirect);
150
                }
151
            }
152
        }
153
        $this->view->setTitle('Корзина');
154
        $bread = [];
155
        $bread[] = [
156
            'text' => 'Каталог',
157
            'href' => '/ecommerce'
158
        ];
159
        $bread[] = [
160
            'text' => 'Корзина',
161
            'href' => '/ecommerce/cart'
162
        ];
163
        $this->view->page(['data' => compact('cart', 'items', 'deliverys', 'payTypes', 'packItem', 'bread')]);
164
    }
165
166
    public function orderDetailAction($id = 0) {
167
        $cart = Ecommerce\Cart::get((int)$id);
168
        if ($cart->user_id != Users\User::$cur->id) {
169
            $this->url->redirect('/', 'Это не ваша корзина');
170
        }
171
        $bread = [];
172
        $bread[] = [
173
            'text' => 'Каталог',
174
            'href' => '/ecommerce'
175
        ];
176
        $bread[] = [
177
            'text' => 'Корзина',
178
            'href' => '/ecommerce/cart'
179
        ];
180
        $bread[] = [
181
            'text' => 'Заказ: №' . $cart->id,
182
            'href' => '/ecommerce/cart/orderDetail/' . $cart->id
183
        ];
184
        $this->view->setTitle('Заказ №' . $cart->id);
185
        $this->view->page(['data' => compact('cart', 'bread')]);
186
    }
187
188
    public function continueAction($id = 0) {
189
        $cart = \Ecommerce\Cart::get((int)$id);
190
        if ($cart->user_id != Users\User::$cur->id) {
191
            Tools::redirect('/', 'Это не ваша корзина');
192
        }
193
        if ($cart->cart_status_id > 1) {
194
            Tools::redirect('/', 'Корзина уже оформлена');
195
        }
196
        $_SESSION['cart']['cart_id'] = $cart->id;
197
        Tools::redirect('/ecommerce/cart');
198
    }
199
200
    public function deleteAction($id = 0) {
201
        $cart = \Ecommerce\Cart::get((int)$id);
202
        if ($cart->user_id != Users\User::$cur->id) {
203
            Tools::redirect('/', 'Это не ваша корзина');
204
        }
205
        if ($cart->cart_status_id > 1) {
206
            Tools::redirect('/', 'Корзина уже оформлена');
207
        }
208
        if (!empty($_SESSION['cart']['cart_id']) && $_SESSION['cart']['cart_id'] == $cart->id) {
209
            unset($_SESSION['cart']['cart_id']);
210
        }
211
        $cart->delete();
212
        Tools::redirect('/users/cabinet/ecommerceOrdersHistory', 'Корзина была удалена', 'success');
213
    }
214
215
    public function refillAction($id = 0) {
216
        $cart = \Ecommerce\Cart::get((int)$id);
217
        if ($cart->user_id != Users\User::$cur->id) {
218
            Tools::redirect('/', 'Это не ваша корзина');
219
        }
220
        if (!empty($_SESSION['cart']['cart_id'])) {
221
            unset($_SESSION['cart']['cart_id']);
222
        }
223
        $newCart = $this->ecommerce->getCurCart();
224
        foreach ($cart->cartItems as $cartitem) {
225
            $newCart->addItem($cartitem->item_offer_price_id, $cartitem->count);
226
        }
227
228
        $newCart->save();
229
230
        Tools::redirect('/ecommerce/cart/');
231
    }
232
233
    public function successAction() {
234
        $bread = [];
235
        $bread[] = [
236
            'text' => 'Каталог',
237
            'href' => '/ecommerce'
238
        ];
239
        $bread[] = [
240
            'text' => 'Корзина',
241
            'href' => '/ecommerce/cart'
242
        ];
243
        $bread[] = [
244
            'text' => 'Заказ принят',
245
            'href' => '/ecommerce/cart/success'
246
        ];
247
        $this->view->setTitle('Заказ принят');
248
        $this->view->page(['data' => compact('bread')]);
249
    }
250
251
    public function addAction() {
252
        $result = new Server\Result();
253
        if (empty($_GET['itemOfferPriceId'])) {
254
            $result->success = false;
255
            $result->content = 'Произошла непредвиденная ошибка при добавлении товара';
256
            $result->send();
257
        }
258
        $price = \Ecommerce\Item\Offer\Price::get((int)$_GET['itemOfferPriceId']);
259
        if (!$price) {
260
            $result->success = false;
261
            $result->content = 'Такой цены не найдено';
262
            $result->send();
263
        }
264
        $item = $price->offer->item;
265
266
        if (!$item) {
267
            $result->success = false;
268
            $result->content = 'Такого товара не существует';
269
            $result->send();
270
        }
271
272
        $item->sales++;
273
        $item->save();
274
275
        if (empty($_GET['count'])) {
276
            $count = 1;
277
        } else {
278
            $count = (float)$_GET['count'];
279
        }
280
281
        $cart = $this->ecommerce->getCurCart();
282
        if (empty($this->module->config['sell_over_warehouse']) && $price->offer->warehouseCount() < $count) {
283
            $result->success = false;
284
            $result->content = 'На складе недостаточно товара! Доступно: ' . $price->offer->warehouseCount();
285
            $result->send();
286
        }
287
288
        $isset = false;
289
        foreach ($cart->cartItems as $cartItem) {
290
            if ($cartItem->item_id == $item->id && $cartItem->item_offer_price_id == $price->id) {
291
                $cartItem->count += $count;
292
                $cartItem->save();
293
                $isset = true;
294
                break;
295
            }
296
        }
297
        if (!$isset) {
298
            $cart->addItem($price->id, $count);
299
        }
300
        $cart->date_last_activ = date('Y-m-d H:i:s');
301
        $cart->calc();
302
303
        $result->successMsg = '<a href="/ecommerce/view/' . $item->id . '">' . $item->name() . ($price->offer->name() ? ' (' . $price->offer->name() . ')' : '') . '</a> добавлен <a href="/ecommerce/cart">в корзину покупок</a>!';
304
        $result->send();
305
    }
306
307
    public function deleteItemAction() {
308
        $result = new Server\Result();
309
        if (empty($_GET['cartItemId'])) {
310
            $result->success = false;
311
            $result->content = 'Произошла непредвиденная ошибка при добавлении товара';
312
            $result->send();
313
        }
314
315
        $cart = $this->ecommerce->getCurCart();
316
        if (!isset($cart->cartItems[$_GET['cartItemId']])) {
317
            $result->success = false;
318
            $result->content = 'Такого товара нет в вашей корзине';
319
            $result->send();
320
        }
321
        $cart->cartItems[$_GET['cartItemId']]->delete();
322
        ob_start();
323
        $this->view->widget('Ecommerce\cart');
324
        $result->content = ob_get_contents();
325
        ob_end_clean();
326
        $result->successMsg = 'Товар был удален';
327
        $result->send();
328
    }
329
330
    public function getcartAction() {
331
        $result = new Server\Result();
332
        ob_start();
333
        $this->view->widget('Ecommerce\cart');
334
        $result->content = ob_get_contents();
335
        ob_end_clean();
336
        $result->send();
337
    }
338
339
}
340