This commit is contained in:
seb
2026-09-24 23:26:25 +02:00
parent 075b1f0ddc
commit f8f61a1212
40 changed files with 1245 additions and 337 deletions

148
src/store/ledger/add.js Normal file
View File

@@ -0,0 +1,148 @@
import { createHash } from 'node:crypto';
import * as mssqlQueries from '../../providers/mssql/queries/ledger.js';
import * as sqliteQueries from '../../providers/sqlite3/queries/ledger.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import makeRunner from '../runner.js';
export const INIT_HASH = 'TODO_TSE_BASED_INITHASH';
export function shape(row) {
return {
id: row.id,
manifestarticle_id: row.manifestarticle_id,
transaction_type: row.transaction_type,
amount: row.amount,
transaction_text: row.transaction_text,
hash_version: row.hash_version,
prev_hash: row.prev_hash,
created_at:
row.created_at instanceof Date
? row.created_at.toISOString()
: new Date(row.created_at).toISOString(),
};
}
// Computes the SHA-512 hex hash of a previous ledger entry row
// containing all database columns in canonical JSON format.
export function computePrevHash(row) {
if (!row) {
return INIT_HASH;
}
const createdAt =
row.created_at instanceof Date
? row.created_at.toISOString()
: new Date(row.created_at).toISOString();
const payload = JSON.stringify({
id: row.id,
manifestarticle_id: row.manifestarticle_id,
transaction_type: row.transaction_type,
amount: row.amount,
transaction_text: row.transaction_text,
hash_version: row.hash_version,
prev_hash: row.prev_hash,
created_at: createdAt,
});
return createHash('sha512').update(payload, 'utf8').digest('hex');
}
/**
* Appends a new append-only entry to the ledger table.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {object} input - Ledger entry payload.
* @param {number} input.manifestarticle_id - ID of the referenced manifest line (can also pass manifestarticleId).
* @param {string} input.transaction_type - Transaction type (can also pass transactionType).
* @param {number} input.amount - Movement amount.
* @param {string} input.transaction_text - Transaction memo/details (can also pass transactionText).
* @param {object} [tx] - Optional transaction to run within.
* @returns {Promise<{id: number, manifestarticle_id: number, transaction_type: string, amount: number, transaction_text: string, hash_version: number, prev_hash: string, created_at: string}>} The created ledger row.
* @throws {Error} If user not authorized, company not selected, manifest article not found, or input invalid.
*
* @example
* const entry = await store.ledger.add(googleAuthId, {
* manifestarticle_id: 1,
* transaction_type: 'PAYMENT',
* amount: 100.5,
* transaction_text: 'Invoice paid',
* });
*/
export default function add(provider) {
const access = resolveSelectedCompanyAccess(provider);
const isSqlite = provider?.dialect === 'sqlite3';
const queries = isSqlite ? sqliteQueries : mssqlQueries;
return async (googleAuthId, input = {}, tx) => {
const rawManifestarticleId =
input.manifestarticle_id ?? input.manifestarticleId;
const rawTransactionType =
input.transaction_type ?? input.transactionType;
const rawAmount = input.amount;
const rawTransactionText =
input.transaction_text ?? input.transactionText;
const manifestarticleId = Number(rawManifestarticleId);
if (!Number.isInteger(manifestarticleId) || manifestarticleId <= 0) {
throw new Error('Invalid ledger entry');
}
const transactionType =
typeof rawTransactionType === 'string'
? rawTransactionType.trim()
: '';
if (!transactionType || transactionType.length > 100) {
throw new Error('Invalid ledger entry');
}
const amount = Number(rawAmount);
if (!Number.isFinite(amount)) {
throw new Error('Invalid ledger entry');
}
if (rawTransactionText == null) {
throw new Error('Invalid ledger entry');
}
const transactionText = String(rawTransactionText);
const doAdd = async (runner) => {
const { companyId } = await access(googleAuthId, runner);
const check = await runner.query(queries.CHECK_MANIFESTARTICLE_ACCESS, {
manifestarticleId,
companyId,
});
if (!check.rows[0]) {
throw new Error('Manifest article not found');
}
const latest = await runner.query(queries.GET_LATEST_ROW);
const prevRow = latest.rows[0];
const prevHash = computePrevHash(prevRow);
const inserted = await runner.query(queries.INSERT_ROW, {
manifestarticleId,
transactionType,
amount,
transactionText,
hashVersion: 1,
prevHash,
});
const row = inserted.rows[0];
if (!row) {
throw new Error('Failed to insert ledger entry');
}
return shape(row);
};
if (tx) {
return doAdd(makeRunner(provider, tx));
}
if (typeof provider?.transaction === 'function') {
return provider.transaction(doAdd);
}
return doAdd(makeRunner(provider));
};
}