Completed
Push — development ( e90f69...2fb2af )
by Ashutosh
11:39
created

InvoiceController::checkCode()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 19
rs 9.7998
c 0
b 0
f 0
cc 4
nc 8
nop 3
1
<?php
2
3
namespace App\Http\Controllers\Order;
4
5
use App\Http\Controllers\Front\CartController;
6
use App\Http\Controllers\Order\TaxRatesAndCodeExpiryController;
7
use App\Model\Common\Setting;
8
use App\Model\Common\Template;
9
use App\Model\Order\Invoice;
10
use App\Model\Order\InvoiceItem;
11
use App\Model\Order\Order;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, App\Http\Controllers\Order\Order. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
12
use App\Model\Order\Payment;
13
use App\Model\Payment\Currency;
14
use App\Model\Payment\PLan;
15
use App\Model\Payment\PLanPrice;
16
use App\Model\Payment\Promotion;
17
use App\Model\Payment\Tax;
18
use App\Model\Payment\TaxByState;
19
use App\Model\Payment\TaxOption;
20
use App\Model\Product\Price;
21
use App\Model\Product\Product;
22
use App\User;
23
use Bugsnag;
24
use Illuminate\Http\Request;
25
use Input;
26
use Log;
27
28
class InvoiceController extends TaxRatesAndCodeExpiryController
29
{
30
    public $invoice;
31
    public $invoiceItem;
32
    public $user;
33
    public $template;
34
    public $setting;
35
    public $payment;
36
    public $product;
37
    public $price;
38
    public $promotion;
39
    public $currency;
40
    public $tax;
41
    public $tax_option;
42
    public $order;
43
    public $cartController;
44
45
    public function __construct()
46
    {
47
        $this->middleware('auth');
48
        $this->middleware('admin', ['except' => ['pdf']]);
49
50
        $invoice = new Invoice();
51
        $this->invoice = $invoice;
52
53
        $invoiceItem = new InvoiceItem();
54
        $this->invoiceItem = $invoiceItem;
55
56
        $user = new User();
57
        $this->user = $user;
58
59
        $template = new Template();
60
        $this->template = $template;
61
62
        $seting = new Setting();
63
        $this->setting = $seting;
64
65
        $payment = new Payment();
66
        $this->payment = $payment;
67
68
        $product = new Product();
69
        $this->product = $product;
70
71
        $price = new Price();
72
        $this->price = $price;
73
74
        $promotion = new Promotion();
75
        $this->promotion = $promotion;
76
77
        $currency = new Currency();
78
        $this->currency = $currency;
79
80
        $tax = new Tax();
81
        $this->tax = $tax;
82
83
        $tax_option = new TaxOption();
84
        $this->tax_option = $tax_option;
85
86
        $order = new Order();
87
        $this->order = $order;
88
89
        $tax_by_state = new TaxByState();
90
        $this->tax_by_state = new $tax_by_state();
91
92
        $cartController = new CartController();
93
        $this->cartController = $cartController;
94
    }
95
96
    public function index()
97
    {
98
        try {
99
            //dd($this->invoice->get());
100
            return view('themes.default1.invoice.index');
101
        } catch (\Exception $ex) {
102
            Bugsnag::notifyException($ex);
103
104
            return redirect()->back()->with('fails', $ex->getMessage());
105
        }
106
    }
107
108
    public function getInvoices()
109
    {
110
        $invoice = \DB::table('invoices');
111
        // $new_invoice = $invoice->select('id', 'user_id', 'number', 'date', 'grand_total', 'status', 'created_at');
112
113
        return \DataTables::of($invoice->get())
114
                        ->addColumn('checkbox', function ($model) {
115
                            return "<input type='checkbox' class='invoice_checkbox' value=".$model->id.' name=select[] id=check>';
116
                        })
117
                        ->addColumn('user_id', function ($model) {
118
                            $first = $this->user->where('id', $model->user_id)->first()->first_name;
119
                            $last = $this->user->where('id', $model->user_id)->first()->last_name;
120
                            $id = $this->user->where('id', $model->user_id)->first()->id;
121
122
                            return '<a href='.url('clients/'.$id).'>'.ucfirst($first).' '.ucfirst($last).'</a>';
123
                        })
124
                         ->addColumn('number', function ($model) {
125
                             return ucfirst($model->number);
126
                         })
127
128
                        ->addColumn('date', function ($model) {
129
                            $date = date_create($model->created_at);
130
131
                            return "<span style='display:none'>$model->id</span>".$date->format('l, F j, Y H:m');
132
                        })
133
                         ->addColumn('grand_total', function ($model) {
134
                             return ucfirst($model->number);
135
                         })
136
                          ->addColumn('status', function ($model) {
137
                              return ucfirst($model->status);
138
                          })
139
140
                        ->addColumn('action', function ($model) {
141
                            $action = '';
142
143
                            $check = $this->checkExecution($model->id);
144
                            if ($check == false) {
145
                                $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>";
146
                            }
147
148
                            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>"
149
                                    ."   $action";
150
                        })
151
152
                         ->rawColumns(['checkbox', 'user_id', 'number', 'date', 'grand_total', 'status', 'action'])
153
                        ->make(true);
154
    }
155
156
    public function show(Request $request)
157
    {
158
        try {
159
            $id = $request->input('invoiceid');
160
            $invoice = $this->invoice->where('id', $id)->first();
161
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
162
            $user = $this->user->find($invoice->user_id);
163
164
            return view('themes.default1.invoice.show', compact('invoiceItems', 'invoice', 'user'));
165
        } catch (\Exception $ex) {
166
            Bugsnag::notifyException($ex);
167
168
            return redirect()->back()->with('fails', $ex->getMessage());
169
        }
170
    }
171
172
    /**
173
     * not in use case.
174
     *
175
     * @param Request $request
176
     *
177
     * @return type
178
     */
179
    public function generateById(Request $request)
180
    {
181
        try {
182
            $clientid = $request->input('clientid');
183
            if ($clientid) {
184
                $user = new User();
185
                $user = $user->where('id', $clientid)->first();
186
                if (!$user) {
187
                    return redirect()->back()->with('fails', 'Invalid user');
188
                }
189
            } else {
190
                $user = '';
191
            }
192
            $products = $this->product->where('id', '!=', 1)->pluck('name', 'id')->toArray();
193
            $currency = $this->currency->pluck('name', 'code')->toArray();
194
195
            return view('themes.default1.invoice.generate', compact('user', 'products', 'currency'));
196
        } catch (\Exception $ex) {
197
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
198
            app('log')->info($ex->getMessage());
199
            Bugsnag::notifyException($ex);
200
201
            return redirect()->back()->with('fails', $ex->getMessage());
202
        }
203
    }
204
205
    public function invoiceGenerateByForm(Request $request, $user_id = '')
206
    {
207
        $qty = 1;
208
209
        try {
210
            if ($user_id == '') {
211
                $user_id = \Request::input('user');
212
            }
213
            $productid = $request->input('product');
214
            $code = $request->input('code');
215
            $total = $request->input('price');
216
            $plan = $request->input('plan');
217
            $description = $request->input('description');
218
            if ($request->has('domain')) {
219
                $domain = $request->input('domain');
220
                $this->setDomain($productid, $domain);
221
            }
222
            $controller = new \App\Http\Controllers\Front\CartController();
223
            $currency = $controller->currency($user_id);
224
            $number = rand(11111111, 99999999);
225
            $date = \Carbon\Carbon::now();
226
            $product = $this->product->find($productid);
227
            $cost = $controller->cost($productid, $user_id, $plan);
228
            if ($cost != $total) {
229
                $grand_total = $total;
230
            }
231
            $grand_total = $this->getGrandTotal($code, $total, $cost, $productid, $currency);
232
            $grand_total = $qty * $grand_total;
233
234
            $tax = $this->checkTax($product->id, $user_id);
235
            $tax_name = '';
236
            $tax_rate = '';
237
            if (!empty($tax)) {
238
                $tax_name = $tax[0];
239
                $tax_rate = $tax[1];
240
            }
241
242
            $grand_total = $this->calculateTotal($tax_rate, $grand_total);
243
            $grand_total = \App\Http\Controllers\Front\CartController::rounding($grand_total);
244
245
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'currency' => $currency, 'status' => 'pending', 'description' => $description]);
246
247
            $items = $this->createInvoiceItemsByAdmin($invoice->id, $productid, $code, $total, $currency, $qty, $plan, $user_id, $tax_name, $tax_rate);
248
            // dd($items);
249
            $result = $this->getMessage($items, $user_id);
250
        } catch (\Exception $ex) {
251
            app('log')->useDailyFiles(storage_path().'/laravel.log');
252
            app('log')->info($ex->getMessage());
253
            Bugsnag::notifyException($ex);
254
            $result = ['fails' => $ex->getMessage()];
255
        }
256
257
        return response()->json(compact('result'));
258
    }
259
260
    /*
261
    *Edit Invoice Total.
262
    */
263
    public function invoiceTotalChange(Request $request)
264
    {
265
        $total = $request->input('total');
266
        $number = $request->input('number');
267
        $invoiceId = Invoice::where('number', $number)->value('id');
268
        $invoiceItem = $this->invoiceItem->where('invoice_id', $invoiceId)->update(['subtotal'=>$total]);
269
        $invoices = $this->invoice->where('number', $number)->update(['grand_total'=>$total]);
270
    }
271
272
    public function sendmailClientAgent($userid, $invoiceid)
273
    {
274
        try {
275
            $agent = \Input::get('agent');
276
            $client = \Input::get('client');
277
            if ($agent == 1) {
278
                $id = \Auth::user()->id;
279
                $this->sendMail($id, $invoiceid);
280
            }
281
            if ($client == 1) {
282
                $this->sendMail($userid, $invoiceid);
283
            }
284
        } catch (\Exception $ex) {
285
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
286
            app('log')->info($ex->getMessage());
287
            Bugsnag::notifyException($ex);
288
289
            throw new \Exception($ex->getMessage());
290
        }
291
    }
292
293
    /**
294
     * Generate invoice.
295
     *
296
     * @throws \Exception
297
     */
298
    public function generateInvoice()
299
    {
300
        try {
301
            // dd(\Cart::getContent());
302
            $tax_rule = new \App\Model\Payment\TaxOption();
303
            $rule = $tax_rule->findOrFail(1);
304
            $rounding = $rule->rounding;
305
306
            $user_id = \Auth::user()->id;
307
            if (\Auth::user()->currency == 'INR') {
308
                $grand_total = \Cart::getSubTotal();
309
            } else {
310
                foreach (\Cart::getContent() as $cart) {
311
312
                    // $grand_total = $cart->price;
313
                    $grand_total = \Cart::getSubTotal();
314
                }
315
            }
316
            // dd($grand_total);
317
318
            $number = rand(11111111, 99999999);
319
            $date = \Carbon\Carbon::now();
320
321
            if ($rounding == 1) {
322
                $grand_total = round($grand_total);
323
            }
324
            $content = \Cart::getContent();
325
            $attributes = [];
326
            foreach ($content as $key => $item) {
327
                $attributes[] = $item->attributes;
328
            }
329
330
            $symbol = $attributes[0]['currency'][0]['code'];
331
            //dd($symbol);
332
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'status' => 'pending', 'currency' => $symbol]);
333
334
            foreach (\Cart::getContent() as $cart) {
335
                $this->createInvoiceItems($invoice->id, $cart);
336
            }
337
            //$this->sendMail($user_id, $invoice->id);
338
            return $invoice;
339
        } catch (\Exception $ex) {
340
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
341
            app('log')->info($ex->getMessage());
342
            Bugsnag::notifyException($ex);
343
344
            throw new \Exception('Can not Generate Invoice');
345
        }
346
    }
347
348
    public function createInvoiceItems($invoiceid, $cart)
349
    {
350
        try {
351
            $planid = 0;
352
            $product_name = $cart->name;
353
            $regular_price = $cart->price;
354
            $quantity = $cart->quantity;
355
            $domain = $this->domain($cart->id);
356
            $cart_cont = new \App\Http\Controllers\Front\CartController();
357
            if ($cart_cont->checkPlanSession() == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
358
                $planid = \Session::get('plan');
359
            }
360
            $user_currency = \Auth::user()->currency;
361
            $subtotal = $this->getSubtotal($user_currency, $cart);
362
363
            $tax_name = '';
364
            $tax_percentage = '';
365
366
            foreach ($cart->attributes['tax'] as $tax) {
367
                $tax_name .= $tax['name'].',';
368
                $tax_percentage .= $tax['rate'].',';
369
            }
370
371
            $invoiceItem = $this->invoiceItem->create([
372
                'invoice_id'     => $invoiceid,
373
                'product_name'   => $product_name,
374
                'regular_price'  => $regular_price,
375
                'quantity'       => $quantity,
376
                'tax_name'       => $tax_name,
377
                'tax_percentage' => $tax_percentage,
378
                'subtotal'       => $subtotal,
379
                'domain'         => $domain,
380
                'plan_id'        => $planid,
381
            ]);
382
383
            return $invoiceItem;
384
        } catch (\Exception $ex) {
385
            Bugsnag::notifyException($ex);
386
387
            throw new \Exception('Can not create Invoice Items');
388
        }
389
    }
390
391
    public function doPayment($payment_method, $invoiceid, $amount, $parent_id = '', $userid = '', $payment_status = 'pending')
392
    {
393
        try {
394
            if ($amount > 0) {
395
                if ($userid == '') {
396
                    $userid = \Auth::user()->id;
397
                }
398
                if ($amount == 0) {
399
                    $payment_status = 'success';
400
                }
401
                $this->payment->create([
402
                    'parent_id'      => $parent_id,
403
                    'invoice_id'     => $invoiceid,
404
                    'user_id'        => $userid,
405
                    'amount'         => $amount,
406
                    'payment_method' => $payment_method,
407
                    'payment_status' => $payment_status,
408
                ]);
409
                $this->updateInvoice($invoiceid);
410
            }
411
        } catch (\Exception $ex) {
412
            Bugsnag::notifyException($ex);
413
414
            throw new \Exception($ex->getMessage());
415
        }
416
    }
417
418
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code, $price, $currency, $qty, $planid = '', $userid = '', $tax_name = '', $tax_rate = '')
419
    {
420
        try {
421
            $discount = '';
422
            $mode = '';
423
            $product = $this->product->findOrFail($productid);
424
            $price_model = $this->price->where('product_id', $product->id)->where('currency', $currency)->first();
425
            $price = $this->getPrice($price, $price_model);
426
            $subtotal = $qty * $price;
427
            //dd($subtotal);
428
            if ($code) {
429
                $subtotal = $this->checkCode($code, $productid, $currency);
430
                $mode = 'coupon';
431
                $discount = $price - $subtotal;
432
            }
433
            $userid = \Auth::user()->id;
434
435
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
436
437
            $domain = $this->domain($productid);
438
            $items = $this->invoiceItem->create([
439
                'invoice_id'     => $invoiceid,
440
                'product_name'   => $product->name,
441
                'regular_price'  => $price,
442
                'quantity'       => $qty,
443
                'discount'       => $discount,
444
                'discount_mode'  => $mode,
445
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
446
                'tax_name'       => $tax_name,
447
                'tax_percentage' => $tax_rate,
448
                'domain'         => $domain,
449
                'plan_id'        => $planid,
450
            ]);
451
452
            return $items;
453
        } catch (\Exception $ex) {
454
            Bugsnag::notifyException($ex);
455
456
            return redirect()->back()->with('fails', $ex->getMessage());
457
        }
458
    }
459
460
    public function findCostAfterDiscount($promoid, $productid, $currency)
461
    {
462
        try {
463
            $promotion = $this->promotion->findOrFail($promoid);
464
            $product = $this->product->findOrFail($productid);
465
            $promotion_type = $promotion->type;
466
            $promotion_value = $promotion->value;
467
            $planId = Plan::where('product', $productid)->pluck('id')->first();
468
            // dd($planId);
469
            $product_price = PlanPrice::where('plan_id', $planId)->where('currency', $currency)->pluck('add_price')->first();
470
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
471
472
            return $updated_price;
473
        } catch (\Exception $ex) {
474
            Bugsnag::notifyException($ex);
475
476
            throw new \Exception(\Lang::get('message.find-discount-error'));
477
        }
478
    }
479
480
    public function findCost($type, $value, $price, $productid)
481
    {
482
        try {
483
            switch ($type) {
484
                case 1:
485
                    $percentage = $price * ($value / 100);
486
487
                     return $price - $percentage;
488
                case 2:
489
                    return $price - $value;
490
                case 3:
491
                    return $value;
492
                case 4:
493
                    return 0;
494
            }
495
        } catch (\Exception $ex) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $ex) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
496
            Bugsnag::notifyException($ex);
497
498
            throw new \Exception(\Lang::get('message.find-cost-error'));
499
        }
500
    }
501
502
    public function checkNumberOfUses($code)
503
    {
504
        try {
505
            $promotion = $this->promotion->where('code', $code)->first();
506
            $uses = $promotion->uses;
507
            if ($uses == 0) {
508
                return 'success';
509
            }
510
            $used_number = $this->invoice->where('coupon_code', $code)->count();
511
            if ($uses >= $used_number) {
512
                return 'success';
513
            } else {
514
                return 'fails';
515
            }
516
        } catch (\Exception $ex) {
517
            Bugsnag::notifyException($ex);
518
519
            throw new \Exception(\Lang::get('message.find-cost-error'));
520
        }
521
    }
522
523
524
    public function checkCode($code, $productid, $currency)
525
    {
526
        try {
527
            if ($code != '') {
528
                $promo = $this->getPromotionDetails($code);
529
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
530
                return $value;
531
            } else {
532
                $product = $this->product->find($productid);
533
                $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...
534
                if (!$price) {
535
                    $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...
536
                }
537
538
                return $price;
539
            }
540
        } catch (\Exception $ex) {
541
            Bugsnag::notifyException($ex);
542
            throw new \Exception(\Lang::get('message.check-code-error'));
543
        }
544
    }
545
546
547
    public function getPromotionDetails($code)
548
    {
549
        $promo = $this->promotion->where('code', $code)->first();
550
        //check promotion code is valid
551
        if (!$promo) {
552
            throw new \Exception(\Lang::get('message.no-such-code'));
553
        }
554
        $relation = $promo->relation()->get();
555
        //check the relation between code and product
556
        if (count($relation) == 0) {
557
            throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
558
        }
559
        //check the usess
560
        $uses = $this->checkNumberOfUses($code);
561
        //dd($uses);
562
        if ($uses != 'success') {
563
            throw new \Exception(\Lang::get('message.usage-of-code-completed'));
564
        }
565
        //check for the expiry date
566
        $expiry = $this->checkExpiry($code);
567
        //dd($expiry);
568
        if ($expiry != 'success') {
569
            throw new \Exception(\Lang::get('message.usage-of-code-expired'));
570
        }
571
        return $promo;
572
    }
573
574
    public function checkExpiry($code = '')
575
    {
576
        try {
577
            if ($code != '') {
578
                $promotion = $this->promotion->where('code', $code)->first();
579
                $start = $promotion->start;
580
                $end = $promotion->expiry;
581
                //dd($end);
582
                $now = \Carbon\Carbon::now();
583
                $getExpiryStatus = $this->getExpiryStatus($start, $end, $now);
584
585
                return $getExpiryStatus;
586
            } else {
587
            }
588
        } catch (\Exception $ex) {
589
            throw new \Exception(\Lang::get('message.check-expiry'));
590
        }
591
    }
592
593
    public function checkTax($productid, $userid)
594
    {
595
        try {
596
            $taxs = [];
597
            $taxs[0] = ['name' => 'null', 'rate' => 0];
598
            $geoip_state = User::where('id', $userid)->pluck('state')->first();
599
            $geoip_country = User::where('id', $userid)->pluck('country')->first();
600
            $product = $this->product->findOrFail($productid);
601
            $cartController = new CartController();
602
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
603
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
604
                    $taxs = $this->getTaxWhenEnable($productid, $taxs[0], $userid);
605
                } elseif ($this->tax_option->tax_enable == 0) {//if tax_enable is 0
606
607
                    $taxClassId = Tax::where('country', '')->where('state', 'Any State')
608
                     ->pluck('tax_classes_id')->first(); //In case of India when other tax is available and tax is not enabled
609
                    if ($taxClassId) {
610
                        $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
611
                    } 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)
612
613
                        $taxClassId = Tax::where('state', $geoip_state)->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
614
                        if ($taxClassId) { //if state equals the user State
615
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
616
                        }
617
                        $taxs = ([$taxes[0]['name'], $taxes[0]['rate']]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $taxes does not exist. Did you maybe mean $taxs?
Loading history...
618
                    }
619
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
620
                } else {
621
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
622
                }
623
            }
624
625
            return $taxs;
626
        } catch (\Exception $ex) {
627
            throw new \Exception(\Lang::get('message.check-tax-error'));
628
        }
629
    }
630
631
    public function getRate($productid, $taxs, $userid)
632
    {
633
        $tax_attribute = [];
634
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
635
        $tax_value = '0';
636
637
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
638
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
639
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
640
        $origin_state = $this->setting->first()->state; //Get the State of origin
641
        $cartController = new CartController();
642
643
        $rate = 0;
644
        $name1 = 'CGST';
645
        $name2 = 'SGST';
646
        $name3 = 'IGST';
647
        $name4 = 'UTGST';
648
        $c_gst = 0;
649
        $s_gst = 0;
650
        $i_gst = 0;
651
        $ut_gst = 0;
652
        $state_code = '';
653
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
654
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
655
            $taxes = $tax['taxes'];
656
            $value = $tax['value'];
657
        } else {//If user from other Country
658
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
659
            $taxes = $tax['taxes'];
660
            $value = $tax['value'];
661
            $rate = $tax['rate'];
662
        }
663
664
        foreach ($taxes as $key => $tax) {
665
            if ($taxes[0]) {
666
                $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];
667
668
                $rate = $tax->rate;
669
670
                $tax_value = $value;
671
            } else {
672
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
673
                $tax_value = '0%';
674
            }
675
        }
676
677
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
678
    }
679
680
    public function pdf(Request $request)
681
    {
682
        try {
683
            $id = $request->input('invoiceid');
684
            if (!$id) {
685
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
686
            }
687
            $invoice = $this->invoice->where('id', $id)->first();
688
            if (!$invoice) {
689
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
690
            }
691
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
692
            if ($invoiceItems->count() == 0) {
693
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
694
            }
695
            $user = $this->user->find($invoice->user_id);
696
            if (!$user) {
697
                return redirect()->back()->with('fails', 'No User');
698
            }
699
            //return view('themes.default1.invoice.pdfinvoice', compact('invoiceItems', 'invoice', 'user'));
700
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
701
            // $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user'));
702
703
            return $pdf->download($user->first_name.'-invoice.pdf');
704
        } catch (\Exception $ex) {
705
            Bugsnag::notifyException($ex);
706
707
            return redirect()->back()->with('fails', $ex->getMessage());
708
        }
709
    }
710
711
    /**
712
     * Remove the specified resource from storage.
713
     *
714
     * @param int $id
715
     *
716
     * @return Response
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\Order\Response was not found. Did you mean Response? If so, make sure to prefix the type with \.
Loading history...
717
     */
718
    public function destroy(Request $request)
719
    {
720
        try {
721
            $ids = $request->input('select');
722
            if (!empty($ids)) {
723
                foreach ($ids as $id) {
724
                    $invoice = $this->invoice->where('id', $id)->first();
725
                    if ($invoice) {
726
                        $invoice->delete();
727
                    } else {
728
                        echo "<div class='alert alert-danger alert-dismissable'>
729
                    <i class='fa fa-ban'></i>
730
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
731
                    \Lang::get('message.failed').'
732
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
733
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
734
                </div>';
735
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
736
                    }
737
                }
738
                echo "<div class='alert alert-success alert-dismissable'>
739
                    <i class='fa fa-ban'></i>
740
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
741
                    \Lang::get('message.success').'
742
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
743
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
744
                </div>';
745
            } else {
746
                echo "<div class='alert alert-danger alert-dismissable'>
747
                    <i class='fa fa-ban'></i>
748
                    <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

748
                    <b>"./** @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
Loading history...
749
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
750
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
751
                </div>';
752
                //echo \Lang::get('message.select-a-row');
753
            }
754
        } catch (\Exception $e) {
755
            echo "<div class='alert alert-danger alert-dismissable'>
756
                    <i class='fa fa-ban'></i>
757
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
758
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
759
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
760
                        '.$e->getMessage().'
761
                </div>';
762
        }
763
    }
764
765
    public function setDomain($productid, $domain)
766
    {
767
        try {
768
            if (\Session::has('domain'.$productid)) {
769
                \Session::forget('domain'.$productid);
770
            }
771
            \Session::put('domain'.$productid, $domain);
772
        } catch (\Exception $ex) {
773
            Bugsnag::notifyException($ex);
774
775
            throw new \Exception($ex->getMessage());
776
        }
777
    }
778
779
    public function domain($id)
780
    {
781
        try {
782
            if (\Session::has('domain'.$id)) {
783
                $domain = \Session::get('domain'.$id);
784
            } else {
785
                $domain = '';
786
            }
787
788
            return $domain;
789
        } catch (\Exception $ex) {
790
            Bugsnag::notifyException($ex);
791
        }
792
    }
793
794
    public function updateInvoice($invoiceid)
795
    {
796
        try {
797
            $invoice = $this->invoice->findOrFail($invoiceid);
798
            $payment = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
799
            $total = array_sum($payment);
800
            if ($total < $invoice->grand_total) {
801
                $invoice->status = 'pending';
802
            }
803
            if ($total >= $invoice->grand_total) {
804
                $invoice->status = 'success';
805
            }
806
            if ($total > $invoice->grand_total) {
807
                $user = $invoice->user()->first();
808
                $balance = $total - $invoice->grand_total;
809
                $user->debit = $balance;
810
                $user->save();
811
            }
812
813
            $invoice->save();
814
        } catch (\Exception $ex) {
815
            Bugsnag::notifyException($ex);
816
817
            throw new \Exception($ex->getMessage());
818
        }
819
    }
820
821
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
822
    {
823
        try {
824
            $invoice = $this->invoice->find($invoiceid);
825
            $invoice_status = 'pending';
826
827
            $payment = $this->payment->create([
828
                'invoice_id'     => $invoiceid,
829
                'user_id'        => $invoice->user_id,
830
                'amount'         => $amount,
831
                'payment_method' => $payment_method,
832
                'payment_status' => $payment_status,
833
                'created_at'     => $payment_date,
834
            ]);
835
            $all_payments = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->pluck('amount')->toArray();
836
            $total_paid = array_sum($all_payments);
837
            if ($total_paid >= $invoice->grand_total) {
838
                $invoice_status = 'success';
839
            }
840
            if ($invoice) {
841
                $invoice->status = $invoice_status;
842
                $invoice->save();
843
            }
844
845
            return $payment;
846
        } catch (\Exception $ex) {
847
            Bugsnag::notifyException($ex);
848
849
            throw new \Exception($ex->getMessage());
850
        }
851
    }
852
853
    public function payment(Request $request)
854
    {
855
        try {
856
            if ($request->has('invoiceid')) {
857
                $invoice_id = $request->input('invoiceid');
858
                $invoice = $this->invoice->find($invoice_id);
859
                //dd($invoice);
860
                $invoice_status = '';
861
                $payment_status = '';
862
                $payment_method = '';
863
                $domain = '';
864
                if ($invoice) {
865
                    $invoice_status = $invoice->status;
866
                    $items = $invoice->invoiceItem()->first();
867
                    if ($items) {
868
                        $domain = $items->domain;
869
                    }
870
                }
871
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
872
                if ($payment) {
873
                    $payment_status = $payment->payment_status;
874
                    $payment_method = $payment->payment_method;
875
                }
876
877
                return view('themes.default1.invoice.payment', compact('invoice_status', 'payment_status', 'payment_method', 'invoice_id', 'domain', 'invoice'));
878
            }
879
880
            return redirect()->back();
881
        } catch (\Exception $ex) {
882
            Bugsnag::notifyException($ex);
883
884
            return redirect()->back()->with('fails', $ex->getMessage());
885
        }
886
    }
887
888
    public function postPayment($invoiceid, Request $request)
889
    {
890
        $this->validate($request, [
891
            'payment_method' => 'required',
892
            'amount'         => 'required|numeric',
893
            'payment_date'   => 'required|date_format:Y-m-d',
894
        ]);
895
896
        try {
897
            $payment_method = $request->input('payment_method');
898
            $payment_status = 'success';
899
            $payment_date = $request->input('payment_date');
900
            $amount = $request->input('amount');
901
            $payment = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
902
            if ($payment) {
0 ignored issues
show
introduced by
$payment is of type App\Model\Order\Payment, thus it always evaluated to true.
Loading history...
903
                return redirect()->back()->with('success', 'Payment Accepted Successfully');
904
            }
905
        } catch (\Exception $ex) {
906
            Bugsnag::notifyException($ex);
907
908
            return redirect()->back()->with('fails', $ex->getMessage());
909
        }
910
    }
911
912
    public function postRazorpayPayment($invoiceid, $grand_total)
913
    {
914
        try {
915
            $payment_method = 'Razorpay';
916
            $payment_status = 'success';
917
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
918
            $amount = $grand_total;
919
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount);
920
921
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
922
        } catch (\Exception $ex) {
923
            return redirect()->back()->with('fails', $ex->getMessage());
924
        }
925
    }
926
927
    public function sendMail($userid, $invoiceid)
928
    {
929
        try {
930
            $invoice = $this->invoice->find($invoiceid);
931
            $number = $invoice->number;
932
            $total = $invoice->grand_total;
933
934
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
935
        } catch (\Exception $ex) {
936
            Bugsnag::notifyException($ex);
937
938
            throw new \Exception($ex->getMessage());
939
        }
940
    }
941
942
    public function deletePayment(Request $request)
943
    {
944
        try {
945
            $ids = $request->input('select');
946
            if (!empty($ids)) {
947
                foreach ($ids as $id) {
948
                    $payment = $this->payment->where('id', $id)->first();
949
                    if ($payment) {
950
                        $invoice = $this->invoice->find($payment->invoice_id);
951
                        if ($invoice) {
952
                            $invoice->status = 'pending';
953
                            $invoice->save();
954
                        }
955
                        $payment->delete();
956
                    } else {
957
                        echo "<div class='alert alert-danger alert-dismissable'>
958
                    <i class='fa fa-ban'></i>
959
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
960
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
961
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
962
                </div>';
963
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
964
                    }
965
                }
966
                echo "<div class='alert alert-success alert-dismissable'>
967
                    <i class='fa fa-ban'></i>
968
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
969
                    \Lang::get('message.success').'
970
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
971
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
972
                </div>';
973
            } else {
974
                echo "<div class='alert alert-danger alert-dismissable'>
975
                    <i class='fa fa-ban'></i>
976
                    <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

976
                    <b>"./** @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
Loading history...
977
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
978
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
979
                </div>';
980
                //echo \Lang::get('message.select-a-row');
981
            }
982
        } catch (\Exception $e) {
983
            Bugsnag::notifyException($e);
984
            echo "<div class='alert alert-danger alert-dismissable'>
985
                    <i class='fa fa-ban'></i>
986
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
987
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
988
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
989
                        '.$e->getMessage().'
990
                </div>';
991
        }
992
    }
993
994
    public function deleleById($id)
995
    {
996
        try {
997
            $invoice = $this->invoice->find($id);
998
            if ($invoice) {
999
                $invoice->delete();
1000
            } else {
1001
                return redirect()->back()->with('fails', 'Can not delete');
1002
            }
1003
1004
            return redirect()->back()->with('success', "Invoice $invoice->number has Deleted Successfully");
1005
        } catch (\Exception $e) {
1006
            Bugsnag::notifyException($e);
1007
1008
            return redirect()->back()->with('fails', $e->getMessage());
1009
        }
1010
    }
1011
1012
    public function paymentDeleleById($id)
1013
    {
1014
        try {
1015
            $invoice_no = '';
1016
            $payment = $this->payment->find($id);
1017
            if ($payment) {
1018
                $invoice_id = $payment->invoice_id;
1019
                $invoice = $this->invoice->find($invoice_id);
1020
                if ($invoice) {
1021
                    $invoice_no = $invoice->number;
1022
                }
1023
                $payment->delete();
1024
            } else {
1025
                return redirect()->back()->with('fails', 'Can not delete');
1026
            }
1027
1028
            return redirect()->back()->with('success', "Payment for invoice no: $invoice_no has Deleted Successfully");
1029
        } catch (\Exception $e) {
1030
            Bugsnag::notifyException($e);
1031
1032
            return redirect()->back()->with('fails', $e->getMessage());
1033
        }
1034
    }
1035
1036
    public function checkExecution($invoiceid)
1037
    {
1038
        try {
1039
            $response = false;
1040
            $invoice = $this->invoice->find($invoiceid);
1041
            // dd($invoice);
1042
            $order = $this->order->where('invoice_id', $invoiceid);
1043
            // dd($order);
1044
            $order_invoice_relation = $invoice->orderRelation()->first();
1045
            if ($order_invoice_relation) {
1046
                $response = true;
1047
            } elseif ($order->get()->count() > 0) {
1048
                $response = true;
1049
            }
1050
1051
            return $response;
1052
        } catch (\Exception $e) {
1053
            Bugsnag::notifyException($e);
1054
1055
            return redirect()->back()->with('fails', $e->getMessage());
1056
        }
1057
    }
1058
1059
    public function sendInvoiceMail($userid, $number, $total, $invoiceid)
1060
    {
1061
1062
        //user
1063
        $users = new User();
1064
        $user = $users->find($userid);
1065
        //check in the settings
1066
        $settings = new \App\Model\Common\Setting();
1067
        $setting = $settings->where('id', 1)->first();
1068
        $invoiceurl = $this->invoiceUrl($invoiceid);
1069
        //template
1070
        $templates = new \App\Model\Common\Template();
1071
        $temp_id = $setting->invoice;
1072
        $template = $templates->where('id', $temp_id)->first();
1073
        $from = $setting->email;
1074
        $to = $user->email;
1075
        $subject = $template->name;
1076
        $data = $template->data;
1077
        $replace = [
1078
            'name'       => $user->first_name.' '.$user->last_name,
1079
            'number'     => $number,
1080
            'address'    => $user->address,
1081
            'invoiceurl' => $invoiceurl,
1082
            'content'    => $this->invoiceContent($invoiceid),
1083
            'currency'   => $this->currency($invoiceid),
1084
        ];
1085
        $type = '';
1086
        if ($template) {
1087
            $type_id = $template->type;
1088
            $temp_type = new \App\Model\Common\TemplateType();
1089
            $type = $temp_type->where('id', $type_id)->first()->name;
1090
        }
1091
        //dd($type);
1092
        $templateController = new \App\Http\Controllers\Common\TemplateController();
1093
        $mail = $templateController->mailing($from, $to, $data, $subject, $replace, $type);
1094
1095
        return $mail;
1096
    }
1097
1098
    public function invoiceUrl($invoiceid)
1099
    {
1100
        $url = url('my-invoice/'.$invoiceid);
1101
1102
        return $url;
1103
    }
1104
1105
    public function invoiceContent($invoiceid)
1106
    {
1107
        $invoice = $this->invoice->find($invoiceid);
1108
        $items = $invoice->invoiceItem()->get();
1109
        $content = '';
1110
        if ($items->count() > 0) {
1111
            foreach ($items as $item) {
1112
                $content .= '<tr>'.
1113
                        '<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>'.
1114
                        '<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>'.
1115
                        '<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>'.
1116
                        '</tr>';
1117
            }
1118
        }
1119
1120
        return $content;
1121
    }
1122
1123
    public function currency($invoiceid)
1124
    {
1125
        $invoice = $this->invoice->find($invoiceid);
1126
        $currency_code = $invoice->currency;
1127
        $cur = ' ';
1128
        if ($invoice->grand_total == 0) {
1129
            return $cur;
1130
        }
1131
        $currency = $this->currency->where('code', $currency_code)->first();
1132
        if ($currency) {
1133
            $cur = $currency->symbol;
1134
            if (!$cur) {
1135
                $cur = $currency->code;
1136
            }
1137
        }
1138
1139
        return $cur;
1140
    }
1141
}
1142