forked from sonata-project/ecommerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasketController.php
472 lines (375 loc) · 17.2 KB
/
BasketController.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
<?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\BasketBundle\Controller;
use Sonata\Component\Delivery\UndeliverableCountryException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DomCrawler\Form;
use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapper;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Intl\Intl;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Sonata\Component\Customer\AddressInterface;
/**
* This controller manages the Basket operation and most of the order process
*/
class BasketController extends Controller
{
/**
* Shows the basket
*
* @param Form $form
* @return \Symfony\Component\HttpFoundation\Response
*/
public function indexAction($form = null)
{
$form = $form ?: $this->createForm('sonata_basket_basket', clone $this->get('sonata.basket'), array(
'validation_groups' => array('elements')
));
// always validate the basket
if (!$form->isBound()) {
if ($violations = $this->get('validator')->validate($form)) {
$violationMapper = new ViolationMapper();
foreach ($violations as $violation) {
$violationMapper->mapViolation($violation, $form, true);
}
}
}
$this->get('session')->set('sonata_basket_delivery_redirect', 'sonata_basket_delivery_address');
$this->get('sonata.seo.page')->setTitle($this->get('translator')->trans('basket_index_title', array(), "SonataBasketBundle"));
return $this->render('SonataBasketBundle:Basket:index.html.twig', array(
'basket' => $this->get('sonata.basket'),
'form' => $form->createView(),
));
}
/**
* Update basket form rendering & saving
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function updateAction()
{
$form = $this->createForm('sonata_basket_basket', clone $this->get('sonata.basket'), array('validation_groups' => array('elements')));
$form->bind($this->get('request'));
if ($form->isValid()) {
$basket = $form->getData();
$basket->reset(false); // remove delivery and payment information
$basket->clean(); // clean the basket
// update the basket
$this->get('sonata.basket.factory')->save($basket);
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
return $this->forward('SonataBasketBundle:Basket:index', array(
'form' => $form
));
}
/**
* Adds a product to the basket
*
* @throws MethodNotAllowedException
* @throws NotFoundHttpException
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function addProductAction()
{
$request = $this->get('request');
$params = $request->get('add_basket');
if ($request->getMethod() != 'POST') {
throw new MethodNotAllowedException(array('POST'));
}
// retrieve the product
$product = $this->get('sonata.product.set.manager')->findOneBy(array('id' => $params['productId']));
if (!$product) {
throw new NotFoundHttpException(sprintf('Unable to find the product with id=%d', $params['productId']));
}
// retrieve the custom provider for the product type
$provider = $this->get('sonata.product.pool')->getProvider($product);
$formBuilder = $this->get('form.factory')->createNamedBuilder('add_basket', 'form', null, array('data_class' => $this->container->getParameter('sonata.basket.basket_element.class'), 'csrf_protection' => false));
$provider->defineAddBasketForm($product, $formBuilder);
// load and bind the form
$form = $formBuilder->getForm();
$form->bind($request);
// if the form is valid add the product to the basket
if ($form->isValid()) {
$basket = $this->get('sonata.basket');
$basketElement = $form->getData();
$quantity = $basketElement->getQuantity();
$currency = $this->get('sonata.basket')->getCurrency();
$price = $provider->calculatePrice($product, $currency, true, $quantity);
if ($basket->hasProduct($product)) {
$basketElement = $provider->basketMergeProduct($basket, $product, $basketElement);
} else {
$basketElement = $provider->basketAddProduct($basket, $product, $basketElement);
}
if ($request->isXmlHttpRequest() && $provider->getOption('product_add_modal')) {
return $this->render('SonataBasketBundle:Basket:add_product_popin.html.twig', array(
'basketElement' => $basketElement,
'locale' => $basket->getLocale(),
'product' => $product,
'price' => $price,
'currency' => $currency,
'quantity' => $quantity,
'provider' => $provider,
));
} else {
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
}
// an error occur, forward the request to the view
return $this->forward('SonataProductBundle:Product:view', array(
'productId' => $product,
'slug' => $product->getSlug(),
));
}
/**
* Resets (empties) the basket
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function resetAction()
{
$this->get('sonata.basket')->reset();
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
/**
* Displays a header preview of the basket
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function headerPreviewAction()
{
return $this->render('SonataBasketBundle:Basket:header_preview.html.twig', array(
'basket' => $this->get('sonata.basket')
));
}
/**
* Order process step 1: retrieve the customer associated with the logged in user if there's one
* or create an empty customer and put it in the basket
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function authenticationStepAction()
{
$customer = $this->get('sonata.customer.selector')->get();
$basket = $this->get('sonata.basket');
$basket->setCustomer($customer);
$this->get('sonata.basket.factory')->save($basket);
return new RedirectResponse($this->generateUrl('sonata_basket_delivery_address'));
}
/**
* Order process step 5: choose payment mode
*
* @throws HttpException
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function paymentStepAction()
{
$basket = clone $this->get('sonata.basket');
if ($basket->countBasketElements() == 0) {
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
$customer = $basket->getCustomer();
if (!$customer) {
throw new HttpException('Invalid customer');
}
if (null === $basket->getBillingAddress()) {
// If no payment address is specified, we assume it's the same as the delivery
$billingAddress = clone $basket->getDeliveryAddress();
$billingAddress->setType(AddressInterface::TYPE_BILLING);
$basket->setBillingAddress($billingAddress);
}
$form = $this->createForm('sonata_basket_payment', $basket, array(
'validation_groups' => array('delivery')
));
if ($this->get('request')->getMethod() == 'POST') {
$form->bind($this->get('request'));
if ($form->isValid()) {
// save the basket
$this->get('sonata.basket.factory')->save($basket);
return new RedirectResponse($this->generateUrl('sonata_basket_final'));
}
}
$this->get('sonata.seo.page')->setTitle($this->get('translator')->trans('basket_payment_title', array(), "SonataBasketBundle"));
return $this->render('SonataBasketBundle:Basket:payment_step.html.twig', array(
'basket' => $basket,
'form' => $form->createView(),
'customer' => $customer,
));
}
/**
* Order process step 3: choose delivery mode
*
* @throws NotFoundHttpException
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function deliveryStepAction()
{
$basket = clone $this->get('sonata.basket');
if ($basket->countBasketElements() == 0) {
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
$customer = $basket->getCustomer();
if (!$customer) {
throw new NotFoundHttpException('customer not found');
}
try {
$form = $this->createForm('sonata_basket_shipping', $basket, array(
'validation_groups' => array('delivery')
));
} catch (UndeliverableCountryException $ex) {
$countryName = Intl::getRegionBundle()->getCountryName($ex->getAddress()->getCountryCode());
$message = $this->get('translator')->trans('undeliverable_country', array('%country%' => $countryName), 'SonataBasketBundle');
$this->get('session')->getFlashBag()->add('error', $message);
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
$template = 'SonataBasketBundle:Basket:delivery_step.html.twig';
if ($this->get('request')->getMethod() == 'POST') {
$form->bind($this->get('request'));
if ($form->isValid()) {
// save the basket
$this->get('sonata.basket.factory')->save($form->getData());
return new RedirectResponse($this->generateUrl('sonata_basket_payment_address'));
}
}
$this->get('sonata.seo.page')->setTitle($this->get('translator')->trans('basket_delivery_title', array(), "SonataBasketBundle"));
return $this->render($template, array(
'basket' => $basket,
'form' => $form->createView(),
'customer' => $customer,
));
}
/**
* Order process step 2: choose an address from existing ones or create a new one
*
* @throws NotFoundHttpException
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function deliveryAddressStepAction()
{
$customer = $this->get('sonata.customer.selector')->get();
if (!$customer) {
throw new NotFoundHttpException('customer not found');
}
$basket = $this->get('sonata.basket');
$basket->setCustomer($customer);
if ($basket->countBasketElements() == 0) {
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
$addresses = $customer->getAddressesByType(AddressInterface::TYPE_DELIVERY);
// Show address creation / selection form
$form = $this->createForm('sonata_basket_address', null, array('addresses' => $addresses->toArray()));
$template = 'SonataBasketBundle:Basket:delivery_address_step.html.twig';
if ($this->get('request')->getMethod() == 'POST') {
$form->bind($this->get('request'));
if ($form->isValid()) {
if ($form->has('useSelected') && $form->get('useSelected')->isClicked()) {
$address = $form->get('addresses')->getData();
} else {
$address = $form->getData();
$address->setType(AddressInterface::TYPE_DELIVERY);
$customer->addAddress($address);
$this->get('sonata.customer.manager')->save($customer);
$this->get('session')->getFlashBag()->add('sonata_customer_success', 'address_add_success');
}
$basket->setCustomer($customer);
$basket->setDeliveryAddress($address);
// save the basket
$this->get('sonata.basket.factory')->save($basket);
return new RedirectResponse($this->generateUrl('sonata_basket_delivery'));
}
}
// Set URL to be redirected to once edited address
$this->get('session')->set('sonata_address_redirect', $this->generateUrl('sonata_basket_delivery_address'));
$this->get('sonata.seo.page')->setTitle($this->get('translator')->trans('basket_delivery_title', array(), "SonataBasketBundle"));
return $this->render($template, array(
'form' => $form->createView(),
'addresses' => $addresses
));
}
/**
* Order process step 4: choose a billing address from existing ones or create a new one
*
* @throws NotFoundHttpException
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function paymentAddressStepAction()
{
$basket = $this->get('sonata.basket');
if ($basket->countBasketElements() == 0) {
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
$customer = $basket->getCustomer();
if (!$customer) {
throw new NotFoundHttpException('customer not found');
}
$addresses = $customer->getAddressesByType(AddressInterface::TYPE_BILLING);
// Show address creation / selection form
$form = $this->createForm('sonata_basket_address', null, array('addresses' => $addresses->toArray()));
$template = 'SonataBasketBundle:Basket:payment_address_step.html.twig';
if ($this->get('request')->getMethod() == 'POST') {
$form->bind($this->get('request'));
if ($form->isValid()) {
if ($form->has('useSelected') && $form->get('useSelected')->isClicked()) {
$address = $form->get('addresses')->getData();
} else {
$address = $form->getData();
$address->setType(AddressInterface::TYPE_BILLING);
$customer->addAddress($address);
$this->get('sonata.customer.manager')->save($customer);
$this->get('session')->getFlashBag()->add('sonata_customer_success', 'address_add_success');
}
$basket->setCustomer($customer);
$basket->setBillingAddress($address);
// save the basket
$this->get('sonata.basket.factory')->save($basket);
return new RedirectResponse($this->generateUrl('sonata_basket_payment'));
}
}
// Set URL to be redirected to once edited address
$this->get('session')->set('sonata_address_redirect', $this->generateUrl('sonata_basket_payment_address'));
$this->get('sonata.seo.page')->setTitle($this->get('translator')->trans('basket_payment_title', array(), "SonataBasketBundle"));
return $this->render($template, array(
'form' => $form->createView(),
'addresses' => $addresses
));
}
/**
* Order process step 6: order's review & conditions acceptance checkbox
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function finalReviewStepAction()
{
$basket = $this->get('sonata.basket');
$violations = $this
->get('validator')
->validate($basket, array('elements', 'delivery', 'payment'));
if ($violations->count() > 0) {
// basket not valid
// todo : add flash message rendering in template
foreach ($violations as $violation) {
$this->get('session')->getFlashBag()->add('error', 'Error: '.$violation->getMessage());
}
return new RedirectResponse($this->generateUrl('sonata_basket_index'));
}
if ($this->get('request')->getMethod() == 'POST' ) {
if ($this->get('request')->get('tac')) {
// send the basket to the payment callback
return $this->forward('SonataPaymentBundle:Payment:sendbank');
}
}
$this->get('sonata.seo.page')->setTitle($this->get('translator')->trans('basket_review_title', array(), "SonataBasketBundle"));
return $this->render('SonataBasketBundle:Basket:final_review_step.html.twig', array(
'basket' => $basket,
'tac_error' => $this->get('request')->getMethod() == 'POST'
));
}
}