73 lines
2.2 KiB
TypeScript
73 lines
2.2 KiB
TypeScript
import fs from 'node:fs/promises'
|
|
import { existsSync } from 'node:fs'
|
|
import path from 'node:path'
|
|
import db from '../server/lib/kysely.ts'
|
|
|
|
const dirs = process.argv.slice(2)
|
|
|
|
// 172-972, 2020-01-08, Great Security Sverige AB.pdf'
|
|
const rFileName = /^172-(\d+),\s(\d{4,4}-\d{2,2}-\d{2,2}), (.*)\.pdf$/
|
|
|
|
for await (const dir of dirs) {
|
|
await readdir(dir)
|
|
}
|
|
|
|
db.destroy()
|
|
|
|
async function readdir(dir: string) {
|
|
const files = (await fs.readdir(dir)).toSorted((a: string, b: string) => {
|
|
const [, aNum] = a.match(rFileName) as string[]
|
|
const [, bNum] = b.match(rFileName) as string[]
|
|
|
|
if (parseInt(aNum) > parseInt(bNum)) {
|
|
return 1
|
|
} else {
|
|
return -1
|
|
}
|
|
})
|
|
|
|
const trx = await db.startTransaction().execute()
|
|
|
|
for await (const originalFilename of files) {
|
|
const result = originalFilename.match(rFileName)
|
|
|
|
if (!result) {
|
|
throw new Error(originalFilename)
|
|
}
|
|
|
|
const [, fiskenNumber, invoiceDate, supplierName] = result
|
|
|
|
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({ fiskenNumber: parseInt(fiskenNumber), invoiceDate, supplierId: supplier.id })
|
|
.returningAll()
|
|
.executeTakeFirstOrThrow()
|
|
|
|
const ext = path.extname(originalFilename)
|
|
const filename = `${invoiceDate}_fisken_${fiskenNumber}_${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(dir, 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()
|
|
}
|