Test Setup Failed
Push — development ( 07e8d5...22dd1e )
by Ashutosh
10:11
created

InvoiceController::checkCode()   B

Complexity

Conditions 8
Paths 16

Size

Total Lines 42
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 42
rs 8.4444
c 0
b 0
f 0
cc 8
nc 16
nop 3
1
<?php
2
3
namespace App\Http\Controllers\Order;
4
5
use App\Http\Controllers\Front\CartController;
6
use App\Model\Common\Setting;
7
use App\Model\Common\Template;
8
use App\Model\Order\Invoice;
9
use App\Model\Order\InvoiceItem;
10
use App\Model\Order\Order;
11
use App\Model\Order\Payment;
12
use App\Model\Payment\Currency;
13
use App\Model\Payment\PLan;
14
use App\Model\Payment\PLanPrice;
15
use App\Model\Payment\Promotion;
16
use App\Model\Payment\Tax;
17
use App\Model\Payment\TaxByState;
18
use App\Model\Payment\TaxOption;
19
use App\Model\Product\Price;
20
use App\Model\Product\Product;
21
use App\User;
22
use Bugsnag;
23
use Illuminate\Http\Request;
24
use Input;
25
use Log;
26
27
class InvoiceController extends TaxRatesAndCodeExpiryController
28
{
29
    public $invoice;
30
    public $invoiceItem;
31
    public $user;
32
    public $template;
33
    public $setting;
34
    public $payment;
35
    public $product;
36
    public $price;
37
    public $promotion;
38
    public $currency;
39
    public $tax;
40
    public $tax_option;
41
    public $order;
42
    public $cartController;
43
44
    public function __construct()
45
    {
46
        $this->middleware('auth');
47
        $this->middleware('admin', ['except' => ['pdf']]);
48
49
        $invoice = new Invoice();
50
        $this->invoice = $invoice;
51
52
        $invoiceItem = new InvoiceItem();
53
        $this->invoiceItem = $invoiceItem;
54
55
        $user = new User();
56
        $this->user = $user;
57
58
        $template = new Template();
59
        $this->template = $template;
60
61
        $seting = new Setting();
62
        $this->setting = $seting;
63
64
        $payment = new Payment();
65
        $this->payment = $payment;
66
67
        $product = new Product();
68
        $this->product = $product;
69
70
        $price = new Price();
71
        $this->price = $price;
72
73
        $promotion = new Promotion();
74
        $this->promotion = $promotion;
75
76
        $currency = new Currency();
77
        $this->currency = $currency;
78
79
        $tax = new Tax();
80
        $this->tax = $tax;
81
82
        $tax_option = new TaxOption();
83
        $this->tax_option = $tax_option;
84
85
        $order = new Order();
86
        $this->order = $order;
87
88
        $tax_by_state = new TaxByState();
89
        $this->tax_by_state = new $tax_by_state();
90
91
        $cartController = new CartController();
92
        $this->cartController = $cartController;
93
    }
94
95
    public function index()
96
    {
97
        try {
98
            //dd($this->invoice->get());
99
            return view('themes.default1.invoice.index');
100
        } catch (\Exception $ex) {
101
            Bugsnag::notifyException($ex);
102
103
            return redirect()->back()->with('fails', $ex->getMessage());
104
        }
105
    }
106
107
    public function getInvoices()
108
    {
109
        $invoice = \DB::table('invoices');
110
        // $new_invoice = $invoice->select('id', 'user_id', 'number', 'date', 'grand_total', 'status', 'created_at');
111
112
        return \DataTables::of($invoice->get())
113
                        ->addColumn('checkbox', function ($model) {
114
                            return "<input type='checkbox' class='invoice_checkbox' value=".$model->id.' name=select[] id=check>';
115
                        })
116
                        ->addColumn('user_id', function ($model) {
117
                            $first = $this->user->where('id', $model->user_id)->first()->first_name;
118
                            $last = $this->user->where('id', $model->user_id)->first()->last_name;
119
                            $id = $this->user->where('id', $model->user_id)->first()->id;
120
121
                            return '<a href='.url('clients/'.$id).'>'.ucfirst($first).' '.ucfirst($last).'</a>';
122
                        })
123
                         ->addColumn('number', function ($model) {
124
                             return ucfirst($model->number);
125
                         })
126
127
                        ->addColumn('date', function ($model) {
128
                            $date = date_create($model->created_at);
129
130
                            return "<span style='display:none'>$model->id</span>".$date->format('l, F j, Y H:m');
131
                        })
132
                         ->addColumn('grand_total', function ($model) {
133
                             return ucfirst($model->number);
134
                         })
135
                          ->addColumn('status', function ($model) {
136
                              return ucfirst($model->status);
137
                          })
138
139
                        ->addColumn('action', function ($model) {
140
                            $action = '';
141
142
                            $check = $this->checkExecution($model->id);
143
                            if ($check == false) {
144
                                $action = '<a href='.url('order/execute?invoiceid='.$model->id)." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-tasks' style='color:white;'> </i>&nbsp;&nbsp; Execute Order</a>";
145
                            }
146
147
                            return '<a href='.url('invoices/show?invoiceid='.$model->id)." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-eye' style='color:white;'> </i>&nbsp;&nbsp;View</a>"
148
                                    ."   $action";
149
                        })
150
151
                         ->rawColumns(['checkbox', 'user_id', 'number', 'date', 'grand_total', 'status', 'action'])
152
                        ->make(true);
153
    }
154
155
    public function show(Request $request)
156
    {
157
        try {
158
            $id = $request->input('invoiceid');
159
            $invoice = $this->invoice->where('id', $id)->first();
160
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
161
            $user = $this->user->find($invoice->user_id);
162
163
            return view('themes.default1.invoice.show', compact('invoiceItems', 'invoice', 'user'));
164
        } catch (\Exception $ex) {
165
            Bugsnag::notifyException($ex);
166
167
            return redirect()->back()->with('fails', $ex->getMessage());
168
        }
169
    }
170
171
    /**
172
     * not in use case.
173
     *
174
     * @param Request $request
175
     *
176
     * @return type
177
     */
178
    public function generateById(Request $request)
179
    {
180
        try {
181
            $clientid = $request->input('clientid');
182
            if ($clientid) {
183
                $user = new User();
184
                $user = $user->where('id', $clientid)->first();
185
                if (!$user) {
186
                    return redirect()->back()->with('fails', 'Invalid user');
187
                }
188
            } else {
189
                $user = '';
190
            }
191
            $products = $this->product->where('id', '!=', 1)->pluck('name', 'id')->toArray();
192
            $currency = $this->currency->pluck('name', 'code')->toArray();
193
194
            return view('themes.default1.invoice.generate', compact('user', 'products', 'currency'));
195
        } catch (\Exception $ex) {
196
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
197
            app('log')->info($ex->getMessage());
198
            Bugsnag::notifyException($ex);
199
200
            return redirect()->back()->with('fails', $ex->getMessage());
201
        }
202
    }
203
204
    public function invoiceGenerateByForm(Request $request, $user_id = '')
205
    {
206
        $qty = 1;
207
208
        try {
209
            if ($user_id == '') {
210
                $user_id = \Request::input('user');
211
            }
212
            $productid = $request->input('product');
213
            $code = $request->input('code');
214
            $total = $request->input('price');
215
            $plan = $request->input('plan');
216
            $description = $request->input('description');
217
            if ($request->has('domain')) {
218
                $domain = $request->input('domain');
219
                $this->setDomain($productid, $domain);
220
            }
221
            $controller = new \App\Http\Controllers\Front\CartController();
222
            $currency = $controller->currency($user_id);
223
            $number = rand(11111111, 99999999);
224
            $date = \Carbon\Carbon::now();
225
            $product = $this->product->find($productid);
226
            $cost = $controller->cost($productid, $user_id, $plan);
227
            if ($cost != $total) {
228
                $grand_total = $total;
229
            }
230
            $grand_total = $this->getGrandTotal($code, $total, $cost, $productid, $currency);
231
            $grand_total = $qty * $grand_total;
232
233
            $tax = $this->checkTax($product->id, $user_id);
234
            $tax_name = '';
235
            $tax_rate = '';
236
            if (!empty($tax)) {
237
                $tax_name = $tax[0];
238
                $tax_rate = $tax[1];
239
            }
240
241
            $grand_total = $this->calculateTotal($tax_rate, $grand_total);
242
            $grand_total = \App\Http\Controllers\Front\CartController::rounding($grand_total);
243
244
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'currency' => $currency, 'status' => 'pending', 'description' => $description]);
245
246
            $items = $this->createInvoiceItemsByAdmin($invoice->id, $productid, $code, $total, $currency, $qty, $plan, $user_id, $tax_name, $tax_rate);
247
            // dd($items);
248
            $result = $this->getMessage($items, $user_id);
249
        } catch (\Exception $ex) {
250
            app('log')->useDailyFiles(storage_path().'/laravel.log');
251
            app('log')->info($ex->getMessage());
252
            Bugsnag::notifyException($ex);
253
            $result = ['fails' => $ex->getMessage()];
254
        }
255
256
        return response()->json(compact('result'));
257
    }
258
259
    /*
260
    *Edit Invoice Total.
261
    */
262
    public function invoiceTotalChange(Request $request)
263
    {
264
        $total = $request->input('total');
265
        $number = $request->input('number');
266
        $invoiceId = Invoice::where('number', $number)->value('id');
267
        $invoiceItem = $this->invoiceItem->where('invoice_id', $invoiceId)->update(['subtotal'=>$total]);
268
        $invoices = $this->invoice->where('number', $number)->update(['grand_total'=>$total]);
269
    }
270
271
    public function sendmailClientAgent($userid, $invoiceid)
272
    {
273
        try {
274
            $agent = \Input::get('agent');
275
            $client = \Input::get('client');
276
            if ($agent == 1) {
277
                $id = \Auth::user()->id;
278
                $this->sendMail($id, $invoiceid);
279
            }
280
            if ($client == 1) {
281
                $this->sendMail($userid, $invoiceid);
282
            }
283
        } catch (\Exception $ex) {
284
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
285
            app('log')->info($ex->getMessage());
286
            Bugsnag::notifyException($ex);
287
288
            throw new \Exception($ex->getMessage());
289
        }
290
    }
291
292
    /**
293
     * Generate invoice.
294
     *
295
     * @throws \Exception
296
     */
297
    public function generateInvoice()
298
    {
299
        try {
300
            // dd(\Cart::getContent());
301
            $tax_rule = new \App\Model\Payment\TaxOption();
302
            $rule = $tax_rule->findOrFail(1);
303
            $rounding = $rule->rounding;
304
305
            $user_id = \Auth::user()->id;
306
            if (\Auth::user()->currency == 'INR') {
307
                $grand_total = \Cart::getSubTotal();
308
            } else {
309
                foreach (\Cart::getContent() as $cart) {
310
311
                    // $grand_total = $cart->price;
312
                    $grand_total = \Cart::getSubTotal();
313
                }
314
            }
315
            // dd($grand_total);
316
317
            $number = rand(11111111, 99999999);
318
            $date = \Carbon\Carbon::now();
319
320
            if ($rounding == 1) {
321
                $grand_total = round($grand_total);
322
            }
323
            $content = \Cart::getContent();
324
            $attributes = [];
325
            foreach ($content as $key => $item) {
326
                $attributes[] = $item->attributes;
327
            }
328
329
            $symbol = $attributes[0]['currency'][0]['code'];
330
            //dd($symbol);
331
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'status' => 'pending', 'currency' => $symbol]);
332
333
            foreach (\Cart::getContent() as $cart) {
334
                $this->createInvoiceItems($invoice->id, $cart);
335
            }
336
            //$this->sendMail($user_id, $invoice->id);
337
            return $invoice;
338
        } catch (\Exception $ex) {
339
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
340
            app('log')->info($ex->getMessage());
341
            Bugsnag::notifyException($ex);
342
343
            throw new \Exception('Can not Generate Invoice');
344
        }
345
    }
346
347
    public function createInvoiceItems($invoiceid, $cart)
348
    {
349
        try {
350
            $planid = 0;
351
            $product_name = $cart->name;
352
            $regular_price = $cart->price;
353
            $quantity = $cart->quantity;
354
            $domain = $this->domain($cart->id);
355
            $cart_cont = new \App\Http\Controllers\Front\CartController();
356
            if ($cart_cont->checkPlanSession() === true) {
357
                $planid = \Session::get('plan');
358
            }
359
            $user_currency = \Auth::user()->currency;
360
            $subtotal = $this->getSubtotal($user_currency, $cart);
361
362
            $tax_name = '';
363
            $tax_percentage = '';
364
365
            foreach ($cart->attributes['tax'] as $tax) {
366
                $tax_name .= $tax['name'].',';
367
                $tax_percentage .= $tax['rate'].',';
368
            }
369
370
            $invoiceItem = $this->invoiceItem->create([
371
                'invoice_id'     => $invoiceid,
372
                'product_name'   => $product_name,
373
                'regular_price'  => $regular_price,
374
                'quantity'       => $quantity,
375
                'tax_name'       => $tax_name,
376
                'tax_percentage' => $tax_percentage,
377
                'subtotal'       => $subtotal,
378
                'domain'         => $domain,
379
                'plan_id'        => $planid,
380
            ]);
381
382
            return $invoiceItem;
383
        } catch (\Exception $ex) {
384
            Bugsnag::notifyException($ex);
385
386
            throw new \Exception('Can not create Invoice Items');
387
        }
388
    }
389
390
    public function doPayment($payment_method, $invoiceid, $amount, $parent_id = '', $userid = '', $payment_status = 'pending')
391
    {
392
        try {
393
            if ($amount > 0) {
394
                if ($userid == '') {
395
                    $userid = \Auth::user()->id;
396
                }
397
                if ($amount == 0) {
398
                    $payment_status = 'success';
399
                }
400
                $this->payment->create([
401
                    'parent_id'      => $parent_id,
402
                    'invoice_id'     => $invoiceid,
403
                    'user_id'        => $userid,
404
                    'amount'         => $amount,
405
                    'payment_method' => $payment_method,
406
                    'payment_status' => $payment_status,
407
                ]);
408
                $this->updateInvoice($invoiceid);
409
            }
410
        } catch (\Exception $ex) {
411
            Bugsnag::notifyException($ex);
412
413
            throw new \Exception($ex->getMessage());
414
        }
415
    }
416
417
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code, $price, $currency, $qty, $planid = '', $userid = '', $tax_name = '', $tax_rate = '')
418
    {
419
        try {
420
            $discount = '';
421
            $mode = '';
422
            $product = $this->product->findOrFail($productid);
423
            $price_model = $this->price->where('product_id', $product->id)->where('currency', $currency)->first();
424
            $price = $this->getPrice($price, $price_model);
425
            $subtotal = $qty * $price;
426
            //dd($subtotal);
427
            if ($code) {
428
                $subtotal = $this->checkCode($code, $productid, $currency);
429
                $mode = 'coupon';
430
                $discount = $price - $subtotal;
431
            }
432
            $userid = \Auth::user()->id;
433
            if (\Auth::user()->role == 'user') {
434
                $tax = $this->checkTax($product->id, $userid);
435
                $tax_name = '';
436
                $tax_rate = '';
437
                if (!empty($tax)) {
438
439
                    //dd($value);
440
                    $tax_name = $tax[0];
441
                    $tax_rate = $tax[1];
442
                }
443
            }
444
445
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
446
447
            $domain = $this->domain($productid);
448
            $items = $this->invoiceItem->create([
449
                'invoice_id'     => $invoiceid,
450
                'product_name'   => $product->name,
451
                'regular_price'  => $price,
452
                'quantity'       => $qty,
453
                'discount'       => $discount,
454
                'discount_mode'  => $mode,
455
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
456
                'tax_name'       => $tax_name,
457
                'tax_percentage' => $tax_rate,
458
                'domain'         => $domain,
459
                'plan_id'        => $planid,
460
            ]);
461
462
            return $items;
463
        } catch (\Exception $ex) {
464
            Bugsnag::notifyException($ex);
465
466
            return redirect()->back()->with('fails', $ex->getMessage());
467
        }
468
    }
469
470
    public function findCostAfterDiscount($promoid, $productid, $currency)
471
    {
472
        try {
473
            $promotion = $this->promotion->findOrFail($promoid);
474
            $product = $this->product->findOrFail($productid);
475
            $promotion_type = $promotion->type;
476
            $promotion_value = $promotion->value;
477
            $planId = Plan::where('product', $productid)->pluck('id')->first();
478
            // dd($planId);
479
            $product_price = PlanPrice::where('plan_id', $planId)->where('currency', $currency)->pluck('add_price')->first();
480
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
481
482
            return $updated_price;
483
        } catch (\Exception $ex) {
484
            Bugsnag::notifyException($ex);
485
486
            throw new \Exception(\Lang::get('message.find-discount-error'));
487
        }
488
    }
489
490
    public function findCost($type, $value, $price, $productid)
491
    {
492
        switch ($type) {
493
                case 1:
494
                    $percentage = $price * ($value / 100);
495
496
                     return $price - $percentage;
497
                case 2:
498
                    return $price - $value;
499
                case 3:
500
                    return $value;
501
                case 4:
502
                    return 0;
503
            }
504
    }
505
506
    public function checkNumberOfUses($code)
507
    {
508
        try {
509
            $promotion = $this->promotion->where('code', $code)->first();
510
            $uses = $promotion->uses;
511
            if ($uses == 0) {
512
                return 'success';
513
            }
514
            $used_number = $this->invoice->where('coupon_code', $code)->count();
515
            if ($uses >= $used_number) {
516
                return 'success';
517
            } else {
518
                return 'fails';
519
            }
520
        } catch (\Exception $ex) {
521
            Bugsnag::notifyException($ex);
522
523
            throw new \Exception(\Lang::get('message.find-cost-error'));
524
        }
525
    }
526
527
    public function checkCode($code, $productid, $currency)
528
       {
529
        try {
530
            if ($code != '') {
531
                $promo = $this->promotion->where('code', $code)->first();
532
                //check promotion code is valid
533
                if (!$promo) {
534
                    throw new \Exception(\Lang::get('message.no-such-code'));
535
                }
536
                $relation = $promo->relation()->get();
537
                //check the relation between code and product
538
                if (count($relation) == 0) {
539
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
540
                }
541
                //check the usess
542
                $uses = $this->checkNumberOfUses($code);
543
                //dd($uses);
544
                if ($uses != 'success') {
545
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
546
                }
547
                //check for the expiry date
548
                $expiry = $this->checkExpiry($code);
549
                //dd($expiry);
550
                if ($expiry != 'success') {
551
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
552
                }
553
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
554
555
                return $value;
556
            } else {
557
                $product = $this->product->find($productid);
558
                $price = $product->price()->sales_price;
0 ignored issues
show
Bug introduced by
The property sales_price does not seem to exist on Illuminate\Database\Eloquent\Relations\HasMany.
Loading history...
559
                if (!$price) {
560
                    $price = $product->price()->price;
0 ignored issues
show
Bug introduced by
The property price does not seem to exist on Illuminate\Database\Eloquent\Relations\HasMany.
Loading history...
561
                }
562
563
                return $price;
564
            }
565
        } catch (\Exception $ex) {
566
            dd($ex);
567
568
            throw new \Exception(\Lang::get('message.check-code-error'));
569
        }
570
    }
571
572
    public function getPromotionDetails($code)
573
    {
574
        $promo = $this->promotion->where('code', $code)->first();
575
         //check promotion code is valid
576
        if (!$promo) {
577
            throw new \Exception(\Lang::get('message.no-such-code'));
578
        }
579
        $relation = $promo->relation()->get();
580
        //check the relation between code and product
581
        if (count($relation) == 0) {
582
            throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
583
        }
584
        //check the usess
585
        $uses = $this->checkNumberOfUses($code);
586
        //dd($uses);
587
        if ($uses != 'success') {
588
            throw new \Exception(\Lang::get('message.usage-of-code-completed'));
589
        }
590
        //check for the expiry date
591
        $expiry = $this->checkExpiry($code);
592
        //dd($expiry);
593
        if ($expiry != 'success') {
594
            throw new \Exception(\Lang::get('message.usage-of-code-expired'));
595
        }
596
597
        return $promo;
598
    }
599
600
    public function checkExpiry($code = '')
601
    {
602
        try {
603
            if ($code != '') {
604
                $promotion = $this->promotion->where('code', $code)->first();
605
                $start = $promotion->start;
606
                $end = $promotion->expiry;
607
                //dd($end);
608
                $now = \Carbon\Carbon::now();
609
                $getExpiryStatus = $this->getExpiryStatus($start, $end, $now);
610
611
                return $getExpiryStatus;
612
            } else {
613
            }
614
        } catch (\Exception $ex) {
615
            throw new \Exception(\Lang::get('message.check-expiry'));
616
        }
617
    }
618
619
    public function checkTax($productid, $userid)
620
    {
621
        try {
622
            $taxs = [];
623
            $taxs[0] = ['name' => 'null', 'rate' => 0];
624
            $geoip_state = User::where('id', $userid)->pluck('state')->first();
625
            $geoip_country = User::where('id', $userid)->pluck('country')->first();
626
            $product = $this->product->findOrFail($productid);
627
            $cartController = new CartController();
628
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
629
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
630
                    $taxs = $this->getTaxWhenEnable($productid, $taxs[0], $userid);
631
                } elseif ($this->tax_option->tax_enable == 0) {//if tax_enable is 0
632
633
                    $taxClassId = Tax::where('country', '')->where('state', 'Any State')
634
                     ->pluck('tax_classes_id')->first(); //In case of India when other tax is available and tax is not enabled
635
                    if ($taxClassId) {
636
                        $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
637
                        $taxs = $rate['taxes'];
638
                        $rate = $rate['rate'];
639
                    } elseif ($geoip_country != 'IN') {//In case of other country when tax is available and tax is not enabled(Applicable when Global Tax class for any country and state is not there)
640
641
                        $taxClassId = Tax::where('state', $geoip_state)->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
642
                        if ($taxClassId) { //if state equals the user State
643
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
644
                            $taxs = $rate['taxes'];
645
                            $rate = $rate['rate'];
646
                        }
647
                        $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
648
649
                        return $taxs;
650
                    }
651
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
652
                } else {
653
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
654
                }
655
            }
656
657
            return $taxs;
658
        } catch (\Exception $ex) {
659
            throw new \Exception(\Lang::get('message.check-tax-error'));
660
        }
661
    }
662
663
    public function getRate($productid, $taxs, $userid)
664
    {
665
        $tax_attribute = [];
666
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
667
        $tax_value = '0';
668
669
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
670
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
671
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
672
        $origin_state = $this->setting->first()->state; //Get the State of origin
673
        $cartController = new CartController();
674
675
        $rate = 0;
676
        $name1 = 'CGST';
677
        $name2 = 'SGST';
678
        $name3 = 'IGST';
679
        $name4 = 'UTGST';
680
        $c_gst = 0;
681
        $s_gst = 0;
682
        $i_gst = 0;
683
        $ut_gst = 0;
684
        $state_code = '';
685
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
686
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
687
            $taxes = $tax['taxes'];
688
            $value = $tax['value'];
689
        } else {//If user from other Country
690
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
691
            $taxes = $tax['taxes'];
692
            $value = $tax['value'];
693
            $rate = $tax['rate'];
694
        }
695
696
        foreach ($taxes as $key => $tax) {
697
            if ($taxes[0]) {
698
                $tax_attribute[$key] = ['name' => $tax->name, 'name1' => $name1, 'name2'=> $name2, 'name3' => $name3, 'name4' => $name4, 'rate' => $value, 'rate1'=>$c_gst, 'rate2'=>$s_gst, 'rate3'=>$i_gst, 'rate4'=>$ut_gst, 'state'=>$state_code, 'origin_state'=>$origin_state];
699
700
                $rate = $tax->rate;
701
702
                $tax_value = $value;
703
            } else {
704
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
705
                $tax_value = '0%';
706
            }
707
        }
708
709
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
710
    }
711
712
    public function pdf(Request $request)
713
    {
714
        try {
715
            $id = $request->input('invoiceid');
716
            if (!$id) {
717
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
718
            }
719
            $invoice = $this->invoice->where('id', $id)->first();
720
            if (!$invoice) {
721
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
722
            }
723
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
724
            if ($invoiceItems->count() == 0) {
725
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
726
            }
727
            $user = $this->user->find($invoice->user_id);
728
            if (!$user) {
729
                return redirect()->back()->with('fails', 'No User');
730
            }
731
            //return view('themes.default1.invoice.pdfinvoice', compact('invoiceItems', 'invoice', 'user'));
732
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
733
            // $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
734
735
            return $pdf->download($user->first_name.'-invoice.pdf');
736
        } catch (\Exception $ex) {
737
            Bugsnag::notifyException($ex);
738
739
            return redirect()->back()->with('fails', $ex->getMessage());
740
        }
741
    }
742
743
    /**
744
     * Remove the specified resource from storage.
745
     *
746
     * @param int $id
747
     *
748
     * @return \Response
749
     */
750
    public function destroy(Request $request)
751
    {
752
        try {
753
            $ids = $request->input('select');
754
            if (!empty($ids)) {
755
                foreach ($ids as $id) {
756
                    $invoice = $this->invoice->where('id', $id)->first();
757
                    if ($invoice) {
758
                        $invoice->delete();
759
                    } else {
760
                        echo "<div class='alert alert-danger alert-dismissable'>
761
                    <i class='fa fa-ban'></i>
762
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
763
                    \Lang::get('message.failed').'
764
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
765
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
766
                </div>';
767
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
768
                    }
769
                }
770
                echo "<div class='alert alert-success alert-dismissable'>
771
                    <i class='fa fa-ban'></i>
772
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
773
                    \Lang::get('message.success').'
774
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
775
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
776
                </div>';
777
            } else {
778
                echo "<div class='alert alert-danger alert-dismissable'>
779
                    <i class='fa fa-ban'></i>
780
                    <b>".\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
0 ignored issues
show
Bug introduced by
Are you sure Lang::get('message.alert') of type null|string|array can be used in concatenation? ( Ignorable by Annotation )

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

780
                    <b>"./** @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
Loading history...
781
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
782
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
783
                </div>';
784
                //echo \Lang::get('message.select-a-row');
785
            }
786
        } catch (\Exception $e) {
787
            echo "<div class='alert alert-danger alert-dismissable'>
788
                    <i class='fa fa-ban'></i>
789
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
790
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
791
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
792
                        '.$e->getMessage().'
793
                </div>';
794
        }
795
    }
796
797
    public function setDomain($productid, $domain)
798
    {
799
        try {
800
            if (\Session::has('domain'.$productid)) {
801
                \Session::forget('domain'.$productid);
802
            }
803
            \Session::put('domain'.$productid, $domain);
804
        } catch (\Exception $ex) {
805
            Bugsnag::notifyException($ex);
806
807
            throw new \Exception($ex->getMessage());
808
        }
809
    }
810
811
    public function domain($id)
812
    {
813
        try {
814
            if (\Session::has('domain'.$id)) {
815
                $domain = \Session::get('domain'.$id);
816
            } else {
817
                $domain = '';
818
            }
819
820
            return $domain;
821
        } catch (\Exception $ex) {
822
            Bugsnag::notifyException($ex);
823
        }
824
    }
825
826
    public function updateInvoice($invoiceid)
827
    {
828
        try {
829
            $invoice = $this->invoice->findOrFail($invoiceid);
830
            $payment = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
831
            $total = array_sum($payment);
832
            if ($total < $invoice->grand_total) {
833
                $invoice->status = 'pending';
834
            }
835
            if ($total >= $invoice->grand_total) {
836
                $invoice->status = 'success';
837
            }
838
            if ($total > $invoice->grand_total) {
839
                $user = $invoice->user()->first();
840
                $balance = $total - $invoice->grand_total;
841
                $user->debit = $balance;
842
                $user->save();
843
            }
844
845
            $invoice->save();
846
        } catch (\Exception $ex) {
847
            Bugsnag::notifyException($ex);
848
849
            throw new \Exception($ex->getMessage());
850
        }
851
    }
852
853
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
854
    {
855
        try {
856
            $invoice = $this->invoice->find($invoiceid);
857
            $invoice_status = 'pending';
858
859
            $payment = $this->payment->create([
860
                'invoice_id'     => $invoiceid,
861
                'user_id'        => $invoice->user_id,
862
                'amount'         => $amount,
863
                'payment_method' => $payment_method,
864
                'payment_status' => $payment_status,
865
                'created_at'     => $payment_date,
866
            ]);
867
            $all_payments = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
868
            $total_paid = array_sum($all_payments);
869
            if ($total_paid >= $invoice->grand_total) {
870
                $invoice_status = 'success';
871
            }
872
            if ($invoice) {
873
                $invoice->status = $invoice_status;
874
                $invoice->save();
875
            }
876
877
            return $payment;
878
        } catch (\Exception $ex) {
879
            Bugsnag::notifyException($ex);
880
881
            throw new \Exception($ex->getMessage());
882
        }
883
    }
884
885
    public function payment(Request $request)
886
    {
887
        try {
888
            if ($request->has('invoiceid')) {
889
                $invoice_id = $request->input('invoiceid');
890
                $invoice = $this->invoice->find($invoice_id);
891
                //dd($invoice);
892
                $invoice_status = '';
893
                $payment_status = '';
894
                $payment_method = '';
895
                $domain = '';
896
                if ($invoice) {
897
                    $invoice_status = $invoice->status;
898
                    $items = $invoice->invoiceItem()->first();
899
                    if ($items) {
900
                        $domain = $items->domain;
901
                    }
902
                }
903
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
904
                if ($payment) {
905
                    $payment_status = $payment->payment_status;
906
                    $payment_method = $payment->payment_method;
907
                }
908
909
                return view('themes.default1.invoice.payment', compact('invoice_status', 'payment_status', 'payment_method', 'invoice_id', 'domain', 'invoice'));
910
            }
911
912
            return redirect()->back();
913
        } catch (\Exception $ex) {
914
            Bugsnag::notifyException($ex);
915
916
            return redirect()->back()->with('fails', $ex->getMessage());
917
        }
918
    }
919
920
    public function postPayment($invoiceid, Request $request)
921
    {
922
        $this->validate($request, [
923
            'payment_method' => 'required',
924
            'amount'         => 'required|numeric',
925
            'payment_date'   => 'required|date_format:Y-m-d',
926
        ]);
927
928
        try {
929
            $payment_method = $request->input('payment_method');
930
            $payment_status = 'success';
931
            $payment_date = $request->input('payment_date');
932
            $amount = $request->input('amount');
933
            $payment = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
934
935
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
936
        } catch (\Exception $ex) {
937
            Bugsnag::notifyException($ex);
938
939
            return redirect()->back()->with('fails', $ex->getMessage());
940
        }
941
    }
942
943
    public function postRazorpayPayment($invoiceid, $grand_total)
944
    {
945
        try {
946
            $payment_method = 'Razorpay';
947
            $payment_status = 'success';
948
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
949
            $amount = $grand_total;
950
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
951
952
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
953
        } catch (\Exception $ex) {
954
            return redirect()->back()->with('fails', $ex->getMessage());
955
        }
956
    }
957
958
    public function sendMail($userid, $invoiceid)
959
    {
960
        try {
961
            $invoice = $this->invoice->find($invoiceid);
962
            $number = $invoice->number;
963
            $total = $invoice->grand_total;
964
965
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
966
        } catch (\Exception $ex) {
967
            Bugsnag::notifyException($ex);
968
969
            throw new \Exception($ex->getMessage());
970
        }
971
    }
972
973
    public function deletePayment(Request $request)
974
    {
975
        try {
976
            $ids = $request->input('select');
977
            if (!empty($ids)) {
978
                foreach ($ids as $id) {
979
                    $payment = $this->payment->where('id', $id)->first();
980
                    if ($payment) {
981
                        $invoice = $this->invoice->find($payment->invoice_id);
982
                        if ($invoice) {
983
                            $invoice->status = 'pending';
984
                            $invoice->save();
985
                        }
986
                        $payment->delete();
987
                    } else {
988
                        echo "<div class='alert alert-danger alert-dismissable'>
989
                    <i class='fa fa-ban'></i>
990
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
991
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
992
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
993
                </div>';
994
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
995
                    }
996
                }
997
                echo "<div class='alert alert-success alert-dismissable'>
998
                    <i class='fa fa-ban'></i>
999
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
1000
                    \Lang::get('message.success').'
1001
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
1002
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
1003
                </div>';
1004
            } else {
1005
                echo "<div class='alert alert-danger alert-dismissable'>
1006
                    <i class='fa fa-ban'></i>
1007
                    <b>".\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
0 ignored issues
show
Bug introduced by
Are you sure Lang::get('message.alert') of type null|string|array can be used in concatenation? ( Ignorable by Annotation )

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

1007
                    <b>"./** @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
Loading history...
1008
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
1009
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
1010
                </div>';
1011
                //echo \Lang::get('message.select-a-row');
1012
            }
1013
        } catch (\Exception $e) {
1014
            Bugsnag::notifyException($e);
1015
            echo "<div class='alert alert-danger alert-dismissable'>
1016
                    <i class='fa fa-ban'></i>
1017
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
1018
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
1019
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
1020
                        '.$e->getMessage().'
1021
                </div>';
1022
        }
1023
    }
1024
1025
    public function deleleById($id)
1026
    {
1027
        try {
1028
            $invoice = $this->invoice->find($id);
1029
            if ($invoice) {
1030
                $invoice->delete();
1031
            } else {
1032
                return redirect()->back()->with('fails', 'Can not delete');
1033
            }
1034
1035
            return redirect()->back()->with('success', "Invoice $invoice->number has Deleted Successfully");
1036
        } catch (\Exception $e) {
1037
            Bugsnag::notifyException($e);
1038
1039
            return redirect()->back()->with('fails', $e->getMessage());
1040
        }
1041
    }
1042
1043
    public function paymentDeleleById($id)
1044
    {
1045
        try {
1046
            $invoice_no = '';
1047
            $payment = $this->payment->find($id);
1048
            if ($payment) {
1049
                $invoice_id = $payment->invoice_id;
1050
                $invoice = $this->invoice->find($invoice_id);
1051
                if ($invoice) {
1052
                    $invoice_no = $invoice->number;
1053
                }
1054
                $payment->delete();
1055
            } else {
1056
                return redirect()->back()->with('fails', 'Can not delete');
1057
            }
1058
1059
            return redirect()->back()->with('success', "Payment for invoice no: $invoice_no has Deleted Successfully");
1060
        } catch (\Exception $e) {
1061
            Bugsnag::notifyException($e);
1062
1063
            return redirect()->back()->with('fails', $e->getMessage());
1064
        }
1065
    }
1066
1067
    public function getPrice($price, $price_model)
1068
    {
1069
        if ($price == '') {
1070
            $price = $price_model->sales_price;
1071
            if (!$price) {
1072
                $price = $price_model->price;
1073
            }
1074
        }
1075
1076
        return $price;
1077
    }
1078
1079
    public function getExpiryStatus($start, $end, $now)
1080
    {
1081
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
1082
        if ($whenDateNotSet) {
1083
            return $whenDateNotSet;
1084
        }
1085
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
1086
        if ($whenStartDateSet) {
1087
            return $whenStartDateSet;
1088
        }
1089
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
1090
        if ($whenEndDateSet) {
1091
            return $whenEndDateSet;
1092
        }
1093
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
1094
        if ($whenBothAreSet) {
1095
            return $whenBothAreSet;
1096
        }
1097
    }
1098
1099
    public function checkExecution($invoiceid)
1100
    {
1101
        try {
1102
            $response = false;
1103
            $invoice = $this->invoice->find($invoiceid);
1104
            // dd($invoice);
1105
            $order = $this->order->where('invoice_id', $invoiceid);
1106
            // dd($order);
1107
            $order_invoice_relation = $invoice->orderRelation()->first();
1108
            if ($order_invoice_relation) {
1109
                $response = true;
1110
            } elseif ($order->get()->count() > 0) {
1111
                $response = true;
1112
            }
1113
1114
            return $response;
1115
        } catch (\Exception $e) {
1116
            Bugsnag::notifyException($e);
1117
1118
            return redirect()->back()->with('fails', $e->getMessage());
1119
        }
1120
    }
1121
1122
    public function sendInvoiceMail($userid, $number, $total, $invoiceid)
1123
    {
1124
1125
        //user
1126
        $users = new User();
1127
        $user = $users->find($userid);
1128
        //check in the settings
1129
        $settings = new \App\Model\Common\Setting();
1130
        $setting = $settings->where('id', 1)->first();
1131
        $invoiceurl = $this->invoiceUrl($invoiceid);
1132
        //template
1133
        $templates = new \App\Model\Common\Template();
1134
        $temp_id = $setting->invoice;
1135
        $template = $templates->where('id', $temp_id)->first();
1136
        $from = $setting->email;
1137
        $to = $user->email;
1138
        $subject = $template->name;
1139
        $data = $template->data;
1140
        $replace = [
1141
            'name'       => $user->first_name.' '.$user->last_name,
1142
            'number'     => $number,
1143
            'address'    => $user->address,
1144
            'invoiceurl' => $invoiceurl,
1145
            'content'    => $this->invoiceContent($invoiceid),
1146
            'currency'   => $this->currency($invoiceid),
1147
        ];
1148
        $type = '';
1149
        if ($template) {
1150
            $type_id = $template->type;
1151
            $temp_type = new \App\Model\Common\TemplateType();
1152
            $type = $temp_type->where('id', $type_id)->first()->name;
1153
        }
1154
        //dd($type);
1155
        $templateController = new \App\Http\Controllers\Common\TemplateController();
1156
        $mail = $templateController->mailing($from, $to, $data, $subject, $replace, $type);
1157
1158
        return $mail;
1159
    }
1160
1161
    public function invoiceUrl($invoiceid)
1162
    {
1163
        $url = url('my-invoice/'.$invoiceid);
1164
1165
        return $url;
1166
    }
1167
1168
    public function invoiceContent($invoiceid)
1169
    {
1170
        $invoice = $this->invoice->find($invoiceid);
1171
        $items = $invoice->invoiceItem()->get();
1172
        $content = '';
1173
        if ($items->count() > 0) {
1174
            foreach ($items as $item) {
1175
                $content .= '<tr>'.
1176
                        '<td style="border-bottom: 1px solid#ccc; color: #333; font-family: Arial,sans-serif; font-size: 14px; line-height: 20px; padding: 15px 8px;" valign="top">'.$invoice->number.'</td>'.
1177
                        '<td style="border-bottom: 1px solid#ccc; color: #333; font-family: Arial,sans-serif; font-size: 14px; line-height: 20px; padding: 15px 8px;" valign="top">'.$item->product_name.'</td>'.
1178
                        '<td style="border-bottom: 1px solid#ccc; color: #333; font-family: Arial,sans-serif; font-size: 14px; line-height: 20px; padding: 15px 8px;" valign="top">'.$this->currency($invoiceid).' '.$item->subtotal.'</td>'.
1179
                        '</tr>';
1180
            }
1181
        }
1182
1183
        return $content;
1184
    }
1185
1186
    public function currency($invoiceid)
1187
    {
1188
        $invoice = $this->invoice->find($invoiceid);
1189
        $currency_code = $invoice->currency;
1190
        $cur = ' ';
1191
        if ($invoice->grand_total == 0) {
1192
            return $cur;
1193
        }
1194
        $currency = $this->currency->where('code', $currency_code)->first();
1195
        if ($currency) {
1196
            $cur = $currency->symbol;
1197
            if (!$cur) {
1198
                $cur = $currency->code;
1199
            }
1200
        }
1201
1202
        return $cur;
1203
    }
1204
}
1205