f0b570284e
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
51 lines
1.8 KiB
TypeScript
51 lines
1.8 KiB
TypeScript
"use server";
|
|
|
|
import { revalidatePath } from "next/cache";
|
|
import { z } from "zod";
|
|
import { tr } from "@/i18n/tr";
|
|
import { fail, type ActionResult } from "@/lib/action-result";
|
|
import { getHouseholdActionContext } from "@/lib/dal";
|
|
import { productFormSchema } from "@/shared/schemas/product";
|
|
import { createProduct, setProductArchived, updateProduct } from "./service";
|
|
|
|
const idSchema = z.string().regex(/^[a-f0-9]{24}$/i);
|
|
|
|
function fieldErrors(error: z.ZodError) {
|
|
const out: Record<string, string> = {};
|
|
for (const issue of error.issues) {
|
|
const key = issue.path.join(".");
|
|
if (key && !out[key]) out[key] = issue.message;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
async function run<T, R>(
|
|
schema: z.ZodType<T>,
|
|
input: unknown,
|
|
fn: (userId: string, householdId: string, data: T) => Promise<ActionResult<R>>,
|
|
): Promise<ActionResult<R>> {
|
|
const ctx = await getHouseholdActionContext("member");
|
|
if (!ctx) return fail(tr.common.unauthorized);
|
|
const parsed = schema.safeParse(input);
|
|
if (!parsed.success) return fail(tr.adminUsers.errors.checkFields, fieldErrors(parsed.error));
|
|
const result = await fn(ctx.user.id, ctx.household.id, parsed.data);
|
|
if (result.ok) revalidatePath("/", "layout");
|
|
return result;
|
|
}
|
|
|
|
/** Yeni (id boş) veya mevcut ürün. */
|
|
export async function saveProductAction(productId: unknown, input: unknown) {
|
|
if (productId) {
|
|
const id = idSchema.safeParse(productId);
|
|
if (!id.success) return fail(tr.common.notFound);
|
|
return run(productFormSchema, input, (u, h, d) => updateProduct(u, h, id.data, d));
|
|
}
|
|
return run(productFormSchema, input, createProduct);
|
|
}
|
|
|
|
export async function setProductArchivedAction(productId: unknown, archived: unknown) {
|
|
const id = idSchema.safeParse(productId);
|
|
if (!id.success) return fail(tr.common.notFound);
|
|
return run(z.boolean(), archived, (u, h, a) => setProductArchived(u, h, id.data, a));
|
|
}
|