Handballbooking/server/utils/pdfHandler.js
2025-06-04 15:13:40 +02:00

66 lines
No EOL
2 KiB
JavaScript

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Function to extract seat number from filename
export const extractSeatNumber = (filename) => {
// Try to find a number in the filename
const matches = filename.match(/\d+/);
return matches ? parseInt(matches[0], 10) : null;
};
// Function to find the correct PDF for a seat number
export const findPdfForSeat = async (matchId, seatNumber) => {
try {
// Get the match's PDF files from the database
const [match] = await query('SELECT pdfFiles FROM matches WHERE id = ?', [matchId]);
if (!match || !match.pdfFiles) return null;
const pdfFiles = JSON.parse(match.pdfFiles);
// First try to find a PDF with the seat number in the filename
for (const pdfFile of pdfFiles) {
const filename = path.basename(pdfFile);
const pdfSeatNumber = extractSeatNumber(filename);
if (pdfSeatNumber === seatNumber) {
return path.join(__dirname, '..', 'uploads', pdfFile);
}
}
// If no match found, return the first PDF (admin will need to manually match)
if (pdfFiles.length > 0) {
return path.join(__dirname, '..', 'uploads', pdfFiles[0]);
}
return null;
} catch (error) {
console.error('Error finding PDF for seat:', error);
return null;
}
};
// Function to store uploaded PDFs
export const storePdf = async (file, matchId) => {
try {
const uploadDir = path.join(__dirname, '..', 'uploads', matchId);
// Create directory if it doesn't exist
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const filename = `${Date.now()}-${file.originalname}`;
const filepath = path.join(uploadDir, filename);
// Move the file to the upload directory
await fs.promises.writeFile(filepath, file.buffer);
return path.join(matchId, filename);
} catch (error) {
console.error('Error storing PDF:', error);
throw error;
}
};