worldplay-website/api/booking-sheet.js

295 lines
8.8 KiB
JavaScript

// Booking sheet integration for WORLDPLAY
// Manages bed assignments on a Google Sheets booking sheet
// Adapted from VotC booking-sheet.js for single-week event
const fs = require('fs');
let sheetsClient = null;
// Accommodation criteria mapping — maps accommodation_type to sheet matching rules
const ACCOMMODATION_CRITERIA = {
'ch-shared': {
venue: 'Commons Hub',
bedTypes: ['Bunk up', 'Bunk down', 'Single'],
},
'ch-double': {
venue: 'Commons Hub',
bedTypes: ['Double'],
},
'hh-living': {
venue: 'Herrnhof Villa',
bedTypes: ['Living room', 'Sofa bed', 'Daybed'],
},
'hh-triple': {
venue: 'Herrnhof Villa',
bedTypes: ['Triple'],
},
'hh-twin': {
venue: 'Herrnhof Villa',
bedTypes: ['Twin', 'Double (separate)'],
},
'hh-single': {
venue: 'Herrnhof Villa',
bedTypes: ['Single'],
},
'hh-couple': {
venue: 'Herrnhof Villa',
bedTypes: ['Double (shared)', 'Double', 'Couple'],
},
};
// Per-day columns for WORLDPLAY (June 7-13)
const DAY_COLUMNS = ['Jun 7', 'Jun 8', 'Jun 9', 'Jun 10', 'Jun 11', 'Jun 12', 'Jun 13'];
const DAY_ID_TO_LABEL = {
'2026-06-07': 'Jun 7', '2026-06-08': 'Jun 8', '2026-06-09': 'Jun 9',
'2026-06-10': 'Jun 10', '2026-06-11': 'Jun 11', '2026-06-12': 'Jun 12',
'2026-06-13': 'Jun 13',
};
/** Convert 0-based column index to spreadsheet letter (supports A-Z, AA-AZ) */
function colIdxToLetter(col) {
if (col < 26) return String.fromCharCode(65 + col);
return String.fromCharCode(64 + Math.floor(col / 26)) + String.fromCharCode(65 + (col % 26));
}
function getCredentials() {
const filePath = process.env.GOOGLE_SERVICE_ACCOUNT_FILE;
if (filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (err) {
console.error('[Booking Sheet] Failed to read credentials file:', err.message);
return null;
}
}
const raw = process.env.GOOGLE_SERVICE_ACCOUNT;
if (!raw) return null;
try {
return JSON.parse(raw.trim());
} catch {
console.error('[Booking Sheet] Failed to parse service account JSON');
return null;
}
}
async function getSheetsClient() {
if (sheetsClient) return sheetsClient;
const creds = getCredentials();
if (!creds) return null;
const { google } = require('googleapis');
const auth = new google.auth.GoogleAuth({
credentials: creds,
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
sheetsClient = google.sheets({ version: 'v4', auth });
return sheetsClient;
}
/**
* Read and parse the booking sheet.
* Expected structure per venue section:
* Row: "Commons Hub" or "Herrnhof Villa" (venue header)
* Row: Room | Bed Type | Week 1 (column headers)
* Row: 5 | Bunk up | (bed rows)
* ...
* Empty row (section separator)
*
* Returns array of bed objects:
* { venue, room, bedType, rowIndex, dayColumns: { 'Jun 7': colIndex, ... }, occupancy: { 'Jun 7': 'Guest Name' | null, ... } }
*/
async function parseBookingSheet() {
const sheets = await getSheetsClient();
if (!sheets) {
console.log('[Booking Sheet] No credentials configured — skipping');
return null;
}
const sheetId = process.env.BOOKING_SHEET_ID;
if (!sheetId) {
console.log('[Booking Sheet] No BOOKING_SHEET_ID configured — skipping');
return null;
}
const sheetName = process.env.BOOKING_SHEET_TAB || 'Booking Sheet';
const quotedName = `'${sheetName}'`;
const response = await sheets.spreadsheets.values.get({
spreadsheetId: sheetId,
range: `${quotedName}!A:J`,
});
const rows = response.data.values || [];
const beds = [];
let currentVenue = null;
let dayColIndexes = {};
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
if (!row || row.length === 0 || row.every(cell => !cell || !cell.toString().trim())) {
currentVenue = null;
dayColIndexes = {};
continue;
}
const firstCell = (row[0] || '').toString().trim();
// Check if this is a venue header
if (firstCell === 'Commons Hub' || firstCell === 'Herrnhof Villa') {
currentVenue = firstCell;
dayColIndexes = {};
continue;
}
// Check if this is the column header row (contains "Room" and day columns)
if (firstCell.toLowerCase() === 'room' && currentVenue) {
for (let c = 0; c < row.length; c++) {
const header = (row[c] || '').toString().trim();
if (DAY_COLUMNS.includes(header)) {
dayColIndexes[header] = c;
}
}
continue;
}
// If we have a venue and day columns, this is a bed row
if (currentVenue && Object.keys(dayColIndexes).length > 0 && firstCell) {
const room = firstCell;
const bedType = (row[1] || '').toString().trim();
if (!bedType) continue;
const occupancy = {};
for (const [day, colIdx] of Object.entries(dayColIndexes)) {
const cellValue = (row[colIdx] || '').toString().trim();
occupancy[day] = cellValue || null;
}
beds.push({
venue: currentVenue,
room,
bedType,
rowIndex: i,
dayColumns: { ...dayColIndexes },
occupancy,
});
}
}
return beds;
}
/**
* Find an available bed matching the accommodation criteria.
* A bed is "available" if ALL selected day columns are empty.
* @param {object[]} beds - parsed bed objects
* @param {string} accommodationType - e.g. 'ch-shared'
* @param {string[]} dayLabels - e.g. ['Jun 7', 'Jun 9', 'Jun 10']
*/
function findAvailableBed(beds, accommodationType, dayLabels) {
const criteria = ACCOMMODATION_CRITERIA[accommodationType];
if (!criteria) {
console.error(`[Booking Sheet] Unknown accommodation type: ${accommodationType}`);
return null;
}
for (const bed of beds) {
if (bed.venue !== criteria.venue) continue;
const bedTypeLower = bed.bedType.toLowerCase();
const matchesBedType = criteria.bedTypes.some(bt => bedTypeLower.includes(bt.toLowerCase()));
if (!matchesBedType) continue;
// Check ALL selected days are empty for this bed
const allEmpty = dayLabels.every(day => !bed.occupancy[day]);
if (allEmpty) {
return bed;
}
}
return null;
}
/**
* Assign a guest to a bed on the booking sheet.
* Writes guest name into each selected day column for the matched bed row.
*
* @param {string} guestName - Full name of the guest
* @param {string} accommodationType - e.g. 'ch-shared', 'hh-single'
* @param {string|string[]} selectedDays - 'full-week' or array of date strings like ['2026-06-07', ...]
* @returns {object} Result with success status, venue, room, bedType
*/
async function assignBooking(guestName, accommodationType, selectedDays) {
if (!accommodationType) {
return { success: false, reason: 'Missing accommodation type' };
}
// Convert selectedDays to day labels
let dayLabels;
if (selectedDays === 'full-week' || !selectedDays) {
dayLabels = [...DAY_COLUMNS]; // all 7 days
} else {
dayLabels = selectedDays.map(id => DAY_ID_TO_LABEL[id]).filter(Boolean);
if (dayLabels.length === 0) {
return { success: false, reason: 'No valid days selected' };
}
}
try {
const beds = await parseBookingSheet();
if (!beds) {
return { success: false, reason: 'Booking sheet not configured' };
}
const bed = findAvailableBed(beds, accommodationType, dayLabels);
if (!bed) {
console.warn(`[Booking Sheet] No available bed for ${accommodationType} on days: ${dayLabels.join(', ')}`);
return { success: false, reason: 'No available bed matching criteria' };
}
const sheets = await getSheetsClient();
const sheetId = process.env.BOOKING_SHEET_ID;
const sheetName = process.env.BOOKING_SHEET_TAB || 'Booking Sheet';
const quotedName = `'${sheetName}'`;
const rowNum = bed.rowIndex + 1; // Sheets is 1-indexed
// Build batch update data for each selected day column
const data = [];
for (const dayLabel of dayLabels) {
const colIdx = bed.dayColumns[dayLabel];
if (colIdx === undefined) continue;
const colLetter = colIdxToLetter(colIdx);
data.push({
range: `${quotedName}!${colLetter}${rowNum}`,
values: [[guestName]],
});
}
if (data.length === 0) {
return { success: false, reason: 'No matching day columns found on sheet' };
}
await sheets.spreadsheets.values.batchUpdate({
spreadsheetId: sheetId,
resource: {
valueInputOption: 'USER_ENTERED',
data,
},
});
console.log(`[Booking Sheet] Assigned ${guestName} to ${bed.venue} Room ${bed.room} (${bed.bedType}) for ${dayLabels.length} days`);
return {
success: true,
venue: bed.venue,
room: bed.room,
bedType: bed.bedType,
};
} catch (error) {
console.error('[Booking Sheet] Assignment failed:', error);
return { success: false, reason: error.message };
}
}
module.exports = { assignBooking, parseBookingSheet, findAvailableBed, ACCOMMODATION_CRITERIA };