// Next.js API route support: https://nextjs.org/docs/api-routes/introduction export default function handler(req, res) { res.status(200).json({ name: 'John Doe' }) } export function parseBeanCount(content) { // console.log(content) const lines = content.split(/\r?\n/) var statements = [] var statement = { parts: [], type: null, _zs: 0 } // stats var stats = {} stats.time = {} stats.time.interval = [null, null] for (const [ix, line] of lines.entries()) { if (line.match(/^\s*$/)) { if (statement.type !== null) { if (statement.parts.every(({amount}) => {return amount === ''})) { throw(`missing transaction amount (:${ix+1})`) } statements.push(statement) statement = { parts: [], type: null, _zs: 0 } } } else if (statement.type === null) { try { const { date, type, payee, descr } = line.match(/(?\d{4}-\d{2}-\d{2}) (?(txn|\!|\*)) ("|')(?[\w\s\d]*)("|') ("|')(?[\w\d\s]*)("|')/).groups statement.type = type statement.date = date statement.payee = payee statement.descr = descr; const d = new Date(date) if (d && stats.time.interval[0] && stats.time.interval) { stats.time.interval = [(d < stats.time.interval[0]) ? d :stats.time.interval[0], (d > stats.time.interval[1]) ? d : stats.time.interval[1]] } else if (d) { stats.time.interval = [d, d] } } catch (error) { console.error(`could not parse an operation (line ${ix + 1})`) throw(`Could not parse beancount file (:${ix+1}, ${error}])`) } } else { const groups = line.match(/\s+(?[:\w\d]+)(\s+(?[-.\d]+)\s+(?\w+))?/).groups const amount = parseFloat(groups.amount) || null const currency = groups.currency || null console.log(amount, statement._zs) const extract = groups.amount < 0 statement.parts.push({ ...groups, amount, extract, currency }) statement._zs += amount } } stats.time.range = (stats.time.interval[1] - stats.time.interval[0]) / 1000 / 60 / 60 / 24 // now in days stats.time.interval = [stats.time.interval[0].toISOString().slice(0,10), stats.time.interval[1].toISOString().slice(0,10)] return { statements, stats } }