Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 115
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
ClearMarginGatedApprovals
0.00% covered (danger)
0.00%
0 / 115
0.00% covered (danger)
0.00%
0 / 4
2756
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 110
0.00% covered (danger)
0.00%
0 / 1
2256
 withoutGate
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 filled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 num
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3namespace App\Console\Commands;
4
5use App\Services\ApprovalThresholdEngine;
6use App\Services\ResultCache;
7use Illuminate\Console\Command;
8use Illuminate\Support\Facades\DB;
9
10/**
11 * Back-fill for the new margin-approval condition ("Require margin approval only
12 * for budgets above the revenue amount", `min_amount_for_margin_check`, migration
13 * 2026_08_11_000001).
14 *
15 * The rule only changes the future: a budget flagged BEFORE the gate existed
16 * keeps its `for_approval` / `approval_type` until something re-saves it. So the
17 * small budgets the gate was introduced to stop bothering approvers about — the
18 * 150 € correctivo with a thin margin that pulled in a regional approver — are
19 * still sitting in the approver's pending list. This command finds exactly that
20 * population and clears it, quietly: no email, no in-app notification, no
21 * approval-request modal.
22 *
23 * "Exactly that population" is decided by running the engine TWICE per budget:
24 * once as it behaves now (gate honoured) and once with the gate disabled (the
25 * pre-change behaviour). A budget is affected only when the two disagree AND the
26 * engine reports the gate as the reason it now suppresses the minimums. Anything
27 * whose approval has another leg to stand on — amount over the technical or
28 * financial threshold, the legacy workflow-question trigger — is left alone,
29 * even if its margin is also below the minimum.
30 *
31 * Relationship to `approvals:reconcile`: that command re-derives EVERY pending
32 * budget's type from scratch and would sweep these up as a side effect, along
33 * with unrelated corrections. This one is deliberately narrow, so the margin-gate
34 * change can be rolled out and reported on by itself.
35 *
36 * SAFETY: dry-run by default, writes only with --apply. It never touches a budget
37 * that already carries an approval decision (approved/rejected) — those print as
38 * REVIEW for a human. Terminal (3/4/7/20) and in-progress (12) budgets are
39 * skipped, mirroring update_quotation. Only the live-state flags are cleared;
40 * `approval_requested_at`, `approved_by*`, `rejected_by*` and the change log stay
41 * intact so the audit trail still shows the budget passed through the circuit.
42 */
43class ClearMarginGatedApprovals extends Command
44{
45    protected $signature = 'approvals:clear-margin-gated
46        {--apply : Actually write the changes (default is a dry-run preview)}
47        {--company= : Limit to a single company_id}
48        {--id= : Limit to a single quotation id}';
49
50    protected $description = 'Clear pending approvals that only existed because a margin/revenue minimum fired below the new margin-check amount. No emails sent.';
51
52    /** Mirrors ReconcileApprovals: decided (3/4/7/20) and in-progress (12). */
53    private const TERMINAL_STATUSES = [3, 4, 7, 20, 12];
54
55    public function handle(): int
56    {
57        if (! config('approvals.use_matrix_engine')) {
58            $this->error('approvals.use_matrix_engine is OFF — the legacy classifier governs and it has no margin gate, so there is nothing to back-fill. Enable it (and rebuild the config cache) first.');
59
60            return self::FAILURE;
61        }
62
63        $apply = (bool) $this->option('apply');
64        $engine = new ApprovalThresholdEngine;
65
66        $query = DB::table('tbl_quotations')
67            ->whereNotNull('for_approval')
68            ->where('for_approval', '!=', 0)
69            ->whereNotIn('budget_status_id', self::TERMINAL_STATUSES);
70
71        if ($this->option('company') !== null) {
72            $query->where('company_id', (int) $this->option('company'));
73        }
74        if ($this->option('id') !== null) {
75            $query->where('id', (int) $this->option('id'));
76        }
77
78        $budgets = $query->get([
79            'id', 'quote_id', 'company_id', 'budget_type_id', 'customer_type_id',
80            'amount', 'invoice_margin', 'revenue_per_date_per_worked', 'budget_margin_enabled',
81            'question_enabled', 'question_ids_no', 'for_approval', 'approval_type',
82            'approved_by', 'approved_by_v2', 'rejected_by', 'rejected_by_v2',
83        ]);
84
85        $this->info(($apply ? 'APPLYING' : 'DRY-RUN — no changes written').' · '.$budgets->count().' pending budget(s) examined'.PHP_EOL);
86
87        $companies = [];
88        $rows = [];
89        $counts = ['clear' => 0, 'retype' => 0, 'review' => 0, 'unaffected' => 0, 'skip-legacy' => 0];
90
91        foreach ($budgets as $b) {
92            $cid = (int) $b->company_id;
93            $company = $companies[$cid] ??= DB::table('tbl_companies')->where('company_id', $cid)->first();
94            if (! $company) {
95                $counts['skip-legacy']++;
96
97                continue;
98            }
99
100            $row = $engine->resolveRow(
101                $cid,
102                $b->budget_type_id !== null ? (int) $b->budget_type_id : null,
103                $b->customer_type_id !== null ? (int) $b->customer_type_id : null,
104            );
105
106            // No matrix row → this company/combo still runs on the legacy
107            // thresholds, which have no margin gate. Nothing to back-fill.
108            if ($row === null) {
109                $counts['skip-legacy']++;
110
111                continue;
112            }
113
114            // Same input shaping as Quotations::evaluateApprovalForBudget: both
115            // financial minimums are only meaningful with margin tracking on,
116            // and a stored 0 in either invoice_margin or
117            // revenue_per_date_per_worked means "no measurement" (every G3W
118            // import lands like that), so it is passed as null. Mirrors
119            // Quotations::measuredFloatOrNull (FIRE-1730, 2026-08-18).
120            $marginOn = (int) $b->budget_margin_enabled > 0;
121            $margin = $marginOn && $b->invoice_margin !== null ? (float) $b->invoice_margin : null;
122            if ($margin == 0.0) {
123                $margin = null;
124            }
125            $revenue = $marginOn && $b->revenue_per_date_per_worked !== null
126                ? (float) $b->revenue_per_date_per_worked
127                : null;
128            if ($revenue == 0.0) {
129                $revenue = null;
130            }
131
132            $amount = $b->amount !== null ? (float) $b->amount : null;
133
134            // The two readings that decide whether this budget is in scope.
135            $now = $engine->evaluateForRow($row, $amount, $margin, $revenue);
136            $before = $engine->evaluateForRow($this->withoutGate($row), $amount, $margin, $revenue);
137
138            // In scope only when the gate is demonstrably what changed the answer:
139            // the minimums used to force a technical approval, they no longer do,
140            // and the engine says it skipped them because of the margin-check
141            // amount. Anything else (over threshold, question trigger) is not ours.
142            $gateSuppressed = in_array('financial_minimums_skipped_below_margin_check_amount', $now['reasons'], true);
143            $affected = $gateSuppressed && $before['reqTechnical'] && ! $now['reqTechnical'];
144
145            if (! $affected) {
146                $counts['unaffected']++;
147
148                continue;
149            }
150
151            $reqTech = $now['reqTechnical'];
152            $reqFin = $now['reqFinancial'];
153
154            // Legacy workflow-question trigger forces a technical approval
155            // independently of any threshold — identical gate to
156            // evaluateApprovalForBudget(). A budget held by it is not "only here
157            // because of the margin", so it keeps its technical requirement.
158            if ((int) $b->question_enabled > 0
159                && ! empty($b->question_ids_no)
160                && $company->workflow_budget_size !== null
161                && (float) ($b->amount ?? 0) >= (float) $company->workflow_budget_size) {
162                $reqTech = true;
163            }
164
165            $newType = ($reqTech && $reqFin) ? 3 : ($reqFin ? 2 : ($reqTech ? 1 : null));
166
167            $curType = $b->approval_type !== null ? (int) $b->approval_type : null;
168            $curFor = (int) $b->for_approval;
169
170            if ($newType === $curType && $newType === $curFor) {
171                // The question trigger (or a surviving financial leg) reproduces
172                // the flags exactly — the gate changes nothing here after all.
173                $counts['unaffected']++;
174
175                continue;
176            }
177
178            // A recorded decision means an approver already acted on this budget.
179            // Clearing the flags now would strand or silently discard that, so it
180            // goes to a human instead.
181            $hasDecision = $this->filled($b->approved_by) || $this->filled($b->approved_by_v2)
182                || $this->filled($b->rejected_by) || $this->filled($b->rejected_by_v2);
183
184            if ($hasDecision) {
185                $action = 'review';
186                $set = null;
187            } elseif ($newType === null) {
188                $action = 'clear';
189                $set = ['for_approval' => null, 'approval_type' => null];
190            } else {
191                // The margin leg is gone but a financial leg survives (amount over
192                // the financial threshold) — downgrade rather than clear.
193                $action = 'retype';
194                $set = ['for_approval' => $newType, 'approval_type' => $newType];
195            }
196
197            $counts[$action]++;
198
199            $rows[] = [
200                $b->id,
201                $b->quote_id,
202                $cid,
203                $this->num($amount),
204                $margin === null ? '—' : $this->num($margin),
205                $revenue === null ? '—' : $this->num($revenue),
206                $this->num($row->min_amount_for_margin_check ?? null),
207                'for='.($b->for_approval ?? 'null').' type='.($curType ?? 'null'),
208                $newType === null ? 'none' : "type={$newType}",
209                strtoupper($action),
210            ];
211
212            if ($apply && $set !== null) {
213                DB::table('tbl_quotations')->where('id', $b->id)->update($set + ['updated_at' => date('Y-m-d H:i:s')]);
214            }
215        }
216
217        if ($rows) {
218            $this->table(
219                ['id', 'quote_id', 'co', 'amount', 'margin', 'rev/day', 'gate', 'current', 'engine', 'action'],
220                $rows,
221            );
222        }
223
224        $this->line('');
225        $this->info(sprintf(
226            'clear: %d · retype: %d · review(manual): %d · unaffected: %d · skipped(legacy/no-row): %d',
227            $counts['clear'], $counts['retype'], $counts['review'], $counts['unaffected'], $counts['skip-legacy'],
228        ));
229
230        if ($apply && ($counts['clear'] > 0 || $counts['retype'] > 0)) {
231            // Approval state feeds list_quotations + the approver counters.
232            ResultCache::forgetDomain(['quotations', 'users']);
233            $this->info('Applied. Caches flushed. No emails or notifications were sent.');
234        } elseif (! $apply) {
235            $this->comment('Dry-run only. Re-run with --apply to write these changes.');
236        }
237
238        if ($counts['review'] > 0) {
239            $this->warn($counts['review'].' budget(s) marked REVIEW no longer need the margin approval but already carry an approver decision — clear those by hand.');
240        }
241
242        return self::SUCCESS;
243    }
244
245    /**
246     * A copy of the matrix row with the margin-check gate disabled, i.e. how the
247     * engine behaved before `min_amount_for_margin_check` existed (0/NULL = the
248     * minimums are evaluated at any amount).
249     */
250    private function withoutGate(object $row): object
251    {
252        $clone = clone $row;
253        $clone->min_amount_for_margin_check = null;
254
255        return $clone;
256    }
257
258    private function filled($value): bool
259    {
260        return $value !== null && $value !== '';
261    }
262
263    private function num($value): string
264    {
265        return $value === null ? '—' : number_format((float) $value, 2);
266    }
267}