import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import { addAddress } from "../domain/businessPartner"; import type { Transaction } from "../generated/kysely-tailordb"; import { PartnerNotFoundError } from "../lib/errors.generated"; import { createBusinessPartnerRepository, type BusinessPartnerRepository, } from "../repository/businessPartnerRepository"; export interface CreatePartnerAddressInput { partnerId: string; line1: string; line2?: string; city: string; state?: string; postalCode: string; country: string; } /** Adds an identity-level address to the BusinessPartner aggregate. */ export async function run>( db: Transaction, input: CreatePartnerAddressInput & CF, _ctx?: CommandContext, repositoryFactory: ( db: Transaction, ) => BusinessPartnerRepository = createBusinessPartnerRepository, ) { const { partnerId, line1, line2, city, state, postalCode, country, ...customFields } = input; const repository = repositoryFactory(db); const partner = await repository.findById(partnerId, { forUpdate: true }); if (!partner) return err(new PartnerNotFoundError(partnerId)); const created = addAddress(partner, { line1, line2, city, state, postalCode, country, customFields, }); if (!created.ok) return created; await repository.save(created.value.partner); return ok({ partnerAddressId: created.value.address.id }); }