@uidu/client 3.11.0 → 3.13.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.
@@ -0,0 +1,90 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ const request = vi.fn();
4
+
5
+ vi.mock('graphql-request', () => ({
6
+ GraphQLClient: class {
7
+ request = request;
8
+ },
9
+ ClientError: class extends Error {},
10
+ }));
11
+
12
+ const { createClient } = await import('./client');
13
+ const goals = await import('./goals');
14
+
15
+ const client = createClient({
16
+ endpoint: 'https://acme.uidu.org/graphql',
17
+ getToken: async () => 'session',
18
+ });
19
+
20
+ const q2 = { id: 'tf_1', name: 'Q2', startDate: '2026-04-01', endDate: '2026-06-30' };
21
+
22
+ beforeEach(() => request.mockReset());
23
+
24
+ describe('reads', () => {
25
+ it('listGoals flattens the connection', async () => {
26
+ request.mockResolvedValue({
27
+ currentWorkspace: {
28
+ goals: {
29
+ pageInfo: { hasNextPage: false, endCursor: null },
30
+ edges: [{ node: { id: 'g1', name: 'Revenue' } }],
31
+ },
32
+ },
33
+ });
34
+ await expect(goals.listGoals(client)).resolves.toEqual([
35
+ { id: 'g1', name: 'Revenue' },
36
+ ]);
37
+ });
38
+
39
+ it('getGoal returns null when the goal is not there', async () => {
40
+ request.mockResolvedValue({ currentWorkspace: { goal: null } });
41
+ await expect(goals.getGoal(client, { id: 'g1' })).resolves.toBeNull();
42
+ });
43
+
44
+ it('asks only for fields a custom app may read', async () => {
45
+ request.mockResolvedValue({ currentWorkspace: { goal: null } });
46
+ await goals.getGoal(client, { id: 'g1' });
47
+ const printed = JSON.stringify(request.mock.calls[0][0]);
48
+ for (const shut of ['"owner"', '"members"', '"logs"', '"workspace"']) {
49
+ expect(printed).not.toContain(`"value":${shut}`);
50
+ }
51
+ });
52
+ });
53
+
54
+ describe('values are stored x100', () => {
55
+ it('goalValue divides by 100, checkbox is 1 or 0', () => {
56
+ expect(goals.goalValue({ metricKind: 'percentage' }, 4500)).toBe(45);
57
+ expect(goals.goalValue({ metricKind: 'currency' }, 12_050)).toBe(120.5);
58
+ expect(goals.goalValue({ metricKind: 'checkbox' }, 100)).toBe(1);
59
+ expect(goals.goalValue({ metricKind: 'number' }, null)).toBeNull();
60
+ expect(goals.toGoalRaw(120.5)).toBe(12_050);
61
+ });
62
+
63
+ it('goalProgress reads 10000 as done', () => {
64
+ expect(goals.goalProgress({ progress: 10_000 })).toBe(1);
65
+ expect(goals.goalProgress({ progress: 4500 })).toBe(0.45);
66
+ expect(goals.goalProgress({ progress: null })).toBe(0);
67
+ });
68
+ });
69
+
70
+ describe('behind schedule', () => {
71
+ const midQ2 = new Date('2026-05-16T00:00:00Z');
72
+
73
+ it('goalTimeElapsed counts the last day of the timeframe', () => {
74
+ expect(goals.goalTimeElapsed({ timeframe: q2 }, new Date('2026-07-01T00:00:00Z'))).toBe(1);
75
+ expect(goals.goalTimeElapsed({ timeframe: q2 }, midQ2)).toBeCloseTo(0.5, 1);
76
+ expect(goals.goalTimeElapsed({ timeframe: null })).toBeNull();
77
+ });
78
+
79
+ it('isGoalBehind compares progress with time elapsed', () => {
80
+ expect(goals.isGoalBehind({ timeframe: q2, progress: 2000 }, { now: midQ2 })).toBe(true);
81
+ expect(goals.isGoalBehind({ timeframe: q2, progress: 6000 }, { now: midQ2 })).toBe(false);
82
+ expect(
83
+ goals.isGoalBehind({ timeframe: q2, progress: 4500 }, { now: midQ2, tolerance: 0.1 }),
84
+ ).toBe(false);
85
+ expect(
86
+ goals.isGoalBehind({ timeframe: q2, progress: 0, status: 'accomplished' }, { now: midQ2 }),
87
+ ).toBe(false);
88
+ expect(goals.isGoalBehind({ timeframe: null, progress: 0 })).toBe(false);
89
+ });
90
+ });
package/src/goals.ts ADDED
@@ -0,0 +1,144 @@
1
+ import type { UiduClient } from './client';
2
+ import {
3
+ GetGoalDocument,
4
+ type GetGoalQuery,
5
+ type GetGoalQueryVariables,
6
+ ListGoalsDocument,
7
+ type ListGoalsQueryVariables,
8
+ ListTimeframesDocument,
9
+ type ListTimeframesQuery,
10
+ type ListTimeframesQueryVariables,
11
+ UpdateGoalDocument,
12
+ type UpdateGoalMutationVariables,
13
+ } from './generated';
14
+ import { nodes } from './utils/relay';
15
+
16
+ // Goals (OKRs) are native to every uidu workspace: an objective is a Goal, its
17
+ // key results are its subgoals, and the period it runs over is a Timeframe.
18
+ //
19
+ // Reads work with any client that may see the workspace, including a custom
20
+ // app's session token — which sees the workspace-level goals and those of the
21
+ // Space the app sits in, and only the fields in `GoalFields`. `updateGoal`
22
+ // needs an account (Bearer / apiKey): a custom app cannot write goals.
23
+
24
+ export type Goal = NonNullable<
25
+ NonNullable<GetGoalQuery['currentWorkspace']>['goal']
26
+ >;
27
+ export type Timeframe = NonNullable<
28
+ NonNullable<
29
+ NonNullable<
30
+ NonNullable<ListTimeframesQuery['currentWorkspace']>['timeframes']
31
+ >['edges']
32
+ >[number]
33
+ >['node'];
34
+
35
+ /** Every goal of the workspace (objectives and key results alike), newest first. Without `first`, all of them. */
36
+ export async function listGoals(
37
+ client: UiduClient,
38
+ variables: ListGoalsQueryVariables = {},
39
+ ) {
40
+ const result = await client.query(ListGoalsDocument, variables);
41
+ return nodes(result.currentWorkspace?.goals);
42
+ }
43
+
44
+ /** One goal with its key results (`subgoals`). */
45
+ export async function getGoal(
46
+ client: UiduClient,
47
+ variables: GetGoalQueryVariables,
48
+ ): Promise<Goal | null> {
49
+ const result = await client.query(GetGoalDocument, variables);
50
+ return result.currentWorkspace?.goal ?? null;
51
+ }
52
+
53
+ export async function listTimeframes(
54
+ client: UiduClient,
55
+ variables: ListTimeframesQueryVariables = {},
56
+ ) {
57
+ const result = await client.query(ListTimeframesDocument, variables);
58
+ return nodes(result.currentWorkspace?.timeframes);
59
+ }
60
+
61
+ /**
62
+ * Authoring (Bearer / apiKey). Returns the payload, incl. `errors`.
63
+ * `initialValue` / `currentValue` / `targetValue` are stored x100: pass
64
+ * `toGoalRaw(value)`, never the number a person typed.
65
+ */
66
+ export async function updateGoal(
67
+ client: UiduClient,
68
+ variables: UpdateGoalMutationVariables,
69
+ ) {
70
+ const result = await client.mutate(UpdateGoalDocument, variables);
71
+ return result.updateGoal ?? null;
72
+ }
73
+
74
+ type GoalMetric = { metricKind?: string | null };
75
+
76
+ /**
77
+ * A stored goal value (`initialValue`, `currentValue`, `targetValue`) in the
78
+ * unit a person typed: uidu keeps every one of them x100. For `percentage`
79
+ * that is percent points (45 = 45%), for `currency` whole units of
80
+ * `goal.currency`, for `checkbox` 1 or 0. `null` stays `null`.
81
+ */
82
+ export function goalValue(
83
+ goal: GoalMetric,
84
+ raw: number | null | undefined,
85
+ ): number | null {
86
+ if (raw == null) return null;
87
+ if (goal.metricKind === 'checkbox') return raw ? 1 : 0;
88
+ return raw / 100;
89
+ }
90
+
91
+ /** The inverse of `goalValue`, for `updateGoal`. */
92
+ export function toGoalRaw(value: number): number {
93
+ return Math.round(value * 100);
94
+ }
95
+
96
+ /**
97
+ * How far the goal is, 0 to 1 (above 1 when it overshoots). `goal.progress`
98
+ * itself is percent x100: 10000 is done.
99
+ */
100
+ export function goalProgress(goal: { progress?: number | null }): number {
101
+ return (goal.progress ?? 0) / 10_000;
102
+ }
103
+
104
+ /**
105
+ * How much of the goal's timeframe has passed, 0 to 1, or `null` when it has
106
+ * none. A goal whose `goalProgress` is below this is behind schedule.
107
+ */
108
+ export function goalTimeElapsed(
109
+ goal: {
110
+ timeframe?: {
111
+ startDate?: string | null;
112
+ endDate?: string | null;
113
+ } | null;
114
+ },
115
+ now: Date = new Date(),
116
+ ): number | null {
117
+ const start = goal.timeframe?.startDate;
118
+ const end = goal.timeframe?.endDate;
119
+ if (!start || !end) return null;
120
+ const from = Date.parse(start);
121
+ // endDate is the last day of the period: count it whole.
122
+ const to = Date.parse(end) + 24 * 60 * 60 * 1000;
123
+ if (!(to > from)) return null;
124
+ return Math.min(1, Math.max(0, (now.getTime() - from) / (to - from)));
125
+ }
126
+
127
+ /**
128
+ * Behind schedule: less done than time elapsed, by more than `tolerance`
129
+ * (0.1 = ten points). `false` for a goal with no timeframe or one already
130
+ * accomplished. The goal's own `status` (`off_track`, `needs_attention`) is
131
+ * its owner's judgement — show it next to this, don't replace one with the other.
132
+ */
133
+ export function isGoalBehind(
134
+ goal: Parameters<typeof goalTimeElapsed>[0] & {
135
+ progress?: number | null;
136
+ status?: string | null;
137
+ },
138
+ { now = new Date(), tolerance = 0 }: { now?: Date; tolerance?: number } = {},
139
+ ): boolean {
140
+ if (goal.status === 'accomplished') return false;
141
+ const elapsed = goalTimeElapsed(goal, now);
142
+ if (elapsed == null) return false;
143
+ return goalProgress(goal) + tolerance < elapsed;
144
+ }
package/src/index.ts CHANGED
@@ -25,11 +25,13 @@ export {
25
25
  ListEnrollmentsDocument,
26
26
  ListEventsDocument,
27
27
  ListFormsDocument,
28
+ ListGoalsDocument,
28
29
  ListKbArticlesDocument,
29
30
  ListKbCollectionsDocument,
30
31
  ListLecturesDocument,
31
32
  ListPagesDocument,
32
33
  ListStoriesDocument,
34
+ ListTimeframesDocument,
33
35
  } from './generated';
34
36
 
35
37
  export {
@@ -51,6 +53,7 @@ export {
51
53
  getPageBySlug,
52
54
  listSitePages,
53
55
  getSingletonBlock,
56
+ createSite,
54
57
  } from './sites';
55
58
  export type {
56
59
  Site,
@@ -109,6 +112,7 @@ export {
109
112
  createCompensation,
110
113
  updateCompensation,
111
114
  deleteCompensation,
115
+ createTimeClock,
112
116
  } from './mutations';
113
117
 
114
118
  export {
@@ -134,7 +138,12 @@ export type { Call } from './calls';
134
138
  export { getJob, listJobs } from './jobs';
135
139
  export type { Job } from './jobs';
136
140
 
137
- export { listApplications, createApplication } from './applications';
141
+ export {
142
+ listApplications,
143
+ createApplication,
144
+ updateApplication,
145
+ completeApplication,
146
+ } from './applications';
138
147
  export type { Application } from './applications';
139
148
 
140
149
  export {
@@ -198,6 +207,18 @@ export type { Campaign } from './campaigns';
198
207
 
199
208
  export { getContact, listContacts, getDeal, listDeals } from './contacts';
200
209
  export type { Contact, Deal } from './contacts';
210
+ export {
211
+ listGoals,
212
+ getGoal,
213
+ listTimeframes,
214
+ updateGoal,
215
+ goalValue,
216
+ toGoalRaw,
217
+ goalProgress,
218
+ goalTimeElapsed,
219
+ isGoalBehind,
220
+ } from './goals';
221
+ export type { Goal, Timeframe } from './goals';
201
222
 
202
223
  export {
203
224
  getKbArticle,
package/src/mutations.ts CHANGED
@@ -25,6 +25,8 @@ import {
25
25
  type CreateKbArticleMutationVariables,
26
26
  CreateKbCollectionDocument,
27
27
  type CreateKbCollectionMutationVariables,
28
+ CreateTimeClockDocument,
29
+ type CreateTimeClockMutationVariables,
28
30
  DeleteChannelDocument,
29
31
  type DeleteChannelMutationVariables,
30
32
  DeleteContactDocument,
@@ -156,6 +158,11 @@ export async function terminateEmployment(
156
158
  });
157
159
  }
158
160
 
161
+ // --- Time clocks (punches) ---
162
+ export async function createTimeClock(c: UiduClient, v: CreateTimeClockMutationVariables) {
163
+ return (await c.mutate(CreateTimeClockDocument, v)).createTimeClock ?? null;
164
+ }
165
+
159
166
  // --- Compensation (pay items on an employment) ---
160
167
  export async function createCompensation(c: UiduClient, v: CreateCompensationMutationVariables) {
161
168
  return (await c.mutate(CreateCompensationDocument, v)).createCompensation ?? null;
@@ -0,0 +1,17 @@
1
+ mutation UpdateApplication($input: UpdateApplicationInput!) {
2
+ updateApplication(input: $input) {
3
+ errors {
4
+ key
5
+ name
6
+ type
7
+ }
8
+ application {
9
+ id
10
+ aasmState
11
+ completedAt
12
+ formResponse {
13
+ id
14
+ }
15
+ }
16
+ }
17
+ }
@@ -0,0 +1,14 @@
1
+ query GetGoal($id: ID!) {
2
+ currentWorkspace {
3
+ goal(id: $id) {
4
+ ...GoalFields
5
+ subgoals {
6
+ edges {
7
+ node {
8
+ ...GoalFields
9
+ }
10
+ }
11
+ }
12
+ }
13
+ }
14
+ }
@@ -0,0 +1,28 @@
1
+ # Only fields a custom app's session token may read (uidu's
2
+ # CustomApps::Scope::NATIVE_READS): asking for one outside that list — owner,
3
+ # members, logs — fails the whole query inside uidu.
4
+ fragment GoalFields on Goal {
5
+ id
6
+ name
7
+ description
8
+ kind
9
+ metricKind
10
+ status
11
+ currency
12
+ initialValue
13
+ currentValue
14
+ targetValue
15
+ progress
16
+ weight
17
+ updateFrequency
18
+ parentId
19
+ subgoalsCount
20
+ createdAt
21
+ updatedAt
22
+ timeframe {
23
+ id
24
+ name
25
+ startDate
26
+ endDate
27
+ }
28
+ }
@@ -0,0 +1,12 @@
1
+ mutation UpdateGoal($input: UpdateGoalInput!) {
2
+ updateGoal(input: $input) {
3
+ goal {
4
+ ...GoalFields
5
+ }
6
+ errors {
7
+ key
8
+ name
9
+ type
10
+ }
11
+ }
12
+ }
@@ -0,0 +1,15 @@
1
+ query ListGoals($first: Int, $after: String) {
2
+ currentWorkspace {
3
+ goals(first: $first, after: $after) {
4
+ pageInfo {
5
+ hasNextPage
6
+ endCursor
7
+ }
8
+ edges {
9
+ node {
10
+ ...GoalFields
11
+ }
12
+ }
13
+ }
14
+ }
15
+ }
@@ -0,0 +1,20 @@
1
+ query ListTimeframes($first: Int, $after: String) {
2
+ currentWorkspace {
3
+ timeframes(first: $first, after: $after) {
4
+ pageInfo {
5
+ hasNextPage
6
+ endCursor
7
+ }
8
+ edges {
9
+ node {
10
+ id
11
+ name
12
+ startDate
13
+ endDate
14
+ year
15
+ active
16
+ }
17
+ }
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,17 @@
1
+ mutation CreateTimeClock($input: CreateTimeClockInput!) {
2
+ createTimeClock(input: $input) {
3
+ timeClock {
4
+ node {
5
+ id
6
+ beginsAt
7
+ finishesAt
8
+ kind
9
+ }
10
+ }
11
+ errors {
12
+ key
13
+ name
14
+ type
15
+ }
16
+ }
17
+ }
@@ -0,0 +1,15 @@
1
+ mutation CreateSite($input: CreateSiteInput!) {
2
+ createSite(input: $input) {
3
+ site {
4
+ node {
5
+ id
6
+ name
7
+ }
8
+ }
9
+ errors {
10
+ key
11
+ name
12
+ type
13
+ }
14
+ }
15
+ }
package/src/sites.test.ts CHANGED
@@ -313,3 +313,29 @@ describe('getSingletonBlock', () => {
313
313
  ).resolves.toBeNull();
314
314
  });
315
315
  });
316
+
317
+ describe('createSite', () => {
318
+ it('provisions a Site and returns the mutation payload', async () => {
319
+ request.mockResolvedValue({
320
+ createSite: { site: { node: { id: 'site_2', name: 'Acme' } }, errors: [] },
321
+ });
322
+ const result = await sites.createSite(client, {
323
+ input: { attributes: { name: 'Acme', tenantId: 'tnt_1' } },
324
+ });
325
+ expect(operation(request.mock.calls[0])).toBe('CreateSite');
326
+ expect(request.mock.calls[0][1]).toEqual({
327
+ input: { attributes: { name: 'Acme', tenantId: 'tnt_1' } },
328
+ });
329
+ expect(result).toEqual({ site: { node: { id: 'site_2', name: 'Acme' } }, errors: [] });
330
+ });
331
+
332
+ it('returns the payload as-is, including errors, without throwing', async () => {
333
+ request.mockResolvedValue({
334
+ createSite: { site: null, errors: [{ key: 'name', name: "can't be blank", type: 'blank' }] },
335
+ });
336
+ const result = await sites.createSite(client, {
337
+ input: { attributes: { tenantId: 'tnt_1' } },
338
+ });
339
+ expect(result?.errors).toEqual([{ key: 'name', name: "can't be blank", type: 'blank' }]);
340
+ });
341
+ });
package/src/sites.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { UiduClient } from './client';
2
2
  import {
3
+ CreateSiteDocument,
4
+ type CreateSiteMutationVariables,
3
5
  GetSiteByDomainDocument,
4
6
  GetSiteDocument,
5
7
  GetSitePageBySlugDocument,
@@ -171,3 +173,18 @@ export async function getSingletonBlock(
171
173
  if (node?.__typename !== 'Site' || !node.singletonBlock) return null;
172
174
  return toPage(node.singletonBlock);
173
175
  }
176
+
177
+ // --- writes -----------------------------------------------------------------
178
+
179
+ /**
180
+ * Provisions a new Site in the workspace/account (`tenantId`). Bearer token
181
+ * (`apiKey`) — this is workspace admin territory, never a public write.
182
+ * Returns the mutation payload as-is, including `errors`.
183
+ */
184
+ export async function createSite(
185
+ client: UiduClient,
186
+ variables: CreateSiteMutationVariables,
187
+ ) {
188
+ const result = await client.mutate(CreateSiteDocument, variables);
189
+ return result.createSite ?? null;
190
+ }