Add file watcher service for auto-importing XML invoices

Watches a configured folder for new .xml files using chokidar,
imports existing files on startup, and auto-imports newly added files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
consultoria-as
2026-02-17 06:29:59 +00:00
parent 364d6d591e
commit ab71989440

48
src/services/watcher.js Normal file
View File

@@ -0,0 +1,48 @@
const chokidar = require('chokidar');
const path = require('path');
const fs = require('fs');
const { importXmlFile } = require('./import-service');
function startWatcher(db, folderPath) {
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
// Import existing XMLs first
const existingFiles = fs.readdirSync(folderPath)
.filter(f => f.toLowerCase().endsWith('.xml'))
.map(f => path.join(folderPath, f));
let imported = 0;
let skipped = 0;
for (const file of existingFiles) {
const result = importXmlFile(db, file);
if (result.success) imported++;
else skipped++;
}
console.log(`Initial scan: ${imported} imported, ${skipped} skipped`);
// Watch for new files
const watcher = chokidar.watch(path.join(folderPath, '*.xml'), {
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 2000,
pollInterval: 100,
},
});
watcher.on('add', (filePath) => {
console.log(`New XML detected: ${path.basename(filePath)}`);
const result = importXmlFile(db, filePath);
if (result.success) {
console.log(` Imported: ${result.uuid}`);
} else {
console.log(` Skipped: ${result.reason}`);
}
});
return watcher;
}
module.exports = { startWatcher };