Passed
Push — dev5 ( 1c738e...7a9344 )
by Ron
06:10
created

TechTipsController::update()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 38
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.343

Importance

Changes 0
Metric Value
cc 4
eloc 21
nc 3
nop 2
dl 0
loc 38
ccs 13
cts 18
cp 0.7221
crap 4.343
rs 9.584
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Controllers\TechTips;
4
5
use App\User;
6
use App\Files;
7
use App\TechTips;
8
use App\TechTipFavs;
9
use App\TechTipFiles;
10
use App\TechTipTypes;
11
use App\TechTipSystems;
12
use Illuminate\Http\File;
13
use App\SystemCategories;
14
use Illuminate\Http\Request;
15
use App\Notifications\NewTechTip;
16
use Illuminate\Http\UploadedFile;
17
use Illuminate\Support\Facades\Log;
18
use App\Http\Controllers\Controller;
19
use Illuminate\Support\Facades\Auth;
20
use Illuminate\Support\Facades\Route;
21
use Illuminate\Support\Facades\Storage;
22
use App\Http\Resources\TechTipsCollection;
23
use Illuminate\Support\Facades\Notification;
24
use App\Http\Resources\TechTipTypesCollection;
25
use App\Http\Resources\SystemCategoriesCollection;
26
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
27
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
28
use App\Http\Resources\SystemCategoriesCollection as CategoriesCollection;
29
30
class TechTipsController extends Controller
31
{
32 80
    public function __construct()
33
    {
34 80
        $this->middleware('auth');
35 80
    }
36
37
    //  Tech Tips landing page
38 2
    public function index()
39
    {
40 2
        $tipTypes = new TechTipTypesCollection(TechTipTypes::all());
41 2
        $sysList  = new CategoriesCollection(SystemCategories::with('SystemTypes')->with('SystemTypes.SystemDataFields.SystemDataFieldTypes')->get());
42 2
        return view('tips.index', [
43 2
            'tipTypes' => $tipTypes,
44 2
            'sysTypes' => $sysList,
45 2
            'canCreate' => $this->authorize('hasAccess', 'create_tech_tip') ? true : false
46
        ]);
47
    }
48
49
    //  Search for an existing tip - If no paramaters, return all tips
50 8
    public function search(Request $request)
51
    {
52 8
        Log::debug('request Data -> ', $request->toArray());
53
54
        //  See if there are any search paramaters entered
55 8
        if (!$request->search['searchText'] && !isset($request->search['articleType']) && !isset($request->search['systemType'])) {
56
            //  No search paramaters, send all tech tips
57 2
            $tips = new TechTipsCollection(
58 2
                TechTips::orderBy('created_at', 'DESC')
59 2
                    ->with('SystemTypes')
60 2
                    ->paginate($request->pagination['perPage'])
61
            );
62
        } else {
63 6
            $article = isset($request->search['articleType']) ? true : false;
64 6
            $system  = isset($request->search['systemType'])  ? true : false;
65
            //  Search paramaters, filter results
66 6
            $tips = new TechTipsCollection(
67 6
                TechTips::orderBy('created_at', 'DESC')
68
                    //  Search by id or a phrase in the title or description
69
                    ->where(function ($query) use ($request) {
70 6
                        $query->where('subject', 'like', '%' . $request->search['searchText'] . '%')
71 6
                            ->orWhere('tip_id', 'like', '%' . $request->search['searchText'] . '%')
72 6
                            ->orWhere('description', 'like', '%' . $request->search['searchText'] . '%');
73 6
                    })
74
                    ->when($article, function ($query) use ($request) {
75 2
                        $query->whereIn('tip_type_id', $request->search['articleType']);
76 6
                    })
77
                    ->when($system, function ($query) use ($request) {
78
                        $query->whereHas('SystemTypes', function ($query) use ($request) {
79 2
                            $query->whereIn('system_types.sys_id', $request->search['systemType']);
80 2
                        });
81 6
                    })
82 6
                    ->with('SystemTypes')
83 6
                    ->paginate($request->pagination['perPage'])
84
            );
85
        }
86
87 8
        return $tips;
88
    }
89
90
    //  Process an image that is attached to a tech tip
91 6
    public function processImage(Request $request)
92
    {
93 6
        $this->authorize('hasAccess', 'create_tech_tip');
94
95 4
        $request->validate([
96 4
            'file' => 'mimes:jpeg,bmp,png,jpg,gif'
97
        ]);
98
99
        //  Generate a unique hash as the file name and store it in a publicly accessable folder
100 2
        $path = 'img/tip_img';
101 2
        $location = Storage::disk('public')->putFile($path, new File($request->file));
102
103
        //  Return the full url path to the image
104 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
105 2
        return response()->json(['location' => Storage::url($location)]);
106
    }
107
108
    //  Create a new Tech Tip form
109 4
    public function create()
110
    {
111 4
        $this->authorize('hasAccess', 'create_tech_tip');
112
113 2
        $typesArr   = new TechTipTypesCollection(TechTipTypes::all());
114 2
        $systemsArr = new SystemCategoriesCollection(SystemCategories::with('SystemTypes')->get());
115
116 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
117 2
        return view('tips.create', [
118 2
            'tipTypes' => $typesArr,
119 2
            'sysTypes' => $systemsArr,
120
        ]);
121
    }
122
123
    //  Submit the form to create a new tech tip
124 14
    public function store(Request $request)
125
    {
126 14
        $this->authorize('hasAccess', 'create_tech_tip');
127
128 12
        $request->validate([
129 12
            'subject'   => 'required',
130
            'equipment' => 'required',
131
            'tipType'   => 'required',
132
            'tip'       => 'required',
133
        ]);
134
135 4
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
136
137
        //  Verify if there is a file to be processed or not
138 4
        if($receiver->isUploaded() === false || $request->_completed)
139
        {
140 4
            Log::debug('about to create a tip');
141 4
            $tipID = $this->createTip($request);
142 4
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
143 4
            return response()->json(['tip_id' => $tipID]);
144
        }
145
146
        //  Recieve and process the file
147 2
        $save = $receiver->receive();
148
149
        //  See if the uploade has finished
150 2
        if ($save->isFinished()) {
151 2
            $this->saveFile($save->getFile());
152
153 2
            return 'uploaded successfully';
154
        }
155
156
        //  Get the current progress
157
        $handler = $save->handler();
158
159
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
160
        Log::debug('File being uploaded.  Percentage done - ' . $handler->getPercentageDone());
161
        return response()->json([
162
            'done'   => $handler->getPercentageDone(),
163
            'status' => true
164
        ]);
165
    }
166
167
    //  Save a file attached to the link
168 4
    private function saveFile(UploadedFile $file, $id = '_tmp')
169
    {
170
        // $folder = $id ? $id ? '_tmp';
171 4
        $filePath = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.$id;
172
173
        //  Clean the file and store it
174 4
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
175 4
        $file->storeAs($filePath, $fileName);
176
177
        //  Place file in Files table of DB
178 4
        $newFile = Files::create([
179 4
            'file_name' => $fileName,
180 4
            'file_link' => $filePath.DIRECTORY_SEPARATOR
181
        ]);
182 4
        $fileID = $newFile->file_id;
183
184
        //  Save the file ID in the session array
185 4
        if($id === '_tmp')
186
        {
187
188 2
            $fileArr = session('newTipFile') != null ? session('newTipFile') : [];
189 2
            $fileArr[] = $fileID;
190 2
            session(['newTipFile' => $fileArr]);
191
        }
192
        else
193
        {
194 2
            TechTipFiles::create([
195 2
                'tip_id' => $id,
196 2
                'file_id' => $fileID,
197
            ]);
198
        }
199
200
        //  Log stored file
201 4
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath . DIRECTORY_SEPARATOR . $fileName]);
202 4
        return $fileID;
203
    }
204
205
    //  Create the tech tip
206 4
    private function createTip($tipData)
207
    {
208
        //  Remove any forward slash (/) from the Subject Field
209 4
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
210
211
        //  Enter the tip details and return the tip ID
212 4
        $tip = TechTips::create([
213 4
            'tip_type_id' => $tipData->tipType,
214 4
            'subject'     => $tipData->subject,
215 4
            'description' => $tipData->tip,
216 4
            'user_id'     => Auth::user()->user_id
217
        ]);
218 4
        $tipID = $tip->tip_id;
219
220 4
        foreach($tipData->equipment as $sys)
221
        {
222 4
            TechTipSystems::create([
223 4
                'tip_id' => $tipID,
224 4
                'sys_id' => $sys['sys_id']
225
            ]);
226
        }
227
228
        //  If there were any files uploaded, move them to the proper folder
229 4
        if(session('newTipFile') != null)
230
        {
231 2
            $files = session('newTipFile');
232 2
            $path = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.$tipID;
233 2
            foreach($files as $file)
234
            {
235 2
                $data = Files::find($file);
236
                //  Move the file to the proper folder
237 2
                Storage::move($data->file_link.$data->file_name, $path.DIRECTORY_SEPARATOR.$data->file_name);
238
                // Update the database
239 2
                $data->update([
240 2
                    'file_link' => $path.DIRECTORY_SEPARATOR
241
                ]);
242
243 2
                TechTipFiles::create([
244 2
                    'tip_id' => $tipID,
245 2
                    'file_id' => $data->file_id
246
                ]);
247
            }
248
        }
249
250
        //  Send out the notifications
251 4
        if(!$tipData->supressEmail)
252
        {
253 4
            $details = TechTips::find($tipID);
254
            $users = User::where('active', 1)->whereHas('UserSettings', function($query)
255
            {
256 4
                $query->where('em_tech_tip', 1);
257 4
            })->get();
258
259 4
            Notification::send($users, new NewTechTip($details));
260
        }
261
262 4
        Log::info('New Tech Tip created.  Tip Data - ', $tip->toArray());
263 4
        return $tipID;
264
    }
265
266
    //  Details controller - will move to the show controller with just the tech tip id
267 2
    public function details($id, $subject)
268
    {
269 2
        if (session()->has('newTipFile')) {
270
            session()->forget('newTipFile');
271
        }
272
273 2
        return $this->show($id);
274
    }
275
276
    //  Show the details about the tech tip
277 2
    public function show($id)
278
    {
279 2
        $tipData = TechTips::where('tip_id', $id)->with('User')->with('SystemTypes')->first();
280
281 2
        if(!$tipData)
282
        {
283
            return view('tips.tipNotFound');
284
        }
285
286 2
        $isFav = TechTipFavs::where('user_id', Auth::user()->user_id)->where('tip_id', $id)->first();
287 2
        $files = TechTipFiles::where('tip_id', $id)->with('Files')->get();
288
289 2
        return view('tips.details', [
290 2
            'details' => $tipData,
291 2
            'isFav'   => empty($isFav) ? 'false' : 'true',
292 2
            'files'   => $files,
293
        ]);
294
    }
295
296
    //  Add or remove this tip as a favorite of the user
297
    public function toggleFav($action, $id)
298
    {
299
        switch ($action) {
300
            case 'add':
301
                TechTipFavs::create([
302
                    'user_id' => Auth::user()->user_id,
303
                    'tip_id' => $id
304
                ]);
305
                break;
306
            case 'remove':
307
                $tipFav = TechTipFavs::where('user_id', Auth::user()->user_id)->where('tip_id', $id)->first();
308
                $tipFav->delete();
309
                break;
310
        }
311
312
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
313
        Log::debug('Tech Tip Bookmark Updated.', [
314
            'user_id' => Auth::user()->user_id,
315
            'tip_id' => $id,
316
            'action'  => $action
317
        ]);
318
        return response()->json(['success' => true]);
319
    }
320
321
    //  Edit an existing tech tip
322 6
    public function edit($id)
323
    {
324 6
        $this->authorize('hasAccess', 'edit_tech_tip');
325 4
        $tipData = TechTips::where('tip_id', $id)->with('User')->with('SystemTypes')->with('TechTipTypes')->first();
326
327 4
        if (!$tipData) {
328 2
            return view('tips.tipNotFound');
329
        }
330
331 2
        $typesArr   = new TechTipTypesCollection(TechTipTypes::all());
332 2
        $systemsArr = new SystemCategoriesCollection(SystemCategories::with('SystemTypes')->get());
333 2
        $files = TechTipFiles::where('tip_id', $id)->with('Files')->get();
334
335 2
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
336 2
        return view('tips.editTip', [
337 2
            'tipTypes' => $typesArr,
338 2
            'sysTypes' => $systemsArr,
339 2
            'details' => $tipData,
340 2
            'files'   => $files,
341
        ]);
342
    }
343
344
    //  Store the edited Tech Tip
345 16
    public function update(Request $request, $id)
346
    {
347 16
        $this->authorize('hasAccess', 'edit_tech_tip');
348
349 14
        $request->validate([
350 14
            'subject'   => 'required',
351
            'equipment' => 'required',
352
            'tipType'   => 'required',
353
            'tip'       => 'required',
354
        ]);
355
356 6
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
357
358
        //  Verify if there is a file to be processed or not
359 6
        if ($receiver->isUploaded() === false || $request->_completed) {
360 6
            $this->storeUpdatedTip($request, $id);
361 6
            Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
362 6
            return response()->json(['tip_id' => $id]);
363
        }
364
365
        //  Recieve and process the file
366 2
        $save = $receiver->receive();
367
368
        //  See if the uploade has finished
369 2
        if ($save->isFinished()) {
370 2
            $this->saveFile($save->getFile(), $id);
371
372 2
            return 'uploaded successfully';
373
        }
374
375
        //  Get the current progress
376
        $handler = $save->handler();
377
378
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
379
        Log::debug('File being uploaded.  Percentage done - ' . $handler->getPercentageDone());
380
        return response()->json([
381
            'done'   => $handler->getPercentageDone(),
382
            'status' => true
383
        ]);
384
    }
385
386
    //  Store the updated tip
387 6
    public function storeUpdatedTip($tipData, $id)
388
    {
389 6
        $this->authorize('hasAccess', 'edit_tech_tip');
390
391
        //  Remove any forward slash (/) from the Subject Field
392 6
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
393
394
        //  Enter the tip details and return the tip ID
395 6
        TechTips::find($id)->update([
396 6
            'tip_type_id' => $tipData->tipType,
397 6
            'subject'     => $tipData->subject,
398 6
            'description' => $tipData->tip,
399
            // 'user_id'     => Auth::user()->user_id TODO - updated user who modified tip
400
        ]);
401
402
        //  Add any additional equipment types to the tip
403 6
        $tipEquip = TechTipSystems::where('tip_id', $id)->get();
404 6
        foreach($tipData->equipment as $equip)
405
        {
406 6
            $found = false;
407 6
            foreach($tipEquip as $key => $value)
408
            {
409 6
                if($equip['sys_id'] == $value->sys_id)
410
                {
411
                    $tipEquip->forget($key);
412
                    $found = true;
413
                    break;
414
                }
415
            }
416 6
            if(!$found)
417
            {
418 6
                TechTipSystems::create([
419 6
                    'tip_id' => $id,
420 6
                    'sys_id' => $equip['sys_id'],
421
                ]);
422
            }
423
        }
424
425
        //  Remove the remainaing equipment types that have been removed
426 6
        foreach($tipEquip as $remaining)
427
        {
428 6
            TechTipSystems::find($remaining->tip_tag_id)->delete();
429
        }
430
431
        //  Remove any files that no longer apply
432 6
        foreach($tipData->deletedFileList as $file)
433
        {
434 2
            $file = TechTipFiles::find($file);
435 2
            $fileID = $file->file_id;
436 2
            $file->delete();
437
            //  Try to delete the file itself
438 2
            Files::deleteFile($fileID);
439
        }
440
441 6
        return true;
442
    }
443
444
    //  Soft delet the Tech Tip
445 4
    public function destroy($id)
446
    {
447 4
        $this->authorize('hasAccess', 'delete_tech_tip');
448
449 2
        TechTips::find($id)->delete();
450 2
        Log::warning('User - '.Auth::user()->user_id.' deleted Tech Tip ID - '.$id);
451 2
        return response()->json(['success' => true]);
452
    }
453
}
454