Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
031b13f8c8 | ||
|
|
2cf07ed5ee | ||
|
|
36158ae761 | ||
|
|
fa38ff581e | ||
|
|
c4213aa697 | ||
|
|
f7507f2370 | ||
|
|
2f9a9afc0d | ||
|
|
7e71a993d0 | ||
|
|
aa5867c8ea | ||
|
|
5549a1e0cf | ||
|
|
c6feae9522 | ||
|
|
93f817158e | ||
|
|
29ae9fa5bc | ||
|
|
9973488330 | ||
|
|
75dcbc11b8 | ||
|
|
9929a9a3ac |
No files matched your search
+2
-1
@@ -22,12 +22,13 @@ OPS_DB_ADMIN_USER=
|
||||
OPS_DB_ADMIN_PASSWORD=
|
||||
|
||||
# Company info — printed in the header of every report (PDF + browser
|
||||
# print). Leave blank to use the placeholders. COMPANY_LOGO_PATH is
|
||||
# print). Leave blank to use the defaults in company.ts. COMPANY_LOGO_PATH is
|
||||
# optional; when unset the API falls back to apps/api/assets/company_logo.png.
|
||||
COMPANY_NAME=Jorge Cuadros & Asociados
|
||||
COMPANY_ADDRESS_LINE1=
|
||||
COMPANY_ADDRESS_LINE2=
|
||||
COMPANY_CITY_STATE=
|
||||
COMPANY_MAILING_ADDRESS=
|
||||
COMPANY_PHONE=
|
||||
COMPANY_EMAIL=
|
||||
COMPANY_TAX_ID=
|
||||
|
||||
@@ -25,6 +25,10 @@
|
||||
# through this workflow at all.
|
||||
# 4. app (api + web) the new images.
|
||||
# 5. verify ask the running API what it actually is.
|
||||
# 6. prune images reclaim the superseded api/web images. LAST, and
|
||||
# after verify: Docker will not prune an image a
|
||||
# container references, so the running stack is what
|
||||
# protects the release we just shipped.
|
||||
#
|
||||
# Rollback = re-dispatch with an older `tag`. That rolls back CODE only; the
|
||||
# schema stays forward. This is exactly why every schema change must be
|
||||
@@ -386,3 +390,24 @@ jobs:
|
||||
echo "dispatched '$WANT'; tiers report '$API_VER' (not directly comparable)"
|
||||
;;
|
||||
esac
|
||||
|
||||
# --- housekeeping ------------------------------------------------------
|
||||
# Runs LAST, and only after the verify step proved the new containers are
|
||||
# up. See deploy/scripts/prune-images.mjs: Docker refuses to prune an
|
||||
# image a container references, so "the stack is running" is what makes
|
||||
# the current images safe. Pruning earlier would have nothing holding
|
||||
# them.
|
||||
#
|
||||
# continue-on-error: reclaiming disk is not what the deploy is for. A
|
||||
# prune that fails leaves a fat host, not a broken release.
|
||||
- name: Prune unused images
|
||||
continue-on-error: true
|
||||
env:
|
||||
PORTAINER_URL: ${{ secrets.PORTAINER_URL_GALACTUS }}
|
||||
PORTAINER_API_KEY: ${{ secrets.PORTAINER_API_KEY_GALACTUS }}
|
||||
PORTAINER_ENDPOINT_ID: ${{ secrets.PORTAINER_ENDPOINT_ID_GALACTUS }}
|
||||
# Grace window. Keeps the previous few releases on disk so a rollback
|
||||
# dispatch is a stack swap instead of a re-pull.
|
||||
KEEP_HOURS: "168"
|
||||
NODE_TLS_REJECT_UNAUTHORIZED: "0"
|
||||
run: node deploy/scripts/prune-images.mjs
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@jorgecuadros/api",
|
||||
"version": "1.0.23",
|
||||
"version": "1.0.26",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
|
||||
@@ -115,13 +115,26 @@ describe("balance floor", () => {
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* statement() issues two findMany calls: first the period discovery (which
|
||||
* years this customer has an archive for), then the statement rows. Select
|
||||
* the rows query by its shape so adding another lookup later moves nothing
|
||||
* here — the previous version indexed call 0 and broke the moment period
|
||||
* support landed.
|
||||
*/
|
||||
function rowsQuery(findMany: jest.Mock) {
|
||||
const call = findMany.mock.calls.find((c) => c[0]?.orderBy);
|
||||
if (!call) throw new Error("statement() issued no ordered rows query");
|
||||
return call[0];
|
||||
}
|
||||
|
||||
it("bounds the statement at the floor, inclusive", async () => {
|
||||
const floor = new Date("2026-01-01T00:00:00Z");
|
||||
const { service, findMany } = serviceWith(floor);
|
||||
|
||||
await service.statement("c1");
|
||||
|
||||
expect(findMany.mock.calls[0][0].where).toMatchObject({
|
||||
expect(rowsQuery(findMany).where).toMatchObject({
|
||||
customerId: "c1",
|
||||
transactionDate: { gte: floor },
|
||||
});
|
||||
@@ -132,23 +145,44 @@ describe("balance floor", () => {
|
||||
|
||||
await service.statement("c1");
|
||||
|
||||
expect(findMany.mock.calls[0][0].where).not.toHaveProperty(
|
||||
"transactionDate",
|
||||
);
|
||||
expect(rowsQuery(findMany).where).not.toHaveProperty("transactionDate");
|
||||
});
|
||||
|
||||
it("keeps the source-table exclusion alongside the floor", async () => {
|
||||
// The two guards answer different questions — one reproduces legacy's
|
||||
// DATOS2-only materialization, the other drops superseded history — and
|
||||
// dropping either one changes the customer's balance.
|
||||
// The three guards answer different questions — one windows imported
|
||||
// periods, one drops the cash receipt book the ledger already posts, the
|
||||
// floor drops superseded history — and dropping any one of them changes
|
||||
// the customer's balance.
|
||||
const { service, findMany } = serviceWith(new Date("2026-01-01T00:00:00Z"));
|
||||
|
||||
await service.statement("c1");
|
||||
|
||||
const where = findMany.mock.calls[0][0].where;
|
||||
expect(where.OR).toEqual([
|
||||
const where = rowsQuery(findMany).where;
|
||||
// Imported periods are windowed rather than excluded: history below the
|
||||
// year start (the only carry a floored-by-archive customer has), never
|
||||
// at or above it (those rows sit inside the next BALANCE FORWARD).
|
||||
expect(where.AND).toEqual([
|
||||
{
|
||||
OR: [
|
||||
{ legacySourceTable: null },
|
||||
{ legacySourceTable: { notIn: expect.arrayContaining(["EFECTIVO"]) } },
|
||||
{ legacySourceTable: { not: { startsWith: "datos2@" } } },
|
||||
{ transactionDate: { lt: expect.any(Date) } },
|
||||
],
|
||||
},
|
||||
// The cash journal, qualified by the database it came from — the
|
||||
// insurance line has its own EFECTIVO and that one is a real ledger.
|
||||
{
|
||||
OR: [
|
||||
{ legacySourceDb: null },
|
||||
{ legacySourceDb: { not: "UTILITIES" } },
|
||||
{ legacySourceTable: null },
|
||||
{
|
||||
legacySourceTable: {
|
||||
notIn: expect.arrayContaining(["EFECTIVO"]),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -119,10 +119,23 @@ export class BillingController {
|
||||
return this.billing.byCheck(n);
|
||||
}
|
||||
|
||||
/** One customer's full statement across both business lines. */
|
||||
/**
|
||||
* One customer's statement across both business lines, for one period.
|
||||
*
|
||||
* `year` omitted means the current one. Any earlier year is served from its
|
||||
* imported archive; the response carries `availableYears` so the caller can
|
||||
* offer only the periods this customer actually has.
|
||||
*/
|
||||
@Get("customers/:id")
|
||||
statement(@Param("id") id: string) {
|
||||
return this.billing.statement(id);
|
||||
statement(@Param("id") id: string, @Query("year") year?: string) {
|
||||
let parsed: number | undefined;
|
||||
if (year !== undefined && year !== "") {
|
||||
parsed = Number(year);
|
||||
if (!Number.isInteger(parsed)) {
|
||||
throw new BadRequestException("year debe ser un año de cuatro dígitos");
|
||||
}
|
||||
}
|
||||
return this.billing.statement(id, parsed);
|
||||
}
|
||||
|
||||
/** Cross-customer movement browser. */
|
||||
|
||||
@@ -210,18 +210,47 @@ export const BALANCE_FLOOR_JOIN = Prisma.sql`
|
||||
export const NOT_SUPERSEDED = Prisma.sql`(bfloor.floorDate IS NULL OR t.transactionDate >= bfloor.floorDate)`;
|
||||
|
||||
/**
|
||||
* Source tables excluded from the customer-facing statement.
|
||||
* `legacySourceTable` of an imported prior period.
|
||||
*
|
||||
* The legacy portal's `datosfreak` table was materialized from DATOS2 only
|
||||
* (`objects.json:1358`), so the customer's "current balance" never saw
|
||||
* EFECTIVO / EFECTIVO FM3 / CHEQUE FM3 / EFECTIVO_BACKUP cash receipts, nor
|
||||
* the IVA 2015 snapshot. The unified `transactions` table has all of them, so
|
||||
* the statement must drop them to match the legacy number the customer has
|
||||
* been quoted for years. The staff-facing balances worklist and movement
|
||||
* browser keep them — they're real money, just tracked separately
|
||||
* (FM3 = visa fee stream, EFECTIVO = cash receipt stream).
|
||||
* A closed year arrives as its own Access snapshot and is tagged rather than
|
||||
* dated (see migration/transform_transactions.py). The tag is what a period
|
||||
* view filters on: the archives are not cleanly date-bounded — 2025 carries
|
||||
* rows dated into 2026 — and legacy did not filter by date either, it selected
|
||||
* `FROM \`2025\``. Filtering on provenance reproduces the legacy period exactly.
|
||||
*/
|
||||
const STATEMENT_EXCLUDED_SOURCE_TABLES: readonly string[] = [
|
||||
export const periodSourceTable = (year: number) => `datos2@${year}`;
|
||||
|
||||
/** Matches any imported period tag, for discovering which years a customer has. */
|
||||
export const PERIOD_TABLE_PREFIX = "datos2@";
|
||||
|
||||
/**
|
||||
* The legacy cash receipt book — a journal, not a ledger.
|
||||
*
|
||||
* `EFECTIVO` is the office's numbered receipt pad: money is handed over the
|
||||
* counter, a folio is written, and the same receipt is then *posted* to the
|
||||
* utilities ledger (`DATOS2`) as reference `C<folio>`. Legacy summed the ledger
|
||||
* alone — `ws/v2/lib/ledger_repository.php` reads `datosfreak`, which is
|
||||
* materialized from DATOS2 only (`objects.json:1358`). The migration flattened
|
||||
* both tables into one `transactions` table, so anything summing a customer's
|
||||
* rows counts every cash receipt twice.
|
||||
*
|
||||
* Verified against the live legacy database on 2026-08-20: of the 297 receipts
|
||||
* written in 2026, 296 carry a matching DATOS2 posting. Only folio 13536 (CL
|
||||
* 717, $400 USD) has no posting anywhere, and it wants a human's eyes rather
|
||||
* than a code change. Six receipts post converted to pesos under a mistyped
|
||||
* folio, which is why matching on folio and amount found fewer duplicate pairs
|
||||
* than actually exist — a reason to exclude the whole journal rather than to
|
||||
* exclude a list of confirmed pairs.
|
||||
*
|
||||
* THE DATABASE QUALIFIER IS LOAD-BEARING. `SEGUROS 16_be` keeps its own table
|
||||
* also called `EFECTIVO`, and that one is the insurance line's *only* ledger —
|
||||
* nothing posts it anywhere else. Excluding by table name alone erases the
|
||||
* whole insurance balance: 55,444.95 USD and 63,957.78 MXN across 102
|
||||
* customers, 99 of whom have no other rows at all.
|
||||
*/
|
||||
export const CASH_JOURNAL_SOURCE_DB = "UTILITIES";
|
||||
|
||||
export const CASH_JOURNAL_SOURCE_TABLES: readonly string[] = [
|
||||
"EFECTIVO",
|
||||
"EFECTIVO_BACKUP",
|
||||
"EFECTIVO FM3",
|
||||
@@ -229,6 +258,62 @@ const STATEMENT_EXCLUDED_SOURCE_TABLES: readonly string[] = [
|
||||
"IVA 2015",
|
||||
];
|
||||
|
||||
/**
|
||||
* Prisma form of the cash-journal exclusion.
|
||||
*
|
||||
* Spelled as a positive OR on purpose. `notIn` alone compiles to SQL `NOT IN`,
|
||||
* and `NULL NOT IN (...)` is NULL rather than true, so every app-captured row
|
||||
* (no `legacySourceTable`) would silently vanish. Same for the database test.
|
||||
*/
|
||||
export const notCashJournal = (): Prisma.TransactionWhereInput => ({
|
||||
OR: [
|
||||
{ legacySourceDb: null },
|
||||
{ legacySourceDb: { not: CASH_JOURNAL_SOURCE_DB } },
|
||||
{ legacySourceTable: null },
|
||||
{ legacySourceTable: { notIn: [...CASH_JOURNAL_SOURCE_TABLES] } },
|
||||
],
|
||||
});
|
||||
|
||||
/** Raw-SQL form, for the aggregate queries that cannot use Prisma's builder. */
|
||||
export const NOT_CASH_JOURNAL = Prisma.sql`(
|
||||
t.legacySourceDb IS NULL
|
||||
OR t.legacySourceDb <> ${CASH_JOURNAL_SOURCE_DB}
|
||||
OR t.legacySourceTable IS NULL
|
||||
OR t.legacySourceTable NOT IN (${Prisma.join([
|
||||
...CASH_JOURNAL_SOURCE_TABLES,
|
||||
])}))`;
|
||||
|
||||
/**
|
||||
* Keeps an imported prior period out of the *current* period, NULL-safely.
|
||||
*
|
||||
* The balance floor does not settle the archives on its own, in both
|
||||
* directions. A customer whose newest BALANCE FORWARD lives *inside* an archive
|
||||
* floors at that archive's own January 1st, so every row of it clears the floor
|
||||
* — and that is correct, because below the year start the archive is the only
|
||||
* carry there is. At or above the year start it must go: the archives spill a
|
||||
* couple of rows into the following January and those already sit inside the
|
||||
* next year's BALANCE FORWARD, which is the sum of the whole archive.
|
||||
*
|
||||
* Spelled as a positive OR for the same NULL reason as above.
|
||||
*/
|
||||
export const archiveIsHistorySql = (yearStart: Date) => Prisma.sql`(
|
||||
t.legacySourceTable IS NULL
|
||||
OR t.legacySourceTable NOT LIKE ${`${PERIOD_TABLE_PREFIX}%`}
|
||||
OR t.transactionDate < ${yearStart})`;
|
||||
|
||||
/** January 1st of the running year, UTC — the current period's lower bound. */
|
||||
export const currentYearStart = () =>
|
||||
new Date(Date.UTC(new Date().getUTCFullYear(), 0, 1));
|
||||
|
||||
/**
|
||||
* What a balance sums over beyond "not voided": the cash journal out, the
|
||||
* archives kept to history. Shared by `balances()`, `stats()` and the reports,
|
||||
* so a customer's balance reads the same on every screen that quotes one.
|
||||
* Pair it with BALANCE_FLOOR_JOIN + NOT_SUPERSEDED.
|
||||
*/
|
||||
export const balanceScopeSql = () =>
|
||||
Prisma.sql`AND ${NOT_CASH_JOURNAL} AND ${archiveIsHistorySql(currentYearStart())}`;
|
||||
|
||||
@Injectable()
|
||||
export class BillingService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@@ -398,6 +483,14 @@ export class BillingService {
|
||||
async balances(params: BalanceParams) {
|
||||
const { query, page, pageSize, currency, balance, domain, sort } = params;
|
||||
|
||||
// A balance is what the customer owes, so it takes the same rules the
|
||||
// statement takes: the floor, the cash journal, and the archive window.
|
||||
// Without the last two the worklist quoted a different number than the
|
||||
// customer's own statement — NUMid 295 read 14,377.46 against a statement
|
||||
// of 4,377.46, and NUMid 10 read 2,362.20 against -1,137.80, the gap in
|
||||
// each case being a cash receipt already posted to the ledger.
|
||||
const scope = balanceScopeSql();
|
||||
|
||||
const filters: Prisma.Sql[] = [];
|
||||
if (domain) filters.push(Prisma.sql`t.domain = ${domain}`);
|
||||
const txFilter = filters.length
|
||||
@@ -460,7 +553,7 @@ export class BillingService {
|
||||
FROM customers c
|
||||
JOIN transactions t ON t.customerId = c.id
|
||||
${BALANCE_FLOOR_JOIN}
|
||||
WHERE t.voidedAt IS NULL AND t.outstanding = 0 AND ${NOT_SUPERSEDED} ${nameFilter} ${txFilter}
|
||||
WHERE t.voidedAt IS NULL AND t.outstanding = 0 AND ${NOT_SUPERSEDED} ${scope} ${nameFilter} ${txFilter}
|
||||
GROUP BY c.id, c.name, c.nameSource, c.nameMissing, c.city, c.state
|
||||
${having}
|
||||
${orderBy}
|
||||
@@ -476,7 +569,7 @@ export class BillingService {
|
||||
-- Must match the page query's filters exactly, or the total disagrees
|
||||
-- with the rows. (The void exclusion was missing here before the
|
||||
-- outstanding work; a voided-only customer inflated the count.)
|
||||
WHERE t.voidedAt IS NULL AND t.outstanding = 0 AND ${NOT_SUPERSEDED} ${nameFilter} ${txFilter}
|
||||
WHERE t.voidedAt IS NULL AND t.outstanding = 0 AND ${NOT_SUPERSEDED} ${scope} ${nameFilter} ${txFilter}
|
||||
GROUP BY c.id
|
||||
${having}
|
||||
) x
|
||||
@@ -523,11 +616,20 @@ export class BillingService {
|
||||
* Two different questions live here and they use different row sets.
|
||||
* `movements`, `ledgerCustomers`, `crossLineCustomers` and the date range are
|
||||
* INVENTORY — what is stored — and count everything not voided. Everything
|
||||
* under `byCurrency` / `byDomain` is a BALANCE, so it applies NOT_SUPERSEDED
|
||||
* and drops rows an opening balance already accounts for. The four aggregates
|
||||
* moved from Prisma groupBy to raw SQL to express that join; groupBy cannot.
|
||||
* under `byCurrency` / `byDomain` is a BALANCE, so it takes the same scope
|
||||
* `balances()` takes — the opening-balance floor, the cash journal and the
|
||||
* archive window — and the book has to agree with the worklist that sits
|
||||
* under it. The four aggregates moved from Prisma groupBy to raw SQL to
|
||||
* express that join; groupBy cannot.
|
||||
*
|
||||
* KNOWN DIVERGENCE, left deliberately: these three do not drop outstanding
|
||||
* rows, while `balances()` does. Reconciling them moves the book by about
|
||||
* 1.95M MXN and turns on whether an unfunded charge is owed by the customer,
|
||||
* which is the client's call and not settled yet.
|
||||
*/
|
||||
async stats() {
|
||||
const scope = balanceScopeSql();
|
||||
|
||||
const [movements, ledgerCustomers] = await Promise.all([
|
||||
this.prisma.transaction.count({ where: NOT_VOIDED }),
|
||||
this.prisma.transaction
|
||||
@@ -559,7 +661,7 @@ export class BillingService {
|
||||
SUM(t.amount > 0) AS creditCount
|
||||
FROM transactions t
|
||||
${BALANCE_FLOOR_JOIN}
|
||||
WHERE t.voidedAt IS NULL AND ${NOT_SUPERSEDED}
|
||||
WHERE t.voidedAt IS NULL AND ${NOT_SUPERSEDED} ${scope}
|
||||
GROUP BY t.currency
|
||||
`;
|
||||
|
||||
@@ -575,7 +677,7 @@ export class BillingService {
|
||||
SUM(t.amount) AS net, COUNT(*) AS count
|
||||
FROM transactions t
|
||||
${BALANCE_FLOOR_JOIN}
|
||||
WHERE t.voidedAt IS NULL AND ${NOT_SUPERSEDED}
|
||||
WHERE t.voidedAt IS NULL AND ${NOT_SUPERSEDED} ${scope}
|
||||
GROUP BY t.domain, t.currency
|
||||
`;
|
||||
|
||||
@@ -596,7 +698,7 @@ export class BillingService {
|
||||
SELECT t.customerId, t.currency, SUM(t.amount) AS bal
|
||||
FROM transactions t
|
||||
${BALANCE_FLOOR_JOIN}
|
||||
WHERE t.voidedAt IS NULL AND ${NOT_SUPERSEDED}
|
||||
WHERE t.voidedAt IS NULL AND ${NOT_SUPERSEDED} ${scope}
|
||||
GROUP BY t.customerId, t.currency
|
||||
) x
|
||||
GROUP BY currency
|
||||
@@ -701,16 +803,22 @@ export class BillingService {
|
||||
/**
|
||||
* One customer's statement across both business lines.
|
||||
*
|
||||
* Scoped to the current calendar year and listed oldest-first, matching the
|
||||
* legacy EDO CUENTA report the office has printed for years: an opening
|
||||
* balance at the top, then the year's movements in the order they happened.
|
||||
* Scoped to one calendar year and listed oldest-first, matching the legacy
|
||||
* EDO CUENTA report the office has printed for years: an opening balance at
|
||||
* the top, then the year's movements in the order they happened.
|
||||
*
|
||||
* `year` selects the period. The current year is read from the live tables;
|
||||
* any earlier year is read from its imported archive, which legacy kept as a
|
||||
* separate table and this reads by its `datos2@YYYY` tag. `availableYears`
|
||||
* reports which periods this customer actually has, so a caller never offers
|
||||
* a year that would render empty.
|
||||
*
|
||||
* Returns the *whole* year rather than a page of it: the heaviest customer
|
||||
* carries 365 movements (mean 26), and a running balance is meaningless if
|
||||
* the client only holds a slice. The running balance is accumulated per
|
||||
* currency in chronological order, with each row's balance-after attached.
|
||||
*/
|
||||
async statement(customerId: string) {
|
||||
async statement(customerId: string, year?: number) {
|
||||
const customer = await this.prisma.customer.findUnique({
|
||||
where: { id: customerId },
|
||||
select: {
|
||||
@@ -734,6 +842,49 @@ export class BillingService {
|
||||
throw new NotFoundException(`Customer ${customerId} not found`);
|
||||
}
|
||||
|
||||
// Which periods this customer has. The current year is always offered —
|
||||
// it is the live ledger even when empty — and each imported archive adds
|
||||
// the year it holds.
|
||||
const archives = await this.prisma.transaction.findMany({
|
||||
where: {
|
||||
customerId,
|
||||
voidedAt: null,
|
||||
legacySourceTable: { startsWith: PERIOD_TABLE_PREFIX },
|
||||
},
|
||||
distinct: ["legacySourceTable"],
|
||||
select: { legacySourceTable: true },
|
||||
});
|
||||
const thisYear = new Date().getUTCFullYear();
|
||||
const archiveYears = archives
|
||||
.map((a) => Number(a.legacySourceTable?.slice(PERIOD_TABLE_PREFIX.length)))
|
||||
.filter((y) => Number.isInteger(y) && y < thisYear);
|
||||
const availableYears = [...new Set([thisYear, ...archiveYears])].sort(
|
||||
(a, b) => b - a,
|
||||
);
|
||||
|
||||
// An unknown year would silently render as the current one, which reads as
|
||||
// "this customer had no activity in 2019" rather than "there is no 2019".
|
||||
const requested = year ?? thisYear;
|
||||
if (!availableYears.includes(requested)) {
|
||||
throw new NotFoundException(
|
||||
`El cliente no tiene movimientos del periodo ${requested}.`,
|
||||
);
|
||||
}
|
||||
const isArchive = requested !== thisYear;
|
||||
|
||||
//
|
||||
// Deliberately open-ended at the top. A period is a table in legacy, not a
|
||||
// date range, so whatever the office filed in it belongs to it — including
|
||||
// the future-dated rows the current ledger carries (it runs to 2028). An
|
||||
// upper bound would hide them from every view, which is not what legacy did
|
||||
// and not what the office has been reading.
|
||||
//
|
||||
// An archive needs no fold at all: it *is* the period, and its own Jan-1
|
||||
// BALANCE FORWARD row is the carry, listed exactly as legacy listed it.
|
||||
const yearStart = isArchive
|
||||
? new Date(0)
|
||||
: new Date(Date.UTC(requested, 0, 1));
|
||||
|
||||
// One customer, so the balance floor is a single date rather than the
|
||||
// derived table the aggregate queries join. See NOT_SUPERSEDED: rows before
|
||||
// the opening balance are already inside it, and showing them would both
|
||||
@@ -759,22 +910,49 @@ export class BillingService {
|
||||
const rows = await this.prisma.transaction.findMany({
|
||||
where: {
|
||||
customerId,
|
||||
...(isArchive
|
||||
? // An archive is already exactly one period's ledger, so the tag is
|
||||
// the whole filter. The balance floor is deliberately NOT applied:
|
||||
// it exists to stop a later opening balance double-counting the
|
||||
// history it summarizes, and here that history is the thing being
|
||||
// asked for. The exclusion list is moot too — an archive holds only
|
||||
// DATOS2 rows, which is what legacy's year table held.
|
||||
{ legacySourceTable: periodSourceTable(requested) }
|
||||
: {
|
||||
...(floor ? { transactionDate: { gte: floor.transactionDate } } : {}),
|
||||
// NULL-safe exclusion. `notIn` alone compiles to SQL `NOT IN`, and
|
||||
// `NULL NOT IN (...)` is NULL, not true — so every app-captured row
|
||||
// (which has no legacySourceTable) silently vanished from the
|
||||
// statement while still showing in the movement browser. Rows the app
|
||||
// books must appear on the customer's statement, so the null case is
|
||||
// spelled out.
|
||||
// An archive row belongs to this period only as history. Below
|
||||
// the year start it is exactly what `opening` is for, and for the
|
||||
// one customer whose newest BALANCE FORWARD lives *inside* an
|
||||
// archive it is the only carry there is — dropping it outright
|
||||
// understated NUMid 295 by his whole 2025 closing balance, 785.46.
|
||||
//
|
||||
// At or above the year start it must go. The archives spill a
|
||||
// couple of rows into the following January, and those are
|
||||
// already inside the next year's BALANCE FORWARD (which is the
|
||||
// sum of the whole archive), so listing them here would both
|
||||
// double-count and file a closed year's row as current.
|
||||
//
|
||||
// Spelled as a positive OR because `NOT (col LIKE ... AND ...)`
|
||||
// is NULL for an app-captured row, which would drop every one.
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{ legacySourceTable: null },
|
||||
{
|
||||
legacySourceTable: {
|
||||
notIn: STATEMENT_EXCLUDED_SOURCE_TABLES as string[],
|
||||
not: { startsWith: PERIOD_TABLE_PREFIX },
|
||||
},
|
||||
},
|
||||
{ transactionDate: { lt: yearStart } },
|
||||
],
|
||||
},
|
||||
// The cash receipt book is the ledger's own postings written a
|
||||
// second time, so listing it here would show every counter
|
||||
// payment twice and double the credit side.
|
||||
notCashJournal(),
|
||||
],
|
||||
}),
|
||||
},
|
||||
orderBy: [{ transactionDate: "asc" }, { id: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
@@ -800,8 +978,6 @@ export class BillingService {
|
||||
// opening balance), the earlier rows still have to be *counted* or every
|
||||
// balance below is wrong, so they are folded into `opening` rather than
|
||||
// listed. That is the same thing a BALANCE FORWARD row does, just computed.
|
||||
const yearStart = new Date(Date.UTC(new Date().getUTCFullYear(), 0, 1));
|
||||
|
||||
const running = new Map<string, Prisma.Decimal>();
|
||||
/** Balance carried into `yearStart`, per currency. */
|
||||
const opening = new Map<string, Prisma.Decimal>();
|
||||
@@ -976,7 +1152,8 @@ export class BillingService {
|
||||
propertyCount: customer._count.properties,
|
||||
policyCount: customer._count.policies,
|
||||
},
|
||||
year: yearStart.getUTCFullYear(),
|
||||
year: requested,
|
||||
availableYears,
|
||||
summary: [...perCurrency.values()].map((c) => {
|
||||
const open = opening.get(c.currency) ?? new Prisma.Decimal(0);
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Prisma } from "@jorgecuadros/database";
|
||||
import {
|
||||
CASH_JOURNAL_SOURCE_DB,
|
||||
CASH_JOURNAL_SOURCE_TABLES,
|
||||
NOT_CASH_JOURNAL,
|
||||
notCashJournal,
|
||||
} from "./billing.service";
|
||||
|
||||
/**
|
||||
* `EFECTIVO` is the office's paper receipt book, and every receipt in it is
|
||||
* also posted to the utilities ledger as `C<folio>`. Both copies were imported
|
||||
* into one `transactions` table, so a balance that reads the journal counts
|
||||
* each counter payment twice — 1,094,347.78 MXN of phantom credit book-wide,
|
||||
* and 3,500.00 of it on NUMid 10 alone.
|
||||
*
|
||||
* These fail silently in the worst way: the numbers stay plausible, they are
|
||||
* just too generous to the customer. Two shapes of mistake are easy to make
|
||||
* here and both are covered below — dropping the database qualifier (which
|
||||
* erases the insurance line's only ledger) and writing the exclusion as a bare
|
||||
* `NOT IN` (which erases every app-captured row).
|
||||
*/
|
||||
describe("cash journal exclusion", () => {
|
||||
describe("raw SQL form", () => {
|
||||
it("binds the source database rather than interpolating it", () => {
|
||||
expect(NOT_CASH_JOURNAL.values).toContain(CASH_JOURNAL_SOURCE_DB);
|
||||
});
|
||||
|
||||
it("qualifies the table names with the database they came from", () => {
|
||||
// `SEGUROS 16_be` has its own EFECTIVO and it is the insurance line's
|
||||
// ONLY ledger — nothing posts it anywhere else. Matching on the table
|
||||
// name alone erases 55,444.95 USD and 63,957.78 MXN across 102 customers.
|
||||
expect(NOT_CASH_JOURNAL.sql).toContain("t.legacySourceDb <>");
|
||||
expect(NOT_CASH_JOURNAL.values).toContain(CASH_JOURNAL_SOURCE_DB);
|
||||
});
|
||||
|
||||
it("spells both null cases out instead of relying on NOT IN", () => {
|
||||
// `NULL NOT IN (...)` is NULL, not true. Without these branches every
|
||||
// app-captured row — the ones staff key in by hand — drops out of the
|
||||
// balance while still showing in the movement browser.
|
||||
expect(NOT_CASH_JOURNAL.sql).toContain("t.legacySourceDb IS NULL");
|
||||
expect(NOT_CASH_JOURNAL.sql).toContain("t.legacySourceTable IS NULL");
|
||||
});
|
||||
|
||||
it("covers the whole cash family, not just EFECTIVO", () => {
|
||||
for (const table of CASH_JOURNAL_SOURCE_TABLES) {
|
||||
expect(NOT_CASH_JOURNAL.values).toContain(table);
|
||||
}
|
||||
});
|
||||
|
||||
it("is a single parenthesised term, safe to AND into a WHERE clause", () => {
|
||||
// It is composed as `... AND ${NOT_CASH_JOURNAL} AND ...`. An unbracketed
|
||||
// OR chain would swallow every condition after it and silently widen the
|
||||
// whole query to the entire table.
|
||||
const sql = NOT_CASH_JOURNAL.sql.trim();
|
||||
expect(sql.startsWith("(")).toBe(true);
|
||||
expect(sql.endsWith(")")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Prisma form", () => {
|
||||
it("matches the raw form's terms so the two cannot drift apart", () => {
|
||||
const branches = notCashJournal().OR as Prisma.TransactionWhereInput[];
|
||||
expect(branches).toEqual([
|
||||
{ legacySourceDb: null },
|
||||
{ legacySourceDb: { not: CASH_JOURNAL_SOURCE_DB } },
|
||||
{ legacySourceTable: null },
|
||||
{ legacySourceTable: { notIn: [...CASH_JOURNAL_SOURCE_TABLES] } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns a fresh object each call", () => {
|
||||
// It is spread into `AND: [...]` arrays that Prisma may mutate; a shared
|
||||
// singleton would leak one query's filters into the next.
|
||||
expect(notCashJournal()).not.toBe(notCashJournal());
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { periodSourceTable } from "./billing.service";
|
||||
|
||||
/**
|
||||
* A closed year is imported as its own tagged set of rows rather than being
|
||||
* identified by date. The tag is written by migration/transform_transactions.py
|
||||
* and read by BillingService.statement, the edo-cuenta-datos report, and the
|
||||
* PHP portal — three places that must agree on the exact string.
|
||||
*/
|
||||
describe("periodSourceTable", () => {
|
||||
it("names the archive the migration writes", () => {
|
||||
expect(periodSourceTable(2025)).toBe("datos2@2025");
|
||||
expect(periodSourceTable(2024)).toBe("datos2@2024");
|
||||
});
|
||||
|
||||
it("stays distinct from the live ledger's own table", () => {
|
||||
// The live table is plain `datos2`. legacyId is a positional ordinal that
|
||||
// restarts at 0 in every archive, so a shared name would collide with the
|
||||
// current year row-for-row on the unique key.
|
||||
expect(periodSourceTable(2025)).not.toBe("datos2");
|
||||
expect(periodSourceTable(2025).startsWith("datos2@")).toBe(true);
|
||||
});
|
||||
|
||||
it("is not matched by the statement's cash-source exclusion list", () => {
|
||||
// STATEMENT_EXCLUDED_SOURCE_TABLES drops the EFECTIVO family to reproduce
|
||||
// legacy's DATOS2-only datosfreak. An archive holds DATOS2 rows, so it must
|
||||
// survive that filter or a prior year renders empty.
|
||||
const excluded = [
|
||||
"EFECTIVO",
|
||||
"EFECTIVO_BACKUP",
|
||||
"EFECTIVO FM3",
|
||||
"CHEQUE FM3",
|
||||
"IVA 2015",
|
||||
];
|
||||
expect(excluded).not.toContain(periodSourceTable(2025));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { CustomersService } from "./customers.service";
|
||||
import { BALANCE_FORWARD_TYPE } from "../billing/billing.service";
|
||||
|
||||
/**
|
||||
* The /clientes/:id ledger card is titled "Estado de cuenta" and links straight
|
||||
* to the statement, so its per-line totals must be the statement's numbers.
|
||||
*
|
||||
* They were a raw lifetime sum — no floor, no source exclusion — which
|
||||
* double-counted the pre-cutover history each BALANCE FORWARD row absorbs.
|
||||
* Importing prior periods made it visibly worse: every closed year is now held
|
||||
* a second time as its own tagged copy, so an unfloored sum adds each one on
|
||||
* top of the opening balance that already contains it.
|
||||
*/
|
||||
describe("customer file ledger card", () => {
|
||||
function serviceWith(floor: Date | null) {
|
||||
const groupBy = jest.fn().mockResolvedValue([]);
|
||||
const prisma = {
|
||||
customer: {
|
||||
findUnique: jest.fn().mockResolvedValue({ id: "c1", transactions: [] }),
|
||||
},
|
||||
transaction: {
|
||||
findFirst: jest
|
||||
.fn()
|
||||
.mockResolvedValue(floor ? { transactionDate: floor } : null),
|
||||
groupBy,
|
||||
},
|
||||
};
|
||||
return {
|
||||
service: new CustomersService(prisma as never),
|
||||
prisma,
|
||||
groupBy,
|
||||
};
|
||||
}
|
||||
|
||||
it("takes the same balance floor the statement takes", async () => {
|
||||
const floor = new Date("2026-01-01T00:00:00Z");
|
||||
const { service, prisma, groupBy } = serviceWith(floor);
|
||||
|
||||
await service.detail("c1");
|
||||
|
||||
expect(prisma.transaction.findFirst).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
type: { nameEn: BALANCE_FORWARD_TYPE },
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(groupBy.mock.calls[0][0].where).toMatchObject({
|
||||
transactionDate: { gte: floor },
|
||||
});
|
||||
});
|
||||
|
||||
it("applies no floor when the customer never had an opening balance", async () => {
|
||||
// 102 customers have no BALANCE FORWARD row at all. Inventing a floor for
|
||||
// them would hide their whole ledger.
|
||||
const { service, groupBy } = serviceWith(null);
|
||||
|
||||
await service.detail("c1");
|
||||
|
||||
expect(groupBy.mock.calls[0][0].where).not.toHaveProperty("transactionDate");
|
||||
});
|
||||
|
||||
it("counts an archive as history but never as current", async () => {
|
||||
// The floor alone is not enough: a customer floored by an archive clears
|
||||
// it with every row of that archive, and the rows archives spill into the
|
||||
// following January clear any floor. But excluding archives outright is
|
||||
// wrong too — below the year start they are the only carry a
|
||||
// floored-by-archive customer has (NUMid 295, 785.46).
|
||||
const { service, groupBy } = serviceWith(new Date("2026-01-01T00:00:00Z"));
|
||||
|
||||
await service.detail("c1");
|
||||
|
||||
const and = groupBy.mock.calls[0][0].where.AND;
|
||||
const rule = and.find((c: { OR?: unknown[] }) =>
|
||||
JSON.stringify(c).includes("datos2@"),
|
||||
);
|
||||
expect(rule.OR).toEqual([
|
||||
{ legacySourceTable: null },
|
||||
{ legacySourceTable: { not: { startsWith: "datos2@" } } },
|
||||
{ transactionDate: { lt: expect.any(Date) } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the cash-source exclusion so it reads like the statement", async () => {
|
||||
const { service, groupBy } = serviceWith(new Date("2026-01-01T00:00:00Z"));
|
||||
|
||||
await service.detail("c1");
|
||||
|
||||
const and = groupBy.mock.calls[0][0].where.AND;
|
||||
const sourceRule = and.find((c: { OR?: unknown[] }) =>
|
||||
JSON.stringify(c).includes("EFECTIVO"),
|
||||
);
|
||||
expect(sourceRule).toBeDefined();
|
||||
});
|
||||
|
||||
it("drops outstanding rows, as every balance does", async () => {
|
||||
const { service, groupBy } = serviceWith(null);
|
||||
|
||||
await service.detail("c1");
|
||||
|
||||
expect(groupBy.mock.calls[0][0].where).toMatchObject({
|
||||
outstanding: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps archives out of the year's movement list too", async () => {
|
||||
// datos2@2024 carries rows dated into 2026; a date test alone would show
|
||||
// them as current-year movements next to the live ledger's own copy.
|
||||
const { service, prisma } = serviceWith(null);
|
||||
|
||||
await service.detail("c1");
|
||||
|
||||
const include = prisma.customer.findUnique.mock.calls[0][0].include;
|
||||
expect(include.transactions.where.OR).toEqual([
|
||||
{ legacySourceTable: null },
|
||||
{ legacySourceTable: { not: { startsWith: "datos2@" } } },
|
||||
// Nothing below yearStart reaches this list, so the third branch never
|
||||
// admits an archive row here — it is carried for one shared rule.
|
||||
{ transactionDate: { lt: expect.any(Date) } },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,35 @@ import { Prisma } from "@jorgecuadros/database";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { CreateCustomerDto } from "./create-customer.dto";
|
||||
import { UpdateCustomerDto } from "./update-customer.dto";
|
||||
import {
|
||||
BALANCE_FORWARD_TYPE,
|
||||
notCashJournal,
|
||||
PERIOD_TABLE_PREFIX,
|
||||
} from "../billing/billing.service";
|
||||
|
||||
/**
|
||||
* Keeps an imported prior period out of the *current* period, NULL-safely.
|
||||
*
|
||||
* A closed year is imported as its own tagged copy (`datos2@2025`). Below the
|
||||
* year start it is history and counts — for the one customer whose newest
|
||||
* BALANCE FORWARD lives inside an archive it is the only carry there is, and
|
||||
* dropping it understated NUMid 295 by his entire 2025 closing balance. At or
|
||||
* above the year start it must go: the archives spill a couple of rows into the
|
||||
* following January, and those already sit inside the next year's BALANCE
|
||||
* FORWARD, which is the sum of the whole archive.
|
||||
*
|
||||
* Spelled as a positive OR because `NOT (col LIKE ... AND ...)` evaluates to
|
||||
* NULL for an app-captured row (no legacySourceTable), dropping every one.
|
||||
*/
|
||||
const archiveIsHistory = (
|
||||
yearStart: Date,
|
||||
): Prisma.TransactionWhereInput => ({
|
||||
OR: [
|
||||
{ legacySourceTable: null },
|
||||
{ legacySourceTable: { not: { startsWith: PERIOD_TABLE_PREFIX } } },
|
||||
{ transactionDate: { lt: yearStart } },
|
||||
],
|
||||
});
|
||||
|
||||
export interface ListParams {
|
||||
query?: string;
|
||||
@@ -96,6 +125,13 @@ export class CustomersService {
|
||||
|
||||
/** Full unified customer view: identity + both business lines + ledger. */
|
||||
async detail(id: string) {
|
||||
// The movement list on the customer file is the same statement the office
|
||||
// prints, so it follows the same rule as BillingService.statement: this
|
||||
// calendar year, oldest-first. No `take` any more — the cap used to hide
|
||||
// the end of a busy customer's year once the order flipped, and a single
|
||||
// year is small (365 rows for the heaviest customer in the book).
|
||||
const yearStart = new Date(Date.UTC(new Date().getUTCFullYear(), 0, 1));
|
||||
|
||||
const customer = await this.prisma.customer.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
@@ -117,8 +153,21 @@ export class CustomersService {
|
||||
},
|
||||
},
|
||||
transactions: {
|
||||
orderBy: { transactionDate: "desc" },
|
||||
take: 100,
|
||||
// Archives are excluded by tag, not by date. They are not cleanly
|
||||
// bounded — datos2@2024 carries rows dated 2022, 2023, 2025 and one
|
||||
// in 2026, datos2@2025 two more — so a date test alone would surface
|
||||
// a closed year's rows in the current year's list, duplicating the
|
||||
// live ledger's own copy of them for three customers.
|
||||
// Archives are kept out by tag, not by date. They are not cleanly
|
||||
// bounded — datos2@2025 carries rows dated into 2026 — so a date test
|
||||
// alone would surface a closed year's rows in the current year's
|
||||
// list. Nothing below yearStart reaches this list anyway, so the
|
||||
// window rule reduces to a plain exclusion here.
|
||||
where: {
|
||||
transactionDate: { gte: yearStart },
|
||||
...archiveIsHistory(yearStart),
|
||||
},
|
||||
orderBy: [{ transactionDate: "asc" }, { id: "asc" }],
|
||||
include: { type: true },
|
||||
},
|
||||
},
|
||||
@@ -130,16 +179,51 @@ export class CustomersService {
|
||||
|
||||
// Ledger totals per domain + currency (the "one statement across both
|
||||
// business lines" payoff), computed in the DB rather than in JS.
|
||||
//
|
||||
// These have to answer the same question BillingService.statement answers,
|
||||
// because this card is titled "Estado de cuenta" and links straight to it —
|
||||
// two screens quoting one customer two different balances is worse than
|
||||
// either number alone. So it takes the same three rules the statement uses:
|
||||
// the balance floor, the cash-source exclusion, and dropping outstanding
|
||||
// rows the office has not paid yet.
|
||||
//
|
||||
// Without the floor these were a raw lifetime sum, double-counting the
|
||||
// pre-cutover history each BALANCE FORWARD row already absorbs. Importing
|
||||
// prior periods made that visibly worse: for NUMid 501 the tiles read
|
||||
// -7,119.29 before the archives landed and -15,270.59 after, against a true
|
||||
// -10,715.29 — the difference being exactly the 2024 and 2025 closing
|
||||
// balances, added a second time on top of the opening row that contains
|
||||
// them.
|
||||
const floor = await this.prisma.transaction.findFirst({
|
||||
where: {
|
||||
customerId: id,
|
||||
voidedAt: null,
|
||||
type: { nameEn: BALANCE_FORWARD_TYPE },
|
||||
},
|
||||
orderBy: { transactionDate: "desc" },
|
||||
select: { transactionDate: true },
|
||||
});
|
||||
|
||||
const summary = await this.prisma.transaction.groupBy({
|
||||
by: ["domain", "currency"],
|
||||
// Exclude voided rows so the per-domain balance matches the statement.
|
||||
where: { customerId: id, voidedAt: null },
|
||||
where: {
|
||||
customerId: id,
|
||||
voidedAt: null,
|
||||
outstanding: false,
|
||||
...(floor ? { transactionDate: { gte: floor.transactionDate } } : {}),
|
||||
// The floor alone does not settle the archives: a customer floored by
|
||||
// an archive clears it with every row of that archive, and the rows
|
||||
// archives spill into the following January clear any floor.
|
||||
AND: [archiveIsHistory(yearStart), notCashJournal()],
|
||||
},
|
||||
_sum: { amount: true },
|
||||
_count: { _all: true },
|
||||
});
|
||||
|
||||
return {
|
||||
...customer,
|
||||
/** Calendar year the movement list covers. */
|
||||
transactionYear: yearStart.getUTCFullYear(),
|
||||
transactionSummary: summary.map((s) => ({
|
||||
domain: s.domain,
|
||||
currency: s.currency,
|
||||
|
||||
@@ -31,6 +31,29 @@ export const INGEST_FILES = [
|
||||
] as const;
|
||||
export type IngestName = (typeof INGEST_FILES)[number];
|
||||
|
||||
/**
|
||||
* A prior-period archive: one Access snapshot per closed year, named for the
|
||||
* period it holds. `2025.accdb` is UTILITIES as it stood when 2025 was cut.
|
||||
*
|
||||
* The filename is the entire declaration of the period — nothing inside the
|
||||
* file names its year, because a snapshot's `datos2` is indistinguishable from
|
||||
* the live one — so this pattern is both the allowlist and the contract. It is
|
||||
* anchored and allows no separator, which is what keeps an upload from
|
||||
* escaping the ingest directory.
|
||||
*/
|
||||
const PERIOD_FILE_RE = /^(\d{4})\.accdb$/i;
|
||||
|
||||
/** Earliest period we will accept, so a typo'd year cannot mint a bogus one. */
|
||||
const PERIOD_MIN_YEAR = 1990;
|
||||
|
||||
export function periodYearOf(name: string): number | null {
|
||||
const m = PERIOD_FILE_RE.exec(name);
|
||||
if (!m) return null;
|
||||
const year = Number(m[1]);
|
||||
if (year < PERIOD_MIN_YEAR || year > new Date().getUTCFullYear()) return null;
|
||||
return year;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefix for every command containing a pipe. Without it the exit status of
|
||||
* `mysqldump | gzip` is gzip's, so a dump that failed immediately still looks
|
||||
@@ -120,19 +143,30 @@ export class OpsService implements OnModuleInit {
|
||||
|
||||
/* -------------------------------------------------------------- ingest */
|
||||
|
||||
private assertIngestName(name: string): IngestName {
|
||||
if (!INGEST_FILES.includes(name as IngestName)) {
|
||||
private assertIngestName(name: string): string {
|
||||
if (INGEST_FILES.includes(name as IngestName)) return name;
|
||||
if (periodYearOf(name) !== null) return name;
|
||||
throw new BadRequestException(
|
||||
`Archivo no permitido. Debe ser uno de: ${INGEST_FILES.join(", ")}`,
|
||||
`Archivo no permitido. Debe ser uno de: ${INGEST_FILES.join(", ")}` +
|
||||
`, o un archivo de periodo anterior con nombre AAAA.accdb (por ejemplo 2025.accdb).`,
|
||||
);
|
||||
}
|
||||
return name as IngestName;
|
||||
}
|
||||
|
||||
async listIngest(): Promise<
|
||||
{ name: string; present: boolean; size: number | null; modifiedAt: string | null }[]
|
||||
{
|
||||
name: string;
|
||||
present: boolean;
|
||||
size: number | null;
|
||||
modifiedAt: string | null;
|
||||
/** Set only on a prior-period archive; null on the four fixed sources. */
|
||||
periodYear: number | null;
|
||||
}[]
|
||||
> {
|
||||
return Promise.all(
|
||||
// The four fixed sources are listed whether present or not — they are
|
||||
// required, so "missing" is the useful state to show. Period archives are
|
||||
// optional and unbounded, so they are listed only once uploaded, newest
|
||||
// year first.
|
||||
const fixed = await Promise.all(
|
||||
INGEST_FILES.map(async (name) => {
|
||||
try {
|
||||
const st = await fs.stat(path.join(this.ingestDir, name));
|
||||
@@ -141,12 +175,46 @@ export class OpsService implements OnModuleInit {
|
||||
present: true,
|
||||
size: st.size,
|
||||
modifiedAt: st.mtime.toISOString(),
|
||||
periodYear: null as number | null,
|
||||
};
|
||||
} catch {
|
||||
return { name, present: false, size: null, modifiedAt: null };
|
||||
return {
|
||||
name,
|
||||
present: false,
|
||||
size: null,
|
||||
modifiedAt: null,
|
||||
periodYear: null as number | null,
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
let entries: string[] = [];
|
||||
try {
|
||||
entries = await fs.readdir(this.ingestDir);
|
||||
} catch {
|
||||
entries = [];
|
||||
}
|
||||
const periods = (
|
||||
await Promise.all(
|
||||
entries
|
||||
.map((name) => ({ name, year: periodYearOf(name) }))
|
||||
.filter((e): e is { name: string; year: number } => e.year !== null)
|
||||
.sort((a, b) => b.year - a.year)
|
||||
.map(async ({ name, year }) => {
|
||||
const st = await fs.stat(path.join(this.ingestDir, name));
|
||||
return {
|
||||
name,
|
||||
present: true,
|
||||
size: st.size,
|
||||
modifiedAt: st.mtime.toISOString(),
|
||||
periodYear: year,
|
||||
};
|
||||
}),
|
||||
)
|
||||
).filter(Boolean);
|
||||
|
||||
return [...fixed, ...periods];
|
||||
}
|
||||
|
||||
async saveIngest(name: string, data: Buffer): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { periodYearOf } from "./ops.service";
|
||||
|
||||
/**
|
||||
* `periodYearOf` is the upload allowlist for prior-period archives, so it is
|
||||
* doing two jobs at once: deciding what counts as a period file, and keeping a
|
||||
* caller-supplied name from escaping the ingest directory. Both are pinned here.
|
||||
*/
|
||||
describe("periodYearOf", () => {
|
||||
it("accepts a four-digit year archive", () => {
|
||||
expect(periodYearOf("2025.accdb")).toBe(2025);
|
||||
expect(periodYearOf("1999.accdb")).toBe(1999);
|
||||
});
|
||||
|
||||
it("is case-insensitive on the extension", () => {
|
||||
expect(periodYearOf("2025.ACCDB")).toBe(2025);
|
||||
});
|
||||
|
||||
it("rejects a path that would escape the ingest directory", () => {
|
||||
// The name is joined onto the ingest path, so anything with a separator or
|
||||
// a parent reference has to fail before it reaches the filesystem.
|
||||
expect(periodYearOf("../2025.accdb")).toBeNull();
|
||||
expect(periodYearOf("../../etc/passwd")).toBeNull();
|
||||
expect(periodYearOf("sub/2025.accdb")).toBeNull();
|
||||
expect(periodYearOf("2025.accdb/../../x")).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects names that only look like a period", () => {
|
||||
expect(periodYearOf("202.accdb")).toBeNull();
|
||||
expect(periodYearOf("20255.accdb")).toBeNull();
|
||||
expect(periodYearOf("2025.mdb")).toBeNull();
|
||||
expect(periodYearOf("copia 2025.accdb")).toBeNull();
|
||||
expect(periodYearOf("2025.accdb.bak")).toBeNull();
|
||||
expect(periodYearOf("UTILITIES.accdb")).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects years outside the plausible range", () => {
|
||||
// A typo'd year would otherwise mint a period nobody can ever reconcile:
|
||||
// there is no BALANCE FORWARD for the year after it to check against.
|
||||
expect(periodYearOf("1889.accdb")).toBeNull();
|
||||
expect(periodYearOf(`${new Date().getUTCFullYear() + 1}.accdb`)).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts the current year, which is the earliest a period can be cut", () => {
|
||||
expect(periodYearOf(`${new Date().getUTCFullYear()}.accdb`)).toBe(
|
||||
new Date().getUTCFullYear(),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -46,6 +46,20 @@ describe("renderRenewalEmail", () => {
|
||||
expect(result.html).toContain("Calle Uno 123");
|
||||
});
|
||||
|
||||
it("omits the premium when the sender did not ask for it", () => {
|
||||
// The unattended sweep quotes no amount: the premium can still be
|
||||
// re-rated at renewal, and a number a robot mailed out is one the office
|
||||
// has to walk back.
|
||||
const result = renderRenewalEmail(letter(), { includePremium: false });
|
||||
|
||||
expect(result.html).not.toContain("Prima");
|
||||
expect(result.html).not.toContain("1,392.00");
|
||||
// Everything else the customer needs is still there.
|
||||
expect(result.html).toContain("POL-123");
|
||||
expect(result.html).toContain("01/09/2026");
|
||||
expect(result.html).toContain("Ana Pérez");
|
||||
});
|
||||
|
||||
it("uses overdue wording for generation three", () => {
|
||||
const result = renderRenewalEmail(letter({ generation: 3 }));
|
||||
|
||||
|
||||
@@ -34,10 +34,23 @@ function row(label: string, value: string): string {
|
||||
return `<tr><th style="padding:8px 12px;text-align:left;background:#f4f4f4;border:1px solid #ddd">${escapeHtml(label)}</th><td style="padding:8px 12px;border:1px solid #ddd">${escapeHtml(value)}</td></tr>`;
|
||||
}
|
||||
|
||||
export function renderRenewalEmail(letter: RenewalLetterRow): {
|
||||
/**
|
||||
* Render one renewal letter.
|
||||
*
|
||||
* `includePremium` decides whether the "Prima" row appears. The unattended
|
||||
* sweep sends without it — an amount quoted by a robot, on a premium that may
|
||||
* still be re-rated at renewal, is a number the office has to walk back — and
|
||||
* every staff-triggered send (the manual barrido and the per-row "Enviar
|
||||
* aviso") keeps it, because a person chose to quote it.
|
||||
*/
|
||||
export function renderRenewalEmail(
|
||||
letter: RenewalLetterRow,
|
||||
options: { includePremium?: boolean } = {},
|
||||
): {
|
||||
subject: string;
|
||||
html: string;
|
||||
} {
|
||||
const includePremium = options.includePremium !== false;
|
||||
const expired = letter.generation === 3;
|
||||
const subject = expired
|
||||
? `Póliza vencida: ${letter.policyNumber}`
|
||||
@@ -51,7 +64,7 @@ export function renderRenewalEmail(letter: RenewalLetterRow): {
|
||||
row("Tipo de póliza", letter.policyType),
|
||||
row("Aseguradora", letter.provider),
|
||||
row("Fecha de vencimiento", displayDate(letter.policyTo)),
|
||||
row("Prima", money(premium, letter.currency)),
|
||||
...(includePremium ? [row("Prima", money(premium, letter.currency))] : []),
|
||||
row("Cliente", letter.customerName),
|
||||
row("Correo", letter.customerEmail ?? "No disponible"),
|
||||
row("Teléfono", phone),
|
||||
|
||||
@@ -183,6 +183,50 @@ describe("renewal notices write the shared notification log", () => {
|
||||
expect(prisma.renewalNotice.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("quotes the premium on a staff-triggered sweep but not the scheduled one", async () => {
|
||||
const manual = build({});
|
||||
await manual.service.sweep("user-1");
|
||||
expect(manual.record.mock.calls[0][0].bodySnapshot).toContain("Prima");
|
||||
|
||||
const automatic = build({});
|
||||
await automatic.service.scheduledSweep();
|
||||
const body = automatic.record.mock.calls[0][0].bodySnapshot;
|
||||
// The snapshot has to match the mail that actually went out, or the
|
||||
// office reads a letter the customer never received.
|
||||
expect(body).not.toContain("Prima");
|
||||
expect(body).toContain("700442181");
|
||||
});
|
||||
|
||||
it("scopes a sweep to one aseguradora without advancing the catch-up window", async () => {
|
||||
const { service, prisma, send } = build({});
|
||||
|
||||
const result = await service.sweep("user-1", { providerId: "gmx-id" });
|
||||
|
||||
expect(result.sent).toBe(1);
|
||||
expect(result.providerId).toBe("gmx-id");
|
||||
expect(prisma.policy.findMany.mock.calls[0][0].where).toMatchObject({
|
||||
insuranceProviderId: "gmx-id",
|
||||
});
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
// Only one carrier was mailed, so the days this run covered are still owed
|
||||
// to every other carrier: advancing `lastSuccessfulAt` would move them out
|
||||
// of tomorrow's window and they would never be sent.
|
||||
const release = prisma.scheduledJobState.update.mock.calls.at(-1)?.[0];
|
||||
expect(release.data.lastSuccessfulAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it("advances the catch-up window on a clean unfiltered sweep", async () => {
|
||||
const { service, prisma } = build({});
|
||||
|
||||
await service.sweep("user-1");
|
||||
|
||||
expect(prisma.policy.findMany.mock.calls[0][0].where).not.toHaveProperty(
|
||||
"insuranceProviderId",
|
||||
);
|
||||
const release = prisma.scheduledJobState.update.mock.calls.at(-1)?.[0];
|
||||
expect(release.data.lastSuccessfulAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it("does not fail a delivered notice when the log write throws", async () => {
|
||||
const { service, record } = build({});
|
||||
record.mockRejectedValue(new Error("log table gone"));
|
||||
|
||||
@@ -25,6 +25,13 @@ class RenewalFlagsDto {
|
||||
debug?: boolean;
|
||||
}
|
||||
|
||||
class SweepRenewalsDto extends RenewalFlagsDto {
|
||||
/** Sweep one aseguradora only (GMX, ANA, …). Omitted = todas. */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
providerId?: string;
|
||||
}
|
||||
|
||||
class SendRenewalDto extends RenewalFlagsDto {
|
||||
@IsString()
|
||||
policyId!: string;
|
||||
@@ -43,17 +50,22 @@ export class RenewalsController {
|
||||
constructor(private readonly renewals: RenewalsService) {}
|
||||
|
||||
@Get("pending")
|
||||
pending(@Query("days") days?: string) {
|
||||
pending(
|
||||
@Query("days") days?: string,
|
||||
@Query("providerId") providerId?: string,
|
||||
) {
|
||||
return this.renewals.pending(
|
||||
Math.min(365, Math.max(1, Number(days) || 30)),
|
||||
providerId?.trim() || undefined,
|
||||
);
|
||||
}
|
||||
|
||||
@Post("sweep")
|
||||
@RequireAbility("renewal:send")
|
||||
sweep(@Body() dto: RenewalFlagsDto, @Req() req: Request) {
|
||||
sweep(@Body() dto: SweepRenewalsDto, @Req() req: Request) {
|
||||
return this.renewals.sweep((req.user as { id: string }).id, {
|
||||
debug: dto?.debug,
|
||||
providerId: dto?.providerId,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -84,10 +84,14 @@ export class RenewalsService implements OnModuleInit {
|
||||
|
||||
/** The unattended run always sends for real: `debug` is a per-click switch
|
||||
* in the UI, never persisted, so the schedule cannot inherit a forgotten
|
||||
* test toggle and silently stop mailing customers. */
|
||||
* test toggle and silently stop mailing customers.
|
||||
*
|
||||
* `automatic` is what drops the premium from the letter — see
|
||||
* `renderRenewalEmail`. It is set here and nowhere else, so every sweep a
|
||||
* person clicks still quotes the amount. */
|
||||
async scheduledSweep(): Promise<void> {
|
||||
try {
|
||||
await this.sweep();
|
||||
await this.sweep(undefined, { automatic: true });
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Falló el barrido de renovaciones: ${(error as Error).message}`,
|
||||
@@ -95,7 +99,10 @@ export class RenewalsService implements OnModuleInit {
|
||||
}
|
||||
}
|
||||
|
||||
async pending(days = 30) {
|
||||
/** @param providerId Restrict to one aseguradora. The list has to agree
|
||||
* with what a sweep would send, or the carrier-scoped barrido shows rows it
|
||||
* will not mail. */
|
||||
async pending(days = 30, providerId?: string) {
|
||||
const today = dateInTimeZone(new Date());
|
||||
const state = await this.prisma.scheduledJobState.findUnique({
|
||||
where: { name: JOB_NAME },
|
||||
@@ -111,6 +118,7 @@ export class RenewalsService implements OnModuleInit {
|
||||
item,
|
||||
today,
|
||||
state?.lastSuccessfulAt ?? null,
|
||||
providerId,
|
||||
),
|
||||
})),
|
||||
);
|
||||
@@ -122,8 +130,20 @@ export class RenewalsService implements OnModuleInit {
|
||||
);
|
||||
}
|
||||
|
||||
async sweep(userId?: string, flags: { debug?: boolean } = {}) {
|
||||
/**
|
||||
* @param flags.providerId Sweep only one aseguradora. GMX and ANA are worked
|
||||
* as separate batches by the office, so mixing them in one run is what this
|
||||
* exists to prevent.
|
||||
* @param flags.automatic Set only by the scheduler. Drops the premium from
|
||||
* the letter.
|
||||
*/
|
||||
async sweep(
|
||||
userId?: string,
|
||||
flags: { debug?: boolean; providerId?: string; automatic?: boolean } = {},
|
||||
) {
|
||||
const debug = !!flags.debug;
|
||||
const providerId = flags.providerId?.trim() || undefined;
|
||||
const includePremium = !flags.automatic;
|
||||
const now = new Date();
|
||||
const state = await this.acquireLock(now);
|
||||
|
||||
@@ -145,6 +165,7 @@ export class RenewalsService implements OnModuleInit {
|
||||
cadence,
|
||||
today,
|
||||
state.lastSuccessfulAt,
|
||||
providerId,
|
||||
);
|
||||
eligible += policies.length;
|
||||
|
||||
@@ -157,13 +178,17 @@ export class RenewalsService implements OnModuleInit {
|
||||
await this.recordLog(policy, cadence.generation, "", {
|
||||
status: "SKIPPED_NO_EMAIL",
|
||||
debug,
|
||||
includePremium,
|
||||
});
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.deliver(policy, cadence.generation, to, userId, debug);
|
||||
await this.deliver(policy, cadence.generation, to, userId, {
|
||||
debug,
|
||||
includePremium,
|
||||
});
|
||||
sent++;
|
||||
} catch (error) {
|
||||
failures.push({
|
||||
@@ -182,11 +207,18 @@ export class RenewalsService implements OnModuleInit {
|
||||
failed: failures.length,
|
||||
failures,
|
||||
debug,
|
||||
providerId: providerId ?? null,
|
||||
};
|
||||
// A debug run must not advance `lastSuccessfulAt`: it wrote no
|
||||
// RenewalNotice rows, so the days it "covered" are still owed, and
|
||||
// narrowing tomorrow's window back to a single day would drop them.
|
||||
await this.releaseLock(!debug && failures.length === 0 ? now : null);
|
||||
//
|
||||
// A carrier-scoped run must not advance it either, for the same reason
|
||||
// one step out: it looked at the whole window but only mailed one
|
||||
// aseguradora, so every other carrier's letters in those days would fall
|
||||
// outside tomorrow's window and never be sent at all.
|
||||
const complete = !debug && !providerId && failures.length === 0;
|
||||
await this.releaseLock(complete ? now : null);
|
||||
void this.audit.log(userId, "renewalNotice.sweep", result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
@@ -233,12 +265,14 @@ export class RenewalsService implements OnModuleInit {
|
||||
throw new BadRequestException("El cliente no tiene correo registrado.");
|
||||
}
|
||||
|
||||
// A person clicked this, so the premium stays in the letter — only the
|
||||
// scheduler's unattended run omits it.
|
||||
const { sentAt, providerMessageId, addressedTo } = await this.deliver(
|
||||
policy,
|
||||
generation,
|
||||
to,
|
||||
userId,
|
||||
debug,
|
||||
{ debug, includePremium: true },
|
||||
);
|
||||
return {
|
||||
policyId,
|
||||
@@ -270,10 +304,12 @@ export class RenewalsService implements OnModuleInit {
|
||||
generation: number,
|
||||
to: string,
|
||||
userId?: string,
|
||||
debug = false,
|
||||
options: { debug?: boolean; includePremium?: boolean } = {},
|
||||
) {
|
||||
const debug = !!options.debug;
|
||||
const includePremium = options.includePremium !== false;
|
||||
const letter = toRenewalLetterRow(policy, generation);
|
||||
const message = renderRenewalEmail(letter);
|
||||
const message = renderRenewalEmail(letter, { includePremium });
|
||||
const addressedTo = debug ? DEBUG_RECIPIENT : to;
|
||||
|
||||
let result: Awaited<ReturnType<MailService["send"]>>;
|
||||
@@ -291,6 +327,7 @@ export class RenewalsService implements OnModuleInit {
|
||||
status: "FAILED",
|
||||
error: detail,
|
||||
debug,
|
||||
includePremium,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
@@ -324,6 +361,7 @@ export class RenewalsService implements OnModuleInit {
|
||||
providerResponse: result.response || undefined,
|
||||
sendDate: sentAt,
|
||||
debug,
|
||||
includePremium,
|
||||
});
|
||||
void this.audit.log(userId, "renewalNotice.send", {
|
||||
policyId: policy.id,
|
||||
@@ -355,10 +393,15 @@ export class RenewalsService implements OnModuleInit {
|
||||
error?: string;
|
||||
sendDate?: Date;
|
||||
debug?: boolean;
|
||||
/** Must match what `deliver` rendered, or `bodySnapshot` shows the
|
||||
* office a letter the customer never received. */
|
||||
includePremium?: boolean;
|
||||
},
|
||||
): Promise<void> {
|
||||
const letter = toRenewalLetterRow(policy, generation);
|
||||
const message = renderRenewalEmail(letter);
|
||||
const message = renderRenewalEmail(letter, {
|
||||
includePremium: outcome.includePremium,
|
||||
});
|
||||
try {
|
||||
await this.notificationLog.record({
|
||||
notificationType: "RENEWAL_NOTICE",
|
||||
@@ -391,11 +434,13 @@ export class RenewalsService implements OnModuleInit {
|
||||
cadence: (typeof RENEWAL_CADENCE)[number],
|
||||
today: Date,
|
||||
lastSuccessfulAt: Date | null,
|
||||
providerId?: string,
|
||||
) {
|
||||
const window = renewalWindow(today, cadence.offsetDays, lastSuccessfulAt);
|
||||
return this.prisma.policy.findMany({
|
||||
where: {
|
||||
archivedAt: null,
|
||||
...(providerId && { insuranceProviderId: providerId }),
|
||||
policyTo: { gte: window.from, lte: window.to },
|
||||
customer: {
|
||||
archivedAt: null,
|
||||
|
||||
@@ -21,6 +21,8 @@ export interface CompanyInfo {
|
||||
addressLine2: string;
|
||||
/** "City, State, ZIP, Country" — single line. */
|
||||
cityState: string;
|
||||
/** US postal address, printed after the office address. Optional. */
|
||||
mailingAddress: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
/** Mexican tax ID ("RFC"). Optional. */
|
||||
@@ -83,19 +85,23 @@ export function getCompanyInfo(): CompanyInfo {
|
||||
}
|
||||
cached = {
|
||||
name: envOr("COMPANY_NAME", "Jorge Cuadros & Asociados"),
|
||||
addressLine1: envOr(
|
||||
"COMPANY_ADDRESS_LINE1",
|
||||
"Av. Revolución 1234, Int. 5",
|
||||
),
|
||||
// The office's real locator, as published on jorgecuadros.com. Prod sets
|
||||
// no COMPANY_* variables, so these defaults ARE what every printed
|
||||
// statement shows — they were placeholders until 2026-10.
|
||||
addressLine1: envOr("COMPANY_ADDRESS_LINE1", "Quinta Plaza Ste 3-B"),
|
||||
addressLine2: envOr("COMPANY_ADDRESS_LINE2", ""),
|
||||
cityState: envOr(
|
||||
"COMPANY_CITY_STATE",
|
||||
"Tijuana, Baja California 22000, México",
|
||||
"Rosarito, Baja California, México",
|
||||
),
|
||||
phone: envOr("COMPANY_PHONE", "(664) 000-0000"),
|
||||
email: envOr("COMPANY_EMAIL", "contacto@jorgecuadros.local"),
|
||||
mailingAddress: envOr(
|
||||
"COMPANY_MAILING_ADDRESS",
|
||||
"US: 416 W. San Ysidro Blvd L #3108, San Ysidro, CA 92173",
|
||||
),
|
||||
phone: envOr("COMPANY_PHONE", "011-52 (661) 612-1295"),
|
||||
email: envOr("COMPANY_EMAIL", "info@jorgecuadros.com"),
|
||||
taxId: envOr("COMPANY_TAX_ID", ""),
|
||||
website: envOr("COMPANY_WEBSITE", "jorgecuadros.local"),
|
||||
website: envOr("COMPANY_WEBSITE", "jorgecuadros.com"),
|
||||
logoPath,
|
||||
logo,
|
||||
};
|
||||
|
||||
@@ -199,6 +199,7 @@ export function renderPdf(
|
||||
company.addressLine1,
|
||||
company.addressLine2,
|
||||
[company.cityState].filter(Boolean).join(" · "),
|
||||
company.mailingAddress,
|
||||
[company.phone, company.email].filter(Boolean).join(" · "),
|
||||
company.taxId ? `RFC: ${company.taxId}` : "",
|
||||
].filter(Boolean);
|
||||
@@ -363,6 +364,7 @@ export function renderPrintHtml(
|
||||
company.addressLine1,
|
||||
company.addressLine2,
|
||||
company.cityState,
|
||||
company.mailingAddress,
|
||||
[company.phone, company.email].filter(Boolean).join(" · "),
|
||||
company.taxId ? `RFC: ${company.taxId}` : "",
|
||||
].filter(Boolean);
|
||||
|
||||
@@ -14,9 +14,23 @@
|
||||
* the EFECTIVO* set OR `checkNumber` null + amount > 0 (true cash).
|
||||
*/
|
||||
|
||||
import { Prisma } from "@jorgecuadros/database";
|
||||
import { BALANCE_FORWARD_TYPE } from "../billing/billing.service";
|
||||
import { Prisma, type ServiceKind } from "@jorgecuadros/database";
|
||||
import {
|
||||
BALANCE_FLOOR_JOIN,
|
||||
BALANCE_FORWARD_TYPE,
|
||||
balanceScopeSql,
|
||||
NOT_SUPERSEDED,
|
||||
notCashJournal,
|
||||
periodSourceTable,
|
||||
} from "../billing/billing.service";
|
||||
import {
|
||||
UTILITIES_SYSTEM,
|
||||
UTILITIES_TABLE,
|
||||
} from "../customers/numid.service";
|
||||
import type { PrismaService } from "../prisma/prisma.service";
|
||||
import { CONCEPT_BY_KIND } from "../statements/statements.service";
|
||||
import {
|
||||
type ColumnDef,
|
||||
intParam,
|
||||
NOT_VOIDED,
|
||||
parseDate,
|
||||
@@ -33,19 +47,80 @@ function nameOf(c: { name: string; nameMissing: boolean }): string {
|
||||
return c.nameMissing ? "(sin nombre)" : c.name;
|
||||
}
|
||||
|
||||
const isoDay = (d: Date | null | undefined) =>
|
||||
d ? d.toISOString().slice(0, 10) : "—";
|
||||
|
||||
/** Every report leads with the legacy customer number (2026-10 meeting). */
|
||||
const NUMID_COLUMN: ColumnDef = { key: "numid", label: "NUMid", type: "text" };
|
||||
/** Policy reports add the insurance file number beside it. */
|
||||
const INSURANCE_NO_COLUMN: ColumnDef = {
|
||||
key: "insuranceNo",
|
||||
label: "No. seguros",
|
||||
type: "text",
|
||||
};
|
||||
|
||||
/**
|
||||
* Legacy customer numbers for a page of report rows. The office files,
|
||||
* captures and talks in NUMids, not platform ids.
|
||||
*
|
||||
* The utilities NUMid is the portal number, one per customer. insurance/DATGRAL
|
||||
* is a separate id space under the same table name, so it is read on its own
|
||||
* and never shown as a NUMid; 16 customers hold more than one.
|
||||
*/
|
||||
async function legacyNumbers(prisma: PrismaService, customerIds: string[]) {
|
||||
const ids = [...new Set(customerIds)];
|
||||
const refs = ids.length
|
||||
? await prisma.customerLegacyRef.findMany({
|
||||
where: {
|
||||
customerId: { in: ids },
|
||||
sourceTable: UTILITIES_TABLE,
|
||||
sourceSystem: { in: [UTILITIES_SYSTEM, "insurance"] },
|
||||
},
|
||||
select: { customerId: true, sourceSystem: true, legacyId: true },
|
||||
})
|
||||
: [];
|
||||
const byCustomer = new Map<string, { numid?: string; insurance: string[] }>();
|
||||
for (const r of refs) {
|
||||
const e = byCustomer.get(r.customerId) ?? { insurance: [] };
|
||||
if (r.sourceSystem === UTILITIES_SYSTEM) e.numid = r.legacyId;
|
||||
else e.insurance.push(r.legacyId);
|
||||
byCustomer.set(r.customerId, e);
|
||||
}
|
||||
return {
|
||||
numid: (id: string) => byCustomer.get(id)?.numid ?? "—",
|
||||
insurance: (id: string) =>
|
||||
byCustomer
|
||||
.get(id)
|
||||
?.insurance.sort((a, b) => Number(a) - Number(b))
|
||||
.join(", ") || "—",
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ reports */
|
||||
|
||||
/**
|
||||
* LISTADO EN ROJO — overdue customers worklist.
|
||||
* Same data as the receivables worklist with balance=owing, but presented
|
||||
* as a printable report rather than a paginated browser.
|
||||
*
|
||||
* Legacy printed it from `ALFABETICO EN ROJO`: `SUM(CHARGECREDIT) < 0` over
|
||||
* DATOS2, by name. That sum was only honest because DATOS2 held one year plus
|
||||
* its BALANCE FORWARD. The platform keeps every year, so the balance here is
|
||||
* the statement's own — the floor, the cash journal and the archive window via
|
||||
* the same fragments `BillingService.balances()` uses. Summed raw, as this
|
||||
* report used to, 195 customers read in the red against 22 real ones: every
|
||||
* closed account whose history the opening balance had already settled.
|
||||
*
|
||||
* Ordered by the most recent real movement (Jorge, 2026-10): the oldest
|
||||
* debtors are the accounts that closed, the ones worth chasing are recent.
|
||||
* Inactive customers (`status = 0` — the office's own and internal accounts,
|
||||
* e.g. TRASPASOS PAYPAL at -12M) stay out unless asked for.
|
||||
*/
|
||||
const listadoEnRojo: ReportDef = {
|
||||
slug: "listado-en-rojo",
|
||||
title: "Clientes en rojo",
|
||||
description:
|
||||
"Cartera vencida: clientes con saldo deudor en la moneda seleccionada, " +
|
||||
"ordenados del más antiguo al más reciente.",
|
||||
"Cartera vencida: clientes con saldo deudor en la moneda seleccionada — " +
|
||||
"el mismo saldo de su estado de cuenta — ordenados por el movimiento " +
|
||||
"más reciente. Los clientes inactivos quedan fuera salvo que se pidan.",
|
||||
domain: "estado-cuenta",
|
||||
legacyName: "LISTADO EN ROJO",
|
||||
format: "tabular",
|
||||
@@ -60,6 +135,45 @@ const listadoEnRojo: ReportDef = {
|
||||
],
|
||||
defaultValue: "MXN",
|
||||
},
|
||||
{
|
||||
key: "domain",
|
||||
label: "Ramo",
|
||||
kind: "select",
|
||||
options: [
|
||||
{ value: "ALL", label: "Todos" },
|
||||
{ value: "UTILITY", label: "Servicios" },
|
||||
{ value: "INSURANCE", label: "Seguros" },
|
||||
],
|
||||
defaultValue: "ALL",
|
||||
},
|
||||
{ key: "since", label: "Con movimiento desde", kind: "date" },
|
||||
{
|
||||
key: "minOwed",
|
||||
label: "Adeudo mínimo",
|
||||
kind: "number",
|
||||
placeholder: "0",
|
||||
},
|
||||
{
|
||||
key: "inactive",
|
||||
label: "Clientes inactivos",
|
||||
kind: "select",
|
||||
options: [
|
||||
{ value: "no", label: "Excluir" },
|
||||
{ value: "yes", label: "Incluir" },
|
||||
],
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
key: "sort",
|
||||
label: "Orden",
|
||||
kind: "select",
|
||||
options: [
|
||||
{ value: "recent", label: "Movimiento más reciente" },
|
||||
{ value: "debt", label: "Mayor adeudo" },
|
||||
{ value: "name", label: "Nombre" },
|
||||
],
|
||||
defaultValue: "recent",
|
||||
},
|
||||
{
|
||||
key: "query",
|
||||
label: "Buscar (nombre o ciudad)",
|
||||
@@ -68,24 +182,48 @@ const listadoEnRojo: ReportDef = {
|
||||
},
|
||||
],
|
||||
columns: [
|
||||
{ key: "id", label: "#", type: "text" },
|
||||
NUMID_COLUMN,
|
||||
{ key: "name", label: "Cliente", type: "text" },
|
||||
{ key: "city", label: "Ciudad", type: "text" },
|
||||
{ key: "movements", label: "Movs.", type: "number", align: "right" },
|
||||
{ key: "balance", label: "Saldo", type: "money", align: "right" },
|
||||
{ key: "lastMovement", label: "Último movimiento", type: "date" },
|
||||
{ key: "lastPayment", label: "Último abono", type: "date" },
|
||||
{ key: "balance", label: "Saldo", type: "money", align: "right" },
|
||||
],
|
||||
async run(prisma, p) {
|
||||
const currency = (p.currency === "USD" ? "USD" : "MXN") as "MXN" | "USD";
|
||||
const q = p.query?.trim();
|
||||
const nameFilter = q
|
||||
? Prisma.sql`AND (c.name LIKE ${`%${q}%`} OR c.city LIKE ${`%${q}%`})`
|
||||
const since = parseDate(p.since);
|
||||
const minOwed = Math.max(Number(p.minOwed) || 0, 0.005);
|
||||
|
||||
const filters: Prisma.Sql[] = [];
|
||||
if (q) {
|
||||
filters.push(Prisma.sql`(c.name LIKE ${`%${q}%`} OR c.city LIKE ${`%${q}%`})`);
|
||||
}
|
||||
if (p.domain === "UTILITY" || p.domain === "INSURANCE") {
|
||||
filters.push(Prisma.sql`t.domain = ${p.domain}`);
|
||||
}
|
||||
if (p.inactive !== "yes") {
|
||||
filters.push(Prisma.sql`c.status = 1 AND c.archivedAt IS NULL`);
|
||||
}
|
||||
const where = filters.length
|
||||
? Prisma.sql`AND ${Prisma.join(filters, " AND ")}`
|
||||
: Prisma.empty;
|
||||
|
||||
const bal =
|
||||
currency === "USD"
|
||||
? Prisma.sql`SUM(CASE WHEN t.currency = 'USD' THEN t.amount ELSE 0 END)`
|
||||
: Prisma.sql`SUM(CASE WHEN t.currency = 'MXN' THEN t.amount ELSE 0 END)`;
|
||||
// The Jan 1 BALANCE FORWARD is not a movement — every customer has one, so
|
||||
// counting it would date every closed account to this year.
|
||||
const real = Prisma.sql`(tt.nameEn IS NULL OR tt.nameEn <> ${BALANCE_FORWARD_TYPE})`;
|
||||
const lastMovement = Prisma.sql`MAX(CASE WHEN ${real} THEN t.transactionDate END)`;
|
||||
|
||||
const orderBy =
|
||||
p.sort === "debt"
|
||||
? Prisma.sql`ORDER BY balance ASC`
|
||||
: p.sort === "name"
|
||||
? Prisma.sql`ORDER BY c.nameMissing ASC, c.name ASC`
|
||||
: Prisma.sql`ORDER BY lastMovement DESC, balance ASC`;
|
||||
|
||||
const rows = await prisma.$queryRaw<
|
||||
Array<{
|
||||
@@ -93,38 +231,39 @@ const listadoEnRojo: ReportDef = {
|
||||
name: string;
|
||||
nameMissing: boolean;
|
||||
city: string | null;
|
||||
movements: bigint | number | string;
|
||||
balance: Prisma.Decimal | null;
|
||||
lastMovement: Date | null;
|
||||
lastPayment: Date | null;
|
||||
}>
|
||||
>`
|
||||
SELECT c.id, c.name, c.nameMissing, c.city,
|
||||
COUNT(*) AS movements,
|
||||
${bal} AS balance,
|
||||
MAX(t.transactionDate) AS lastMovement
|
||||
${lastMovement} AS lastMovement,
|
||||
MAX(CASE WHEN ${real} AND t.amount > 0 THEN t.transactionDate END) AS lastPayment
|
||||
FROM customers c
|
||||
JOIN transactions t ON t.customerId = c.id
|
||||
WHERE t.voidedAt IS NULL ${nameFilter}
|
||||
LEFT JOIN type_transactions tt ON tt.id = t.typeId
|
||||
${BALANCE_FLOOR_JOIN}
|
||||
WHERE t.voidedAt IS NULL AND t.outstanding = 0 AND ${NOT_SUPERSEDED}
|
||||
${balanceScopeSql()} ${where}
|
||||
GROUP BY c.id, c.name, c.nameMissing, c.city
|
||||
HAVING ${bal} < -0.005
|
||||
ORDER BY MAX(t.transactionDate) ASC, c.nameMissing ASC, c.name ASC
|
||||
HAVING ${bal} < ${-minOwed}
|
||||
${since ? Prisma.sql`AND ${lastMovement} >= ${since}` : Prisma.empty}
|
||||
${orderBy}
|
||||
`;
|
||||
|
||||
const nums = await legacyNumbers(prisma, rows.map((r) => r.id));
|
||||
let totalBalance = new Prisma.Decimal(0);
|
||||
let totalMovs = 0;
|
||||
const out = rows.map((r) => {
|
||||
const b = r.balance ?? new Prisma.Decimal(0);
|
||||
totalBalance = totalBalance.plus(b);
|
||||
totalMovs += Number(r.movements);
|
||||
return {
|
||||
id: r.id.slice(0, 8),
|
||||
numid: nums.numid(r.id),
|
||||
name: nameOf(r),
|
||||
city: r.city ?? "—",
|
||||
movements: Number(r.movements),
|
||||
lastMovement: isoDay(r.lastMovement),
|
||||
lastPayment: isoDay(r.lastPayment),
|
||||
balance: b.toFixed(2),
|
||||
lastMovement: r.lastMovement
|
||||
? r.lastMovement.toISOString().slice(0, 10)
|
||||
: "—",
|
||||
};
|
||||
});
|
||||
|
||||
@@ -132,31 +271,58 @@ const listadoEnRojo: ReportDef = {
|
||||
rows: out,
|
||||
totals: {
|
||||
customers: out.length,
|
||||
movements: totalMovs,
|
||||
balance: totalBalance.toFixed(2),
|
||||
currency,
|
||||
},
|
||||
subtitle: `Moneda: ${currency} · ${out.length} clientes con saldo deudor`,
|
||||
subtitle: `Moneda: ${currency} · ${out.length} clientes con saldo deudor${
|
||||
p.inactive === "yes" ? " · incluye inactivos" : ""
|
||||
}`,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/** The services whose bill the office pays and books as a ledger concept. */
|
||||
const SERVICE_OPTIONS: { value: ServiceKind; label: string }[] = [
|
||||
{ value: "WATER", label: "Agua" },
|
||||
{ value: "ELECTRIC", label: "Luz" },
|
||||
{ value: "TELEPHONE", label: "Teléfono" },
|
||||
{ value: "GAS", label: "Gas" },
|
||||
{ value: "PROPERTY_TAX", label: "Predial" },
|
||||
{ value: "FEDERAL_ZONE", label: "Zona federal" },
|
||||
{ value: "CABLE", label: "Cable" },
|
||||
];
|
||||
|
||||
const serviceLabel = (kind: string) =>
|
||||
SERVICE_OPTIONS.find((o) => o.value === kind)?.label ?? kind;
|
||||
|
||||
/**
|
||||
* PAGOS NO EFECTUADOS (AGUA / LUZ / TEL).
|
||||
* Customers enrolled in a service (by PropertyService.kind) with no
|
||||
* related ledger charge in the last N days. Heuristic: any non-voided
|
||||
* charge-type transaction in the window counts as "they paid". The
|
||||
* report groups by property so the same customer with two water meters
|
||||
* appears once per property.
|
||||
* PAGOS NO EFECTUADOS (AGUA / LUZ / TEL / …).
|
||||
*
|
||||
* Legacy `PAGO AGUA/LUZ/TEL NO`: every customer with the service, LEFT JOIN
|
||||
* `LOCALIZA PAGO *` — the rows of THAT service's concept dated in the period
|
||||
* the operator typed — where nothing was found. So: "whose water did we not
|
||||
* pay this month". The first port asked a different question ("no charge of
|
||||
* any kind in N days"), which is why customers who were up to date kept
|
||||
* showing: one IZZI or annual-fee row hid a missing water bill, and the
|
||||
* reverse. It also passed `ELECTRICITY`/`PHONE`, which are not ServiceKind
|
||||
* values, so Luz and Teléfono never returned a row at all.
|
||||
*
|
||||
* Matched per customer, as legacy did. A charge row carries no link to the
|
||||
* service it paid, and its reference only matches the stored account for
|
||||
* water and phone (813/822, 501/521) — CFE bills post under a reference that
|
||||
* is not the RPU (5 of 1109) — so matching on the reference would list every
|
||||
* electric customer as unpaid.
|
||||
*
|
||||
* A row captured "sin fondos" in the window is not a payment: the customer is
|
||||
* listed with that status, which is the follow-up the office actually owes.
|
||||
*/
|
||||
const pagosNoEfectuados: ReportDef = {
|
||||
slug: "pagos-no-efectuados",
|
||||
title: "Pagos no efectuados",
|
||||
description:
|
||||
"Clientes con un servicio contratado (agua, luz o teléfono) sin " +
|
||||
"movimientos de cargo en los últimos N días. Heurística basada en el " +
|
||||
"servicio registrado en la propiedad y la ausencia de cargos en el " +
|
||||
"periodo seleccionado.",
|
||||
"Clientes con el servicio contratado sin un pago de ese servicio " +
|
||||
"registrado en el periodo. Sin fechas, revisa un ciclo hacia atrás " +
|
||||
"desde hoy: 31 días, o 62 para luz (bimestral).",
|
||||
domain: "servicios",
|
||||
legacyName: "PAGOS NO EFECTUADOS AGUA/LUZ/TEL",
|
||||
format: "tabular",
|
||||
@@ -165,139 +331,143 @@ const pagosNoEfectuados: ReportDef = {
|
||||
key: "serviceKind",
|
||||
label: "Servicio",
|
||||
kind: "select",
|
||||
options: [
|
||||
{ value: "WATER", label: "Agua" },
|
||||
{ value: "ELECTRICITY", label: "Luz" },
|
||||
{ value: "PHONE", label: "Teléfono" },
|
||||
],
|
||||
options: SERVICE_OPTIONS,
|
||||
defaultValue: "WATER",
|
||||
},
|
||||
{ key: "from", label: "Desde (por defecto, un ciclo atrás)", kind: "date" },
|
||||
{ key: "to", label: "Hasta (por defecto, hoy)", kind: "date", endOfDay: true },
|
||||
{
|
||||
key: "days",
|
||||
label: "Días sin movimiento",
|
||||
kind: "number",
|
||||
defaultValue: "60",
|
||||
},
|
||||
{
|
||||
key: "currency",
|
||||
label: "Moneda",
|
||||
key: "inactive",
|
||||
label: "Clientes inactivos",
|
||||
kind: "select",
|
||||
options: [
|
||||
{ value: "MXN", label: "MXN" },
|
||||
{ value: "USD", label: "USD" },
|
||||
{ value: "no", label: "Excluir" },
|
||||
{ value: "yes", label: "Incluir" },
|
||||
],
|
||||
defaultValue: "MXN",
|
||||
defaultValue: "no",
|
||||
},
|
||||
],
|
||||
columns: [
|
||||
{ key: "customerId", label: "Cliente #", type: "text" },
|
||||
NUMID_COLUMN,
|
||||
{ key: "customerName", label: "Cliente", type: "text" },
|
||||
{ key: "propertyAddress", label: "Dirección", type: "text" },
|
||||
{ key: "accountNumber", label: "Cuenta / Medidor", type: "text" },
|
||||
{ key: "lastCharge", label: "Último cargo", type: "date" },
|
||||
{ key: "balance", label: "Saldo", type: "money", align: "right" },
|
||||
{ key: "accountNumber", label: "Cuenta", type: "text" },
|
||||
{ key: "status", label: "Estado", type: "text" },
|
||||
{ key: "lastPaid", label: "Último pago del servicio", type: "date" },
|
||||
],
|
||||
async run(prisma, p) {
|
||||
const kind = (p.serviceKind ?? "WATER") as
|
||||
| "WATER"
|
||||
| "ELECTRICITY"
|
||||
| "PHONE";
|
||||
const days = intParam(p, "days", 60, 1, 365);
|
||||
const currency = (p.currency === "USD" ? "USD" : "MXN") as "MXN" | "USD";
|
||||
const cutoff = new Date(Date.now() - days * 86400000);
|
||||
const kind = (
|
||||
SERVICE_OPTIONS.some((o) => o.value === p.serviceKind)
|
||||
? p.serviceKind
|
||||
: "WATER"
|
||||
) as ServiceKind;
|
||||
const concept = CONCEPT_BY_KIND[kind]!;
|
||||
// No period given: one billing cycle back from the end date, so the
|
||||
// report means the same on the 2nd as on the 28th. "This month" listed
|
||||
// nearly everyone early in the month — the bills are captured ~20th.
|
||||
const to = parseDate(p.to, true) ?? new Date();
|
||||
const cycleDays = kind === "ELECTRIC" ? 62 : 31;
|
||||
const from =
|
||||
parseDate(p.from) ?? new Date(to.getTime() - cycleDays * 86400000);
|
||||
const inactive =
|
||||
p.inactive === "yes"
|
||||
? Prisma.empty
|
||||
: Prisma.sql`AND c.status = 1`;
|
||||
|
||||
// One concept row for the customer, not voided, in the window.
|
||||
const conceptRow = (outstanding: 0 | 1) => Prisma.sql`
|
||||
SELECT 1 FROM transactions t
|
||||
JOIN type_transactions tt ON tt.id = t.typeId
|
||||
WHERE t.customerId = c.id AND t.voidedAt IS NULL
|
||||
AND t.outstanding = ${outstanding} AND tt.nameEn = ${concept}
|
||||
AND t.transactionDate >= ${from} AND t.transactionDate <= ${to}`;
|
||||
|
||||
// Customers enrolled in the service on a non-archived property, with no
|
||||
// charge-type transaction in the window. The subquery picks up
|
||||
// *anything* the customer paid (any domain, any type) — close enough
|
||||
// for the staff's "who's overdue" view; the precise per-service match
|
||||
// would need a per-service typeId taxonomy that doesn't exist in the
|
||||
// legacy data.
|
||||
const rows = await prisma.$queryRaw<
|
||||
Array<{
|
||||
customerId: string;
|
||||
customerName: string;
|
||||
nameMissing: boolean;
|
||||
propertyId: string;
|
||||
propertyAddress: string | null;
|
||||
accountNumber: string | null;
|
||||
lastCharge: Date | null;
|
||||
balance: Prisma.Decimal | null;
|
||||
addresses: string | null;
|
||||
accounts: string | null;
|
||||
unfunded: bigint | number;
|
||||
lastPaid: Date | null;
|
||||
}>
|
||||
>`
|
||||
SELECT
|
||||
c.id AS customerId,
|
||||
c.name AS customerName,
|
||||
c.nameMissing AS nameMissing,
|
||||
pr.id AS propertyId,
|
||||
pr.addressLine1 AS propertyAddress,
|
||||
ps.accountNumber AS accountNumber,
|
||||
GROUP_CONCAT(DISTINCT pr.addressLine1 ORDER BY pr.addressLine1 SEPARATOR ' / ') AS addresses,
|
||||
GROUP_CONCAT(DISTINCT NULLIF(ps.accountNumber, '') SEPARATOR ', ') AS accounts,
|
||||
EXISTS(${conceptRow(1)}) AS unfunded,
|
||||
(SELECT MAX(t.transactionDate) FROM transactions t
|
||||
JOIN type_transactions tt ON tt.id = t.typeId
|
||||
WHERE t.customerId = c.id AND t.voidedAt IS NULL
|
||||
AND t.amount < 0
|
||||
AND t.transactionDate >= ${cutoff}) AS lastCharge,
|
||||
(SELECT SUM(t.amount) FROM transactions t
|
||||
WHERE t.customerId = c.id AND t.voidedAt IS NULL
|
||||
AND t.currency = ${currency}) AS balance
|
||||
AND t.outstanding = 0 AND tt.nameEn = ${concept}) AS lastPaid
|
||||
FROM property_services ps
|
||||
JOIN properties pr ON pr.id = ps.propertyId AND pr.archivedAt IS NULL
|
||||
JOIN customers c ON c.id = pr.customerId AND c.archivedAt IS NULL
|
||||
WHERE ps.kind = ${kind} AND ps.active = 1
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM transactions t
|
||||
WHERE t.customerId = c.id AND t.voidedAt IS NULL
|
||||
AND t.amount < 0 AND t.transactionDate >= ${cutoff}
|
||||
)
|
||||
ORDER BY c.nameMissing ASC, c.name ASC, pr.addressLine1 ASC
|
||||
WHERE ps.kind = ${kind} AND ps.active = 1 ${inactive}
|
||||
AND NOT EXISTS (${conceptRow(0)})
|
||||
GROUP BY c.id, c.name, c.nameMissing
|
||||
ORDER BY c.nameMissing ASC, c.name ASC
|
||||
`;
|
||||
|
||||
let totalBalance = new Prisma.Decimal(0);
|
||||
const nums = await legacyNumbers(prisma, rows.map((r) => r.customerId));
|
||||
let unfunded = 0;
|
||||
const out = rows.map((r) => {
|
||||
const b = r.balance ?? new Prisma.Decimal(0);
|
||||
totalBalance = totalBalance.plus(b);
|
||||
if (Number(r.unfunded)) unfunded++;
|
||||
return {
|
||||
customerId: r.customerId.slice(0, 8),
|
||||
customerName: nameOf({
|
||||
name: r.customerName,
|
||||
nameMissing: r.nameMissing,
|
||||
}),
|
||||
propertyAddress: r.propertyAddress ?? "—",
|
||||
accountNumber: r.accountNumber ?? "—",
|
||||
lastCharge: r.lastCharge
|
||||
? r.lastCharge.toISOString().slice(0, 10)
|
||||
: "—",
|
||||
balance: b.toFixed(2),
|
||||
numid: nums.numid(r.customerId),
|
||||
customerName: nameOf({ name: r.customerName, nameMissing: r.nameMissing }),
|
||||
propertyAddress: r.addresses ?? "—",
|
||||
accountNumber: r.accounts ?? "—",
|
||||
status: Number(r.unfunded) ? "Sin fondos" : "Sin pago",
|
||||
lastPaid: isoDay(r.lastPaid),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
rows: out,
|
||||
totals: {
|
||||
rows: out.length,
|
||||
balance: totalBalance.toFixed(2),
|
||||
currency,
|
||||
clientes: out.length,
|
||||
"sin pago": out.length - unfunded,
|
||||
"sin fondos": unfunded,
|
||||
},
|
||||
subtitle: `Servicio: ${
|
||||
kind === "WATER" ? "Agua" : kind === "ELECTRICITY" ? "Luz" : "Teléfono"
|
||||
} · ${days} días · ${out.length} propiedades sin cargo reciente`,
|
||||
subtitle: `Servicio: ${serviceLabel(kind)} · ${isoDay(from)} a ${isoDay(to)} · ${out.length} clientes sin pago registrado`,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* FALTANTES DE (AGUA / LUZ / TEL).
|
||||
* Data-quality report: properties enrolled in a service that are missing
|
||||
* the key identifier the legacy system required (account/meter/route).
|
||||
* Different `faltante` per service kind in the legacy because the
|
||||
* service's identifier fields differ; here we flag any of the three
|
||||
* common identifiers being blank.
|
||||
* What each service must have on file to be paid and matched — the columns
|
||||
* legacy's FALTANTES DE AGUA/LUZ/TEL read (DATMEX.AGUA; MEDIDOR + RPU;
|
||||
* TELEFONO), in the field `scopedRefField` stores each one in. The first port
|
||||
* demanded account AND meter AND route of every kind; water and phone have no
|
||||
* route, so every one of them was flagged.
|
||||
*/
|
||||
const REQUIRED_FIELDS: Partial<
|
||||
Record<ServiceKind, Array<["accountNumber" | "meterNumber", string]>>
|
||||
> = {
|
||||
WATER: [["accountNumber", "Sin número de cuenta"]],
|
||||
ELECTRIC: [
|
||||
["accountNumber", "Sin RPU"],
|
||||
["meterNumber", "Sin medidor"],
|
||||
],
|
||||
TELEPHONE: [["accountNumber", "Sin número de teléfono"]],
|
||||
};
|
||||
|
||||
/**
|
||||
* FALTANTES DE (AGUA / LUZ / TEL) — data quality: active services missing the
|
||||
* identifier the office needs to pay and match the bill.
|
||||
*/
|
||||
const faltantes: ReportDef = {
|
||||
slug: "faltantes",
|
||||
title: "Faltantes de datos por servicio",
|
||||
description:
|
||||
"Calidad de datos: propiedades con un servicio contratado que no " +
|
||||
"tienen número de cuenta, medidor o ruta registrado. El reporte que " +
|
||||
"en la legacy corría como FALTANTES DE AGUA / LUZ / TEL.",
|
||||
"Calidad de datos: servicios activos sin el dato que se necesita para " +
|
||||
"pagar el recibo — agua: número de cuenta; luz: RPU y medidor; " +
|
||||
"teléfono: número.",
|
||||
domain: "servicios",
|
||||
legacyName: "FALTANTES DE AGUA/LUZ/TEL",
|
||||
format: "tabular",
|
||||
@@ -306,37 +476,34 @@ const faltantes: ReportDef = {
|
||||
key: "serviceKind",
|
||||
label: "Servicio",
|
||||
kind: "select",
|
||||
options: [
|
||||
{ value: "WATER", label: "Agua" },
|
||||
{ value: "ELECTRICITY", label: "Luz" },
|
||||
{ value: "PHONE", label: "Teléfono" },
|
||||
],
|
||||
options: SERVICE_OPTIONS.filter((o) => REQUIRED_FIELDS[o.value]),
|
||||
defaultValue: "WATER",
|
||||
},
|
||||
],
|
||||
columns: [
|
||||
{ key: "customerId", label: "Cliente #", type: "text" },
|
||||
NUMID_COLUMN,
|
||||
{ key: "customerName", label: "Cliente", type: "text" },
|
||||
{ key: "propertyAddress", label: "Dirección", type: "text" },
|
||||
{ key: "missing", label: "Faltante", type: "text" },
|
||||
{ key: "dueDay", label: "Día de vencimiento", type: "text" },
|
||||
],
|
||||
async run(prisma, p) {
|
||||
const kind = (p.serviceKind ?? "WATER") as
|
||||
| "WATER"
|
||||
| "ELECTRICITY"
|
||||
| "PHONE";
|
||||
const kind = (
|
||||
p.serviceKind && REQUIRED_FIELDS[p.serviceKind as ServiceKind]
|
||||
? p.serviceKind
|
||||
: "WATER"
|
||||
) as ServiceKind;
|
||||
const required = REQUIRED_FIELDS[kind]!;
|
||||
|
||||
// Column names come from the constant above, never from the request.
|
||||
const blank = (field: string) =>
|
||||
Prisma.sql`(ps.${Prisma.raw(field)} IS NULL OR TRIM(ps.${Prisma.raw(field)}) = '')`;
|
||||
|
||||
// A row per (property, missing field). The "missing" string describes
|
||||
// what's blank so the report is self-explanatory when printed.
|
||||
const rows = await prisma.$queryRaw<
|
||||
Array<{
|
||||
customerId: string;
|
||||
customerName: string;
|
||||
nameMissing: boolean;
|
||||
propertyId: string;
|
||||
propertyAddress: string | null;
|
||||
dueDay: string | null;
|
||||
missing: string;
|
||||
}>
|
||||
>`
|
||||
@@ -344,44 +511,30 @@ const faltantes: ReportDef = {
|
||||
c.id AS customerId,
|
||||
c.name AS customerName,
|
||||
c.nameMissing AS nameMissing,
|
||||
pr.id AS propertyId,
|
||||
pr.addressLine1 AS propertyAddress,
|
||||
ps.dueDay AS dueDay,
|
||||
CASE
|
||||
WHEN ps.accountNumber IS NULL OR ps.accountNumber = '' THEN 'Sin número de cuenta'
|
||||
WHEN ps.meterNumber IS NULL OR ps.meterNumber = '' THEN 'Sin número de medidor'
|
||||
WHEN ps.route IS NULL OR ps.route = '' THEN 'Sin ruta'
|
||||
ELSE ''
|
||||
END AS missing
|
||||
CONCAT_WS(', ', ${Prisma.join(
|
||||
required.map(([field, label]) => Prisma.sql`IF(${blank(field)}, ${label}, NULL)`),
|
||||
)}) AS missing
|
||||
FROM property_services ps
|
||||
JOIN properties pr ON pr.id = ps.propertyId AND pr.archivedAt IS NULL
|
||||
JOIN customers c ON c.id = pr.customerId AND c.archivedAt IS NULL
|
||||
WHERE ps.kind = ${kind} AND ps.active = 1
|
||||
AND (
|
||||
ps.accountNumber IS NULL OR ps.accountNumber = ''
|
||||
OR ps.meterNumber IS NULL OR ps.meterNumber = ''
|
||||
OR ps.route IS NULL OR ps.route = ''
|
||||
)
|
||||
WHERE ps.kind = ${kind} AND ps.active = 1 AND c.status = 1
|
||||
AND (${Prisma.join(required.map(([field]) => blank(field)), " OR ")})
|
||||
ORDER BY c.nameMissing ASC, c.name ASC, pr.addressLine1 ASC
|
||||
`;
|
||||
|
||||
const nums = await legacyNumbers(prisma, rows.map((r) => r.customerId));
|
||||
const out = rows.map((r) => ({
|
||||
customerId: r.customerId.slice(0, 8),
|
||||
customerName: nameOf({
|
||||
name: r.customerName,
|
||||
nameMissing: r.nameMissing,
|
||||
}),
|
||||
numid: nums.numid(r.customerId),
|
||||
customerName: nameOf({ name: r.customerName, nameMissing: r.nameMissing }),
|
||||
propertyAddress: r.propertyAddress ?? "—",
|
||||
missing: r.missing,
|
||||
dueDay: r.dueDay ?? "—",
|
||||
}));
|
||||
|
||||
return {
|
||||
rows: out,
|
||||
totals: { rows: out.length },
|
||||
subtitle: `Servicio: ${
|
||||
kind === "WATER" ? "Agua" : kind === "ELECTRICITY" ? "Luz" : "Teléfono"
|
||||
} · ${out.length} propiedades con datos faltantes`,
|
||||
subtitle: `Servicio: ${serviceLabel(kind)} · ${out.length} servicios con datos faltantes`,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -418,6 +571,7 @@ const reporteDeEfectivo: ReportDef = {
|
||||
],
|
||||
columns: [
|
||||
{ key: "date", label: "Fecha", type: "date" },
|
||||
NUMID_COLUMN,
|
||||
{ key: "customerName", label: "Cliente", type: "text" },
|
||||
{ key: "concept", label: "Concepto", type: "text" },
|
||||
{ key: "source", label: "Origen", type: "text" },
|
||||
@@ -432,6 +586,8 @@ const reporteDeEfectivo: ReportDef = {
|
||||
NOT_VOIDED,
|
||||
{ amount: { gt: 0 } },
|
||||
{ currency },
|
||||
// A credit opening balance has no check number but is not cash.
|
||||
{ OR: [{ typeId: null }, { type: { nameEn: { not: BALANCE_FORWARD_TYPE } } }] },
|
||||
{
|
||||
OR: [
|
||||
{ legacySourceTable: { in: ["EFECTIVO", "EFECTIVO_BACKUP"] } },
|
||||
@@ -464,15 +620,17 @@ const reporteDeEfectivo: ReportDef = {
|
||||
message: true,
|
||||
legacySourceTable: true,
|
||||
type: { select: { nameEs: true, nameEn: true } },
|
||||
customer: { select: { name: true, nameMissing: true } },
|
||||
customer: { select: { id: true, name: true, nameMissing: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const nums = await legacyNumbers(prisma, rows.map((r) => r.customer.id));
|
||||
let total = new Prisma.Decimal(0);
|
||||
const out = rows.map((r) => {
|
||||
total = total.plus(r.amount);
|
||||
return {
|
||||
date: r.transactionDate.toISOString().slice(0, 10),
|
||||
numid: nums.numid(r.customer.id),
|
||||
customerName: nameOf(r.customer),
|
||||
concept: r.message ?? r.type?.nameEs ?? r.type?.nameEn ?? "—",
|
||||
source: r.legacySourceTable ?? "—",
|
||||
@@ -537,6 +695,8 @@ const vigente: ReportDef = {
|
||||
],
|
||||
columns: [
|
||||
{ key: "policyNumber", label: "Póliza", type: "text" },
|
||||
NUMID_COLUMN,
|
||||
INSURANCE_NO_COLUMN,
|
||||
{ key: "customerName", label: "Cliente", type: "text" },
|
||||
{ key: "provider", label: "Aseguradora", type: "text" },
|
||||
{ key: "agent", label: "Agente", type: "text" },
|
||||
@@ -567,11 +727,12 @@ const vigente: ReportDef = {
|
||||
policyTo: true,
|
||||
netPremium: true,
|
||||
agentName: true,
|
||||
customer: { select: { name: true, nameMissing: true } },
|
||||
customer: { select: { id: true, name: true, nameMissing: true } },
|
||||
insuranceProvider: { select: { name: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const nums = await legacyNumbers(prisma, rows.map((r) => r.customer.id));
|
||||
let totalPremium = new Prisma.Decimal(0);
|
||||
const out = rows.map((r) => {
|
||||
const daysTo = r.policyTo
|
||||
@@ -582,6 +743,8 @@ const vigente: ReportDef = {
|
||||
if (r.netPremium) totalPremium = totalPremium.plus(r.netPremium);
|
||||
return {
|
||||
policyNumber: r.policyNumber,
|
||||
numid: nums.numid(r.customer.id),
|
||||
insuranceNo: nums.insurance(r.customer.id),
|
||||
customerName: nameOf(r.customer),
|
||||
provider: r.insuranceProvider?.name ?? "—",
|
||||
agent: r.agentName ?? "—",
|
||||
@@ -685,6 +848,8 @@ const avisoRenovacion: ReportDef = {
|
||||
// ReportRunner.tsx) — same trade-off edoCuentaDatos makes for "statement".
|
||||
columns: [
|
||||
{ key: "policyNumber", label: "Póliza", type: "text" },
|
||||
NUMID_COLUMN,
|
||||
INSURANCE_NO_COLUMN,
|
||||
{ key: "customerName", label: "Cliente", type: "text" },
|
||||
{ key: "provider", label: "Aseguradora", type: "text" },
|
||||
{ key: "policyTo", label: "Vence", type: "date" },
|
||||
@@ -716,11 +881,16 @@ const avisoRenovacion: ReportDef = {
|
||||
select: renewalLetterSelect(generation),
|
||||
});
|
||||
|
||||
const nums = await legacyNumbers(prisma, rows.map((r) => r.customer.id));
|
||||
let totalPremium = new Prisma.Decimal(0);
|
||||
let sentCount = 0;
|
||||
const out = rows.map((r) => {
|
||||
if (r.netPremium) totalPremium = totalPremium.plus(r.netPremium);
|
||||
const letter = toRenewalLetterRow(r, generation);
|
||||
const letter = {
|
||||
...toRenewalLetterRow(r, generation),
|
||||
numid: nums.numid(r.customer.id),
|
||||
insuranceNo: nums.insurance(r.customer.id),
|
||||
};
|
||||
if (letter.sentAt) sentCount++;
|
||||
return letter;
|
||||
});
|
||||
@@ -759,6 +929,15 @@ const edoCuentaDatos: ReportDef = {
|
||||
format: "statement",
|
||||
params: [
|
||||
{ key: "customerId", label: "Cliente", kind: "customer-picker" },
|
||||
// Which period to print. Blank means the year in progress; an earlier year
|
||||
// prints from its imported archive, the same source the on-screen
|
||||
// statement reads.
|
||||
{
|
||||
key: "year",
|
||||
label: "Periodo (año)",
|
||||
kind: "number",
|
||||
placeholder: "año en curso",
|
||||
},
|
||||
],
|
||||
columns: [
|
||||
// Statement rows carry synthetic `__kind` discriminators instead of
|
||||
@@ -789,6 +968,7 @@ const edoCuentaDatos: ReportDef = {
|
||||
},
|
||||
});
|
||||
if (!customer) return { rows: [], subtitle: "Cliente no encontrado" };
|
||||
const numid = (await legacyNumbers(prisma, [customer.id])).numid(customer.id);
|
||||
|
||||
// The source-table exclusion, the balance floor and the year scope below
|
||||
// are BillingService.statement's, because this report and
|
||||
@@ -804,29 +984,50 @@ const edoCuentaDatos: ReportDef = {
|
||||
select: { transactionDate: true },
|
||||
});
|
||||
|
||||
// Which period to print. An earlier year comes from its imported archive,
|
||||
// tagged rather than dated, exactly as the on-screen statement reads it.
|
||||
const thisYear = new Date().getUTCFullYear();
|
||||
const askedYear = Number(p.year);
|
||||
const requestedYear =
|
||||
Number.isInteger(askedYear) && askedYear > 0 ? askedYear : thisYear;
|
||||
const isArchive = requestedYear !== thisYear;
|
||||
|
||||
const rows = await prisma.transaction.findMany({
|
||||
where: {
|
||||
customerId,
|
||||
voidedAt: null,
|
||||
...(isArchive
|
||||
? // The archive is one period's ledger already, so the tag is the
|
||||
// whole filter and the balance floor must not apply — the floor
|
||||
// hides exactly the history this period is asking for.
|
||||
{ legacySourceTable: periodSourceTable(requestedYear) }
|
||||
: {
|
||||
...(floor ? { transactionDate: { gte: floor.transactionDate } } : {}),
|
||||
// NULL-safe: `NULL NOT IN (...)` is NULL, not true, so a bare `notIn`
|
||||
// drops every app-captured row (they have no legacySourceTable) — the
|
||||
// same defect this report's on-screen twin was fixed for.
|
||||
// Archive rows count as history below the year start (that is
|
||||
// what `opening` is for, and for a customer floored by an archive
|
||||
// it is the only carry there is) and are dropped at or above it.
|
||||
// Same rule as the on-screen twin — see BillingService.statement.
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{ legacySourceTable: null },
|
||||
{ legacySourceTable: { not: { startsWith: "datos2@" } } },
|
||||
{
|
||||
legacySourceTable: {
|
||||
notIn: [
|
||||
"EFECTIVO",
|
||||
"EFECTIVO_BACKUP",
|
||||
"EFECTIVO FM3",
|
||||
"CHEQUE FM3",
|
||||
"IVA 2015",
|
||||
],
|
||||
transactionDate: {
|
||||
lt: new Date(Date.UTC(requestedYear, 0, 1)),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
// The cash receipt book, which the ledger already carries as
|
||||
// its own `C<folio>` postings. Taken from the shared helper
|
||||
// rather than restated, so the printed statement and the screen
|
||||
// cannot drift apart — and so this keeps the database
|
||||
// qualifier that spares the insurance line's own EFECTIVO.
|
||||
notCashJournal(),
|
||||
],
|
||||
}),
|
||||
},
|
||||
orderBy: [{ transactionDate: "asc" }, { id: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
@@ -847,8 +1048,12 @@ const edoCuentaDatos: ReportDef = {
|
||||
// EDO CUENTA sheet reads. Rows from earlier years still move the running
|
||||
// balance — they are folded into `opening` and printed as a single "saldo
|
||||
// anterior" line, which is what a BALANCE FORWARD row is.
|
||||
const yearStart = new Date(Date.UTC(new Date().getUTCFullYear(), 0, 1));
|
||||
const year = yearStart.getUTCFullYear();
|
||||
// An archive needs no fold: it *is* the period, and its own Jan-1 BALANCE
|
||||
// FORWARD row is the carry, printed like legacy printed it.
|
||||
const yearStart = isArchive
|
||||
? new Date(0)
|
||||
: new Date(Date.UTC(requestedYear, 0, 1));
|
||||
const year = requestedYear;
|
||||
|
||||
const running = new Map<string, Prisma.Decimal>();
|
||||
const opening = new Map<string, Prisma.Decimal>();
|
||||
@@ -928,6 +1133,7 @@ const edoCuentaDatos: ReportDef = {
|
||||
{
|
||||
__kind: "header",
|
||||
name: nameOf(customer),
|
||||
numid,
|
||||
address: customer.addressLine1 ?? "",
|
||||
city: [customer.city, customer.state].filter(Boolean).join(", "),
|
||||
phone: customer.phone ?? "",
|
||||
@@ -945,7 +1151,7 @@ const edoCuentaDatos: ReportDef = {
|
||||
...carried,
|
||||
...movements,
|
||||
],
|
||||
subtitle: `${nameOf(customer)} · ${year} · ${visible.length} movimientos`,
|
||||
subtitle: `NUMid ${numid} · ${nameOf(customer)} · ${year} · ${visible.length} movimientos`,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -983,6 +1189,7 @@ const chequeCount: ReportDef = {
|
||||
},
|
||||
],
|
||||
columns: [
|
||||
NUMID_COLUMN,
|
||||
{ key: "customerName", label: "Cliente", type: "text" },
|
||||
{ key: "reference", label: "Referencia", type: "text" },
|
||||
{ key: "period", label: "Periodo", type: "text" },
|
||||
@@ -1012,7 +1219,7 @@ const chequeCount: ReportDef = {
|
||||
period: true,
|
||||
outstanding: true,
|
||||
type: { select: { nameEn: true, nameEs: true } },
|
||||
customer: { select: { name: true, nameMissing: true } },
|
||||
customer: { select: { id: true, name: true, nameMissing: true } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1038,8 +1245,10 @@ const chequeCount: ReportDef = {
|
||||
}
|
||||
if (outstandingCount) totalsOut["sin fondos"] = outstandingCount;
|
||||
|
||||
const nums = await legacyNumbers(prisma, rows.map((r) => r.customer.id));
|
||||
return {
|
||||
rows: rows.map((r) => ({
|
||||
numid: nums.numid(r.customer.id),
|
||||
customerName: nameOf(r.customer),
|
||||
reference: r.reference ?? "—",
|
||||
period: r.period ?? "—",
|
||||
|
||||
@@ -24,7 +24,7 @@ import type { ConfirmBatchDto, ReviewDocumentDto } from "./statement.dto";
|
||||
* `TYPE OF TRX` values already in `type_transactions`, resolved by name once
|
||||
* per confirm rather than hard-coded as ids, which differ per environment.
|
||||
*/
|
||||
const CONCEPT_BY_KIND: Partial<Record<ServiceKind, string>> = {
|
||||
export const CONCEPT_BY_KIND: Partial<Record<ServiceKind, string>> = {
|
||||
ELECTRIC: "ELECTRIC",
|
||||
WATER: "WATER",
|
||||
TELEPHONE: "TELEPHONE",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@jorgecuadros/web",
|
||||
"version": "1.0.23",
|
||||
"version": "1.0.26",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev -p 4500",
|
||||
|
||||
@@ -128,6 +128,7 @@ function Detail({ id }: { id: string }) {
|
||||
customerId={data.id}
|
||||
summary={data.transactionSummary}
|
||||
transactions={data.transactions}
|
||||
year={data.transactionYear}
|
||||
/>
|
||||
<DocumentosSection data={data} />
|
||||
</div>
|
||||
@@ -746,16 +747,18 @@ function EstadoCuentaSection({
|
||||
customerId,
|
||||
summary,
|
||||
transactions,
|
||||
year,
|
||||
}: {
|
||||
customerId: string;
|
||||
summary: TransactionSummaryRow[];
|
||||
transactions: Transaction[];
|
||||
year: number;
|
||||
}) {
|
||||
return (
|
||||
<section className="section">
|
||||
<SectionHead
|
||||
rule="cuenta"
|
||||
title="Estado de cuenta"
|
||||
title={`Estado de cuenta ${year}`}
|
||||
count={transactions.length}
|
||||
countSuffix="movimientos"
|
||||
/>
|
||||
@@ -782,7 +785,7 @@ function EstadoCuentaSection({
|
||||
|
||||
<div className="card">
|
||||
{transactions.length === 0 ? (
|
||||
<div className="empty-inline">Sin movimientos registrados.</div>
|
||||
<div className="empty-inline">Sin movimientos en {year}.</div>
|
||||
) : (
|
||||
<div className="tx-scroll">
|
||||
<table className="tx-table">
|
||||
@@ -804,11 +807,11 @@ function EstadoCuentaSection({
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{transactions.length >= 100 && (
|
||||
<div className="section-note" style={{ padding: "0 16px 14px" }}>
|
||||
Mostrando los 100 movimientos más recientes.
|
||||
Movimientos de {year}, del más antiguo al más reciente. Los saldos de
|
||||
arriba son el saldo actual por línea de negocio — los mismos del
|
||||
estado de cuenta, no la suma del año.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{transactions.length > 0 && (
|
||||
<p className="section-note">
|
||||
|
||||
@@ -40,8 +40,10 @@ import type {
|
||||
* currency at a time — a column that alternated between pesos and dollars would
|
||||
* be a meaningless number.
|
||||
*
|
||||
* Like the legacy EDO CUENTA report, the table covers the current year only and
|
||||
* runs oldest-first, opening on the balance carried in from before it.
|
||||
* Like the legacy EDO CUENTA report, the table covers one calendar year and runs
|
||||
* oldest-first, opening on the balance carried in from before it. The period
|
||||
* selector switches years; earlier ones are served from the imported archive of
|
||||
* that year, which is how legacy kept them — one table per closed year.
|
||||
*/
|
||||
export default function EstadoCuentaDetailPage({
|
||||
params,
|
||||
@@ -67,19 +69,27 @@ function StatementView({ id }: { id: string }) {
|
||||
|
||||
const [currency, setCurrency] = useState<LedgerCurrency | null>(null);
|
||||
const [domain, setDomain] = useState<TransactionDomain | "">("");
|
||||
/** null = the current period; the API decides what that is. */
|
||||
const [year, setYear] = useState<number | null>(null);
|
||||
|
||||
function reload() {
|
||||
let alive = true;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
getStatement(id)
|
||||
getStatement(id, year ?? undefined)
|
||||
.then((d) => {
|
||||
if (!alive) return;
|
||||
setData(d);
|
||||
// Default to the currency the customer actually moves the most in;
|
||||
// preserve a previously-chosen currency across reloads.
|
||||
// preserve a previously-chosen currency across reloads — but only if
|
||||
// the loaded period still has it. Switching to a year the customer
|
||||
// never moved dollars in would otherwise leave the picker on USD with
|
||||
// no matching option, showing an empty table for a year that has rows.
|
||||
const busiest = [...d.summary].sort((a, b) => b.count - a.count)[0];
|
||||
setCurrency((prev) => prev ?? busiest?.currency ?? "MXN");
|
||||
const fallback = busiest?.currency ?? "MXN";
|
||||
setCurrency((prev) =>
|
||||
prev && d.summary.some((s) => s.currency === prev) ? prev : fallback,
|
||||
);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch((e) => {
|
||||
@@ -101,7 +111,7 @@ function StatementView({ id }: { id: string }) {
|
||||
getBillingFacets().then(setFacets).catch(() => setFacets(null));
|
||||
return cleanup;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id]);
|
||||
}, [id, year]);
|
||||
|
||||
const movements = useMemo(() => {
|
||||
if (!data || !currency) return [];
|
||||
@@ -229,6 +239,26 @@ function StatementView({ id }: { id: string }) {
|
||||
)}
|
||||
|
||||
<div className="filter-row">
|
||||
{/* Only the periods this customer has. A year with no archive would
|
||||
render an empty table that reads as "no hubo movimientos" when the
|
||||
truth is that the year was never imported. */}
|
||||
{data.availableYears.length > 1 && (
|
||||
<label className="filter-field">
|
||||
<span className="filter-label">Periodo</span>
|
||||
<select
|
||||
className="input select"
|
||||
value={data.year}
|
||||
onChange={(e) => setYear(Number(e.target.value))}
|
||||
>
|
||||
{data.availableYears.map((y) => (
|
||||
<option key={y} value={y}>
|
||||
{y}
|
||||
{y === data.availableYears[0] ? " (en curso)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="filter-field">
|
||||
<span className="filter-label">Moneda</span>
|
||||
<select
|
||||
|
||||
@@ -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 */}
|
||||
|
||||
@@ -4,7 +4,13 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import { useCan } from "@/lib/abilities";
|
||||
import { formatDate, formatMoney } from "@/lib/labels";
|
||||
import { NotificationLogPanel } from "@/components/NotificationLogPanel";
|
||||
import { apiFetch, POLIZAS_LOG_SCOPE, type NotificationFlags } from "@/lib/api";
|
||||
import {
|
||||
apiFetch,
|
||||
getLookups,
|
||||
POLIZAS_LOG_SCOPE,
|
||||
type NotificationFlags,
|
||||
} from "@/lib/api";
|
||||
import type { ProviderRow } from "@/lib/types";
|
||||
|
||||
/**
|
||||
* Renewal notices — the "Pólizas" half of /notificaciones. Shows which
|
||||
@@ -22,6 +28,12 @@ import { apiFetch, POLIZAS_LOG_SCOPE, type NotificationFlags } from "@/lib/api";
|
||||
* thing here as it does for servicios: the mail is diverted to the override
|
||||
* inbox. It additionally does NOT mark the notice as sent, so a test send
|
||||
* leaves the row exactly where it was — pending.
|
||||
*
|
||||
* The barrido manual is scoped by aseguradora because the office works GMX and
|
||||
* ANA as separate batches. The selection filters the pending list too, so what
|
||||
* is on screen is exactly what "Ejecutar barrido" will mail. A carrier-scoped
|
||||
* run deliberately does not advance the sweep's catch-up window — it only
|
||||
* covered one carrier — so the other carriers' letters stay pending.
|
||||
*/
|
||||
|
||||
export interface RenewalLetter {
|
||||
@@ -46,6 +58,8 @@ export interface RenewalSweepResult {
|
||||
failed: number;
|
||||
failures: { policyId: string; generation: number; error: string }[];
|
||||
debug: boolean;
|
||||
/** Echoed back so the confirmation says which carrier actually ran. */
|
||||
providerId: string | null;
|
||||
}
|
||||
|
||||
export interface RenewalSendResult {
|
||||
@@ -68,6 +82,10 @@ export function NotificacionesPolizas({ flags }: { flags: NotificationFlags }) {
|
||||
const allowed = useCan("renewal:send");
|
||||
const debug = !!flags.debug;
|
||||
const [days, setDays] = useState(30);
|
||||
/** "" = ambas/todas. Holds an InsuranceProvider id, never a name — carriers
|
||||
* are renamed in the lookups screen and the filter must survive that. */
|
||||
const [providerId, setProviderId] = useState("");
|
||||
const [providers, setProviders] = useState<ProviderRow[]>([]);
|
||||
const [pending, setPending] = useState<RenewalLetter[] | null>(null);
|
||||
const [pendingError, setPendingError] = useState<string | null>(null);
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
@@ -81,8 +99,10 @@ export function NotificacionesPolizas({ flags }: { flags: NotificationFlags }) {
|
||||
const refresh = useCallback(async () => {
|
||||
setPendingError(null);
|
||||
try {
|
||||
const params = new URLSearchParams({ days: String(days) });
|
||||
if (providerId) params.set("providerId", providerId);
|
||||
const data = await apiFetch<RenewalLetter[]>(
|
||||
`/renewals/pending?days=${days}`,
|
||||
`/renewals/pending?${params.toString()}`,
|
||||
);
|
||||
setPending(data);
|
||||
} catch (e) {
|
||||
@@ -91,18 +111,44 @@ export function NotificacionesPolizas({ flags }: { flags: NotificationFlags }) {
|
||||
);
|
||||
setPending([]);
|
||||
}
|
||||
}, [days]);
|
||||
}, [days, providerId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (allowed) refresh();
|
||||
}, [allowed, refresh]);
|
||||
|
||||
// Carriers come from the same lookups the policy form uses, so a new
|
||||
// aseguradora shows up here without a code change.
|
||||
useEffect(() => {
|
||||
if (!allowed) return;
|
||||
let cancelled = false;
|
||||
getLookups()
|
||||
.then((data) => {
|
||||
if (!cancelled) setProviders(data.providers);
|
||||
})
|
||||
.catch(() => {
|
||||
// A failed lookup only costs the filter; the unfiltered sweep still
|
||||
// works, so this must not blank the screen.
|
||||
if (!cancelled) setProviders([]);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [allowed]);
|
||||
|
||||
const providerLabel =
|
||||
providers.find((item) => item.id === providerId)?.name ?? "todas las compañías";
|
||||
|
||||
async function handleSweep() {
|
||||
// Only worth confirming when debug is off — that is the case where real
|
||||
// customers receive mail. Mirrors "Ejecutar todos" on the servicios tab.
|
||||
// The carrier is named in the prompt: running GMX when ANA was meant is
|
||||
// exactly the mistake this filter exists to prevent, and it is not
|
||||
// reversible once the mail is out.
|
||||
if (!debug) {
|
||||
const ok = window.confirm(
|
||||
"debug está desactivado: los avisos irán a los correos reales de los clientes. ¿Ejecutar el barrido?",
|
||||
`debug está desactivado: los avisos irán a los correos reales de los clientes. ` +
|
||||
`¿Ejecutar el barrido de ${providerLabel}?`,
|
||||
);
|
||||
if (!ok) return;
|
||||
}
|
||||
@@ -112,10 +158,11 @@ export function NotificacionesPolizas({ flags }: { flags: NotificationFlags }) {
|
||||
try {
|
||||
const result = await apiFetch<RenewalSweepResult>("/renewals/sweep", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ debug }),
|
||||
body: JSON.stringify({ debug, providerId: providerId || undefined }),
|
||||
});
|
||||
setNotice(
|
||||
`Enviados ${result.sent} avisos (${result.failed} con error).` +
|
||||
`Enviados ${result.sent} avisos de ${providerLabel} ` +
|
||||
`(${result.failed} con error).` +
|
||||
(result.debug
|
||||
? " Modo debug: fueron al buzón de pruebas y siguen pendientes."
|
||||
: ""),
|
||||
@@ -199,7 +246,9 @@ export function NotificacionesPolizas({ flags }: { flags: NotificationFlags }) {
|
||||
<h2 className="section-title">Barrido manual</h2>
|
||||
<p className="muted small" style={{ marginTop: 4 }}>
|
||||
Usa la fecha actual del servidor como referencia para seleccionar
|
||||
avisos vencidos a 30 y 15 días, y vencidos hace 7 días.
|
||||
avisos vencidos a 30 y 15 días, y vencidos hace 7 días. La
|
||||
compañía elegida filtra también la lista de abajo: se envía
|
||||
exactamente lo que está en pantalla.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
@@ -211,7 +260,11 @@ export function NotificacionesPolizas({ flags }: { flags: NotificationFlags }) {
|
||||
{sweeping ? "Enviando…" : "Ejecutar barrido"}
|
||||
</button>
|
||||
</div>
|
||||
<div className="field" style={{ maxWidth: 180, marginTop: 12, marginBottom: 0 }}>
|
||||
<div
|
||||
className="row-actions"
|
||||
style={{ marginTop: 12, alignItems: "flex-end", gap: 16 }}
|
||||
>
|
||||
<div className="field" style={{ maxWidth: 180, marginBottom: 0 }}>
|
||||
<span className="field-label">Ventana (días)</span>
|
||||
<input
|
||||
className="input"
|
||||
@@ -224,6 +277,22 @@ export function NotificacionesPolizas({ flags }: { flags: NotificationFlags }) {
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="field" style={{ maxWidth: 260, marginBottom: 0 }}>
|
||||
<span className="field-label">Compañía</span>
|
||||
<select
|
||||
className="input"
|
||||
value={providerId}
|
||||
onChange={(e) => setProviderId(e.target.value)}
|
||||
>
|
||||
<option value="">Todas las compañías</option>
|
||||
{providers.map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{pendingError && <div className="state-box state-error">{pendingError}</div>}
|
||||
|
||||
@@ -390,6 +390,9 @@ function StatementLayout({ result }: { result: ReportRunResult }) {
|
||||
<div className="statement">
|
||||
<header className="statement-head">
|
||||
<h2 className="statement-name">{String(header.name ?? "—")}</h2>
|
||||
{header.numid && header.numid !== "—" ? (
|
||||
<p className="muted">NUMid {String(header.numid)}</p>
|
||||
) : null}
|
||||
{Boolean(header.address) && (
|
||||
<p className="muted">{String(header.address)}</p>
|
||||
)}
|
||||
|
||||
@@ -615,8 +615,13 @@ export function getBillingFacets(): Promise<BillingFacets> {
|
||||
return apiFetch<BillingFacets>("/billing/facets");
|
||||
}
|
||||
|
||||
export function getStatement(customerId: string): Promise<Statement> {
|
||||
return apiFetch<Statement>(`/billing/customers/${customerId}`);
|
||||
/** `year` omitted reads the current period; earlier years come from an archive. */
|
||||
export function getStatement(
|
||||
customerId: string,
|
||||
year?: number,
|
||||
): Promise<Statement> {
|
||||
const q = year === undefined ? "" : `?year=${year}`;
|
||||
return apiFetch<Statement>(`/billing/customers/${customerId}${q}`);
|
||||
}
|
||||
|
||||
/** Append a new ledger movement. Booked movements are never edited — fix
|
||||
|
||||
@@ -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 {
|
||||
@@ -1094,6 +1096,13 @@ export interface Statement {
|
||||
};
|
||||
/** Calendar year the statement covers; movements are scoped to it. */
|
||||
year: number;
|
||||
/**
|
||||
* Periods this customer actually has, newest first. The current year is
|
||||
* always present; each earlier year comes from an imported archive. Offering
|
||||
* anything outside this list would render an empty statement that reads as
|
||||
* "no activity" rather than "not imported".
|
||||
*/
|
||||
availableYears: number[];
|
||||
summary: StatementSummary[];
|
||||
byDomain: StatementDomainRow[];
|
||||
byType: StatementTypeRow[];
|
||||
@@ -1129,6 +1138,8 @@ export interface CustomerDetail {
|
||||
properties: Property[];
|
||||
policies: Policy[];
|
||||
transactions: Transaction[];
|
||||
/** Calendar year `transactions` covers. */
|
||||
transactionYear: number;
|
||||
transactionSummary: TransactionSummaryRow[];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Delete unused images from the target host after a successful deploy.
|
||||
*
|
||||
* This exists because nothing else reclaims them. Every build.yml run pushes a
|
||||
* new api + web image, every deploy pulls both onto the host, and the previous
|
||||
* pair is left behind untagged-but-present forever. On galactus that reached
|
||||
* 63 images / 83.85GB (79.26GB of it unused) and filled the 98GB root
|
||||
* filesystem to 100% on 2026-08-20 — which surfaced as "re-import is broken",
|
||||
* because the Operaciones REIMPORT job leads with a mysqldump that could no
|
||||
* longer write its safety backup.
|
||||
*
|
||||
* Two things keep this from eating a live deployment:
|
||||
*
|
||||
* - Docker never prunes an image that a container references, running or
|
||||
* stopped. The five images the prod stacks use are therefore untouchable
|
||||
* for as long as their containers exist.
|
||||
* - `until` gives a grace window on top of that, so a rollback target stays
|
||||
* on disk instead of forcing a re-pull from the registry.
|
||||
*
|
||||
* TRAP: `until` filters on the image's CREATION time, not when the host pulled
|
||||
* it. Rolling back to an old tag pulls an image that is already older than the
|
||||
* window, so the grace period does NOT protect it — the running-container rule
|
||||
* is what does. That is why this step must run AFTER the app stack is deployed
|
||||
* and verified, never before.
|
||||
*
|
||||
* Required env:
|
||||
* PORTAINER_URL, PORTAINER_API_KEY, PORTAINER_ENDPOINT_ID
|
||||
* Optional:
|
||||
* KEEP_HOURS grace window in hours (default 168 = 7 days)
|
||||
*
|
||||
* TLS: Portainer here is self-signed; the caller sets
|
||||
* NODE_TLS_REJECT_UNAUTHORIZED=0 for this step.
|
||||
*/
|
||||
|
||||
function required(name) {
|
||||
const v = process.env[name];
|
||||
if (!v) {
|
||||
console.error(`missing required env: ${name}`);
|
||||
process.exit(1);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
const PORTAINER_URL = required("PORTAINER_URL").replace(/\/+$/, "");
|
||||
const API_KEY = required("PORTAINER_API_KEY");
|
||||
const ENDPOINT_ID = required("PORTAINER_ENDPOINT_ID");
|
||||
const KEEP_HOURS = process.env.KEEP_HOURS || "168";
|
||||
|
||||
const DOCKER = `${PORTAINER_URL}/api/endpoints/${ENDPOINT_ID}/docker`;
|
||||
|
||||
// `dangling: ["false"]` is what makes this `docker image prune -a` rather than
|
||||
// the default, which only collects untagged layers. The tagged-but-superseded
|
||||
// api/web images are the whole problem, and the default filter walks straight
|
||||
// past them.
|
||||
const FILTERS = JSON.stringify({
|
||||
dangling: ["false"],
|
||||
until: [`${KEEP_HOURS}h`],
|
||||
});
|
||||
|
||||
function human(bytes) {
|
||||
if (!bytes) return "0B";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
let i = 0;
|
||||
let n = bytes;
|
||||
while (n >= 1024 && i < units.length - 1) {
|
||||
n /= 1024;
|
||||
i += 1;
|
||||
}
|
||||
return `${n.toFixed(i === 0 ? 0 : 2)}${units[i]}`;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const url = `${DOCKER}/images/prune?filters=${encodeURIComponent(FILTERS)}`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "X-API-Key": API_KEY },
|
||||
});
|
||||
const body = await res.text();
|
||||
if (!res.ok) {
|
||||
throw new Error(`prune -> HTTP ${res.status} ${body.slice(0, 300)}`);
|
||||
}
|
||||
|
||||
let report;
|
||||
try {
|
||||
report = JSON.parse(body);
|
||||
} catch {
|
||||
throw new Error(`prune returned non-JSON: ${body.slice(0, 300)}`);
|
||||
}
|
||||
|
||||
const deleted = report.ImagesDeleted ?? [];
|
||||
const reclaimed = report.SpaceReclaimed ?? 0;
|
||||
console.log(
|
||||
`pruned images older than ${KEEP_HOURS}h and unused by any container`,
|
||||
);
|
||||
console.log(` entries removed : ${deleted.length}`);
|
||||
console.log(` space reclaimed : ${human(reclaimed)}`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
// Non-fatal by contract: the step that calls this sets continue-on-error, so
|
||||
// housekeeping never turns a good deploy red. Exit non-zero anyway so the
|
||||
// failure is visible in the run rather than swallowed.
|
||||
console.error(`::warning::image prune FAILED: ${err.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -18,6 +18,7 @@ the four Access source files.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
# The folder holding the four Access source files. Overridable via INGEST_DIR so
|
||||
@@ -95,3 +96,59 @@ SOURCES = {
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# --- prior-period archives ----------------------------------------------
|
||||
#
|
||||
# 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. Access keeps the closed year as a whole-database snapshot named for
|
||||
# the period it holds — `2025.accdb` is UTILITIES as it stood when 2025 was
|
||||
# cut — and the office archives one per year.
|
||||
#
|
||||
# Only the ledger is staged out of a snapshot. Everything else in it (DATMEX,
|
||||
# PROFILE, EFECTIVO, ...) is a year-stale copy of a table the live
|
||||
# UTILITIES.accdb already provides, and staging all ~50 of them would triple
|
||||
# the extract time to import data we would then have to ignore. DATGRAL comes
|
||||
# along solely to check that a NUMid still means the same customer it did that
|
||||
# year; see the recycle guard in transform_transactions.py.
|
||||
#
|
||||
# The cash side is deliberately NOT taken from the snapshot: `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_FILE_RE = re.compile(r"^(\d{4})\.accdb$", re.IGNORECASE)
|
||||
PERIOD_TABLES = {"datos2", "DATGRAL"}
|
||||
|
||||
|
||||
def period_schema(year: int) -> str:
|
||||
return f"stg_period_{year}"
|
||||
|
||||
|
||||
def discover_periods(root: Path) -> dict[str, dict]:
|
||||
"""Find every `YYYY.accdb` archive sitting in the ingest folder.
|
||||
|
||||
Discovery is by filename because that is the whole upload contract: the
|
||||
operator drops `2025.accdb` on the Operaciones page and the period is 2025.
|
||||
Nothing inside the file names the year — a snapshot's `datos2` looks
|
||||
identical to the live one — so the name is the only declaration of intent
|
||||
we get, and it is what the allowlist on the upload endpoint enforces.
|
||||
"""
|
||||
found: dict[str, dict] = {}
|
||||
if not root.is_dir():
|
||||
return found
|
||||
for path in sorted(root.iterdir()):
|
||||
m = PERIOD_FILE_RE.match(path.name)
|
||||
if not m:
|
||||
continue
|
||||
year = int(m.group(1))
|
||||
found[f"period_{year}"] = {
|
||||
"path": path,
|
||||
"schema": period_schema(year),
|
||||
"exclude": set(),
|
||||
"include": set(PERIOD_TABLES),
|
||||
"period_year": year,
|
||||
}
|
||||
return found
|
||||
|
||||
|
||||
SOURCES.update(discover_periods(SOURCE_ROOT))
|
||||
@@ -40,6 +40,17 @@ def stage_source(source_name: str, source_cfg: dict, sink) -> None:
|
||||
tables = extract.list_tables(cnxn)
|
||||
excluded = source_cfg["exclude"]
|
||||
|
||||
# A source may name the only tables it is worth staging. Prior-period
|
||||
# archives do: they are whole-database snapshots, but everything in them
|
||||
# except the ledger is a year-stale copy of a live table, so staging the
|
||||
# rest costs minutes per file to produce data nothing reads.
|
||||
include = source_cfg.get("include")
|
||||
if include is not None:
|
||||
missing = include - set(tables)
|
||||
if missing:
|
||||
print(f" [WARN] {source_name}: missing expected table(s) {sorted(missing)}", file=sys.stderr)
|
||||
tables = [t for t in tables if t in include]
|
||||
|
||||
for table_name in tables:
|
||||
if table_name in excluded:
|
||||
print(f" [exclude] {table_name}")
|
||||
|
||||
@@ -164,18 +164,21 @@ def main():
|
||||
services.append((str(uuid.uuid4()), pid, kind, account, meter, route,
|
||||
due, 1 if active else 0, notes))
|
||||
|
||||
# WATER (primary + extra meters)
|
||||
# WATER — the CESPT account only. DATMEX has no water meter column.
|
||||
if s(row["agua"]) or flag("water1", False):
|
||||
svc("WATER", account=s(row["agua"]), meter=s(row["medidor"]),
|
||||
route=s(row["ruta"]), due=s(row["diagua"]), active=flag("water1"))
|
||||
for mcol, rcol in (("medidor2", "ruta2"), ("medidor3", "ruta3")):
|
||||
if s(row[mcol]) or s(row[rcol]):
|
||||
svc("WATER", meter=s(row[mcol]), route=s(row[rcol]),
|
||||
notes="secondary meter", active=flag("water1"))
|
||||
# ELECTRIC (rpu account + extras); luz_tipo as note
|
||||
for rc in ("rpu", "rpu2", "rpu3"):
|
||||
if s(row[rc]):
|
||||
svc("ELECTRIC", account=s(row[rc]),
|
||||
svc("WATER", account=s(row["agua"]), due=s(row["diagua"]),
|
||||
active=flag("water1"))
|
||||
# ELECTRIC — rpu account + the CFE meter and route beside it. MEDIDOR/
|
||||
# RUTA are the electric meter, not water: they are filled on exactly
|
||||
# the 1113 rows that carry an RPU (100% overlap), the meters are CFE's
|
||||
# alphanumeric `53MT58` form, and every legacy query that reads them is
|
||||
# a LUZ one (LUZ, FALTANTES DE LUZ, "luz ruta 325 y 329"). They used to
|
||||
# land on the WATER row, leaving every electric service without a meter.
|
||||
# Paired by suffix: medidor2/ruta2 belong to rpu2. luz_tipo as note.
|
||||
for rc, mc, rtc in (("rpu", "medidor", "ruta"), ("rpu2", "medidor2", "ruta2"),
|
||||
("rpu3", "medidor3", "ruta3")):
|
||||
if s(row[rc]) or s(row[mc]):
|
||||
svc("ELECTRIC", account=s(row[rc]), meter=s(row[mc]), route=s(row[rtc]),
|
||||
notes=s(row["luz_tipo"]) if rc == "rpu" else None,
|
||||
active=flag("electric"))
|
||||
# GAS — the column mixes two things: an account/meter number for 160 of
|
||||
|
||||
@@ -90,6 +90,62 @@ def load(src, name):
|
||||
return df
|
||||
|
||||
|
||||
def verify_corte(c, year: int) -> None:
|
||||
"""Assert legacy's corte identity: SUM(period Y) == BALANCE FORWARD(Y+1).
|
||||
|
||||
This is the whole reason a year can be shown on its own. Legacy closed each
|
||||
year by summing it and writing that total back as every customer's Jan-1
|
||||
opening row for the next one, so if an archive is the right file, complete,
|
||||
and attached to the right customers, its per-customer total lands exactly on
|
||||
the next year's BALANCE FORWARD. A truncated export, a file dropped under
|
||||
the wrong year, or a botched customer match all break the identity loudly
|
||||
here instead of quietly six months from now.
|
||||
|
||||
Reported, never fatal. Legacy publishes on its own schedule, so a handful of
|
||||
customers legitimately drift between the snapshot and the cut — the run that
|
||||
established this reconciled 1,160 of 1,170.
|
||||
"""
|
||||
c.execute(
|
||||
"""
|
||||
SELECT sums.customerId, sums.total, bf.amount
|
||||
FROM (
|
||||
SELECT customerId, ROUND(SUM(amount), 2) AS total
|
||||
FROM transactions
|
||||
WHERE legacySourceTable = %s AND voidedAt IS NULL
|
||||
GROUP BY customerId
|
||||
) sums
|
||||
LEFT JOIN (
|
||||
SELECT t.customerId, ROUND(SUM(t.amount), 2) AS amount
|
||||
FROM transactions t
|
||||
JOIN type_transactions tt ON tt.id = t.typeId
|
||||
WHERE tt.nameEn = 'BALANCE FORWARD' AND t.voidedAt IS NULL
|
||||
AND t.transactionDate >= %s AND t.transactionDate < %s
|
||||
GROUP BY t.customerId
|
||||
) bf ON bf.customerId = sums.customerId
|
||||
""",
|
||||
(f"datos2@{year}", f"{year + 1}-01-01", f"{year + 1}-01-02"),
|
||||
)
|
||||
rows = c.fetchall()
|
||||
matched = mismatched = 0
|
||||
missing = 0
|
||||
drift = Decimal(0)
|
||||
for _cid, total, amount in rows:
|
||||
if amount is None:
|
||||
missing += 1
|
||||
continue
|
||||
if abs(Decimal(str(total)) - Decimal(str(amount))) < Decimal("0.02"):
|
||||
matched += 1
|
||||
else:
|
||||
mismatched += 1
|
||||
drift += abs(Decimal(str(total)) - Decimal(str(amount)))
|
||||
checked = matched + mismatched
|
||||
pct = (100 * matched / checked) if checked else 0
|
||||
print(
|
||||
f" corte {year} -> BF {year + 1}: {matched}/{checked} match ({pct:.1f}%)"
|
||||
f", {mismatched} off by {drift:,.2f}, {missing} with no BF row"
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
env, sync_mode = parse_mode()
|
||||
conn = connect(env)
|
||||
@@ -230,9 +286,13 @@ def main():
|
||||
message=s(r["conepto"]), check=s(r[check_col]) if check_col else None,
|
||||
src_db="UTILITIES", src_tbl=legacy_tbl, legacy=str(int(r["_row_num"])))
|
||||
|
||||
def billing(name, legacy_tbl):
|
||||
def billing(name, legacy_tbl, *, src="stg_utilities", skip_numids=None):
|
||||
"""Load a DATOS2-shaped billing ledger.
|
||||
|
||||
`src` names the staging schema, so a prior-period archive
|
||||
(stg_period_2025) loads through this same path: the snapshot's `datos2`
|
||||
is the identical eleven-column shape, one year older.
|
||||
|
||||
NOPAGO is the legacy "still owed" flag. The website reads it directly —
|
||||
`account.statement.php` splits the statement on `NOPAGO = 0` vs
|
||||
`NOPAGO = 1` and renders the latter as the "Outstanding Bills Requiring
|
||||
@@ -241,10 +301,13 @@ def main():
|
||||
Only these three tables carry it (76 rows set in DATOS2 today); the
|
||||
EFECTIVO/FM3 cash streams have no such column and stay 0.
|
||||
"""
|
||||
nonlocal skip_cust, skip_date
|
||||
df = load("stg_utilities", name)
|
||||
nonlocal skip_cust, skip_date, skip_recycled
|
||||
df = load(src, name)
|
||||
for _, r in df.iterrows():
|
||||
cid = util_cust.get(norm_id(r["numid"]))
|
||||
numid = norm_id(r["numid"])
|
||||
if skip_numids and numid in skip_numids:
|
||||
skip_recycled += 1; continue
|
||||
cid = util_cust.get(numid)
|
||||
if not cid:
|
||||
skip_cust += 1; continue
|
||||
td = dt(r["date"])
|
||||
@@ -257,6 +320,53 @@ def main():
|
||||
legacy=str(int(r["_row_num"])),
|
||||
outstanding=1 if s(r["nopago"]) == "1" else 0)
|
||||
|
||||
skip_recycled = 0
|
||||
recycle_report: list[tuple[int, str, str, str]] = []
|
||||
|
||||
def period_numid_guard(year: int) -> set[str]:
|
||||
"""NUMids whose prior-period owner is not today's customer.
|
||||
|
||||
Prior-period rows attach by NUMid and nothing else, so a number the
|
||||
office retired and reissued would file one customer's ledger under
|
||||
another's name — the one error this feature must never make, because it
|
||||
shows a stranger's charges to whoever holds the number now.
|
||||
|
||||
Reuse is real but rare: 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 — a typo fixed (VIKIE -> VICKIE), a spouse added
|
||||
or dropped (STEWART, ALAN R. -> STEWART, ALAN & JENNIFER). A few are
|
||||
genuinely a different household (STRONKS, BOB -> SWEET, DONALD E.).
|
||||
|
||||
Sharing any word of three or more characters separates the two cleanly:
|
||||
a rename keeps the surname, a reissue keeps nothing. Names are compared
|
||||
legacy-to-legacy, archive DATGRAL against live DATGRAL, deliberately not
|
||||
against `customers.name` — that column has been through the blank-name
|
||||
recovery pass, and comparing to it reported 121 drifts where there are
|
||||
13, every extra one a false positive that would have discarded good
|
||||
history.
|
||||
"""
|
||||
try:
|
||||
arch = load(f"stg_period_{year}", "datgral")
|
||||
live = load("stg_utilities", "datgral")
|
||||
except (FileNotFoundError, OSError):
|
||||
return set()
|
||||
|
||||
def toks(v) -> set[str]:
|
||||
return {w for w in "".join(ch if ch.isalnum() else " " for ch in (s(v) or "").upper()).split() if len(w) >= 3}
|
||||
|
||||
live_names = {norm_id(r["num_id"]): s(r["nombre"]) for _, r in live.iterrows()}
|
||||
blocked: set[str] = set()
|
||||
for _, r in arch.iterrows():
|
||||
numid = norm_id(r["num_id"])
|
||||
was, now = s(r["nombre"]), live_names.get(numid)
|
||||
if not numid or not was or not now:
|
||||
continue
|
||||
if toks(was) & toks(now):
|
||||
continue
|
||||
blocked.add(numid)
|
||||
recycle_report.append((year, numid, was, now))
|
||||
return blocked
|
||||
|
||||
def iva():
|
||||
nonlocal skip_cust
|
||||
df = load("stg_utilities", "iva_2015")
|
||||
@@ -286,6 +396,31 @@ def main():
|
||||
billing("fee_anual", "FEE ANUAL")
|
||||
billing("fee15", "fee15")
|
||||
iva()
|
||||
|
||||
# --- prior periods -----------------------------------------------------
|
||||
#
|
||||
# Legacy kept each closed year in its own table and opened the next one with
|
||||
# a Jan-1 BALANCE FORWARD carrying the closing total. The platform has one
|
||||
# `transactions` table, so the period a row belongs to has to travel with
|
||||
# the row: it rides 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's ledger carries ten undated rows and two
|
||||
# dated into 2026 — and legacy itself never filtered by date either: its
|
||||
# reader is `SELECT ... FROM \`2025\``. Keying on provenance reproduces the
|
||||
# legacy period exactly and strands nothing.
|
||||
#
|
||||
# The tag also keeps the unique key safe. legacyId is a positional row
|
||||
# ordinal, so every archive restarts it at 0 and would collide with the live
|
||||
# `datos2` row-for-row if they shared a source-table name.
|
||||
periods = sorted(
|
||||
int(d.name.rsplit("_", 1)[1])
|
||||
for d in STG.glob("stg_period_*")
|
||||
if d.is_dir() and d.name.rsplit("_", 1)[1].isdigit()
|
||||
)
|
||||
for year in periods:
|
||||
billing("datos2", f"datos2@{year}", src=f"stg_period_{year}",
|
||||
skip_numids=period_numid_guard(year))
|
||||
# Same record shape in the seguros DB. Labelled for consistency in the
|
||||
# platform's own UI; unverifiable against the site, which only ever reads
|
||||
# domain='UTILITY', so no customer-facing behaviour depends on it.
|
||||
@@ -334,6 +469,7 @@ def main():
|
||||
print(f" skipped (unresolved customer): {skip_cust}")
|
||||
print(f" skipped (unparseable date) : {skip_date}")
|
||||
print(f" skipped (EFECTIVO_BACKUP dup): {skip_dupe}")
|
||||
print(f" skipped (reissued NUMid) : {skip_recycled}")
|
||||
print(f" -> transactions : {count('transactions')}")
|
||||
print(f" by domain : {dict(by_dom)}")
|
||||
for src, n in by_src:
|
||||
@@ -342,6 +478,17 @@ def main():
|
||||
print(f" -> exchange_rates : {count('exchange_rates')}")
|
||||
print(f" orphan transactions (bad customer FK): {orphans}")
|
||||
assert orphans == 0, "transaction customer FK invariant failed"
|
||||
|
||||
if recycle_report:
|
||||
print(f" ! reissued NUMids, prior-period rows NOT imported: {len(recycle_report)}")
|
||||
for year, numid, was, now in recycle_report[:8]:
|
||||
print(f" {year} NUMid {numid}: '{was}' -> '{now}'")
|
||||
if len(recycle_report) > 8:
|
||||
print(f" ... {len(recycle_report) - 8} more")
|
||||
|
||||
for year in periods:
|
||||
verify_corte(c, year)
|
||||
|
||||
print(" validation: OK")
|
||||
conn.close()
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "jorgecuadros-platform",
|
||||
"version": "1.0.23",
|
||||
"version": "1.0.26",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"apps/*",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@jorgecuadros/database",
|
||||
"version": "1.0.23",
|
||||
"version": "1.0.26",
|
||||
"private": true,
|
||||
"main": "generated/client/index.js",
|
||||
"types": "generated/client/index.d.ts",
|
||||
|
||||
@@ -0,0 +1,550 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Corte (year-end cut) audit — READ ONLY. Writes nothing, voids nothing.
|
||||
*
|
||||
* Legacy Access ran a corte every year: it moved the year's utility movements
|
||||
* into a per-year table and stamped one BALANCE FORWARD row per customer,
|
||||
* dated Jan 1, carrying the closing balance. The platform inherited the ROWS
|
||||
* (1,170 of them, dated 2026-01-01 — legacy's last cut before the extract) but
|
||||
* not the PROCESS, and BillingService uses those rows as a per-customer floor
|
||||
* (BALANCE_FLOOR_JOIN / NOT_SUPERSEDED in apps/api/src/billing/billing.service.ts).
|
||||
*
|
||||
* This script reports the two populations that floor does not cover:
|
||||
*
|
||||
* A. FLOORLESS customers — no BALANCE FORWARD row at all, so their balance
|
||||
* is a raw lifetime sum. The platform only migrated the CURRENT-year
|
||||
* charge ledger (datos2); the per-year charge tables live in DreamHost
|
||||
* and were never staged. What survives before the cutover is therefore
|
||||
* a cash journal — receipts with no matching charges — so those sums read
|
||||
* as the office owing money it does not owe.
|
||||
*
|
||||
* READ THE COMPOSITION LINE BEFORE ACTING ON THIS. After the prior-period
|
||||
* import the group is mostly insurance-only customers whose rows come from
|
||||
* the seguros database's own EFECTIVO, which is that line's ONLY ledger.
|
||||
* Flooring those deletes receipts instead of removing a double count. The
|
||||
* "floor them, never carry" argument holds for the utilities rows alone.
|
||||
*
|
||||
* B. DOUBLE-BOOKED 2026 RECEIPTS — one cash receipt appearing twice, once in
|
||||
* EFECTIVO with folio `N` and once in datos2 with reference `CN`.
|
||||
*
|
||||
* This is NOT an office data-entry defect, which is what it looked like
|
||||
* while the pair count kept growing at ~40/month. EFECTIVO is the paper
|
||||
* receipt book and every receipt in it is POSTED to the datos2 ledger by
|
||||
* design — verified against the live legacy database, 296 of the 297
|
||||
* receipts written in 2026 carry a matching posting. Legacy summed the
|
||||
* ledger alone. The duplication was the migration flattening a journal and
|
||||
* its postings into one table, and since 1.0.26 the application drops the
|
||||
* journal from every balance. Section B now reports what the journal holds
|
||||
* and asserts that none of it still reaches a balance.
|
||||
*
|
||||
* The folio alone neither proves nor disproves a pair, so it is used as a
|
||||
* lead and never as the verdict. Folios are reused, so `C13483` can collide
|
||||
* with an unrelated receipt; folios are also mistyped, so a genuine pair can
|
||||
* carry two different numbers. Detection therefore runs twice — once on the
|
||||
* `CN` cross-reference, once over the C-refs that pass left orphaned, this
|
||||
* time on proximity alone (same customer, within three days) — and BOTH
|
||||
* passes are then judged on the money: identical amount when the two legs
|
||||
* share a currency, or an implied USD->MXN rate inside the band the
|
||||
* exchange_rates table actually observed that year. Anything that fails is
|
||||
* reported apart and must not be counted as duplicated money.
|
||||
*
|
||||
* The second pass is not a refinement. Jorge Jr's own account carries
|
||||
* `C13647` against EFECTIVO folio `13649` — same day, same 3,500.00 — and
|
||||
* POWERS carries `C135808` against `13508`. Folio matching alone reports
|
||||
* both accounts as clean.
|
||||
*
|
||||
* node scripts/corte-audit.mjs # summary + both sections
|
||||
* node scripts/corte-audit.mjs --cutover 2026-01-01
|
||||
* node scripts/corte-audit.mjs --csv-a # per-customer table, section A
|
||||
* node scripts/corte-audit.mjs --csv-b # per-pair table, section B
|
||||
* node scripts/corte-audit.mjs --limit 40 # rows printed per section
|
||||
*
|
||||
* Needs DATABASE_URL. Point it at PROD — a stale copy answers about itself.
|
||||
* On a database imported before the BALANCE FORWARD type was minted those rows
|
||||
* carry typeId NULL instead (see numid.service.ts:80), so the floor is matched
|
||||
* in BOTH shapes here; matching only the type name reports every customer as
|
||||
* floorless on such a copy.
|
||||
*/
|
||||
import pkg from "../packages/database/generated/client/index.js";
|
||||
|
||||
const { PrismaClient } = pkg;
|
||||
|
||||
/** Prisma hands raw DECIMAL back as Decimal|string|null; counts as BigInt. */
|
||||
const d = (v) => (v == null ? 0 : Number(v));
|
||||
const money = (v) => d(v).toFixed(2).padStart(13);
|
||||
/**
|
||||
* Raw DATE/DATETIME columns arrive as JS Date objects. String() would render
|
||||
* them in the host's local zone, which turns a row stored at 2026-01-01 00:00
|
||||
* UTC into "Dec 31" on a US Pacific laptop — the ledger is keyed on UTC dates
|
||||
* everywhere else, so format in UTC and nowhere else.
|
||||
*/
|
||||
const day = (v) => (v == null ? "—" : new Date(v).toISOString().slice(0, 10));
|
||||
|
||||
function arg(args, name, fallback = null) {
|
||||
const i = args.indexOf(name);
|
||||
return i === -1 ? fallback : args[i + 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* A row is a balance-forward marker in either of two shapes. Keep in step with
|
||||
* EMPTY_NUMID_SQL in apps/api/src/customers/numid.service.ts.
|
||||
*/
|
||||
const BF_PREDICATE = `(
|
||||
tt.nameEn = 'BALANCE FORWARD'
|
||||
OR (t.typeId IS NULL AND MONTH(t.transactionDate) = 1 AND DAY(t.transactionDate) = 1
|
||||
AND t.legacySourceTable = 'datos2')
|
||||
)`;
|
||||
|
||||
/**
|
||||
* The rest of what a balance query drops, over and above the floor. Mirrors
|
||||
* NOT_CASH_JOURNAL and archiveIsHistorySql in billing.service.ts — an audit
|
||||
* that computes a different book than the application is worse than no audit,
|
||||
* because its numbers look authoritative and diff cleanly against yesterday's.
|
||||
*
|
||||
* The database qualifier is not decoration. `SEGUROS 16_be` keeps its own table
|
||||
* called EFECTIVO and that one is the insurance line's only ledger; matching on
|
||||
* the table name alone would report 55,444.95 USD of real receivables as
|
||||
* duplicate cash. See efectivo-is-a-journal-not-a-ledger.
|
||||
*/
|
||||
const NOT_CASH_JOURNAL = `(
|
||||
t.legacySourceDb IS NULL
|
||||
OR t.legacySourceDb <> 'UTILITIES'
|
||||
OR t.legacySourceTable IS NULL
|
||||
OR t.legacySourceTable NOT IN
|
||||
('EFECTIVO', 'EFECTIVO_BACKUP', 'EFECTIVO FM3', 'CHEQUE FM3', 'IVA 2015')
|
||||
)`;
|
||||
|
||||
/**
|
||||
* An imported period counts as history below the year start and is dropped at
|
||||
* or above it. Spelled as a positive OR: `NOT (col LIKE ... AND ...)` is NULL
|
||||
* for an app-captured row, which would silently drop every one.
|
||||
*
|
||||
* The bound is the running calendar year, matching currentYearStart() in the
|
||||
* application rather than the cutover — the app's current period is "this
|
||||
* year", whatever cut the data happens to reflect.
|
||||
*/
|
||||
const yearStart = `${new Date().getUTCFullYear()}-01-01`;
|
||||
const ARCHIVE_IS_HISTORY = `(
|
||||
t.legacySourceTable IS NULL
|
||||
OR t.legacySourceTable NOT LIKE 'datos2@%'
|
||||
OR t.transactionDate < '${yearStart}'
|
||||
)`;
|
||||
|
||||
/** Everything a balance drops apart from the floor itself. */
|
||||
const READ_SCOPE = `(${NOT_CASH_JOURNAL} AND ${ARCHIVE_IS_HISTORY})`;
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const limit = Number(arg(args, "--limit", "25"));
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
try {
|
||||
// ---- cutover -----------------------------------------------------------
|
||||
// Default to the newest balance-forward date actually in the book rather
|
||||
// than to the current year: the cut the data reflects is a fact, not a
|
||||
// preference, and hardcoding 2026 would silently lie on any other copy.
|
||||
const [bfDates] = await prisma.$queryRawUnsafe(`
|
||||
SELECT MAX(t.transactionDate) AS newest, MIN(t.transactionDate) AS oldest,
|
||||
COUNT(*) AS rows_, COUNT(DISTINCT t.customerId) AS custs
|
||||
FROM transactions t LEFT JOIN type_transactions tt ON tt.id = t.typeId
|
||||
WHERE t.voidedAt IS NULL AND ${BF_PREDICATE}
|
||||
`);
|
||||
|
||||
const cutover =
|
||||
arg(args, "--cutover") ??
|
||||
(bfDates.newest ? new Date(bfDates.newest).toISOString().slice(0, 10) : null);
|
||||
|
||||
if (!cutover) {
|
||||
console.log("No BALANCE FORWARD rows in this database and no --cutover given.");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`corte audit — cutover ${cutover}`);
|
||||
console.log(
|
||||
` balance-forward rows: ${d(bfDates.rows_)} across ${d(bfDates.custs)} customers` +
|
||||
`, dated ${day(bfDates.oldest)}..${day(bfDates.newest)}`,
|
||||
);
|
||||
|
||||
// ---- book totals -------------------------------------------------------
|
||||
const [book] = await prisma.$queryRawUnsafe(
|
||||
`
|
||||
WITH bfloor AS (
|
||||
SELECT t.customerId, MAX(t.transactionDate) AS floorDate
|
||||
FROM transactions t LEFT JOIN type_transactions tt ON tt.id = t.typeId
|
||||
WHERE t.voidedAt IS NULL AND ${BF_PREDICATE}
|
||||
GROUP BY t.customerId
|
||||
)
|
||||
SELECT
|
||||
ROUND(SUM(CASE WHEN t.currency='MXN' THEN t.amount ELSE 0 END), 2) AS rawMxn,
|
||||
ROUND(SUM(CASE WHEN t.currency='USD' THEN t.amount ELSE 0 END), 2) AS rawUsd,
|
||||
ROUND(SUM(CASE WHEN t.currency='MXN' AND (b.floorDate IS NULL OR t.transactionDate >= b.floorDate)
|
||||
THEN t.amount ELSE 0 END), 2) AS floorOnlyMxn,
|
||||
ROUND(SUM(CASE WHEN t.currency='USD' AND (b.floorDate IS NULL OR t.transactionDate >= b.floorDate)
|
||||
THEN t.amount ELSE 0 END), 2) AS floorOnlyUsd,
|
||||
ROUND(SUM(CASE WHEN t.currency='MXN' AND (b.floorDate IS NULL OR t.transactionDate >= b.floorDate)
|
||||
AND ${READ_SCOPE} THEN t.amount ELSE 0 END), 2) AS todayMxn,
|
||||
ROUND(SUM(CASE WHEN t.currency='USD' AND (b.floorDate IS NULL OR t.transactionDate >= b.floorDate)
|
||||
AND ${READ_SCOPE} THEN t.amount ELSE 0 END), 2) AS todayUsd,
|
||||
ROUND(SUM(CASE WHEN t.currency='MXN' AND t.transactionDate >= ?
|
||||
THEN t.amount ELSE 0 END), 2) AS flooredMxn,
|
||||
ROUND(SUM(CASE WHEN t.currency='USD' AND t.transactionDate >= ?
|
||||
THEN t.amount ELSE 0 END), 2) AS flooredUsd
|
||||
FROM transactions t
|
||||
LEFT JOIN bfloor b ON b.customerId = t.customerId
|
||||
WHERE t.voidedAt IS NULL AND t.outstanding = 0
|
||||
`,
|
||||
cutover,
|
||||
cutover,
|
||||
);
|
||||
|
||||
// ---- section A: floorless customers ------------------------------------
|
||||
const floorless = await prisma.$queryRawUnsafe(
|
||||
`
|
||||
WITH nobf AS (
|
||||
SELECT c.id, c.name
|
||||
FROM customers c
|
||||
WHERE EXISTS (SELECT 1 FROM transactions t WHERE t.customerId = c.id AND t.voidedAt IS NULL)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM transactions t LEFT JOIN type_transactions tt ON tt.id = t.typeId
|
||||
WHERE t.customerId = c.id AND t.voidedAt IS NULL AND ${BF_PREDICATE}
|
||||
)
|
||||
)
|
||||
SELECT n.id, n.name,
|
||||
COUNT(*) AS rows_,
|
||||
SUM(t.transactionDate < ?) AS preRows,
|
||||
SUM(t.transactionDate >= ?) AS postRows,
|
||||
MIN(t.transactionDate) AS firstTx,
|
||||
MAX(t.transactionDate) AS lastTx,
|
||||
SUM(t.domain = 'UTILITY') AS utilRows,
|
||||
SUM(t.domain = 'INSURANCE') AS insRows,
|
||||
ROUND(SUM(CASE WHEN t.currency='MXN' AND t.outstanding=0 THEN t.amount ELSE 0 END), 2) AS todayMxn,
|
||||
ROUND(SUM(CASE WHEN t.currency='USD' AND t.outstanding=0 THEN t.amount ELSE 0 END), 2) AS todayUsd,
|
||||
ROUND(SUM(CASE WHEN t.currency='MXN' AND t.outstanding=0 AND t.transactionDate >= ?
|
||||
THEN t.amount ELSE 0 END), 2) AS afterMxn,
|
||||
ROUND(SUM(CASE WHEN t.currency='USD' AND t.outstanding=0 AND t.transactionDate >= ?
|
||||
THEN t.amount ELSE 0 END), 2) AS afterUsd
|
||||
FROM nobf n
|
||||
JOIN transactions t ON t.customerId = n.id AND t.voidedAt IS NULL
|
||||
GROUP BY n.id, n.name
|
||||
ORDER BY ABS(SUM(CASE WHEN t.currency='MXN' AND t.transactionDate < ? THEN t.amount ELSE 0 END)) DESC
|
||||
`,
|
||||
cutover, cutover, cutover, cutover, cutover,
|
||||
);
|
||||
|
||||
// Direction of the pre-cutover history, which is the whole argument for
|
||||
// flooring rather than carrying it: a corte carries a NET, and a net built
|
||||
// from receipts whose charges were never migrated is not one.
|
||||
const [split] = await prisma.$queryRawUnsafe(
|
||||
`
|
||||
WITH nobf AS (
|
||||
SELECT c.id FROM customers c
|
||||
WHERE EXISTS (SELECT 1 FROM transactions t WHERE t.customerId = c.id AND t.voidedAt IS NULL)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM transactions t LEFT JOIN type_transactions tt ON tt.id = t.typeId
|
||||
WHERE t.customerId = c.id AND t.voidedAt IS NULL AND ${BF_PREDICATE}
|
||||
)
|
||||
)
|
||||
SELECT SUM(t.amount < 0) AS charges, ROUND(SUM(CASE WHEN t.amount < 0 THEN t.amount ELSE 0 END), 2) AS chargeMxn,
|
||||
SUM(t.amount > 0) AS credits, ROUND(SUM(CASE WHEN t.amount > 0 THEN t.amount ELSE 0 END), 2) AS creditMxn
|
||||
FROM transactions t JOIN nobf n ON n.id = t.customerId
|
||||
WHERE t.voidedAt IS NULL AND t.transactionDate < ?
|
||||
`,
|
||||
cutover,
|
||||
);
|
||||
|
||||
// What the floorless population's balance is actually MADE OF.
|
||||
//
|
||||
// "Floor them, never carry" was written when this group looked like
|
||||
// utilities cash receipts whose charges were never migrated. It is not that
|
||||
// any more. After the prior-period import the group is 99 customers, and
|
||||
// almost all of them are insurance-only — their rows come from the seguros
|
||||
// database's own EFECTIVO, which is that line's ONLY ledger. Nothing posts
|
||||
// it a second time, so flooring it does not remove a double count, it
|
||||
// deletes receipts. Split the two so the remedy is chosen per population
|
||||
// rather than for the group.
|
||||
const [floorlessMix] = await prisma.$queryRawUnsafe(
|
||||
`
|
||||
WITH nobf AS (
|
||||
SELECT c.id FROM customers c
|
||||
WHERE EXISTS (SELECT 1 FROM transactions t WHERE t.customerId = c.id AND t.voidedAt IS NULL)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM transactions t LEFT JOIN type_transactions tt ON tt.id = t.typeId
|
||||
WHERE t.customerId = c.id AND t.voidedAt IS NULL AND ${BF_PREDICATE}
|
||||
)
|
||||
)
|
||||
SELECT
|
||||
COUNT(DISTINCT CASE WHEN t.legacySourceDb = 'SEGUROS 16_be' THEN t.customerId END) AS insCusts,
|
||||
ROUND(SUM(CASE WHEN t.legacySourceDb = 'SEGUROS 16_be' AND t.currency='MXN'
|
||||
THEN t.amount ELSE 0 END), 2) AS insMxn,
|
||||
ROUND(SUM(CASE WHEN t.legacySourceDb = 'SEGUROS 16_be' AND t.currency='USD'
|
||||
THEN t.amount ELSE 0 END), 2) AS insUsd,
|
||||
COUNT(DISTINCT CASE WHEN t.legacySourceDb <> 'SEGUROS 16_be' THEN t.customerId END) AS utilCusts
|
||||
FROM transactions t JOIN nobf n ON n.id = t.customerId
|
||||
WHERE t.voidedAt IS NULL AND t.outstanding = 0 AND t.transactionDate < ?
|
||||
`,
|
||||
cutover,
|
||||
);
|
||||
|
||||
// ---- section B: double-booked receipts ---------------------------------
|
||||
const pairs = await prisma.$queryRawUnsafe(
|
||||
`
|
||||
SELECT d.id AS datos2Id, e.id AS efectivoId, c.name,
|
||||
DATE(d.transactionDate) AS datos2Date, DATE(e.transactionDate) AS efectivoDate,
|
||||
d.amount AS datos2Amount, d.currency AS datos2Currency,
|
||||
e.amount AS efectivoAmount, e.currency AS efectivoCurrency,
|
||||
d.reference AS datos2Ref, e.reference AS efectivoRef,
|
||||
fx.lo AS rateLo, fx.hi AS rateHi
|
||||
FROM transactions d
|
||||
JOIN transactions e
|
||||
ON e.customerId = d.customerId
|
||||
AND e.legacySourceTable = 'EFECTIVO'
|
||||
AND e.voidedAt IS NULL
|
||||
AND e.reference = SUBSTRING(d.reference, 2)
|
||||
JOIN customers c ON c.id = d.customerId
|
||||
LEFT JOIN (
|
||||
SELECT YEAR(effectiveDate) AS y, MIN(rate) AS lo, MAX(rate) AS hi
|
||||
FROM exchange_rates GROUP BY YEAR(effectiveDate)
|
||||
) fx ON fx.y = YEAR(d.transactionDate)
|
||||
WHERE d.voidedAt IS NULL
|
||||
AND d.legacySourceTable = 'datos2'
|
||||
AND d.reference REGEXP '^C[0-9]+$'
|
||||
ORDER BY d.transactionDate
|
||||
`,
|
||||
);
|
||||
|
||||
// Pass two — the leads pass one could not follow. Same shape of row, judged
|
||||
// by the same money rules below, so a folio typo costs nothing.
|
||||
const nearby = await prisma.$queryRawUnsafe(
|
||||
`
|
||||
SELECT d.id AS datos2Id, e.id AS efectivoId, c.name,
|
||||
DATE(d.transactionDate) AS datos2Date, DATE(e.transactionDate) AS efectivoDate,
|
||||
d.amount AS datos2Amount, d.currency AS datos2Currency,
|
||||
e.amount AS efectivoAmount, e.currency AS efectivoCurrency,
|
||||
d.reference AS datos2Ref, e.reference AS efectivoRef,
|
||||
fx.lo AS rateLo, fx.hi AS rateHi
|
||||
FROM transactions d
|
||||
JOIN transactions e
|
||||
ON e.customerId = d.customerId AND e.legacySourceTable = 'EFECTIVO'
|
||||
AND e.voidedAt IS NULL AND e.amount > 0
|
||||
AND ABS(DATEDIFF(e.transactionDate, d.transactionDate)) <= 3
|
||||
JOIN customers c ON c.id = d.customerId
|
||||
LEFT JOIN (
|
||||
SELECT YEAR(effectiveDate) AS y, MIN(rate) AS lo, MAX(rate) AS hi
|
||||
FROM exchange_rates GROUP BY YEAR(effectiveDate)
|
||||
) fx ON fx.y = YEAR(d.transactionDate)
|
||||
WHERE d.voidedAt IS NULL AND d.legacySourceTable = 'datos2'
|
||||
AND d.reference REGEXP '^C[0-9]+$'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM transactions x
|
||||
WHERE x.customerId = d.customerId AND x.legacySourceTable = 'EFECTIVO'
|
||||
AND x.voidedAt IS NULL AND x.reference = SUBSTRING(d.reference, 2)
|
||||
)
|
||||
ORDER BY d.transactionDate
|
||||
`,
|
||||
);
|
||||
|
||||
const [unpaired] = await prisma.$queryRawUnsafe(
|
||||
`
|
||||
SELECT COUNT(*) AS n
|
||||
FROM transactions d
|
||||
WHERE d.voidedAt IS NULL AND d.legacySourceTable = 'datos2'
|
||||
AND d.reference REGEXP '^C[0-9]+$'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM transactions e
|
||||
WHERE e.customerId = d.customerId AND e.legacySourceTable = 'EFECTIVO'
|
||||
AND e.voidedAt IS NULL AND e.reference = SUBSTRING(d.reference, 2)
|
||||
)
|
||||
`,
|
||||
);
|
||||
|
||||
// REGRESSION GUARD. Since 1.0.26 the application drops the whole cash
|
||||
// journal from every balance, so none of section B's rows should reach one
|
||||
// any more. This counts the ones that still do: it is 0 while the exclusion
|
||||
// holds, and goes non-zero the moment someone reintroduces a balance query
|
||||
// that forgets it. A defect list that cannot tell you whether the defect is
|
||||
// still live is just history.
|
||||
const [stillCounted] = await prisma.$queryRawUnsafe(
|
||||
`
|
||||
WITH bfloor AS (
|
||||
SELECT t.customerId, MAX(t.transactionDate) AS floorDate
|
||||
FROM transactions t LEFT JOIN type_transactions tt ON tt.id = t.typeId
|
||||
WHERE t.voidedAt IS NULL AND ${BF_PREDICATE}
|
||||
GROUP BY t.customerId
|
||||
)
|
||||
SELECT COUNT(*) AS n,
|
||||
ROUND(SUM(CASE WHEN t.currency='MXN' THEN t.amount ELSE 0 END), 2) AS mxn,
|
||||
ROUND(SUM(CASE WHEN t.currency='USD' THEN t.amount ELSE 0 END), 2) AS usd
|
||||
FROM transactions t
|
||||
LEFT JOIN bfloor b ON b.customerId = t.customerId
|
||||
WHERE t.voidedAt IS NULL AND t.outstanding = 0
|
||||
AND t.legacySourceDb = 'UTILITIES'
|
||||
AND t.legacySourceTable IN
|
||||
('EFECTIVO', 'EFECTIVO_BACKUP', 'EFECTIVO FM3', 'CHEQUE FM3', 'IVA 2015')
|
||||
AND (b.floorDate IS NULL OR t.transactionDate >= b.floorDate)
|
||||
AND ${READ_SCOPE}
|
||||
`,
|
||||
);
|
||||
|
||||
// ---- CSV escapes -------------------------------------------------------
|
||||
if (args.includes("--csv-a")) return dumpCsv(floorless);
|
||||
if (args.includes("--csv-b")) return dumpCsv([...pairs, ...nearby]);
|
||||
|
||||
// ---- report ------------------------------------------------------------
|
||||
console.log("\nBOOK (voided and outstanding rows excluded)");
|
||||
console.log(` raw lifetime sum, no floor ${money(book.rawMxn)} MXN ${money(book.rawUsd)} USD`);
|
||||
console.log(` BF floor only (pre-1.0.26) ${money(book.floorOnlyMxn)} MXN ${money(book.floorOnlyUsd)} USD`);
|
||||
console.log(` TODAY, as the app computes it ${money(book.todayMxn)} MXN ${money(book.todayUsd)} USD`);
|
||||
console.log(` flat floor at ${cutover} ${money(book.flooredMxn)} MXN ${money(book.flooredUsd)} USD`);
|
||||
console.log(
|
||||
" (the middle line is the floor alone, kept only so older runs of this\n" +
|
||||
" script still diff against something. The app has dropped the cash\n" +
|
||||
" journal and windowed the archives since 1.0.26; USD going to zero on\n" +
|
||||
" the utilities side is correct, that ledger is peso-denominated.)",
|
||||
);
|
||||
|
||||
const preRowsTotal = floorless.reduce((s, r) => s + d(r.preRows), 0);
|
||||
const wouldZero = floorless.filter((r) => d(r.postRows) === 0);
|
||||
const deltaMxn = floorless.reduce((s, r) => s + (d(r.todayMxn) - d(r.afterMxn)), 0);
|
||||
const deltaUsd = floorless.reduce((s, r) => s + (d(r.todayUsd) - d(r.afterUsd)), 0);
|
||||
|
||||
console.log(`\nA. FLOORLESS CUSTOMERS — ${floorless.length}`);
|
||||
console.log(` pre-cutover rows they still count: ${preRowsTotal}`);
|
||||
console.log(` of those rows: ${d(split.charges)} charges (${d(split.chargeMxn).toFixed(2)})` +
|
||||
` vs ${d(split.credits)} credits (${d(split.creditMxn).toFixed(2)})`);
|
||||
console.log(` balance moved by flooring: ${money(-deltaMxn)} MXN ${money(-deltaUsd)} USD`);
|
||||
console.log(` customers left with NO rows at all after the cut: ${wouldZero.length}` +
|
||||
` (their balance becomes 0 — an assertion, not a migrated figure)`);
|
||||
console.log(
|
||||
` of the ${floorless.length}: ${d(floorlessMix.insCusts)} carry insurance-line cash` +
|
||||
` (${d(floorlessMix.insMxn).toFixed(2)} MXN / ${d(floorlessMix.insUsd).toFixed(2)} USD)` +
|
||||
`, ${d(floorlessMix.utilCusts)} carry utilities rows`,
|
||||
);
|
||||
console.log(
|
||||
` READ THAT LINE BEFORE FLOORING ANYONE. The seguros EFECTIVO is that\n` +
|
||||
` line's only ledger — nothing posts it twice — so flooring those\n` +
|
||||
` customers deletes receipts rather than removing a double count.\n` +
|
||||
` The argument for flooring holds for the utilities rows alone.`,
|
||||
);
|
||||
console.log(
|
||||
`\n ${"customer".padEnd(30)} ${"pre".padStart(4)} ${"post".padStart(4)}` +
|
||||
` ${"today MXN".padStart(13)} ${"after MXN".padStart(13)} ${"first tx".padStart(10)}`,
|
||||
);
|
||||
for (const r of floorless.slice(0, limit)) {
|
||||
console.log(
|
||||
` ${(r.name || "(sin nombre)").slice(0, 30).padEnd(30)}` +
|
||||
` ${String(d(r.preRows)).padStart(4)} ${String(d(r.postRows)).padStart(4)}` +
|
||||
` ${money(r.todayMxn)} ${money(r.afterMxn)} ${day(r.firstTx).padStart(10)}`,
|
||||
);
|
||||
}
|
||||
if (floorless.length > limit) console.log(` ... ${floorless.length - limit} more (--csv-a)`);
|
||||
|
||||
// A folio match is a hypothesis; the money is the evidence. The band is
|
||||
// widened by 10% either side of what exchange_rates observed that year,
|
||||
// because the office keys receipts at its own counter rate, not at a
|
||||
// published one, and a pair should not be called false over a few centavos.
|
||||
const classify = (p) => {
|
||||
const dAmt = d(p.datos2Amount);
|
||||
const eAmt = d(p.efectivoAmount);
|
||||
if (p.datos2Currency === p.efectivoCurrency) {
|
||||
return Math.abs(dAmt - eAmt) < 0.005 ? "confirmed" : "suspect";
|
||||
}
|
||||
if (p.efectivoCurrency !== "USD" || p.datos2Currency !== "MXN") return "suspect";
|
||||
if (!eAmt || !p.rateLo) return "suspect";
|
||||
const implied = dAmt / eAmt;
|
||||
return implied >= d(p.rateLo) * 0.9 && implied <= d(p.rateHi) * 1.1
|
||||
? "confirmed"
|
||||
: "suspect";
|
||||
};
|
||||
for (const p of pairs) {
|
||||
p.pass = "folio";
|
||||
p.verdict = classify(p);
|
||||
}
|
||||
for (const p of nearby) {
|
||||
p.pass = "proximity";
|
||||
p.verdict = classify(p);
|
||||
}
|
||||
pairs.push(...nearby);
|
||||
|
||||
const confirmed = pairs.filter((p) => p.verdict === "confirmed");
|
||||
const suspect = pairs.filter((p) => p.verdict === "suspect");
|
||||
const byCust = new Set(confirmed.map((p) => p.name));
|
||||
const sameCur = confirmed.filter((p) => p.datos2Currency === p.efectivoCurrency);
|
||||
const converted = confirmed.filter((p) => p.efectivoCurrency === "USD" && p.datos2Currency === "MXN");
|
||||
const efecMxn = confirmed.reduce((s, p) => s + (p.efectivoCurrency === "MXN" ? d(p.efectivoAmount) : 0), 0);
|
||||
const efecUsd = confirmed.reduce((s, p) => s + (p.efectivoCurrency === "USD" ? d(p.efectivoAmount) : 0), 0);
|
||||
|
||||
console.log(`\nB. DOUBLE-BOOKED RECEIPTS — ${confirmed.length} confirmed pairs across ${byCust.size} customers`);
|
||||
const byFolio = confirmed.filter((p) => p.pass === "folio").length;
|
||||
console.log(` candidates examined: ${pairs.length} (confirmed ${confirmed.length}, rejected on money ${suspect.length})`);
|
||||
console.log(` found by folio cross-reference: ${byFolio}, by proximity after a folio miss: ${confirmed.length - byFolio}`);
|
||||
console.log(` confirmed same-currency, amount equal to the cent: ${sameCur.length}`);
|
||||
console.log(` confirmed USD receipt posted to datos2 in MXN: ${converted.length}`);
|
||||
console.log(` datos2 C-refs with no EFECTIVO partner at all: ${d(unpaired.n)}`);
|
||||
console.log(` EFECTIVO side of the confirmed pairs: ${money(efecMxn)} MXN ${money(efecUsd)} USD`);
|
||||
console.log(
|
||||
` still reaching a balance after the 1.0.26 exclusion: ${d(stillCounted.n)} rows` +
|
||||
` (${d(stillCounted.mxn).toFixed(2)} MXN / ${d(stillCounted.usd).toFixed(2)} USD)` +
|
||||
`${d(stillCounted.n) === 0 ? " <- 0 is the passing value" : " <- REGRESSION"}`,
|
||||
);
|
||||
console.log(
|
||||
` The rows below still exist and always will; the ledger's own C<folio>\n` +
|
||||
` posting is the copy that counts. This section is now a record of what\n` +
|
||||
` the journal holds, not a list of money being double-counted.`,
|
||||
);
|
||||
console.log(
|
||||
`\n ${"customer".padEnd(28)} ${"datos2".padStart(10)} ${"efectivo".padStart(10)}` +
|
||||
` ${"datos2 amt".padStart(13)} ${"efectivo amt".padStart(13)} ref`,
|
||||
);
|
||||
for (const p of confirmed.slice(0, limit)) {
|
||||
console.log(
|
||||
` ${(p.name || "(sin nombre)").slice(0, 28).padEnd(28)}` +
|
||||
` ${day(p.datos2Date).padStart(10)} ${day(p.efectivoDate).padStart(10)}` +
|
||||
` ${money(p.datos2Amount)} ${p.datos2Currency}` +
|
||||
` ${money(p.efectivoAmount)} ${p.efectivoCurrency} ${p.datos2Ref}/${p.efectivoRef}`,
|
||||
);
|
||||
}
|
||||
if (confirmed.length > limit) console.log(` ... ${confirmed.length - limit} more (--csv-b)`);
|
||||
|
||||
if (suspect.length) {
|
||||
console.log(`\n REJECTED — folio matched, money did not. Not duplicates on this evidence:`);
|
||||
for (const p of suspect.slice(0, limit)) {
|
||||
const implied =
|
||||
d(p.efectivoAmount) && p.datos2Currency !== p.efectivoCurrency
|
||||
? ` implied ${(d(p.datos2Amount) / d(p.efectivoAmount)).toFixed(2)}`
|
||||
: "";
|
||||
console.log(
|
||||
` ${(p.name || "(sin nombre)").slice(0, 28).padEnd(28)}` +
|
||||
` ${day(p.datos2Date).padStart(10)} ${day(p.efectivoDate).padStart(10)}` +
|
||||
` ${money(p.datos2Amount)} ${p.datos2Currency}` +
|
||||
` ${money(p.efectivoAmount)} ${p.efectivoCurrency} ${p.datos2Ref}${implied}`,
|
||||
);
|
||||
}
|
||||
if (suspect.length > limit) console.log(` ... ${suspect.length - limit} more (--csv-b)`);
|
||||
}
|
||||
|
||||
console.log(
|
||||
"\nNOTE: nothing above has been changed. Section A is a proposal to move the\n" +
|
||||
"floor, not a carried-forward balance: the pre-cutover charge ledger was\n" +
|
||||
"never migrated, so no true opening balance can be computed from this\n" +
|
||||
"database. It exists in the DreamHost per-year tables. Section B is no\n" +
|
||||
"longer an open defect — it was fixed read-side in 1.0.26 — and the line\n" +
|
||||
"that matters there is the regression count, which must stay at 0.",
|
||||
);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
function dumpCsv(rows) {
|
||||
if (!rows.length) return;
|
||||
const cols = Object.keys(rows[0]);
|
||||
console.log(cols.join(","));
|
||||
for (const r of rows) {
|
||||
console.log(cols.map((c) => JSON.stringify(r[c] == null ? "" : String(r[c]))).join(","));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user