Passed
Pull Request — master (#43)
by Raúl
11:17
created

PagantisPaymentModuleFrontController::getTaxId()   B

Complexity

Conditions 9
Paths 5

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 10
c 1
b 0
f 0
nc 5
nop 3
dl 0
loc 12
rs 8.0555
1
<?php
2
/**
3
 * This file is part of the official Pagantis module for PrestaShop.
4
 *
5
 * @author    Pagantis <[email protected]>
6
 * @copyright 2019 Pagantis
7
 * @license   proprietary
8
 */
9
10
require_once('AbstractController.php');
11
12
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
13
use Pagantis\ModuleUtils\Exception\UnknownException;
14
15
/**
16
 * Class PagantisRedirectModuleFrontController
17
 */
18
class PagantisPaymentModuleFrontController extends AbstractController
19
{
20
    /**
21
     * @param $customer
22
     * @param $exception
23
     */
24
    protected function addLog($customer, $exception)
25
    {
26
        if (_PS_VERSION_ < 1.6) {
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
27
            Logger::addLog(
0 ignored issues
show
Bug introduced by
The type Logger was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
                'Pagantis Exception For user ' .
29
                $customer->email .
30
                ' : ' .
31
                $exception->getMessage(),
32
                3,
33
                $exception->getCode(),
34
                null,
35
                null,
36
                true
37
            );
38
        } else {
39
            PrestaShopLogger::addLog(
0 ignored issues
show
Bug introduced by
The type PrestaShopLogger was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
40
                'Pagantis Exception For user ' .
41
                $customer->email .
42
                ' : ' .
43
                $exception->getMessage(),
44
                3,
45
                $exception->getCode(),
46
                null,
47
                null,
48
                true
49
            );
50
        }
51
    }
52
53
    /**
54
     * Process Post Request
55
     *
56
     * @throws \Exception
57
     */
58
    public function postProcess()
59
    {
60
        $lang = Language::getLanguage($this->context->language->id);
0 ignored issues
show
Bug introduced by
The type Language was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
61
        $langArray = explode("-", $lang['language_code']);
62
        $this->language = strtoupper($langArray[1]);
0 ignored issues
show
Bug Best Practice introduced by
The property language does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
63
64
        /** @var Cart $cart */
65
        $cart = $this->context->cart;
66
67
        if (!$cart->id) {
68
            Tools::redirect('index.php?controller=order');
0 ignored issues
show
Bug introduced by
The type Tools was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
69
        }
70
71
        /** @var Customer $customer */
72
        $customer = $this->context->customer;
73
        $query = array(
74
            'id_cart' => $cart->id,
75
            'key' => $cart->secure_key,
76
        );
77
78
        $koUrl = $this->context->link->getPageLink(
79
            'order',
80
            null,
81
            null,
82
            array('step'=>3)
83
        );
84
        $iframe = Pagantis::getExtraConfig('PAGANTIS_FORM_DISPLAY_TYPE');
85
        $cancelUrl = (Pagantis::getExtraConfig('PAGANTIS_URL_KO') !== '') ?
86
            Pagantis::getExtraConfig('PAGANTIS_URL_KO') : $koUrl;
87
        $pagantisPublicKey = Configuration::get('pagantis_public_key');
0 ignored issues
show
Bug introduced by
The type Configuration was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
88
        $pagantisPrivateKey = Configuration::get('pagantis_private_key');
89
        $okUrl = _PS_BASE_URL_.__PS_BASE_URI__
0 ignored issues
show
Bug introduced by
The constant _PS_BASE_URL_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant __PS_BASE_URI__ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
90
                 .'index.php?canonical=true&fc=module&module=pagantis&controller=notify&'
91
                 .http_build_query($query)
92
        ;
93
94
        $shippingAddress = new Address($cart->id_address_delivery);
0 ignored issues
show
Bug introduced by
The type Address was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
95
        $billingAddress = new Address($cart->id_address_invoice);
96
        $curlInfo = curl_version();
97
        $curlVersion = $curlInfo['version'];
98
        $metadata = array(
99
            'ps' => _PS_VERSION_,
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
100
            'pagantis' => $this->module->version,
101
            'php' => phpversion(),
102
            'curl' => $curlVersion,
103
        );
104
105
        try {
106
            $userAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
107
            $userAddress
108
                ->setZipCode($shippingAddress->postcode)
109
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
110
                ->setCountryCode('ES')
111
                ->setCity($shippingAddress->city)
112
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
113
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
114
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
115
            ;
116
117
            $orderShippingAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
118
            $orderShippingAddress
119
                ->setZipCode($shippingAddress->postcode)
120
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
121
                ->setCountryCode('ES')
122
                ->setCity($shippingAddress->city)
123
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
124
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
125
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
126
                ->setFixPhone($shippingAddress->phone)
127
                ->setMobilePhone($shippingAddress->phone_mobile)
128
            ;
129
130
            $orderBillingAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
131
            $orderBillingAddress
132
                ->setZipCode($billingAddress->postcode)
133
                ->setFullName($billingAddress->firstname . ' ' . $billingAddress->lastname)
134
                ->setCountryCode('ES')
135
                ->setCity($billingAddress->city)
136
                ->setAddress($billingAddress->address1 . ' ' . $billingAddress->address2)
137
                ->setTaxId($this->getTaxId($customer, $billingAddress, $shippingAddress))
138
                ->setNationalId($this->getNationalId($customer, $billingAddress, $shippingAddress))
139
                ->setFixPhone($billingAddress->phone)
140
                ->setMobilePhone($billingAddress->phone_mobile)
141
            ;
142
143
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
144
            $orderUser
145
                ->setAddress($userAddress)
146
                ->setFullName($orderShippingAddress->getFullName())
147
                ->setBillingAddress($orderBillingAddress)
148
                ->setEmail($this->context->cookie->logged ? $this->context->cookie->email : $customer->email)
149
                ->setFixPhone($shippingAddress->phone)
150
                ->setMobilePhone($shippingAddress->phone_mobile)
151
                ->setShippingAddress($orderShippingAddress)
152
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
153
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
154
            ;
155
156
            if ($customer->birthday!='0000-00-00') {
157
                $orderUser->setDateOfBirth($customer->birthday);
158
            }
159
160
            $orders = Order::getCustomerOrders($customer->id);
0 ignored issues
show
Bug introduced by
The type Order was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
161
            /** @var \PrestaShop\PrestaShop\Adapter\Entity\Order $order */
162
            foreach ($orders as $order) {
163
                if ($order['valid']) {
164
                    $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
165
                    $orderHistory
166
                        ->setAmount((string) floor(100 * $order['total_paid']))
167
                        ->setDate(new \DateTime($order['date_add']))
0 ignored issues
show
Bug introduced by
new DateTime($order['date_add']) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

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

167
                        ->setDate(/** @scrutinizer ignore-type */ new \DateTime($order['date_add']))
Loading history...
168
                    ;
169
                    $orderUser->addOrderHistory($orderHistory);
170
                }
171
            }
172
173
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
174
            $details->setShippingCost((string) floor(100 * $cart->getTotalShippingCost()));
175
            $items = $cart->getProducts();
176
            foreach ($items as $key => $item) {
177
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
178
                $product
179
                    ->setAmount((string) floor(100 * $item['price_wt']))
180
                    ->setQuantity($item['quantity'])
181
                    ->setDescription($item['name']);
182
                $details->addProduct($product);
183
            }
184
185
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
186
            $totalAmount = (string) floor(100 * $cart->getOrderTotal(true));
187
            $orderShoppingCart
188
                ->setDetails($details)
189
                ->setOrderReference($cart->id)
190
                ->setPromotedAmount(0)
191
                ->setTotalAmount($totalAmount)
192
            ;
193
194
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
195
            $orderConfigurationUrls
196
                ->setCancel($cancelUrl)
197
                ->setKo($cancelUrl)
198
                ->setAuthorizedNotificationCallback($okUrl)
199
                ->setRejectedNotificationCallback($okUrl)
200
                ->setOk($okUrl)
201
            ;
202
203
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
204
            $orderChannel
205
                ->setAssistedSale(false)
206
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE)
207
            ;
208
209
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
210
            $orderConfiguration
211
                ->setChannel($orderChannel)
212
                ->setUrls($orderConfigurationUrls)
213
                ->setPurchaseCountry($this->language)
214
            ;
215
216
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
217
            foreach ($metadata as $key => $metadatum) {
218
                $metadataOrder
219
                    ->addMetadata($key, $metadatum);
220
            }
221
222
            $order = new \Pagantis\OrdersApiClient\Model\Order();
223
            $order
224
                ->setConfiguration($orderConfiguration)
225
                ->setMetadata($metadataOrder)
226
                ->setShoppingCart($orderShoppingCart)
227
                ->setUser($orderUser)
228
            ;
229
        } catch (\Exception $exception) {
230
            $this->saveLog(array(), $exception);
231
            Tools::redirect($cancelUrl);
232
        }
233
234
        $url ='';
235
        try {
236
            $orderClient = new \Pagantis\OrdersApiClient\Client(
237
                $pagantisPublicKey,
238
                $pagantisPrivateKey
239
            );
240
            $order = $orderClient->createOrder($order);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $order does not seem to be defined for all execution paths leading up to this point.
Loading history...
241
242
            if ($order instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$order is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
243
                $url = $order->getActionUrls()->getForm();
244
                $orderId = $order->getId();
245
                $sql = "INSERT INTO `" . _DB_PREFIX_ . "pagantis_order` (`id`, `order_id`)
0 ignored issues
show
Bug introduced by
The constant _DB_PREFIX_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
246
                     VALUES ('$cart->id','$orderId') 
247
                     ON DUPLICATE KEY UPDATE `order_id` = '$orderId'";
248
                $result = Db::getInstance()->execute($sql);
0 ignored issues
show
Bug introduced by
The type Db was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
249
                if (!$result) {
250
                    throw new UnknownException('Unable to save pagantis-order-id in database: '. $sql);
251
                }
252
            } else {
253
                throw new OrderNotFoundException();
254
            }
255
        } catch (\Exception $exception) {
256
            $this->saveLog(array(), $exception);
257
            Tools::redirect($cancelUrl);
258
        }
259
260
        if (!$iframe) {
261
            Tools::redirect($url);
262
        } else {
263
            $this->context->smarty->assign(array(
264
                'url'           => $url,
265
                'checkoutUrl'   => $cancelUrl,
266
            ));
267
268
            try {
269
                if (_PS_VERSION_ < 1.7) {
270
                    $this->setTemplate('payment-15.tpl');
271
                } else {
272
                    $this->setTemplate('module:pagantis/views/templates/front/payment-17.tpl');
273
                }
274
            } catch (\Exception $exception) {
275
                $this->saveLog(array(), $exception);
276
                Tools::redirect($url);
277
            }
278
        }
279
    }
280
281
    /**
282
     * @param null $customer
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $customer is correct as it would always require null to be passed?
Loading history...
283
     * @param null $addressOne
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $addressOne is correct as it would always require null to be passed?
Loading history...
284
     * @param null $addressTwo
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $addressTwo is correct as it would always require null to be passed?
Loading history...
285
     * @return mixed|null
286
     */
287
    private function getNationalId($customer = null, $addressOne = null, $addressTwo = null)
288
    {
289
        if ($customer !== null && isset($customer->national_id)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
290
            return $customer->national_id;
291
        } elseif ($addressOne !== null and isset($addressOne->national_id)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
292
            return $addressOne->national_id;
293
        } elseif ($addressOne !== null and isset($addressOne->dni)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
294
            return $addressOne->dni;
295
        } elseif ($addressTwo !== null and isset($addressTwo->national_id)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
296
            return $addressTwo->national_id;
297
        } elseif ($addressTwo !== null and isset($addressTwo->dni)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
298
            return $addressTwo->dni;
299
        } else {
300
            return null;
301
        }
302
    }
303
304
    /**
305
     * @param null $customer
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $customer is correct as it would always require null to be passed?
Loading history...
306
     * @param null $addressOne
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $addressOne is correct as it would always require null to be passed?
Loading history...
307
     * @param null $addressTwo
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $addressTwo is correct as it would always require null to be passed?
Loading history...
308
     * @return mixed|null
309
     */
310
    private function getTaxId($customer = null, $addressOne = null, $addressTwo = null)
311
    {
312
        if ($customer !== null && isset($customer->tax_id)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
313
            return $customer->tax_id;
314
        } elseif ($customer !== null && isset($customer->fiscalcode)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
315
            return $customer->fiscalcode;
316
        } elseif ($addressOne !== null and isset($addressOne->tax_id)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
317
            return $addressOne->tax_id;
318
        } elseif ($addressTwo !== null and isset($addressTwo->tax_id)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
319
            return $addressTwo->tax_id;
320
        } else {
321
            return null;
322
        }
323
    }
324
325
}
326