@uidu/client 3.17.0 → 3.19.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/declarations/src/calls.d.ts +9 -1
  3. package/dist/declarations/src/candidates.d.ts +102 -0
  4. package/dist/declarations/src/contacts.d.ts +22 -1
  5. package/dist/declarations/src/contracts.d.ts +8 -0
  6. package/dist/declarations/src/expenses.d.ts +169 -0
  7. package/dist/declarations/src/field-values.d.ts +34 -0
  8. package/dist/declarations/src/generated/index.d.ts +13283 -4414
  9. package/dist/declarations/src/index.d.ts +24 -8
  10. package/dist/declarations/src/meetings.d.ts +41 -0
  11. package/dist/declarations/src/mutations.d.ts +168 -131
  12. package/dist/declarations/src/people.d.ts +13 -1
  13. package/dist/declarations/src/reviews.d.ts +195 -0
  14. package/dist/declarations/src/skills.d.ts +34 -0
  15. package/dist/declarations/src/work-sites.d.ts +9 -0
  16. package/dist/uidu-client.cjs.dev.js +570 -31
  17. package/dist/uidu-client.cjs.prod.js +570 -31
  18. package/dist/uidu-client.esm.js +523 -32
  19. package/package.json +1 -1
  20. package/src/calls.ts +37 -0
  21. package/src/candidates.ts +105 -0
  22. package/src/contacts.ts +33 -0
  23. package/src/contracts.ts +44 -0
  24. package/src/expenses.test.ts +155 -0
  25. package/src/expenses.ts +155 -0
  26. package/src/field-values.ts +95 -0
  27. package/src/generated/index.ts +3461 -2268
  28. package/src/index.ts +83 -4
  29. package/src/meetings.ts +37 -0
  30. package/src/mutations.test.ts +40 -1
  31. package/src/mutations.ts +170 -60
  32. package/src/people.ts +33 -0
  33. package/src/queries/calls/ListCallStatuses.graphql +26 -0
  34. package/src/queries/candidates/CandidateFields.graphql +28 -0
  35. package/src/queries/candidates/CandidateMutations.graphql +35 -0
  36. package/src/queries/candidates/CandidateQueries.graphql +94 -0
  37. package/src/queries/contacts/ContactMutations.graphql +0 -13
  38. package/src/queries/contacts/GetOrganization.graphql +17 -0
  39. package/src/queries/contacts/ListOrganizations.graphql +21 -0
  40. package/src/queries/contacts/OrganizationMutations.graphql +17 -0
  41. package/src/queries/contracts/ContractQueries.graphql +67 -0
  42. package/src/queries/courses/CourseMutations.graphql +0 -13
  43. package/src/queries/discardable/DiscardableMutations.graphql +32 -0
  44. package/src/queries/expenses/ExpenseFields.graphql +29 -0
  45. package/src/queries/expenses/ExpenseMutations.graphql +81 -0
  46. package/src/queries/expenses/GetExpenseReport.graphql +14 -0
  47. package/src/queries/expenses/ListAnalyticAccounts.graphql +20 -0
  48. package/src/queries/expenses/ListExpenseReports.graphql +22 -0
  49. package/src/queries/field-values/FieldValueFields.graphql +18 -0
  50. package/src/queries/field-values/FieldValueQueries.graphql +43 -0
  51. package/src/queries/forms/FormMutations.graphql +0 -13
  52. package/src/queries/help-center/ChannelMutations.graphql +0 -13
  53. package/src/queries/kb/KbMutations.graphql +0 -26
  54. package/src/queries/meetings/MeetingQueries.graphql +48 -0
  55. package/src/queries/notes/NoteMutations.graphql +0 -13
  56. package/src/queries/people/EmploymentVariationKindMutations.graphql +51 -0
  57. package/src/queries/people/ListEmploymentVariationKinds.graphql +23 -0
  58. package/src/queries/people/PeopleMutations.graphql +0 -13
  59. package/src/queries/reviews/ReviewFields.graphql +35 -0
  60. package/src/queries/reviews/ReviewMutations.graphql +32 -0
  61. package/src/queries/reviews/ReviewQueries.graphql +86 -0
  62. package/src/queries/skills/SkillQueries.graphql +53 -0
  63. package/src/queries/spaces/SpaceMutations.graphql +0 -13
  64. package/src/queries/tasks/TaskMutations.graphql +0 -13
  65. package/src/queries/work-sites/ListWorkSites.graphql +32 -0
  66. package/src/recruiting.test.ts +196 -0
  67. package/src/reviews.ts +114 -0
  68. package/src/skills.ts +47 -0
  69. package/src/work-sites.ts +28 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uidu/client",
3
- "version": "3.17.0",
3
+ "version": "3.19.0",
4
4
  "description": "Typed GraphQL client for the uidu platform. Server-first, framework-agnostic.",
5
5
  "license": "MIT",
6
6
  "author": "uidu",
package/src/calls.ts CHANGED
@@ -3,15 +3,32 @@ import {
3
3
  GetCallDocument,
4
4
  type GetCallQuery,
5
5
  type GetCallQueryVariables,
6
+ ListCallStatusesDocument,
7
+ type ListCallStatusesQuery,
8
+ type ListCallStatusesQueryVariables,
6
9
  ListCallsDocument,
7
10
  type ListCallsQueryVariables,
8
11
  } from './generated';
12
+ import { paginate } from './utils/paginate';
9
13
  import { nodes } from './utils/relay';
10
14
 
11
15
  export type Call = NonNullable<
12
16
  NonNullable<GetCallQuery['currentWorkspace']>['call']
13
17
  >;
14
18
 
19
+ /** One stage of a call's pipeline — what `Application.status` points at. */
20
+ export type CallStatus = NonNullable<
21
+ NonNullable<
22
+ NonNullable<
23
+ NonNullable<
24
+ NonNullable<
25
+ NonNullable<ListCallStatusesQuery['currentWorkspace']>['call']
26
+ >['statuses']
27
+ >['edges']
28
+ >[number]
29
+ >['node']
30
+ >;
31
+
15
32
  /**
16
33
  * One call (a job opening or open call) with its application `form`, same
17
34
  * shape as `getForm`, or null.
@@ -35,3 +52,23 @@ export async function listCalls(
35
52
  const result = await client.query(ListCallsDocument, variables);
36
53
  return nodes(result.currentWorkspace?.calls);
37
54
  }
55
+
56
+ /**
57
+ * The pipeline of a call: the statuses its applications move through, sorted
58
+ * by `position`, walking all pages. Move an application along it with
59
+ * `updateApplication` (`attributes.statusId`). Requires a Bearer token.
60
+ */
61
+ export async function listCallStatuses(
62
+ client: UiduClient,
63
+ variables: Omit<ListCallStatusesQueryVariables, 'after'>,
64
+ ): Promise<CallStatus[]> {
65
+ const statuses = await paginate(client, ListCallStatusesDocument, {
66
+ variables: { first: 100, ...variables },
67
+ extract: (data) => data.currentWorkspace?.call?.statuses,
68
+ });
69
+ return statuses.sort(
70
+ (a, b) =>
71
+ (a.position ?? Number.MAX_SAFE_INTEGER) -
72
+ (b.position ?? Number.MAX_SAFE_INTEGER),
73
+ );
74
+ }
@@ -0,0 +1,105 @@
1
+ import type { UiduClient } from './client';
2
+ import {
3
+ CreatePoolContactDocument,
4
+ type CreatePoolContactMutationVariables,
5
+ FindCandidatesDocument,
6
+ type FindCandidatesQuery,
7
+ type FindCandidatesQueryVariables,
8
+ GetCandidateDocument,
9
+ type GetCandidateQuery,
10
+ type GetCandidateQueryVariables,
11
+ ListPoolsDocument,
12
+ type ListPoolsQuery,
13
+ type ListPoolsQueryVariables,
14
+ UpdateCandidateDocument,
15
+ type UpdateCandidateMutationVariables,
16
+ } from './generated';
17
+ import { nodes } from './utils/relay';
18
+
19
+ // Candidates are the people in a workspace's talent pool: a `Candidate` wraps
20
+ // the person's `user` and `contact` with their pool consent and retention.
21
+ // `Pool`s group contacts (a `PoolContact` is one contact in one pool).
22
+ //
23
+ // Everything here holds private personal data: reads and writes need an
24
+ // account (Bearer / apiKey), server-side.
25
+
26
+ export type CandidateSearch = NonNullable<
27
+ NonNullable<FindCandidatesQuery['currentWorkspace']>['findCandidates']
28
+ >;
29
+ export type Candidate = CandidateSearch['candidates'][number];
30
+ export type CandidateDetail = Extract<
31
+ NonNullable<GetCandidateQuery['node']>,
32
+ { __typename: 'Candidate' }
33
+ >;
34
+ export type Pool = NonNullable<
35
+ NonNullable<
36
+ NonNullable<
37
+ NonNullable<ListPoolsQuery['currentWorkspace']>['pools']['edges']
38
+ >[number]
39
+ >['node']
40
+ >;
41
+
42
+ /**
43
+ * Rank the talent pool against a description (`term`) — and, with `callId`,
44
+ * that call's applications too — and return the `candidates`, `applications`
45
+ * and per-record `evidence`, or null when the viewer may not search.
46
+ *
47
+ * This is the only way to list candidates: the workspace has no plain
48
+ * `candidates` connection. A blank `term` with a `callId` uses the call's own
49
+ * words; `near` + `withinKm` keep only those living close enough, and
50
+ * `eligibleFor` only those of an age the contract allows.
51
+ */
52
+ export async function findCandidates(
53
+ client: UiduClient,
54
+ variables: FindCandidatesQueryVariables = {},
55
+ ): Promise<CandidateSearch | null> {
56
+ const result = await client.query(FindCandidatesDocument, variables);
57
+ return result.currentWorkspace?.findCandidates ?? null;
58
+ }
59
+
60
+ /**
61
+ * One candidate by GlobalID, with their applications and the pools they are
62
+ * in, or null.
63
+ */
64
+ export async function getCandidate(
65
+ client: UiduClient,
66
+ variables: GetCandidateQueryVariables,
67
+ ): Promise<CandidateDetail | null> {
68
+ const result = await client.query(GetCandidateDocument, variables);
69
+ const node = result.node;
70
+ return node?.__typename === 'Candidate' ? (node as CandidateDetail) : null;
71
+ }
72
+
73
+ /**
74
+ * Update a candidate: pool consent (`poolConsentAt`), `source`, or
75
+ * `extendRetention: true` to push `retainUntil` out by another retention
76
+ * period. Returns the mutation payload as-is (including any `errors`).
77
+ */
78
+ export async function updateCandidate(
79
+ client: UiduClient,
80
+ variables: UpdateCandidateMutationVariables,
81
+ ) {
82
+ const result = await client.mutate(UpdateCandidateDocument, variables);
83
+ return result.updateCandidate ?? null;
84
+ }
85
+
86
+ /** The workspace's talent pools with how many contacts each holds; page with `first`/`after`. */
87
+ export async function listPools(
88
+ client: UiduClient,
89
+ variables: ListPoolsQueryVariables = {},
90
+ ): Promise<Pool[]> {
91
+ const result = await client.query(ListPoolsDocument, variables);
92
+ return nodes(result.currentWorkspace?.pools);
93
+ }
94
+
95
+ /**
96
+ * Add a contact to a pool (`attributes: { poolId, contactId }`). Returns the
97
+ * mutation payload as-is (including any `errors`).
98
+ */
99
+ export async function createPoolContact(
100
+ client: UiduClient,
101
+ variables: CreatePoolContactMutationVariables,
102
+ ) {
103
+ const result = await client.mutate(CreatePoolContactDocument, variables);
104
+ return result.createPoolContact ?? null;
105
+ }
package/src/contacts.ts CHANGED
@@ -6,9 +6,14 @@ import {
6
6
  GetDealDocument,
7
7
  type GetDealQuery,
8
8
  type GetDealQueryVariables,
9
+ GetOrganizationDocument,
10
+ type GetOrganizationQuery,
11
+ type GetOrganizationQueryVariables,
9
12
  ListContactsDocument,
10
13
  ListDealsDocument,
11
14
  type ListDealsQueryVariables,
15
+ ListOrganizationsDocument,
16
+ type ListOrganizationsQueryVariables,
12
17
  } from './generated';
13
18
  import { nodes } from './utils/relay';
14
19
 
@@ -18,6 +23,10 @@ export type Contact = NonNullable<
18
23
  export type Deal = NonNullable<
19
24
  NonNullable<GetDealQuery['currentWorkspace']>['deal']
20
25
  >;
26
+ /** A CRM organization (company) — the contactable a `Contact` wraps. */
27
+ export type Organization = NonNullable<
28
+ NonNullable<GetOrganizationQuery['currentWorkspace']>['organization']
29
+ >;
21
30
 
22
31
  /**
23
32
  * One contact with its address and custom fields (`fieldValuesByShortname`),
@@ -63,3 +72,27 @@ export async function listDeals(
63
72
  const result = await client.query(ListDealsDocument, variables);
64
73
  return nodes(result.currentWorkspace?.deals);
65
74
  }
75
+
76
+ /**
77
+ * One organization (company) with its fiscal/VAT codes and custom fields, or
78
+ * null.
79
+ */
80
+ export async function getOrganization(
81
+ client: UiduClient,
82
+ variables: GetOrganizationQueryVariables,
83
+ ): Promise<Organization | null> {
84
+ const result = await client.query(GetOrganizationDocument, variables);
85
+ return result.currentWorkspace?.organization ?? null;
86
+ }
87
+
88
+ /**
89
+ * The workspace's organizations as a flat array, optionally filtered with
90
+ * search `params`; page with `first`/`after`.
91
+ */
92
+ export async function listOrganizations(
93
+ client: UiduClient,
94
+ variables: ListOrganizationsQueryVariables = {},
95
+ ) {
96
+ const result = await client.query(ListOrganizationsDocument, variables);
97
+ return nodes(result.currentWorkspace?.organizations);
98
+ }
@@ -0,0 +1,44 @@
1
+ import type { UiduClient } from './client';
2
+ import {
3
+ GetContractDocument,
4
+ type GetContractQuery,
5
+ type GetContractQueryVariables,
6
+ ListContractsDocument,
7
+ type ListContractsQuery,
8
+ type ListContractsQueryVariables,
9
+ } from './generated';
10
+ import { nodes } from './utils/relay';
11
+
12
+ // Contracts: an agreement with a counterpart (a Contact or an Organization),
13
+ // booked on an analytic account. Like deals, a contract carries the custom
14
+ // fields the workspace added to it: read them as `fieldValuesByShortname`
15
+ // (`{ shortname: value }`) or `fieldValues`. Reads need an account (Bearer).
16
+
17
+ export type Contract = NonNullable<
18
+ NonNullable<
19
+ NonNullable<
20
+ NonNullable<ListContractsQuery['currentWorkspace']>['contracts']['edges']
21
+ >[number]
22
+ >['node']
23
+ >;
24
+ export type ContractDetail = NonNullable<
25
+ NonNullable<GetContractQuery['currentWorkspace']>['contract']
26
+ >;
27
+
28
+ /** The workspace's contracts with their custom fields, filtered with `params`; page with `first`/`after`. */
29
+ export async function listContracts(
30
+ client: UiduClient,
31
+ variables: ListContractsQueryVariables = {},
32
+ ): Promise<Contract[]> {
33
+ const result = await client.query(ListContractsDocument, variables);
34
+ return nodes(result.currentWorkspace?.contracts);
35
+ }
36
+
37
+ /** One contract with its field values and the fields that apply to it, or null. */
38
+ export async function getContract(
39
+ client: UiduClient,
40
+ variables: GetContractQueryVariables,
41
+ ): Promise<ContractDetail | null> {
42
+ const result = await client.query(GetContractDocument, variables);
43
+ return result.currentWorkspace?.contract ?? null;
44
+ }
@@ -0,0 +1,155 @@
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 expenses = await import('./expenses');
14
+
15
+ const client = createClient({
16
+ endpoint: 'https://acme.uidu.org/graphql',
17
+ apiKey: 'key',
18
+ });
19
+
20
+ const taxi = {
21
+ id: 'e1',
22
+ amount: 2350,
23
+ currency: 'EUR',
24
+ spentAt: '2026-10-30T09:00:00Z',
25
+ category: 2,
26
+ paymentMethod: 'card',
27
+ fieldValuesByShortname: { commessa: 'C-104' },
28
+ };
29
+
30
+ const report = {
31
+ id: 'r1',
32
+ name: 'Trasferta Milano',
33
+ paidAt: null,
34
+ fieldValuesByShortname: {},
35
+ user: { id: 'u1', name: 'Ada' },
36
+ expenses: { edges: [{ node: taxi }, null] },
37
+ };
38
+
39
+ beforeEach(() => request.mockReset());
40
+
41
+ describe('reads', () => {
42
+ it('listExpenseReports flattens reports and their expenses', async () => {
43
+ request.mockResolvedValue({
44
+ currentWorkspace: {
45
+ expenseReports: {
46
+ pageInfo: { hasNextPage: false, endCursor: null },
47
+ edges: [{ node: report }],
48
+ },
49
+ },
50
+ });
51
+ await expect(expenses.listExpenseReports(client)).resolves.toEqual([
52
+ { ...report, expenses: [taxi] },
53
+ ]);
54
+ });
55
+
56
+ it('getExpenseReport flattens its expenses', async () => {
57
+ request.mockResolvedValue({ currentWorkspace: { expenseReport: report } });
58
+ await expect(
59
+ expenses.getExpenseReport(client, { id: 'r1' }),
60
+ ).resolves.toEqual({ ...report, expenses: [taxi] });
61
+ });
62
+
63
+ it('getExpenseReport returns null when the report is not there', async () => {
64
+ request.mockResolvedValue({ currentWorkspace: { expenseReport: null } });
65
+ await expect(
66
+ expenses.getExpenseReport(client, { id: 'r1' }),
67
+ ).resolves.toBeNull();
68
+ });
69
+
70
+ it('asks for the person, not the derived contact', async () => {
71
+ request.mockResolvedValue({ currentWorkspace: { expenseReport: null } });
72
+ await expenses.getExpenseReport(client, { id: 'r1' });
73
+ const printed = JSON.stringify(request.mock.calls[0][0]);
74
+ expect(printed).toContain('"value":"user"');
75
+ expect(printed).not.toContain('"value":"contact"');
76
+ });
77
+
78
+ it('listAnalyticAccounts flattens the connection', async () => {
79
+ request.mockResolvedValue({
80
+ currentWorkspace: {
81
+ analyticAccounts: {
82
+ pageInfo: { hasNextPage: false, endCursor: null },
83
+ edges: [{ node: { id: 'a1', code: 'C-104', name: 'Rilievi' } }],
84
+ },
85
+ },
86
+ });
87
+ await expect(expenses.listAnalyticAccounts(client)).resolves.toEqual([
88
+ { id: 'a1', code: 'C-104', name: 'Rilievi' },
89
+ ]);
90
+ });
91
+ });
92
+
93
+ describe('writes', () => {
94
+ it('createExpenseReport sends userId and fieldValues as given', async () => {
95
+ const payload = { expenseReport: { node: { id: 'r1' } }, errors: [] };
96
+ request.mockResolvedValue({ createExpenseReport: payload });
97
+ const input = {
98
+ attributes: {
99
+ userId: 'u1',
100
+ name: 'Trasferta Milano',
101
+ fieldValues: { 'gid://uidu/Field/7': 'C-104' },
102
+ },
103
+ };
104
+ await expect(
105
+ expenses.createExpenseReport(client, { input }),
106
+ ).resolves.toEqual(payload);
107
+ expect(request.mock.calls[0][1]).toEqual({ input });
108
+ });
109
+
110
+ it('createExpense returns the payload with its errors', async () => {
111
+ const payload = {
112
+ expense: null,
113
+ errors: [{ key: 'amount', name: 'blank', type: 'blank' }],
114
+ };
115
+ request.mockResolvedValue({ createExpense: payload });
116
+ await expect(
117
+ expenses.createExpense(client, {
118
+ input: { attributes: { expenseReportId: 'r1' } },
119
+ }),
120
+ ).resolves.toEqual(payload);
121
+ });
122
+
123
+ it('updateExpenseReport and updateExpense return null without a payload', async () => {
124
+ request.mockResolvedValue({});
125
+ await expect(
126
+ expenses.updateExpenseReport(client, {
127
+ input: { id: 'r1', attributes: { paidAt: '2026-11-03T00:00:00Z' } },
128
+ }),
129
+ ).resolves.toBeNull();
130
+ await expect(
131
+ expenses.updateExpense(client, {
132
+ input: { id: 'e1', attributes: { amount: 2400 } },
133
+ }),
134
+ ).resolves.toBeNull();
135
+ });
136
+
137
+ it('allocateExpense books the expense on an analytic account', async () => {
138
+ const payload = {
139
+ analyticAccountAllocation: { node: { id: 'al1', amount: 2350 } },
140
+ errors: [],
141
+ };
142
+ request.mockResolvedValue({ createAnalyticAccountAllocation: payload });
143
+ await expect(
144
+ expenses.allocateExpense(client, {
145
+ input: {
146
+ attributes: {
147
+ allocatableId: 'e1',
148
+ analyticAccountId: 'a1',
149
+ amount: 2350,
150
+ },
151
+ },
152
+ }),
153
+ ).resolves.toEqual(payload);
154
+ });
155
+ });
@@ -0,0 +1,155 @@
1
+ import type { UiduClient } from './client';
2
+ import {
3
+ CreateAnalyticAccountAllocationDocument,
4
+ type CreateAnalyticAccountAllocationMutationVariables,
5
+ CreateExpenseDocument,
6
+ type CreateExpenseMutationVariables,
7
+ CreateExpenseReportDocument,
8
+ type CreateExpenseReportMutationVariables,
9
+ GetExpenseReportDocument,
10
+ type GetExpenseReportQuery,
11
+ type GetExpenseReportQueryVariables,
12
+ ListAnalyticAccountsDocument,
13
+ type ListAnalyticAccountsQuery,
14
+ type ListAnalyticAccountsQueryVariables,
15
+ ListExpenseReportsDocument,
16
+ type ListExpenseReportsQueryVariables,
17
+ UpdateExpenseDocument,
18
+ type UpdateExpenseMutationVariables,
19
+ UpdateExpenseReportDocument,
20
+ type UpdateExpenseReportMutationVariables,
21
+ } from './generated';
22
+ import { nodes } from './utils/relay';
23
+
24
+ // Expense reports: an ExpenseReport reimburses one person (`user`, written as
25
+ // `userId`) and holds their Expenses. `amount` is in cents of `currency`.
26
+ // Both carry the custom fields the workspace added to them: read them as
27
+ // `fieldValuesByShortname` (`{ shortname: value }`), write them as
28
+ // `attributes.fieldValues`, a map of the Field's GlobalID to the value.
29
+ //
30
+ // Reads and writes need an account (Bearer / apiKey), server-side: a custom
31
+ // app's session token does not reach expense reports.
32
+
33
+ type ExpenseReportRecord = NonNullable<
34
+ NonNullable<GetExpenseReportQuery['currentWorkspace']>['expenseReport']
35
+ >;
36
+
37
+ export type ExpenseReport = Omit<ExpenseReportRecord, 'expenses'> & {
38
+ expenses: Expense[];
39
+ };
40
+ export type Expense = NonNullable<
41
+ NonNullable<
42
+ NonNullable<NonNullable<ExpenseReportRecord['expenses']>['edges']>[number]
43
+ >['node']
44
+ >;
45
+ export type AnalyticAccount = NonNullable<
46
+ NonNullable<
47
+ NonNullable<
48
+ NonNullable<
49
+ ListAnalyticAccountsQuery['currentWorkspace']
50
+ >['analyticAccounts']
51
+ >['edges']
52
+ >[number]
53
+ >['node'];
54
+
55
+ function withExpenses(report: ExpenseReportRecord): ExpenseReport {
56
+ return { ...report, expenses: nodes(report.expenses) };
57
+ }
58
+
59
+ /**
60
+ * The workspace's expense reports, newest first, each with its `expenses` as a
61
+ * flat array; page with `first`/`after`.
62
+ */
63
+ export async function listExpenseReports(
64
+ client: UiduClient,
65
+ variables: ListExpenseReportsQueryVariables = {},
66
+ ): Promise<ExpenseReport[]> {
67
+ const result = await client.query(ListExpenseReportsDocument, variables);
68
+ return nodes(result.currentWorkspace?.expenseReports).map(withExpenses);
69
+ }
70
+
71
+ /** One expense report with its `expenses` as a flat array, or null. */
72
+ export async function getExpenseReport(
73
+ client: UiduClient,
74
+ variables: GetExpenseReportQueryVariables,
75
+ ): Promise<ExpenseReport | null> {
76
+ const result = await client.query(GetExpenseReportDocument, variables);
77
+ const report = result.currentWorkspace?.expenseReport;
78
+ return report ? withExpenses(report) : null;
79
+ }
80
+
81
+ /**
82
+ * Create an expense report for a person: `{ input: { attributes: { userId,
83
+ * name, fieldValues } } }`. Returns the payload (with `errors`) or null.
84
+ */
85
+ export async function createExpenseReport(
86
+ client: UiduClient,
87
+ variables: CreateExpenseReportMutationVariables,
88
+ ) {
89
+ const result = await client.mutate(CreateExpenseReportDocument, variables);
90
+ return result.createExpenseReport ?? null;
91
+ }
92
+
93
+ /**
94
+ * Update an expense report — rename it, set `paidAt`, change its custom
95
+ * `fieldValues`. Returns the payload (with `errors`) or null.
96
+ */
97
+ export async function updateExpenseReport(
98
+ client: UiduClient,
99
+ variables: UpdateExpenseReportMutationVariables,
100
+ ) {
101
+ const result = await client.mutate(UpdateExpenseReportDocument, variables);
102
+ return result.updateExpenseReport ?? null;
103
+ }
104
+
105
+ /**
106
+ * Add an expense to a report: `{ input: { attributes: { expenseReportId,
107
+ * amount, currency, spentAt, category, paymentMethod, fieldValues } } }`, with
108
+ * `amount` in cents. Returns the payload (with `errors`) or null.
109
+ */
110
+ export async function createExpense(
111
+ client: UiduClient,
112
+ variables: CreateExpenseMutationVariables,
113
+ ) {
114
+ const result = await client.mutate(CreateExpenseDocument, variables);
115
+ return result.createExpense ?? null;
116
+ }
117
+
118
+ /** Update an expense. Returns the payload (with `errors`) or null. */
119
+ export async function updateExpense(
120
+ client: UiduClient,
121
+ variables: UpdateExpenseMutationVariables,
122
+ ) {
123
+ const result = await client.mutate(UpdateExpenseDocument, variables);
124
+ return result.updateExpense ?? null;
125
+ }
126
+
127
+ /**
128
+ * The workspace's analytic accounts (commesse, cost centres) as a flat array —
129
+ * what `allocateExpense` books an expense on. `parentId` narrows to the
130
+ * children of one account; page with `first`/`after`.
131
+ */
132
+ export async function listAnalyticAccounts(
133
+ client: UiduClient,
134
+ variables: ListAnalyticAccountsQueryVariables = {},
135
+ ) {
136
+ const result = await client.query(ListAnalyticAccountsDocument, variables);
137
+ return nodes(result.currentWorkspace?.analyticAccounts);
138
+ }
139
+
140
+ /**
141
+ * Book an expense (or part of it) on an analytic account: `{ input: {
142
+ * attributes: { allocatableId: expense.id, analyticAccountId, amount } } }`,
143
+ * `amount` in cents, `currency` defaulting to the expense's. Call it once per
144
+ * account to split an expense. Returns the payload (with `errors`) or null.
145
+ */
146
+ export async function allocateExpense(
147
+ client: UiduClient,
148
+ variables: CreateAnalyticAccountAllocationMutationVariables,
149
+ ) {
150
+ const result = await client.mutate(
151
+ CreateAnalyticAccountAllocationDocument,
152
+ variables,
153
+ );
154
+ return result.createAnalyticAccountAllocation ?? null;
155
+ }
@@ -0,0 +1,95 @@
1
+ import type { UiduClient } from './client';
2
+ import {
3
+ GetRecordFieldValuesDocument,
4
+ type GetRecordFieldValuesQueryVariables,
5
+ ListFieldValueHistoryDocument,
6
+ type ListFieldValueHistoryQueryVariables,
7
+ type RecordFieldValueFragment,
8
+ } from './generated';
9
+ import { paginate } from './utils/paginate';
10
+
11
+ // Field values over time. A value holds from `validFrom` (a row without one
12
+ // counts from the day of its `createdAt`); a field's history on a record is
13
+ // every value it has held, oldest first. Reads need an account (Bearer).
14
+
15
+ export type RecordFieldValue = RecordFieldValueFragment;
16
+
17
+ export type RecordFieldValues = {
18
+ /** The record's GraphQL type, e.g. `Contact`, `Contract`, `Employee`. */
19
+ typename: string;
20
+ id: string;
21
+ /** Current values keyed by field shortname. */
22
+ byShortname: Record<string, unknown>;
23
+ /** Current values with their field and dates. */
24
+ fieldValues: RecordFieldValue[];
25
+ };
26
+
27
+ /**
28
+ * The current field values of any record that carries custom fields (contact,
29
+ * employee, contract, work site, application…), by GlobalID; null when the id
30
+ * resolves to nothing or to a type without fields.
31
+ */
32
+ export async function getRecordFieldValues(
33
+ client: UiduClient,
34
+ variables: GetRecordFieldValuesQueryVariables,
35
+ ): Promise<RecordFieldValues | null> {
36
+ const result = await client.query(GetRecordFieldValuesDocument, variables);
37
+ const node = result.node;
38
+ if (!node || !('fieldValues' in node)) return null;
39
+ return {
40
+ typename: node.__typename,
41
+ id: node.id,
42
+ byShortname: (node.fieldValuesByShortname ?? {}) as Record<string, unknown>,
43
+ fieldValues: node.fieldValues ?? [],
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Every value `fieldId` has held on the record `modelId`, oldest first, walking
49
+ * all pages. Pair it with {@link fieldValueAsOf} to answer "what did it say on
50
+ * a given day?".
51
+ */
52
+ export async function listFieldValueHistory(
53
+ client: UiduClient,
54
+ variables: Omit<ListFieldValueHistoryQueryVariables, 'after'>,
55
+ ): Promise<RecordFieldValue[]> {
56
+ return paginate(client, ListFieldValueHistoryDocument, {
57
+ variables: { first: 100, ...variables },
58
+ extract: (data) => data.currentWorkspace?.field?.fieldValues,
59
+ });
60
+ }
61
+
62
+ /** The day a value starts to hold: `validFrom`, else the day of `createdAt`. */
63
+ function holdsFrom(value: RecordFieldValue): string {
64
+ return String(value.validFrom ?? String(value.createdAt).slice(0, 10));
65
+ }
66
+
67
+ /**
68
+ * The value that held on `date` (an ISO8601 date, default today) among a
69
+ * field's history: the latest `validFrom` not after the date, ties going to
70
+ * the row written last. Null when nothing held yet.
71
+ *
72
+ * The same rule uidu applies server-side for a record's current value; the
73
+ * GraphQL API takes no as-of argument, so reports read the history with
74
+ * {@link listFieldValueHistory} and pick here.
75
+ */
76
+ export function fieldValueAsOf(
77
+ history: readonly RecordFieldValue[],
78
+ date: string = new Date().toISOString().slice(0, 10),
79
+ ): RecordFieldValue | null {
80
+ const day = date.slice(0, 10);
81
+ let best: RecordFieldValue | null = null;
82
+ for (const value of history) {
83
+ const from = holdsFrom(value);
84
+ if (from > day) continue;
85
+ if (
86
+ !best ||
87
+ from > holdsFrom(best) ||
88
+ (from === holdsFrom(best) &&
89
+ String(value.createdAt) >= String(best.createdAt))
90
+ ) {
91
+ best = value;
92
+ }
93
+ }
94
+ return best;
95
+ }