import { FastifyInstance } from "fastify"; import jwt from "jsonwebtoken"; import {insertHistoryItem} from "../utils/history"; import {buildExportZip} from "../utils/export/datev"; import {s3} from "../utils/s3"; import {GetObjectCommand, PutObjectCommand} from "@aws-sdk/client-s3" import {getSignedUrl} from "@aws-sdk/s3-request-presigner"; import dayjs from "dayjs"; import {randomUUID} from "node:crypto"; import {secrets} from "../utils/secrets"; const createExport = async (server:FastifyInstance,req:any,startDate,endDate,beraternr,mandantennr) => { console.log(startDate,endDate,beraternr,mandantennr) // 1) ZIP erzeugen const buffer = await buildExportZip(server,req.user.tenant_id, startDate, endDate, beraternr, mandantennr) console.log("ZIP created") // 2) Dateiname & Key festlegen const fileKey = `${req.user.tenant_id}/exports/Export_${dayjs(startDate).format("YYYY-MM-DD")}_${dayjs(endDate).format("YYYY-MM-DD")}_${randomUUID()}.zip` console.log(fileKey) // 3) In S3 hochladen await s3.send( new PutObjectCommand({ Bucket: secrets.S3_BUCKET, Key: fileKey, Body: buffer, ContentType: "application/zip", }) ) // 4) Presigned URL erzeugen (24h gültig) const url = await getSignedUrl( s3, new GetObjectCommand({ Bucket: secrets.S3_BUCKET, Key: fileKey, }), { expiresIn: 60 * 60 * 24 } ) console.log(url) // 5) In Supabase-DB speichern const { data, error } = await server.supabase .from("exports") .insert([ { tenant_id: req.user.tenant_id, start_date: startDate, end_date: endDate, valid_until: dayjs().add(24,"hours").toISOString(), file_path: fileKey, url: url, created_at: new Date().toISOString(), }, ]) .select() .single() console.log(data) console.log(error) } export default async function exportRoutes(server: FastifyInstance) { //Export DATEV server.post("/exports/datev", async (req, reply) => { const { start_date, end_date, beraternr, mandantennr } = req.body as { start_date: string end_date: string beraternr: string mandantennr: string } reply.send({success:true}) setImmediate(async () => { try { await createExport(server,req,start_date,end_date,beraternr,mandantennr) console.log("Job done ✅") } catch (err) { console.error("Job failed ❌", err) } }) }) //List Exports Available for Download server.get("/exports", async (req,reply) => { const {data,error} = await server.supabase.from("exports").select().eq("tenant_id",req.user.tenant_id) console.log(data,error) reply.send(data) }) }