CommandsHandler::isFirstCommand()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace XoopsModules\Oledrion;
4
5
/*
6
 You may not change or alter any portion of this comment or credits
7
 of supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit authors.
9
10
 This program is distributed in the hope that it will be useful,
11
 but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
*/
14
15
/**
16
 * oledrion
17
 *
18
 * @copyright   {@link https://xoops.org/ XOOPS Project}
19
 * @license     {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
20
 * @author      Hervé Thouzard (http://www.herve-thouzard.com/)
21
 */
22
23
use XoopsModules\Oledrion;
24
25
/**
26
 * Sales order management
27
 */
28
29
/**
30
 * Class CommandsHandler
31
 */
32
class CommandsHandler extends OledrionPersistableObjectHandler
33
{
34
    /**
35
     * CommandsHandler constructor.
36
     * @param \XoopsDatabase|null $db
37
     */
38
    public function __construct(\XoopsDatabase $db = null)
39
    {
40
        //                        Table                   Classe           Id
41
        parent::__construct($db, 'oledrion_commands', Commands::class, 'cmd_id');
0 ignored issues
show
Bug introduced by
It seems like $db can also be of type null; however, parameter $db of XoopsModules\Oledrion\Ol...tHandler::__construct() does only seem to accept XoopsDatabase, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

41
        parent::__construct(/** @scrutinizer ignore-type */ $db, 'oledrion_commands', Commands::class, 'cmd_id');
Loading history...
42
    }
43
44
    /**
45
     * Indicates if this is the first order of a customer
46
     *
47
     * @param int $uid Identifiant de l'utilisateur
48
     * @return bool Indique si c'est le cas ou pas
49
     */
50
    public function isFirstCommand($uid = 0)
51
    {
52
        if (0 == $uid) {
53
            $uid = Oledrion\Utility::getCurrentUserID();
54
        }
55
        $critere = new \Criteria('cmd_uid', (int)$uid, '=');
56
57
        return $this->getCount($critere) > 0;
58
    }
59
60
    /**
61
     * Indicates if a product has already been purchased by a user
62
     *
63
     * @param int $uid       User ID
64
     * @param int $productId Product ID
65
     * @return bool Indicates whether this is the case or not
66
     */
67
    public function productAlreadyBought($uid = 0, $productId = 0)
68
    {
69
        if (0 == $uid) {
70
            $uid = Oledrion\Utility::getCurrentUserID();
71
        }
72
        $sql    = 'SELECT Count(*) AS cpt FROM ' . $this->db->prefix('oledrion_caddy') . ' c, ' . $this->db->prefix('oledrion_commands') . ' f WHERE c.caddy_product_id = ' . (int)$productId . ' AND c.caddy_cmd_id = f.cmd_id AND f.cmd_uid = ' . (int)$uid;
73
        $result = $this->db->query($sql);
74
        if (!$result) {
75
            return false;
76
        }
77
        list($count) = $this->db->fetchRow($result);
78
79
        return $count > 0;
80
    }
81
82
    /**
83
     * Inventory update for each product composing the order
84
     *
85
     * @param  Commands $order La commande à traiter
86
     * @return bool
87
     */
88
    public function updateStocks($order)
89
    {
90
        global $caddyHandler, $productsHandler, $persistentCartHandler;
91
        $orderId = $order->getVar('cmd_id');
92
        // Recherche de tous les produits du caddy
93
        $caddy  = $caddyHandler->getCaddyFromCommand($orderId);
94
        $tblTmp = $tblProducts = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $tblProducts is dead and can be removed.
Loading history...
95
        foreach ($caddy as $item) {
96
            $tblTmp[] = $item->getVar('caddy_product_id');
97
        }
98
        // Chargement de tous les produits
99
        $critere     = new \Criteria('product_id', '(' . implode(',', $tblTmp) . ')', 'IN');
100
        $tblProducts = $productsHandler->getObjects($critere, true);
101
        // Boucle sur le caddy pour mettre à jour les quantités
102
        foreach ($caddy as $item) {
103
            if (isset($tblProducts[$item->getVar('caddy_product_id')])) {
104
                $product = $tblProducts[$item->getVar('caddy_product_id')];
105
                $productsHandler->decreaseStock($product, $item->getVar('caddy_qte'));
106
                $productsHandler->verifyLowStock($product); // Vérification du stock d'alerte
107
                $persistentCartHandler->deleteUserProduct($item->getVar('caddy_product_id'), $order->getVar('cmd_uid'));
108
            }
109
        }
110
111
        return true;
112
    }
113
114
    /**
115
     * Returns the list of download URLs linked to a command
116
     *
117
     * @param  Commands $order La commande en question
118
     * @return array                    Les URL
119
     */
120
    public function getOrderUrls(Commands $order)
121
    {
122
        global $caddyHandler, $productsHandler;
123
        $retval = $carts = $productsList = $products = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $products is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $carts is dead and can be removed.
Loading history...
124
        // Recherche des produits du caddy associés à cette commande
125
        $carts = $caddyHandler->getObjects(new \Criteria('caddy_cmd_id', $order->getVar('cmd_id'), '='));
0 ignored issues
show
Bug introduced by
It seems like $order->getVar('cmd_id') can also be of type array and array; however, parameter $value of Criteria::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

125
        $carts = $caddyHandler->getObjects(new \Criteria('caddy_cmd_id', /** @scrutinizer ignore-type */ $order->getVar('cmd_id'), '='));
Loading history...
126
        foreach ($carts as $item) {
127
            $productsList[] = $item->getVar('caddy_product_id');
128
        }
129
        if (count($productsList) > 0) {
130
            $products = $productsHandler->getObjects(new \Criteria('product_id', '(' . implode(',', $productsList) . ')', 'IN'), true);
131
            if (count($products) > 0) {
132
                foreach ($carts as $item) {
133
                    $produit = null;
134
                    if (isset($products[$item->getVar('caddy_product_id')])) {
135
                        $produit = $products[$item->getVar('caddy_product_id')];
136
                        if ('' !== xoops_trim($produit->getVar('product_download_url'))) {
137
                            $retval[] = OLEDRION_URL . 'download.php?download_id=' . $item->getVar('caddy_pass');
138
                        }
139
                    }
140
                }
141
            }
142
        }
143
144
        return $retval;
145
    }
146
147
    /**
148
     * Sending the mail to inform the customer and the store that an order is validated
149
     *
150
     * @param Commands $order   La commande en question
151
     * @param string   $comment Optionel, un commentaire pour le webmaster
152
     */
153
    public function notifyOrderValidated(Commands $order, $comment = '')
154
    {
155
        global $xoopsConfig;
156
        $msg                       = [];
157
        $Urls                      = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $Urls is dead and can be removed.
Loading history...
158
        $Urls                      = $this->getOrderUrls($order); // On récupère les URL des fichiers à télécharger
159
        $msg['ADDITIONAL_CONTENT'] = '';
160
        $msg['NUM_COMMANDE']       = $order->getVar('cmd_id');
161
        $msg['COMMENT']            = $comment;
162
        if (count($Urls) > 0) {
163
            $msg['ADDITIONAL_CONTENT'] = _OLEDRION_YOU_CAN_DOWNLOAD . "\n" . implode("\n", $Urls);
164
        }
165
        Oledrion\Utility::sendEmailFromTpl('command_shop_verified.tpl', Oledrion\Utility::getEmailsFromGroup(Oledrion\Utility::getModuleOption('grp_sold')), _OLEDRION_GATEWAY_VALIDATED, $msg);
166
        Oledrion\Utility::sendEmailFromTpl('command_client_verified.tpl', $order->getVar('cmd_email'), sprintf(_OLEDRION_GATEWAY_VALIDATED, $xoopsConfig['sitename']), $msg);
0 ignored issues
show
Bug introduced by
It seems like $order->getVar('cmd_email') can also be of type boolean and string; however, parameter $recipients of XoopsModules\Oledrion\Utility::sendEmailFromTpl() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

166
        Oledrion\Utility::sendEmailFromTpl('command_client_verified.tpl', /** @scrutinizer ignore-type */ $order->getVar('cmd_email'), sprintf(_OLEDRION_GATEWAY_VALIDATED, $xoopsConfig['sitename']), $msg);
Loading history...
167
    }
168
169
    /**
170
     * Validation of an order and inventory update
171
     *
172
     * @param  Commands $order   La commande à traiter
173
     * @param  string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
174
     * @return bool                     Indique si la validation de la commande s'est bien faite ou pas
175
     */
176
    public function validateOrder(Commands $order, $comment = '')
177
    {
178
        $retval = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $retval is dead and can be removed.
Loading history...
179
        $order->setVar('cmd_state', Constants::OLEDRION_STATE_VALIDATED);
180
        $order->setVar('cmd_comment', $comment);
181
        $retval = $this->insert($order, true);
182
        if ($retval) {
183
            $this->updateStocks($order);
184
            // B.R. Validation emails redundant since order emails now sent @gateway (paypal) validation
185
            // B.R. $this->notifyOrderValidated($order, $comment);
186
        }
187
188
        return $retval;
189
    }
190
191
    /**
192
     * pack an order and update inventory
193
     *
194
     * @param  Commands $order   La commande à traiter
195
     * @param  string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
196
     * @return bool                     Indique si la validation de la commande s'est bien faite ou pas
197
     */
198
    public function packOrder(Commands $order, $comment = '')
199
    {
200
        $retval = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $retval is dead and can be removed.
Loading history...
201
        $order->setVar('cmd_state', Constants::OLEDRION_STATE_PACKED);
202
        $order->setVar('cmd_comment', $comment);
203
        $retval = $this->insert($order, true);
204
205
        return $retval;
206
    }
207
208
    /**
209
     * submit an order and inventory update
210
     *
211
     * @param  Commands $order   La commande à traiter
212
     * @param  string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
213
     * @return bool                     Indique si la validation de la commande s'est bien faite ou pas
214
     */
215
    public function submitOrder(Commands $order, $comment = '')
216
    {
217
        $retval = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $retval is dead and can be removed.
Loading history...
218
        $order->setVar('cmd_state', Constants::OLEDRION_STATE_SUBMITED);
219
        $order->setVar('cmd_comment', $comment);
220
        $retval = $this->insert($order, true);
221
222
        return $retval;
223
    }
224
225
    /**
226
     * delivery an order and inventory update
227
     *
228
     * @param  Commands $order   La commande à traiter
229
     * @param  string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
230
     * @return bool                     Indique si la validation de la commande s'est bien faite ou pas
231
     */
232
    public function deliveryOrder(Commands $order, $comment = '')
233
    {
234
        $retval = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $retval is dead and can be removed.
Loading history...
235
        $order->setVar('cmd_state', Constants::OLEDRION_STATE_DELIVERED);
236
        $order->setVar('cmd_comment', $comment);
237
        $retval = $this->insert($order, true);
238
239
        return $retval;
240
    }
241
242
    /**
243
     * Inform the site owner that an order is fraudulent
244
     *
245
     * @param Commands $order   La commande en question
246
     * @param string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
247
     */
248
    public function notifyOrderFraudulent(Commands $order, $comment = '')
249
    {
250
        $msg                 = [];
251
        $msg['NUM_COMMANDE'] = $order->getVar('cmd_id');
252
        $msg['COMMENT']      = $comment;
253
        Oledrion\Utility::sendEmailFromTpl('command_shop_fraud.tpl', Oledrion\Utility::getEmailsFromGroup(Oledrion\Utility::getModuleOption('grp_sold')), _OLEDRION_GATEWAY_FRAUD, $msg);
254
    }
255
256
    /**
257
     * Apply fraudulent order status to an order
258
     *
259
     * @param object|Commands $order   La commande à traiter
260
     * @param string          $comment Optionel, un commentaire pour le mail envoyé au webmaster
261
     */
262
    public function setFraudulentOrder(Commands $order, $comment = '')
263
    {
264
        $order->setVar('cmd_state', Constants::OLEDRION_STATE_FRAUD);
265
        $order->setVar('cmd_comment', $comment);
266
        $this->insert($order, true);
267
        $this->notifyOrderFraudulent($order, $comment);
268
    }
269
270
    /**
271
     * Inform the site owner that an order is pending
272
     *
273
     * @param Commands $order   La commande en question
274
     * @param string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
275
     */
276
    public function notifyOrderPending(Commands $order, $comment = '')
277
    {
278
        $msg                 = [];
279
        $msg['NUM_COMMANDE'] = $order->getVar('cmd_id');
280
        $msg['COMMENT']      = $comment;
281
        Oledrion\Utility::sendEmailFromTpl('command_shop_pending.tpl', Oledrion\Utility::getEmailsFromGroup(Oledrion\Utility::getModuleOption('grp_sold')), _OLEDRION_GATEWAY_PENDING, $msg);
282
    }
283
284
    /**
285
     * Apply pending order status to an order
286
     *
287
     * @param Commands $order   La commande à traiter
288
     * @param string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
289
     */
290
    public function setOrderPending(Commands $order, $comment = '')
291
    {
292
        $order->setVar('cmd_state', Constants::OLEDRION_STATE_PENDING); // En attente
293
        $order->setVar('cmd_comment', $comment);
294
        $this->insert($order, true);
295
        $this->notifyOrderPending($order, $comment);
296
    }
297
298
    /**
299
     * Inform the site owner that an order has failed (payment)
300
     *
301
     * @param Commands $order   La commande en question
302
     * @param string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
303
     */
304
    public function notifyOrderFailed(Commands $order, $comment = '')
305
    {
306
        $msg                 = [];
307
        $msg['NUM_COMMANDE'] = $order->getVar('cmd_id');
308
        $msg['COMMENT']      = $comment;
309
        Oledrion\Utility::sendEmailFromTpl('command_shop_failed.tpl', Oledrion\Utility::getEmailsFromGroup(Oledrion\Utility::getModuleOption('grp_sold')), _OLEDRION_GATEWAY_FAILED, $msg);
310
    }
311
312
    /**
313
     * Applies failed order status to an order
314
     *
315
     * @param Commands $order   La commande à traiter
316
     * @param string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
317
     */
318
    public function setOrderFailed(Commands $order, $comment = '')
319
    {
320
        $order->setVar('cmd_state', Constants::OLEDRION_STATE_FAILED); // Echec
321
        $order->setVar('cmd_comment', $comment);
322
        $this->insert($order, true);
323
        $this->notifyOrderFailed($order, $comment);
324
    }
325
326
    /**
327
     * Inform the site owner that an order has failed (payment)
328
     *
329
     * @param Commands $order   La commande en question
330
     * @param string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
331
     */
332
    public function notifyOrderCanceled(Commands $order, $comment = '')
333
    {
334
        $msg                 = [];
335
        $msg['NUM_COMMANDE'] = $order->getVar('cmd_id');
336
        $msg['COMMENT']      = $comment;
337
        Oledrion\Utility::sendEmailFromTpl('command_shop_cancel.tpl', Oledrion\Utility::getEmailsFromGroup(Oledrion\Utility::getModuleOption('grp_sold')), _OLEDRION_ORDER_CANCELED, $msg);
338
        Oledrion\Utility::sendEmailFromTpl('command_client_cancel.tpl', $order->getVar('cmd_email'), _OLEDRION_ORDER_CANCELED, $msg);
0 ignored issues
show
Bug introduced by
It seems like $order->getVar('cmd_email') can also be of type boolean and string; however, parameter $recipients of XoopsModules\Oledrion\Utility::sendEmailFromTpl() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

338
        Oledrion\Utility::sendEmailFromTpl('command_client_cancel.tpl', /** @scrutinizer ignore-type */ $order->getVar('cmd_email'), _OLEDRION_ORDER_CANCELED, $msg);
Loading history...
339
    }
340
341
    /**
342
     * Apply canceled order status to an order
343
     *
344
     * @param Commands $order   La commande à traiter
345
     * @param string   $comment Optionel, un commentaire pour le mail envoyé au webmaster
346
     */
347
    public function setOrderCanceled(Commands $order, $comment = '')
348
    {
349
        $order->setVar('cmd_state', Constants::OLEDRION_STATE_CANCELED); // Annulée
350
        $order->setVar('cmd_comment', $comment);
351
        $this->insert($order, true);
352
        $this->notifyOrderCanceled($order, $comment);
353
    }
354
355
    /**
356
     * Returns an order from its cancellation password
357
     *
358
     * @param  string $cmd_cancel Le mot de passe d'annulation
359
     * @return mixed  Soit un objet soit null
360
     */
361
    public function getOrderFromCancelPassword($cmd_cancel)
362
    {
363
        $critere = new \Criteria('cmd_cancel', $cmd_cancel, '=');
364
        if ($this->getCount($critere) > 0) {
365
            $tblCmd = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $tblCmd is dead and can be removed.
Loading history...
366
            $tblCmd = $this->getObjects($critere);
367
            if (count($tblCmd) > 0) {
368
                return $tblCmd[0];
369
            }
370
        }
371
372
        return null;
373
    }
374
375
    /**
376
     * Returns the last command of a user (if it exists)
377
     *
378
     * @param int $uid Identifiant de la commande
379
     * @return null|string
380
     */
381
    public function getLastUserOrder($uid)
382
    {
383
        $order    = null;
384
        $orders   = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $orders is dead and can be removed.
Loading history...
385
        $criteria = new \CriteriaCompo();
386
        $criteria->add(new \Criteria('cmd_uid', $uid));
387
        $criteria->add(new \Criteria('cmd_status', 2));
388
        $criteria->setSort('cmd_date');
389
        $criteria->setOrder('DESC');
390
        $criteria->setLimit(1);
391
        $orders = $this->getObjects($criteria, false);
392
        if (count($orders) > 0) {
393
            $order = $orders[0];
394
        }
395
396
        return $order;
397
    }
398
399
    /**
400
     * Deletes an order and everything related to it
401
     *
402
     * @param  Commands $order
403
     * @return bool
404
     */
405
    public function removeOrder(Commands $order)
406
    {
407
        /** @var \XoopsDatabase $db */
408
        $db = \XoopsDatabaseFactory::getDatabaseConnection();
409
        //        $handlers = HandlerManager::getInstance();
410
        $cmd_id = $order->getVar('cmd_id');
411
        $res    = $this->delete($order);
412
        // Suppression des objets associés
413
        // 1) Ses propres caddies
414
        $caddyHandler = new Oledrion\CaddyHandler($db);
415
        $caddyHandler->removeCartsFromOrderId($cmd_id);
416
        // 2) Les caddies des attributs
417
        $caddyAttributesHandler = new Oledrion\CaddyAttributesHandler($db);
418
        $caddyAttributesHandler->removeCartsFromOrderId($cmd_id);
419
420
        return $res;
421
    }
422
}
423