@uidu/client 3.10.0 → 3.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.
@@ -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 {
@@ -44,6 +46,23 @@ export {
44
46
  } from './cms';
45
47
  export type { Page, Template } from './cms';
46
48
 
49
+ // Sites (new CMS)
50
+ export {
51
+ getSiteByDomain,
52
+ getSite,
53
+ getPageBySlug,
54
+ listSitePages,
55
+ getSingletonBlock,
56
+ } from './sites';
57
+ export type {
58
+ Site,
59
+ SiteModel,
60
+ SiteFields,
61
+ SiteBlock,
62
+ SitePage,
63
+ SitePageSummary,
64
+ } from './sites';
65
+
47
66
  export { createWorkspace, generateWorkspaceApiCredentials } from './system';
48
67
 
49
68
  export { createSpace } from './spaces';
@@ -181,6 +200,18 @@ export type { Campaign } from './campaigns';
181
200
 
182
201
  export { getContact, listContacts, getDeal, listDeals } from './contacts';
183
202
  export type { Contact, Deal } from './contacts';
203
+ export {
204
+ listGoals,
205
+ getGoal,
206
+ listTimeframes,
207
+ updateGoal,
208
+ goalValue,
209
+ toGoalRaw,
210
+ goalProgress,
211
+ goalTimeElapsed,
212
+ isGoalBehind,
213
+ } from './goals';
214
+ export type { Goal, Timeframe } from './goals';
184
215
 
185
216
  export {
186
217
  getKbArticle,
@@ -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,51 @@
1
+ # The new CMS substrate: a Site owns page-kind Models (page types), whose
2
+ # ModelItems are pages; each page's `blocks` are block-kind ModelItems placed
3
+ # in order. Distinct from the legacy `currentWorkspace.project(id:)` path read
4
+ # by `cms.ts`, which stays as it is.
5
+
6
+ fragment SiteFields on Site {
7
+ id
8
+ name
9
+ shortname
10
+ domain
11
+ preferences
12
+ }
13
+
14
+ fragment SiteModelFields on Model {
15
+ id
16
+ name
17
+ kind
18
+ }
19
+
20
+ fragment SitePageMeta on ModelItem {
21
+ id
22
+ name
23
+ slug
24
+ publishedAt
25
+ publishableStatus
26
+ model {
27
+ ...SiteModelFields
28
+ }
29
+ }
30
+
31
+ fragment SiteBlockItem on ModelItem {
32
+ id
33
+ name
34
+ fieldValuesByShortname
35
+ model {
36
+ ...SiteModelFields
37
+ }
38
+ }
39
+
40
+ fragment SitePageContent on ModelItem {
41
+ ...SitePageMeta
42
+ fieldValuesByShortname
43
+ blocks {
44
+ id
45
+ position
46
+ fieldValueId
47
+ modelItem {
48
+ ...SiteBlockItem
49
+ }
50
+ }
51
+ }
@@ -0,0 +1,53 @@
1
+ # `siteByDomain` and `node(id:)` are both public: they resolve with a
2
+ # `publicToken` or no credentials at all.
3
+
4
+ query GetSiteByDomain($domain: String!) {
5
+ siteByDomain(domain: $domain) {
6
+ ...SiteFields
7
+ }
8
+ }
9
+
10
+ query GetSite($id: ID!) {
11
+ node(id: $id) {
12
+ __typename
13
+ ... on Site {
14
+ ...SiteFields
15
+ }
16
+ }
17
+ }
18
+
19
+ query GetSitePageBySlug($siteId: ID!, $slug: String!, $includeDrafts: Boolean) {
20
+ node(id: $siteId) {
21
+ __typename
22
+ ... on Site {
23
+ id
24
+ pageBySlug(slug: $slug, includeDrafts: $includeDrafts) {
25
+ ...SitePageContent
26
+ }
27
+ }
28
+ }
29
+ }
30
+
31
+ query ListSitePages($siteId: ID!) {
32
+ node(id: $siteId) {
33
+ __typename
34
+ ... on Site {
35
+ id
36
+ pages {
37
+ ...SitePageMeta
38
+ }
39
+ }
40
+ }
41
+ }
42
+
43
+ query GetSiteSingletonBlock($siteId: ID!, $shortname: String!) {
44
+ node(id: $siteId) {
45
+ __typename
46
+ ... on Site {
47
+ id
48
+ singletonBlock(shortname: $shortname) {
49
+ ...SitePageContent
50
+ }
51
+ }
52
+ }
53
+ }