Completed
Branch feature-dynamic-fields (a5624d)
by Ashutosh
09:27
created

CoupCodeAndInvoiceSearch   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 300
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 45
eloc 165
dl 0
loc 300
rs 8.8
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A findCost() 0 14 5
B checkCode() 0 37 7
A findCostAfterDiscount() 0 18 2
A advanceSearch() 0 25 1
A name() 0 6 2
A currency() 0 8 2
A getFromDate() 0 8 2
A getExpiryStatus() 0 17 5
A getTillDate() 0 8 2
A invoice_from() 0 13 2
A invoice_no() 0 6 2
A till_date() 0 10 2
A status() 0 6 2
A destroy() 0 46 5
A updateInvoicePayment() 0 32 4

How to fix   Complexity   

Complex Class

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

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

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

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
104
        $this->invoice_from($from, $till, $join);
105
        $this->till_date($till, $from, $join);
106
107
        $join = $join->select('id', 'user_id', 'number', 'date', 'grand_total', 'currency', 'status', 'created_at');
108
109
        $join = $join->orderBy('created_at', 'desc')
110
        ->select(
111
            'invoices.id',
112
            'first_name',
113
            'invoices.created_at',
114
            'invoices.currency',
115
            'user_id',
116
            'number',
117
            'status'
118
        );
119
120
        return $join;
121
    }
122
123
    public function name($name, $join)
124
    {
125
        if ($name) {
126
            $join = $join->where('first_name', $name);
127
128
            return $join;
129
        }
130
    }
131
132
    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...
133
    {
134
        if ($invoice_no) {
135
            $join = $join->where('number', $invoice_no);
136
137
            return $join;
138
        }
139
    }
140
141
    public function status($status, $join)
142
    {
143
        if ($status) {
144
            $join = $join->where('status', $status);
145
146
            return $join;
147
        }
148
    }
149
150
    public function currency($currency, $join)
151
    {
152
        if ($currency) {
153
            $join = $join->where('invoices.currency', $currency);
154
155
            return $join;
156
        }
157
        $return;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $return seems to be never defined.
Loading history...
158
    }
159
160
    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...
161
    {
162
        if ($from) {
163
            $fromdate = date_create($from);
164
            $from = date_format($fromdate, 'Y-m-d H:m:i');
165
            $tills = date('Y-m-d H:m:i');
166
            $tillDate = $this->getTillDate($from, $till, $tills);
167
            $join = $join->whereBetween('invoices.created_at', [$from, $tillDate]);
168
169
            return $join;
170
        }
171
172
        return $join;
173
    }
174
175
    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...
176
    {
177
        if ($till) {
178
            $tilldate = date_create($till);
179
            $till = date_format($tilldate, 'Y-m-d H:m:i');
180
            $froms = Invoice::first()->created_at;
181
            $fromDate = $this->getFromDate($from, $froms);
182
            $join = $join->whereBetween('invoices.created_at', [$fromDate, $till]);
183
184
            return $join;
185
        }
186
    }
187
188
    public function getExpiryStatus($start, $end, $now)
189
    {
190
        $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

190
        /** @scrutinizer ignore-call */ 
191
        $whenDateNotSet = $this->whenDateNotSet($start, $end);
Loading history...
191
        if ($whenDateNotSet) {
192
            return $whenDateNotSet;
193
        }
194
        $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

194
        /** @scrutinizer ignore-call */ 
195
        $whenStartDateSet = $this->whenStartDateSet($start, $end, $now);
Loading history...
195
        if ($whenStartDateSet) {
196
            return $whenStartDateSet;
197
        }
198
        $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

198
        /** @scrutinizer ignore-call */ 
199
        $whenEndDateSet = $this->whenEndDateSet($start, $end, $now);
Loading history...
199
        if ($whenEndDateSet) {
200
            return $whenEndDateSet;
201
        }
202
        $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

202
        /** @scrutinizer ignore-call */ 
203
        $whenBothAreSet = $this->whenBothSet($start, $end, $now);
Loading history...
203
        if ($whenBothAreSet) {
204
            return $whenBothAreSet;
205
        }
206
    }
207
208
    public function getTillDate($from, $till, $tills)
209
    {
210
        if ($till) {
211
            $todate = date_create($till);
212
            $tills = date_format($todate, 'Y-m-d H:m:i');
213
        }
214
215
        return $tills;
216
    }
217
218
    public function getFromDate($from, $froms)
219
    {
220
        if ($from) {
221
            $fromdate = date_create($from);
222
            $froms = date_format($fromdate, 'Y-m-d H:m:i');
223
        }
224
225
        return $froms;
226
    }
227
228
    public function updateInvoicePayment($invoiceid, $payment_method, $payment_status, $payment_date, $amount)
229
    {
230
        try {
231
            $invoice = Invoice::find($invoiceid);
232
            $invoice_status = 'pending';
233
234
            $payment = $this->payment->create([
235
                'invoice_id'     => $invoiceid,
236
                'user_id'        => $invoice->user_id,
237
                'amount'         => $amount,
238
                'payment_method' => $payment_method,
239
                'payment_status' => $payment_status,
240
                'created_at'     => $payment_date,
241
            ]);
242
            $all_payments = $this->payment
243
            ->where('invoice_id', $invoiceid)
244
            ->where('payment_status', 'success')
245
            ->pluck('amount')->toArray();
246
            $total_paid = array_sum($all_payments);
247
            if ($total_paid >= $invoice->grand_total) {
248
                $invoice_status = 'success';
249
            }
250
            if ($invoice) {
251
                $invoice->status = $invoice_status;
252
                $invoice->save();
253
            }
254
255
            return $payment;
256
        } catch (\Exception $ex) {
257
            Bugsnag::notifyException($ex);
258
259
            throw new \Exception($ex->getMessage());
260
        }
261
    }
262
263
    /**
264
     * Remove the specified resource from storage.
265
     *
266
     * @param int $id
267
     *
268
     * @return \Response
269
     */
270
    public function destroy(Request $request)
271
    {
272
        try {
273
            $ids = $request->input('select');
274
            if (!empty($ids)) {
275
                foreach ($ids as $id) {
276
                    $invoice = $this->invoice->where('id', $id)->first();
277
                    if ($invoice) {
278
                        $invoice->delete();
279
                    } else {
280
                        echo "<div class='alert alert-danger alert-dismissable'>
281
                    <i class='fa fa-ban'></i>
282
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
283
                    /* @scrutinizer ignore-type */
284
                    \Lang::get('message.failed').'
285
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
286
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
287
                </div>';
288
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
289
                    }
290
                }
291
                echo "<div class='alert alert-success alert-dismissable'>
292
                    <i class='fa fa-ban'></i>
293
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
294
                    /* @scrutinizer ignore-type */
295
                    \Lang::get('message.success').'
296
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
297
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
298
                </div>';
299
            } else {
300
                echo "<div class='alert alert-danger alert-dismissable'>
301
                    <i class='fa fa-ban'></i>
302
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
303
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
304
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
305
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
306
                </div>';
307
                //echo \Lang::get('message.select-a-row');
308
            }
309
        } catch (\Exception $e) {
310
            echo "<div class='alert alert-danger alert-dismissable'>
311
                    <i class='fa fa-ban'></i>
312
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
313
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
314
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
315
                        '.$e->getMessage().'
316
                </div>';
317
        }
318
    }
319
}
320