Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.92% covered (danger)
0.92%
1 / 109
12.50% covered (danger)
12.50%
1 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
ResyncMargins
0.92% covered (danger)
0.92%
1 / 109
12.50% covered (danger)
12.50%
1 / 8
632.96
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
56
 processOne
0.00% covered (danger)
0.00%
0 / 60
0.00% covered (danger)
0.00%
0 / 1
132
 readMarginTriple
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 invariantHolds
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 regionForCompanyId
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 parseIds
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 fmt
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace App\Console\Commands;
4
5use App\Models\TblCompanies;
6use App\Models\TblQuotations;
7use App\Models\TblQuotationsLog;
8use App\Services\PresupuestosService;
9use Illuminate\Console\Command;
10use Illuminate\Support\Facades\Log;
11
12/**
13 * FIRE-1644 follow-up: force a re-sync on the 19 quotations that broke BEFORE
14 * the labor-override margin fix landed and still carry wrong totals. Berta's
15 * observation (comment 26682) is that most of them won't heal on their own —
16 * 14 are already Enviado, 2 Aceptado, so no future edit will trigger a sync.
17 *
18 * What this command does, per Titan id:
19 *
20 *   1. Look up the row's `internal_quote_id` + region (from tbl_companies).
21 *   2. Call `PresupuestosService::syncById` — same code path the fix ships in,
22 *      so a sync where G3W now sends a different value will recalculate all
23 *      seven fields (cost_of_labor, total_cost_of_job, invoice_margin,
24 *      margin_for_the_company, revenue_per_date_per_worked, gross_margin,
25 *      labor_percentage).
26 *   3. Re-read the row. If the invariant `total_cost_of_job =
27 *      estimated_cost_of_materials + cost_of_labor` still fails, the sync
28 *      was a no-op (identical inputs) — recompute `cost_of_labor` directly:
29 *
30 *          cost_of_labor := total_cost_of_job - estimated_cost_of_materials
31 *
32 *      This mirrors what the fixed sync would have written and is the same
33 *      value the invariant demands. Recording an audit row keeps this
34 *      distinguishable from a real sync-driven update.
35 *
36 * Reports one line per id: healed by sync / auto-fixed / already correct / no
37 * matching row. `--dry-run` prints what would change without writing.
38 *
39 * Invariant reminder from Berta:
40 *   total_cost_of_job = estimated_cost_of_materials + cost_of_labor
41 */
42class ResyncMargins extends Command
43{
44    protected $signature = 'quotations:resync-margins
45        {--ids= : Comma-separated Titan tbl_quotations.id list. Defaults to the FIRE-1644 residual set.}
46        {--dry-run : Report per-id decisions without writing.}';
47
48    protected $description = 'FIRE-1644: force a re-sync of the 19 residual quotations and auto-fix any that stay violated.';
49
50    /** Berta 2026-08-06 in FIRE-1644 comment 26682 — the 19 residuals. */
51    private const FIRE_1644_IDS = [
52        193247, 194087, 194758, 193397, 190990, 192010, 195925, 193163, 193290,
53        195225, 196216, 195216, 195364, 195135, 194050, 194657, 195502, 193244,
54        195200,
55    ];
56
57    public function __construct(private readonly PresupuestosService $presupuestos)
58    {
59        parent::__construct();
60    }
61
62    public function handle(): int
63    {
64        @set_time_limit(0);
65
66        $dryRun = (bool) $this->option('dry-run');
67        $ids = $this->parseIds((string) $this->option('ids'));
68
69        $this->line(sprintf(
70            'FIRE-1644 residuals: %d id(s) · %s',
71            count($ids),
72            $dryRun ? '<fg=green>DRY RUN</>' : '<fg=yellow>APPLY</>',
73        ));
74        $this->newLine();
75
76        $summary = [
77            'already_correct' => 0,
78            'healed_by_sync' => 0,
79            'auto_fixed' => 0,
80            'still_violated' => 0,
81            'not_found' => 0,
82            'errors' => 0,
83        ];
84
85        foreach ($ids as $id) {
86            try {
87                $result = $this->processOne($id, $dryRun);
88            } catch (\Throwable $e) {
89                $summary['errors']++;
90                $this->error(sprintf('id %d · error: %s', $id, $e->getMessage()));
91
92                continue;
93            }
94            $summary[$result]++;
95        }
96
97        $this->newLine();
98        $this->line('Summary');
99        foreach ($summary as $bucket => $n) {
100            $this->line(sprintf('  %-18s : %d', $bucket, $n));
101        }
102
103        // Non-zero exit if anything's still violated after the auto-fix path,
104        // so a downstream check-runner treats it as a failure.
105        return $summary['still_violated'] === 0 && $summary['errors'] === 0
106            ? self::SUCCESS
107            : self::FAILURE;
108    }
109
110    /**
111     * @return 'already_correct'|'healed_by_sync'|'auto_fixed'|'still_violated'|'not_found'
112     */
113    private function processOne(int $id, bool $dryRun): string
114    {
115        $row = TblQuotations::find($id);
116        if (! $row) {
117            $this->line(sprintf('  id %-6d  <fg=red>not found</>', $id));
118
119            return 'not_found';
120        }
121
122        [$materials, $labor, $total] = $this->readMarginTriple($row);
123
124        if ($this->invariantHolds($materials, $labor, $total)) {
125            $this->line(sprintf(
126                '  id %-6d  <fg=green>already correct</> · materials=%s labor=%s total=%s',
127                $id, $this->fmt($materials), $this->fmt($labor), $this->fmt($total),
128            ));
129
130            return 'already_correct';
131        }
132
133        $region = $this->regionForCompanyId((int) $row->company_id);
134        if ($region === null) {
135            $this->line(sprintf('  id %-6d  <fg=red>no region for company_id=%d</> · %s',
136                $id, $row->company_id, $row->internal_quote_id));
137
138            return 'not_found';
139        }
140
141        $internalQuoteId = (string) $row->internal_quote_id;
142
143        // Ask the fixed sync path to re-read this budget and recompute. In
144        // dry-run we DO NOT call syncById — it would still write to the DB,
145        // and Berta's rule is no writes without the confirmed approach.
146        if (! $dryRun) {
147            $sync = $this->presupuestos->syncById($internalQuoteId, $region);
148            if (empty($sync['success'])) {
149                $this->warn(sprintf(
150                    '  id %-6d  sync failed for %s in %s: %s',
151                    $id, $internalQuoteId, $region, $sync['error'] ?? 'unknown',
152                ));
153            }
154        }
155
156        // Re-read; syncById() may have moved fields even if it reported an
157        // error (it wraps its own writes in a transaction, but a partial
158        // update path can still land).
159        $row->refresh();
160        [$materials, $labor, $total] = $this->readMarginTriple($row);
161
162        if ($this->invariantHolds($materials, $labor, $total)) {
163            $this->line(sprintf(
164                '  id %-6d  <fg=cyan>healed by sync</>%s · materials=%s labor=%s total=%s',
165                $id, $dryRun ? ' <fg=yellow>[dry-run — sync was NOT run]</>' : '',
166                $this->fmt($materials), $this->fmt($labor), $this->fmt($total),
167            ));
168
169            // In dry-run we don't know whether the sync would have healed it,
170            // so classify honestly.
171            return $dryRun ? 'still_violated' : 'healed_by_sync';
172        }
173
174        // Sync ran and didn't move it — Berta's "identical inputs" case.
175        // Recompute cost_of_labor directly to satisfy the invariant.
176        $newLabor = round($total - $materials, 2);
177
178        $this->line(sprintf(
179            '  id %-6d  <fg=magenta>auto-fix</>%s · materials=%s total=%s · cost_of_labor %s -> %s',
180            $id, $dryRun ? ' <fg=yellow>[dry-run — no write]</>' : '',
181            $this->fmt($materials), $this->fmt($total),
182            $this->fmt($labor), $this->fmt($newLabor),
183        ));
184
185        if ($dryRun) {
186            return 'auto_fixed';
187        }
188
189        // Write + audit. The category matches how PresupuestosService labels
190        // its own margin recalculations so the log reads consistently.
191        TblQuotations::where('id', $id)->update([
192            'cost_of_labor' => $newLabor,
193            'updated_at' => now()->format('Y-m-d H:i:s'),
194            'updated_by' => 'fire1644:resync-margins',
195        ]);
196
197        TblQuotationsLog::create([
198            'category' => 'Modificacion de presupuesto',
199            'quotation_id' => $id,
200            'user' => 'fire1644:resync-margins',
201            'field' => 'cost_of_labor',
202            'old_value' => (string) $labor,
203            'new_value' => (string) $newLabor,
204        ]);
205
206        Log::channel('allInfoQuotationsG3w')->info(sprintf(
207            'FIRE-1644 auto-fix: quotation %d (%s) cost_of_labor %s -> %s (total=%s, materials=%s).',
208            $id, $internalQuoteId, $labor, $newLabor, $total, $materials,
209        ));
210
211        return 'auto_fixed';
212    }
213
214    /** @return array{0: float, 1: float, 2: float} materials, labor, total */
215    private function readMarginTriple(TblQuotations $row): array
216    {
217        return [
218            (float) ($row->estimated_cost_of_materials ?? 0),
219            (float) ($row->cost_of_labor ?? 0),
220            (float) ($row->total_cost_of_job ?? 0),
221        ];
222    }
223
224    /**
225     * True when the row satisfies Berta's invariant within a small epsilon.
226     * Money columns are stored as DECIMAL and can drift by ±0.01 through the
227     * cast round-trip — matching to the cent avoids false positives on rows
228     * that are already correct.
229     */
230    private function invariantHolds(float $materials, float $labor, float $total): bool
231    {
232        return abs(($materials + $labor) - $total) < 0.01;
233    }
234
235    private function regionForCompanyId(int $companyId): ?string
236    {
237        $company = TblCompanies::where('company_id', $companyId)->first();
238
239        return $company?->region;
240    }
241
242    /**
243     * Parse the --ids option. Empty / missing falls back to the FIRE-1644 set
244     * so this command is safe to run without arguments for the residual sweep.
245     *
246     * @return int[]
247     */
248    private function parseIds(string $raw): array
249    {
250        $raw = trim($raw);
251        if ($raw === '') {
252            return self::FIRE_1644_IDS;
253        }
254
255        $ids = array_values(array_filter(array_map(
256            static fn (string $s): int => (int) trim($s),
257            explode(',', $raw),
258        ), static fn (int $n): bool => $n > 0));
259
260        return array_values(array_unique($ids));
261    }
262
263    private function fmt(float $v): string
264    {
265        return number_format($v, 2, '.', '');
266    }
267}