@finopsbricks/tally-sync 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -0
- package/.next/app-build-manifest.json +66 -0
- package/.next/app-path-routes-manifest.json +7 -0
- package/.next/build-manifest.json +33 -0
- package/.next/export-marker.json +6 -0
- package/.next/images-manifest.json +58 -0
- package/.next/next-minimal-server.js.nft.json +1 -0
- package/.next/next-server.js.nft.json +1 -0
- package/.next/package.json +1 -0
- package/.next/prerender-manifest.json +11 -0
- package/.next/react-loadable-manifest.json +1 -0
- package/.next/required-server-files.json +322 -0
- package/.next/routes-manifest.json +80 -0
- package/.next/server/app/_not-found/page.js +2 -0
- package/.next/server/app/_not-found/page.js.nft.json +1 -0
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -0
- package/.next/server/app/companies/[guid]/page.js +2 -0
- package/.next/server/app/companies/[guid]/page.js.nft.json +1 -0
- package/.next/server/app/companies/[guid]/page_client-reference-manifest.js +1 -0
- package/.next/server/app/companies/[guid]/tables/[table]/page.js +2 -0
- package/.next/server/app/companies/[guid]/tables/[table]/page.js.nft.json +1 -0
- package/.next/server/app/companies/[guid]/tables/[table]/page_client-reference-manifest.js +1 -0
- package/.next/server/app/companies/[guid]/vouchers/[voucher_guid]/page.js +2 -0
- package/.next/server/app/companies/[guid]/vouchers/[voucher_guid]/page.js.nft.json +1 -0
- package/.next/server/app/companies/[guid]/vouchers/[voucher_guid]/page_client-reference-manifest.js +1 -0
- package/.next/server/app/page.js +2 -0
- package/.next/server/app/page.js.nft.json +1 -0
- package/.next/server/app/page_client-reference-manifest.js +1 -0
- package/.next/server/app-paths-manifest.json +7 -0
- package/.next/server/chunks/230.js +32 -0
- package/.next/server/chunks/611.js +6 -0
- package/.next/server/chunks/706.js +1 -0
- package/.next/server/chunks/748.js +1 -0
- package/.next/server/functions-config-manifest.json +4 -0
- package/.next/server/interception-route-rewrite-manifest.js +1 -0
- package/.next/server/middleware-build-manifest.js +1 -0
- package/.next/server/middleware-manifest.json +6 -0
- package/.next/server/middleware-react-loadable-manifest.js +1 -0
- package/.next/server/next-font-manifest.js +1 -0
- package/.next/server/next-font-manifest.json +1 -0
- package/.next/server/pages/500.html +1 -0
- package/.next/server/pages/_app.js +1 -0
- package/.next/server/pages/_app.js.nft.json +1 -0
- package/.next/server/pages/_document.js +1 -0
- package/.next/server/pages/_document.js.nft.json +1 -0
- package/.next/server/pages/_error.js +19 -0
- package/.next/server/pages/_error.js.nft.json +1 -0
- package/.next/server/pages-manifest.json +5 -0
- package/.next/server/server-reference-manifest.js +1 -0
- package/.next/server/server-reference-manifest.json +1 -0
- package/.next/server/webpack-runtime.js +1 -0
- package/.next/static/V0rxN1KuyEM0zJoOJVDoX/_buildManifest.js +1 -0
- package/.next/static/V0rxN1KuyEM0zJoOJVDoX/_ssgManifest.js +1 -0
- package/.next/static/chunks/122-df645619bf29fc6e.js +1 -0
- package/.next/static/chunks/255-73938ce8a8eac1ad.js +1 -0
- package/.next/static/chunks/4bd1b696-c023c6e3521b1417.js +1 -0
- package/.next/static/chunks/510-5993a923674db2de.js +1 -0
- package/.next/static/chunks/658-dfe2290e75772c42.js +1 -0
- package/.next/static/chunks/788-e10fcb5f53c6428d.js +1 -0
- package/.next/static/chunks/9ad0e60a-ad37bddef782d7c2.js +1 -0
- package/.next/static/chunks/app/_not-found/page-f187ad254cc1b0eb.js +1 -0
- package/.next/static/chunks/app/companies/[guid]/page-042071b4790e1a86.js +1 -0
- package/.next/static/chunks/app/companies/[guid]/tables/[table]/page-a46008185adae0f8.js +1 -0
- package/.next/static/chunks/app/companies/[guid]/vouchers/[voucher_guid]/page-1b17cd59db180e1f.js +1 -0
- package/.next/static/chunks/app/layout-d46ad692723a97e0.js +1 -0
- package/.next/static/chunks/app/not-found-61f58c9ef91de921.js +1 -0
- package/.next/static/chunks/app/page-042071b4790e1a86.js +1 -0
- package/.next/static/chunks/framework-acd67e14855de5a2.js +1 -0
- package/.next/static/chunks/main-6f56cad8fb2c15f2.js +1 -0
- package/.next/static/chunks/main-app-f136a4b0e7f8f69b.js +1 -0
- package/.next/static/chunks/pages/_app-7d307437aca18ad4.js +1 -0
- package/.next/static/chunks/pages/_error-cb2a52f75f2162e2.js +1 -0
- package/.next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
- package/.next/static/chunks/webpack-4354c1f6ffe64d9d.js +1 -0
- package/.next/static/css/a8e56a10001bee9f.css +1 -0
- package/CHANGELOG.md +16 -0
- package/LICENSE +201 -0
- package/NOTICE +40 -0
- package/README.md +109 -2
- package/bin/tally-sync.js +12 -0
- package/ecosystem.config.cjs +12 -0
- package/next.config.mjs +7 -0
- package/package.json +58 -4
- package/src/app/companies/[guid]/page.jsx +261 -0
- package/src/app/companies/[guid]/tables/[table]/page.jsx +116 -0
- package/src/app/companies/[guid]/vouchers/[voucher_guid]/page.jsx +156 -0
- package/src/app/globals.css +3 -0
- package/src/app/layout.jsx +29 -0
- package/src/app/not-found.jsx +22 -0
- package/src/app/page.jsx +172 -0
- package/src/cli/_helpers.js +71 -0
- package/src/cli/index.js +56 -0
- package/src/cli/paths.js +26 -0
- package/src/cli/probe.js +61 -0
- package/src/cli/sync.js +84 -0
- package/src/cli/web.js +32 -0
- package/src/components/AppShell.jsx +17 -0
- package/src/components/AppSidebar.jsx +81 -0
- package/src/components/MainContainer.jsx +12 -0
- package/src/components/RowsTable.jsx +111 -0
- package/src/components/Section.jsx +16 -0
- package/src/mirror/agentDb.js +131 -0
- package/src/mirror/companyDb.js +54 -0
- package/src/mirror/schema.js +49 -0
- package/src/mirror/sqlite.js +41 -0
- package/src/probe/probeFile.js +54 -0
- package/src/probe/runProbe.js +118 -0
- package/src/sync/checkPull.js +61 -0
- package/src/sync/pullCompany.js +54 -0
- package/src/sync/runSyncPass.js +50 -0
- package/src/sync/syncCompany.js +75 -0
- package/src/sync/tieOut.js +93 -0
- package/src/tally/dates.js +23 -0
- package/src/tally/definitions.js +22 -0
- package/src/tally/definitions.yaml +370 -0
- package/src/tally/gateway.js +77 -0
- package/src/tally/http.js +92 -0
- package/src/tally/requests.js +133 -0
- package/src/tally/tallyErrors.js +25 -0
- package/src/tally/xml.js +329 -0
- package/src/utils/config.js +46 -0
- package/src/utils/debugLog.js +23 -0
- package/src/web/format.js +160 -0
- package/src/web/mirror.js +132 -0
- package/src/web/status.js +80 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
// @ts-check
|
|
3
|
+
|
|
4
|
+
import Link from 'next/link';
|
|
5
|
+
import { useIsMobile } from '@fob/lib-ui/hooks/use-mobile';
|
|
6
|
+
import { cn } from '@fob/lib-ui/lib/utils';
|
|
7
|
+
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@fob/lib-ui/primitives/table';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {Object} Column
|
|
11
|
+
* @property {string} key
|
|
12
|
+
* @property {string} label
|
|
13
|
+
* @property {'right'} [align] - numbers and money
|
|
14
|
+
* @property {boolean} [nowrap]
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {Object} Row
|
|
19
|
+
* @property {string} key
|
|
20
|
+
* @property {Record<string, React.ReactNode>} cells - by column key, already formatted
|
|
21
|
+
* @property {{title: React.ReactNode, value?: React.ReactNode, meta?: React.ReactNode[], extra?: React.ReactNode, href?: string}} [card]
|
|
22
|
+
* the row as a card on phones: the label and key value, then the facts that tell it apart
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A table, or on phones a list of cards when the table is too wide to read there
|
|
27
|
+
* (design-standards foundations/responsive › Wide tables become cards). Rows with no `card`
|
|
28
|
+
* keep the table at every width; a wide one scrolls sideways inside itself, not the page.
|
|
29
|
+
* Cells come formatted from the server page, so the same text shows in both forms.
|
|
30
|
+
* @param {{columns: Column[], rows: Row[], label: string, cards?: boolean}} props
|
|
31
|
+
* `label` names the table for screen readers; `cards` turns the phone cards on
|
|
32
|
+
*/
|
|
33
|
+
export default function RowsTable({ columns, rows, label, cards = false }) {
|
|
34
|
+
const is_mobile = useIsMobile();
|
|
35
|
+
|
|
36
|
+
if (cards && is_mobile) {
|
|
37
|
+
return (
|
|
38
|
+
<ul aria-label={label} className="flex flex-col gap-2">
|
|
39
|
+
{rows.map((row) => (
|
|
40
|
+
<li key={row.key}>
|
|
41
|
+
<RowCard card={row.card ?? { title: row.key }} />
|
|
42
|
+
</li>
|
|
43
|
+
))}
|
|
44
|
+
</ul>
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return (
|
|
49
|
+
<div className="min-w-0 rounded-md border">
|
|
50
|
+
<Table variant="compact" aria-label={label}>
|
|
51
|
+
<TableHeader className="bg-muted/50">
|
|
52
|
+
<TableRow>
|
|
53
|
+
{columns.map((c) => (
|
|
54
|
+
<TableHead key={c.key} className={cn('h-9 whitespace-nowrap', c.align === 'right' && 'text-right')}>
|
|
55
|
+
{c.label}
|
|
56
|
+
</TableHead>
|
|
57
|
+
))}
|
|
58
|
+
</TableRow>
|
|
59
|
+
</TableHeader>
|
|
60
|
+
<TableBody>
|
|
61
|
+
{rows.map((row) => (
|
|
62
|
+
<TableRow key={row.key}>
|
|
63
|
+
{columns.map((c) => (
|
|
64
|
+
<TableCell
|
|
65
|
+
key={c.key}
|
|
66
|
+
className={cn('align-top', c.align === 'right' && 'text-right tabular-nums whitespace-nowrap', c.nowrap && 'whitespace-nowrap')}
|
|
67
|
+
>
|
|
68
|
+
{row.cells[c.key]}
|
|
69
|
+
</TableCell>
|
|
70
|
+
))}
|
|
71
|
+
</TableRow>
|
|
72
|
+
))}
|
|
73
|
+
</TableBody>
|
|
74
|
+
</Table>
|
|
75
|
+
</div>
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @param {{card: NonNullable<Row['card']>}} props
|
|
81
|
+
*/
|
|
82
|
+
function RowCard({ card }) {
|
|
83
|
+
const body = (
|
|
84
|
+
<>
|
|
85
|
+
<div className="flex items-start justify-between gap-3">
|
|
86
|
+
<div className="line-clamp-2 min-w-0 font-medium">{card.title}</div>
|
|
87
|
+
{card.value !== undefined && <div className="shrink-0 text-right tabular-nums">{card.value}</div>}
|
|
88
|
+
</div>
|
|
89
|
+
{card.meta && card.meta.length > 0 && (
|
|
90
|
+
<div className="text-sm text-muted-foreground">
|
|
91
|
+
{card.meta.filter(Boolean).map((part, i) => (
|
|
92
|
+
<span key={i}>
|
|
93
|
+
{i > 0 && ' · '}
|
|
94
|
+
{part}
|
|
95
|
+
</span>
|
|
96
|
+
))}
|
|
97
|
+
</div>
|
|
98
|
+
)}
|
|
99
|
+
{card.extra}
|
|
100
|
+
</>
|
|
101
|
+
);
|
|
102
|
+
const class_name = 'flex flex-col gap-1 rounded-md border bg-card px-3 py-2.5 text-sm';
|
|
103
|
+
if (card.href) {
|
|
104
|
+
return (
|
|
105
|
+
<Link href={card.href} className={cn(class_name, 'hover:bg-accent focus-visible:ring-ring/50 outline-none focus-visible:ring-[3px]')}>
|
|
106
|
+
{body}
|
|
107
|
+
</Link>
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
return <div className={class_name}>{body}</div>;
|
|
111
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A titled block on a page. The page title (PageHeader) is an h3, so section titles are h4.
|
|
5
|
+
* @param {{title: string, id: string, children: React.ReactNode}} props
|
|
6
|
+
*/
|
|
7
|
+
export default function Section({ title, id, children }) {
|
|
8
|
+
return (
|
|
9
|
+
<section aria-labelledby={id} className="flex min-w-0 flex-col gap-2">
|
|
10
|
+
<h4 id={id} className="text-base font-semibold">
|
|
11
|
+
{title}
|
|
12
|
+
</h4>
|
|
13
|
+
{children}
|
|
14
|
+
</section>
|
|
15
|
+
);
|
|
16
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The agent's own state (data/agent.db): the companies it has seen and its sync runs.
|
|
3
|
+
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { openSqlite } from './sqlite.js';
|
|
6
|
+
|
|
7
|
+
const SCHEMA_SQL = `
|
|
8
|
+
CREATE TABLE IF NOT EXISTS companies (
|
|
9
|
+
guid TEXT PRIMARY KEY,
|
|
10
|
+
name TEXT NOT NULL,
|
|
11
|
+
first_seen_at TEXT NOT NULL,
|
|
12
|
+
last_seen_loaded_at TEXT NOT NULL,
|
|
13
|
+
last_checked_at TEXT
|
|
14
|
+
);
|
|
15
|
+
CREATE TABLE IF NOT EXISTS sync_runs (
|
|
16
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
17
|
+
company_guid TEXT,
|
|
18
|
+
company_name TEXT NOT NULL,
|
|
19
|
+
started_at TEXT NOT NULL,
|
|
20
|
+
finished_at TEXT,
|
|
21
|
+
status TEXT NOT NULL,
|
|
22
|
+
alter_id_master INTEGER,
|
|
23
|
+
alter_id_transaction INTEGER,
|
|
24
|
+
counts_json TEXT,
|
|
25
|
+
problems_json TEXT,
|
|
26
|
+
tie_out_json TEXT,
|
|
27
|
+
error TEXT
|
|
28
|
+
);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS sync_runs_company ON sync_runs (company_guid, id);
|
|
30
|
+
CREATE TABLE IF NOT EXISTS agent_status (
|
|
31
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
32
|
+
last_pass_at TEXT NOT NULL,
|
|
33
|
+
tally_reachable INTEGER NOT NULL,
|
|
34
|
+
loaded_companies_json TEXT,
|
|
35
|
+
error TEXT
|
|
36
|
+
);
|
|
37
|
+
`;
|
|
38
|
+
|
|
39
|
+
/** Run statuses. */
|
|
40
|
+
export const RUN_STATUS = Object.freeze({
|
|
41
|
+
RUNNING: 'running',
|
|
42
|
+
SUCCEEDED: 'succeeded',
|
|
43
|
+
FAILED: 'failed',
|
|
44
|
+
ABANDONED: 'abandoned',
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {string} data_dir
|
|
49
|
+
* @returns {import('node:sqlite').DatabaseSync}
|
|
50
|
+
*/
|
|
51
|
+
export function openAgentDb(data_dir) {
|
|
52
|
+
const db = openSqlite(path.join(data_dir, 'agent.db'));
|
|
53
|
+
db.exec(SCHEMA_SQL);
|
|
54
|
+
return db;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Marks runs left "running" by a crash or a restart as abandoned.
|
|
59
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
60
|
+
* @param {string} now
|
|
61
|
+
* @returns {number} how many runs were marked
|
|
62
|
+
*/
|
|
63
|
+
export function markAbandonedRuns(db, now) {
|
|
64
|
+
const result = db.prepare('UPDATE sync_runs SET status = ?, finished_at = ? WHERE status = ?').run(RUN_STATUS.ABANDONED, now, RUN_STATUS.RUNNING);
|
|
65
|
+
return Number(result.changes);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Records that a company is loaded in Tally right now.
|
|
70
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
71
|
+
* @param {{guid: string, name: string}} company
|
|
72
|
+
* @param {string} now
|
|
73
|
+
*/
|
|
74
|
+
export function recordCompanySeen(db, { guid, name }, now) {
|
|
75
|
+
db.prepare(
|
|
76
|
+
`INSERT INTO companies (guid, name, first_seen_at, last_seen_loaded_at, last_checked_at) VALUES (?, ?, ?, ?, ?)
|
|
77
|
+
ON CONFLICT (guid) DO UPDATE SET name = excluded.name, last_seen_loaded_at = excluded.last_seen_loaded_at, last_checked_at = excluded.last_checked_at`,
|
|
78
|
+
).run(guid, name, now, now, now);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
83
|
+
* @param {{company_guid: string|null, company_name: string, started_at: string, alter_id_master?: number|null, alter_id_transaction?: number|null}} run
|
|
84
|
+
* @returns {number} the run id
|
|
85
|
+
*/
|
|
86
|
+
export function startRun(db, { company_guid, company_name, started_at, alter_id_master = null, alter_id_transaction = null }) {
|
|
87
|
+
const result = db
|
|
88
|
+
.prepare('INSERT INTO sync_runs (company_guid, company_name, started_at, status, alter_id_master, alter_id_transaction) VALUES (?, ?, ?, ?, ?, ?)')
|
|
89
|
+
.run(company_guid, company_name, started_at, RUN_STATUS.RUNNING, alter_id_master, alter_id_transaction);
|
|
90
|
+
return Number(result.lastInsertRowid);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
95
|
+
* @param {number} run_id
|
|
96
|
+
* @param {{status: string, finished_at: string, counts?: unknown, problems?: unknown, tie_out?: unknown, error?: string|null}} outcome
|
|
97
|
+
*/
|
|
98
|
+
export function finishRun(db, run_id, { status, finished_at, counts = null, problems = null, tie_out = null, error = null }) {
|
|
99
|
+
db.prepare('UPDATE sync_runs SET status = ?, finished_at = ?, counts_json = ?, problems_json = ?, tie_out_json = ?, error = ? WHERE id = ?').run(
|
|
100
|
+
status,
|
|
101
|
+
finished_at,
|
|
102
|
+
counts === null ? null : JSON.stringify(counts),
|
|
103
|
+
problems === null ? null : JSON.stringify(problems),
|
|
104
|
+
tie_out === null ? null : JSON.stringify(tie_out),
|
|
105
|
+
error,
|
|
106
|
+
run_id,
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The company's last successful run, or undefined.
|
|
112
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
113
|
+
* @param {string} company_guid
|
|
114
|
+
* @returns {Record<string, any>|undefined}
|
|
115
|
+
*/
|
|
116
|
+
export function lastSucceededRun(db, company_guid) {
|
|
117
|
+
return db.prepare('SELECT * FROM sync_runs WHERE company_guid = ? AND status = ? ORDER BY id DESC LIMIT 1').get(company_guid, RUN_STATUS.SUCCEEDED);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Records the outcome of the latest sync pass: whether Tally answered and which companies were loaded.
|
|
122
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
123
|
+
* @param {{at: string, tally_reachable: boolean, loaded_companies: string[], error: string|null}} status
|
|
124
|
+
*/
|
|
125
|
+
export function recordPass(db, { at, tally_reachable, loaded_companies, error }) {
|
|
126
|
+
db.prepare(
|
|
127
|
+
`INSERT INTO agent_status (id, last_pass_at, tally_reachable, loaded_companies_json, error) VALUES (1, ?, ?, ?, ?)
|
|
128
|
+
ON CONFLICT (id) DO UPDATE SET last_pass_at = excluded.last_pass_at, tally_reachable = excluded.tally_reachable,
|
|
129
|
+
loaded_companies_json = excluded.loaded_companies_json, error = excluded.error`,
|
|
130
|
+
).run(at, tally_reachable ? 1 : 0, JSON.stringify(loaded_companies), error);
|
|
131
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// One SQLite file per Tally company (data/<company guid>.db). Each full sync replaces the whole
|
|
3
|
+
// mirror in one transaction, so a failed sync leaves the previous mirror as it was.
|
|
4
|
+
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { openSqlite, inTransaction } from './sqlite.js';
|
|
7
|
+
import { COMPANY_TABLE_SQL, columnName, columnValue, createTableSql } from './schema.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {string} data_dir
|
|
11
|
+
* @param {string} company_guid
|
|
12
|
+
* @returns {string}
|
|
13
|
+
*/
|
|
14
|
+
export function companyDbFile(data_dir, company_guid) {
|
|
15
|
+
const safe_name = company_guid.replace(/[^A-Za-z0-9_-]/g, '_');
|
|
16
|
+
return path.join(data_dir, `${safe_name}.db`);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Replaces a company's mirror with freshly pulled tables. Tables are dropped and recreated,
|
|
21
|
+
* so a change in the definitions needs no migration.
|
|
22
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
23
|
+
* @param {Object} mirror
|
|
24
|
+
* @param {import('../tally/xml.js').TableDefinition[]} mirror.tables - definitions, in order
|
|
25
|
+
* @param {Record<string, Record<string, unknown>[]>} mirror.rows - rows per table name
|
|
26
|
+
* @param {import('../tally/xml.js').CompanyInfo} mirror.info
|
|
27
|
+
* @param {{run_id: number, synced_at: string, tie_out: unknown}} mirror.sync
|
|
28
|
+
*/
|
|
29
|
+
export function replaceMirror(db, { tables, rows, info, sync }) {
|
|
30
|
+
inTransaction(db, () => {
|
|
31
|
+
for (const table of tables) {
|
|
32
|
+
db.exec(`DROP TABLE IF EXISTS "${table.name}";`);
|
|
33
|
+
db.exec(createTableSql(table));
|
|
34
|
+
const columns = table.fields.map((field) => `"${columnName(field)}"`).join(', ');
|
|
35
|
+
const placeholders = table.fields.map(() => '?').join(', ');
|
|
36
|
+
const insert = db.prepare(`INSERT INTO "${table.name}" (${columns}) VALUES (${placeholders})`);
|
|
37
|
+
for (const row of rows[table.name] ?? []) insert.run(...table.fields.map((field) => columnValue(field, row[field.name])));
|
|
38
|
+
}
|
|
39
|
+
db.exec('DROP TABLE IF EXISTS "company";');
|
|
40
|
+
db.exec(COMPANY_TABLE_SQL);
|
|
41
|
+
db.prepare(
|
|
42
|
+
'INSERT INTO "company" (guid, name, books_from, last_voucher_date, alter_id_master, alter_id_transaction, synced_at, run_id, tie_out_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
|
43
|
+
).run(info.guid, info.name, info.books_from, info.last_voucher_date, info.alter_id_master, info.alter_id_transaction, sync.synced_at, sync.run_id, JSON.stringify(sync.tie_out));
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Opens a company's mirror file for writing.
|
|
49
|
+
* @param {string} data_dir
|
|
50
|
+
* @param {string} company_guid
|
|
51
|
+
*/
|
|
52
|
+
export function openCompanyDb(data_dir, company_guid) {
|
|
53
|
+
return openSqlite(companyDbFile(data_dir, company_guid));
|
|
54
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The mirror's tables, generated from the table definitions. Column names are the loader's,
|
|
3
|
+
// except money: every amount column holds integer paise and is named <name>_paise.
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @param {import('../tally/xml.js').FieldDefinition} field
|
|
7
|
+
* @returns {string}
|
|
8
|
+
*/
|
|
9
|
+
export function columnName(field) {
|
|
10
|
+
return field.type === 'amount' ? `${field.name}_paise` : field.name;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const SQL_TYPES = { text: 'TEXT', date: 'TEXT', logical: 'INTEGER', amount: 'INTEGER', number: 'REAL', quantity: 'REAL', rate: 'REAL' };
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {import('../tally/xml.js').TableDefinition} table
|
|
17
|
+
* @returns {string}
|
|
18
|
+
*/
|
|
19
|
+
export function createTableSql(table) {
|
|
20
|
+
const columns = table.fields.map((field) => `"${columnName(field)}" ${SQL_TYPES[field.type] ?? 'TEXT'}`);
|
|
21
|
+
return `CREATE TABLE "${table.name}" (${columns.join(', ')});`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Converts a parsed value to what the column stores: amounts to integer paise, logicals to 0/1.
|
|
26
|
+
* @param {import('../tally/xml.js').FieldDefinition} field
|
|
27
|
+
* @param {unknown} value
|
|
28
|
+
* @returns {string|number|null}
|
|
29
|
+
*/
|
|
30
|
+
export function columnValue(field, value) {
|
|
31
|
+
if (value === null || value === undefined) return null;
|
|
32
|
+
if (field.type === 'amount') return Math.round(Number(value) * 100);
|
|
33
|
+
if (field.type === 'logical') return value ? 1 : 0;
|
|
34
|
+
if (typeof value === 'number') return value;
|
|
35
|
+
return String(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The company file's own table: which company it holds and the sync that wrote it. */
|
|
39
|
+
export const COMPANY_TABLE_SQL = `CREATE TABLE "company" (
|
|
40
|
+
guid TEXT NOT NULL,
|
|
41
|
+
name TEXT NOT NULL,
|
|
42
|
+
books_from TEXT,
|
|
43
|
+
last_voucher_date TEXT,
|
|
44
|
+
alter_id_master INTEGER,
|
|
45
|
+
alter_id_transaction INTEGER,
|
|
46
|
+
synced_at TEXT NOT NULL,
|
|
47
|
+
run_id INTEGER,
|
|
48
|
+
tie_out_json TEXT
|
|
49
|
+
);`;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Opening SQLite files with Node's built-in driver (node:sqlite): nothing native to build
|
|
3
|
+
// on Windows.
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Opens (creating if needed) a SQLite file in WAL mode, so the web process can read while
|
|
11
|
+
* the sync process writes.
|
|
12
|
+
* @param {string} file
|
|
13
|
+
* @param {{readonly?: boolean}} [options]
|
|
14
|
+
* @returns {DatabaseSync}
|
|
15
|
+
*/
|
|
16
|
+
export function openSqlite(file, { readonly = false } = {}) {
|
|
17
|
+
if (!readonly) fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
18
|
+
const db = new DatabaseSync(file, { readOnly: readonly });
|
|
19
|
+
if (!readonly) db.exec('PRAGMA journal_mode = WAL;');
|
|
20
|
+
db.exec('PRAGMA busy_timeout = 5000;');
|
|
21
|
+
return db;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Runs fn inside one transaction: everything or nothing.
|
|
26
|
+
* @template T
|
|
27
|
+
* @param {DatabaseSync} db
|
|
28
|
+
* @param {() => T} fn
|
|
29
|
+
* @returns {T}
|
|
30
|
+
*/
|
|
31
|
+
export function inTransaction(db, fn) {
|
|
32
|
+
db.exec('BEGIN IMMEDIATE;');
|
|
33
|
+
try {
|
|
34
|
+
const result = fn();
|
|
35
|
+
db.exec('COMMIT;');
|
|
36
|
+
return result;
|
|
37
|
+
} catch (err) {
|
|
38
|
+
db.exec('ROLLBACK;');
|
|
39
|
+
throw err;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The probe file: one JSON file with the probe's findings and every raw exchange with Tally.
|
|
3
|
+
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @typedef {Object} ProbeFile
|
|
9
|
+
* @property {string} tool
|
|
10
|
+
* @property {string} version - tally-sync version
|
|
11
|
+
* @property {string} created_at
|
|
12
|
+
* @property {{node: string, platform: string, arch: string}} system
|
|
13
|
+
* @property {{host: string, port: number}} tally
|
|
14
|
+
* @property {{steps: number, failed: number}} summary
|
|
15
|
+
* @property {import('./runProbe.js').ProbeStep[]} steps
|
|
16
|
+
* @property {import('../tally/gateway.js').Exchange[]} exchanges
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {Object} parts
|
|
21
|
+
* @param {string} parts.version
|
|
22
|
+
* @param {Date} parts.now
|
|
23
|
+
* @param {{node: string, platform: string, arch: string}} parts.system
|
|
24
|
+
* @param {{host: string, port: number}} parts.tally
|
|
25
|
+
* @param {import('./runProbe.js').ProbeStep[]} parts.steps
|
|
26
|
+
* @param {import('../tally/gateway.js').Exchange[]} parts.exchanges
|
|
27
|
+
* @returns {ProbeFile}
|
|
28
|
+
*/
|
|
29
|
+
export function buildProbeFile({ version, now, system, tally, steps, exchanges }) {
|
|
30
|
+
return {
|
|
31
|
+
tool: 'tally-sync probe',
|
|
32
|
+
version,
|
|
33
|
+
created_at: now.toISOString(),
|
|
34
|
+
system,
|
|
35
|
+
tally,
|
|
36
|
+
summary: { steps: steps.length, failed: steps.filter((s) => !s.ok).length },
|
|
37
|
+
steps,
|
|
38
|
+
exchanges,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Writes the probe file into dir and returns its path.
|
|
44
|
+
* @param {string} dir
|
|
45
|
+
* @param {ProbeFile} probe_file
|
|
46
|
+
* @returns {string}
|
|
47
|
+
*/
|
|
48
|
+
export function writeProbeFile(dir, probe_file) {
|
|
49
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
50
|
+
const stamp = probe_file.created_at.replace(/[-:]/g, '').replace(/\..+$/, '').replace('T', '-');
|
|
51
|
+
const file = path.join(dir, `probe-${stamp}.json`);
|
|
52
|
+
fs.writeFileSync(file, `${JSON.stringify(probe_file, null, 2)}\n`);
|
|
53
|
+
return file;
|
|
54
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The probe: a fixed list of read-only requests that shows how a real Tally answers.
|
|
3
|
+
// A failing step is recorded and the probe moves on, so one file shows everything at once.
|
|
4
|
+
|
|
5
|
+
import { countVouchersByDate, fetchTable, fetchTransactionWindow, getCompanyInfo, listCompanies, planDateWindows } from '../tally/requests.js';
|
|
6
|
+
import { addDays, laterDate } from '../tally/dates.js';
|
|
7
|
+
import { unbalancedVouchers } from '../sync/checkPull.js';
|
|
8
|
+
|
|
9
|
+
/** Days of vouchers the probe pulls for each transaction table. */
|
|
10
|
+
export const PROBE_VOUCHER_DAYS = 7;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @typedef {Object} ProbeStep
|
|
14
|
+
* @property {string} name
|
|
15
|
+
* @property {string|null} company
|
|
16
|
+
* @property {boolean} ok
|
|
17
|
+
* @property {number} ms
|
|
18
|
+
* @property {Record<string, unknown>} [result] - what the step found
|
|
19
|
+
* @property {{code: string, message: string}} [error]
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Runs one step, timing it and catching its error.
|
|
24
|
+
* @template T
|
|
25
|
+
* @param {ProbeStep[]} steps - the step is appended here
|
|
26
|
+
* @param {string} name
|
|
27
|
+
* @param {string|null} company
|
|
28
|
+
* @param {() => Promise<T>} run
|
|
29
|
+
* @param {(value: T) => Record<string, unknown>} describe - what to record from the value
|
|
30
|
+
* @returns {Promise<T|null>} the value, or null when the step failed
|
|
31
|
+
*/
|
|
32
|
+
async function step(steps, name, company, run, describe) {
|
|
33
|
+
const started = Date.now();
|
|
34
|
+
try {
|
|
35
|
+
const value = await run();
|
|
36
|
+
steps.push({ name, company, ok: true, ms: Date.now() - started, result: describe(value) });
|
|
37
|
+
return value;
|
|
38
|
+
} catch (err) {
|
|
39
|
+
steps.push({ name, company, ok: false, ms: Date.now() - started, error: { code: err.code ?? 'ERROR', message: err.message } });
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Probes one company: its info, every master table, voucher counts, and one week of
|
|
46
|
+
* every transaction table.
|
|
47
|
+
* @param {ProbeStep[]} steps
|
|
48
|
+
* @param {import('../tally/gateway.js').Gateway} gateway
|
|
49
|
+
* @param {import('../tally/definitions.js').Definitions} definitions
|
|
50
|
+
* @param {string} company
|
|
51
|
+
*/
|
|
52
|
+
async function probeCompany(steps, gateway, definitions, company) {
|
|
53
|
+
const info = await step(steps, 'company info', company, () => getCompanyInfo(gateway, company), (value) =>
|
|
54
|
+
value ? { ...value } : { loaded: false },
|
|
55
|
+
);
|
|
56
|
+
if (!info) return;
|
|
57
|
+
|
|
58
|
+
const from_date = info.books_from;
|
|
59
|
+
const to_date = laterDate(info.last_voucher_date, info.books_from);
|
|
60
|
+
|
|
61
|
+
for (const table of definitions.master) {
|
|
62
|
+
await step(steps, `table ${table.name}`, company, () => fetchTable(gateway, table, { company, from_date, to_date }), (rows) => ({
|
|
63
|
+
rows: rows.length,
|
|
64
|
+
rows_without_guid: rows.filter((row) => !row.guid).length,
|
|
65
|
+
first_row: rows[0] ?? null,
|
|
66
|
+
}));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const counts = await step(steps, 'voucher counts', company, () => countVouchersByDate(gateway, { company, from_date, to_date }), (value) => ({
|
|
70
|
+
total: value.total,
|
|
71
|
+
days_with_vouchers: Object.keys(value.by_date).length,
|
|
72
|
+
first_date: Object.keys(value.by_date).sort()[0] ?? null,
|
|
73
|
+
last_date: Object.keys(value.by_date).sort().at(-1) ?? null,
|
|
74
|
+
planned_windows: planDateWindows(value.by_date, { from_date, to_date }).length,
|
|
75
|
+
}));
|
|
76
|
+
|
|
77
|
+
const window_from = laterDate(addDays(to_date, -(PROBE_VOUCHER_DAYS - 1)), from_date);
|
|
78
|
+
const window = { from_date: window_from, to_date, count: counts ? countInWindow(counts.by_date, window_from, to_date) : 0 };
|
|
79
|
+
|
|
80
|
+
for (const table of definitions.transaction) {
|
|
81
|
+
await step(steps, `table ${table.name} (${window.from_date} to ${window.to_date})`, company, () => fetchTransactionWindow(gateway, table, { company, window }), (rows) => ({
|
|
82
|
+
rows: rows.length,
|
|
83
|
+
...(table.name === 'trn_voucher' ? { vouchers_counted_for_window: window.count, matches_count: rows.length === window.count } : {}),
|
|
84
|
+
...(table.name === 'trn_accounting' ? { unbalanced_vouchers: unbalancedVouchers(rows) } : {}),
|
|
85
|
+
first_row: rows[0] ?? null,
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @param {Record<string, number>} by_date
|
|
92
|
+
* @param {string} from_date
|
|
93
|
+
* @param {string} to_date
|
|
94
|
+
*/
|
|
95
|
+
function countInWindow(by_date, from_date, to_date) {
|
|
96
|
+
return Object.entries(by_date)
|
|
97
|
+
.filter(([day]) => day >= from_date && day <= to_date)
|
|
98
|
+
.reduce((sum, [, count]) => sum + count, 0);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Runs the probe against Tally.
|
|
103
|
+
* @param {Object} options
|
|
104
|
+
* @param {import('../tally/gateway.js').Gateway} options.gateway
|
|
105
|
+
* @param {import('../tally/definitions.js').Definitions} options.definitions
|
|
106
|
+
* @param {string} [options.company] - probe only this company; all loaded companies when absent
|
|
107
|
+
* @returns {Promise<ProbeStep[]>}
|
|
108
|
+
*/
|
|
109
|
+
export async function runProbe({ gateway, definitions, company }) {
|
|
110
|
+
/** @type {ProbeStep[]} */
|
|
111
|
+
const steps = [];
|
|
112
|
+
const companies = await step(steps, 'list companies', null, () => listCompanies(gateway), (names) => ({ companies: names }));
|
|
113
|
+
if (!companies) return steps;
|
|
114
|
+
|
|
115
|
+
const targets = company ? [company] : companies;
|
|
116
|
+
for (const target of targets) await probeCompany(steps, gateway, definitions, target);
|
|
117
|
+
return steps;
|
|
118
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Checks a pull before it may replace the mirror. Each check catches a way Tally has been
|
|
3
|
+
// seen to answer wrongly (tally-to-duckdb, sync.py): windows ignored, short answers,
|
|
4
|
+
// vouchers missing or doubled.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {Object} Problem
|
|
8
|
+
* @property {string} check
|
|
9
|
+
* @property {string} message
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** A full pull with fewer than this share of the vouchers already mirrored is refused. */
|
|
13
|
+
export const MIN_SHARE_OF_PREVIOUS = 0.9;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Vouchers whose accounting lines don't net to zero, to the paisa.
|
|
17
|
+
* @param {Record<string, unknown>[]} lines - trn_accounting rows
|
|
18
|
+
* @returns {string[]} voucher GUIDs
|
|
19
|
+
*/
|
|
20
|
+
export function unbalancedVouchers(lines) {
|
|
21
|
+
/** @type {Map<string, number>} */
|
|
22
|
+
const totals = new Map();
|
|
23
|
+
for (const line of lines) {
|
|
24
|
+
const guid = String(line.guid);
|
|
25
|
+
totals.set(guid, (totals.get(guid) ?? 0) + Math.round(Number(line.amount) * 100));
|
|
26
|
+
}
|
|
27
|
+
return [...totals].filter(([, paise]) => paise !== 0).map(([guid]) => guid);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {import('./pullCompany.js').Pull} pull
|
|
32
|
+
* @param {{previous_voucher_count?: number|null}} [options]
|
|
33
|
+
* @returns {Problem[]} empty when the pull may be used
|
|
34
|
+
*/
|
|
35
|
+
export function checkPull(pull, { previous_voucher_count = null } = {}) {
|
|
36
|
+
/** @type {Problem[]} */
|
|
37
|
+
const problems = [];
|
|
38
|
+
const vouchers = pull.rows.trn_voucher ?? [];
|
|
39
|
+
|
|
40
|
+
if (vouchers.length !== pull.counts.total) {
|
|
41
|
+
problems.push({ check: 'voucher_total', message: `pulled ${vouchers.length} vouchers, Tally counted ${pull.counts.total}` });
|
|
42
|
+
}
|
|
43
|
+
for (const window of pull.windows) {
|
|
44
|
+
if (window.vouchers_pulled !== window.count) {
|
|
45
|
+
problems.push({ check: 'window_count', message: `${window.from_date} to ${window.to_date}: pulled ${window.vouchers_pulled} vouchers, Tally counted ${window.count}` });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const guids = vouchers.map((v) => String(v.guid));
|
|
49
|
+
const duplicates = guids.length - new Set(guids).size;
|
|
50
|
+
if (duplicates > 0) problems.push({ check: 'duplicate_vouchers', message: `${duplicates} vouchers were pulled more than once` });
|
|
51
|
+
|
|
52
|
+
const unbalanced = unbalancedVouchers(pull.rows.trn_accounting ?? []);
|
|
53
|
+
if (unbalanced.length > 0) {
|
|
54
|
+
problems.push({ check: 'unbalanced_vouchers', message: `${unbalanced.length} vouchers' lines don't net to zero, e.g. ${unbalanced.slice(0, 3).join(', ')}` });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (previous_voucher_count && vouchers.length < previous_voucher_count * MIN_SHARE_OF_PREVIOUS) {
|
|
58
|
+
problems.push({ check: 'shrunk', message: `pulled ${vouchers.length} vouchers, the mirror has ${previous_voucher_count}: refusing to replace it` });
|
|
59
|
+
}
|
|
60
|
+
return problems;
|
|
61
|
+
}
|