feat: add unlimited option to tier limits

Use -1 as a sentinel meaning "no cap" in tier_definitions numeric
columns. checkAndIncrementTierLimit skips the usage-cap WHERE clause
when the limit is -1. Admin tier UI gets an Unlimited switch per
field that disables the input and sends -1.
This commit is contained in:
Arnaud
2026-07-03 20:19:43 +02:00
parent 487e7755be
commit 9412529120
3 changed files with 58 additions and 17 deletions
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/api-auth";
import { db, tierDefinitions, auditLogs, eq } from "@epicure/db";
import { randomUUID } from "crypto";
import { UNLIMITED } from "@/lib/tiers";
interface RouteContext {
params: Promise<{ tier: string }>;
@@ -25,7 +26,7 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
for (const field of NUMERIC_FIELDS) {
const value = body[field];
if (value === undefined) continue;
if (!Number.isInteger(value) || value < 0) {
if (!Number.isInteger(value) || (value < 0 && value !== UNLIMITED)) {
return NextResponse.json({ error: `Invalid value for ${field}` }, { status: 400 });
}
updateData[field] = value;
+49 -14
View File
@@ -5,6 +5,9 @@ import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
const UNLIMITED = -1;
const FIELDS = [
{ key: "maxRecipes", label: "Max Recipes" },
@@ -28,6 +31,13 @@ export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinit
storageMb: tierDefinition.storageMb,
maxPublicRecipes: tierDefinition.maxPublicRecipes,
});
// Remembers the last finite value per field so toggling "Unlimited" off restores it.
const [lastFinite, setLastFinite] = useState<Record<string, number>>({
maxRecipes: tierDefinition.maxRecipes === UNLIMITED ? 0 : tierDefinition.maxRecipes,
aiCallsPerMonth: tierDefinition.aiCallsPerMonth === UNLIMITED ? 0 : tierDefinition.aiCallsPerMonth,
storageMb: tierDefinition.storageMb === UNLIMITED ? 0 : tierDefinition.storageMb,
maxPublicRecipes: tierDefinition.maxPublicRecipes === UNLIMITED ? 0 : tierDefinition.maxPublicRecipes,
});
const [saving, setSaving] = useState(false);
async function handleSave() {
@@ -55,20 +65,45 @@ export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinit
<h2 className="font-semibold text-lg capitalize">{tierDefinition.tier}</h2>
<div className="grid grid-cols-2 gap-4">
{FIELDS.map(({ key, label }) => (
<div key={key} className="space-y-1.5">
<Label htmlFor={`${tierDefinition.tier}-${key}`}>{label}</Label>
<Input
id={`${tierDefinition.tier}-${key}`}
type="number"
min={0}
value={values[key]}
onChange={(e) =>
setValues((prev) => ({ ...prev, [key]: Number(e.target.value) }))
}
/>
</div>
))}
{FIELDS.map(({ key, label }) => {
const isUnlimited = values[key] === UNLIMITED;
return (
<div key={key} className="space-y-1.5">
<div className="flex items-center justify-between">
<Label htmlFor={`${tierDefinition.tier}-${key}`}>{label}</Label>
<div className="flex items-center gap-1.5">
<Switch
id={`${tierDefinition.tier}-${key}-unlimited`}
size="sm"
checked={isUnlimited}
onCheckedChange={(checked) => {
if (checked) {
setLastFinite((prev) => ({ ...prev, [key]: values[key] ?? 0 }));
setValues((prev) => ({ ...prev, [key]: UNLIMITED }));
} else {
setValues((prev) => ({ ...prev, [key]: lastFinite[key] ?? 0 }));
}
}}
/>
<Label htmlFor={`${tierDefinition.tier}-${key}-unlimited`} className="text-xs text-muted-foreground">
Unlimited
</Label>
</div>
</div>
<Input
id={`${tierDefinition.tier}-${key}`}
type="number"
min={0}
disabled={isUnlimited}
value={isUnlimited ? "" : values[key]}
placeholder={isUnlimited ? "Unlimited" : undefined}
onChange={(e) =>
setValues((prev) => ({ ...prev, [key]: Number(e.target.value) }))
}
/>
</div>
);
})}
</div>
<Button onClick={() => { void handleSave(); }} disabled={saving} size="sm">
+7 -2
View File
@@ -9,6 +9,9 @@ function currentMonth() {
export type LimitKey = "recipe" | "aiCall" | "storage";
/** Sentinel stored in tier_definitions numeric columns to mean "no cap". */
export const UNLIMITED = -1;
export class TierLimitError extends Error {
constructor(public readonly limit: LimitKey, public readonly tier: string) {
super(`Tier limit reached: ${limit} (tier: ${tier})`);
@@ -42,12 +45,13 @@ export async function checkAndIncrementTierLimit(
if (key === "aiCall") {
const limit = tierDef.aiCallsPerMonth;
const cap = limit === UNLIMITED ? sql`true` : sql`user_usage.ai_calls_used < ${limit}`;
const result = await db.execute(sql`
INSERT INTO user_usage (id, user_id, month, ai_calls_used, recipe_count, storage_used_mb)
VALUES (${id}, ${userId}, ${month}, 1, 0, 0)
ON CONFLICT (user_id, month) DO UPDATE
SET ai_calls_used = user_usage.ai_calls_used + 1
WHERE user_usage.ai_calls_used < ${limit}
WHERE ${cap}
RETURNING ai_calls_used
`);
if (result.length === 0) {
@@ -55,12 +59,13 @@ export async function checkAndIncrementTierLimit(
}
} else {
const limit = tierDef.maxRecipes;
const cap = limit === UNLIMITED ? sql`true` : sql`user_usage.recipe_count < ${limit}`;
const result = await db.execute(sql`
INSERT INTO user_usage (id, user_id, month, ai_calls_used, recipe_count, storage_used_mb)
VALUES (${id}, ${userId}, ${month}, 0, 1, 0)
ON CONFLICT (user_id, month) DO UPDATE
SET recipe_count = user_usage.recipe_count + 1
WHERE user_usage.recipe_count < ${limit}
WHERE ${cap}
RETURNING recipe_count
`);
if (result.length === 0) {