@cogover/sdk 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -12
- package/dist/email.d.ts +77 -0
- package/dist/email.js +190 -0
- package/dist/index.d.ts +2 -0
- package/dist/internal/job-runtime.js +4 -0
- package/dist/internal/messaging.js +75 -0
- package/dist/internal/trigger-runtime.js +5 -0
- package/dist/jobs.d.ts +4 -0
- package/dist/notifications.d.ts +56 -0
- package/dist/notifications.js +92 -0
- package/dist/router.js +2 -0
- package/dist/script.d.ts +4 -0
- package/dist/script.js +4 -0
- package/dist/trigger.d.ts +6 -0
- package/docs/en/api-reference.md +341 -16
- package/docs/en/usage-guide.md +203 -7
- package/package.json +1 -1
package/docs/en/usage-guide.md
CHANGED
|
@@ -480,7 +480,8 @@ router.post("/recalculate", async ({ jobs, response }) => {
|
|
|
480
480
|
|
|
481
481
|
- A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
|
|
482
482
|
to `enqueue` (or `null`), and the same `data`, `schema`, `log`, `state`, `locks`,
|
|
483
|
-
`jobs`, `secrets`, `crypto`, and `org` APIs as a script.
|
|
483
|
+
`notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` APIs as a script.
|
|
484
|
+
Its return value is ignored.
|
|
484
485
|
- A run enqueued from a route or trigger acts as the user of that call. A scheduled
|
|
485
486
|
run has no user: `data.object()` works only when the identity policy allows the
|
|
486
487
|
system identity, so approve `allowInternalSystem` for projects with schedules.
|
|
@@ -501,6 +502,200 @@ router.post("/recalculate", async ({ jobs, response }) => {
|
|
|
501
502
|
See the [background job reference](api-reference.md#background-jobs) for every
|
|
502
503
|
option and rule.
|
|
503
504
|
|
|
505
|
+
## Send notifications and email
|
|
506
|
+
|
|
507
|
+
`notifications.send` puts a notification in people's notification list (the bell)
|
|
508
|
+
and, as the workspace's notification channel decides, also delivers it by web and
|
|
509
|
+
mobile push and as an email copy. `email.send` sends a real email from a shared
|
|
510
|
+
workspace mailbox or from the personal mailbox of the user who started the
|
|
511
|
+
execution, and can log it on a record's timeline. Both work in scripts, routes,
|
|
512
|
+
after-change triggers, and jobs; before-change triggers cannot use them.
|
|
513
|
+
|
|
514
|
+
### Ask for an approval
|
|
515
|
+
|
|
516
|
+
```typescript
|
|
517
|
+
import { defineTrigger } from "@cogover/sdk";
|
|
518
|
+
|
|
519
|
+
// Record ID of the workspace's "Approvals" notification channel.
|
|
520
|
+
const APPROVAL_CHANNEL = "NCHXXXXXXXXXXXX";
|
|
521
|
+
|
|
522
|
+
export const triggers = [
|
|
523
|
+
defineTrigger({
|
|
524
|
+
key: "leave_request_submitted",
|
|
525
|
+
object: "leave_request",
|
|
526
|
+
timing: "afterChange",
|
|
527
|
+
operations: ["create", "update"],
|
|
528
|
+
fields: ["status", "days"],
|
|
529
|
+
changedFields: ["status"],
|
|
530
|
+
when: { op: "=", field: "status", params: "submitted" },
|
|
531
|
+
runWhen: "onEnter",
|
|
532
|
+
}, async ({ records, trigger, invocation, org, notifications }) => {
|
|
533
|
+
const requesterId = invocation.user?.membership.personnelId;
|
|
534
|
+
if (requesterId === undefined) return;
|
|
535
|
+
// The nearest managers of the requester approve.
|
|
536
|
+
const [chain] = await org.personnel.managerChain(requesterId, { accountOnly: true });
|
|
537
|
+
const approverIds = chain?.tiers[0]?.personnelIds ?? [];
|
|
538
|
+
if (approverIds.length === 0) return;
|
|
539
|
+
|
|
540
|
+
for (const record of records) {
|
|
541
|
+
await notifications.send({
|
|
542
|
+
to: approverIds,
|
|
543
|
+
exclude: ["actor"],
|
|
544
|
+
sender: "actor",
|
|
545
|
+
title: "Leave request waiting for your approval",
|
|
546
|
+
subtitle: `${record.new.days} day(s)`,
|
|
547
|
+
content: "A leave request was submitted and needs your decision.",
|
|
548
|
+
link: { url: `/app/leave_request/${record.id}` },
|
|
549
|
+
channel: APPROVAL_CHANNEL,
|
|
550
|
+
// The same change of the same record always produces the same key.
|
|
551
|
+
idempotencyKey: `leave-approval:${trigger.changeId}:${record.id}`,
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
}),
|
|
555
|
+
];
|
|
556
|
+
```
|
|
557
|
+
|
|
558
|
+
- `to` takes 1 to 200 personnel IDs. Personnel without a user account are skipped
|
|
559
|
+
and returned in `skippedPersonnelIds`; `exclude: ["actor"]` skips the user who
|
|
560
|
+
caused the execution, and `sender: "actor"` shows that user as the sender.
|
|
561
|
+
- `channel` is the record ID of a notification channel of the workspace. It decides
|
|
562
|
+
which deliveries (in the web app, web push, mobile push, email) are enabled, and
|
|
563
|
+
each user may override it; without a channel, every delivery is enabled. Pass
|
|
564
|
+
`email: false` to never send the email copy. The copy comes from a Cogover
|
|
565
|
+
notification address and counts against the workspace plan's daily
|
|
566
|
+
notification-email limit.
|
|
567
|
+
- `link.url` is a path of the web app starting with `/` or an absolute `http(s)`
|
|
568
|
+
URL. `contentType: "html"` keeps only basic formatting such as paragraphs, lists,
|
|
569
|
+
tables, and links.
|
|
570
|
+
- Notifications need no approval in the identity policy.
|
|
571
|
+
|
|
572
|
+
### Send a quote from a shared mailbox
|
|
573
|
+
|
|
574
|
+
```typescript
|
|
575
|
+
import { createRouter, NotFoundError } from "@cogover/sdk";
|
|
576
|
+
|
|
577
|
+
const router = createRouter();
|
|
578
|
+
|
|
579
|
+
router.post("/quotes/:id/send", async ({ request, data, email, response }) => {
|
|
580
|
+
const quotes = data.object("quote");
|
|
581
|
+
const quote = await quotes.records.get(request.params.id, { fields: ["code"] });
|
|
582
|
+
if (!quote) throw new NotFoundError("quote", request.params.id);
|
|
583
|
+
|
|
584
|
+
// Pick the mailbox by address instead of hard-coding its ID.
|
|
585
|
+
const sales = (await email.senders()).find(sender => sender.email === "sales@example.com");
|
|
586
|
+
if (!sales) {
|
|
587
|
+
return response.json({ msg: "The sales mailbox is not available to this module." }, { status: 409 });
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const result = await email.send({
|
|
591
|
+
from: { mailbox: sales.id },
|
|
592
|
+
subject: `Quote ${quote.fields.code}`,
|
|
593
|
+
html: "<p>Dear customer,</p><p>Please find our quote attached.</p>",
|
|
594
|
+
// Logs the email on the quote's timeline, with open and click tracking.
|
|
595
|
+
record: { object: "quote", recordId: quote.id },
|
|
596
|
+
// The customer's address comes from the quote's email field.
|
|
597
|
+
recordEmailFields: ["contact_email"],
|
|
598
|
+
attachments: [{ object: "quote", recordId: quote.id, field: "quote_pdf" }],
|
|
599
|
+
// A double click or a retried request does not send the quote twice.
|
|
600
|
+
idempotencyKey: `quote-email:${quote.id}`,
|
|
601
|
+
});
|
|
602
|
+
return response.json({ requestId: result.requestId, duplicate: result.duplicate }, { status: 202 });
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
export default router.toHandler();
|
|
606
|
+
```
|
|
607
|
+
|
|
608
|
+
- `from` is `{ mailbox: id }` for a shared workspace mailbox or `"actor"` for the
|
|
609
|
+
default personal mailbox of the user who started the execution. Recipients are
|
|
610
|
+
addresses, `{ email, name }`, or `{ personnelId }`, at most 50 in `to`, `cc`, and
|
|
611
|
+
`bcc` together. Give exactly one of `html` and `text`.
|
|
612
|
+
- `recordEmailFields`, `attachments` (at most 10 files and 20 MB in total), and
|
|
613
|
+
`appendSignature` require `record`; `appendSignature` also requires
|
|
614
|
+
`from: "actor"`. The records must be readable by the execution's default identity.
|
|
615
|
+
- Without `record`, the email is only sent from the mailbox (`delivery: "direct"`).
|
|
616
|
+
|
|
617
|
+
### Allow the module to send email
|
|
618
|
+
|
|
619
|
+
A module can send email only from the mailboxes an administrator allowed. The
|
|
620
|
+
administrator adds an `email` section to the Project's identity policy and approves
|
|
621
|
+
the policy for the version you publish:
|
|
622
|
+
|
|
623
|
+
```json
|
|
624
|
+
{
|
|
625
|
+
"email": {
|
|
626
|
+
"workspaceMailboxIds": ["EMWXXXXXXXXXXXX"],
|
|
627
|
+
"allowActorMailbox": false
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
`workspaceMailboxIds` lists the shared mailboxes the module may send from, and
|
|
633
|
+
`allowActorMailbox: true` allows `from: "actor"`. The section follows the rest of
|
|
634
|
+
the policy: it applies to the callers selected by `callerPersonnelIds`, and to
|
|
635
|
+
executions without a user (scheduled jobs, inbound webhooks) only when the policy
|
|
636
|
+
sets `allowInternalSystem: true`. A policy may contain only an `email` section. Any
|
|
637
|
+
other sender is refused with `PermissionDeniedError` and
|
|
638
|
+
`details.reason === "EMAIL_SENDER_NOT_GRANTED"`; `email.senders()` shows the
|
|
639
|
+
mailboxes the current execution may use.
|
|
640
|
+
|
|
641
|
+
### Best-effort delivery
|
|
642
|
+
|
|
643
|
+
- A successful call means Cogover accepted the notification or email. Delivery
|
|
644
|
+
happens afterwards, and a later failure, such as a rejected address, is not
|
|
645
|
+
reported to the script. Record "sent" in your data as "accepted for sending", not
|
|
646
|
+
as proof of delivery.
|
|
647
|
+
- A sent notification or email cannot be recalled.
|
|
648
|
+
- By default a project may address 5,000 notification recipients and send 500
|
|
649
|
+
emails per hour; beyond that the call throws `RateLimitError` and sends nothing.
|
|
650
|
+
Spread large mailings over several job runs.
|
|
651
|
+
|
|
652
|
+
### Use `idempotencyKey` in jobs and triggers
|
|
653
|
+
|
|
654
|
+
Jobs are delivered at least once and after-change triggers may run more than once,
|
|
655
|
+
so a retried run would notify or email again. Give each message an
|
|
656
|
+
`idempotencyKey` that stays the same across retries: a second call with the same
|
|
657
|
+
key within 7 days returns the first result with `duplicate: true` and sends
|
|
658
|
+
nothing.
|
|
659
|
+
|
|
660
|
+
```typescript
|
|
661
|
+
import { defineJob } from "@cogover/sdk";
|
|
662
|
+
|
|
663
|
+
const BILLING_MAILBOX = "EMWXXXXXXXXXXXX";
|
|
664
|
+
|
|
665
|
+
export const overdueReminders = defineJob({
|
|
666
|
+
key: "overdue_invoice_reminders",
|
|
667
|
+
schedule: { cron: "0 8 * * *", timezone: "Asia/Ho_Chi_Minh" },
|
|
668
|
+
}, async ({ job, data, email }) => {
|
|
669
|
+
const invoices = data.object("invoice");
|
|
670
|
+
const overdue = await invoices.records.list({
|
|
671
|
+
where: invoices.fields.status.eq("overdue"),
|
|
672
|
+
fields: ["code"],
|
|
673
|
+
limit: 200,
|
|
674
|
+
});
|
|
675
|
+
for (const invoice of overdue.items) {
|
|
676
|
+
await email.send({
|
|
677
|
+
from: { mailbox: BILLING_MAILBOX },
|
|
678
|
+
subject: `Invoice ${invoice.fields.code} is overdue`,
|
|
679
|
+
text: "Our records show that this invoice is overdue. Please arrange payment.",
|
|
680
|
+
record: { object: "invoice", recordId: invoice.id },
|
|
681
|
+
recordEmailFields: ["billing_email"],
|
|
682
|
+
// job.id stays the same across attempts, so a retried run skips the emails it already sent.
|
|
683
|
+
idempotencyKey: `${job.id}:${invoice.id}`,
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
export const jobs = [overdueReminders];
|
|
689
|
+
```
|
|
690
|
+
|
|
691
|
+
A scheduled run has no user, so this job needs `allowInternalSystem: true` in the
|
|
692
|
+
identity policy for both `data.object()` and the mailbox grant, and it cannot use
|
|
693
|
+
`from: "actor"`. A call made while an earlier call with the same key is still
|
|
694
|
+
sending throws `CogoverApiError` with `code: "DUPLICATE_IN_PROGRESS"`; let the run
|
|
695
|
+
fail with `RetryableError` or try again later. See
|
|
696
|
+
[Notifications](api-reference.md#notifications) and
|
|
697
|
+
[Email](api-reference.md#email) in the API reference for every option and error.
|
|
698
|
+
|
|
504
699
|
## Choose the identity for record operations
|
|
505
700
|
|
|
506
701
|
Keep using `data.object("order")` to inherit the caller's identity. When an
|
|
@@ -651,10 +846,11 @@ inside the loop. Collect the IDs, call `records.getMany` once, and look the resu
|
|
|
651
846
|
up from a `Map`, as in the example above.
|
|
652
847
|
|
|
653
848
|
**Read-only.** A before-change trigger may read records and schema. Record writes,
|
|
654
|
-
`fetch`, locks, state writes,
|
|
655
|
-
(`details.reason === "TRIGGER_READ_ONLY"`), for every identity.
|
|
656
|
-
has `records`, `trigger`, `invocation`, `data`, `schema`, `log`,
|
|
657
|
-
no `request`, `response`, `state`, or
|
|
849
|
+
`fetch`, locks, state writes, push messages, notifications, and email are refused with
|
|
850
|
+
`PermissionDeniedError` (`details.reason === "TRIGGER_READ_ONLY"`), for every identity.
|
|
851
|
+
The trigger context has `records`, `trigger`, `invocation`, `data`, `schema`, `log`,
|
|
852
|
+
`push`, `notifications`, and `email`; it has no `request`, `response`, `state`, or
|
|
853
|
+
`locks`.
|
|
658
854
|
|
|
659
855
|
**Identity.** `data.object()` acts as the user who made the change, with that user's
|
|
660
856
|
permissions, so a read can legitimately return nothing for a record the user cannot
|
|
@@ -672,8 +868,8 @@ rejected and nothing is saved. Keep handlers short and deterministic. See the
|
|
|
672
868
|
Set `timing: "afterChange"` to run code after a change has been saved. The handler
|
|
673
869
|
runs asynchronously, shortly after the write: the writer does not wait for it, and
|
|
674
870
|
the handler can neither reject nor modify the saved change. Unlike a before-change
|
|
675
|
-
trigger it may write records, call `fetch`, read secrets,
|
|
676
|
-
jobs, like a script.
|
|
871
|
+
trigger it may write records, call `fetch`, read secrets, send notifications and
|
|
872
|
+
email, and enqueue background jobs, like a script.
|
|
677
873
|
|
|
678
874
|
```typescript
|
|
679
875
|
import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
|