All files / dal/whatsapp conversations.dal.ts

100% Statements 57/57
100% Branches 36/36
100% Functions 17/17
100% Lines 57/57

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                                                                                      80x               3x                     3x       2x         2x                                 11x   11x                     11x 8x   3x                           3x 3x       4x   4x       4x 2x 2x   2x 2x                 1x 1x                                     1x         1x                       2x       2x 2x       2x 1x 1x       2x       1x       1x             2x         2x                   2x 2x                   2x       1x                   1x                               2x                   2x             25x   25x 6x               25x 1x 1x 1x         25x 2x         25x 3x                           25x 3x                             25x 8x           25x      
import {
	and,
	asc,
	desc,
	eq,
	gt,
	inArray,
	isNotNull,
	isNull,
	lt,
	or,
	type SQL,
	sql,
} from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import type { NewWaConversation, WaConversation } from "../../db/schema";
import * as schema from "../../db/schema";
import { sanitizeSearchInput } from "../../lib/utils";
import { whatsappNumberVariants } from "../../lib/whatsapp/phone-variants";
 
export type WaConversationFilters = {
	contactType?: string;
	search?: string;
	hasUnread?: boolean;
	/** Contact has written to us at least once. */
	hasCustomerReply?: boolean;
	/** A human on our side has replied. Automated sends do not count. */
	answeredByUs?: boolean;
	/**
	 * Nothing outbound since their last inbound — the triage backlog.
	 *
	 * Distinct from both neighbours above: `hasCustomerReply` is "has ever
	 * written", `answeredByUs` is "has ever been answered". Neither means
	 * "is waiting right now", and `unreadCount` cannot stand in either — the
	 * inbox zeroes it the moment a conversation is selected, so merely looking
	 * at a thread would destroy the signal.
	 *
	 * Ordering follows: see {@link WaConversationsDal.findAll}.
	 */
	waitingOnUs?: boolean;
};
 
export class WaConversationsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	/**
	 * Matches any spelling of the number (`91…`, `+91…`, ten digits, spaces).
	 * Where older duplicate rows exist for one number, the most recently
	 * active thread wins.
	 */
	async findByPhoneNumber(phone: string): Promise<WaConversation | undefined> {
		const result = await this.db
			.select()
			.from(schema.waConversations)
			.where(
				inArray(
					schema.waConversations.phoneNumber,
					whatsappNumberVariants(phone),
				),
			)
			.orderBy(desc(schema.waConversations.lastMessageAt))
			.limit(1);
		return result[0];
	}
 
	async findById(id: number): Promise<WaConversation | undefined> {
		const result = await this.db
			.select()
			.from(schema.waConversations)
			.where(eq(schema.waConversations.id, id))
			.limit(1);
		return result[0];
	}
 
	/**
	 * The waiting list is ordered oldest-inbound-first; everything else is
	 * ordered most-recently-active-first.
	 *
	 * Two branches rather than a `sort=` parameter, deliberately. On a triage
	 * screen a re-order can only hide the one row that matters, and the
	 * endpoint is paginated — sorting a page of 25 in the browser yields "the
	 * oldest of the newest 25", which is a different and wrong number.
	 */
	async findAll(
		filters: WaConversationFilters = {},
		offset = 0,
		limit = 50,
	): Promise<WaConversation[]> {
		const conditions = this.buildConditions(filters);
 
		const query = this.db
			.select()
			.from(schema.waConversations)
			.orderBy(
				filters.waitingOnUs
					? asc(schema.waConversations.lastCustomerMessageAt)
					: desc(schema.waConversations.lastMessageAt),
			)
			.limit(limit)
			.offset(offset);
 
		if (conditions.length > 0) {
			return query.where(and(...conditions));
		}
		return query;
	}
 
	/**
	 * When the oldest unanswered contact wrote, or null on an empty backlog.
	 *
	 * Deliberately the first row of {@link findAll}'s waiting branch rather
	 * than a `min()` of its own: it is then provably the same conversation the
	 * inbox puts at the top, and the predicate is spelled once. The RRM
	 * ancestor of this query was rewritten after a second spelling of the
	 * condition, over a second table, shipped a badge that disagreed with the
	 * screen it sat next to.
	 */
	async oldestWaitingAt(): Promise<Date | null> {
		const [oldest] = await this.findAll({ waitingOnUs: true }, 0, 1);
		return oldest?.lastCustomerMessageAt ?? null;
	}
 
	async count(filters: WaConversationFilters = {}): Promise<number> {
		const conditions = this.buildConditions(filters);
 
		const query = this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.waConversations);
 
		if (conditions.length > 0) {
			const result = await query.where(and(...conditions));
			return result[0]?.count ?? 0;
		}
		const result = await query;
		return result[0]?.count ?? 0;
	}
 
	/** The Pros tab: every pro with a WhatsApp number, messaged or not. */
	async findProInbox(
		filters: WaConversationFilters,
		offset: number,
		limit: number,
	) {
		const c = schema.waConversations;
		return this.db
			.select({
				conversation: c,
				proId: schema.pros.id,
				whatsapp: schema.pros.whatsapp,
			})
			.from(schema.pros)
			.leftJoin(c, this.latestConversationOfPro())
			.where(this.proInboxWhere(filters))
			.orderBy(
				sql`${c.lastMessageAt} IS NULL`,
				desc(c.lastMessageAt),
				asc(schema.pros.businessName),
			)
			.limit(limit)
			.offset(offset);
	}
 
	async countProInbox(filters: WaConversationFilters): Promise<number> {
		const result = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.pros)
			.leftJoin(schema.waConversations, this.latestConversationOfPro())
			.where(this.proInboxWhere(filters));
		return result[0]?.count ?? 0;
	}
 
	/**
	 * The pro's most recently active conversation: one linked to them, or the
	 * one on their number. The number matters when two pros share one — it is
	 * one WhatsApp chat, linked to whichever pro it matched first, and both
	 * rows should show it. New conversations store 91 + the ten digits, which
	 * is what the second clause builds from the profile number. One row per
	 * pro even where old duplicates exist. Rides the pro and phone indexes.
	 */
	private latestConversationOfPro(): SQL {
		return sql`${schema.waConversations.id} = (SELECT c2.id FROM wa_conversations c2 WHERE c2.pro_id = ${schema.pros.id} OR c2.phone_number = '91' || substr(replace(replace(${schema.pros.whatsapp}, '+', ''), ' ', ''), -10) ORDER BY c2.last_message_at DESC LIMIT 1)`;
	}
 
	private proInboxWhere(filters: WaConversationFilters) {
		const { search, contactType: _, ...conversationFilters } = filters;
		const conditions = [
			isNotNull(schema.pros.whatsapp),
			...this.buildConditions(conversationFilters),
		];
		if (search) {
			const term = `%${sanitizeSearchInput(search)}%`;
			conditions.push(
				sql`(${schema.pros.businessName} LIKE ${term} OR ${schema.pros.whatsapp} LIKE ${term} OR ${schema.waConversations.contactName} LIKE ${term})`,
			);
		}
		return and(...conditions);
	}
 
	async create(data: NewWaConversation): Promise<WaConversation> {
		const result = await this.db
			.insert(schema.waConversations)
			.values(data)
			.returning();
		return result[0];
	}
 
	async update(
		id: number,
		data: Partial<WaConversation>,
	): Promise<WaConversation | undefined> {
		const result = await this.db
			.update(schema.waConversations)
			.set({ ...data, dateUpdated: new Date() })
			.where(eq(schema.waConversations.id, id))
			.returning();
		return result[0];
	}
 
	/**
	 * Stamps the contact's latest message time, but only if the thread has had
	 * no message either way since `quietSince` (or none ever). A reply in a
	 * thread we wrote in is not a new chat. One conditional UPDATE, so of two
	 * webhook deliveries racing for the same new number, one wins.
	 */
	async claimNewChat(id: number, at: Date, quietSince: Date): Promise<boolean> {
		const c = schema.waConversations;
		const rows = await this.db
			.update(c)
			.set({ lastMessageAt: at, lastCustomerMessageAt: at })
			.where(
				and(
					eq(c.id, id),
					or(isNull(c.lastMessageAt), lt(c.lastMessageAt, quietSince)),
				),
			)
			.returning({ id: c.id });
		return rows.length > 0;
	}
 
	async incrementUnread(id: number): Promise<void> {
		await this.db
			.update(schema.waConversations)
			.set({
				unreadCount: sql`${schema.waConversations.unreadCount} + 1`,
				dateUpdated: new Date(),
			})
			.where(eq(schema.waConversations.id, id));
	}
 
	async resetUnread(id: number): Promise<void> {
		await this.db
			.update(schema.waConversations)
			.set({ unreadCount: 0, dateUpdated: new Date() })
			.where(eq(schema.waConversations.id, id));
	}
 
	/**
	 * Previously returned a third count, `activeToday`, that no caller ever
	 * read — a query per dashboard load rendered nowhere, and a second
	 * UTC-midnight "today" boundary to get wrong. Day-scoped counts now live in
	 * WaMessagesDal and start at IST midnight (src/lib/ist-time.ts).
	 */
	async getStats(): Promise<{
		total: number;
		unread: number;
	}> {
		const [totalResult, unreadResult] = await Promise.all([
			this.db
				.select({ count: sql<number>`count(*)` })
				.from(schema.waConversations),
			this.db
				.select({ count: sql<number>`count(*)` })
				.from(schema.waConversations)
				.where(gt(schema.waConversations.unreadCount, 0)),
		]);
 
		return {
			total: totalResult[0]?.count ?? 0,
			unread: unreadResult[0]?.count ?? 0,
		};
	}
 
	private buildConditions(filters: WaConversationFilters) {
		const conditions = [];
 
		if (filters.contactType) {
			conditions.push(
				eq(
					schema.waConversations.contactType,
					filters.contactType as WaConversation["contactType"],
				),
			);
		}
 
		if (filters.search) {
			const sanitized = sanitizeSearchInput(filters.search);
			const searchTerm = `%${sanitized}%`;
			conditions.push(
				sql`(${schema.waConversations.phoneNumber} LIKE ${searchTerm} OR ${schema.waConversations.contactName} LIKE ${searchTerm})`,
			);
		}
 
		if (filters.hasUnread) {
			conditions.push(gt(schema.waConversations.unreadCount, 0));
		}
 
		// The conversation row already records this, so no join is needed. It is
		// set by the inbound webhook, which is the only writer.
		if (filters.hasCustomerReply) {
			conditions.push(isNotNull(schema.waConversations.lastCustomerMessageAt));
		}
 
		// `sent_by` is what separates a human reply from an automated send —
		// campaigns and other automated sends leave it null (see reply() in
		// conversation.service.ts). Without that clause every conversation we
		// ever sent a template to would count as answered.
		//
		// Raw sql rather than drizzle's exists() + a subquery builder, because
		// that would need `this.db` and buildConditions is a pure function of its
		// filters. The search clause above is raw sql for the same reason.
		//
		// The correlated subquery rides wa_messages_conversation_idx, so it is a
		// per-row index seek rather than a scan.
		if (filters.answeredByUs) {
			conditions.push(
				sql`EXISTS (SELECT 1 FROM ${schema.waMessages} WHERE ${schema.waMessages.conversationId} = ${schema.waConversations.id} AND ${schema.waMessages.direction} = 'outbound' AND ${schema.waMessages.sentBy} IS NOT NULL)`,
			);
		}
 
		// Waiting on us = nothing outbound since their last inbound. Copied
		// verbatim from the deleted services/rrm/unanswered.service.ts, which is
		// the only place this condition has ever been correct — do not spell it a
		// second way. Equal timestamps count as UNANSWERED on purpose:
		// `date_created` is second-precision, and erring toward showing the row
		// is the safe half.
		//
		// One table, no join. An automated send (campaign, notification adapter,
		// ask-to-resend) leaves `last_message_at` alone, so a blast cannot make a
		// waiting conversation look answered.
		if (filters.waitingOnUs) {
			conditions.push(
				isNotNull(schema.waConversations.lastCustomerMessageAt),
				sql`(${schema.waConversations.lastMessageAt} IS NULL OR ${schema.waConversations.lastMessageAt} <= ${schema.waConversations.lastCustomerMessageAt})`,
			);
		}
 
		return conditions;
	}
}