Implemented FilesystemInvoiceReader

This commit is contained in:
dankito 2024-11-18 21:06:07 +01:00
parent af94ff2049
commit ddd6e01f1f
3 changed files with 102 additions and 0 deletions

View File

@ -0,0 +1,49 @@
package net.codinux.invoicing.filesystem
import net.codinux.invoicing.model.Invoice
import net.codinux.invoicing.reader.EInvoiceReader
import net.codinux.log.logger
import java.nio.file.Path
import kotlin.io.path.*
class FilesystemInvoiceReader(
private val eInvoiceReader: EInvoiceReader = EInvoiceReader()
) {
private val log by logger()
fun readAllInvoicesOfDirectory(directory: Path, recursive: Boolean = false) =
readInvoicesFromFiles(collectFiles(directory, recursive))
private fun collectFiles(directory: Path, recursive: Boolean): List<Path> = buildList {
directory.listDirectoryEntries().forEach { child ->
if (child.isRegularFile()) {
add(child)
} else if (recursive && child.isDirectory()) {
addAll(collectFiles(child, recursive))
}
}
}
fun readInvoicesFromFiles(vararg files: Path) =
readInvoicesFromFiles(files.toList())
fun readInvoicesFromFiles(files: List<Path>): List<InvoiceOnFilesystem> =
files.mapNotNull { file -> readInvoiceFromFile(file)?.let { InvoiceOnFilesystem(file, it) } }
fun readInvoiceFromFile(file: Path): Invoice? = try {
val extension = file.extension.lowercase()
if (extension == "pdf") {
eInvoiceReader.extractFromPdf(file.inputStream())
} else if (extension == "xml") {
eInvoiceReader.readFromXml(file.inputStream())
} else {
null
}
} catch (e: Throwable) {
log.debug(e) { "Could not extract invoices from $file" }
null
}
}

View File

@ -0,0 +1,12 @@
package net.codinux.invoicing.filesystem
import net.codinux.invoicing.model.Invoice
import java.nio.file.Path
import kotlin.io.path.name
class InvoiceOnFilesystem(
val file: Path,
val invoice: Invoice
) {
override fun toString() = "${file.name} $invoice"
}

View File

@ -0,0 +1,41 @@
package net.codinux.invoicing.filesystem
import assertk.assertThat
import assertk.assertions.hasSize
import net.codinux.invoicing.model.Invoice
import net.codinux.invoicing.test.InvoiceAsserter
import net.codinux.invoicing.test.TestUtils
import java.nio.file.Path
import kotlin.test.Test
class FilesystemInvoiceReaderTest {
private val underTest = FilesystemInvoiceReader()
@Test
fun readAllInvoicesOfDirectory() {
val testDirectory = getTestFile("XRechnung.xml").parent
val result = underTest.readAllInvoicesOfDirectory(testDirectory)
assertThat(result).hasSize(3)
}
@Test
fun readInvoiceFromFile() {
val xRechnung = getTestFile("XRechnung.xml")
val result = underTest.readInvoiceFromFile(xRechnung)
assertInvoice(result)
}
private fun getTestFile(filename: String): Path =
TestUtils.getTestFile(filename).toPath()
private fun assertInvoice(invoice: Invoice?) {
InvoiceAsserter.assertInvoice(invoice)
}
}