Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 187
0.00% covered (danger)
0.00%
0 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
UserController
0.00% covered (danger)
0.00%
0 / 187
0.00% covered (danger)
0.00%
0 / 11
2162
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
 update
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
30
 details
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 delete
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
2
 setHeapId
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getUserBillingData
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
90
 patchOnboarding
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
56
 getOnboardingQuestions
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 storeOnboardingQuestionAnswers
0.00% covered (danger)
0.00%
0 / 63
0.00% covered (danger)
0.00%
0 / 1
306
 acceptCompanyInvitation
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 rejectCompanyInvitation
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace App\Http\Controllers\v1;
4
5use Carbon\Carbon;
6use App\Http\Models\Plans;
7use Illuminate\Http\Request;
8use App\Http\Models\Auth\User;
9use Illuminate\Http\JsonResponse;
10use App\Http\Controllers\Controller;
11use App\Http\Models\FlyGrammarLanguage;
12use App\Http\Models\OnboardingAnswer;
13use Illuminate\Support\Facades\Cache;
14use App\Http\Requests\UserFormRequest;
15use Illuminate\Support\Facades\Config;
16use App\Http\Models\OnboardingQuestion;
17use App\Http\Models\Setting;
18use App\Http\Models\UserInfo;
19use App\Http\Services\Admin\Users\AdminUsersService;
20use Illuminate\Support\Facades\Log;
21
22class UserController extends Controller
23{
24    /**
25     * Create a new controller instance.
26     *
27     * @return void
28     */
29    public function __construct(
30        private AdminUsersService $adminUsersService,
31    ) {}
32
33    public function update(UserFormRequest $request)
34    {
35        $data = $request->validated();
36        $user = $request->user();
37        $userId = $user->getKey();
38
39        $result = User::where('_id', $userId)->update($data);
40        $userInfo = UserInfo::where('email', $user->email)->first();
41
42        if (!$userInfo) {
43            $userInfo = UserInfo::where('user_id', $userId)->first();
44        }
45
46        if (isset($data['title'])) {
47            $userInfo->job_title = $data['title'];
48        }
49
50        if (isset($data['company_name'])) {
51            $userInfo->company = $data['company_name'];
52        }
53
54        if (isset($data['phone_number'])) {
55            $userInfo->phone = $data['phone_number'];
56        }
57
58        $userInfo->save();
59
60        $cacheKey = 'user_details_' . $userId;
61        Cache::forget($cacheKey);
62
63        return response()->json((bool) $result);
64    }
65
66    public function details(Request $request)
67    {
68        $userId = $request->user()->getKey();
69        $cacheKey = 'user_details_' . $userId;
70        $result = Cache::remember($cacheKey, Config::get('cache.expiry'), function () use ($request) {
71            $userId = $request->user()->getKey();
72            $searchArray = ['_id' => $userId];
73            $result = User::where($searchArray)->first();
74            $result['is_poc'] = $result->isPOC();
75
76            $result['is_password_set'] = $result->isPasswordSet();
77
78            return $result;
79        });
80
81        return response()->json($result);
82    }
83
84    public function delete(Request $request): JsonResponse
85    {
86        Log::info('User delete request', [
87            'user' => $request->user()->email,
88            'ip' => $request->ip(),
89            'date' => Carbon::now()->toDateTimeString(),
90        ]);
91
92        //Notification::send($request->user(), new DeleteAccount);
93
94        $userId = $request->user()->getKey();
95        $user = User::where('_id', $userId)->first();
96
97        $this->adminUsersService->delete($user);
98
99        return response()->json(
100            data: [
101                'success' => true,
102                'message' => "user deleted successfully",
103            ],
104            status: 200
105        );
106    }
107
108    public function setHeapId(Request $request, User $user): JsonResponse
109    {
110        if (isset($request->heap_analytics_id)) {
111            $user->heap_analytics_id = $request->heap_analytics_id;
112            $user->save();
113        }
114
115        return response()->json([], 201);
116    }
117
118    public function getUserBillingData(Request $request): JsonResponse
119    {
120        try {
121            $data = [];
122            $user = $request->user();
123
124            $data['payment_methods'] = $user->paymentMethods();
125            $data['default_payment_method'] = $user->defaultPaymentMethod();
126            $invoices = $user->invoices()->toArray();
127
128            foreach ($invoices as $key => $invoice) {
129                // Formating time.
130                $time_start = $invoice['status_transitions']['finalized_at'];
131                $d_start = new \DateTime(date('F jS, Y', $time_start));
132
133                // Setting intervel.
134                $last_index = $invoice['lines']['total_count'] - 1;
135                $interval = $invoice['lines']['data'][$last_index]['plan']['interval'];
136
137                if ($interval == 'year') {
138                    $interval = 'Annualy';
139                } else {
140                    $interval = 'Monthly';
141                }
142
143                // Billing reason.
144                $billing_reason = ucfirst($invoice['billing_reason']);
145                $billing_reason = str_replace('_', ' ', $billing_reason);
146
147                // Plan Name.
148                $plan_name = $invoice['lines']['data'][$last_index]['plan']['nickname'];
149
150                // Incase of null get the name from DB
151                if (!$plan_name) {
152                    $plan_id = $invoice['lines']['data'][$last_index]['plan']['id'];
153                    $plan = Plans::where('stripe_id', $plan_id)->first();
154                    if (isset($plan)) {
155                        $plan_name = $plan['title'];
156                    }
157                }
158
159                if (str_contains($plan_name, 'Growth')) {
160                    $plan_name = 'Growth';
161                }
162                if (str_contains($plan_name, 'Starter')) {
163                    $plan_name = 'Starter';
164                }
165                if (str_contains($plan_name, 'Sales')) {
166                    $plan_name = 'Sales Pro';
167                }
168
169                // End of Plan Name.
170                $data['invoices'][$key]['plan_name'] = $plan_name . ' Plan';
171                $data['invoices'][$key]['billing_reason'] = $billing_reason;
172                $data['invoices'][$key]['interval'] = $interval;
173                $data['invoices'][$key]['status'] = $invoice['status'];
174                $data['invoices'][$key]['total'] = $invoice['total'] / 100 . ' ' . ucfirst($invoice['currency']);
175                $data['invoices'][$key]['invoice_pdf'] = $invoice['invoice_pdf'];
176                $data['invoices'][$key]['billing_date'] = $d_start->format('F j, Y');
177            }
178
179            return response()->json($data);
180        } catch (\Exception $e) {
181            return response()->json([], 422);
182        }
183    }
184
185    public function patchOnboarding(Request $request, User $user): JsonResponse
186    {
187        try {
188            $validated_data = $request->validate([
189                "step" => "required|numeric",
190                "max_step" => "required|numeric",
191                "tooltip_learning_resources_showed" => "sometimes|boolean",
192                "onboardingv2_presented" => "sometimes|boolean",
193            ]);
194
195            $step = $validated_data['step'];
196            $max_step = $validated_data['max_step'];
197
198            if (empty($user->onboardingv2_step) || $step > $user->onboardingv2_step) {
199                $user->onboardingv2_step = $step;
200            }
201
202            if ($step > $max_step) {
203                $user->onboardingv2_completed = true;
204            }
205
206            if (isset($validated_data['tooltip_learning_resources_showed'])) {
207                $user->tooltip_learning_resources_showed = $validated_data['tooltip_learning_resources_showed'];
208            }
209
210            if (isset($validated_data['onboardingv2_presented'])) {
211                $user->onboardingv2_presented = $validated_data['onboardingv2_presented'];
212            }
213
214            $user->save();
215            return response()->json($user);
216        } catch (\Exception $e) {
217            return response()->json([], 422);
218        }
219    }
220
221    /**
222     * [getOnboardingQuestions function to get onboarding process questions]
223     *
224     * @param  Request  $request []
225     * @return [json] [list of all questions step wise]
226     */
227    public function getOnboardingQuestions(Request $request): JsonResponse
228    {
229        $user_onboarding = User::find(auth('api')->id());
230        $result['data'] = OnboardingQuestion::all();
231
232        $result['steps'] = [
233            'next_step' => $user_onboarding?->onboarding_step + 1,
234            'onboarding_percentage' => $user_onboarding?->onboarding_percentage ?? 0,
235        ];
236
237        return response()->json($result);
238    }
239
240    /**
241     * [storeOnboardingQuestionAnswers function to store onboarding process question answers]
242     *
243     * @param  Request  $request []
244     * @return [json] [true/false]
245     */
246    public function storeOnboardingQuestionAnswers(Request $request): JsonResponse
247    {
248        $searchArray = [
249            'user_id' => $request->user_id,
250            'question_id' => $request->question_id,
251            'step' => $request->step,
252        ];
253
254        $userDetails = User::find($request->user_id);
255        if ($userDetails) {
256            $user_email = $userDetails['email'];
257        } else {
258            $user_email = $request->user()->email;
259        }
260
261        $userInfo = UserInfo::where('email', $user_email)->first();
262
263        $result = null;
264        if ($request->question_id) {
265            $existingAnswer = OnboardingAnswer::where($searchArray)->first();
266
267            if (!empty($existingAnswer)) {
268                $existingAnswer->answer = $request->answer;
269                $result = $existingAnswer->save();
270            } else {
271                $data = $request->all();
272                $data['next_step'] = $request->step + 1;
273                $result = OnboardingAnswer::create($data);
274            }
275
276            if ($request->step == 1) {
277                if ($request->question_index_id == 1) {
278                    $language = FlyGrammarLanguage::where('description', $request->answer)->first();
279
280                    if ($language) {
281                        $userInfo->fly_grammar_default_language = $language->value;
282                    } else {
283                        $userInfo->fly_grammar_default_language = 'auto';
284                    }
285
286                    $result = Setting::where('user_id', $request->user_id)->update([
287                        'fly_grammar_default_language' => $userInfo->fly_grammar_default_language,
288                    ]);
289                }
290
291                if ($request->question_index_id == 2) {
292                    $userInfo->department = $request->answer;
293                }
294
295                if ($request->question_index_id == 4) {
296                    $userInfo->flymsg_use_case = $request->answer;
297                }
298
299                if ($request->question_index_id == 3) {
300                    $userInfo->job_role = $request->answer;
301                }
302            }
303
304
305            if ($request->step == 2 && $request->question_index_id == 1) {
306                // get question details
307                $quesArray = [
308                    '_id' => $request->question_id,
309                ];
310
311                $question = OnboardingQuestion::where($quesArray)->first()->toArray();
312                $step2options = $question['questions'][1]['options'];
313                array_pop($step2options);
314
315                //parse the answer
316                $other_option_value = $productivity_problems_answer = '';
317                $is_other_option_exists = false;
318                $answer_options = json_decode($request->answer);
319                if (!empty($answer_options)) {
320                    foreach ($answer_options as $answer_option) {
321                        if (!in_array($answer_option, $step2options)) {
322                            $other_option_value = $answer_option;
323                            $is_other_option_exists = true;
324                        }
325                    }
326
327                    if ($is_other_option_exists) {
328                        array_pop($answer_options);
329                    }
330
331                    $productivity_problems_answer = implode(';', $answer_options);
332                }
333
334                $userInfo->productivity_problems = $productivity_problems_answer;
335                $userInfo->type_here_how_flymsg_will_help_you___ = $other_option_value;
336            }
337        }
338
339        $userInfo->save();
340
341        // Store onboarding status in the user document.
342        $userData['onboarding_step'] = $request->step;
343        $userData['onboarding_percentage'] = ((int) $request->step / 10) * 100; // 10 steps counts
344        if ($request->step == 10) {
345            $userData['onboarding'] = 'completed';
346            $userData['onboarding_percentage'] = 100;
347        }
348        $result = User::where('_id', $request->user_id)->update($userData);
349        $result = $userData;
350
351        return response()->json($result);
352    }
353
354    public function acceptCompanyInvitation(Request $request, User $user)
355    {
356        $validated_data = $request->validate([
357            "company_id" => "required|string",
358        ]);
359
360        $company_id = $validated_data['company_id'];
361
362        $user = $this->adminUsersService->acceptUserInvitation($user, $company_id);
363
364        return response()->json($user->toArray());
365    }
366
367    public function rejectCompanyInvitation(Request $request, User $user)
368    {
369        $validated_data = $request->validate([
370            "company_id" => "required|string",
371        ]);
372
373        $company_id = $validated_data['company_id'];
374
375        $user = $this->adminUsersService->rejectUserInvitation($user, $company_id);
376
377        return response()->json($user->toArray());
378    }
379}