Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
6.67% covered (danger)
6.67%
3 / 45
40.00% covered (danger)
40.00%
2 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
IfexReference
6.67% covered (danger)
6.67%
3 / 45
40.00% covered (danger)
40.00%
2 / 5
281.42
0.00% covered (danger)
0.00%
0 / 1
 normalize
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 isValid
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 parse
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 withVersion
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 gaps
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2
3namespace App\Services;
4
5/**
6 * Canonical IFEX budget reference (`tbl_quotations.internal_quote_id` for
7 * `commercial = 'Ifex'`).
8 *
9 * WHY THIS EXISTS
10 * The importer used to store IFEX's `codigo` verbatim: no trimming, no case
11 * normalisation, no format check. That produced the three reference defects in
12 * this ticket — references stored in lowercase (a case-variant of a reference
13 * that already exists is a second row, not the same row), references that parse
14 * under no format at all, and collisions with no way to tell an original from a
15 * revision.
16 *
17 * THE FORMAT (agreed 2026-08-12)
18 *
19 *     ^[0-9]{4}(?:[0-9]{2}[A-Z]|G[0-9]{2})[0-9]{13}(?:-R[0-9]{1,3})?$
20 *      \______/ \_____________________/ \_________/ \_____________/
21 *        year       series (2 shapes)     sequence   version (opt.)
22 *
23 * Two series layouts exist in IFEX and both are legitimate:
24 *   - `YYYY` + `YY` + letter  → e.g. 202626C0000000000905  (C/O/P: correctivos,
25 *     instalaciones, mantenimiento — the budgets Titan imports)
26 *   - `YYYY` + `G`  + `YY`    → e.g. 2026G260000000000051  (series G,
27 *     oportunidades — no longer imported, but 1,002 historical rows exist and
28 *     they are real accepted money, so the format must parse them)
29 *
30 * VERSION. IFEX sends no version/revision field — verified against the live
31 * endpoint, whose payload is exactly: codigo, estado, clienteNombre,
32 * clienteTelefono, clienteMail, fecha, fechaAlta, fechaAceptacion,
33 * fechaUltimaModificacion, baseImponible. Every reference in the system today is
34 * therefore version 0, the original document. The optional `-R<n>` suffix is the
35 * slot a revision occupies **when the same codigo arrives describing a different
36 * document**: instead of overwriting the original (silent data loss) or storing a
37 * second row under an identical reference (a collision), the revision is stored
38 * as `<reference>-R1`, `-R2`, … So the suffix is not decoration — it is the
39 * mechanism that makes collisions representable instead of destructive.
40 *
41 * GAP DETECTION (FIRE-1673). Gaps are computed per series key
42 * (year + series) over the SEQUENCE only; the version is ignored, so a revision
43 * never looks like a missing number and never fills one. See gaps().
44 *
45 * Worked example — parsing the three shapes:
46 *
47 *   202626C0000000000905     → series C · year 2026 · sequence 905   · version 0
48 *   2026G260000000000051     → series G · year 2026 · sequence 51    · version 0
49 *   202626C0000000000905-R2  → series C · year 2026 · sequence 905   · version 2
50 *
51 *   seriesKey() for all three C rows is "2026-26C", so 905 appears once in the
52 *   sequence set regardless of how many revisions exist.
53 */
54class IfexReference
55{
56    /** Canonical pattern. Anchored; used by the importer, the repair command and the verification SQL. */
57    public const PATTERN = '/^([0-9]{4})(?:([0-9]{2})([A-Z])|(G)([0-9]{2}))([0-9]{13})(?:-R([0-9]{1,3}))?$/';
58
59    /**
60     * The same pattern in MySQL REGEXP form, for the ticket's verification query
61     * 3. Kept next to PATTERN so the SQL and the code can never drift.
62     */
63    public const MYSQL_PATTERN = '^[0-9]{4}([0-9]{2}[A-Z]|G[0-9]{2})[0-9]{13}(-R[0-9]{1,3})?$';
64
65    /**
66     * Clean a raw `codigo` into storable form: trim surrounding and inner
67     * whitespace, upper-case. Returns null for an empty value.
68     *
69     * Upper-casing is what stops the case-variant collisions: MySQL's default
70     * collation is case-insensitive, so `202626c…` and `202626C…` compare equal
71     * in a WHERE but are two distinct strings on disk — the row that gets found
72     * by the importer's lookup and the row a human reads are not the same shape.
73     */
74    public static function normalize($raw): ?string
75    {
76        $value = preg_replace('/\s+/', '', (string) ($raw ?? ''));
77
78        return $value === '' ? null : strtoupper($value);
79    }
80
81    /** True when $reference is already canonical. Does NOT normalize first. */
82    public static function isValid(?string $reference): bool
83    {
84        return $reference !== null && preg_match(self::PATTERN, $reference) === 1;
85    }
86
87    /**
88     * Break a canonical reference into its parts. Returns null when it does not
89     * parse — callers treat that as "refuse to store", never as "store anyway".
90     *
91     * @return array{reference: string, year: int, series: string, seriesYear: int, sequence: int, version: int, seriesKey: string}|null
92     */
93    public static function parse(?string $reference): ?array
94    {
95        if ($reference === null || ! preg_match(self::PATTERN, $reference, $m)) {
96            return null;
97        }
98
99        // Either group 2+3 (YY + letter) or group 4+5 (G + YY) matched. Both
100        // alternatives sit before the final group, so PHP fills the losing side
101        // with '' rather than omitting it — no ?? needed here.
102        $isGSeries = $m[4] === 'G';
103        $series = $isGSeries ? 'G' : $m[3];
104        $seriesYear = (int) ($isGSeries ? $m[5] : $m[2]);
105
106        return [
107            'reference' => $reference,
108            'year' => (int) $m[1],
109            'series' => $series,
110            'seriesYear' => $seriesYear,
111            'sequence' => (int) $m[6],
112            // The version group is the LAST one, so an absent -R suffix leaves it
113            // out of $m entirely (unlike group 4 above). No suffix = the
114            // original document, version 0.
115            'version' => isset($m[7]) ? (int) $m[7] : 0,
116            'seriesKey' => $m[1].'-'.str_pad((string) $seriesYear, 2, '0', STR_PAD_LEFT).$series,
117        ];
118    }
119
120    /**
121     * Build the reference for revision $version of $baseReference. Version 0
122     * returns the base reference unchanged, so callers never special-case it.
123     */
124    public static function withVersion(string $baseReference, int $version): string
125    {
126        $base = preg_replace('/-R[0-9]{1,3}$/', '', $baseReference);
127
128        return $version > 0 ? $base.'-R'.$version : $base;
129    }
130
131    /**
132     * FIRE-1673 gap detection: the sequence numbers missing from each series.
133     *
134     * Versions collapse onto their sequence (a revision is the same document, so
135     * it must neither create a gap nor fill one), and unparseable references are
136     * reported separately rather than silently skipped — a reference nobody can
137     * parse is exactly the kind of thing that hides a missing number.
138     *
139     * @param  iterable<int, string>  $references
140     * @return array{series: array<string, array{min: int, max: int, present: int, missing: array<int, int>}>, unparseable: array<int, string>}
141     */
142    public static function gaps(iterable $references): array
143    {
144        $sequences = [];
145        $unparseable = [];
146
147        foreach ($references as $reference) {
148            $parsed = self::parse(self::normalize($reference));
149            if ($parsed === null) {
150                $unparseable[] = (string) $reference;
151
152                continue;
153            }
154            // A set, so revisions of the same sequence count once.
155            $sequences[$parsed['seriesKey']][$parsed['sequence']] = true;
156        }
157
158        $series = [];
159        foreach ($sequences as $key => $set) {
160            $present = array_keys($set);
161            sort($present);
162            $min = $present[0];
163            $max = $present[count($present) - 1];
164
165            $missing = [];
166            foreach (range($min, $max) as $n) {
167                if (! isset($set[$n])) {
168                    $missing[] = $n;
169                }
170            }
171
172            $series[$key] = [
173                'min' => $min,
174                'max' => $max,
175                'present' => count($present),
176                'missing' => $missing,
177            ];
178        }
179
180        ksort($series);
181
182        return ['series' => $series, 'unparseable' => $unparseable];
183    }
184}