firt commit
This commit is contained in:
commit
c2e63830e1
71 changed files with 9613 additions and 0 deletions
293
server/controllers/adminController.js
Executable file
293
server/controllers/adminController.js
Executable file
|
@ -0,0 +1,293 @@
|
|||
import { query } from '../utils/database.js';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
// Helper to calculate timeout date
|
||||
const calculateTimeoutDate = (matchDate, timeoutMinutes) => {
|
||||
const date = new Date(matchDate);
|
||||
date.setMinutes(date.getMinutes() + timeoutMinutes);
|
||||
return date;
|
||||
};
|
||||
|
||||
// Helper to convert BigInt to Number
|
||||
const convertBigIntToNumber = (obj) => {
|
||||
if (obj === null || obj === undefined) return obj;
|
||||
if (typeof obj === 'bigint') return Number(obj);
|
||||
if (Array.isArray(obj)) return obj.map(convertBigIntToNumber);
|
||||
if (typeof obj === 'object') {
|
||||
const result = {};
|
||||
for (const key in obj) {
|
||||
result[key] = convertBigIntToNumber(obj[key]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Helper to extract seat info from filename
|
||||
const extractSeatInfoFromFilename = (filename) => {
|
||||
// Look for 3 to 5 uppercase letters, followed by an underscore, then numbers
|
||||
const regex = /^([A-Z]{3,5})_(\d+)\.pdf$/; // Updated regex to match DIRECTION_NUMBER.pdf format
|
||||
const match = filename.match(regex);
|
||||
if (match && match[1] && match[2]) {
|
||||
return {
|
||||
direction: match[1],
|
||||
extractedSeatNumber: parseInt(match[2], 10)
|
||||
};
|
||||
} else {
|
||||
return { direction: null, extractedSeatNumber: null };
|
||||
}
|
||||
};
|
||||
|
||||
export const addMatch = async (req, res) => {
|
||||
try {
|
||||
const { name, date, location, totalSeats, price, timeoutDate } = req.body;
|
||||
const uploadedFiles = req.files; // Access uploaded files via multer
|
||||
// Parse the seatInfo array sent as a JSON string(s) from the frontend
|
||||
const seatInfoArray = req.body.seatInfo ? (Array.isArray(req.body.seatInfo) ? req.body.seatInfo.map(info => JSON.parse(info)) : [JSON.parse(req.body.seatInfo)]) : [];
|
||||
|
||||
console.log('Uploaded files:', uploadedFiles); // Log uploaded files
|
||||
console.log('Received seatInfoArray:', seatInfoArray); // Log received seat info array
|
||||
|
||||
// Basic validation
|
||||
if (!name || !date || !location || !totalSeats || !timeoutDate) {
|
||||
return res.status(400).json({ message: 'Missing required fields' });
|
||||
}
|
||||
|
||||
// Ensure totalSeats is a number
|
||||
const parsedTotalSeats = parseInt(totalSeats, 10);
|
||||
const parsedPrice = parseFloat(price || 0);
|
||||
|
||||
if (isNaN(parsedTotalSeats) || parsedTotalSeats < 0 || isNaN(parsedPrice) || parsedPrice < 0) {
|
||||
return res.status(400).json({ message: 'Invalid number format for seats or price' });
|
||||
}
|
||||
|
||||
// Optional: Validate number of uploaded files vs totalSeats
|
||||
if (uploadedFiles && uploadedFiles.length > 0 && uploadedFiles.length !== parsedTotalSeats) {
|
||||
console.warn(`Number of uploaded files (${uploadedFiles.length}) does not match total seats (${parsedTotalSeats}). Seat info may not be fully populated.`);
|
||||
}
|
||||
|
||||
// Start a transaction
|
||||
await query('START TRANSACTION');
|
||||
|
||||
try {
|
||||
// Insert match
|
||||
const matchResult = await query(
|
||||
`INSERT INTO matches (
|
||||
name, date, location, totalSeats, availableSeats,
|
||||
price, timeoutDate
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
name,
|
||||
date,
|
||||
location,
|
||||
parsedTotalSeats,
|
||||
parsedTotalSeats,
|
||||
parsedPrice,
|
||||
timeoutDate
|
||||
]
|
||||
);
|
||||
|
||||
const matchId = matchResult.insertId;
|
||||
|
||||
// Create seats for the match and store extracted/manual info
|
||||
const seatValues = Array.from({ length: parsedTotalSeats }, (_, i) => {
|
||||
// Ensure we process files up to the number of uploaded files or totalSeats, whichever is smaller
|
||||
if (i >= uploadedFiles.length && i >= seatInfoArray.length) {
|
||||
return null; // No file or seat info for this seat index
|
||||
}
|
||||
|
||||
const seatNumberDefault = i + 1; // Sequential seat number as default fallback
|
||||
const file = uploadedFiles && uploadedFiles[i]; // Corresponding uploaded file
|
||||
const frontendSeatInfo = seatInfoArray[i]; // Get seat info by index (assuming order matches files)
|
||||
|
||||
console.log(`Processing seat ${i + 1}: File`, file ? file.originalname : 'No file', 'Frontend Info:', frontendSeatInfo); // Log processing details
|
||||
|
||||
let seatNumberToSave = seatNumberDefault; // Use a new variable name for the final seat number
|
||||
let uploadedPdfPath = null;
|
||||
let sourceOfDirection = null; // Keep track of where direction came from
|
||||
|
||||
// Determine seatDirection and seatNumberToSave based on available data, prioritizing frontend
|
||||
const determinedSeatInfo = (() => {
|
||||
if (frontendSeatInfo) {
|
||||
return {
|
||||
direction: frontendSeatInfo.direction,
|
||||
seatNumber: frontendSeatInfo.manualSeatNumber !== null ? frontendSeatInfo.manualSeatNumber : (frontendSeatInfo.extractedSeatNumber !== null ? frontendSeatInfo.extractedSeatNumber : seatNumberDefault),
|
||||
source: 'frontend'
|
||||
};
|
||||
} else if (file) {
|
||||
// Fallback to backend extraction if no frontend info
|
||||
const extractedInfo = extractSeatInfoFromFilename(file.originalname);
|
||||
return {
|
||||
direction: extractedInfo.direction,
|
||||
seatNumber: extractedInfo.extractedSeatNumber !== null ? extractedInfo.extractedSeatNumber : seatNumberDefault,
|
||||
source: 'backend_extraction'
|
||||
};
|
||||
} else {
|
||||
// Default if no frontend info and no file
|
||||
return {
|
||||
direction: null,
|
||||
seatNumber: seatNumberDefault,
|
||||
source: 'default'
|
||||
};
|
||||
}
|
||||
})();
|
||||
|
||||
const seatDirection = determinedSeatInfo.direction; // Assign determined direction
|
||||
seatNumberToSave = determinedSeatInfo.seatNumber; // Assign determined seat number
|
||||
sourceOfDirection = determinedSeatInfo.source; // Assign source
|
||||
|
||||
if (file) {
|
||||
// Construct the path assuming multer saves to /public/uploads
|
||||
uploadedPdfPath = `/uploads/${file.filename}`; // Use file.filename provided by multer
|
||||
}
|
||||
|
||||
// Log values after PDF path assignment, before returning for insertion
|
||||
console.log(`Seat ${i + 1} - Values after PDF path assignment: Direction = ${seatDirection}, Seat Number = ${seatNumberToSave}, PDF Path = ${uploadedPdfPath}, Source = ${sourceOfDirection}`);
|
||||
|
||||
// Log values right before returning for insertion
|
||||
console.log(`Seat ${i + 1} - Values before return for insertion: Direction = ${seatDirection}, Seat Number = ${seatNumberToSave}, PDF Path = ${uploadedPdfPath}, Source = ${sourceOfDirection}`);
|
||||
|
||||
// Return the values in the order expected by the INSERT query
|
||||
return [matchId, seatNumberToSave, seatDirection, uploadedPdfPath];
|
||||
}).filter(value => value !== null); // Filter out null values if totalSeats was higher than uploaded files/seatInfo
|
||||
|
||||
const seatPlaceholders = seatValues.map(() => '(?, ?, ?, ?)').join(', ');
|
||||
|
||||
if (seatValues.length > 0) {
|
||||
await query(
|
||||
`INSERT INTO seats (matchId, seatNumber, direction, uploadedPdfPath) VALUES ${seatPlaceholders}`,
|
||||
seatValues.flat()
|
||||
);
|
||||
} else if (parsedTotalSeats > 0 && (uploadedFiles.length === 0 || seatInfoArray.length === 0)) {
|
||||
// If totalSeats > 0 but no files uploaded or seatInfo processed, create seats with default info
|
||||
const defaultSeatValues = Array.from({ length: parsedTotalSeats }, (_, i) => [matchId, i + 1, null, null]);
|
||||
const defaultPlaceholders = defaultSeatValues.map(() => '(?, ?, ?, ?)').join(', ');
|
||||
await query(
|
||||
`INSERT INTO seats (matchId, seatNumber, direction, uploadedPdfPath) VALUES ${defaultPlaceholders}`,
|
||||
defaultSeatValues.flat()
|
||||
);
|
||||
}
|
||||
|
||||
// Commit transaction
|
||||
await query('COMMIT');
|
||||
|
||||
// Convert BigInt to Number before sending response
|
||||
const response = convertBigIntToNumber({
|
||||
message: 'Match added successfully',
|
||||
matchId: matchId
|
||||
});
|
||||
|
||||
res.status(201).json(response);
|
||||
} catch (error) {
|
||||
// Rollback transaction on error
|
||||
await query('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error adding match:', error);
|
||||
res.status(500).json({
|
||||
message: 'Failed to add match',
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getMatchSeats = async (req, res) => {
|
||||
try {
|
||||
const { matchId } = req.params;
|
||||
|
||||
const seats = await query(`
|
||||
SELECT s.*, t.name as bookedBy, t.email as bookedByEmail
|
||||
FROM seats s
|
||||
LEFT JOIN tickets t ON s.ticketId = t.id
|
||||
WHERE s.matchId = ?
|
||||
ORDER BY s.seatNumber
|
||||
`, [matchId]);
|
||||
|
||||
res.status(200).json(convertBigIntToNumber(seats));
|
||||
} catch (error) {
|
||||
console.error('Error fetching seats:', error);
|
||||
res.status(500).json({
|
||||
message: 'Failed to fetch seats',
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteMatch = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
if (!id) {
|
||||
return res.status(400).json({ message: 'Match ID is required' });
|
||||
}
|
||||
|
||||
// Start a transaction
|
||||
await query('START TRANSACTION');
|
||||
|
||||
try {
|
||||
// Get file paths of associated PDFs before deleting records
|
||||
const seatPdfs = await query('SELECT uploadedPdfPath FROM seats WHERE matchId = ? AND uploadedPdfPath IS NOT NULL', [id]);
|
||||
const ticketPdfs = await query('SELECT pdfFile FROM tickets WHERE matchId = ? AND pdfFile IS NOT NULL', [id]);
|
||||
|
||||
// Delete associated seats
|
||||
await query('DELETE FROM seats WHERE matchId = ?', [id]);
|
||||
|
||||
// Delete associated tickets
|
||||
await query('DELETE FROM tickets WHERE matchId = ?', [id]);
|
||||
|
||||
// Delete the match
|
||||
const result = await query('DELETE FROM matches WHERE id = ?', [id]);
|
||||
|
||||
// Commit transaction
|
||||
await query('COMMIT');
|
||||
|
||||
// Delete physical PDF files after successful database deletion
|
||||
const filesToDelete = [
|
||||
...seatPdfs.map(row => row.uploadedPdfPath),
|
||||
...ticketPdfs.map(row => row.pdfFile)
|
||||
];
|
||||
|
||||
const publicDir = path.join(__dirname, '..', '..' , 'public');
|
||||
|
||||
for (const filePath of filesToDelete) {
|
||||
if (filePath) {
|
||||
const absolutePath = path.join(publicDir, filePath);
|
||||
fs.unlink(absolutePath, (err) => {
|
||||
if (err) {
|
||||
console.error(`Error deleting file ${absolutePath}:`, err);
|
||||
} else {
|
||||
console.log(`Deleted file: ${absolutePath}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (result.affectedRows === 0) {
|
||||
return res.status(404).json({ message: 'Match not found' });
|
||||
}
|
||||
|
||||
res.status(200).json({ message: 'Match deleted successfully' });
|
||||
|
||||
} catch (error) {
|
||||
// Rollback transaction on error
|
||||
await query('ROLLBACK');
|
||||
console.error('Error deleting match:', error);
|
||||
res.status(500).json({
|
||||
message: 'Failed to delete match',
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error processing delete request:', error);
|
||||
res.status(500).json({ message: 'Failed to delete match', error: error.message });
|
||||
}
|
||||
};
|
||||
|
||||
// Add other admin controller functions here later (e.g., for status page)
|
63
server/controllers/authController.js
Normal file
63
server/controllers/authController.js
Normal file
|
@ -0,0 +1,63 @@
|
|||
import { query } from '../utils/database.js';
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
export const checkPassword = async (req, res) => {
|
||||
try {
|
||||
const [settings] = await query('SELECT id FROM admin_settings WHERE setting_key = ?', ['admin_password']);
|
||||
res.json({ isFirstTime: !settings });
|
||||
} catch (error) {
|
||||
console.error('Error checking password:', error);
|
||||
res.status(500).json({ message: 'Failed to check password status' });
|
||||
}
|
||||
};
|
||||
|
||||
export const setPassword = async (req, res) => {
|
||||
try {
|
||||
const { password } = req.body;
|
||||
if (!password) {
|
||||
return res.status(400).json({ message: 'Password is required' });
|
||||
}
|
||||
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
|
||||
// Check if a password already exists
|
||||
const [existingSettings] = await query('SELECT id FROM admin_settings WHERE setting_key = ?', ['admin_password']);
|
||||
|
||||
if (existingSettings) {
|
||||
// Update existing password
|
||||
await query('UPDATE admin_settings SET setting_value = ? WHERE setting_key = ?', [hashedPassword, 'admin_password']);
|
||||
} else {
|
||||
// Insert new password
|
||||
await query('INSERT INTO admin_settings (setting_key, setting_value) VALUES (?, ?)', ['admin_password', hashedPassword]);
|
||||
}
|
||||
|
||||
res.json({ message: 'Password set successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error setting password:', error);
|
||||
res.status(500).json({ message: 'Failed to set password' });
|
||||
}
|
||||
};
|
||||
|
||||
export const verifyPassword = async (req, res) => {
|
||||
try {
|
||||
const { password } = req.body;
|
||||
if (!password) {
|
||||
return res.status(400).json({ message: 'Password is required' });
|
||||
}
|
||||
|
||||
const [settings] = await query('SELECT setting_value FROM admin_settings WHERE setting_key = ?', ['admin_password']);
|
||||
if (!settings) {
|
||||
return res.status(404).json({ message: 'No password set' });
|
||||
}
|
||||
|
||||
const isValid = await bcrypt.compare(password, settings.setting_value);
|
||||
if (!isValid) {
|
||||
return res.status(401).json({ message: 'Invalid password' });
|
||||
}
|
||||
|
||||
res.json({ message: 'Password verified successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error verifying password:', error);
|
||||
res.status(500).json({ message: 'Failed to verify password' });
|
||||
}
|
||||
};
|
30
server/controllers/matchController.js
Executable file
30
server/controllers/matchController.js
Executable file
|
@ -0,0 +1,30 @@
|
|||
import { query } from '../utils/database.js';
|
||||
|
||||
export const getMatches = async (req, res) => {
|
||||
try {
|
||||
// Fetch all matches, ordered by date
|
||||
const matches = await query('SELECT id, name, date, location, totalSeats, availableSeats, price, timeoutDate FROM matches ORDER BY date');
|
||||
res.status(200).json(matches);
|
||||
} catch (error) {
|
||||
console.error('Error fetching matches:', error);
|
||||
res.status(500).json({ message: 'Failed to fetch matches', error: error.message });
|
||||
}
|
||||
};
|
||||
|
||||
export const getMatchDetails = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
// Fetch details for a specific match
|
||||
const match = await query('SELECT id, name, date, location, totalSeats, availableSeats, price, timeoutDate FROM matches WHERE id = ?', [id]);
|
||||
|
||||
if (match.length === 0) {
|
||||
return res.status(404).json({ message: 'Match not found' });
|
||||
}
|
||||
|
||||
res.status(200).json(match[0]);
|
||||
} catch (error) {
|
||||
console.error('Error fetching match details:', error);
|
||||
res.status(500).json({ message: 'Failed to fetch match details', error: error.message });
|
||||
}
|
||||
};
|
156
server/controllers/ticketController.js
Executable file
156
server/controllers/ticketController.js
Executable file
|
@ -0,0 +1,156 @@
|
|||
import { query } from '../utils/database.js';
|
||||
import { sendEmail } from '../utils/email.js';
|
||||
import { generateTicketPDF } from '../utils/pdf.js';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
export const createTicket = async (req, res) => {
|
||||
try {
|
||||
const { matchId, name, email, phone, selectedSeats, deliveryMethod } = req.body;
|
||||
|
||||
// Start transaction
|
||||
await query('START TRANSACTION');
|
||||
|
||||
try {
|
||||
// Check if seats are available
|
||||
const seats = await query(
|
||||
'SELECT * FROM seats WHERE matchId = ? AND seatNumber IN (?) AND status = "available"',
|
||||
[matchId, selectedSeats]
|
||||
);
|
||||
|
||||
if (seats.length !== selectedSeats.length) {
|
||||
throw new Error('Some selected seats are not available');
|
||||
}
|
||||
|
||||
// Create ticket
|
||||
const ticketResult = await query(
|
||||
`INSERT INTO tickets (
|
||||
matchId, name, email, phone, seats, deliveryMethod
|
||||
) VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
[matchId, name, email, phone, selectedSeats.length, deliveryMethod]
|
||||
);
|
||||
|
||||
const ticketId = ticketResult.insertId;
|
||||
|
||||
// Update seats status
|
||||
await query(
|
||||
'UPDATE seats SET status = "booked", ticketId = ? WHERE matchId = ? AND seatNumber IN (?)',
|
||||
[ticketId, matchId, selectedSeats]
|
||||
);
|
||||
|
||||
// Update match available seats
|
||||
await query(
|
||||
'UPDATE matches SET availableSeats = availableSeats - ? WHERE id = ?',
|
||||
[selectedSeats.length, matchId]
|
||||
);
|
||||
|
||||
// Generate PDF
|
||||
const pdfFileName = `${Date.now()}-${name}-${selectedSeats.length}.pdf`;
|
||||
const pdfPath = path.join(__dirname, '..', '..', 'public', 'uploads', pdfFileName);
|
||||
|
||||
const match = await query('SELECT * FROM matches WHERE id = ?', [matchId]);
|
||||
await generateTicketPDF({
|
||||
ticketId,
|
||||
match: match[0],
|
||||
name,
|
||||
email,
|
||||
phone,
|
||||
seats: seats,
|
||||
pdfFile: pdfFileName
|
||||
});
|
||||
|
||||
// Update ticket with PDF path
|
||||
await query(
|
||||
'UPDATE tickets SET pdfFile = ? WHERE id = ?',
|
||||
[`/uploads/${pdfFileName}`, ticketId]
|
||||
);
|
||||
|
||||
// Send email if requested
|
||||
if (deliveryMethod === 'email') {
|
||||
await sendEmail({
|
||||
to: email,
|
||||
subject: `Your tickets for ${match[0].name}`,
|
||||
text: `Thank you for booking tickets for ${match[0].name}. Your seat numbers are: ${selectedSeats.join(', ')}`,
|
||||
attachments: [{
|
||||
filename: pdfFileName,
|
||||
path: pdfPath
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
// Commit transaction
|
||||
await query('COMMIT');
|
||||
|
||||
res.status(201).json({
|
||||
message: 'Ticket created successfully',
|
||||
ticketId,
|
||||
pdfUrl: `/uploads/${pdfFileName}`
|
||||
});
|
||||
} catch (error) {
|
||||
// Rollback transaction on error
|
||||
await query('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creating ticket:', error);
|
||||
res.status(500).json({
|
||||
message: 'Failed to create ticket',
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getMatchSeats = async (req, res) => {
|
||||
try {
|
||||
const { matchId } = req.params;
|
||||
|
||||
const seats = await query(`
|
||||
SELECT s.*, t.name as bookedBy, t.email as bookedByEmail
|
||||
FROM seats s
|
||||
LEFT JOIN tickets t ON s.ticketId = t.id
|
||||
WHERE s.matchId = ?
|
||||
ORDER BY s.seatNumber
|
||||
`, [matchId]);
|
||||
|
||||
res.status(200).json(seats);
|
||||
} catch (error) {
|
||||
console.error('Error fetching seats:', error);
|
||||
res.status(500).json({
|
||||
message: 'Failed to fetch seats',
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getTicketStatus = async (req, res) => {
|
||||
try {
|
||||
const ticketId = req.params.ticketId || req;
|
||||
// If called as a controller (req, res), req.params.ticketId is used
|
||||
// If called as a service (just ticketId), req is the id
|
||||
const id = typeof ticketId === 'object' ? ticketId.ticketId : ticketId;
|
||||
const result = await query('SELECT * FROM tickets WHERE id = ?', [id]);
|
||||
if (!result || result.length === 0) {
|
||||
if (res) {
|
||||
return res.status(404).json({ message: 'Ticket not found' });
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (res) {
|
||||
res.json(result[0]);
|
||||
} else {
|
||||
return result[0];
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting ticket status:', error);
|
||||
if (res) {
|
||||
res.status(500).json({ message: 'Failed to get ticket status', error: error.message });
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
56
server/index.js
Executable file
56
server/index.js
Executable file
|
@ -0,0 +1,56 @@
|
|||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import initDatabase from './utils/initDatabase.js';
|
||||
import matchesRouter from './routes/matches.js';
|
||||
import ticketsRouter from './routes/tickets.js';
|
||||
import adminRouter from './routes/admin.js';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const app = express();
|
||||
const port = process.env.PORT || 3000;
|
||||
|
||||
// Create uploads directory if it doesn't exist
|
||||
const uploadsDir = path.join(__dirname, '..', 'public', 'uploads');
|
||||
if (!fs.existsSync(uploadsDir)) {
|
||||
fs.mkdirSync(uploadsDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Middleware
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// Serve static files from the uploads directory
|
||||
app.use('/uploads', express.static(path.join(__dirname, '..', 'public', 'uploads')));
|
||||
|
||||
// Routes
|
||||
app.use('/api/matches', matchesRouter);
|
||||
app.use('/api/tickets', ticketsRouter);
|
||||
app.use('/api/admin', adminRouter);
|
||||
|
||||
// Error handling middleware
|
||||
app.use((err, req, res, next) => {
|
||||
console.error('Error:', err);
|
||||
res.status(500).json({
|
||||
message: 'Something broke!',
|
||||
error: err.message,
|
||||
stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
|
||||
});
|
||||
});
|
||||
|
||||
// Initialize database and start server
|
||||
initDatabase()
|
||||
.then(() => {
|
||||
app.listen(port, () => {
|
||||
console.log(`Server running on port ${port}`);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Failed to initialize database:', error);
|
||||
process.exit(1);
|
||||
});
|
0
server/middleware/auth.js
Executable file
0
server/middleware/auth.js
Executable file
0
server/middleware/fileUpload.js
Executable file
0
server/middleware/fileUpload.js
Executable file
0
server/models/booking.js
Executable file
0
server/models/booking.js
Executable file
0
server/models/match.js
Executable file
0
server/models/match.js
Executable file
0
server/models/ticket.js
Executable file
0
server/models/ticket.js
Executable file
1798
server/package-lock.json
generated
Normal file
1798
server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
28
server/package.json
Normal file
28
server/package.json
Normal file
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"name": "handball-server",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node index.js",
|
||||
"dev": "nodemon index.js",
|
||||
"reset-db": "node utils/initDatabase.js --reset"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.18.3",
|
||||
"mariadb": "^3.2.3",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"nodemailer": "^6.10.1",
|
||||
"pdfkit": "^0.17.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/multer": "^1.4.11",
|
||||
"@types/nodemailer": "^6.4.14",
|
||||
"nodemon": "^3.1.10"
|
||||
}
|
||||
}
|
32
server/routes/admin.js
Executable file
32
server/routes/admin.js
Executable file
|
@ -0,0 +1,32 @@
|
|||
import express from 'express';
|
||||
import multer from 'multer';
|
||||
import { addMatch, deleteMatch } from '../controllers/adminController.js'; // Assuming this controller file/function
|
||||
import { checkPassword, setPassword, verifyPassword } from '../controllers/authController.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Set up multer for file uploads
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, './public/uploads/'); // Directory for uploaded files
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
cb(null, `${Date.now()}-${file.originalname}`);
|
||||
}
|
||||
});
|
||||
const upload = multer({ storage: storage });
|
||||
|
||||
// Admin authentication routes
|
||||
router.get('/check-password', checkPassword);
|
||||
router.post('/set-password', setPassword);
|
||||
router.post('/verify-password', verifyPassword);
|
||||
|
||||
// Route to add a new match
|
||||
router.post('/matches', upload.array('pdfFiles'), addMatch);
|
||||
|
||||
// Route to delete a match
|
||||
router.delete('/matches/:id', deleteMatch);
|
||||
|
||||
// Add other admin routes here later (e.g., for status page)
|
||||
|
||||
export default router;
|
12
server/routes/matches.js
Executable file
12
server/routes/matches.js
Executable file
|
@ -0,0 +1,12 @@
|
|||
import express from 'express';
|
||||
import { getMatches, getMatchDetails } from '../controllers/matchController.js'; // Assuming this controller file/functions
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Route to get all matches
|
||||
router.get('/', getMatches);
|
||||
|
||||
// Route to get details for a specific match
|
||||
router.get('/:id', getMatchDetails);
|
||||
|
||||
export default router;
|
82
server/routes/tickets.js
Executable file
82
server/routes/tickets.js
Executable file
|
@ -0,0 +1,82 @@
|
|||
import express from 'express';
|
||||
import { createTicket, getTicketStatus, getMatchSeats } from '../controllers/ticketController.js';
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Configure multer for file uploads
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
cb(null, path.join(__dirname, '../uploads'));
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
|
||||
cb(null, uniqueSuffix + path.extname(file.originalname));
|
||||
}
|
||||
});
|
||||
|
||||
const upload = multer({
|
||||
storage: storage,
|
||||
fileFilter: (req, file, cb) => {
|
||||
if (file.mimetype === 'application/pdf') {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error('Only PDF files are allowed'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Create a new ticket
|
||||
router.post('/', upload.single('pdfFile'), async (req, res) => {
|
||||
try {
|
||||
const { matchId, name, email, phone, seats, deliveryMethod } = req.body;
|
||||
const pdfFile = req.file;
|
||||
|
||||
if (!matchId || !name || !email || !phone || !seats || !deliveryMethod) {
|
||||
return res.status(400).json({ message: 'Missing required fields' });
|
||||
}
|
||||
|
||||
if (deliveryMethod === 'email' && !email) {
|
||||
return res.status(400).json({ message: 'Email is required for email delivery' });
|
||||
}
|
||||
|
||||
const ticket = await createTicket({
|
||||
matchId,
|
||||
name,
|
||||
email,
|
||||
phone,
|
||||
seats: parseInt(seats),
|
||||
pdfFile: pdfFile ? pdfFile.filename : null,
|
||||
deliveryMethod
|
||||
});
|
||||
|
||||
res.status(201).json(ticket);
|
||||
} catch (error) {
|
||||
console.error('Error creating ticket:', error);
|
||||
res.status(500).json({ message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get ticket status
|
||||
router.get('/:ticketId', async (req, res) => {
|
||||
try {
|
||||
const ticket = await getTicketStatus(req.params.ticketId);
|
||||
if (!ticket) {
|
||||
return res.status(404).json({ message: 'Ticket not found' });
|
||||
}
|
||||
res.json(ticket);
|
||||
} catch (error) {
|
||||
console.error('Error getting ticket status:', error);
|
||||
res.status(500).json({ message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get seats for a match
|
||||
router.get('/match/:matchId/seats', getMatchSeats);
|
||||
|
||||
export default router;
|
14
server/scripts/resetDb.js
Normal file
14
server/scripts/resetDb.js
Normal file
|
@ -0,0 +1,14 @@
|
|||
import initDatabase from '../utils/initDatabase.js';
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
console.log('Starting database reset...');
|
||||
await initDatabase(true);
|
||||
console.log('Database reset script finished.');
|
||||
} catch (error) {
|
||||
console.error('Database reset script failed:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
29
server/utils/database.js
Executable file
29
server/utils/database.js
Executable file
|
@ -0,0 +1,29 @@
|
|||
import mariadb from 'mariadb';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
// Create a pool without database selection first
|
||||
const initialPool = mariadb.createPool({
|
||||
host: '172.10.1.4', // Remote database host
|
||||
user: 'handball', // Remote database user
|
||||
password: 'Gabi2104@', // Remote database password
|
||||
database: 'handball', // Database name
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
export const pool = initialPool;
|
||||
|
||||
export async function query(sql, params) {
|
||||
let conn;
|
||||
try {
|
||||
conn = await pool.getConnection();
|
||||
const result = await conn.query(sql, params);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Database query error:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
if (conn) conn.release();
|
||||
}
|
||||
}
|
34
server/utils/email.js
Executable file
34
server/utils/email.js
Executable file
|
@ -0,0 +1,34 @@
|
|||
import nodemailer from 'nodemailer';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
// Create a transporter using SMTP
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: 'mail.pandem.fr',
|
||||
port: 465,
|
||||
secure: true, // SSL
|
||||
auth: {
|
||||
user: 'datacenter@nazuna.ovh',
|
||||
pass: '13,{,oCAlLaGENNiamoThFUllERpOrECriENI'
|
||||
}
|
||||
});
|
||||
|
||||
export async function sendEmail({ to, subject, text, attachments = [] }) {
|
||||
try {
|
||||
const mailOptions = {
|
||||
from: '"HandBall Ticketer" <datacenter@nazuna.ovh>',
|
||||
to,
|
||||
subject,
|
||||
text,
|
||||
attachments
|
||||
};
|
||||
|
||||
const info = await transporter.sendMail(mailOptions);
|
||||
console.log('Email sent:', info.messageId);
|
||||
return info;
|
||||
} catch (error) {
|
||||
console.error('Error sending email:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
47
server/utils/emailService.js
Normal file
47
server/utils/emailService.js
Normal file
|
@ -0,0 +1,47 @@
|
|||
import nodemailer from 'nodemailer';
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: 'mail.pandem.fr',
|
||||
port: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: 'datacenter@nazuna.ovh',
|
||||
pass: '13,{,oCAlLaGENNiamoThFUllERpOrECriENI'
|
||||
}
|
||||
});
|
||||
|
||||
export const sendTicketEmail = async (ticketData, matchData, pdfPath) => {
|
||||
try {
|
||||
const mailOptions = {
|
||||
from: '"HandBall Tickets" <datacenter@nazuna.ovh>',
|
||||
to: ticketData.customerEmail,
|
||||
subject: `Your Ticket for ${matchData.name}`,
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h2 style="color: #2563eb;">Your Handball Match Ticket</h2>
|
||||
<div style="background-color: #1f2937; color: white; padding: 20px; border-radius: 8px;">
|
||||
<h3>${matchData.name}</h3>
|
||||
<p><strong>Date:</strong> ${new Date(matchData.date).toLocaleString('fr-FR')}</p>
|
||||
<p><strong>Location:</strong> ${matchData.location}</p>
|
||||
<p><strong>Seat Number:</strong> ${ticketData.seatNumber}</p>
|
||||
<p><strong>Ticket ID:</strong> ${ticketData.id}</p>
|
||||
</div>
|
||||
<p style="margin-top: 20px;">Thank you for your purchase! Your ticket is attached to this email.</p>
|
||||
</div>
|
||||
`,
|
||||
attachments: [
|
||||
{
|
||||
filename: `ticket-${ticketData.id}.pdf`,
|
||||
path: pdfPath
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const info = await transporter.sendMail(mailOptions);
|
||||
console.log('Email sent:', info.messageId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error sending email:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
0
server/utils/fileStorage.js
Executable file
0
server/utils/fileStorage.js
Executable file
231
server/utils/initDatabase.js
Executable file
231
server/utils/initDatabase.js
Executable file
|
@ -0,0 +1,231 @@
|
|||
import mariadb from 'mariadb';
|
||||
// import dotenv from 'dotenv'; // Remove dotenv
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
// dotenv.config(); // Remove dotenv config
|
||||
|
||||
// Create a pool using hardcoded database credentials (LESS SECURE)
|
||||
const initialPool = mariadb.createPool({
|
||||
host: '172.10.1.4',
|
||||
user: 'handball',
|
||||
password: 'Gabi2104@',
|
||||
database: 'handball',
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
// Ensure required directories exist
|
||||
const ensureDirectories = () => {
|
||||
const uploadsDir = path.join(__dirname, '..', '..', 'public', 'uploads');
|
||||
const pdfDir = path.join(__dirname, '..', '..', 'public', 'pdfs');
|
||||
|
||||
// Create uploads directory if it doesn't exist
|
||||
if (!fs.existsSync(uploadsDir)) {
|
||||
fs.mkdirSync(uploadsDir, { recursive: true });
|
||||
console.log('Created uploads directory');
|
||||
}
|
||||
|
||||
// Create pdfs directory if it doesn't exist
|
||||
if (!fs.existsSync(pdfDir)) {
|
||||
fs.mkdirSync(pdfDir, { recursive: true });
|
||||
console.log('Created pdfs directory');
|
||||
}
|
||||
};
|
||||
|
||||
// Ensure .env file exists with required variables (This check is no longer strictly necessary but can be kept as a reminder)
|
||||
const ensureEnvFile = () => {
|
||||
const envPath = path.join(__dirname, '..' , '.env');
|
||||
const requiredEnvVars = [
|
||||
'DB_HOST',
|
||||
'DB_USER',
|
||||
'DB_PASSWORD',
|
||||
'DB_NAME',
|
||||
'PORT',
|
||||
'SMTP_HOST',
|
||||
'SMTP_PORT',
|
||||
'SMTP_USER',
|
||||
'SMTP_PASS'
|
||||
];
|
||||
|
||||
if (!fs.existsSync(envPath)) {
|
||||
console.warn('Warning: .env file not found. Using hardcoded credentials.'); // Change to warning
|
||||
// Do not throw error, just warn
|
||||
} else {
|
||||
const envContent = fs.readFileSync(envPath, 'utf8');
|
||||
const missingVars = requiredEnvVars.filter(varName => !envContent.includes(`${varName}=`)); // Check for key=value
|
||||
if (missingVars.length > 0) {
|
||||
console.warn('Warning: Missing required environment variables in .env:', missingVars.join(', ')); // Change to warning
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// List of all required tables and their creation SQL
|
||||
const tableDefinitions = {
|
||||
matches: `
|
||||
CREATE TABLE matches (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
date DATETIME NOT NULL,
|
||||
location VARCHAR(255) NOT NULL,
|
||||
totalSeats INT NOT NULL,
|
||||
availableSeats INT NOT NULL,
|
||||
price DECIMAL(10,2) DEFAULT 0,
|
||||
timeoutDate DATETIME NOT NULL,
|
||||
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`,
|
||||
tickets: `
|
||||
CREATE TABLE tickets (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
matchId INT NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) NOT NULL,
|
||||
phone VARCHAR(20) NOT NULL,
|
||||
seats INT NOT NULL,
|
||||
status ENUM('pending', 'confirmed', 'cancelled') DEFAULT 'pending',
|
||||
pdfFile VARCHAR(255),
|
||||
deliveryMethod ENUM('download', 'email') DEFAULT 'download',
|
||||
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_ticket_match FOREIGN KEY (matchId) REFERENCES matches(id) ON DELETE CASCADE
|
||||
) /* Added ON DELETE CASCADE */
|
||||
`,
|
||||
seats: `
|
||||
CREATE TABLE seats (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
matchId INT NOT NULL,
|
||||
seatNumber INT NOT NULL,
|
||||
status ENUM('available', 'reserved', 'booked') DEFAULT 'available',
|
||||
ticketId INT NULL,
|
||||
direction VARCHAR(50),
|
||||
extractedSeatNumber INT,
|
||||
uploadedPdfPath VARCHAR(255),
|
||||
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_seat_match FOREIGN KEY (matchId) REFERENCES matches(id) ON DELETE CASCADE, /* Added ON DELETE CASCADE */
|
||||
CONSTRAINT fk_seat_ticket FOREIGN KEY (ticketId) REFERENCES tickets(id) ON DELETE SET NULL, /* Added ON DELETE SET NULL */
|
||||
UNIQUE KEY unique_seat_match (matchId, seatNumber)
|
||||
)
|
||||
`,
|
||||
admin: `
|
||||
CREATE TABLE admin (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
passwordHash VARCHAR(255) NOT NULL,
|
||||
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
) /* No foreign keys */
|
||||
`,
|
||||
admin_settings: `
|
||||
CREATE TABLE admin_settings (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
setting_key VARCHAR(255) NOT NULL UNIQUE,
|
||||
setting_value TEXT,
|
||||
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
) /* No foreign keys */
|
||||
`
|
||||
};
|
||||
|
||||
// Check if table exists
|
||||
const tableExists = async (conn, tableName) => {
|
||||
try {
|
||||
const result = await conn.query(
|
||||
`SELECT COUNT(*) as count FROM information_schema.tables
|
||||
WHERE table_schema = ? AND table_name = ?`, // Use env var for schema
|
||||
[process.env.DB_NAME, tableName]
|
||||
);
|
||||
return result[0].count > 0;
|
||||
} catch (error) {
|
||||
console.error(`Error checking if table ${tableName} exists:`, error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Create all tables
|
||||
const createTables = async (conn) => {
|
||||
try {
|
||||
// Create tables in correct order to satisfy foreign keys
|
||||
const orderedTableNames = ['matches', 'tickets', 'seats', 'admin', 'admin_settings'];
|
||||
|
||||
for (const tableName of orderedTableNames) {
|
||||
const createSQL = tableDefinitions[tableName];
|
||||
if (!createSQL) {
|
||||
console.error(`Error: Table definition for ${tableName} not found.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Creating ${tableName} table...`);
|
||||
await conn.query(createSQL);
|
||||
console.log(`${tableName} table created successfully`);
|
||||
} catch (error) {
|
||||
// If table already exists, that's fine - just log it
|
||||
if (error.code === 'ER_TABLE_EXISTS_ERROR') {
|
||||
console.log(`${tableName} table already exists, skipping creation`);
|
||||
} else {
|
||||
// For any other error, rethrow it
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creating tables:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// Export the initialPool (Keep this export)
|
||||
export { initialPool };
|
||||
|
||||
async function initDatabase() {
|
||||
try {
|
||||
// Check required directories and files
|
||||
ensureDirectories();
|
||||
ensureEnvFile(); // Keep the check but it won't stop execution
|
||||
|
||||
console.log('Attempting to connect to database server using hardcoded credentials...'); // Updated log
|
||||
let conn;
|
||||
try {
|
||||
// Connect directly to the database using hardcoded credentials
|
||||
conn = await initialPool.getConnection();
|
||||
console.log('Connected to database server.');
|
||||
|
||||
// Check if the database exists (Keep this logic)
|
||||
const dbCheck = await conn.query(
|
||||
`SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?`,
|
||||
['handball'] // Use hardcoded DB name here
|
||||
);
|
||||
|
||||
if (dbCheck.length === 0) {
|
||||
console.log(`Database 'handball' not found. Creating...`); // Updated log
|
||||
// Create the database
|
||||
await conn.query(`CREATE DATABASE handball`); // Use hardcoded DB name here
|
||||
console.log(`Database 'handball' created.`); // Updated log
|
||||
} else {
|
||||
console.log(`Database 'handball' already exists.`); // Updated log
|
||||
}
|
||||
|
||||
// Now that the database exists, ensure the connection is using it
|
||||
// (Initial pool is already configured with hardcoded DB name)
|
||||
|
||||
console.log('Attempting to create tables (if they don\'t exist)...');
|
||||
// Create tables if they don't exist
|
||||
await createTables(conn);
|
||||
|
||||
console.log('Database initialization completed successfully');
|
||||
} catch (error) {
|
||||
console.error('Error during database initialization:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
if (conn) conn.release();
|
||||
// The pool created with hardcoded DB name is needed for the main server
|
||||
console.log('Database initialization complete, pool kept open for server using hardcoded credentials.'); // Updated log
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Startup checks failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export default initDatabase;
|
74
server/utils/pdf.js
Normal file
74
server/utils/pdf.js
Normal file
|
@ -0,0 +1,74 @@
|
|||
import PDFDocument from 'pdfkit';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
export async function generateTicketPDF({ ticketId, match, name, email, phone, seats, pdfFile }) {
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
margin: 50
|
||||
});
|
||||
|
||||
const outputPath = path.join(__dirname, '../uploads', `ticket-${ticketId}.pdf`);
|
||||
const writeStream = fs.createWriteStream(outputPath);
|
||||
doc.pipe(writeStream);
|
||||
|
||||
// Add logo if exists
|
||||
const logoPath = path.join(__dirname, '../assets/logo.png');
|
||||
if (fs.existsSync(logoPath)) {
|
||||
doc.image(logoPath, 50, 50, { width: 100 });
|
||||
}
|
||||
|
||||
// Add ticket information
|
||||
doc.fontSize(24).text('Handball Match Ticket', { align: 'center' });
|
||||
doc.moveDown();
|
||||
doc.fontSize(16).text(match.name, { align: 'center' });
|
||||
doc.moveDown();
|
||||
|
||||
// Add match details
|
||||
doc.fontSize(12);
|
||||
doc.text(`Date: ${new Date(match.date).toLocaleString()}`);
|
||||
doc.text(`Location: ${match.location}`);
|
||||
|
||||
// Add detailed seat information
|
||||
doc.text('Seats:');
|
||||
seats.forEach(seat => {
|
||||
doc.text(` - ${seat.direction || 'Seat'} ${seat.extractedSeatNumber || seat.seatNumber}`);
|
||||
});
|
||||
|
||||
doc.moveDown();
|
||||
|
||||
// Add customer details
|
||||
doc.text('Customer Information:');
|
||||
doc.text(`Name: ${name}`);
|
||||
doc.text(`Email: ${email}`);
|
||||
doc.text(`Phone: ${phone}`);
|
||||
doc.moveDown();
|
||||
|
||||
// Add ticket ID
|
||||
doc.text(`Ticket ID: ${ticketId}`);
|
||||
doc.moveDown();
|
||||
|
||||
// Add QR code or barcode if needed
|
||||
// TODO: Add QR code generation
|
||||
|
||||
// Add terms and conditions
|
||||
doc.fontSize(10);
|
||||
doc.text('Terms and Conditions:', { underline: true });
|
||||
doc.text('1. This ticket is non-refundable');
|
||||
doc.text('2. Please arrive at least 30 minutes before the match');
|
||||
doc.text('3. Present this ticket at the entrance');
|
||||
|
||||
// Finalize PDF
|
||||
doc.end();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
writeStream.on('finish', () => {
|
||||
resolve(outputPath);
|
||||
});
|
||||
writeStream.on('error', reject);
|
||||
});
|
||||
}
|
66
server/utils/pdfHandler.js
Normal file
66
server/utils/pdfHandler.js
Normal file
|
@ -0,0 +1,66 @@
|
|||
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;
|
||||
}
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue