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 | 10x 10x 59x 35x 35x 4x 4x 4x 4x 4x 1x 1x 3x 3x 1x 4x 11x 11x 10x 10x 10x 10x 10x 10x 10x 22x 2x 9x 9x 1x 8x 1x 7x 1x 6x 5x 9x 5x 5x 17x 17x 1x 16x 15x 17x 15x 15x 2x 2x 2x 2x 1x 1x 1x 13x 12x 13x 10x 3x 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";
const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
const MAX_TEXT_MESSAGE_LENGTH = 4096;
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 by exact matching
let contactType: "pro" | "customer" | "unknown" = "unknown";
let proId: string | null = null;
const inquiryId: number | null = null;
// Check if this phone belongs to a pro (exact match on whatsapp field)
const pro = await this.dal.pros.findByWhatsappNumber(phoneNumber);
if (pro) {
contactType = "pro";
proId = pro.id;
} else {
// Check if this phone belongs to a customer (from inquiries)
const isCustomer = await this.dal.inquiries.existsByPhone(phoneNumber);
if (isCustomer) {
contactType = "customer";
}
}
return this.dal.waConversations.create({
phoneNumber,
contactName: contactName ?? null,
contactType,
proId,
inquiryId,
});
}
/**
* Store an inbound message from webhook. Creates conversation if needed.
* Deduplicates by wamid.
*/
async addInboundMessage(
message: WhatsAppInboundMessage,
contactName: string,
): Promise<WaMessage> {
// Dedup check
const existing = await this.dal.waMessages.findByWamid(message.id);
if (existing) return existing;
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",
});
// 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 stored;
}
/**
* 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;
}
/**
* 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,
) {
const [conversations, total] = await Promise.all([
this.dal.waConversations.findAll(filters, offset, limit),
this.dal.waConversations.count(filters),
]);
return { conversations, total };
}
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 messages = await this.dal.waMessages.findByConversationId(
id,
offset,
limit,
);
return { conversation, messages };
}
/**
* 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 {
if (!conversation.lastCustomerMessageAt) return false;
const lastCustomerMsg =
conversation.lastCustomerMessageAt instanceof Date
? conversation.lastCustomerMessageAt.getTime()
: Number(conversation.lastCustomerMessageAt) * 1000;
return Date.now() - lastCustomerMsg < TWENTY_FOUR_HOURS_MS;
}
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 "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 };
}
}
}
|