import { createContext, DomainError } from "@tailor-platform/erp-kit/app"; import { createResolver, t } from "@tailor-platform/sdk"; import { getDB } from "@/generated/kysely-tailordb"; import { orgModulesExport } from "@/modules"; export default createResolver({ name: "createSite", operation: "mutation", input: { name: t.string().description("Site name"), type: t.string().description("Site type (e.g. WAREHOUSE, OFFICE)"), companyId: t.string().description("Company ID"), street: t.string().description("Street address"), city: t.string().description("City"), state: t.string({ optional: true }).description("State or province"), postalCode: t.string().description("Postal code"), country: t.string().description("Country"), timezone: t.string().description("Timezone (e.g. America/New_York)"), }, body: async (context) => { const ctx = createContext(context); const db = getDB("main-db"); return db .transaction() .execute(async (trx) => { const result = await orgModulesExport.commands.createSite( trx, { name: context.input.name, type: context.input.type, companyId: context.input.companyId, street: context.input.street, city: context.input.city, state: context.input.state ?? undefined, postalCode: context.input.postalCode, country: context.input.country, timezone: context.input.timezone, }, ctx, ); if (!result.ok) { switch (result.error.code) { case "ORGANIZATION_INVALID_NAME": throw new DomainError(`Invalid site name: ${context.input.name}`); case "ORGANIZATION_INVALID_TYPE": throw new DomainError(`Invalid site type: ${context.input.type}`); case "ORGANIZATION_COMPANY_NOT_FOUND": throw new DomainError(`Company not found: ${context.input.companyId}`); case "ORGANIZATION_COMPANY_INACTIVE": throw new DomainError(`Company is inactive: ${context.input.companyId}`); case "ORGANIZATION_DUPLICATE_NAME": throw new DomainError(`Site name already exists: ${context.input.name}`); case "ORGANIZATION_MISSING_REQUIRED_FIELDS": throw new DomainError(`Missing required fields: ${result.error.message}`); case "ORGANIZATION_INVALID_COUNTRY": throw new DomainError(`Invalid country: ${context.input.country}`); case "ORGANIZATION_INVALID_TIMEZONE": throw new DomainError(`Invalid timezone: ${context.input.timezone}`); case "UNAUTHENTICATED": throw new DomainError("Authentication is required"); case "INSUFFICIENT_PERMISSION": throw new DomainError("You do not have permission to perform this action"); default: throw result.error satisfies never; } } return { id: result.value.site.id }; }) .catch((err: unknown) => { if (err instanceof DomainError) throw err; throw new Error("Failed to create the site", { cause: err }); }); }, output: t .object({ id: t.string().description("Created site ID"), }) .description("Created site"), });