Completed
Branch feature-dynamic-fields (a5624d)
by Ashutosh
09:27
created

PaymentsAndInvoices   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 309
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 46
eloc 192
dl 0
loc 309
rs 8.72
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
B pdf() 0 29 6
A getAgents() 0 14 4
A postRazorpayPayment() 0 18 2
A doPayment() 0 30 5
A getQuantity() 0 13 4
A updateInvoice() 0 25 5
A sendmailClientAgent() 0 17 4
B payment() 0 44 6
B deletePayment() 0 51 6
A paymentTotalChange() 0 37 4

How to fix   Complexity   

Complex Class

Complex classes like PaymentsAndInvoices often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PaymentsAndInvoices, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Traits;
4
5
use App\Model\Order\Invoice;
6
use App\Model\Product\Product;
7
use Illuminate\Http\Request;
8
9
//////////////////////////////////////////////////////////////////////////////
10
// PAYMENTS AND EXTRA FUNCTIONALITIES FOR INVOICES
11
//////////////////////////////////////////////////////////////////////////////
12
13
    trait PaymentsAndInvoices
14
    {
15
        /*
16
    *Edit payment Total.
17
    */
18
        public function paymentTotalChange(Request $request)
19
        {
20
            try {
21
                $invoice = new Invoice();
22
                $total = $request->input('total');
23
                if ($total == '') {
24
                    $total = 0;
25
                }
26
                $paymentid = $request->input('id');
27
                $creditAmtUserId = $this->payment->where('id', $paymentid)->value('user_id');
28
                $creditAmt = $this->payment->where('user_id', $creditAmtUserId)
29
        ->where('invoice_id', '=', 0)->value('amt_to_credit');
30
                $invoices = $invoice->where('user_id', $creditAmtUserId)->orderBy('created_at', 'desc')->get();
31
                $cltCont = new \App\Http\Controllers\User\ClientController();
32
                $invoiceSum = $cltCont->getTotalInvoice($invoices);
33
                if ($total > $invoiceSum) {
34
                    $diff = $total - $invoiceSum;
35
                    $creditAmt = $creditAmt + $diff;
36
                    $total = $invoiceSum;
37
                }
38
                $payment = $this->payment->where('id', $paymentid)->update(['amount'=>$total]);
39
40
                $creditAmtInvoiceId = $this->payment->where('user_id', $creditAmtUserId)
41
        ->where('invoice_id', '!=', 0)->first();
42
                $invoiceId = $creditAmtInvoiceId->invoice_id;
43
                $invoice = $invoice->where('id', $invoiceId)->first();
44
                $grand_total = $invoice->grand_total;
45
                $diffSum = $grand_total - $total;
46
47
                $finalAmt = $creditAmt + $diffSum;
48
                $updatedAmt = $this->payment->where('user_id', $creditAmtUserId)
49
        ->where('invoice_id', '=', 0)->update(['amt_to_credit'=>$creditAmt]);
50
            } catch (\Exception $ex) {
51
                app('log')->info($ex->getMessage());
52
                Bugsnag::notifyException($ex);
0 ignored issues
show
Bug introduced by
The type App\Traits\Bugsnag was not found. Did you mean Bugsnag? If so, make sure to prefix the type with \.
Loading history...
53
54
                return redirect()->back()->with('fails', $ex->getMessage());
55
            }
56
        }
57
58
        public function doPayment(
59
        $payment_method,
60
        $invoiceid,
61
        $amount,
62
    $parent_id = '',
63
        $userid = '',
64
        $payment_status = 'pending'
65
    ) {
66
            try {
67
                if ($amount > 0) {
68
                    if ($userid == '') {
69
                        $userid = \Auth::user()->id;
70
                    }
71
                    if ($amount == 0) {
72
                        $payment_status = 'success';
73
                    }
74
                    $this->payment->create([
75
                    'parent_id'      => $parent_id,
76
                    'invoice_id'     => $invoiceid,
77
                    'user_id'        => $userid,
78
                    'amount'         => $amount,
79
                    'payment_method' => $payment_method,
80
                    'payment_status' => $payment_status,
81
                ]);
82
                    $this->updateInvoice($invoiceid);
83
                }
84
            } catch (\Exception $ex) {
85
                Bugsnag::notifyException($ex);
86
87
                throw new \Exception($ex->getMessage());
88
            }
89
        }
90
91
        public function getAgents($agents, $productid, $plan)
92
        {
93
            if (!$agents) {//If agents is not received in the request in the case when
94
                // 'modify agent' is not allowed for the Product,get the no of Agents from the Plan Table.
95
                $planForAgent = Product::find($productid)->planRelation->find($plan);
0 ignored issues
show
Bug introduced by
The property planRelation does not seem to exist on App\Model\Product\Product. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
96
                if ($planForAgent) {//If Plan Exists For the Product ie not a Product without Plan
97
                    $noOfAgents = $planForAgent->planPrice->first()->no_of_agents;
98
                    $agents = $noOfAgents ? $noOfAgents : 0; //If no. of Agents is specified then that,else 0(Unlimited Agents)
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
99
                } else {
100
                    $agents = 0;
101
                }
102
            }
103
104
            return $agents;
105
        }
106
107
        public function getQuantity($qty, $productid, $plan)
108
        {
109
            if (!$qty) {//If quantity is not received in the request in the case when 'modify quantity' is not allowed for the Product,get the Product qUANTITY from the Plan Table.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 180 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
110
                $planForQty = Product::find($productid)->planRelation->find($plan);
0 ignored issues
show
Bug introduced by
The property planRelation does not seem to exist on App\Model\Product\Product. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
111
                if ($planForQty) {
112
                    $quantity = Product::find($productid)->planRelation->find($plan)->planPrice->first()->product_quantity;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
113
                    $qty = $quantity ? $quantity : 1; //If no. of Agents is specified then that,else 0(Unlimited Agents)
114
                } else {
115
                    $qty = 1;
116
                }
117
            }
118
119
            return $qty;
120
        }
121
122
        public function updateInvoice($invoiceid)
123
        {
124
            try {
125
                $invoice = $this->invoice->findOrFail($invoiceid);
126
                $payment = $this->payment->where('invoice_id', $invoiceid)
127
            ->where('payment_status', 'success')->pluck('amount')->toArray();
128
                $total = array_sum($payment);
129
                if ($total < $invoice->grand_total) {
130
                    $invoice->status = 'pending';
131
                }
132
                if ($total >= $invoice->grand_total) {
133
                    $invoice->status = 'success';
134
                }
135
                if ($total > $invoice->grand_total) {
136
                    $user = $invoice->user()->first();
137
                    $balance = $total - $invoice->grand_total;
138
                    $user->debit = $balance;
139
                    $user->save();
140
                }
141
142
                $invoice->save();
143
            } catch (\Exception $ex) {
144
                Bugsnag::notifyException($ex);
145
146
                throw new \Exception($ex->getMessage());
147
            }
148
        }
149
150
        public function postRazorpayPayment($invoiceid, $grand_total)
151
        {
152
            try {
153
                $payment_method = \Session::get('payment_method');
154
                $payment_status = 'success';
155
                $payment_date = \Carbon\Carbon::now()->toDateTimeString();
156
                $amount = $grand_total;
157
                $paymentRenewal = $this->updateInvoicePayment(
0 ignored issues
show
Bug introduced by
The method updateInvoicePayment() does not exist on App\Traits\PaymentsAndInvoices. Did you maybe mean updateInvoice()? ( Ignorable by Annotation )

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

157
                /** @scrutinizer ignore-call */ 
158
                $paymentRenewal = $this->updateInvoicePayment(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
158
                $invoiceid,
159
                $payment_method,
160
             $payment_status,
161
                $payment_date,
162
                $amount
163
            );
164
165
                return redirect()->back()->with('success', 'Payment Accepted Successfully');
166
            } catch (\Exception $ex) {
167
                return redirect()->back()->with('fails', $ex->getMessage());
168
            }
169
        }
170
171
        public function sendmailClientAgent($userid, $invoiceid)
172
        {
173
            try {
174
                $agent = \Input::get('agent');
175
                $client = \Input::get('client');
176
                if ($agent == 1) {
177
                    $id = \Auth::user()->id;
178
                    $this->sendMail($id, $invoiceid);
0 ignored issues
show
Bug introduced by
It seems like sendMail() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

178
                    $this->/** @scrutinizer ignore-call */ 
179
                           sendMail($id, $invoiceid);
Loading history...
179
                }
180
                if ($client == 1) {
181
                    $this->sendMail($userid, $invoiceid);
182
                }
183
            } catch (\Exception $ex) {
184
                app('log')->info($ex->getMessage());
185
                Bugsnag::notifyException($ex);
186
187
                throw new \Exception($ex->getMessage());
188
            }
189
        }
190
191
        public function payment(Request $request)
192
        {
193
            try {
194
                if ($request->has('invoiceid')) {
195
                    $invoice_id = $request->input('invoiceid');
196
                    $invoice = $this->invoice->find($invoice_id);
197
                    $userid = $invoice->user_id;
198
                    //dd($invoice);
199
                    $invoice_status = '';
200
                    $payment_status = '';
201
                    $payment_method = '';
202
                    $domain = '';
203
                    if ($invoice) {
204
                        $invoice_status = $invoice->status;
205
                        $items = $invoice->invoiceItem()->first();
206
                        if ($items) {
207
                            $domain = $items->domain;
208
                        }
209
                    }
210
                    $payment = $this->payment->where('invoice_id', $invoice_id)->first();
211
                    if ($payment) {
212
                        $payment_status = $payment->payment_status;
213
                        $payment_method = $payment->payment_method;
214
                    }
215
216
                    return view(
217
                    'themes.default1.invoice.payment',
218
                 compact(
219
                     'invoice_status',
220
                     'payment_status',
221
                  'payment_method',
222
                     'invoice_id',
223
                     'domain',
224
                     'invoice',
225
                     'userid'
226
                 )
227
                );
228
                }
229
230
                return redirect()->back();
231
            } catch (\Exception $ex) {
232
                Bugsnag::notifyException($ex);
233
234
                return redirect()->back()->with('fails', $ex->getMessage());
235
            }
236
        }
237
238
        public function deletePayment(Request $request)
239
        {
240
            try {
241
                $ids = $request->input('select');
242
                if (!empty($ids)) {
243
                    foreach ($ids as $id) {
244
                        $payment = $this->payment->where('id', $id)->first();
245
                        if ($payment) {
246
                            $invoice = $this->invoice->find($payment->invoice_id);
247
                            if ($invoice) {
248
                                $invoice->status = 'pending';
249
                                $invoice->save();
250
                            }
251
                            $payment->delete();
252
                        } else {
253
                            echo "<div class='alert alert-danger alert-dismissable'>
254
                    <i class='fa fa-ban'></i>
255
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> 
256
                    './* @scrutinizer ignore-type */\Lang::get('message.failed').'
257
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
258
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
259
                </div>';
260
                            //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
261
                        }
262
                    }
263
                    echo "<div class='alert alert-success alert-dismissable'>
264
                    <i class='fa fa-ban'></i>
265
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
266
                    /* @scrutinizer ignore-type */
267
                    \Lang::get('message.success').'
268
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
269
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
270
                </div>';
271
                } else {
272
                    echo "<div class='alert alert-danger alert-dismissable'>
273
                    <i class='fa fa-ban'></i>
274
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
275
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
276
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
277
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
278
                </div>';
279
                    //echo \Lang::get('message.select-a-row');
280
                }
281
            } catch (\Exception $e) {
282
                Bugsnag::notifyException($e);
283
                echo "<div class='alert alert-danger alert-dismissable'>
284
                    <i class='fa fa-ban'></i>
285
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
286
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
287
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
288
                        '.$e->getMessage().'
289
                </div>';
290
            }
291
        }
292
293
        public function pdf(Request $request)
294
        {
295
            try {
296
                $id = $request->input('invoiceid');
297
                if (!$id) {
298
                    return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
299
                }
300
                $invoice = $this->invoice->where('id', $id)->first();
301
                if (!$invoice) {
302
                    return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
303
                }
304
                $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
305
                if ($invoiceItems->count() == 0) {
306
                    return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
307
                }
308
                $user = $this->user->find($invoice->user_id);
309
                if (!$user) {
310
                    return redirect()->back()->with('fails', 'No User');
311
                }
312
                $cont = new \App\Http\Controllers\Front\CartController();
313
                $currency = $cont->currency($user->id);
314
                $symbol = $currency['currency'];
315
                $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user', 'currency', 'symbol'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 138 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
316
317
                return $pdf->download($user->first_name.'-invoice.pdf');
318
            } catch (\Exception $ex) {
319
                Bugsnag::notifyException($ex);
320
321
                return redirect()->back()->with('fails', $ex->getMessage());
322
            }
323
        }
324
    }
325