Completed
Push — development ( 61259f...16e7ec )
by Ashutosh
11:24
created

ClientController   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 456
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 46
eloc 225
dl 0
loc 456
rs 8.72
c 0
b 0
f 0

20 Methods

Rating   Name   Duplication   Size   Complexity  
A GetClients() 0 60 4
A __construct() 0 10 1
A store() 0 15 3
A create() 0 8 1
A index() 0 20 1
A show() 0 21 2
A getAmountPaid() 0 16 3
A getTotalInvoice() 0 15 3
A destroy() 0 33 4
A getUsers() 0 8 1
A edit() 0 20 2
A update() 0 8 1
A soldEdition() 0 8 1
A advanceSearch() 0 11 1
A getInCtCs() 0 12 4
A sendWelcomeMail() 0 30 2
A productCount() 0 5 1
A getNamUserCom() 0 13 4
A getRolPos() 0 9 3
A getMobEmCoun() 0 12 4

How to fix   Complexity   

Complex Class

Complex classes like ClientController 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 ClientController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers\User;
4
5
use App\Http\Controllers\Controller;
6
use App\Http\Requests\User\ClientRequest;
7
use App\Model\Order\Invoice;
8
use App\Model\Order\Order;
9
use App\Model\Order\Payment;
10
use App\Model\User\AccountActivate;
11
use App\User;
12
use Bugsnag;
13
use DB;
14
use Illuminate\Http\Request;
15
use Log;
16
use Spatie\Activitylog\Models\Activity;
17
18
class ClientController extends Controller
19
{
20
    public $user;
21
    public $activate;
22
    public $product;
23
24
    public function __construct()
25
    {
26
        $this->middleware('auth');
27
        // $this->middleware('admin');
28
        $user = new User();
29
        $this->user = $user;
30
        $activate = new AccountActivate();
31
        $this->activate = $activate;
32
        $product = new \App\Model\Product\Product();
33
        $this->product = $product;
34
    }
35
36
    /**
37
     * Display a listing of the resource.
38
     *
39
     * @return Response
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\User\Response was not found. Did you mean Response? If so, make sure to prefix the type with \.
Loading history...
40
     */
41
    public function index(Request $request)
42
    {
43
        $name = $request->input('name');
44
        $username = $request->input('username');
45
        $company = $request->input('company');
46
        $mobile = $request->input('mobile');
47
        $email = $request->input('email');
48
        $country = $request->input('country');
49
        $industry = $request->input('industry');
50
        $company_type = $request->input('company_type');
51
        $company_size = $request->input('company_size');
52
        $role = $request->input('role');
53
        $position = $request->input('position');
54
55
        $count_users = $this->user->get()->count();
56
        $pro_editions = $this->soldEdition('Faveo Helpdesk Pro');
57
        $community = $this->soldEdition('faveo helpdesk community');
58
        $product_count = $this->productCount();
59
60
        return view('themes.default1.user.client.index', compact('name', 'username', 'company', 'mobile', 'email', 'country', 'count_users', 'pro_editions', 'community', 'product_count', 'industry', 'company_type', 'company_size', 'role', 'position'));
61
    }
62
63
    /**
64
     * Get Clients for chumper datatable.
65
     */
66
    public function GetClients(Request $request)
67
    {
68
        $name = $request->input('name');
69
        $username = $request->input('username');
70
        $company = $request->input('company');
71
        $mobile = $request->input('mobile');
72
        $email = $request->input('email');
73
        $country = $request->input('country');
74
        $industry = $request->input('industry');
75
        $company_type = $request->input('company_type');
76
        $company_size = $request->input('company_size');
77
        $role = $request->input('role');
78
        $position = $request->input('position');
79
80
        $user = $this->advanceSearch($name, $username, $company, $mobile, $email, $country, $industry, $company_type, $company_size, $role, $position);
81
82
        return\ DataTables::of($user->get())
83
84
                        ->addColumn('checkbox', function ($model) {
85
                            return "<input type='checkbox' class='user_checkbox' value=".$model->id.' name=select[] id=check>';
86
                        })
87
                        ->addColumn('first_name', function ($model) {
88
                            return '<a href='.url('clients/'.$model->id).'>'.ucfirst($model->first_name).' '.ucfirst($model->last_name).'</a>';
89
                        })
90
                         ->addColumn('email', function ($model) {
91
                             return $model->email;
92
                         })
93
                          ->addColumn('created_at', function ($model) {
94
                              $ends = $model->created_at;
95
                              if ($ends) {
96
                                  $date = date_create($ends);
97
                                  $end = date_format($date, 'l, F j, Y H:m');
98
                              }
99
100
                              return $end;
101
102
                              //   return $model->created_at;
103
                          })
104
                        // ->showColumns('email', 'created_at')
105
                        ->addColumn('active', function ($model) {
106
                            if ($model->active == 1) {
107
                                $email = "<span class='glyphicon glyphicon-envelope' style='color:green' title='verified email'></span>";
108
                            } else {
109
                                $email = "<span class='glyphicon glyphicon-envelope' style='color:red' title='unverified email'></span>";
110
                            }
111
                            if ($model->mobile_verified == 1) {
112
                                $mobile = "<span class='glyphicon glyphicon-phone' style='color:green' title='verified mobile'></span>";
113
                            } else {
114
                                $mobile = "<span class='glyphicon glyphicon-phone' style='color:red' title='unverified mobile'></span>";
115
                            }
116
117
                            return $email.'&nbsp;&nbsp;'.$mobile;
118
                        })
119
                        ->addColumn('action', function ($model) {
120
                            return '<a href='.url('clients/'.$model->id.'/edit')." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-edit' style='color:white;'> </i>&nbsp;&nbsp;Edit</a>"
121
                                    .'  <a href='.url('clients/'.$model->id)." class='btn btn-sm btn-primary btn-xs'><i class='fa fa-eye' style='color:white;'> </i>&nbsp;&nbsp;View</a>";
122
                            // return 'hhhh';
123
                        })
124
                        ->rawColumns(['checkbox', 'first_name', 'email',  'created_at', 'active', 'action'])
125
                        ->make(true);
126
127
        // ->searchColumns('email', 'first_name')
128
                        // ->orderColumns('email', 'first_name', 'created_at')
129
                        // ->make();
130
    }
131
132
    /**
133
     * Show the form for creating a new resource.
134
     *
135
     * @return Response
136
     */
137
    public function create()
138
    {
139
        $timezones = new \App\Model\Common\Timezone();
140
        $timezones = $timezones->pluck('name', 'id')->toArray();
141
        $bussinesses = \App\Model\Common\Bussiness::pluck('name', 'short')->toArray();
142
        $managers = User::where('role', 'admin')->where('position', 'manager')->pluck('first_name', 'id')->toArray();
143
144
        return view('themes.default1.user.client.create', compact('timezones', 'bussinesses', 'managers'));
145
    }
146
147
    /**
148
     * Store a newly created resource in storage.
149
     *
150
     * @return Response
151
     */
152
    public function store(ClientRequest $request)
153
    {
154
        try {
155
            $user = $this->user;
156
            $str = str_random(6);
157
            $password = \Hash::make($str);
158
            $user->password = $password;
159
            $user->fill($request->input())->save();
160
            $this->sendWelcomeMail($user);
161
162
            return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
163
        } catch (\Swift_TransportException $e) {
164
            return redirect()->back()->with('warning', 'User has created successfully But email configuration has some problem!');
165
        } catch (\Exception $e) {
166
            return redirect()->back()->with('fails', $e->getMessage());
167
        }
168
    }
169
170
    /**
171
     * Display the specified resource.
172
     *
173
     * @param int $id
174
     *
175
     * @return Response
176
     */
177
    public function show($id)
178
    {
179
        try {
180
            $invoice = new Invoice();
181
            $order = new Order();
182
            $invoices = $invoice->where('user_id', $id)->orderBy('created_at', 'desc')->get();
183
            $invoiceSum = $this->getTotalInvoice($invoices);
184
            $amountReceived = $this->getAmountPaid($id);
185
            $pendingAmount = $invoiceSum - $amountReceived;
186
            $client = $this->user->where('id', $id)->first();
187
            $currency = $client->currency;
188
            $orders = $order->where('client', $id)->get();
189
            //dd($client);
190
191
            return view('themes.default1.user.client.show', compact('id', 'client', 'invoices', 'model_popup', 'orders', 'payments', 'invoiceSum', 'amountReceived', 'pendingAmount', 'currency'));
192
        } catch (\Exception $ex) {
193
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
194
            app('log')->info($ex->getMessage());
195
            Bugsnag::notifyException($ex);
196
197
            return redirect()->back()->with('fails', $ex->getMessage());
198
        }
199
    }
200
201
    /**
202
     * Get total Amount paid for a particular invoice.
203
     */
204
    public function getAmountPaid($userId)
205
    {
206
        try {
207
            $amounts = Payment::where('user_id', $userId)->select('amount')->get();
208
            $paidSum = 0;
209
            foreach ($amounts as $amount) {
210
                $paidSum = $paidSum + $amount->amount;
211
            }
212
213
            return $paidSum;
214
        } catch (\Exception $ex) {
215
            app('log')->useDailyFiles(storage_path().'/laravel.log');
216
            app('log')->info($ex->getMessage());
217
            Bugsnag::notifyException($ex);
218
219
            return redirect()->back()->with('fails', $ex->getMessage());
220
        }
221
    }
222
223
    /**
224
     * Get total of the Invoices for a User.
225
     */
226
    public function getTotalInvoice($invoices)
227
    {
228
        try {
229
            $sum = 0;
230
            foreach ($invoices as $invoice) {
231
                $sum = $sum + $invoice->grand_total;
232
            }
233
234
            return $sum;
235
        } catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) is not 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...
236
            app('log')->useDailyFiles(storage_path().'/laravel.log');
237
            app('log')->info($e->getMessage());
238
            Bugsnag::notifyException($e);
239
240
            return redirect()->back()->with('fails', $e->getMessage());
241
        }
242
    }
243
244
    /**
245
     * Show the form for editing the specified resource.
246
     *
247
     * @param int $id
248
     *
249
     * @return Response
250
     */
251
    public function edit($id)
252
    {
253
        try {
254
            $user = $this->user->where('id', $id)->first();
255
            $timezones = new \App\Model\Common\Timezone();
256
            $timezones = $timezones->pluck('name', 'id')->toArray();
257
258
            $state = \App\Http\Controllers\Front\CartController::getStateByCode($user->state);
259
            $managers = User::where('role', 'admin')->where('position', 'manager')->pluck('first_name', 'id')->toArray();
260
261
            $states = \App\Http\Controllers\Front\CartController::findStateByRegionId($user->country);
262
263
            $bussinesses = \App\Model\Common\Bussiness::pluck('name', 'short')->toArray();
264
265
            return view('themes.default1.user.client.edit', compact('bussinesses', 'user', 'timezones', 'state', 'states', 'managers'));
266
        } catch (\Exception $ex) {
267
            app('log')->useDailyFiles(storage_path().'/laravel.log');
268
            app('log')->info($ex->getMessage());
269
270
            return redirect()->back()->with('fails', $ex->getMessage());
271
        }
272
    }
273
274
    /**
275
     * Update the specified resource in storage.
276
     *
277
     * @param int $id
278
     *
279
     * @return Response
280
     */
281
    public function update($id, ClientRequest $request)
282
    {
283
        $user = $this->user->where('id', $id)->first();
284
285
        $user->fill($request->input())->save();
286
        // activity()->log('Look mum, I logged something');
287
288
        return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
289
    }
290
291
    /**
292
     * Remove the specified resource from storage.
293
     *
294
     * @param int $id
295
     *
296
     * @return Response
297
     */
298
    public function destroy(Request $request)
299
    {
300
        $ids = $request->input('select');
301
        if (!empty($ids)) {
302
            foreach ($ids as $id) {
303
                $user = $this->user->where('id', $id)->first();
304
                if ($user) {
305
                    $user->delete();
306
                } else {
307
                    echo "<div class='alert alert-success alert-dismissable'>
308
                    <i class='fa fa-ban'></i>
309
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
310
                    \Lang::get('message.success').'
311
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
312
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
313
                </div>';
314
                    //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
315
                }
316
            }
317
            echo "<div class='alert alert-success alert-dismissable'>
318
                    <i class='fa fa-ban'></i>
319
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> './* @scrutinizer ignore-type */
320
                    Lang::get('message.success').'
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\User\Lang was not found. Did you mean Lang? If so, make sure to prefix the type with \.
Loading history...
321
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
322
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
323
                </div>';
324
        } else {
325
            echo "<div class='alert alert-success alert-dismissable'>
326
                    <i class='fa fa-ban'></i>
327
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
328
                    /* @scrutinizer ignore-type */\Lang::get('message.success').'
329
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
330
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
331
                </div>';
332
            //echo \Lang::get('message.select-a-row');
333
        }
334
    }
335
336
    public function getUsers(Request $request)
337
    {
338
        $options = $this->user
339
//->where('email','LIKE','%'.$s.'%')
340
                ->select('email AS text', 'id AS value')
341
                ->get();
342
343
        return response()->json(compact('options'));
344
    }
345
346
    public function advanceSearch($name = '', $username = '', $company = '', $mobile = '', $email = '', $country = '', $industry = '', $company_type = '', $company_size = '', $role = '', $position = '')
347
    {
348
        $join = DB::table('users');
349
        $join = $this->getNamUserCom($join,$name,$username,$company);
350
        $join = $this->getMobEmCoun($join,$mobile,$email,$country);
351
        $join = $this->getInCtCs($join,$industry,$company_type,$company_size);
352
        $join = $this->getRolPos($join,$role,$position);
353
       
354
         $join = $join->orderBy('created_at', 'desc')->select('id', 'first_name', 'last_name', 'email', 'created_at', 'active', 'mobile_verified', 'role', 'position');
355
356
        return $join;
357
    }
358
359
    /**
360
    * Serach for Mobile,Email,Country
361
    */
362
    public function getMobEmCoun($join,$mobile,$email,$country)
363
    {
364
        if ($mobile) {
365
            $join = $join->where('mobile', $mobile);
366
        }
367
        if ($email) {
368
            $join = $join->where('email', 'LIKE', '%'.$email.'%');
369
        }
370
        if ($country) {
371
            $join = $join->where('country', $country);
372
        }
373
        return $join;
374
    }
375
376
     
377
     /**
378
    * Serach for industry,company_type,company_size
379
    */
380
     public function getInCtCs($join,$industry,$company_type,$company_size)
381
    {
382
       if ($industry) {
383
            $join = $join->where('bussiness', $industry);
384
        }
385
        if ($company_type) {
386
            $join = $join->where('company_type', $company_type);
387
        }
388
        if ($company_size) {
389
            $join = $join->where('company_size', $company_size);
390
        }
391
        return $join;
392
    }
393
394
395
    /**
396
    * Serach for Role,Position
397
    */
398
     public function getRolPos($join,$role,$position)
399
    {
400
      if ($role) {
401
            $join = $join->where('role', $role);
402
        }
403
        if ($position) {
404
            $join = $join->where('position', $position);
405
        }
406
        return $join;
407
    }
408
409
     /**
410
    * Serach for Name,UserName,Company
411
    */
412
     public function getNamUserCom($join,$name,$username,$company)
413
    {
414
     if ($name) {
415
            $join = $join->where('first_name', 'LIKE', '%'.$name.'%')
416
                    ->orWhere('last_name', 'LIKE', '%'.$name.'%');
417
        }
418
        if ($username) {
419
            $join = $join->where('user_name', 'LIKE', '%'.$username.'%');
420
        }
421
        if ($company) {
422
            $join = $join->where('company', 'LIKE', '%'.$company.'%');
423
        }
424
        return $join;
425
    }
426
427
    public function soldEdition($name)
428
    {
429
        $invoice = new \App\Model\Order\InvoiceItem();
430
        $product_in_invoice = $invoice->where('product_name', $name)->distinct()->pluck('invoice_id');
431
        $order = new Order();
432
        $orders = $order->whereIn('invoice_id', $product_in_invoice)->get()->count();
433
434
        return $orders;
435
    }
436
437
    public function productCount()
438
    {
439
        $products = $this->product->get()->count();
440
441
        return $products;
442
    }
443
444
    public function sendWelcomeMail($user)
445
    {
446
        $activate_model = new AccountActivate();
447
        $str = str_random(40);
448
        $activate = $activate_model->create(['email' => $user->email, 'token' => $str]);
449
        $token = $activate->token;
450
        $url = url("activate/$token");
451
        //check in the settings
452
        $settings = new \App\Model\Common\Setting();
453
        $setting = $settings->where('id', 1)->first();
454
        //template
455
        $templates = new \App\Model\Common\Template();
456
        $temp_id = $setting->welcome_mail;
457
        $template = $templates->where('id', $temp_id)->first();
458
        $from = $setting->email;
459
        $to = $user->email;
460
        $subject = $template->name;
461
        $data = $template->data;
462
        $replace = ['name' => $user->first_name.' '.$user->last_name, 'username' => $user->email, 'password' => $str, 'url' => $url];
463
        $type = '';
464
        if ($template) {
465
            $type_id = $template->type;
466
            $temp_type = new \App\Model\Common\TemplateType();
467
            $type = $temp_type->where('id', $type_id)->first()->name;
468
        }
469
        //dd($type);
470
        $templateController = new \App\Http\Controllers\Common\TemplateController();
471
        $mail = $templateController->mailing($from, $to, $data, $subject, $replace, $type);
472
473
        return $mail;
474
    }
475
}
476