Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 132
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
ReconcileApprovals
0.00% covered (danger)
0.00%
0 / 132
0.00% covered (danger)
0.00%
0 / 3
3660
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 123
0.00% covered (danger)
0.00%
0 / 1
2862
 filled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 decisionLabel
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
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 * Re-run the matrix approval engine over pending budgets and correct their
12 * `for_approval` / `approval_type` to match the engine's decision — WITHOUT
13 * sending any email or in-app notification and WITHOUT the confirm modal.
14 *
15 * Why this exists: budgets classified by the LEGACY path (before the matrix
16 * engine was switched on) can carry a stale/divergent `approval_type` — most
17 * commonly a margin-below-minimum budget stamped `2` (financial) that the
18 * matrix engine would call `1` (technical), which locks out the technical
19 * approver. The only in-app way to re-classify is to edit an approval input and
20 * save, which pops the approval-request modal and e-mails the approvers. This
21 * command does the re-classification quietly, in bulk.
22 *
23 * It also clears budgets left flagged pending after their circuit was actually
24 * completed (approved/rejected) — the "approved but still pending" stranding.
25 *
26 * SAFETY: preview by default. It only writes with --apply, and it NEVER
27 * re-types a budget that has a partial/mismatched decision already recorded
28 * (those are printed as "review" for a human). Terminal (3/4/7/20) and
29 * in-progress (12) budgets are skipped, mirroring update_quotation.
30 */
31class ReconcileApprovals extends Command
32{
33    protected $signature = 'approvals:reconcile
34        {--apply : Actually write the changes (default is a dry-run preview)}
35        {--company= : Limit to a single company_id}
36        {--id= : Limit to a single quotation id}';
37
38    protected $description = 'Re-classify pending budgets with the matrix engine and fix for_approval/approval_type, no emails sent.';
39
40    private const TERMINAL_STATUSES = [3, 4, 7, 20, 12];
41
42    public function handle(): int
43    {
44        if (! config('approvals.use_matrix_engine')) {
45            $this->error('approvals.use_matrix_engine is OFF — the legacy classifier governs, nothing to reconcile against. Enable it (and rebuild config cache) first.');
46
47            return self::FAILURE;
48        }
49
50        $apply = (bool) $this->option('apply');
51        $engine = new ApprovalThresholdEngine;
52
53        $query = DB::table('tbl_quotations')
54            ->whereNotNull('for_approval')
55            ->where('for_approval', '!=', 0)
56            ->whereNotIn('budget_status_id', self::TERMINAL_STATUSES);
57
58        if ($this->option('company') !== null) {
59            $query->where('company_id', (int) $this->option('company'));
60        }
61        if ($this->option('id') !== null) {
62            $query->where('id', (int) $this->option('id'));
63        }
64
65        $budgets = $query->get([
66            'id', 'quote_id', 'company_id', 'budget_type_id', 'customer_type_id',
67            'amount', 'invoice_margin', 'revenue_per_date_per_worked', 'budget_margin_enabled',
68            'question_enabled', 'question_ids_no', 'for_approval', 'approval_type',
69            'approved_by', 'approved_by_v2', 'rejected_by', 'rejected_by_v2',
70        ]);
71
72        $this->info(($apply ? 'APPLYING' : 'DRY-RUN — no changes written').' · '.$budgets->count().' pending budget(s) examined'.PHP_EOL);
73
74        $companies = [];
75        $rows = [];
76        $counts = ['retype' => 0, 'clear' => 0, 'review' => 0, 'ok' => 0, 'skip-legacy' => 0];
77
78        foreach ($budgets as $b) {
79            $cid = (int) $b->company_id;
80            $company = $companies[$cid] ??= DB::table('tbl_companies')->where('company_id', $cid)->first();
81            if (! $company) {
82                $counts['skip-legacy']++;
83
84                continue;
85            }
86
87            $row = $engine->resolveRow(
88                $cid,
89                $b->budget_type_id !== null ? (int) $b->budget_type_id : null,
90                $b->customer_type_id !== null ? (int) $b->customer_type_id : null,
91            );
92
93            // No matrix row → this company/combo still runs on the legacy
94            // thresholds (hybrid). Don't touch it; we can't improve on legacy here.
95            if ($row === null) {
96                $counts['skip-legacy']++;
97
98                continue;
99            }
100
101            // Both invoice_margin and revenue_per_date_per_worked treat a stored 0
102            // as "no measurement". G3W-imported budgets carry both columns as
103            // "0" when the source doesn't compute them, and the frontend
104            // serializes empty numeric fields as 0. Feeding the placeholder
105            // through made the engine demand technical approval on budgets far
106            // below any threshold. Mirrors Quotations::measuredFloatOrNull
107            // (FIRE-1730, 2026-08-18).
108            $marginOn = (int) $b->budget_margin_enabled > 0;
109            $margin = $marginOn && $b->invoice_margin !== null
110                ? (float) $b->invoice_margin
111                : null;
112            if ($margin == 0.0) {
113                $margin = null;
114            }
115            $revenue = $marginOn && $b->revenue_per_date_per_worked !== null
116                ? (float) $b->revenue_per_date_per_worked
117                : null;
118            if ($revenue == 0.0) {
119                $revenue = null;
120            }
121
122            $eval = $engine->evaluateForRow(
123                $row,
124                $b->amount !== null ? (float) $b->amount : null,
125                $margin,
126                $revenue,
127            );
128
129            $reqTech = $eval['reqTechnical'];
130            $reqFin = $eval['reqFinancial'];
131
132            // Legacy workflow-question trigger forces a technical approval —
133            // identical gate to evaluateApprovalForBudget().
134            if ((int) $b->question_enabled > 0
135                && ! empty($b->question_ids_no)
136                && $company->workflow_budget_size !== null
137                && (float) ($b->amount ?? 0) >= (float) $company->workflow_budget_size) {
138                $reqTech = true;
139            }
140
141            $newType = ($reqTech && $reqFin) ? 3 : ($reqFin ? 2 : ($reqTech ? 1 : null));
142
143            $curType = $b->approval_type !== null ? (int) $b->approval_type : null;
144            $curFor = (int) $b->for_approval;
145
146            $approvedTech = $this->filled($b->approved_by);
147            $approvedFin = $this->filled($b->approved_by_v2);
148            $rejected = $this->filled($b->rejected_by) || $this->filled($b->rejected_by_v2);
149            $hasDecision = $approvedTech || $approvedFin || $rejected;
150
151            $complete = $newType !== null && (
152                $rejected
153                || ($newType === 1 && $approvedTech)
154                || ($newType === 2 && $approvedFin)
155                || ($newType === 3 && $approvedTech && $approvedFin)
156            );
157
158            // Decide the action.
159            if ($newType === null) {
160                $action = 'clear';   // engine: no approval required anymore
161                $set = ['for_approval' => null, 'approval_type' => null];
162            } elseif ($complete) {
163                $action = 'clear';   // circuit already satisfied → stop showing pending
164                $set = ['for_approval' => null, 'approval_type' => null];
165            } elseif ($hasDecision) {
166                if ($curType === $newType) {
167                    // Type unchanged and a decision is already recorded — this is
168                    // a normal in-progress circuit (e.g. a dual budget with the
169                    // technical slot approved, waiting on finance). Nothing to do.
170                    $action = 'ok';
171                    $set = null;
172                } else {
173                    // The engine's type DIFFERS and a decision exists — rewriting
174                    // would strand or invalidate that decision. Leave for a human.
175                    $action = 'review';
176                    $set = null;
177                }
178            } elseif ($curType === $newType && $curFor === $newType) {
179                $action = 'ok';
180                $set = null;
181            } else {
182                $action = 'retype';
183                $set = ['for_approval' => $newType, 'approval_type' => $newType];
184            }
185
186            $counts[$action] = ($counts[$action] ?? 0) + 1;
187
188            if ($action === 'ok') {
189                continue;
190            }
191
192            $rows[] = [
193                $b->id,
194                $b->quote_id,
195                $cid,
196                'for='.($b->for_approval ?? 'null').' type='.($curType ?? 'null'),
197                $newType === null ? 'none' : "type={$newType}",
198                $this->decisionLabel($approvedTech, $approvedFin, $rejected),
199                strtoupper($action),
200            ];
201
202            if ($apply && $set !== null) {
203                DB::table('tbl_quotations')->where('id', $b->id)->update($set + ['updated_at' => date('Y-m-d H:i:s')]);
204            }
205        }
206
207        if ($rows) {
208            $this->table(
209                ['id', 'quote_id', 'co', 'current', 'engine', 'decisions', 'action'],
210                $rows,
211            );
212        }
213
214        $this->line('');
215        $this->info(sprintf(
216            'retype: %d · clear: %d · review(manual): %d · already-ok: %d · skipped(legacy/no-row): %d',
217            $counts['retype'], $counts['clear'], $counts['review'], $counts['ok'], $counts['skip-legacy'],
218        ));
219
220        if ($apply && ($counts['retype'] > 0 || $counts['clear'] > 0)) {
221            // Approval state feeds list_quotations + the approver counters.
222            ResultCache::forgetDomain(['quotations', 'users']);
223            $this->info('Applied. Caches flushed. No emails or notifications were sent.');
224        } elseif (! $apply) {
225            $this->comment('Dry-run only. Re-run with --apply to write these changes.');
226        }
227
228        if ($counts['review'] > 0) {
229            $this->warn($counts['review'].' budget(s) marked REVIEW have a decision that conflicts with the engine\'s new type — handle those by hand.');
230        }
231
232        return self::SUCCESS;
233    }
234
235    private function filled($value): bool
236    {
237        return $value !== null && $value !== '';
238    }
239
240    private function decisionLabel(bool $tech, bool $fin, bool $rejected): string
241    {
242        $parts = [];
243        if ($tech) {
244            $parts[] = 'appr(v1)';
245        }
246        if ($fin) {
247            $parts[] = 'appr(v2)';
248        }
249        if ($rejected) {
250            $parts[] = 'rejected';
251        }
252
253        return $parts ? implode('+', $parts) : 'none';
254    }
255}