@ram_28/kf-ai-sdk 2.0.10 → 2.0.11

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.
@@ -1,2 +1,3 @@
1
1
  export type { ActivityInstanceFieldsType, ActivityOperations, ActivityProgressType, WorkflowStartResponseType, } from './workflow/types';
2
+ export type { UseActivityTableOptionsType, UseActivityTableReturnType, ActivityTableStatusType, ActivityRowType, } from './workflow/components/useActivityTable/types';
2
3
  //# sourceMappingURL=workflow.types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflow.types.d.ts","sourceRoot":"","sources":["../sdk/workflow.types.ts"],"names":[],"mappings":"AAKA,YAAY,EACV,0BAA0B,EAC1B,kBAAkB,EAClB,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"workflow.types.d.ts","sourceRoot":"","sources":["../sdk/workflow.types.ts"],"names":[],"mappings":"AAKA,YAAY,EACV,0BAA0B,EAC1B,kBAAkB,EAClB,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,kBAAkB,CAAC;AAE1B,YAAY,EACV,2BAA2B,EAC3B,0BAA0B,EAC1B,uBAAuB,EACvB,eAAe,GAChB,MAAM,8CAA8C,CAAC"}
package/docs/workflow.md CHANGED
@@ -11,6 +11,8 @@ import {
11
11
  Activity,
12
12
  ActivityInstance,
13
13
  useActivityForm,
14
+ useActivityTable,
15
+ ActivityTableStatus,
14
16
  } from "@ram_28/kf-ai-sdk/workflow";
15
17
 
16
18
  // Type-only exports
@@ -20,6 +22,9 @@ import type {
20
22
  WorkflowStartResponseType,
21
23
  UseActivityFormOptions,
22
24
  UseActivityFormReturn,
25
+ UseActivityTableOptionsType,
26
+ UseActivityTableReturnType,
27
+ ActivityRowType,
23
28
  } from "@ram_28/kf-ai-sdk/workflow";
24
29
 
25
30
  // Field classes (for defining Activity fields)
@@ -82,11 +87,72 @@ System fields present on every activity instance. Returned alongside activity-sp
82
87
  type ActivityInstanceFieldsType = {
83
88
  _id: StringFieldType;
84
89
  Status: SelectFieldType<"InProgress" | "Completed">;
85
- AssignedTo: ReferenceFieldType<{ _id: StringFieldType; username: StringFieldType }>;
90
+ AssignedTo: UserFieldType;
86
91
  CompletedAt: DateTimeFieldType;
87
92
  };
88
93
  ```
89
94
 
95
+ ### ActivityTableStatus (constant)
96
+
97
+ ```typescript
98
+ const ActivityTableStatus = {
99
+ InProgress: 'inprogress',
100
+ Completed: 'completed',
101
+ } as const;
102
+
103
+ type ActivityTableStatusType =
104
+ (typeof ActivityTableStatus)[keyof typeof ActivityTableStatus];
105
+ ```
106
+
107
+ ### ActivityRowType\<A\>
108
+
109
+ Row type for activity table data. Combines activity instance system fields with entity-specific fields.
110
+
111
+ ```typescript
112
+ type ActivityRowType<A extends Activity<any, any, any>> =
113
+ ActivityInstanceFieldsType & ExtractActivityEntity<A>;
114
+ ```
115
+
116
+ Concrete example — for `ManagerApprovalActivity` with `{ ManagerApproved: boolean, ManagerReason: string }`:
117
+
118
+ ```typescript
119
+ // ActivityRowType<ManagerApprovalActivity> resolves to:
120
+ {
121
+ // System fields (from ActivityInstanceFieldsType)
122
+ _id: string;
123
+ Status: "InProgress" | "Completed";
124
+ AssignedTo: UserFieldType;
125
+ CompletedAt: string;
126
+
127
+ // Entity fields (from ManagerApprovalEntityType)
128
+ ManagerApproved: boolean;
129
+ ManagerReason: string;
130
+ }
131
+ ```
132
+
133
+ ### UseActivityTableOptionsType\<A\>
134
+
135
+ ```typescript
136
+ interface UseActivityTableOptionsType<A extends Activity<any, any, any>> {
137
+ status: ActivityTableStatusType;
138
+ onError?: (error: Error) => void;
139
+ onSuccess?: (data: ActivityRowType<A>[]) => void;
140
+ }
141
+ ```
142
+
143
+ ### UseActivityTableReturnType\<A\>
144
+
145
+ ```typescript
146
+ interface UseActivityTableReturnType<A extends Activity<any, any, any>> {
147
+ rows: ActivityRowType<A>[];
148
+ totalItems: number;
149
+ isLoading: boolean;
150
+ isFetching: boolean;
151
+ error: Error | null;
152
+ refetch: () => Promise<ListResponseType<ActivityRowType<A>>>;
153
+ }
154
+ ```
155
+
90
156
  ### UseActivityFormOptions\<A\>
91
157
 
92
158
  ```typescript
@@ -382,6 +448,40 @@ User clicks Complete
382
448
 
383
449
  ---
384
450
 
451
+ ## useActivityTable Hook
452
+
453
+ React hook for listing workflow activity instances. Fetches data from
454
+ `getInProgressList()` or `getCompletedList()` and the corresponding
455
+ metrics endpoint.
456
+
457
+ ### Signature
458
+
459
+ ```typescript
460
+ useActivityTable(activity: A, options: UseActivityTableOptionsType<A>)
461
+ : UseActivityTableReturnType<A>
462
+ ```
463
+
464
+ ### Options
465
+
466
+ | Property | Type | Default | Description |
467
+ |----------|------|---------|-------------|
468
+ | `status` | `ActivityTableStatusType` | *required* | `ActivityTableStatus.InProgress` or `ActivityTableStatus.Completed` |
469
+ | `onError` | `(error: Error) => void` | — | Error callback |
470
+ | `onSuccess` | `(data: ActivityRowType<A>[]) => void` | — | Success callback |
471
+
472
+ ### Return Value
473
+
474
+ | Property | Type | Description |
475
+ |----------|------|-------------|
476
+ | `rows` | `ActivityRowType<A>[]` | Activity instance records (system + entity fields) |
477
+ | `totalItems` | `number` | Total count (from metrics endpoint) |
478
+ | `isLoading` | `boolean` | Initial load in progress |
479
+ | `isFetching` | `boolean` | Any fetch in progress (including refetch) |
480
+ | `error` | `Error \| null` | Fetch error |
481
+ | `refetch` | `() => Promise<...>` | Refetch both list and metrics |
482
+
483
+ ---
484
+
385
485
  ## Use Case: Employee Creating Leave
386
486
 
387
487
  ### Step 1 — Start the workflow
@@ -542,18 +642,63 @@ function LeaveRequestPage() {
542
642
 
543
643
  ## Use Case: Manager Approving Leave
544
644
 
545
- ### Step 1 — List in-progress items
645
+ ### Step 1 — List in-progress items with useActivityTable
546
646
 
547
- ```typescript
548
- import { SimpleLeaveProcess } from "@/bdo/workflows/SimpleLeaveProcess";
647
+ ```tsx
648
+ import { useMemo, useState } from "react";
649
+ import { useActivityTable, ActivityTableStatus } from "@ram_28/kf-ai-sdk/workflow";
650
+ import { SimpleLeaveProcess, ManagerApprovalActivity } from "@/bdo/workflows/SimpleLeaveProcess";
549
651
 
550
- const wf = new SimpleLeaveProcess();
551
- const activity = wf.managerApprovalActivity();
652
+ function ManagerApprovalPage() {
653
+ const activity = useMemo(() => new SimpleLeaveProcess().managerApprovalActivity(), []);
654
+ const [selectedId, setSelectedId] = useState<string | null>(null);
552
655
 
553
- const result = await activity.getInProgressList();
656
+ const { rows, totalItems, isLoading, error, refetch } = useActivityTable(activity, {
657
+ status: ActivityTableStatus.InProgress,
658
+ });
554
659
 
555
- for (const item of result.Data) {
556
- console.log(item._id, item.Status, item.AssignedTo.username);
660
+ if (isLoading) return <div>Loading...</div>;
661
+ if (error) return <div>Error: {error.message}</div>;
662
+
663
+ if (selectedId) {
664
+ return (
665
+ <ApprovalForm
666
+ activityInstanceId={selectedId}
667
+ onComplete={() => {
668
+ setSelectedId(null);
669
+ refetch();
670
+ }}
671
+ />
672
+ );
673
+ }
674
+
675
+ return (
676
+ <div>
677
+ <h2>Pending Approvals ({totalItems})</h2>
678
+ <table>
679
+ <thead>
680
+ <tr>
681
+ <th>ID</th>
682
+ <th>Status</th>
683
+ <th>Assigned To</th>
684
+ <th>Action</th>
685
+ </tr>
686
+ </thead>
687
+ <tbody>
688
+ {rows.map((row) => (
689
+ <tr key={row._id}>
690
+ <td>{row._id}</td>
691
+ <td>{row.Status}</td>
692
+ <td>{row.AssignedTo._name}</td>
693
+ <td>
694
+ <button onClick={() => setSelectedId(row._id)}>Review</button>
695
+ </td>
696
+ </tr>
697
+ ))}
698
+ </tbody>
699
+ </table>
700
+ </div>
701
+ );
557
702
  }
558
703
  ```
559
704
 
@@ -703,7 +848,7 @@ const progressList = await wf.progress(BPInstanceId);
703
848
  |-------|------|-------------|
704
849
  | `_id` | `StringFieldType` | Unique activity instance identifier |
705
850
  | `Status` | `SelectFieldType<"InProgress" \| "Completed">` | Current status |
706
- | `AssignedTo` | `ReferenceFieldType<UserRefType>` | Assigned user (has `._id` and `.username`) |
851
+ | `AssignedTo` | `UserFieldType` | Assigned user (has `._id` and `._name`) |
707
852
  | `CompletedAt` | `DateTimeFieldType` | Completion timestamp (`"YYYY-MM-DDTHH:MM:SS"`) |
708
853
 
709
854
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ram_28/kf-ai-sdk",
3
- "version": "2.0.10",
3
+ "version": "2.0.11",
4
4
  "description": "Type-safe, AI-driven SDK for building modern web applications with role-based access control",
5
5
  "author": "Ramprasad",
6
6
  "license": "MIT",
@@ -0,0 +1,8 @@
1
+ export { useActivityTable } from './useActivityTable';
2
+ export { ActivityTableStatus } from './types';
3
+ export type {
4
+ UseActivityTableOptionsType,
5
+ UseActivityTableReturnType,
6
+ ActivityTableStatusType,
7
+ ActivityRowType,
8
+ } from './types';
@@ -0,0 +1,67 @@
1
+ // ============================================================
2
+ // TYPE DEFINITIONS FOR useActivityTable HOOK
3
+ // ============================================================
4
+
5
+ import type { Activity } from '../../Activity';
6
+ import type { ActivityInstanceFieldsType } from '../../types';
7
+ import type { ExtractActivityEntity } from '../useActivityForm/types';
8
+ import type { ListResponseType } from '../../../types/common';
9
+
10
+ /**
11
+ * Activity table status — determines which API to call
12
+ */
13
+ export const ActivityTableStatus = {
14
+ InProgress: 'inprogress',
15
+ Completed: 'completed',
16
+ } as const;
17
+
18
+ export type ActivityTableStatusType =
19
+ (typeof ActivityTableStatus)[keyof typeof ActivityTableStatus];
20
+
21
+ /**
22
+ * Row type for activity table data.
23
+ * Combines activity instance system fields with entity-specific fields.
24
+ *
25
+ * For a ManagerApprovalActivity with { ManagerApproved, ManagerReason }:
26
+ * ActivityRowType resolves to:
27
+ * {
28
+ * // System fields (ActivityInstanceFieldsType)
29
+ * _id: string;
30
+ * Status: "InProgress" | "Completed";
31
+ * AssignedTo: UserRefType;
32
+ * CompletedAt: string;
33
+ * // Entity fields
34
+ * ManagerApproved: boolean;
35
+ * ManagerReason: string;
36
+ * }
37
+ */
38
+ export type ActivityRowType<A extends Activity<any, any, any>> =
39
+ ActivityInstanceFieldsType & ExtractActivityEntity<A>;
40
+
41
+ export interface UseActivityTableOptionsType<
42
+ A extends Activity<any, any, any>,
43
+ > {
44
+ /** Which activity instances to fetch */
45
+ status: ActivityTableStatusType;
46
+ /** Error callback */
47
+ onError?: (error: Error) => void;
48
+ /** Success callback with row data */
49
+ onSuccess?: (data: ActivityRowType<A>[]) => void;
50
+ }
51
+
52
+ export interface UseActivityTableReturnType<
53
+ A extends Activity<any, any, any>,
54
+ > {
55
+ /** Activity instance records (system fields + entity fields) */
56
+ rows: ActivityRowType<A>[];
57
+ /** Total count from metrics endpoint */
58
+ totalItems: number;
59
+ /** Initial load in progress */
60
+ isLoading: boolean;
61
+ /** Any fetch in progress (including refetch) */
62
+ isFetching: boolean;
63
+ /** Fetch error */
64
+ error: Error | null;
65
+ /** Refetch both list and metrics */
66
+ refetch: () => Promise<ListResponseType<ActivityRowType<A>>>;
67
+ }
@@ -0,0 +1,145 @@
1
+ // ============================================================
2
+ // USE ACTIVITY TABLE HOOK
3
+ // ============================================================
4
+ // React hook for listing workflow activity instances.
5
+ // Fetches data from getInProgressList() or getCompletedList()
6
+ // and the corresponding metrics endpoint.
7
+
8
+ import { useMemo, useCallback } from 'react';
9
+ import { useQuery } from '@tanstack/react-query';
10
+
11
+ import type { Activity } from '../../Activity';
12
+ import type { ListResponseType } from '../../../types/common';
13
+ import { toError } from '../../../utils/error-handling';
14
+
15
+ import {
16
+ ActivityTableStatus,
17
+ type UseActivityTableOptionsType,
18
+ type UseActivityTableReturnType,
19
+ type ActivityRowType,
20
+ } from './types';
21
+
22
+ // ============================================================
23
+ // MAIN HOOK
24
+ // ============================================================
25
+
26
+ export function useActivityTable<A extends Activity<any, any, any>>(
27
+ activity: A,
28
+ options: UseActivityTableOptionsType<A>,
29
+ ): UseActivityTableReturnType<A> {
30
+ const { status, onError, onSuccess } = options;
31
+
32
+ const { businessProcessId, activityId } = activity.meta;
33
+
34
+ // ============================================================
35
+ // LIST QUERY
36
+ // ============================================================
37
+
38
+ const {
39
+ data,
40
+ isLoading,
41
+ isFetching,
42
+ error,
43
+ refetch: queryRefetch,
44
+ } = useQuery({
45
+ queryKey: ['activity-table', businessProcessId, activityId, status],
46
+ queryFn: async (): Promise<ListResponseType<ActivityRowType<A>>> => {
47
+ try {
48
+ const response =
49
+ status === ActivityTableStatus.InProgress
50
+ ? await activity.getInProgressList()
51
+ : await activity.getCompletedList();
52
+
53
+ if (onSuccess) {
54
+ onSuccess(response.Data as ActivityRowType<A>[]);
55
+ }
56
+
57
+ return response as ListResponseType<ActivityRowType<A>>;
58
+ } catch (err) {
59
+ if (onError) {
60
+ onError(toError(err));
61
+ }
62
+ throw err;
63
+ }
64
+ },
65
+ staleTime: 0,
66
+ gcTime: 30 * 1000,
67
+ });
68
+
69
+ // ============================================================
70
+ // METRICS QUERY (count)
71
+ // ============================================================
72
+
73
+ const {
74
+ data: metricData,
75
+ isLoading: isMetricLoading,
76
+ isFetching: isMetricFetching,
77
+ error: metricError,
78
+ refetch: metricRefetch,
79
+ } = useQuery({
80
+ queryKey: [
81
+ 'activity-table-count',
82
+ businessProcessId,
83
+ activityId,
84
+ status,
85
+ ],
86
+ queryFn: async () => {
87
+ try {
88
+ return status === ActivityTableStatus.InProgress
89
+ ? await activity.inProgressMetrics()
90
+ : await activity.completedMetrics();
91
+ } catch (err) {
92
+ if (onError) {
93
+ onError(toError(err));
94
+ }
95
+ throw err;
96
+ }
97
+ },
98
+ staleTime: 0,
99
+ gcTime: 30 * 1000,
100
+ });
101
+
102
+ // ============================================================
103
+ // COMPUTED VALUES
104
+ // ============================================================
105
+
106
+ const rows = useMemo(
107
+ () => (data?.Data || []) as ActivityRowType<A>[],
108
+ [data],
109
+ );
110
+
111
+ const totalItems = useMemo(
112
+ () => metricData?.Data[0]?.count__id ?? 0,
113
+ [metricData],
114
+ );
115
+
116
+ // ============================================================
117
+ // REFETCH
118
+ // ============================================================
119
+
120
+ const refetch = useCallback(async (): Promise<
121
+ ListResponseType<ActivityRowType<A>>
122
+ > => {
123
+ const [listResult] = await Promise.all([queryRefetch(), metricRefetch()]);
124
+ return (listResult.data || { Data: [] }) as ListResponseType<
125
+ ActivityRowType<A>
126
+ >;
127
+ }, [queryRefetch, metricRefetch]);
128
+
129
+ // ============================================================
130
+ // RETURN
131
+ // ============================================================
132
+
133
+ return {
134
+ rows,
135
+ totalItems,
136
+ isLoading: isLoading || isMetricLoading,
137
+ isFetching: isFetching || isMetricFetching,
138
+ error: error
139
+ ? toError(error)
140
+ : metricError
141
+ ? toError(metricError)
142
+ : null,
143
+ refetch,
144
+ };
145
+ }
@@ -13,9 +13,8 @@ import type {
13
13
  StringFieldType,
14
14
  SelectFieldType,
15
15
  DateTimeFieldType,
16
- ReferenceFieldType,
16
+ UserFieldType,
17
17
  } from "../types/base-fields";
18
- import type { UserRefType } from "../types/base-fields";
19
18
 
20
19
  /**
21
20
  * Response from Workflow.start()
@@ -49,7 +48,7 @@ export interface ActivityProgressType {
49
48
  export type ActivityInstanceFieldsType = {
50
49
  _id: StringFieldType;
51
50
  Status: SelectFieldType<"InProgress" | "Completed">;
52
- AssignedTo: ReferenceFieldType<UserRefType>;
51
+ AssignedTo: UserFieldType;
53
52
  CompletedAt: DateTimeFieldType;
54
53
  };
55
54
 
package/sdk/workflow.ts CHANGED
@@ -23,3 +23,10 @@ export type {
23
23
  UseActivityFormOptions,
24
24
  UseActivityFormReturn,
25
25
  } from './workflow/components/useActivityForm';
26
+
27
+ export { useActivityTable, ActivityTableStatus } from './workflow/components/useActivityTable';
28
+ export type {
29
+ UseActivityTableOptionsType,
30
+ UseActivityTableReturnType,
31
+ ActivityRowType,
32
+ } from './workflow/components/useActivityTable';
@@ -9,3 +9,10 @@ export type {
9
9
  ActivityProgressType,
10
10
  WorkflowStartResponseType,
11
11
  } from './workflow/types';
12
+
13
+ export type {
14
+ UseActivityTableOptionsType,
15
+ UseActivityTableReturnType,
16
+ ActivityTableStatusType,
17
+ ActivityRowType,
18
+ } from './workflow/components/useActivityTable/types';