import { ok, err } from "@tailor-platform/erp-kit/core"; import { currencyLifecycle } from "../db/currency.lifecycle.generated"; import type { Transaction } from "../generated/kysely-tailordb"; import { CurrencyNotFoundError } from "../lib/errors.generated"; export interface ActivateCurrencyInput { currencyId: string; } /** * Function: activateCurrency * * Re-enables a previously deactivated currency, making it available * for new transactions. */ export async function run(db: Transaction, input: ActivateCurrencyInput) { // 1. Find currency by ID const currency = await db .selectFrom("Currency") .selectAll() .where("id", "=", input.currencyId) .forUpdate() .executeTakeFirst(); // 2. If not found, throw error if (!currency) { return err(new CurrencyNotFoundError(input.currencyId)); } // 3. If already active, return currency (idempotent) const nextStatus = currencyLifecycle.tryTransition(currency.status, "activate"); if (!nextStatus) { return ok({ currency }); } // 4. Update status to ACTIVE const updatedCurrency = await db .updateTable("Currency") .set({ status: nextStatus, }) .where("id", "=", input.currencyId) .returningAll() .executeTakeFirstOrThrow(); // 5. Return updated currency return ok({ currency: updatedCurrency }); }