Scaffold custom reports app (LXC 122 · /reports)
Framework for categorised custom reports pulling from NewBook, ResOS, SambaPOS, and internal data. Report tree with collapsible categories and subcategories; date-range params; run-audit log in reports_db. Initial reports: NewBook arrivals/departures/stayovers/bookings-by-source, ResOS covers/revenue, SambaPOS sales-summary/top-products, internal run-history. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
commit
0511ac8d82
31 changed files with 1818 additions and 0 deletions
7
backend/Dockerfile
Normal file
7
backend/Dockerfile
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
COPY package.json .
|
||||
RUN npm install --omit=dev
|
||||
COPY src ./src
|
||||
EXPOSE 3001
|
||||
CMD ["node", "src/index.js"]
|
||||
16
backend/package.json
Normal file
16
backend/package.json
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"name": "hnf-reports-backend",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"dev": "node --watch src/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^9.4.0",
|
||||
"@fastify/cors": "^9.0.1",
|
||||
"fastify": "^4.28.1",
|
||||
"jose": "^5.9.6",
|
||||
"pg": "^8.13.1"
|
||||
}
|
||||
}
|
||||
57
backend/src/auth.js
Normal file
57
backend/src/auth.js
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { jwtVerify } from 'jose'
|
||||
import { isOnsite } from './ip-check.js'
|
||||
|
||||
const APP_SLUG = process.env.APP_SLUG || 'reports'
|
||||
const secret = new TextEncoder().encode(process.env.CENTRAL_AUTH_SECRET || '')
|
||||
|
||||
export async function requireAuth(request, reply) {
|
||||
const token = request.cookies?.hnf_session
|
||||
if (!token) return reply.status(401).send({ error: 'Not authenticated' })
|
||||
|
||||
let payload
|
||||
try {
|
||||
const { payload: p } = await jwtVerify(token, secret)
|
||||
payload = p
|
||||
} catch {
|
||||
return reply.status(401).send({ error: 'Invalid session' })
|
||||
}
|
||||
|
||||
if (!payload.apps?.includes(APP_SLUG)) {
|
||||
return reply.status(403).send({ error: 'No permission for this app' })
|
||||
}
|
||||
|
||||
if (!payload.offsite_allowed) {
|
||||
const clientIP = request.headers['x-real-ip'] || request.ip
|
||||
if (!(await isOnsite(clientIP))) {
|
||||
return reply.status(403).send({ error: 'Access restricted to site network' })
|
||||
}
|
||||
}
|
||||
|
||||
const prefix = `${APP_SLUG}:`
|
||||
let caps
|
||||
if (Array.isArray(payload.caps)) {
|
||||
caps = payload.caps.filter(c => c.startsWith(prefix)).map(c => c.slice(prefix.length))
|
||||
} else {
|
||||
// Legacy token — grant view cap until re-login
|
||||
caps = ['view']
|
||||
}
|
||||
|
||||
request.user = {
|
||||
email: payload.sub,
|
||||
name: payload.name,
|
||||
is_admin: payload.is_admin ?? false,
|
||||
caps,
|
||||
}
|
||||
}
|
||||
|
||||
export function hasCap(request, cap) {
|
||||
return request.user?.is_admin === true || request.user?.caps?.includes(cap) === true
|
||||
}
|
||||
|
||||
export function requireCap(cap) {
|
||||
return async (request, reply) => {
|
||||
if (!hasCap(request, cap)) {
|
||||
return reply.status(403).send({ error: `Missing capability: ${cap}` })
|
||||
}
|
||||
}
|
||||
}
|
||||
23
backend/src/db.js
Normal file
23
backend/src/db.js
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import pg from 'pg'
|
||||
|
||||
const { Pool } = pg
|
||||
export const pool = new Pool({ connectionString: process.env.DATABASE_URL })
|
||||
|
||||
export async function initDb() {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS report_runs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
report_id TEXT NOT NULL,
|
||||
report_name TEXT NOT NULL,
|
||||
user_email TEXT NOT NULL,
|
||||
date_from DATE,
|
||||
date_to DATE,
|
||||
row_count INTEGER,
|
||||
duration_ms INTEGER,
|
||||
error TEXT,
|
||||
ran_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS report_runs_ran_at_idx ON report_runs (ran_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS report_runs_report_id_idx ON report_runs (report_id);
|
||||
`)
|
||||
}
|
||||
25
backend/src/index.js
Normal file
25
backend/src/index.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import Fastify from 'fastify'
|
||||
import cookie from '@fastify/cookie'
|
||||
import cors from '@fastify/cors'
|
||||
import { initDb } from './db.js'
|
||||
import { reportRoutes } from './routes/reports.js'
|
||||
|
||||
const app = Fastify({ logger: true, trustProxy: true })
|
||||
|
||||
await app.register(cookie)
|
||||
await app.register(cors, {
|
||||
origin: process.env.CORS_ORIGIN || false,
|
||||
credentials: true,
|
||||
})
|
||||
|
||||
app.get('/health', async () => ({ status: 'healthy' }))
|
||||
|
||||
await app.register(reportRoutes)
|
||||
|
||||
try {
|
||||
await initDb()
|
||||
await app.listen({ port: 3001, host: '0.0.0.0' })
|
||||
} catch (err) {
|
||||
app.log.error(err)
|
||||
process.exit(1)
|
||||
}
|
||||
80
backend/src/ip-check.js
Normal file
80
backend/src/ip-check.js
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import dns from 'dns/promises'
|
||||
|
||||
const raw = (process.env.OFFICE_IP_CHECK || 'disabled').trim()
|
||||
const matchers = raw.split(',').map(s => s.trim()).filter(Boolean)
|
||||
|
||||
const TTL = 5 * 60 * 1000
|
||||
const cache = new Map()
|
||||
|
||||
const PUBLIC_IP_URLS = [
|
||||
'https://api.ipify.org',
|
||||
'https://ifconfig.co/ip',
|
||||
'https://icanhazip.com',
|
||||
]
|
||||
|
||||
function normalizeIP(ip) {
|
||||
return ip?.startsWith('::ffff:') ? ip.slice(7) : ip
|
||||
}
|
||||
|
||||
function isIPv4(s) {
|
||||
return /^\d{1,3}(\.\d{1,3}){3}$/.test(s)
|
||||
}
|
||||
|
||||
function ipInCidr(ip, cidr) {
|
||||
const [range, bits] = cidr.split('/')
|
||||
if (!isIPv4(ip) || !isIPv4(range)) return false
|
||||
const mask = ~(2 ** (32 - parseInt(bits)) - 1) >>> 0
|
||||
const toInt = s => s.split('.').reduce((a, o) => (a << 8) + parseInt(o), 0) >>> 0
|
||||
return (toInt(ip) & mask) === (toInt(range) & mask)
|
||||
}
|
||||
|
||||
async function fetchPublicIP() {
|
||||
for (const url of PUBLIC_IP_URLS) {
|
||||
try {
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(() => ctrl.abort(), 4000)
|
||||
const res = await fetch(url, { signal: ctrl.signal })
|
||||
clearTimeout(timer)
|
||||
if (!res.ok) continue
|
||||
const ip = (await res.text()).trim()
|
||||
if (isIPv4(ip)) return ip
|
||||
} catch {
|
||||
// try next
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function resolveDynamic(key, resolver) {
|
||||
const hit = cache.get(key)
|
||||
if (hit && Date.now() < hit.expiry) return hit.ip
|
||||
const ip = await resolver()
|
||||
if (ip) {
|
||||
cache.set(key, { ip, expiry: Date.now() + TTL })
|
||||
return ip
|
||||
}
|
||||
return hit ? hit.ip : null
|
||||
}
|
||||
|
||||
export async function isOnsite(requestIP) {
|
||||
if (matchers.length === 0 || matchers.includes('disabled')) return true
|
||||
const ip = normalizeIP(requestIP)
|
||||
if (!ip) return false
|
||||
|
||||
for (const m of matchers) {
|
||||
if (m === 'auto') {
|
||||
const pub = await resolveDynamic('auto', fetchPublicIP)
|
||||
if (pub && ip === pub) return true
|
||||
} else if (m.includes('/')) {
|
||||
if (ipInCidr(ip, m)) return true
|
||||
} else if (/[a-zA-Z]/.test(m)) {
|
||||
const resolved = await resolveDynamic(m, async () => {
|
||||
try { return (await dns.resolve4(m))[0] } catch { return null }
|
||||
})
|
||||
if (resolved && ip === resolved) return true
|
||||
} else {
|
||||
if (ip === m) return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
50
backend/src/lib/newbook.js
Normal file
50
backend/src/lib/newbook.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
const API_BASE = 'https://api.newbook.cloud/rest/'
|
||||
|
||||
async function getCredentials() {
|
||||
const url = `${process.env.SETTINGS_URL}/settings/api/internal/integration/newbook`
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${process.env.SETTINGS_SECRET}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!res.ok) throw new Error(`Settings service returned ${res.status} fetching NewBook credentials`)
|
||||
const s = await res.json()
|
||||
return {
|
||||
username: s.username || '',
|
||||
password: s.password || '',
|
||||
apiKey: s.api_key || '',
|
||||
region: s.region || 'eu',
|
||||
}
|
||||
}
|
||||
|
||||
export async function callApi(endpoint, data = {}) {
|
||||
const creds = await getCredentials()
|
||||
if (!creds.username || !creds.password || !creds.apiKey) {
|
||||
throw new Error('NewBook API credentials not configured — set them in Settings → Integrations')
|
||||
}
|
||||
|
||||
const locationId = process.env.NEWBOOK_LOCATION_ID
|
||||
const body = { ...data, region: creds.region, api_key: creds.apiKey }
|
||||
if (locationId) body.location_id = locationId
|
||||
|
||||
const auth = Buffer.from(`${creds.username}:${creds.password}`).toString('base64')
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(() => ctrl.abort(), 30000)
|
||||
|
||||
try {
|
||||
const res = await fetch(API_BASE + endpoint, {
|
||||
method: 'POST',
|
||||
signal: ctrl.signal,
|
||||
headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${auth}` },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
clearTimeout(timer)
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '')
|
||||
throw new Error(`NewBook API ${res.status}: ${text.slice(0, 200)}`)
|
||||
}
|
||||
return await res.json()
|
||||
} catch (err) {
|
||||
clearTimeout(timer)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
21
backend/src/reports/index.js
Normal file
21
backend/src/reports/index.js
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import newbookArrivals from './newbook/arrivals.js'
|
||||
import newbookDepartures from './newbook/departures.js'
|
||||
import newbookStayovers from './newbook/stayovers.js'
|
||||
import newbookBySource from './newbook/bookings-by-source.js'
|
||||
import resoCovers from './resos/covers.js'
|
||||
import resosRevenue from './resos/revenue.js'
|
||||
import sambaSalesSummary from './samba/sales-summary.js'
|
||||
import sambaTopProducts from './samba/top-products.js'
|
||||
import internalRunHistory from './internal/run-history.js'
|
||||
|
||||
export const registry = [
|
||||
newbookArrivals,
|
||||
newbookDepartures,
|
||||
newbookStayovers,
|
||||
newbookBySource,
|
||||
resoCovers,
|
||||
resosRevenue,
|
||||
sambaSalesSummary,
|
||||
sambaTopProducts,
|
||||
internalRunHistory,
|
||||
]
|
||||
52
backend/src/reports/internal/run-history.js
Normal file
52
backend/src/reports/internal/run-history.js
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
export default {
|
||||
id: 'internal-run-history',
|
||||
name: 'Report Run History',
|
||||
category: 'internal',
|
||||
categoryLabel: 'Internal',
|
||||
subcategory: 'Audit',
|
||||
description: 'Log of all reports run within the selected date range, including who ran them and how many rows were returned.',
|
||||
|
||||
async run({ dateFrom, dateTo }, { db }) {
|
||||
const { rows } = await db.query(`
|
||||
SELECT
|
||||
ran_at,
|
||||
user_email,
|
||||
report_name,
|
||||
date_from,
|
||||
date_to,
|
||||
row_count,
|
||||
duration_ms,
|
||||
error
|
||||
FROM report_runs
|
||||
WHERE ran_at::date BETWEEN $1 AND $2
|
||||
ORDER BY ran_at DESC
|
||||
LIMIT 500
|
||||
`, [dateFrom, dateTo])
|
||||
|
||||
return {
|
||||
columns: [
|
||||
{ key: 'ran_at', label: 'Run At', type: 'datetime' },
|
||||
{ key: 'user_email', label: 'User' },
|
||||
{ key: 'report_name', label: 'Report' },
|
||||
{ key: 'date_from', label: 'From', type: 'date' },
|
||||
{ key: 'date_to', label: 'To', type: 'date' },
|
||||
{ key: 'row_count', label: 'Rows', type: 'number' },
|
||||
{ key: 'duration_ms', label: 'ms', type: 'number' },
|
||||
{ key: 'error', label: 'Error' },
|
||||
],
|
||||
rows: rows.map(r => ({
|
||||
ran_at: r.ran_at instanceof Date ? r.ran_at.toISOString().replace('T', ' ').slice(0, 19) : r.ran_at,
|
||||
user_email: r.user_email,
|
||||
report_name: r.report_name,
|
||||
date_from: r.date_from ? String(r.date_from).slice(0, 10) : '',
|
||||
date_to: r.date_to ? String(r.date_to).slice(0, 10) : '',
|
||||
row_count: r.row_count ?? '',
|
||||
duration_ms: r.duration_ms ?? '',
|
||||
error: r.error ?? '',
|
||||
})),
|
||||
summary: [
|
||||
{ label: 'Total runs', value: String(rows.length) },
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
50
backend/src/reports/newbook/arrivals.js
Normal file
50
backend/src/reports/newbook/arrivals.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
export default {
|
||||
id: 'newbook-arrivals',
|
||||
name: 'Arrivals',
|
||||
category: 'newbook',
|
||||
categoryLabel: 'NewBook',
|
||||
subcategory: 'Reservations',
|
||||
description: 'All bookings with an arrival date within the selected range, including guest name, room, rate, and booking source.',
|
||||
|
||||
async run({ dateFrom, dateTo }, { newbook }) {
|
||||
const data = await newbook.callApi('bookings_list', {
|
||||
arrival_date_from: dateFrom,
|
||||
arrival_date_to: dateTo,
|
||||
})
|
||||
|
||||
const rows = (data?.data ?? []).map(b => ({
|
||||
ref: b.booking_ref ?? b.id,
|
||||
guest: b.guest_name ?? `${b.first_name ?? ''} ${b.last_name ?? ''}`.trim(),
|
||||
arrival: b.arrival_date,
|
||||
departure: b.departure_date,
|
||||
nights: b.nights ?? b.no_nights,
|
||||
room: b.site_name ?? b.room_name ?? b.site_id,
|
||||
adults: b.adults ?? b.no_adults,
|
||||
children: b.children ?? b.no_children ?? 0,
|
||||
source: b.booking_source ?? b.channel,
|
||||
status: b.booking_status ?? b.status,
|
||||
total: b.booking_total ?? b.total_price,
|
||||
}))
|
||||
|
||||
return {
|
||||
columns: [
|
||||
{ key: 'ref', label: 'Ref' },
|
||||
{ key: 'guest', label: 'Guest' },
|
||||
{ key: 'arrival', label: 'Arrival', type: 'date' },
|
||||
{ key: 'departure', label: 'Departure', type: 'date' },
|
||||
{ key: 'nights', label: 'Nights', type: 'number' },
|
||||
{ key: 'room', label: 'Room' },
|
||||
{ key: 'adults', label: 'Adults', type: 'number' },
|
||||
{ key: 'children', label: 'Children', type: 'number' },
|
||||
{ key: 'source', label: 'Source' },
|
||||
{ key: 'status', label: 'Status' },
|
||||
{ key: 'total', label: 'Total', type: 'currency' },
|
||||
],
|
||||
rows,
|
||||
summary: [
|
||||
{ label: 'Arrivals', value: String(rows.length) },
|
||||
{ label: 'Total revenue', value: rows.reduce((s, r) => s + (parseFloat(r.total) || 0), 0).toFixed(2) },
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
56
backend/src/reports/newbook/bookings-by-source.js
Normal file
56
backend/src/reports/newbook/bookings-by-source.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
export default {
|
||||
id: 'newbook-bookings-by-source',
|
||||
name: 'Bookings by Source',
|
||||
category: 'newbook',
|
||||
categoryLabel: 'NewBook',
|
||||
subcategory: 'Revenue',
|
||||
description: 'Breakdown of bookings and revenue grouped by booking source/channel within the selected arrival date range.',
|
||||
|
||||
async run({ dateFrom, dateTo }, { newbook }) {
|
||||
const data = await newbook.callApi('bookings_list', {
|
||||
arrival_date_from: dateFrom,
|
||||
arrival_date_to: dateTo,
|
||||
})
|
||||
|
||||
const bookings = data?.data ?? []
|
||||
const grouped = {}
|
||||
|
||||
for (const b of bookings) {
|
||||
const source = b.booking_source ?? b.channel ?? 'Unknown'
|
||||
if (!grouped[source]) grouped[source] = { bookings: 0, nights: 0, revenue: 0 }
|
||||
grouped[source].bookings++
|
||||
grouped[source].nights += parseInt(b.nights ?? b.no_nights ?? 0) || 0
|
||||
grouped[source].revenue += parseFloat(b.booking_total ?? b.total_price ?? 0) || 0
|
||||
}
|
||||
|
||||
const rows = Object.entries(grouped)
|
||||
.sort((a, b) => b[1].revenue - a[1].revenue)
|
||||
.map(([source, g]) => ({
|
||||
source,
|
||||
bookings: g.bookings,
|
||||
nights: g.nights,
|
||||
revenue: g.revenue.toFixed(2),
|
||||
avg_rate: g.nights > 0 ? (g.revenue / g.nights).toFixed(2) : '0.00',
|
||||
}))
|
||||
|
||||
const totals = rows.reduce((s, r) => ({
|
||||
bookings: s.bookings + r.bookings,
|
||||
revenue: s.revenue + parseFloat(r.revenue),
|
||||
}), { bookings: 0, revenue: 0 })
|
||||
|
||||
return {
|
||||
columns: [
|
||||
{ key: 'source', label: 'Source' },
|
||||
{ key: 'bookings', label: 'Bookings', type: 'number' },
|
||||
{ key: 'nights', label: 'Nights', type: 'number' },
|
||||
{ key: 'revenue', label: 'Revenue', type: 'currency' },
|
||||
{ key: 'avg_rate', label: 'Avg Rate', type: 'currency' },
|
||||
],
|
||||
rows,
|
||||
summary: [
|
||||
{ label: 'Total bookings', value: String(totals.bookings) },
|
||||
{ label: 'Total revenue', value: totals.revenue.toFixed(2) },
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
46
backend/src/reports/newbook/departures.js
Normal file
46
backend/src/reports/newbook/departures.js
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
export default {
|
||||
id: 'newbook-departures',
|
||||
name: 'Departures',
|
||||
category: 'newbook',
|
||||
categoryLabel: 'NewBook',
|
||||
subcategory: 'Reservations',
|
||||
description: 'All bookings with a departure date within the selected range.',
|
||||
|
||||
async run({ dateFrom, dateTo }, { newbook }) {
|
||||
const data = await newbook.callApi('bookings_list', {
|
||||
departure_date_from: dateFrom,
|
||||
departure_date_to: dateTo,
|
||||
})
|
||||
|
||||
const rows = (data?.data ?? []).map(b => ({
|
||||
ref: b.booking_ref ?? b.id,
|
||||
guest: b.guest_name ?? `${b.first_name ?? ''} ${b.last_name ?? ''}`.trim(),
|
||||
arrival: b.arrival_date,
|
||||
departure: b.departure_date,
|
||||
nights: b.nights ?? b.no_nights,
|
||||
room: b.site_name ?? b.room_name ?? b.site_id,
|
||||
source: b.booking_source ?? b.channel,
|
||||
status: b.booking_status ?? b.status,
|
||||
total: b.booking_total ?? b.total_price,
|
||||
}))
|
||||
|
||||
return {
|
||||
columns: [
|
||||
{ key: 'ref', label: 'Ref' },
|
||||
{ key: 'guest', label: 'Guest' },
|
||||
{ key: 'arrival', label: 'Arrival', type: 'date' },
|
||||
{ key: 'departure', label: 'Departure', type: 'date' },
|
||||
{ key: 'nights', label: 'Nights', type: 'number' },
|
||||
{ key: 'room', label: 'Room' },
|
||||
{ key: 'source', label: 'Source' },
|
||||
{ key: 'status', label: 'Status' },
|
||||
{ key: 'total', label: 'Total', type: 'currency' },
|
||||
],
|
||||
rows,
|
||||
summary: [
|
||||
{ label: 'Departures', value: String(rows.length) },
|
||||
{ label: 'Total revenue', value: rows.reduce((s, r) => s + (parseFloat(r.total) || 0), 0).toFixed(2) },
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
43
backend/src/reports/newbook/stayovers.js
Normal file
43
backend/src/reports/newbook/stayovers.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
export default {
|
||||
id: 'newbook-stayovers',
|
||||
name: 'Stayovers',
|
||||
category: 'newbook',
|
||||
categoryLabel: 'NewBook',
|
||||
subcategory: 'Reservations',
|
||||
description: 'Bookings that are in-house (stayovers) on the selected date range — neither arriving nor departing.',
|
||||
|
||||
async run({ dateFrom, dateTo }, { newbook }) {
|
||||
const data = await newbook.callApi('bookings_list', {
|
||||
stayover_date_from: dateFrom,
|
||||
stayover_date_to: dateTo,
|
||||
})
|
||||
|
||||
const rows = (data?.data ?? []).map(b => ({
|
||||
ref: b.booking_ref ?? b.id,
|
||||
guest: b.guest_name ?? `${b.first_name ?? ''} ${b.last_name ?? ''}`.trim(),
|
||||
arrival: b.arrival_date,
|
||||
departure: b.departure_date,
|
||||
nights: b.nights ?? b.no_nights,
|
||||
room: b.site_name ?? b.room_name ?? b.site_id,
|
||||
adults: b.adults ?? b.no_adults,
|
||||
status: b.booking_status ?? b.status,
|
||||
}))
|
||||
|
||||
return {
|
||||
columns: [
|
||||
{ key: 'ref', label: 'Ref' },
|
||||
{ key: 'guest', label: 'Guest' },
|
||||
{ key: 'arrival', label: 'Arrival', type: 'date' },
|
||||
{ key: 'departure', label: 'Departure', type: 'date' },
|
||||
{ key: 'nights', label: 'Nights', type: 'number' },
|
||||
{ key: 'room', label: 'Room' },
|
||||
{ key: 'adults', label: 'Adults', type: 'number' },
|
||||
{ key: 'status', label: 'Status' },
|
||||
],
|
||||
rows,
|
||||
summary: [
|
||||
{ label: 'Stayovers', value: String(rows.length) },
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
57
backend/src/reports/resos/covers.js
Normal file
57
backend/src/reports/resos/covers.js
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
export default {
|
||||
id: 'resos-covers',
|
||||
name: 'Covers by Day',
|
||||
category: 'resos',
|
||||
categoryLabel: 'ResOS',
|
||||
subcategory: 'Bookings',
|
||||
description: 'Daily restaurant covers from ResOS within the selected date range. Requires RESOS_API_KEY environment variable.',
|
||||
|
||||
async run({ dateFrom, dateTo }, { env }) {
|
||||
const apiKey = env.RESOS_API_KEY
|
||||
if (!apiKey) throw new Error('ResOS API key not configured — set RESOS_API_KEY in the .env file')
|
||||
|
||||
const url = `https://api.resos.com/v1/bookings?date_from=${dateFrom}&date_to=${dateTo}&per_page=500`
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '')
|
||||
throw new Error(`ResOS API ${res.status}: ${text.slice(0, 200)}`)
|
||||
}
|
||||
const data = await res.json()
|
||||
const bookings = data?.data ?? data?.bookings ?? []
|
||||
|
||||
// Aggregate by date
|
||||
const byDate = {}
|
||||
for (const b of bookings) {
|
||||
const date = b.date ?? b.booking_date
|
||||
if (!date) continue
|
||||
if (!byDate[date]) byDate[date] = { covers: 0, bookings: 0, no_shows: 0 }
|
||||
byDate[date].bookings++
|
||||
byDate[date].covers += parseInt(b.covers ?? b.party_size ?? 0) || 0
|
||||
if (b.status === 'no_show' || b.no_show) byDate[date].no_shows++
|
||||
}
|
||||
|
||||
const rows = Object.entries(byDate)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([date, g]) => ({ date, bookings: g.bookings, covers: g.covers, no_shows: g.no_shows }))
|
||||
|
||||
const totalCovers = rows.reduce((s, r) => s + r.covers, 0)
|
||||
const totalBookings = rows.reduce((s, r) => s + r.bookings, 0)
|
||||
|
||||
return {
|
||||
columns: [
|
||||
{ key: 'date', label: 'Date', type: 'date' },
|
||||
{ key: 'bookings', label: 'Bookings', type: 'number' },
|
||||
{ key: 'covers', label: 'Covers', type: 'number' },
|
||||
{ key: 'no_shows', label: 'No Shows', type: 'number' },
|
||||
],
|
||||
rows,
|
||||
summary: [
|
||||
{ label: 'Total bookings', value: String(totalBookings) },
|
||||
{ label: 'Total covers', value: String(totalCovers) },
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
58
backend/src/reports/resos/revenue.js
Normal file
58
backend/src/reports/resos/revenue.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
export default {
|
||||
id: 'resos-revenue',
|
||||
name: 'Revenue by Day',
|
||||
category: 'resos',
|
||||
categoryLabel: 'ResOS',
|
||||
subcategory: 'Revenue',
|
||||
description: 'Daily restaurant revenue from ResOS within the selected date range. Requires RESOS_API_KEY environment variable.',
|
||||
|
||||
async run({ dateFrom, dateTo }, { env }) {
|
||||
const apiKey = env.RESOS_API_KEY
|
||||
if (!apiKey) throw new Error('ResOS API key not configured — set RESOS_API_KEY in the .env file')
|
||||
|
||||
const url = `https://api.resos.com/v1/bookings?date_from=${dateFrom}&date_to=${dateTo}&per_page=500`
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '')
|
||||
throw new Error(`ResOS API ${res.status}: ${text.slice(0, 200)}`)
|
||||
}
|
||||
const data = await res.json()
|
||||
const bookings = data?.data ?? data?.bookings ?? []
|
||||
|
||||
const byDate = {}
|
||||
for (const b of bookings) {
|
||||
const date = b.date ?? b.booking_date
|
||||
if (!date) continue
|
||||
if (!byDate[date]) byDate[date] = { revenue: 0, covers: 0 }
|
||||
byDate[date].revenue += parseFloat(b.total ?? b.amount ?? 0) || 0
|
||||
byDate[date].covers += parseInt(b.covers ?? b.party_size ?? 0) || 0
|
||||
}
|
||||
|
||||
const rows = Object.entries(byDate)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([date, g]) => ({
|
||||
date,
|
||||
covers: g.covers,
|
||||
revenue: g.revenue.toFixed(2),
|
||||
revenue_cover: g.covers > 0 ? (g.revenue / g.covers).toFixed(2) : '0.00',
|
||||
}))
|
||||
|
||||
const totalRevenue = rows.reduce((s, r) => s + parseFloat(r.revenue), 0)
|
||||
|
||||
return {
|
||||
columns: [
|
||||
{ key: 'date', label: 'Date', type: 'date' },
|
||||
{ key: 'covers', label: 'Covers', type: 'number' },
|
||||
{ key: 'revenue', label: 'Revenue', type: 'currency' },
|
||||
{ key: 'revenue_cover', label: 'Rev/Cover', type: 'currency' },
|
||||
],
|
||||
rows,
|
||||
summary: [
|
||||
{ label: 'Total revenue', value: totalRevenue.toFixed(2) },
|
||||
],
|
||||
}
|
||||
},
|
||||
}
|
||||
57
backend/src/reports/samba/sales-summary.js
Normal file
57
backend/src/reports/samba/sales-summary.js
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
export default {
|
||||
id: 'samba-sales-summary',
|
||||
name: 'Sales Summary',
|
||||
category: 'samba',
|
||||
categoryLabel: 'SambaPOS',
|
||||
subcategory: 'Sales',
|
||||
description: 'Daily sales totals from SambaPOS within the selected date range. Requires SAMBA_DATABASE_URL environment variable.',
|
||||
|
||||
async run({ dateFrom, dateTo }, { env }) {
|
||||
const connStr = env.SAMBA_DATABASE_URL
|
||||
if (!connStr) throw new Error('SambaPOS database not configured — set SAMBA_DATABASE_URL in the .env file')
|
||||
|
||||
// Dynamic import to avoid pg pool creation if not needed
|
||||
const { Pool } = (await import('pg')).default
|
||||
const sambaPool = new Pool({ connectionString: connStr, max: 2 })
|
||||
|
||||
try {
|
||||
const { rows } = await sambaPool.query(`
|
||||
SELECT
|
||||
CAST(Date AS DATE) AS sale_date,
|
||||
COUNT(*) AS ticket_count,
|
||||
SUM(TotalAmount) AS gross_total,
|
||||
SUM(DiscountAmount) AS discount_total,
|
||||
SUM(TotalAmount - DiscountAmount) AS net_total
|
||||
FROM Tickets
|
||||
WHERE CAST(Date AS DATE) BETWEEN $1 AND $2
|
||||
AND IsCancelled = 0
|
||||
GROUP BY CAST(Date AS DATE)
|
||||
ORDER BY CAST(Date AS DATE)
|
||||
`, [dateFrom, dateTo])
|
||||
|
||||
const totalNet = rows.reduce((s, r) => s + parseFloat(r.net_total ?? 0), 0)
|
||||
|
||||
return {
|
||||
columns: [
|
||||
{ key: 'sale_date', label: 'Date', type: 'date' },
|
||||
{ key: 'ticket_count', label: 'Tickets', type: 'number' },
|
||||
{ key: 'gross_total', label: 'Gross', type: 'currency' },
|
||||
{ key: 'discount_total',label: 'Discounts', type: 'currency' },
|
||||
{ key: 'net_total', label: 'Net Total', type: 'currency' },
|
||||
],
|
||||
rows: rows.map(r => ({
|
||||
sale_date: r.sale_date instanceof Date ? r.sale_date.toISOString().split('T')[0] : r.sale_date,
|
||||
ticket_count: r.ticket_count,
|
||||
gross_total: parseFloat(r.gross_total ?? 0).toFixed(2),
|
||||
discount_total: parseFloat(r.discount_total ?? 0).toFixed(2),
|
||||
net_total: parseFloat(r.net_total ?? 0).toFixed(2),
|
||||
})),
|
||||
summary: [
|
||||
{ label: 'Total net', value: totalNet.toFixed(2) },
|
||||
],
|
||||
}
|
||||
} finally {
|
||||
await sambaPool.end()
|
||||
}
|
||||
},
|
||||
}
|
||||
54
backend/src/reports/samba/top-products.js
Normal file
54
backend/src/reports/samba/top-products.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
export default {
|
||||
id: 'samba-top-products',
|
||||
name: 'Top Products',
|
||||
category: 'samba',
|
||||
categoryLabel: 'SambaPOS',
|
||||
subcategory: 'Products',
|
||||
description: 'Best-selling products from SambaPOS ranked by quantity sold within the selected date range. Requires SAMBA_DATABASE_URL environment variable.',
|
||||
|
||||
async run({ dateFrom, dateTo }, { env }) {
|
||||
const connStr = env.SAMBA_DATABASE_URL
|
||||
if (!connStr) throw new Error('SambaPOS database not configured — set SAMBA_DATABASE_URL in the .env file')
|
||||
|
||||
const { Pool } = (await import('pg')).default
|
||||
const sambaPool = new Pool({ connectionString: connStr, max: 2 })
|
||||
|
||||
try {
|
||||
const { rows } = await sambaPool.query(`
|
||||
SELECT
|
||||
ti.MenuItemName AS product_name,
|
||||
COUNT(*) AS orders,
|
||||
SUM(ti.Quantity) AS qty_sold,
|
||||
SUM(ti.Price * ti.Quantity) AS gross_total
|
||||
FROM TicketItems ti
|
||||
JOIN Tickets t ON t.Id = ti.TicketId
|
||||
WHERE CAST(t.Date AS DATE) BETWEEN $1 AND $2
|
||||
AND t.IsCancelled = 0
|
||||
AND ti.IsVoided = 0
|
||||
GROUP BY ti.MenuItemName
|
||||
ORDER BY qty_sold DESC
|
||||
LIMIT 50
|
||||
`, [dateFrom, dateTo])
|
||||
|
||||
return {
|
||||
columns: [
|
||||
{ key: 'product_name', label: 'Product' },
|
||||
{ key: 'orders', label: 'Orders', type: 'number' },
|
||||
{ key: 'qty_sold', label: 'Qty Sold', type: 'number' },
|
||||
{ key: 'gross_total', label: 'Gross', type: 'currency' },
|
||||
],
|
||||
rows: rows.map(r => ({
|
||||
product_name: r.product_name,
|
||||
orders: r.orders,
|
||||
qty_sold: parseFloat(r.qty_sold ?? 0).toFixed(0),
|
||||
gross_total: parseFloat(r.gross_total ?? 0).toFixed(2),
|
||||
})),
|
||||
summary: [
|
||||
{ label: 'Products shown', value: String(rows.length) },
|
||||
],
|
||||
}
|
||||
} finally {
|
||||
await sambaPool.end()
|
||||
}
|
||||
},
|
||||
}
|
||||
58
backend/src/routes/reports.js
Normal file
58
backend/src/routes/reports.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import { requireAuth, hasCap } from '../auth.js'
|
||||
import { pool } from '../db.js'
|
||||
import { registry } from '../reports/index.js'
|
||||
import * as newbook from '../lib/newbook.js'
|
||||
|
||||
const PUBLIC_META = registry.map(r => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
category: r.category,
|
||||
categoryLabel: r.categoryLabel,
|
||||
subcategory: r.subcategory ?? null,
|
||||
description: r.description,
|
||||
}))
|
||||
|
||||
export async function reportRoutes(fastify) {
|
||||
fastify.addHook('preHandler', requireAuth)
|
||||
|
||||
fastify.get('/api/reports', async () => PUBLIC_META)
|
||||
|
||||
fastify.post('/api/reports/:id/run', async (request, reply) => {
|
||||
if (!hasCap(request, 'view')) {
|
||||
return reply.status(403).send({ error: 'Missing capability: view' })
|
||||
}
|
||||
|
||||
const { id } = request.params
|
||||
const { dateFrom, dateTo } = request.body ?? {}
|
||||
|
||||
const report = registry.find(r => r.id === id)
|
||||
if (!report) return reply.status(404).send({ error: 'Report not found' })
|
||||
|
||||
const ctx = { db: pool, newbook, env: process.env }
|
||||
const start = Date.now()
|
||||
|
||||
try {
|
||||
const result = await report.run({ dateFrom, dateTo }, ctx)
|
||||
const duration = Date.now() - start
|
||||
|
||||
pool.query(
|
||||
`INSERT INTO report_runs (report_id, report_name, user_email, date_from, date_to, row_count, duration_ms)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
[report.id, report.name, request.user.email, dateFrom ?? null, dateTo ?? null, result.rows.length, duration]
|
||||
).catch(() => {})
|
||||
|
||||
return result
|
||||
} catch (err) {
|
||||
const duration = Date.now() - start
|
||||
request.log.error(err)
|
||||
|
||||
pool.query(
|
||||
`INSERT INTO report_runs (report_id, report_name, user_email, date_from, date_to, error, duration_ms)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
[report.id, report.name, request.user.email, dateFrom ?? null, dateTo ?? null, err.message, duration]
|
||||
).catch(() => {})
|
||||
|
||||
return reply.status(500).send({ error: err.message || 'Report failed' })
|
||||
}
|
||||
})
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue