Developers
Menu

Projects and clients in another tool

When the same clients and projects live in Punchly and somewhere else — a CRM, a project tracker, an accounting system — someone has to keep the two lists in step. This recipe reads what changed in Punchly since the last run and applies it on the other side.

Before you start

A workspace key with projects:read (the Read-only preset includes it). To write changes back into Punchly as well, add projects:write.

The script

It prints each change and keeps a mirror in a JSON file; replace apply with calls to the other tool.

js
// Keep clients and projects in step with another tool (a CRM, a project tracker, accounting).
// Node 18 or later; no packages. Usage:
//   PUNCHLY_API_KEY=pkw_… node projects-sync.mjs
// It prints what changed since the last run and keeps a mirror in punchly-projects.json;
// replace `apply` with calls to the other tool.

import { existsSync, readFileSync, writeFileSync } from 'node:fs';

const API = process.env.PUNCHLY_API_URL ?? 'https://api.punchly.work/v1';
const KEY = process.env.PUNCHLY_API_KEY;
const STATE = process.env.PUNCHLY_SYNC_FILE ?? 'punchly-projects.json';
if (!KEY) throw new Error('Set PUNCHLY_API_KEY');

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function punchly(path) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(`${API}${path}`, { headers: { 'X-Api-Key': KEY } });
    if (res.status === 429 && attempt < 5) {
      await sleep(Number(res.headers.get('retry-after') ?? 5) * 1000);
      continue;
    }
    const text = await res.text();
    if (!res.ok) throw new Error(`GET ${path}: ${res.status} ${text}`);
    return JSON.parse(text);
  }
}

/** Every row of a list, following the cursor. */
async function all(path, params) {
  const rows = [];
  let cursor = null;
  do {
    const query = new URLSearchParams({ ...params, limit: '500', ...(cursor && { cursor }) });
    const page = await punchly(`${path}?${query}`);
    rows.push(...page.items);
    cursor = page.nextCursor;
  } while (cursor);
  return rows;
}

async function workspaceId() {
  if (process.env.PUNCHLY_WORKSPACE_ID) return process.env.PUNCHLY_WORKSPACE_ID;
  const { items } = await punchly('/me/workspaces');
  if (items.length !== 1) throw new Error('Set PUNCHLY_WORKSPACE_ID: the key reaches several');
  return items[0].workspaceId;
}

const state = existsSync(STATE)
  ? JSON.parse(readFileSync(STATE, 'utf8'))
  : { since: '1970-01-01T00:00:00Z', clients: {}, projects: {} };

function apply(kind, row) {
  const known = state[kind][row.id];
  const action = !known ? 'create' : row.archivedAt ? 'archive' : 'update';
  console.log(`${action} ${kind.slice(0, -1)}: ${row.name}`);
  state[kind][row.id] = { id: row.id, name: row.name, archived: row.archivedAt !== null };
}

const wid = await workspaceId();
const started = new Date().toISOString();
// status=all: archiving is a change the other tool should hear about too.
const changed = { updatedSince: state.since, status: 'all' };
for (const client of await all(`/workspaces/${wid}/clients`, changed)) apply('clients', client);
for (const project of await all(`/workspaces/${wid}/projects`, changed)) apply('projects', project);

// Lists have no "last change" order, so the next run starts from when this one did.
state.since = started;
writeFileSync(STATE, JSON.stringify(state, null, 2));
console.log(
  `${Object.keys(state.clients).length} clients, ${Object.keys(state.projects).length} projects mirrored`,
);
bash
PUNCHLY_API_KEY=pkw_… node projects-sync.mjs
text
create client: Acme Ltd
create project: Acme website
update project: Acme website (phase 2)
archive project: Old retainer
1 clients, 3 projects mirrored

Notes