-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathColissimoHomeDelivery.php
373 lines (312 loc) · 12.8 KB
/
ColissimoHomeDelivery.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
<?php
/*
* This file is part of the Thelia package.
* http://www.thelia.net
*
* (c) OpenStudio <info@thelia.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
namespace ColissimoHomeDelivery;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshippingQuery;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshippingQuery;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlicesQuery;
use PDO;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Propel;
use Symfony\Component\DependencyInjection\Loader\Configurator\ServicesConfigurator;
use Symfony\Component\Finder\Finder;
use Thelia\Install\Database;
use Thelia\Model\Country;
use Thelia\Model\CountryArea;
use Thelia\Model\Message;
use Thelia\Model\MessageQuery;
use Thelia\Model\ModuleQuery;
use Thelia\Model\State;
use Thelia\Module\AbstractDeliveryModuleWithState;
use Thelia\Module\Exception\DeliveryException;
class ColissimoHomeDelivery extends AbstractDeliveryModuleWithState
{
/** @var string */
const DOMAIN_NAME = 'colissimohomedelivery';
// The shipping confirmation message identifier
const CONFIRMATION_MESSAGE_NAME = 'order_confirmation_colissimo_home_delivery';
// Configuration parameters
const COLISSIMO_USERNAME = 'colissimo_home_delivery_username';
const COLISSIMO_PASSWORD = 'colissimo_home_delivery_password';
const AFFRANCHISSEMENT_ENDPOINT_URL = 'affranchissement_endpoint_url';
const ACTIVATE_DETAILED_DEBUG = 'activate_detailed_debug';
const COLISSIMO_TAX_RULE_ID = 'colissimo_home_delivery_tax_rule_id';
/**
* @throws \Propel\Runtime\Exception\PropelException
*/
public function postActivation(ConnectionInterface $con = null): void
{
// Create table if required.
if (!self::getConfigValue('is_initialized', false)) {
$database = new Database($con->getWrappedConnection());
$database->insertSql(null, [__DIR__.'/Config/thelia.sql']);
self::setConfigValue('is_initialized', true);
}
if (!ColissimoHomeDeliveryFreeshippingQuery::create()->findOne()) {
(new ColissimoHomeDeliveryFreeshipping())
->setActive(0)
->save();
}
if (!self::getConfigValue(self::AFFRANCHISSEMENT_ENDPOINT_URL)) {
self::setConfigValue(self::AFFRANCHISSEMENT_ENDPOINT_URL, 'https://ws.colissimo.fr/sls-ws/SlsServiceWS?wsdl');
}
if (!self::getConfigValue(self::COLISSIMO_USERNAME)) {
self::setConfigValue(self::COLISSIMO_USERNAME, ' ');
}
if (!self::getConfigValue(self::COLISSIMO_PASSWORD)) {
self::setConfigValue(self::COLISSIMO_PASSWORD, ' ');
}
if (!self::getConfigValue(self::ACTIVATE_DETAILED_DEBUG)) {
self::setConfigValue(self::ACTIVATE_DETAILED_DEBUG, '0');
}
if (!self::getConfigValue(self::COLISSIMO_TAX_RULE_ID)) {
self::setConfigValue(self::COLISSIMO_TAX_RULE_ID, null);
}
if (null === MessageQuery::create()->findOneByName(self::CONFIRMATION_MESSAGE_NAME)) {
$message = new Message();
$message
->setName(self::CONFIRMATION_MESSAGE_NAME)
->setHtmlLayoutFileName('order_shipped.html')
->setTextLayoutFileName('order_shipped.txt')
->setLocale('en_US')
->setTitle('Order send confirmation')
->setSubject('Order send confirmation')
->setLocale('fr_FR')
->setTitle('Confirmation d\'envoi de commande')
->setSubject('Confirmation d\'envoi de commande')
->save()
;
}
}
/**
* {@inheritDoc}
*/
public function update($currentVersion, $newVersion, ConnectionInterface $con = null): void
{
$finder = (new Finder())
->files()
->name('#.*?\.sql#')
->sortByName()
->in(__DIR__.DS.'Config'.DS.'update');
$database = new Database($con);
/** @var \Symfony\Component\Finder\SplFileInfo $updateSQLFile */
foreach ($finder as $updateSQLFile) {
if (version_compare($currentVersion, str_replace('.sql', '', $updateSQLFile->getFilename()), '<')) {
$database->insertSql(
null,
[
$updateSQLFile->getPathname(),
]
);
}
}
}
/**
* Returns ids of area containing this country and covered by this module.
*
* @return array Area ids
*/
public function getAllAreasForCountry(Country $country)
{
$areaArray = [];
$sql = 'SELECT ca.area_id as area_id FROM country_area ca
INNER JOIN area_delivery_module adm ON (ca.area_id = adm.area_id AND adm.delivery_module_id = :p0)
WHERE ca.country_id = :p1';
$con = Propel::getConnection();
$stmt = $con->prepare($sql);
$stmt->bindValue(':p0', $this->getModuleModel()->getId(), PDO::PARAM_INT);
$stmt->bindValue(':p1', $country->getId(), PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$areaArray[] = $row['area_id'];
}
return $areaArray;
}
/**
* @param $areaId
* @param $weight
* @param $cartAmount
* @param $deliverModeCode
*
* @return mixed
*
* @throws DeliveryException
*/
public static function getPostageAmount($areaId, $weight, $cartAmount = 0)
{
/* Check if freeshipping is activated */
try {
$freeshipping = ColissimoHomeDeliveryFreeshippingQuery::create()
->findPk(1)
->getActive()
;
} catch (\Exception $exception) {
$freeshipping = false;
}
/* Get the total cart price needed to have a free shipping for all areas, if it exists */
try {
$freeshippingFrom = ColissimoHomeDeliveryFreeshippingQuery::create()
->findPk(1)
->getFreeshippingFrom()
;
} catch (\Exception $exception) {
$freeshippingFrom = false;
}
/** Set the initial postage price as 0 */
$postage = 0;
/* If free shipping is enabled, skip and return 0 */
if (!$freeshipping) {
/* If a min price for general freeshipping is defined and the cart reach this amount, return a postage of 0 */
if (null !== $freeshippingFrom && $freeshippingFrom <= $cartAmount) {
return 0;
}
$areaFreeshipping = ColissimoHomeDeliveryAreaFreeshippingQuery::create()
->filterByAreaId($areaId)
->findOne()
;
if ($areaFreeshipping) {
$areaFreeshipping = $areaFreeshipping->getCartAmount();
}
/* If the cart price is superior to the minimum price for free shipping in the area of the order,
* return the postage as free.
*/
if (null !== $areaFreeshipping && $areaFreeshipping <= $cartAmount) {
return 0;
}
/** Search the list of prices and order it in ascending order */
$areaPrices = ColissimoHomeDeliveryPriceSlicesQuery::create()
->filterByAreaId($areaId)
->filterByMaxWeight($weight, Criteria::GREATER_EQUAL)
->_or()
->filterByMaxWeight(null)
->filterByMaxPrice($cartAmount, Criteria::GREATER_EQUAL)
->_or()
->filterByMaxPrice(null)
->orderByMaxWeight()
->orderByMaxPrice()
;
/** Find the correct postage price for the cart weight and price according to the area and delivery mode in $areaPrices*/
$firstPrice = $areaPrices->find()
->getFirst();
if (null === $firstPrice) {
return null;
//throw new DeliveryException("Colissimo delivery unavailable for your cart weight or delivery country");
}
$postage = $firstPrice->getShipping();
}
return $postage;
}
public function getMinPostage($country, $cartWeight, $cartAmount, $lang)
{
$minPostage = null;
$areaIdArray = $this->getAllAreasForCountry($country);
if (empty($areaIdArray)) {
throw new DeliveryException('Your delivery country is not covered by Colissimo.');
}
foreach ($areaIdArray as $areaId) {
try {
$postage = self::getPostageAmount($areaId, $cartWeight, $cartAmount);
if (null === $postage) {
continue;
}
if ($minPostage === null || $postage < $minPostage) {
$minPostage = $postage;
if ($minPostage == 0) {
break;
}
}
} catch (\Exception $ex) {
throw new DeliveryException($ex->getMessage()); //todo make a better catch
}
}
if (null === $minPostage) {
throw new DeliveryException('Colissimo delivery unavailable for your cart weight or delivery country');
}
return $this->buildOrderPostage($minPostage, $country, $lang, self::getConfigValue(self::COLISSIMO_TAX_RULE_ID));
}
/**
* Calculate and return delivery price.
*
* @return mixed
*
* @throws DeliveryException
*/
public function getPostage(Country $country, State $state = null)
{
$request = $this->getRequest();
$orderPostage = 0;
$freeshippingIsActive = ColissimoHomeDeliveryFreeshippingQuery::create()->findOneById(1)->getActive();
if (false === $freeshippingIsActive) {
$cartWeight = $request->getSession()->getSessionCart($this->getDispatcher())->getWeight();
$cartAmount = $request->getSession()->getSessionCart($this->getDispatcher())->getTaxedAmount($country, false);
if (null === $orderPostage = $this->getMinPostage($country, $cartWeight, $cartAmount, $request->getSession()->getLang()->getLocale())) {
throw new DeliveryException('Colissimo delivery unavailable for your cart weight or delivery country');
}
}
return $orderPostage;
}
/**
* This method is called by the Delivery loop, to check if the current module has to be displayed to the customer.
* Override it to implements your delivery rules/.
*
* If you return true, the delivery method will de displayed to the customer
* If you return false, the delivery method will not be displayed
*
* @param Country $country the country to deliver to
*
* @return bool
*/
public function isValidDelivery(Country $country, State $state = null)
{
if (empty($this->getAllAreasForCountry($country))) {
return false;
}
$countryAreas = $country->getCountryAreas();
$areasArray = [];
/** @var CountryArea $countryArea */
foreach ($countryAreas as $countryArea) {
$areasArray[] = $countryArea->getAreaId();
}
$prices = ColissimoHomeDeliveryPriceSlicesQuery::create()
->filterByAreaId($areasArray)
->findOne();
$freeShipping = ColissimoHomeDeliveryFreeshippingQuery::create()
->filterByActive(1)
->findOne()
;
/* Check if Colissimo delivers the asked area*/
if (null !== $prices || null !== $freeShipping) {
return true;
}
return false;
}
public static function getModCode()
{
return ModuleQuery::create()->findOneByCode('ColissimoHomeDelivery')->getId();
}
public function getDeliveryMode()
{
return 'delivery';
}
public static function configureServices(ServicesConfigurator $servicesConfigurator): void
{
$servicesConfigurator->load(self::getModuleCode().'\\', __DIR__)
->exclude([THELIA_MODULE_DIR . ucfirst(self::getModuleCode()). "/I18n/*"])
->autowire(true)
->autoconfigure(true);
}
}