Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
19.82% covered (danger)
19.82%
22 / 111
40.00% covered (danger)
40.00%
2 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
BusinessGoals
19.82% covered (danger)
19.82%
22 / 111
40.00% covered (danger)
40.00%
2 / 5
526.36
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 list_business_goals
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 business_goals
0.00% covered (danger)
0.00%
0 / 48
0.00% covered (danger)
0.00%
0 / 1
272
 provisionMissingCommercialGoals
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
42
 update_business_goals
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Exceptions\AppException;
6use App\Models\TblBusinessGoals;
7use App\Services\ResultCache;
8use Illuminate\Contracts\Routing\ResponseFactory;
9use Illuminate\Http\Request;
10use Illuminate\Http\Response;
11use Illuminate\Support\Facades\App;
12use Illuminate\Support\Facades\Cache;
13use Illuminate\Support\Facades\DB;
14
15class BusinessGoals extends Controller
16{
17    private $locale;
18
19    private $userId;
20
21    private array $business_goals = [];
22
23    public function __construct()
24    {
25        $this->locale = request()->header('Locale-Id');
26        $this->userId = request()->header('User-Id');
27
28        App::setLocale($this->locale);
29    }
30
31    public function list_business_goals(Request $request): ResponseFactory|Response
32    {
33
34        try {
35
36            $data = $request->all();
37
38            $this->business_goals($data);
39
40            return response([
41                'message' => 'OK',
42                'data' => $this->business_goals,
43            ]);
44
45        } catch (\Exception $e) {
46            report(AppException::fromException($e, 'LIST_BUSINESS_GOALS_EXCEPTION'));
47
48            return response(['message' => 'KO', 'error' => $e->getMessage()]);
49        }
50
51    }
52
53    public function business_goals(array $params): void
54    {
55        // FIRE-1743: auto-provision empty goal rows for any active commercial
56        // that doesn't have any yet. Original bug: Ricardo reported "does not
57        // appear all the comercials (like Ruben Jaramillo and Carlos Alonso)".
58        // Both were active (`is_active = 1`) but had zero rows in
59        // `tbl_business_goals`, so the goals-driven query never returned them.
60        // Provisioning here makes them visible on next page load and lets the
61        // existing update endpoint edit their goals — no FE changes required.
62        $this->provisionMissingCommercialGoals();
63
64        $where = '';
65
66        if (isset($params['budget_type_group_id']) && $params['budget_type_group_id'] != null) {
67            $budgetTypeGroupIds = implode(',', $params['budget_type_group_id']);
68            if (count($params['budget_type_group_id']) > 0) {
69                $where .= " AND bg.budget_type_group_id IN ({$budgetTypeGroupIds}, 999999999)";
70            }
71        } else {
72            $where .= ' AND bg.budget_type_group_id > 0';
73        }
74
75        if (isset($params['user_id']) && $params['user_id'] != null) {
76            $userIds = implode(',', $params['user_id']);
77            if (count($params['user_id']) > 0) {
78                $where .= " AND bg.user_id IN ({$userIds}) OR (bg.is_default = 1 {$where})";
79            }
80        }
81
82        if (isset($params['role_id']) && $params['role_id'] != null) {
83            $roleIds = implode(',', $params['role_id']);
84            if (count($params['role_id']) > 0) {
85                $where .= " AND bg.role_id IN ({$roleIds}, 999999999)";
86            }
87        }
88
89        // FIRE-1743:
90        //   - `is_default` labelled as 'Default' at SQL level so PHP does not
91        //     need a fragile strict-type check (`=== 1`) that PDO can defeat
92        //     when the driver returns integers as strings.
93        //   - Per-user rows whose user is inactive (is_active = 0) or missing
94        //     from tbl_users are excluded, so old / deleted commercials no
95        //     longer appear as blank-name rows on /organization/business-goals.
96        $query = "SELECT
97                    bg.id,
98                    bg.budget_type_group_id,
99                    CASE
100                        WHEN bg.budget_type_group_id = 999999999 THEN 'Default'
101                        ELSE btg.name
102                    END budget_type,
103                    CASE
104                        WHEN bg.is_default = 1 THEN 'Default'
105                        WHEN bg.is_commercial_type = 1 THEN r.name
106                        ELSE u.name
107                    END users,
108                    bg.is_commercial_type,
109                    bg.issue_objective,
110                    bg.acceptance_objective,
111                    bg.new_objective,
112                    bg.role_id,
113                    bg.user_id,
114                    bg.is_default,
115                    bg.is_amount
116                FROM
117                    tbl_business_goals bg
118                LEFT JOIN tbl_budget_type_groups btg
119                    ON btg.budget_type_group_id = bg.budget_type_group_id
120                LEFT JOIN tbl_roles r
121                    ON bg.role_id = r.role_id
122                LEFT JOIN tbl_users u
123                    ON bg.user_id = u.id
124                WHERE bg.id > 0
125                    AND (
126                        bg.user_id IS NULL
127                        OR (u.id IS NOT NULL AND u.is_active = 1)
128                    )
129                    {$where}
130                ORDER BY
131                    FIELD(bg.role_id, 999999999) DESC,
132                    FIELD(btg.budget_type_group_id, 999999999) DESC,
133                    FIELD(bg.is_commercial_type, 1) DESC,
134                    bg.role_id ASC,
135                    btg.priority ASC";
136
137        $data = DB::select($query);
138
139        $result = ['users' => [], 'roles' => [], 'budget_types' => []];
140
141        foreach ($data as $item) {
142
143            if ($item->budget_type != null) {
144                // FIRE-1743: PDO can return integer columns as strings depending
145                // on driver options — using loose comparison here so `1` and
146                // `"1"` both classify the row as a role-scoped goal. The old
147                // strict `=== 1` silently misrouted every row to the `users`
148                // bucket when PDO stringified, and PHP then rendered them with
149                // an empty `name` (Bug 2a).
150                $key = (int) $item->is_commercial_type === 1 ? 'roles' : 'users';
151
152                $id = $item->user_id;
153                if ($key == 'roles') {
154                    $id = $item->role_id;
155                }
156
157                /** @phpstan-ignore-next-line */
158                if (! array_key_exists($id, $result[$key])) {
159
160                    $result[$key][$id] = [
161                        $key == 'roles' ? 'role_id' : 'user_id' => $id,
162                        // FIRE-1743: 'Default' label now comes from the SQL CASE
163                        // (see query above), so we can trust `users` directly.
164                        'name' => $item->users,
165                        'id' => $item->id,
166                        'is_default' => $item->is_default,
167                        'is_amount' => $item->is_amount,
168                        'budget_types' => [],
169                    ];
170
171                }
172
173                $result[$key][$id]['budget_types'][] = [
174                    'id' => $item->id,
175                    'budget_type_group_id' => $item->budget_type_group_id,
176                    'budget_type' => $item->budget_type,
177                    'issue_objective' => $item->issue_objective,
178                    'acceptance_objective' => $item->acceptance_objective,
179                    'new_objective' => $item->new_objective,
180                ];
181
182                array_push($result['budget_types'], $item->budget_type);
183            }
184        }
185
186        $result['users'] = array_values($result['users']);
187        $result['roles'] = array_values($result['roles']);
188        $result['budget_types'] = array_values(array_unique($result['budget_types']));
189
190        $this->business_goals = $result;
191    }
192
193    /**
194     * FIRE-1743: seed empty `tbl_business_goals` rows (one per active
195     * budget_type_group) for every active user whose role is commercial-facing
196     * but who has no goals yet. Idempotent — the `NOT IN` guard makes repeat
197     * calls a no-op once the row exists. Kept private so it only runs from
198     * `list_business_goals`, i.e. the admin actively looking at the page,
199     * never from a background job.
200     *
201     * Role allowlist: 2 (Regular), 3 (Manager), 4 (Asesor de clientes),
202     * 5 (Sales specialist), 6 (GGCC y concurso público). Admins (1) are
203     * excluded — they set goals for others, not for themselves.
204     */
205    private function provisionMissingCommercialGoals(): void
206    {
207        $commercialRoleIds = [2, 3, 4, 5, 6];
208
209        $missingUserIds = DB::table('tbl_users AS u')
210            ->leftJoin('tbl_business_goals AS bg', 'bg.user_id', '=', 'u.id')
211            ->whereIn('u.role_id', $commercialRoleIds)
212            ->where('u.is_active', 1)
213            ->whereNull('bg.id')
214            ->distinct()
215            ->pluck('u.id');
216
217        if ($missingUserIds->isEmpty()) {
218            return;
219        }
220
221        $budgetTypeGroupIds = DB::table('tbl_budget_type_groups')
222            ->pluck('budget_type_group_id');
223
224        if ($budgetTypeGroupIds->isEmpty()) {
225            return;
226        }
227
228        // FIRE-1743: objectives MUST be NULL, not 0. The % cascade in
229        // Quotations::list_quotation_analytics_commercial_productivity checks
230        // `IS NOT NULL` at each level (user → role → default). A 0 here would
231        // short-circuit the cascade at the user level, and `NULLIF(0, 0)` in
232        // the outer % expression collapses back to NULL, so the FE renders
233        // `-%` even when the commercial's ROLE has a goal configured (e.g.
234        // Asesor de clientes = 250.000 €). NULL lets the cascade fall through
235        // to the role or default goal as intended.
236        $now = date('Y-m-d H:i:s');
237        $rows = [];
238        foreach ($missingUserIds as $userId) {
239            foreach ($budgetTypeGroupIds as $btgId) {
240                $rows[] = [
241                    'user_id' => $userId,
242                    'budget_type_group_id' => $btgId,
243                    'is_commercial_type' => 0,
244                    'is_default' => 0,
245                    'is_amount' => 1,
246                    'issue_objective' => null,
247                    'acceptance_objective' => null,
248                    'new_objective' => null,
249                    'created_at' => $now,
250                    'updated_at' => $now,
251                ];
252            }
253        }
254
255        // Chunked insert to stay well under `max_allowed_packet` on any driver.
256        foreach (array_chunk($rows, 500) as $chunk) {
257            DB::table('tbl_business_goals')->insert($chunk);
258        }
259    }
260
261    public function update_business_goals(Request $request): ResponseFactory|Response
262    {
263
264        try {
265
266            $data = $request->all();
267
268            foreach ($data as $item) {
269                $id = $item['id'];
270                unset($item['id']);
271
272                $item['updated_at'] = date('Y-m-d H:i:s');
273
274                if (isset($item['is_amount'])) {
275                    $bg = TblBusinessGoals::where('id', $id)->first();
276                    if (is_numeric($bg->user_id)) {
277                        TblBusinessGoals::where('user_id', $bg->user_id)->update($item);
278                    }
279
280                    if (is_numeric($bg->role_id)) {
281                        TblBusinessGoals::where('role_id', $bg->role_id)->update($item);
282                    }
283                }
284
285                TblBusinessGoals::where('id', $id)->update($item);
286            }
287
288            // FIRE-1145: was Cache::flush() — goals aggregate into the campaign dashboards.
289            ResultCache::forgetDomain('digital_campaign_analytics');
290
291            return response([
292                'message' => 'OK',
293            ]);
294
295        } catch (\Exception $e) {
296            report(AppException::fromException($e, 'UPDATE_BUSINESS_GOALS_EXCEPTION'));
297
298            return response(['message' => 'KO', 'error' => $e->getMessage()]);
299        }
300
301    }
302}