# Weekly task digest

> Send every team member their open Quenza tasks each Monday, overdue and due this week, to Slack or by email, in JavaScript, Python or PHP.

Source: https://quenza.com/help/api/guides/weekly-task-digest/

Tasks are easy to forget when nobody looks at the task list. A short message every Monday morning helps: each member of the team sees what is overdue, what is due this week and for which client.

At Bright Path Coaching, Sarah Bennett and Daniel Weber get a Slack message at 8:00 every Monday. Daniel's says that the intake call notes for Emma Clarke are two days overdue and that he wanted to send Lucas Meyer his reading list by Thursday.

The script comes in JavaScript (Node.js 18 or later), Python (with `requests`) and PHP (with Guzzle, `composer require guzzlehttp/guzzle`); pick your language in the tabs. It posts to a Slack incoming webhook. Swap the last step for an email if your team does not use Slack.

## How it works

1. [List the members](https://quenza.com/help/api/members/list-members/) of the workspace.
2. For each active member, [list their tasks](https://quenza.com/help/api/tasks/list-tasks/) with `assignee_type=professional` and their ID.
3. Keep the open tasks that are overdue or due in the next seven days.
4. Send each member their list.

## The script

**JavaScript**

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

// Reads every page of a list (see Pagination).
async function all(path, query = {}) {
  const records = [];
  let url = `${API}/${path}?${new URLSearchParams({ ...query, 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();
    records.push(...page.data);
    url = page.links.next;
  }
  return records;
}

async function sendDigest(member, lines) {
  await fetch(process.env.SLACK_WEBHOOK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text: `Good morning ${member.first_name}, your open tasks this week:\n${lines.join('\n')}` }),
  });
}

// Client names by ID, so the digest can say who a task is about.
const clients = new Map((await all('clients')).map((c) => [c.id, c]));
const now = new Date();
const weekEnd = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
const day = (date) => date.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });

for (const member of await all('members')) {
  if (member.status !== 'active') continue;
  const tasks = await all('tasks', { assignee_type: 'professional', assignee_id: member.id });

  const lines = tasks
    .filter((task) => !task.is_completed && task.due_at && new Date(task.due_at) <= weekEnd)
    .map((task) => {
      const due = new Date(task.due_at);
      const client = clients.get(task.client_id);
      const icon = due < now ? ':red_circle:' : ':large_yellow_circle:';
      return `${icon} ${task.title}${client ? ` for ${client.first_name} ${client.last_name}` : ''} (due ${day(due)})`;
    });

  if (lines.length) await sendDigest(member, lines);
}
```

**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_records(path, **query):
    """Reads every page of a list (see Pagination)."""
    records = []
    url, params = f"{API}/{path}", {**query, "limit": 100}
    while url:
        response = requests.get(url, headers=HEADERS, params=params)
        response.raise_for_status()
        page = response.json()
        records += page["data"]
        url, params = page["links"]["next"], None  # the next link has the query already
    return records


def parse(timestamp):
    return datetime.fromisoformat(timestamp.replace("Z", "+00:00"))


def send_digest(member, lines):
    requests.post(os.environ["SLACK_WEBHOOK_URL"], json={
        "text": f"Good morning {member['first_name']}, your open tasks this week:\n" + "\n".join(lines),
    })


# Client names by ID, so the digest can say who a task is about.
clients = {c["id"]: c for c in all_records("clients")}
now = datetime.now(timezone.utc)
week_end = now + timedelta(days=7)

for member in all_records("members"):
    if member["status"] != "active":
        continue
    tasks = all_records("tasks", assignee_type="professional", assignee_id=member["id"])

    lines = []
    for task in tasks:
        if task["is_completed"] or not task["due_at"]:
            continue
        due = parse(task["due_at"])
        if due > week_end:
            continue
        client = clients.get(task["client_id"])
        icon = ":red_circle:" if due < now else ":large_yellow_circle:"
        name = f" for {client['first_name']} {client['last_name']}" if client else ""
        lines.append(f"{icon} {task['title']}{name} (due {due:%a %d %b})")

    if lines:
        send_digest(member, lines)
```

**PHP**

```php
<?php

require 'vendor/autoload.php';

$http = new GuzzleHttp\Client([
    'base_uri' => 'https://developers.quenza.com/v1/',
    'headers' => [
        'Authorization' => 'Bearer ' . getenv('QUENZA_API_TOKEN'),
        'Accept' => 'application/json',
    ],
]);

// Reads every page of a list (see Pagination).
function all(GuzzleHttp\Client $http, string $path, array $query = []): array
{
    $records = [];
    $query += ['limit' => 100, 'offset' => 0];
    do {
        $page = json_decode($http->get($path, ['query' => $query])->getBody(), true);
        $records = array_merge($records, $page['data']);
        $query['offset'] += $query['limit'];
    } while ($page['links']['next'] !== null);
    return $records;
}

// Client names by ID, so the digest can say who a task is about.
$clients = array_column(all($http, 'clients'), null, 'id');
$weekEnd = new DateTimeImmutable('+7 days');

foreach (all($http, 'members') as $member) {
    if ($member['status'] !== 'active') {
        continue;
    }
    $tasks = all($http, 'tasks', ['assignee_type' => 'professional', 'assignee_id' => $member['id']]);

    $lines = [];
    foreach ($tasks as $task) {
        if ($task['is_completed'] || $task['due_at'] === null) {
            continue;
        }
        $due = new DateTimeImmutable($task['due_at']);
        if ($due > $weekEnd) {
            continue;
        }
        $client = $clients[$task['client_id']] ?? null;
        $lines[] = sprintf(
            '%s %s%s (due %s)',
            $due < new DateTimeImmutable() ? ':red_circle:' : ':large_yellow_circle:',
            $task['title'],
            $client ? " for {$client['first_name']} {$client['last_name']}" : '',
            $due->format('D j M')
        );
    }

    if ($lines) {
        sendDigest($member, $lines);
    }
}

function sendDigest(array $member, array $lines): void
{
    (new GuzzleHttp\Client())->post(getenv('SLACK_WEBHOOK_URL'), ['json' => [
        'text' => "Good morning {$member['first_name']}, your open tasks this week:\n" . implode("\n", $lines),
    ]]);
}
```


Tasks without a due date are left out; add them as a separate "No due date" list if your team uses them a lot.

## Run it every Monday

Run the script with cron, a scheduled job on your hosting, or a scheduled workflow in GitHub Actions. This cron line runs it at 8:00 every Monday:

**JavaScript**

```text
0 8 * * 1 cd /path/to/digest && node task-digest.mjs
```

**Python**

```text
0 8 * * 1 cd /path/to/digest && python3 task_digest.py
```

**PHP**

```text
0 8 * * 1 cd /path/to/digest && php task-digest.php
```


## Make it your own

- **One message per person:** Slack incoming webhooks post to one channel. To message each member directly, look them up by `email` with Slack's API, or send an email to the member's `email` instead.
- **Client tasks too:** tasks a client has to do have `assignee_type` `client`. List them with `assignee_type=client` and a client's ID to remind the coach which clients still have homework open.
- **Done last week:** keep tasks with a `completed_at` in the last seven days and add a line such as "12 tasks completed last week" to keep the mood up.

[Tasks](https://quenza.com/help/working-with-clients/tasks/) explains tasks in the app.
