All files / services/crm leads-helpers.ts

100% Statements 24/24
100% Branches 36/36
100% Functions 4/4
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154                          5x 5x 5x 5x   5x                                                                     17x 10x                   10x       18x 2x             16x 2x                                 9x 9x                                 9x     9x   9x 1x               9x         4x     4x         4x                       9x    
// Pure constants, types, and helpers shared by LeadsService.
// Extracted to keep the class focused on DAL orchestration.
 
import type { NewLeadActivity } from "../../db/schema";
import {
	LEAD_PROJECT_TYPES,
	LEAD_BUDGET_RANGES,
	LOSS_REASONS,
	CONTACT_METHODS,
} from "../../db/schema/enums";
import { ValidationError } from "../../lib/errors";
import { generateId } from "../../lib/utils";
 
export const VALID_PROJECT_TYPES = new Set<string>(LEAD_PROJECT_TYPES);
export const VALID_BUDGET_RANGES = new Set<string>(LEAD_BUDGET_RANGES);
export const VALID_LOSS_REASONS = new Set<string>(LOSS_REASONS);
export const VALID_CONTACT_METHODS = new Set<string>(CONTACT_METHODS);
 
export const LOSS_REASON_LABELS: Record<string, string> = {
	budget_constraints: "Budget Constraints",
	chose_competitor: "Chose Competitor",
	project_cancelled: "Project Cancelled",
	not_responding: "Not Responding",
	timeline_mismatch: "Timeline Mismatch",
	design_preferences: "Design Preferences",
	scope_change: "Scope Change",
	other: "Other",
};
 
export type CreateLeadInput = {
	customerName: string;
	phone: string;
	email?: string;
	location?: string;
	leadSourceId: number;
	projectType?: string;
	budgetRange?: string;
	requirement?: string;
};
 
export type CreateFromInquiryInput = {
	customerName: string;
	customerPhone: string;
	customerEmail?: string;
	customerLocation?: string;
	requirement?: string;
	requirementType?: string;
	inquiryId: number;
};
 
export function mapRequirementToProjectType(
	requirementType?: string,
): (typeof LEAD_PROJECT_TYPES)[number] | undefined {
	if (!requirementType) return undefined;
	const mapping: Record<string, (typeof LEAD_PROJECT_TYPES)[number]> = {
		modular_kitchen: "modular_kitchen",
		full_home_interior: "full_interior",
		full_office_interior: "full_interior",
		wardrobes_storage: "wardrobe",
		living_room: "full_interior",
		bedroom: "full_interior",
		pooja_room: "pooja_unit",
		other: "other",
	};
	return mapping[requirementType];
}
 
export function validateProjectType(type: string | undefined | null): void {
	if (type !== undefined && type !== null && !VALID_PROJECT_TYPES.has(type)) {
		throw new ValidationError(
			`Invalid project type. Allowed: ${LEAD_PROJECT_TYPES.join(", ")}`,
		);
	}
}
 
export function validateBudgetRange(range: string | undefined | null): void {
	if (range !== undefined && range !== null && !VALID_BUDGET_RANGES.has(range)) {
		throw new ValidationError(
			`Invalid budget range. Allowed: ${LEAD_BUDGET_RANGES.join(", ")}`,
		);
	}
}
 
type StageRef = { name: string; stageType: string } | undefined;
 
/** Build the NewLeadActivity array for a stage-change event. */
export function buildStageChangeActivities(
	leadId: number,
	newStageId: number,
	currentStageId: number,
	oldStage: StageRef,
	newStage: { name: string; stageType: string },
	options?: { lossReasonCategory?: string; lossReason?: string },
): NewLeadActivity[] {
	const groupId = generateId();
	const activities: NewLeadActivity[] = [
		{
			leadId,
			activityType: "stage_changed",
			content: `Stage changed from "${oldStage?.name ?? "Unknown"}" to "${newStage.name}"`,
			metadataJson: {
				fromStageId: currentStageId,
				toStageId: newStageId,
				fromStageName: oldStage?.name,
				toStageName: newStage.name,
			},
			groupId,
		},
	];
 
	// Detect reopening (terminal → non-terminal)
	const wasTerminal =
		oldStage?.stageType === "system_terminal_won" ||
		oldStage?.stageType === "system_terminal_lost";
	const isNonTerminal =
		newStage.stageType !== "system_terminal_won" &&
		newStage.stageType !== "system_terminal_lost";
	if (wasTerminal && isNonTerminal) {
		activities.push({
			leadId,
			activityType: "lead_reopened",
			content: `Lead reopened from "${oldStage?.name}"`,
			groupId,
		});
	}
 
	if (
		newStage.stageType === "system_terminal_lost" &&
		(options?.lossReasonCategory || options?.lossReason)
	) {
		// Category is validated against VALID_LOSS_REASONS, so it's always in LOSS_REASON_LABELS
		const categoryLabel = options?.lossReasonCategory
			? LOSS_REASON_LABELS[options.lossReasonCategory]
			: undefined;
		const content = categoryLabel
			? options?.lossReason
				? `${categoryLabel}: ${options.lossReason}`
				: categoryLabel
			: /* v8 ignore next */ options?.lossReason ?? "";
		activities.push({
			leadId,
			activityType: "loss_reason_recorded",
			content,
			metadataJson: {
				lossReasonCategory: options?.lossReasonCategory ?? null,
				lossReason: options?.lossReason ?? null,
			},
			groupId,
		});
	}
 
	return activities;
}