longevity: registraMisure, unico varco con validazione sul registro

This commit is contained in:
2026-08-21 19:27:41 +02:00
parent 370dcbda56
commit a18bb7c02f
2 changed files with 137 additions and 0 deletions
+74
View File
@@ -0,0 +1,74 @@
import type Database from 'better-sqlite3';
import { esisteTest } from './registro';
export type Fonte = 'manuale' | 'questionario' | 'wellness_tower' | 'vald' | 'calibre' | 'stress_index';
export type MisuraIn = {
test_id: string;
valore_num?: number;
valore_txt?: string;
unita?: string;
};
export function apriSessione(
db: Database.Database,
s: {
client_code: string; data: string; tipo: 'checkup' | 'questionario';
eta_alla_data?: number; operatore?: string; quest_version?: string;
}
): number {
const r = db.prepare(
`INSERT INTO sessioni (client_code, data, tipo, eta_alla_data, operatore, quest_version)
VALUES (?, ?, ?, ?, ?, ?)`
).run(s.client_code, s.data, s.tipo, s.eta_alla_data ?? null, s.operatore ?? null, s.quest_version ?? null);
return Number(r.lastInsertRowid);
}
/**
* L'unico punto in cui si scrive nella tabella `misure`.
* Un test_id sconosciuto fa fallire l'intero lotto: meglio un errore subito che una
* sessione scritta a metà. Un valore fuori dal range atteso invece si scrive e si
* marca — scartarlo perderebbe un dato vero, clamparlo lo falserebbe.
*/
export function registraMisure(
db: Database.Database,
sessioneId: number,
fonte: Fonte,
misure: MisuraIn[]
): { scritte: number; fuoriRange: string[] } {
const sess = db.prepare(`SELECT client_code FROM sessioni WHERE id = ?`).get(sessioneId) as
{ client_code: string } | undefined;
if (!sess) throw new Error(`sessione ${sessioneId} inesistente`);
for (const m of misure) {
if (!esisteTest(db, m.test_id)) {
throw new Error(`test_id non nel registro: ${m.test_id}`);
}
}
const range = db.prepare(`SELECT range_min, range_max FROM registro_test WHERE test_id = ?`);
const ins = db.prepare(
`INSERT INTO misure (sessione_id, client_code, test_id, valore_num, valore_txt, unita, fonte, fuori_range)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
);
const fuoriRange: string[] = [];
const tx = db.transaction(() => {
for (const m of misure) {
const r = range.get(m.test_id) as { range_min: number | null; range_max: number | null };
let fuori = 0;
if (m.valore_num !== undefined) {
if ((r.range_min !== null && m.valore_num < r.range_min) ||
(r.range_max !== null && m.valore_num > r.range_max)) {
fuori = 1;
fuoriRange.push(m.test_id);
}
}
ins.run(sessioneId, sess.client_code, m.test_id,
m.valore_num ?? null, m.valore_txt ?? null, m.unita ?? null, fonte, fuori);
}
});
tx();
return { scritte: misure.length, fuoriRange };
}