Test Failed
Pull Request — master (#236)
by
unknown
23:16
created

PayOnDeliveryController::store()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 52
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 36
c 1
b 0
f 0
dl 0
loc 52
rs 9.344
cc 3
nc 3
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Http\Controllers\Front\Payments;
4
5
use App\Http\Controllers\Controller;
6
use App\Shop\Carts\Repositories\Interfaces\CartRepositoryInterface;
7
use App\Shop\Couriers\Repositories\Interfaces\CourierRepositoryInterface;
8
use App\Shop\Checkout\CheckoutRepository;
9
use App\Shop\Orders\Repositories\OrderRepository;
10
use App\Shop\OrderStatuses\OrderStatus;
11
use App\Shop\OrderStatuses\Repositories\OrderStatusRepository;
12
use App\Shop\Shipping\ShippingInterface;
13
use Gloudemans\Shoppingcart\Facades\Cart;
14
use Illuminate\Http\Request;
15
use Illuminate\Support\Facades\Log;
16
use Ramsey\Uuid\Uuid;
17
use Shippo_Shipment;
18
use Shippo_Transaction;
19
20
class PayOnDeliveryController extends Controller
21
{
22
    /**
23
     * @var CartRepositoryInterface
24
     */
25
    private $cartRepo;
26
27
    /**
28
     * @var CourierRepositoryInterface
29
     */
30
    private $courierRepo;
31
32
    /**
33
     * @var int $shipping
34
     */
35
    private $shippingFee;
36
37
    private $rateObjectId;
38
39
    private $shipmentObjId;
40
41
    private $billingAddress;
42
43
    private $carrier;
44
45
    /**
46
     * BankTransferController constructor.
47
     *
48
     * @param Request $request
49
     * @param CartRepositoryInterface $cartRepository
50
     * @param ShippingInterface $shippingRepo
51
     */
52
    public function __construct(
53
        Request $request,
54
        CartRepositoryInterface $cartRepository,
55
        CourierRepositoryInterface $courierRepository,
56
        ShippingInterface $shippingRepo
57
    )
58
    {
59
        $this->cartRepo = $cartRepository;
60
        $this->courierRepo = $courierRepository;
61
        $rateObjId = null;
62
        $shipmentObjId = null;
63
        $billingAddress = $request->input('billing_address');
64
65
        if ($request->has('rate')) {
66
            if ($request->input('rate') != '') {
67
68
                $rate_id = $request->input('rate');
69
                $rates = $shippingRepo->getRates($request->input('shipment_obj_id'));
70
                $rate = collect($rates->results)->filter(function ($rate) use ($rate_id) {
71
                    return $rate->object_id == $rate_id;
72
                })->first();
73
74
                $fee = $rate->amount;
0 ignored issues
show
Unused Code introduced by
The assignment to $fee is dead and can be removed.
Loading history...
75
                $rateObjId = $rate->object_id;
76
                $shipmentObjId = $request->input('shipment_obj_id');
77
                $this->carrier = $rate;
78
            }
79
        }
80
81
        $this->shippingFee = 0;
82
        $this->rateObjectId = $rateObjId;
83
        $this->shipmentObjId = $shipmentObjId;
84
        $this->billingAddress = $billingAddress;
85
    }
86
87
    /**
88
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
89
     */
90
    public function index()
91
    {
92
        $courier = $this->courierRepo->findCourierById(request()->session()->get('courierId', 1));
93
        $this->shippingFee = $this->cartRepo->getShippingFee($courier);
94
95
        return view('front.pay-on-delivery-redirect', [
96
            'subtotal' => $this->cartRepo->getSubTotal(),
97
            'shipping' => $this->shippingFee,
98
            'tax' => $this->cartRepo->getTax(),
99
            'total' => $this->cartRepo->getTotal(2, $this->shippingFee),
100
            'rateObjectId' => $this->rateObjectId,
101
            'shipmentObjId' => $this->shipmentObjId,
102
            'billingAddress' => $this->billingAddress
103
        ]);
104
    }
105
106
    /**
107
     * @param Request $request
108
     *
109
     * @return \Illuminate\Http\RedirectResponse
110
     * @throws \Exception
111
     */
112
    public function store(Request $request)
113
    {
114
        $checkoutRepo = new CheckoutRepository;
115
        $orderStatusRepo = new OrderStatusRepository(new OrderStatus);
116
        $os = $orderStatusRepo->findByName('Pedido Feito');
117
118
        $order = $checkoutRepo->buildCheckoutItems([
119
            'reference' => Uuid::uuid4()->toString(),
120
            'courier_id' => 1, // @deprecated
121
            'customer_id' => $request->user()->id,
122
            'address_id' => $request->input('billing_address'),
123
            'order_status_id' => $os->id,
124
            'payment' => strtolower(config('pay-on-delivery.name')),
125
            'discounts' => 0,
126
            'total_products' => $this->cartRepo->getSubTotal(),
127
            'total' => $this->cartRepo->getTotal(2, $this->shippingFee),
128
            'total_shipping' => $this->shippingFee,
129
            'total_paid' => 0,
130
            'tax' => $this->cartRepo->getTax()
131
        ]);
132
133
        if (env('ACTIVATE_SHIPPING') == 1) {
134
            $shipment = Shippo_Shipment::retrieve($this->shipmentObjId);
135
136
            $details = [
137
                'shipment' => [
138
                    'address_to' => json_decode($shipment->address_to, true),
139
                    'address_from' => json_decode($shipment->address_from, true),
140
                    'parcels' => [json_decode($shipment->parcels[0], true)]
141
                ],
142
                'carrier_account' => $this->carrier->carrier_account,
143
                'servicelevel_token' => $this->carrier->servicelevel->token
144
            ];
145
146
            $transaction = Shippo_Transaction::create($details);
147
148
            if ($transaction['status'] != 'SUCCESS'){
149
                Log::error($transaction['messages']);
150
                return redirect()->route('checkout.index')->with('error', 'There is an error in the shipment details. Check logs.');
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->route... details. Check logs.') also could return the type Illuminate\Routing\Redirector which is incompatible with the documented return type Illuminate\Http\RedirectResponse.
Loading history...
151
            }
152
153
            $orderRepo = new OrderRepository($order);
154
            $orderRepo->updateOrder([
155
                'courier' => $this->carrier->provider,
156
                'label_url' => $transaction['label_url'],
157
                'tracking_number' => $transaction['tracking_number']
158
            ]);
159
        }
160
161
        Cart::destroy();
162
163
        return redirect()->route('accounts', ['tab' => 'orders'])->with('message', 'Order successful!');
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->route...', 'Order successful!') also could return the type Illuminate\Routing\Redirector which is incompatible with the documented return type Illuminate\Http\RedirectResponse.
Loading history...
164
    }
165
}