Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 1011
0.00% covered (danger)
0.00%
0 / 45
CRAP
0.00% covered (danger)
0.00%
0 / 1
Companies
0.00% covered (danger)
0.00%
0 / 1011
0.00% covered (danger)
0.00%
0 / 45
37056
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 create_company
0.00% covered (danger)
0.00%
0 / 327
0.00% covered (danger)
0.00%
0 / 1
1980
 list_companies
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 get_company
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 get_company_users
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 get_user_companies
0.00% covered (danger)
0.00%
0 / 43
0.00% covered (danger)
0.00%
0 / 1
42
 update_company_users
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 update_company_selected
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 delete_company_users
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 update_company
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
30
 update_company_blocked
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 upload_file
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
30
 delete_company
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 update_company_users_selected
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 create_company_users
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
42
 get_cc_bcc
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_bcc
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_bcc
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_bcc
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 isEmailValid
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 get_blocked_domains
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 delete_blocked_domain
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 update_blocked_domain
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 create_blocked_domain
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 list_project_types
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
30
 get_project_types
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
12
 update_project_types
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
30
 update_project_types_benchmarks
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 delete_project_types
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 list_workflow_project_types
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_workflow_project_types
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 delete_workflow_project_types
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 list_workflow_customer_types
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_workflow_customer_types
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 delete_workflow_customer_types
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 list_workflow_questions
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_workflow_questions
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 get_company_executive
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 get_all_details
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
6
 list_all_companies
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 update_company_permission
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
20
 list_facility_settings
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 update_facility_settings
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
90
 list_trade_alignment_settings
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 update_trade_alignment_settings
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblApprovers;
6use App\Models\TblApproversV2;
7use App\Models\TblBlockedDomains;
8use App\Models\TblCcAcceptanceNotifications;
9use App\Models\TblCcBcc;
10use App\Models\TblCcBccNotifications;
11use App\Models\TblCcBccRequestNotifications;
12use App\Models\TblCcG3WEmailReminders;
13use App\Models\TblCompanies;
14use App\Models\TblCompanyEmails;
15use App\Models\TblCompanyUsers;
16use App\Models\TblEmailConfiguration;
17use App\Models\TblFacilitySettings;
18use App\Models\TblFinalSummary;
19use App\Models\TblLastFollowUpDate;
20use App\Models\TblOngoingJobs;
21use App\Models\TblProjectTypes;
22use App\Models\TblQuotations;
23use App\Models\TblToAcceptanceNotifications;
24use App\Models\TblTradeAlignmentSettings;
25use App\Models\TblUsers;
26use App\Models\TblWorkflowApprover;
27use App\Models\TblWorkflowCustomerTypes;
28use App\Models\TblWorkflowProjectTypes;
29use App\Models\TblWorkflowQuestions;
30use Illuminate\Http\Request;
31use Illuminate\Support\Facades\App;
32use Illuminate\Support\Facades\Cache;
33use Illuminate\Support\Facades\DB;
34use Illuminate\Support\Facades\Storage;
35
36class Companies extends Controller
37{
38    private $locale;
39
40    private $userId;
41
42    private $region;
43
44    private $companyIds;
45
46    private $companyId;
47
48    public function __construct()
49    {
50        $this->locale = @getallheaders()['Locale-ID'];
51        $this->userId = @getallheaders()['User-ID'];
52        $this->region = @getallheaders()['Region'];
53
54        App::setLocale($this->locale);
55
56        $this->companyIds = [];
57
58        if ($this->region != null && $this->region != '' && $this->region != 'All') {
59            $this->region = urldecode($this->region);
60
61            $query = 'SELECT 
62                        b.company_id
63                    FROM 
64                        tbl_company_users a 
65                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
66                    WHERE 
67                        a.user_id = ?
68                        AND b.region = ?';
69
70            $this->companyIds = DB::select($query, [intval($this->userId), $this->region]);
71
72            $this->companyIds = collect($this->companyIds)->pluck('company_id')->toArray();
73        } else {
74            $this->companyIds = TblCompanyUsers::where('user_id', $this->userId)->pluck('company_id')->all();
75        }
76
77        $this->companyId = implode(',', $this->companyIds);
78    }
79
80    public function create_company(Request $request)
81    {
82
83        try {
84
85            $data = $request->all();
86            $data['updated_at'] = date('Y-m-d H:i:s');
87            $logo = Storage::get('logo-light.png');
88            $base64 = base64_encode($logo);
89            $mimetype = 'image/png';
90            $blob = 'data:'.$mimetype.';base64,'.$base64;
91            $data['logo'] = $blob;
92            $data['filename'] = 'logo-light.png';
93            $data['filesize'] = 6233;
94            $data['filetype'] = $mimetype;
95            $data['default_page'] = 'orders';
96            $userId = $data['user_id'];
97            unset($data['user_id']);
98
99            $result = [];
100            $newCompanyId = 0;
101
102            DB::beginTransaction();
103
104            if (isset($data['template_company_id'])) {
105                $companyId = intval($data['template_company_id']);
106
107                $company = TblCompanies::where('company_id', $companyId)->first();
108
109                $data['is_send'] = $company->is_send;
110                $data['limit_send'] = $company->limit_send;
111                $data['is_send_follow_up'] = $company->is_send_follow_up;
112                $data['is_send_request'] = $company->is_send_request;
113                $data['is_send_g3w'] = $company->is_send_g3w;
114                $data['revenue_per_employee_per_day'] = $company->revenue_per_employee_per_day;
115                $data['minimum_margin'] = $company->minimum_margin;
116                $data['general_costs'] = $company->general_costs;
117                $data['hours_per_worker_per_day'] = $company->hours_per_worker_per_day;
118                $data['cost_of_hour'] = $company->cost_of_hour;
119                $data['hours_per_worker_per_day_percentage'] = $company->hours_per_worker_per_day_percentage;
120                $data['convert_to_job_amount_limit'] = $company->convert_to_job_amount_limit;
121                $data['minimum_order_size'] = $company->minimum_order_size;
122                $data['minimum_order_size_v2'] = $company->minimum_order_size_v2;
123                $data['last_follow_up_date'] = $company->last_follow_up_date;
124                $data['limit_reminder_emails'] = $company->limit_reminder_emails;
125                $data['workflow_budget_size'] = $company->workflow_budget_size;
126                $data['is_send_executive'] = $company->is_send_executive;
127                $data['customer_type_ids'] = $company->customer_type_ids;
128                $data['goal_for_the_year'] = $company->goal_for_the_year;
129                $data['logo'] = $company->logo;
130                $data['filetype'] = $company->filetype;
131                $data['filename'] = $company->filename;
132                $data['filesize'] = $company->filesize;
133
134                $result = TblCompanies::create($data);
135                $newCompanyId = $result->company_id;
136
137                $approvers = TblApprovers::where('company_id', $companyId)->get();
138
139                if (count($approvers) > 0) {
140                    $newApprovers = [];
141                    foreach ($approvers as $item) {
142                        $newApprovers[] = [
143                            'company_id' => $newCompanyId,
144                            'user_id' => $item->user_id,
145                            'created_by' => $data['created_by'],
146                        ];
147                    }
148
149                    TblApprovers::insert((array) $newApprovers);
150                }
151
152                $approversV2 = TblApproversV2::where('company_id', $companyId)->get();
153
154                if (count($approversV2) > 0) {
155                    $newApproversV2 = [];
156                    foreach ($approversV2 as $item) {
157                        $newApproversV2[] = [
158                            'company_id' => $newCompanyId,
159                            'user_id' => $item->user_id,
160                            'created_by' => $data['created_by'],
161                        ];
162                    }
163
164                    TblApproversV2::insert((array) $newApproversV2);
165                }
166
167                $blockedDomains = TblBlockedDomains::where('company_id', $companyId)->get();
168
169                if (count($blockedDomains) > 0) {
170                    $newBlockedDomains = [];
171                    foreach ($blockedDomains as $item) {
172                        $newBlockedDomains[] = [
173                            'company_id' => $newCompanyId,
174                            'domain' => $item->domain,
175                            'created_by' => $data['created_by'],
176                        ];
177                    }
178
179                    TblBlockedDomains::insert((array) $newBlockedDomains);
180                }
181
182                $ccAcceptanceNotifications = TblCcAcceptanceNotifications::where('company_id', $companyId)->get();
183
184                if (count($ccAcceptanceNotifications) > 0) {
185                    $newCcAcceptanceNotifications = [];
186                    foreach ($ccAcceptanceNotifications as $item) {
187                        $newCcAcceptanceNotifications[] = [
188                            'company_id' => $newCompanyId,
189                            'email' => $item->email,
190                            'created_by' => $data['created_by'],
191                        ];
192                    }
193
194                    TblCcAcceptanceNotifications::insert((array) $newCcAcceptanceNotifications);
195                }
196
197                $ccBcc = TblCcBcc::where('company_id', $companyId)->get();
198
199                if (count($ccBcc) > 0) {
200                    $newCcBcc = [];
201                    foreach ($ccBcc as $item) {
202                        $newCcBcc[] = [
203                            'company_id' => $newCompanyId,
204                            'email' => $item->email,
205                            'created_by' => $data['created_by'],
206                        ];
207                    }
208
209                    TblCcBcc::insert((array) $newCcBcc);
210                }
211
212                $ccBccNotifications = TblCcBccNotifications::where('company_id', $companyId)->get();
213
214                if (count($ccBccNotifications) > 0) {
215                    $newCcBccNotifications = [];
216                    foreach ($ccBccNotifications as $item) {
217                        $newCcBccNotifications[] = [
218                            'company_id' => $newCompanyId,
219                            'email' => $item->email,
220                            'created_by' => $data['created_by'],
221                        ];
222                    }
223
224                    TblCcBccNotifications::insert((array) $newCcBccNotifications);
225                }
226
227                $ccBccRequestNotifications = TblCcBccRequestNotifications::where('company_id', $companyId)->get();
228
229                if (count($ccBccRequestNotifications) > 0) {
230                    $newCcBccRequestNotifications = [];
231                    foreach ($ccBccRequestNotifications as $item) {
232                        $newCcBccRequestNotifications[] = [
233                            'company_id' => $newCompanyId,
234                            'email' => $item->email,
235                            'created_by' => $data['created_by'],
236                        ];
237                    }
238
239                    TblCcBccRequestNotifications::insert((array) $newCcBccRequestNotifications);
240                }
241
242                $ccG3WEmailReminders = TblCcG3WEmailReminders::where('company_id', $companyId)->get();
243
244                if (count($ccG3WEmailReminders) > 0) {
245                    $newCcG3WEmailReminders = [];
246                    foreach ($ccG3WEmailReminders as $item) {
247                        $newCcG3WEmailReminders[] = [
248                            'company_id' => $newCompanyId,
249                            'email' => $item->email,
250                            'created_by' => $data['created_by'],
251                        ];
252                    }
253
254                    TblCcG3WEmailReminders::insert((array) $newCcG3WEmailReminders);
255                }
256
257                $companyEmails = TblCompanyEmails::where('company_id', $companyId)->get();
258
259                if (count($companyEmails) > 0) {
260                    $newCompanyEmails = [];
261                    foreach ($companyEmails as $item) {
262                        $newCompanyEmails[] = [
263                            'response_id' => $item->response_id,
264                            'company_id' => $newCompanyId,
265                            'nickname' => $item->nickname,
266                            'from_email' => $item->from_email,
267                            'from_name' => $item->from_name,
268                            'reply_to' => $item->reply_to,
269                            'reply_to_name' => $item->reply_to_name,
270                            'address' => $item->address,
271                            'state' => $item->state,
272                            'city' => $item->city,
273                            'country' => $item->country,
274                            'zip' => $item->zip,
275                            'verified' => $item->verified,
276                            'locked' => $item->locked,
277                            'is_active' => $item->is_active,
278                            'created_by' => $data['created_by'],
279                        ];
280                    }
281
282                    TblCompanyEmails::insert((array) $newCompanyEmails);
283                }
284
285                $companyUsers = TblCompanyUsers::where('company_id', $companyId)->get();
286
287                if (count($companyUsers) > 0) {
288                    $newCompanyUsers = [];
289                    foreach ($companyUsers as $item) {
290                        $newCompanyUsers[] = [
291                            'user_id' => $item->user_id,
292                            'company_id' => $newCompanyId,
293                            'can_read' => $item->can_read,
294                            'can_write' => $item->can_write,
295                            'is_selected' => $item->is_selected,
296                            'created_by' => $data['created_by'],
297                        ];
298                    }
299
300                    TblCompanyUsers::insert((array) $newCompanyUsers);
301                }
302
303                $emailConfiguration = TblEmailConfiguration::where('company_id', $companyId)->get();
304
305                if (count($emailConfiguration) > 0) {
306                    $newEmailConfiguration = [];
307                    foreach ($emailConfiguration as $item) {
308                        $newEmailConfiguration[] = [
309                            'company_id' => $newCompanyId,
310                            'from_id' => $item->from_id,
311                            'name' => $item->name,
312                            'subject' => $item->subject,
313                            'html' => $item->html,
314                            'is_active' => $item->is_active,
315                            'type' => $item->type,
316                            'created_by' => $data['created_by'],
317                            'email_template_id_copied' => $item->id,
318                        ];
319                    }
320
321                    TblEmailConfiguration::insert((array) $newEmailConfiguration);
322
323                    $query = "SELECT 
324                                a.id, 
325                                (
326                                    SELECT 
327                                        id 
328                                    FROM 
329                                        tbl_company_emails 
330                                    WHERE 
331                                        from_email = b.from_email 
332                                        AND company_id = {$newCompanyId}
333                                ) from_id 
334                                FROM 
335                                    tbl_email_configuration a 
336                                LEFT JOIN tbl_company_emails b 
337                                    ON a.from_id = b.id 
338                                WHERE 
339                                    a.company_id = {$newCompanyId}";
340
341                    $r = DB::select($query);
342
343                    foreach ($r as $item) {
344                        TblEmailConfiguration::where('id', $item->id)->update(['from_id' => $item->from_id]);
345                    }
346
347                    $query = "INSERT INTO tbl_email_files (
348                                    email_template_id, 
349                                    original_name, 
350                                    filename, 
351                                    uploaded_by, 
352                                    uploaded_at
353                                ) 
354                                SELECT 
355                                    b.id, 
356                                    a.original_name, 
357                                    a.filename, 
358                                    '{$data['created_by']}', 
359                                    NOW() 
360                                FROM 
361                                    tbl_email_files a 
362                                LEFT JOIN tbl_email_configuration b 
363                                    ON a.email_template_id = b.email_template_id_copied 
364                                WHERE 
365                                    b.company_id = {$newCompanyId}";
366
367                    DB::select($query);
368                }
369
370                $projectTypes = TblProjectTypes::where('company_id', $companyId)->get();
371
372                if (count($projectTypes) > 0) {
373                    $newProjectTypes = [];
374                    foreach ($projectTypes as $item) {
375                        $newProjectTypes[] = [
376                            'company_id' => $newCompanyId,
377                            'project_id' => $item->project_id,
378                            'budget_type_id' => $item->budget_type_id,
379                            'customer_type_ids' => $item->customer_type_ids,
380                            'revenue_per_employee_per_day' => $item->revenue_per_employee_per_day,
381                            'minimum_margin' => $item->minimum_margin,
382                            'general_costs' => $item->general_costs,
383                            'minimum_order_size' => $item->minimum_order_size,
384                            'minimum_order_size_v2' => $item->minimum_order_size_v2,
385                            'created_by' => $data['created_by'],
386                        ];
387                    }
388
389                    TblProjectTypes::insert((array) $newProjectTypes);
390                }
391
392                $lastFolloUpDates = TblLastFollowUpDate::where('company_id', $companyId)->get();
393
394                if (count($lastFolloUpDates) > 0) {
395                    $newLastFollowUpDate = [];
396                    foreach ($lastFolloUpDates as $item) {
397                        $newLastFollowUpDate[] = [
398                            'company_id' => $newCompanyId,
399                            'row_id' => $item->row_id,
400                            'budget_type_id' => $item->budget_type_id,
401                            'last_follow_up_date' => $item->last_follow_up_date,
402                            'created_by' => $data['created_by'],
403                        ];
404                    }
405
406                    TblLastFollowUpDate::insert((array) $newLastFollowUpDate);
407                }
408
409                $toAcceptanceNotifications = TblToAcceptanceNotifications::where('company_id', $companyId)->get();
410
411                if (count($toAcceptanceNotifications) > 0) {
412                    $newToAcceptanceNotifications = [];
413                    foreach ($toAcceptanceNotifications as $item) {
414                        $newToAcceptanceNotifications[] = [
415                            'company_id' => $newCompanyId,
416                            'email' => $item->email,
417                            'created_by' => $data['created_by'],
418                        ];
419                    }
420
421                    TblToAcceptanceNotifications::insert((array) $newToAcceptanceNotifications);
422                }
423
424                $workflowApprover = TblWorkflowApprover::where('company_id', $companyId)->get();
425
426                if (count($workflowApprover) > 0) {
427                    $newWorkflowApprover = [];
428                    foreach ($workflowApprover as $item) {
429                        $newWorkflowApprover[] = [
430                            'company_id' => $newCompanyId,
431                            'user_id' => $item->user_id,
432                            'created_by' => $data['created_by'],
433                        ];
434                    }
435
436                    TblWorkflowApprover::insert((array) $newWorkflowApprover);
437                }
438
439                $workflowCustomerTypes = TblWorkflowCustomerTypes::where('company_id', $companyId)->get();
440
441                if (count($workflowCustomerTypes) > 0) {
442                    $newWorkflowCustomerTypes = [];
443                    foreach ($workflowCustomerTypes as $item) {
444                        $newWorkflowCustomerTypes[] = [
445                            'company_id' => $newCompanyId,
446                            'customer_type_id' => $item->customer_type_id,
447                            'created_by' => $data['created_by'],
448                        ];
449                    }
450
451                    TblWorkflowCustomerTypes::insert((array) $newWorkflowCustomerTypes);
452                }
453
454                $workflowProjectTypes = TblWorkflowProjectTypes::where('company_id', $companyId)->get();
455
456                if (count($workflowProjectTypes) > 0) {
457                    $newWorkflowProjectTypes = [];
458                    foreach ($workflowProjectTypes as $item) {
459                        $newWorkflowProjectTypes[] = [
460                            'company_id' => $newCompanyId,
461                            'budget_type_id' => $item->budget_type_id,
462                            'created_by' => $data['created_by'],
463                        ];
464                    }
465
466                    TblWorkflowProjectTypes::insert((array) $newWorkflowProjectTypes);
467                }
468
469                $tradeAlignmentFacility = TblTradeAlignmentSettings::where('company_id', $companyId)->get();
470
471                if (count($tradeAlignmentFacility) > 0) {
472                    $newTradeAlignmentFacility = [];
473                    foreach ($tradeAlignmentFacility as $item) {
474                        $newTradeAlignmentFacility[] = [
475                            'company_id' => $newCompanyId,
476                            'budget_type_id' => $item->budget_type_id,
477                            'minimum_budget_amount' => $item->minimum_budget_amount,
478                            'created_by' => $data['created_by'],
479                        ];
480                    }
481
482                    TblWorkflowProjectTypes::insert((array) $newTradeAlignmentFacility);
483                }
484            } else {
485                $result = TblCompanies::create($data);
486                $newCompanyId = $result->id;
487
488                TblCompanyUsers::create(
489                    [
490                        'company_id' => $newCompanyId,
491                        'user_id' => $userId,
492                        'can_read' => 1,
493                        'can_write' => 1,
494                        'created_by' => $data['created_by'],
495                    ]
496                );
497
498                for ($i = 1; $i < 7; $i++) {
499                    TblProjectTypes::create(
500                        [
501                            'company_id' => $result->id,
502                            'project_id' => $i,
503                            'created_by' => $data['created_by'],
504                        ]
505                    );
506                }
507
508                for ($i = 1; $i < 3; $i++) {
509                    TblLastFollowUpDate::create(
510                        [
511                            'company_id' => $result->id,
512                            'row_id' => $i,
513                            'created_by' => $data['created_by'],
514                        ]
515                    );
516                }
517
518                for ($i = 1; $i < 7; $i++) {
519                    TblTradeAlignmentSettings::create(
520                        [
521                            'company_id' => $result->id,
522                            'minimum_budget_amount' => 0,
523                            'created_by' => $data['created_by'],
524                        ]
525                    );
526                }
527            }
528
529            TblFinalSummary::create(
530                [
531                    'company_id' => $newCompanyId,
532                    'created_by' => $data['created_by'],
533                ]
534            );
535
536            $preLoadedQuestions[1] = '¿Confirma que hemos ofrecido presupuesto de mantenimiento de PCI activo?';
537            $preLoadedQuestions[2] = '¿El pago inicial cubre el coste de materiales y mano de obra?';
538            $preLoadedQuestions[3] = '¿Has solicitado un análisis de riesgo a la administración de Grupo Fire para no correr riesgo de impagos?';
539            $preLoadedQuestions[4] = null;
540            $preLoadedQuestions[5] = null;
541
542            for ($i = 1; $i < 5; $i++) {
543                TblWorkflowQuestions::create(
544                    [
545                        'company_id' => $result->id,
546                        'question' => $preLoadedQuestions[$i],
547                        'created_by' => $data['created_by'],
548                    ]
549                );
550            }
551
552            DB::commit();
553
554            return response(['message' => 'OK', 'data' => $result]);
555
556        } catch (\Exception $e) {
557            /** @disregard P1014 */
558            $e->exceptionCode = 'CREATE_COMPANY_EXCEPTION';
559            report($e);
560
561            return response(['message' => 'KO', 'error' => $e->getMessage()]);
562        }
563    }
564
565    public function list_companies()
566    {
567
568        try {
569
570            $query = "SELECT 
571                        company_id,
572                        name,
573                        fiscal_id,
574                        address,
575                        logo,
576                        filetype,
577                        DATE_FORMAT(created_at, '%b %d, %Y %l:%i%p') 'created_at',
578                        created_by,
579                        DATE_FORMAT(updated_at, '%b %d, %Y %l:%i%p') 'updated_at',
580                        updated_by,
581                        region,
582                        is_send_executive
583                    FROM tbl_companies
584                    ORDER BY region ASC";
585
586            $result = DB::select($query);
587
588            return response(['message' => 'OK', 'data' => $result]);
589
590        } catch (\Exception $e) {
591            /** @disregard P1014 */
592            $e->exceptionCode = 'LIST_COMPANIES_EXCEPTION';
593            report($e);
594
595            return response(['message' => 'KO', 'error' => $e->getMessage()]);
596        }
597    }
598
599    public function get_company($companyId)
600    {
601
602        try {
603
604            $companyId = intval($companyId);
605
606            $query = "SELECT 
607                        company_id,
608                        name,
609                        fiscal_id,
610                        address,
611                        logo,
612                        filetype,
613                        filename,
614                        filesize,
615                        filetype,
616                        default_page,
617                        is_send,
618                        limit_send,
619                        is_send_follow_up,
620                        is_send_request,
621                        is_send_g3w,
622                        revenue_per_employee_per_day,
623                        minimum_margin,
624                        general_costs,
625                        hours_per_worker_per_day,
626                        cost_of_hour,
627                        hours_per_worker_per_day_percentage,
628                        convert_to_job_amount_limit,
629                        minimum_order_size,
630                        minimum_order_size_v2,
631                        last_follow_up_date,
632                        limit_reminder_emails,
633                        workflow_budget_size,
634                        is_send_executive,
635                        customer_type_ids,
636                        goal_for_the_year,
637                        process_limit,
638                        last_id,
639                        region,
640                        created_at,
641                        created_by,
642                        updated_at,
643                        updated_by,
644                        kpi_filters
645                    FROM tbl_companies
646                    WHERE company_id = {$companyId}
647                    ORDER BY created_at DESC";
648
649            $result = DB::select($query);
650
651            if ($result[0]->customer_type_ids != null) {
652                $result[0]->customer_type_ids = array_map('intval', explode(',', $result[0]->customer_type_ids));
653            }
654
655            return response(['message' => 'OK', 'data' => $result]);
656
657        } catch (\Exception $e) {
658            /** @disregard P1014 */
659            $e->exceptionCode = 'GET_COMPANY_EXCEPTION';
660            report($e);
661
662            return response(['message' => 'KO', 'error' => $e->getMessage()]);
663        }
664    }
665
666    public function get_company_users($companyId)
667    {
668
669        try {
670
671            $companyId = intval($companyId);
672
673            $where = '';
674            if ($companyId != 0) {
675                $where = " a.company_id = {$companyId} ";
676            } else {
677                $where = " a.company_id IN ({$this->companyId}";
678            }
679
680            $query = "SELECT
681                        a.id,
682                        a.user_id,
683                        a.company_id,
684                        b.name,
685                        b.email,    
686                        a.can_read,
687                        a.can_write,
688                        b.role_id,
689                        b.is_commercial
690                    FROM tbl_company_users a
691                    LEFT JOIN tbl_users b
692                        ON a.user_id = b.id
693                    WHERE {$where}
694                    GROUP BY a.user_id
695                    ORDER BY b.name ASC";
696
697            $result = DB::select($query);
698
699            return response(['message' => 'OK', 'data' => $result]);
700
701        } catch (\Exception $e) {
702            /** @disregard P1014 */
703            $e->exceptionCode = 'GET_COMPANY_USERS_EXCEPTION';
704            report($e);
705
706            return response(['message' => 'KO', 'error' => $e->getMessage()]);
707        }
708    }
709
710    public function get_user_companies($userId, $region = null)
711    {
712
713        try {
714
715            $userId = intval($userId);
716
717            $where = '';
718
719            if ($region != null && $region != 'All') {
720                $region = urldecode($region);
721                $where = " AND b.region = '{$region}";
722            }
723
724            $query = "SELECT 
725                        a.id,
726                        b.name, 
727                        b.logo, 
728                        b.filename,
729                        b.company_id,
730                        b.region,
731                        a.can_write,
732                        a.can_read,
733                        b.limit_send
734                    FROM 
735                        tbl_company_users a 
736                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
737                    WHERE 
738                        a.user_id = {$userId}
739                    {$where}
740                    ORDER BY b.region ASC";
741
742            $result = DB::select($query);
743
744            if ($result) {
745                array_unshift(
746                    $result,
747                    [
748                        'id' => 0,
749                        'name' => 'All',
750                        'logo' => null,
751                        'company_id' => 0,
752                    ]
753                );
754            }
755
756            $query = "SELECT 
757                        DISTINCT
758                        b.region
759                    FROM 
760                        tbl_company_users a 
761                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
762                    WHERE 
763                        a.user_id = {$userId}
764                        AND b.region IS NOT NULL
765                    ORDER BY b.region ASC";
766
767            $regions = DB::select($query);
768
769            if ($regions) {
770                array_unshift(
771                    $regions,
772                    [
773                        'region' => 'All',
774                    ]
775                );
776            }
777
778            $query = 'SELECT updated_at FROM tbl_quotations ORDER BY updated_at DESC LIMIT 1';
779            $latedDate = DB::select($query);
780
781            return response([
782                'message' => 'OK',
783                'data' => $result,
784                'regions' => $regions,
785                'latestUpdatedDate' => strtotime($latedDate[0]->updated_at) * 1000,
786            ]);
787
788        } catch (\Exception $e) {
789            /** @disregard P1014 */
790            $e->exceptionCode = 'GET_USER_COMPANIES_EXCEPTION';
791            report($e);
792
793            return response(['message' => 'KO', 'error' => $e->getMessage()]);
794        }
795    }
796
797    public function update_company_users(Request $request)
798    {
799
800        try {
801
802            $data = $request->all();
803            $companyId = $data['company_id'];
804            $userId = $data['user_id'];
805
806            unset($data['company_id']);
807            unset($data['user_id']);
808
809            $result = [];
810
811            $result = TblCompanyUsers::where('company_id', $companyId)->where('user_id', $userId)->update($data);
812
813            return response(['message' => 'OK', 'data' => $result]);
814
815        } catch (\Exception $e) {
816            /** @disregard P1014 */
817            $e->exceptionCode = 'UPDATE_COMPANY_USERS_EXCEPTION';
818            report($e);
819
820            return response(['message' => 'KO', 'error' => $e->getMessage()]);
821        }
822
823    }
824
825    public function update_company_selected(Request $request)
826    {
827
828        try {
829
830            $data = $request->all();
831            $userId = $data['user_id'];
832            $id = $data['id'];
833
834            unset($data['user_id']);
835            unset($data['id']);
836
837            TblCompanyUsers::where('user_id', $userId)->update(['is_selected' => 0]);
838            $result = TblCompanyUsers::where('id', $id)->update(['is_selected' => 1]);
839
840            return response(['message' => 'OK', 'data' => $result]);
841
842        } catch (\Exception $e) {
843            /** @disregard P1014 */
844            $e->exceptionCode = 'UPDATE_COMPANY_SELECTED_EXCEPTION';
845            report($e);
846
847            return response(['message' => 'KO', 'error' => $e->getMessage()]);
848        }
849
850    }
851
852    public function delete_company_users(Request $request)
853    {
854
855        try {
856
857            $data = $request->all();
858
859            $id = intval($data['user_id']);
860
861            $user = TblUsers::where('id', $id)->first();
862
863            $count = TblQuotations::where('company_id', $data['company_id'])->where('commercial', $user->name)->count();
864            $countQ = TblOngoingJobs::where('company_id', $data['company_id'])->where('responsible_for_work', $user->name)->count();
865
866            if ($count > 0 || $countQ > 0) {
867                $urlOrder = env('URL')."orders?commercial={$user->name}&company_id=0";
868                $urlJob = env('URL')."ongoing-jobs?responsible_for_work={$user->name}&company_id=0";
869                $urlOrder = "<a href='{$urlOrder}' target='_blank'>{$count}</a>";
870                $urlJob = "<a href='{$urlJob}' target='_blank'>{$countQ}</a>";
871
872                return response(['message' => 'user_cannot_be_deleted', 'error' => __('language.user_cannot_be_deleted'), 'total_job' => $urlJob, 'total_order' => $urlOrder]);
873            }
874
875            $result = TblCompanyUsers::where('user_id', $id)->where('company_id', $data['company_id'])->delete();
876
877            return response(['message' => 'OK', 'data' => $result]);
878
879        } catch (\Exception $e) {
880            /** @disregard P1014 */
881            $e->exceptionCode = 'DELETE_COMPANY_USERS_EXCEPTION';
882            report($e);
883
884            return response(['message' => 'KO', 'error' => $e->getMessage()]);
885        }
886
887    }
888
889    public function update_company(Request $request, $companyId)
890    {
891
892        try {
893
894            $data = $request->all();
895            $companyId = intval($companyId);
896
897            if (@$data['file'] == '') {
898                unset($data['file']);
899            }
900
901            if (isset($data['customer_type_ids'])) {
902                $data['customer_type_ids'] = implode(',', $data['customer_type_ids']);
903            }
904
905            if (isset($data['last_id'])) {
906                $data['before_last_id'] = $data['last_id'];
907            }
908
909            $data['updated_at'] = date('Y-m-d H:i:s');
910
911            $result = TblCompanies::where('company_id', $companyId)->update($data);
912
913            return response(['message' => 'OK', 'data' => $result]);
914
915        } catch (\Exception $e) {
916            /** @disregard P1014 */
917            $e->exceptionCode = 'UPDATE_COMPANY_EXCEPTION';
918            report($e);
919
920            return response(['message' => 'KO', 'error' => $e->getMessage()]);
921        }
922    }
923
924    public function update_company_blocked(Request $request)
925    {
926
927        try {
928
929            $data = $request->all();
930
931            TblCompanies::query()->update(['is_send_executive' => null]);
932            TblCompanies::whereIn('company_id', $data['company_ids'])->update(['is_send_executive' => 1, 'updated_at' => date('Y-m-d H:i:s')]);
933
934            return response(['message' => 'OK']);
935
936        } catch (\Exception $e) {
937            /** @disregard P1014 */
938            $e->exceptionCode = 'UPDATE_COMPANY_BLOCKED_EXCEPTION';
939            report($e);
940
941            return response(['message' => 'KO', 'error' => $e->getMessage()]);
942        }
943    }
944
945    public function upload_file(Request $request)
946    {
947
948        try {
949
950            $data = $request->all();
951            $companyId = $data['company_id'];
952
953            $data['updated_at'] = date('Y-m-d H:i:s');
954
955            if ($request->file('file')) {
956                $file = $request->file('file');
957
958                $mimetype = $file->getMimeType();
959
960                if (strpos($mimetype, 'image') === false) {
961                    return response(['message' => 'invalid_file_type', 'error' => __('language.invalid_file_type')]);
962                }
963
964                $filename = $file->getClientOriginalName();
965                $filesize = $file->getSize();
966
967                if ($filesize > 5000000) {
968                    return response(['message' => 'limit_exceeded', 'error' => __('language.limit_exceeded')]);
969                }
970
971                $path = $file->getRealPath();
972
973                $logo = file_get_contents($path);
974                $base64 = base64_encode($logo);
975
976                $blob = 'data:'.$mimetype.';base64,'.$base64;
977
978                $data['logo'] = $blob;
979                $data['filename'] = $filename;
980                $data['filesize'] = $filesize;
981                $data['filetype'] = $mimetype;
982
983                unset($data['file']);
984            }
985
986            $result = TblCompanies::where('company_id', $companyId)->update($data);
987
988            return response(['message' => 'OK', 'data' => $result]);
989
990        } catch (\Exception $e) {
991            /** @disregard P1014 */
992            $e->exceptionCode = 'UPLOAD_FILE_EXCEPTION';
993            report($e);
994
995            return response(['message' => 'KO', 'error' => $e->getMessage()]);
996        }
997    }
998
999    public function delete_company($companyId)
1000    {
1001
1002        try {
1003
1004            $companyId = intval($companyId);
1005
1006            $count = TblCompanyUsers::where('company_id', $companyId)->count();
1007
1008            if ($count > 0) {
1009                return response(['message' => 'cannot_be_deleted', 'error' => __('language.cannot_be_deleted')]);
1010            }
1011
1012            $result = TblCompanies::where('company_id', $companyId)->delete();
1013            TblEmailConfiguration::where('company_id', $companyId)->delete();
1014
1015            $query = "DELETE FROM tbl_files WHERE quotation_id IN (SELECT id FROM tbl_quotations WHERE company_id = {$companyId})";
1016            DB::select($query);
1017
1018            TblQuotations::where('company_id', $companyId)->delete();
1019            TblProjectTypes::where('company_id', $companyId)->delete();
1020
1021            return response(['message' => 'OK', 'data' => $result]);
1022
1023        } catch (\Exception $e) {
1024            /** @disregard P1014 */
1025            $e->exceptionCode = 'DELETE_COMPANY_EXCEPTION';
1026            report($e);
1027
1028            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1029        }
1030    }
1031
1032    public function update_company_users_selected(Request $request)
1033    {
1034
1035        try {
1036
1037            $request->all();
1038            $data = $request->all();
1039            $companyId = $data['company_id'];
1040
1041            TblCompanyUsers::where('company_id', $companyId)->update(['is_selected' => null]);
1042            for ($i = 0; $i < count($data['user_ids']); $i++) {
1043                TblCompanyUsers::where('company_id', $companyId)->where('user_id', $data['user_ids'][$i])->update(['is_selected' => 1]);
1044            }
1045
1046            return response(['message' => 'OK']);
1047
1048        } catch (\Exception $e) {
1049            /** @disregard P1014 */
1050            $e->exceptionCode = 'UPDATE_COMPANY_USERS_SELECTED_EXCEPTION';
1051            report($e);
1052
1053            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1054        }
1055    }
1056
1057    public function create_company_users(Request $request)
1058    {
1059
1060        try {
1061
1062            $request->all();
1063            $data = $request->all();
1064            $companyId = $data['company_id'];
1065
1066            if ($data['user_ids']) {
1067                $userIds = implode(',', $data['user_ids']);
1068
1069                $query = "DELETE FROM tbl_company_users WHERE user_id NOT IN ({$userIds}) AND company_id = {$companyId}";
1070                DB::select($query);
1071
1072                $companyUsers = [];
1073
1074                $query = "SELECT user_id FROM tbl_company_users WHERE company_id = {$companyId} AND user_id IN ({$userIds})";
1075                $result = DB::select($query);
1076
1077                $ids = [];
1078
1079                for ($i = 0; $i < count($result); $i++) {
1080                    array_push($ids, $result[$i]->user_id);
1081                }
1082
1083                for ($i = 0; $i < count($data['user_ids']); $i++) {
1084                    if (! in_array($data['user_ids'][$i], $ids)) {
1085                        array_push(
1086                            $companyUsers,
1087                            [
1088                                'user_id' => $data['user_ids'][$i],
1089                                'company_id' => $companyId,
1090                                'can_read' => 1,
1091                                'can_write' => 0,
1092                                'created_by' => $data['created_by'],
1093                            ]
1094                        );
1095                    }
1096                }
1097
1098                TblCompanyUsers::insert($companyUsers);
1099            } else {
1100                TblCompanyUsers::where('company_id', $companyId)->delete();
1101            }
1102
1103            return response(['message' => 'OK']);
1104
1105        } catch (\Exception $e) {
1106            /** @disregard P1014 */
1107            $e->exceptionCode = 'CREATE_COMPANY_USERS_EXCEPTION';
1108            report($e);
1109
1110            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1111        }
1112    }
1113
1114    public function get_cc_bcc($id)
1115    {
1116
1117        try {
1118
1119            $companyId = intval($id);
1120
1121            $result = TblCcBcc::where('company_id', $companyId)->get();
1122
1123            return response(['message' => 'OK', 'data' => $result]);
1124
1125        } catch (\Exception $e) {
1126            /** @disregard P1014 */
1127            $e->exceptionCode = 'GET_CC_BCC_EXCEPTION';
1128            report($e);
1129
1130            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1131        }
1132    }
1133
1134    public function delete_cc_bcc($id)
1135    {
1136
1137        try {
1138
1139            $id = intval($id);
1140
1141            TblCcBcc::where('id', $id)->delete();
1142
1143            return response(['message' => 'OK']);
1144
1145        } catch (\Exception $e) {
1146            /** @disregard P1014 */
1147            $e->exceptionCode = 'DELETE_CC_BCC_EXCEPTION';
1148            report($e);
1149
1150            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1151        }
1152    }
1153
1154    public function update_cc_bcc(Request $request, $id)
1155    {
1156
1157        try {
1158
1159            $data = $request->all();
1160            $id = intval($id);
1161
1162            $x = $this->isEmailValid($data['email']);
1163
1164            if ($x) {
1165                $result = TblCcBcc::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1166
1167                if ($result > 0) {
1168                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1169                } else {
1170                    $data['updated_at'] = date('Y-m-d H:i:s');
1171                    TblCcBcc::where('id', $id)->update($data);
1172                }
1173            } else {
1174                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1175            }
1176
1177            return response(['message' => 'OK']);
1178
1179        } catch (\Exception $e) {
1180            /** @disregard P1014 */
1181            $e->exceptionCode = 'UPDATE_CC_BCC_EXCEPTION';
1182            report($e);
1183
1184            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1185        }
1186    }
1187
1188    public function create_cc_bcc(Request $request)
1189    {
1190
1191        try {
1192
1193            $data = $request->all();
1194
1195            $x = $this->isEmailValid($data['email']);
1196
1197            if ($x) {
1198                $result = TblCcBcc::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1199
1200                if ($result > 0) {
1201                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1202                } else {
1203                    TblCcBcc::create($data);
1204                }
1205            } else {
1206                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1207            }
1208
1209            return response(['message' => 'OK']);
1210
1211        } catch (\Exception $e) {
1212            /** @disregard P1014 */
1213            $e->exceptionCode = 'CREATE_CC_BCC_EXCEPTION';
1214            report($e);
1215
1216            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1217        }
1218    }
1219
1220    public function isEmailValid($email)
1221    {
1222        // Regular expression pattern for email validation
1223        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
1224
1225        // Check if the email matches the pattern
1226        if (preg_match($pattern, $email)) {
1227            return true; // Valid email
1228        } else {
1229            return false; // Invalid email
1230        }
1231    }
1232
1233    public function get_blocked_domains($id)
1234    {
1235
1236        try {
1237
1238            $companyId = intval($id);
1239
1240            $result = [];
1241
1242            if ($companyId != 0) {
1243                $result = TblBlockedDomains::where('company_id', $companyId)->get();
1244            } else {
1245                $result = TblBlockedDomains::whereIn('company_id', $this->companyIds)->get();
1246            }
1247
1248            return response(['message' => 'OK', 'data' => $result]);
1249
1250        } catch (\Exception $e) {
1251            /** @disregard P1014 */
1252            $e->exceptionCode = 'GET_BLOCKED_DOMAINS_EXCEPTION';
1253            report($e);
1254
1255            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1256        }
1257    }
1258
1259    public function delete_blocked_domain($id)
1260    {
1261
1262        try {
1263
1264            $id = intval($id);
1265
1266            TblBlockedDomains::where('id', $id)->delete();
1267
1268            Cache::flush();
1269
1270            return response(['message' => 'OK']);
1271
1272        } catch (\Exception $e) {
1273            /** @disregard P1014 */
1274            $e->exceptionCode = 'DELETE_BLOCKED_DOMAIN_EXCEPTION';
1275            report($e);
1276
1277            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1278        }
1279    }
1280
1281    public function update_blocked_domain(Request $request, $id)
1282    {
1283
1284        try {
1285
1286            $data = $request->all();
1287            $id = intval($id);
1288
1289            $result = TblBlockedDomains::where('company_id', $data['company_id'])->where('domain', strtolower($data['domain']))->count();
1290
1291            if ($result > 0) {
1292                return response(['message' => 'KO', 'error' => __('language.domain_exists')]);
1293            } else {
1294                $data['updated_at'] = date('Y-m-d H:i:s');
1295                TblBlockedDomains::where('id', $id)->update($data);
1296            }
1297
1298            Cache::flush();
1299
1300            return response(['message' => 'OK']);
1301
1302        } catch (\Exception $e) {
1303            /** @disregard P1014 */
1304            $e->exceptionCode = 'UPDATE_BLOCKED_DOMAIN_EXCEPTION';
1305            report($e);
1306
1307            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1308        }
1309    }
1310
1311    public function create_blocked_domain(Request $request)
1312    {
1313
1314        try {
1315
1316            $data = $request->all();
1317
1318            $result = TblBlockedDomains::where('company_id', $data['company_id'])->where('domain', strtolower($data['domain']))->count();
1319
1320            if ($result > 0) {
1321                return response(['message' => 'KO', 'error' => __('language.domain_exists')]);
1322            } else {
1323                TblBlockedDomains::create($data);
1324            }
1325
1326            Cache::flush();
1327
1328            return response(['message' => 'OK']);
1329
1330        } catch (\Exception $e) {
1331            /** @disregard P1014 */
1332            $e->exceptionCode = 'CREATE_BLOCKED_DOMAIN_EXCEPTION';
1333            report($e);
1334
1335            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1336        }
1337    }
1338
1339    public function list_project_types($companyId)
1340    {
1341
1342        try {
1343
1344            $companyId = intval($companyId);
1345
1346            $result = TblProjectTypes::where('company_id', $companyId)->orderBy('project_id', 'ASC')->get();
1347
1348            $data = [];
1349
1350            for ($i = 0; $i < count($result); $i++) {
1351                $data[$result[$i]->project_id]['project_id'] = $result[$i]->project_id;
1352                if ($result[$i]->budget_type_id != null) {
1353                    $data[$result[$i]->project_id]['budget_types'][] = $result[$i]->budget_type_id;
1354                }
1355                if ($result[$i]->customer_type_ids != null) {
1356                    $data[$result[$i]->project_id]['customer_types'] = array_map('intval', explode(',', $result[$i]->customer_type_ids));
1357                }
1358                $data[$result[$i]->project_id]['benchmarks'] = [
1359                    'revenue_per_employee_per_day' => $result[$i]->revenue_per_employee_per_day,
1360                    'minimum_margin' => $result[$i]->minimum_margin,
1361                    'general_costs' => $result[$i]->general_costs,
1362                    'minimum_order_size' => $result[$i]->minimum_order_size,
1363                    'minimum_order_size_v2' => $result[$i]->minimum_order_size_v2,
1364                ];
1365            }
1366
1367            return response(['message' => 'OK', 'data' => array_values($data)]);
1368
1369        } catch (\Exception $e) {
1370            /** @disregard P1014 */
1371            $e->exceptionCode = 'LIST_PROJECT_TYPES_EXCEPTION';
1372            report($e);
1373
1374            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1375        }
1376
1377    }
1378
1379    public function get_project_types($companyId)
1380    {
1381
1382        try {
1383
1384            $companyId = intval($companyId);
1385
1386            $result = TblProjectTypes::where('company_id', $companyId)->where('budget_type_id', '!=', null)->get();
1387
1388            $query = "
1389                SELECT a.approver_id, u.name AS approver, 'v1' as type
1390                FROM tbl_approvers a
1391                LEFT JOIN tbl_users u ON a.user_id = u.id
1392                WHERE a.company_id = {$companyId}
1393
1394                UNION ALL
1395
1396                SELECT a.approver_id, u.name AS approver, 'v2' as type
1397                FROM tbl_approvers_v2 a
1398                LEFT JOIN tbl_users u ON a.user_id = u.id
1399                WHERE a.company_id = {$companyId}
1400            ";
1401
1402            $approvers = DB::select($query);
1403
1404            $ids = [];
1405            $names = [];
1406
1407            foreach ($approvers as $item) {
1408                $ids[] = $item->approver_id;
1409                $names[] = $item->approver;
1410            }
1411
1412            return response([
1413                'message' => 'OK',
1414                'data' => $result,
1415                'approversData' => $approvers,
1416                'approvers' => $ids,
1417                'approverNames' => $names,
1418            ]);
1419
1420        } catch (\Exception $e) {
1421            /** @disregard P1014 */
1422            $e->exceptionCode = 'GET_PROJECT_TYPES_EXCEPTION';
1423            report($e);
1424
1425            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1426        }
1427    }
1428
1429    public function update_project_types(Request $request)
1430    {
1431
1432        try {
1433
1434            $data = $request->all();
1435            $companyId = intval($data['company_id']);
1436            $projectId = intval($data['project_id']);
1437            unset($data['company_id']);
1438            unset($data['project_id']);
1439
1440            $previousData = TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->first();
1441
1442            $lastBudgetTypeId = end($data['budget_type_id']);
1443            $project = TblProjectTypes::where('company_id', $companyId)->where('budget_type_id', $lastBudgetTypeId)->first();
1444
1445            TblProjectTypes::where('company_id', $companyId)->whereIn('budget_type_id', $data['budget_type_id'])->delete();
1446            TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->delete();
1447
1448            foreach ($data['budget_type_id'] as $budgetTypeId) {
1449                TblProjectTypes::create(
1450                    [
1451                        'company_id' => $companyId,
1452                        'project_id' => $projectId,
1453                        'customer_type_ids' => $previousData->customer_type_ids,
1454                        'budget_type_id' => $budgetTypeId,
1455                        'revenue_per_employee_per_day' => $previousData->revenue_per_employee_per_day,
1456                        'minimum_margin' => $previousData->minimum_margin,
1457                        'general_costs' => $previousData->general_costs,
1458                        'minimum_order_size' => $previousData->minimum_order_size,
1459                        'minimum_order_size_v2' => $previousData->minimum_order_size_v2,
1460                        'created_by' => $data['created_by'],
1461                    ]
1462                );
1463            }
1464
1465            if ($project != null) {
1466                if ($project->budget_type_id != null) {
1467                    TblProjectTypes::create(
1468                        [
1469                            'company_id' => $companyId,
1470                            'project_id' => $project->project_id,
1471                            'budget_type_id' => null,
1472                            'customer_type_ids' => $project->customer_type_ids,
1473                            'revenue_per_employee_per_day' => $project->revenue_per_employee_per_day,
1474                            'minimum_margin' => $project->minimum_margin,
1475                            'general_costs' => $project->general_costs,
1476                            'minimum_order_size' => $project->minimum_order_size,
1477                            'minimum_order_size_v2' => $project->minimum_order_size_v2,
1478                            'created_by' => $data['created_by'],
1479                        ]
1480                    );
1481                }
1482            }
1483
1484            return $this->list_project_types($companyId);
1485
1486        } catch (\Exception $e) {
1487            /** @disregard P1014 */
1488            $e->exceptionCode = 'CREATE_PROJECT_TYPES_EXCEPTION';
1489            report($e);
1490
1491            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1492        }
1493
1494    }
1495
1496    public function update_project_types_benchmarks(Request $request)
1497    {
1498
1499        try {
1500
1501            $data = $request->all();
1502            $companyId = intval($data['company_id']);
1503            $projectId = intval($data['project_id']);
1504
1505            unset($data['company_id']);
1506            unset($data['project_id']);
1507
1508            if (isset($data['customer_type_ids'])) {
1509                $data['customer_type_ids'] = implode(',', $data['customer_type_ids']);
1510            }
1511
1512            TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->update($data);
1513
1514            return $this->list_project_types($companyId);
1515
1516        } catch (\Exception $e) {
1517            /** @disregard P1014 */
1518            $e->exceptionCode = 'UPDATE_PROJECT_TYPES_BENCHMARKS_EXCEPTION';
1519            report($e);
1520
1521            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1522        }
1523
1524    }
1525
1526    public function delete_project_types(Request $request)
1527    {
1528
1529        try {
1530
1531            $data = $request->all();
1532            $companyId = intval($data['company_id']);
1533            $projectId = intval($data['project_id']);
1534            unset($data['company_id']);
1535            unset($data['project_id']);
1536
1537            $count = TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->count();
1538
1539            if ($count > 1) {
1540                TblProjectTypes::where('company_id', $companyId)->where('budget_type_id', $data['budget_type_id'])->delete();
1541            } else {
1542                TblProjectTypes::where('company_id', $companyId)->where('project_id', $projectId)->update(['budget_type_id' => null]);
1543            }
1544
1545            return $this->list_project_types($companyId);
1546
1547        } catch (\Exception $e) {
1548            /** @disregard P1014 */
1549            $e->exceptionCode = 'DELETE_PROJECT_TYPES_EXCEPTION';
1550            report($e);
1551
1552            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1553        }
1554
1555    }
1556
1557    public function list_workflow_project_types($companyId)
1558    {
1559
1560        try {
1561
1562            $companyId = intval($companyId);
1563
1564            $result = TblWorkflowProjectTypes::where('company_id', $companyId)->get();
1565
1566            return response(['message' => 'OK', 'data' => $result]);
1567
1568        } catch (\Exception $e) {
1569            /** @disregard P1014 */
1570            $e->exceptionCode = 'LIST_WORKFLOW_PROJECT_TYPES_EXCEPTION';
1571            report($e);
1572
1573            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1574        }
1575
1576    }
1577
1578    public function update_workflow_project_types(Request $request)
1579    {
1580
1581        try {
1582
1583            $data = $request->all();
1584
1585            TblWorkflowProjectTypes::where('company_id', $data['company_id'])->delete();
1586
1587            for ($i = 0; $i < count($data['budget_type_id']); $i++) {
1588                TblWorkflowProjectTypes::create(
1589                    [
1590                        'company_id' => $data['company_id'],
1591                        'budget_type_id' => $data['budget_type_id'][$i],
1592                        'created_by' => $data['created_by'],
1593                    ]
1594                );
1595            }
1596
1597            return $this->list_workflow_project_types($data['company_id']);
1598
1599        } catch (\Exception $e) {
1600            /** @disregard P1014 */
1601            $e->exceptionCode = 'UPDATE_WORKFLOW_PROJECT_TYPES_EXCEPTION';
1602            report($e);
1603
1604            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1605        }
1606
1607    }
1608
1609    public function delete_workflow_project_types(Request $request)
1610    {
1611
1612        try {
1613
1614            $data = $request->all();
1615
1616            $companyId = intval($data['company_id']);
1617            $budgetTypeId = intval($data['budget_type_id']);
1618
1619            TblWorkflowProjectTypes::where('budget_type_id', $budgetTypeId)->where('company_id', $companyId)->delete();
1620
1621            return $this->list_workflow_project_types($companyId);
1622
1623        } catch (\Exception $e) {
1624            /** @disregard P1014 */
1625            $e->exceptionCode = 'DELETE_WORKFLOW_PROJECT_TYPES_EXCEPTION';
1626            report($e);
1627
1628            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1629        }
1630
1631    }
1632
1633    public function list_workflow_customer_types($companyId)
1634    {
1635
1636        try {
1637
1638            $companyId = intval($companyId);
1639
1640            $result = TblWorkflowCustomerTypes::where('company_id', $companyId)->get();
1641
1642            return response(['message' => 'OK', 'data' => $result]);
1643
1644        } catch (\Exception $e) {
1645            /** @disregard P1014 */
1646            $e->exceptionCode = 'LIST_WORKFLOW_CUSTOMER_TYPES_EXCEPTION';
1647            report($e);
1648
1649            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1650        }
1651
1652    }
1653
1654    public function update_workflow_customer_types(Request $request)
1655    {
1656
1657        try {
1658
1659            $data = $request->all();
1660
1661            TblWorkflowCustomerTypes::where('company_id', $data['company_id'])->delete();
1662
1663            for ($i = 0; $i < count($data['customer_type_id']); $i++) {
1664                TblWorkflowCustomerTypes::create(
1665                    [
1666                        'company_id' => $data['company_id'],
1667                        'customer_type_id' => $data['customer_type_id'][$i],
1668                        'created_by' => $data['created_by'],
1669                    ]
1670                );
1671            }
1672
1673            return $this->list_workflow_project_types($data['company_id']);
1674
1675        } catch (\Exception $e) {
1676            /** @disregard P1014 */
1677            $e->exceptionCode = 'UPDATE_WORKFLOW_CUSTOMER_TYPES_EXCEPTION';
1678            report($e);
1679
1680            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1681        }
1682
1683    }
1684
1685    public function delete_workflow_customer_types(Request $request)
1686    {
1687
1688        try {
1689
1690            $data = $request->all();
1691
1692            $companyId = intval($data['company_id']);
1693            $customerTypeId = intval($data['customer_type_id']);
1694
1695            TblWorkflowCustomerTypes::where('customer_type_id', $customerTypeId)->where('company_id', $companyId)->delete();
1696
1697            return $this->list_workflow_customer_types($companyId);
1698
1699        } catch (\Exception $e) {
1700            /** @disregard P1014 */
1701            $e->exceptionCode = 'DELETE_WORKFLOW_CUSTOMER_TYPES_EXCEPTION';
1702            report($e);
1703
1704            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1705        }
1706
1707    }
1708
1709    public function list_workflow_questions($companyId)
1710    {
1711
1712        try {
1713
1714            $companyId = intval($companyId);
1715
1716            $result = TblWorkflowQuestions::where('company_id', $companyId)->get();
1717
1718            return response(['message' => 'OK', 'data' => $result]);
1719
1720        } catch (\Exception $e) {
1721            /** @disregard P1014 */
1722            $e->exceptionCode = 'LIST_WORKFLOW_QUESTIONS_EXCEPTION';
1723            report($e);
1724
1725            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1726        }
1727
1728    }
1729
1730    public function update_workflow_questions(Request $request, $questionId)
1731    {
1732
1733        try {
1734
1735            $data = $request->all();
1736            $questionId = intval($questionId);
1737            $companyId = intval($data['company_id']);
1738            unset($data['company_id']);
1739
1740            $data['updated_at'] = date('Y-m-d H:i:s');
1741            TblWorkflowQuestions::where('question_id', $questionId)->update($data);
1742
1743            return $this->list_workflow_questions($companyId);
1744
1745        } catch (\Exception $e) {
1746            /** @disregard P1014 */
1747            $e->exceptionCode = 'UPDATE_WORKFLOW_QUESTIONS_EXCEPTION';
1748            report($e);
1749
1750            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1751        }
1752
1753    }
1754
1755    public function get_company_executive()
1756    {
1757
1758        try {
1759
1760            $result = TblCompanies::where('is_send_executive', 1)->get();
1761
1762            return response(['message' => 'OK', 'data' => $result]);
1763
1764        } catch (\Exception $e) {
1765            /** @disregard P1014 */
1766            $e->exceptionCode = 'GET_COMPANY_EXECUTIVE_EXCEPTION';
1767            report($e);
1768
1769            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1770        }
1771
1772    }
1773
1774    public function get_all_details($companyId)
1775    {
1776
1777        try {
1778
1779            $companyId = intval($companyId);
1780
1781            $getCompany = $this->get_company($companyId);
1782            $listWorkflowQuestions = $this->list_workflow_questions($companyId);
1783            $listWorkflowCustomerTypes = $this->list_workflow_customer_types($companyId);
1784            $listWorkflowProjectTypes = $this->list_workflow_project_types($companyId);
1785            $getProjectTypes = $this->get_project_types($companyId);
1786            $getCompanyUsers = $this->get_company_users($companyId);
1787            $getBlockedDomains = TblBlockedDomains::where('company_id', $companyId)->get();
1788
1789            return response([
1790                'message' => 'OK',
1791                'getCompany' => $getCompany->original['data'],
1792                'approvers' => $getProjectTypes->original['approvers'],
1793                'approverNames' => $getProjectTypes->original['approverNames'],
1794                'listWorkflowQuestions' => $listWorkflowQuestions->original['data'],
1795                'listWorkflowCustomerTypes' => $listWorkflowCustomerTypes->original['data'],
1796                'listWorkflowProjectTypes' => $listWorkflowProjectTypes->original['data'],
1797                'getProjectTypes' => $getProjectTypes->original['data'],
1798                'getBlockedDomains' => $getBlockedDomains,
1799                'getCompanyUsers' => $getCompanyUsers->original['data'],
1800            ]);
1801
1802        } catch (\Exception $e) {
1803            /** @disregard P1014 */
1804            $e->exceptionCode = 'GET_ALL_DETAILS_EXCEPTION';
1805            report($e);
1806
1807            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1808        }
1809    }
1810
1811    public function list_all_companies()
1812    {
1813
1814        try {
1815
1816            $result = TblCompanies::whereIn('company_id', $this->companyIds)->get();
1817
1818            return response([
1819                'message' => 'OK',
1820                'data' => $result,
1821            ]);
1822
1823        } catch (\Exception $e) {
1824            /** @disregard P1014 */
1825            $e->exceptionCode = 'LIST_ALL_COMPANIES_EXCEPTION';
1826            report($e);
1827
1828            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1829        }
1830
1831    }
1832
1833    public function update_company_permission(Request $request, $userId)
1834    {
1835
1836        try {
1837
1838            $data = $request->all();
1839            $userId = intval($userId);
1840
1841            if (isset($data['read_only'])) {
1842                if ($data['read_only'] == false) {
1843                    TblCompanyUsers::where('user_id', $userId)->update(
1844                        [
1845                            'can_read' => 1,
1846                            'can_write' => 0,
1847                            'updated_at' => date('Y-m-d H:i:s'),
1848                            'updated_by' => $data['updated_by'],
1849                        ]
1850                    );
1851                } else {
1852                    TblCompanyUsers::where('user_id', $userId)->update(
1853                        [
1854                            'can_read' => 1,
1855                            'can_write' => 1,
1856                            'updated_at' => date('Y-m-d H:i:s'),
1857                            'updated_by' => $data['updated_by'],
1858                        ]
1859                    );
1860                }
1861            }
1862
1863            return response([
1864                'message' => 'OK',
1865            ]);
1866
1867        } catch (\Exception $e) {
1868            /** @disregard P1014 */
1869            $e->exceptionCode = 'UPDATE_COMPANY_PERMISSION_EXCEPTION';
1870            report($e);
1871
1872            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1873        }
1874
1875    }
1876
1877    public function list_facility_settings()
1878    {
1879
1880        try {
1881
1882            $result = TblFacilitySettings::get();
1883
1884            for ($i = 0; $i < count($result); $i++) {
1885                if ($result[$i]->budget_type_id != null) {
1886                    $result[$i]->budget_type_id = array_map('intval', explode(',', $result[$i]->budget_type_id));
1887                }
1888            }
1889
1890            return response([
1891                'message' => 'OK',
1892                'data' => $result,
1893            ]);
1894
1895        } catch (\Exception $e) {
1896            /** @disregard P1014 */
1897            $e->exceptionCode = 'LIST_FACILITY_SETTINGS_EXCEPTION';
1898            report($e);
1899
1900            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1901        }
1902
1903    }
1904
1905    public function update_facility_settings(Request $request, $id)
1906    {
1907        try {
1908
1909            $data = $request->all();
1910            $id = intval($id);
1911            $data['updated_at'] = date('Y-m-d H:i:s');
1912
1913            if (isset($data['budget_type_id']) && is_array($data['budget_type_id'])) {
1914                $incomingIds = $data['budget_type_id'];
1915
1916                $rows = TblFacilitySettings::all();
1917
1918                foreach ($rows as $row) {
1919                    $currentIds = $row->budget_type_id ? explode(',', $row->budget_type_id) : [];
1920
1921                    $newIds = array_diff($currentIds, $incomingIds);
1922
1923                    if (! empty($newIds)) {
1924                        TblFacilitySettings::where('id', $row->id)->update([
1925                            'budget_type_id' => implode(',', $newIds),
1926                            'updated_at' => date('Y-m-d H:i:s'),
1927                        ]);
1928                    } else {
1929                        TblFacilitySettings::where('id', $row->id)->update([
1930                            'budget_type_id' => '',
1931                            'updated_at' => date('Y-m-d H:i:s'),
1932                        ]);
1933                    }
1934                }
1935
1936                $data['budget_type_id'] = implode(',', $incomingIds);
1937
1938                $exists = TblFacilitySettings::where('id', $id)->exists();
1939                if ($exists) {
1940                    TblFacilitySettings::where('id', $id)->update($data);
1941                } else {
1942                    TblFacilitySettings::create(array_merge($data, ['id' => $id]));
1943                }
1944            } elseif (isset($data['minimum_budget_amount'])) {
1945                TblFacilitySettings::where('id', $id)->update($data);
1946            }
1947
1948            $result = $this->list_facility_settings();
1949
1950            return response([
1951                'message' => 'OK',
1952                'data' => $result->original['data'],
1953            ]);
1954
1955        } catch (\Exception $e) {
1956            /** @disregard P1014 */
1957            $e->exceptionCode = 'UPDATE_FACILITY_SETTINGS_EXCEPTION';
1958            report($e);
1959
1960            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1961        }
1962    }
1963
1964    public function list_trade_alignment_settings($companyId)
1965    {
1966
1967        try {
1968
1969            $companyId = intval($companyId);
1970            $result = TblTradeAlignmentSettings::where('company_id', $companyId)->get();
1971
1972            for ($i = 0; $i < count($result); $i++) {
1973                if ($result[$i]->budget_type_id != null) {
1974                    $result[$i]->budget_type_id = array_map('intval', explode(',', $result[$i]->budget_type_id));
1975                }
1976            }
1977
1978            return response([
1979                'message' => 'OK',
1980                'data' => $result,
1981            ]);
1982
1983        } catch (\Exception $e) {
1984            /** @disregard P1014 */
1985            $e->exceptionCode = 'LIST_TRADE_ALIGNMENT_SETTINGS_EXCEPTION';
1986            report($e);
1987
1988            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1989        }
1990
1991    }
1992
1993    public function update_trade_alignment_settings(Request $request, $id)
1994    {
1995        try {
1996
1997            $data = $request->all();
1998            $id = intval($id);
1999            $data['updated_at'] = date('Y-m-d H:i:s');
2000            $companyId = intval($data['company_id']);
2001
2002            if (isset($data['budget_type_id']) && is_array($data['budget_type_id'])) {
2003                $incomingIds = $data['budget_type_id'];
2004
2005                $rows = TblTradeAlignmentSettings::where('company_id', $companyId)->get();
2006
2007                foreach ($rows as $row) {
2008                    $currentIds = $row->budget_type_id ? explode(',', $row->budget_type_id) : [];
2009
2010                    $newIds = array_diff($currentIds, $incomingIds);
2011
2012                    if (! empty($newIds)) {
2013                        TblTradeAlignmentSettings::where('id', $row->id)->update([
2014                            'budget_type_id' => implode(',', $newIds),
2015                            'updated_at' => date('Y-m-d H:i:s'),
2016                        ]);
2017                    } else {
2018                        TblTradeAlignmentSettings::where('id', $row->id)->update([
2019                            'budget_type_id' => '',
2020                            'updated_at' => date('Y-m-d H:i:s'),
2021                        ]);
2022                    }
2023                }
2024
2025                $data['budget_type_id'] = implode(',', $incomingIds);
2026
2027                $exists = TblTradeAlignmentSettings::where('id', $id)->exists();
2028                if ($exists) {
2029                    TblTradeAlignmentSettings::where('id', $id)->update($data);
2030                } else {
2031                    TblTradeAlignmentSettings::create(array_merge($data, ['id' => $id]));
2032                }
2033            } elseif (isset($data['minimum_budget_amount'])) {
2034                TblTradeAlignmentSettings::where('id', $id)->update($data);
2035            }
2036
2037            $result = $this->list_trade_alignment_settings($companyId);
2038
2039            return response([
2040                'message' => 'OK',
2041                'data' => $result->original['data'],
2042            ]);
2043
2044        } catch (\Exception $e) {
2045            /** @disregard P1014 */
2046            $e->exceptionCode = 'UPDATE_TRADE_ALIGNMENT_SETTINGS_EXCEPTION';
2047            report($e);
2048
2049            return response(['message' => 'KO', 'error' => $e->getMessage()]);
2050        }
2051    }
2052}