import { ok, err } from "@tailor-platform/erp-kit/core"; import { unitLifecycle } from "../db/unit.lifecycle.generated"; import type { Transaction } from "../generated/kysely-tailordb"; import { UnitNotFoundError } from "../lib/errors.generated"; export interface ActivateUnitInput { unitId: string; } /** * Function: activateUnit * * Re-enables a previously deactivated unit of measure, making it available * for new product assignments and quantity conversions. */ export async function run(db: Transaction, input: ActivateUnitInput) { // 1. Find unit by ID const unit = await db .selectFrom("Unit") .selectAll() .where("id", "=", input.unitId) .forUpdate() .executeTakeFirst(); // 2. If not found, throw error if (!unit) { return err(new UnitNotFoundError(input.unitId)); } // 3. If already active, return unit (idempotent) const nextStatus = unitLifecycle.tryTransition(unit.status, "activate"); if (!nextStatus) { return ok({ unit }); } // 4. Update status to ACTIVE const updatedUnit = await db .updateTable("Unit") .set({ status: nextStatus, }) .where("id", "=", input.unitId) .returningAll() .executeTakeFirstOrThrow(); // 5. Return updated unit return ok({ unit: updatedUnit }); }