Completed
Branch feature-dynamic-fields (cdebc1)
by Ashutosh
10:20
created

CoupCodeAndInvoiceSearch::doPayment()   A

Complexity

Conditions 5
Paths 14

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 25
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\Payment\Plan;
7
use App\Model\Payment\PlanPrice;
8
use App\Model\Payment\Promotion;
9
use App\Model\Product\Product;
10
use Illuminate\Http\Request;
11
12
//////////////////////////////////////////////////////////////////////////////
13
// ADVANCE SEARCH FOR INVOICE AND COUPON CODE CALCULATION
14
//////////////////////////////////////////////////////////////////////////////
15
16
trait CoupCodeAndInvoiceSearch
17
{
18
    public function checkCode($code, $productid, $currency)
19
    {
20
        try {
21
            if ($code != '') {
22
                $promo = $this->promotion->where('code', $code)->first();
23
                //check promotion code is valid
24
                if (!$promo) {
25
                    throw new \Exception(\Lang::get('message.no-such-code'));
26
                }
27
                $relation = $promo->relation()->get();
28
                //check the relation between code and product
29
                if (count($relation) == 0) {
30
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
31
                }
32
                //check the usess
33
                $cont = new \App\Http\Controllers\Payment\PromotionController();
34
                $uses = $cont->checkNumberOfUses($code);
35
                if ($uses != 'success') {
36
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
37
                }
38
                //check for the expiry date
39
                $expiry = $this->checkExpiry($code);
0 ignored issues
show
Bug introduced by
It seems like checkExpiry() 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

39
                /** @scrutinizer ignore-call */ 
40
                $expiry = $this->checkExpiry($code);
Loading history...
40
                if ($expiry != 'success') {
41
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
42
                }
43
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
44
45
                return $value;
46
            } else {
47
                $product = $this->product->find($productid);
48
                $plans = Plan::where('product', $product)->pluck('id')->first();
49
                $price = PlanPrice::where('currency', $currency)->where('plan_id', $plans)->pluck('add_price')->first();
50
51
                return $price;
52
            }
53
        } catch (\Exception $ex) {
54
            throw new \Exception($ex->getMessage());
55
        }
56
    }
57
58
    public function findCostAfterDiscount($promoid, $productid, $currency)
59
    {
60
        try {
61
            $promotion = Promotion::findOrFail($promoid);
62
            $product = Product::findOrFail($productid);
63
            $promotion_type = $promotion->type;
64
            $promotion_value = $promotion->value;
65
            $planId = Plan::where('product', $productid)->pluck('id')->first();
66
            // dd($planId);
67
            $product_price = PlanPrice::where('plan_id', $planId)
68
            ->where('currency', $currency)->pluck('add_price')->first();
69
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
70
71
            return $updated_price;
72
        } catch (\Exception $ex) {
73
            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...
74
75
            throw new \Exception(\Lang::get('message.find-discount-error'));
76
        }
77
    }
78
79
    public function findCost($type, $value, $price, $productid)
80
    {
81
        $price = intval($price);
82
        switch ($type) {
83
            case 1:
84
                $percentage = $price * ($value / 100);
85
86
                return $price - $percentage;
87
            case 2:
88
                return $price - $value;
89
            case 3:
90
                return $value;
91
            case 4:
92
                return 0;
93
        }
94
    }
95
96
    public function advanceSearch($name = '', $invoice_no = '', $currency = '', $status = '', $from = '', $till = '')
97
    {
98
        $join = Invoice::leftJoin('users', 'invoices.user_id', '=', 'users.id');
99
        $this->name($name, $join);
100
        $this->invoice_no($invoice_no, $join);
101
        $this->status($status, $join);
102
        $this->currency($currency, $join);
103
104
        $this->invoice_from($from, $till, $join);
105
        $this->till_date($till, $from, $join);
106
107
        $join = $join->select('id', 'user_id', 'number', 'date', 'grand_total', 'currency', 'status', 'created_at');
108
109
        $join = $join->orderBy('created_at', 'desc')
110
        ->select(
111
            'invoices.id',
112
            'first_name',
113
            'invoices.created_at',
114
            'invoices.currency',
115
            'user_id',
116
            'number',
117
            'status'
118
        );
119
120
        return $join;
121
    }
122
123
    public function name($name, $join)
124
    {
125
        if ($name) {
126
            $join = $join->where('first_name', $name);
127
128
            return $join;
129
        }
130
    }
131
132
    public function invoice_no($invoice_no, $join)
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
133
    {
134
        if ($invoice_no) {
135
            $join = $join->where('number', $invoice_no);
136
137
            return $join;
138
        }
139
    }
140
141
    public function status($status, $join)
142
    {
143
        if ($status) {
144
            $join = $join->where('status', $status);
145
146
            return $join;
147
        }
148
    }
149
150
    public function currency($currency, $join)
151
    {
152
        if ($currency) {
153
            $join = $join->where('invoices.currency', $currency);
154
155
            return $join;
156
        }
157
        $return;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $return seems to be never defined.
Loading history...
158
    }
159
160
    public function invoice_from($from, $till, $join)
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
161
    {
162
        if ($from) {
163
            $fromdate = date_create($from);
164
            $from = date_format($fromdate, 'Y-m-d H:m:i');
165
            $tills = date('Y-m-d H:m:i');
166
            $tillDate = $this->getTillDate($from, $till, $tills);
167
            $join = $join->whereBetween('invoices.created_at', [$from, $tillDate]);
168
169
            return $join;
170
        }
171
172
        return $join;
173
    }
174
175
    public function till_date($till, $from, $join)
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
176
    {
177
        if ($till) {
178
            $tilldate = date_create($till);
179
            $till = date_format($tilldate, 'Y-m-d H:m:i');
180
            $froms = Invoice::first()->created_at;
181
            $fromDate = $this->getFromDate($from, $froms);
182
            $join = $join->whereBetween('invoices.created_at', [$fromDate, $till]);
183
184
            return $join;
185
        }
186
    }
187
188
    public function getExpiryStatus($start, $end, $now)
189
    {
190
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
0 ignored issues
show
Bug introduced by
It seems like whenDateNotSet() 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

190
        /** @scrutinizer ignore-call */ 
191
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
Loading history...
191
        if ($whenDateNotSet) {
192
            return $whenDateNotSet;
193
        }
194
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
0 ignored issues
show
Bug introduced by
It seems like whenStartDateSet() 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

194
        /** @scrutinizer ignore-call */ 
195
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
Loading history...
195
        if ($whenStartDateSet) {
196
            return $whenStartDateSet;
197
        }
198
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
0 ignored issues
show
Bug introduced by
It seems like whenEndDateSet() 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

198
        /** @scrutinizer ignore-call */ 
199
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
Loading history...
199
        if ($whenEndDateSet) {
200
            return $whenEndDateSet;
201
        }
202
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
0 ignored issues
show
Bug introduced by
It seems like whenBothSet() 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

202
        /** @scrutinizer ignore-call */ 
203
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
Loading history...
203
        if ($whenBothAreSet) {
204
            return $whenBothAreSet;
205
        }
206
    }
207
208
    public function getTillDate($from, $till, $tills)
209
    {
210
        if ($till) {
211
            $todate = date_create($till);
212
            $tills = date_format($todate, 'Y-m-d H:m:i');
213
        }
214
215
        return $tills;
216
    }
217
218
    public function getFromDate($from, $froms)
219
    {
220
        if ($from) {
221
            $fromdate = date_create($from);
222
            $froms = date_format($fromdate, 'Y-m-d H:m:i');
223
        }
224
225
        return $froms;
226
    }
227
228
    public function postRazorpayPayment($invoiceid, $grand_total)
229
    {
230
        try {
231
            $payment_method = \Session::get('payment_method');
232
            $payment_status = 'success';
233
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
234
            $amount = $grand_total;
235
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method,
236
             $payment_status, $payment_date, $amount);
237
238
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
239
        } catch (\Exception $ex) {
240
            return redirect()->back()->with('fails', $ex->getMessage());
241
        }
242
    }
243
244
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
245
    {
246
        try {
247
            $invoice = Invoice::find($invoiceid);
248
            $invoice_status = 'pending';
249
250
            $payment = $this->payment->create([
251
                'invoice_id'     => $invoiceid,
252
                'user_id'        => $invoice->user_id,
253
                'amount'         => $amount,
254
                'payment_method' => $payment_method,
255
                'payment_status' => $payment_status,
256
                'created_at'     => $payment_date,
257
            ]);
258
            $all_payments = $this->payment
259
            ->where('invoice_id', $invoiceid)
260
            ->where('payment_status', 'success')
261
            ->pluck('amount')->toArray();
262
            $total_paid = array_sum($all_payments);
263
            if ($total_paid >= $invoice->grand_total) {
264
                $invoice_status = 'success';
265
            }
266
            if ($invoice) {
267
                $invoice->status = $invoice_status;
268
                $invoice->save();
269
            }
270
271
            return $payment;
272
        } catch (\Exception $ex) {
273
            Bugsnag::notifyException($ex);
274
275
            throw new \Exception($ex->getMessage());
276
        }
277
    }
278
279
    public function updateInvoice($invoiceid)
280
    {
281
        try {
282
            $invoice = $this->invoice->findOrFail($invoiceid);
283
            $payment = $this->payment->where('invoice_id', $invoiceid)
284
            ->where('payment_status', 'success')->pluck('amount')->toArray();
285
            $total = array_sum($payment);
286
            if ($total < $invoice->grand_total) {
287
                $invoice->status = 'pending';
288
            }
289
            if ($total >= $invoice->grand_total) {
290
                $invoice->status = 'success';
291
            }
292
            if ($total > $invoice->grand_total) {
293
                $user = $invoice->user()->first();
294
                $balance = $total - $invoice->grand_total;
295
                $user->debit = $balance;
296
                $user->save();
297
            }
298
299
            $invoice->save();
300
        } catch (\Exception $ex) {
301
            Bugsnag::notifyException($ex);
302
303
            throw new \Exception($ex->getMessage());
304
        }
305
    }
306
307
    /**
308
     * Remove the specified resource from storage.
309
     *
310
     * @param int $id
311
     *
312
     * @return \Response
313
     */
314
    public function destroy(Request $request)
315
    {
316
        try {
317
            $ids = $request->input('select');
318
            if (!empty($ids)) {
319
                foreach ($ids as $id) {
320
                    $invoice = $this->invoice->where('id', $id)->first();
321
                    if ($invoice) {
322
                        $invoice->delete();
323
                    } else {
324
                        echo "<div class='alert alert-danger alert-dismissable'>
325
                    <i class='fa fa-ban'></i>
326
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
327
                    /* @scrutinizer ignore-type */
328
                    \Lang::get('message.failed').'
329
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
330
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
331
                </div>';
332
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
333
                    }
334
                }
335
                echo "<div class='alert alert-success alert-dismissable'>
336
                    <i class='fa fa-ban'></i>
337
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
338
                    /* @scrutinizer ignore-type */
339
                    \Lang::get('message.success').'
340
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
341
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
342
                </div>';
343
            } else {
344
                echo "<div class='alert alert-danger alert-dismissable'>
345
                    <i class='fa fa-ban'></i>
346
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
347
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
348
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
349
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
350
                </div>';
351
                //echo \Lang::get('message.select-a-row');
352
            }
353
        } catch (\Exception $e) {
354
            echo "<div class='alert alert-danger alert-dismissable'>
355
                    <i class='fa fa-ban'></i>
356
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
357
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
358
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
359
                        '.$e->getMessage().'
360
                </div>';
361
        }
362
    }
363
364
    /*
365
    *Edit payment Total.
366
    */
367
    public function paymentTotalChange(Request $request)
368
    {
369
        try {
370
            $invoice = new Invoice();
371
            $total = $request->input('total');
372
            if ($total == '') {
373
                $total = 0;
374
            }
375
            $paymentid = $request->input('id');
376
            $creditAmtUserId = $this->payment->where('id', $paymentid)->value('user_id');
377
            $creditAmt = $this->payment->where('user_id', $creditAmtUserId)
378
        ->where('invoice_id', '=', 0)->value('amt_to_credit');
379
            $invoices = $invoice->where('user_id', $creditAmtUserId)->orderBy('created_at', 'desc')->get();
380
            $cltCont = new \App\Http\Controllers\User\ClientController();
381
            $invoiceSum = $cltCont->getTotalInvoice($invoices);
382
            if ($total > $invoiceSum) {
383
                $diff = $total - $invoiceSum;
384
                $creditAmt = $creditAmt + $diff;
385
                $total = $invoiceSum;
386
            }
387
            $payment = $this->payment->where('id', $paymentid)->update(['amount'=>$total]);
388
389
            $creditAmtInvoiceId = $this->payment->where('user_id', $creditAmtUserId)
390
        ->where('invoice_id', '!=', 0)->first();
391
            $invoiceId = $creditAmtInvoiceId->invoice_id;
392
            $invoice = $invoice->where('id', $invoiceId)->first();
393
            $grand_total = $invoice->grand_total;
394
            $diffSum = $grand_total - $total;
395
396
            $finalAmt = $creditAmt + $diffSum;
397
            $updatedAmt = $this->payment->where('user_id', $creditAmtUserId)
398
        ->where('invoice_id', '=', 0)->update(['amt_to_credit'=>$creditAmt]);
399
        } catch (\Exception $ex) {
400
            app('log')->info($ex->getMessage());
401
            Bugsnag::notifyException($ex);
402
403
            return redirect()->back()->with('fails', $ex->getMessage());
404
        }
405
    }
406
407
    public function getAgents($agents, $productid, $plan)
408
    {
409
        if (!$agents) {//If agents is not received in the request in the case when
410
            // 'modify agent' is not allowed for the Product,get the no of Agents from the Plan Table.
411
            $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...
412
            if ($planForAgent) {//If Plan Exists For the Product ie not a Product without Plan
413
                $noOfAgents = $planForAgent->planPrice->first()->no_of_agents;
414
                $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 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...
415
            } else {
416
                $agents = 0;
417
            }
418
        }
419
420
        return $agents;
421
    }
422
423
    public function getQuantity($qty, $productid, $plan)
424
    {
425
        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 176 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...
426
            $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...
427
            if ($planForQty) {
428
                $quantity = Product::find($productid)->planRelation->find($plan)->planPrice->first()->product_quantity;
429
                $qty = $quantity ? $quantity : 1; //If no. of Agents is specified then that,else 0(Unlimited Agents)
430
            } else {
431
                $qty = 1;
432
            }
433
        }
434
435
        return $qty;
436
    }
437
438
    public function pdf(Request $request)
439
    {
440
        try {
441
            $id = $request->input('invoiceid');
442
            if (!$id) {
443
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
444
            }
445
            $invoice = $this->invoice->where('id', $id)->first();
446
            if (!$invoice) {
447
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
448
            }
449
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
450
            if ($invoiceItems->count() == 0) {
451
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
452
            }
453
            $user = $this->user->find($invoice->user_id);
454
            if (!$user) {
455
                return redirect()->back()->with('fails', 'No User');
456
            }
457
            $cont = new \App\Http\Controllers\Front\CartController();
458
            $currency = $cont->currency($user->id);
459
            $symbol = $currency['currency'];
460
            $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 134 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...
461
462
            return $pdf->download($user->first_name.'-invoice.pdf');
463
        } catch (\Exception $ex) {
464
            Bugsnag::notifyException($ex);
465
466
            return redirect()->back()->with('fails', $ex->getMessage());
467
        }
468
    }
469
470
    public function doPayment($payment_method, $invoiceid, $amount,
471
    $parent_id = '', $userid = '', $payment_status = 'pending')
472
    {
473
        try {
474
            if ($amount > 0) {
475
                if ($userid == '') {
476
                    $userid = \Auth::user()->id;
477
                }
478
                if ($amount == 0) {
479
                    $payment_status = 'success';
480
                }
481
                $this->payment->create([
482
                    'parent_id'      => $parent_id,
483
                    'invoice_id'     => $invoiceid,
484
                    'user_id'        => $userid,
485
                    'amount'         => $amount,
486
                    'payment_method' => $payment_method,
487
                    'payment_status' => $payment_status,
488
                ]);
489
                $this->updateInvoice($invoiceid);
490
            }
491
        } catch (\Exception $ex) {
492
            Bugsnag::notifyException($ex);
493
494
            throw new \Exception($ex->getMessage());
495
        }
496
    }
497
}
498