import { ok, err } from "@tailor-platform/erp-kit/core"; import { uoMCategoryLifecycle } from "../db/uoMCategory.lifecycle.generated"; import type { Transaction } from "../generated/kysely-tailordb"; import { UomCategoryNotFoundError } from "../lib/errors.generated"; export interface ActivateCategoryInput { categoryId: string; } /** * Function: activateCategory * * Re-enables a previously deactivated UoM category, making it and its units * available for new product assignments and transactions. */ export async function run(db: Transaction, input: ActivateCategoryInput) { // 1. Find category by ID const uoMCategory = await db .selectFrom("UoMCategory") .selectAll() .where("id", "=", input.categoryId) .forUpdate() .executeTakeFirst(); // 2. If not found, throw error if (!uoMCategory) { return err(new UomCategoryNotFoundError(input.categoryId)); } // 3. If already active, return category (idempotent) const nextStatus = uoMCategoryLifecycle.tryTransition(uoMCategory.status, "activate"); if (!nextStatus) { return ok({ uoMCategory }); } // 4. Update status to ACTIVE const updatedCategory = await db .updateTable("UoMCategory") .set({ status: nextStatus, }) .where("id", "=", input.categoryId) .returningAll() .executeTakeFirstOrThrow(); // 5. Return updated category return ok({ uoMCategory: updatedCategory }); }