Repository navigation
Expand file tree
/
Copy pathOrdersController.php
More file actions
1518 lines (1271 loc) · 52 KB
/
Copy pathOrdersController.php
File metadata and controls
1518 lines (1271 loc) · 52 KB
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of the Antvel e-commerce.
*
* (c) Gustavo Ocanto <gustavoocanto@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Http\Controllers;
use Antvel\Product\Products;
use Illuminate\Http\Request;
use Antvel\Users\Models\User;
use Antvel\Product\Models\Product;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Antvel\AddressBook\Models\Address;
use Antvel\Product\Suggestions\Suggest;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Antvel\Users\Notifications\OrderWasUpdated;
use Antvel\Orders\Models\{ Order, OrderDetail };
use Antvel\Users\Notifications\OrderWasCommented;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class OrdersController extends Controller
{
/**
* Adds the selected product to the BASE cart.
*
* @param string $destination type or order ('cart','later',etc)
* @param int $productId The id of the product to be added
*
* @return Response
*/
public function addToOrder($destination, $productId, Request $request)
{
$quantity = $request->get('quantity');
//if there is not quantity requested, the value is 1 as defect
if (!$quantity) {
$quantity = 1;
}
//making sure if the product requested exists, otherwise, we throw a http exception
try {
$product = Product::findOrFail($productId);
} catch (ModelNotFoundException $e) {
throw new NotFoundHttpException();
}
$user = \Auth::user();
//checking if the user is logged
if ($user) {
$basicCart = Order::ofType($destination)->where('user_id', $user->id)->first();
if (!$basicCart) {
$basicCart = new Order();
$basicCart->user_id = $user->id;
$basicCart->type = $destination;
$basicCart->status = 'open';
$basicCart->save();
}
//if the request has an email address, we keep it, otherwise we use the user one
if ($request->has('email')) {
$v = Validator::make($request->all(), ['email' => 'required|email']);
if ($v->fails()) {
$email = $user->email;
} else {
$email = $request->input('email');
}
} else {
$email = $user->email;
}
//checking if the user already has a product so it can be added
$orderDetail = OrderDetail::where('order_id', $basicCart->id)
->where('product_id', $product->id)
->first();
//creating the order detail
if ($orderDetail) {
$orderDetail->price = $product->price;
$orderDetail->quantity = $orderDetail->quantity + $quantity;
} else {
$orderDetail = new OrderDetail();
$orderDetail->order_id = $basicCart->id;
$orderDetail->product_id = $product->id;
$orderDetail->price = $product->price;
$orderDetail->quantity = $quantity;
$orderDetail->status = 1;
}
//saving detail order
$orderDetail->save();
//callback url
if ($destination == 'wishlist') {
Session::push('message', trans('store.productAddedToWishList'));
return redirect()->route('orders.show_wish_list');
} elseif ($destination == 'later') {
Session::push('message', trans('store.productsSavedForLater'));
return redirect()->route('products.show', [$productId]);
} else {
Session::push('message', trans('store.productAdded'));
return redirect()->route('orders.show_cart');
}
}
//creating the user guest shopping cart
else {
/**
* $user_cart is used to keep track the user shopping cart.
*
* @var [array]
*/
$user_cart = Session::get('user.cart');
/*
* $user_cart is used to keep track the user shopping cart details
* @var [array]
*/
$user_cart_content = Session::get('user.cart_content');
//Checking if the user has a session cart, otherwise, it's created
if (!is_array($user_cart)) {
$user_cart = [];
}
//Checking if the user has content in the shopping cart, otherwise, it's added.
if (!is_array($user_cart_content)) {
$user_cart_content = [];
}
//Checking if the user has the product in the shopping cart, otherwise, it's pushed up
if (!in_array($productId, $user_cart)) {
array_push($user_cart, $productId);
}
//Checking if the user has quantity on the selected product, if so, it's quantity is updated, otherwise, 1 is added as defect.
if (!isset($user_cart_content[$productId])) {
$user_cart_content[$productId] = $quantity;
} else {
$user_cart_content[$productId] += $quantity;
}
//Saving session for user logged
Session::put('user.cart_content', $user_cart_content);
Session::put('user.cart', $user_cart);
Session::save();
Session::push('message', trans('store.productAdded'));
if ($destination == 'wishlist') {
/*
* flashWishList lets you save the product wished after login action.
* This var will be delete automatic in show show wishlist route.
*/
Session::put('flashWishList.productId', $productId);
Session::put('flashWishList.quantity', $quantity);
Session::save();
return redirect()->route('orders.show_wish_list');
} else {
return redirect()->route('orders.show_cart');
}
}
}
/**
* Allows adding products to a specific order and create new wish lists.
*
* @param [type] $orderId [order id]
* @param [type] $productId [product id]
* @param Request $request [laravel object]
*/
public function addToOrderById($orderId, $productId, Request $request)
{
$user = \Auth::user();
$quantity = $request->get('quantity') ? $request->get('quantity') : 1;
//checking whether the product required exist or not
try {
$product = Product::findOrFail($productId);
} catch (ModelNotFoundException $e) {
throw new NotFoundHttpException();
}
//checking whether the order required exist or not
try {
$order = Order::findOrFail($orderId);
} catch (ModelNotFoundException $e) {
throw new NotFoundHttpException();
}
if ($order) {
//checking the order to make sure whether it needs an added product increase its quantity
$orderDetail = OrderDetail::where('order_id', $order->id)
->where('product_id', $product->id)
->first();
//if the product exists, its quantity is increased
if ($orderDetail) {
$orderDetail->price = $product->price;
$orderDetail->quantity = $orderDetail->quantity + $quantity;
}
//otherwise, the order details is created from the product received
else {
$orderDetail = new OrderDetail();
$orderDetail->order_id = $order->id;
$orderDetail->product_id = $product->id;
$orderDetail->price = $product->price;
$orderDetail->quantity = $quantity;
$orderDetail->status = 1;
}
$orderDetail->save();
Session::push('message', trans('store.productAddedToWishList').', '.trans('globals.reference_label').$order->description);
} else {
Session::push('messageClass', 'alert-danger');
Session::push('message', trans('store.wishlist_no_exists').', '.trans('globals.reference_label').$order->description);
}
return redirect()->route('orders.show_wish_list_by_id', [$order->id]);
}
/**
* Show the create wish list form.
*
* @return view for orders.cart
*/
public function createWishList()
{
return view('orders.createWishList');
}
/**
* Create the new wishList with a description.
*
* @return Response JSON
*/
public function storeWishList(Request $request)
{
$description = $request->get('description');
$user = \Auth::user();
if ($user) {
//checking if the default wish list exists, otherwise, it is created automatically
$defaultList = Order::ofType('wishlist')
->where('user_id', $user->id)
->select(['id', 'type', 'description', 'status'])
->first();
//creating the default wish list, taking in account that it does not exist
if (!$defaultList) {
$default = new Order();
$default->user_id = $user->id;
$default->description = '';
$default->type = 'wishlist';
$default->status = 'open';
$default->save();
}
//checking if the wish list requested is not in our records
$newList = Order::ofType('wishlist')
->where('user_id', $user->id)
->where('description', $description)
->select(['id', 'type', 'description', 'status'])
->first();
//if the wish list requested is in our records, a error is sent
if ($newList) {
Session::push('messageClass', 'alert-danger');
Session::push('message', trans('store.form_create_list_view.message_fail'));
return \Response::json(['success' => true], 200);
} else {
//Creates the new wishlist with the provided description
$newList = new Order();
$newList->user_id = $user->id;
$newList->description = $description;
$newList->type = 'wishlist';
$newList->status = 'open';
$newList->save();
Session::push('message', trans('store.form_create_list_view.message_success'));
return \Response::json(['success' => true], 200);
}
}
}
/**
* Show the contents of a wish list.
*
* @return view for orders.wish
*/
public function showWishList($id = '')
{
/*
* Checking if there is a product in flashWishList, if so, it will be saved into the basic wish list.
* This process happens just before the user add a product to wishlist being not logged.
* flashWishList will be deleted after being used into addToOrder method
*/
if (Session::get('flashWishList') !== null) {
$this->addToOrder('wishlist', Session::get('flashWishList.productId'), new Request());
Session::forget('flashWishList');
Session::save();
}
//saving added to wishlist message (it happens when the product is added to wishlist, and the method call this one)
Session::forget('suggest-listed');
if (Session::has('message')) {
Session::push('message', Session::get('message'));
}
$user = \Auth::user();
$hasWishList = true;
$hasLaterCart = true;
$wishListName = trans('store.basic_wish_list');
if ($user) {
/*
* it is used to verify whether the order required exist or not.
* if the order exists, its content is returned, otherwise,
* the basic wish list is retrieved
* @var string
*/
$order = '';
/*
* validating if there's a order requested.
* if it fails, there will be an 404 exception threw
*/
try {
$order = Order::findOrFail($id);
} catch (ModelNotFoundException $e) {
if (trim($id) != '') {
throw new NotFoundHttpException();
}
}
//if the user requires a specific wish list, its details will be provided
if ($order) {
$cart = Order::ofType('wishlist')
->with('details')
->where('user_id', $user->id)
->where('id', $order->id)
->first();
/**
* $wishListName will have the wish list name to be showed in the view.
*
* @var string
*/
$wishListName = $cart ? $cart->description : $wishListName;
}
//if the required wish list does not exist, the default one will beprovided
else {
$cart = Order::ofType('wishlist')
->with('details')
->where('user_id', $user->id)
->first();
}
/*
* listing the user wish lists saved in his account.
* if there was a specific wish list requiered, it will be excluded from the directory list
*/
$wishLists = Order::select(['id', 'user_id', 'description'])
->ofType('wishlist')
->with('details')
->where('description', '<>', '')
->where('user_id', $user->id)
->where('id', '<>', $cart ? $cart->id : '')
->take(5)
->get();
//products list saved for later
$laterCart = Order::ofType('later')
->with('details')
->where('user_id', $user->id)
->first();
//evaluating wish list
if ($cart) {
if ($cart->details && $cart->details->count() > 0) {
//saving the ids selected to not include them into suggestions.
} else {
$hasWishList = false;
}
} else {
$hasWishList = false;
}
//evaluating wish list
if ($laterCart) {
if (! $laterCart->details && $laterCart->details->count() == 0) {
$hasLaterCart = false;
}
} else {
$hasLaterCart = false;
}
} //if ($user)
else {
return redirect()->route('/auth/login');
}
$panel = [
'center' => ['width' => '12'],
];
$suggestions = Suggest::for('product_purchased')->shake()->get('product_purchased');
return view('orders.wish',
compact(
'cart',
'user',
'panel',
'suggestions',
'cart',
'laterCart',
'wishLists',
'wishListName',
'hasWishList',
'hasLaterCart'
)
);
}
/**
* wish list directory.
*
* @return view for orders.cart
*/
public function wishListDirectory()
{
$user = \Auth::user();
if ($user) {
$orders = Order::ofType('wishlist')
->with('details')
->where('user_id', $user->id)
->orderBy('id', 'ASC')
->get();
} else {
return redirect()->route('/auth/login');
}
$panel = [
'center' => ['width' => '12'],
];
$suggestions = Suggest::for('product_purchased')->shake()->get('product_purchased');
return view('orders.wishListsDirectory', compact('orders', 'panel', 'suggestions'));
}
/**
* Show the contents of the user Cart.
*
* @return view for orders.cart
*/
public function showCart()
{
$cart = Order::where('type', 'cart')
->where('user_id', auth()->user()->id)
->with('details')
->first();
$laterCart = Order::with('details')->ofType('later')->where('user_id', auth()->user()->id)->first();
$validation_message = [];
$totalAmount = 0;
if (isset($cart) && $cart->exists()) {
foreach ($cart->details as $detail) {
if ($detail->quantity > $detail->product->stock) {
$detail->quantity = $detail->product->stock;
$detail->save();
$validation_message[] = trans('store.cart_view.item_changed_stock1').' '.$detail->product->name.' '.trans('store.cart_view.item_changed_stock2');
}
}
$totalAmount = $cart->details->flatMap(function ($item, $key) {
$results[] = $item->price * $item->quantity;
return $results;
})->sum();
}
if (count($validation_message) > 0) {
Session::push('message', $validation_message);
}
return view('orders.cart', [
'panel' => ['center' => ['width' => '12']],
'suggestions' => Suggest::for('product_purchased')->shake()->get('product_purchased'),
'totalAmount' => $totalAmount,
'laterCart' => $laterCart,
'cart' => $cart,
]);
}
/**
* Removes the selected item from the cart.
*
* @param string $orderName type or order ('cart','later',etc)
* @param int $productId Product id to be removed from the order
*
* @return Redirects back to de cart
*/
public function removeFromOrder($orderName, $productId, $idOrder = '')
{
$product = Product::findOrFail($productId);
$user = \Auth::user();
if (!$user) {
$cart_content = Session::get('user.cart_content');
unset($cart_content[$productId]);
Session::put('user.cart_content', $cart_content);
return redirect()->route('orders.show_cart');
}
$basicCart = Order::ofType($orderName)->where('user_id', $user->id);
if ($idOrder != '') {
$basicCart = $basicCart->where('id', $idOrder);
}
$basicCart = $basicCart->first();
if (!($basicCart)) {
Session::push('message', trans('store.productNotFound'));
} else {
$orderDetail = OrderDetail::where('order_id', $basicCart->id)->where('product_id', $product->id)->first();
$orderDetail->delete();
Session::push('message', trans('store.productDeleted'));
}
if (($orderName == 'wishlist') || ($orderName == 'later')) {
return redirect()->route('orders.show_wish_list');
} else {
return redirect()->route('orders.show_cart');
}
}
/**
* Removes the selected item from the cart, and stores it back in the Later Cart.
*
* @param int $origin type of the origin order ('cart','later',etc)
* @param int $destination type of the destination order ('cart','later',etc)
* @param int $productId of the product
*
* @return Redirects back to de cart
*/
public function moveFromOrder($origin, $destination, $productId)
{
/*
* validating if the product requested is valid.
* if it fails, there will be an 404 exception threw
*/
try {
$product = Product::findOrFail($productId);
} catch (ModelNotFoundException $e) {
throw new NotFoundHttpException();
}
$user = \Auth::user();
/**
* $originType allows tracking the type of origin, if it is coming from a specific wish list.
*
* @var string
*/
$originType = '';
//if it came from a specific wish list
if ($origin != 'later' && $origin != 'cart' && $origin != 'wishlist' && is_string($origin)) {
//getting the list type
$originType = Order::select(['id', 'type'])->where('description', 'LIKE', $origin)->first();
//getting the list information
$basicCart = Order::ofType($originType->type)
->where('user_id', $user->id)
->where('id', $originType->id)
->first();
}
//if it came either from the default wish list or shopping cart
else {
//getting the list information
$basicCart = Order::ofType($origin)
->where('user_id', $user->id)
->first();
}
//getting information of the destination order
$destinationOrder = Order::ofType($destination)
->where('user_id', $user->id)
->first();
//if there is not destination, it is created
if (!$destinationOrder) {
$destinationOrder = new Order();
$destinationOrder->user_id = $user->id;
$destinationOrder->type = $destination;
$destinationOrder->status = 'open';
$destinationOrder->save();
}
//checking if the user already has a product in the origin order, if so, it can be read to update the destination order.
$originDetail = OrderDetail::where('order_id', $basicCart->id)
->where('product_id', $product->id)
->first();
if ($originDetail) {
$oldQuantity = $originDetail->quantity;
$originDetail->delete();
} else {
$oldQuantity = 1;
}
//checking if the product exist in the destination, if so, it can be updated
$orderMoved = OrderDetail::where('order_id', $destinationOrder->id)
->where('product_id', $product->id)
->first();
//creating the new orden
if ($orderMoved) {
$orderMoved->price = $product->price;
$orderMoved->quantity = $orderMoved->quantity + $oldQuantity;
} else {
$orderMoved = new OrderDetail();
$orderMoved->order_id = $destinationOrder->id;
$orderMoved->product_id = $product->id;
$orderMoved->price = $product->price;
$orderMoved->quantity = $oldQuantity;
$orderMoved->status = 1;
}
//save new order
$orderMoved->save();
if ($destination == 'later') {
Session::push('message', trans('store.productSavedForLater'));
} elseif ($destination == 'cart') {
Session::push('message', trans('store.productAdded'));
}
return redirect()->route('orders.show_cart');
}
/**
* this method is able to update the quantities values in the shopping cart.
*
* @param $orderId is the shopping cart order id
* @param $orderDetailId is the shopping cart order details
* @param $newValue is new quantity to be used in the update
*
* @return Response
*/
public function updateQuantity($orderId, $orderDetailId, $newValue)
{
$user = \Auth::user();
if ($user) {
$orderDetail = OrderDetail::where('id', $orderDetailId)
->where('order_id', $orderId)
->select(['id', 'order_id', 'product_id', 'quantity', 'price'])
->first();
if ($orderDetail) {
$oldQuantity = $orderDetail->quantity;
$orderDetail->quantity = $newValue;
$orderDetail->save();
return \Response::json(
[
'success' => true,
'oldQuantity' => $oldQuantity,
'detail' => $orderDetail->toArray(),
'price' => $orderDetail->price,
], 200);
} else {
return \Response::json(['success' => false], 404);
}
}
}
/**
* Starts the checkout process.
*
* @param int $id
*
* @return Response
*/
public function checkOut()
{
$user = \Auth::user();
$cart = Order::ofType('cart')->where('user_id', $user->id)->select('id')->first();
$cartDetail = $cart ? OrderDetail::where('order_id', $cart->id)->get() : [];
$addresses = $user->addresses->sortByDesc('default');
$defaultId = '';
foreach ($addresses as $value) {
if ($value->default == '1') {
$defaultId = $value->id;
break;
}
}
$total_points = 0;
foreach ($cartDetail as $orderDetail) {
$product = Product::find($orderDetail->product_id);
$total_points += $orderDetail->quantity * $product->price;
}
if ($user->current_points < $total_points && config('app.payment_method') == 'Points') {
return redirect()->route('orders.show_cart')->withErrors(['main_error' => [trans('store.cart_view.insufficient_funds')]]);
} else {
$panel = [
'center' => ['width' => '12'],
];
$callBackUrl = 'user/orders/checkOut';
return view('address.list', compact('user', 'panel', 'cart', 'addresses', 'callBackUrl', 'defaultId'));
}
}
/**
* Starts the checkout process.
*
* @param int $addressId The address id selected to be copied
*
* @return Response
*/
public function checkOutResume($addressId)
{
$user = \Auth::user();
$cart = Order::ofType('cart')->with('details')->where('user_id', $user->id)->first();
$cartDetail = OrderDetail::where('order_id', $cart->id)->get();
$address = Address::find($addressId);
$totalAmount = 0;
$totalItems = 0;
//Checks if the user selected an address that belongs to him/her
$userAddress = Address::where('user_id', $user->id)->where('id', $address->id)->first();
if ($userAddress) {
//Checks if the user has points for the cart price and the store has stock
$total_points = 0;
foreach ($cartDetail as $orderDetail) {
$product = Product::find($orderDetail->product_id);
$totalItems += $orderDetail->quantity;
$totalAmount += ($orderDetail->quantity * $orderDetail->price);
if ($product->stock < $orderDetail->quantity) {
return redirect()->route('orders.show_cart')->withErrors(['main_error' => [trans('store.insufficientStock')]]);
}
}
//Checks if the user has points for the cart price
if ($user->current_points < $total_points && config('app.payment_method') == 'Points') {
return redirect()->route('orders.show_cart')->withErrors(['main_error' => [trans('store.cart_view.insufficient_funds')]]);
} else {
//Copies the Address to a new one and attaches it to the order or replaces the old one
$cartAddress = Address::find($cart->address_id);
if (!$cartAddress) {
//if the order does not has an address yet
$newAddress = new Address();
$newAddress->line1 = $address->line1;
$newAddress->line2 = $address->line2;
$newAddress->phone = $address->phone;
$newAddress->name_contact = $address->name_contact;
$newAddress->zipcode = $address->zipcode;
$newAddress->city = $address->city;
$newAddress->country = $address->country;
$newAddress->state = $address->state;
$newAddress->save();
$cart->address_id = $newAddress->id;
$cart->save();
$cartAddress = $newAddress;
} else {
//if the order needs to be updated
$cartAddress->line1 = $address->line1;
$cartAddress->line2 = $address->line2;
$cartAddress->phone = $address->phone;
$cartAddress->name_contact = $address->name_contact;
$cartAddress->zipcode = $address->zipcode;
$cartAddress->city = $address->city;
$cartAddress->country = $address->country;
$cartAddress->state = $address->state;
$cartAddress->save();
}
$panel = [
'center' => ['width' => '12'],
];
//Sets the resume option to use the same view
$isResume = true;
$is_logged = true;
return view('orders.cart', compact('cart', 'user', 'panel', 'isResume', 'cartAddress', 'totalItems', 'totalAmount'));
}
} else {
return redirect()->route('orders.show_cart')->withErrors(['main_error' => [trans('store.errorOnAddress')]]);
}
}
/**
* Starts the checkout process.
*
* @param int $addressId The address id selected to be copied
*
* @return Response
*/
public function placeOrder($type)
{
$errors = Order::placeOrders($type);
if ($errors) {
return redirect()->route('orders.show_cart')->withErrors(['main_error' => [$errors]]);
} else {
Session::push('message', trans('store.order_placed'));
return redirect()->route('orders.show_orders');
}
}
/**
* cancels one of the user orders.
*
* @return Response
*/
public function cancel($orderId, Request $request)
{
$user = \Auth::user();
/**
* $route description
* destination route after process the action.
*
* @var string
*/
$route = 'orders.pendingOrders';
/*
* $message
* provide control on the processed message to users
* @var array
*/
$message['msg'] = trans('store.cancelled_order');
$message['class'] = 'alert alert-success';
/**
* $order
* retrieve the evaluated order information. So what, we can update
* its status and return its items stock.
*
* @var [type]
*/
$order = Order::where('id', $orderId)
->with('details')
->where('user_id', $user->id)
->ofStatus('open')
->select('id', 'status', 'user_id')
->first();
//checking if the user is a seller
if (!$order) {
$route = '/user/orders';
$order = Order::where('id', $orderId)
->with('details')
->where('seller_id', $user->id)
->ofStatus('open')
->select('id', 'status', 'user_id')
->first();
}
//checking if it is our order
if ($order) {
$order->status = 'cancelled';
//Returning the stock to products
foreach ($order->details as $detail) {
$product = Product::find($detail->product_id);
$product->stock += $detail->quantity;
$product->save();
}
$order->save();
} else {
$message['msg'] = trans('store.no_order_message');
$message['class'] = 'alert alert-danger';
}
Session::push('message', $message['msg']);
Session::push('messageClass', $message['class']);
Session::save();
return redirect($route);
}
/**
* Changes the status of an order to pending, so the process can start.
*
* @param order_id The order id to be updated
*/
public function startOrder($order_id)
{
$order = Order::where('id', $order_id)
->where('seller_id', Auth::user()->id)
->ofStatus('open')
->first();
if ($order) {
$order->status = 'pending';
$order->save();
$order->owner->notify(new OrderWasUpdated($order));
Session::push('message', trans('store.orders_index.order_started').' (#'.$order->id.')');
}
return redirect(route('orders.pendingOrders'));
}
/**
* Changes the status of an order to pending, so the process can start.
*
* @param order_id The order id to be updated
*/
public function sendOrder($order_id)
{
$order = Order::where('id', $order_id)
->where('seller_id', Auth::user()->id)
->ofStatus('pending')
->select('id', 'user_id', 'status', 'seller_id')
->first();
if ($order) {
$order->status = 'sent';
$order->save();
$order->owner->notify(new OrderWasUpdated($order));
Session::push(
'message',
trans('store.orders_index.order_sent') .'(#'. $order->id .')'
);
}
return redirect(route('orders.pendingOrders'));
}
/**
* Changes the status of an order to close, so the user can now check if received.
*
* @param order_id The order id to be updated
*/
public function closeOrder($order_id)
{
$order = Order::where('id', $order_id)