Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

feat: csv company import (#253)

grim81afb5fe7f6e
diff --git a/apps/api/src/agent/agent-trigger.service.ts b/apps/api/src/agent/agent-trigger.service.ts
index 7275f455..98cde03d 100644
--- a/apps/api/src/agent/agent-trigger.service.ts
+++ b/apps/api/src/agent/agent-trigger.service.ts
@@ -54,16 +54,23 @@ export class AgentTriggerService {
companyId: string,
reason = "New company",
): Promise<void> {
- await this.enqueue({
- companyId,
+ await this.companiesCreated([companyId], reason);
+ }
+
+ async companiesCreated(
+ companyIds: string[],
+ reason = "New company",
+ ): Promise<void> {
+ await this.backfill({
+ companyIds,
kind: "brand",
reason,
priority: PRIORITY.brand,
budget: 2,
});
- await this.enqueue({
- companyId,
+ await this.backfill({
+ companyIds,
kind: "company-profile",
reason,
priority: PRIORITY.companyProfile,
@@ -197,13 +204,16 @@ export class AgentTriggerService {
emit: (input: CrmEventInput) => Promise<void>,
) => Promise<Result>,
): Promise<Result> {
- const queued: CrmEventInput[] = [];
- const result = await this.db.$transaction((tx) =>
- work(tx, async (input) => {
- await this.createEventTask(tx, input);
- queued.push(input);
- }),
- );
+ let queued: CrmEventInput[] = [];
+ const result = await this.db.$transaction(async (tx) => {
+ const pending: CrmEventInput[] = [];
+ const completed = await work(tx, async (input) => {
+ pending.push(input);
+ });
+ await this.createEventTasks(tx, pending);
+ queued = pending;
+ return completed;
+ });
for (const input of queued) {
this.logger.log({
@@ -218,6 +228,40 @@ export class AgentTriggerService {
return result;
}
+ async fieldBackfillNewRecords(
+ entity: FieldEntity,
+ keys: string[],
+ ids: string[],
+ reason: string,
+ ): Promise<{ queued: number }> {
+ const recordIds = [...new Set(ids)];
+ if (recordIds.length === 0 || keys.length === 0) return { queued: 0 };
+
+ const column = RECORD_ID_COLUMNS[entity];
+ const dueAt = new Date();
+ const data: Prisma.AgentTaskCreateManyInput[] = recordIds.map((id) => ({
+ [column]: id,
+ kind: "field-backfill",
+ reason,
+ priority: PRIORITY.fieldBackfill,
+ budget: 8,
+ dueAt,
+ payload: { entity, keys } satisfies Prisma.InputJsonValue,
+ }));
+ const result = await this.db.agentTask.createMany({ data });
+
+ this.logger.log({
+ message: "Agent task queued",
+ kind: "field-backfill",
+ entity,
+ keys,
+ queued: result.count,
+ });
+ if (result.count > 0) this.poke();
+
+ return { queued: result.count };
+ }
+
async fieldBackfillRecords(
entity: FieldEntity,
keys: string[],
@@ -517,18 +561,17 @@ export class AgentTriggerService {
}
}
- private async createEventTask(
+ private async createEventTasks(
tx: Prisma.TransactionClient,
- input: CrmEventInput,
+ inputs: CrmEventInput[],
): Promise<void> {
- const recordIds = {
- contactId: input.record.kind === "contact" ? input.record.id : null,
- companyId: input.record.kind === "company" ? input.record.id : null,
- dealId: input.record.kind === "deal" ? input.record.id : null,
- };
- await tx.agentTask.create({
- data: {
- ...recordIds,
+ if (inputs.length === 0) return;
+ const dueAt = new Date();
+ await tx.agentTask.createMany({
+ data: inputs.map((input) => ({
+ contactId: input.record.kind === "contact" ? input.record.id : null,
+ companyId: input.record.kind === "company" ? input.record.id : null,
+ dealId: input.record.kind === "deal" ? input.record.id : null,
kind: "agent-event",
reason: input.type,
payload: {
@@ -539,8 +582,8 @@ export class AgentTriggerService {
},
priority: PRIORITY.event,
budget: 1,
- dueAt: new Date(),
- },
+ dueAt,
+ })),
});
}
diff --git a/apps/api/src/companies/companies.contracts.ts b/apps/api/src/companies/companies.contracts.ts
index d2157334..d2107d8a 100644
--- a/apps/api/src/companies/companies.contracts.ts
+++ b/apps/api/src/companies/companies.contracts.ts
@@ -1,5 +1,9 @@
import { DealStage, EnrichmentStatus, RecordSource } from "@crm/db";
import { FIELD_TYPES } from "@crm/db/fields";
+import {
+ type CompanyImportInput,
+ companyImportInput as sharedCompanyImportInput,
+} from "@crm/validation/company-import";
import { z } from "zod";
import { bulkIdsInput } from "../crm/bulk";
import { fieldEntity, recordFieldValues } from "../fields/fields.contracts";
@@ -25,6 +29,9 @@ export const companyCreateInput = z.object({
export type CompanyCreateInput = z.infer<typeof companyCreateInput>;
+export const companyImportInput = sharedCompanyImportInput;
+export type { CompanyImportInput };
+
const companyUpdateInput = z.object({
name: z.string().trim().min(1).optional(),
domain: z.string().optional(),
@@ -241,6 +248,12 @@ export const companyBulkResultOutput = z.object({
message: z.string().nullable(),
});
+export const companyImportOutput = z.object({
+ created: z.number(),
+ skipped: z.number(),
+ skips: z.array(z.object({ row: z.number(), reason: z.string() })),
+});
+
export const companyEnrichOutput = z.object({
id: z.string(),
queued: z.boolean(),
diff --git a/apps/api/src/companies/companies.router.ts b/apps/api/src/companies/companies.router.ts
index ac11ccd3..8a8578c3 100644
--- a/apps/api/src/companies/companies.router.ts
+++ b/apps/api/src/companies/companies.router.ts
@@ -20,6 +20,8 @@ import {
companyDetailOutput,
companyEnrichOutput,
companyIdInput,
+ companyImportInput,
+ companyImportOutput,
companyListInput,
companyListOutput,
companyOptionOutput,
@@ -75,6 +77,15 @@ export class CompaniesRouter {
return this.companies.create(input);
}
+ @Mutation({
+ input: companyImportInput,
+ output: companyImportOutput,
+ meta: restMeta("POST", "/companies/import", ["Companies"]),
+ })
+ async import(@Input() input: z.infer<typeof companyImportInput>) {
+ return this.companies.import(input);
+ }
+
@Mutation({
input: companyUpdateArgs,
output: companySummaryOutput,
diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.ts
index 3960dc33..5d896f5c 100644
--- a/apps/api/src/companies/companies.service.ts
+++ b/apps/api/src/companies/companies.service.ts
@@ -1,12 +1,17 @@
import {
type Db,
- type EnrichmentStatus,
+ EnrichmentStatus,
type Prisma,
Prisma as PrismaNamespace,
- type RecordSource,
+ RecordSource,
} from "@crm/db";
import { OPEN_DEAL_STAGES } from "@crm/db/deal-stage";
import type { FieldDefinitionWithOptions } from "@crm/db/fields";
+import { lockIdempotencyKey, lockIdempotencyKeys } from "@crm/db/idempotency";
+import {
+ COMPANY_IMPORT,
+ type CompanyImportInput,
+} from "@crm/validation/company-import";
import {
BadRequestException,
ConflictException,
@@ -274,19 +279,20 @@ export class CompaniesService {
async create(input: CompanyCreateInput) {
const domain = normalizeDomain(input.domain);
- if (domain) {
- const existing = await this.db.company.findFirst({
- where: { domain, archivedAt: null },
- select: { id: true, name: true },
- });
- if (existing) {
- throw new ConflictException(
- `${existing.name} already uses the domain ${domain}.`,
- );
+ const company = await this.agent.withCrmEvents(async (tx, emit) => {
+ if (domain) {
+ await lockIdempotencyKey(tx, `company-directory:${domain}`);
+ const existing = await tx.company.findFirst({
+ where: { domain, archivedAt: null },
+ select: { name: true },
+ });
+ if (existing) {
+ throw new ConflictException(
+ `${existing.name} already uses the domain ${domain}.`,
+ );
+ }
}
- }
- const company = await this.agent.withCrmEvents(async (tx, emit) => {
const created = await tx.company.create({
data: {
name: input.name.trim(),
@@ -319,6 +325,125 @@ export class CompaniesService {
return { id: company.id, name: company.name, domain: company.domain };
}
+ async import(input: CompanyImportInput) {
+ const skips: Array<{ row: number; reason: string }> = [];
+ const candidates = input.rows.flatMap((row, index) => {
+ const rowNumber = index + 2;
+ const name = row.name.trim();
+ if (!name) {
+ skips.push({ row: rowNumber, reason: "A company needs a name." });
+ return [];
+ }
+
+ const website = row.website?.trim() ?? "";
+ const domain = normalizeDomain(website);
+ if (website && !domain) {
+ skips.push({
+ row: rowNumber,
+ reason: `"${website}" is not a valid domain.`,
+ });
+ return [];
+ }
+
+ return [
+ {
+ row: rowNumber,
+ name,
+ domain,
+ phone: blankToNull(row.phone ?? ""),
+ city: blankToNull(row.city ?? ""),
+ stateCode: blankToNull(row.stateCode ?? ""),
+ industry: blankToNull(row.industry ?? ""),
+ subIndustry: blankToNull(row.subIndustry ?? ""),
+ description: blankToNull(row.description ?? ""),
+ },
+ ];
+ });
+
+ const created = await this.agent.withCrmEvents(async (tx, emit) => {
+ const domains = [
+ ...new Set(
+ candidates.flatMap((candidate) =>
+ candidate.domain ? [candidate.domain] : [],
+ ),
+ ),
+ ].toSorted();
+ await lockIdempotencyKeys(
+ tx,
+ domains.map((domain) => `company-directory:${domain}`),
+ );
+
+ const existing = new Set(
+ (
+ await tx.company.findMany({
+ where: { domain: { in: domains }, archivedAt: null },
+ select: { domain: true },
+ })
+ ).flatMap((company) => (company.domain ? [company.domain] : [])),
+ );
+ const accepted = [];
+ const seen = new Set<string>();
+ for (const candidate of candidates) {
+ if (candidate.domain && existing.has(candidate.domain)) {
+ skips.push({
+ row: candidate.row,
+ reason: `${candidate.domain} already belongs to a company.`,
+ });
+ continue;
+ }
+ if (candidate.domain && seen.has(candidate.domain)) {
+ skips.push({
+ row: candidate.row,
+ reason: `${candidate.domain} appears more than once in this file.`,
+ });
+ continue;
+ }
+ if (candidate.domain) seen.add(candidate.domain);
+ accepted.push(candidate);
+ }
+
+ if (accepted.length === 0) return [];
+ const rows = await tx.company.createManyAndReturn({
+ data: accepted.map(({ row: _row, ...company }) => ({
+ ...company,
+ website: company.domain ? `https://${company.domain}` : null,
+ source: RecordSource.IMPORT,
+ enrichmentStatus: EnrichmentStatus.PENDING,
+ })),
+ select: { id: true, name: true, domain: true, createdAt: true },
+ });
+
+ for (const company of rows) {
+ await emit({
+ type: "company.created",
+ record: { kind: "company", id: company.id },
+ occurredAt: company.createdAt,
+ data: { name: company.name, domain: company.domain },
+ });
+ }
+ return rows;
+ });
+
+ const ids = created.map((company) => company.id);
+ await Promise.all([
+ this.agent.companiesCreated(ids, "Imported from CSV"),
+ this.fields.queueBackfillForNewRecords("COMPANY", ids),
+ ]);
+ void this.backfillFavicons(created);
+
+ this.logger.log({
+ message: "Companies imported",
+ created: created.length,
+ skipped: skips.length,
+ });
+
+ return {
+ created: created.length,
+ skipped: skips.length,
+ skips: skips.toSorted((left, right) => left.row - right.row),
+ };
+ }
+
async update(id: string, input: CompanyUpdateInput) {
const data: Prisma.CompanyUpdateInput = {};
@@ -733,4 +858,18 @@ export class CompaniesService {
}
throw cause;
}
+
+ private async backfillFavicons(
+ companies: Array<{ id: string; domain: string | null }>,
+ ): Promise<void> {
+ const queue = companies[Symbol.iterator]();
+ const width = Math.min(COMPANY_IMPORT.faviconConcurrency, companies.length);
+ await Promise.all(
+ Array.from({ length: width }, async () => {
+ for (const company of queue) {
+ await this.favicon.backfill(company.id, company.domain);
+ }
+ }),
+ );
+ }
}
diff --git a/apps/api/src/fields/fields.service.ts b/apps/api/src/fields/fields.service.ts
index be1855ff..715a4af7 100644
--- a/apps/api/src/fields/fields.service.ts
+++ b/apps/api/src/fields/fields.service.ts
@@ -341,6 +341,14 @@ export class FieldsService {
entity: FieldEntity,
recordId: string,
): Promise<void> {
+ await this.queueBackfillForNewRecords(entity, [recordId]);
+ }
+
+ async queueBackfillForNewRecords(
+ entity: FieldEntity,
+ recordIds: string[],
+ ): Promise<void> {
+ if (recordIds.length === 0) return;
const definitions = await this.db.fieldDefinition.findMany({
where: { entity, archivedAt: null, agentFilled: true },
select: { key: true },
@@ -348,10 +356,10 @@ export class FieldsService {
if (definitions.length === 0) return;
- await this.agent.fieldBackfillRecords(
+ await this.agent.fieldBackfillNewRecords(
entity,
definitions.map((definition) => definition.key),
- [recordId],
+ recordIds,
"New record",
);
}
diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.ts
index 161206d7..83d5bd0e 100644
--- a/apps/api/src/generated/server.ts
+++ b/apps/api/src/generated/server.ts
@@ -16,7 +16,7 @@ const publicProcedure = t.procedure;
import { timelineInput, timelineOutput, timelineCountsInput, timelineCountsOutput, myTasksInput, myTasksOutput, activityCreateInput, activityCreateOutput, completeInput, completeOutput } from "../activities/activities.contracts";
import { agentListOutput, agentReviseInput, agentReviseOutput, agentIdInput, agentFilesOutput, agentSaveFileInput, agentSaveFileOutput, agentByIdOutput, agentHistoryInput, agentHistoryOutput, agentActivityOutput, agentUpdateInput, agentUpdateOutput, agentDeployInput, agentDeployOutput, agentPauseOutput, agentResumeOutput, agentArchiveOutput, agentRestoreOutput, agentRemoveOutput, agentRunNowInput, agentRunNowOutput, agentRetryRunInput, agentRetryRunOutput, agentCancelRunInput, agentCancelRunOutput } from "../agent/agents.contracts";
import { apiKeyListInput, apiKeyListOutput, createApiKeyInput, createApiKeyOutput, revokeApiKeyInput, revokeApiKeyOutput } from "../api-keys/api-keys.contracts";
-import { companyListInput, companyListOutput, companyIdInput, companyDetailOutput, companyOptionsInput, companyOptionOutput, companyCreateInput, companySummaryOutput, companyUpdateArgs, companyArchiveResultOutput, companyBulkOwnerInput, companyBulkResultOutput, companyBulkInput, companyEnrichOutput, companyResearchOutput, setPrimaryContactInput, companySetPrimaryContactOutput } from "../companies/companies.contracts";
+import { companyListInput, companyListOutput, companyIdInput, companyDetailOutput, companyOptionsInput, companyOptionOutput, companyCreateInput, companySummaryOutput, companyImportInput, companyImportOutput, companyUpdateArgs, companyArchiveResultOutput, companyBulkOwnerInput, companyBulkResultOutput, companyBulkInput, companyEnrichOutput, companyResearchOutput, setPrimaryContactInput, companySetPrimaryContactOutput } from "../companies/companies.contracts";
import { contactListInput, contactListOutput, contactIdInput, contactByIdOutput, contactCreateInput, contactBasicOutput, contactUpdateArgs, contactNameOutput, contactEnrichOutput, contactBulkOwnerInput, bulkResultOutput, contactBulkCompanyInput, contactBulkInput, factDecisionInput, decideFactOutput } from "../contacts/contacts.contracts";
import { conversationListInput, conversationListOutput, builderListOutput, builderResourceSearchInput, builderResourcesOutput, conversationIdInput, builderConversationDetailOutput, conversationEventsInput, conversationEventsOutput, conversationSaveInput, conversationIdOutput, builderConversationCreateInput, builderConversationSubmitInput, builderQuestionResponseInput, builderApprovalResponseInput, builderPermissionModeInput, builderResponseRatingInput, builderResponseRatingOutput, conversationShareStatusOutput, conversationShareTokenOutput, sharedConversationInput, sharedConversationOutput } from "../conversations/conversations.contracts";
import { currencySettingsOutput, setReportingCurrencyInput, setManualRateInput, removeManualRateInput } from "../currency/currency.contracts";
@@ -158,6 +158,10 @@ const appRouter = t.router({
.input(companyCreateInput)
.output(companySummaryOutput)
.mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as any),
+ import: publicProcedure
+ .input(companyImportInput)
+ .output(companyImportOutput)
+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as any),
update: publicProcedure
.input(companyUpdateArgs)
.output(companySummaryOutput)
diff --git a/apps/api/test/agent-trigger-bulk.spec.ts b/apps/api/test/agent-trigger-bulk.spec.ts
new file mode 100644
index 00000000..78e18c46
--- /dev/null
+++ b/apps/api/test/agent-trigger-bulk.spec.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "bun:test";
+import type { Db, Prisma } from "@crm/db";
+import { AgentTriggerService } from "../src/agent/agent-trigger.service";
+
+function service() {
+ const writes: Prisma.AgentTaskCreateManyInput[][] = [];
+ const agentTask = {
+ createMany: async ({ data }: Prisma.AgentTaskCreateManyArgs) => {
+ const rows = Array.isArray(data) ? data : [data];
+ writes.push(rows);
+ return { count: rows.length };
+ },
+ };
+ const transaction = { agentTask } as unknown as Prisma.TransactionClient;
+ const db = {
+ agentTask,
+ $transaction: async <Result>(
+ work: (tx: Prisma.TransactionClient) => Promise<Result>,
+ ) => work(transaction),
+ } as unknown as Db;
+
+ return { trigger: new AgentTriggerService(db), writes };
+}
+
+describe("bulk agent task queues", () => {
+ it("writes CRM events in one batch", async () => {
+ const { trigger, writes } = service();
+
+ await trigger.withCrmEvents(async (_tx, emit) => {
+ for (let index = 0; index < 50; index += 1) {
+ await emit({
+ type: "company.created",
+ record: { kind: "company", id: `company-${index}` },
+ occurredAt: new Date("2026-10-22T00:00:00.000Z"),
+ data: { name: `Company ${index}`, domain: null },
+ });
+ }
+ });
+
+ expect(writes).toHaveLength(1);
+ expect(writes[0]).toHaveLength(50);
+ expect(writes[0]?.every((row) => row.kind === "agent-event")).toBe(true);
+ });
+
+ it("writes new-record field backfills in one batch", async () => {
+ const { trigger, writes } = service();
+ const ids = Array.from({ length: 50 }, (_, index) => `company-${index}`);
+
+ const result = await trigger.fieldBackfillNewRecords(
+ "COMPANY",
+ ["summary"],
+ ids,
+ "New record",
+ );
+
+ expect(result).toEqual({ queued: 50 });
+ expect(writes).toHaveLength(1);
+ expect(writes[0]).toHaveLength(50);
+ expect(writes[0]?.every((row) => row.kind === "field-backfill")).toBe(true);
+ });
+});
diff --git a/apps/api/test/company-import.spec.ts b/apps/api/test/company-import.spec.ts
new file mode 100644
index 00000000..f202e151
--- /dev/null
+++ b/apps/api/test/company-import.spec.ts
@@ -0,0 +1,157 @@
+import { afterAll, describe, expect, it } from "bun:test";
+import { db } from "@crm/db";
+import { AgentQueueService } from "../src/agent/agent-queue.service";
+import type {
+ AgentTriggerService,
+ CrmEventInput,
+} from "../src/agent/agent-trigger.service";
+import { CompaniesService } from "../src/companies/companies.service";
+import type { FaviconService } from "../src/companies/favicon.service";
+import { ActivityStampService } from "../src/crm/activity-stamp.service";
+import { ConversionService } from "../src/currency/conversion.service";
+import type { FieldsService } from "../src/fields/fields.service";
+
+const suffix = process.env.TEST_RUN_ID ?? "company-import-spec";
+const domain = `company-import-${suffix}.test`;
+const secondDomain = `second-company-import-${suffix}.test`;
+const importedIds: string[] = [];
+const events: CrmEventInput[] = [];
+const lifecycleIds: string[][] = [];
+const fieldBackfillIds: string[][] = [];
+
+const agent = {
+ companyCreated: async () => undefined,
+ companiesCreated: async (ids: string[]) => {
+ lifecycleIds.push(ids);
+ },
+ withCrmEvents: async <Result>(
+ work: (
+ tx: Parameters<Parameters<typeof db.$transaction>[0]>[0],
+ emit: (input: CrmEventInput) => Promise<void>,
+ ) => Promise<Result>,
+ ) =>
+ db.$transaction((tx) =>
+ work(tx, async (input) => {
+ events.push(input);
+ }),
+ ),
+} as unknown as AgentTriggerService;
+
+const fields = {
+ queueBackfillForNewRecords: async (_entity: string, ids: string[]) => {
+ fieldBackfillIds.push(ids);
+ },
+} as unknown as FieldsService;
+
+const favicon = {
+ backfill: async () => false,
+} as unknown as FaviconService;
+
+const companies = new CompaniesService(
+ db,
+ agent,
+ new AgentQueueService(db),
+ favicon,
+ new ActivityStampService(db),
+ new ConversionService(db),
+ fields,
+);
+
+async function clean() {
+ await db.agentTask.deleteMany({ where: { companyId: { in: importedIds } } });
+ await db.company.deleteMany({
+ where: { domain: { in: [domain, secondDomain] } },
+ });
+}
+
+afterAll(clean);
+
+describe("importing companies", () => {
+ it("normalizes domains and preserves the company creation lifecycle", async () => {
+ await clean();
+ events.length = 0;
+ lifecycleIds.length = 0;
+ fieldBackfillIds.length = 0;
+
+ const result = await companies.import({
+ rows: [
+ {
+ name: " Acme ",
+ website: `https://www.${domain}/pricing`,
+ industry: " Software ",
+ },
+ { name: "Second", website: secondDomain },
+ ],
+ });
+
+ const stored = await db.company.findMany({
+ where: { domain: { in: [domain, secondDomain] } },
+ orderBy: { name: "asc" },
+ select: {
+ id: true,
+ name: true,
+ domain: true,
+ website: true,
+ industry: true,
+ source: true,
+ enrichmentStatus: true,
+ },
+ });
+ importedIds.push(...stored.map((company) => company.id));
+ const [first, second] = stored;
+ if (!first || !second) {
+ throw new Error("The import did not create two companies.");
+ }
+
+ expect(stored).toHaveLength(2);
+ expect(result).toEqual({ created: 2, skipped: 0, skips: [] });
+ expect(stored).toEqual([
+ {
+ id: first.id,
+ name: "Acme",
+ domain,
+ website: `https://${domain}`,
+ industry: "Software",
+ source: "IMPORT",
+ enrichmentStatus: "PENDING",
+ },
+ {
+ id: second.id,
+ name: "Second",
+ domain: secondDomain,
+ website: `https://${secondDomain}`,
+ industry: null,
+ source: "IMPORT",
+ enrichmentStatus: "PENDING",
+ },
+ ]);
+ expect(events.map((event) => event.type)).toEqual([
+ "company.created",
+ "company.created",
+ ]);
+ expect(lifecycleIds).toEqual([stored.map((company) => company.id)]);
+ expect(fieldBackfillIds).toEqual([stored.map((company) => company.id)]);
+ });
+
+ it("skips blank, invalid, repeated, and existing company rows", async () => {
+ const result = await companies.import({
+ rows: [
+ { name: "", website: "blank.test" },
+ { name: "Invalid", website: "not a domain" },
+ { name: "Repeated", website: domain },
+ { name: "Repeated again", website: `https://${domain}` },
+ ],
+ });
+
+ expect(result).toEqual({
+ created: 0,
+ skipped: 4,
+ skips: [
+ { row: 2, reason: "A company needs a name." },
+ { row: 3, reason: '"not a domain" is not a valid domain.' },
+ { row: 4, reason: `${domain} already belongs to a company.` },
+ { row: 5, reason: `${domain} already belongs to a company.` },
+ ],
+ });
+ });
+});
diff --git a/apps/app/app/(app)/[slug]/companies/import-companies-link.tsx b/apps/app/app/(app)/[slug]/companies/import-companies-link.tsx
new file mode 100644
index 00000000..56f492e4
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/companies/import-companies-link.tsx
@@ -0,0 +1,30 @@
+import Upload from "@carbon/icons-react/es/Upload";
+import { Button } from "@crm/ui/components/button";
+import { Icon } from "@crm/ui/components/icon";
+import Link from "next/link";
+import { workspaceUrl } from "@/lib/workspace-url";
+
+export async function ImportCompaniesLink({
+ params,
+}: {
+ params: Promise<{ slug: string }>;
+}) {
+ const { slug } = await params;
+ return (
+ <Button asChild variant="outline">
+ <Link href={workspaceUrl(slug, "/companies/import")}>
+ <Icon icon={Upload} data-icon="inline-start" />
+ Import CSV
+ </Link>
+ </Button>
+ );
+}
+
+export function ImportCompaniesLinkFallback() {
+ return (
+ <Button variant="outline" disabled>
+ <Icon icon={Upload} data-icon="inline-start" />
+ Import CSV
+ </Button>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/companies/import/csv-import.test.ts b/apps/app/app/(app)/[slug]/companies/import/csv-import.test.ts
new file mode 100644
index 00000000..b8f382a3
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/companies/import/csv-import.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from "bun:test";
+import {
+ buildImportRows,
+ createInitialMapping,
+ parseCsv,
+ reduceImportWizard,
+} from "./csv-import";
+
+describe("company CSV parsing", () => {
+ it("parses quoted commas, escaped quotes, and quoted line breaks", () => {
+ expect(
+ parseCsv(
+ 'name,website,description\r\n"Acme, Inc.",https://acme.test,"A ""quoted""\nsummary"',
+ ),
+ ).toEqual({
+ headers: ["name", "website", "description"],
+ rows: [["Acme, Inc.", "https://acme.test", 'A "quoted"\nsummary']],
+ });
+ });
+
+ it("rejects files without headers or company rows", () => {
+ expect(() => parseCsv("\n\n")).toThrow("The CSV file has no headers.");
+ expect(() => parseCsv("name,website\n")).toThrow(
+ "The CSV file has no company rows.",
+ );
+ });
+
+ it("rejects malformed rows and unterminated quoted fields", () => {
+ expect(() => parseCsv("name,website\nAcme,acme.test,extra")).toThrow(
+ "Row 2 has 3 columns. The header has 2.",
+ );
+ expect(() => parseCsv('name\n"Acme')).toThrow(
+ "Row 2 has an unterminated quoted field.",
+ );
+ });
+
+ it("keeps blank lines so skipped row numbers match the source file", () => {
+ expect(parseCsv("name,website\nAcme,acme.test\n,\nBeta,beta.test")).toEqual(
+ {
+ headers: ["name", "website"],
+ rows: [
+ ["Acme", "acme.test"],
+ ["", ""],
+ ["Beta", "beta.test"],
+ ],
+ },
+ );
+ });
+});
+
+describe("company CSV mapping", () => {
+ it("keys repeated header labels by column index", () => {
+ const parsed = parseCsv("name,name,website\nAcme,Alias,acme.test");
+ const mapping = createInitialMapping(parsed.headers);
+
+ expect(mapping).toEqual(["name", null, "website"]);
+ expect(buildImportRows(parsed, mapping)).toEqual([
+ { name: "Acme", website: "acme.test" },
+ ]);
+ });
+
+ it("rejects duplicate destinations", () => {
+ const parsed = parseCsv("company,account\nAcme,Alias");
+ expect(() => buildImportRows(parsed, ["name", "name"])).toThrow(
+ "Each company field can use only one CSV column.",
+ );
+ });
+});
+
+describe("company import wizard", () => {
+ it("moves through mapping and results, then restores upload state", () => {
+ const parsed = parseCsv("name,website\nAcme,acme.test");
+ const mapping = createInitialMapping(parsed.headers);
+ const mapped = reduceImportWizard(
+ { step: "upload", message: "" },
+ { type: "file-loaded", parsed, mapping },
+ );
+ const result = reduceImportWizard(mapped, {
+ type: "import-finished",
+ result: { created: 1, skipped: 0, skips: [] },
+ });
+
+ expect(mapped.step).toBe("map");
+ expect(result.step).toBe("result");
+ expect(reduceImportWizard(result, { type: "restart" })).toEqual({
+ step: "upload",
+ message: "Choose a CSV file.",
+ });
+ });
+
+ it("keeps one destination when the user remaps a column", () => {
+ const parsed = parseCsv("name,company website\nAcme,acme.test");
+ const mapped = reduceImportWizard(
+ {
+ step: "map",
+ message: "Map the CSV columns.",
+ parsed,
+ mapping: ["name", "website"],
+ },
+ { type: "mapping-changed", column: 1, field: "name" },
+ );
+
+ expect(mapped.step).toBe("map");
+ if (mapped.step === "map") expect(mapped.mapping).toEqual([null, "name"]);
+ });
+});
diff --git a/apps/app/app/(app)/[slug]/companies/import/csv-import.ts b/apps/app/app/(app)/[slug]/companies/import/csv-import.ts
new file mode 100644
index 00000000..b990671c
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/companies/import/csv-import.ts
@@ -0,0 +1,263 @@
+import {
+ COMPANY_IMPORT,
+ type CompanyImportRow,
+ companyImportInput,
+} from "@crm/validation/company-import";
+
+export type ParsedCsv = {
+ headers: string[];
+ rows: string[][];
+};
+
+export type CompanyImportField = Exclude<keyof CompanyImportRow, undefined>;
+export type CompanyImportMapping = Array<CompanyImportField | null>;
+
+export type CompanyImportResult = {
+ created: number;
+ skipped: number;
+ skips: Array<{ row: number; reason: string }>;
+};
+
+export type ImportWizardState =
+ | { step: "upload"; message: string; error?: string }
+ | {
+ step: "map";
+ message: string;
+ parsed: ParsedCsv;
+ mapping: CompanyImportMapping;
+ error?: string;
+ }
+ | {
+ step: "result";
+ message: string;
+ result: CompanyImportResult;
+ };
+
+export type ImportWizardAction =
+ | {
+ type: "file-loaded";
+ parsed: ParsedCsv;
+ mapping: CompanyImportMapping;
+ }
+ | {
+ type: "mapping-changed";
+ column: number;
+ field: CompanyImportField | null;
+ }
+ | { type: "back" }
+ | { type: "failed"; message: string }
+ | { type: "import-finished"; result: CompanyImportResult }
+ | { type: "restart" };
+
+const HEADER_ALIASES = {
+ name: "name",
+ company: "name",
+ companyname: "name",
+ account: "name",
+ accountname: "name",
+ phone: "phone",
+ telephone: "phone",
+ mobile: "phone",
+ city: "city",
+ town: "city",
+ state: "stateCode",
+ statecode: "stateCode",
+ region: "stateCode",
+ province: "stateCode",
+ industry: "industry",
+ sector: "industry",
+ subindustry: "subIndustry",
+ subsector: "subIndustry",
+ vertical: "subIndustry",
+ website: "website",
+ url: "website",
+ domain: "website",
+ web: "website",
+ description: "description",
+ about: "description",
+ notes: "description",
+} as const satisfies Record<string, CompanyImportField>;
+
+export function parseCsv(text: string): ParsedCsv {
+ const records = parseRecords(text.replace(/^\uFEFF/, ""));
+ const [headerRecord, ...dataRecords] = records;
+ if (!headerRecord || headerRecord.every((field) => field.trim() === "")) {
+ throw new Error("The CSV file has no headers.");
+ }
+
+ const headers = headerRecord.map((header) => header.trim());
+ for (const [index, header] of headers.entries()) {
+ if (header === "") throw new Error(`Column ${index + 1} needs a header.`);
+ }
+
+ if (dataRecords.length === 0) {
+ throw new Error("The CSV file has no company rows.");
+ }
+ if (dataRecords.length > COMPANY_IMPORT.maxRows) {
+ throw new Error(
+ `The CSV file has ${dataRecords.length} rows. The limit is ${COMPANY_IMPORT.maxRows}.`,
+ );
+ }
+
+ for (const [index, row] of dataRecords.entries()) {
+ if (row.length !== headers.length) {
+ throw new Error(
+ `Row ${index + 2} has ${row.length} columns. The header has ${headers.length}.`,
+ );
+ }
+ }
+
+ return { headers, rows: dataRecords };
+}
+
+export function createInitialMapping(headers: string[]): CompanyImportMapping {
+ const used = new Set<CompanyImportField>();
+ return headers.map((header) => {
+ const key = header.toLowerCase().replace(/[^a-z]/g, "");
+ const field = HEADER_ALIASES[key as keyof typeof HEADER_ALIASES];
+ if (!field || used.has(field)) return null;
+ used.add(field);
+ return field;
+ });
+}
+
+export function buildImportRows(
+ parsed: ParsedCsv,
+ mapping: CompanyImportMapping,
+): CompanyImportRow[] {
+ if (mapping.length !== parsed.headers.length) {
+ throw new Error("Map every CSV column before importing.");
+ }
+
+ const mappedFields = mapping.filter(
+ (field): field is CompanyImportField => field !== null,
+ );
+ if (!mappedFields.includes("name")) {
+ throw new Error("Map one CSV column to Name before importing.");
+ }
+ if (new Set(mappedFields).size !== mappedFields.length) {
+ throw new Error("Each company field can use only one CSV column.");
+ }
+
+ const rows = parsed.rows.map((row) => {
+ const company: Partial<Record<CompanyImportField, string>> = {};
+ for (const [column, field] of mapping.entries()) {
+ if (field) company[field] = row[column] ?? "";
+ }
+ return company;
+ });
+
+ return companyImportInput.parse({ rows }).rows;
+}
+
+export function reduceImportWizard(
+ state: ImportWizardState,
+ action: ImportWizardAction,
+): ImportWizardState {
+ if (action.type === "file-loaded") {
+ return {
+ step: "map",
+ message: `${action.parsed.rows.length} company rows are ready to map.`,
+ parsed: action.parsed,
+ mapping: action.mapping,
+ };
+ }
+ if (action.type === "mapping-changed" && state.step === "map") {
+ const mapping = state.mapping.map((field, column) => {
+ if (column === action.column) return action.field;
+ if (action.field && field === action.field) return null;
+ return field;
+ });
+ return { ...state, mapping, error: undefined };
+ }
+ if (action.type === "back") {
+ return { step: "upload", message: "Choose a CSV file." };
+ }
+ if (action.type === "failed") {
+ return state.step === "result"
+ ? state
+ : { ...state, error: action.message };
+ }
+ if (action.type === "import-finished") {
+ return {
+ step: "result",
+ message: `${action.result.created} companies imported.`,
+ result: action.result,
+ };
+ }
+ if (action.type === "restart") {
+ return { step: "upload", message: "Choose a CSV file." };
+ }
+ return state;
+}
+
+function parseRecords(text: string): string[][] {
+ const records: string[][] = [];
+ let record: string[] = [];
+ let field = "";
+ let quoted = false;
+ let closedQuote = false;
+ let rowNumber = 1;
+
+ for (let index = 0; index < text.length; index += 1) {
+ const character = text[index] ?? "";
+ const next = text[index + 1];
+
+ if (quoted) {
+ if (character === '"' && next === '"') {
+ field += '"';
+ index += 1;
+ continue;
+ }
+ if (character === '"') {
+ quoted = false;
+ closedQuote = true;
+ continue;
+ }
+ field += character === "\r" && next === "\n" ? "\n" : character;
+ if (character === "\r" && next === "\n") index += 1;
+ continue;
+ }
+
+ if (
+ closedQuote &&
+ character !== "," &&
+ character !== "\n" &&
+ character !== "\r"
+ ) {
+ throw new Error(`Row ${rowNumber} has text after a quoted field.`);
+ }
+ if (character === '"') {
+ if (field !== "")
+ throw new Error(`Row ${rowNumber} has an unexpected quote.`);
+ quoted = true;
+ closedQuote = false;
+ continue;
+ }
+ if (character === ",") {
+ record.push(field);
+ field = "";
+ closedQuote = false;
+ continue;
+ }
+ if (character === "\n" || character === "\r") {
+ record.push(field);
+ records.push(record);
+ record = [];
+ field = "";
+ closedQuote = false;
+ rowNumber += 1;
+ if (character === "\r" && next === "\n") index += 1;
+ continue;
+ }
+ field += character;
+ }
+
+ if (quoted)
+ throw new Error(`Row ${rowNumber} has an unterminated quoted field.`);
+ if (field !== "" || record.length > 0) {
+ record.push(field);
+ records.push(record);
+ }
+ return records;
+}
diff --git a/apps/app/app/(app)/[slug]/companies/import/import-wizard.tsx b/apps/app/app/(app)/[slug]/companies/import/import-wizard.tsx
new file mode 100644
index 00000000..cdcffd31
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/companies/import/import-wizard.tsx
@@ -0,0 +1,450 @@
+"use client";
+
+import Upload from "@carbon/icons-react/es/Upload";
+import { Alert, AlertDescription, AlertTitle } from "@crm/ui/components/alert";
+import { Button } from "@crm/ui/components/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardPanel,
+ CardTitle,
+} from "@crm/ui/components/card";
+import {
+ Field,
+ FieldDescription,
+ FieldGroup,
+ FieldLabel,
+} from "@crm/ui/components/field";
+import { Icon } from "@crm/ui/components/icon";
+import { Input } from "@crm/ui/components/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@crm/ui/components/select";
+import { Spinner } from "@crm/ui/components/spinner";
+import {
+ Table,
+ TableBody,
+ TableCaption,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@crm/ui/components/table";
+import { COMPANY_IMPORT } from "@crm/validation/company-import";
+import { useMutation } from "@tanstack/react-query";
+import Link from "next/link";
+import { useId, useReducer, useState } from "react";
+import { useCrmCache } from "@/lib/trpc/cache";
+import { useTRPC } from "@/lib/trpc/client";
+import {
+ buildImportRows,
+ type CompanyImportField,
+ type CompanyImportMapping,
+ createInitialMapping,
+ parseCsv,
+ reduceImportWizard,
+} from "./csv-import";
+
+const IMPORT_FIELDS: Array<{
+ value: CompanyImportField;
+ label: string;
+}> = [
+ { value: "name", label: "Name" },
+ { value: "website", label: "Website or domain" },
+ { value: "phone", label: "Phone" },
+ { value: "city", label: "City" },
+ { value: "stateCode", label: "State or region" },
+ { value: "industry", label: "Industry" },
+ { value: "subIndustry", label: "Sub-industry" },
+ { value: "description", label: "Description" },
+];
+
+const FIELD_LABELS = new Map(
+ IMPORT_FIELDS.map((field) => [field.value, field.label]),
+);
+const SKIP = "skip";
+const PREVIEW_ROWS = 5;
+
+function focusElement(element: HTMLElement | null) {
+ element?.focus();
+}
+
+export function ImportWizard({ companiesUrl }: { companiesUrl: string }) {
+ const trpc = useTRPC();
+ const cache = useCrmCache();
+ const [state, dispatch] = useReducer(reduceImportWizard, {
+ step: "upload",
+ message: "Choose a CSV file.",
+ });
+ const [reading, setReading] = useState(false);
+
+ const importCompanies = useMutation(
+ trpc.companies.import.mutationOptions({
+ onSuccess: async (result) => {
+ if (result.created > 0) await cache.company();
+ dispatch({ type: "import-finished", result });
+ },
+ onError: (error) => dispatch({ type: "failed", message: error.message }),
+ }),
+ );
+
+ async function readFile(file: File) {
+ setReading(true);
+ try {
+ if (file.size > COMPANY_IMPORT.maxFileBytes) {
+ throw new Error("The CSV file is larger than 5 MB.");
+ }
+ if (!file.name.toLowerCase().endsWith(".csv")) {
+ throw new Error("Choose a file with a .csv extension.");
+ }
+ const parsed = parseCsv(await file.text());
+ dispatch({
+ type: "file-loaded",
+ parsed,
+ mapping: createInitialMapping(parsed.headers),
+ });
+ } catch (error) {
+ dispatch({
+ type: "failed",
+ message:
+ error instanceof Error
+ ? error.message
+ : "The CSV file cannot be read.",
+ });
+ } finally {
+ setReading(false);
+ }
+ }
+
+ function startImport() {
+ if (state.step !== "map") return;
+ try {
+ importCompanies.mutate({
+ rows: buildImportRows(state.parsed, state.mapping),
+ });
+ } catch (error) {
+ dispatch({
+ type: "failed",
+ message:
+ error instanceof Error
+ ? error.message
+ : "The column mapping is invalid.",
+ });
+ }
+ }
+
+ return (
+ <div className="flex w-full max-w-3xl flex-col gap-4">
+ <p className="sr-only" role="status" aria-live="polite">
+ {state.message}
+ </p>
+ {state.step === "upload" ? (
+ <UploadStep error={state.error} reading={reading} onFile={readFile} />
+ ) : null}
+ {state.step === "map" ? (
+ <MapStep
+ parsed={state.parsed}
+ mapping={state.mapping}
+ error={state.error}
+ pending={importCompanies.isPending}
+ onMappingChange={(column, field) =>
+ dispatch({ type: "mapping-changed", column, field })
+ }
+ onBack={() => dispatch({ type: "back" })}
+ onImport={startImport}
+ />
+ ) : null}
+ {state.step === "result" ? (
+ <ResultStep
+ result={state.result}
+ companiesUrl={companiesUrl}
+ onRestart={() => dispatch({ type: "restart" })}
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function UploadStep({
+ error,
+ reading,
+ onFile,
+}: {
+ error?: string;
+ reading: boolean;
+ onFile: (file: File) => Promise<void>;
+}) {
+ const inputId = useId();
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <h2 ref={focusElement} tabIndex={-1}>
+ Choose a CSV file
+ </h2>
+ </CardTitle>
+ <CardDescription>
+ The first row must contain column names. Files can contain 5,000
+ companies and must stay under 5 MB.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {error ? (
+ <Alert variant="destructive">
+ <AlertTitle>The file cannot be used</AlertTitle>
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ ) : null}
+ <FieldGroup>
+ <Field data-disabled={reading || undefined}>
+ <FieldLabel htmlFor={inputId}>CSV file</FieldLabel>
+ <Input
+ id={inputId}
+ type="file"
+ accept=".csv,text/csv"
+ disabled={reading}
+ onChange={(event) => {
+ const file = event.currentTarget.files?.[0];
+ event.currentTarget.value = "";
+ if (file) void onFile(file);
+ }}
+ />
+ <FieldDescription>
+ You can review every column before the import starts.
+ </FieldDescription>
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ {reading ? (
+ <CardFooter divider="none">
+ <Spinner /> Reading the file
+ </CardFooter>
+ ) : null}
+ </Card>
+ );
+}
+
+function MapStep({
+ parsed,
+ mapping,
+ error,
+ pending,
+ onMappingChange,
+ onBack,
+ onImport,
+}: {
+ parsed: { headers: string[]; rows: string[][] };
+ mapping: CompanyImportMapping;
+ error?: string;
+ pending: boolean;
+ onMappingChange: (column: number, field: CompanyImportField | null) => void;
+ onBack: () => void;
+ onImport: () => void;
+}) {
+ const mappedColumns = mapping.flatMap((field, column) =>
+ field ? [{ field, column, key: `${field}:${column}` }] : [],
+ );
+ const columns = parsed.headers.map((header, column) => ({
+ header,
+ column,
+ key: `${header}:${column}`,
+ }));
+ const previewRows = parsed.rows
+ .slice(0, PREVIEW_ROWS)
+ .map((row, rowIndex) => ({
+ row,
+ key: `${row.join("\u0000")}:${rowIndex}`,
+ }));
+ const hasName = mapping.includes("name");
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <h2 ref={focusElement} tabIndex={-1}>
+ Match the columns
+ </h2>
+ </CardTitle>
+ <CardDescription>
+ Each company field can use one CSV column. Name is required.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {error ? (
+ <Alert variant="destructive">
+ <AlertTitle>The import cannot start</AlertTitle>
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ ) : null}
+ <CardPanel size="content">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>CSV column</TableHead>
+ <TableHead>Company field</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {columns.map(({ header, column, key }) => {
+ const field = mapping[column] ?? null;
+ const selectId = `company-import-column-${column}`;
+ return (
+ <TableRow key={key}>
+ <TableCell>
+ <FieldLabel htmlFor={selectId}>{header}</FieldLabel>
+ </TableCell>
+ <TableCell>
+ <Select
+ value={field ?? SKIP}
+ onValueChange={(value) =>
+ onMappingChange(
+ column,
+ value === SKIP
+ ? null
+ : (value as CompanyImportField),
+ )
+ }
+ >
+ <SelectTrigger id={selectId} className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectItem value={SKIP}>Do not import</SelectItem>
+ {IMPORT_FIELDS.map((option) => (
+ <SelectItem
+ key={option.value}
+ value={option.value}
+ disabled={mapping.some(
+ (mapped, mappedColumn) =>
+ mappedColumn !== column &&
+ mapped === option.value,
+ )}
+ >
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </CardPanel>
+ {mappedColumns.length > 0 ? (
+ <CardPanel size="content">
+ <Table>
+ <TableCaption>
+ Previewing {Math.min(PREVIEW_ROWS, parsed.rows.length)} of{" "}
+ {parsed.rows.length} rows
+ </TableCaption>
+ <TableHeader>
+ <TableRow>
+ {mappedColumns.map(({ field, key }) => (
+ <TableHead key={key}>{FIELD_LABELS.get(field)}</TableHead>
+ ))}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {previewRows.map(({ row, key }) => (
+ <TableRow key={key}>
+ {mappedColumns.map(({ column, key: columnKey }) => (
+ <TableCell key={columnKey}>
+ {row[column] || "Empty"}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardPanel>
+ ) : null}
+ </CardContent>
+ <CardFooter>
+ <Button onClick={onImport} disabled={pending || !hasName}>
+ {pending ? <Spinner data-icon="inline-start" /> : null}
+ {pending ? "Importing" : `Import ${parsed.rows.length} companies`}
+ </Button>
+ <Button variant="outline" onClick={onBack} disabled={pending}>
+ Back
+ </Button>
+ </CardFooter>
+ </Card>
+ );
+}
+
+function ResultStep({
+ result,
+ companiesUrl,
+ onRestart,
+}: {
+ result: {
+ created: number;
+ skipped: number;
+ skips: Array<{ row: number; reason: string }>;
+ };
+ companiesUrl: string;
+ onRestart: () => void;
+}) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <h2 ref={focusElement} tabIndex={-1}>
+ Import complete
+ </h2>
+ </CardTitle>
+ <CardDescription>
+ {result.created} companies imported. {result.skipped} rows skipped.
+ </CardDescription>
+ </CardHeader>
+ {result.skips.length > 0 ? (
+ <CardContent>
+ <Alert>
+ <AlertTitle>Skipped rows</AlertTitle>
+ <AlertDescription>
+ Fix these rows in the CSV file before importing them again.
+ </AlertDescription>
+ </Alert>
+ <CardPanel size="content">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Row</TableHead>
+ <TableHead>Reason</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {result.skips.map((skip) => (
+ <TableRow key={skip.row}>
+ <TableCell>{skip.row}</TableCell>
+ <TableCell>{skip.reason}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardPanel>
+ </CardContent>
+ ) : null}
+ <CardFooter divider={result.skips.length > 0 ? "top" : "none"}>
+ <Button asChild>
+ <Link href={companiesUrl}>View companies</Link>
+ </Button>
+ <Button variant="outline" onClick={onRestart}>
+ <Icon icon={Upload} data-icon="inline-start" />
+ Import another file
+ </Button>
+ </CardFooter>
+ </Card>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/companies/import/page.tsx b/apps/app/app/(app)/[slug]/companies/import/page.tsx
new file mode 100644
index 00000000..a56dfb0d
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/companies/import/page.tsx
@@ -0,0 +1,46 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import {
+ PageShell,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellLoading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { workspaceUrl } from "@/lib/workspace-url";
+import { ImportWizard } from "./import-wizard";
+
+export const metadata: Metadata = {
+ title: "Import Companies",
+};
+
+export default function ImportCompaniesPage({
+ params,
+}: PageProps<"/[slug]/companies/import">) {
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Import companies</PageShellTitle>
+ <PageShellDescription>
+ Upload a CSV file and match its columns to company fields.
+ </PageShellDescription>
+ </PageShellHeading>
+ </PageShellHeader>
+ <PageShellContent>
+ <Suspense fallback={<PageShellLoading />}>
+ <ImportWizardForWorkspace params={params} />
+ </Suspense>
+ </PageShellContent>
+ </PageShell>
+ );
+}
+
+async function ImportWizardForWorkspace({
+ params,
+}: Pick<PageProps<"/[slug]/companies/import">, "params">) {
+ const { slug } = await params;
+ return <ImportWizard companiesUrl={workspaceUrl(slug, "/companies")} />;
+}
diff --git a/apps/app/app/(app)/[slug]/companies/page.tsx b/apps/app/app/(app)/[slug]/companies/page.tsx
index 95f0f247..943801e3 100644
--- a/apps/app/app/(app)/[slug]/companies/page.tsx
+++ b/apps/app/app/(app)/[slug]/companies/page.tsx
@@ -16,12 +16,17 @@ import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
import { companiesSearchParams } from "./companies-search-params";
import { CompaniesTable } from "./companies-table";
import { CreateCompanySheet } from "./create-company-sheet";
+import {
+ ImportCompaniesLink,
+ ImportCompaniesLinkFallback,
+} from "./import-companies-link";
export const metadata: Metadata = {
title: "Companies",
};
export default function CompaniesPage({
+ params,
searchParams,
}: PageProps<"/[slug]/companies">) {
return (
@@ -34,6 +39,9 @@ export default function CompaniesPage({
</PageShellDescription>
</PageShellHeading>
<PageShellActions>
+ <Suspense fallback={<ImportCompaniesLinkFallback />}>
+ <ImportCompaniesLink params={params} />
+ </Suspense>
<CreateCompanySheet />
</PageShellActions>
</PageShellHeader>
diff --git a/packages/db/src/idempotency.ts b/packages/db/src/idempotency.ts
index 4c7ac99c..bcd563df 100644
--- a/packages/db/src/idempotency.ts
+++ b/packages/db/src/idempotency.ts
@@ -1,4 +1,4 @@
-import type { Prisma } from "./generated/prisma/client";
+import { Prisma } from "./generated/prisma/client";
export async function lockIdempotencyKey(
tx: Prisma.TransactionClient,
@@ -8,3 +8,19 @@ export async function lockIdempotencyKey(
SELECT pg_advisory_xact_lock(hashtextextended(${key}, 0)) IS NULL AS locked
`;
}
+
+export async function lockIdempotencyKeys(
+ tx: Prisma.TransactionClient,
+ keys: string[],
+): Promise<void> {
+ const ordered = [...new Set(keys)].sort();
+ if (ordered.length === 0) return;
+
+ await tx.$queryRaw<Array<{ locked: boolean }>>`
+ SELECT pg_advisory_xact_lock(hashtextextended(requested.key, 0)) IS NULL AS locked
+ FROM (
+ VALUES ${Prisma.join(ordered.map((key) => Prisma.sql`(${key})`))}
+ ) AS requested(key)
+ ORDER BY requested.key
+ `;
+}
diff --git a/packages/validation/package.json b/packages/validation/package.json
index 58bc475a..26fe57a5 100644
--- a/packages/validation/package.json
+++ b/packages/validation/package.json
@@ -11,6 +11,7 @@
"./agent-manifest": "./src/agent-manifest.ts",
"./agent-permission": "./src/agent-permission.ts",
"./builder-question": "./src/builder-question.ts",
+ "./company-import": "./src/company-import.ts",
"./enrichment-queue": "./src/enrichment-queue.ts",
"./eve-stream": "./src/eve-stream.ts",
"./eve-public-event": "./src/eve-public-event.ts",
diff --git a/packages/validation/src/company-import.ts b/packages/validation/src/company-import.ts
new file mode 100644
index 00000000..e35cdc1e
--- /dev/null
+++ b/packages/validation/src/company-import.ts
@@ -0,0 +1,26 @@
+import { z } from "zod";
+
+export const COMPANY_IMPORT = {
+ maxFileBytes: 5 * 1024 * 1024,
+ maxRows: 5000,
+ faviconConcurrency: 8,
+} as const;
+
+export const companyImportRow = z.object({
+ name: z.string(),
+ phone: z.string().optional(),
+ city: z.string().optional(),
+ stateCode: z.string().optional(),
+ industry: z.string().optional(),
+ subIndustry: z.string().optional(),
+ website: z.string().optional(),
+ description: z.string().optional(),
+});
+
+export type CompanyImportRow = z.infer<typeof companyImportRow>;
+
+export const companyImportInput = z.object({
+ rows: z.array(companyImportRow).min(1).max(COMPANY_IMPORT.maxRows),
+});
+
+export type CompanyImportInput = z.infer<typeof companyImportInput>;