/**
* @file Contains service functions for canteen-related operations.
*
* This file encapsulates the core business logic and database interactions
* for canteens, keeping the tRPC router lean and focused on API exposure.
*/
import { TRPCError } from "@trpc/server";
import type { TRPCContext } from "../../trpc"; // Adjust path if necessary
import { type AuthenticatedUser } from "../../types"; // Assuming you have a type for your authenticated user,
// which includes `id`, `businessId`, `canteenAccess`.
// This might be based on your NextAuth session user.
import { createOwnCanteenSchema, updateOwnCanteenSchema } from "./canteen.zod"; // Import Zod schemas for typing
// --- Helper Functions (can remain local or be exported if widely used) ---
/**
* Generates a unique-ish slug from canteen name and city.
* @param name Canteen name
* @param city Canteen city
* @returns A slug string
*/
export const generateCanteenSlug = (name: string, city: string): string => {
// Simple slug generation: lowercase, replace spaces with hyphens
return `${name.toLowerCase().replace(/\s/g, "-")}-${city.toLowerCase().replace(/\s/g, "-")}`;
};
/**
* Asserts that the user is authenticated and returns their session user object.
* This function should ideally be part of a core `auth.service.ts` or similar.
* @param ctx The tRPC context.
* @returns The authenticated user object.
* @throws TRPCError if the user is not authenticated.
*/
export const assertAuthenticated = (ctx: TRPCContext): AuthenticatedUser => {
if (!ctx.session?.user) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "Not authenticated." });
}
// Cast to your specific AuthenticatedUser type, assuming ctx.session.user
// is populated with businessId and canteenAccess through your NextAuth setup.
return ctx.session.user as AuthenticatedUser;
};
/**
* Ensures a canteen name/city combination (slug) is unique within a business.
* Throws a CONFLICT error if a duplicate is found.
* @param ctx tRPC context
* @param params Parameters including name, city, businessId, and optional excludeCanteenId.
*/
export async function ensureUniqueCanteenName(
ctx: TRPCContext,
{
name,
city,
businessId,
excludeCanteenId,
}: {
name: string;
city: string;
businessId: string;
excludeCanteenId?: string;
},
): Promise<void> {
const slug = generateCanteenSlug(name, city);
const existing = await ctx.db.canteen.findFirst({
where: {
slug,
businessId,
id: excludeCanteenId ? { not: excludeCanteenId } : undefined,
},
});
if (existing) {
throw new TRPCError({
code: "CONFLICT",
message: "A canteen with the same name and city (slug) already exists in your business.",
});
}
}
/**
* Asserts that the authenticated user has access to a specific canteen.
* This combines the check for `canteenAccess` with fetching the canteen.
* @param ctx tRPC context
* @param user Authenticated user object
* @param canteenId The ID of the canteen to check access for.
* @returns The canteen object if access is granted, throws otherwise.
* @throws TRPCError (FORBIDDEN or NOT_FOUND)
*/
export async function assertUserCanAccessCanteen(
ctx: TRPCContext,
user: AuthenticatedUser,
canteenId: string,
) {
if (!user.canteenAccess?.includes(canteenId)) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permission to access this canteen.",
});
}
const canteen = await ctx.db.canteen.findUnique({
where: { id: canteenId },
include: { address: true },
});
if (!canteen) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Canteen not found.",
});
}
return canteen;
}
// --- Canteen Service Functions ---
/**
* Provides a set of service methods for Canteen operations.
* Each method encapsulates specific business logic and database interactions.
*/
export const canteenService = {
/**
* Lists canteens accessible by the current user.
*/
async listOwn(ctx: TRPCContext, user: AuthenticatedUser) {
return ctx.db.canteen.findMany({
where: { id: { in: user.canteenAccess ?? [] } },
include: {
address: true,
},
});
},
/**
* Creates a new canteen for the current user's business.
* Only business owners can create canteens.
*/
async createOwn(
ctx: TRPCContext,
user: AuthenticatedUser,
input: typeof createOwnCanteenSchema._input, // Use _input for runtime value types
) {
// Only business owners can create new canteens.
if (!user.businessId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only business owners can create new canteens.",
});
}
await ensureUniqueCanteenName(ctx, {
name: input.name,
city: input.city,
businessId: user.businessId,
});
const newCanteen = await ctx.db.canteen.create({
data: {
name: input.name,
fullName: input.fullName,
slug: generateCanteenSlug(input.name, input.city),
notes: input.notes,
business: { connect: { id: user.businessId } },
address: {
create: {
street: input.street,
city: input.city,
state: input.state,
zip: input.zip,
country: input.country,
},
},
},
include: {
address: true,
},
});
// Create a CanteenAccess record for the user (business owner)
// assertAuthenticated ensures user.id exists
await ctx.db.canteenAccess.create({
data: {
userId: user.id,
canteenId: newCanteen.id,
},
});
return newCanteen;
},
/**
* Updates an existing canteen.
* User must have `canManageOwnCanteens` permission and access to the specific canteen.
*/
async updateOwn(
ctx: TRPCContext,
user: AuthenticatedUser,
input: typeof updateOwnCanteenSchema._input,
) {
// This single call handles both canteen existence and user access verification
const canteenToUpdate = await assertUserCanAccessCanteen(ctx, user, input.id);
// If name or city is being updated, ensure the new combination is unique
if (input.name !== undefined && input.city !== undefined) {
// Only re-check uniqueness if both name and city are provided for a potential slug change
await ensureUniqueCanteenName(ctx, {
name: input.name,
city: input.city,
businessId: canteenToUpdate.businessId,
excludeCanteenId: input.id,
});
}
// Prepare address data for update
const addressUpdateData: Record<string, string | undefined> = {
street: input.street,
city: input.city,
state: input.state,
zip: input.zip,
country: input.country,
};
// Check if any address fields are actually provided for update
const hasAddressData = Object.values(addressUpdateData).some((v) => v !== undefined);
return ctx.db.canteen.update({
where: {
id: input.id,
},
data: {
name: input.name,
fullName: input.fullName,
// Only update slug if both name and city are provided in the update
slug:
input.name !== undefined && input.city !== undefined
? generateCanteenSlug(input.name, input.city)
: undefined,
notes: input.notes,
address: hasAddressData ? { update: addressUpdateData } : undefined,
},
include: {
address: true,
},
});
},
/**
* Retrieves a single canteen by ID, ensuring user has access.
*/
async getOwnById(ctx: TRPCContext, user: AuthenticatedUser, id: string) {
// assertUserCanAccessCanteen already includes the `findUnique` and `include: address` logic
return assertUserCanAccessCanteen(ctx, user, id);
},
/**
* Deletes a canteen, ensuring user has access.
*/
async deleteOwn(ctx: TRPCContext, user: AuthenticatedUser, id: string) {
// First, check if the user has access to this canteen.
// We don't need the returned canteen object, just the permission check.
await assertUserCanAccessCanteen(ctx, user, id);
// Delete related CanteenAccess records first (to avoid FK errors)
await ctx.db.canteenAccess.deleteMany({ where: { canteenId: id } });
// Then delete the canteen
await ctx.db.canteen.delete({ where: { id } });
return { success: true };
},
};