Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 67
0.00% covered (danger)
0.00%
0 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApprovalThresholdEngine
0.00% covered (danger)
0.00%
0 / 67
0.00% covered (danger)
0.00%
0 / 7
2070
0.00% covered (danger)
0.00%
0 / 1
 evaluate
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 resolveRow
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 selectRow
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
56
 evaluateForRow
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
462
 enabled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 csvContains
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
56
 result
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2
3namespace App\Services;
4
5use App\Models\TblApprovalThresholds;
6
7/**
8 * Approval threshold engine (SOP "Circuito de aprobación de presupuestos" v2.0,
9 * §3 "Reglas de evaluación" + "Notas y reglas"). Single source of truth for
10 * "does this budget require approval, and of which kind".
11 *
12 * It reads the admin-editable matrix in `tbl_approval_thresholds` and returns
13 * the two independent approval dimensions:
14 *   - TECHNICAL (regional approver, tbl_approvers / V1) — required if EITHER
15 *       (a) amount >= technical threshold, OR
16 *       (b) the budget fails a financial minimum of its row (invoice margin
17 *           below the minimum, or revenue per employee/day below the minimum)
18 *           AND its amount reaches `min_amount_for_margin_check` — see the
19 *           revenue gate below.
20 *   - FINANCIAL (central approvers, tbl_approvers_v2 / V2) — required if
21 *       amount >= financial threshold.
22 *
23 * Rules:
24 *   - Comparison is `>=`.
25 *   - Row = the (project type, customer type) match; fall back to the
26 *     "Todos los demás" catch-all row when no specific row matches.
27 *   - A threshold of 0 or NULL means that dimension is DISABLED (SOP §15 Q23),
28 *     NOT "everything needs approval".
29 *
30 * Revenue gate on rule (b) ("Require margin approval only for budgets above the
31 * revenue amount"): the financial minimums used to fire at ANY amount above 0,
32 * so a €150 correctivo with a thin margin pulled a regional approver in. They
33 * are now only evaluated once the amount reaches the row's
34 * `min_amount_for_margin_check`.
35 *
36 * That gate is its OWN column, deliberately not `technical_threshold`: gating on
37 * the amount threshold would make rule (b) decision-inert, because any amount
38 * that opened the gate already required technical approval through rule (a), so
39 * a below-minimum margin could never be the reason an approval was requested.
40 * With a separate (typically lower) floor, rule (b) keeps its teeth: between the
41 * gate and the technical threshold, a thin margin is the SOLE trigger.
42 *
43 * `min_amount_for_margin_check` of 0 / NULL means no gate — the minimums are
44 * evaluated at any amount, as they were before this rule existed. For a gate,
45 * "disabled" means "does not restrict"; it never blocks the check.
46 *
47 * The matching (selectRow) and evaluation (evaluateForRow) are pure so they can
48 * be unit-tested without a database; evaluate()/resolveRow() add the DB lookup.
49 */
50class ApprovalThresholdEngine
51{
52    /**
53     * Full evaluation for a budget. Pass the budget's computed financial
54     * metrics so the technical rule (b) can be checked; pass null for a metric
55     * to skip that particular minimum.
56     *
57     * @return array{reqTechnical: bool, reqFinancial: bool, requiresApproval: bool, approvalType: int|null, matchedRowId: int|null, reasons: array<int, string>, financialMinimumsApplied: bool}
58     */
59    public function evaluate(
60        int $companyId,
61        ?int $budgetTypeId,
62        ?int $customerTypeId,
63        ?float $amount,
64        ?float $invoiceMargin = null,
65        ?float $revenuePerEmployeeDay = null,
66    ): array {
67        $row = $this->resolveRow($companyId, $budgetTypeId, $customerTypeId);
68
69        return $this->evaluateForRow($row, $amount, $invoiceMargin, $revenuePerEmployeeDay);
70    }
71
72    /**
73     * Find the matrix row that applies to a budget: scoped to the company and
74     * enabled, the customer type must be listed, and a row whose budget types
75     * include this budget type wins over the catch-all.
76     */
77    public function resolveRow(int $companyId, ?int $budgetTypeId, ?int $customerTypeId): ?TblApprovalThresholds
78    {
79        $rows = TblApprovalThresholds::where('company_id', $companyId)
80            ->where('disabled', false)
81            ->orderBy('priority')
82            ->orderBy('id')
83            ->get();
84
85        return $this->selectRow($rows, $budgetTypeId, $customerTypeId);
86    }
87
88    /**
89     * Pure row selection. `$rows` must already be scoped to the company and
90     * enabled, ordered so specific rows precede the catch-all (priority asc).
91     *
92     * @param  iterable<int, object>  $rows
93     */
94    public function selectRow(iterable $rows, ?int $budgetTypeId, ?int $customerTypeId): ?object
95    {
96        $catchAll = null;
97
98        foreach ($rows as $row) {
99            if (! $this->csvContains($row->customer_type_ids, $customerTypeId)) {
100                continue;
101            }
102            if (! ($row->is_catch_all ?? false) && $this->csvContains($row->budget_type_ids, $budgetTypeId)) {
103                return $row; // specific match wins immediately (rows are priority-ordered)
104            }
105            if (($row->is_catch_all ?? false) && $catchAll === null) {
106                $catchAll = $row;
107            }
108        }
109
110        return $catchAll;
111    }
112
113    /**
114     * Pure evaluation of an already-resolved row against a budget's numbers.
115     *
116     * @return array{reqTechnical: bool, reqFinancial: bool, requiresApproval: bool, approvalType: int|null, matchedRowId: int|null, reasons: array<int, string>, financialMinimumsApplied: bool}
117     */
118    public function evaluateForRow(
119        ?object $row,
120        ?float $amount,
121        ?float $invoiceMargin = null,
122        ?float $revenuePerEmployeeDay = null,
123    ): array {
124        if ($row === null) {
125            return $this->result(false, false, null, ['no_matching_row']);
126        }
127
128        $amount = (float) ($amount ?? 0);
129        $reasons = [];
130
131        // An empty / zero-amount budget never requires approval. At amount 0 no
132        // threshold can be crossed, and the financial-minimum checks
133        // (margin/revenue) would otherwise fire on a 0% margin that only exists
134        // because the budget has no figures yet — e.g. a fresh draft during
135        // creation. Approval is re-evaluated on later saves once a real amount
136        // is present. (The margin/revenue tests deliberately use amount 100, not
137        // 0, so this preserves their intent.)
138        if ($amount <= 0) {
139            return $this->result(false, false, $row->id ?? null, ['zero_amount']);
140        }
141
142        // Technical (a): amount crosses the technical threshold.
143        $techByAmount = $this->enabled($row->technical_threshold)
144            && $amount >= (float) $row->technical_threshold;
145        if ($techByAmount) {
146            $reasons[] = 'amount_ge_technical_threshold';
147        }
148
149        // Revenue gate on rule (b): the financial minimums only apply to budgets
150        // whose amount reaches the row's margin-check floor. 0/NULL = no gate, so
151        // they apply at any amount (see the class docblock). `?? null` because a
152        // row can predate the column.
153        $marginCheckFrom = $row->min_amount_for_margin_check ?? null;
154        $minimumsApply = ! $this->enabled($marginCheckFrom) || $amount >= (float) $marginCheckFrom;
155
156        // Technical (b): budget fails a financial minimum of its row.
157        $marginBelowMin = $this->enabled($row->min_invoice_margin)
158            && $invoiceMargin !== null
159            && $invoiceMargin < (float) $row->min_invoice_margin;
160
161        $revenueBelowMin = $this->enabled($row->min_revenue_per_employee_day)
162            && $revenuePerEmployeeDay !== null
163            && $revenuePerEmployeeDay < (float) $row->min_revenue_per_employee_day;
164
165        $marginFail = $minimumsApply && $marginBelowMin;
166        if ($marginFail) {
167            $reasons[] = 'invoice_margin_below_min';
168        }
169
170        $revenueFail = $minimumsApply && $revenueBelowMin;
171        if ($revenueFail) {
172            $reasons[] = 'revenue_per_employee_day_below_min';
173        }
174
175        // Record the suppression so ops can tell "margin was fine" apart from
176        // "margin was below the minimum but the budget is under the margin-check
177        // amount" when reading a reconcile report.
178        if (! $minimumsApply && ($marginBelowMin || $revenueBelowMin)) {
179            $reasons[] = 'financial_minimums_skipped_below_margin_check_amount';
180        }
181
182        $reqTechnical = $techByAmount || $marginFail || $revenueFail;
183
184        // Financial: amount crosses the financial threshold.
185        $reqFinancial = $this->enabled($row->financial_threshold)
186            && $amount >= (float) $row->financial_threshold;
187        if ($reqFinancial) {
188            $reasons[] = 'amount_ge_financial_threshold';
189        }
190
191        return $this->result($reqTechnical, $reqFinancial, $row->id ?? null, $reasons, $minimumsApply);
192    }
193
194    /** A threshold is "set" only when it is a positive number (0/null = disabled). */
195    public function enabled($value): bool
196    {
197        return $value !== null && (float) $value > 0;
198    }
199
200    /** True when the integer $id is a member of a "1,2,3" CSV string. */
201    public function csvContains(?string $csv, ?int $id): bool
202    {
203        if ($csv === null || $csv === '' || $id === null) {
204            return false;
205        }
206
207        foreach (explode(',', $csv) as $part) {
208            $part = trim($part);
209            if ($part !== '' && (int) $part === $id) {
210                return true;
211            }
212        }
213
214        return false;
215    }
216
217    /**
218     * @param  array<int, string>  $reasons
219     * @param  bool  $minimumsApply  whether the revenue gate let the financial
220     *                               minimums be evaluated at all
221     * @return array{reqTechnical: bool, reqFinancial: bool, requiresApproval: bool, approvalType: int|null, matchedRowId: int|null, reasons: array<int, string>, financialMinimumsApplied: bool}
222     */
223    private function result(bool $tech, bool $fin, ?int $rowId, array $reasons, bool $minimumsApply = false): array
224    {
225        // Bridge to the existing `approval_type` column: 1 = technical (V1),
226        // 2 = financial (V2), 3 = both, null = none.
227        $approvalType = $tech && $fin ? 3 : ($fin ? 2 : ($tech ? 1 : null));
228
229        return [
230            'reqTechnical' => $tech,
231            'reqFinancial' => $fin,
232            'requiresApproval' => $tech || $fin,
233            'approvalType' => $approvalType,
234            'matchedRowId' => $rowId,
235            'reasons' => $reasons,
236            'financialMinimumsApplied' => $minimumsApply,
237        ];
238    }
239}