Spaces:
Sleeping
Sleeping
Download server.js from sarransh/voucher-pdf-api: direct link, hf CLI and curl.
- Browser
- Download file 31.2 kB
-
https://huggingface.co/spaces/sarransh/voucher-pdf-api/resolve/main/server.js
- Command line
-
hf download hf://spaces/sarransh/voucher-pdf-api/server.js
-
curl -L -o server.js https://huggingface.co/spaces/sarransh/voucher-pdf-api/resolve/main/server.js
31.2 kB
| const express = require('express'); | |
| const puppeteer = require('puppeteer'); | |
| const ejs = require('ejs'); | |
| const path = require('path'); | |
| const fs = require('fs'); | |
| const sgMail = require('@sendgrid/mail'); | |
| const bwipjs = require('bwip-js'); | |
| const pino = require('pino'); | |
| const sqlite3 = require('sqlite3').verbose(); | |
| const session = require('express-session'); | |
| const axios = require('axios'); | |
| // βββ Database Setup ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const db = new sqlite3.Database(path.join(__dirname, 'history.db')); | |
| db.serialize(() => { | |
| // Drop and recreate to sync new schema for the upgrade | |
| // db.run("DROP TABLE IF EXISTS logs"); | |
| db.run(`CREATE TABLE IF NOT EXISTS logs ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| type TEXT, | |
| method TEXT, | |
| include_fare BOOLEAN, | |
| pnr TEXT, | |
| passenger_name TEXT, | |
| ag_id TEXT, | |
| status INTEGER, | |
| payload TEXT, | |
| created_at DATETIME DEFAULT CURRENT_TIMESTAMP | |
| )`); | |
| }); | |
| const purgeOldLogs = () => { | |
| db.run("DELETE FROM logs WHERE created_at < datetime('now', '-3 days')", function(err) { | |
| if (!err && this.changes > 0) { | |
| logger.info(`[Purge] Cleaned up ${this.changes} expired log entries older than 3 days.`); | |
| } | |
| }); | |
| }; | |
| const logGenerationActivity = (type, data, status, method, includeFare, agId) => { | |
| const pnr = data.pnr_number || data.airline_pnr || (data.glx ? data.glx.pnr : ''); | |
| // Use the Agency ID passed from the route (which handles query params) | |
| const agencyId = agId || data.ag_id || (data.additional_details ? data.additional_details.agency_id : '0'); | |
| let paxName = 'N/A'; | |
| if (type === 'FLIGHT' && data.passengers && data.passengers[0]) { | |
| paxName = `${data.passengers[0].surname}/${data.passengers[0].name}`; | |
| } else if (type === 'HOTEL') { | |
| const fName = data.holder?.first_name || data.holder?.name || ''; | |
| const lName = data.holder?.last_name || ''; | |
| paxName = `${fName} ${lName}`.trim() || 'N/A'; | |
| } | |
| const stmt = db.prepare("INSERT INTO logs (type, method, include_fare, pnr, passenger_name, ag_id, status, payload) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); | |
| stmt.run(type, method, includeFare ? 1 : 0, pnr, paxName, String(agencyId), status, JSON.stringify(data)); | |
| stmt.finalize(); | |
| }; | |
| // βββ Logger Setup ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const logger = pino({ | |
| level: process.env.LOG_LEVEL || 'info', | |
| transport: process.env.NODE_ENV !== 'production' ? { | |
| target: 'pino-pretty', | |
| options: { colorize: true } | |
| } : undefined | |
| }); | |
| // βββ SendGrid Setup ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| sgMail.setApiKey('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'); | |
| // βββ From-Email mapping by ag_id ββββββββββββββββββββββββββββββββββββββββββββββ | |
| // Add/update ag_idβemail entries here as needed | |
| const AGENCY_FROM_EMAIL_MAP = { | |
| '26': 'optimusx@pnrpro.io', | |
| '8': 'donotreply@skiltravel.com', | |
| '2': 'bookings@flightsouk.com', | |
| }; | |
| const DEFAULT_FROM_EMAIL = 'optimusx@pnrpro.io'; | |
| function getFromEmail(agId) { | |
| if (!agId) return DEFAULT_FROM_EMAIL; | |
| return AGENCY_FROM_EMAIL_MAP[String(agId)] || DEFAULT_FROM_EMAIL; | |
| } | |
| // βββ Shared: Puppeteer launch options βββββββββββββββββββββββββββββββββββββββββ | |
| function getPuppeteerOptions() { | |
| const opts = { | |
| headless: 'new', | |
| args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'] | |
| }; | |
| if (process.env.PUPPETEER_EXECUTABLE_PATH) { | |
| opts.executablePath = process.env.PUPPETEER_EXECUTABLE_PATH; | |
| } | |
| return opts; | |
| } | |
| // βββ Shared: Generate PDF buffer from EJS template ββββββββββββββββββββββββββββ | |
| async function generatePdfBuffer(templateName, templateData) { | |
| const templatePath = path.join(__dirname, 'views', templateName); | |
| const html = await ejs.renderFile(templatePath, templateData); | |
| const browser = await puppeteer.launch(getPuppeteerOptions()); | |
| const page = await browser.newPage(); | |
| await page.emulateMediaType('print'); | |
| await page.setContent(html, { waitUntil: 'networkidle0' }); | |
| const pdfBuffer = await page.pdf({ | |
| format: 'A4', | |
| printBackground: true, | |
| margin: { top: '20px', right: '20px', bottom: '20px', left: '20px' } | |
| }); | |
| await browser.close(); | |
| return pdfBuffer; | |
| } | |
| const app = express(); | |
| app.use(express.json({ limit: '10mb' })); | |
| app.use(express.urlencoded({ extended: true })); | |
| app.set('view engine', 'ejs'); | |
| app.set('views', path.join(__dirname, 'views')); | |
| // Sessions for Dashboard | |
| app.use(session({ | |
| secret: 'flight-voucher-secret-key-12345', | |
| resave: false, | |
| saveUninitialized: true, | |
| cookie: { maxAge: 24 * 60 * 60 * 1000 } // 24 hours | |
| })); | |
| // Admin Credentials (Recommended to move these to ENV variables on Hugging Face) | |
| const ADMIN_USERNAME = process.env.ADMIN_USER || 'admin'; | |
| const ADMIN_PASSWORD = process.env.ADMIN_PASS || 'admin123'; | |
| async function attachHotelQRCode(data) { | |
| if (!data) return; | |
| let booking_id = data.additional_details?.booking_id || data.booking_reference || data.pnr_number || ''; | |
| let fName = data.holder?.first_name || data.holder?.name || ''; | |
| let lName = data.holder?.last_name || ''; | |
| let guest_name = `${fName} ${lName}`.trim(); | |
| let hotel_name = data.hotel?.name || ''; | |
| let checkin = data.checkin || ''; | |
| let checkout = data.checkout || ''; | |
| let pnr = data.pnr_number || data.glx?.pnr || ''; | |
| let supplier_ref = data.additional_info?.provider_confirmation_number || ''; | |
| let qrPayload = {}; | |
| if (booking_id) qrPayload.booking_id = booking_id; | |
| if (guest_name) qrPayload.guest_name = guest_name; | |
| if (hotel_name) qrPayload.hotel_name = hotel_name; | |
| if (checkin) qrPayload.checkin = checkin; | |
| if (checkout) qrPayload.checkout = checkout; | |
| if (pnr) qrPayload.pnr = pnr; | |
| if (supplier_ref) qrPayload.supplier_ref = supplier_ref; | |
| if (Object.keys(qrPayload).length === 0) return; | |
| const qrString = JSON.stringify(qrPayload); | |
| try { | |
| const pngBuffer = await bwipjs.toBuffer({ | |
| bcid: 'qrcode', | |
| text: qrString, | |
| scale: 3, | |
| height: 10, | |
| width: 10 | |
| }); | |
| if (!data.voucher_info) data.voucher_info = {}; | |
| data.voucher_info.qr_code = { | |
| type: "QR", | |
| standard: "CUSTOM", | |
| value: qrString, | |
| image_base64: `data:image/png;base64,${pngBuffer.toString('base64')}` | |
| }; | |
| } catch (err) { | |
| logger.error({ err }, "QR generation failed"); | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // HOTEL VOUCHER β GENERATE PDF | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app.post('/api/generate-voucher', async (req, res) => { | |
| try { | |
| const payload = req.body; | |
| const includeFare = req.query.includeFare === 'true' || req.body.includeFare === true; | |
| let data = payload; | |
| if (payload && payload.fetch_booking_response) { | |
| data = payload.fetch_booking_response; | |
| } | |
| if (!data || Object.keys(data).length === 0 || (!data.hotel && !data.glx)) { | |
| return res.status(400).json({ error: "Invalid payload: missing booking data" }); | |
| } | |
| await attachHotelQRCode(data); | |
| // Normalize price from rate if data.price is null | |
| if (!data.price && data.rate) { | |
| if (data.rate.price_details) { | |
| data.price = { ...data.rate.price_details }; | |
| if (!data.price.total) data.price.total = data.rate.price; | |
| } else { | |
| data.price = { total: data.rate.price, currency: data.rate.currency || 'USD' }; | |
| } | |
| } | |
| await generatePdfBuffer('voucher.ejs', { data, includeFare }).then(pdfBuffer => { | |
| logGenerationActivity('HOTEL', data, 200, 'DOWNLOAD', includeFare, req.query.ag_id); | |
| let docketNumber = data.additional_details?.docket_number || data.glx?.docket || 'Hotel'; | |
| let bookingId = data.additional_details?.booking_id || data.booking_reference || data.pnr_number || data.glx?.pnr || 'Voucher'; | |
| const filename = `${docketNumber}_${bookingId}.pdf`.replace(/[^a-zA-Z0-9_\-\.]/g, '_'); | |
| res.set({ | |
| 'Content-Type': 'application/pdf', | |
| 'Content-Length': pdfBuffer.length, | |
| 'Content-Disposition': `attachment; filename="${filename}"` | |
| }); | |
| res.send(pdfBuffer); | |
| }).catch(err => { | |
| logGenerationActivity('HOTEL', data, 500, 'DOWNLOAD', includeFare, req.query.ag_id); | |
| throw err; | |
| }); | |
| } catch (error) { | |
| logger.error({ err: error }, "Error generating PDF"); | |
| res.status(500).json({ error: "Failed to generate PDF", details: error.message }); | |
| } | |
| }); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // HOTEL VOUCHER β SEND EMAIL | |
| // POST /api/send-hotel-voucher-email?toEmail=x@y.com&includeFare=true&ag_id=26 | |
| // Body: raw booking JSON ({ fetch_booking_response: {...} }) | |
| // toEmail / includeFare / ag_id can be query params OR body fields (query takes priority) | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app.post('/api/send-hotel-voucher-email', async (req, res) => { | |
| try { | |
| const payload = req.body; | |
| // Resolve from query params first, then body fields | |
| const toEmail = req.query.toEmail || payload.toEmail; | |
| const includeFare = req.query.includeFare === 'true' || payload.includeFare === true || payload.includeFare === 'true'; | |
| const agId = req.query.ag_id || payload.ag_id || payload.agId; | |
| if (!toEmail) { | |
| return res.status(400).json({ error: "Missing required param: toEmail (pass as query param or body field)" }); | |
| } | |
| let data = payload; | |
| if (payload && payload.fetch_booking_response) { | |
| data = payload.fetch_booking_response; | |
| } | |
| if (!data || Object.keys(data).length === 0 || (!data.hotel && !data.glx)) { | |
| return res.status(400).json({ error: "Invalid payload: missing booking data" }); | |
| } | |
| await attachHotelQRCode(data); | |
| // Normalize price from rate if data.price is null | |
| if (!data.price && data.rate) { | |
| if (data.rate.price_details) { | |
| data.price = { ...data.rate.price_details }; | |
| if (!data.price.total) data.price.total = data.rate.price; | |
| } else { | |
| data.price = { total: data.rate.price, currency: data.rate.currency || 'USD' }; | |
| } | |
| } | |
| logger.info({ toEmail, includeFare, agId }, `[Hotel Email] Generating PDF`); | |
| const pdfBuffer = await generatePdfBuffer('voucher.ejs', { data, includeFare }); | |
| logGenerationActivity('HOTEL', data, 200, 'EMAIL', includeFare, agId); | |
| // Determine from-email, subject, hotel name | |
| const fromEmail = getFromEmail(agId); | |
| const hotelName = data.hotel && data.hotel.name ? data.hotel.name : 'your hotel'; | |
| const pnr = data.pnr_number || data.glx && data.glx.pnr || 'N/A'; | |
| const msg = { | |
| to: toEmail, | |
| from: { email: fromEmail, name: 'PNRPro Bookings' }, | |
| subject: `Hotel Voucher β ${hotelName} (PNR: ${pnr})`, | |
| text: `Please find your hotel voucher attached.`, | |
| html: ` | |
| <p>Dear Guest,</p> | |
| <p>Please find your <strong>Hotel Voucher</strong> for <strong>${hotelName}</strong> attached to this email.</p> | |
| <p><strong>Booking Reference:</strong> ${pnr}</p> | |
| <br/> | |
| <p>For any assistance, please reply to this email or contact your travel agent.</p> | |
| <p>Regards,<br/>PNRPro Bookings Team</p> | |
| `, | |
| attachments: [ | |
| { | |
| content: pdfBuffer.toString('base64'), | |
| filename: `Hotel-Voucher-${pnr}.pdf`, | |
| type: 'application/pdf', | |
| disposition: 'attachment', | |
| } | |
| ] | |
| }; | |
| try { | |
| await sgMail.send(msg); | |
| logger.info({ toEmail, fromEmail, pnr }, `[Hotel Email] β Sent successfully`); | |
| } catch (sendError) { | |
| if (fromEmail !== DEFAULT_FROM_EMAIL) { | |
| logger.warn({ toEmail, fromEmail, pnr, err: sendError.message }, `[Hotel Email] β οΈ Failed with current sender, trying fallback`); | |
| msg.from.email = DEFAULT_FROM_EMAIL; | |
| await sgMail.send(msg); | |
| logger.info({ toEmail, DEFAULT_FROM_EMAIL, pnr }, `[Hotel Email] β Sent successfully using fallback`); | |
| } else { | |
| throw sendError; | |
| } | |
| } | |
| logger.info({ toEmail, pnr, includeFare }, `[Hotel Email] β Sent successfully`); | |
| res.json({ | |
| success: true, | |
| message: `Hotel voucher email sent to ${toEmail}`, | |
| fromEmail, | |
| toEmail, | |
| pnr, | |
| includeFare, | |
| }); | |
| } catch (error) { | |
| logger.error({ toEmail, err: error.response ? error.response.body : error.message }, "Error sending hotel voucher email"); | |
| res.status(500).json({ | |
| error: "Failed to send hotel voucher email", | |
| details: error.response ? error.response.body : error.message | |
| }); | |
| } | |
| }); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // FLIGHT VOUCHER β BARCODE GENERATOR | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| function padString(str, length, padRight = true, padChar = ' ') { | |
| str = (str || '').toString().toUpperCase().replace(/[^A-Z0-9\s/]/g, ''); | |
| if (str.length > length) return str.substring(0, length); | |
| if (padRight) return str.padEnd(length, padChar); | |
| return str.padStart(length, padChar); | |
| } | |
| function getJulianDate(dateString) { | |
| if (!dateString) return '001'; | |
| const date = new Date(dateString); | |
| if (isNaN(date)) return '001'; | |
| const start = new Date(date.getFullYear(), 0, 0); | |
| const diff = (date - start) + ((start.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000); | |
| const oneDay = 1000 * 60 * 60 * 24; | |
| const day = Math.floor(diff / oneDay); | |
| return padString(day.toString(), 3, false, '0'); | |
| } | |
| async function attachBarcodes(data) { | |
| if (!data || !data.passengers || !Array.isArray(data.passengers)) return; | |
| const pnr_number = data.pnr_number || data.airline_pnr || ''; | |
| for (let pax of data.passengers) { | |
| if (!pax.ticket_info) pax.ticket_info = {}; | |
| let origin = ''; | |
| let destination = ''; | |
| let airline_code = ''; | |
| let flight_number = ''; | |
| let flight_date = ''; | |
| let fare_basis = ''; | |
| if (pax.ticket_info.coupon_data && pax.ticket_info.coupon_data.length > 0) { | |
| const firstCoupon = pax.ticket_info.coupon_data[0]; | |
| origin = firstCoupon.origin?.airport_code || ''; | |
| destination = firstCoupon.destination?.airport_code || ''; | |
| airline_code = firstCoupon.airline_code || ''; | |
| flight_number = firstCoupon.flight_number || ''; | |
| flight_date = firstCoupon.origin?.date || ''; | |
| fare_basis = firstCoupon.fare_basis_code || ''; | |
| } | |
| const passengerNameRaw = `${pax.surname || ''}/${pax.name || ''}`; | |
| const passengerName = padString(passengerNameRaw, 20, true, ' '); | |
| const pnr = padString(pnr_number, 7, true, ' '); | |
| const fromCode = padString(origin, 3, true, ' '); | |
| const toCode = padString(destination, 3, true, ' '); | |
| const carrier = padString(airline_code, 3, true, ' '); | |
| let fltNoNum = flight_number.replace(/[^0-9]/g, ''); | |
| fltNoNum = padString(fltNoNum, 4, false, '0'); | |
| const fltNo = padString(fltNoNum, 5, true, ' '); | |
| const julianDate = getJulianDate(flight_date); | |
| const compartment = padString(fare_basis.charAt(0) || 'Y', 1, true, ' '); | |
| // M1 + Name(20) + E + PNR(7) + From(3) + To(3) + Carrier(3) + Flt(5) + Date(3) + Class(1) + Seat(4) + Seq(5) + Status(1) + VarLen(2) | |
| const bcbpString = `M1${passengerName}E${pnr}${fromCode}${toCode}${carrier}${fltNo}${julianDate}${compartment} 0001 00`; | |
| try { | |
| const pngBuffer = await bwipjs.toBuffer({ | |
| bcid: 'pdf417', | |
| text: bcbpString, | |
| columns: 2, | |
| height: 3, | |
| }); | |
| pax.ticket_info.barcode = { | |
| type: 'PDF417', | |
| standard: 'IATA_BCBP', | |
| raw_value: bcbpString, | |
| image_base64: `data:image/png;base64,${pngBuffer.toString('base64')}` | |
| }; | |
| } catch (err) { | |
| logger.error({ err, paxName: pax.name }, "Barcode generation failed for pax"); | |
| } | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // FLIGHT VOUCHER β GENERATE PDF | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app.post('/api/generate-flight-voucher', async (req, res) => { | |
| try { | |
| const payload = req.body; | |
| const includeFare = req.query.includeFare === 'true' || req.body.includeFare === true; | |
| let data = payload; | |
| if (payload && payload.offer_data) { | |
| data = payload.offer_data; | |
| } | |
| if (!data || Object.keys(data).length === 0) { | |
| return res.status(400).json({ error: "Invalid payload: missing flight booking data" }); | |
| } | |
| await attachBarcodes(data); | |
| logger.info({ pnr: data.pnr_number || data.airline_pnr, includeFare }, `[Flight PDF] Generating PDF`); | |
| const pdfBuffer = await generatePdfBuffer('flight-voucher.ejs', { data, includeFare }); | |
| logGenerationActivity('FLIGHT', data, 200, 'DOWNLOAD', includeFare, req.query.ag_id); | |
| let docketNumber = data.additional_details?.docket_number || data.docket_number || 'Flight'; | |
| let pnrNumber = data.pnr_number || data.airline_pnr || data.booking_id || 'Ticket'; | |
| const filename = `${docketNumber}_${pnrNumber}.pdf`.replace(/[^a-zA-Z0-9_\-\.]/g, '_'); | |
| res.set({ | |
| 'Content-Type': 'application/pdf', | |
| 'Content-Length': pdfBuffer.length, | |
| 'Content-Disposition': `attachment; filename="${filename}"` | |
| }); | |
| res.send(pdfBuffer); | |
| } catch (error) { | |
| logger.error({ err: error }, "Error generating flight PDF"); | |
| res.status(500).json({ error: "Failed to generate flight PDF", details: error.message }); | |
| } | |
| }); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // FLIGHT VOUCHER β SEND EMAIL | |
| // POST /api/send-flight-voucher-email?toEmail=x@y.com&includeFare=true&ag_id=26 | |
| // Body: raw booking JSON ({ offer_data: {...} }) | |
| // toEmail / includeFare / ag_id can be query params OR body fields (query takes priority) | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app.post('/api/send-flight-voucher-email', async (req, res) => { | |
| try { | |
| const payload = req.body; | |
| // Resolve from query params first, then body fields | |
| const toEmail = req.query.toEmail || payload.toEmail; | |
| const includeFare = req.query.includeFare === 'true' || payload.includeFare === true || payload.includeFare === 'true'; | |
| const agId = req.query.ag_id || payload.ag_id || payload.agId; | |
| if (!toEmail) { | |
| return res.status(400).json({ error: "Missing required param: toEmail (pass as query param or body field)" }); | |
| } | |
| let data = payload; | |
| if (payload && payload.offer_data) { | |
| data = payload.offer_data; | |
| } | |
| if (!data || Object.keys(data).length === 0) { | |
| return res.status(400).json({ error: "Invalid payload: missing flight booking data" }); | |
| } | |
| await attachBarcodes(data); | |
| logger.info({ toEmail, pnr: data.pnr_number || data.airline_pnr, includeFare }, `[Flight Email] Generating PDF`); | |
| const pdfBuffer = await generatePdfBuffer('flight-voucher.ejs', { data, includeFare }); | |
| logGenerationActivity('FLIGHT', data, 200, 'EMAIL', includeFare, agId); | |
| // Build readable route label e.g. "BOM β NRT" | |
| let routeLabel = 'your flight'; | |
| if (data.itineraries && data.itineraries.length > 0) { | |
| const segs = data.itineraries[0].segments; | |
| if (segs && segs.length > 0) { | |
| const origin = segs[0].departure.iataCode; | |
| const dest = segs[segs.length - 1].arrival.iataCode; | |
| routeLabel = `${origin} β ${dest}`; | |
| } | |
| } | |
| const pnr = data.pnr_number || data.airline_pnr || 'N/A'; | |
| const fromEmail = getFromEmail(agId); | |
| // Build passenger list for email body | |
| let paxList = ''; | |
| if (data.passengers && data.passengers.length > 0) { | |
| paxList = data.passengers.map(p => | |
| `${p.title || ''} ${p.name || ''} ${p.surname || ''} (${p.pax_type || ''})` | |
| ).join(', '); | |
| } | |
| const msg = { | |
| to: toEmail, | |
| from: { email: fromEmail, name: 'PNRPro Bookings' }, | |
| subject: `E-Ticket: ${routeLabel} (PNR: ${pnr})`, | |
| text: `Please find your flight e-ticket attached.`, | |
| html: ` | |
| <p>Dear Traveller,</p> | |
| <p>Please find your <strong>Flight E-Ticket</strong> for <strong>${routeLabel}</strong> attached to this email.</p> | |
| <p><strong>Booking Reference (PNR):</strong> ${pnr}</p> | |
| ${paxList ? `<p><strong>Passengers:</strong> ${paxList}</p>` : ''} | |
| <br/> | |
| <p>Please carry a printout or digital copy of this e-ticket while travelling.</p> | |
| <p>For any assistance, please reply to this email or contact your travel agent.</p> | |
| <p>Regards,<br/>PNRPro Bookings Team</p> | |
| `, | |
| attachments: [ | |
| { | |
| content: pdfBuffer.toString('base64'), | |
| filename: `Flight-Voucher-${pnr}.pdf`, | |
| type: 'application/pdf', | |
| disposition: 'attachment', | |
| } | |
| ] | |
| }; | |
| try { | |
| await sgMail.send(msg); | |
| logger.info({ toEmail, fromEmail, pnr: data.pnr_number }, `[Flight Email] β Sent successfully`); | |
| } catch (sendError) { | |
| if (fromEmail !== DEFAULT_FROM_EMAIL) { | |
| logger.warn({ toEmail, fromEmail, err: sendError.message }, `[Flight Email] β οΈ Failed with current sender, trying fallback`); | |
| msg.from.email = DEFAULT_FROM_EMAIL; | |
| await sgMail.send(msg); | |
| logger.info({ toEmail, DEFAULT_FROM_EMAIL }, `[Flight Email] β Sent successfully using fallback`); | |
| } else { | |
| throw sendError; | |
| } | |
| } | |
| res.json({ | |
| success: true, | |
| message: `Flight voucher email sent to ${toEmail}`, | |
| fromEmail, | |
| toEmail, | |
| pnr, | |
| route: routeLabel, | |
| includeFare, | |
| }); | |
| } catch (error) { | |
| logger.error({ toEmail, err: error.response ? error.response.body : error.message }, "Error sending flight voucher email"); | |
| res.status(500).json({ | |
| error: "Failed to send flight voucher email", | |
| details: error.response ? error.response.body : error.message | |
| }); | |
| } | |
| }); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // DASHBOARD ROUTES | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app.get('/login', (req, res) => { | |
| res.render('login', { error: null }); | |
| }); | |
| app.post('/login', (req, res) => { | |
| const { username, password } = req.body; | |
| if (username === ADMIN_USERNAME && password === ADMIN_PASSWORD) { | |
| req.session.authenticated = true; | |
| res.redirect('/dashboard'); | |
| } else { | |
| res.render('login', { error: "Invalid username or password" }); | |
| } | |
| }); | |
| app.get('/logout', (req, res) => { | |
| req.session.destroy(); | |
| res.redirect('/login'); | |
| }); | |
| app.get('/dashboard', (req, res) => { | |
| if (!req.session.authenticated) { | |
| return res.redirect('/login'); | |
| } | |
| // Run purge whenever someone visits dashboard | |
| purgeOldLogs(); | |
| db.all("SELECT * FROM logs ORDER BY created_at DESC LIMIT 500", [], (err, rows) => { | |
| if (err) { | |
| return res.status(500).send("Database error"); | |
| } | |
| res.render('dashboard', { logs: rows }); | |
| }); | |
| }); | |
| app.get('/dashboard/view-pdf/:id', async (req, res) => { | |
| if (!req.session.authenticated) { | |
| return res.status(401).send("Unauthorized"); | |
| } | |
| const { id } = req.params; | |
| db.get("SELECT * FROM logs WHERE id = ?", [id], async (err, row) => { | |
| if (err || !row) { | |
| return res.status(404).send("Log entry not found"); | |
| } | |
| try { | |
| const data = JSON.parse(row.payload); | |
| const type = row.type; | |
| const includeFare = true; // Default to true for historical viewing | |
| let pdfBuffer; | |
| if (type === 'FLIGHT') { | |
| await attachBarcodes(data); | |
| pdfBuffer = await generatePdfBuffer('flight-voucher.ejs', { data, includeFare }); | |
| } else { | |
| await attachHotelQRCode(data); | |
| pdfBuffer = await generatePdfBuffer('voucher.ejs', { data, includeFare }); | |
| } | |
| res.set({ | |
| 'Content-Type': 'application/pdf', | |
| 'Content-Length': pdfBuffer.length, | |
| 'Content-Disposition': `inline; filename="${type}-Voucher-${row.pnr}.pdf"` | |
| }); | |
| res.send(pdfBuffer); | |
| } catch (error) { | |
| logger.error({ err: error, logId: id }, "Failed to re-generate PDF from history"); | |
| res.status(500).send("Error re-generating PDF: " + error.message); | |
| } | |
| }); | |
| }); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // βββ Keep-Alive System ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const PUBLIC_URL = process.env.PUBLIC_URL || 'https://sarransh-voucher-pdf-api.hf.space'; | |
| // Lightweight health check endpoint | |
| app.get('/health', (req, res) => { | |
| res.status(200).json({ status: 'alive' }); | |
| }); | |
| // Self-pinging function to reset Hugging Face's 48h inactivity timer | |
| const keepAlive = async () => { | |
| try { | |
| const url = `${PUBLIC_URL}/health`; | |
| await axios.get(url); | |
| logger.info(`[Keep-Alive] Successfully pinged ${url}`); | |
| } catch (error) { | |
| logger.error(`[Keep-Alive] Failed to ping: ${error.message}`); | |
| } | |
| }; | |
| // Start pinging every 20 minutes (1200000 ms) in production | |
| if (process.env.NODE_ENV === 'production') { | |
| setInterval(keepAlive, 20 * 60 * 1000); | |
| logger.info(`[Keep-Alive] Self-pinging interval started (20m) for ${PUBLIC_URL}`); | |
| } | |
| const PORT = process.env.PORT || 3000; | |
| app.listen(PORT, () => { | |
| logger.info(`Voucher Generation API listening on port ${PORT}`); | |
| logger.info(` POST /api/generate-voucher`); | |
| logger.info(` POST /api/generate-flight-voucher`); | |
| logger.info(` POST /api/send-hotel-voucher-email`); | |
| logger.info(` POST /api/send-flight-voucher-email`); | |
| logger.info(` GET /health`); | |
| }); | |