Completed
Push — master ( 81ffa0...2d214f )
by vijay
107:48 queued 56:59
created

InvoiceController::index()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 3 Features 0
Metric Value
cc 2
eloc 5
c 6
b 3
f 0
nc 2
nop 0
dl 0
loc 9
rs 9.6666
1
<?php
2
3
namespace App\Http\Controllers\Order;
4
5
use App\Http\Controllers\Common\TemplateController;
6
use App\Http\Controllers\Controller;
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\Payment;
12
use App\Model\Payment\Currency;
13
use App\Model\Payment\Promotion;
14
use App\Model\Payment\Tax;
15
use App\Model\Payment\TaxOption;
16
use App\Model\Product\Price;
17
//use Symfony\Component\HttpFoundation\Request as Requests;
18
use App\Model\Product\Product;
19
use App\User;
20
use Illuminate\Http\Request;
21
use Input;
22
23
class InvoiceController extends Controller
24
{
25
    public $invoice;
26
    public $invoiceItem;
27
    public $user;
28
    public $template;
29
    public $setting;
30
    public $payment;
31
    public $product;
32
    public $price;
33
    public $promotion;
34
    public $currency;
35
    public $tax;
36
    public $tax_option;
37
38
    public function __construct()
39
    {
40
        $this->middleware('auth');
41
//        $this->middleware('admin');
42
43
        $invoice = new Invoice();
44
        $this->invoice = $invoice;
45
46
        $invoiceItem = new InvoiceItem();
47
        $this->invoiceItem = $invoiceItem;
48
49
        $user = new User();
50
        $this->user = $user;
51
52
        $template = new Template();
53
        $this->template = $template;
54
55
        $seting = new Setting();
56
        $this->setting = $seting;
57
58
        $payment = new Payment();
59
        $this->payment = $payment;
60
61
        $product = new Product();
62
        $this->product = $product;
63
64
        $price = new Price();
65
        $this->price = $price;
66
67
        $promotion = new Promotion();
68
        $this->promotion = $promotion;
69
70
        $currency = new Currency();
71
        $this->currency = $currency;
72
73
        $tax = new Tax();
74
        $this->tax = $tax;
75
76
        $tax_option = new TaxOption();
77
        $this->tax_option = $tax_option;
78
    }
79
80
    public function index()
81
    {
82
        try {
83
            //dd($this->invoice->get());
84
            return view('themes.default1.invoice.index');
85
        } catch (\Exception $ex) {
86
            return redirect()->back()->with('fails', $ex->getMessage());
87
        }
88
    }
89
90
    public function GetInvoices()
91
    {
92
        //dd($this->invoice->get());
93
        //$invoice = \DB::table('invoices');
94
        return \Datatable::query($this->invoice->select('id', 'user_id', 'number', 'date', 'grand_total', 'status', 'created_at'))
95
                        ->addColumn('#', function ($model) {
96
                            return "<input type='checkbox' value=".$model->id.' name=select[] id=check>';
97
                        })
98
                        ->addColumn('user_id', function ($model) {
99
100
                            $first = $this->user->where('id', $model->user_id)->first()->first_name;
101
                            $last = $this->user->where('id', $model->user_id)->first()->last_name;
102
                            $id = $this->user->where('id', $model->user_id)->first()->id;
103
104
                            return '<a href='.url('clients/'.$id).'>'.ucfirst($first).' '.ucfirst($last).'</a>';
105
                        })
106
                        ->showColumns('number', 'created_at', 'grand_total', 'status')
107
                        ->addColumn('action', function ($model) {
108
                            $order = \App\Model\Order\Order::where('invoice_id', $model->id)->first();
109
                            if (!$order) {
110
                                $action = '<a href='.url('order/execute?invoiceid='.$model->id)." class='btn btn-sm btn-primary'>Execute Order</a>";
111
                            } else {
112
                                $action = '';
113
                            }
114
115
                            return '<a href='.url('invoices/show?invoiceid='.$model->id)." class='btn btn-sm btn-primary'>View</a>"
116
                                    ."   $action";
117
                        })
118
                        ->searchColumns('created_at', 'user_id', 'number', 'grand_total', 'status')
119
                        ->orderColumns('created_at', 'user_id', 'number', 'grand_total', 'status')
120
                        ->make();
121
    }
122
123
    public function show(Request $request)
124
    {
125
        try {
126
            $id = $request->input('invoiceid');
127
            $invoice = $this->invoice->where('id', $id)->first();
128
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
129
            $user = $this->user->find($invoice->user_id);
130
131
            return view('themes.default1.invoice.show', compact('invoiceItems', 'invoice', 'user'));
132
        } catch (\Exception $ex) {
133
            return redirect()->back()->with('fails', $ex->getMessage());
134
        }
135
    }
136
137
    /**
138
     * not in use case.
139
     *
140
     * @param Request $request
141
     *
142
     * @return type
143
     */
144
    public function generateById(Request $request)
145
    {
146
        try {
147
            $clientid = $request->input('clientid');
148
            //dd($clientid);
149
            if ($clientid) {
150
                $user = new User();
151
                $user = $user->where('id', $clientid)->first();
152
                if (!$user) {
153
                    return redirect()->back()->with('fails', 'Invalid user');
154
                }
155
            } else {
156
                $user = '';
157
            }
158
            $products = $this->product->lists('name', 'id')->toArray();
159
            $currency = $this->currency->lists('name', 'code')->toArray();
160
161
            return view('themes.default1.invoice.generate', compact('user', 'products', 'currency'));
162
        } catch (\Exception $ex) {
163
            return redirect()->back()->with('fails', $ex->getMessage());
164
        }
165
    }
166
167
    public function invoiceGenerateByForm(Request $request, $user_id = '')
168
    {
169
        if (array_key_exists('domain', $request->all())) {
170
            $this->validate($request, [
171
                'domain' => 'required|url',
172
            ]);
173
        }
174
175
        $this->validate($request, [
176
            'product' => 'required',
177
        ]);
178
        try {
179
            if ($user_id == '') {
180
                $user_id = \Input::get('user');
181
            }
182
183
            $productid = Input::get('product');
184
            $code = Input::get('code');
185
            $total = Input::get('price');
186
            if ($request->has('domain')) {
187
                $domain = $request->input('domain');
188
                $this->setDomain($productid, $domain);
189
            }
190
            $currency = $this->user->find($user_id)->currency;
191
            if (!$currency) {
192
                $currency = 'USD';
193
            }
194
            if ($currency == 1) {
195
                $currency = 'USD';
196
            } else {
197
                $currency = 'INR';
198
            }
199
            $number = rand(11111111, 99999999);
200
            $date = \Carbon\Carbon::now();
201
            $product = $this->product->findOrFail($productid);
202
            $price = $product->price()->where('currency', $currency)->first();
203
            //dd($price);
204
            $cost = $price->sales_price;
205
            if (!$cost) {
206
                $cost = $price->price;
207
            }
208
            if ($cost != $total) {
209
                $grand_total = $total;
210
            }
211
            //dd($cost);
212
            if ($code) {
213
                $grand_total = $this->checkCode($code, $productid);
214
                //dd($grand_total);
215
            } else {
216
                if (!$total) {
217
                    $grand_total = $cost;
218
                } else {
219
                    $grand_total = $total;
220
                }
221
            }
222
            $grand_total = $grand_total;
0 ignored issues
show
Bug introduced by
Why assign $grand_total to itself?

This checks looks for cases where a variable has been assigned to itself.

This assignement can be removed without consequences.

Loading history...
223
            //dd($grand_total);
224
            $tax = $this->checkTax($product->id);
225
            //dd($tax);
226
            $tax_name = '';
227
            $tax_rate = '';
228 View Code Duplication
            if (!empty($tax)) {
229
                foreach ($tax as $key => $value) {
230
                    //dd($value);
231
                    $tax_name .= $value['name'].',';
232
                    $tax_rate .= $value['rate'].',';
233
                }
234
            }
235
            //dd('dsjcgv');
236
            $grand_total = $this->calculateTotal($tax_rate, $grand_total);
237
238
            //dd($grand_total);
239
            $grand_total = \App\Http\Controllers\Front\CartController::rounding($grand_total);
240
241
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'currency' => $currency, 'status' => 'pending']);
242
            if ($grand_total > 0) {
243
                $this->doPayment('online payment', $invoice->id, $grand_total, '', $user_id);
244
            }
245
            $items = $this->createInvoiceItemsByAdmin($invoice->id, $productid, $code, $total, $currency);
246
            if ($items) {
247
                $this->sendmailClientAgent($user_id, $items->invoice_id);
248
                $result = ['success' => \Lang::get('message.invoice-generated-successfully')];
249
            } else {
250
                $result = ['fails' => \Lang::get('message.can-not-generate-invoice')];
251
            }
252
        } catch (\Exception $ex) {
253
            $result = ['fails' => $ex->getMessage()];
254
        }
255
256
        return response()->json(compact('result'));
257
    }
258
259
    public function sendmailClientAgent($userid, $invoiceid)
260
    {
261
        try {
262
            $agent = \Input::get('agent');
263
            $client = \Input::get('client');
264
            if ($agent == 1) {
265
                $id = \Auth::user()->id;
266
                $this->sendMail($id, $invoiceid);
267
            }
268
            if ($client == 1) {
269
                $this->sendMail($userid, $invoiceid);
270
            }
271
        } catch (\Exception $ex) {
272
            throw new \Exception($ex->getMessage());
273
        }
274
    }
275
276
    /**
277
     * Generate invoice.
278
     *
279
     * @throws \Exception
280
     */
281
    public function GenerateInvoice()
282
    {
283
        try {
284
            $tax_rule = new \App\Model\Payment\TaxOption();
285
            $rule = $tax_rule->findOrFail(1);
286
            $rounding = $rule->rounding;
287
288
            $user_id = \Auth::user()->id;
289
            $grand_total = \Cart::getSubTotal();
290
291
            $number = rand(11111111, 99999999);
292
            $date = \Carbon\Carbon::now();
293
294
            if ($rounding == 1) {
295
                $grand_total = round($grand_total);
296
            }
297
298
            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total, 'status' => 'pending']);
299
300
            foreach (\Cart::getContent() as $cart) {
301
                $this->createInvoiceItems($invoice->id, $cart);
302
            }
303
304
            return $invoice;
305
        } catch (\Exception $ex) {
306
            dd($ex);
307
            throw new \Exception('Can not Generate Invoice');
308
        }
309
    }
310
311
    public function createInvoiceItems($invoiceid, $cart)
312
    {
313
        try {
314
            $product_name = $cart->name;
315
            $regular_price = $cart->price;
316
            $quantity = $cart->quantity;
317
            $domain = $this->domain($cart->id);
318
            //dd($quantity);
319
            $subtotal = \App\Http\Controllers\Front\CartController::rounding($cart->getPriceSumWithConditions());
320
321
            $tax_name = '';
322
            $tax_percentage = '';
323
324
            foreach ($cart->attributes['tax'] as $tax) {
325
                //dd($tax['name']);
326
                $tax_name .= $tax['name'].',';
327
                $tax_percentage .= $tax['rate'].',';
328
            }
329
330
//            dd($tax_name);
331
332
            $invoiceItem = $this->invoiceItem->create([
333
                'invoice_id'     => $invoiceid,
334
                'product_name'   => $product_name,
335
                'regular_price'  => $regular_price,
336
                'quantity'       => $quantity,
337
                'tax_name'       => $tax_name,
338
                'tax_percentage' => $tax_percentage,
339
                'subtotal'       => $subtotal,
340
                'domain'         => $domain,
341
            ]);
342
343
            return $invoiceItem;
344
        } catch (\Exception $ex) {
345
            dd($ex);
346
            throw new \Exception('Can not create Invoice Items');
347
        }
348
    }
349
350
    public function doPayment($payment_method, $invoiceid, $amount, $parent_id = '', $userid = '', $payment_status = 'pending')
351
    {
352
        try {
353
            if ($amount > 0) {
354
                if ($userid == '') {
355
                    $userid = \Auth::user()->id;
356
                }
357
                if ($amount == 0) {
358
                    $payment_status = 'success';
359
                }
360
                $this->payment->create([
361
                    'parent_id'      => $parent_id,
362
                    'invoice_id'     => $invoiceid,
363
                    'user_id'        => $userid,
364
                    'amount'         => $amount,
365
                    'payment_method' => $payment_method,
366
                    'payment_status' => $payment_status,
367
                ]);
368
                $this->updateInvoice($invoiceid);
369
            }
370
        } catch (\Exception $ex) {
371
            throw new \Exception($ex->getMessage());
372
        }
373
    }
374
375
    public function createInvoiceItemsByAdmin($invoiceid, $productid, $code = '', $price = '', $currency = 'USD')
376
    {
377
        try {
378
            $discount = '';
379
            $mode = '';
380
            $product = $this->product->findOrFail($productid);
381
            $price_model = $this->price->where('product_id', $product->id)->where('currency', $currency)->first();
382
            if ($price == '') {
383
                $price = $price_model->sales_price;
384
                if (!$price) {
385
                    $price = $price_model->price;
386
                }
387
            }
388
            $subtotal = $price;
389
            //dd($subtotal);
390
            if ($code) {
391
                $subtotal = $this->checkCode($code, $productid);
392
                $mode = 'coupon';
393
                $discount = $price - $subtotal;
394
            }
395
            $tax = $this->checkTax($product->id);
396
            //dd($tax);
397
            $tax_name = '';
398
            $tax_rate = '';
399 View Code Duplication
            if (!empty($tax)) {
400
                foreach ($tax as $key => $value) {
401
                    //dd($value);
402
                    $tax_name .= $value['name'].',';
403
                    $tax_rate .= $value['rate'].',';
404
                }
405
            }
406
            $subtotal = $this->calculateTotal($tax_rate, $subtotal);
407
            $domain = $this->domain($productid);
408
            $items = $this->invoiceItem->create([
409
                'invoice_id'     => $invoiceid,
410
                'product_name'   => $product->name,
411
                'regular_price'  => $price,
412
                'quantity'       => 1,
413
                'discount'       => $discount,
414
                'discount_mode'  => $mode,
415
                'subtotal'       => \App\Http\Controllers\Front\CartController::rounding($subtotal),
416
                'tax_name'       => $tax_name,
417
                'tax_percentage' => $tax_rate,
418
                'domain'         => $domain,
419
            ]);
420
421
            return $items;
422
        } catch (\Exception $ex) {
423
            dd($ex);
424
425
            return redirect()->back()->with('fails', $ex->getMessage());
426
        }
427
    }
428
429
    public function checkCode($code, $productid)
430
    {
431
        try {
432
            if ($code != '') {
433
                $promo = $this->promotion->where('code', $code)->first();
434
                //check promotion code is valid
435
                if (!$promo) {
436
                    throw new \Exception(\Lang::get('message.no-such-code'));
437
                }
438
                $relation = $promo->relation()->get();
439
                //check the relation between code and product
440
                if (count($relation) == 0) {
441
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
442
                }
443
                //check the usess
444
                $uses = $this->checkNumberOfUses($code);
445
                //dd($uses);
446
                if ($uses != 'success') {
447
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
448
                }
449
                //check for the expiry date
450
                $expiry = $this->checkExpiry($code);
451
                //dd($expiry);
452
                if ($expiry != 'success') {
453
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
454
                }
455
                $value = $this->findCostAfterDiscount($promo->id, $productid);
456
457
                return $value;
458
            } else {
459
                $product = $this->product->find($productid);
460
                $price = $product->price()->sales_price;
461
                if (!$price) {
462
                    $price = $product->price()->price;
463
                }
464
465
                return $price;
466
            }
467
        } catch (\Exception $ex) {
468
            dd($ex);
469
            throw new \Exception(\Lang::get('message.check-code-error'));
470
        }
471
    }
472
473 View Code Duplication
    public function findCostAfterDiscount($promoid, $productid)
474
    {
475
        try {
476
            $promotion = $this->promotion->findOrFail($promoid);
477
            $product = $this->product->findOrFail($productid);
478
            $promotion_type = $promotion->type;
479
            $promotion_value = $promotion->value;
480
            $product_price = $product->price()->first()->sales_price;
481
            if (!$product_price) {
482
                $product_price = $product->price()->first()->price;
483
            }
484
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
485
486
            return $updated_price;
487
        } catch (\Exception $ex) {
488
            throw new \Exception(\Lang::get('message.find-discount-error'));
489
        }
490
    }
491
492
    public function findCost($type, $value, $price, $productid)
493
    {
494
        try {
495
            switch ($type) {
496
497
                case 1:
498
                    $percentage = $price * ($value / 100);
499
500
                    return $price - $percentage;
501
                case 2:
502
                    return $price - $value;
503
                case 3:
504
                    return $value;
505
                case 4:
506
                    return 0;
507
            }
508
        } catch (\Exception $ex) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $ex) {...e.find-cost-error')); } does not seem to be 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...
509
            throw new \Exception(\Lang::get('message.find-cost-error'));
510
        }
511
    }
512
513 View Code Duplication
    public function checkNumberOfUses($code)
514
    {
515
        try {
516
            $promotion = $this->promotion->where('code', $code)->first();
517
            $uses = $promotion->uses;
518
            if ($uses == 0) {
519
                return 'success';
520
            }
521
            $used_number = $this->invoice->where('coupon_code', $code)->count();
522
            if ($uses >= $used_number) {
523
                return 'success';
524
            } else {
525
                return 'fails';
526
            }
527
        } catch (\Exception $ex) {
528
            throw new \Exception(\Lang::get('message.find-cost-error'));
529
        }
530
    }
531
532 View Code Duplication
    public function checkExpiry($code = '')
533
    {
534
        try {
535
            if ($code != '') {
536
                $promotion = $this->promotion->where('code', $code)->first();
537
                $start = $promotion->start;
538
                $end = $promotion->expiry;
539
                //dd($end);
540
                $now = \Carbon\Carbon::now();
541
                //both not set, always true
542
                if (($start == null || $start == '0000-00-00 00:00:00') && ($end == null || $end == '0000-00-00 00:00:00')) {
543
                    return 'success';
544
                }
545
                //only starting date set, check the date is less or equel to today
546
                if (($start != null || $start != '0000-00-00 00:00:00') && ($end == null || $end == '0000-00-00 00:00:00')) {
547
                    if ($start <= $now) {
548
                        return 'success';
549
                    }
550
                }
551
                //only ending date set, check the date is greater or equel to today
552
                if (($end != null || $end != '0000-00-00 00:00:00') && ($start == null || $start == '0000-00-00 00:00:00')) {
553
                    if ($end >= $now) {
554
                        return 'success';
555
                    }
556
                }
557
                //both set
558
                if (($end != null || $start != '0000-00-00 00:00:00') && ($start != null || $start != '0000-00-00 00:00:00')) {
559
                    if ($end >= $now && $start <= $now) {
560
                        return 'success';
561
                    }
562
                }
563
            } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
564
            }
565
        } catch (\Exception $ex) {
566
            dd($ex);
567
            throw new \Exception(\Lang::get('message.check-expiry'));
568
        }
569
    }
570
571
    public function checkTax($productid)
572
    {
573
        try {
574
            //dd($productid);
575
            $taxs[0] = ['name' => 'null', 'rate' => 0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$taxs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $taxs = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
576
            $product = $this->product->findOrFail($productid);
577
            if ($this->tax_option->findOrFail(1)->inclusive == 0) {
578
                if ($product->tax()->first()) {
579
                    $tax_class_id = $product->tax()->first()->tax_class_id;
580
                } else {
581
                    return $taxs;
582
                }
583
584
                if ($this->tax_option->findOrFail(1)->tax_enable == 1) {
585
                    $cart_controller = new \App\Http\Controllers\Front\CartController();
586
                    $taxes = $cart_controller->getTaxByPriority($tax_class_id);
587
588
                    foreach ($taxes as $key => $tax) {
589
                        //dd($tax);
590
                        if ($tax->compound == 1) {
591
                            $taxs[$key] = ['name' => $tax->name, 'rate' => $tax->rate];
592
                        } else {
593
                            $rate = '';
594
                            $rate += $tax->rate;
595
                            $taxs[$key] = ['name' => $tax->name, 'rate' => $rate];
596
                        }
597
                    }
598
                }
599
            }
600
            //dd($taxs);
601
            return $taxs;
602
        } catch (\Exception $ex) {
603
            dd($ex);
604
            throw new \Exception(\Lang::get('message.check-tax-error'));
605
        }
606
    }
607
608
    public function pdf(Request $request)
609
    {
610
        try {
611
            $id = $request->input('invoiceid');
612
            if (!$id) {
613
                return redirect()->back()->with('fails', \Lang::get('message.no-invoice-id'));
614
            }
615
            $invoice = $this->invoice->where('id', $id)->first();
616
            if (!$invoice) {
617
                return redirect()->back()->with('fails', \Lang::get('message.invalid-invoice-id'));
618
            }
619
            $invoiceItems = $this->invoiceItem->where('invoice_id', $id)->get();
620
            $user = $this->user->find($invoice->user_id);
621
            //return view('themes.default1.invoice.pdfinvoice', compact('invoiceItems', 'invoice', 'user'));
622
            $pdf = \PDF::loadView('themes.default1.invoice.pdfinvoice', compact('invoiceItems', 'invoice', 'user'));
623
624
            return $pdf->download($user->first_name.'-invoice.pdf');
625
        } catch (\Exception $ex) {
626
            return redirect()->back()->with('fails', $ex->getMessage());
627
        }
628
    }
629
630
    public function calculateTotal($rate, $total)
631
    {
632
        try {
633
            //dd($total);
634
            $rates = explode(',', $rate);
635
            //dd($rates);
636
//            $total = '';
637
            $rule = new TaxOption();
638
            $rule = $rule->findOrFail(1);
639
            if ($rule->tax_enable == 1 && $rule->inclusive == 0) {
640
                foreach ($rates as $rate) {
641
                    $total += $total * ($rate / 100);
642
                }
643
            }
644
            //dd($total);
645
            return $total;
646
        } catch (\Exception $ex) {
647
            dd($ex);
648
            throw new \Exception($ex->getMessage());
649
        }
650
    }
651
652
    /**
653
     * Remove the specified resource from storage.
654
     *
655
     * @param int $id
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
656
     *
657
     * @return Response
658
     */
659 View Code Duplication
    public function destroy(Request $request)
660
    {
661
        try {
662
            $ids = $request->input('select');
663
            if (!empty($ids)) {
664
                foreach ($ids as $id) {
0 ignored issues
show
Bug introduced by
The expression $ids of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
665
                    $invoice = $this->invoice->where('id', $id)->first();
666
                    if ($invoice) {
667
                        $invoice->delete();
668
                    } else {
669
                        echo "<div class='alert alert-danger alert-dismissable'>
670
                    <i class='fa fa-ban'></i>
671
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
672
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
673
                        '.\Lang::get('message.no-record').'
674
                </div>';
675
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
676
                    }
677
                }
678
                echo "<div class='alert alert-success alert-dismissable'>
679
                    <i class='fa fa-ban'></i>
680
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.success').'
681
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
682
                        '.\Lang::get('message.deleted-successfully').'
683
                </div>';
684
            } else {
685
                echo "<div class='alert alert-danger alert-dismissable'>
686
                    <i class='fa fa-ban'></i>
687
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
688
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
689
                        '.\Lang::get('message.select-a-row').'
690
                </div>';
691
                //echo \Lang::get('message.select-a-row');
692
            }
693
        } catch (\Exception $e) {
694
            echo "<div class='alert alert-danger alert-dismissable'>
695
                    <i class='fa fa-ban'></i>
696
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
697
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
698
                        '.$e->getMessage().'
699
                </div>';
700
        }
701
    }
702
703
    public function setDomain($productid, $domain)
704
    {
705
        try {
706
            if (\Session::has('domain'.$productid)) {
707
                \Session::forget('domain'.$productid);
708
            }
709
            \Session::put('domain'.$productid, $domain);
710
        } catch (\Exception $ex) {
711
            throw new \Exception($ex->getMessage());
712
        }
713
    }
714
715
    public function domain($id)
716
    {
717
        try {
718
            if (\Session::has('domain'.$id)) {
719
                $domain = \Session::get('domain'.$id);
720
            } else {
721
                $domain = '';
722
            }
723
724
            return $domain;
725
        } catch (\Exception $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
726
        }
727
    }
728
729
    public function updateInvoice($invoiceid)
730
    {
731
        try {
732
            $invoice = $this->invoice->findOrFail($invoiceid);
733
            $payment = $this->payment->where('invoice_id', $invoiceid)->where('payment_status', 'success')->lists('amount')->toArray();
734
            $total = array_sum($payment);
735
            if ($total < $invoice->grand_total) {
736
                $invoice->status = 'pending';
737
            }
738
            if ($total >= $invoice->grand_total) {
739
                $invoice->status = 'success';
740
            }
741
            if ($total > $invoice->grand_total) {
742
                $user = $invoice->user()->first();
743
                $balance = $total - $invoice->grand_total;
744
                $user->debit = $balance;
745
                $user->save();
746
            }
747
748
            $invoice->save();
749
        } catch (\Exception $ex) {
750
            throw new \Exception($ex->getMessage());
751
        }
752
    }
753
754
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status = 'pending', $invoice_status = 'pending', $domain = '')
755
    {
756
        try {
757
            $invoice = $this->invoice->find($invoiceid);
758 View Code Duplication
            if ($invoice) {
759
                $invoice->status = $invoice_status;
760
                $invoice->save();
761
                $item = $invoice->invoiceItem()->first();
762
                if ($item) {
763
                    $item->domain = $domain;
764
                    $item->save();
765
                }
766
            }
767
            $payment = $this->payment->where('invoice_id', $invoiceid)->first();
768
            if ($payment) {
769
                $payment->payment_status = $payment_status;
770
                $payment->payment_method = $payment_method;
771
                $payment->save();
772
773
                return $payment;
774
            }
775
        } catch (\Exception $ex) {
776
            throw new \Exception($ex->getMessage());
777
        }
778
    }
779
780
    public function payment(Request $request)
781
    {
782
        try {
783
            if ($request->has('invoiceid')) {
784
                $invoice_id = $request->input('invoiceid');
785
                $invoice = $this->invoice->find($invoice_id);
786
                //dd($invoice);
787
                $invoice_status = '';
788
                $payment_status = '';
789
                $payment_method = '';
790
                $domain = '';
791 View Code Duplication
                if ($invoice) {
792
                    $invoice_status = $invoice->status;
793
                    $items = $invoice->invoiceItem()->first();
794
                    if ($items) {
795
                        $domain = $items->domain;
796
                    }
797
                }
798
                $payment = $this->payment->where('invoice_id', $invoice_id)->first();
799
                if ($payment) {
800
                    $payment_status = $payment->payment_status;
801
                    $payment_method = $payment->payment_method;
802
                }
803
804
                return view('themes.default1.invoice.payment', compact('invoice_status', 'payment_status', 'payment_method', 'invoice_id', 'domain'));
805
            }
806
807
            return redirect()->back();
808
        } catch (\Exception $ex) {
809
            return redirect()->back()->with('fails', $ex->getMessage());
810
        }
811
    }
812
813
    public function postPayment($invoiceid, Request $request)
814
    {
815
        try {
816
            $payment_method = $request->input('payment_method');
817
            $payment_status = $request->input('payment_status');
818
            $invoice_status = $request->input('invoice_status');
819
            $domain = $request->input('domain');
820
            $payment = $this->updateInvoicePayment($invoiceid, $payment_method, $payment_status, $invoice_status, $domain);
0 ignored issues
show
Bug introduced by
It seems like $payment_status defined by $request->input('payment_status') on line 817 can also be of type array; however, App\Http\Controllers\Ord...:updateInvoicePayment() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $invoice_status defined by $request->input('invoice_status') on line 818 can also be of type array; however, App\Http\Controllers\Ord...:updateInvoicePayment() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $domain defined by $request->input('domain') on line 819 can also be of type array; however, App\Http\Controllers\Ord...:updateInvoicePayment() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
821
            if ($payment) {
822
                return redirect()->back()->with('success', 'Payment Accepted Successfully');
823
            }
824
        } catch (\Exception $ex) {
825
            return redirect()->back()->with('fails', $ex->getMessage());
826
        }
827
    }
828
829
    public function sendMail($userid, $invoiceid, $templatetype = 7)
830
    {
831
        try {
832
            $settings = new Setting();
833
            $settings = $settings->findOrFail(1);
834
            $user = $this->user->find($userid);
835
            $name = '';
836
            $to = '';
837
            $product = '';
838
            if ($user) {
839
                $name = $user->first_name.' '.$user->last_name;
840
                $to = $user->email;
841
            }
842
            $invoice = $this->invoice->find($invoiceid);
843
            $invoice_number = $invoice->number;
844
            $item = $invoice->invoiceItem()->first();
845
            if ($item) {
846
                $product = $item->product_name;
847
            }
848
849
            $url = url("download/$userid/$invoice_number");
850
            $from = $settings->email;
851
852
            $data = $this->template->where('type', $templatetype)->first()->data;
853
            $subject = $this->template->where('type', $templatetype)->first()->name;
854
            $replace = ['url' => $url, 'name' => $name, 'product' => $product];
855
856
            //send mail
857
            $template_controller = new TemplateController();
858
            $template_controller->Mailing($from, $to, $data, $subject, $replace);
859
        } catch (\Exception $ex) {
860
            throw new \Exception($ex->getMessage());
861
        }
862
    }
863
}
864