import fs from 'node:fs/promises' import { existsSync } from 'node:fs' import path from 'node:path' import knex from '../server/lib/knex.ts' import split from '../server/lib/split.ts' import { csvParseRows } from 'd3-dsv' const csvFilename = process.argv[2] const csvString = await fs.readFile(csvFilename, { encoding: 'utf8' }) const rows = csvParseRows(csvString) const trx = await knex.transaction() for (const row of rows.toReversed()) { const [ phmNumber, type, supplierId, supplierName, invoiceDate, dueDate, invoiceNumber, ocr, amount, vat, balance, currency, status, filesString, ] = row let supplier = await trx('supplier').first('*').where('name', supplierName) if (!supplier) { supplier = (await trx('supplier').insert({ name: supplierName, supplierTypeId: 1 }).returning('*'))[0] } const invoice = ( await trx('invoice') .insert({ invoiceDate, supplierId: supplier.id, dueDate, ocr, invoiceNumber, phmNumber, amount, }) .returning('id') )[0] const filenames = filesString.split(',').map((filename) => filename.trim()) // TODO handle names if multiple files with same extension (otherwise they will have the same name) for (const originalFilename of filenames) { const ext = path.extname(originalFilename) const filename = `${invoiceDate}_phm_${phmNumber}_${supplierName.split(/[\s/]/).join('_').split(/[']/).join('')}${ext}` const pathname = path.join('uploads', 'invoices', filename) if (!existsSync(pathname)) { console.info(filename) await fs.copyFile(path.join('invoices', 'phm', originalFilename), pathname) } const file = (await trx('file').insert({ filename }).returning('id'))[0] trx('filesToInvoice').insert({ fileId: file.id, invoiceId: invoice.id }) } } trx.commit() knex.destroy()