Completed
Push — development ( 26d9cf...abf04d )
by Ashutosh
09:30
created

InvoiceController   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 599
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 53
eloc 395
dl 0
loc 599
rs 6.96
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 49 1
A generateById() 0 22 4
B getInvoices() 0 82 2
A index() 0 19 2
A sendMail() 0 12 2
A createInvoiceItems() 0 45 5
A show() 0 15 2
B checkTax() 0 45 8
A setDomain() 0 11 3
A getCodeFromSession() 0 9 2
B invoiceGenerateByForm() 0 69 6
A getRate() 0 50 4
B generateInvoice() 0 44 7
A createInvoiceItemsByAdmin() 0 47 5

How to fix   Complexity   

Complex Class

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

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

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

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\Promotion;
15
use App\Model\Payment\Tax;
16
use App\Model\Payment\TaxByState;
17
use App\Model\Payment\TaxOption;
18
use App\Model\Product\Price;
19
use App\Model\Product\Product;
20
use App\Traits\CoupCodeAndInvoiceSearch;
21
use App\Traits\PaymentsAndInvoices;
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
    use  CoupCodeAndInvoiceSearch;
0 ignored issues
show
introduced by
The trait App\Traits\CoupCodeAndInvoiceSearch requires some properties which are not provided by App\Http\Controllers\Order\InvoiceController: $grand_total, $id, $created_at, $type, $value
Loading history...
31
    use  PaymentsAndInvoices;
0 ignored issues
show
introduced by
The trait App\Traits\PaymentsAndInvoices requires some properties which are not provided by App\Http\Controllers\Order\InvoiceController: $grand_total, $first_name, $planPrice, $domain, $amount, $payment_method, $product_quantity, $id, $amt_to_credit, $planRelation, $no_of_agents
Loading history...
32
33
    public $invoice;
34
    public $invoiceItem;
35
    public $user;
36
    public $template;
37
    public $setting;
38
    public $payment;
39
    public $product;
40
    public $price;
41
    public $promotion;
42
    public $currency;
43
    public $tax;
44
    public $tax_option;
45
    public $order;
46
    public $cartController;
47
48
    public function __construct()
49
    {
50
        $this->middleware('auth');
51
        $this->middleware('admin', ['except' => ['pdf']]);
52
53
        $invoice = new Invoice();
54
        $this->invoice = $invoice;
55
56
        $invoiceItem = new InvoiceItem();
57
        $this->invoiceItem = $invoiceItem;
58
59
        $user = new User();
60
        $this->user = $user;
61
62
        $template = new Template();
63
        $this->template = $template;
64
65
        $seting = new Setting();
66
        $this->setting = $seting;
67
68
        $payment = new Payment();
69
        $this->payment = $payment;
70
71
        $product = new Product();
72
        $this->product = $product;
73
74
        $price = new Price();
75
        $this->price = $price;
76
77
        $promotion = new Promotion();
78
        $this->promotion = $promotion;
79
80
        $currency = new Currency();
81
        $this->currency = $currency;
82
83
        $tax = new Tax();
84
        $this->tax = $tax;
85
86
        $tax_option = new TaxOption();
87
        $this->tax_option = $tax_option;
88
89
        $order = new Order();
90
        $this->order = $order;
91
92
        $tax_by_state = new TaxByState();
93
        $this->tax_by_state = new $tax_by_state();
94
95
        $cartController = new CartController();
96
        $this->cartController = $cartController;
97
    }
98
99
    public function index(Request $request)
100
    {
101
        try {
102
            $currencies = Currency::where('status', 1)->pluck('code')->toArray();
103
            $name = $request->input('name');
104
            $invoice_no = $request->input('invoice_no');
105
            $status = $request->input('status');
106
107
            $currency_id = $request->input('currency_id');
108
            $from = $request->input('from');
109
            $till = $request->input('till');
110
111
            return view('themes.default1.invoice.index', compact('name','invoice_no','status','currencies','currency_id','from',
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 128 characters

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

Loading history...
112
113
                'till'));
114
        } catch (\Exception $ex) {
115
            Bugsnag::notifyException($ex);
116
117
            return redirect()->back()->with('fails', $ex->getMessage());
118
        }
119
    }
120
121
    public function getInvoices(Request $request)
122
    {
123
        $name = $request->input('name');
124
        $invoice_no = $request->input('invoice_no');
125
        $status = $request->input('status');
126
        $currency = $request->input('currency_id');
127
        $from = $request->input('from');
128
        $till = $request->input('till');
129
        $query = $this->advanceSearch($name, $invoice_no, $currency, $status, $from, $till);
130
131
        return \DataTables::of($query->take(100))
132
         ->setTotalRecords($query->count())
133
134
         ->addColumn('checkbox', function ($model) {
135
             return "<input type='checkbox' class='invoice_checkbox' 
136
                            value=".$model->id.' name=select[] id=check>';
137
         })
138
                        ->addColumn('user_id', function ($model) {
139
                            $first = $this->user->where('id', $model->user_id)->first()->first_name;
140
                            $last = $this->user->where('id', $model->user_id)->first()->last_name;
141
                            $id = $this->user->where('id', $model->user_id)->first()->id;
142
143
                            return '<a href='.url('clients/'.$id).'>'.ucfirst($first).' '.ucfirst($last).'</a>';
144
                        })
145
                         ->addColumn('number', function ($model) {
146
                             return ucfirst($model->number);
147
                         })
148
149
                        ->addColumn('date', function ($model) {
150
                            $date = ($model->created_at);
151
152
                            return $date;
153
                            // return "<span style='display:none'>$model->id</span>".$date->format('l, F j, Y H:m');
154
                        })
155
                         ->addColumn('grand_total', function ($model) {
156
                             return $model->grand_total;
157
                         })
158
                          ->addColumn('status', function ($model) {
159
                              return ucfirst($model->status);
160
                          })
161
162
                        ->addColumn('action', function ($model) {
163
                            $action = '';
164
165
                            $check = $this->checkExecution($model->id);
166
                            if ($check == false) {
167
                                $action = '<a href='.url('order/execute?invoiceid='.$model->id)
168
                                ." class='btn btn-sm btn-primary btn-xs'>
169
                                <i class='fa fa-tasks' style='color:white;'>
170
                                 </i>&nbsp;&nbsp; Execute Order</a>";
171
                            }
172
173
                            return '<a href='.url('invoices/show?invoiceid='.$model->id)
174
                            ." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-eye' 
175
                            style='color:white;'> </i>&nbsp;&nbsp;View</a>"
176
                                    ."   $action";
177
                        })
178
                         ->filterColumn('user_id', function ($query, $keyword) {
179
                             $sql = 'first_name like ?';
180
                             $query->whereRaw($sql, ["%{$keyword}%"]);
181
                         })
182
183
                          ->filterColumn('status', function ($query, $keyword) {
184
                              $sql = 'status like ?';
185
                              $query->whereRaw($sql, ["%{$keyword}%"]);
186
                          })
187
188
                        ->filterColumn('number', function ($query, $keyword) {
189
                            $sql = 'number like ?';
190
                            $query->whereRaw($sql, ["%{$keyword}%"]);
191
                        })
192
                         ->filterColumn('grand_total', function ($query, $keyword) {
193
                             $sql = 'grand_total like ?';
194
                             $query->whereRaw($sql, ["%{$keyword}%"]);
195
                         })
196
                          ->filterColumn('date', function ($query, $keyword) {
197
                              $sql = 'date like ?';
198
                              $query->whereRaw($sql, ["%{$keyword}%"]);
199
                          })
200
201
                         ->rawColumns(['checkbox', 'user_id', 'number', 'date', 'grand_total', 'status', 'action'])
202
                        ->make(true);
203
    }
204
205
    /**
206
     * Shoe Invoice when view Invoice is selected from dropdown in Admin Panel.
207
     *
208
     * @param Request $request Get InvoiceId as Request
209
     */
210
    public function show(Request $request)
211
    {
212
        try {
213
            $id = $request->input('invoiceid');
214
            $invoice = $this->invoice->where('id', $id)->first();
215
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
216
            $user = $this->user->find($invoice->user_id);
217
            $currency = CartController::currency($user->id);
218
            $symbol = $currency['symbol'];
219
            return view('themes.default1.invoice.show', compact('invoiceItems', 'invoice', 'user', 'currency', 'symbol'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 characters

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

Loading history...
220
        } catch (\Exception $ex) {
221
            app('log')->warning($ex->getMessage());
222
            Bugsnag::notifyException($ex);
223
224
            return redirect()->back()->with('fails', $ex->getMessage());
225
        }
226
    }
227
228
    /**
229
     * not in use case.
230
     *
231
     * @param Request $request
232
     *
233
     * @return type
234
     */
235
    public function generateById(Request $request)
236
    {
237
        try {
238
            $clientid = $request->input('clientid');
239
            $user = new User();
240
            if ($clientid) {
241
                $user = $user->where('id', $clientid)->first();
242
                if (!$user) {
243
                    return redirect()->back()->with('fails', 'Invalid user');
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...fails', 'Invalid user') also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type App\Http\Controllers\Order\type.
Loading history...
244
                }
245
            } else {
246
                $user = '';
247
            }
248
            $products = $this->product->where('id', '!=', 1)->pluck('name', 'id')->toArray();
249
            $currency = $this->currency->pluck('name', 'code')->toArray();
250
251
            return view('themes.default1.invoice.generate', compact('user', 'products', 'currency'));
252
        } catch (\Exception $ex) {
253
            app('log')->info($ex->getMessage());
254
            Bugsnag::notifyException($ex);
255
256
            return redirect()->back()->with('fails', $ex->getMessage());
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...ls', $ex->getMessage()) also could return the type Illuminate\Http\Redirect...nate\Routing\Redirector which is incompatible with the documented return type App\Http\Controllers\Order\type.
Loading history...
257
        }
258
    }
259
260
    /**
261
     * Generate invoice.
262
     *
263
     * @throws \Exception
264
     */
265
    public function generateInvoice()
266
    {
267
        try {
268
269
            $sessionValue = $this->getCodeFromSession();
270
            $code = $sessionValue['code'];
271
            $codeValue = $sessionValue['codevalue'];
272
            $tax_rule = new \App\Model\Payment\TaxOption();
273
            $rule = $tax_rule->findOrFail(1);
274
            $rounding = $rule->rounding;
275
            $user_id = \Auth::user()->id;
276
            if (\Auth::user()->currency == 'INR') {
277
                $grand_total = \Cart::getSubTotal();
278
            } else {
279
                foreach (\Cart::getContent() as $cart) {
280
                    $grand_total = \Cart::getSubTotal();
281
                }
282
            }
283
            $number = rand(11111111, 99999999);
284
            $date = \Carbon\Carbon::now();
285
            if ($rounding == 1) {
286
                $grand_total = round($grand_total);
287
            }
288
            $content = \Cart::getContent();
289
            $attributes = [];
290
            foreach ($content as $key => $item) {
291
                $attributes[] = $item->attributes;
292
            }
293
294
            $symbol = $attributes[0]['currency']['symbol'];
295
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number,
296
             'date'                                      => $date, 'discount'=>$codevalue, 'grand_total' => $grand_total, 'coupon_code'=>$code, 'status' => 'pending',
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $codevalue does not exist. Did you maybe mean $codeValue?
Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 166 characters

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

Loading history...
297
             'currency'                                  => \Auth::user()->currency, ]);
298
            foreach (\Cart::getContent() as $cart) {
299
                $this->createInvoiceItems($invoice->id, $cart, $codevalue);
300
            }
301
            $this->sendMail($user_id, $invoice->id);
302
303
            return $invoice;
304
        } catch (\Exception $ex) {
305
            app('log')->error($ex->getMessage());
306
            Bugsnag::notifyException($ex);
307
308
            throw new \Exception('Can not Generate Invoice');
309
        }
310
    }
311
    
312
    /**
313
     * Check if Session has Code and Value of Code
314
     *
315
     * @author Ashutosh Pathak <[email protected]>
316
     *
317
     * @date   2019-02-22T13:10:50+0530
318
     *
319
     * @return array
320
     */
321
    protected function getCodeFromSession() 
322
    {
323
        $code = '';
324
        $codevalue = '';
325
         if(\Session::has('code')){//If coupon code is applied get it here from Session
326
              $code = \Session::get('code');
327
              $codevalue = \Session::get('codevalue');
328
            }
329
            return ['code'=> $code , 'codevalue'=>$codevalue] ; 
330
    }
331
332
    public function createInvoiceItems($invoiceid, $cart, $codevalue = '')
333
    {
334
        try {
335
            $planid = 0;
336
            $product_name = $cart->name;
337
            $regular_price = $cart->price;
338
            $quantity = $cart->quantity;
339
            $agents = $cart->attributes->agents;
340
            $domain = $this->domain($cart->id);
341
            $cart_cont = new \App\Http\Controllers\Front\CartController();
342
            if ($cart_cont->checkPlanSession() === true) {
343
                $planid = \Session::get('plan');
344
            }
345
            if ($planid == 0) {
346
                //When Product is added from Faveo Website
347
                $planid = Plan::where('product', $cart->id)->pluck('id')->first();
348
            }
349
            $user_currency = \Auth::user()->currency;
350
            $subtotal = $this->getSubtotal($user_currency, $cart);
351
352
            $tax_name = '';
353
            $tax_percentage = '';
354
355
            foreach ($cart->attributes['tax'] as $tax) {
356
                $tax_name .= $tax['name'].',';
357
                $tax_percentage .= $tax['rate'].',';
358
            }
359
            $invoiceItem = $this->invoiceItem->create([
360
                'invoice_id'     => $invoiceid,
361
                'product_name'   => $product_name,
362
                'regular_price'  => $regular_price,
363
                'quantity'       => $quantity,
364
                'tax_name'       => $tax_name,
365
                'discount'       => $codevalue,
366
                'tax_percentage' => $tax_percentage,
367
                'subtotal'       => $subtotal,
368
                'domain'         => $domain,
369
                'plan_id'        => $planid,
370
                'agents'         => $agents,
371
            ]);
372
373
            return $invoiceItem;
374
        } catch (\Exception $ex) {
375
            Bugsnag::notifyException($ex->getMessage());
376
            throw new \Exception('Can not create Invoice Items');
377
        }
378
    }
379
380
    public function invoiceGenerateByForm(Request $request, $user_id = '')
381
    {
382
        $this->validate($request, [
383
384
                'plan'      => 'required_if:subscription,true',
385
                'price'     => 'required',
386
            ], [
387
                'plan.required_if' => 'Select a Plan',
388
            ]);
389
390
        try {
391
            $agents = $request->input('agents');
392
            $status = 'pending';
393
            $qty = $request->input('quantity');
394
            if ($user_id == '') {
395
                $user_id = \Request::input('user');
396
            }
397
            $productid = $request->input('product');
398
399
            $plan = $request->input('plan');
400
            $agents = $this->getAgents($agents, $productid, $plan);
401
            $qty = $this->getQuantity($qty, $productid, $plan);
402
403
            $code = $request->input('code');
404
            $total = $request->input('price');
405
            $description = $request->input('description');
406
            if ($request->has('domain')) {
407
                $domain = $request->input('domain');
408
                $this->setDomain($productid, $domain);
409
            }
410
            $controller = new \App\Http\Controllers\Front\CartController();
411
            $userCurrency = $controller->currency($user_id);
412
            $currency = $userCurrency['currency'];
413
            $number = rand(11111111, 99999999);
414
            $date = \Carbon\Carbon::now();
415
            $product = Product::find($productid);
416
            $cost = $controller->cost($productid, $user_id, $plan);
417
            $grand_total = $this->getGrandTotal($code, $total, $cost, $productid, $currency);
418
            $promo = $this->promotion->where('code', $code)->first();
419
            $codeValue = $this->getCodeValue($promo, $code); //get coupon code value to be added to Invoice
420
            $grand_total = $qty * $grand_total;
421
            if ($grand_total == 0) {
422
                $status = 'success';
423
            }
424
            $tax = $this->checkTax($product->id, $user_id);
425
            $tax_name = '';
426
            $tax_rate = '';
427
            if (!empty($tax)) {
428
                $tax_name = $tax[0];
429
                $tax_rate = $tax[1];
430
            }
431
432
            $grand_total = $this->calculateTotal($tax_rate, $grand_total);
433
            $grand_total = \App\Http\Controllers\Front\CartController::rounding($grand_total);
434
435
            $invoice = Invoice::create(['user_id' => $user_id, 'number' => $number, 'date' => $date,
436
             'coupon_code'                        => $code, 'discount'=>$codeValue,
437
                'grand_total'                     => $grand_total,  'currency'  => $currency, 'status' => $status, 'description' => $description, ]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 149 characters

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

Loading history...
438
439
            $items = $this->createInvoiceItemsByAdmin($invoice->id, $productid,
440
             $code, $total, $currency, $qty, $agents, $plan, $user_id, $tax_name, $tax_rate);
441
            $result = $this->getMessage($items, $user_id);
442
        } catch (\Exception $ex) {
443
            app('log')->info($ex->getMessage());
444
            Bugsnag::notifyException($ex);
445
            $result = ['fails' => $ex->getMessage()];
446
        }
447
448
        return response()->json(compact('result'));
449
    }
450
451
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code, $price,
452
        $currency, $qty, $agents, $planid = '', $userid = '', $tax_name = '', $tax_rate = '')
453
    {
454
        try {
455
            $discount = '';
456
            $mode = '';
457
            $product = $this->product->findOrFail($productid);
458
            $plan = Plan::where('product', $productid)->first();
459
            $subtotal = $qty * intval($price);
460
            if ($code) {
461
                $subtotal = $this->checkCode($code, $productid, $currency);
462
                $mode = 'coupon';
463
                $discount = $price - $subtotal;
464
            }
465
            $userid = \Auth::user()->id;
466
            if (\Auth::user()->role == 'user') {
467
                $tax = $this->checkTax($product->id, $userid);
468
                $tax_name = '';
469
                $tax_rate = '';
470
                if (!empty($tax)) {
471
                    $tax_name = $tax[0];
472
                    $tax_rate = $tax[1];
473
                }
474
            }
475
476
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
477
            $domain = $this->domain($productid);
478
            $items = $this->invoiceItem->create([
479
                'invoice_id'     => $invoiceid,
480
                'product_name'   => $product->name,
481
                'regular_price'  => $price,
482
                'quantity'       => $qty,
483
                'discount'       => $discount,
484
                'discount_mode'  => $mode,
485
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
486
                'tax_name'       => $tax_name,
487
                'tax_percentage' => $tax_rate,
488
                'domain'         => $domain,
489
                'plan_id'        => $planid,
490
                'agents'         => $agents,
491
            ]);
492
493
            return $items;
494
        } catch (\Exception $ex) {
495
            Bugsnag::notifyException($ex);
496
497
            return redirect()->back()->with('fails', $ex->getMessage());
498
        }
499
    }
500
501
    public function checkTax($productid, $userid)
502
    {
503
        try {
504
            $taxs = [];
505
            $taxs[0] = ['name' => 'null', 'rate' => 0];
506
            $geoip_state = User::where('id', $userid)->pluck('state')->first();
507
            $geoip_country = User::where('id', $userid)->pluck('country')->first();
508
            $product = $this->product->findOrFail($productid);
509
            $cartController = new CartController();
510
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
511
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
512
                    $taxs = $this->getTaxWhenEnable($productid, $taxs[0], $userid);
513
                } elseif ($this->tax_option->tax_enable == 0) {//if tax_enable is 0
514
515
                    $taxClassId = Tax::where('country', '')->where('state', 'Any State')
516
                     ->pluck('tax_classes_id')->first(); //In case of India when
517
                    //other tax is available and tax is not enabled
518
                    if ($taxClassId) {
519
                        $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
520
                        $taxs = $rate['taxes'];
521
                        $rate = $rate['rate'];
522
                    } elseif ($geoip_country != 'IN') {//In case of other country
523
                        // when tax is available and tax is not enabled(Applicable
524
                        //when Global Tax class for any country and state is not there)
525
526
                        $taxClassId = Tax::where('state', $geoip_state)
527
                        ->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
528
                        if ($taxClassId) { //if state equals the user State
529
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
530
                            $taxs = $rate['taxes'];
531
                            $rate = $rate['rate'];
532
                        }
533
                        $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
534
535
                        return $taxs;
536
                    }
537
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
538
                } else {
539
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
540
                }
541
            }
542
543
            return $taxs;
544
        } catch (\Exception $ex) {
545
            throw new \Exception(\Lang::get('message.check-tax-error'));
546
        }
547
    }
548
549
    public function getRate($productid, $taxs, $userid)
550
    {
551
        $tax_attribute = [];
552
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
553
        $tax_value = '0';
554
555
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
556
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
557
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
558
        $origin_state = $this->setting->first()->state; //Get the State of origin
559
        $cartController = new CartController();
560
        $rate = 0;
561
        $name1 = 'CGST';
562
        $name2 = 'SGST';
563
        $name3 = 'IGST';
564
        $name4 = 'UTGST';
565
        $c_gst = 0;
566
        $s_gst = 0;
567
        $i_gst = 0;
568
        $ut_gst = 0;
569
        $state_code = '';
570
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
571
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
572
            $taxes = $tax['taxes'];
573
            $value = $tax['value'];
574
        } else {//If user from other Country
575
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
576
            $taxes = $tax['taxes'];
577
            $value = $tax['value'];
578
            $rate = $tax['rate'];
579
        }
580
581
        foreach ($taxes as $key => $tax) {
582
            if ($taxes[0]) {
583
                $tax_attribute[$key] = ['name' => $tax->name, 'name1' => $name1,
584
                 'name2'                       => $name2, 'name3' => $name3, 'name4' => $name4,
585
                 'rate'                        => $value, 'rate1'=>$c_gst, 'rate2'=>$s_gst,
586
                 'rate3'                       => $i_gst, 'rate4'=>$ut_gst, 'state'=>$state_code,
587
                  'origin_state'               => $origin_state, ];
588
589
                $rate = $tax->rate;
590
591
                $tax_value = $value;
592
            } else {
593
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
594
                $tax_value = '0%';
595
            }
596
        }
597
598
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
599
    }
600
601
    public function setDomain($productid, $domain)
602
    {
603
        try {
604
            if (\Session::has('domain'.$productid)) {
605
                \Session::forget('domain'.$productid);
606
            }
607
            \Session::put('domain'.$productid, $domain);
608
        } catch (\Exception $ex) {
609
            Bugsnag::notifyException($ex);
610
611
            throw new \Exception($ex->getMessage());
612
        }
613
    }
614
615
    public function sendMail($userid, $invoiceid)
616
    {
617
        try {
618
            $invoice = $this->invoice->find($invoiceid);
619
            $number = $invoice->number;
620
            $total = $invoice->grand_total;
621
622
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
623
        } catch (\Exception $ex) {
624
            Bugsnag::notifyException($ex);
625
626
            throw new \Exception($ex->getMessage());
627
        }
628
    }
629
}
630