All files / src/lib/api whatsapp.ts

100% Statements 30/30
100% Branches 6/6
100% Functions 26/26
100% Lines 30/30

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                        12x                                                                                                                                                                                                                                                                                           93x     1x                                                     6x     8x 8x     6x                 1x                               1x                             2x                   1x             1x                     1x                                   1x           1x                     2x     3x 3x         2x           1x                   1x                   2x     2x 2x     2x                 1x             1x                         1x             1x                                     2x                              
// WhatsApp Admin API client
import { API_BASE_URL, request, uploadFile } from "./base";
 
/**
 * Absolute URL for the bytes of one media message.
 *
 * Meta media is not public — the API proxies it behind the platform-admin
 * guard, keyed on the MESSAGE so authorisation follows what the admin can
 * already see in the thread. Built from the shared base like every other
 * portal URL; never hardcode a host.
 */
export function getWaMediaUrl(messageId: number): string {
	return `${API_BASE_URL}/api/admin/whatsapp/messages/${messageId}/media`;
}
 
// ─── Types ───────────────────────────────────────────────────────────────────
 
export type WaConversation = {
	id: number;
	phoneNumber: string;
	contactName: string | null;
	contactType: "pro" | "customer" | "unknown";
	proId: string | null;
	/** The pro behind the number, when it matches one. */
	pro: {
		id: string;
		businessName: string;
		status: string;
		whatsapp: string | null;
		email: string | null;
		city: string | null;
		ownerName: string | null;
		ownerEmail: string | null;
	} | null;
	inquiryId: number | null;
	unreadCount: number;
	lastMessageAt: string | null;
	lastCustomerMessageAt: string | null;
	dateCreated: string;
	dateUpdated: string;
};
 
/**
 * A row in the inbox list. On the Pros tab a pro we have never messaged has no
 * conversation yet, so `id` is null until one is opened.
 */
export type WaInboxRow = Omit<WaConversation, "id" | "dateCreated" | "dateUpdated"> & {
	id: number | null;
	dateCreated: string | null;
	dateUpdated: string | null;
};
 
export type WaMessage = {
	id: number;
	conversationId: number;
	wamid: string | null;
	direction: "inbound" | "outbound";
	type: string;
	content: string | null;
	templateName: string | null;
	status: string;
	errorCode: string | null;
	campaignId: number | null;
	sentBy: string | null;
	dateCreated: string;
	dateUpdated: string;
};
 
export type WaTemplate = {
	id: number;
	metaTemplateId: string | null;
	name: string;
	language: string;
	category: string;
	status: string;
	components: string | null;
	rejectionReason: string | null;
	dateCreated: string;
	dateUpdated: string;
};
 
export type WaCampaign = {
	id: number;
	name: string;
	templateId: number;
	templateParams: string | null;
	status: string;
	statsTotal: number;
	statsSent: number;
	statsDelivered: number;
	statsRead: number;
	statsFailed: number;
	createdBy: string;
	dateCreated: string;
	dateUpdated: string;
};
 
export type WaCampaignRecipient = {
	id: number;
	campaignId: number;
	phoneNumber: string;
	contactName: string | null;
	templateParams: string | null;
	status: string;
	wamid: string | null;
	errorCode: string | null;
	dateCreated: string;
	dateUpdated: string;
};
 
export type WaStats = {
	totalConversations: number;
	unreadCount: number;
	/** Volume, both directions, automated sends included. NOT work done. */
	messagesToday: number;
	pendingTemplates: number;
	activeCampaigns: number;
	/**
	 * When the oldest unanswered contact wrote, or null on an empty backlog.
	 * The server reads it off the first row of the inbox's waiting branch, so
	 * the SLA strip's "oldest" and the list's top row cannot disagree.
	 */
	oldestWaitingAt: string | null;
	/**
	 * Replies a HUMAN sent today, IST. `messagesToday` counts volume; this
	 * counts work done, and it is the one an SLA strip may label as such.
	 */
	answeredToday: number;
};
 
/**
 * Everything the campaign detail screen renders, in one response.
 *
 * `template` resolves the campaign's `templateId` server-side, so the page no
 * longer fetches the whole template list to name one row; `recipientTotal` is
 * a COUNT of recipient rows rather than the `statsTotal` counter the send path
 * maintains, so "Recipients (N)" is the real N and not a page size.
 *
 * `stoppable` is the honest dead end: a launched campaign cannot be stopped,
 * and the server says so rather than the page assuming it. `launch()` enqueues
 * every recipient onto `wa-send` in one pass, so the work lives in the queue
 * the moment the request returns — stopping it is a new capability with
 * in-flight-message semantics, not a read view. The day a cancel path lands,
 * this flag is the only thing the page has to re-read.
 */
export type WaCampaignDetail = {
	campaign: WaCampaign;
	template: WaTemplate | null;
	recipientTotal: number;
	stoppable: boolean;
};
 
// ─── API Client ──────────────────────────────────────────────────────────────
 
export const whatsappApi = {
	// ── Stats ──────────────────────────────────────────────────────────────
	async getStats() {
		return request<WaStats>("/api/admin/whatsapp/stats");
	},
 
	// ── Conversations ──────────────────────────────────────────────────────
	async getConversations(params?: {
		contactType?: string;
		search?: string;
		/** Nobody has OPENED it. Zeroed the moment a thread is selected. */
		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;
		/**
		 * The triage backlog: nothing outbound since their last inbound. The
		 * server also ORDERS this branch oldest-waiting-first, which is why
		 * there is no sort parameter — on a triage screen a re-order can only
		 * hide the row that matters, and this list is paginated, so sorting a
		 * page in the browser yields "the oldest of the newest 25".
		 *
		 * The `total` that comes back with it is the inbox-wide count the SLA
		 * strip labels "waiting on us".
		 */
		waitingOnUs?: boolean;
		limit?: number;
		offset?: number;
	}) {
		const query = params
			? `?${new URLSearchParams(
					Object.entries(params)
						.filter(([, v]) => v !== undefined)
						.map(([k, v]) => [k, String(v)]),
				).toString()}`
			: "";
		return request<{
			conversations: WaInboxRow[];
			total: number;
			limit: number;
			offset: number;
		}>(`/api/admin/whatsapp/conversations${query}`);
	},
 
	async getConversation(id: number) {
		return request<{
			conversation: WaConversation;
			messages: WaMessage[];
			/**
			 * When a plain reply stops being legal — null once closed, and never
			 * a past instant, so a non-null value always means "free-form is
			 * allowed". Server-owned on purpose: deriving the deadline from the
			 * browser clock means a client five minutes fast offers a send Meta
			 * rejects with 131047.
			 */
			windowExpiresAt: string | null;
		}>(`/api/admin/whatsapp/conversations/${id}`);
	},
 
	/** Open the conversation with a pro without sending anything. */
	async startProConversation(proId: string) {
		return request<{ conversation: WaConversation }>(
			"/api/admin/whatsapp/conversations",
			{ method: "POST", body: { proId } },
		);
	},
 
	async replyToConversation(
		id: number,
		body: {
			message?: string;
			templateName?: string;
			language?: string;
			components?: unknown[];
		},
	) {
		return request<{ message: WaMessage }>(
			`/api/admin/whatsapp/conversations/${id}/reply`,
			{
				method: "POST",
				body,
			},
		);
	},
 
	async markConversationRead(id: number) {
		return request(`/api/admin/whatsapp/conversations/${id}/read`, {
			method: "POST",
		});
	},
 
	// ── Templates ──────────────────────────────────────────────────────────
	async getTemplates() {
		return request<{ templates: WaTemplate[] }>(
			"/api/admin/whatsapp/templates",
		);
	},
 
	async createTemplate(data: {
		name: string;
		language: string;
		category: string;
		components: unknown[];
	}) {
		return request<{ template: WaTemplate }>("/api/admin/whatsapp/templates", {
			method: "POST",
			body: data,
		});
	},
 
	// No `updateTemplate`. The client method had no caller and no UI — the
	// templates page offers Create / Sync from Meta / Delete and no edit
	// affordance — and template SYNC is a different route
	// (`POST /templates/sync`), so removing this breaks nothing.
	//
	// `PUT /templates/:id` SURVIVES, deliberately, as API-only: it is the only
	// way to amend a submitted template's components, and a template already
	// sent to Meta is otherwise immutable from our side. That decision is
	// recorded in the route's own comment, which is where it belongs. This is
	// a documented pair, not a half-deleted one.
 
	async deleteTemplate(id: number) {
		return request(`/api/admin/whatsapp/templates/${id}`, {
			method: "DELETE",
		});
	},
 
	async syncTemplates() {
		return request<{ synced: number }>("/api/admin/whatsapp/templates/sync", {
			method: "POST",
		});
	},
 
	// ── Campaigns ──────────────────────────────────────────────────────────
	async getCampaigns(params?: {
		status?: string;
		limit?: number;
		offset?: number;
	}) {
		const query = params
			? `?${new URLSearchParams(
					Object.entries(params)
						.filter(([, v]) => v !== undefined)
						.map(([k, v]) => [k, String(v)]),
				).toString()}`
			: "";
		// `total` is what the list's heading counts. Dropping it here is why
		// the card printed "Campaigns (N)" where N was the page size.
		return request<{ campaigns: WaCampaign[]; total: number }>(
			`/api/admin/whatsapp/campaigns${query}`,
		);
	},
 
	async getCampaign(id: number) {
		return request<WaCampaignDetail>(
			`/api/admin/whatsapp/campaigns/${id}`,
		);
	},
 
	async createCampaign(data: {
		name: string;
		templateId: number;
		templateParams?: string;
	}) {
		return request<{ campaign: WaCampaign }>("/api/admin/whatsapp/campaigns", {
			method: "POST",
			body: data,
		});
	},
 
	async getCampaignRecipients(
		id: number,
		params?: { status?: string; limit?: number; offset?: number },
	) {
		const query = params
			? `?${new URLSearchParams(
					Object.entries(params)
						.filter(([, v]) => v !== undefined)
						.map(([k, v]) => [k, String(v)]),
				).toString()}`
			: "";
		return request<{ recipients: WaCampaignRecipient[] }>(
			`/api/admin/whatsapp/campaigns/${id}/recipients${query}`,
		);
	},
 
	async addRecipientsManual(
		id: number,
		recipients: Array<{ phone: string; name?: string }>,
	) {
		return request(`/api/admin/whatsapp/campaigns/${id}/recipients/manual`, {
			method: "POST",
			body: { recipients },
		});
	},
 
	async addRecipientsCSV(id: number, file: File) {
		return uploadFile(
			`/api/admin/whatsapp/campaigns/${id}/recipients/upload`,
			file,
		);
	},
 
	// No `addRecipientsFilter`. The route it called declared five filters and
	// honoured two — `requirementType`, `dateFrom` and `dateTo` were accepted
	// and silently dropped, so a narrowed audience quietly got the unnarrowed
	// one — and answered HTTP 200 with `{added: 0}` for any source but "pros".
	// It had no caller. Audiences come from manual paste and CSV upload.
 
	async launchCampaign(id: number) {
		return request(`/api/admin/whatsapp/campaigns/${id}/send`, {
			method: "POST",
		});
	},
 
	// ── Send ───────────────────────────────────────────────────────────────
	async checkPhone(phone: string) {
		return request<{
			exists: boolean;
			windowOpen: boolean;
			contactName: string | null;
			contactType: string | null;
			canSendText: boolean;
			lastCustomerMessageAt?: string | null;
		}>(
			`/api/admin/whatsapp/send/check-phone?phone=${encodeURIComponent(phone)}`,
		);
	},
 
	async sendMessage(data: {
		phone: string;
		message?: string;
		templateName?: string;
		language?: string;
		components?: unknown[];
	}) {
		return request<{ message: WaMessage; conversationId: number }>(
			"/api/admin/whatsapp/send",
			{
				method: "POST",
				body: data,
			},
		);
	},
 
	// No `searchContacts`. `GET /whatsapp/contacts` was an audience builder
	// that was never built: it could only ever return pros, ignored three of
	// the four filters its client sent, capped at a hardcoded 500 with no
	// truncation signal, and had no caller in the product. Route, client and
	// hook all went together.
};