feat(migration): import prior periods so a closed year can be shown on its own
Build and Push Images / Build jorgecuadros-web (push) Successful in 1m43s
Build and Push Images / Build jorgecuadros-api (push) Successful in 2m19s

Legacy ran a year-end corte: it summed the closing year, wrote that total back
as each customer's Jan-1 BALANCE FORWARD, and started the next year clean. The
platform inherited those opening rows but never the years behind them — only
the current year's charges were ever staged, so every prior year held receipts
and no bills. Rendering one would have shown a customer credits with nothing
owed against them, which is worse than showing nothing.

The archives are whole-database Access snapshots named for the period they
hold, so `2025.accdb` is discovered by filename, staged, and loaded through the
existing DATOS2 branch — a snapshot's `datos2` is the identical shape, one year
older. Only the ledger and DATGRAL come out of a snapshot; everything else in
it is a year-stale copy of a live table. The cash side is deliberately left
behind: EFECTIVO is a lifetime journal, so the snapshot's copy is a subset of
the live one and importing it would double-book every prior-year receipt.

Period travels with the row, in legacySourceTable as `datos2@2025`. That tag,
not the date, is what a year view should filter on: the archives are not
cleanly bounded (2025 carries ten undated rows and two dated into 2026) and
legacy never filtered by date either — its reader is `SELECT ... FROM \`2025\``.
The tag also keeps legacyId safe, since it is a positional ordinal that
restarts at 0 in every archive and would otherwise collide row-for-row.

Two guards, because attaching a prior year by NUMid is the one thing here that
can go quietly wrong:

  - Reissued numbers are skipped, not imported. Comparing each archive's
    DATGRAL against the live one, 13 names moved since 2025 and 40 since 2024;
    most are the same customer re-described, but a few are a different
    household holding a recycled number, and filing their ledger under the new
    owner would show a stranger's charges. Sharing any word of three or more
    characters separates a rename from a reissue. Names are compared
    legacy-to-legacy: `customers.name` has been through blank-name recovery,
    and comparing to it reported 121 drifts where there are 13.
  - Every period is checked against the corte identity it must satisfy —
    SUM(year N) == BALANCE FORWARD(N+1) — and the result is reported per year.
    A truncated export, a file dropped under the wrong year, or a botched
    customer match all fail loudly here. 2025 reconciles 1,159/1,167 (99.3%)
    and 2024 1,144/1,156 (99.0%); the recycle guard raised 2024 from 98.2%.

Balances are untouched: BALANCE_FLOOR_JOIN floors on the newest BALANCE FORWARD
per customer, so rows behind it are already excluded from every balance read.

Uploads go through the existing ingest endpoint, allowlisted by an anchored
`AAAA.accdb` pattern that also keeps a caller-supplied name inside the ingest
directory. The Operaciones page grows an entry point for an archive that has no
row yet, reading the period off the chosen file's own name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-19 15:26:58 -07:00
co-authored by Claude Opus 5
parent 9973488330
commit 29ae9fa5bc
7 changed files with 405 additions and 18 deletions
+58 -4
View File
@@ -68,6 +68,7 @@ function Operaciones() {
const [starting, setStarting] = useState(false);
const fileInputs = useRef<Record<string, HTMLInputElement | null>>({});
const periodInput = useRef<HTMLInputElement | null>(null);
const refreshLists = useCallback(() => {
listIngest().then(setIngest).catch(() => setIngest([]));
@@ -143,6 +144,20 @@ function Operaciones() {
}
}
/** Upload a prior-period archive under its own filename. */
async function handleUploadPeriod(file: File | undefined) {
if (!file) return;
if (!/^\d{4}\.accdb$/i.test(file.name)) {
setError(
`"${file.name}" no es un archivo de periodo. Debe llamarse AAAA.accdb, por ejemplo 2025.accdb.`,
);
if (periodInput.current) periodInput.current.value = "";
return;
}
await handleUpload(file.name, file);
if (periodInput.current) periodInput.current.value = "";
}
async function handleDeleteIngest(name: string) {
setError(null);
try {
@@ -197,7 +212,11 @@ function Operaciones() {
else await start("RESTORE", c.file);
}
const ingestReady = (ingest ?? []).every((f) => f.present);
// Only the four fixed Access sources gate a run. Period archives are
// optional extras — having none simply means no prior years are available.
const ingestReady = (ingest ?? [])
.filter((f) => f.periodYear === null)
.every((f) => f.present);
return (
<>
@@ -244,8 +263,9 @@ function Operaciones() {
<div className="card" style={{ padding: 20, marginBottom: 20 }}>
<h2 className="section-title">Carpeta de ingesta</h2>
<p className="inline-form-note">
Los cuatro archivos originales de Access. La reimportación y la
sincronización leen de aquí. Tamaño máximo por archivo: {formatBytes(INGEST_MAX_BYTES)}.
Los cuatro archivos originales de Access, más los archivos de periodos
anteriores. La reimportación y la sincronización leen de aquí. Tamaño
máximo por archivo: {formatBytes(INGEST_MAX_BYTES)}.
</p>
<div className="tx-scroll">
<table className="tx-table">
@@ -262,7 +282,14 @@ function Operaciones() {
{(ingest ?? []).map((f) => (
<Fragment key={f.name}>
<tr>
<td className="mono">{f.name}</td>
<td className="mono">
{f.name}
{f.periodYear !== null && (
<span className="badge" style={{ marginLeft: 8 }}>
periodo {f.periodYear}
</span>
)}
</td>
<td>
<span className={`badge ${f.present ? "badge-positive" : "badge-negative"}`}>
{f.present ? "Presente" : "Falta"}
@@ -313,6 +340,33 @@ function Operaciones() {
</tbody>
</table>
</div>
{/* A period archive that has never been uploaded has no row to click,
so it needs its own entry point. The file names itself: the archive
IS `2025.accdb`, and that name is what declares the period, so the
control reads it off the chosen file rather than asking twice. */}
<div className="row-actions" style={{ marginTop: 16 }}>
<input
ref={periodInput}
type="file"
accept=".accdb"
style={{ display: "none" }}
onChange={(e) => handleUploadPeriod(e.target.files?.[0])}
/>
<button
className="btn btn-outline"
type="button"
disabled={uploading !== null}
onClick={() => periodInput.current?.click()}
>
Agregar periodo anterior
</button>
<span className="inline-form-note">
Un archivo de Access por año cerrado, nombrado con su periodo:{" "}
<span className="mono">2025.accdb</span>. Aporta el año anterior al
estado de cuenta; no altera el saldo actual.
</span>
</div>
</div>
{/* Operations */}
+2
View File
@@ -192,6 +192,8 @@ export interface IngestFile {
present: boolean;
size: number | null;
modifiedAt: string | null;
/** Year of a prior-period archive (`2025.accdb`); null on the four fixed sources. */
periodYear: number | null;
}
export interface BackupFile {