@openade/pel
Version:
Punto di Elaborazione (Elaboration Point) - Server library for managing PEMs and communicating with ADE
103 lines • 3.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.OutcomePoller = void 0;
class OutcomePoller {
constructor(config) {
this.isRunning = false;
this.pendingTransmissions = new Map();
this.config = {
pollingInterval: 5 * 60 * 1000,
maxRetries: 288,
...config,
};
}
start() {
if (this.isRunning) {
console.warn('Outcome poller already running');
return;
}
console.log(`Starting outcome poller (interval: ${this.config.pollingInterval}ms)`);
this.isRunning = true;
this.poll().catch(console.error);
this.intervalId = setInterval(() => {
this.poll().catch(console.error);
}, this.config.pollingInterval);
}
stop() {
if (!this.isRunning) {
return;
}
console.log('Stopping outcome poller');
this.isRunning = false;
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
}
registerTransmission(transmission) {
const key = this.getTransmissionKey(transmission.vatNumber, transmission.emissionPointId, transmission.referenceDate);
this.pendingTransmissions.set(key, {
...transmission,
retries: 0,
});
console.log(`Registered transmission for polling: ${key}`);
}
async poll() {
if (this.pendingTransmissions.size === 0) {
return;
}
console.log(`Polling ${this.pendingTransmissions.size} pending transmissions...`);
const toRemove = [];
for (const [key, transmission] of this.pendingTransmissions.entries()) {
try {
const outcome = await this.checkOutcome(transmission);
if (outcome) {
await this.config.database.saveDailyReceiptsOutcome(outcome);
console.log(`✓ Outcome received for ${key}: ${outcome.codiceEsito} - ${outcome.descrizioneEsito}`);
toRemove.push(key);
}
else {
transmission.retries++;
if (transmission.retries >= (this.config.maxRetries || 288)) {
console.warn(`Max retries reached for ${key}, removing from poll queue`);
toRemove.push(key);
}
}
}
catch (error) {
console.error(`Error polling outcome for ${key}:`, error);
transmission.retries++;
if (transmission.retries >= (this.config.maxRetries || 288)) {
toRemove.push(key);
}
}
}
for (const key of toRemove) {
this.pendingTransmissions.delete(key);
}
if (toRemove.length > 0) {
console.log(`Removed ${toRemove.length} transmissions from poll queue`);
}
}
async checkOutcome(transmission) {
try {
const existing = await this.config.database.getDailyReceiptsOutcome(transmission.vatNumber, transmission.emissionPointId, transmission.referenceDate);
return existing;
}
catch (error) {
console.error('Error checking outcome from ADE:', error);
return null;
}
}
getTransmissionKey(vatNumber, emissionPointId, referenceDate) {
return `${vatNumber}_${emissionPointId}_${referenceDate}`;
}
getQueueSize() {
return this.pendingTransmissions.size;
}
getPendingTransmissions() {
return Array.from(this.pendingTransmissions.values());
}
}
exports.OutcomePoller = OutcomePoller;
//# sourceMappingURL=outcome.poller.js.map