@ram_28/kf-ai-sdk 1.0.22 → 1.0.23

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/docs/api.md ADDED
@@ -0,0 +1,648 @@
1
+ # API
2
+
3
+ Direct API methods for CRUD operations, drafts, metrics, and metadata.
4
+
5
+ ## Setup
6
+
7
+ ```typescript
8
+ import { Product, ProductType } from "../sources";
9
+ import { Roles } from "../sources/roles";
10
+
11
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
12
+
13
+ const product = new Product(Roles.Buyer);
14
+ ```
15
+
16
+ ---
17
+
18
+ ## Type Definitions
19
+
20
+ ### ListOptionsType
21
+
22
+ ```typescript
23
+ // Options for listing records with pagination, filtering, and sorting
24
+ interface ListOptionsType {
25
+ // Specific fields to return (omit for all fields)
26
+ Field?: string[];
27
+
28
+ // Filter criteria (see useFilter docs)
29
+ Filter?: FilterType;
30
+
31
+ // Sort configuration
32
+ // Format: [{ "fieldName": "ASC" }] or [{ "fieldName": "DESC" }]
33
+ Sort?: SortType;
34
+
35
+ // Full-text search query
36
+ Search?: string;
37
+
38
+ // Page number (1-indexed, default: 1)
39
+ Page?: number;
40
+
41
+ // Records per page (default: 10)
42
+ PageSize?: number;
43
+ }
44
+ ```
45
+
46
+ ### ListResponseType
47
+
48
+ ```typescript
49
+ // Response from list operation
50
+ interface ListResponseType<T> {
51
+ // Array of records for current page
52
+ Data: T[];
53
+ }
54
+ ```
55
+
56
+ ### CreateUpdateResponseType
57
+
58
+ ```typescript
59
+ // Response from create or update operations
60
+ interface CreateUpdateResponseType {
61
+ // ID of the created or updated record
62
+ _id: string;
63
+ }
64
+ ```
65
+
66
+ ### DeleteResponseType
67
+
68
+ ```typescript
69
+ // Response from delete operation
70
+ interface DeleteResponseType {
71
+ // Always "success" on successful deletion
72
+ status: "success";
73
+ }
74
+ ```
75
+
76
+ ### DraftResponseType
77
+
78
+ ```typescript
79
+ // Response from draft operations
80
+ // Contains computed field values returned by server
81
+ interface DraftResponseType {
82
+ // Keys are field names, values are computed results
83
+ [fieldName: string]: any;
84
+ }
85
+ ```
86
+
87
+ ### MetricFieldType
88
+
89
+ ```typescript
90
+ // Definition for a single metric aggregation
91
+ interface MetricFieldType {
92
+ // Field to aggregate
93
+ Field: string;
94
+
95
+ // Aggregation function
96
+ // Sum | Avg | Count | Max | Min | DistinctCount | BlankCount | NotBlankCount | Concat | DistinctConcat
97
+ Type: MetricTypeType;
98
+ }
99
+ ```
100
+
101
+ ### MetricOptionsType
102
+
103
+ ```typescript
104
+ // Options for metric aggregation queries
105
+ interface MetricOptionsType {
106
+ // Fields to group by (empty array for totals)
107
+ GroupBy: string[];
108
+
109
+ // Metric definitions
110
+ Metric: MetricFieldType[];
111
+
112
+ // Optional filter criteria
113
+ Filter?: FilterType;
114
+ }
115
+ ```
116
+
117
+ ### MetricResponseType
118
+
119
+ ```typescript
120
+ // Response from metric aggregation
121
+ interface MetricResponseType {
122
+ // Aggregated data rows
123
+ // Keys follow pattern: {type}_{Field} (e.g., "count__id", "sum_Stock", "avg_Price")
124
+ Data: Record<string, any>[];
125
+ }
126
+ ```
127
+
128
+ ### PivotOptionsType
129
+
130
+ ```typescript
131
+ // Options for pivot table queries
132
+ interface PivotOptionsType {
133
+ // Row dimension fields
134
+ Row: string[];
135
+
136
+ // Column dimension fields
137
+ Column: string[];
138
+
139
+ // Metric definitions
140
+ Metric: MetricFieldType[];
141
+
142
+ // Optional filter criteria
143
+ Filter?: FilterType;
144
+ }
145
+ ```
146
+
147
+ ### PivotHeaderItemType
148
+
149
+ ```typescript
150
+ // Header item in pivot response
151
+ interface PivotHeaderItemType {
152
+ // Header label
153
+ Label: string;
154
+
155
+ // Nested child headers (for hierarchical dimensions)
156
+ Children?: PivotHeaderItemType[];
157
+ }
158
+ ```
159
+
160
+ ### PivotResponseType
161
+
162
+ ```typescript
163
+ // Response from pivot table query
164
+ interface PivotResponseType {
165
+ Data: {
166
+ // Row headers (hierarchical)
167
+ RowHeader: PivotHeaderItemType[];
168
+
169
+ // Column headers (hierarchical)
170
+ ColumnHeader: PivotHeaderItemType[];
171
+
172
+ // Value matrix [row][column]
173
+ Value: (number | string | null)[][];
174
+ };
175
+ }
176
+ ```
177
+
178
+ ### FieldsResponseType
179
+
180
+ ```typescript
181
+ // Response from fields metadata query
182
+ interface FieldsResponseType {
183
+ // Field metadata array
184
+ Data: Record<string, any>[];
185
+ }
186
+ ```
187
+
188
+ ---
189
+
190
+ ## Methods
191
+
192
+ ### list
193
+
194
+ Fetches paginated records with optional filtering, sorting, and search.
195
+
196
+ ```typescript
197
+ const response = await product.list(options?: ListOptionsType): Promise<ListResponseType<T>>
198
+ ```
199
+
200
+ **Example:** Fetch paginated products with filter
201
+
202
+ ```typescript
203
+ import { Product, ProductType } from "../sources";
204
+ import { Roles } from "../sources/roles";
205
+
206
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
207
+
208
+ const product = new Product(Roles.Buyer);
209
+
210
+ const response = await product.list({
211
+ Field: ["Title", "Price", "Category"],
212
+ Filter: {
213
+ Operator: "And",
214
+ Conditions: [
215
+ {
216
+ LHSField: "Category",
217
+ Operator: "EQ",
218
+ RHSValue: "Electronics",
219
+ RHSType: "Constant",
220
+ },
221
+ ],
222
+ },
223
+ Sort: [{ Price: "ASC" }],
224
+ Page: 1,
225
+ PageSize: 20,
226
+ });
227
+
228
+ // response.Data contains array of products
229
+ response.Data.forEach((item) => {
230
+ console.log(item.Title, item.Price);
231
+ });
232
+ ```
233
+
234
+ ---
235
+
236
+ ### get
237
+
238
+ Fetches a single record by ID.
239
+
240
+ ```typescript
241
+ const record = await product.get(id: string): Promise<T>
242
+ ```
243
+
244
+ **Example:** Fetch single product
245
+
246
+ ```typescript
247
+ import { Product, ProductType } from "../sources";
248
+ import { Roles } from "../sources/roles";
249
+
250
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
251
+
252
+ const product = new Product(Roles.Buyer);
253
+
254
+ const item = await product.get("prod_abc123");
255
+
256
+ console.log(item.Title);
257
+ console.log(item.Price);
258
+ console.log(item.Description);
259
+ ```
260
+
261
+ ---
262
+
263
+ ### create
264
+
265
+ Creates a new record.
266
+
267
+ ```typescript
268
+ const response = await product.create(data: Partial<T>): Promise<CreateUpdateResponseType>
269
+ ```
270
+
271
+ **Example:** Create new product
272
+
273
+ ```typescript
274
+ import { Product, ProductType } from "../sources";
275
+ import { Roles } from "../sources/roles";
276
+
277
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
278
+
279
+ const product = new Product(Roles.Buyer);
280
+
281
+ const response = await product.create({
282
+ Title: "Wireless Headphones",
283
+ Price: 99.99,
284
+ Category: "Electronics",
285
+ Stock: 50,
286
+ Description: "High-quality wireless headphones with noise cancellation",
287
+ });
288
+
289
+ console.log("Created product with ID:", response._id);
290
+ ```
291
+
292
+ ---
293
+
294
+ ### update
295
+
296
+ Updates an existing record.
297
+
298
+ ```typescript
299
+ const response = await product.update(id: string, data: Partial<T>): Promise<CreateUpdateResponseType>
300
+ ```
301
+
302
+ **Example:** Update product price
303
+
304
+ ```typescript
305
+ import { Product, ProductType } from "../sources";
306
+ import { Roles } from "../sources/roles";
307
+
308
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
309
+
310
+ const product = new Product(Roles.Buyer);
311
+
312
+ const response = await product.update("prod_abc123", {
313
+ Price: 79.99,
314
+ Stock: 45,
315
+ });
316
+
317
+ console.log("Updated product:", response._id);
318
+ ```
319
+
320
+ ---
321
+
322
+ ### delete
323
+
324
+ Deletes a record by ID.
325
+
326
+ ```typescript
327
+ const response = await product.delete(id: string): Promise<DeleteResponseType>
328
+ ```
329
+
330
+ **Example:** Delete product
331
+
332
+ ```typescript
333
+ import { Product, ProductType } from "../sources";
334
+ import { Roles } from "../sources/roles";
335
+
336
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
337
+
338
+ const product = new Product(Roles.Buyer);
339
+
340
+ const response = await product.delete("prod_abc123");
341
+
342
+ if (response.status === "success") {
343
+ console.log("Product deleted successfully");
344
+ }
345
+ ```
346
+
347
+ ---
348
+
349
+ ### draft
350
+
351
+ Previews computed field values for a new record without saving.
352
+
353
+ ```typescript
354
+ const response = await product.draft(data: Partial<T>): Promise<DraftResponseType>
355
+ ```
356
+
357
+ **Example:** Preview computed discount
358
+
359
+ ```typescript
360
+ import { Product, ProductType } from "../sources";
361
+ import { Roles } from "../sources/roles";
362
+
363
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
364
+
365
+ const product = new Product(Roles.Buyer);
366
+
367
+ const draftResponse = await product.draft({
368
+ Price: 100,
369
+ DiscountPercent: 15,
370
+ });
371
+
372
+ // Server computes and returns calculated fields
373
+ console.log("Computed discount amount:", draftResponse.DiscountAmount);
374
+ console.log("Computed final price:", draftResponse.FinalPrice);
375
+ ```
376
+
377
+ ---
378
+
379
+ ### draftPatch
380
+
381
+ Previews computed field values for an existing record being edited.
382
+
383
+ ```typescript
384
+ const response = await product.draftPatch(id: string, data: Partial<T>): Promise<DraftResponseType>
385
+ ```
386
+
387
+ **Example:** Update draft during editing
388
+
389
+ ```typescript
390
+ import { Product, ProductType } from "../sources";
391
+ import { Roles } from "../sources/roles";
392
+
393
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
394
+
395
+ const product = new Product(Roles.Buyer);
396
+
397
+ const draftResponse = await product.draftPatch("prod_abc123", {
398
+ Price: 120,
399
+ DiscountPercent: 20,
400
+ });
401
+
402
+ // Server computes updated calculated fields
403
+ console.log("Updated discount amount:", draftResponse.DiscountAmount);
404
+ console.log("Updated final price:", draftResponse.FinalPrice);
405
+ ```
406
+
407
+ ---
408
+
409
+ ### metric
410
+
411
+ Performs aggregation queries on records.
412
+
413
+ ```typescript
414
+ const response = await product.metric(options: MetricOptionsType): Promise<MetricResponseType>
415
+ ```
416
+
417
+ **Example 1:** Total count
418
+
419
+ ```typescript
420
+ import { Product, ProductType } from "../sources";
421
+ import { Roles } from "../sources/roles";
422
+
423
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
424
+
425
+ const product = new Product(Roles.Buyer);
426
+
427
+ const response = await product.metric({
428
+ GroupBy: [],
429
+ Metric: [{ Field: "_id", Type: "Count" }],
430
+ });
431
+
432
+ // Response: { Data: [{ "count__id": 150 }] }
433
+ console.log("Total products:", response.Data[0]["count__id"]);
434
+ ```
435
+
436
+ **Example 2:** Sum with filter (low stock count)
437
+
438
+ ```typescript
439
+ import { Product, ProductType } from "../sources";
440
+ import { Roles } from "../sources/roles";
441
+
442
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
443
+
444
+ const product = new Product(Roles.Buyer);
445
+
446
+ const response = await product.metric({
447
+ GroupBy: [],
448
+ Metric: [{ Field: "_id", Type: "Count" }],
449
+ Filter: {
450
+ Operator: "And",
451
+ Conditions: [
452
+ {
453
+ LHSField: "Stock",
454
+ Operator: "LT",
455
+ RHSValue: 10,
456
+ RHSType: "Constant",
457
+ },
458
+ ],
459
+ },
460
+ });
461
+
462
+ // Response: { Data: [{ "count__id": 12 }] }
463
+ console.log("Low stock products:", response.Data[0]["count__id"]);
464
+ ```
465
+
466
+ **Example 3:** Group by field (products by category)
467
+
468
+ ```typescript
469
+ import { Product, ProductType } from "../sources";
470
+ import { Roles } from "../sources/roles";
471
+
472
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
473
+
474
+ const product = new Product(Roles.Buyer);
475
+
476
+ const response = await product.metric({
477
+ GroupBy: ["Category"],
478
+ Metric: [{ Field: "_id", Type: "Count" }],
479
+ });
480
+
481
+ // Response: { Data: [
482
+ // { "Category": "Electronics", "count__id": 45 },
483
+ // { "Category": "Books", "count__id": 30 },
484
+ // { "Category": "Clothing", "count__id": 25 }
485
+ // ] }
486
+ response.Data.forEach((row) => {
487
+ console.log(`${row.Category}: ${row["count__id"]} products`);
488
+ });
489
+ ```
490
+
491
+ **Example 4:** Multiple metrics (stock sum and average by category)
492
+
493
+ ```typescript
494
+ import { Product, ProductType } from "../sources";
495
+ import { Roles } from "../sources/roles";
496
+
497
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
498
+
499
+ const product = new Product(Roles.Buyer);
500
+
501
+ const response = await product.metric({
502
+ GroupBy: ["Category"],
503
+ Metric: [
504
+ { Field: "Stock", Type: "Sum" },
505
+ { Field: "Price", Type: "Avg" },
506
+ ],
507
+ });
508
+
509
+ // Response: { Data: [
510
+ // { "Category": "Electronics", "sum_Stock": 500, "avg_Price": 299.99 },
511
+ // { "Category": "Books", "sum_Stock": 1200, "avg_Price": 24.99 }
512
+ // ] }
513
+ response.Data.forEach((row) => {
514
+ console.log(`${row.Category}: ${row["sum_Stock"]} total stock, $${row["avg_Price"]} avg price`);
515
+ });
516
+ ```
517
+
518
+ ---
519
+
520
+ ### pivot
521
+
522
+ Creates pivot table aggregations with row and column dimensions.
523
+
524
+ ```typescript
525
+ const response = await product.pivot(options: PivotOptionsType): Promise<PivotResponseType>
526
+ ```
527
+
528
+ **Example:** Sales pivot by region and quarter
529
+
530
+ ```typescript
531
+ import { Order, OrderType } from "../sources";
532
+ import { Roles } from "../sources/roles";
533
+
534
+ type AdminOrder = OrderType<typeof Roles.Admin>;
535
+
536
+ const order = new Order(Roles.Admin);
537
+
538
+ const response = await order.pivot({
539
+ Row: ["Region"],
540
+ Column: ["Quarter"],
541
+ Metric: [{ Field: "Amount", Type: "Sum" }],
542
+ });
543
+
544
+ // Response structure:
545
+ // {
546
+ // Data: {
547
+ // RowHeader: [
548
+ // { Label: "North" },
549
+ // { Label: "South" },
550
+ // { Label: "East" },
551
+ // { Label: "West" }
552
+ // ],
553
+ // ColumnHeader: [
554
+ // { Label: "Q1" },
555
+ // { Label: "Q2" },
556
+ // { Label: "Q3" },
557
+ // { Label: "Q4" }
558
+ // ],
559
+ // Value: [
560
+ // [10000, 12000, 15000, 18000], // North
561
+ // [8000, 9500, 11000, 13000], // South
562
+ // [7500, 8000, 9000, 10500], // East
563
+ // [6000, 7000, 8500, 9000] // West
564
+ // ]
565
+ // }
566
+ // }
567
+
568
+ const { RowHeader, ColumnHeader, Value } = response.Data;
569
+
570
+ RowHeader.forEach((row, rowIndex) => {
571
+ ColumnHeader.forEach((col, colIndex) => {
572
+ console.log(`${row.Label} - ${col.Label}: $${Value[rowIndex][colIndex]}`);
573
+ });
574
+ });
575
+ ```
576
+
577
+ ---
578
+
579
+ ### fields
580
+
581
+ Fetches field metadata for the source.
582
+
583
+ ```typescript
584
+ const response = await product.fields(): Promise<FieldsResponseType>
585
+ ```
586
+
587
+ **Example:** Get field metadata
588
+
589
+ ```typescript
590
+ import { Product, ProductType } from "../sources";
591
+ import { Roles } from "../sources/roles";
592
+
593
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
594
+
595
+ const product = new Product(Roles.Buyer);
596
+
597
+ const response = await product.fields();
598
+
599
+ // response.Data contains array of field metadata objects
600
+ response.Data.forEach((field) => {
601
+ console.log(`Field: ${field.Name}, Type: ${field.Type}`);
602
+ });
603
+ ```
604
+
605
+ ---
606
+
607
+ ### fetchField
608
+
609
+ Fetches options for reference or static fields (used for dropdowns).
610
+
611
+ ```typescript
612
+ const options = await product.fetchField(instanceId: string, fieldId: keyof T): Promise<T[] | StaticOptionType[]>
613
+ ```
614
+
615
+ **Parameters:**
616
+
617
+ - `instanceId: string` - Record ID or draft ID
618
+ - `fieldId: keyof T` - Field name
619
+
620
+ **Response:** Depends on field type:
621
+
622
+ - **Reference fields:** Returns `T[]` (full referenced records)
623
+ - **Static fields:** Returns `{ Value: string; Label: string }[]`
624
+
625
+ **Example:** Fetch supplier options for dropdown
626
+
627
+ ```typescript
628
+ import { Product, ProductType } from "../sources";
629
+ import { Roles } from "../sources/roles";
630
+
631
+ type BuyerProduct = ProductType<typeof Roles.Buyer>;
632
+
633
+ const product = new Product(Roles.Buyer);
634
+
635
+ // For a new record, use empty string or draft ID
636
+ const suppliers = await product.fetchField("", "Supplier");
637
+
638
+ // For reference fields, returns full records
639
+ suppliers.forEach((supplier) => {
640
+ console.log(`${supplier._id}: ${supplier.Name}`);
641
+ });
642
+
643
+ // For static fields, returns value/label pairs
644
+ const statuses = await product.fetchField("prod_abc123", "Status");
645
+ statuses.forEach((option) => {
646
+ console.log(`${option.Value}: ${option.Label}`);
647
+ });
648
+ ```