59 lines
2.1 KiB
TypeScript
59 lines
2.1 KiB
TypeScript
"use server";
|
|
|
|
import { auth } from "@/auth";
|
|
import { prisma } from "@/lib/db/prisma";
|
|
import { Permission } from "@/generated/prisma/enums";
|
|
import { hasPermission } from "@/lib/auth/permissions";
|
|
import { redeemReward } from "@/services/loyalty/loyalty.service";
|
|
import { writeAuditLog } from "@/lib/audit/write-audit-log";
|
|
|
|
export interface RedeemRewardResult {
|
|
success: boolean;
|
|
error?: string;
|
|
discountAmount?: string;
|
|
}
|
|
|
|
/**
|
|
* Redemption is an operational action a permitted barber does day to day
|
|
* (not "configure the loyalty programme"), so it's gated on
|
|
* MANAGE_LOYALTY_STAMPS — the same permission Phase 5 already grants to
|
|
* the Barber role for adding/correcting stamps — rather than
|
|
* MANAGE_LOYALTY_PROGRAMME, which is owner-only configuration. Both Owner
|
|
* and Barber roles hold MANAGE_LOYALTY_STAMPS in the seed. See
|
|
* docs/phase-6-summary.md, "Loyalty configuration and redemption approach".
|
|
*/
|
|
export async function redeemRewardAction(params: {
|
|
rewardId: string;
|
|
appointmentId: string;
|
|
}): Promise<RedeemRewardResult> {
|
|
const session = await auth();
|
|
if (!session?.user) return { success: false, error: "You must be signed in." };
|
|
|
|
const allowed = await hasPermission(session.user.id, Permission.MANAGE_LOYALTY_STAMPS);
|
|
if (!allowed) return { success: false, error: "You don't have permission to do that." };
|
|
|
|
const staff = await prisma.staffProfile.findUnique({ where: { userId: session.user.id } });
|
|
if (!staff) return { success: false, error: "You must be signed in as staff." };
|
|
|
|
const result = await redeemReward(prisma, {
|
|
rewardId: params.rewardId,
|
|
appointmentId: params.appointmentId,
|
|
staffId: staff.id,
|
|
businessId: staff.businessId,
|
|
});
|
|
|
|
if (!result.success) {
|
|
return { success: false, error: result.validation.issues[0]?.message ?? "Couldn't redeem this reward." };
|
|
}
|
|
|
|
await writeAuditLog(prisma, {
|
|
actorUserId: session.user.id,
|
|
action: "LOYALTY_REWARD_REDEEMED",
|
|
entityType: "LoyaltyReward",
|
|
entityId: params.rewardId,
|
|
metadata: { appointmentId: params.appointmentId, discountAmount: result.discountAmount },
|
|
});
|
|
|
|
return { success: true, discountAmount: result.discountAmount };
|
|
}
|