# Follow up on invitations

> Find clients who have not accepted their Quenza invitation after a week and remind your coaches, so no new client gets lost before the start.

Source: https://quenza.com/help/api/guides/follow-up-on-invitations/

A client who never opens their invitation never sees their first activity. Most of them only need a friendly reminder. This guide finds clients whose invitation is more than a week old and still not accepted, and sends their coach a short list every Monday.

At Bright Path Coaching, Lucas Meyer was invited ten days ago and has not set up his account. On Monday, Sarah Bennett's list says so, and she sends him the invitation again with one click.

The examples come in JavaScript (Node.js 18 or later), Python (with `requests`) and PHP (with Guzzle); pick your language in the tabs.

## Find the waiting clients

[List the clients](https://quenza.com/help/api/clients/list-clients/) and keep those with the status `pending` whose `invited_at` is more than seven days ago:

**JavaScript**

```js
const API = 'https://developers.quenza.com/v1';
const headers = { Authorization: `Bearer ${process.env.QUENZA_API_TOKEN}`, Accept: 'application/json' };

async function* allClients() {
  let url = `${API}/clients?limit=100`;
  while (url) {
    const response = await fetch(url, { headers });
    if (!response.ok) throw new Error(`Quenza API error ${response.status}`);
    const page = await response.json();
    yield* page.data;
    url = page.links.next;
  }
}

const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
const waiting = [];
for await (const client of allClients()) {
  if (client.status === 'pending' && client.invited_at && Date.parse(client.invited_at) < weekAgo) {
    waiting.push(client);
  }
}
```

**Python**

```python
import os
from datetime import datetime, timedelta, timezone

import requests

API = "https://developers.quenza.com/v1"
HEADERS = {
    "Authorization": f"Bearer {os.environ['QUENZA_API_TOKEN']}",
    "Accept": "application/json",
}


def all_clients():
    url = f"{API}/clients?limit=100"
    while url:
        response = requests.get(url, headers=HEADERS)
        response.raise_for_status()
        page = response.json()
        yield from page["data"]
        url = page["links"]["next"]


week_ago = datetime.now(timezone.utc) - timedelta(days=7)
waiting = [
    c for c in all_clients()
    if c["status"] == "pending"
    and c["invited_at"]
    and datetime.fromisoformat(c["invited_at"].replace("Z", "+00:00")) < week_ago
]
```

**PHP**

```php
<?php

require 'vendor/autoload.php';

$http = new GuzzleHttp\Client(['headers' => [
    'Authorization' => 'Bearer ' . getenv('QUENZA_API_TOKEN'),
    'Accept' => 'application/json',
]]);

$weekAgo = new DateTimeImmutable('-7 days');
$waiting = [];
$url = 'https://developers.quenza.com/v1/clients?limit=100';
while ($url !== null) {
    $page = json_decode($http->get($url)->getBody(), true);
    foreach ($page['data'] as $client) {
        if ($client['status'] === 'pending' && $client['invited_at'] !== null
            && new DateTimeImmutable($client['invited_at']) < $weekAgo) {
            $waiting[] = $client;
        }
    }
    $url = $page['links']['next'];
}
```


## Send the list

Send the list to whoever follows up, for example by email. Use your mail provider's server settings; most need a login as well:

**JavaScript**

```js
 // npm install nodemailer

const lines = waiting
  .sort((a, b) => a.invited_at.localeCompare(b.invited_at))
  .map((c) => `- ${c.first_name} ${c.last_name} (${c.email}), invited ${c.invited_at.slice(0, 10)}`);

if (lines.length) {
  const mail = nodemailer.createTransport({ host: process.env.SMTP_HOST, port: Number(process.env.SMTP_PORT ?? 25) });
  await mail.sendMail({
    from: 'reports@example.com',
    to: 'sarah.bennett@example.com',
    subject: `${lines.length} clients have not accepted their invitation yet`,
    text:
      'These clients were invited more than a week ago and have not set up their account:\n\n' +
      lines.join('\n') +
      "\n\nResend the invitation from the client's ⋯ menu in Quenza.",
  });
}
```

**Python**

```python
import smtplib
from email.message import EmailMessage

lines = [
    f"- {c['first_name']} {c['last_name']} ({c['email']}), invited {c['invited_at'][:10]}"
    for c in sorted(waiting, key=lambda c: c["invited_at"])
]

if lines:
    message = EmailMessage()
    message["Subject"] = f"{len(lines)} clients have not accepted their invitation yet"
    message["From"] = "reports@example.com"
    message["To"] = "sarah.bennett@example.com"
    message.set_content(
        "These clients were invited more than a week ago and have not set up their account:\n\n"
        + "\n".join(lines)
        + "\n\nResend the invitation from the client's ⋯ menu in Quenza."
    )
    with smtplib.SMTP(os.environ["SMTP_HOST"], int(os.environ.get("SMTP_PORT", 25))) as smtp:
        smtp.send_message(message)
```

**PHP**

```php
usort($waiting, fn (array $a, array $b) => strcmp($a['invited_at'], $b['invited_at']));
$lines = array_map(
    fn (array $c) => sprintf('- %s %s (%s), invited %s', $c['first_name'], $c['last_name'], $c['email'], substr($c['invited_at'], 0, 10)),
    $waiting,
);

if ($lines) {
    // mail() uses your server's mail setup; for an SMTP server, use symfony/mailer instead.
    mail(
        'sarah.bennett@example.com',
        count($lines) . ' clients have not accepted their invitation yet',
        "These clients were invited more than a week ago and have not set up their account:\n\n"
            . implode("\n", $lines)
            . "\n\nResend the invitation from the client's ⋯ menu in Quenza.",
        ['From' => 'reports@example.com', 'Content-Type' => 'text/plain; charset=utf-8'],
    );
}
```


Run it once a week, for example every Monday morning with cron.

## Resend the invitation

The API cannot resend invitations. In Quenza, open the client's **⋯** menu and choose **Resend Invitation**. See [Add clients](https://quenza.com/help/clients/add-clients/).

## Make it your own

- **Per coach:** a token sees every client in the workspace, and the client record does not say who their professional is. To split the list per coach, keep the mapping in your own system, for example the CRM that created the client.
- **Know the moment they start:** the **Client Invitation Accepted** [webhook](https://quenza.com/help/integrations/webhooks/) tells your system as soon as a client sets up their account, so you can thank them or mark them as started in your CRM.
- **Clean up:** archive clients who never respond after several reminders with [Archive a client](https://quenza.com/help/api/clients/archive-a-client/), so your lists stay short. Archived clients still count toward your client limit; to free a place, delete them in Quenza. See [Client limits](https://quenza.com/help/billing/client-limits/).
