@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,46 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Where tally-sync keeps its config, data and logs, and what the config holds.
|
|
3
|
+
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import yaml from 'js-yaml';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {Object} Config
|
|
10
|
+
* @property {{host: string, port: number, url?: string, timeout_seconds: number}} tally
|
|
11
|
+
* url, when set, replaces host and port: Tally reached through a tunnel, e.g. https://name.ngrok-free.app
|
|
12
|
+
* @property {{interval_minutes: number, batch_size: number}} sync
|
|
13
|
+
* @property {{port: number}} web - the local UI, served on 127.0.0.1 only
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** @type {Config} */
|
|
17
|
+
export const DEFAULT_CONFIG = {
|
|
18
|
+
tally: { host: 'localhost', port: 9000, timeout_seconds: 1800 },
|
|
19
|
+
sync: { interval_minutes: 5, batch_size: 5000 },
|
|
20
|
+
web: { port: 7780 },
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The config directory: FOB_TALLY_SYNC_CONFIG_DIR when set, else ~/.fob/tally-sync.
|
|
25
|
+
* @param {{env: Record<string, string|undefined>, homedir: string}} options
|
|
26
|
+
* @returns {string}
|
|
27
|
+
*/
|
|
28
|
+
export function resolveConfigDir({ env, homedir }) {
|
|
29
|
+
return env.FOB_TALLY_SYNC_CONFIG_DIR || path.join(homedir, '.fob', 'tally-sync');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Reads config.yml from the config directory, over the defaults. A missing file means defaults.
|
|
34
|
+
* @param {string} config_dir
|
|
35
|
+
* @returns {Config}
|
|
36
|
+
*/
|
|
37
|
+
export function loadConfig(config_dir) {
|
|
38
|
+
const file = path.join(config_dir, 'config.yml');
|
|
39
|
+
if (!fs.existsSync(file)) return DEFAULT_CONFIG;
|
|
40
|
+
const parsed = /** @type {Partial<Config>} */ (yaml.load(fs.readFileSync(file, 'utf8')) ?? {});
|
|
41
|
+
return {
|
|
42
|
+
tally: { ...DEFAULT_CONFIG.tally, ...(parsed.tally ?? {}) },
|
|
43
|
+
sync: { ...DEFAULT_CONFIG.sync, ...(parsed.sync ?? {}) },
|
|
44
|
+
web: { ...DEFAULT_CONFIG.web, ...(parsed.web ?? {}) },
|
|
45
|
+
};
|
|
46
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The debug log: every exchange with Tally, one JSON object per line, in
|
|
3
|
+
// <config dir>/logs/tally-sync-<date>.log. It holds the company's books: read it before sharing.
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Opens (creating if needed) today's debug log.
|
|
10
|
+
* @param {string} logs_dir
|
|
11
|
+
* @param {Date} now
|
|
12
|
+
* @returns {{file: string, write: (entry: Record<string, unknown>) => void}}
|
|
13
|
+
*/
|
|
14
|
+
export function openDebugLog(logs_dir, now) {
|
|
15
|
+
fs.mkdirSync(logs_dir, { recursive: true });
|
|
16
|
+
const file = path.join(logs_dir, `tally-sync-${now.toISOString().slice(0, 10)}.log`);
|
|
17
|
+
return {
|
|
18
|
+
file,
|
|
19
|
+
write(entry) {
|
|
20
|
+
fs.appendFileSync(file, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`);
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// How the local UI writes money, dates and sync runs. Plain functions, so pages and tests
|
|
3
|
+
// share them. Times are shown in the PC's own time zone: the UI runs on that PC.
|
|
4
|
+
|
|
5
|
+
const RUPEES = new Intl.NumberFormat('en-IN');
|
|
6
|
+
const DATE = new Intl.DateTimeFormat('en-IN', { day: 'numeric', month: 'short', year: 'numeric' });
|
|
7
|
+
const DATE_UTC = new Intl.DateTimeFormat('en-IN', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' });
|
|
8
|
+
const TIME = new Intl.DateTimeFormat('en-IN', { hour: 'numeric', minute: '2-digit', hour12: true });
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Paise as Indian-format rupees with Dr or Cr. Tally's sign: negative is a debit.
|
|
12
|
+
* @param {number|null|undefined} paise
|
|
13
|
+
* @returns {string} e.g. "12,34,567.00 Dr"; "0.00" for zero; "" for no value
|
|
14
|
+
*/
|
|
15
|
+
export function formatMoney(paise) {
|
|
16
|
+
if (paise === null || paise === undefined || Number.isNaN(Number(paise))) return '';
|
|
17
|
+
const amount = Number(paise);
|
|
18
|
+
const abs = Math.abs(amount);
|
|
19
|
+
const text = `${RUPEES.format(Math.floor(abs / 100))}.${String(abs % 100).padStart(2, '0')}`;
|
|
20
|
+
if (amount < 0) return `${text} Dr`;
|
|
21
|
+
if (amount > 0) return `${text} Cr`;
|
|
22
|
+
return text;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A Tally date (YYYY-MM-DD) as "1 Apr 2025".
|
|
27
|
+
* @param {string|null|undefined} date
|
|
28
|
+
* @returns {string}
|
|
29
|
+
*/
|
|
30
|
+
export function formatDate(date) {
|
|
31
|
+
if (!date) return '';
|
|
32
|
+
const parsed = new Date(`${date}T00:00:00Z`);
|
|
33
|
+
return Number.isNaN(parsed.getTime()) ? String(date) : DATE_UTC.format(parsed);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A timestamp as "27 Nov 2026, 1:08 pm", in the PC's time zone.
|
|
38
|
+
* @param {string|null|undefined} iso
|
|
39
|
+
* @returns {string}
|
|
40
|
+
*/
|
|
41
|
+
export function formatDateTime(iso) {
|
|
42
|
+
if (!iso) return '';
|
|
43
|
+
const parsed = new Date(iso);
|
|
44
|
+
if (Number.isNaN(parsed.getTime())) return String(iso);
|
|
45
|
+
return `${DATE.format(parsed)}, ${TIME.format(parsed)}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* How long ago a timestamp was: "just now", "5 min ago", "3 h ago", else the date and time.
|
|
50
|
+
* @param {string|null|undefined} iso
|
|
51
|
+
* @param {Date} [now]
|
|
52
|
+
* @returns {string}
|
|
53
|
+
*/
|
|
54
|
+
export function formatAgo(iso, now = new Date()) {
|
|
55
|
+
if (!iso) return '';
|
|
56
|
+
const parsed = new Date(iso);
|
|
57
|
+
if (Number.isNaN(parsed.getTime())) return String(iso);
|
|
58
|
+
const minutes = Math.floor((now.getTime() - parsed.getTime()) / 60000);
|
|
59
|
+
if (minutes < 1) return 'just now';
|
|
60
|
+
if (minutes < 60) return `${minutes} min ago`;
|
|
61
|
+
if (minutes < 24 * 60) return `${Math.floor(minutes / 60)} h ago`;
|
|
62
|
+
return formatDateTime(iso);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* How long a run took: "under 1 s", "42 s", "3 min 5 s".
|
|
67
|
+
* @param {string|null|undefined} started_at
|
|
68
|
+
* @param {string|null|undefined} finished_at
|
|
69
|
+
* @returns {string} "" while it hasn't finished
|
|
70
|
+
*/
|
|
71
|
+
export function formatDuration(started_at, finished_at) {
|
|
72
|
+
if (!started_at || !finished_at) return '';
|
|
73
|
+
const seconds = Math.round((new Date(finished_at).getTime() - new Date(started_at).getTime()) / 1000);
|
|
74
|
+
if (Number.isNaN(seconds)) return '';
|
|
75
|
+
if (seconds < 1) return 'under 1 s';
|
|
76
|
+
if (seconds < 60) return `${seconds} s`;
|
|
77
|
+
const rest = seconds % 60;
|
|
78
|
+
return `${Math.floor(seconds / 60)} min${rest ? ` ${rest} s` : ''}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** @typedef {'success'|'destructive'|'warning'|'default'|'secondary'} BadgeVariant */
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A sync run's status in words, and the badge it gets (design-standards StateLabel).
|
|
85
|
+
* @param {string|null|undefined} status
|
|
86
|
+
* @returns {{label: string, variant: BadgeVariant}}
|
|
87
|
+
*/
|
|
88
|
+
export function runStatus(status) {
|
|
89
|
+
if (status === 'succeeded') return { label: 'Synced', variant: 'success' };
|
|
90
|
+
if (status === 'failed') return { label: 'Failed', variant: 'destructive' };
|
|
91
|
+
if (status === 'running') return { label: 'Syncing', variant: 'default' };
|
|
92
|
+
if (status === 'abandoned') return { label: 'Interrupted', variant: 'secondary' };
|
|
93
|
+
return { label: 'Not synced yet', variant: 'secondary' };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const CHECK_NAMES = {
|
|
97
|
+
voucher_total: 'Voucher count differs from Tally',
|
|
98
|
+
window_count: 'Vouchers missing in a date range',
|
|
99
|
+
duplicate_vouchers: 'Vouchers pulled twice',
|
|
100
|
+
unbalanced_vouchers: "Vouchers that don't balance",
|
|
101
|
+
shrunk: 'Fewer vouchers than the last sync',
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* @typedef {Object} RunDetail
|
|
106
|
+
* @property {Record<string, number>|null} counts
|
|
107
|
+
* @property {string[]} problems - each in plain words
|
|
108
|
+
* @property {import('../sync/tieOut.js').TieOut|null} tie_out
|
|
109
|
+
*/
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* A sync_runs row's JSON columns, parsed, with each problem in plain words.
|
|
113
|
+
* @param {Record<string, any>|null|undefined} run
|
|
114
|
+
* @returns {RunDetail}
|
|
115
|
+
*/
|
|
116
|
+
export function runDetail(run) {
|
|
117
|
+
const parse = (/** @type {unknown} */ text) => (text ? JSON.parse(String(text)) : null);
|
|
118
|
+
/** @type {{check: string, message: string}[]} */
|
|
119
|
+
const problems = parse(run?.problems_json) ?? [];
|
|
120
|
+
return {
|
|
121
|
+
counts: parse(run?.counts_json),
|
|
122
|
+
problems: problems.map((p) => `${CHECK_NAMES[p.check] ?? p.check}: ${p.message}`),
|
|
123
|
+
tie_out: parse(run?.tie_out_json),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The tie-out in a few words, and the badge it gets.
|
|
129
|
+
* @param {import('../sync/tieOut.js').TieOut|null|undefined} tie_out
|
|
130
|
+
* @returns {{label: string, variant: BadgeVariant}|null} null when there's no tie-out yet
|
|
131
|
+
*/
|
|
132
|
+
export function tieOutVerdict(tie_out) {
|
|
133
|
+
if (!tie_out) return null;
|
|
134
|
+
if (tie_out.matched) return { label: 'Matches Tally', variant: 'success' };
|
|
135
|
+
const n = tie_out.differences.length;
|
|
136
|
+
return { label: `${n} ${n === 1 ? 'ledger differs' : 'ledgers differ'}`, variant: 'warning' };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const TABLE_LABELS = {
|
|
140
|
+
mst_group: 'Groups',
|
|
141
|
+
mst_ledger: 'Ledgers',
|
|
142
|
+
mst_vouchertype: 'Voucher types',
|
|
143
|
+
mst_cost_category: 'Cost categories',
|
|
144
|
+
mst_cost_centre: 'Cost centres',
|
|
145
|
+
mst_opening_bill_allocation: 'Opening bills',
|
|
146
|
+
trn_voucher: 'Vouchers',
|
|
147
|
+
trn_accounting: 'Ledger lines',
|
|
148
|
+
trn_bill: 'Bill allocations',
|
|
149
|
+
trn_bank: 'Bank allocations',
|
|
150
|
+
trn_cost_centre: 'Cost-centre allocations',
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* A mirror table's name in words: "Ledgers" for mst_ledger.
|
|
155
|
+
* @param {string} table
|
|
156
|
+
* @returns {string}
|
|
157
|
+
*/
|
|
158
|
+
export function tableLabel(table) {
|
|
159
|
+
return TABLE_LABELS[table] ?? table;
|
|
160
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Reading one company's mirror for the local UI: the company, its tables, a page of rows,
|
|
3
|
+
// one voucher. Read-only. Table names are checked against the mirror's own tables, never
|
|
4
|
+
// taken from the request as is.
|
|
5
|
+
//
|
|
6
|
+
// The tables and columns come from the mirror file's schema, which the sync generated from
|
|
7
|
+
// the definitions. The web process doesn't load definitions.yaml: Next's bundler rewrites
|
|
8
|
+
// the `new URL(..., import.meta.url)` that finds it.
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import { companyDbFile } from '../mirror/companyDb.js';
|
|
12
|
+
import { openSqlite } from '../mirror/sqlite.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The mirror's tables (mst_* and trn_*), in the order the sync created them, with their columns.
|
|
16
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
17
|
+
* @returns {{name: string, kind: 'master'|'transaction', columns: {name: string, type: string}[]}[]}
|
|
18
|
+
*/
|
|
19
|
+
function mirrorTables(db) {
|
|
20
|
+
return db
|
|
21
|
+
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND (name LIKE 'mst\\_%' ESCAPE '\\' OR name LIKE 'trn\\_%' ESCAPE '\\') ORDER BY rowid")
|
|
22
|
+
.all()
|
|
23
|
+
.map((row) => {
|
|
24
|
+
const name = String(row.name);
|
|
25
|
+
const columns = db.prepare(`PRAGMA table_info("${name}")`).all().map((c) => ({ name: String(c.name), type: String(c.type) }));
|
|
26
|
+
return { name, kind: /** @type {'master'|'transaction'} */ (name.startsWith('mst_') ? 'master' : 'transaction'), columns };
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Rows per page in the table browser. */
|
|
31
|
+
export const PAGE_SIZE = 50;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @template T
|
|
35
|
+
* @param {string} data_dir
|
|
36
|
+
* @param {string} company_guid
|
|
37
|
+
* @param {(db: import('node:sqlite').DatabaseSync) => T} read
|
|
38
|
+
* @returns {T|null} null when the company has no mirror yet
|
|
39
|
+
*/
|
|
40
|
+
function withCompanyDb(data_dir, company_guid, read) {
|
|
41
|
+
const file = companyDbFile(data_dir, company_guid);
|
|
42
|
+
if (!fs.existsSync(file)) return null;
|
|
43
|
+
const db = openSqlite(file, { readonly: true });
|
|
44
|
+
try {
|
|
45
|
+
return read(db);
|
|
46
|
+
} finally {
|
|
47
|
+
db.close();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @typedef {Object} CompanyMirror
|
|
53
|
+
* @property {Record<string, any>} company - the company row: name, dates, AlterIDs, synced_at
|
|
54
|
+
* @property {import('../sync/tieOut.js').TieOut|null} tie_out
|
|
55
|
+
* @property {{name: string, kind: 'master'|'transaction', rows: number}[]} tables
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {string} data_dir
|
|
60
|
+
* @param {string} company_guid
|
|
61
|
+
* @returns {CompanyMirror|null}
|
|
62
|
+
*/
|
|
63
|
+
export function readCompanyMirror(data_dir, company_guid) {
|
|
64
|
+
return withCompanyDb(data_dir, company_guid, (db) => {
|
|
65
|
+
const company = db.prepare('SELECT * FROM company').get() ?? {};
|
|
66
|
+
const tables = mirrorTables(db).map((table) => ({
|
|
67
|
+
name: table.name,
|
|
68
|
+
kind: table.kind,
|
|
69
|
+
rows: Number(db.prepare(`SELECT count(*) AS n FROM "${table.name}"`).get()?.n ?? 0),
|
|
70
|
+
}));
|
|
71
|
+
return { company, tie_out: company.tie_out_json ? JSON.parse(String(company.tie_out_json)) : null, tables };
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @typedef {Object} TablePage
|
|
77
|
+
* @property {string} table
|
|
78
|
+
* @property {string[]} columns
|
|
79
|
+
* @property {Record<string, unknown>[]} rows
|
|
80
|
+
* @property {number} total - rows matching the search
|
|
81
|
+
* @property {number} page - 1-based
|
|
82
|
+
* @property {number} page_size
|
|
83
|
+
*/
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* One page of a mirror table, optionally filtered by a search over its text columns.
|
|
87
|
+
* @param {string} data_dir
|
|
88
|
+
* @param {string} company_guid
|
|
89
|
+
* @param {string} table_name - must be one of the mirror's tables
|
|
90
|
+
* @param {{page?: number, search?: string}} [options]
|
|
91
|
+
* @returns {TablePage|null} null when the table or the mirror doesn't exist
|
|
92
|
+
*/
|
|
93
|
+
export function readTablePage(data_dir, company_guid, table_name, { page = 1, search = '' } = {}) {
|
|
94
|
+
const result = withCompanyDb(data_dir, company_guid, (db) => {
|
|
95
|
+
const table = mirrorTables(db).find((t) => t.name === table_name);
|
|
96
|
+
if (!table) return null;
|
|
97
|
+
const columns = table.columns.map((c) => c.name);
|
|
98
|
+
const text_columns = table.columns.filter((c) => c.type === 'TEXT').map((c) => c.name);
|
|
99
|
+
const where = search && text_columns.length ? `WHERE ${text_columns.map((c) => `"${c}" LIKE ?`).join(' OR ')}` : '';
|
|
100
|
+
const params = where ? text_columns.map(() => `%${search}%`) : [];
|
|
101
|
+
const total = Number(db.prepare(`SELECT count(*) AS n FROM "${table.name}" ${where}`).get(...params)?.n ?? 0);
|
|
102
|
+
const current = Math.max(1, Math.floor(page));
|
|
103
|
+
const rows = db.prepare(`SELECT * FROM "${table.name}" ${where} LIMIT ? OFFSET ?`).all(...params, PAGE_SIZE, (current - 1) * PAGE_SIZE);
|
|
104
|
+
return { table: table.name, columns, rows, total, page: current, page_size: PAGE_SIZE };
|
|
105
|
+
});
|
|
106
|
+
return result ?? null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* @typedef {Object} VoucherDetail
|
|
111
|
+
* @property {Record<string, unknown>} voucher - the trn_voucher row
|
|
112
|
+
* @property {Record<string, unknown>[]} lines - trn_accounting rows
|
|
113
|
+
* @property {Record<string, unknown>[]} bills - trn_bill rows
|
|
114
|
+
* @property {Record<string, unknown>[]} bank - trn_bank rows
|
|
115
|
+
* @property {Record<string, unknown>[]} cost_centres - trn_cost_centre rows
|
|
116
|
+
* Allocations carry the voucher GUID and the ledger name, not the line they belong to.
|
|
117
|
+
*/
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* @param {string} data_dir
|
|
121
|
+
* @param {string} company_guid
|
|
122
|
+
* @param {string} voucher_guid
|
|
123
|
+
* @returns {VoucherDetail|null}
|
|
124
|
+
*/
|
|
125
|
+
export function readVoucher(data_dir, company_guid, voucher_guid) {
|
|
126
|
+
return withCompanyDb(data_dir, company_guid, (db) => {
|
|
127
|
+
const voucher = db.prepare('SELECT * FROM trn_voucher WHERE guid = ?').get(voucher_guid);
|
|
128
|
+
if (!voucher) return null;
|
|
129
|
+
const rowsOf = (table) => db.prepare(`SELECT * FROM "${table}" WHERE guid = ?`).all(voucher_guid);
|
|
130
|
+
return { voucher, lines: rowsOf('trn_accounting'), bills: rowsOf('trn_bill'), bank: rowsOf('trn_bank'), cost_centres: rowsOf('trn_cost_centre') };
|
|
131
|
+
});
|
|
132
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// What the local UI shows, read from the agent's SQLite files. The web process only reads;
|
|
3
|
+
// the sync process is the only writer.
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { openSqlite } from '../mirror/sqlite.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {Object} CompanyStatus
|
|
11
|
+
* @property {string} guid
|
|
12
|
+
* @property {string} name
|
|
13
|
+
* @property {boolean} loaded - loaded in Tally at the last pass
|
|
14
|
+
* @property {string} last_seen_loaded_at
|
|
15
|
+
* @property {string|null} last_checked_at - when the sync last asked Tally about it, even if nothing had changed
|
|
16
|
+
* @property {Record<string, any>|null} last_run - the company's latest sync run
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {Object} AgentStatus
|
|
21
|
+
* @property {string|null} last_pass_at
|
|
22
|
+
* @property {boolean|null} tally_reachable - null before the first pass
|
|
23
|
+
* @property {string|null} error
|
|
24
|
+
* @property {CompanyStatus[]} companies
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {string} data_dir
|
|
29
|
+
* @returns {AgentStatus}
|
|
30
|
+
*/
|
|
31
|
+
export function readAgentStatus(data_dir) {
|
|
32
|
+
const file = path.join(data_dir, 'agent.db');
|
|
33
|
+
if (!fs.existsSync(file)) return { last_pass_at: null, tally_reachable: null, error: null, companies: [] };
|
|
34
|
+
const db = openSqlite(file, { readonly: true });
|
|
35
|
+
try {
|
|
36
|
+
const status = db.prepare('SELECT * FROM agent_status WHERE id = 1').get();
|
|
37
|
+
const loaded = new Set(status ? JSON.parse(String(status.loaded_companies_json ?? '[]')) : []);
|
|
38
|
+
const latest_run = db.prepare('SELECT * FROM sync_runs WHERE company_guid = ? ORDER BY id DESC LIMIT 1');
|
|
39
|
+
const companies = db
|
|
40
|
+
.prepare('SELECT guid, name, last_seen_loaded_at, last_checked_at FROM companies ORDER BY name')
|
|
41
|
+
.all()
|
|
42
|
+
.map((row) => ({
|
|
43
|
+
guid: String(row.guid),
|
|
44
|
+
name: String(row.name),
|
|
45
|
+
loaded: loaded.has(row.name),
|
|
46
|
+
last_seen_loaded_at: String(row.last_seen_loaded_at),
|
|
47
|
+
last_checked_at: row.last_checked_at ? String(row.last_checked_at) : null,
|
|
48
|
+
last_run: latest_run.get(row.guid) ?? null,
|
|
49
|
+
}));
|
|
50
|
+
return {
|
|
51
|
+
last_pass_at: status ? String(status.last_pass_at) : null,
|
|
52
|
+
tally_reachable: status ? Boolean(status.tally_reachable) : null,
|
|
53
|
+
error: status?.error ? String(status.error) : null,
|
|
54
|
+
companies,
|
|
55
|
+
};
|
|
56
|
+
} finally {
|
|
57
|
+
db.close();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Runs shown on a company's page. */
|
|
62
|
+
export const RECENT_RUNS = 20;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A company's latest sync runs, newest first.
|
|
66
|
+
* @param {string} data_dir
|
|
67
|
+
* @param {string} company_guid
|
|
68
|
+
* @param {number} [limit]
|
|
69
|
+
* @returns {Record<string, any>[]}
|
|
70
|
+
*/
|
|
71
|
+
export function readRecentRuns(data_dir, company_guid, limit = RECENT_RUNS) {
|
|
72
|
+
const file = path.join(data_dir, 'agent.db');
|
|
73
|
+
if (!fs.existsSync(file)) return [];
|
|
74
|
+
const db = openSqlite(file, { readonly: true });
|
|
75
|
+
try {
|
|
76
|
+
return db.prepare('SELECT * FROM sync_runs WHERE company_guid = ? ORDER BY id DESC LIMIT ?').all(company_guid, limit);
|
|
77
|
+
} finally {
|
|
78
|
+
db.close();
|
|
79
|
+
}
|
|
80
|
+
}
|