Completed
Push — development ( 6f9f18...b1cef6 )
by Ashutosh
10:23
created

ClientController::advanceSearch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 15
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 11

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
namespace App\Http\Controllers\User;
4
5
use App\Http\Requests\User\ClientRequest;
6
use App\Model\Order\Invoice;
7
use App\Model\Order\Order;
8
use App\Model\Order\Payment;
9
use App\Model\Payment\Currency;
10
use App\Model\User\AccountActivate;
11
use App\User;
12
use Bugsnag;
13
use Illuminate\Http\Request;
14
use Log;
15
16
class ClientController extends AdvanceSearchController
17
{
18
    public $user;
19
    public $activate;
20
    public $product;
21
22
    public function __construct()
23
    {
24
        $this->middleware('auth');
25
        // $this->middleware('admin');
26
        $user = new User();
27
        $this->user = $user;
28
        $activate = new AccountActivate();
29
        $this->activate = $activate;
30
        $product = new \App\Model\Product\Product();
31
        $this->product = $product;
32
    }
33
34
    /**
35
     * Display a listing of the resource.
36
     *
37
     * @return \Response
38
     */
39
    public function index(Request $request)
40
    {
41
        $name = $request->input('name');
42
        $username = $request->input('username');
43
        $company = $request->input('company');
44
        $mobile = $request->input('mobile');
45
        $email = $request->input('email');
46
        $country = $request->input('country');
47
        $industry = $request->input('industry');
48
        $company_type = $request->input('company_type');
49
        $company_size = $request->input('company_size');
50
        $role = $request->input('role');
51
        $position = $request->input('position');
52
53
        return view('themes.default1.user.client.index',
54
            compact('name', 'username', 'company', 'mobile', 'email',
55
                'country', 'industry', 'company_type', 'company_size', 'role', 'position'));
56
    }
57
58
    /**
59
     * Get Clients for chumper datatable.
60
     */
61
    public function getClients(Request $request)
62
    {
63
        $name = $request->input('name');
64
        $username = $request->input('username');
65
        $company = $request->input('company');
66
        $mobile = $request->input('mobile');
67
        $email = $request->input('email');
68
        $country = $request->input('country');
69
        $industry = $request->input('industry');
70
        $company_type = $request->input('company_type');
71
        $company_size = $request->input('company_size');
72
        $role = $request->input('role');
73
        $position = $request->input('position');
74
75
        $user = $this->advanceSearch($name, $username, $company,
76
         $mobile, $email, $country, $industry, $company_type, $company_size, $role, $position);
77
78
        return\ DataTables::of($user->get())
79
                         ->addColumn('checkbox', function ($model) {
80
                             return "<input type='checkbox' class='user_checkbox' 
81
                            value=".$model->id.' name=select[] id=check>';
82
                         })
83
                        ->addColumn('first_name', function ($model) {
84
                            return '<a href='.url('clients/'.$model->id).'>'
85
                            .ucfirst($model->first_name).' '.ucfirst($model->last_name).'</a>';
86
                        })
87
                         ->addColumn('email', function ($model) {
88
                             return $model->email;
89
                         })
90
                          ->addColumn('created_at', function ($model) {
91
                              $ends = $model->created_at;
92
                              if ($ends) {
93
                                  $date = date_create($ends);
94
                                  $end = date_format($date, 'l, F j, Y H:m');
95
                              }
96
97
                              return $end;
98
                          })
99
                        // ->showColumns('email', 'created_at')
100
                        ->addColumn('active', function ($model) {
101
                            if ($model->active == 1) {
102
                                $email = "<span class='glyphicon glyphicon-envelope'
103
                                 style='color:green' title='verified email'></span>";
104
                            } else {
105
                                $email = "<span class='glyphicon glyphicon-envelope'
106
                                 style='color:red' title='unverified email'></span>";
107
                            }
108
                            if ($model->mobile_verified == 1) {
109
                                $mobile = "<span class='glyphicon glyphicon-phone' 
110
                                style='color:green' title='verified mobile'></span>";
111
                            } else {
112
                                $mobile = "<span class='glyphicon glyphicon-phone'
113
                                 style='color:red' title='unverified mobile'></span>";
114
                            }
115
116
                            return $email.'&nbsp;&nbsp;'.$mobile;
117
                        })
118
                        ->addColumn('action', function ($model) {
119
                            return '<a href='.url('clients/'.$model->id.'/edit')
120
                            ." class='btn btn-sm btn-primary btn-xs'>
121
                            <i class='fa fa-edit' style='color:white;'> </i>&nbsp;&nbsp;Edit</a>"
122
                                    .'  <a href='.url('clients/'.$model->id)
123
                                    ." class='btn btn-sm btn-primary btn-xs'>
124
                                    <i class='fa fa-eye' style='color:white;'> </i>&nbsp;&nbsp;View</a>";
125
                            // return 'hhhh';
126
                        })
127
                        ->rawColumns(['checkbox', 'first_name', 'email',  'created_at', 'active', 'action'])
128
                        ->make(true);
129
130
        // ->searchColumns('email', 'first_name')
131
                        // ->orderColumns('email', 'first_name', 'created_at')
132
                        // ->make();
133
    }
134
135
    /**
136
     * Show the form for creating a new resource.
137
     *
138
     * @return \Response
139
     */
140
    public function create()
141
    {
142
        $timezones = new \App\Model\Common\Timezone();
143
        $timezones = $timezones->pluck('name', 'id')->toArray();
144
        $bussinesses = \App\Model\Common\Bussiness::pluck('name', 'short')->toArray();
145
        $managers = User::where('role', 'admin')->where('position', 'manager')
146
        ->pluck('first_name', 'id')->toArray();
147
        $timezonesList = \App\Model\Common\Timezone::get();
148
        foreach ($timezonesList as $timezone) {
149
            $location = $timezone->location;
150
            if ($location) {
151
                $start = strpos($location, '(');
152
                $end = strpos($location, ')', $start + 1);
153
                $length = $end - $start;
154
                $result = substr($location, $start + 1, $length - 1);
155
                $display[] = (['id'=>$timezone->id, 'name'=> '('.$result.')'.' '.$timezone->name]);
156
            }
157
        }
158
        $timezones = array_column($display, 'name', 'id');
159
160
        return view('themes.default1.user.client.create', compact('timezones', 'bussinesses', 'managers'));
161
    }
162
163
    /**
164
     * Store a newly created resource in storage.
165
     *
166
     * @return \Response
167
     */
168
    public function store(ClientRequest $request)
169
    {
170
        try {
171
            $user = $this->user;
172
            $str = str_random(6);
173
            $password = \Hash::make($str);
174
            $user->password = $password;
175
            $user->fill($request->input())->save();
176
            $this->sendWelcomeMail($user);
177
178
            return redirect()->back()->with('success', \Lang::get('message.saved-successfully'));
179
        } catch (\Swift_TransportException $e) {
180
            return redirect()->back()->with('warning', 'User has created successfully
181
             But email configuration has some problem!');
182
        } catch (\Exception $e) {
183
            return redirect()->back()->with('fails', $e->getMessage());
184
        }
185
    }
186
187
    /**
188
     * Display the specified resource.
189
     *
190
     * @param int $id
191
     *
192
     * @return \Response
193
     */
194
    public function show($id)
195
    {
196
        try {
197
            $invoice = new Invoice();
198
            $order = new Order();
199
            $invoices = $invoice->where('user_id', $id)->orderBy('created_at', 'desc')->get();
200
            $invoiceSum = $this->getTotalInvoice($invoices);
201
            $amountReceived = $this->getAmountPaid($id);
202
            $pendingAmount = $invoiceSum - $amountReceived;
203
            $extraAmt = $this->getExtraAmt($id);
204
            $client = $this->user->where('id', $id)->first();
205
            $currency = $client->currency;
206
            $orders = $order->where('client', $id)->get();
207
            //dd($client);
208
209
            return view('themes.default1.user.client.show',
210
                compact('id', 'client', 'invoices', 'model_popup', 'orders',
211
                 'payments', 'invoiceSum', 'amountReceived', 'pendingAmount', 'currency','extraAmt'));
212
        } catch (\Exception $ex) {
213
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
214
            app('log')->info($ex->getMessage());
215
            Bugsnag::notifyException($ex);
216
217
            return redirect()->back()->with('fails', $ex->getMessage());
218
        }
219
    }
220
     
221
    public function getExtraAmt($userId)
222
    {
223
        try {
224
            $amounts = Payment::where('user_id', $userId)->select('amt_to_credit')->get();
225
            $paidSum = 0;
226
            foreach ($amounts as $amount) {
227
                $paidSum = $paidSum + $amount->amt_to_credit;
228
            }
229
            return $paidSum;
230
        } catch (\Exception $ex) {
231
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
232
            app('log')->info($ex->getMessage());
233
            Bugsnag::notifyException($ex);
234
235
            return redirect()->back()->with('fails', $ex->getMessage());
236
        }
237
    }
238
239
240
    /**
241
     * Get total Amount paid for a particular invoice.
242
     */
243
    public function getAmountPaid($userId)
244
    {
245
        try {
246
            $amounts = Payment::where('user_id', $userId)->select('amount')->get();
247
            $paidSum = 0;
248
            foreach ($amounts as $amount) {
249
                $paidSum = $paidSum + $amount->amount;
250
            }
251
252
            return $paidSum;
253
        } catch (\Exception $ex) {
254
            app('log')->useDailyFiles(storage_path().'/logs/laravel.log');
255
            app('log')->info($ex->getMessage());
256
            Bugsnag::notifyException($ex);
257
258
            return redirect()->back()->with('fails', $ex->getMessage());
259
        }
260
    }
261
262
    /**
263
     * Get total of the Invoices for a User.
264
     */
265
    public function getTotalInvoice($invoices)
266
    {
267
        $sum = 0;
268
        foreach ($invoices as $invoice) {
269
            $sum = $sum + $invoice->grand_total;
270
        }
271
272
        return $sum;
273
    }
274
275
    /**
276
     * Show the form for editing the specified resource.
277
     *
278
     * @param int $id
279
     *
280
     * @return \Response
281
     */
282
    public function edit($id)
283
    {
284
        try {
285
            $user = $this->user->where('id', $id)->first();
286
            $timezonesList = \App\Model\Common\Timezone::get();
287
            foreach ($timezonesList as $timezone) {
288
                $location = $timezone->location;
289
                if ($location) {
290
                    $start = strpos($location, '(');
291
                    $end = strpos($location, ')', $start + 1);
292
                    $length = $end - $start;
293
                    $result = substr($location, $start + 1, $length - 1);
294
                    $display[] = (['id'=>$timezone->id, 'name'=> '('.$result.')'.' '.$timezone->name]);
295
                }
296
            }
297
            //for display
298
            $timezones = array_column($display, 'name', 'id');
299
            $state = \App\Http\Controllers\Front\CartController::getStateByCode($user->state);
300
            $managers = User::where('role', 'admin')
301
            ->where('position', 'manager')
302
            ->pluck('first_name', 'id')->toArray();
303
            $selectedCurrency = Currency::where('code', $user->currency)
304
            ->pluck('name', 'code')->toArray();
305
            $selectedCompany = \DB::table('company_types')->where('short', $user->company_type)
306
            ->pluck('name', 'short')->toArray();
307
            $selectedIndustry = \App\Model\Common\Bussiness::where('short', $user->bussiness)
308
            ->pluck('name', 'short')->toArray();
309
            $selectedCompanySize = \DB::table('company_sizes')->where('short', $user->company_size)
310
            ->pluck('name', 'short')->toArray();
311
            $states = \App\Http\Controllers\Front\CartController::findStateByRegionId($user->country);
312
313
            $bussinesses = \App\Model\Common\Bussiness::pluck('name', 'short')->toArray();
314
315
            return view('themes.default1.user.client.edit',
316
                compact('bussinesses', 'user', 'timezones', 'state', 'states', 'managers', 'selectedCurrency', 'selectedCompany', 'selectedIndustry', 'selectedCompanySize'));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 174 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
317
        } catch (\Exception $ex) {
318
            app('log')->useDailyFiles(storage_path().'/laravel.log');
319
            app('log')->info($ex->getMessage());
320
321
            return redirect()->back()->with('fails', $ex->getMessage());
322
        }
323
    }
324
325
    /**
326
     * Update the specified resource in storage.
327
     *
328
     * @param int $id
329
     *
330
     * @return \Response
331
     */
332
    public function update($id, Request $request)
333
    {
334
        $user = $this->user->where('id', $id)->first();
335
336
        $user->fill($request->input())->save();
337
338
        return redirect()->back()->with('success', \Lang::get('message.updated-successfully'));
339
    }
340
341
    /**
342
     * Remove the specified resource from storage.
343
     *
344
     * @param int $id
345
     *
346
     * @return \Response
347
     */
348
    public function destroy(Request $request)
349
    {
350
        $ids = $request->input('select');
351
        if (!empty($ids)) {
352
            foreach ($ids as $id) {
353
                $user = $this->user->where('id', $id)->first();
354
                if ($user) {
355
                    $user->delete();
356
                } else {
357
                    echo "<div class='alert alert-success alert-dismissable'>
358
                    <i class='fa fa-ban'></i>
359
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '.
360
                    /* @scrutinizer ignore-type */
361
                    \Lang::get('message.success').'
362
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
363
                        './* @scrutinizer ignore-type */\Lang::get('message.no-record').'
364
                </div>';
365
                    //echo \Lang::get('message.no-record') . '  [id=>' . $id . ']';
366
                }
367
            }
368
            echo "<div class='alert alert-success alert-dismissable'>
369
                    <i class='fa fa-ban'></i>
370
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert')
371
                    .'!</b> './* @scrutinizer ignore-type */
372
                    \Lang::get('message.success').'
373
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
374
                        './* @scrutinizer ignore-type */\Lang::get('message.deleted-successfully').'
375
                </div>';
376
        } else {
377
            echo "<div class='alert alert-success alert-dismissable'>
378
                    <i class='fa fa-ban'></i>
379
                    <b>"./* @scrutinizer ignore-type */\Lang::get('message.alert').'!</b> '
380
                    ./* @scrutinizer ignore-type */\Lang::get('message.success').'
381
                    <button type=button class=close data-dismiss=alert aria-hidden=true>&times;</button>
382
                        './* @scrutinizer ignore-type */\Lang::get('message.select-a-row').'
383
                </div>';
384
        }
385
    }
386
387
    public function getUsers(Request $request)
388
    {
389
        $options = $this->user
390
//->where('email','LIKE','%'.$s.'%')
391
                ->select('email AS text', 'id AS value')
392
                ->get();
393
394
        return response()->json(compact('options'));
395
    }
396
397
    public function search(Request $request)
398
    {
399
        try {
400
            $term = trim($request->q);
401
            if (empty($term)) {
402
                return \Response::json([]);
403
            }
404
            $users = User::where('email', 'LIKE', '%'.$term.'%')
405
             ->orWhere('first_name', 'LIKE', '%'.$term.'%')
406
             ->orWhere('last_name', 'LIKE', '%'.$term.'%')
407
             ->select('id', 'email', 'profile_pic', 'first_name', 'last_name')->get();
408
            $formatted_tags = [];
409
410
            foreach ($users as $user) {
411
                $formatted_users[] = ['id' => $user->id, 'text' => $user->email, 'profile_pic' => $user->profile_pic,
412
            'first_name'                   => $user->first_name, 'last_name' => $user->last_name, ];
413
            }
414
415
            return \Response::json($formatted_users);
1 ignored issue
show
Comprehensibility Best Practice introduced by
The variable $formatted_users seems to be defined by a foreach iteration on line 410. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
416
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\User\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
417
            // returns if try fails with exception meaagse
418
            return redirect()->back()->with('fails', $e->getMessage());
419
        }
420
    }
421
422
    public function advanceSearch($name = '', $username = '', $company = '',
423
     $mobile = '', $email = '', $country = '', $industry = '',
424
      $company_type = '', $company_size = '', $role = '', $position = '')
425
    {
426
        $join = \DB::table('users');
427
        $join = $this->getNamUserCom($join, $name, $username, $company);
428
        $join = $this->getMobEmCoun($join, $mobile, $email, $country);
429
        $join = $this->getInCtCs($join, $industry, $company_type, $company_size);
430
        $join = $this->getRolPos($join, $role, $position);
431
432
        $join = $join->orderBy('created_at', 'desc')
433
        ->select('id', 'first_name', 'last_name', 'email', 'created_at',
434
         'active', 'mobile_verified', 'role', 'position');
435
436
        return $join;
437
    }
438
439
    public function sendWelcomeMail($user)
440
    {
441
        $activate_model = new AccountActivate();
442
        $str = str_random(40);
443
        $activate = $activate_model->create(['email' => $user->email, 'token' => $str]);
444
        $token = $activate->token;
445
        $url = url("activate/$token");
446
        //check in the settings
447
        $settings = new \App\Model\Common\Setting();
448
        $setting = $settings->where('id', 1)->first();
449
        //template
450
        $templates = new \App\Model\Common\Template();
451
        $temp_id = $setting->welcome_mail;
452
        $template = $templates->where('id', $temp_id)->first();
453
        $from = $setting->email;
454
        $to = $user->email;
455
        $subject = $template->name;
456
        $data = $template->data;
457
        $replace = ['name' => $user->first_name.' '.$user->last_name,
458
        'username'         => $user->email, 'password' => $str, 'url' => $url, ];
459
        $type = '';
460
        if ($template) {
461
            $type_id = $template->type;
462
            $temp_type = new \App\Model\Common\TemplateType();
463
            $type = $temp_type->where('id', $type_id)->first()->name;
464
        }
465
        //dd($type);
466
        $templateController = new \App\Http\Controllers\Common\TemplateController();
467
        $mail = $templateController->mailing($from, $to, $data, $subject, $replace, $type);
468
469
        return $mail;
470
    }
471
}
472