import fs from 'node:fs/promises' import { existsSync } from 'node:fs' import path from 'node:path' import db from '../server/lib/kysely.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 db.startTransaction().execute() 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.selectFrom('supplier').selectAll().where('name', '=', supplierName).executeTakeFirst() if (!supplier) { supplier = await trx .insertInto('supplier') .values({ name: supplierName, supplierTypeId: 1 }) .returningAll() .executeTakeFirstOrThrow() } const invoice = await trx .insertInto('invoice') .values({ invoiceDate, supplierId: supplier.id, dueDate, ocr, invoiceNumber, phmNumber: parseInt(phmNumber), amount, }) .returning('id') .executeTakeFirstOrThrow() 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('COPYING: ' + filename) await fs.copyFile(path.join('invoices', 'phm', originalFilename), pathname) } else { console.info('ALREADY EXISTS: ' + filename) } const file = await trx.insertInto('file').values({ filename }).returning('id').executeTakeFirstOrThrow() await trx.insertInto('filesToInvoice').values({ fileId: file.id, invoiceId: invoice.id }).execute() } } await trx.commit().execute() db.destroy()