Completed
Push — development ( db1c54...00218f )
by Ashutosh
10:15
created

ProductController::fileDestroy()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 50
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 50
rs 8.8497
c 0
b 0
f 0
cc 6
nc 16
nop 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A ProductController::getProductField() 0 19 4
1
<?php
2
3
namespace App\Http\Controllers\Product;
4
5
// use Illuminate\Http\Request;
6
    use App\Model\Order\Order;
7
    use App\Model\Payment\Currency;
8
    use App\Model\Payment\Period;
9
    use App\Model\Payment\Plan;
10
    use App\Model\Payment\Tax;
11
    use App\Model\Payment\TaxClass;
12
    use App\Model\Payment\TaxProductRelation;
13
    use App\Model\Product\Price;
14
    use App\Model\Product\Product;
15
    use App\Model\Product\ProductGroup;
16
    use App\Model\Product\ProductUpload;
17
    use App\Model\Product\Subscription;
18
    use App\Model\Product\Type;
19
    use Bugsnag\BugsnagLaravel\Facades\Bugsnag;
20
    use Illuminate\Http\Request;
21
    use Illuminate\Support\Facades\Input;
22
    use Spatie\Activitylog\Models\Activity;
23
24
    // use Input;
25
26
    class ProductController extends BaseProductController
27
    {
28
        public $product;
29
        public $price;
30
        public $type;
31
        public $subscription;
32
        public $currency;
33
        public $group;
34
        public $plan;
35
        public $tax;
36
        public $tax_relation;
37
        public $tax_class;
38
        public $product_upload;
39
40
        public function __construct()
41
        {
42
            $this->middleware('auth');
43
            $this->middleware('admin', ['except' => ['adminDownload', 'userDownload']]);
44
45
            $product = new Product();
46
            $this->product = $product;
47
48
            $price = new Price();
49
            $this->price = $price;
50
51
            $type = new Type();
52
            $this->type = $type;
53
54
            $subscription = new Subscription();
55
            $this->subscription = $subscription;
56
57
            $currency = new Currency();
58
            $this->currency = $currency;
59
60
            $group = new ProductGroup();
61
            $this->group = $group;
62
63
            $plan = new Plan();
64
            $this->plan = $plan;
65
66
            $tax = new Tax();
67
            $this->tax = $tax;
68
69
            $period = new Period();
70
            $this->period = $period;
71
72
            $tax_relation = new TaxProductRelation();
73
            $this->tax_relation = $tax_relation;
74
75
            $tax_class = new TaxClass();
76
            $this->tax_class = $tax_class;
77
78
            $product_upload = new ProductUpload();
79
            $this->product_upload = $product_upload;
80
        }
81
82
        /**
83
         * Display a listing of the resource.
84
         *
85
         * @return \Response
86
         */
87
        public function index()
88
        {
89
            try {
90
                return view('themes.default1.product.product.index');
91
            } catch (\Exception $e) {
92
                Bugsnag::notifyException($e);
93
94
                return redirect('/')->with('fails', $e->getMessage());
95
            }
96
        }
97
98
        /**
99
         * Display a listing of the resource.
100
         *
101
         * @return \Response
102
         */
103
        public function getProducts()
104
        {
105
            try {
106
                $new_product = Product::select('id', 'name', 'type', 'group')->get();
107
108
                return\ DataTables::of($new_product)
109
            // return \Datatable::collection($this->product->select('id', 'name', 'type', 'group')->where('id', '!=', 1)->get())
110
                            ->addColumn('checkbox', function ($model) {
111
                                return "<input type='checkbox' class='product_checkbox' value=".$model->id.' name=select[] id=check>';
112
                            })
113
                            ->addColumn('name', function ($model) {
114
                                return ucfirst($model->name);
115
                            })
116
                            ->addColumn('type', function ($model) {
117
                                //dd($model->type());
118
                                if ($this->type->where('id', $model->type)->first()) {
119
                                    return $this->type->where('id', $model->type)->first()->name;
120
                                } else {
121
                                    return 'Not available';
122
                                }
123
                            })
124
                            ->addColumn('group', function ($model) {
125
                                //dd($model->type());
126
                                if ($this->group->where('id', $model->group)->first()) {
127
                                    return $this->group->where('id', $model->group)->first()->name;
128
                                } else {
129
                                    return 'Not available';
130
                                }
131
                            })
132
                            ->addColumn('price', function ($model) {
133
                                if ($this->price->where('product_id', $model->id)->first()) {
134
                                    return $this->price->where('product_id', $model->id)->first()->price;
135
                                } else {
136
                                    return 'Not available';
137
                                }
138
                            })
139
                            ->addColumn('currency', function ($model) {
140
                                if ($this->price->where('product_id', $model->id)->first()) {
141
                                    return $this->price->where('product_id', $model->id)->first()->currency;
142
                                } else {
143
                                    return 'Not available';
144
                                }
145
                            })
146
                            ->addColumn('Action', function ($model) {
147
                                $url = '';
148
                                if ($model->type == 2) {
149
                                    $url = '<a href='.url('product/download/'.$model->id)." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-download' style='color:white;'> </i>&nbsp;&nbsp;Download</a>";
150
                                }
151
152
                                return '<p><a href='.url('products/'.$model->id.'/edit')." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-edit' style='color:white;'> </i>&nbsp;&nbsp;Edit</a>&nbsp;$url</p>";
153
                            })
154
155
                            ->rawColumns(['checkbox', 'name', 'type', 'group', 'price', 'currency', 'Action'])
156
                            ->make(true);
157
            } catch (\Exception $e) {
158
                Bugsnag::notifyException($e);
159
160
                return redirect()->back()->with('fails', $e->getMessage());
161
            }
162
        }
163
164
        public function getUpload($id)
165
        {
166
            $new_upload = ProductUpload::where('product_id', '=', $id)->select('id', 'product_id', 'title', 'description', 'version', 'file')->get();
167
168
            return \DataTables::of($new_upload)
169
        ->addColumn('checkbox', function ($model) {
170
            return "<input type='checkbox' class='upload_checkbox' value=".$model->id.' name=select[] id=checks>';
171
        })
172
173
        ->addColumn('product_id', function ($model) {
174
            return ucfirst($this->product->where('id', $model->product_id)->first()->name);
175
        })
176
177
        ->addColumn('title', function ($model) {
178
            return ucfirst($model->title);
179
        })
180
        ->addColumn('description', function ($model) {
181
            return ucfirst($model->description);
182
        })
183
        ->addColumn('version', function ($model) {
184
            return $model->version;
185
        })
186
187
        ->addColumn('file', function ($model) {
188
            return $model->file;
189
        })
190
        ->addColumn('action', function ($model) {
191
            return '<a href='.('#edit-upload-option/'.$model->id).'  class=" btn btn-sm btn-primary " data-title="'.$model->title.'" data-description="'.$model->description.'" data-version="'.$model->version.'" data-id="'.$model->id.'" onclick="openEditPopup(this)" >Edit</a>';
192
        })
193
        ->rawcolumns(['checkbox', 'product_id', 'title', 'description', 'version', 'file', 'action'])
194
        ->make(true);
195
        }
196
197
        // Save file Info in Modal popup
198
        public function save(Request $request)
199
        {
200
            try {
201
                $product_id = Product::where('name', '=', $request->input('product'))->select('id')->first();
202
203
                $this->product_upload->product_id = $product_id->id;
204
                $this->product_upload->title = $request->input('title');
205
                $this->product_upload->description = $request->input('description');
206
                $this->product_upload->version = $request->input('version');
207
208
                if ($request->file) {
209
                    $file = $request->file('file')->getClientOriginalName();
210
211
                    $destination = storage_path().'/products';
212
                    $request->file('file')->move($destination, $file);
213
                    $this->product_upload->file = $file;
214
                }
215
                $this->product_upload->save();
216
                return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
217
            } catch (\Exception $e) {
218
                Bugsnag::notifyException($e);
219
220
                return redirect()->with('fails', $e->getMessage());
221
            }
222
        }
223
224
        //Update the File Info
225
        public function uploadUpdate($id, Request $request)
226
        {
227
            $file_upload = ProductUpload::find($id);
228
229
            $file_upload->title = $request->input('title');
230
            $file_upload->description = $request->input('description');
231
            $file_upload->version = $request->input('version');
232
            if ($request->file) {
233
                $file = $request->file('file')->getClientOriginalName();
234
235
                $destination = storage_path().'/products';
236
                $request->file('file')->move($destination, $file);
237
                $file_upload->file = $file;
238
            }
239
            $file_upload->save();
240
241
            return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
242
        }
243
244
        /**
245
         * Show the form for creating a new resource.
246
         *
247
         * @return Response
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\Product\Response was not found. Did you mean Response? If so, make sure to prefix the type with \.
Loading history...
248
         */
249
        public function create()
250
        {
251
            try {
252
                /*
253
                 * server url
254
                 */
255
                $url = $this->GetMyUrl();
256
                $i = $this->product->orderBy('created_at', 'desc')->first()->id + 1;
257
                $cartUrl = $url.'/pricing?id='.$i;
258
                $type = $this->type->pluck('name', 'id')->toArray();
259
                $subscription = $this->plan->pluck('name', 'id')->toArray();
260
                $currency = $this->currency->pluck('name', 'code')->toArray();
261
                $group = $this->group->pluck('name', 'id')->toArray();
262
                $products = $this->product->pluck('name', 'id')->toArray();
263
                $periods = $this->period->pluck('name', 'days')->toArray();
264
                $taxes = $this->tax_class->pluck('name', 'id')->toArray();
265
266
                return view('themes.default1.product.product.create', compact('subscription', 'type', 'periods', 'currency', 'group', 'cartUrl', 'products', 'taxes'));
267
            } catch (\Exception $e) {
268
                Bugsnag::notifyException($e);
269
270
                return redirect()->back()->with('fails', $e->getMessage());
271
            }
272
        }
273
274
        /**
275
         * Store a newly created resource in storage.
276
         *
277
         * @return Response
278
         */
279
        public function store(Request $request)
280
        {
281
            $input = $request->all();
282
            // dd($input);
283
            $v = \Validator::make($input, [
284
                        'name'    => 'required|unique:products,name',
285
                        'type'    => 'required',
286
                        'group'   => 'required',
287
                        // 'image'   => 'sometimes | mimes:jpeg,jpg,png,gif | max:1000',
288
                        // 'version' => 'required',
289
            ]);
290
          if ($v->fails()) {
291
                //     $currency = $input['currency'];
292
293
                return redirect()->back()
294
                        ->withErrors($v)
295
                        ->withInput()
296
                        ->with('currency');
297
            }
298
299
            try {
300
                if ($request->hasFile('image')) {
301
                    $image = $request->file('image')->getClientOriginalName();
302
                    $imagedestinationPath = 'dist/product/images';
303
                    $request->file('image')->move($imagedestinationPath, $image);
304
                    $this->product->image = $image;
305
                }
306
307
                $product = $this->product;
308
                $product->fill($request->except('image', 'file'))->save();
309
                // Product::where('id',$product->id)->update(['name'=>$request->names]);
310
311
                $product_id = $product->id;
312
                $subscription = $request->input('subscription');
313
314
                $price = $request->input('price');
315
                // $price=
316
317
                $sales_price = $request->input('sales_price');
318
                $currencies = $request->input('currency');
319
                $taxes = $request->input('tax');
320
                 if ($taxes) {
321
                    foreach ($taxes as $key=>$value) {
322
                        $newtax = new TaxProductRelation();
323
                        $newtax->product_id = $product_id;
324
                        $newtax->tax_class_id = $value;
325
                        $newtax->save();
326
                    }
327
                }
328
329
                return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
330
            } catch (\Exception $e) {
331
                Bugsnag::notifyException($e);
332
333
                return redirect()->with('fails', $e->getMessage());
334
            }
335
        }
336
337
        /**
338
         * Show the form for editing the specified resource.
339
         *
340
         * @param int $id
341
         *
342
         * @return Response
343
         */
344
        public function edit($id)
345
        {
346
            try {
347
                $type = $this->type->pluck('name', 'id')->toArray();
348
349
                $subscription = $this->plan->pluck('name', 'id')->toArray();
350
                $currency = $this->currency->pluck('name', 'code')->toArray();
351
                $group = $this->group->pluck('name', 'id')->toArray();
352
                $products = $this->product->pluck('name', 'id')->toArray();
353
                $periods = $this->period->pluck('name', 'days')->toArray();
354
                $url = $this->GetMyUrl();
355
                $cartUrl = $url.'/cart?id='.$id;
356
                $product = $this->product->where('id', $id)->first();
357
                $price = $this->price->where('product_id', $product->id);
358
                foreach ($currency as $key => $value) {
359
                    if ($this->price->where('product_id', $product->id)->where('currency', $key)->first()) {
360
                        $regular[$key] = $this->price->where('product_id', $product->id)->where('currency', $key)->first()->price;
361
                        $sales[$key] = $this->price->where('product_id', $product->id)->where('currency', $key)->first()->sales_price;
362
                    } else {
363
                        $regular[$key] = '';
364
                        $sales[$key] = '';
365
                    }
366
                }
367
368
                $taxes = $this->tax_class->pluck('name', 'id')->toArray();
369
                // dd($taxes);
370
                $saved_taxes = $this->tax_relation->where('product_id', $id)->get();
371
                $savedTaxes = $this->tax_relation->where('product_id', $id)->pluck('tax_class_id')->toArray();
372
373
                return view('themes.default1.product.product.edit', compact('product', 'periods', 'type', 'subscription', 'currency', 'group', 'price', 'cartUrl', 'products', 'regular', 'sales', 'taxes', 'saved_taxes', 'savedTaxes'));
374
            } catch (\Exception $e) {
375
                Bugsnag::notifyException($e);
376
377
                return redirect()->back()->with('fails', $e->getMessage());
378
            }
379
        }
380
381
        /**
382
         * Update the specified resource in storage.
383
         *
384
         * @param int $id
385
         *
386
         * @return Response
387
         */
388
        public function update($id, Request $request)
389
        {
390
            $input = $request->all();
391
            $v = \Validator::make($input, [
392
                        'name'    => 'required',
393
                        'type'    => 'required',
394
                        'group'   => 'required',
395
                        'image'   => 'sometimes | mimes:jpeg,jpg,png,gif | max:1000',
396
    //                    'subscription' => 'required',
397
    //                    'currency.*' => 'required',
398
    //                    'price.*' => 'required',
399
            ]);
400
401
            if ($v->fails()) {
402
                return redirect()->back()->with('errors', $v->errors());
403
            }
404
405
            try {
406
                $product = $this->product->where('id', $id)->first();
407
                if ($request->hasFile('image')) {
408
                    $image = $request->file('image')->getClientOriginalName();
409
                    $imagedestinationPath = 'dist/product/images';
410
                    $request->file('image')->move($imagedestinationPath, $image);
411
                    $product->image = $image;
412
                }
413
                if ($request->hasFile('file')) {
414
                    $file = $request->file('file')->getClientOriginalName();
415
                    $filedestinationPath = storage_path().'/products';
416
                    $request->file('file')->move($filedestinationPath, $file);
417
                    $product->file = $file;
418
                }
419
                $product->fill($request->except('image', 'file'))->save();
420
                $this->updateVersionFromGithub($product->id);
421
422
                $product_id = $product->id;
423
                $subscription = $request->input('subscription');
424
                $cost = $request->input('price');
425
                $sales_price = $request->input('sales_price');
426
                $currencies = $request->input('currency');
427
                $prices = $this->price->where('product_id', $product->id)->get();
428
429
                if (count($currencies) > 0) {
430
                    foreach ($prices as $price) {
431
                        $price->delete();
432
                    }
433
434
                    foreach ($currencies as $key => $currency) {
435
                        $this->price->create(['product_id' => $product_id, 'currency' => $currency, 'price' => $cost[$key], 'sales_price' => $sales_price[$key]]);
436
                    }
437
                }
438
                //add tax class to tax_product_relation table
439
                $taxes = $request->input('tax');
440
                if ($taxes) {
441
                    $this->tax_relation->where('product_id', $product_id)->delete();
442
                    foreach ($taxes as $tax) {
443
                        $newTax = new TaxProductRelation();
444
                        $newTax->product_id = $product_id;
445
                        $newTax->tax_class_id = $tax;
446
                        $newTax->save();
447
                    }
448
                }
449
450
                return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
451
            } catch (\Exception $e) {
452
                Bugsnag::notifyException($e);
453
                return redirect()->back()->with('fails', $e->getMessage());
454
            }
455
        }
456
457
        /**
458
         * Remove the specified resource from storage.
459
         *
460
         * @param int $id
461
         *
462
         * @return Response
463
         */
464
        public function destroy(Request $request)
465
        {
466
            try {
467
                $ids = $request->input('select');
468
                if (!empty($ids)) {
469
                    foreach ($ids as $id) {
470
                        if ($id != 1) {
471
                            $product = $this->product->where('id', $id)->first();
472
                            if ($product) {
473
                                $product->delete();
474
                            } else {
475
                                echo "<div class='alert alert-danger alert-dismissable'>
476
                    <i class='fa fa-ban'></i>
477
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */\Lang::get('message.failed').'
478
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
479
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
480
                </div>';
481
                                //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
482
                            }
483
                            echo "<div class='alert alert-success alert-dismissable'>
484
                    <i class='fa fa-ban'></i>
485
                    <b>"./** @scrutinizer ignore-type */
486
                    \Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */ \Lang::get('message.success').'
487
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
488
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
489
                </div>';
490
                        } else {
491
                            echo "<div class='alert alert-danger alert-dismissable'>
492
                    <i class='fa fa-ban'></i>
493
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
494
                    /* @scrutinizer ignore-type */\Lang::get('message.failed').'
495
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
496
                        './* @scrutinizer ignore-type */ \Lang::get('message.can-not-delete-default').'
497
                </div>';
498
                        }
499
                    }
500
                } else {
501
                    echo "<div class='alert alert-danger alert-dismissable'>
502
                    <i class='fa fa-ban'></i>
503
                    <b>"./** @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
504
                    /** @scrutinizer ignore-type */\Lang::get('message.failed').'
505
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
506
                        './** @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
507
                </div>';
508
                    //echo \Lang::get('message.select-a-row');
509
                }
510
                $lastActivity = Activity::all()->last();
511
            } catch (\Exception $e) {
512
                echo "<div class='alert alert-danger alert-dismissable'>
513
                    <i class='fa fa-ban'></i>
514
                    <b>".\Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
0 ignored issues
show
Bug introduced by
Are you sure Lang::get('message.failed') of type null|string|array can be used in concatenation? ( Ignorable by Annotation )

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

514
                    <b>".\Lang::get('message.alert').'!</b> './** @scrutinizer ignore-type */ \Lang::get('message.failed').'
Loading history...
Bug introduced by
Are you sure Lang::get('message.alert') of type null|string|array can be used in concatenation? ( Ignorable by Annotation )

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

514
                    <b>"./** @scrutinizer ignore-type */ \Lang::get('message.alert').'!</b> '.\Lang::get('message.failed').'
Loading history...
515
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
516
                        '.$e->getMessage().'
517
                </div>';
518
            }
519
        }
520
521
        /*
522
        *  Download Files from Filesystem/Github
523
        */
524
        public function downloadProduct($uploadid, $id, $invoice_id, $version_id = '')
525
        {
526
            try {
527
                $product = $this->product->findOrFail($uploadid);
528
                $type = $product->type;
529
                $owner = $product->github_owner;
530
                $repository = $product->github_repository;
531
                $file = $this->product_upload->where('product_id', '=', $uploadid)->where('id', $version_id)->select('file')->first();
532
                $order = Order::where('invoice_id', '=', $invoice_id)->first();
533
                $order_id = $order->id;
534
                if ($type == 2) {
535
                    $relese = $this->getRelease($owner, $repository, $order_id, $file);
536
537
                    return $relese;
538
                }
539
            } catch (\Exception $e) {
540
                Bugsnag::notifyException($e);
541
542
                return redirect()->back()->with('fails', $e->getMessage());
543
            }
544
        }
545
546
        public function adminDownload($id, $invoice = '', $api = false)
547
        {
548
            try {
549
                $role = \Auth::user()->role;
550
                $release = $this->getLinkToDownload($role, $invoice, $id);
551
552
                if (is_array($release) && array_key_exists('type', $release)) {
553
                    header('Location: '.$release['release']);
554
                    exit;
555
                } else {
556
                    header('Content-type: Zip');
557
                    header('Content-Description: File Transfer');
558
                    header('Content-Disposition: attachment; filename=Faveo.zip');
559
                    header('Content-Length: '.filesize($release));
560
                    flush();
561
                    readfile("$release");
562
                }
563
            } catch (\Exception $e) {
564
                if ($api) {
565
                    return response()->json(['error'=>$e->getMessage()]);
566
                }
567
                Bugsnag::notifyException($e);
568
569
                return redirect()->back()->with('fails', $e->getMessage());
570
            }
571
        }
572
573
        public function getProductField($productid)
574
        {
575
            try {
576
                $field = '';
577
                $product = $this->product->find($productid);
578
                if ($product) {
579
                    if ($product->require_domain == 1) {
580
                        $field .= "<div class='col-md-4 form-group'>
581
                            <label class='required'>"./* @scrutinizer ignore-type */ \Lang::get('message.domain')."</label>
582
                            <input type='text' name='domain' class='form-control' id='domain' placeholder='http://example.com'>
583
                    </div>";
584
                    }
585
                }
586
587
                return $field;
588
            } catch (\Exception $ex) {
589
                Bugsnag::notifyException($ex);
590
591
                return $ex->getMessage();
592
            }
593
        }
594
595
        public function getSubscriptionCheckScript()
596
        {
597
            $response = "<script>
598
        function getPrice(val) {
599
            var user = document.getElementsByName('user')[0].value;
600
            var plan = '';
601
            if ($('#plan').length > 0) {
602
                var plan = document.getElementsByName('plan')[0].value;
603
            }
604
            //var plan = document.getElementsByName('plan')[0].value;
605
            //alert(user);
606
607
            $.ajax({
608
                type: 'POST',
609
                url: ".url('get-price').",
610
                data: {'product': val, 'user': user,'plan':plan},
611
                //data: 'product=' + val+'user='+user,
612
                success: function (data) {
613
                    var price = data['price'];
614
                    var field = data['field'];
615
                    $('#price').val(price);
616
                    $('#fields').append(field);
617
                }
618
            });
619
        }
620
621
    </script>";
622
        }
623
    }
624