Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 352
0.00% covered (danger)
0.00%
0 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
ShortcutController
0.00% covered (danger)
0.00%
0 / 352
0.00% covered (danger)
0.00%
0 / 21
6006
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 index
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
72
 create
0.00% covered (danger)
0.00%
0 / 63
0.00% covered (danger)
0.00%
0 / 1
90
 update
0.00% covered (danger)
0.00%
0 / 86
0.00% covered (danger)
0.00%
0 / 1
156
 list
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 applyFilters
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 applyOrdering
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 applyPagination
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 details
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 delete
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 dispatchShortcutEvent
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 latest
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 duplicate
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 saveBrowserUsed
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 deleteShortcutVersion
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 rollbackToPreviousVersion
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
12
 getShorcutVersions
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 makeShareable
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 getShared
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 mediaSize
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 deleteBulkFlycuts
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2
3namespace App\Http\Controllers\v1;
4
5use App\Events\TrackingExtensionDeployEvent;
6use App\Http\Controllers\Controller;
7use App\Http\Models\Auth\BusinessUser;
8use App\Http\Models\Auth\User;
9use App\Http\Models\FlyCutUsage;
10use App\Http\Models\Shortcut;
11use App\Http\Models\ShortcutCategory;
12use App\Http\Models\ShortcutSharedLinks;
13use App\Http\Models\ShortcutSubCategoryLv1;
14use App\Http\Models\ShortcutSubCategoryLv2;
15use App\Http\Models\ShortcutVersion;
16use App\Http\Models\UserInfo;
17use App\Http\Requests\FlycutBulkDeleteRequest;
18use App\Http\Requests\ShortcutFormRequest;
19use App\Http\Services\StatisticsService;
20use App\Traits\SubscriptionTrait;
21use Illuminate\Http\JsonResponse;
22use Illuminate\Http\Request;
23use Illuminate\Support\Facades\Cache;
24use Illuminate\Support\Facades\DB;
25use Illuminate\Support\Facades\Log;
26use Illuminate\Support\Facades\Validator;
27use Jenssegers\Agent\Agent;
28
29class ShortcutController extends Controller
30{
31    use SubscriptionTrait;
32
33    public function __construct(
34        protected StatisticsService $statisticsService,
35    ) {}
36
37    /**
38     * Get Shortcuts.
39     */
40    public function index(Request $request): JsonResponse
41    {
42        $query = $request->query('q');
43
44        if ($query === 'recently_used') {
45            $shortcuts = Shortcut::query()
46                ->whereNotNull('last_deployed_date')
47                ->orderByDesc('last_deployed_date')
48                ->limit(5)
49                ->get();
50
51            $user_id = $request->user()->getKey();
52            $user = User::find($user_id);
53            // Skip the code if $shortcuts already has 5 records
54            if ($shortcuts->count() === 5 || $user->recently_used_get_updated == true) {
55                return response()->json($shortcuts);
56            }
57
58            // If we this user still using the old way proceed using the old method and update the DB to use the new methond next time.
59
60            $records = FlyCutUsage::query()
61                ->select('shortcut_id', 'created_at')
62                ->where('user_id', $user_id)
63                ->orderBy('created_at', 'desc')
64                ->groupBy('shortcut_id')
65                ->limit(5)
66                ->get();
67
68            // Mark that we updated the user shortcuts get method.
69            if ($user) {
70                $user->recently_used_get_updated = true;
71                $user->save();
72            }
73
74            $shortcuts = [];
75            foreach ($records as $record) {
76                $shortcutId = $record->shortcut_id;
77                $shortcut = Shortcut::query()->where('_id', $shortcutId)->first();
78
79                if ($shortcut) {
80                    $formattedDate = $record->created_at->format('Y-m-d\TH:i:sP');
81                    $shortcut->last_deployed_date = $formattedDate;
82                    $shortcut->save();
83                    $shortcuts[] = $shortcut;
84                }
85            }
86        } elseif ($query === 'mostly_used') {
87            $shortcuts = Shortcut::query()
88                ->whereNotNull('flycutUsage_count')
89                ->orderBy('flycutUsage_count', 'desc')
90                ->limit(5)
91                ->get();
92        } else {
93            $shortcuts = Shortcut::query()
94                ->latest()
95                ->limit(5)
96                ->get();
97        }
98
99        return response()->json($shortcuts);
100    }
101
102    /**
103     * Creates a new shortcut
104     *
105     * @return JsonResponse
106     */
107    public function create(ShortcutFormRequest $request)
108    {
109        $data = $request->validated();
110        $user = $request->user();
111        $userId = $request->user()->getKey();
112        $data['user_id'] = $userId;
113        $data['version'] = 1;
114        $data['user_defined'] = true;
115        $isOnboarding = $data['onboarding'] ?? false;
116
117        $type = $request['type'];
118        $categoryId = $request['category_id'];
119
120        if (isset($type)) {
121            if ($type == 'sub_categories_lv2') {
122                $data['sub_categories_lv2_id'] = $categoryId;
123            } elseif ($type == 'sub_categories_lv1') {
124                $data['sub_categories_lv1_id'] = $categoryId;
125            } else {
126                $data['category_id'] = $categoryId;
127            }
128        }
129
130        $data['version_counts'] = 1;
131
132        $charactors_count = strlen(strip_tags($data['text']));
133        $words_count = str_word_count(strip_tags($data['text']));
134        $html_count = strlen(strip_tags($data['html']));
135
136        $data['charactors_count'] = $charactors_count;
137        $data['words_count'] = $words_count;
138        $data['html_count'] = $html_count;
139
140        $result = Shortcut::create($data);
141
142        $shortcutId = $result['_id'];
143
144        $mediaCount = $this->mediaSize($data['uploads']);
145
146        $browser_type = 'chrome';
147
148        if ($request->header('Browser-type')) {
149            $browser_type = strtolower($request->header('Browser-type'));
150        } elseif ($request->header('browser-type')) {
151            $browser_type = strtolower($request->header('browser-type'));
152        } elseif ($request->header('browser')) {
153            $browser_type = strtolower($request['browser']);
154        } elseif ($request['browser']) {
155            $browser_type = strtolower($request['browser']);
156        }
157
158        dispatch(function () use ($user, $userId, $charactors_count, $words_count, $html_count, $mediaCount, $data, $shortcutId, $isOnboarding, $result, $browser_type) {
159            // Create a flymessage version
160            $shortcutVersionHistory = new ShortcutVersion;
161            $statisticsData = [
162                'charactors_count' => $charactors_count,
163                'words_count' => $words_count,
164                'html_count' => $html_count,
165                'media_count' => $mediaCount,
166                'updated_at' => now(),
167            ];
168
169            $flymsg_details = array_merge($data, $statisticsData);
170            $versionHistoryData[1] = json_encode($flymsg_details, true);
171            $versionHistoryData['shortcut_id'] = $shortcutId;
172            $versionHistoryData['user_id'] = $userId;
173            $versionHistoryData['last_version_count'] = 1;
174            $versionHistoryData['current_version'] = 0;
175
176            $shortcutVersionHistory->fill($versionHistoryData);
177            $shortcutVersionHistory->push();
178
179            $this->dispatchShortcutEvent();
180
181            $this->saveBrowserUsed($userId);
182
183            if ($isOnboarding) {
184                $data = [
185                    'value' => $charactors_count,
186                    'shortcut_id' => $shortcutId,
187                    'executed_at' => config('romeo.frontend-base-url'),
188                    'tag' => 'total_char_by_a_FlyCut',
189                ];
190
191                event(new TrackingExtensionDeployEvent($user, $data, $result, $browser_type));
192            }
193        });
194
195        return response()->json($result);
196    }
197
198    public function update(ShortcutFormRequest $request, $shortcutId): JsonResponse
199    {
200        $data = $request->validated();
201        $userId = $request->user()->getKey();
202
203        $shortcutSearchArray = ['_id' => $shortcutId];
204        $searchArray = ['_id' => $request['category_id']];
205        $result = false;
206        $shortcut = Shortcut::find($shortcutId);
207
208        // Check if it's a category update or a Normal flycut update.
209        if (isset($request['category_level'])) {
210
211            if ($request['category_level'] == 0) {
212                $this->checkCategoriesCount($request);
213
214                $category = ShortcutCategory::where($searchArray)->first();
215                if ($category) {
216                    $object = Shortcut::find($shortcutId);
217                    $object->category_id = $request['category_id'];
218                    $object->sub_categories_lv1_id = null;
219                    $object->sub_categories_lv2_id = null;
220                    $object->version = $shortcut->version + 1;
221                    $object->save();
222                    $result = $object;
223                    $result['category_name'] = $category['name'];
224                }
225            }
226
227            if ($request['category_level'] == 1) {
228                $this->checkSubCategoriesCount($request);
229
230                $category = ShortcutSubCategoryLv1::where($searchArray)->first();
231                if ($category) {
232                    $object = Shortcut::find($shortcutId);
233                    $object->category_id = $category['category_id'];
234                    $object->sub_categories_lv1_id = $request['category_id'];
235                    $object->sub_categories_lv2_id = null;
236                    $object->version = $shortcut->version + 1;
237                    $object->save();
238                    $result = $object;
239                    $result['category_name'] = $category['name'];
240                }
241            }
242
243            if ($request['category_level'] == 2) {
244                $this->checkSubCategoriesCount($request);
245
246                $category = ShortcutSubCategoryLv2::where($searchArray)->first();
247                if ($category) {
248                    $object = Shortcut::find($shortcutId);
249                    $object->category_id = $category['category_id'];
250                    $object->sub_categories_lv1_id = $category['sub_categories_lv1_id'];
251                    $object->sub_categories_lv2_id = $request['category_id'];
252                    $object->version = $shortcut->version + 1;
253                    $object->save();
254                    $result = $object;
255                    $result['category_name'] = $category['name'];
256                }
257            }
258        } else {
259            $whereShortCutVersions = ['shortcut_id' => $shortcutId];
260            $versionData = ShortcutVersion::where($whereShortCutVersions)->first();
261
262            $data['version'] = $shortcut->version + 1;
263            $data['version_counts'] = (isset($shortcut->version_counts)) ? $shortcut->version_counts + 1 : 1;
264            $data['sub_categories_lv1'] = $request->get('sub_categories_lv1', '');
265            $data['sub_categories_lv2'] = $request->get('sub_categories_lv2', '');
266
267            $charactors_count = strlen(strip_tags($data['text']));
268            $words_count = str_word_count(strip_tags($data['text']));
269            $html_count = strlen(strip_tags($data['html']));
270
271            $data['charactors_count'] = $charactors_count;
272            $data['words_count'] = $words_count;
273            $data['html_count'] = $html_count;
274
275            $result = Shortcut::find($shortcutId);
276            try {
277                $result = $result->update($data);
278            } catch (\Throwable $th) {
279                Log::error('error', [
280                    'message' => $th->getMessage(),
281                    'file' => $th->getFile(),
282                    'line' => $th->getLine(),
283                ]);
284            }
285
286            // if (!empty($versionData)) {
287            //     $last_version_count = (isset($versionData->last_version_count)) ? $versionData->last_version_count + 1 : 1;
288
289            //     $statisticsData = array(
290            //         'charactors_count' => $charactors_count,
291            //         'words_count' => $words_count,
292            //         'html_count' => $html_count,
293            //         'media_count' => count($data['uploads']),
294            //         'updated_at' => now(),
295            //     );
296
297            //     $current_flycutData = array_merge($data, $statisticsData);
298            //     $current_flycutData = json_encode($current_flycutData, true);
299            //     $versionData = $versionData->toArray();
300            //     $versionData['last_version_count'] = $last_version_count;
301            //     if(!isset($versionData['current_version'])){
302            //         $versionData['current_version']=0;
303            //     }
304            //     $versionData['current_version'] = $versionData['current_version'] + 1;
305
306            //     array_push($versionData, $current_flycutData);
307
308            //     unset($versionData['_id']);
309            //     Log::info(['ShortcutVersion' => $versionData]);
310            //     $shortcut_versions = ShortcutVersion::where($whereShortCutVersions)->first();
311            //     try {
312            //         $shortcut_versions = $shortcut_versions->update($versionData);
313            //         Log::info(['ShortcutVersion' => $shortcut_versions]);
314            //     } catch (\Throwable $th) {
315            //         Log::error([
316            //             'message' => $th->getMessage(),
317            //             'file' => $th->getFile(),
318            //             'line' => $th->getLine(),
319            //         ]);
320            //     }
321            // } else {
322            $shortcutVersionHistory = new ShortcutVersion;
323            $statisticsData = [
324                'charactors_count' => $charactors_count,
325                'words_count' => $words_count,
326                'html_count' => $html_count,
327                'media_count' => count($data['uploads']),
328            ];
329            $flymsg_details = array_merge($data, $statisticsData);
330            $versionHistoryData[0] = json_encode($flymsg_details, true);
331            $versionHistoryData['shortcut_id'] = $shortcutId;
332            $versionHistoryData['user_id'] = $userId;
333            $versionHistoryData['last_version_count'] = 0;
334            if (isset($versionHistoryData['current_version'])) {
335                $versionHistoryData['current_version'] = $versionHistoryData['current_version'] + 1;
336            } else {
337                $versionHistoryData['current_version'] = 0;
338            }
339            $shortcutVersionHistory->fill($versionHistoryData);
340            $shortcutVersionHistory->push();
341            // }
342        }
343
344        $this->dispatchShortcutEvent();
345
346        $userId = $request->user()->getKey();
347        $this->saveBrowserUsed($userId);
348
349        if (isset($request['category_level'])) {
350            return response()->json($result);
351        } else {
352            return response()->json((bool) $result);
353        }
354    }
355
356    /**
357     * Filters a list of shortcuts by category id, shortcut and direction
358     */
359    // public function list(Request $request): JsonResponse
360    // {
361    //     try {
362    //         $limit = $request->get('limit');
363    //         $skip = $request->get('skip');
364    //         $orderBy = $request->get('order_by');
365
366    //         $result = Shortcut::when($request->anyFilled(['category_id', 'sub_categories_lv1_id', 'sub_categories_lv2_id']), function ($query) use ($request) {
367    //             $categoryId = $request->get('category_id');
368    //             $subCategoryLv1Id = $request->get('sub_categories_lv1_id');
369    //             $subCategoryLv2Id = $request->get('sub_categories_lv2_id');
370
371    //             if (filled($subCategoryLv2Id)) {
372    //                 return $query->where('sub_categories_lv2_id', $subCategoryLv2Id);
373    //             } else if (filled($subCategoryLv1Id)) {
374    //                 return $query->where('sub_categories_lv1_id', $subCategoryLv1Id);
375    //             } else if (filled($categoryId)) {
376    //                 return $query->where('category_id', $categoryId);
377    //             }
378    //         })->when($orderBy, function ($query, string $orderBy) {
379    //             $order = explode(",", $orderBy);
380    //             $query->orderBy($order[0], $order[1]);
381    //         }, function ($query) {
382    //             $query->latest();
383    //         })
384    //         ->when($skip, function ($query, $skip) {
385    //             $query->skip($skip);
386    //         })
387    //         ->when($limit, function ($query, $limit) {
388    //             $query->limit($limit);
389    //         })
390    //         ->get();
391
392    //         return response()->json($result);
393    //     } catch (\Throwable $th) {
394    //         Log::info([
395    //             'message' => $th->getMessage(),
396    //             'file' => $th->getFile(),
397    //             'line' => $th->getLine(),
398    //         ]);
399    //         return response()->json(["error" => "Something went wrong"]);
400    //     }
401    // }
402
403    public function list(Request $request): JsonResponse
404    {
405        try {
406            $query = Shortcut::where('user_id', $request->user()->id);
407
408            $this->applyFilters($query, $request);
409            $this->applyOrdering($query, $request->get('order_by'));
410            $this->applyPagination($query, $request->get('skip'), $request->get('limit'));
411
412            $result = $query->get();
413
414            return response()->json($result);
415        } catch (\Throwable $th) {
416            Log::error('error', [
417                'message' => $th->getMessage(),
418                'file' => $th->getFile(),
419                'line' => $th->getLine(),
420            ]);
421
422            return response()->json(['error' => 'Something went wrong'], 500);
423        }
424    }
425
426    private function applyFilters($query, Request $request)
427    {
428        if ($request->filled('sub_categories_lv2_id')) {
429            $query->where('sub_categories_lv2_id', $request->get('sub_categories_lv2_id'));
430        } elseif ($request->filled('sub_categories_lv1_id')) {
431            $query->where('sub_categories_lv1_id', $request->get('sub_categories_lv1_id'));
432        } elseif ($request->filled('category_id')) {
433            $query->where('category_id', $request->get('category_id'));
434        }
435    }
436
437    private function applyOrdering($query, ?string $orderBy)
438    {
439        if ($orderBy) {
440            [$column, $direction] = explode(',', $orderBy);
441            $query->orderBy($column, $direction);
442        } else {
443            $query->latest();
444        }
445    }
446
447    private function applyPagination($query, ?int $skip, ?int $limit)
448    {
449        if ($skip !== null) {
450            $query->skip($skip);
451        }
452        if ($limit !== null) {
453            $query->limit($limit);
454        }
455    }
456
457    public function details(Request $request, $shortcutId)
458    {
459        $searchArray = ['_id' => $shortcutId];
460        $shortcut = Shortcut::with('category')->where($searchArray)->first();
461
462        if (!$shortcut) {
463            return response()->json(['error' => 'Shortcut not found'], 404);
464        }
465
466        // check if word counts and characters counts not found for the shortcut
467        if (! isset($shortcut->charactors_count) || ($shortcut->charactors_count == '')) {
468            $shortcut->charactors_count = strlen(strip_tags($shortcut->text));
469            $shortcut->words_count = str_word_count(strip_tags($shortcut->text));
470            $shortcut->html_count = strlen(strip_tags($shortcut->html));
471
472            $shortcut->save();
473        }
474
475        $result = $shortcut->toArray();
476        $result['category_name'] = $shortcut->category->name;
477        unset($result['category']);
478
479        return response()->json($result);
480    }
481
482    public function delete(Request $request, $shortcutId): JsonResponse
483    {
484        try {
485            ShortcutVersion::where('shortcut_id', $shortcutId)->delete();
486            $result = Shortcut::where('_id', $shortcutId)->delete();
487            $userId = $request->user()->getKey();
488
489            dispatch(function () use ($userId) {
490                $this->dispatchShortcutEvent();
491                Cache::forget('template_'.$userId);
492            });
493
494            return response()->json((bool) $result);
495        } catch (\Throwable $th) {
496            Log::error($th->getMessage());
497
498            return response()->json(false);
499        }
500    }
501
502    public function dispatchShortcutEvent()
503    {
504        $user = request()->user();
505        if ($user instanceof User) {
506            event(new \App\Events\User\ShortcutUpdated($user));
507        }
508        if ($user instanceof BusinessUser) {
509            event(new \App\Events\Business\ShortcutUpdated($user));
510        }
511    }
512
513    public function latest(Request $request): JsonResponse
514    {
515        $latest_shortcuts = Shortcut::with('category')->orderBy('created_at', 'desc')->paginate(20);
516
517        return response()->json($latest_shortcuts);
518    }
519
520    public function duplicate(Request $request, $id): JsonResponse
521    {
522        $flycut = Shortcut::findOrFail($id);
523
524        $new = $flycut->replicate(['created_at', 'updated_at', 'id']);
525        $new->shortcut = "{$flycut->shortcut} (Copy)";
526        $new->save();
527
528        return response()->json($new);
529    }
530
531    private function saveBrowserUsed($userId): void
532    {
533        $user = User::firstWhere('_id', $userId);
534        $userInfo = UserInfo::firstWhere('email', $user['email']);
535        $agent = new Agent;
536        $browser = $agent->browser();
537        $propertyValue = $browser;
538        if ($browser === 'Edge' || $browser === 'IE') {
539            $propertyValue = 'Edge';
540        }
541        $propertyValue = is_string($propertyValue) ? ucfirst($propertyValue) : '';
542        $userInfo->last_browser_used = $propertyValue;
543        $userInfo->save();
544    }
545
546    /**
547     * Function to delete the shortcut version
548     */
549    public function deleteShortcutVersion(Request $request, $shortcutId, $shortcut_version_index, $versionId = null): JsonResponse
550    {
551        // New
552        if (filled($versionId)) {
553            $result = ShortcutVersion::where('_id', $versionId)->delete();
554        } else {
555            // Old
556            $versionDataArray = [];
557
558            $whereShortCutVersions = ['shortcut_id' => $shortcutId];
559            $versionData = ShortcutVersion::where($whereShortCutVersions)->first();
560
561            if (! empty($versionData)) {
562                $versionDataArray = $versionData->toArray();
563
564                unset($versionDataArray['_id']);
565                unset($versionDataArray[$shortcut_version_index]);
566            }
567            $versionData->delete();
568
569            $versionData = new ShortcutVersion;
570            $versionData->fill($versionDataArray);
571            $result = $versionData->push();
572
573            $searchArray = ['_id' => $shortcutId];
574            $shortcut = Shortcut::where($searchArray)->first();
575            // $shortcut->version = $shortcut->version - 1;
576            $shortcut->decrement('version_counts');
577            $shortcut->save();
578        }
579
580        return response()->json((bool) $result);
581    }
582
583    /**
584     * Function to Roll back the previous added version to the current shortcut
585     */
586    public function rollbackToPreviousVersion(Request $request): JsonResponse
587    {
588        $validator = Validator::make($request->all(), [
589            'shortcutId' => ['required', 'exists:shortcut_versions,shortcut_id'],
590            'versionId' => ['required', 'exists:shortcut_versions,_id'],
591        ]);
592
593        if ($validator->fails()) {
594            return response()->json($validator->errors());
595        }
596
597        $shortcutVersion = ShortcutVersion::find($request->versionId);
598
599        $collection = collect($shortcutVersion->getAttributes());
600
601        $maxKey = $collection->filter(function ($value, $key) {
602            return is_int($key);
603        })->keys()->max();
604
605        $maxValue = $collection->get($maxKey);
606
607        $versionData = json_decode($maxValue);
608
609        $shortcut = Shortcut::find($request->shortcutId);
610
611        // Update Shortcut to current version data
612        $result = $shortcut->update([
613            'shortcut' => $versionData->shortcut,
614            'title' => $versionData->title,
615            'text' => $versionData->text,
616            'html' => $versionData->html,
617            'first_line' => $versionData->first_line,
618            'rollback_counts' => isset($shortcut->rollback_counts) ? $shortcut->rollback_counts + 1 : 1,
619        ]);
620
621        // Update ShortcutVersion updated_at field so it can be picked on frontend as current version
622        $shortcutVersion->touch();
623
624        $this->dispatchShortcutEvent();
625
626        $userId = $request->user()->getKey();
627        $this->saveBrowserUsed($userId);
628
629        return response()->json((bool) $result);
630    }
631
632    /**
633     * getShortcutVersions function to get all shortcut versions list
634     *
635     * @param  string  $shortcutId  main shortcut id
636     */
637    public function getShorcutVersions(Request $request, string $shortcutId): JsonResponse
638    {
639        $shortcutVersions = ShortcutVersion::where('shortcut_id', $shortcutId)->get();
640
641        return response()->json($shortcutVersions);
642    }
643
644    /**
645     * Make a Flycut  shareable function.
646     *
647     * @param  string  $shortcutId  main shortcut id
648     * @return string encyrpted key or empty string
649     */
650    public function makeShareable(Request $request, string $shortcutId): JsonResponse
651    {
652        $shortcutSearchArray = ['_id' => $shortcutId];
653        $result = Shortcut::where($shortcutSearchArray)->update(['shareable' => 1]);
654        // EncryptString using  to minimize the key.
655
656        $ShortcutSharedLinks = new ShortcutSharedLinks;
657        $ShortcutSharedLinks->shortcut_id = $shortcutId;
658        $ShortcutSharedLinks->save();
659
660        $this->dispatchShortcutEvent();
661
662        $userId = $request->user()->getKey();
663        $this->saveBrowserUsed($userId);
664
665        if ($result) {
666            return response()->json((string) $ShortcutSharedLinks->id);
667        } else {
668            return response()->json((bool) $result);
669        }
670    }
671
672    /**
673     * Get a Shared Flycut Details.
674     *
675     * @param  string  $shortcutId  encrypted token
676     * @return JsonResponse Shortcut
677     */
678    public function getShared(Request $request, $key): JsonResponse
679    {
680        $shortcutSearchArray = ['_id' => $key];
681        $shortcut_shared_links = DB::table('shortcut_shared_links')->where($shortcutSearchArray)->first();
682
683        $shortcutSearchArray = ['_id' => $shortcut_shared_links->shortcut_id];
684        $result = DB::table('shortcuts')->where($shortcutSearchArray)->first();
685        if ($result && isset($result->shareable) && (int) $result->shareable == 1) {
686            return response()->json(['status' => true, 'data' => $result]);
687        } else {
688            return response()->json(['status' => false, 'msg' => "This Flycut has been deleted or it's not shareable anymore"]);
689        }
690    }
691
692    private function mediaSize($uploads)
693    {
694        if (empty($uploads)) {
695            return 0;
696        }
697
698        $totalSum = collect($uploads)->sum(function ($item) {
699            return isset($item['size']) ? $item['size'] : 0;
700        });
701
702        // Default back to legacy mode of counting number of source paths.
703        if (empty($totalSum)) {
704            return count($uploads) ?? 0;
705        }
706
707        return $totalSum;
708    }
709
710    public function deleteBulkFlycuts(FlycutBulkDeleteRequest $request): JsonResponse
711    {
712        try {
713            $shortcut_ids = $request->shortcut_ids;
714            $userId = $request->user()->getKey();
715
716            if (! empty($shortcut_ids)) {
717                foreach ($shortcut_ids as $shortcut_id) {
718                    $versions = ShortcutVersion::where('shortcut_id', $shortcut_id);
719                    $versions->forceDelete();
720
721                    $result = Shortcut::where('_id', $shortcut_id)->delete();
722
723                    dispatch(function () use ($userId) {
724                        $this->dispatchShortcutEvent();
725                        Cache::forget('template_'.$userId);
726                    });
727                }
728            }
729
730            return response()->json((bool) $result);
731        } catch (\Throwable $th) {
732            Log::error($th->getMessage());
733
734            return response()->json(false);
735        }
736    }
737}