@cogover/sdk 0.9.0 → 0.11.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 +40 -1
- package/dist/index.d.ts +2 -1
- package/dist/internal/invocation.js +24 -0
- package/dist/internal/job-runtime.js +2 -0
- package/dist/internal/trigger-runtime.js +2 -0
- package/dist/invocation.d.ts +9 -0
- package/dist/jobs.d.ts +2 -0
- package/dist/org.d.ts +227 -0
- package/dist/org.js +227 -0
- package/dist/router.js +1 -0
- package/dist/script.d.ts +2 -0
- package/dist/script.js +2 -0
- package/dist/trigger.d.ts +2 -0
- package/docs/en/api-reference.md +349 -6
- package/docs/en/usage-guide.md +83 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -76,6 +76,18 @@ invocations and to `null` for system invocations. Only the documented profile,
|
|
|
76
76
|
membership, locale, and workspace fields are included. Raw authentication data
|
|
77
77
|
and Cogover credentials are never exposed.
|
|
78
78
|
|
|
79
|
+
`invocation.user.membership.isSuperAdmin` tells whether the user holds the
|
|
80
|
+
workspace's Super Admin role, and `invocation.user.membership.roles` lists the
|
|
81
|
+
user's roles in the current workspace as `{ id, name }` entries. Compare roles by
|
|
82
|
+
`id`; role permissions are not exposed, and Cogover still enforces record and
|
|
83
|
+
field access for the user, so use these fields for business rules only:
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
const user = invocation.user;
|
|
87
|
+
const canApprove = user !== null && (user.membership.isSuperAdmin
|
|
88
|
+
|| user.membership.roles.some((role) => role.id === APPROVER_ROLE_ID));
|
|
89
|
+
```
|
|
90
|
+
|
|
79
91
|
## Full HTTP routes and responses
|
|
80
92
|
|
|
81
93
|
```typescript
|
|
@@ -232,7 +244,7 @@ export const jobs = [
|
|
|
232
244
|
|
|
233
245
|
A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
|
|
234
246
|
to `enqueue` or `null`, and the same `data`, `schema`, `log`, `state`, `locks`,
|
|
235
|
-
`jobs`, `secrets`, and `
|
|
247
|
+
`jobs`, `secrets`, `crypto`, and `org` APIs as a script. Runs are delivered at least once
|
|
236
248
|
and retried with growing delays when the handler throws `RetryableError` or times
|
|
237
249
|
out, up to `maxAttempts` (default 5) attempts; other errors fail the run. A run
|
|
238
250
|
enqueued from a route acts as that route's user, while a scheduled run uses the
|
|
@@ -497,6 +509,33 @@ Delivery is best-effort, each call counts as one capability call, and before-cha
|
|
|
497
509
|
triggers cannot push. Invalid input throws `ValidationError`; an unknown object or
|
|
498
510
|
personnel throws `NotFoundError`.
|
|
499
511
|
|
|
512
|
+
## Organization structure
|
|
513
|
+
|
|
514
|
+
`org` reads the departments, positions, and personnel of the workspace, and the
|
|
515
|
+
manager chain of a personnel, without reading records. Structure answers are
|
|
516
|
+
served from memory; `withDisplay: true` adds names in the caller's language.
|
|
517
|
+
|
|
518
|
+
```typescript
|
|
519
|
+
import { defineScript } from "@cogover/sdk";
|
|
520
|
+
|
|
521
|
+
export default defineScript(async ({ org, invocation, input }) => {
|
|
522
|
+
const { ownerId } = input as { ownerId: string };
|
|
523
|
+
const callerId = invocation.user?.membership.personnelId;
|
|
524
|
+
const allowed = callerId !== undefined && await org.isManagerOf(callerId, ownerId);
|
|
525
|
+
|
|
526
|
+
const [chain] = await org.personnel.managerChain(ownerId, { accountOnly: true, withDisplay: true });
|
|
527
|
+
return {
|
|
528
|
+
allowed,
|
|
529
|
+
approvers: chain?.tiers.flatMap(tier => tier.personnel.map(person => person.display?.name ?? person.id)) ?? [],
|
|
530
|
+
};
|
|
531
|
+
});
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
Available calls: `org.me`, `org.personnel.get/getMany/managerChain`,
|
|
535
|
+
`org.departments.get/tree/ancestors/members/managers/managerChain`,
|
|
536
|
+
`org.positions.list/get/members`, `org.isInDepartment`, and `org.isManagerOf`.
|
|
537
|
+
Membership `level` is `0` for staff and `1`, `2`, ... for managers, highest first.
|
|
538
|
+
|
|
500
539
|
## Workspace types
|
|
501
540
|
|
|
502
541
|
`WorkspaceObjects` is an open interface augmented by a generated declaration for
|
package/dist/index.d.ts
CHANGED
|
@@ -13,9 +13,10 @@ export type { TriggerTiming, TriggerOperation, TriggerRunWhen, TriggerFilterCond
|
|
|
13
13
|
export { defineJob } from "./jobs.js";
|
|
14
14
|
export type { JobSchedule, JobConfig, JobManifest, JobDefinition, JobInfo, EnqueueOptions, EnqueueResult, JobsApi, JobContext, JobHandler, } from "./jobs.js";
|
|
15
15
|
export type { SecretsApi } from "./secrets.js";
|
|
16
|
+
export type { OrgApi, OrgPersonnelApi, OrgDepartmentsApi, OrgPositionsApi, OrgReadOptions, OrgPageOptions, OrgDepartmentMembersOptions, OrgPositionMembersOptions, OrgManagerOptions, OrgPersonnelChainOptions, OrgTreeOptions, OrgIsInDepartmentOptions, OrgIsManagerOfOptions, OrgPersonnelDisplay, OrgNameDisplay, OrgMembership, OrgMember, OrgPersonnel, OrgDepartment, OrgDepartmentNode, OrgPosition, OrgManagerTier, OrgManagerChain, OrgPage, OrgGetManyResult, } from "./org.js";
|
|
16
17
|
export { crypto } from "./crypto.js";
|
|
17
18
|
export type { CryptoApi, BinaryEncoding, DecryptOutput, SecretKeyReference, AesKey, AsymmetricKey, AesMode, AesEncryptOptions, AesEncryptResult, AesDecryptOptions, RsaPadding, RsaEncryptOptions, RsaDecryptOptions, SignatureAlgorithm, SignatureOptions, } from "./crypto.js";
|
|
18
|
-
export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
|
|
19
|
+
export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentWorkspaceRole, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
|
|
19
20
|
export { createRouter } from "./router.js";
|
|
20
21
|
export type { ScriptRouter } from "./router.js";
|
|
21
22
|
export type { RequestMethod, ScriptRequest, ScriptQuery, ScriptHeaders, ScriptPathParams, } from "./request.js";
|
|
@@ -32,6 +32,8 @@ function userSnapshot(raw) {
|
|
|
32
32
|
...optionalStringFields(membershipRaw, ["personnelId", "language", "timezone"]),
|
|
33
33
|
...(membershipRaw.personnelId === undefined && typeof raw.personnelId === "string" && raw.personnelId !== ""
|
|
34
34
|
? { personnelId: raw.personnelId } : {}),
|
|
35
|
+
isSuperAdmin: superAdminFlag(membershipRaw.isSuperAdmin),
|
|
36
|
+
roles: roleSnapshots(membershipRaw.roles),
|
|
35
37
|
});
|
|
36
38
|
return Object.freeze({
|
|
37
39
|
accountId: requiredString(raw.accountId, "account id"),
|
|
@@ -39,6 +41,28 @@ function userSnapshot(raw) {
|
|
|
39
41
|
membership,
|
|
40
42
|
});
|
|
41
43
|
}
|
|
44
|
+
// A Runtime or development host that predates these fields omits them; the tolerant
|
|
45
|
+
// defaults keep project code working against it.
|
|
46
|
+
function superAdminFlag(value) {
|
|
47
|
+
if (value === undefined)
|
|
48
|
+
return false;
|
|
49
|
+
if (typeof value !== "boolean")
|
|
50
|
+
throw new ValidationError("Invalid invocation isSuperAdmin");
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
function roleSnapshots(value) {
|
|
54
|
+
if (value === undefined)
|
|
55
|
+
return Object.freeze([]);
|
|
56
|
+
if (!Array.isArray(value))
|
|
57
|
+
throw new ValidationError("Invalid invocation roles");
|
|
58
|
+
return Object.freeze(value.map((role) => {
|
|
59
|
+
if (!isRecord(role) || typeof role.id !== "string" || role.id === "" || typeof role.name !== "string") {
|
|
60
|
+
throw new ValidationError("Invalid invocation role");
|
|
61
|
+
}
|
|
62
|
+
// Only the documented keys are copied so that no other role metadata reaches project code.
|
|
63
|
+
return Object.freeze({ id: role.id, name: role.name });
|
|
64
|
+
}));
|
|
65
|
+
}
|
|
42
66
|
function inboundSnapshot(raw) {
|
|
43
67
|
if (!isRecord(raw))
|
|
44
68
|
throw new ValidationError("Invalid invocation identity metadata");
|
|
@@ -4,6 +4,7 @@ import { ValidationError } from "../errors.js";
|
|
|
4
4
|
import { installCogoverFetch } from "../fetch.js";
|
|
5
5
|
import { createLocksApi } from "../locks.js";
|
|
6
6
|
import { SCRIPT_LOGGER } from "../logger.js";
|
|
7
|
+
import { createOrgApi } from "../org.js";
|
|
7
8
|
import { createSchemaApi } from "../schema.js";
|
|
8
9
|
import { createSecretsApi } from "../secrets.js";
|
|
9
10
|
import { createStateApi } from "../state.js";
|
|
@@ -45,6 +46,7 @@ export function createJobSandboxHandler(manifest, handler) {
|
|
|
45
46
|
jobs: createJobsApi(),
|
|
46
47
|
secrets: createSecretsApi(),
|
|
47
48
|
crypto,
|
|
49
|
+
org: createOrgApi(() => invocation ??= invocationContext(input)),
|
|
48
50
|
}));
|
|
49
51
|
// The result of a job is not delivered anywhere, so nothing is serialized.
|
|
50
52
|
return null;
|
|
@@ -2,6 +2,7 @@ import { crypto } from "../crypto.js";
|
|
|
2
2
|
import { createDataApi } from "../data.js";
|
|
3
3
|
import { ValidationError } from "../errors.js";
|
|
4
4
|
import { installCogoverFetch } from "../fetch.js";
|
|
5
|
+
import { createOrgApi } from "../org.js";
|
|
5
6
|
import { SCRIPT_LOGGER } from "../logger.js";
|
|
6
7
|
import { createPushApi } from "../push.js";
|
|
7
8
|
import { createSchemaApi } from "../schema.js";
|
|
@@ -58,6 +59,7 @@ export function createTriggerSandboxHandler(manifest, handler) {
|
|
|
58
59
|
jobs: createJobsApi(),
|
|
59
60
|
secrets: createSecretsApi(),
|
|
60
61
|
crypto,
|
|
62
|
+
org: createOrgApi(() => invocation ??= invocationContext(input)),
|
|
61
63
|
}));
|
|
62
64
|
const results = [];
|
|
63
65
|
for (const entry of entries) {
|
package/dist/invocation.d.ts
CHANGED
|
@@ -9,11 +9,20 @@ export interface CurrentWorkspace {
|
|
|
9
9
|
readonly timeFormat?: string;
|
|
10
10
|
readonly numberFormat?: string;
|
|
11
11
|
}
|
|
12
|
+
/** A role assigned to the current user in the current workspace. */
|
|
13
|
+
export interface CurrentWorkspaceRole {
|
|
14
|
+
readonly id: string;
|
|
15
|
+
readonly name: string;
|
|
16
|
+
}
|
|
12
17
|
/** Public membership metadata for the current user in the current workspace. */
|
|
13
18
|
export interface CurrentWorkspaceMembership {
|
|
14
19
|
readonly personnelId?: string;
|
|
15
20
|
readonly language?: string;
|
|
16
21
|
readonly timezone?: string;
|
|
22
|
+
/** True when one of the user's roles is the workspace's highest administrator (Super Admin) role. */
|
|
23
|
+
readonly isSuperAdmin: boolean;
|
|
24
|
+
/** Roles assigned to the user in this workspace, sorted by name. Compare roles by `id`. */
|
|
25
|
+
readonly roles: readonly CurrentWorkspaceRole[];
|
|
17
26
|
}
|
|
18
27
|
/** Public account metadata for the authenticated user who initiated the invocation. */
|
|
19
28
|
export interface CurrentUser {
|
package/dist/jobs.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { DataApi } from "./data.js";
|
|
|
3
3
|
import type { InvocationContext } from "./invocation.js";
|
|
4
4
|
import type { DistributedLocks } from "./locks.js";
|
|
5
5
|
import type { ScriptLogger } from "./logger.js";
|
|
6
|
+
import type { OrgApi } from "./org.js";
|
|
6
7
|
import type { SchemaApi } from "./schema.js";
|
|
7
8
|
import type { SandboxHandler } from "./script.js";
|
|
8
9
|
import type { SecretsApi } from "./secrets.js";
|
|
@@ -89,6 +90,7 @@ export interface JobContext<TPayload = unknown, TSchema extends object = Effecti
|
|
|
89
90
|
readonly jobs: JobsApi;
|
|
90
91
|
readonly secrets: SecretsApi;
|
|
91
92
|
readonly crypto: CryptoApi;
|
|
93
|
+
readonly org: OrgApi;
|
|
92
94
|
}
|
|
93
95
|
export type JobHandler<TPayload = unknown, TSchema extends object = EffectiveWorkspaceObjects> = (context: JobContext<TPayload, TSchema>) => void | Promise<void>;
|
|
94
96
|
/** Declares a background job. Add the result to the project's `jobs` export. */
|
package/dist/org.d.ts
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/** Options of a read that can also return display data. */
|
|
2
|
+
export interface OrgReadOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Adds names in `language`, and for personnel their email, avatar and code. Costs at most one extra read
|
|
5
|
+
* per kind of data; without it the answer comes from memory.
|
|
6
|
+
*/
|
|
7
|
+
readonly withDisplay?: boolean;
|
|
8
|
+
/** Language of department and position names, such as `"vi-VN"`; defaults to the invocation language. */
|
|
9
|
+
readonly language?: string;
|
|
10
|
+
}
|
|
11
|
+
type WithDisplay = {
|
|
12
|
+
readonly withDisplay: true;
|
|
13
|
+
};
|
|
14
|
+
type Displayed<D extends boolean, T> = D extends true ? T : {};
|
|
15
|
+
/** Display data of a personnel. */
|
|
16
|
+
export interface OrgPersonnelDisplay {
|
|
17
|
+
/** Full name as the workspace shows it. */
|
|
18
|
+
readonly name: string;
|
|
19
|
+
readonly email: string | null;
|
|
20
|
+
/** Public URL of the avatar, or `null`. */
|
|
21
|
+
readonly avatar: string | null;
|
|
22
|
+
/** Personnel code, or `null`. */
|
|
23
|
+
readonly code: string | null;
|
|
24
|
+
}
|
|
25
|
+
/** Display data of a department or position. */
|
|
26
|
+
export interface OrgNameDisplay {
|
|
27
|
+
/** Name in the requested language, or the stored default name. */
|
|
28
|
+
readonly name: string;
|
|
29
|
+
}
|
|
30
|
+
/** The place of a personnel in one department. A personnel has at most one membership per department. */
|
|
31
|
+
export type OrgMembership<D extends boolean = false> = {
|
|
32
|
+
readonly personnelId: string;
|
|
33
|
+
readonly departmentId: string;
|
|
34
|
+
readonly positionId: string | null;
|
|
35
|
+
/** `0` for staff; `1` for the highest manager level of the department, `2` for the next one, and so on. */
|
|
36
|
+
readonly level: number;
|
|
37
|
+
/** Whether this is the personnel's primary department. */
|
|
38
|
+
readonly primary: boolean;
|
|
39
|
+
} & Displayed<D, {
|
|
40
|
+
readonly departmentName: string | null;
|
|
41
|
+
readonly positionName: string | null;
|
|
42
|
+
}>;
|
|
43
|
+
/** An active personnel of the workspace. */
|
|
44
|
+
export type OrgPersonnel<D extends boolean = false> = {
|
|
45
|
+
readonly id: string;
|
|
46
|
+
/** `null` for a personnel without a workspace account. */
|
|
47
|
+
readonly accountId: string | null;
|
|
48
|
+
/** Primary department first, then in tree order. */
|
|
49
|
+
readonly memberships: readonly OrgMembership<D>[];
|
|
50
|
+
} & Displayed<D, {
|
|
51
|
+
readonly display: OrgPersonnelDisplay | null;
|
|
52
|
+
}>;
|
|
53
|
+
/** One membership row returned by a member listing, with the personnel's account. */
|
|
54
|
+
export type OrgMember<D extends boolean = false> = OrgMembership<D> & {
|
|
55
|
+
readonly accountId: string | null;
|
|
56
|
+
} & Displayed<D, {
|
|
57
|
+
readonly display: OrgPersonnelDisplay | null;
|
|
58
|
+
}>;
|
|
59
|
+
/** An active department. */
|
|
60
|
+
export type OrgDepartment<D extends boolean = false> = {
|
|
61
|
+
readonly id: string;
|
|
62
|
+
/** `null` for a root department. */
|
|
63
|
+
readonly parentId: string | null;
|
|
64
|
+
/** `1` for a root department, `2` for its children, and so on. */
|
|
65
|
+
readonly level: number;
|
|
66
|
+
/** Child departments in display order. */
|
|
67
|
+
readonly childIds: readonly string[];
|
|
68
|
+
/** Positions that apply to the department. */
|
|
69
|
+
readonly positionIds: readonly string[];
|
|
70
|
+
} & Displayed<D, {
|
|
71
|
+
readonly display: OrgNameDisplay | null;
|
|
72
|
+
}>;
|
|
73
|
+
/** A department with its child departments, as returned by `departments.tree()`. */
|
|
74
|
+
export type OrgDepartmentNode<D extends boolean = false> = OrgDepartment<D> & {
|
|
75
|
+
/** Empty below the requested depth even when `childIds` is not. */
|
|
76
|
+
readonly children: readonly OrgDepartmentNode<D>[];
|
|
77
|
+
};
|
|
78
|
+
/** An active position. */
|
|
79
|
+
export type OrgPosition<D extends boolean = false> = {
|
|
80
|
+
readonly id: string;
|
|
81
|
+
/** `true`: applies only to `departmentIds`; `false`: applies to every department except `excludedDepartmentIds`. */
|
|
82
|
+
readonly departmentOnly: boolean;
|
|
83
|
+
readonly departmentIds: readonly string[];
|
|
84
|
+
readonly excludedDepartmentIds: readonly string[];
|
|
85
|
+
} & Displayed<D, {
|
|
86
|
+
readonly display: OrgNameDisplay | null;
|
|
87
|
+
}>;
|
|
88
|
+
/** The managers of one level of one department. */
|
|
89
|
+
export type OrgManagerTier<D extends boolean = false> = {
|
|
90
|
+
readonly departmentId: string;
|
|
91
|
+
readonly level: number;
|
|
92
|
+
/** `0` for the starting department, `1` for its parent, and so on. */
|
|
93
|
+
readonly distance: number;
|
|
94
|
+
/** Several personnel may share a level. */
|
|
95
|
+
readonly personnelIds: readonly string[];
|
|
96
|
+
} & Displayed<D, {
|
|
97
|
+
readonly departmentName: string | null;
|
|
98
|
+
readonly personnel: readonly {
|
|
99
|
+
readonly id: string;
|
|
100
|
+
readonly display: OrgPersonnelDisplay | null;
|
|
101
|
+
}[];
|
|
102
|
+
}>;
|
|
103
|
+
/** Managers above a personnel or a department, nearest first, up to the root department. */
|
|
104
|
+
export interface OrgManagerChain<D extends boolean = false> {
|
|
105
|
+
readonly fromDepartmentId: string;
|
|
106
|
+
/** Level of the personnel in `fromDepartmentId`; `0` for a department chain. */
|
|
107
|
+
readonly personnelLevel: number;
|
|
108
|
+
readonly tiers: readonly OrgManagerTier<D>[];
|
|
109
|
+
/** Departments passed without any eligible manager. */
|
|
110
|
+
readonly vacantDepartmentIds: readonly string[];
|
|
111
|
+
/** `true` when a parent department is inactive, so the chain stops before the real root. */
|
|
112
|
+
readonly truncated: boolean;
|
|
113
|
+
}
|
|
114
|
+
/** One page of a listing. */
|
|
115
|
+
export interface OrgPage<T> {
|
|
116
|
+
readonly items: readonly T[];
|
|
117
|
+
/** Number of items in all pages. */
|
|
118
|
+
readonly total: number;
|
|
119
|
+
/** Pass as `cursor` to read the next page; absent on the last page. */
|
|
120
|
+
readonly nextCursor?: string;
|
|
121
|
+
}
|
|
122
|
+
/** Result of `personnel.getMany()`. */
|
|
123
|
+
export interface OrgGetManyResult<T> {
|
|
124
|
+
/** Found personnel, in request order. */
|
|
125
|
+
readonly items: readonly T[];
|
|
126
|
+
/** Requested IDs that are not active personnel, in request order. */
|
|
127
|
+
readonly missingIds: readonly string[];
|
|
128
|
+
}
|
|
129
|
+
/** Options of a member listing. */
|
|
130
|
+
export interface OrgPageOptions extends OrgReadOptions {
|
|
131
|
+
/** Also list the members of every sub-department. */
|
|
132
|
+
readonly includeSubDepartments?: boolean;
|
|
133
|
+
/** Only personnel with a workspace account. */
|
|
134
|
+
readonly accountOnly?: boolean;
|
|
135
|
+
/** Page size: default 500 and at most 2000; default and at most 200 with `withDisplay`. */
|
|
136
|
+
readonly limit?: number;
|
|
137
|
+
readonly cursor?: string;
|
|
138
|
+
}
|
|
139
|
+
export interface OrgDepartmentMembersOptions extends OrgPageOptions {
|
|
140
|
+
/** Only members holding this position. */
|
|
141
|
+
readonly positionId?: string;
|
|
142
|
+
}
|
|
143
|
+
export interface OrgPositionMembersOptions extends OrgPageOptions {
|
|
144
|
+
/** Only holders in this department (and its sub-departments with `includeSubDepartments`). */
|
|
145
|
+
readonly departmentId?: string;
|
|
146
|
+
}
|
|
147
|
+
export interface OrgManagerOptions extends OrgReadOptions {
|
|
148
|
+
/** Only managers with a workspace account, for example approvers. */
|
|
149
|
+
readonly accountOnly?: boolean;
|
|
150
|
+
}
|
|
151
|
+
export interface OrgPersonnelChainOptions extends OrgManagerOptions {
|
|
152
|
+
/** Only the chain that starts in this department. */
|
|
153
|
+
readonly departmentId?: string;
|
|
154
|
+
}
|
|
155
|
+
export interface OrgTreeOptions extends OrgReadOptions {
|
|
156
|
+
/** Start below this department instead of at every root. */
|
|
157
|
+
readonly rootId?: string;
|
|
158
|
+
/** Number of levels to return, 1 to 100; defaults to all. */
|
|
159
|
+
readonly depth?: number;
|
|
160
|
+
}
|
|
161
|
+
export interface OrgIsInDepartmentOptions {
|
|
162
|
+
/** Also count membership of a sub-department. */
|
|
163
|
+
readonly includeSubDepartments?: boolean;
|
|
164
|
+
}
|
|
165
|
+
export interface OrgIsManagerOfOptions {
|
|
166
|
+
/** Only consider the chain that starts in this department of the personnel. */
|
|
167
|
+
readonly departmentId?: string;
|
|
168
|
+
/** Only the nearest manager level counts. */
|
|
169
|
+
readonly directOnly?: boolean;
|
|
170
|
+
}
|
|
171
|
+
/** Personnel of the workspace. */
|
|
172
|
+
export interface OrgPersonnelApi {
|
|
173
|
+
get(id: string, options: OrgReadOptions & WithDisplay): Promise<OrgPersonnel<true> | null>;
|
|
174
|
+
get(id: string, options?: OrgReadOptions): Promise<OrgPersonnel | null>;
|
|
175
|
+
/** Reads up to 200 personnel in one call; unknown IDs are reported in `missingIds`. */
|
|
176
|
+
getMany(ids: readonly string[], options: OrgReadOptions & WithDisplay): Promise<OrgGetManyResult<OrgPersonnel<true>>>;
|
|
177
|
+
getMany(ids: readonly string[], options?: OrgReadOptions): Promise<OrgGetManyResult<OrgPersonnel>>;
|
|
178
|
+
/** One chain per department of the personnel, primary department first; empty for an unknown personnel. */
|
|
179
|
+
managerChain(id: string, options: OrgPersonnelChainOptions & WithDisplay): Promise<readonly OrgManagerChain<true>[]>;
|
|
180
|
+
managerChain(id: string, options?: OrgPersonnelChainOptions): Promise<readonly OrgManagerChain[]>;
|
|
181
|
+
}
|
|
182
|
+
/** Departments of the workspace. */
|
|
183
|
+
export interface OrgDepartmentsApi {
|
|
184
|
+
get(id: string, options: OrgReadOptions & WithDisplay): Promise<OrgDepartment<true> | null>;
|
|
185
|
+
get(id: string, options?: OrgReadOptions): Promise<OrgDepartment | null>;
|
|
186
|
+
/** Root departments (or `rootId`) with their sub-departments; at most 5000 departments. */
|
|
187
|
+
tree(options: OrgTreeOptions & WithDisplay): Promise<readonly OrgDepartmentNode<true>[]>;
|
|
188
|
+
tree(options?: OrgTreeOptions): Promise<readonly OrgDepartmentNode[]>;
|
|
189
|
+
/** Parent first, root last. */
|
|
190
|
+
ancestors(id: string, options: OrgReadOptions & WithDisplay): Promise<readonly OrgDepartment<true>[]>;
|
|
191
|
+
ancestors(id: string, options?: OrgReadOptions): Promise<readonly OrgDepartment[]>;
|
|
192
|
+
/** Memberships of the department, managers first by level, then staff. */
|
|
193
|
+
members(id: string, options: OrgDepartmentMembersOptions & WithDisplay): Promise<OrgPage<OrgMember<true>>>;
|
|
194
|
+
members(id: string, options?: OrgDepartmentMembersOptions): Promise<OrgPage<OrgMember>>;
|
|
195
|
+
/** Managers of this department only, level 1 first. */
|
|
196
|
+
managers(id: string, options: OrgManagerOptions & WithDisplay): Promise<readonly OrgManagerTier<true>[]>;
|
|
197
|
+
managers(id: string, options?: OrgManagerOptions): Promise<readonly OrgManagerTier[]>;
|
|
198
|
+
/** Managers above a staff member of the department, nearest first. */
|
|
199
|
+
managerChain(id: string, options: OrgManagerOptions & WithDisplay): Promise<OrgManagerChain<true>>;
|
|
200
|
+
managerChain(id: string, options?: OrgManagerOptions): Promise<OrgManagerChain>;
|
|
201
|
+
}
|
|
202
|
+
/** Positions of the workspace. */
|
|
203
|
+
export interface OrgPositionsApi {
|
|
204
|
+
list(options: OrgReadOptions & WithDisplay): Promise<readonly OrgPosition<true>[]>;
|
|
205
|
+
list(options?: OrgReadOptions): Promise<readonly OrgPosition[]>;
|
|
206
|
+
get(id: string, options: OrgReadOptions & WithDisplay): Promise<OrgPosition<true> | null>;
|
|
207
|
+
get(id: string, options?: OrgReadOptions): Promise<OrgPosition | null>;
|
|
208
|
+
/** Holders of the position, in tree order of their departments. */
|
|
209
|
+
members(id: string, options: OrgPositionMembersOptions & WithDisplay): Promise<OrgPage<OrgMember<true>>>;
|
|
210
|
+
members(id: string, options?: OrgPositionMembersOptions): Promise<OrgPage<OrgMember>>;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Read-only access to the departments, positions and personnel of the workspace. Structure answers come from
|
|
214
|
+
* memory; `withDisplay` adds names and avatars. Other personnel fields are read with `data.object("personnel")`.
|
|
215
|
+
*/
|
|
216
|
+
export interface OrgApi {
|
|
217
|
+
readonly personnel: OrgPersonnelApi;
|
|
218
|
+
readonly departments: OrgDepartmentsApi;
|
|
219
|
+
readonly positions: OrgPositionsApi;
|
|
220
|
+
/** The personnel of the invocation's user; `null` without a user. */
|
|
221
|
+
me(options: OrgReadOptions & WithDisplay): Promise<OrgPersonnel<true> | null>;
|
|
222
|
+
me(options?: OrgReadOptions): Promise<OrgPersonnel | null>;
|
|
223
|
+
isInDepartment(personnelId: string, departmentId: string, options?: OrgIsInDepartmentOptions): Promise<boolean>;
|
|
224
|
+
/** Whether `managerId` appears in a manager chain of `personnelId`. */
|
|
225
|
+
isManagerOf(managerId: string, personnelId: string, options?: OrgIsManagerOfOptions): Promise<boolean>;
|
|
226
|
+
}
|
|
227
|
+
export {};
|
package/dist/org.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "./errors.js";
|
|
2
|
+
import { callBridge } from "./internal/bridge.js";
|
|
3
|
+
import { isRecord } from "./internal/values.js";
|
|
4
|
+
const MAX_IDS = 200;
|
|
5
|
+
const MAX_PAGE_SIZE = 2000;
|
|
6
|
+
const MAX_TREE_DEPTH = 100;
|
|
7
|
+
const ID = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
8
|
+
const LANGUAGE = /^[A-Za-z]{2,8}(?:[-_][A-Za-z0-9]{1,8}){0,3}$/u;
|
|
9
|
+
const DISPLAY_OPTIONS = ["withDisplay", "language"];
|
|
10
|
+
/** @internal */
|
|
11
|
+
export function createOrgApi(invocation) {
|
|
12
|
+
function payloadFor(method, options, allowed, display) {
|
|
13
|
+
if (options === undefined || options === null)
|
|
14
|
+
return {};
|
|
15
|
+
if (!isRecord(options))
|
|
16
|
+
throw new ValidationError(`${method} options must be an object`);
|
|
17
|
+
const payload = {};
|
|
18
|
+
for (const [name, value] of Object.entries(options)) {
|
|
19
|
+
if (value === undefined)
|
|
20
|
+
continue;
|
|
21
|
+
if (display && name === "withDisplay") {
|
|
22
|
+
payload.withDisplay = requireBoolean(value, `${method} withDisplay`);
|
|
23
|
+
}
|
|
24
|
+
else if (display && name === "language") {
|
|
25
|
+
payload.language = requireLanguage(value, `${method} language`);
|
|
26
|
+
}
|
|
27
|
+
else if (Object.prototype.hasOwnProperty.call(allowed, name)) {
|
|
28
|
+
payload[name] = option(allowed[name], value, `${method} ${name}`);
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
throw new ValidationError(`${method} does not support option '${name}'`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (display && payload.withDisplay === true && payload.language === undefined) {
|
|
35
|
+
const language = defaultLanguage();
|
|
36
|
+
if (language !== undefined)
|
|
37
|
+
payload.language = language;
|
|
38
|
+
}
|
|
39
|
+
return payload;
|
|
40
|
+
}
|
|
41
|
+
function defaultLanguage() {
|
|
42
|
+
let context;
|
|
43
|
+
try {
|
|
44
|
+
context = invocation();
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// Without invocation metadata the stored default names are returned.
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
const language = context.user?.membership.language ?? context.user?.language ?? context.workspace.language;
|
|
51
|
+
return typeof language === "string" && LANGUAGE.test(language) ? language : undefined;
|
|
52
|
+
}
|
|
53
|
+
async function read(operation, payload) {
|
|
54
|
+
return callBridge(operation, payload);
|
|
55
|
+
}
|
|
56
|
+
async function object(operation, payload) {
|
|
57
|
+
const result = await read(operation, payload);
|
|
58
|
+
if (!isRecord(result))
|
|
59
|
+
throw invalidResponse(operation);
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
async function nullableObject(operation, payload) {
|
|
63
|
+
const result = await read(operation, payload);
|
|
64
|
+
if (result !== null && !isRecord(result))
|
|
65
|
+
throw invalidResponse(operation);
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
async function list(operation, payload) {
|
|
69
|
+
const result = await read(operation, payload);
|
|
70
|
+
if (!Array.isArray(result))
|
|
71
|
+
throw invalidResponse(operation);
|
|
72
|
+
return Object.freeze(result);
|
|
73
|
+
}
|
|
74
|
+
async function flag(operation, payload) {
|
|
75
|
+
const result = await read(operation, payload);
|
|
76
|
+
if (typeof result !== "boolean")
|
|
77
|
+
throw invalidResponse(operation);
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
const pageOptions = {
|
|
81
|
+
includeSubDepartments: "boolean", accountOnly: "boolean", limit: "limit", cursor: "cursor",
|
|
82
|
+
};
|
|
83
|
+
const personnel = {
|
|
84
|
+
get(id, options) {
|
|
85
|
+
return nullableObject("org.personnel.get", {
|
|
86
|
+
...payloadFor("personnel.get()", options, {}, true), id: requireId(id, "personnel id"),
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
getMany(ids, options) {
|
|
90
|
+
if (!Array.isArray(ids))
|
|
91
|
+
throw new ValidationError("personnel.getMany() requires an array of ids");
|
|
92
|
+
const unique = [...new Set(ids.map(id => requireId(id, "personnel id")))];
|
|
93
|
+
if (unique.length > MAX_IDS) {
|
|
94
|
+
throw new ValidationError(`personnel.getMany() supports at most ${MAX_IDS} unique ids`);
|
|
95
|
+
}
|
|
96
|
+
return object("org.personnel.getMany", {
|
|
97
|
+
...payloadFor("personnel.getMany()", options, {}, true), ids: unique,
|
|
98
|
+
});
|
|
99
|
+
},
|
|
100
|
+
managerChain(id, options) {
|
|
101
|
+
return list("org.personnel.managerChain", {
|
|
102
|
+
...payloadFor("personnel.managerChain()", options, { departmentId: "id", accountOnly: "boolean" }, true),
|
|
103
|
+
id: requireId(id, "personnel id"),
|
|
104
|
+
});
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
const departments = {
|
|
108
|
+
get(id, options) {
|
|
109
|
+
return nullableObject("org.departments.get", {
|
|
110
|
+
...payloadFor("departments.get()", options, {}, true), id: requireId(id, "department id"),
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
tree(options) {
|
|
114
|
+
return list("org.departments.tree", payloadFor("departments.tree()", options, { rootId: "id", depth: "depth" }, true));
|
|
115
|
+
},
|
|
116
|
+
ancestors(id, options) {
|
|
117
|
+
return list("org.departments.ancestors", {
|
|
118
|
+
...payloadFor("departments.ancestors()", options, {}, true), id: requireId(id, "department id"),
|
|
119
|
+
});
|
|
120
|
+
},
|
|
121
|
+
members(id, options) {
|
|
122
|
+
return object("org.departments.members", {
|
|
123
|
+
...payloadFor("departments.members()", options, { ...pageOptions, positionId: "id" }, true),
|
|
124
|
+
id: requireId(id, "department id"),
|
|
125
|
+
});
|
|
126
|
+
},
|
|
127
|
+
managers(id, options) {
|
|
128
|
+
return list("org.departments.managers", {
|
|
129
|
+
...payloadFor("departments.managers()", options, { accountOnly: "boolean" }, true),
|
|
130
|
+
id: requireId(id, "department id"),
|
|
131
|
+
});
|
|
132
|
+
},
|
|
133
|
+
managerChain(id, options) {
|
|
134
|
+
return object("org.departments.managerChain", {
|
|
135
|
+
...payloadFor("departments.managerChain()", options, { accountOnly: "boolean" }, true),
|
|
136
|
+
id: requireId(id, "department id"),
|
|
137
|
+
});
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
const positions = {
|
|
141
|
+
list(options) {
|
|
142
|
+
return list("org.positions.list", payloadFor("positions.list()", options, {}, true));
|
|
143
|
+
},
|
|
144
|
+
get(id, options) {
|
|
145
|
+
return nullableObject("org.positions.get", {
|
|
146
|
+
...payloadFor("positions.get()", options, {}, true), id: requireId(id, "position id"),
|
|
147
|
+
});
|
|
148
|
+
},
|
|
149
|
+
members(id, options) {
|
|
150
|
+
return object("org.positions.members", {
|
|
151
|
+
...payloadFor("positions.members()", options, { ...pageOptions, departmentId: "id" }, true),
|
|
152
|
+
id: requireId(id, "position id"),
|
|
153
|
+
});
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
return Object.freeze({
|
|
157
|
+
personnel: Object.freeze(personnel),
|
|
158
|
+
departments: Object.freeze(departments),
|
|
159
|
+
positions: Object.freeze(positions),
|
|
160
|
+
async me(options) {
|
|
161
|
+
// Validate before deciding, so a wrong option fails the same way with and without a user.
|
|
162
|
+
payloadFor("me()", options, {}, true);
|
|
163
|
+
const context = invocation();
|
|
164
|
+
const personnelId = context.identity === "user" ? context.user.membership.personnelId : undefined;
|
|
165
|
+
if (personnelId === undefined)
|
|
166
|
+
return null;
|
|
167
|
+
return personnel.get(personnelId, options);
|
|
168
|
+
},
|
|
169
|
+
isInDepartment(personnelId, departmentId, options) {
|
|
170
|
+
return flag("org.isInDepartment", {
|
|
171
|
+
...payloadFor("isInDepartment()", options, { includeSubDepartments: "boolean" }, false),
|
|
172
|
+
personnelId: requireId(personnelId, "personnel id"),
|
|
173
|
+
departmentId: requireId(departmentId, "department id"),
|
|
174
|
+
});
|
|
175
|
+
},
|
|
176
|
+
isManagerOf(managerId, personnelId, options) {
|
|
177
|
+
return flag("org.isManagerOf", {
|
|
178
|
+
...payloadFor("isManagerOf()", options, { departmentId: "id", directOnly: "boolean" }, false),
|
|
179
|
+
managerId: requireId(managerId, "manager id"),
|
|
180
|
+
personnelId: requireId(personnelId, "personnel id"),
|
|
181
|
+
});
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
function option(kind, value, label) {
|
|
186
|
+
switch (kind) {
|
|
187
|
+
case "boolean":
|
|
188
|
+
return requireBoolean(value, label);
|
|
189
|
+
case "id":
|
|
190
|
+
return requireId(value, label);
|
|
191
|
+
case "limit":
|
|
192
|
+
return requireInteger(value, label, 1, MAX_PAGE_SIZE);
|
|
193
|
+
case "depth":
|
|
194
|
+
return requireInteger(value, label, 1, MAX_TREE_DEPTH);
|
|
195
|
+
case "cursor":
|
|
196
|
+
if (typeof value !== "string" || value === "")
|
|
197
|
+
throw new ValidationError(`${label} must be a cursor`);
|
|
198
|
+
return value;
|
|
199
|
+
default:
|
|
200
|
+
throw new ValidationError(`${label} is not supported`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function requireId(value, label) {
|
|
204
|
+
if (typeof value !== "string" || !ID.test(value))
|
|
205
|
+
throw new ValidationError(`${label} must be a valid id`);
|
|
206
|
+
return value;
|
|
207
|
+
}
|
|
208
|
+
function requireBoolean(value, label) {
|
|
209
|
+
if (typeof value !== "boolean")
|
|
210
|
+
throw new ValidationError(`${label} must be a boolean`);
|
|
211
|
+
return value;
|
|
212
|
+
}
|
|
213
|
+
function requireInteger(value, label, min, max) {
|
|
214
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
|
|
215
|
+
throw new ValidationError(`${label} must be an integer between ${min} and ${max}`);
|
|
216
|
+
}
|
|
217
|
+
return value;
|
|
218
|
+
}
|
|
219
|
+
function requireLanguage(value, label) {
|
|
220
|
+
if (typeof value !== "string" || !LANGUAGE.test(value)) {
|
|
221
|
+
throw new ValidationError(`${label} must be a language tag such as "vi-VN"`);
|
|
222
|
+
}
|
|
223
|
+
return value;
|
|
224
|
+
}
|
|
225
|
+
function invalidResponse(operation) {
|
|
226
|
+
return new CogoverApiError("INVALID_BRIDGE_RESPONSE", `${operation} returned an unexpected response`);
|
|
227
|
+
}
|
package/dist/router.js
CHANGED
package/dist/script.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ import type { InvocationContext } from "./invocation.js";
|
|
|
11
11
|
import type { JobsApi } from "./jobs.js";
|
|
12
12
|
import type { SecretsApi } from "./secrets.js";
|
|
13
13
|
import type { CryptoApi } from "./crypto.js";
|
|
14
|
+
import type { OrgApi } from "./org.js";
|
|
14
15
|
export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspaceObjects> {
|
|
15
16
|
readonly input: TInput;
|
|
16
17
|
readonly request: ScriptRequest<TInput>;
|
|
@@ -25,6 +26,7 @@ export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspa
|
|
|
25
26
|
readonly jobs: JobsApi;
|
|
26
27
|
readonly secrets: SecretsApi;
|
|
27
28
|
readonly crypto: CryptoApi;
|
|
29
|
+
readonly org: OrgApi;
|
|
28
30
|
}
|
|
29
31
|
export type ScriptHandler<TInput, TOutput, TSchema extends object = EffectiveWorkspaceObjects> = (context: ScriptContext<TInput, TSchema>) => TOutput | ScriptResponse<unknown> | null | Promise<TOutput | ScriptResponse<unknown> | null>;
|
|
30
32
|
export type SandboxHandler = (inputJson: string) => Promise<string | null>;
|
package/dist/script.js
CHANGED
|
@@ -13,6 +13,7 @@ import { invocationContext } from "./internal/invocation.js";
|
|
|
13
13
|
import { createJobsApi } from "./internal/jobs-api.js";
|
|
14
14
|
import { createSecretsApi } from "./secrets.js";
|
|
15
15
|
import { crypto } from "./crypto.js";
|
|
16
|
+
import { createOrgApi } from "./org.js";
|
|
16
17
|
export function defineScript(handler) {
|
|
17
18
|
if (typeof handler !== "function") {
|
|
18
19
|
throw new ValidationError("defineScript() requires a handler function");
|
|
@@ -51,6 +52,7 @@ export function createSandboxHandler(handler) {
|
|
|
51
52
|
jobs: createJobsApi(),
|
|
52
53
|
secrets: createSecretsApi(),
|
|
53
54
|
crypto,
|
|
55
|
+
org: createOrgApi(() => invocation ??= invocationContext(input)),
|
|
54
56
|
});
|
|
55
57
|
if (output === null) {
|
|
56
58
|
return null;
|
package/dist/trigger.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { CryptoApi } from "./crypto.js";
|
|
2
2
|
import type { DataApi } from "./data.js";
|
|
3
3
|
import type { JobsApi } from "./jobs.js";
|
|
4
|
+
import type { OrgApi } from "./org.js";
|
|
4
5
|
import type { SecretsApi } from "./secrets.js";
|
|
5
6
|
import type { InvocationContext } from "./invocation.js";
|
|
6
7
|
import type { ScriptLogger } from "./logger.js";
|
|
@@ -125,6 +126,7 @@ export interface TriggerContext<TObject extends string = string, TOperation exte
|
|
|
125
126
|
/** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
|
|
126
127
|
readonly secrets: SecretsApi;
|
|
127
128
|
readonly crypto: CryptoApi;
|
|
129
|
+
readonly org: OrgApi;
|
|
128
130
|
}
|
|
129
131
|
export type TriggerHandler<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> = (context: TriggerContext<TObject, TOperation, TSchema>) => void | Promise<void>;
|
|
130
132
|
/** Declares a record trigger. Add the result to the project's `triggers` export. */
|
package/docs/en/api-reference.md
CHANGED
|
@@ -9,7 +9,7 @@ configured for the project.
|
|
|
9
9
|
|
|
10
10
|
`defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
|
|
11
11
|
the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
|
|
12
|
-
`push`, `jobs`, `secrets`, and `
|
|
12
|
+
`push`, `jobs`, `secrets`, `crypto`, and `org`, awaits the handler, and serializes its result.
|
|
13
13
|
|
|
14
14
|
```typescript
|
|
15
15
|
function defineScript<
|
|
@@ -43,6 +43,7 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
|
|
|
43
43
|
readonly jobs: JobsApi;
|
|
44
44
|
readonly secrets: SecretsApi;
|
|
45
45
|
readonly crypto: CryptoApi;
|
|
46
|
+
readonly org: OrgApi;
|
|
46
47
|
}
|
|
47
48
|
```
|
|
48
49
|
|
|
@@ -53,7 +54,7 @@ Returning `null` produces a null handler result; returning `undefined` is invali
|
|
|
53
54
|
## HTTP routers and request context
|
|
54
55
|
|
|
55
56
|
`ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
|
|
56
|
-
`log`, `state`, `locks`, `push`, `jobs`, `secrets`, and `
|
|
57
|
+
`log`, `state`, `locks`, `push`, `jobs`, `secrets`, `crypto`, and `org` to both script and route handlers. `input`
|
|
57
58
|
preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
|
|
58
59
|
metadata and transport/authentication fields removed by Cogover.
|
|
59
60
|
|
|
@@ -107,10 +108,17 @@ interface CurrentWorkspace {
|
|
|
107
108
|
readonly numberFormat?: string;
|
|
108
109
|
}
|
|
109
110
|
|
|
111
|
+
interface CurrentWorkspaceRole {
|
|
112
|
+
readonly id: string;
|
|
113
|
+
readonly name: string;
|
|
114
|
+
}
|
|
115
|
+
|
|
110
116
|
interface CurrentWorkspaceMembership {
|
|
111
117
|
readonly personnelId?: string;
|
|
112
118
|
readonly language?: string;
|
|
113
119
|
readonly timezone?: string;
|
|
120
|
+
readonly isSuperAdmin: boolean; // Holds the workspace's Super Admin role
|
|
121
|
+
readonly roles: readonly CurrentWorkspaceRole[]; // Sorted by name
|
|
114
122
|
}
|
|
115
123
|
|
|
116
124
|
interface CurrentUser {
|
|
@@ -178,6 +186,38 @@ the authenticated request context. Raw authentication data, tokens, inbound keys
|
|
|
178
186
|
and credentials are not included. A handler called outside Cogover has no
|
|
179
187
|
authenticated invocation snapshot.
|
|
180
188
|
|
|
189
|
+
### Workspace roles of the current user
|
|
190
|
+
|
|
191
|
+
`user.membership` describes the caller's membership in the current workspace:
|
|
192
|
+
|
|
193
|
+
- `isSuperAdmin` is `true` when one of the user's roles is the workspace's
|
|
194
|
+
highest administrator (Super Admin) role, otherwise `false`.
|
|
195
|
+
- `roles` lists the roles assigned to the user in the current workspace, sorted
|
|
196
|
+
by name. Each `CurrentWorkspaceRole` has only an `id` and a `name`; the list is
|
|
197
|
+
empty when the user has no role. Role permissions are not exposed.
|
|
198
|
+
|
|
199
|
+
Compare roles by `id`: a role can be renamed, and the same role name has a
|
|
200
|
+
different `id` in each workspace. Record and field access is still enforced by
|
|
201
|
+
Cogover under the user's identity, so use these fields for business rules, such
|
|
202
|
+
as who may approve an order, not as a replacement for security rules.
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
const APPROVER_ROLE_ID = "RO6P2N1K9X4A";
|
|
206
|
+
|
|
207
|
+
export default defineScript(({ invocation }) => {
|
|
208
|
+
const user = invocation.user;
|
|
209
|
+
const canApprove = user !== null && (user.membership.isSuperAdmin
|
|
210
|
+
|| user.membership.roles.some((role) => role.id === APPROVER_ROLE_ID));
|
|
211
|
+
return {canApprove};
|
|
212
|
+
});
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
HTTP invocations reflect the user's roles at the time of the request. Record
|
|
216
|
+
triggers and background jobs may see a role change up to about one minute late.
|
|
217
|
+
In local development with the Cogover Dev CLI, the values are captured when the
|
|
218
|
+
development session starts; restart `cogover-dev` to pick up role changes. A
|
|
219
|
+
`system` or `inbound` invocation has `user: null` and therefore no membership.
|
|
220
|
+
|
|
181
221
|
### `createRouter<TSchema = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>`
|
|
182
222
|
|
|
183
223
|
Creates an independent router. `TSchema extends object` defaults to the effective
|
|
@@ -501,6 +541,7 @@ interface TriggerContext<
|
|
|
501
541
|
readonly jobs: JobsApi;
|
|
502
542
|
readonly secrets: SecretsApi;
|
|
503
543
|
readonly crypto: CryptoApi;
|
|
544
|
+
readonly org: OrgApi;
|
|
504
545
|
}
|
|
505
546
|
|
|
506
547
|
interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
|
|
@@ -536,8 +577,8 @@ receives all records of the same change that run the trigger, up to 200 records
|
|
|
536
577
|
once per record. Keep `fields` short, and read related data for the whole list with
|
|
537
578
|
one `records.getMany` call rather than one read per record.
|
|
538
579
|
|
|
539
|
-
`data`, `schema`, `log`, `invocation`, `push`, `jobs`, `secrets`, and `
|
|
540
|
-
same APIs that scripts receive. A trigger context has no `input`, `request`, `response`,
|
|
580
|
+
`data`, `schema`, `log`, `invocation`, `push`, `jobs`, `secrets`, `crypto`, and `org` are
|
|
581
|
+
the same APIs that scripts receive. A trigger context has no `input`, `request`, `response`,
|
|
541
582
|
`state`, or `locks`; `push` is refused in a before-change trigger. `trigger.operation` is
|
|
542
583
|
the operation of the current call, `trigger.id` identifies the trigger registration, and
|
|
543
584
|
`trigger.changeId` identifies the record change that caused the call.
|
|
@@ -622,7 +663,8 @@ a request that only validates input without saving.
|
|
|
622
663
|
`PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
|
|
623
664
|
applies to every identity, including `data.asSystem()`. Every `crypto` operation
|
|
624
665
|
with a key given in the call remains available, as do `crypto.sha256`,
|
|
625
|
-
`crypto.randomBytes`, `crypto.randomUUID`,
|
|
666
|
+
`crypto.randomBytes`, `crypto.randomUUID`, `crypto.timingSafeEqual`, and every
|
|
667
|
+
[`org`](#organization-structure) read.
|
|
626
668
|
- **Identity.** `data.object()` acts as the user who made the change, with that
|
|
627
669
|
user's permissions, and `invocation` describes the same user. When a change has
|
|
628
670
|
no user, `invocation.identity` is `"system"` and `data.object()` works only if the
|
|
@@ -872,6 +914,7 @@ interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspa
|
|
|
872
914
|
readonly jobs: JobsApi;
|
|
873
915
|
readonly secrets: SecretsApi;
|
|
874
916
|
readonly crypto: CryptoApi;
|
|
917
|
+
readonly org: OrgApi;
|
|
875
918
|
}
|
|
876
919
|
|
|
877
920
|
interface JobInfo {
|
|
@@ -886,7 +929,7 @@ interface JobInfo {
|
|
|
886
929
|
```
|
|
887
930
|
|
|
888
931
|
A handler may be synchronous or asynchronous; its return value is ignored. `data`,
|
|
889
|
-
`schema`, `log`, `invocation`, `state`, `locks`, `jobs`, `secrets`, and `
|
|
932
|
+
`schema`, `log`, `invocation`, `state`, `locks`, `jobs`, `secrets`, `crypto`, and `org`
|
|
890
933
|
are the same APIs that scripts receive. A job context has no `input`, `request`, or
|
|
891
934
|
`response`.
|
|
892
935
|
|
|
@@ -2063,6 +2106,305 @@ custom component listening for it. `content` is required (up to 16,384 character
|
|
|
2063
2106
|
- A sent message cannot be recalled, and retrying a failed execution may send it
|
|
2064
2107
|
again.
|
|
2065
2108
|
|
|
2109
|
+
## Organization structure
|
|
2110
|
+
|
|
2111
|
+
`org` reads the departments, positions and personnel of the workspace: who works in
|
|
2112
|
+
which department, which positions apply where, and who manages whom. Every method is
|
|
2113
|
+
a read. Structure answers are served from a cached copy of the organization, so they
|
|
2114
|
+
are fast; a change made in Cogover is visible within a few seconds. Add
|
|
2115
|
+
`withDisplay: true` to also receive department and position names in a language and,
|
|
2116
|
+
for personnel, their display name, email, avatar and code. Other personnel fields,
|
|
2117
|
+
such as phone numbers or custom fields, are read with `data.object("personnel")`,
|
|
2118
|
+
which applies record permissions.
|
|
2119
|
+
|
|
2120
|
+
```typescript
|
|
2121
|
+
interface OrgApi {
|
|
2122
|
+
readonly personnel: OrgPersonnelApi;
|
|
2123
|
+
readonly departments: OrgDepartmentsApi;
|
|
2124
|
+
readonly positions: OrgPositionsApi;
|
|
2125
|
+
me(options?: OrgReadOptions): Promise<OrgPersonnel | null>;
|
|
2126
|
+
isInDepartment(personnelId: string, departmentId: string,
|
|
2127
|
+
options?: OrgIsInDepartmentOptions): Promise<boolean>;
|
|
2128
|
+
isManagerOf(managerId: string, personnelId: string,
|
|
2129
|
+
options?: OrgIsManagerOfOptions): Promise<boolean>;
|
|
2130
|
+
}
|
|
2131
|
+
|
|
2132
|
+
interface OrgPersonnelApi {
|
|
2133
|
+
get(id: string, options?: OrgReadOptions): Promise<OrgPersonnel | null>;
|
|
2134
|
+
getMany(ids: readonly string[], options?: OrgReadOptions):
|
|
2135
|
+
Promise<OrgGetManyResult<OrgPersonnel>>;
|
|
2136
|
+
managerChain(id: string, options?: OrgPersonnelChainOptions):
|
|
2137
|
+
Promise<readonly OrgManagerChain[]>;
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
interface OrgDepartmentsApi {
|
|
2141
|
+
get(id: string, options?: OrgReadOptions): Promise<OrgDepartment | null>;
|
|
2142
|
+
tree(options?: OrgTreeOptions): Promise<readonly OrgDepartmentNode[]>;
|
|
2143
|
+
ancestors(id: string, options?: OrgReadOptions): Promise<readonly OrgDepartment[]>;
|
|
2144
|
+
members(id: string, options?: OrgDepartmentMembersOptions): Promise<OrgPage<OrgMember>>;
|
|
2145
|
+
managers(id: string, options?: OrgManagerOptions): Promise<readonly OrgManagerTier[]>;
|
|
2146
|
+
managerChain(id: string, options?: OrgManagerOptions): Promise<OrgManagerChain>;
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
interface OrgPositionsApi {
|
|
2150
|
+
list(options?: OrgReadOptions): Promise<readonly OrgPosition[]>;
|
|
2151
|
+
get(id: string, options?: OrgReadOptions): Promise<OrgPosition | null>;
|
|
2152
|
+
members(id: string, options?: OrgPositionMembersOptions): Promise<OrgPage<OrgMember>>;
|
|
2153
|
+
}
|
|
2154
|
+
```
|
|
2155
|
+
|
|
2156
|
+
Every method that returns data has a second overload: when `options.withDisplay` is
|
|
2157
|
+
the literal `true`, the result type is the `<true>` variant of the types below, whose
|
|
2158
|
+
display fields are always present. Without it, the display fields do not exist on the
|
|
2159
|
+
type.
|
|
2160
|
+
|
|
2161
|
+
```typescript
|
|
2162
|
+
interface OrgReadOptions {
|
|
2163
|
+
readonly withDisplay?: boolean;
|
|
2164
|
+
readonly language?: string; // such as "vi-VN"; defaults to the invocation language
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
interface OrgPageOptions extends OrgReadOptions {
|
|
2168
|
+
readonly includeSubDepartments?: boolean;
|
|
2169
|
+
readonly accountOnly?: boolean;
|
|
2170
|
+
readonly limit?: number; // default 500, at most 2000; 200 with withDisplay
|
|
2171
|
+
readonly cursor?: string;
|
|
2172
|
+
}
|
|
2173
|
+
interface OrgDepartmentMembersOptions extends OrgPageOptions { readonly positionId?: string; }
|
|
2174
|
+
interface OrgPositionMembersOptions extends OrgPageOptions { readonly departmentId?: string; }
|
|
2175
|
+
interface OrgManagerOptions extends OrgReadOptions { readonly accountOnly?: boolean; }
|
|
2176
|
+
interface OrgPersonnelChainOptions extends OrgManagerOptions { readonly departmentId?: string; }
|
|
2177
|
+
interface OrgTreeOptions extends OrgReadOptions {
|
|
2178
|
+
readonly rootId?: string;
|
|
2179
|
+
readonly depth?: number; // 1 to 100; defaults to every level
|
|
2180
|
+
}
|
|
2181
|
+
interface OrgIsInDepartmentOptions { readonly includeSubDepartments?: boolean; }
|
|
2182
|
+
interface OrgIsManagerOfOptions {
|
|
2183
|
+
readonly departmentId?: string;
|
|
2184
|
+
readonly directOnly?: boolean;
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
interface OrgPersonnelDisplay {
|
|
2188
|
+
readonly name: string;
|
|
2189
|
+
readonly email: string | null;
|
|
2190
|
+
readonly avatar: string | null; // public URL
|
|
2191
|
+
readonly code: string | null;
|
|
2192
|
+
}
|
|
2193
|
+
interface OrgNameDisplay { readonly name: string; }
|
|
2194
|
+
|
|
2195
|
+
type OrgMembership<D extends boolean = false> = {
|
|
2196
|
+
readonly personnelId: string;
|
|
2197
|
+
readonly departmentId: string;
|
|
2198
|
+
readonly positionId: string | null;
|
|
2199
|
+
readonly level: number; // 0 staff, 1 highest manager level, 2 next, ...
|
|
2200
|
+
readonly primary: boolean;
|
|
2201
|
+
} & (D extends true
|
|
2202
|
+
? { readonly departmentName: string | null; readonly positionName: string | null }
|
|
2203
|
+
: {});
|
|
2204
|
+
|
|
2205
|
+
type OrgPersonnel<D extends boolean = false> = {
|
|
2206
|
+
readonly id: string;
|
|
2207
|
+
readonly accountId: string | null; // null: no workspace account
|
|
2208
|
+
readonly memberships: readonly OrgMembership<D>[];
|
|
2209
|
+
} & (D extends true ? { readonly display: OrgPersonnelDisplay | null } : {});
|
|
2210
|
+
|
|
2211
|
+
type OrgMember<D extends boolean = false> = OrgMembership<D> & {
|
|
2212
|
+
readonly accountId: string | null;
|
|
2213
|
+
} & (D extends true ? { readonly display: OrgPersonnelDisplay | null } : {});
|
|
2214
|
+
|
|
2215
|
+
type OrgDepartment<D extends boolean = false> = {
|
|
2216
|
+
readonly id: string;
|
|
2217
|
+
readonly parentId: string | null;
|
|
2218
|
+
readonly level: number; // 1 for a root department
|
|
2219
|
+
readonly childIds: readonly string[];
|
|
2220
|
+
readonly positionIds: readonly string[];
|
|
2221
|
+
} & (D extends true ? { readonly display: OrgNameDisplay | null } : {});
|
|
2222
|
+
|
|
2223
|
+
type OrgDepartmentNode<D extends boolean = false> = OrgDepartment<D> & {
|
|
2224
|
+
readonly children: readonly OrgDepartmentNode<D>[];
|
|
2225
|
+
};
|
|
2226
|
+
|
|
2227
|
+
type OrgPosition<D extends boolean = false> = {
|
|
2228
|
+
readonly id: string;
|
|
2229
|
+
readonly departmentOnly: boolean;
|
|
2230
|
+
readonly departmentIds: readonly string[];
|
|
2231
|
+
readonly excludedDepartmentIds: readonly string[];
|
|
2232
|
+
} & (D extends true ? { readonly display: OrgNameDisplay | null } : {});
|
|
2233
|
+
|
|
2234
|
+
type OrgManagerTier<D extends boolean = false> = {
|
|
2235
|
+
readonly departmentId: string;
|
|
2236
|
+
readonly level: number;
|
|
2237
|
+
readonly distance: number; // 0 starting department, 1 its parent, ...
|
|
2238
|
+
readonly personnelIds: readonly string[];
|
|
2239
|
+
} & (D extends true ? {
|
|
2240
|
+
readonly departmentName: string | null;
|
|
2241
|
+
readonly personnel: readonly { readonly id: string; readonly display: OrgPersonnelDisplay | null }[];
|
|
2242
|
+
} : {});
|
|
2243
|
+
|
|
2244
|
+
interface OrgManagerChain<D extends boolean = false> {
|
|
2245
|
+
readonly fromDepartmentId: string;
|
|
2246
|
+
readonly personnelLevel: number;
|
|
2247
|
+
readonly tiers: readonly OrgManagerTier<D>[];
|
|
2248
|
+
readonly vacantDepartmentIds: readonly string[];
|
|
2249
|
+
readonly truncated: boolean;
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
interface OrgPage<T> {
|
|
2253
|
+
readonly items: readonly T[];
|
|
2254
|
+
readonly total: number;
|
|
2255
|
+
readonly nextCursor?: string;
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
interface OrgGetManyResult<T> {
|
|
2259
|
+
readonly items: readonly T[];
|
|
2260
|
+
readonly missingIds: readonly string[];
|
|
2261
|
+
}
|
|
2262
|
+
```
|
|
2263
|
+
|
|
2264
|
+
```typescript
|
|
2265
|
+
export default defineScript(async ({ org, input }) => {
|
|
2266
|
+
const order = input as { ownerId: string; departmentId: string };
|
|
2267
|
+
// Structure only: answered without reading records.
|
|
2268
|
+
const [chain] = await org.personnel.managerChain(order.ownerId, {
|
|
2269
|
+
departmentId: order.departmentId,
|
|
2270
|
+
accountOnly: true,
|
|
2271
|
+
});
|
|
2272
|
+
const approverIds = chain?.tiers[0]?.personnelIds ?? [];
|
|
2273
|
+
|
|
2274
|
+
// Names for a screen: one extra read per kind of data.
|
|
2275
|
+
const me = await org.me({ withDisplay: true });
|
|
2276
|
+
return {
|
|
2277
|
+
approverIds,
|
|
2278
|
+
greeting: me?.display?.name,
|
|
2279
|
+
departments: me?.memberships.map(m => m.departmentName) ?? [],
|
|
2280
|
+
};
|
|
2281
|
+
});
|
|
2282
|
+
```
|
|
2283
|
+
|
|
2284
|
+
### Display data
|
|
2285
|
+
|
|
2286
|
+
- `withDisplay` adds `display` to personnel, departments and positions, and
|
|
2287
|
+
`departmentName`/`positionName` to memberships. A value is `null` when the record
|
|
2288
|
+
behind it cannot be read, for example because it was deleted a moment ago.
|
|
2289
|
+
- `language` selects the translation of department and position names, such as
|
|
2290
|
+
`"vi-VN"` or `"en-US"`; a tag without a region (`"vi"`) matches the first
|
|
2291
|
+
translation of that language. It defaults to the language of the invocation's user
|
|
2292
|
+
membership, then of the user, then of the workspace, and falls back to the stored
|
|
2293
|
+
name when there is no matching translation.
|
|
2294
|
+
- A personnel `name` is the full name the workspace shows; `email` is the account
|
|
2295
|
+
email, else the work email; `avatar` is a public image URL.
|
|
2296
|
+
- Display data is limited to these fields and is readable by every member of the
|
|
2297
|
+
workspace, as in user pickers. It costs at most one read per kind of data and per
|
|
2298
|
+
200 IDs, and recently read values are cached.
|
|
2299
|
+
|
|
2300
|
+
### `org.me(options?)`
|
|
2301
|
+
|
|
2302
|
+
Returns the personnel of the invocation's user, or `null` for a `system` or
|
|
2303
|
+
`inbound` invocation. It is `org.personnel.get` with
|
|
2304
|
+
`invocation.user.membership.personnelId`.
|
|
2305
|
+
|
|
2306
|
+
### `org.personnel.get(id, options?)` and `org.personnel.getMany(ids, options?)`
|
|
2307
|
+
|
|
2308
|
+
`get` returns an active personnel with every department membership, primary
|
|
2309
|
+
department first, or `null` when the ID is not an active personnel of the workspace.
|
|
2310
|
+
`getMany` reads up to 200 IDs in one call: duplicates are removed, `items` follows
|
|
2311
|
+
the request order, and unknown IDs are listed in `missingIds`. A personnel without a
|
|
2312
|
+
workspace account has `accountId: null`; people who left the workspace are not
|
|
2313
|
+
returned.
|
|
2314
|
+
|
|
2315
|
+
### `org.departments.get(id, options?)`, `tree(options?)` and `ancestors(id, options?)`
|
|
2316
|
+
|
|
2317
|
+
- `get` returns one active department or `null`. `childIds` are in display order;
|
|
2318
|
+
`positionIds` are the positions that apply to the department.
|
|
2319
|
+
- `tree` returns the root departments (or `rootId` alone) with their sub-departments.
|
|
2320
|
+
`depth: 1` returns only the roots; below the requested depth `children` is empty
|
|
2321
|
+
while `childIds` still lists the sub-departments. A tree of more than 5000
|
|
2322
|
+
departments throws `ValidationError`; narrow it with `rootId` or `depth`.
|
|
2323
|
+
- `ancestors` returns the parent first and the root last.
|
|
2324
|
+
- A department whose parent is inactive or deleted is returned as a root
|
|
2325
|
+
(`parentId: null`).
|
|
2326
|
+
|
|
2327
|
+
### `org.departments.members(id, options?)` and `org.positions.members(id, options?)`
|
|
2328
|
+
|
|
2329
|
+
Return one page of memberships: managers first by level, then staff. A personnel who
|
|
2330
|
+
belongs to several listed departments appears once per department.
|
|
2331
|
+
`includeSubDepartments` adds every sub-department in tree order, `positionId` keeps
|
|
2332
|
+
only the holders of a position, `departmentId` limits position holders to a
|
|
2333
|
+
department, and `accountOnly` keeps only personnel with a workspace account. Pass
|
|
2334
|
+
`nextCursor` as `cursor` to read the next page; `total` counts every page. The page
|
|
2335
|
+
size is 500 by default and at most 2000, or at most 200 with `withDisplay`.
|
|
2336
|
+
|
|
2337
|
+
### `org.positions.list(options?)` and `org.positions.get(id, options?)`
|
|
2338
|
+
|
|
2339
|
+
Return active positions, oldest first. A department-only position applies to
|
|
2340
|
+
`departmentIds`; any other position applies to every department except
|
|
2341
|
+
`excludedDepartmentIds`.
|
|
2342
|
+
|
|
2343
|
+
### Managers and manager chains
|
|
2344
|
+
|
|
2345
|
+
A membership's `level` marks managers: `0` is staff, `1` the highest manager level of
|
|
2346
|
+
the department, `2` the next one, and so on. Several people may share a level.
|
|
2347
|
+
|
|
2348
|
+
- `org.departments.managers(id, options?)` returns the managers of that department
|
|
2349
|
+
only, one tier per level, level `1` first.
|
|
2350
|
+
- `org.departments.managerChain(id, options?)` returns the managers above a staff
|
|
2351
|
+
member of the department, nearest first, up to the root department.
|
|
2352
|
+
- `org.personnel.managerChain(id, options?)` returns one chain per department of the
|
|
2353
|
+
personnel, primary department first; `departmentId` keeps only the chain that
|
|
2354
|
+
starts in that department. The result is empty for an unknown personnel.
|
|
2355
|
+
|
|
2356
|
+
A chain is built with these rules:
|
|
2357
|
+
|
|
2358
|
+
1. In the starting department, the managers of the personnel are those with a lower
|
|
2359
|
+
level number than the personnel's own level (every manager for staff), nearest
|
|
2360
|
+
first: level `3`, then `2`, then `1`. A department head has none there.
|
|
2361
|
+
2. Then every parent department up to the root adds all its managers, largest level
|
|
2362
|
+
number first. Every manager of a parent department ranks above every manager of
|
|
2363
|
+
its sub-departments.
|
|
2364
|
+
3. A personnel is listed once, at the nearest tier, and the starting personnel is
|
|
2365
|
+
never listed.
|
|
2366
|
+
4. `accountOnly: true` skips personnel without a workspace account, for example when
|
|
2367
|
+
the chain lists approvers.
|
|
2368
|
+
5. `vacantDepartmentIds` lists the departments passed without any eligible manager;
|
|
2369
|
+
the chain continues with their parent. A department head's own department is not
|
|
2370
|
+
vacant.
|
|
2371
|
+
6. `truncated` is `true` when a parent department is inactive, so the chain stops
|
|
2372
|
+
before the real root.
|
|
2373
|
+
|
|
2374
|
+
For example, with a company board (CEO level `1`, deputy CEO level `2`), an
|
|
2375
|
+
Engineering department under it (director level `1`), and a Testing department under
|
|
2376
|
+
Engineering (head `1`, deputy `2`, team lead `3`), the chain of a tester is: team lead,
|
|
2377
|
+
deputy, head, director, deputy CEO, CEO. The chain of the Testing deputy is: head,
|
|
2378
|
+
director, deputy CEO, CEO.
|
|
2379
|
+
|
|
2380
|
+
### `org.isInDepartment(personnelId, departmentId, options?)` and `org.isManagerOf(managerId, personnelId, options?)`
|
|
2381
|
+
|
|
2382
|
+
`isInDepartment` tells whether the personnel belongs to the department, or to one of
|
|
2383
|
+
its sub-departments with `includeSubDepartments`. `isManagerOf` tells whether
|
|
2384
|
+
`managerId` appears in a manager chain of `personnelId`; `departmentId` considers
|
|
2385
|
+
only the chain that starts there and `directOnly` only its nearest tier. Both return
|
|
2386
|
+
`false` for unknown IDs.
|
|
2387
|
+
|
|
2388
|
+
### Rules
|
|
2389
|
+
|
|
2390
|
+
- `org` is available in scripts, routes, record triggers of both timings, background
|
|
2391
|
+
jobs and Development Sessions.
|
|
2392
|
+
- It follows the default identity of the execution: an execution with a user or a
|
|
2393
|
+
system identity may read it. An execution without a user (a background job, an
|
|
2394
|
+
inbound webhook, or a record trigger started by a system write) may read it only
|
|
2395
|
+
when the project's approved identity policy sets `allowInternalSystem: true`;
|
|
2396
|
+
otherwise every call throws `PermissionDeniedError` with `details.reason`
|
|
2397
|
+
`"IDENTITY_NOT_GRANTED"`.
|
|
2398
|
+
- All calls of one execution read the same version of the structure.
|
|
2399
|
+
- IDs are validated by the SDK and again by Cogover; an invalid ID or option throws
|
|
2400
|
+
`ValidationError`. `get` methods return `null` for an unknown ID; `members`,
|
|
2401
|
+
`managers`, `managerChain`, `ancestors` and `tree({ rootId })` throw
|
|
2402
|
+
`NotFoundError` with `resource` `"department"` or `"position"`.
|
|
2403
|
+
- When the structure cannot be read, the call throws `CogoverApiError` with code
|
|
2404
|
+
`ORGANIZATION_UNAVAILABLE`.
|
|
2405
|
+
- Call `getMany` or `members` instead of calling `get` in a loop: each call is one
|
|
2406
|
+
capability call.
|
|
2407
|
+
|
|
2066
2408
|
## Schema API
|
|
2067
2409
|
|
|
2068
2410
|
`SchemaApi<Schema>.object(slug)` reads Object metadata and returns:
|
|
@@ -2218,6 +2560,7 @@ For SDK errors escaping `defineScript`, the HTTP endpoint returns an error with
|
|
|
2218
2560
|
| `LOCK_LOST` | 409 |
|
|
2219
2561
|
| `STATE_SERVICE_UNAVAILABLE` | 503 |
|
|
2220
2562
|
| `LOCK_SERVICE_UNAVAILABLE` | 503 |
|
|
2563
|
+
| `ORGANIZATION_UNAVAILABLE` | 503 |
|
|
2221
2564
|
| `FETCH_DISABLED` | 503 |
|
|
2222
2565
|
| `FETCH_BLOCKED` | 400 |
|
|
2223
2566
|
| `FETCH_REQUEST_TOO_LARGE` | 413 |
|
package/docs/en/usage-guide.md
CHANGED
|
@@ -88,10 +88,90 @@ export default defineScript(({ invocation }) => {
|
|
|
88
88
|
});
|
|
89
89
|
```
|
|
90
90
|
|
|
91
|
-
Use
|
|
92
|
-
|
|
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
|
|
|
96
|
+
### Allow an action by workspace role
|
|
97
|
+
|
|
98
|
+
`invocation.user.membership` also tells whether the caller is a Super Admin of the
|
|
99
|
+
current workspace and which roles the caller holds there. For example, allow an
|
|
100
|
+
approval only for Super Admins or users holding the approver role:
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
const APPROVER_ROLE_ID = "RO6P2N1K9X4A";
|
|
104
|
+
|
|
105
|
+
export default defineScript(({ invocation }) => {
|
|
106
|
+
const user = invocation.user;
|
|
107
|
+
const canApprove = user !== null && (user.membership.isSuperAdmin
|
|
108
|
+
|| user.membership.roles.some((role) => role.id === APPROVER_ROLE_ID));
|
|
109
|
+
if (!canApprove) {
|
|
110
|
+
return {approved: false, reason: "Only approvers can approve this order"};
|
|
111
|
+
}
|
|
112
|
+
return {approved: true};
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
- The values describe the caller's roles in the current workspace. Each role has
|
|
117
|
+
only an `id` and a `name`; role permissions are not exposed.
|
|
118
|
+
- Compare roles by `id`, not by name: a role can be renamed, and role IDs differ
|
|
119
|
+
between workspaces.
|
|
120
|
+
- Cogover still enforces record and field access under the user's identity. Use
|
|
121
|
+
these fields for business rules, not as a replacement for security rules.
|
|
122
|
+
- HTTP invocations reflect the roles at the time of the request. Record triggers
|
|
123
|
+
and background jobs may see a role change up to about one minute late.
|
|
124
|
+
- In local development with the Cogover Dev CLI, the values are captured when the
|
|
125
|
+
development session starts. Restart `cogover-dev` to pick up role changes.
|
|
126
|
+
- `system` and `inbound` invocations have `user: null`, so there is no membership.
|
|
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
|
+
|
|
95
175
|
## Filter and sort records
|
|
96
176
|
|
|
97
177
|
```typescript
|
|
@@ -400,7 +480,7 @@ router.post("/recalculate", async ({ jobs, response }) => {
|
|
|
400
480
|
|
|
401
481
|
- A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
|
|
402
482
|
to `enqueue` (or `null`), and the same `data`, `schema`, `log`, `state`, `locks`,
|
|
403
|
-
`jobs`, `secrets`, and `
|
|
483
|
+
`jobs`, `secrets`, `crypto`, and `org` APIs as a script. Its return value is ignored.
|
|
404
484
|
- A run enqueued from a route or trigger acts as the user of that call. A scheduled
|
|
405
485
|
run has no user: `data.object()` works only when the identity policy allows the
|
|
406
486
|
system identity, so approve `allowInternalSystem` for projects with schedules.
|