Test Setup Failed
Push — development ( 63d518...d700b6 )
by Ashutosh
11:10 queued 10s
created

PaymentsAndInvoices::doPayment()   A

Complexity

Conditions 5
Paths 14

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 30
rs 9.3888
c 0
b 0
f 0
cc 5
nc 14
nop 6
1
<?php
2
3
namespace App\Traits;
4
5
use App\Model\Order\Invoice;
6
use App\Model\Order\Payment;
7
use App\Model\Product\Product;
8
use Illuminate\Http\Request;
9
10
//////////////////////////////////////////////////////////////////////////////
11
// PAYMENTS AND EXTRA FUNCTIONALITIES FOR INVOICES
12
//////////////////////////////////////////////////////////////////////////////
13
14
    trait PaymentsAndInvoices
15
    {
16
        /*
17
    *Edit payment Total.
18
    */
19
        public function paymentTotalChange(Request $request)
20
        {
21
            try {
22
                $invoice = new Invoice();
23
                $total = $request->input('total');
24
                if ($total == '') {
25
                    $total = 0;
26
                }
27
                $paymentid = $request->input('id');
28
                $creditAmtUserId = $this->payment->where('id', $paymentid)->value('user_id');
29
                $creditAmt = $this->payment->where('user_id', $creditAmtUserId)
30
        ->where('invoice_id', '=', 0)->value('amt_to_credit');
31
                $invoices = $invoice->where('user_id', $creditAmtUserId)->orderBy('created_at', 'desc')->get();
32
                $cltCont = new \App\Http\Controllers\User\ClientController();
33
                $invoiceSum = $cltCont->getTotalInvoice($invoices);
34
                if ($total > $invoiceSum) {
35
                    $diff = $total - $invoiceSum;
36
                    $creditAmt = $creditAmt + $diff;
37
                    $total = $invoiceSum;
38
                }
39
                $payment = $this->payment->where('id', $paymentid)->update(['amount'=>$total]);
40
41
                $creditAmtInvoiceId = $this->payment->where('user_id', $creditAmtUserId)
42
        ->where('invoice_id', '!=', 0)->first();
43
                $invoiceId = $creditAmtInvoiceId->invoice_id;
44
                $invoice = $invoice->where('id', $invoiceId)->first();
45
                $grand_total = $invoice->grand_total;
46
                $diffSum = $grand_total - $total;
47
48
                $finalAmt = $creditAmt + $diffSum;
49
                $updatedAmt = $this->payment->where('user_id', $creditAmtUserId)
50
        ->where('invoice_id', '=', 0)->update(['amt_to_credit'=>$creditAmt]);
51
            } catch (\Exception $ex) {
52
                app('log')->info($ex->getMessage());
53
                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...
54
55
                return redirect()->back()->with('fails', $ex->getMessage());
56
            }
57
        }
58
59
        public function doPayment(
60
        $payment_method,
61
        $invoiceid,
62
        $amount,
63
    $parent_id = '',
64
        $userid = '',
65
        $payment_status = 'pending'
66
    ) {
67
            try {
68
                if ($amount > 0) {
69
                    if ($userid == '') {
70
                        $userid = \Auth::user()->id;
71
                    }
72
                    if ($amount == 0) {
73
                        $payment_status = 'success';
74
                    }
75
                    $this->payment->create([
76
                    'parent_id'      => $parent_id,
77
                    'invoice_id'     => $invoiceid,
78
                    'user_id'        => $userid,
79
                    'amount'         => $amount,
80
                    'payment_method' => $payment_method,
81
                    'payment_status' => $payment_status,
82
                ]);
83
                    $this->updateInvoice($invoiceid);
84
                }
85
            } catch (\Exception $ex) {
86
                Bugsnag::notifyException($ex);
87
88
                throw new \Exception($ex->getMessage());
89
            }
90
        }
91
92
        public function getAgents($agents, $productid, $plan)
93
        {
94
            if (!$agents) {//If agents is not received in the request in the case when
95
                // 'modify agent' is not allowed for the Product,get the no of Agents from the Plan Table.
96
                $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...
97
                if ($planForAgent) {//If Plan Exists For the Product ie not a Product without Plan
98
                    $noOfAgents = $planForAgent->planPrice->first()->no_of_agents;
99
                    $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...
100
                } else {
101
                    $agents = 0;
102
                }
103
            }
104
105
            return $agents;
106
        }
107
108
        public function getQuantity($qty, $productid, $plan)
109
        {
110
            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...
111
                $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...
112
                if ($planForQty) {
113
                    $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...
114
                    $qty = $quantity ? $quantity : 1; //If no. of Agents is specified then that,else 0(Unlimited Agents)
115
                } else {
116
                    $qty = 1;
117
                }
118
            }
119
120
            return $qty;
121
        }
122
123
        public function updateInvoice($invoiceid)
124
        {
125
            try {
126
                $invoice = $this->invoice->findOrFail($invoiceid);
127
                $payment = $this->payment->where('invoice_id', $invoiceid)
128
            ->where('payment_status', 'success')->pluck('amount')->toArray();
129
                $total = array_sum($payment);
130
                if ($total < $invoice->grand_total) {
131
                    $invoice->status = 'pending';
132
                }
133
                if ($total >= $invoice->grand_total) {
134
                    $invoice->status = 'success';
135
                }
136
                if ($total > $invoice->grand_total) {
137
                    $user = $invoice->user()->first();
138
                    $balance = $total - $invoice->grand_total;
139
                    $user->debit = $balance;
140
                    $user->save();
141
                }
142
143
                $invoice->save();
144
            } catch (\Exception $ex) {
145
                Bugsnag::notifyException($ex);
146
147
                throw new \Exception($ex->getMessage());
148
            }
149
        }
150
151
        public function postRazorpayPayment($invoiceid, $grand_total)
152
        {
153
            try {
154
                $payment_method = \Session::get('payment_method');
155
                $payment_status = 'success';
156
                $payment_date = \Carbon\Carbon::now()->toDateTimeString();
157
                $amount = $grand_total;
158
                $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

158
                /** @scrutinizer ignore-call */ 
159
                $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...
159
                $invoiceid,
160
                $payment_method,
161
             $payment_status,
162
                $payment_date,
163
                $amount
164
            );
165
166
                return redirect()->back()->with('success', 'Payment Accepted Successfully');
167
            } catch (\Exception $ex) {
168
                return redirect()->back()->with('fails', $ex->getMessage());
169
            }
170
        }
171
172
        public function sendmailClientAgent($userid, $invoiceid)
173
        {
174
            try {
175
                $agent = \Input::get('agent');
176
                $client = \Input::get('client');
177
                if ($agent == 1) {
178
                    $id = \Auth::user()->id;
179
                    $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

179
                    $this->/** @scrutinizer ignore-call */ 
180
                           sendMail($id, $invoiceid);
Loading history...
180
                }
181
                if ($client == 1) {
182
                    $this->sendMail($userid, $invoiceid);
183
                }
184
            } catch (\Exception $ex) {
185
                app('log')->info($ex->getMessage());
186
                Bugsnag::notifyException($ex);
187
188
                throw new \Exception($ex->getMessage());
189
            }
190
        }
191
192
        public function payment(Request $request)
193
        {
194
            try {
195
                if ($request->has('invoiceid')) {
196
                    $invoice_id = $request->input('invoiceid');
197
                    $invoice = $this->invoice->find($invoice_id);
198
                    $userid = $invoice->user_id;
199
                    //dd($invoice);
200
                    $invoice_status = '';
201
                    $payment_status = '';
202
                    $payment_method = '';
203
                    $domain = '';
204
                    if ($invoice) {
205
                        $invoice_status = $invoice->status;
206
                        $items = $invoice->invoiceItem()->first();
207
                        if ($items) {
208
                            $domain = $items->domain;
209
                        }
210
                    }
211
                    $payment = $this->payment->where('invoice_id', $invoice_id)->first();
212
                    if ($payment) {
213
                        $payment_status = $payment->payment_status;
214
                        $payment_method = $payment->payment_method;
215
                    }
216
217
                    return view(
218
                    'themes.default1.invoice.payment',
219
                 compact(
220
                     'invoice_status',
221
                     'payment_status',
222
                  'payment_method',
223
                     'invoice_id',
224
                     'domain',
225
                     'invoice',
226
                     'userid'
227
                 )
228
                );
229
                }
230
231
                return redirect()->back();
232
            } catch (\Exception $ex) {
233
                Bugsnag::notifyException($ex);
234
235
                return redirect()->back()->with('fails', $ex->getMessage());
236
            }
237
        }
238
239
        public function deletePayment(Request $request)
240
        {
241
            try {
242
                $ids = $request->input('select');
243
                if (!empty($ids)) {
244
                    foreach ($ids as $id) {
245
                        $payment = $this->payment->where('id', $id)->first();
246
                        if ($payment) {
247
                            $invoice = $this->invoice->find($payment->invoice_id);
248
                            if ($invoice) {
249
                                $invoice->status = 'pending';
250
                                $invoice->save();
251
                            }
252
                            $payment->delete();
253
                        } else {
254
                            echo "<div class='alert alert-danger alert-dismissable'>
255
                    <i class='fa fa-ban'></i>
256
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> 
257
                    './* @scrutinizer ignore-type */\Lang::get('message.failed').'
258
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
259
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
260
                </div>';
261
                            //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
262
                        }
263
                    }
264
                    echo "<div class='alert alert-success alert-dismissable'>
265
                    <i class='fa fa-ban'></i>
266
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
267
                    /* @scrutinizer ignore-type */
268
                    \Lang::get('message.success').'
269
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
270
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
271
                </div>';
272
                } else {
273
                    echo "<div class='alert alert-danger alert-dismissable'>
274
                    <i class='fa fa-ban'></i>
275
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
276
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
277
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
278
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
279
                </div>';
280
                    //echo \Lang::get('message.select-a-row');
281
                }
282
            } catch (\Exception $e) {
283
                Bugsnag::notifyException($e);
284
                echo "<div class='alert alert-danger alert-dismissable'>
285
                    <i class='fa fa-ban'></i>
286
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
287
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
288
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
289
                        '.$e->getMessage().'
290
                </div>';
291
            }
292
        }
293
294
        public function pdf(Request $request)
295
        {
296
            try {
297
                $id = $request->input('invoiceid');
298
                if (!$id) {
299
                    return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
300
                }
301
                $invoice = $this->invoice->where('id', $id)->first();
302
                if (!$invoice) {
303
                    return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
304
                }
305
                $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
306
                if ($invoiceItems->count() == 0) {
307
                    return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
308
                }
309
                $user = $this->user->find($invoice->user_id);
310
                if (!$user) {
311
                    return redirect()->back()->with('fails', 'No User');
312
                }
313
                $cont = new \App\Http\Controllers\Front\CartController();
314
                $currency = $cont->currency($user->id);
315
                $symbol = $currency['currency'];
316
                $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...
317
318
                return $pdf->download($user->first_name.'-invoice.pdf');
319
            } catch (\Exception $ex) {
320
                Bugsnag::notifyException($ex);
321
322
                return redirect()->back()->with('fails', $ex->getMessage());
323
            }
324
        }
325
326
        public function getExtraAmtPaid($userId)
327
        {
328
            try {
329
                $amounts = Payment::where('user_id', $userId)->where('invoice_id', 0)->select('amt_to_credit')->get();
330
                $balance = 0;
331
                foreach ($amounts as $amount) {
332
                    if ($amount) {
333
                        $balance = $balance + $amount->amt_to_credit;
334
                    }
335
                }
336
337
                return $balance;
338
            } catch (\Exception $ex) {
339
                app('log')->info($ex->getMessage());
340
                Bugsnag::notifyException($ex);
341
342
                return redirect()->back()->with('fails', $ex->getMessage());
343
            }
344
        }
345
346
        /**
347
         * Get total of the Invoices for a User.
348
         */
349
        public function getTotalInvoice($invoices)
350
        {
351
            $sum = 0;
352
            foreach ($invoices as $invoice) {
353
                $sum = $sum + $invoice->grand_total;
354
            }
355
356
            return $sum;
357
        }
358
359
    public function getAmountPaid($userId)
360
    {
361
        try {
362
            $amounts = Payment::where('user_id', $userId)->select('amount', 'amt_to_credit')->get();
363
            $paidSum = 0;
364
            foreach ($amounts as $amount) {
365
                if ($amount) {
366
                    $paidSum = $paidSum + $amount->amount;
367
                   // $credit = $paidSum + $amount->amt_to_credit;
368
                }
369
            }
370
            return $paidSum;
371
        } catch (\Exception $ex) {
372
            app('log')->info($ex->getMessage());
373
            Bugsnag::notifyException($ex);
374
375
            return redirect()->back()->with('fails', $ex->getMessage());
376
        }
377
     }
378
    }
379