# A collections campaign that follows the rules

> Payment reminders by phone: an assistant that confirms identity before it mentions a debt, records promises to pay through your server, hands hardship to people, and dials only within calling hours, never on Shabbat. With webhooks for every attempt.

Collection calls are hard calls. This recipe builds a campaign that makes them carefully: the assistant confirms it is talking to the right person before it says anything about a debt, records a promise to pay in your system, and hands anyone in hardship or disputing the debt to a person. The dialer keeps to the calling hours, Shabbat and holidays, and your do-not-call list, for every call.

> **Rules first, and counsel**
>
> A collection call is a `service` call: it isn't advertising, so §30A marketing consent and the national do-not-call registry don't apply to it, but your do-not-call list, the calling hours, Shabbat and holidays do, and an opt-out stops all calls. If a call also offers something (a new loan, a payment plan with a fee), it is marketing: run it as a separate `marketing` campaign, with consent. Collections are regulated: have counsel review your scripts and process. See [compliance](https://docs.morevoice.ai/guides/compliance/).

## How it works

| Piece | What it does |
| --- | --- |
| The assistant | Opens with who it is and asks for the person by name. Only after the person confirms, with the last four digits of their ID, does it mention the balance. |
| `record_promise` | A custom tool on your server: the amount, the date and the method the person agreed to. |
| `transfer_call` | Hardship, a dispute, or "I want a person": straight to your collections team's queue. |
| The campaign | `service`, narrow calling windows, Shabbat and holidays respected, three attempts at most, no messages on voicemail, and the AI and recording disclosure on. |
| Webhooks | Every attempt (`contact.attempted`), every final result (`contact.completed`) and every opt-out (`contact.opted_out`) update the account in your system. |

The account details reach the assistant as the contact's **variables**: `{{name}}`, `{{amount}}`, `{{due_date}}`, `{{reference}}` and `{{id_last4}}` in its instructions are filled in per call.

## Before you start

- A **test key**, your **tool signing secret** for test mode, and a **webhook endpoint** for `contact.attempted`, `contact.completed` and `contact.opted_out` (see [webhooks](https://docs.morevoice.ai/webhooks/setup/#add-an-endpoint)).
- A queue for your collections team, to transfer to (`collections-team` below): see [human agents and queues](https://docs.morevoice.ai/guides/human-agents/).
- Node.js 18 or later, and the SDK: `npm install @morevoice/sdk`.

## Build it

1. **Create the assistant and the campaign.** Read the instructions closely: they put identity first, never threaten, and hand over instead of arguing. The campaign's windows are narrower than the law allows on purpose.

   ```ts title="setup.ts"
   // Step 1: the collections assistant and its campaign. Collection calls are `service` calls; the dialer still applies
   // your do-not-call list, the calling hours, Shabbat and holidays to every one of them.
   import MoreVoice from "@morevoice/sdk";

   const mv = new MoreVoice(); // reads MOREVOICE_API_KEY

   const assistant = await mv.assistants.create({
   	name: "Collections: payment reminders",
   	language: "he",
   	// No debt details before the person confirms who they are: whoever answers may not be the customer.
   	first_message: "שלום, מדברת הנציגה הדיגיטלית של {{company}}. האם אני מדברת עם {{name}}?",
   	system_prompt: [
   		"You call customers of {{company}} about an unpaid balance, in Hebrew. You are a digital assistant; say so if asked.",
   		"1. Identity first: until the person confirms they are {{name}} and gives the last four digits of their ID number, matching {{id_last4}}, say nothing about the debt. If it is someone else, ask when {{name}} can be reached, thank them and end the call.",
   		"2. Then say the balance is {{amount}} NIS, due since {{due_date}} (reference {{reference}}), and ask when they can pay.",
   		"3. When they commit to a date and an amount, read both back, then call record_promise.",
   		"4. If they describe hardship (illness, unemployment, a loss) or dispute the debt, don't argue: offer a person and transfer the call.",
   		"5. Never threaten, never pressure, never call the debt by another amount. If they ask not to be called again, confirm and end the call.",
   	].join("\n"),
   	tools: {
   		end_call: true,
   		get_current_time: true,
   		transfer_call: { destination: "queue:collections-team" },
   		custom: [
   			{
   				name: "record_promise",
   				description: "Record the customer's promise to pay: the amount and the date they agreed to.",
   				parameters: {
   					type: "object",
   					properties: {
   						reference: { type: "string", description: "The account's reference, {{reference}}" },
   						amount: { type: "number", description: "The amount in NIS" },
   						pay_by: { type: "string", description: "The date, YYYY-MM-DD" },
   						method: { type: "string", enum: ["card", "bank_transfer", "payment_link", "other"] },
   					},
   					required: ["reference", "amount", "pay_by"],
   				},
   				url: process.env.TOOL_URL!, // your collections system: see promise-server.ts
   				timeout_seconds: 10,
   			},
   		],
   	},
   });

   const campaign = await mv.campaigns.create({
   	name: "Payment reminders: November",
   	purpose: "service",
   	assistant_id: assistant.id,
   	schedule: {
   		timezone: "Asia/Jerusalem",
   		// Narrower than the legal hours: mid-morning to early evening, a short Friday, never Shabbat or a holiday.
   		windows: [
   			{ days: ["sun", "mon", "tue", "wed", "thu"], start: "10:00", end: "19:00" },
   			{ days: ["fri"], start: "09:00", end: "12:00" },
   		],
   		respect_shabbat: true,
   		respect_holidays: true,
   	},
   	retry: {
   		max_attempts: 3,
   		busy: { enabled: true, delay_minutes: 30 },
   		no_answer: { enabled: true, delay_minutes: 180 },
   		voicemail: { enabled: false, delay_minutes: 180 }, // a debt is not a voicemail topic
   		declined: { enabled: false, delay_minutes: 240 },
   		failed: { enabled: true, delay_minutes: 30 },
   	},
   	amd: { mode: "hangup" },
   	disclosure: { enabled: true, text: "שלום, זוהי שיחה ממערכת בינה מלאכותית, והשיחה מוקלטת." },
   	dispositions: ["promise_to_pay", "paid_already", "hardship", "dispute", "wrong_person", "callback"],
   	max_concurrent: 5,
   });
   console.log(`ASSISTANT_ID=${assistant.id}\nCAMPAIGN_ID=${campaign.id}`);
   ```

2. **Add the people to call**, with what the assistant may say about each one. Numbers on your do-not-call list are kept with the status `dnc` and never dialled.

   ```ts title="add-debtors.ts"
   // Step 2: add the customers to call, with what the assistant may say about each one. Numbers on your do-not-call list
   // are kept with the status `dnc` and never dialled. In test mode, try +972500000001 (answers), +972500000002 (busy,
   // retried) and +972500000004 (on the do-not-call list).
   import MoreVoice from "@morevoice/sdk";

   const mv = new MoreVoice(); // reads MOREVOICE_API_KEY
   const campaignId = process.env.CAMPAIGN_ID!;

   const debtors = [
   	{ phone: "+972500000001", name: "דנה לוי", reference: "INV-1042", amount: "1,250", due_date: "1 באוקטובר", id_last4: "4821" },
   	{ phone: "+972500000002", name: "יוסי כהן", reference: "INV-1043", amount: "380", due_date: "15 בספטמבר", id_last4: "1177" },
   	{ phone: "+972500000004", name: "רונית אזולאי", reference: "INV-1044", amount: "2,900", due_date: "20 בספטמבר", id_last4: "3365" },
   ];

   const batch = await mv.campaigns.contacts.create(campaignId, {
   	default_country: "IL",
   	contacts: debtors.map(({ phone, name, ...variables }) => ({ phone, name, variables: { ...variables, company: "אשראי השרון" } })),
   });
   console.log(`${batch.imported} added, ${batch.rejected} rejected`, batch.rejected_reasons);
   ```

3. **Receive promises and results.** One server serves the `record_promise` tool and the campaign's webhooks. An opt-out marks the account so your other channels stop too.

   ```ts title="promise-server.ts"
   // Step 4: your collections system's side. The record_promise tool lands here during the call, and the campaign's
   // webhooks keep each account up to date: every attempt, the final result, the call's analysis and any opt-out.
   import { createServer } from "node:http";
   import { defineTool, tools, webhooks, WebhookVerificationError, type MoreVoiceEvent } from "@morevoice/sdk";

   // Your collections database goes here: accounts by phone number, promises by account reference.
   interface Account {
   	phone: string;
   	attempts: number;
   	status: string;
   	outcome?: string | null;
   	doNotCall?: boolean;
   }
   const accounts = new Map<string, Account>();
   const promises = new Map<string, { amount: number; pay_by: string; method?: string; callId: string }>();

   const account = (phone: string) => {
   	const a = accounts.get(phone) ?? { phone, attempts: 0, status: "pending" };
   	accounts.set(phone, a);
   	return a;
   };

   const toolHandler = tools.nodeHandler({
   	secret: process.env.MOREVOICE_TOOL_SECRET!,
   	handlers: {
   		record_promise: defineTool({
   			parameters: {
   				type: "object",
   				properties: { reference: { type: "string" }, amount: { type: "number" }, pay_by: { type: "string" }, method: { type: "string" } },
   				required: ["reference", "amount", "pay_by"],
   			},
   			async handler({ reference, amount, pay_by, method }, ctx) {
   				promises.set(reference, { amount, pay_by, method, callId: ctx.call.id });
   				return { result: { recorded: true, reference, amount, pay_by } }; // the assistant confirms it in its own words
   			},
   		}),
   	},
   });

   const webhookSecret = process.env.MOREVOICE_WEBHOOK_SECRET!;

   async function onEvent(event: MoreVoiceEvent): Promise<void> {
   	switch (event.type) {
   		case "contact.attempted": {
   			const c = event.data.object;
   			if (!c.phone) break;
   			Object.assign(account(c.phone), { attempts: c.attempt_number ?? 0, status: c.status ?? "attempted" });
   			break;
   		}
   		case "contact.completed": {
   			const c = event.data.object;
   			if (c.phone) Object.assign(account(c.phone), { status: c.status ?? "done", outcome: c.disposition ?? null });
   			break;
   		}
   		case "contact.opted_out": {
   			const c = event.data.object;
   			if (c.phone) account(c.phone).doNotCall = true; // stop every other channel too: letters, texts, agents
   			break;
   		}
   	}
   }

   createServer(async (req, res) => {
   	if (req.method === "POST" && req.url === "/morevoice/tools") return void toolHandler(req, res);
   	if (req.method !== "POST" || req.url !== "/webhooks/morevoice") return void res.writeHead(404).end();
   	const chunks: Buffer[] = [];
   	for await (const chunk of req) chunks.push(chunk as Buffer);
   	try {
   		await onEvent(webhooks.constructEvent(Buffer.concat(chunks), req.headers, webhookSecret));
   		res.writeHead(204).end();
   	} catch (err) {
   		res.writeHead(err instanceof WebhookVerificationError ? 400 : 500).end();
   	}
   }).listen(Number(process.env.PORT ?? 3000));

   // A report for your team: where each account stands, and the promises made.
   setInterval(() => {
   	console.table([...accounts.values()]);
   	console.table(Object.fromEntries(promises));
   }, 60_000).unref();
   ```

4. **Check, then start.** The pre-flight says how many contacts can be called and when the next window opens; `start` runs the same checks and refuses with `409 preflight_failed` when something blocks.

   ```ts title="start.ts"
   // Step 3: check, then start. The pre-flight lists everything that would stop the campaign (no connection, no caller
   // ID, windows that never open); start runs it again and answers 409 preflight_failed when something blocks.
   import MoreVoice from "@morevoice/sdk";

   const mv = new MoreVoice(); // reads MOREVOICE_API_KEY
   const campaignId = process.env.CAMPAIGN_ID!;

   const preflight = await mv.campaigns.preflight(campaignId);
   console.log(`${preflight.dialable} to call; next window ${preflight.next_window_at ?? "none in 3 weeks"}`);
   for (const w of preflight.warnings) console.log(`warning: ${w}`);
   if (!preflight.ok) throw new Error(`can't start: ${preflight.errors.join("; ")}`);

   const campaign = await mv.campaigns.start(campaignId);
   console.log(`${campaign.id} is ${campaign.state}`); // "running": it dials whenever a window is open
   ```

## Try it in test mode

With a test key the campaign dials the virtual carrier, and the [test numbers](https://docs.morevoice.ai/get-started/test-mode/#test-numbers) behave like people: `+972500000001` answers and talks, `+972500000002` is busy and is retried by your retry policy, and `+972500000004` is on the do-not-call list and is never dialled. A test campaign needs no SIP connection.

Calling hours apply in test mode too. Outside them, `start` succeeds, the campaign is `running`, the pre-flight's `next_window_at` says when dialling begins, and a [`campaign.blocked`](https://docs.morevoice.ai/webhooks/events/#campaign.blocked) event tells your webhook why it waits. Run it during the day to hear the calls.

## Go live

- Use a live key, a SIP connection and a caller ID your customers recognise. Keep `disclosure` on.
- Take the variables from your collections system at import time, and never put more in them than the call needs: the assistant reads what it is given.
- Review the outcomes (`contact.completed`, `disposition`) and listen to a sample of calls every week, especially transfers and opt-outs. [QA scorecards](https://docs.morevoice.ai/guides/qa/) can score every call for you.
- Stop the campaign when a payment arrives: set the contact to `skipped` ([requeue or skip a contact](https://docs.morevoice.ai/guides/campaigns/#requeue-or-skip-a-contact)).
