Passed
Push — dev5 ( 1f5b4d...1c738e )
by Ron
05:57
created

TechTipsController::update()   A

Complexity

Conditions 4
Paths 3

Size

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