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

CoupCodeAndInvoiceSearch::checkCode()   B

Complexity

Conditions 7
Paths 16

Size

Total Lines 37
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 37
rs 8.6026
c 0
b 0
f 0
cc 7
nc 16
nop 3
1
<?php
2
3
namespace App\Traits;
4
5
use App\Model\Order\Invoice;
6
use App\Model\Payment\Plan;
7
use App\Model\Payment\PlanPrice;
8
use App\Model\Payment\Promotion;
9
use App\Model\Product\Product;
10
use Illuminate\Http\Request;
11
12
//////////////////////////////////////////////////////////////////////////////
13
// ADVANCE SEARCH FOR INVOICE AND COUPON CODE CALCULATION
14
//////////////////////////////////////////////////////////////////////////////
15
16
trait CoupCodeAndInvoiceSearch
17
{
18
    public function checkCode($code, $productid, $currency)
19
    {
20
        try {
21
            if ($code != '') {
22
                $promo = $this->promotion->where('code', $code)->first();
23
                //check promotion code is valid
24
                if (!$promo) {
25
                    throw new \Exception(\Lang::get('message.no-such-code'));
26
                }
27
                $relation = $promo->relation()->get();
28
                //check the relation between code and product
29
                if (count($relation) == 0) {
30
                    throw new \Exception(\Lang::get('message.no-product-related-to-this-code'));
31
                }
32
                //check the usess
33
                $cont = new \App\Http\Controllers\Payment\PromotionController();
34
                $uses = $cont->checkNumberOfUses($code);
35
                if ($uses != 'success') {
36
                    throw new \Exception(\Lang::get('message.usage-of-code-completed'));
37
                }
38
                //check for the expiry date
39
                $expiry = $this->checkExpiry($code);
0 ignored issues
show
Bug introduced by
It seems like checkExpiry() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

39
                /** @scrutinizer ignore-call */ 
40
                $expiry = $this->checkExpiry($code);
Loading history...
40
                if ($expiry != 'success') {
41
                    throw new \Exception(\Lang::get('message.usage-of-code-expired'));
42
                }
43
                $value = $this->findCostAfterDiscount($promo->id, $productid, $currency);
44
45
                return $value;
46
            } else {
47
                $product = $this->product->find($productid);
48
                $plans = Plan::where('product', $product)->pluck('id')->first();
49
                $price = PlanPrice::where('currency', $currency)->where('plan_id', $plans)->pluck('add_price')->first();
50
51
                return $price;
52
            }
53
        } catch (\Exception $ex) {
54
            throw new \Exception($ex->getMessage());
55
        }
56
    }
57
58
    public function findCostAfterDiscount($promoid, $productid, $currency)
59
    {
60
        try {
61
            $promotion = Promotion::findOrFail($promoid);
62
            $product = Product::findOrFail($productid);
63
            $promotion_type = $promotion->type;
64
            $promotion_value = $promotion->value;
65
            $planId = Plan::where('product', $productid)->pluck('id')->first();
66
            // dd($planId);
67
            $product_price = PlanPrice::where('plan_id', $planId)
68
            ->where('currency', $currency)->pluck('add_price')->first();
69
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
70
71
            return $updated_price;
72
        } catch (\Exception $ex) {
73
            Bugsnag::notifyException($ex);
0 ignored issues
show
Bug introduced by
The type App\Traits\Bugsnag was not found. Did you mean Bugsnag? If so, make sure to prefix the type with \.
Loading history...
74
75
            throw new \Exception(\Lang::get('message.find-discount-error'));
76
        }
77
    }
78
79
    public function findCost($type, $value, $price, $productid)
80
    {
81
        $price = intval($price);
82
        switch ($type) {
83
            case 1:
84
                $percentage = $price * ($value / 100);
85
86
                return $price - $percentage;
87
            case 2:
88
                return $price - $value;
89
            case 3:
90
                return $value;
91
            case 4:
92
                return 0;
93
        }
94
    }
95
96
    public function advanceSearch($name = '', $invoice_no = '', $currency = '', $status = '', $from = '', $till = '')
97
    {
98
        $join = Invoice::leftJoin('users', 'invoices.user_id', '=', 'users.id');
99
        $this->name($name, $join);
100
        $this->invoice_no($invoice_no, $join);
101
        $this->status($status, $join);
102
        $this->currency($currency, $join);
103
        $this->invoice_from($from, $till, $join);
104
        $this->till_date($till, $from, $join);
105
106
        $join = $join->select('id', 'user_id', 'number', 'date', 'grand_total', 'currency', 'status', 'created_at');
107
108
        $join = $join->orderBy('created_at', 'desc')
109
        ->select(
110
            'invoices.id',
111
            'first_name',
112
            'invoices.created_at',
113
            'invoices.currency',
114
            'user_id',
115
            'number',
116
            'status'
117
        );
118
119
        return $join;
120
    }
121
122
    public function name($name, $join)
123
    {
124
        if ($name) {
125
            $join = $join->where('first_name', $name);
126
127
            return $join;
128
        }
129
    }
130
131
    public function invoice_no($invoice_no, $join)
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
132
    {
133
        if ($invoice_no) {
134
            $join = $join->where('number', $invoice_no);
135
136
            return $join;
137
        }
138
    }
139
140
    public function status($status, $join)
141
    {
142
        if ($status) {
143
            $join = $join->where('status', $status);
144
145
            return $join;
146
        }
147
    }
148
149
    public function currency($currency, $join)
150
    {
151
        if ($currency) {
152
            $join = $join->where('invoices.currency', $currency);
153
154
            return $join;
155
        }
156
        $return;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $return seems to be never defined.
Loading history...
157
    }
158
159
    public function invoice_from($from, $till, $join)
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
160
    {
161
        if ($from) {
162
            $fromdate = date_create($from);
163
            $from = date_format($fromdate, 'Y-m-d H:m:i');
164
            $tills = date('Y-m-d H:m:i');
165
            $tillDate = $this->getTillDate($from, $till, $tills);
166
            $join = $join->whereBetween('invoices.created_at', [$from, $tillDate]);
167
168
            return $join;
169
        }
170
171
        return $join;
172
    }
173
174
    public function till_date($till, $from, $join)
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
175
    {
176
        if ($till) {
177
            $tilldate = date_create($till);
178
            $till = date_format($tilldate, 'Y-m-d H:m:i');
179
            $froms = Invoice::first()->created_at;
180
            $fromDate = $this->getFromDate($from, $froms);
181
            $join = $join->whereBetween('invoices.created_at', [$fromDate, $till]);
182
183
            return $join;
184
        }
185
    }
186
187
    public function getExpiryStatus($start, $end, $now)
188
    {
189
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
0 ignored issues
show
Bug introduced by
It seems like whenDateNotSet() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

189
        /** @scrutinizer ignore-call */ 
190
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
Loading history...
190
        if ($whenDateNotSet) {
191
            return $whenDateNotSet;
192
        }
193
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
0 ignored issues
show
Bug introduced by
It seems like whenStartDateSet() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

193
        /** @scrutinizer ignore-call */ 
194
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
Loading history...
194
        if ($whenStartDateSet) {
195
            return $whenStartDateSet;
196
        }
197
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
0 ignored issues
show
Bug introduced by
It seems like whenEndDateSet() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

197
        /** @scrutinizer ignore-call */ 
198
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
Loading history...
198
        if ($whenEndDateSet) {
199
            return $whenEndDateSet;
200
        }
201
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
0 ignored issues
show
Bug introduced by
It seems like whenBothSet() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

201
        /** @scrutinizer ignore-call */ 
202
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
Loading history...
202
        if ($whenBothAreSet) {
203
            return $whenBothAreSet;
204
        }
205
    }
206
207
    public function getTillDate($from, $till, $tills)
208
    {
209
        if ($till) {
210
            $todate = date_create($till);
211
            $tills = date_format($todate, 'Y-m-d H:m:i');
212
        }
213
214
        return $tills;
215
    }
216
217
    public function getFromDate($from, $froms)
218
    {
219
        if ($from) {
220
            $fromdate = date_create($from);
221
            $froms = date_format($fromdate, 'Y-m-d H:m:i');
222
        }
223
224
        return $froms;
225
    }
226
227
    public function postRazorpayPayment($invoiceid, $grand_total)
228
    {
229
        try {
230
            $payment_method = \Session::get('payment_method');
231
            $payment_status = 'success';
232
            $payment_date = \Carbon\Carbon::now()->toDateTimeString();
233
            $amount = $grand_total;
234
            $paymentRenewal = $this->updateInvoicePayment($invoiceid, $payment_method,
235
             $payment_status, $payment_date, $amount);
236
237
            return redirect()->back()->with('success', 'Payment Accepted Successfully');
238
        } catch (\Exception $ex) {
239
            return redirect()->back()->with('fails', $ex->getMessage());
240
        }
241
    }
242
243
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
244
    {
245
        try {
246
            $invoice = Invoice::find($invoiceid);
247
            $invoice_status = 'pending';
248
249
            $payment = $this->payment->create([
250
                'invoice_id'     => $invoiceid,
251
                'user_id'        => $invoice->user_id,
252
                'amount'         => $amount,
253
                'payment_method' => $payment_method,
254
                'payment_status' => $payment_status,
255
                'created_at'     => $payment_date,
256
            ]);
257
            $all_payments = $this->payment
258
            ->where('invoice_id', $invoiceid)
259
            ->where('payment_status', 'success')
260
            ->pluck('amount')->toArray();
261
            $total_paid = array_sum($all_payments);
262
            if ($total_paid >= $invoice->grand_total) {
263
                $invoice_status = 'success';
264
            }
265
            if ($invoice) {
266
                $invoice->status = $invoice_status;
267
                $invoice->save();
268
            }
269
270
            return $payment;
271
        } catch (\Exception $ex) {
272
            Bugsnag::notifyException($ex);
273
274
            throw new \Exception($ex->getMessage());
275
        }
276
    }
277
278
    public function updateInvoice($invoiceid)
279
    {
280
        try {
281
            $invoice = $this->invoice->findOrFail($invoiceid);
282
            $payment = $this->payment->where('invoice_id', $invoiceid)
283
            ->where('payment_status', 'success')->pluck('amount')->toArray();
284
            $total = array_sum($payment);
285
            if ($total < $invoice->grand_total) {
286
                $invoice->status = 'pending';
287
            }
288
            if ($total >= $invoice->grand_total) {
289
                $invoice->status = 'success';
290
            }
291
            if ($total > $invoice->grand_total) {
292
                $user = $invoice->user()->first();
293
                $balance = $total - $invoice->grand_total;
294
                $user->debit = $balance;
295
                $user->save();
296
            }
297
298
            $invoice->save();
299
        } catch (\Exception $ex) {
300
            Bugsnag::notifyException($ex);
301
302
            throw new \Exception($ex->getMessage());
303
        }
304
    }
305
306
    /**
307
     * Remove the specified resource from storage.
308
     *
309
     * @param int $id
310
     *
311
     * @return \Response
312
     */
313
    public function destroy(Request $request)
314
    {
315
        try {
316
            $ids = $request->input('select');
317
            if (!empty($ids)) {
318
                foreach ($ids as $id) {
319
                    $invoice = $this->invoice->where('id', $id)->first();
320
                    if ($invoice) {
321
                        $invoice->delete();
322
                    } else {
323
                        echo "<div class='alert alert-danger alert-dismissable'>
324
                    <i class='fa fa-ban'></i>
325
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
326
                    /* @scrutinizer ignore-type */
327
                    \Lang::get('message.failed').'
328
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
329
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
330
                </div>';
331
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
332
                    }
333
                }
334
                echo "<div class='alert alert-success alert-dismissable'>
335
                    <i class='fa fa-ban'></i>
336
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
337
                    /* @scrutinizer ignore-type */
338
                    \Lang::get('message.success').'
339
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
340
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
341
                </div>';
342
            } else {
343
                echo "<div class='alert alert-danger alert-dismissable'>
344
                    <i class='fa fa-ban'></i>
345
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
346
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
347
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
348
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
349
                </div>';
350
                //echo \Lang::get('message.select-a-row');
351
            }
352
        } catch (\Exception $e) {
353
            echo "<div class='alert alert-danger alert-dismissable'>
354
                    <i class='fa fa-ban'></i>
355
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
356
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
357
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
358
                        '.$e->getMessage().'
359
                </div>';
360
        }
361
    }
362
363
    /*
364
    *Edit payment Total.
365
    */
366
    public function paymentTotalChange(Request $request)
367
    {
368
        try {
369
            $invoice = new Invoice();
370
            $total = $request->input('total');
371
            if ($total == '') {
372
                $total = 0;
373
            }
374
            $paymentid = $request->input('id');
375
            $creditAmtUserId = $this->payment->where('id', $paymentid)->value('user_id');
376
            $creditAmt = $this->payment->where('user_id', $creditAmtUserId)
377
        ->where('invoice_id', '=', 0)->value('amt_to_credit');
378
            $invoices = $invoice->where('user_id', $creditAmtUserId)->orderBy('created_at', 'desc')->get();
379
            $cltCont = new \App\Http\Controllers\User\ClientController();
380
            $invoiceSum = $cltCont->getTotalInvoice($invoices);
381
            if ($total > $invoiceSum) {
382
                $diff = $total - $invoiceSum;
383
                $creditAmt = $creditAmt + $diff;
384
                $total = $invoiceSum;
385
            }
386
            $payment = $this->payment->where('id', $paymentid)->update(['amount'=>$total]);
387
388
            $creditAmtInvoiceId = $this->payment->where('user_id', $creditAmtUserId)
389
        ->where('invoice_id', '!=', 0)->first();
390
            $invoiceId = $creditAmtInvoiceId->invoice_id;
391
            $invoice = $invoice->where('id', $invoiceId)->first();
392
            $grand_total = $invoice->grand_total;
393
            $diffSum = $grand_total - $total;
394
395
            $finalAmt = $creditAmt + $diffSum;
396
            $updatedAmt = $this->payment->where('user_id', $creditAmtUserId)
397
        ->where('invoice_id', '=', 0)->update(['amt_to_credit'=>$creditAmt]);
398
        } catch (\Exception $ex) {
399
            app('log')->info($ex->getMessage());
400
            Bugsnag::notifyException($ex);
401
402
            return redirect()->back()->with('fails', $ex->getMessage());
403
        }
404
    }
405
}
406