From ab71989440a9249d207317ae427b1a4839d7554a Mon Sep 17 00:00:00 2001 From: consultoria-as Date: Tue, 17 Feb 2026 06:29:59 +0000 Subject: [PATCH] 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 --- src/services/watcher.js | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/services/watcher.js diff --git a/src/services/watcher.js b/src/services/watcher.js new file mode 100644 index 0000000..81cd809 --- /dev/null +++ b/src/services/watcher.js @@ -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 };