Treasury & Bank Transfer Management System — سامانه مدیریت خزانه‌داری و حواله‌های بانکی

1 import {randomUUID} from 'node:crypto';
2 import {DatabaseSync} from 'node:sqlite';
3 import {constants as fsConstants,copyFileSync,existsSync,mkdirSync,rmSync} from 'node:fs';
4 import {dirname,join,resolve} from 'node:path';
5
6 const expectedTables=['accounts','audit','beneficiaries','meta','payments'] as const;
7
8 /** Verify the entire backup, not just that SQLite can open its header. */
9 export function verifyTreasurySqliteBackup(file:string){
10 const db=new DatabaseSync(file,{readOnly:true});
11 try{
12 const result=db.prepare('PRAGMA integrity_check').all() as Array<{integrity_check:string}>;
13 if(result.length!==1||result[0].integrity_check!=='ok'){
14 throw new Error('SQLITE_BACKUP_INTEGRITY_FAILED');
15 }
16 const tables=(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all() as Array<{name:string}>)
17 .map(row=>row.name);
18 for(const name of expectedTables)if(!tables.includes(name)){
19 throw new Error('SQLITE_BACKUP_REQUIRED_TABLE_MISSING');
20 }
21 const row=db.prepare("SELECT value FROM meta WHERE key='schema_version'").get() as {value?:string}|undefined;
22 if(row?.value!=='1')throw new Error('SQLITE_BACKUP_UNSUPPORTED_SCHEMA');
23 // The desktop finance domain represents IRR as safe integer Number.
24 // SQLite can store 64-bit amounts exceeding that representable range.
25 const unsafeAmount=db.prepare('SELECT 1 AS invalid FROM payments WHERE amount_irr < 1 OR amount_irr > ? LIMIT 1')
26 .get(Number.MAX_SAFE_INTEGER);
27 if(unsafeAmount)throw new Error('SQLITE_BACKUP_FINANCIAL_AMOUNT_OUT_OF_SAFE_RANGE');
28 return {
29 schemaVersion:1,
30 accounts:Number((db.prepare('SELECT COUNT(*) AS count FROM accounts').get() as {count:number}).count),
31 beneficiaries:Number((db.prepare('SELECT COUNT(*) AS count FROM beneficiaries').get() as {count:number}).count),
32 payments:Number((db.prepare('SELECT COUNT(*) AS count FROM payments').get() as {count:number}).count),
33 audit:Number((db.prepare('SELECT COUNT(*) AS count FROM audit').get() as {count:number}).count)
34 };
35 }finally{db.close()}
36 }
37
38 /**
39 * VACUUM INTO makes a consistent SQLite snapshot, including committed WAL data.
40 * The temporary file is unique and only files created by this invocation are
41 * removed. COPYFILE_EXCL ensures an existing backup is never overwritten.
42 */
43 export function createVerifiedSqliteBackup(db:DatabaseSync,destination:string){
44 const dest=resolve(destination);
45 if(existsSync(dest))throw new Error('SQLITE_BACKUP_DESTINATION_EXISTS');
46 mkdirSync(dirname(dest),{recursive:true});
47 const temporary=join(dirname(dest),'.treasuryflow-backup-'+randomUUID()+'.sqlite');
48 let createdDestination=false;
49 try{
50 db.prepare('VACUUM main INTO ?').run(temporary);
51 const summary=verifyTreasurySqliteBackup(temporary);
52 copyFileSync(temporary,dest,fsConstants.COPYFILE_EXCL);
53 createdDestination=true;
54 const copied=verifyTreasurySqliteBackup(dest);
55 if(JSON.stringify(summary)!==JSON.stringify(copied))throw new Error('SQLITE_BACKUP_VERIFICATION_MISMATCH');
56 return copied;
57 }catch(error){
58 if(createdDestination)rmSync(dest,{force:true});
59 throw error;
60 }finally{
61 rmSync(temporary,{force:true});
62 }
63 }
64
65 /** Restore to a new location only. Never replace an existing operational DB. */
66 export function restoreVerifiedSqliteBackupToNewPath(source:string,destination:string){
67 const src=resolve(source),dest=resolve(destination);
68 if(src===dest||existsSync(dest))throw new Error('SQLITE_RESTORE_WOULD_OVERWRITE_EXISTING_DATA');
69 const expected=verifyTreasurySqliteBackup(src);
70 mkdirSync(dirname(dest),{recursive:true});
71 let created=false;
72 try{
73 copyFileSync(src,dest,fsConstants.COPYFILE_EXCL);
74 created=true;
75 const recovered=verifyTreasurySqliteBackup(dest);
76 if(JSON.stringify(expected)!==JSON.stringify(recovered))throw new Error('SQLITE_RESTORE_VERIFICATION_MISMATCH');
77 return recovered;
78 }catch(error){
79 if(created)rmSync(dest,{force:true});
80 throw error;
81 }
82 }