import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import * as domain from "../domain/accountingPeriod"; import type { Transaction } from "../generated/kysely-tailordb"; import { AccountingPeriodNotFoundError } from "../lib/errors.generated"; import { createAccountingPeriodRepository, type AccountingPeriodRepository, } from "../repository/accountingPeriodRepository"; import { createJournalEntryRepository, type JournalEntryRepository, } from "../repository/journalEntryRepository"; export interface DeleteAccountingPeriodInput { id: string; } export async function run( db: Transaction, input: DeleteAccountingPeriodInput, _ctx: CommandContext, accountingPeriodRepositoryFactory: ( db: Transaction, ) => AccountingPeriodRepository = createAccountingPeriodRepository, journalEntryRepositoryFactory: ( db: Transaction, ) => JournalEntryRepository = createJournalEntryRepository, ) { const accountingPeriodRepository = accountingPeriodRepositoryFactory(db); const journalEntryRepository = journalEntryRepositoryFactory(db); const period = await accountingPeriodRepository.findById(input.id, { forUpdate: true }); if (!period) return err(new AccountingPeriodNotFoundError(input.id)); const allowed = domain.checkDeletable( input.id, await journalEntryRepository.hasPeriodEntries(input.id), ); if (!allowed.ok) return allowed; await accountingPeriodRepository.delete(input.id); return ok({ deleted: true }); }