Completed
Branch feature-dynamic-fields (3b03cc)
by Ashutosh
09:05
created

InvoiceController::invoiceGenerateByForm()   F

Complexity

Conditions 12
Paths 2715

Size

Total Lines 73
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 57
dl 0
loc 73
rs 3.1781
c 0
b 0
f 0
cc 12
nc 2715
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\User;
22
use Bugsnag;
23
use Illuminate\Http\Request;
24
use Input;
25
use Log;
26
27
class InvoiceController extends TaxRatesAndCodeExpiryController
28
{
29
    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...
30
31
    public $invoice;
32
    public $invoiceItem;
33
    public $user;
34
    public $template;
35
    public $setting;
36
    public $payment;
37
    public $product;
38
    public $price;
39
    public $promotion;
40
    public $currency;
41
    public $tax;
42
    public $tax_option;
43
    public $order;
44
    public $cartController;
45
46
    public function __construct()
47
    {
48
        $this->middleware('auth');
49
        $this->middleware('admin', ['except' => ['pdf']]);
50
51
        $invoice = new Invoice();
52
        $this->invoice = $invoice;
53
54
        $invoiceItem = new InvoiceItem();
55
        $this->invoiceItem = $invoiceItem;
56
57
        $user = new User();
58
        $this->user = $user;
59
60
        $template = new Template();
61
        $this->template = $template;
62
63
        $seting = new Setting();
64
        $this->setting = $seting;
65
66
        $payment = new Payment();
67
        $this->payment = $payment;
68
69
        $product = new Product();
70
        $this->product = $product;
71
72
        $price = new Price();
73
        $this->price = $price;
74
75
        $promotion = new Promotion();
76
        $this->promotion = $promotion;
77
78
        $currency = new Currency();
79
        $this->currency = $currency;
80
81
        $tax = new Tax();
82
        $this->tax = $tax;
83
84
        $tax_option = new TaxOption();
85
        $this->tax_option = $tax_option;
86
87
        $order = new Order();
88
        $this->order = $order;
89
90
        $tax_by_state = new TaxByState();
91
        $this->tax_by_state = new $tax_by_state();
92
93
        $cartController = new CartController();
94
        $this->cartController = $cartController;
95
    }
96
97
    public function index(Request $request)
98
    {
99
        try {
100
            $currencies = Currency::where('status', 1)->pluck('code')->toArray();
101
            $name = $request->input('name');
102
            $invoice_no = $request->input('invoice_no');
103
            $status = $request->input('status');
104
105
            $currency_id = $request->input('currency_id');
106
            $from = $request->input('from');
107
            $till = $request->input('till');
108
109
            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...
110
111
                'till'));
112
        } catch (\Exception $ex) {
113
            Bugsnag::notifyException($ex);
114
115
            return redirect()->back()->with('fails', $ex->getMessage());
116
        }
117
    }
118
119
    public function getInvoices(Request $request)
120
    {
121
        $name = $request->input('name');
122
        $invoice_no = $request->input('invoice_no');
123
        $status = $request->input('status');
124
        $currency = $request->input('currency_id');
125
        $from = $request->input('from');
126
        $till = $request->input('till');
127
        $query = $this->advanceSearch($name, $invoice_no, $currency, $status, $from, $till);
128
129
        return \DataTables::of($query->take(100))
130
         ->setTotalRecords($query->count())
131
132
         ->addColumn('checkbox', function ($model) {
133
             return "<input type='checkbox' class='invoice_checkbox' 
134
                            value=".$model->id.' name=select[] id=check>';
135
         })
136
                        ->addColumn('user_id', function ($model) {
137
                            $first = $this->user->where('id', $model->user_id)->first()->first_name;
138
                            $last = $this->user->where('id', $model->user_id)->first()->last_name;
139
                            $id = $this->user->where('id', $model->user_id)->first()->id;
140
141
                            return '<a href='.url('clients/'.$id).'>'.ucfirst($first).' '.ucfirst($last).'</a>';
142
                        })
143
                         ->addColumn('number', function ($model) {
144
                             return ucfirst($model->number);
145
                         })
146
147
                        ->addColumn('date', function ($model) {
148
                            $date = ($model->created_at);
149
150
                            return $date;
151
                            // return "<span style='display:none'>$model->id</span>".$date->format('l, F j, Y H:m');
152
                        })
153
                         ->addColumn('grand_total', function ($model) {
154
                             return ucfirst($model->number);
155
                         })
156
                          ->addColumn('status', function ($model) {
157
                              return ucfirst($model->status);
158
                          })
159
160
                        ->addColumn('action', function ($model) {
161
                            $action = '';
162
163
                            $check = $this->checkExecution($model->id);
164
                            if ($check == false) {
165
                                $action = '<a href='.url('order/execute?invoiceid='.$model->id)
166
                                ." class='btn btn-sm btn-primary btn-xs'>
167
                                <i class='fa fa-tasks' style='color:white;'>
168
                                 </i>&nbsp;&nbsp; Execute Order</a>";
169
                            }
170
171
                            return '<a href='.url('invoices/show?invoiceid='.$model->id)
172
                            ." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-eye' 
173
                            style='color:white;'> </i>&nbsp;&nbsp;View</a>"
174
                                    ."   $action";
175
                        })
176
                         ->filterColumn('user_id', function ($query, $keyword) {
177
                             $sql = 'first_name like ?';
178
                             $query->whereRaw($sql, ["%{$keyword}%"]);
179
                         })
180
181
                          ->filterColumn('status', function ($query, $keyword) {
182
                              $sql = 'status like ?';
183
                              $query->whereRaw($sql, ["%{$keyword}%"]);
184
                          })
185
186
                        ->filterColumn('number', function ($query, $keyword) {
187
                            $sql = 'number like ?';
188
                            $query->whereRaw($sql, ["%{$keyword}%"]);
189
                        })
190
                         ->filterColumn('grand_total', function ($query, $keyword) {
191
                             $sql = 'grand_total like ?';
192
                             $query->whereRaw($sql, ["%{$keyword}%"]);
193
                         })
194
                          ->filterColumn('date', function ($query, $keyword) {
195
                              $sql = 'date like ?';
196
                              $query->whereRaw($sql, ["%{$keyword}%"]);
197
                          })
198
199
                         ->rawColumns(['checkbox', 'user_id', 'number', 'date', 'grand_total', 'status', 'action'])
200
                        ->make(true);
201
    }
202
203
    /**
204
     * Shoe Invoice when view Invoice is selected from dropdown in Admin Panel.
205
     *
206
     * @param Request $request Get InvoiceId as Request
207
     */
208
    public function show(Request $request)
209
    {
210
        try {
211
            $id = $request->input('invoiceid');
212
            $invoice = $this->invoice->where('id', $id)->first();
213
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
214
            $user = $this->user->find($invoice->user_id);
215
            $currency = CartController::currency($user);
216
            $symbol = $currency['symbol'];
217
218
            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...
219
        } catch (\Exception $ex) {
220
            Bugsnag::notifyException($ex);
221
222
            return redirect()->back()->with('fails', $ex->getMessage());
223
        }
224
    }
225
226
    /**
227
     * not in use case.
228
     *
229
     * @param Request $request
230
     *
231
     * @return type
232
     */
233
    public function generateById(Request $request)
234
    {
235
        try {
236
            $clientid = $request->input('clientid');
237
            $user = new User();
238
            if ($clientid) {
239
                $user = $user->where('id', $clientid)->first();
240
                if (!$user) {
241
                    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...
242
                }
243
            } else {
244
                $user = '';
245
            }
246
            $products = $this->product->where('id', '!=', 1)->pluck('name', 'id')->toArray();
247
            $currency = $this->currency->pluck('name', 'code')->toArray();
248
249
            return view('themes.default1.invoice.generate', compact('user', 'products', 'currency'));
250
        } catch (\Exception $ex) {
251
            app('log')->info($ex->getMessage());
252
            Bugsnag::notifyException($ex);
253
254
            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...
255
        }
256
    }
257
258
    public function sendmailClientAgent($userid, $invoiceid)
259
    {
260
        try {
261
            $agent = \Input::get('agent');
262
            $client = \Input::get('client');
263
            if ($agent == 1) {
264
                $id = \Auth::user()->id;
265
                $this->sendMail($id, $invoiceid);
266
            }
267
            if ($client == 1) {
268
                $this->sendMail($userid, $invoiceid);
269
            }
270
        } catch (\Exception $ex) {
271
            app('log')->info($ex->getMessage());
272
            Bugsnag::notifyException($ex);
273
274
            throw new \Exception($ex->getMessage());
275
        }
276
    }
277
278
    /**
279
     * Generate invoice.
280
     *
281
     * @throws \Exception
282
     */
283
284
    //Is this Method only for cliet?? because Auth::user->id?
285
    public function generateInvoice()
286
    {
287
        try {
288
            $tax_rule = new \App\Model\Payment\TaxOption();
289
            $rule = $tax_rule->findOrFail(1);
290
            $rounding = $rule->rounding;
291
            $user_id = \Auth::user()->id;
292
            if (\Auth::user()->currency == 'INR') {
293
                $grand_total = \Cart::getSubTotal();
294
            } else {
295
                foreach (\Cart::getContent() as $cart) {
296
                    $grand_total = \Cart::getSubTotal();
297
                }
298
            }
299
            $number = rand(11111111, 99999999);
300
            $date = \Carbon\Carbon::now();
301
            if ($rounding == 1) {
302
                $grand_total = round($grand_total);
303
            }
304
            $content = \Cart::getContent();
305
            $attributes = [];
306
            foreach ($content as $key => $item) {
307
                $attributes[] = $item->attributes;
308
            }
309
            $symbol = $attributes[0]['currency']['symbol'];
310
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number,
311
             'date'                                      => $date, 'grand_total' => $grand_total, 'status' => 'pending',
312
             'currency'                                  => $symbol, ]);
313
            foreach (\Cart::getContent() as $cart) {
314
                $this->createInvoiceItems($invoice->id, $cart);
315
            }
316
            $this->sendMail($user_id, $invoice->id);
317
318
            return $invoice;
319
        } catch (\Exception $ex) {
320
            app('log')->error($ex->getMessage());
321
            Bugsnag::notifyException($ex);
322
323
            throw new \Exception('Can not Generate Invoice');
324
        }
325
    }
326
327
    public function createInvoiceItems($invoiceid, $cart)
328
    {
329
        try {
330
            $planid = 0;
331
            $product_name = $cart->name;
332
            $regular_price = $cart->price;
333
            $quantity = $cart->quantity;
334
            $agents = $cart->attributes->agents;
335
            $domain = $this->domain($cart->id);
336
            $cart_cont = new \App\Http\Controllers\Front\CartController();
337
            if ($cart_cont->checkPlanSession() === true) {
338
                $planid = \Session::get('plan');
339
            }
340
            if ($planid == 0) {
341
                //When Product is added from Faveo Website
342
                $planid = Plan::where('product', $cart->id)->pluck('id')->first();
343
            }
344
            $user_currency = \Auth::user()->currency;
345
            $subtotal = $this->getSubtotal($user_currency, $cart);
346
347
            $tax_name = '';
348
            $tax_percentage = '';
349
350
            foreach ($cart->attributes['tax'] as $tax) {
351
                $tax_name .= $tax['name'].',';
352
                $tax_percentage .= $tax['rate'].',';
353
            }
354
            $invoiceItem = $this->invoiceItem->create([
355
                'invoice_id'     => $invoiceid,
356
                'product_name'   => $product_name,
357
                'regular_price'  => $regular_price,
358
                'quantity'       => $quantity,
359
                'tax_name'       => $tax_name,
360
                'tax_percentage' => $tax_percentage,
361
                'subtotal'       => $subtotal,
362
                'domain'         => $domain,
363
                'plan_id'        => $planid,
364
                'agents'         => $agents,
365
            ]);
366
367
            return $invoiceItem;
368
        } catch (\Exception $ex) {
369
            Bugsnag::notifyException($ex);
370
371
            throw new \Exception('Can not create Invoice Items');
372
        }
373
    }
374
375
    public function invoiceGenerateByForm(Request $request, $user_id = '')
376
    {
377
        try {
378
            $agents = $request->input('agents');
379
            $qty = $request->input('quantity');
380
            if ($user_id == '') {
381
                $user_id = \Request::input('user');
382
            }
383
            $productid = $request->input('product');
384
            $plan = $request->input('plan');
385
            if (!$agents) {//If agents is not received in the request in the case when 'modify agent' is not allowed for the Product,get the no of Agents from the Plan Table.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 174 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...
386
                $planForAgent = Product::find($productid)->planRelation->find($plan);
0 ignored issues
show
Bug introduced by
The property planRelation does not seem to exist on App\Model\Product\Product. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
387
                if ($planForAgent) {//If Plan Exists For the Product ie not a Product without Plan
388
                    $noOfAgents = $planForAgent->planPrice->first()->no_of_agents;
389
                    $agents = $noOfAgents ? $noOfAgents : 0; //If no. of Agents is specified then that,else 0(Unlimited Agents)
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

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

Loading history...
390
                } else {
391
                    $agents = 0;
392
                }
393
            }
394
            if (!$qty) {//If quantity is not received in the request in the case when 'modify quantity' is not allowed for the Product,get the Product qUANTITY from the Plan Table.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 180 characters

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

Loading history...
395
                $planForQty = Product::find($productid)->planRelation->find($plan);
396
                if ($planForQty) {
397
                    $quantity = Product::find($productid)->planRelation->find($plan)->planPrice->first()->product_quantity;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

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

Loading history...
398
                    $qty = $quantity ? $quantity : 1; //If no. of Agents is specified then that,else 0(Unlimited Agents)
399
                } else {
400
                    $qty = 1;
401
                }
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
            if ($cost != $total) {
418
                $grand_total = $total;
419
            }
420
            $grand_total = $this->getGrandTotal($code, $total, $cost, $productid, $currency);
421
            $grand_total = $qty * $grand_total;
422
423
            $tax = $this->checkTax($product->id, $user_id);
424
            $tax_name = '';
425
            $tax_rate = '';
426
            if (!empty($tax)) {
427
                $tax_name = $tax[0];
428
                $tax_rate = $tax[1];
429
            }
430
431
            $grand_total = $this->calculateTotal($tax_rate, $grand_total);
432
            $grand_total = \App\Http\Controllers\Front\CartController::rounding($grand_total);
433
434
            $invoice = Invoice::create(['user_id' => $user_id,
435
                'number'                          => $number, 'date' => $date, 'grand_total' => $grand_total,
436
                'currency'                        => $currency, 'status' => 'pending', 'description' => $description, ]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 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...
437
438
            $items = $this->createInvoiceItemsByAdmin($invoice->id, $productid,
439
             $code, $total, $currency, $qty, $agents, $plan, $user_id, $tax_name, $tax_rate);
440
            $result = $this->getMessage($items, $user_id);
441
        } catch (\Exception $ex) {
442
            app('log')->info($ex->getMessage());
443
            Bugsnag::notifyException($ex);
444
            $result = ['fails' => $ex->getMessage()];
445
        }
446
447
        return response()->json(compact('result'));
448
    }
449
450
    public function doPayment($payment_method, $invoiceid, $amount,
451
        $parent_id = '', $userid = '', $payment_status = 'pending')
452
    {
453
        try {
454
            if ($amount > 0) {
455
                if ($userid == '') {
456
                    $userid = \Auth::user()->id;
457
                }
458
                if ($amount == 0) {
459
                    $payment_status = 'success';
460
                }
461
                $this->payment->create([
462
                    'parent_id'      => $parent_id,
463
                    'invoice_id'     => $invoiceid,
464
                    'user_id'        => $userid,
465
                    'amount'         => $amount,
466
                    'payment_method' => $payment_method,
467
                    'payment_status' => $payment_status,
468
                ]);
469
                $this->updateInvoice($invoiceid);
470
            }
471
        } catch (\Exception $ex) {
472
            Bugsnag::notifyException($ex);
473
474
            throw new \Exception($ex->getMessage());
475
        }
476
    }
477
478
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code, $price,
479
        $currency, $qty, $agents, $planid = '', $userid = '', $tax_name = '', $tax_rate = '')
480
    {
481
        try {
482
            $discount = '';
483
            $mode = '';
484
            $product = $this->product->findOrFail($productid);
485
            $plan = Plan::where('product', $productid)->first();
486
            $subtotal = $qty * intval($price);
487
            if ($code) {
488
                $subtotal = $this->checkCode($code, $productid, $currency);
489
                $mode = 'coupon';
490
                $discount = $price - $subtotal;
491
            }
492
            $userid = \Auth::user()->id;
493
            if (\Auth::user()->role == 'user') {
494
                $tax = $this->checkTax($product->id, $userid);
495
                $tax_name = '';
496
                $tax_rate = '';
497
                if (!empty($tax)) {
498
                    $tax_name = $tax[0];
499
                    $tax_rate = $tax[1];
500
                }
501
            }
502
503
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
504
505
            $domain = $this->domain($productid);
506
            $items = $this->invoiceItem->create([
507
                'invoice_id'     => $invoiceid,
508
                'product_name'   => $product->name,
509
                'regular_price'  => $price,
510
                'quantity'       => $qty,
511
                'discount'       => $discount,
512
                'discount_mode'  => $mode,
513
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
514
                'tax_name'       => $tax_name,
515
                'tax_percentage' => $tax_rate,
516
                'domain'         => $domain,
517
                'plan_id'        => $planid,
518
                'agents'         => $agents,
519
            ]);
520
521
            return $items;
522
        } catch (\Exception $ex) {
523
            Bugsnag::notifyException($ex);
524
525
            return redirect()->back()->with('fails', $ex->getMessage());
526
        }
527
    }
528
529
    public function checkTax($productid, $userid)
530
    {
531
        try {
532
            $taxs = [];
533
            $taxs[0] = ['name' => 'null', 'rate' => 0];
534
            $geoip_state = User::where('id', $userid)->pluck('state')->first();
535
            $geoip_country = User::where('id', $userid)->pluck('country')->first();
536
            $product = $this->product->findOrFail($productid);
537
            $cartController = new CartController();
538
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
539
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
540
                    $taxs = $this->getTaxWhenEnable($productid, $taxs[0], $userid);
541
                } elseif ($this->tax_option->tax_enable == 0) {//if tax_enable is 0
542
543
                    $taxClassId = Tax::where('country', '')->where('state', 'Any State')
544
                     ->pluck('tax_classes_id')->first(); //In case of India when
545
                    //other tax is available and tax is not enabled
546
                    if ($taxClassId) {
547
                        $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
548
                        $taxs = $rate['taxes'];
549
                        $rate = $rate['rate'];
550
                    } elseif ($geoip_country != 'IN') {//In case of other country
551
                        // when tax is available and tax is not enabled(Applicable
552
                        //when Global Tax class for any country and state is not there)
553
554
                        $taxClassId = Tax::where('state', $geoip_state)
555
                        ->orWhere('country', $geoip_country)->pluck('tax_classes_id')->first();
556
                        if ($taxClassId) { //if state equals the user State
557
                            $rate = $this->getTotalRate($taxClassId, $productid, $taxs);
558
                            $taxs = $rate['taxes'];
559
                            $rate = $rate['rate'];
560
                        }
561
                        $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
562
563
                        return $taxs;
564
                    }
565
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
566
                } else {
567
                    $taxs = ([$taxs[0]['name'], $taxs[0]['rate']]);
568
                }
569
            }
570
571
            return $taxs;
572
        } catch (\Exception $ex) {
573
            throw new \Exception(\Lang::get('message.check-tax-error'));
574
        }
575
    }
576
577
    public function getRate($productid, $taxs, $userid)
578
    {
579
        $tax_attribute = [];
580
        $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
581
        $tax_value = '0';
582
583
        $geoip_state = User::where('id', $userid)->pluck('state')->first();
584
        $geoip_country = User::where('id', $userid)->pluck('country')->first();
585
        $user_state = $this->tax_by_state::where('state_code', $geoip_state)->first();
586
        $origin_state = $this->setting->first()->state; //Get the State of origin
587
        $cartController = new CartController();
588
        $rate = 0;
589
        $name1 = 'CGST';
590
        $name2 = 'SGST';
591
        $name3 = 'IGST';
592
        $name4 = 'UTGST';
593
        $c_gst = 0;
594
        $s_gst = 0;
595
        $i_gst = 0;
596
        $ut_gst = 0;
597
        $state_code = '';
598
        if ($user_state != '') {//Get the CGST,SGST,IGST,STATE_CODE of the user
599
            $tax = $this->getTaxWhenState($user_state, $productid, $origin_state);
600
            $taxes = $tax['taxes'];
601
            $value = $tax['value'];
602
        } else {//If user from other Country
603
            $tax = $this->getTaxWhenOtherCountry($geoip_state, $geoip_country, $productid);
604
            $taxes = $tax['taxes'];
605
            $value = $tax['value'];
606
            $rate = $tax['rate'];
607
        }
608
609
        foreach ($taxes as $key => $tax) {
610
            if ($taxes[0]) {
611
                $tax_attribute[$key] = ['name' => $tax->name, 'name1' => $name1,
612
                 'name2'                       => $name2, 'name3' => $name3, 'name4' => $name4,
613
                 'rate'                        => $value, 'rate1'=>$c_gst, 'rate2'=>$s_gst,
614
                 'rate3'                       => $i_gst, 'rate4'=>$ut_gst, 'state'=>$state_code,
615
                  'origin_state'               => $origin_state, ];
616
617
                $rate = $tax->rate;
618
619
                $tax_value = $value;
620
            } else {
621
                $tax_attribute[0] = ['name' => 'null', 'rate' => 0, 'tax_enable' =>0];
622
                $tax_value = '0%';
623
            }
624
        }
625
626
        return ['taxs'=>$tax_attribute, 'value'=>$tax_value];
627
    }
628
629
    public function pdf(Request $request)
630
    {
631
        try {
632
            $id = $request->input('invoiceid');
633
            if (!$id) {
634
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
635
            }
636
            $invoice = $this->invoice->where('id', $id)->first();
637
            if (!$invoice) {
638
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
639
            }
640
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
641
            if ($invoiceItems->count() == 0) {
642
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
643
            }
644
            $user = $this->user->find($invoice->user_id);
645
            if (!$user) {
646
                return redirect()->back()->with('fails', 'No User');
647
            }
648
            $cont = new \App\Http\Controllers\Front\CartController();
649
            $currency = $cont->currency($user);
650
            $symbol = $currency['currency'];
651
            $pdf = \PDF::loadView('themes.default1.invoice.newpdf', compact('invoiceItems', 'invoice', 'user', 'currency', 'symbol'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 characters

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

Loading history...
652
653
            return $pdf->download($user->first_name.'-invoice.pdf');
654
        } catch (\Exception $ex) {
655
            Bugsnag::notifyException($ex);
656
657
            return redirect()->back()->with('fails', $ex->getMessage());
658
        }
659
    }
660
661
    public function payment(Request $request)
662
    {
663
        try {
664
            if ($request->has('invoiceid')) {
665
                $invoice_id = $request->input('invoiceid');
666
                $invoice = $this->invoice->find($invoice_id);
667
                $userid = $invoice->user_id;
668
                //dd($invoice);
669
                $invoice_status = '';
670
                $payment_status = '';
671
                $payment_method = '';
672
                $domain = '';
673
                if ($invoice) {
674
                    $invoice_status = $invoice->status;
675
                    $items = $invoice->invoiceItem()->first();
676
                    if ($items) {
677
                        $domain = $items->domain;
678
                    }
679
                }
680
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
681
                if ($payment) {
682
                    $payment_status = $payment->payment_status;
683
                    $payment_method = $payment->payment_method;
684
                }
685
686
                return view('themes.default1.invoice.payment',
687
                 compact('invoice_status', 'payment_status',
688
                  'payment_method', 'invoice_id', 'domain', 'invoice', 'userid'));
689
            }
690
691
            return redirect()->back();
692
        } catch (\Exception $ex) {
693
            Bugsnag::notifyException($ex);
694
695
            return redirect()->back()->with('fails', $ex->getMessage());
696
        }
697
    }
698
699
    public function setDomain($productid, $domain)
700
    {
701
        try {
702
            if (\Session::has('domain'.$productid)) {
703
                \Session::forget('domain'.$productid);
704
            }
705
            \Session::put('domain'.$productid, $domain);
706
        } catch (\Exception $ex) {
707
            Bugsnag::notifyException($ex);
708
709
            throw new \Exception($ex->getMessage());
710
        }
711
    }
712
713
    public function sendMail($userid, $invoiceid)
714
    {
715
        try {
716
            $invoice = $this->invoice->find($invoiceid);
717
            $number = $invoice->number;
718
            $total = $invoice->grand_total;
719
720
            return $this->sendInvoiceMail($userid, $number, $total, $invoiceid);
721
        } catch (\Exception $ex) {
722
            Bugsnag::notifyException($ex);
723
724
            throw new \Exception($ex->getMessage());
725
        }
726
    }
727
728
    public function deletePayment(Request $request)
729
    {
730
        try {
731
            $ids = $request->input('select');
732
            if (!empty($ids)) {
733
                foreach ($ids as $id) {
734
                    $payment = $this->payment->where('id', $id)->first();
735
                    if ($payment) {
736
                        $invoice = $this->invoice->find($payment->invoice_id);
737
                        if ($invoice) {
738
                            $invoice->status = 'pending';
739
                            $invoice->save();
740
                        }
741
                        $payment->delete();
742
                    } else {
743
                        echo "<div class='alert alert-danger alert-dismissable'>
744
                    <i class='fa fa-ban'></i>
745
                    <b>"./* @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> 
746
                    './* @scrutinizer ignore-type */\Lang::get('message.failed').'
747
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
748
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
749
                </div>';
750
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
751
                    }
752
                }
753
                echo "<div class='alert alert-success alert-dismissable'>
754
                    <i class='fa fa-ban'></i>
755
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
756
                    /* @scrutinizer ignore-type */
757
                    \Lang::get('message.success').'
758
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
759
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
760
                </div>';
761
            } else {
762
                echo "<div class='alert alert-danger alert-dismissable'>
763
                    <i class='fa fa-ban'></i>
764
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
765
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
766
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
767
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
768
                </div>';
769
                //echo \Lang::get('message.select-a-row');
770
            }
771
        } catch (\Exception $e) {
772
            Bugsnag::notifyException($e);
773
            echo "<div class='alert alert-danger alert-dismissable'>
774
                    <i class='fa fa-ban'></i>
775
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
776
                    /* @scrutinizer ignore-type */ \Lang::get('message.failed').'
777
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
778
                        '.$e->getMessage().'
779
                </div>';
780
        }
781
    }
782
}
783