@openade/pem
Version:
Punto di Emissione (Emission Point) - Device library for fiscal receipts
107 lines • 3.39 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JournalManager = void 0;
const crypto_1 = require("crypto");
class JournalManager {
constructor() {
this.entries = [];
this.currentHash = '0'.repeat(64);
this.isOpen = false;
}
openCash() {
if (this.isOpen)
throw new Error('Cash register already open');
const entry = {
type: 'AA',
timestamp: new Date().toISOString(),
data: { dataOraApertura: new Date().toISOString() },
previousHash: this.currentHash,
hash: '',
};
entry.hash = this.calculateHash(entry);
this.currentHash = entry.hash;
this.entries.push(entry);
this.isOpen = true;
return entry.hash;
}
addDocument(document) {
if (!this.isOpen)
throw new Error('Cash register not open');
const entry = {
type: 'DC',
timestamp: new Date().toISOString(),
data: document,
previousHash: this.currentHash,
hash: '',
};
entry.hash = this.calculateHash(entry);
this.currentHash = entry.hash;
this.entries.push(entry);
return entry.hash;
}
closeCash() {
if (!this.isOpen)
throw new Error('Cash register not open');
const documents = this.entries.filter((e) => e.type === 'DC');
const totalAmount = documents.reduce((sum, e) => {
const data = e.data;
return sum + (data?.importoTotale || 0);
}, 0);
const entry = {
type: 'CC',
timestamp: new Date().toISOString(),
data: {
dataOraChiusura: new Date().toISOString(),
totaleNumeroDCProdottiJournal: documents.length,
importoTotaleGiornaliero: totalAmount,
},
previousHash: this.currentHash,
hash: '',
};
entry.hash = this.calculateHash(entry);
this.currentHash = entry.hash;
this.entries.push(entry);
this.isOpen = false;
return {
hash: entry.hash,
totalDocuments: documents.length,
totalAmount,
};
}
getEntries() {
return [...this.entries];
}
verify() {
let previousHash = '0'.repeat(64);
for (const entry of this.entries) {
if (entry.previousHash !== previousHash)
return false;
const calculatedHash = this.calculateHash({
...entry,
hash: '',
});
if (calculatedHash !== entry.hash)
return false;
previousHash = entry.hash;
}
return true;
}
calculateHash(entry) {
const data = JSON.stringify({
type: entry.type,
timestamp: entry.timestamp,
data: entry.data,
previousHash: entry.previousHash,
});
return (0, crypto_1.createHash)('sha256').update(data).digest('hex');
}
exportJournal() {
return JSON.stringify({
entries: this.entries,
currentHash: this.currentHash,
verified: this.verify(),
}, null, 2);
}
}
exports.JournalManager = JournalManager;
//# sourceMappingURL=journal.manager.js.map