add review and booking policies

This commit is contained in:
root
2026-05-25 18:29:05 -04:00
parent 8ed572b3bd
commit 0d969ab095
37 changed files with 3775 additions and 113 deletions
+109
View File
@@ -0,0 +1,109 @@
import { prisma } from '../../lib/prisma'
const REVIEW_INCLUDE = {
reservation: {
select: {
id: true,
startDate: true,
endDate: true,
reviewToken: true,
reviewRequestSentAt: true,
reviewReminderSentAt: true,
reviewFinalReminderSentAt: true,
reviewPaused: true,
customer: {
select: {
id: true,
firstName: true,
lastName: true,
email: true,
reviewOptOut: true,
},
},
vehicle: {
select: {
id: true,
make: true,
model: true,
year: true,
},
},
},
},
}
export async function findMany(
companyId: string,
where: Record<string, unknown>,
skip: number,
take: number,
) {
const baseWhere = { companyId, ...where }
return Promise.all([
prisma.review.findMany({
where: baseWhere,
include: REVIEW_INCLUDE,
skip,
take,
orderBy: { createdAt: 'desc' },
}),
prisma.review.count({ where: baseWhere }),
])
}
export async function findById(id: string, companyId: string) {
return prisma.review.findFirst({
where: { id, companyId },
include: REVIEW_INCLUDE,
})
}
export async function updateById(id: string, data: Record<string, unknown>) {
return prisma.review.update({
where: { id },
data,
include: REVIEW_INCLUDE,
})
}
export async function getStats(companyId: string) {
const reviews = await prisma.review.findMany({
where: { companyId },
select: { overallRating: true, vehicleRating: true, serviceRating: true },
})
const total = reviews.length
const byRating: Record<number, number> = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }
let sumOverall = 0
let sumVehicle = 0
let countVehicle = 0
let sumService = 0
let countService = 0
for (const r of reviews) {
sumOverall += r.overallRating
byRating[r.overallRating] = (byRating[r.overallRating] ?? 0) + 1
if (r.vehicleRating != null) { sumVehicle += r.vehicleRating; countVehicle++ }
if (r.serviceRating != null) { sumService += r.serviceRating; countService++ }
}
return {
total,
averageOverall: total > 0 ? Math.round((sumOverall / total) * 10) / 10 : 0,
averageVehicle: countVehicle > 0 ? Math.round((sumVehicle / countVehicle) * 10) / 10 : 0,
averageService: countService > 0 ? Math.round((sumService / countService) * 10) / 10 : 0,
byRating,
}
}
export async function sendReminder(
reservationId: string,
sentAt: Date,
field: 'reviewReminderSentAt' | 'reviewFinalReminderSentAt',
) {
return prisma.reservation.update({
where: { id: reservationId },
data: { [field]: sentAt },
})
}
@@ -0,0 +1,54 @@
import { Router } from 'express'
import { requireCompanyAuth } from '../../middleware/requireCompanyAuth'
import { requireTenant } from '../../middleware/requireTenant'
import { requireSubscription } from '../../middleware/requireSubscription'
import { parseBody, parseQuery, parseParams } from '../../http/validate'
import { ok } from '../../http/respond'
import * as service from './review.service'
import { replySchema, listQuerySchema, idParamSchema } from './review.schemas'
const router = Router()
router.use(requireCompanyAuth, requireTenant, requireSubscription)
router.get('/', async (req, res, next) => {
try {
const query = parseQuery(listQuerySchema, req)
const result = await service.listReviews(req.companyId, query)
ok(res, result)
} catch (err) { next(err) }
})
router.get('/stats', async (req, res, next) => {
try {
const stats = await service.getStats(req.companyId)
ok(res, stats)
} catch (err) { next(err) }
})
router.get('/:id', async (req, res, next) => {
try {
const { id } = parseParams(idParamSchema, req)
const review = await service.getReview(id, req.companyId)
ok(res, review)
} catch (err) { next(err) }
})
router.patch('/:id/reply', async (req, res, next) => {
try {
const { id } = parseParams(idParamSchema, req)
const { companyReply } = parseBody(replySchema, req)
const updated = await service.replyToReview(id, req.companyId, companyReply)
ok(res, updated)
} catch (err) { next(err) }
})
router.post('/:id/remind', async (req, res, next) => {
try {
const { id } = parseParams(idParamSchema, req)
const result = await service.sendReviewReminder(id, req.companyId)
ok(res, result)
} catch (err) { next(err) }
})
export default router
@@ -0,0 +1,15 @@
import { z } from 'zod'
export const replySchema = z.object({
companyReply: z.string().min(1),
})
export const listQuerySchema = z.object({
rating: z.coerce.number().int().min(1).max(5).optional(),
page: z.coerce.number().int().min(1).default(1),
pageSize: z.coerce.number().int().min(1).max(100).default(20),
})
export const idParamSchema = z.object({
id: z.string(),
})
@@ -0,0 +1,76 @@
import { NotFoundError, AppError } from '../../http/errors'
import { sendTransactionalEmail } from '../../services/notificationService'
import { reviewRequestEmail, type Lang } from '../../lib/emailTranslations'
import * as repo from './review.repo'
import * as reservationRepo from '../reservations/reservation.repo'
export async function listReviews(
companyId: string,
query: { rating?: number; page: number; pageSize: number },
) {
const { rating, page, pageSize } = query
const where: Record<string, unknown> = {}
if (rating != null) where.overallRating = rating
const [reviews, total] = await repo.findMany(companyId, where, (page - 1) * pageSize, pageSize)
return {
data: reviews,
meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) },
}
}
export async function getReview(id: string, companyId: string) {
const review = await repo.findById(id, companyId)
if (!review) throw new NotFoundError('Review not found')
return review
}
export async function replyToReview(id: string, companyId: string, companyReply: string) {
const review = await repo.findById(id, companyId)
if (!review) throw new NotFoundError('Review not found')
return repo.updateById(id, {
companyReply,
companyRepliedAt: new Date(),
})
}
export async function getStats(companyId: string) {
return repo.getStats(companyId)
}
export async function sendReviewReminder(id: string, companyId: string) {
const review = await repo.findById(id, companyId)
if (!review) throw new NotFoundError('Review not found')
const reservation = review.reservation as any
if (!reservation) throw new AppError('Review has no linked reservation', 400, 'no_reservation')
if (reservation.reviewPaused) throw new AppError('Review requests are paused for this reservation', 400, 'review_paused')
const customer = reservation.customer
if (!customer || customer.reviewOptOut) throw new AppError('Customer has opted out of review requests', 400, 'opted_out')
if (!customer.email) throw new AppError('Customer has no email address', 400, 'no_email')
if (!reservation.reviewToken) throw new AppError('No review token available for this reservation', 400, 'no_token')
// Determine which reminder field to update
const field: 'reviewReminderSentAt' | 'reviewFinalReminderSentAt' =
reservation.reviewReminderSentAt ? 'reviewFinalReminderSentAt' : 'reviewReminderSentAt'
const company = await reservationRepo.findCompanyWithBrand(companyId)
const lang = (company?.brand?.defaultLocale ?? 'fr') as Lang
const companyName = company?.brand?.displayName ?? company?.name ?? 'the rental company'
const vehicle = reservation.vehicle
const vehicleLabel = vehicle ? `${vehicle.year} ${vehicle.make} ${vehicle.model}` : 'your rental vehicle'
const reviewUrl = `${process.env.MARKETPLACE_URL ?? 'http://localhost:3000'}/review?token=${reservation.reviewToken}`
await sendTransactionalEmail({
to: customer.email,
subject: reviewRequestEmail.subject(vehicleLabel, lang),
html: reviewRequestEmail.html({ firstName: customer.firstName, companyName, vehicleLabel, reviewUrl }, lang),
text: reviewRequestEmail.text({ firstName: customer.firstName, companyName, vehicleLabel, reviewUrl }, lang),
})
await repo.sendReminder(reservation.id, new Date(), field)
return { success: true, field }
}