59 lines
2.3 KiB
JavaScript
59 lines
2.3 KiB
JavaScript
// documents.js — file-store and PDF-saving helpers shared by ipc.js (desktop) and
|
|
// webserver.js (tablet/Mac web client), so both talk to the exact same document
|
|
// pipeline instead of two copies of it.
|
|
"use strict";
|
|
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
const crypto = require("crypto");
|
|
|
|
const db = require("./db");
|
|
const pdfRenderer = require("./pdf");
|
|
|
|
function filesDirFor(dataFolder, animalId) {
|
|
const dir = path.join(dataFolder, "files", animalId);
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
return dir;
|
|
}
|
|
|
|
function copyIntoStore(dataFolder, animalId, sourcePath) {
|
|
const original = path.basename(sourcePath);
|
|
const stored = `${crypto.randomUUID()}-${original}`;
|
|
const destDir = filesDirFor(dataFolder, animalId);
|
|
const destPath = path.join(destDir, stored);
|
|
fs.copyFileSync(sourcePath, destPath);
|
|
const size = fs.statSync(destPath).size;
|
|
return { original, relativePath: path.join("files", animalId, stored), size, absPath: destPath };
|
|
}
|
|
|
|
function fileToDataUri(absPath) {
|
|
try {
|
|
const buf = fs.readFileSync(absPath);
|
|
const ext = (path.extname(absPath).slice(1) || "png").replace("jpg", "jpeg");
|
|
return `data:image/${ext};base64,${buf.toString("base64")}`;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function logoDataUri() {
|
|
return fileToDataUri(path.join(__dirname, "..", "assets", "logo.png"));
|
|
}
|
|
|
|
// Renders a PDF and saves it into the animal's document store, registering it as a
|
|
// normal document row so it shows up in the Dokumente tab like any uploaded file.
|
|
async function savePdfAsDocument(dataFolder, animalId, filenamePrefix, pdfOptions) {
|
|
const buffer = await pdfRenderer.renderPdf({ logoDataUri: logoDataUri(), ...pdfOptions });
|
|
const bundle = db.getAnimalBundle(animalId);
|
|
const safeName = bundle.animal.name.replace(/[^a-z0-9äöüß]+/gi, "_");
|
|
const filename = `${filenamePrefix}_${safeName}_${new Date().toISOString().slice(0, 10)}_${Date.now()}.pdf`;
|
|
const dir = filesDirFor(dataFolder, animalId);
|
|
const absPath = path.join(dir, filename);
|
|
fs.writeFileSync(absPath, buffer);
|
|
const relativePath = path.join("files", animalId, filename);
|
|
const docId = db.addDocumentRow(animalId, "document", filename, relativePath, buffer.length);
|
|
return { docId, absPath, relativePath, filename };
|
|
}
|
|
|
|
module.exports = { filesDirFor, copyIntoStore, fileToDataUri, logoDataUri, savePdfAsDocument };
|