Passed
Push — dev5 ( 3ab1f5...1f5b4d )
by Ron
06:22
created

TechTipsController::show()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 0
Metric Value
cc 3
eloc 11
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 19
ccs 9
cts 10
cp 0.9
crap 3.009
rs 9.9
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
40
class TechTipsController extends Controller
41
{
42 54
    public function __construct()
43
    {
44 54
        $this->middleware('auth');
45 54
    }
46
47
    //  Tech Tips landing page
48 2
    public function index()
49
    {
50 2
        $tipTypes = new TechTipTypesCollection(TechTipTypes::all());
51 2
        $sysList  = new CategoriesCollection(SystemCategories::with('SystemTypes')->with('SystemTypes.SystemDataFields.SystemDataFieldTypes')->get());
52 2
        return view('tips.index', [
53 2
            'tipTypes' => $tipTypes,
54 2
            'sysTypes' => $sysList,
55 2
            'canCreate' => $this->authorize('hasAccess', 'create_tech_tip') ? true : false
56
        ]);
57
    }
58
59
    //  Search for an existing tip - If no paramaters, return all tips
60 8
    public function search(Request $request)
61
    {
62 8
        Log::debug('request Data -> ', $request->toArray());
63
64
        //  See if there are any search paramaters entered
65 8
        if (!$request->search['searchText'] && !isset($request->search['articleType']) && !isset($request->search['systemType'])) {
66
            //  No search paramaters, send all tech tips
67 2
            $tips = new TechTipsCollection(
68 2
                TechTips::orderBy('created_at', 'DESC')
69 2
                    ->with('SystemTypes')
70 2
                    ->paginate($request->pagination['perPage'])
71
            );
72
        } else {
73 6
            $article = isset($request->search['articleType']) ? true : false;
74 6
            $system  = isset($request->search['systemType'])  ? true : false;
75
            //  Search paramaters, filter results
76 6
            $tips = new TechTipsCollection(
77 6
                TechTips::orderBy('created_at', 'DESC')
78
                    //  Search by id or a phrase in the title or description
79
                    ->where(function ($query) use ($request) {
80 6
                        $query->where('subject', 'like', '%' . $request->search['searchText'] . '%')
81 6
                            ->orWhere('tip_id', 'like', '%' . $request->search['searchText'] . '%')
82 6
                            ->orWhere('description', 'like', '%' . $request->search['searchText'] . '%');
83 6
                    })
84
                    ->when($article, function ($query) use ($request) {
85 2
                        $query->whereIn('tip_type_id', $request->search['articleType']);
86 6
                    })
87
                    ->when($system, function ($query) use ($request) {
88
                        $query->whereHas('SystemTypes', function ($query) use ($request) {
89 2
                            $query->whereIn('system_types.sys_id', $request->search['systemType']);
90 2
                        });
91 6
                    })
92 6
                    ->with('SystemTypes')
93 6
                    ->paginate($request->pagination['perPage'])
94
            );
95
        }
96
97 8
        return $tips;
98
    }
99
100
    //  Process an image that is attached to a tech tip
101 6
    public function processImage(Request $request)
102
    {
103 6
        $this->authorize('hasAccess', 'create_tech_tip');
104
105 4
        $request->validate([
106 4
            'file' => 'mimes:jpeg,bmp,png,jpg,gif'
107
        ]);
108
109
        //  Generate a unique hash as the file name and store it in a publicly accessable folder
110 2
        $path = 'img/tip_img';
111 2
        $location = Storage::disk('public')->putFile($path, new File($request->file));
112
113
        //  Return the full url path to the image
114 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
115 2
        return response()->json(['location' => Storage::url($location)]);
116
    }
117
118
    //  Create a new Tech Tip form
119 4
    public function create()
120
    {
121 4
        $this->authorize('hasAccess', 'create_tech_tip');
122
123 2
        $typesArr   = new TechTipTypesCollection(TechTipTypes::all());
124 2
        $systemsArr = new SystemCategoriesCollection(SystemCategories::with('SystemTypes')->get());
125
126 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
127 2
        return view('tips.create', [
128 2
            'tipTypes' => $typesArr,
129 2
            'sysTypes' => $systemsArr,
130
        ]);
131
    }
132
133
    //  Submit the form to create a new tech tip
134 14
    public function store(Request $request)
135
    {
136 14
        $this->authorize('hasAccess', 'create_tech_tip');
137
138 12
        $request->validate([
139 12
            'subject'   => 'required',
140
            'equipment' => 'required',
141
            'tipType'   => 'required',
142
            'tip'       => 'required',
143
        ]);
144
145 4
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
146
147
        //  Verify if there is a file to be processed or not
148 4
        if($receiver->isUploaded() === false || $request->_completed)
149
        {
150 4
            Log::debug('about to create a tip');
151 4
            $tipID = $this->createTip($request);
152 4
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
153 4
            return response()->json(['tip_id' => $tipID]);
154
        }
155
156
        //  Recieve and process the file
157 2
        $save = $receiver->receive();
158
159
        //  See if the uploade has finished
160 2
        if ($save->isFinished()) {
161 2
            $this->saveFile($save->getFile());
162
163 2
            return 'uploaded successfully';
164
        }
165
166
        //  Get the current progress
167
        $handler = $save->handler();
168
169
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
170
        Log::debug('File being uploaded.  Percentage done - ' . $handler->getPercentageDone());
171
        return response()->json([
172
            'done'   => $handler->getPercentageDone(),
173
            'status' => true
174
        ]);
175
    }
176
177
    //  Save a file attached to the link
178 2
    private function saveFile(UploadedFile $file)
179
    {
180 2
        $filePath = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.'_tmp';
181
182
        //  Clean the file and store it
183 2
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
184 2
        $file->storeAs($filePath, $fileName);
185
186
        //  Place file in Files table of DB
187 2
        $newFile = Files::create([
188 2
            'file_name' => $fileName,
189 2
            'file_link' => $filePath.DIRECTORY_SEPARATOR
190
        ]);
191 2
        $fileID = $newFile->file_id;
192
193
        //  Save the file ID in the session array
194 2
        $fileArr = session('newTipFile') != null ? session('newTipFile') : [];
195 2
        $fileArr[] = $fileID;
196 2
        session(['newTipFile' => $fileArr]);
197
198
        //  Log stored file
199 2
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath . DIRECTORY_SEPARATOR . $fileName]);
200 2
        return $fileID;
201
    }
202
203
    //  Create the tech tip
204 4
    private function createTip($tipData)
205
    {
206
        //  Remove any forward slash (/) from the Subject Field
207 4
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
208
209
        //  Enter the tip details and return the tip ID
210 4
        $tip = TechTips::create([
211 4
            'tip_type_id' => $tipData->tipType,
212 4
            'subject'     => $tipData->subject,
213 4
            'description' => $tipData->tip,
214 4
            'user_id'     => Auth::user()->user_id
215
        ]);
216 4
        $tipID = $tip->tip_id;
217
218 4
        foreach($tipData->equipment as $sys)
219
        {
220 4
            TechTipSystems::create([
221 4
                'tip_id' => $tipID,
222 4
                'sys_id' => $sys['sys_id']
223
            ]);
224
        }
225
226
        //  If there were any files uploaded, move them to the proper folder
227 4
        if(session('newTipFile') != null)
228
        {
229 2
            $files = session('newTipFile');
230 2
            $path = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.$tipID;
231 2
            foreach($files as $file)
232
            {
233 2
                $data = Files::find($file);
234
                //  Move the file to the proper folder
235 2
                Storage::move($data->file_link.$data->file_name, $path.DIRECTORY_SEPARATOR.$data->file_name);
236
                // Update the database
237 2
                $data->update([
238 2
                    'file_link' => $path.DIRECTORY_SEPARATOR
239
                ]);
240
241 2
                TechTipFiles::create([
242 2
                    'tip_id' => $tipID,
243 2
                    'file_id' => $data->file_id
244
                ]);
245
            }
246
        }
247
248 4
        Log::debug('data - ', $tipData->toArray());
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
            //  TODO - fix this!!!!!!!
293
            'canEdit' => false, // $this->authorize('hasAccess', 'edit_tech_tip') ? 'true' : 'false',
294
            'canDel'  => false, // $this->authorize('hasAccess', 'delete_tech_tip') ? 'true' : 'false',
295 2
            'files'   => $files,
296
        ]);
297
    }
298
299
    //
300
    public function toggleFav($action, $id)
301
    {
302
        //
303
        switch ($action) {
304
            case 'add':
305
                TechTipFavs::create([
306
                    'user_id' => Auth::user()->user_id,
307
                    'tip_id' => $id
308
                ]);
309
                break;
310
            case 'remove':
311
                $tipFav = TechTipFavs::where('user_id', Auth::user()->user_id)->where('tip_id', $id)->first();
312
                $tipFav->delete();
313
                break;
314
        }
315
316
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
317
        Log::debug('Tech Tip Bookmark Updated.', [
318
            'user_id' => Auth::user()->user_id,
319
            'tip_id' => $id,
320
            'action'  => $action
321
        ]);
322
        return response()->json(['success' => true]);
323
    }
324
325
326
327
328
329
330
331
332
333
334
335
336
337
    /**
338
     * Show the form for editing the specified resource.
339
     *
340
     * @param  int  $id
341
     * @return \Illuminate\Http\Response
342
     */
343
    public function edit($id)
344
    {
345
        //
346
        return 'edit tip';
347
    }
348
349
    /**
350
     * Update the specified resource in storage.
351
     *
352
     * @param  \Illuminate\Http\Request  $request
353
     * @param  int  $id
354
     * @return \Illuminate\Http\Response
355
     */
356
    public function update(Request $request, $id)
357
    {
358
        //
359
    }
360
361
    /**
362
     * Remove the specified resource from storage.
363
     *
364
     * @param  int  $id
365
     * @return \Illuminate\Http\Response
366
     */
367 4
    public function destroy($id)
368
    {
369 4
        $this->authorize('hasAccess', 'delete_tech_tip');
370
371 2
        TechTips::find($id)->delete();
372 2
        Log::warning('User - '.Auth::user()->user_id.' deleted Tech Tip ID - '.$id);
373 2
        return response()->json(['success' => true]);
374
    }
375
}
376