Back to Docs

Triggers

Events, cron, and action links — with handler recipes for each.

Every extension has to declare at least one trigger. You can mix them freely — an extension can react to three events, run nightly on cron, and expose an action button, all from the same manifest.

This page covers the three trigger families and shows a real handler for each. prosaic.context.trigger tells your code which one fired: the event type, "cron" or "action.link". Replies to emails your extension sent arrive as a fourth, "email.reply" — see Replies.

Events

The platform emits events when domain things happen. If an event matches your manifest and the extension is installed on that entity, the runtime queues an execution.

Declared like this:

toml
[[targets.events]]
type = "journal.posted"

[[targets.events]]
type = "transaction.reconciled"

The full list:

Event typeFires wheninput payload
journal.createdA manual journal is created{ journalId: string, logicalJournalId: string }
journal.postedA journal is posted (becomes final){ journalId: string }
journal.voidedA journal is voided{ journalId: string, reversalJournalId: string }
transaction.reconciledA bank transaction is matched to a journal{ transactionId: string, journalId: string }
file.uploadedA file is uploaded to an entity{ fileId: string, filename: string }
gst.period.rolloverA new GST period starts (phase: 'started') or the previous period's return is finalised (phase: 'previous-finalised'){ phase: 'started' | 'previous-finalised', gstReturnId: string, periodStart: string, periodEnd: string, dueDate: string, gstPeriodMonths: 1 | 2 | 6, previousReturnId: string | null }
gst.return.finalisedA GST return is finalised (draft → finalised); its figures are locked{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string | null, isAmendment: boolean }
gst.return.reverted_to_draftA finalised or rejected GST return is reverted to draft{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string | null, isAmendment: boolean }
gst.return.filedA finalised GST return is filed with IRD (finalised → filed){ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string | null, isAmendment: boolean }
gst.return.acceptedIRD accepts a filed GST return (filed → accepted){ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string | null, isAmendment: boolean }
gst.return.rejectedIRD rejects a filed GST return (filed → rejected){ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string | null, isAmendment: boolean, rejectionCode: string, rejectionMessage: string }
gst.return.awaiting_paymentAn accepted GST return has an outstanding IRD balance (accepted → awaiting_payment){ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string | null, isAmendment: boolean, balance: string }
gst.return.completedA GST return reaches its end state — paid/settled (auto) or marked completed (manual){ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string | null, isAmendment: boolean }

Handler recipe — react to journal.posted

toml
name = "journal-posted-notifier"
version = "0.0.1"

[scopes]
required = ["read:journals", "read:entities", "send:email"]

[[targets.events]]
type = "journal.posted"
typescript
const { input, entityId } = prosaic.context;
const journal = await prosaic.journals.get(input.journalId);
const entity = await prosaic.entities.get(entityId);
// The date is midnight in the entity's timezone, stored as UTC.
const date = new Date(journal.date).toLocaleDateString('en-CA', {
  timeZone: entity.timezone ?? 'Pacific/Auckland',
});

await prosaic.email.send({
  to: 'accountant@example.com',
  subject: `Journal posted — ${entity.name}`,
  text: `A journal dated ${date} was posted.\n\n${journal.narration}`,
  emailMode: 'outbound-only',
});

Handler recipe — chase commission statements when a new GST period starts

gst.period.rollover fires twice through the GST lifecycle. Filter on input.phase to pick a moment:

  • 'started' — fires on day 1 (NZ time) of a new period, when the draft return is created. There is no triggering user, so this phase cannot use email.send with onBehalf: true.
  • 'previous-finalised' — fires when someone finalises the prior period's return. The person who finalised it is the triggering user.
toml
name = "commission-statement-chaser"
version = "0.0.1"

[scopes]
required = ["read:entities", "send:email"]

[[targets.events]]
type = "gst.period.rollover"
typescript
const CLIENT_EMAIL = 'client@example.com'; // Your client's address

async function main(): Promise<void> {
  const { trigger, input, entityId } = prosaic.context;

  // The client's reply runs this extension again.
  if (trigger === 'email.reply') {
    prosaic.log.info('Client replied', {
      from: input.fromAddress,
      subject: input.subject,
    });
    return;
  }

  if (input.phase !== 'started') return;

  const entity = await prosaic.entities.get(entityId);
  const localDate = (iso: string): string =>
    new Date(iso).toLocaleDateString('en-CA', {
      timeZone: entity.timezone ?? 'Pacific/Auckland',
    });

  await prosaic.email.send({
    to: CLIENT_EMAIL,
    subject: 'New GST period — please send your commission statements',
    text: `Hi ${entity.name},\n\nA new GST period started on ${localDate(input.periodStart)} (due ${localDate(input.dueDate)}). Please reply with your latest commission statements when ready.\n\nThanks.`,
  });
}

await main();

Gotchas

  • Each matching event gets its own execution. If you have two [[targets.events]] blocks and both fire, your code runs twice.
  • Events are per entity. An extension only fires for entities it's installed on.
  • Order isn't guaranteed. If you need ordering, track it yourself in storage.
  • Errors in your code aren't retried. The run is recorded as failed, with your logs and the error. The queue does retry a job when the platform itself fails, so make handlers safe to run twice — a dedupe key in storage is usually enough.

Cron

Runs on a schedule. One cron block per extension, five-field Unix syntax, all UTC.

toml
[targets.cron]
schedule = "0 9 * * *"     # 09:00 UTC daily

A cron runs once for each entity the extension is installed on. prosaic.context.input is undefined — the trigger is the schedule itself. context.entityId says which entity this run is for, and every prosaic.* call is already scoped to it.

Handler recipe — daily unreconciled summary

toml
name = "daily-unreconciled-summary"
version = "0.0.1"

[scopes]
required = ["read:transactions", "read:entities", "send:email"]

[targets.cron]
schedule = "0 20 * * 0-4"   # 08:00 or 09:00 NZ time, Monday to Friday
typescript
async function main(): Promise<void> {
  const { data, totalCount } = await prosaic.transactions.list({
    isReconciled: false,
  });

  if (totalCount === 0) {
    prosaic.log.info('Nothing unreconciled, skipping email');
    return;
  }

  const entity = await prosaic.entities.get(prosaic.context.entityId);
  const timeZone = entity.timezone ?? 'Pacific/Auckland';
  const lines = data
    .slice(0, 20)
    .map((t) => {
      const date = new Date(t.date).toLocaleDateString('en-CA', { timeZone });
      return `• ${date}  ${t.amount}  ${t.description}`;
    })
    .join('\n');

  await prosaic.email.send({
    to: 'client@example.com',
    subject: `${totalCount} unreconciled transactions`,
    text: `The 20 most recent:\n\n${lines}`,
    emailMode: 'outbound-only',
  });
}

await main();

Schedule cheatsheet

ScheduleRuns
*/15 * * * *Every 15 minutes
0 * * * *Every hour on the hour
0 9 * * *09:00 UTC daily
0 9 * * 1-509:00 UTC weekdays
0 9 * * 109:00 UTC every Monday
0 9 1 * *09:00 UTC on the 1st every month
0 0 1 */3 *Midnight UTC every quarter-start

Schedules are in UTC, so convert from local time. New Zealand is UTC+12, or UTC+13 in daylight saving; eastern Australia is UTC+10, or UTC+11. A morning run in either country is the previous evening in UTC, which is why the recipe above uses 0-4 (Sunday to Thursday in UTC) for Monday to Friday locally.

A button in the Prosaic UI. User clicks, your extension runs. Good for "look at this thing" or "do this thing to these things" flows.

toml
[[targets.actions]]
placement = "transaction.single"
label = "Analyse this"

[[targets.actions]]
placement = "transaction.bulk"
label = "Analyse selected"
PlacementShows upinput payload
transaction.singleIn the detail view of a single transaction{ placement: "transaction.single", transactionId: string }
transaction.bulkOn the transaction list after multi-selecting rows{ placement: "transaction.bulk", transactionIds: string[] }
reportAbove the Profit and loss report{ placement: "report", reportType: "profit-loss", entityId: string, startDate: string, endDate: string }

In the app, the transaction actions are listed under Extensions in the Transactions page's actions menu (⌘K or Ctrl+K): transaction.single with one transaction selected, transaction.bulk with two or more. The report button appears above the Profit and loss report, and its input also carries reportType: "profit-loss", entityId, and the report's startDate and endDate as YYYY-MM-DD. Using extensions shows what the person clicking sees.

The person who clicked is the triggering user, so action links can send email with onBehalf: true.

Handler recipe — suggest accounts for selected transactions

This uses the manifest from the Manifest reference: read:transactions, read:entities, use:tools and use:ai, with a single and a bulk button.

typescript
async function main(): Promise<void> {
  const { input, entityId } = prosaic.context;
  const ids: string[] =
    input?.transactionIds ??
    (input?.transactionId ? [input.transactionId] : []);

  if (ids.length === 0) {
    prosaic.log.warn('No transactions selected');
    return;
  }

  // The chart of accounts is only reachable through the tool registry.
  const accounts = await prosaic.tools.invoke('accounts.list', {});
  const chart = accounts.map((a) => `${a.code}: ${a.name}`).join('\n');

  for (const id of ids.slice(0, 20)) {
    const txn = await prosaic.transactions.get(id);

    const { content } = await prosaic.ai.complete({
      messages: [
        {
          role: 'system',
          content: `Pick the best account for a bank transaction from this chart of accounts. Reply with the account code only.\n\n${chart}`,
        },
        { role: 'user', content: `${txn.description} (${txn.amount})` },
      ],
    });

    const code = content?.trim() ?? '';
    prosaic.log.info('Suggested account', {
      transactionId: id,
      description: txn.description,
      code,
    });
    await prosaic.storage.set(`${entityId}:suggestion:${id}`, code);
  }
}

await main();

The suggestions land in the execution logs and in storage. Extensions can't reconcile a transaction or post a journal, so a person applies the suggestion in Prosaic.

Gotchas

  • The extension must be installed on the entity, and switched on. Otherwise the action doesn't show.
  • Bulk selections can be long. Hundreds of IDs is possible. Cap how many you process (the recipe takes 20) so you stay inside the time limit, and page the rest over later runs if you need to.
  • Labels matter. They're what users click. "Run my-extension" ages badly — make the label a verb that describes the action.
  • Buttons get clicked twice. Make the handler safe to repeat.

Picking the right trigger

Rough rule of thumb:

  • Reactive to a domain event? Event.
  • Periodic, no user in the loop? Cron.
  • User in the loop, triggered on demand? Action link.
  • Waiting for someone to answer an email? Send a conversational email and handle email.reply.
  • Two of the above? Declare both. They coexist happily.