All files / services/crm leads.service.ts

99.41% Statements 170/171
98.66% Branches 148/150
100% Functions 24/24
99.38% Lines 162/163

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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603                                          5x 5x 5x 5x   5x                                                                 92x     4x             4x 4x 2x       4x   4x             4x 4x 4x 4x               4x 10x                   48x 48x 7x   41x               7x 5x 3x   2x         14x 1x   13x 1x               12x     14x 1x       11x 11x 1x           10x 10x 2x       8x 1x       7x 1x           6x 6x 6x 1x     5x                           5x           5x           17x 10x                   10x               20x 20x 1x             19x                     20x 19x 19x   18x 18x 18x   18x   17x                         17x             17x                                   11x     10x         1x       9x         1x         8x 8x 1x 8x 8x 8x 8x 2x 8x 2x 8x 8x   8x 8x 1x   7x                       14x   14x 1x     13x 13x         2x     11x       11x         11x       1x       11x 5x 3x 1x       2x   4x 3x         10x         1x 1x     10x 10x 1x       9x 9x                                 14x     14x   14x 1x                 9x         4x     4x         4x                       9x   9x             4x   3x 1x         2x       2x 1x     1x             1x       3x   2x       2x 1x     1x           1x       3x   2x       2x 1x     1x           1x       2x 2x   2x     2x 1x     1x             1x       2x 2x   2x     2x 1x     1x             1x                   3x 3x 3x       3x 1x                
// Leads Service - Business Logic Layer
import type { Dal } from "../../dal";
import type { Lead, NewLeadActivity } from "../../db/schema";
import {
	ConflictError,
	ForbiddenError,
	NotFoundError,
	ValidationError,
} from "../../lib/errors";
import {
	LEAD_PROJECT_TYPES,
	LEAD_BUDGET_RANGES,
	LOSS_REASONS,
	CONTACT_METHODS,
} from "../../db/schema/enums";
import {
	normalizeToE164,
	normalizeInternationalToE164,
} from "@interioring/utils/validation/phone";
import { generateId } from "../../lib/utils";
 
const VALID_PROJECT_TYPES = new Set<string>(LEAD_PROJECT_TYPES);
const VALID_BUDGET_RANGES = new Set<string>(LEAD_BUDGET_RANGES);
const VALID_LOSS_REASONS = new Set<string>(LOSS_REASONS);
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 class LeadsService {
	constructor(private dal: Dal) {}
 
	async getKanbanData(proId: string) {
		const [leads, stages, stageCounts, stageValues] = await Promise.all([
			this.dal.leads.getKanbanData(proId),
			this.dal.pipelineStages.findByProId(proId),
			this.dal.leads.countByStage(proId),
			this.dal.leads.getStageValueSums(proId),
		]);
 
		const countMap = new Map(stageCounts.map((s) => [s.stageId, s.count]));
		const valueMap = new Map(
			stageValues.map((s) => [s.stageId, s.totalQuoteValue]),
		);
 
		// Enrich leads with reminder/document counts for kanban cards
		const leadIds = leads.map((l) => l.id);
		const [reminderStats, documentCounts] =
			leadIds.length > 0
				? await Promise.all([
						this.dal.leads.getReminderStatsForLeads(proId, leadIds),
						this.dal.leads.getDocumentCountsForLeads(leadIds),
					])
				: [new Map(), new Map()];
 
		const enrichedLeads = leads.map((lead) => {
			const reminderStat = reminderStats.get(lead.id);
			const docCount = documentCounts.get(lead.id);
			return {
				...lead,
				reminderCount: reminderStat?.count ?? 0,
				nextReminderDueAt: reminderStat?.nextDueAt ?? null,
				documentCount: docCount ?? 0,
			};
		});
 
		return {
			stages: stages.map((stage) => ({
				...stage,
				leadCount: countMap.get(stage.id) ?? 0,
				totalValue: valueMap.get(stage.id) ?? 0,
			})),
			leads: enrichedLeads,
		};
	}
 
	async getById(leadId: number): Promise<Lead> {
		const lead = await this.dal.leads.findById(leadId);
		if (!lead) {
			throw new NotFoundError("Lead", String(leadId));
		}
		return lead;
	}
 
	/**
	 * Verify that a lead belongs to the given pro.
	 * Returns the lead if ownership is verified; throws ForbiddenError otherwise.
	 */
	async verifyProOwnership(leadId: number, proId: string): Promise<Lead> {
		const lead = await this.getById(leadId);
		if (lead.proId !== proId) {
			throw new ForbiddenError("Lead does not belong to this pro");
		}
		return lead;
	}
 
	async createManual(proId: string, input: CreateLeadInput): Promise<Lead> {
		// Validate required fields
		if (!input.customerName?.trim()) {
			throw new ValidationError("Customer name is required");
		}
		if (!input.phone?.trim()) {
			throw new ValidationError("Phone number is required");
		}
 
		// The route's Zod schema (createLeadSchema, internationalPhoneSchema)
		// already validates and normalizes to E.164. Re-parse defensively in
		// case this service is invoked from a non-route path that didn't go
		// through Zod. Try Indian first (covers legacy 10-digit input),
		// then international (covers +1, +971, etc.).
		const phone =
			normalizeToE164(input.phone) ??
			normalizeInternationalToE164(input.phone);
		if (!phone) {
			throw new ValidationError("Invalid phone number");
		}
 
		// Phone dedup check
		const existing = await this.dal.leads.findByPhone(proId, phone);
		if (existing) {
			throw new ConflictError(
				`A lead with phone ${phone} already exists: ${existing.customerName}`,
			);
		}
 
		// Validate source exists
		const source = await this.dal.leadSources.findById(input.leadSourceId);
		if (!source || source.proId !== proId) {
			throw new ValidationError("Invalid lead source");
		}
 
		// Validate enum fields
		if (input.projectType && !VALID_PROJECT_TYPES.has(input.projectType)) {
			throw new ValidationError(
				`Invalid project type. Allowed: ${LEAD_PROJECT_TYPES.join(", ")}`,
			);
		}
		if (input.budgetRange && !VALID_BUDGET_RANGES.has(input.budgetRange)) {
			throw new ValidationError(
				`Invalid budget range. Allowed: ${LEAD_BUDGET_RANGES.join(", ")}`,
			);
		}
 
		// Get the "New" (entry) stage
		const stages = await this.dal.pipelineStages.findByProId(proId);
		const entryStage = stages.find((s) => s.stageType === "system_entry");
		if (!entryStage) {
			throw new ValidationError("Pipeline not initialized");
		}
 
		const lead = await this.dal.leads.create({
			proId,
			currentStageId: entryStage.id,
			leadSourceId: input.leadSourceId,
			customerName: input.customerName.trim(),
			phone,
			email: input.email?.trim(),
			location: input.location?.trim(),
			projectType: input.projectType as Lead["projectType"],
			budgetRange: input.budgetRange as Lead["budgetRange"],
			requirement: input.requirement?.trim(),
		});
 
		// Log activity
		await this.dal.leadActivities.create({
			leadId: lead.id,
			activityType: "lead_created_manual",
			content: `Lead created manually`,
		});
 
		return lead;
	}
 
	private 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];
	}
 
	async createFromInquiry(
		proId: string,
		input: CreateFromInquiryInput,
	): Promise<Lead | null> {
		// Check if pro has CRM initialized
		const stageCount = await this.dal.pipelineStages.countByProId(proId);
		if (stageCount === 0) {
			return null; // Pro hasn't used CRM yet
		}
 
		// Inquiry-sourced leads come from already-validated routes (E.164),
		// but defensively re-parse so legacy/un-migrated values are still
		// stored consistently. Falls back to digit-strip on parse failure
		// to preserve the prior tolerant behavior.
		const phone =
			normalizeToE164(input.customerPhone) ??
			input.customerPhone.replace(/\D/g, "");
 
		// Intentionally skips phone dedup (unlike createManual):
		// Each marketplace inquiry is a distinct opportunity, even from the
		// same customer. Pros see duplicate leads and can merge manually.
		// This prevents silently losing new inquiries when a returning
		// customer submits again.
 
		// Get entry stage and marketplace source
		const stages = await this.dal.pipelineStages.findByProId(proId);
		const entryStage = stages.find((s) => s.stageType === "system_entry");
		if (!entryStage) return null;
 
		const sources = await this.dal.leadSources.findActiveByProId(proId);
		const marketplaceSource = sources.find(
			(s) => s.isSystem && s.name === "Interioring Marketplace",
		);
		if (!marketplaceSource) return null;
 
		const lead = await this.dal.leads.create({
			proId,
			currentStageId: entryStage.id,
			leadSourceId: marketplaceSource.id,
			customerName: input.customerName,
			phone,
			email: input.customerEmail,
			location: input.customerLocation,
			projectType: this.mapRequirementToProjectType(input.requirementType),
			requirement: input.requirement,
			inquiryId: input.inquiryId,
		});
 
		await this.dal.leadActivities.create({
			leadId: lead.id,
			activityType: "lead_created_auto",
			content: "Lead auto-created from Interioring Marketplace inquiry",
			metadataJson: { inquiryId: input.inquiryId },
		});
 
		return lead;
	}
 
	async update(
		leadId: number,
		updates: Partial<
			Pick<
				Lead,
				| "customerName"
				| "phone"
				| "email"
				| "location"
				| "projectType"
				| "budgetRange"
				| "requirement"
			>
		>,
	): Promise<Lead> {
		await this.getById(leadId); // Existence check
 
		// Validate enum fields
		if (
			updates.projectType !== undefined &&
			updates.projectType !== null &&
			!VALID_PROJECT_TYPES.has(updates.projectType)
		) {
			throw new ValidationError(
				`Invalid project type. Allowed: ${LEAD_PROJECT_TYPES.join(", ")}`,
			);
		}
		if (
			updates.budgetRange !== undefined &&
			updates.budgetRange !== null &&
			!VALID_BUDGET_RANGES.has(updates.budgetRange)
		) {
			throw new ValidationError(
				`Invalid budget range. Allowed: ${LEAD_BUDGET_RANGES.join(", ")}`,
			);
		}
 
		const data: Record<string, unknown> = {};
		if (updates.customerName !== undefined)
			data.customerName = updates.customerName.trim();
		if (updates.email !== undefined) data.email = updates.email?.trim() || null;
		if (updates.location !== undefined)
			data.location = updates.location?.trim() || null;
		if (updates.projectType !== undefined)
			data.projectType = updates.projectType;
		if (updates.budgetRange !== undefined)
			data.budgetRange = updates.budgetRange;
		if (updates.requirement !== undefined)
			data.requirement = updates.requirement?.trim() || null;
 
		const updated = await this.dal.leads.update(leadId, data);
		if (!updated) {
			throw new NotFoundError("Lead", String(leadId));
		}
		return updated;
	}
 
	async changeStage(
		leadId: number,
		newStageId: number,
		options?: {
			orderValuePaise?: number;
			lossReason?: string;
			lossReasonCategory?: string;
		},
	): Promise<Lead> {
		const lead = await this.getById(leadId);
 
		if (lead.currentStageId === newStageId) {
			return lead; // No change needed
		}
 
		const newStage = await this.dal.pipelineStages.findById(newStageId);
		if (
			!newStage ||
			newStage.deletedAt ||
			newStage.proId !== lead.proId
		) {
			throw new ValidationError("Invalid target stage");
		}
 
		const oldStage = await this.dal.pipelineStages.findById(
			lead.currentStageId,
		);
 
		const updateData: Record<string, unknown> = {
			currentStageId: newStageId,
		};
 
		// Won stage: capture order value
		if (
			newStage.stageType === "system_terminal_won" &&
			options?.orderValuePaise !== undefined
		) {
			updateData.orderValuePaise = options.orderValuePaise;
		}
 
		// Lost stage: capture loss reason category + detail
		if (newStage.stageType === "system_terminal_lost") {
			if (options?.lossReasonCategory) {
				if (!VALID_LOSS_REASONS.has(options.lossReasonCategory)) {
					throw new ValidationError(
						`Invalid loss reason. Allowed: ${LOSS_REASONS.join(", ")}`,
					);
				}
				updateData.lossReasonCategory = options.lossReasonCategory;
			}
			if (options?.lossReason) {
				updateData.lossReason = options.lossReason;
			}
		}
 
		// Unarchive if moving to a non-terminal stage from archived
		if (
			lead.isArchived &&
			newStage.stageType !== "system_terminal_won" &&
			newStage.stageType !== "system_terminal_lost"
		) {
			updateData.isArchived = false;
			updateData.archivedAt = null;
		}
 
		const updated = await this.dal.leads.update(leadId, updateData);
		if (!updated) {
			throw new NotFoundError("Lead", String(leadId));
		}
 
		// Log activity
		const groupId = generateId();
		const activities: NewLeadActivity[] = [
			{
				leadId,
				activityType: "stage_changed",
				content: `Stage changed from "${oldStage?.name ?? "Unknown"}" to "${newStage.name}"`,
				metadataJson: {
					fromStageId: lead.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,
			});
		}
 
		// Loss reason activity
		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,
			});
		}
 
		await this.dal.leadActivities.createMany(activities);
 
		return updated;
	}
 
	async updateContactStatus(
		leadId: number,
		input: { method: string; noteContent?: string },
	): Promise<Lead> {
		await this.getById(leadId); // Existence check
 
		if (!VALID_CONTACT_METHODS.has(input.method)) {
			throw new ValidationError(
				`Invalid contact method. Allowed: ${CONTACT_METHODS.join(", ")}`,
			);
		}
 
		const updated = await this.dal.leads.update(leadId, {
			lastContactedAt: new Date(),
			lastContactMethod: input.method as Lead["lastContactMethod"],
		});
		if (!updated) {
			throw new NotFoundError("Lead", String(leadId));
		}
 
		await this.dal.leadActivities.create({
			leadId,
			activityType: "contacted",
			content: input.noteContent || `Contacted via ${input.method}`,
			metadataJson: { method: input.method },
		});
 
		return updated;
	}
 
	async archive(leadId: number): Promise<Lead> {
		await this.getById(leadId); // Existence check
 
		const updated = await this.dal.leads.update(leadId, {
			isArchived: true,
			archivedAt: new Date(),
		});
		if (!updated) {
			throw new NotFoundError("Lead", String(leadId));
		}
 
		await this.dal.leadActivities.create({
			leadId,
			activityType: "lead_archived",
			content: "Lead archived",
		});
 
		return updated;
	}
 
	async unarchive(leadId: number): Promise<Lead> {
		await this.getById(leadId); // Existence check
 
		const updated = await this.dal.leads.update(leadId, {
			isArchived: false,
			archivedAt: null,
		});
		if (!updated) {
			throw new NotFoundError("Lead", String(leadId));
		}
 
		await this.dal.leadActivities.create({
			leadId,
			activityType: "lead_unarchived",
			content: "Lead unarchived",
		});
 
		return updated;
	}
 
	async updateQuoteValue(leadId: number, valuePaise: number): Promise<Lead> {
		const existing = await this.getById(leadId);
		const oldValue = existing.quoteValuePaise;
 
		const updated = await this.dal.leads.update(leadId, {
			quoteValuePaise: valuePaise,
		});
		if (!updated) {
			throw new NotFoundError("Lead", String(leadId));
		}
 
		await this.dal.leadActivities.create({
			leadId,
			activityType: "quote_value_changed",
			content: "Quote value updated",
			metadataJson: { oldValuePaise: oldValue, newValuePaise: valuePaise },
		});
 
		return updated;
	}
 
	async updateOrderValue(leadId: number, valuePaise: number): Promise<Lead> {
		const existing = await this.getById(leadId);
		const oldValue = existing.orderValuePaise;
 
		const updated = await this.dal.leads.update(leadId, {
			orderValuePaise: valuePaise,
		});
		if (!updated) {
			throw new NotFoundError("Lead", String(leadId));
		}
 
		await this.dal.leadActivities.create({
			leadId,
			activityType: "order_value_changed",
			content: "Order value updated",
			metadataJson: { oldValuePaise: oldValue, newValuePaise: valuePaise },
		});
 
		return updated;
	}
 
	async checkPhone(
		proId: string,
		phone: string,
	): Promise<{ exists: boolean; lead?: Lead }> {
		// checkPhone takes any user-typed phone and looks for a matching lead.
		// Match on E.164 if the input parses; otherwise fall back to the raw
		// digit-stripped form to find legacy rows.
		const normalized = normalizeToE164(phone) ?? phone.replace(/\D/g, "");
		const existing = await this.dal.leads.findByPhone(proId, normalized);
		return existing ? { exists: true, lead: existing } : { exists: false };
	}
 
	async deleteLead(proId: string, leadId: number): Promise<void> {
		await this.verifyProOwnership(leadId, proId);
		const deleted = await this.dal.leads.delete(leadId);
		/* v8 ignore start -- defensive guard: verifyProOwnership ensures lead exists */
		if (!deleted) {
		/* v8 ignore stop */
			throw new NotFoundError("Lead", String(leadId));
		}
	}
}