@cogover/sdk 0.10.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.
@@ -88,8 +88,9 @@ export default defineScript(({ invocation }) => {
88
88
  });
89
89
  ```
90
90
 
91
- Use the Record API only when you need richer, current Personnel business fields
92
- such as department, position, manager, or custom fields. The snapshot intentionally
91
+ Use [`org`](#read-departments-positions-and-managers) for departments, positions,
92
+ and managers, and the Record API only when you need other current Personnel fields
93
+ such as custom fields. The snapshot intentionally
93
94
  contains only documented fields and omits credentials and raw authentication data.
94
95
 
95
96
  ### Allow an action by workspace role
@@ -124,6 +125,53 @@ export default defineScript(({ invocation }) => {
124
125
  development session starts. Restart `cogover-dev` to pick up role changes.
125
126
  - `system` and `inbound` invocations have `user: null`, so there is no membership.
126
127
 
128
+ ## Read departments, positions, and managers
129
+
130
+ `org` answers structure questions without reading records: who belongs to a
131
+ department, which positions apply, and who manages whom. Add `withDisplay: true`
132
+ when you also need names, for example to show them on a screen.
133
+
134
+ ```typescript
135
+ export default defineScript(async ({ org, invocation, input }) => {
136
+ const { ownerId, departmentId } = input as { ownerId: string; departmentId: string };
137
+ const callerId = invocation.user?.membership.personnelId;
138
+ if (callerId === undefined) {
139
+ return { approved: false, reason: "Only a user can approve this order" };
140
+ }
141
+ // Only a manager of the order owner, in the order's department, may approve.
142
+ if (!await org.isManagerOf(callerId, ownerId, { departmentId })) {
143
+ return { approved: false, reason: "Only a manager of the owner can approve this order" };
144
+ }
145
+ return { approved: true };
146
+ });
147
+ ```
148
+
149
+ List the approvers of a personnel, nearest first, with their names:
150
+
151
+ ```typescript
152
+ const [chain] = await org.personnel.managerChain(ownerId, {
153
+ departmentId,
154
+ accountOnly: true, // approvers need an account
155
+ withDisplay: true,
156
+ });
157
+ const approvers = chain?.tiers.flatMap(tier =>
158
+ tier.personnel.map(person => ({ id: person.id, name: person.display?.name }))) ?? [];
159
+ ```
160
+
161
+ - `level` marks managers: `0` is staff, `1` the highest manager level of a
162
+ department, `2` the next one. A chain climbs from the personnel's department to
163
+ the root, and every manager of a parent department ranks above those of its
164
+ sub-departments. `vacantDepartmentIds` shows departments without a manager.
165
+ - Structure answers are served from memory and reflect changes within a few
166
+ seconds. `withDisplay` costs at most one extra read per kind of data; names follow
167
+ the caller's language unless you pass `language`.
168
+ - Read many personnel with `org.personnel.getMany` or a page of
169
+ `org.departments.members` rather than calling `get` in a loop.
170
+ - `org` works in scripts, triggers (including before-change) and jobs. An execution
171
+ without a user needs `allowInternalSystem: true` in the project's identity policy.
172
+ - For other personnel fields, such as custom fields, use
173
+ `data.object("personnel")`, which applies record permissions.
174
+
127
175
  ## Filter and sort records
128
176
 
129
177
  ```typescript
@@ -432,7 +480,8 @@ router.post("/recalculate", async ({ jobs, response }) => {
432
480
 
433
481
  - A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
434
482
  to `enqueue` (or `null`), and the same `data`, `schema`, `log`, `state`, `locks`,
435
- `jobs`, `secrets`, and `crypto` APIs as a script. Its return value is ignored.
483
+ `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` APIs as a script.
484
+ Its return value is ignored.
436
485
  - A run enqueued from a route or trigger acts as the user of that call. A scheduled
437
486
  run has no user: `data.object()` works only when the identity policy allows the
438
487
  system identity, so approve `allowInternalSystem` for projects with schedules.
@@ -453,6 +502,200 @@ router.post("/recalculate", async ({ jobs, response }) => {
453
502
  See the [background job reference](api-reference.md#background-jobs) for every
454
503
  option and rule.
455
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
+
456
699
  ## Choose the identity for record operations
457
700
 
458
701
  Keep using `data.object("order")` to inherit the caller's identity. When an
@@ -603,10 +846,11 @@ inside the loop. Collect the IDs, call `records.getMany` once, and look the resu
603
846
  up from a `Map`, as in the example above.
604
847
 
605
848
  **Read-only.** A before-change trigger may read records and schema. Record writes,
606
- `fetch`, locks, state writes, and push messages are refused with `PermissionDeniedError`
607
- (`details.reason === "TRIGGER_READ_ONLY"`), for every identity. The trigger context
608
- has `records`, `trigger`, `invocation`, `data`, `schema`, `log`, and `push`; it has
609
- no `request`, `response`, `state`, or `locks`.
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`.
610
854
 
611
855
  **Identity.** `data.object()` acts as the user who made the change, with that user's
612
856
  permissions, so a read can legitimately return nothing for a record the user cannot
@@ -624,8 +868,8 @@ rejected and nothing is saved. Keep handlers short and deterministic. See the
624
868
  Set `timing: "afterChange"` to run code after a change has been saved. The handler
625
869
  runs asynchronously, shortly after the write: the writer does not wait for it, and
626
870
  the handler can neither reject nor modify the saved change. Unlike a before-change
627
- trigger it may write records, call `fetch`, read secrets, and enqueue background
628
- 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.
629
873
 
630
874
  ```typescript
631
875
  import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,