All files / services/crm reminders.service.ts

100% Statements 66/66
100% Branches 44/44
100% Functions 9/9
100% Lines 66/66

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                      5x     37x           17x 17x 3x         2x 2x 1x   1x             9x 9x 1x       8x 8x 2x           6x 6x 2x         4x 4x 1x         3x                 3x             3x             6x 6x 1x   5x 4x 2x     2x       2x 1x     1x             1x             6x 6x 1x   5x 4x 2x     2x     2x 1x     1x             1x               8x 8x 1x   7x 6x 2x     4x 4x 1x         3x       3x 1x           2x   2x           2x                                   2x     2x                     2x           2x       2x      
// Reminders Service - Create, complete, dismiss, snooze reminders
import { eq } from "drizzle-orm";
import type { Dal } from "../../dal";
import { leadReminders as leadRemindersTable } from "../../db/schema";
import type { LeadReminder } from "../../db/schema";
import {
	ForbiddenError,
	NotFoundError,
	ValidationError,
} from "../../lib/errors";
 
const MAX_ACTIVE_REMINDERS_PER_LEAD = 10;
 
export class RemindersService {
	constructor(private dal: Dal) {}
 
	private async verifyOwnership(
		reminder: LeadReminder,
		proId: string,
	): Promise<void> {
		const lead = await this.dal.leads.findById(reminder.leadId);
		if (!lead || lead.proId !== proId) {
			throw new ForbiddenError("Reminder does not belong to this pro");
		}
	}
 
	async listByLead(leadId: number): Promise<LeadReminder[]> {
		const lead = await this.dal.leads.findById(leadId);
		if (!lead) {
			throw new NotFoundError("Lead", String(leadId));
		}
		return this.dal.leadReminders.findByLeadId(leadId);
	}
 
	async create(
		leadId: number,
		input: { title: string; dueAt: number; notes?: string },
	): Promise<LeadReminder> {
		const lead = await this.dal.leads.findById(leadId);
		if (!lead) {
			throw new NotFoundError("Lead", String(leadId));
		}
 
		// Validate title
		const title = input.title.trim();
		if (!title || title.length > 100) {
			throw new ValidationError(
				"Reminder title is required (max 100 characters)",
			);
		}
 
		// Validate due date is in the future
		const nowUnix = Math.floor(Date.now() / 1000);
		if (input.dueAt <= nowUnix) {
			throw new ValidationError("Reminder due date must be in the future");
		}
 
		// Validate active reminders limit
		const activeCount =
			await this.dal.leadReminders.countActiveByLeadId(leadId);
		if (activeCount >= MAX_ACTIVE_REMINDERS_PER_LEAD) {
			throw new ValidationError(
				`Maximum ${MAX_ACTIVE_REMINDERS_PER_LEAD} active reminders per lead`,
			);
		}
 
		const reminder = await this.dal.leadReminders.create({
			leadId,
			title,
			notes: input.notes?.trim() || null,
			dueAt: new Date(input.dueAt * 1000),
			status: "upcoming",
		});
 
		// Log activity
		await this.dal.leadActivities.create({
			leadId,
			activityType: "reminder_set",
			content: `Reminder set: "${title}"`,
			metadataJson: { reminderId: reminder.id, dueAt: input.dueAt },
		});
 
		return reminder;
	}
 
	async complete(
		proId: string,
		reminderId: number,
	): Promise<LeadReminder> {
		const reminder = await this.dal.leadReminders.findById(reminderId);
		if (!reminder) {
			throw new NotFoundError("Reminder", String(reminderId));
		}
		await this.verifyOwnership(reminder, proId);
		if (reminder.status === "completed" || reminder.status === "dismissed") {
			throw new ValidationError("Reminder is already resolved");
		}
 
		const updated = await this.dal.leadReminders.update(reminderId, {
			status: "completed",
			completedAt: new Date(),
		});
		if (!updated) {
			throw new NotFoundError("Reminder", String(reminderId));
		}
 
		await this.dal.leadActivities.create({
			leadId: reminder.leadId,
			activityType: "reminder_completed",
			content: `Reminder completed: "${reminder.title}"`,
			metadataJson: { reminderId },
		});
 
		return updated;
	}
 
	async dismiss(
		proId: string,
		reminderId: number,
	): Promise<LeadReminder> {
		const reminder = await this.dal.leadReminders.findById(reminderId);
		if (!reminder) {
			throw new NotFoundError("Reminder", String(reminderId));
		}
		await this.verifyOwnership(reminder, proId);
		if (reminder.status === "completed" || reminder.status === "dismissed") {
			throw new ValidationError("Reminder is already resolved");
		}
 
		const updated = await this.dal.leadReminders.update(reminderId, {
			status: "dismissed",
		});
		if (!updated) {
			throw new NotFoundError("Reminder", String(reminderId));
		}
 
		await this.dal.leadActivities.create({
			leadId: reminder.leadId,
			activityType: "reminder_dismissed",
			content: `Reminder dismissed: "${reminder.title}"`,
			metadataJson: { reminderId },
		});
 
		return updated;
	}
 
	async snooze(
		proId: string,
		reminderId: number,
		newDueAt: number,
	): Promise<LeadReminder> {
		const reminder = await this.dal.leadReminders.findById(reminderId);
		if (!reminder) {
			throw new NotFoundError("Reminder", String(reminderId));
		}
		await this.verifyOwnership(reminder, proId);
		if (reminder.status === "completed" || reminder.status === "dismissed") {
			throw new ValidationError("Reminder is already resolved");
		}
 
		const nowUnix = Math.floor(Date.now() / 1000);
		if (newDueAt <= nowUnix) {
			throw new ValidationError("New due date must be in the future");
		}
 
		// Re-check active count (snooze creates a new reminder, but dismiss
		// will free one slot so we check against count - 1)
		const activeCount = await this.dal.leadReminders.countActiveByLeadId(
			reminder.leadId,
		);
		// After dismiss we'll have activeCount-1 active; adding one brings it back to activeCount
		if (activeCount >= MAX_ACTIVE_REMINDERS_PER_LEAD + 1) {
			throw new ValidationError(
				`Maximum ${MAX_ACTIVE_REMINDERS_PER_LEAD} active reminders per lead`,
			);
		}
 
		// Wrap dismiss + create in a transaction so the reminder is never lost
		const snoozed = await this.dal.db.transaction(async (tx) => {
			// Dismiss the old reminder
			await tx
				.update(leadRemindersTable)
				.set({ status: "dismissed" })
				.where(eq(leadRemindersTable.id, reminderId));
 
			// Create a new reminder with snoozedFromId reference
			const [created] = await tx
				.insert(leadRemindersTable)
				.values({
					leadId: reminder.leadId,
					title: reminder.title,
					notes: reminder.notes,
					dueAt: new Date(newDueAt * 1000),
					status: "upcoming",
					snoozedFromId: reminderId,
				})
				.returning();
 
			/* v8 ignore start -- defensive guard: insert always succeeds */
			if (!created) {
				throw new Error("Failed to create snoozed reminder");
			}
			/* v8 ignore stop */
 
			return created;
		});
 
		await this.dal.leadActivities.create({
			leadId: reminder.leadId,
			activityType: "reminder_snoozed",
			content: `Reminder snoozed: "${reminder.title}"`,
			metadataJson: {
				oldReminderId: reminderId,
				newReminderId: snoozed.id,
				newDueAt,
			},
		});
 
		return snoozed;
	}
 
	async getProReminderCounts(
		proId: string,
	): Promise<{ overdue: number; upcoming: number }> {
		const [overdue, upcoming] = await Promise.all([
			this.dal.leadReminders.countOverdueByProId(proId),
			this.dal.leadReminders.countUpcomingByProId(proId),
		]);
		return { overdue, upcoming };
	}
}