Completed
Pull Request — master (#113)
by vijay
105:56 queued 52:59
created

PromotionController::edit()   B

Complexity

Conditions 2
Paths 6

Size

Total Lines 24
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 2 Features 0
Metric Value
c 4
b 2
f 0
dl 0
loc 24
rs 8.9713
cc 2
eloc 9
nc 6
nop 1
1
<?php
2
3
namespace App\Http\Controllers\Payment;
4
5
use App\Http\Controllers\Controller;
6
use App\Http\Requests\Payment\PromotionRequest;
7
use App\Model\Order\Invoice;
8
use App\Model\Payment\PromoProductRelation;
9
use App\Model\Payment\Promotion;
10
use App\Model\Payment\PromotionType;
11
use App\Model\Product\Product;
12
use Darryldecode\Cart\CartCondition;
13
use Illuminate\Http\Request;
14
15
class PromotionController extends Controller
16
{
17
    public $promotion;
18
    public $product;
19
    public $promoRelation;
20
    public $type;
21
    public $invoice;
22
23
    public function __construct()
24
    {
25
        $this->middleware('auth');
26
        $this->middleware('admin');
27
28
        $promotion = new Promotion();
29
        $this->promotion = $promotion;
30
31
        $product = new Product();
32
        $this->product = $product;
33
34
        $promoRelation = new PromoProductRelation();
35
        $this->promoRelation = $promoRelation;
36
37
        $type = new PromotionType();
38
        $this->type = $type;
39
40
        $invoice = new Invoice();
41
        $this->invoice = $invoice;
42
    }
43
44
    /**
45
     * Display a listing of the resource.
46
     *
47
     * @return Response
48
     */
49
    public function index()
50
    {
51
        try {
52
            return view('themes.default1.payment.promotion.index');
53
        } catch (\Exception $ex) {
54
            return redirect()->back()->with('fails', $ex->getMessage());
55
        }
56
    }
57
58
    public function GetPromotion()
59
    {
60
        return \Datatable::collection($this->promotion->select('code', 'type', 'id')->get())
61
                        ->addColumn('#', function ($model) {
62
                            return "<input type='checkbox' value=".$model->id.' name=select[] id=check>';
63
                        })
64
                        ->showColumns('code')
65
                        ->addColumn('type', function ($model) {
66
                            return $this->type->where('id', $model->type)->first()->name;
67
                        })
68
                        ->addColumn('products', function ($model) {
69
                            $selected = $this->promoRelation->select('product_id')->where('promotion_id', $model->id)->get();
70
71
                            foreach ($selected as $key => $select) {
72
                                $result[$key] = $this->product->where('id', $select->product_id)->first()->name;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = 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...
73
                            }
74
                            if (!empty($result)) {
75
                                return implode(',', $result);
76
                            } else {
77
                                return 'None';
78
                            }
79
                        })
80
                        ->addColumn('action', function ($model) {
81
                            return '<a href='.url('promotions/'.$model->id.'/edit')." class='btn btn-sm btn-primary'>Edit</a>";
82
                        })
83
                        ->searchColumns('products')
84
                        ->orderColumns('code')
85
                        ->make();
86
    }
87
88
    /**
89
     * Show the form for creating a new resource.
90
     *
91
     * @return Response
92
     */
93 View Code Duplication
    public function create()
94
    {
95
        try {
96
            $product = $this->product->lists('name', 'id')->toArray();
97
            $type = $this->type->lists('name', 'id')->toArray();
98
99
            return view('themes.default1.payment.promotion.create', compact('product', 'type'));
100
        } catch (\Exception $ex) {
101
            return redirect()->back()->with('fails', $ex->getMessage());
102
        }
103
    }
104
105
    /**
106
     * Store a newly created resource in storage.
107
     *
108
     * @return Response
109
     */
110
    public function store(PromotionRequest $request)
111
    {
112
        try {
113
            $promo = $this->promotion->fill($request->input())->save();
0 ignored issues
show
Bug introduced by
It seems like $request->input() targeting Illuminate\Http\Request::input() can also be of type string; however, Illuminate\Database\Eloquent\Model::fill() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Unused Code introduced by
$promo is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
114
            //dd($this->promotion);
115
            $products = $request->input('applied');
116
117
            foreach ($products as $product) {
0 ignored issues
show
Bug introduced by
The expression $products 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...
118
                $this->promoRelation->create(['product_id' => $product, 'promotion_id' => $this->promotion->id]);
119
            }
120
121
            return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
122
        } catch (Exception $ex) {
0 ignored issues
show
Bug introduced by
The class App\Http\Controllers\Payment\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
123
            return redirect()->back()->with('fails', $ex->getMessage());
124
        }
125
    }
126
127
    /**
128
     * Display the specified resource.
129
     *
130
     * @param int $id
131
     *
132
     * @return Response
133
     */
134
    public function show($id)
135
    {
136
        //
137
    }
138
139
    /**
140
     * Show the form for editing the specified resource.
141
     *
142
     * @param int $id
143
     *
144
     * @return Response
145
     */
146
    public function edit($id)
147
    {
148
        try {
149
            $promotion = $this->promotion->where('id', $id)->first();
150
            $product = $this->product->lists('name', 'id')->toArray();
151
            $type = $this->type->lists('name', 'id')->toArray();
152
//            if ($promotion->start != null) {
153
//                $start = $promotion->start;
154
//            } else {
155
//                $start = null;
156
//            }
157
//            if ($promotion->expiry != null) {
158
//                $expiry=$promotion->expiry;
159
//            } else {
160
//                $expiry = null;
161
//            }
162
            $selectedProduct = $this->promoRelation->where('promotion_id', $id)->lists('product_id', 'product_id')->toArray();
163
            //dd($selectedProduct);
164
            return view('themes.default1.payment.promotion.edit', compact('product', 'promotion', 'selectedProduct', 'type'));
165
        } catch (\Exception $ex) {
166
            dd($ex);
167
            //return redirect()->back()->with('fails',$ex->getMessage());
168
        }
169
    }
170
171
    /**
172
     * Update the specified resource in storage.
173
     *
174
     * @param int $id
175
     *
176
     * @return Response
177
     */
178
    public function update($id, PromotionRequest $request)
179
    {
180
        try {
181
            $promotion = $this->promotion->where('id', $id)->first();
182
            $promotion->fill($request->input())->save();
183
            /* Delete the products has this id */
184
            $deletes = $this->promoRelation->where('promotion_id', $id)->get();
185
            foreach ($deletes as $delete) {
186
                $delete->delete();
187
            }
188
            /* Update the realtion details */
189
            $products = $request->input('applied');
190
            foreach ($products as $product) {
0 ignored issues
show
Bug introduced by
The expression $products 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...
191
                $this->promoRelation->create(['product_id' => $product, 'promotion_id' => $promotion->id]);
192
            }
193
194
            return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
195
        } catch (Exception $ex) {
0 ignored issues
show
Bug introduced by
The class App\Http\Controllers\Payment\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
196
            return redirect()->back()->with('fails', $ex->getMessage());
197
        }
198
    }
199
200
    /**
201
     * Remove the specified resource from storage.
202
     *
203
     * @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...
204
     *
205
     * @return Response
206
     */
207 View Code Duplication
    public function destroy(Request $request)
208
    {
209
        try {
210
            $ids = $request->input('select');
211
            if (!empty($ids)) {
212
                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...
213
                    $promotion = $this->promotion->where('id', $id)->first();
214
                    if ($promotion) {
215
                        $promotion->delete();
216
                    } else {
217
                        echo "<div class='alert alert-danger alert-dismissable'>
218
                    <i class='fa fa-ban'></i>
219
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
220
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
221
                        '.\Lang::get('message.no-record').'
222
                </div>';
223
                        //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
224
                    }
225
                }
226
                echo "<div class='alert alert-success alert-dismissable'>
227
                    <i class='fa fa-ban'></i>
228
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.success').'
229
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
230
                        '.\Lang::get('message.deleted-successfully').'
231
                </div>';
232
            } else {
233
                echo "<div class='alert alert-danger alert-dismissable'>
234
                    <i class='fa fa-ban'></i>
235
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
236
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
237
                        '.\Lang::get('message.select-a-row').'
238
                </div>';
239
                //echo \Lang::get('message.select-a-row');
240
            }
241
        } catch (\Exception $e) {
242
            echo "<div class='alert alert-danger alert-dismissable'>
243
                    <i class='fa fa-ban'></i>
244
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
245
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
246
                        '.$e->getMessage().'
247
                </div>';
248
        }
249
    }
250
251
    public function GetCode()
252
    {
253
        try {
254
            $code = str_random(6);
255
            echo strtoupper($code);
256
        } catch (\Exception $ex) {
257
            return redirect()->back()->with('fails', $ex->getMessage());
258
        }
259
    }
260
261
    public function checkCode($code, $productid)
262
    {
263
        try {
264
            $promo = $this->promotion->where('code', $code)->first();
265
            //check promotion code is valid
266
            if (!$promo) {
267
                return redirect()->back()->with('fails', \Lang::get('message.no-such-code'));
268
            }
269
            $relation = $promo->relation()->get();
270
            //check the relation between code and product
271
            if (count($relation) == 0) {
272
                return redirect()->back()->with('fails', \Lang::get('message.no-product-related-to-this-code'));
273
            }
274
            //check the usess
275
            $uses = $this->checkNumberOfUses($code);
276
            //dd($uses);
277
            if ($uses != 'success') {
278
                return redirect()->back()->with('fails', \Lang::get('message.usage-of-code-completed'));
279
            }
280
            //check for the expiry date
281
            $expiry = $this->checkExpiry($code);
282
            //dd($expiry);
283
            if ($expiry != 'success') {
284
                return redirect()->back()->with('fails', \Lang::get('message.usage-of-code-expired'));
285
            }
286
            $value = $this->findCostAfterDiscount($promo->id, $productid);
287
            //dd($value);
288
            //dd($promo->code);
289
            //return the updated cartcondition
290
            $coupon = new CartCondition([
291
                'name'   => $promo->code,
292
                'type'   => 'coupon',
293
                'target' => 'item',
294
                'value'  => $value,
295
            ]);
296
297
            $items = \Cart::getContent();
298
            foreach ($items as $item) {
299
                if (count($item->conditions) == 2) {
300
                    \Cart::addItemCondition($productid, $coupon);
301
                }
302
            }
303
304
            return 'success';
305
        } catch (\Exception $ex) {
306
            dd($ex);
307
            throw new \Exception(\Lang::get('message.check-code-error'));
308
        }
309
    }
310
311 View Code Duplication
    public function findCostAfterDiscount($promoid, $productid)
312
    {
313
        try {
314
            $promotion = $this->promotion->findOrFail($promoid);
315
            $product = $this->product->findOrFail($productid);
316
            $promotion_type = $promotion->type;
317
            $promotion_value = $promotion->value;
318
            $product_price = $product->price()->first()->sales_price;
319
            if (!$product_price) {
320
                $product_price = $product->price()->first()->price;
321
            }
322
            $updated_price = $this->findCost($promotion_type, $promotion_value, $product_price, $productid);
323
324
            return $updated_price;
325
        } catch (\Exception $ex) {
326
            throw new \Exception(\Lang::get('message.find-discount-error'));
327
        }
328
    }
329
330
    public function findCost($type, $value, $price, $productid)
331
    {
332
        try {
333
            switch ($type) {
334
335
                case 1:
336
                    $percentage = $price * ($value / 100);
337
338
                    return '-'.$percentage;
339
                case 2:
340
                    return '-'.$value;
341
                case 3:
342
                    \Cart::update($productid, [
343
                        'price' => $value,
344
                    ]);
345
346
                    return '-0';
347
                case 4:
348
                    return '-'.$price;
349
            }
350
        } catch (\Exception $ex) {
351
            throw new \Exception(\Lang::get('message.find-cost-error'));
352
        }
353
    }
354
355 View Code Duplication
    public function checkNumberOfUses($code)
356
    {
357
        try {
358
            $promotion = $this->promotion->where('code', $code)->first();
359
            $uses = $promotion->uses;
360
            if ($uses == 0) {
361
                return 'success';
362
            }
363
            $used_number = $this->invoice->where('coupon_code', $code)->count();
364
            if ($uses >= $used_number) {
365
                return 'success';
366
            } else {
367
                return 'fails';
368
            }
369
        } catch (\Exception $ex) {
370
            throw new \Exception(\Lang::get('message.find-cost-error'));
371
        }
372
    }
373
374
    public function checkExpiry($code)
375
    {
376
        try {
377
            $promotion = $this->promotion->where('code', $code)->first();
378
            $start = $promotion->start;
379
            $end = $promotion->expiry;
380
            //dd($end);
381
            $now = \Carbon\Carbon::now();
382
            //both not set, always true
383
            if ($start == null && $end == null) {
384
                return 'success';
385
            }
386
            //only starting date set, check the date is less or equel to today
387 View Code Duplication
            if ($start != null && $end == null) {
388
                if ($start <= $now) {
389
                    return 'success';
390
                }
391
            }
392
            //only ending date set, check the date is greater or equel to today
393 View Code Duplication
            if ($end != null && $start == null) {
394
                if ($end >= $now) {
395
                    return 'success';
396
                }
397
            }
398
            //both set
399 View Code Duplication
            if ($end != null && $start != null) {
400
                if ($end >= $now && $start <= $now) {
401
                    return 'success';
402
                }
403
            }
404
        } catch (\Exception $ex) {
405
            dd($ex);
406
            throw new \Exception(\Lang::get('message.check-expiry'));
407
        }
408
    }
409
}
410