Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 145
0.00% covered (danger)
0.00%
0 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
IfexRepair
0.00% covered (danger)
0.00%
0 / 145
0.00% covered (danger)
0.00%
0 / 6
812
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
56
 baseQuery
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 reportIssuedTotal
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 normaliseCase
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
56
 reportUnparseable
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
42
 reportCollisions
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2
3namespace App\Console\Commands;
4
5use App\Models\TblQuotationsLog;
6use App\Services\IfexReference;
7use Illuminate\Console\Command;
8use Illuminate\Database\Query\Builder;
9use Illuminate\Support\Facades\DB;
10
11/**
12 * Repair the IFEX reference data already stored.
13 *
14 * The importer fix stops NEW bad data. This corrects what is already there —
15 * the other half of the ticket. Nothing here invents a value: it upper-cases
16 * references that were stored lower-case, reports references that parse under
17 * no format, and reports collisions with the numbers needed to decide what to
18 * do about them.
19 *
20 * Dry run by default. `--apply` performs only the safe, reversible rewrites
21 * (case normalisation). Collisions are NEVER resolved automatically: merging or
22 * re-keying rows moves money between budgets, so this command shows the issued
23 * totals and leaves the decision to a human.
24 */
25class IfexRepair extends Command
26{
27    protected $signature = 'ifex:repair
28        {--apply : Write the case-normalisation fixes (default is a dry-run preview)}
29        {--collisions : Show the full breakdown of colliding references}';
30
31    protected $description = 'Normalise and report IFEX budget references (case, format, collisions). Dry-run by default.';
32
33    private const COMMERCIAL = 'Ifex';
34
35    public function handle(): int
36    {
37        $apply = (bool) $this->option('apply');
38
39        $this->line('IFEX reference repair · '.($apply ? '<fg=yellow>APPLY</>' : '<fg=green>DRY RUN</>'));
40        $this->line('format: '.IfexReference::MYSQL_PATTERN);
41        $this->newLine();
42
43        $total = $this->baseQuery()->count();
44        $this->line("IFEX rows: {$total}");
45        $this->newLine();
46
47        $this->reportIssuedTotal('BEFORE');
48
49        $normalised = $this->normaliseCase($apply);
50        $unparseable = $this->reportUnparseable();
51        $collisions = $this->reportCollisions();
52
53        $this->newLine();
54        if ($apply) {
55            $this->reportIssuedTotal('AFTER');
56            $this->newLine();
57            // Rule 6: case normalisation cannot move money — it rewrites a
58            // string, never an amount, and merges nothing. Stated explicitly so
59            // the before/after pair above is not read as a coincidence.
60            $this->line('<fg=green>Issued total is unchanged by design:</> case normalisation rewrites');
61            $this->line('the reference string only. No row was merged, moved or deleted.');
62        }
63
64        $this->newLine();
65        $this->line('Summary');
66        $this->line("  references upper-cased : {$normalised}".($apply ? '' : ' (would be)'));
67        $this->line('  unparseable references : '.count($unparseable));
68        $this->line('  colliding references   : '.count($collisions));
69
70        if (! $apply && ($normalised > 0)) {
71            $this->newLine();
72            $this->line('Re-run with --apply to write the case fixes.');
73        }
74
75        if ($collisions !== []) {
76            $this->newLine();
77            $this->warn('Collisions are NOT fixed automatically — they change the issued total.');
78            $this->warn('Re-run with --collisions for the per-row breakdown and decide per family.');
79        }
80
81        return self::SUCCESS;
82    }
83
84    /** @return Builder */
85    private function baseQuery()
86    {
87        return DB::table('tbl_quotations')->where('commercial', self::COMMERCIAL);
88    }
89
90    /** Rule 6: the figure that must be explained if it moves. */
91    private function reportIssuedTotal(string $label): void
92    {
93        // `rows` is reserved in MySQL 8 — alias must be quoted or renamed.
94        $row = $this->baseQuery()
95            ->selectRaw('COUNT(*) row_count, COALESCE(SUM(amount), 0) total, SUM(budget_status_id = 3) accepted')
96            ->first();
97
98        $this->line(sprintf(
99            '%-6s issued: %s rows · total %s € · %s accepted',
100            $label,
101            number_format((float) $row->row_count),
102            number_format((float) $row->total, 2),
103            number_format((float) $row->accepted)
104        ));
105    }
106
107    /**
108     * Upper-case references stored with lower-case letters.
109     *
110     * Safe because the column's collation is case-insensitive: the row is
111     * already reachable under the upper-case spelling, so no lookup changes
112     * meaning. It is written row-by-row so each change lands in the audit trail
113     * — a silent bulk UPDATE is what this ticket is complaining about.
114     */
115    private function normaliseCase(bool $apply): int
116    {
117        $rows = $this->baseQuery()
118            ->whereRaw("internal_quote_id COLLATE utf8mb4_bin REGEXP '[a-z]'")
119            ->get(['id', 'internal_quote_id']);
120
121        if ($rows->isEmpty()) {
122            $this->line('Case: no lower-case references found.');
123
124            return 0;
125        }
126
127        $this->line('Case: '.$rows->count().' reference(s) with lower-case letters');
128
129        $changed = 0;
130        foreach ($rows as $row) {
131            $canonical = IfexReference::normalize($row->internal_quote_id);
132
133            if ($canonical === null || $canonical === $row->internal_quote_id) {
134                continue;
135            }
136
137            // Refuse to rewrite into a reference another row already owns —
138            // that would manufacture a collision while fixing a case defect.
139            $taken = $this->baseQuery()
140                ->where('id', '!=', $row->id)
141                ->whereRaw('internal_quote_id COLLATE utf8mb4_bin = ?', [$canonical])
142                ->exists();
143
144            if ($taken) {
145                $this->line("  <fg=red>skip</>  id {$row->id}  {$row->internal_quote_id} → {$canonical} (already taken)");
146
147                continue;
148            }
149
150            $this->line("  fix   id {$row->id}  {$row->internal_quote_id} → {$canonical}");
151
152            if ($apply) {
153                $this->baseQuery()->where('id', $row->id)->update([
154                    'internal_quote_id' => $canonical,
155                    'updated_at' => now()->format('Y-m-d H:i:s'),
156                ]);
157
158                TblQuotationsLog::create([
159                    'category' => 'Modificacion de presupuesto',
160                    'quotation_id' => $row->id,
161                    'user' => 'ifex:repair',
162                    'field' => 'internal_quote_id',
163                    'old_value' => $row->internal_quote_id,
164                    'new_value' => $canonical,
165                ]);
166            }
167
168            $changed++;
169        }
170
171        return $changed;
172    }
173
174    /**
175     * References that parse under no format. Reported, never rewritten: there is
176     * no way to infer the series and sequence a reference like
177     * `20260000000000100` was meant to have, and inventing one would put a
178     * budget in a series it does not belong to.
179     *
180     * @return array<int, object>
181     */
182    private function reportUnparseable(): array
183    {
184        $bad = [];
185        $caseOnly = 0;
186
187        foreach ($this->baseQuery()->get(['id', 'internal_quote_id', 'amount', 'budget_status_id']) as $row) {
188            if (IfexReference::isValid((string) $row->internal_quote_id)) {
189                continue;
190            }
191
192            // Distinguish "fails only because it is lower-case" (normaliseCase
193            // fixes it) from "fails whatever we do to it". Reporting them as one
194            // number makes the case fix look like it did nothing.
195            if (IfexReference::isValid(IfexReference::normalize($row->internal_quote_id))) {
196                $caseOnly++;
197
198                continue;
199            }
200
201            $bad[] = $row;
202        }
203
204        $this->newLine();
205        $this->line('Format: '.(count($bad) + $caseOnly).' reference(s) do not parse as stored');
206        $this->line("  of which fixed by case normalisation : {$caseOnly}");
207        $this->line('  of which genuinely unparseable       : '.count($bad));
208
209        foreach ($bad as $row) {
210            $this->line(sprintf(
211                '  id %-8s [%s]  amount %s  status %s',
212                $row->id,
213                $row->internal_quote_id,
214                number_format((float) $row->amount, 2),
215                $row->budget_status_id
216            ));
217        }
218
219        if ($bad !== []) {
220            $this->line('  → not auto-fixed: the intended series/sequence cannot be inferred.');
221            $this->line('    Get the correct codigo from IFEX and set it, or leave them.');
222        }
223
224        return $bad;
225    }
226
227    /**
228     * References held by more than one row.
229     *
230     * Uses a binary comparison so case-variants are counted as the distinct
231     * strings they are — the ticket's query 2 uses the column's default
232     * (case-insensitive) collation, so run this after --apply for the two to
233     * agree.
234     *
235     * @return array<string, array<int, object>>
236     */
237    private function reportCollisions(): array
238    {
239        $refs = $this->baseQuery()
240            ->selectRaw('internal_quote_id COLLATE utf8mb4_bin ref, COUNT(*) c')
241            ->groupBy('ref')
242            ->havingRaw('COUNT(*) > 1')
243            ->pluck('ref')
244            ->all();
245
246        $this->newLine();
247        $this->line('Collisions: '.count($refs).' reference(s) held by more than one row');
248
249        if ($refs === []) {
250            return [];
251        }
252
253        $families = [];
254        foreach ($refs as $ref) {
255            $rows = $this->baseQuery()
256                ->whereRaw('internal_quote_id COLLATE utf8mb4_bin = ?', [$ref])
257                ->orderBy('id')
258                ->get(['id', 'internal_quote_id', 'amount', 'budget_status_id', 'issue_date', 'created_at', 'updated_at']);
259
260            $families[$ref] = $rows->all();
261
262            if (! $this->option('collisions')) {
263                continue;
264            }
265
266            $this->newLine();
267            $this->line("  <fg=yellow>{$ref}</> — ".$rows->count().' rows');
268
269            foreach ($rows as $row) {
270                $logs = DB::table('tbl_quotations_log')->where('quotation_id', $row->id)->count();
271                $this->line(sprintf(
272                    '    id %-8s amount %12s  status %-3s issued %s  created %s  log rows %s',
273                    $row->id,
274                    number_format((float) $row->amount, 2),
275                    $row->budget_status_id,
276                    $row->issue_date ?? 'NULL',
277                    $row->created_at ?? 'NULL',
278                    $logs
279                ));
280            }
281
282            // Rule 6: what each possible resolution would do to the total.
283            $amounts = array_map(fn ($r) => (float) $r->amount, $rows->all());
284            $this->line(sprintf(
285                '    → keeping one row would change the issued total by %s € (sum %s, max %s)',
286                number_format(max($amounts) - array_sum($amounts), 2),
287                number_format(array_sum($amounts), 2),
288                number_format(max($amounts), 2)
289            ));
290            $this->line('    → keeping BOTH and re-keying the later one as '
291                .IfexReference::withVersion((string) $ref, 1).' changes it by 0.00 €');
292        }
293
294        if (! $this->option('collisions')) {
295            $this->line('  (re-run with --collisions for the per-row breakdown)');
296        }
297
298        return $families;
299    }
300}