import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core"; import { updateAddress } from "../domain/businessPartner"; import type { Transaction } from "../generated/kysely-tailordb"; import { AddressNotFoundError } from "../lib/errors.generated"; import { createBusinessPartnerRepository, type BusinessPartnerRepository, } from "../repository/businessPartnerRepository"; export type UpdatePartnerAddressInput = { id: string; line1?: string; line2?: string | null; city?: string; state?: string | null; postalCode?: string; country?: string; }; /** Updates an address through its owning BusinessPartner aggregate. */ export async function run>( db: Transaction, input: UpdatePartnerAddressInput & Partial, _ctx?: CommandContext, repositoryFactory: ( db: Transaction, ) => BusinessPartnerRepository = createBusinessPartnerRepository, ) { const { id, line1, line2, city, state, postalCode, country, ...customFields } = input; const repository = repositoryFactory(db); const partner = await repository.findByAddressId(id, { forUpdate: true }); if (!partner) return err(new AddressNotFoundError(id)); const updated = updateAddress(partner, id, { line1, line2, city, state, postalCode, country, customFields, }); if (!updated.ok) return updated; await repository.save(updated.value.partner); return ok({ partnerAddressId: updated.value.address.id }); }