All files / src/hooks/queries useWhatsAppQueries.ts

100% Statements 82/82
77.77% Branches 14/18
100% Functions 52/52
100% Lines 81/81

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                10x 4x 6x 6x 4x           2x     1x 1x                                               6x   6x     3x 3x                           3x     1x 1x                   1x   1x                       1x   1x     1x               3x   3x   2x 2x     2x               1x   1x 1x   1x     1x     1x                   4x     2x 2x             1x   1x 1x   1x               1x   1x           1x   1x               2x   2x 1x   1x                           4x   4x     2x 2x                                   3x     1x 1x             1x   1x         1x   1x               1x   1x 1x   1x     1x                             3x     1x 1x                   3x     1x 1x                   1x   1x             1x   1x     1x                   1x   1x             1x   1x                 2x   2x             1x   1x                        
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { whatsappApi } from "../../lib/api";
import { queryKeys } from "../../lib/query-keys";
 
/** Convert params to a stable string-valued object for use as a query key fragment. */
function toFilterKey(
	params?: Record<string, unknown>,
): Record<string, string> | undefined {
	if (!params) return undefined;
	const entries = Object.entries(params)
		.filter(([, v]) => v !== undefined)
		.map(([k, v]) => [k, String(v)]);
	return entries.length > 0 ? Object.fromEntries(entries) : undefined;
}
 
// ─── Stats ───────────────────────────────────────────────────────────────────
 
export function useWhatsAppStats() {
	return useQuery({
		queryKey: queryKeys.admin.whatsapp.stats(),
		queryFn: async () => {
			const res = await whatsappApi.getStats();
			return res.data;
		},
		staleTime: 1000 * 60 * 2, // 2 min
	});
}
 
// ─── Conversations ───────────────────────────────────────────────────────────
 
/**
 * Returns the page, not just the rows. `total` is what the inbox pager counts
 * against; dropping it here is why the list silently stopped at the API's
 * default of 50 with no way to reach the rest.
 */
export function useWhatsAppConversations(params?: {
	contactType?: string;
	search?: string;
	hasUnread?: boolean;
	hasCustomerReply?: boolean;
	answeredByUs?: boolean;
	/** The triage backlog, which the server also orders oldest-waiting-first. */
	waitingOnUs?: boolean;
	limit?: number;
	offset?: number;
}) {
	const filterKey = toFilterKey(params);
 
	return useQuery({
		queryKey: queryKeys.admin.whatsapp.conversations(filterKey),
		queryFn: async () => {
			const res = await whatsappApi.getConversations(params);
			return {
				conversations: res.data?.conversations ?? [],
				total: res.data?.total ?? 0,
			};
		},
		// A failed list must not look like an empty one. The page renders
		// `isError` as "the clock is still running, we just cannot see it";
		// retrying forever behind an empty panel is how a triage screen reads
		// "nothing to do" during an outage.
		staleTime: 1000 * 30, // 30 sec for real-time feel
	});
}
 
export function useWhatsAppConversation(id: number | null) {
	return useQuery({
		queryKey: queryKeys.admin.whatsapp.conversation(id as number),
		queryFn: async () => {
			const res = await whatsappApi.getConversation(id as number);
			return res.data;
		},
		enabled: id !== null,
		staleTime: 1000 * 10, // 10 sec
		refetchInterval: 1000 * 10, // Poll every 10 sec
		refetchIntervalInBackground: false,
	});
}
 
export function useReplyToConversation() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: ({
			id,
			body,
		}: {
			id: number;
			body: {
				message?: string;
				templateName?: string;
				language?: string;
				components?: unknown[];
			};
		}) => whatsappApi.replyToConversation(id, body),
		onSuccess: (_, variables) => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.conversation(variables.id),
			});
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.conversations(),
			});
		},
	});
}
 
export function useStartProConversation() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: async (proId: string) => {
			const res = await whatsappApi.startProConversation(proId);
			return res.data?.conversation;
		},
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.conversations(),
			});
		},
	});
}
 
export function useMarkConversationRead() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: (id: number) => whatsappApi.markConversationRead(id),
		onSuccess: (_, id) => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.conversation(id),
			});
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.conversations(),
			});
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.stats(),
			});
		},
	});
}
 
// ─── Templates ───────────────────────────────────────────────────────────────
 
export function useWhatsAppTemplates() {
	return useQuery({
		queryKey: queryKeys.admin.whatsapp.templates(),
		queryFn: async () => {
			const res = await whatsappApi.getTemplates();
			return res.data?.templates ?? [];
		},
		staleTime: 1000 * 60 * 5, // 5 min
	});
}
 
export function useSyncTemplates() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: () => whatsappApi.syncTemplates(),
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.templates(),
			});
		},
	});
}
 
export function useCreateTemplate() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: (data: {
			name: string;
			language: string;
			category: string;
			components: unknown[];
		}) => whatsappApi.createTemplate(data),
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.templates(),
			});
		},
	});
}
 
export function useDeleteTemplate() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: (id: number) => whatsappApi.deleteTemplate(id),
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.templates(),
			});
		},
	});
}
 
// ─── Campaigns ───────────────────────────────────────────────────────────────
 
export function useWhatsAppCampaigns(params?: {
	status?: string;
	limit?: number;
	offset?: number;
}) {
	const filterKey = toFilterKey(params);
 
	return useQuery({
		queryKey: queryKeys.admin.whatsapp.campaigns(filterKey),
		queryFn: async () => {
			const res = await whatsappApi.getCampaigns(params);
			return {
				campaigns: res.data?.campaigns ?? [],
				total: res.data?.total ?? 0,
			};
		},
		staleTime: 1000 * 60 * 2,
	});
}
 
/**
 * The campaign detail response, not just the campaign row.
 *
 * Returning the whole envelope is what lets a detail screen name its template
 * and count its recipients without a second request, and what carries
 * `stoppable` — the server's answer to "can this be cancelled", which the page
 * must not assume.
 */
export function useWhatsAppCampaign(id: number | null) {
	return useQuery({
		queryKey: queryKeys.admin.whatsapp.campaign(id as number),
		queryFn: async () => {
			const res = await whatsappApi.getCampaign(id as number);
			return res.data;
		},
		enabled: id !== null,
	});
}
 
export function useCreateCampaign() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: (data: {
			name: string;
			templateId: number;
			templateParams?: string;
		}) => whatsappApi.createCampaign(data),
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.campaigns(),
			});
		},
	});
}
 
export function useLaunchCampaign() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: (id: number) => whatsappApi.launchCampaign(id),
		onSuccess: (_, id) => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.campaign(id),
			});
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.campaigns(),
			});
		},
	});
}
 
/**
 * The first 100 recipients. There is no pager, and the route returns no total
 * for this slice — so the screen that renders it must say "the first 100 of
 * N", taking N from the detail response's `recipientTotal`. A 5 000-recipient
 * campaign showing 100 rows with no indication that it is a slice is the
 * defect this comment exists to stop coming back.
 */
export function useCampaignRecipients(campaignId: number | null) {
	return useQuery({
		queryKey: queryKeys.admin.whatsapp.campaignRecipients(campaignId as number),
		queryFn: async () => {
			const res = await whatsappApi.getCampaignRecipients(campaignId as number, { limit: 100 });
			return res.data?.recipients ?? [];
		},
		enabled: campaignId !== null,
		staleTime: 1000 * 30, // 30 sec
	});
}
 
// ─── Phone Check ─────────────────────────────────────────────────────────────
 
export function useCheckPhone(phone: string | null) {
	return useQuery({
		queryKey: queryKeys.admin.whatsapp.checkPhone(phone ?? ""),
		queryFn: async () => {
			const res = await whatsappApi.checkPhone(phone as string);
			return res.data;
		},
		enabled: !!phone,
		staleTime: 1000 * 30, // 30 sec
	});
}
 
// ─── Send ────────────────────────────────────────────────────────────────────
 
export function useSendMessage() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: (data: {
			phone: string;
			message?: string;
			templateName?: string;
			language?: string;
			components?: unknown[];
		}) => whatsappApi.sendMessage(data),
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.conversations(),
			});
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.whatsapp.stats(),
			});
		},
	});
}
 
// ─── Recipients ──────────────────────────────────────────────────────────────
 
export function useAddRecipientsManual() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: ({
			campaignId,
			recipients,
		}: {
			campaignId: number;
			recipients: Array<{ phone: string; name?: string }>;
		}) => whatsappApi.addRecipientsManual(campaignId, recipients),
		onSuccess: (_, { campaignId }) => {
			queryClient.invalidateQueries({
				queryKey:
					queryKeys.admin.whatsapp.campaignRecipients(campaignId),
			});
		},
	});
}
 
export function useAddRecipientsCSV() {
	const queryClient = useQueryClient();
 
	return useMutation({
		mutationFn: ({
			campaignId,
			file,
		}: {
			campaignId: number;
			file: File;
		}) => whatsappApi.addRecipientsCSV(campaignId, file),
		onSuccess: (_, { campaignId }) => {
			queryClient.invalidateQueries({
				queryKey:
					queryKeys.admin.whatsapp.campaignRecipients(campaignId),
			});
		},
	});
}
 
// No `useWhatsAppContacts`. `GET /whatsapp/contacts` was an audience builder
// that was never built — pros only, three of its four filters ignored, a
// hardcoded 500-row cap with no truncation signal, and no caller outside its
// own unit test. Route, client method and hook were deleted together.