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 | 9x 9x 9x 9x 62x 25x 25x 9x 9x 9x 9x 25x 9x 2x 2x 7x 7x 2x 2x 2x 9x 9x 9x 2x 2x 1x 14x 14x 1x 13x 13x 13x 13x 13x 13x 13x 13x 5x 2x 5x 5x 1x 4x 1x 3x 1x 2x 2x 5x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 1x 1x 1x 2x 1x 1x 4x 1x 3x 3x 3x 1x 1x 2x 1x 5x 5x 4x 1x 3x 3x 2x 4x 4x 1x 3x 3x 7x 9x 7x 9x 27x 27x 24x 15x 15x 14x 12x 12x 10x 10x 13x 5x 1x 1x 1x 1x 1x 1x 1x 1x | import type { Dal } from "../../dal";
import type { WaConversationFilters } from "../../dal/whatsapp/conversations.dal";
import type { WaConversation, WaMessage } from "../../db/schema";
import { NotFoundError, ValidationError } from "../../lib/errors";
import type {
WhatsAppClient,
WhatsAppInboundMessage,
} from "../../lib/whatsapp";
import { whatsappNumberVariants } from "../../lib/whatsapp/phone-variants";
const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
const MAX_TEXT_MESSAGE_LENGTH = 4096;
// A thread with no message either way for a week counts as a new chat.
const NEW_CHAT_QUIET_MS = 7 * 24 * 60 * 60 * 1000;
/** Sent when Meta tells us a message arrived but not what was in it. */
export const RESEND_REQUEST_TEXT =
"Sorry, we couldn't see your last message. WhatsApp doesn't pass some " +
"kinds of message, like polls or view-once photos, to business accounts. " +
"Could you send it again as a regular message or photo?";
export class ConversationService {
constructor(private dal: Dal) {}
/**
* Find or create a conversation for a phone number.
* Auto-maps contact type by checking pros and inquiries.
*/
async getOrCreateConversation(
phoneNumber: string,
contactName?: string,
): Promise<WaConversation> {
const existing =
await this.dal.waConversations.findByPhoneNumber(phoneNumber);
if (existing) return existing;
// Auto-map contact type. Both lookups match any spelling of the number.
let contactType: "pro" | "customer" | "unknown" = "unknown";
let proId: string | null = null;
let inquiryId: number | null = null;
let name = contactName || null;
const pro = await this.dal.pros.findByWhatsappNumber(phoneNumber);
if (pro) {
contactType = "pro";
proId = pro.id;
} else {
const inquiry = await this.dal.inquiries.findLatestByPhone(phoneNumber);
if (inquiry) {
contactType = "customer";
inquiryId = inquiry.id;
name ??= inquiry.customerName;
}
}
// Stored the way Meta's webhook sends it (91XXXXXXXXXX), so a thread we
// start and one the contact starts are the same row, and a ten-digit
// number gets the country code Meta needs to deliver to it.
const variants = whatsappNumberVariants(phoneNumber);
try {
return await this.dal.waConversations.create({
phoneNumber:
variants.length > 1 ? variants[1] : phoneNumber.replace(/\D/g, ""),
contactName: name,
contactType,
proId,
inquiryId,
});
} catch (err) {
// Two requests for the same new number (a double click, or a send
// racing the webhook): the unique phone index rejects the second
// insert, and the row the first one made is the answer.
const created =
await this.dal.waConversations.findByPhoneNumber(phoneNumber);
if (created) return created;
throw err;
}
}
/**
* Store an inbound message from webhook. Creates conversation if needed.
* Deduplicates by wamid. `newChat` is true for the contact's first message,
* or their first after a quiet week, and false for a Meta redelivery.
*/
async addInboundMessage(
message: WhatsAppInboundMessage,
contactName: string,
): Promise<{
message: WaMessage;
conversation: WaConversation | undefined;
newChat: boolean;
}> {
// Dedup check
const existing = await this.dal.waMessages.findByWamid(message.id);
if (existing) {
return { message: existing, conversation: undefined, newChat: false };
}
const conversation = await this.getOrCreateConversation(
message.from,
contactName,
);
const content = this.extractContent(message);
const now = new Date();
const stored = await this.dal.waMessages.create({
conversationId: conversation.id,
wamid: message.id,
direction: "inbound",
type: message.type as WaMessage["type"],
content: JSON.stringify(content),
status: "delivered",
});
const newChat = await this.dal.waConversations.claimNewChat(
conversation.id,
now,
new Date(now.getTime() - NEW_CHAT_QUIET_MS),
);
// Update conversation metadata
await this.dal.waConversations.update(conversation.id, {
lastMessageAt: now,
lastCustomerMessageAt: now,
contactName: contactName || conversation.contactName,
});
await this.dal.waConversations.incrementUnread(conversation.id);
return { message: stored, conversation, newChat };
}
/**
* Store an outbound message record.
*/
async addOutboundMessage(
conversationId: number,
type: string,
content: string,
options?: {
templateName?: string;
sentBy?: string | null;
campaignId?: number;
wamid?: string;
status?: string;
},
): Promise<WaMessage> {
return this.dal.waMessages.create({
conversationId,
wamid: options?.wamid ?? null,
direction: "outbound",
type: type as WaMessage["type"],
content,
templateName: options?.templateName ?? null,
sentBy: options?.sentBy ?? null,
campaignId: options?.campaignId ?? null,
status: (options?.status ?? "queued") as WaMessage["status"],
});
}
/**
* Update a message's delivery status by wamid.
*/
async updateMessageStatus(
wamid: string,
status: string,
errorCode?: string,
): Promise<void> {
await this.dal.waMessages.updateStatus(wamid, status, errorCode);
}
/**
* Reply to a conversation with free-form text (within 24hr window)
* or template (any time).
*/
async reply(
conversationId: number,
text: string,
/** null for a system-triggered send — `sent_by` is an FK to users.id. */
adminUserId: string | null,
whatsAppClient: WhatsAppClient,
): Promise<WaMessage> {
const conversation =
await this.dal.waConversations.findById(conversationId);
if (!conversation) {
throw new NotFoundError("Conversation", String(conversationId));
}
if (!this.isWindowOpen(conversation)) {
throw new Error(
"24-hour messaging window has expired. Use a template message instead.",
);
}
if (text.length > MAX_TEXT_MESSAGE_LENGTH) {
throw new ValidationError(
`Message too long (${text.length} chars). Maximum is ${MAX_TEXT_MESSAGE_LENGTH} characters.`,
);
}
const result = await whatsAppClient.sendText(
conversation.phoneNumber,
text,
);
const wamid = result.messages[0]?.id;
const stored = await this.addOutboundMessage(
conversationId,
"text",
JSON.stringify({ body: text }),
{ sentBy: adminUserId, wamid, status: "sent" },
);
await this.dal.waConversations.update(conversationId, {
lastMessageAt: new Date(),
});
return stored;
}
/**
* Ask the customer to resend a message WhatsApp would not pass on. At most
* once a day per conversation: three polls in a row get one answer.
*
* ponytail: check-then-send, so two webhook deliveries racing each other
* can both pass the check; a conditional insert if double replies turn up.
*/
async askToResend(
conversationId: number,
whatsAppClient: WhatsAppClient,
): Promise<boolean> {
const since = new Date(Date.now() - TWENTY_FOUR_HOURS_MS);
const content = JSON.stringify({ body: RESEND_REQUEST_TEXT });
if (await this.dal.waMessages.sentSince(conversationId, content, since)) {
return false;
}
await this.reply(conversationId, RESEND_REQUEST_TEXT, null, whatsAppClient);
return true;
}
/**
* Reply with media — a video, image or document by public URL.
*
* Same window rule as `reply`: free-form, so an open 24-hour window is
* required. Stored with the URL, not the bytes, because that is what was
* sent and what Meta fetched.
*/
async replyWithMedia(
conversationId: number,
kind: "video" | "image" | "document",
link: string,
caption: string | undefined,
/** null for a system-triggered send — `sent_by` is an FK to users.id. */
adminUserId: string | null,
whatsAppClient: WhatsAppClient,
): Promise<WaMessage> {
const conversation =
await this.dal.waConversations.findById(conversationId);
if (!conversation) {
throw new NotFoundError("Conversation", String(conversationId));
}
if (!this.isWindowOpen(conversation)) {
throw new Error(
"24-hour messaging window has expired. Media can only be sent free-form, inside an open window.",
);
}
const result = await whatsAppClient.sendMedia(
conversation.phoneNumber,
kind,
link,
caption,
);
const stored = await this.addOutboundMessage(
conversationId,
kind,
JSON.stringify({ link, ...(caption ? { caption } : {}) }),
{ sentBy: adminUserId, wamid: result.messages[0]?.id, status: "sent" },
);
await this.dal.waConversations.update(conversationId, {
lastMessageAt: new Date(),
});
return stored;
}
/**
* Reply with a template message (works outside 24hr window).
*/
async replyWithTemplate(
conversationId: number,
templateName: string,
language: string,
components: unknown[] | undefined,
/** null for a system-triggered send — `sent_by` is an FK to users.id. */
adminUserId: string | null,
whatsAppClient: WhatsAppClient,
): Promise<WaMessage> {
const conversation =
await this.dal.waConversations.findById(conversationId);
if (!conversation) {
throw new NotFoundError("Conversation", String(conversationId));
}
const result = await whatsAppClient.sendTemplate(
conversation.phoneNumber,
templateName,
language,
components as Parameters<typeof whatsAppClient.sendTemplate>[3],
);
const wamid = result.messages[0]?.id;
const stored = await this.addOutboundMessage(
conversationId,
"template",
JSON.stringify({ templateName, language, components }),
{ templateName, sentBy: adminUserId, wamid, status: "sent" },
);
await this.dal.waConversations.update(conversationId, {
lastMessageAt: new Date(),
});
return stored;
}
async listConversations(
filters: WaConversationFilters,
offset: number,
limit: number,
) {
if (filters.contactType === "pro") {
return this.listProInbox(filters, offset, limit);
}
const [rows, total] = await Promise.all([
this.dal.waConversations.findAll(filters, offset, limit),
this.dal.waConversations.count(filters),
]);
const conversations = await this.withPros(rows);
return { conversations, total };
}
/** `id: null` = never messaged; opened by `startProConversation`. */
private async listProInbox(
filters: WaConversationFilters,
offset: number,
limit: number,
) {
const [rows, total] = await Promise.all([
this.dal.waConversations.findProInbox(filters, offset, limit),
this.dal.waConversations.countProInbox(filters),
]);
const conversations = await this.withPros(
rows.map(({ conversation, proId, whatsapp }) => ({
...(conversation ?? {
id: null,
phoneNumber: whatsapp ?? "",
contactName: null,
inquiryId: null,
lastMessageAt: null,
lastCustomerMessageAt: null,
unreadCount: 0,
dateCreated: null,
dateUpdated: null,
}),
contactType: "pro" as const,
proId,
})),
);
return { conversations, total };
}
/** Open (or find) the conversation with a pro, without sending anything. */
async startProConversation(proId: string): Promise<WaConversation> {
const pro = await this.dal.pros.findById(proId);
if (!pro) throw new NotFoundError("Pro", proId);
if (!pro.whatsapp) {
throw new ValidationError("This pro has no WhatsApp number");
}
const conversation = await this.getOrCreateConversation(pro.whatsapp);
// An existing thread for this number that was never matched to a pro
// (e.g. a Quick Send before the number was on a profile) is theirs.
if (conversation.proId) return conversation;
return (
(await this.dal.waConversations.update(conversation.id, {
proId,
contactType: "pro",
})) ?? conversation
);
}
async getConversation(id: number, offset = 0, limit = 100) {
const conversation = await this.dal.waConversations.findById(id);
if (!conversation) {
throw new NotFoundError("Conversation", String(id));
}
const [[withPro], messages] = await Promise.all([
this.withPros([conversation]),
this.dal.waMessages.findByConversationId(id, offset, limit),
]);
return {
conversation: withPro,
messages,
// Stated, not inferred. Whether a plain reply is legal is Meta's
// 24-hour rule, and the server already refuses a late one (see
// reply()); deriving the deadline from the browser clock means a
// client five minutes fast offers a send that will be rejected with
// 131047. Null once closed and never a past instant, so a non-null
// value always means "a plain reply is allowed".
windowExpiresAt: this.windowExpiresAt(conversation),
};
}
/**
* Attach the pro behind each conversation, so the inbox can show a business
* and a person rather than a bare number. Read-only: the link is made when
* the conversation is created (and by migration 0021 for older rows).
*
* ponytail: a pro who adds their WhatsApp number after the conversation
* exists stays unlinked; re-link on profile save if that turns up.
*/
private async withPros<T extends { proId: string | null }>(
conversations: T[],
) {
const contacts = await this.dal.pros.findInboxContacts(
conversations.flatMap((c) => c.proId ?? []),
);
const byId = new Map(contacts.map((c) => [c.id, c]));
return conversations.map((c) => ({
...c,
pro: (c.proId && byId.get(c.proId)) || null,
}));
}
/**
* `last_customer_message_at` in epoch ms, or null if they have never
* written. Drizzle hands back a Date; a row read through a path that has
* not decoded the column yet hands back unix seconds.
*/
private lastCustomerMessageMs(conversation: WaConversation): number | null {
const at = conversation.lastCustomerMessageAt;
if (!at) return null;
return at instanceof Date ? at.getTime() : Number(at) * 1000;
}
/**
* Check if the 24-hour customer messaging window is open.
* The window is open if the customer sent a message in the last 24 hours.
*/
isWindowOpen(conversation: WaConversation): boolean {
const lastCustomerMsg = this.lastCustomerMessageMs(conversation);
if (lastCustomerMsg === null) return false;
return Date.now() - lastCustomerMsg < TWENTY_FOUR_HOURS_MS;
}
/**
* When the 24-hour window closes, or null if it is already closed (or was
* never opened). Never a past instant, so the UI cannot offer a send Meta
* would reject.
*/
windowExpiresAt(conversation: WaConversation): Date | null {
const lastCustomerMsg = this.lastCustomerMessageMs(conversation);
if (lastCustomerMsg === null) return null;
const expiresAt = lastCustomerMsg + TWENTY_FOUR_HOURS_MS;
return expiresAt > Date.now() ? new Date(expiresAt) : null;
}
private extractContent(
message: WhatsAppInboundMessage,
): Record<string, unknown> {
switch (message.type) {
case "text":
return { body: message.text?.body ?? "" };
case "image":
return {
mediaId: message.image?.id,
caption: message.image?.caption,
};
case "video":
return {
mediaId: message.video?.id,
caption: message.video?.caption,
};
case "document":
return {
mediaId: message.document?.id,
filename: message.document?.filename,
caption: message.document?.caption,
};
case "audio":
return { mediaId: message.audio?.id };
case "sticker":
return { mediaId: message.sticker?.id };
case "interactive":
return {
type: message.interactive?.type,
buttonReply: message.interactive?.button_reply,
listReply: message.interactive?.list_reply,
};
case "location":
return {
latitude: message.location?.latitude,
longitude: message.location?.longitude,
name: message.location?.name,
address: message.location?.address,
};
default:
return { raw: message };
}
}
}
|