Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions apps/api/src/controllers/crm-custom-fields.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import type { Context } from "hono";
import type {
CreateCustomFieldDefinitionInput,
CustomFieldEntityType,
UpdateCustomFieldDefinitionInput,
} from "@workspace/validators/schemas/crm";
import { and, asc, eq } from "drizzle-orm";
import { STATUS_CODES } from "@/constants/status-codes.js";
import { db } from "@/db/client.js";
import { crmCustomFieldDefinitions } from "@/db/schema/index.js";
import { sendSuccess } from "@/lib/api-response.js";
import { AppError } from "@/lib/app-error.js";
import { getSessionWorkspaceId } from "@/lib/workspace.js";
import {
assertLabelUnique,
buildUpdatedSelectOptions,
clearFieldValues,
clearOptionValue,
normalizeOptions,
} from "@/utils/crm-custom-fields.js";

export async function listCustomFieldDefinitions(c: Context, entityType: CustomFieldEntityType) {
const workspaceId = getSessionWorkspaceId(c);

const customFields = await db
.select()
.from(crmCustomFieldDefinitions)
.where(
and(
eq(crmCustomFieldDefinitions.workspaceId, workspaceId),
eq(crmCustomFieldDefinitions.entityType, entityType),
),
)
.orderBy(asc(crmCustomFieldDefinitions.createdAt));

return sendSuccess(c, { customFields }, STATUS_CODES.OK);
}

export async function createCustomFieldDefinition(
c: Context,
entityType: CustomFieldEntityType,
payload: CreateCustomFieldDefinitionInput,
) {
const workspaceId = getSessionWorkspaceId(c);

const label = payload.label.trim();
await assertLabelUnique(workspaceId, entityType, label);

const options = payload.type === "select" ? normalizeOptions(payload.options) : [];

const [customField] = await db
.insert(crmCustomFieldDefinitions)
.values({
workspaceId,
entityType,
label,
fieldType: payload.type,
options,
})
.returning();

return sendSuccess(c, { customField }, STATUS_CODES.CREATED);
}

export async function updateCustomFieldDefinition(
c: Context,
entityType: CustomFieldEntityType,
id: string,
payload: UpdateCustomFieldDefinitionInput,
) {
const workspaceId = getSessionWorkspaceId(c);

const existing = await db.query.crmCustomFieldDefinitions.findFirst({
where: and(
eq(crmCustomFieldDefinitions.id, id),
eq(crmCustomFieldDefinitions.workspaceId, workspaceId),
eq(crmCustomFieldDefinitions.entityType, entityType),
),
});

if (!existing) {
throw new AppError("Custom field definition not found", STATUS_CODES.NOT_FOUND);
}

const updates: {
label?: string;
options?: { id: string; label: string }[];
updatedAt: Date;
} = {
updatedAt: new Date(),
};

if (payload.label !== undefined) {
const label = payload.label.trim();
await assertLabelUnique(workspaceId, entityType, label, id);
updates.label = label;
}

let removedOptionIds: string[] = [];
if (payload.options !== undefined) {
if (existing.fieldType !== "select") {
throw new AppError(
"Only select custom fields can update options",
STATUS_CODES.UNPROCESSABLE_ENTITY,
);
}

const selectOptionsResult = buildUpdatedSelectOptions(existing.options ?? [], payload.options);
removedOptionIds = selectOptionsResult.removedOptionIds;
updates.options = selectOptionsResult.options;
}

const customField = await db.transaction(async (tx) => {
const [updated] = await tx
.update(crmCustomFieldDefinitions)
.set(updates)
.where(
and(
eq(crmCustomFieldDefinitions.id, id),
eq(crmCustomFieldDefinitions.workspaceId, workspaceId),
eq(crmCustomFieldDefinitions.entityType, entityType),
),
)
.returning();

for (const optionId of removedOptionIds) {
await clearOptionValue(entityType, workspaceId, id, optionId, tx);
}

return updated;
});

return sendSuccess(c, { customField }, STATUS_CODES.OK);
}

export async function deleteCustomFieldDefinition(
c: Context,
entityType: CustomFieldEntityType,
id: string,
) {
const workspaceId = getSessionWorkspaceId(c);

const customField = await db.transaction(async (tx) => {
const [deleted] = await tx
.delete(crmCustomFieldDefinitions)
.where(
and(
eq(crmCustomFieldDefinitions.id, id),
eq(crmCustomFieldDefinitions.workspaceId, workspaceId),
eq(crmCustomFieldDefinitions.entityType, entityType),
),
)
.returning();

if (!deleted) {
throw new AppError("Custom field definition not found", STATUS_CODES.NOT_FOUND);
}

await clearFieldValues(entityType, workspaceId, id, tx);

return deleted;
});

return sendSuccess(c, { customField }, STATUS_CODES.OK);
}
13 changes: 4 additions & 9 deletions apps/api/src/controllers/deals.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Context } from "hono";
import type { CreateDeal, ListDealsQuery, UpdateDeal } from "@workspace/validators/schemas/crm";
import { and, asc, count, desc, eq, ilike, or } from "drizzle-orm";
import { db } from "@/db/client.js";
import { deals, orgs, people, user } from "@/db/schema/index.js";
import { deals, org, people, user } from "@/db/schema/index.js";
import { STATUS_CODES } from "@/constants/status-codes.js";
import { sendSuccess } from "@/lib/api-response.js";
import { AppError } from "@/lib/app-error.js";
Expand Down Expand Up @@ -58,12 +58,12 @@ export async function listDeals(c: Context, query: ListDealsQuery) {
closeDate: deals.closeDate,
createdAt: deals.createdAt,
updatedAt: deals.updatedAt,
orgName: orgs.name,
orgName: org.name,
personName: people.name,
ownerName: user.name,
})
.from(deals)
.leftJoin(orgs, eq(deals.orgId, orgs.id))
.leftJoin(org, eq(deals.orgId, org.id))
.leftJoin(people, eq(deals.personId, people.id))
.leftJoin(user, eq(deals.ownerId, user.id))
.where(whereClause)
Expand All @@ -79,12 +79,7 @@ export async function listDeals(c: Context, query: ListDealsQuery) {
return sendSuccess(
c,
{
deals: results.map((deal) => ({
...deal,
orgName: deal.orgName ?? null,
personName: deal.personName ?? null,
ownerName: deal.ownerName ?? null,
})),
deals: results,
meta: {
page,
pageSize,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type {
} from "@workspace/validators/schemas/crm";
import { and, asc, count, desc, eq, ilike, inArray, or } from "drizzle-orm";
import { db } from "@/db/client.js";
import { orgs, people } from "@/db/schema/index.js";
import { org, people } from "@/db/schema/index.js";
import { STATUS_CODES } from "@/constants/status-codes.js";
import { sendSuccess } from "@/lib/api-response.js";
import { AppError } from "@/lib/app-error.js";
Expand All @@ -17,18 +17,18 @@ export async function listOrgs(c: Context, query: ListOrgsQuery) {
const workspaceId = getSessionWorkspaceId(c);
const { page, pageSize, sortOrder, sortBy, search, industry, size } = query;

const conditions = [eq(orgs.workspaceId, workspaceId)];
if (industry) conditions.push(eq(orgs.industry, industry));
if (size) conditions.push(eq(orgs.size, size));
const conditions = [eq(org.workspaceId, workspaceId)];
if (industry) conditions.push(eq(org.industry, industry));
if (size) conditions.push(eq(org.size, size));
if (search) {
const searchTerm = `%${search}%`;
conditions.push(
or(
ilike(orgs.name, searchTerm),
ilike(orgs.domain, searchTerm),
ilike(orgs.industry, searchTerm),
ilike(orgs.size, searchTerm),
ilike(orgs.location, searchTerm),
ilike(org.name, searchTerm),
ilike(org.domain, searchTerm),
ilike(org.industry, searchTerm),
ilike(org.size, searchTerm),
ilike(org.location, searchTerm),
)!,
);
}
Expand All @@ -39,32 +39,32 @@ export async function listOrgs(c: Context, query: ListOrgsQuery) {
const orderBy = (() => {
switch (sortBy) {
case "domain":
return direction(orgs.domain);
return direction(org.domain);
case "industry":
return direction(orgs.industry);
return direction(org.industry);
case "size":
return direction(orgs.size);
return direction(org.size);
case "location":
return direction(orgs.location);
return direction(org.location);
case "createdAt":
return direction(orgs.createdAt);
return direction(org.createdAt);
case "updatedAt":
return direction(orgs.updatedAt);
return direction(org.updatedAt);
case "name":
default:
return direction(orgs.name);
return direction(org.name);
}
})();

const [rows, totalCountResult, peopleCounts] = await Promise.all([
db
.select()
.from(orgs)
.from(org)
.where(whereClause)
.orderBy(orderBy)
.limit(pageSize)
.offset((page - 1) * pageSize),
db.select({ totalCount: count() }).from(orgs).where(whereClause),
db.select({ totalCount: count() }).from(org).where(whereClause),
db
.select({ orgId: people.orgId, count: count() })
.from(people)
Expand All @@ -79,7 +79,7 @@ export async function listOrgs(c: Context, query: ListOrgsQuery) {
return sendSuccess(
c,
{
orgs: rows.map((org) => ({ ...org, peopleCount: peopleCountMap.get(org.id) ?? 0 })),
org: rows.map((o) => ({ ...o, peopleCount: peopleCountMap.get(o.id) ?? 0 })),
meta: { page, pageSize, totalCount, totalPages },
},
STATUS_CODES.OK,
Expand All @@ -88,8 +88,8 @@ export async function listOrgs(c: Context, query: ListOrgsQuery) {

export async function getOrg(c: Context, id: string) {
const workspaceId = getSessionWorkspaceId(c);
const org = await db.query.orgs.findFirst({
where: and(eq(orgs.id, id), eq(orgs.workspaceId, workspaceId)),
const result = await db.query.org.findFirst({
where: and(eq(org.id, id), eq(org.workspaceId, workspaceId)),
with: {
people: {
columns: {
Expand All @@ -100,64 +100,64 @@ export async function getOrg(c: Context, id: string) {
},
});

if (!org) {
if (!result) {
throw new AppError("Organization not found", STATUS_CODES.NOT_FOUND);
}

return sendSuccess(c, { org }, STATUS_CODES.OK);
return sendSuccess(c, { org: result }, STATUS_CODES.OK);
}

export async function createOrg(c: Context, payload: CreateOrg) {
const workspaceId = getSessionWorkspaceId(c);
const [org] = await db
.insert(orgs)
const [result] = await db
.insert(org)
.values({
...payload,
workspaceId,
})
.returning();

return sendSuccess(c, { org }, STATUS_CODES.CREATED);
return sendSuccess(c, { org: result }, STATUS_CODES.CREATED);
}

export async function updateOrg(c: Context, id: string, payload: UpdateOrg) {
const workspaceId = getSessionWorkspaceId(c);
const [org] = await db
.update(orgs)
const [result] = await db
.update(org)
.set({
...payload,
updatedAt: new Date(),
})
.where(and(eq(orgs.id, id), eq(orgs.workspaceId, workspaceId)))
.where(and(eq(org.id, id), eq(org.workspaceId, workspaceId)))
.returning();

if (!org) {
if (!result) {
throw new AppError("Organization not found", STATUS_CODES.NOT_FOUND);
}

return sendSuccess(c, { org }, STATUS_CODES.OK);
return sendSuccess(c, { org: result }, STATUS_CODES.OK);
}

export async function deleteOrg(c: Context, id: string) {
const workspaceId = getSessionWorkspaceId(c);
const [org] = await db
.delete(orgs)
.where(and(eq(orgs.id, id), eq(orgs.workspaceId, workspaceId)))
const [result] = await db
.delete(org)
.where(and(eq(org.id, id), eq(org.workspaceId, workspaceId)))
.returning();

if (!org) {
if (!result) {
throw new AppError("Organization not found", STATUS_CODES.NOT_FOUND);
}

return sendSuccess(c, { org }, STATUS_CODES.OK);
return sendSuccess(c, { org: result }, STATUS_CODES.OK);
}

export async function bulkDeleteOrgs(c: Context, payload: BulkDeleteInput) {
const workspaceId = getSessionWorkspaceId(c);
const deletedOrgs = await db
.delete(orgs)
.where(and(eq(orgs.workspaceId, workspaceId), inArray(orgs.id, payload.ids)))
.returning({ id: orgs.id });
const deleted = await db
.delete(org)
.where(and(eq(org.workspaceId, workspaceId), inArray(org.id, payload.ids)))
.returning({ id: org.id });

return sendSuccess(c, { deleted: deletedOrgs.length }, STATUS_CODES.OK);
return sendSuccess(c, { deleted: deleted.length }, STATUS_CODES.OK);
}
Loading
Loading