@ram_28/kf-ai-sdk 2.0.9 → 2.0.10
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/dist/api.cjs +1 -1
- package/dist/api.mjs +1 -1
- package/dist/auth.cjs +1 -1
- package/dist/auth.mjs +1 -1
- package/dist/bdo.cjs +1 -1
- package/dist/bdo.mjs +1 -1
- package/dist/{constants-CYJih7y4.js → constants-ConHc1oS.js} +5 -3
- package/dist/constants-QX2RX-wu.cjs +1 -0
- package/dist/filter.cjs +1 -1
- package/dist/filter.mjs +1 -1
- package/dist/form.cjs +1 -1
- package/dist/form.mjs +1 -1
- package/dist/table.cjs +1 -1
- package/dist/table.mjs +1 -1
- package/dist/types/constants.d.ts +5 -3
- package/dist/types/constants.d.ts.map +1 -1
- package/docs/api.md +1 -1
- package/docs/useFilter.md +279 -6
- package/package.json +1 -1
- package/sdk/components/hooks/useFilter/useFilter.llm.txt +73 -4
- package/sdk/types/constants.ts +5 -3
- package/dist/constants-D0J69if5.cjs +0 -1
package/dist/api.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./client-BnVxSHAm.cjs"),u=require("./metadata-BfJtHz84.cjs"),o=require("./constants-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./client-BnVxSHAm.cjs"),u=require("./metadata-BfJtHz84.cjs"),o=require("./constants-QX2RX-wu.cjs"),p={DATE:"%Y-%m-%d",TIME:"%H:%M:%S",DATE_TIME:"%Y-%m-%d %H:%M:%S"};function D(t){const[e,a,r]=t.$__d__.split("-").map(Number);return new Date(e,a-1,r)}function g(t){return new Date(t.$__dt__*1e3)}function l(t){const e=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${a}-${r}`}function S(t){const e=t.getFullYear(),a=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0"),c=String(t.getSeconds()).padStart(2,"0");return`${e}-${a}-${r} ${s}:${i}:${c}`}function y(t){const[e,a,r]=t.split("-").map(Number);return new Date(e,a-1,r)}function f(t){const[e,a]=t.split(" "),[r,s,i]=e.split("-").map(Number),[c,d,m]=a.split(":").map(Number);return new Date(r,s-1,i,c,d,m)}exports.api=n.api;exports.getApiBaseUrl=n.getApiBaseUrl;exports.getDefaultHeaders=n.getDefaultHeaders;exports.setApiBaseUrl=n.setApiBaseUrl;exports.setDefaultHeaders=n.setDefaultHeaders;exports.getBdoSchema=u.getBdoSchema;exports.listMetadata=u.listMetadata;exports.DateEncodingKey=o.DateEncodingKey;exports.DeleteStatus=o.DeleteStatus;exports.HttpMethod=o.HttpMethod;exports.MetricType=o.MetricType;exports.QueryType=o.QueryType;exports.DatetimeFormat=p;exports.decodeDate=D;exports.decodeDateTime=g;exports.formatDate=l;exports.formatDateTime=S;exports.parseDate=y;exports.parseDateTime=f;
|
package/dist/api.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as f, c as h, g as M, s as $, b as T } from "./client-CMERmrC-.js";
|
|
2
2
|
import { g as H, l as b } from "./metadata-CwAo6a8e.js";
|
|
3
|
-
import { a as w, b as x, H as A, M as N, Q as Y } from "./constants-
|
|
3
|
+
import { a as w, b as x, H as A, M as N, Q as Y } from "./constants-ConHc1oS.js";
|
|
4
4
|
const m = {
|
|
5
5
|
/** Date format: "YYYY-MM-DD" */
|
|
6
6
|
DATE: "%Y-%m-%d",
|
package/dist/auth.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var J=Object.defineProperty;var X=(e,t,n)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var M=(e,t,n)=>X(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react/jsx-runtime"),r=require("react"),N=require("@tanstack/react-query"),L=require("./client-BnVxSHAm.cjs"),W=require("./constants-
|
|
1
|
+
"use strict";var J=Object.defineProperty;var X=(e,t,n)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var M=(e,t,n)=>X(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react/jsx-runtime"),r=require("react"),N=require("@tanstack/react-query"),L=require("./client-BnVxSHAm.cjs"),W=require("./constants-QX2RX-wu.cjs"),H={sessionEndpoint:"/api/id",providers:{google:{loginPath:"/api/auth/google/login",logoutPath:"/api/auth/logout"}},defaultProvider:"google",autoRedirect:!1,sessionCheckInterval:0,retry:{count:3,delay:1e3},staleTime:5*60*1e3,refetchOnWindowFocus:!1,refetchOnReconnect:!0};let h={...H};function Y(e){h={...h,...e,providers:{...h.providers,...e.providers},retry:{...h.retry,...e.retry}}}function Z(e,t){h.providers[e]=t}function b(){return{...h}}function k(){return h.baseUrl||L.getApiBaseUrl()||(typeof window<"u"?window.location.origin:"")}function G(e){return h.providers[e]}function D(){h={...H}}class E extends Error{constructor(n,o){super(n);M(this,"statusCode");this.name="AuthenticationError",this.statusCode=o}}async function ee(){const e=b(),t=k(),n=L.getDefaultHeaders(),o=await fetch(`${t}${e.sessionEndpoint}`,{method:"GET",headers:n,credentials:"include"});if(!o.ok)throw o.status===401||o.status===403?new E("Not authenticated",o.status):new E(`Session check failed: ${o.statusText}`,o.status);return await o.json()}function _(e,t){return new Promise(()=>{const n=b(),o=k();if(!o)throw new Error('Auth base URL is not configured. Call setApiBaseUrl("https://...") or configureAuth({ baseUrl: "https://..." }) first.');const u=e||n.defaultProvider,c=G(u);if(!c){const A=Object.keys(n.providers||{}).join(", ")||"none";throw new Error(`Auth provider "${u}" is not configured. Available providers: ${A}`)}if(!c.loginPath)throw new Error(`Login path not configured for provider "${u}". Configure it with: configureAuth({ providers: { ${u}: { loginPath: '/api/auth/...' } } })`);let f;try{f=new URL(`${o}${c.loginPath}`)}catch{throw new Error(`Failed to construct login URL. Base URL: "${o}", Login path: "${c.loginPath}". Ensure baseUrl is a valid URL (e.g., "https://example.com").`)}(t!=null&&t.callbackUrl||n.callbackUrl)&&f.searchParams.set("callbackUrl",(t==null?void 0:t.callbackUrl)||n.callbackUrl||window.location.href),t!=null&&t.params&&Object.entries(t.params).forEach(([A,v])=>{f.searchParams.set(A,v)}),window.open(f.toString(),"_blank")})}async function te(e){const t=b(),n=k(),o=L.getDefaultHeaders(),u=G(t.defaultProvider),c=u==null?void 0:u.logoutPath;if(c&&(e==null?void 0:e.callLogoutEndpoint)!==!1)try{await fetch(`${n}${c}`,{method:"POST",headers:o,credentials:"include"})}catch(f){console.warn("Logout endpoint call failed:",f)}e!=null&&e.redirectUrl?window.location.href=e.redirectUrl:t.loginRedirectUrl&&(window.location.href=t.loginRedirectUrl)}const V=r.createContext(null),K=["auth","session"];function re({children:e,config:t,onAuthChange:n,onError:o,loadingComponent:u,unauthenticatedComponent:c,skipInitialCheck:f=!1}){const A=r.useRef(!1);t&&!A.current&&(Y(t),A.current=!0);const v=N.useQueryClient(),l=b(),{data:a,isLoading:g,error:U,refetch:R,isFetching:P}=N.useQuery({queryKey:K,queryFn:ee,enabled:!f,retry:(s,w)=>w instanceof E&&(w.statusCode===401||w.statusCode===403)?!1:s<l.retry.count,retryDelay:l.retry.delay,staleTime:l.staleTime,gcTime:l.staleTime*2,refetchOnWindowFocus:l.refetchOnWindowFocus??!0,refetchOnReconnect:l.refetchOnReconnect??!0,refetchInterval:l.sessionCheckInterval||!1}),[x,S]=r.useState(null),d=r.useMemo(()=>g||P?"loading":Object.keys((a==null?void 0:a.userDetails)||{}).length>0?"authenticated":"unauthenticated",[g,P,a]),i=(a==null?void 0:a.userDetails)||null,$=(a==null?void 0:a.staticBaseUrl)||null,O=(a==null?void 0:a.buildId)||null,j=d==="authenticated",C=r.useRef(n);C.current=n;const m=r.useRef(o);m.current=o,r.useEffect(()=>{var s;g||(s=C.current)==null||s.call(C,d,i)},[d,i,g]),r.useEffect(()=>{var s;U&&(S(U),(s=m.current)==null||s.call(m,U))},[U]),r.useEffect(()=>{d==="unauthenticated"&&l.autoRedirect&&!g&&_()},[d,g,l.autoRedirect]);const p=r.useCallback((s,w)=>{_(s,w)},[]),q=r.useCallback(async s=>{v.removeQueries({queryKey:K}),await te(s)},[v]),B=r.useCallback(async()=>{if(P)return a||null;try{return(await R()).data||null}catch(s){return S(s),null}},[R,P,a]),I=r.useCallback(s=>(i==null?void 0:i.Role)===s,[i]),T=r.useCallback(s=>s.includes((i==null?void 0:i.Role)||""),[i]),F=r.useCallback(()=>{S(null)},[]),Q=r.useCallback(()=>{R()},[R]),z=r.useMemo(()=>({user:i,staticBaseUrl:$,buildId:O,status:d,isAuthenticated:j,isLoading:g,login:p,logout:q,refreshSession:B,hasRole:I,hasAnyRole:T,error:x,clearError:F,_forceCheck:Q}),[i,$,O,d,j,g,p,q,B,I,T,x,F,Q]);return d==="loading"&&u?y.jsx(y.Fragment,{children:u}):d==="unauthenticated"&&!l.autoRedirect&&c?y.jsx(y.Fragment,{children:c}):y.jsx(V.Provider,{value:z,children:e})}function ne(){const e=r.useContext(V);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}function oe(){const e=ne();return r.useMemo(()=>({user:e.user,staticBaseUrl:e.staticBaseUrl,buildId:e.buildId,status:e.status,isAuthenticated:e.isAuthenticated,isLoading:e.isLoading,login:e.login,logout:e.logout,refreshSession:e.refreshSession,hasRole:e.hasRole,hasAnyRole:e.hasAnyRole,error:e.error,clearError:e.clearError}),[e.user,e.staticBaseUrl,e.buildId,e.status,e.isAuthenticated,e.isLoading,e.login,e.logout,e.refreshSession,e.hasRole,e.hasAnyRole,e.error,e.clearError])}exports.AuthProviderName=W.AuthProviderName;exports.AuthStatus=W.AuthStatus;exports.AuthProvider=re;exports.AuthenticationError=E;exports.configureAuth=Y;exports.getAuthBaseUrl=k;exports.getAuthConfig=b;exports.resetAuthConfig=D;exports.setAuthProvider=Z;exports.useAuth=oe;
|
package/dist/auth.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { jsx as C, Fragment as W } from "react/jsx-runtime";
|
|
|
5
5
|
import { useRef as p, useState as D, useMemo as k, useEffect as L, useCallback as g, createContext as ee, useContext as te } from "react";
|
|
6
6
|
import { useQueryClient as re, useQuery as ne } from "@tanstack/react-query";
|
|
7
7
|
import { c as oe, g as H } from "./client-CMERmrC-.js";
|
|
8
|
-
import { c as me, A as be } from "./constants-
|
|
8
|
+
import { c as me, A as be } from "./constants-ConHc1oS.js";
|
|
9
9
|
const M = {
|
|
10
10
|
sessionEndpoint: "/api/id",
|
|
11
11
|
providers: {
|
package/dist/bdo.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var U=Object.defineProperty;var B=(r,e,t)=>e in r?U(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var c=(r,e,t)=>B(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./client-BnVxSHAm.cjs"),m=require("./BaseField-Drp0-OxL.cjs"),C=require("./constants-D0J69if5.cjs"),D=new Set(["jpg","jpeg","png","gif","webp","bmp","tiff","tif","heic","heif"]),M=new Set(["jpg","jpeg","png","gif","webp","bmp","tiff","tif","heic","heif","mp4","mov","avi","webm","mkv","m4v","wmv","flv","pdf","doc","docx","xls","xlsx","ppt","pptx","txt","csv","zip"]);function x(r){if(!r.includes("."))return"";const e=r.split(".");return(e[e.length-1]??"").toLowerCase()}function S(r,e){const t=x(r),s=e==="Image"?D:M;if(!t||!s.has(t)){const a=[...s].sort().join(", ");throw new Error(`File "${r}" has unsupported extension "${t||"(none)"}". Supported for ${e} fields: ${a}`)}}class w{constructor(e,t){c(this,"_data");c(this,"_bdo");c(this,"_accessorCache",new Map);return this._bdo=e,this._data={...t},new Proxy(this,{get(s,a,i){return a==="validate"||a==="toJSON"||a==="_bdo"||a==="_data"||a==="_accessorCache"||a==="_getAccessor"||a==="_requireInstanceId"||typeof a=="symbol"?Reflect.get(s,a,i):a==="_id"?s._data._id:s._getAccessor(a)},set(s,a,i){return a==="_bdo"||a==="_data"||a==="_accessorCache"||a==="validate"||a==="toJSON"?!1:typeof a=="symbol"?Reflect.set(s,a,i):(s._data[a]=i,!0)},has(s,a){return a==="validate"||a==="toJSON"?!0:a in s._data||a in s._bdo.getFields()},ownKeys(s){return[...Object.keys(s._bdo.getFields()),"validate","toJSON"]},getOwnPropertyDescriptor(s,a){if(a==="validate"||a==="toJSON")return{configurable:!0,enumerable:!1,value:s[a]};const i=s._bdo.getFields();if(a in i||a in s._data)return{configurable:!0,enumerable:!0,get:()=>s._getAccessor(a)}}})}_requireInstanceId(){const e=this._data._id;if(!e)throw new Error("Cannot perform attachment operation: item has no _id. Save the item first.");return e}_getAccessor(e){if(this._accessorCache.has(e))return this._accessorCache.get(e);const s=this._bdo.getFields()[e],a=(s==null?void 0:s.meta)??{_id:e,Name:e,Type:"String"},i=(s==null?void 0:s.readOnly)??!1,u=()=>{if(s){const f=s.validate(this._data[e]);if(!f.valid)return f}return this._bdo.hasMetadata()?this._bdo.validateFieldExpression(e,this._data[e],this.toJSON()):{valid:!0,errors:[]}},h=f=>{const g=this._data[e];return g??f};let p;if(i?p={label:(s==null?void 0:s.label)??e,required:(s==null?void 0:s.required)??!1,readOnly:!0,defaultValue:s==null?void 0:s.defaultValue,meta:a,get:()=>this._data[e],getOrDefault:h,validate:u}:p={label:(s==null?void 0:s.label)??e,required:(s==null?void 0:s.required)??!1,readOnly:!1,defaultValue:s==null?void 0:s.defaultValue,meta:a,get:()=>this._data[e],getOrDefault:h,set:f=>{this._data[e]=f},validate:u},a.Type==="Image"||a.Type==="File"){const f=this._bdo.getBoId(),g=p;a.Type==="Image"?(g.getDownloadUrl=async o=>{const d=this._requireInstanceId(),_=this._data[e];if(!(_!=null&&_._id))throw new Error(`${e} has no image to download`);return n.api(f).getDownloadUrl(d,e,_._id,o)},i||(g.upload=async o=>{S(o.name,"Image");const d=this._requireInstanceId(),_={FileName:o.name,Size:o.size,FileExtension:x(o.name)},[l]=await n.api(f).getUploadUrl(d,e,[_]);await fetch(l.UploadUrl.URL,{method:"PUT",headers:{"Content-Type":l.ContentType},body:o});const v={_id:l._id,_name:l._name,FileName:l.FileName,FileExtension:l.FileExtension,Size:l.Size,ContentType:l.ContentType};return this._data[e]=v,v},g.deleteAttachment=async()=>{const o=this._requireInstanceId(),d=this._data[e];if(!(d!=null&&d._id))throw new Error(`${e} has no image to delete`);await n.api(f).deleteAttachment(o,e,d._id),this._data[e]=null})):(g.getDownloadUrl=async(o,d)=>{const _=this._requireInstanceId();return n.api(f).getDownloadUrl(_,e,o,d)},g.getDownloadUrls=async o=>{const d=this._requireInstanceId();return n.api(f).getDownloadUrls(d,e,o)},i||(g.upload=async o=>{for(const N of o)S(N.name,"File");const d=this._requireInstanceId(),_=o.map(N=>({FileName:N.name,Size:N.size,FileExtension:x(N.name)})),l=await n.api(f).getUploadUrl(d,e,_),v=await Promise.all(o.map(async(N,y)=>(await fetch(l[y].UploadUrl.URL,{method:"PUT",headers:{"Content-Type":l[y].ContentType},body:N}),{_id:l[y]._id,_name:l[y]._name,FileName:l[y].FileName,FileExtension:l[y].FileExtension,Size:l[y].Size,ContentType:l[y].ContentType}))),A=this._data[e]??[];return this._data[e]=[...A,...v],v},g.deleteAttachment=async o=>{const d=this._requireInstanceId();await n.api(f).deleteAttachment(d,e,o);const _=this._data[e]??[];this._data[e]=_.filter(l=>l._id!==o)}))}return this._accessorCache.set(e,p),p}validate(){const e=this._bdo.getFields(),t=[],s=this.toJSON();for(const[a,i]of Object.entries(e)){if(i.readOnly)continue;const u=this._data[a],h=i.validate(u);if(!h.valid){t.push(...h.errors);continue}if(this._bdo.hasMetadata()){const p=this._bdo.validateFieldExpression(a,u,s);p.valid||t.push(...p.errors)}}return{valid:t.length===0,errors:t}}toJSON(){return{...this._data}}}class F extends m.BaseField{constructor(e){super(e)}get length(){var e;return(e=this._meta.Constraint)==null?void 0:e.Length}validate(e){return e!=null&&typeof e!="string"?{valid:!1,errors:[`${this.label} must be a string`]}:{valid:!0,errors:[]}}}class E extends m.BaseField{constructor(e){super(e)}get precision(){var e;return((e=this._meta.Constraint)==null?void 0:e.Precision)??"Second"}validate(e){if(e==null||e==="")return{valid:!0,errors:[]};if(typeof e!="string")return{valid:!1,errors:[`${this.label} must be a valid date string`]};const t=new Date(e);return isNaN(t.getTime())?{valid:!1,errors:[`${this.label} is not a valid date`]}:{valid:!0,errors:[]}}}class T extends m.BaseField{constructor(e){super(e)}get businessEntity(){var e;return(e=this._meta.View)==null?void 0:e.BusinessEntity}validate(e){if(e==null)return{valid:!0,errors:[]};if(typeof e!="object")return{valid:!1,errors:[`${this.label} must be a valid user object`]};const t=e;return!("_id"in t)||typeof t._id!="string"?{valid:!1,errors:[`${this.label} must have a valid _id`]}:{valid:!0,errors:[]}}}const R={CONCAT:(...r)=>r.map(e=>String(e??"")).join(""),UPPER:r=>String(r??"").toUpperCase(),LOWER:r=>String(r??"").toLowerCase(),TRIM:r=>String(r??"").trim(),LENGTH:r=>String(r??"").length,SUBSTRING:(r,e,t)=>String(r??"").substring(e,t!==void 0?e+t:void 0),REPLACE:(r,e,t)=>String(r??"").replace(e,t),SUM:(...r)=>r.reduce((e,t)=>e+(Number(t)||0),0),AVG:(...r)=>{const e=r.filter(t=>t!=null&&!isNaN(Number(t)));return e.length===0?0:e.reduce((t,s)=>t+Number(s),0)/e.length},MIN:(...r)=>{const e=r.filter(t=>t!=null&&!isNaN(Number(t))).map(t=>Number(t));return e.length===0?0:Math.min(...e)},MAX:(...r)=>{const e=r.filter(t=>t!=null&&!isNaN(Number(t))).map(t=>Number(t));return e.length===0?0:Math.max(...e)},ABS:r=>Math.abs(Number(r)||0),ROUND:r=>Math.round(Number(r)||0),FLOOR:r=>Math.floor(Number(r)||0),CEIL:r=>Math.ceil(Number(r)||0),YEAR:r=>{const e=new Date(r);return isNaN(e.getTime())?0:e.getFullYear()},MONTH:r=>{const e=new Date(r);return isNaN(e.getTime())?0:e.getMonth()+1},DAY:r=>{const e=new Date(r);return isNaN(e.getTime())?0:e.getDate()},DATE_DIFF:(r,e)=>{const t=new Date(r),s=new Date(e);if(isNaN(t.getTime())||isNaN(s.getTime()))return 0;const a=Math.abs(t.getTime()-s.getTime());return Math.ceil(a/(1e3*60*60*24))},ADD_DAYS:(r,e)=>{const t=new Date(r);return isNaN(t.getTime())?new Date(NaN):(t.setDate(t.getDate()+e),t)},ADD_MONTHS:(r,e)=>{const t=new Date(r);return isNaN(t.getTime())?new Date(NaN):(t.setMonth(t.getMonth()+e),t)},IF:(r,e,t)=>r?e:t,UUID:()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})};function I(){const r=new Date;return{NOW:r,TODAY:new Date(r.getFullYear(),r.getMonth(),r.getDate()),CURRENT_USER:{Id:"",Email:"",FirstName:"",LastName:""}}}function b(r,e){var t;switch(r.Type){case"Literal":return r.Value;case"Identifier":return e.formValues[r.Name];case"SystemIdentifier":return $(r,e);case"BinaryExpression":return j(r,e);case"LogicalExpression":return V(r,e);case"CallExpression":return P(r,e);case"MemberExpression":return q(r,e);case"AssignmentExpression":return((t=r.Arguments)==null?void 0:t.length)===1?b(r.Arguments[0],e):void 0;default:throw new Error(`Unsupported expression type: ${r.Type}`)}}function $(r,e){const t=r.Name,s=e.systemValues[t];return r.Property?s&&typeof s=="object"?s[r.Property.Name]:void 0:s}function j(r,e){if(!r.Arguments||r.Arguments.length<2)throw new Error("BinaryExpression requires 2 arguments");const[t,s]=r.Arguments,a=b(t,e),i=b(s,e);switch(r.Operator){case"==":return a==i;case"!=":return a!=i;case"<":return Number(a)<Number(i);case"<=":return Number(a)<=Number(i);case">":return Number(a)>Number(i);case">=":return Number(a)>=Number(i);case"+":return Number(a)+Number(i);case"-":return Number(a)-Number(i);case"*":return Number(a)*Number(i);case"/":return Number(i)!==0?Number(a)/Number(i):0;case"%":return Number(a)%Number(i);default:throw new Error(`Unsupported binary operator: ${r.Operator}`)}}function V(r,e){if(!r.Arguments||r.Arguments.length===0)throw new Error("LogicalExpression requires at least 1 argument");const t=r.Arguments;switch(r.Operator){case"AND":return t.every(s=>!!b(s,e));case"OR":return t.some(s=>!!b(s,e));case"!":return!b(t[0],e);default:throw new Error(`Unsupported logical operator: ${r.Operator}`)}}function P(r,e){if(!r.Callee)throw new Error("CallExpression requires a Callee");const t=R[r.Callee];if(!t)throw new Error(`Unknown function: ${r.Callee}`);const s=(r.Arguments??[]).map(a=>b(a,e));return t(...s)}function q(r,e){var a,i;if(!((a=r.Arguments)!=null&&a.length))return;const t=b(r.Arguments[0],e),s=(i=r.Arguments[0].Property)==null?void 0:i.Name;return s&&t&&typeof t=="object"?t[s]:t}class L{constructor(){c(this,"fieldRules",new Map);c(this,"metadata",null)}loadMetadata(e){var t,s;this.metadata=e,this.fieldRules.clear();for(const[a,i]of Object.entries(e.Fields)){const u=[];if(i.Validation&&Array.isArray(i.Validation)){for(const h of i.Validation)if(typeof h=="object"&&h.ExpressionTree)u.push(h);else if(typeof h=="string"){const p=(s=(t=e.Rules)==null?void 0:t.Validation)==null?void 0:s[h];p&&u.push(p)}}u.length>0&&this.fieldRules.set(a,u)}}hasMetadata(){return this.metadata!==null}getFieldRules(e){return this.fieldRules.get(e)??[]}validateField(e,t,s){const a=this.fieldRules.get(e);if(!a||a.length===0)return{valid:!0,errors:[]};const i={formValues:{...s,[e]:t},systemValues:I()};for(const u of a)try{if(!b(u.ExpressionTree,i))return{valid:!1,errors:[u.Message||`Validation failed: ${u.Name||u.Id}`]}}catch(h){console.warn(`Expression evaluation failed for rule ${u.Id}:`,h)}return{valid:!0,errors:[]}}validateAll(e){const t=[];for(const s of this.fieldRules.keys()){const a=this.validateField(s,e[s],e);a.valid||t.push(...a.errors)}return{valid:t.length===0,errors:t}}}class Y{constructor(){c(this,"_id",new F({_id:"_id",Name:"ID",Type:"String",ReadOnly:!0}));c(this,"_created_at",new E({_id:"_created_at",Name:"Created At",Type:"DateTime",ReadOnly:!0}));c(this,"_modified_at",new E({_id:"_modified_at",Name:"Modified At",Type:"DateTime",ReadOnly:!0}));c(this,"_created_by",new T({_id:"_created_by",Name:"Created By",Type:"User",ReadOnly:!0}));c(this,"_modified_by",new T({_id:"_modified_by",Name:"Modified By",Type:"User",ReadOnly:!0}));c(this,"_version",new F({_id:"_version",Name:"Version",Type:"String",ReadOnly:!0}));c(this,"_m_version",new F({_id:"_m_version",Name:"Metadata Version",Type:"String",ReadOnly:!0}));c(this,"_fieldsBound",!1);c(this,"_fieldsCache",null);c(this,"_expressionEngine",new L)}getBoId(){return this.meta._id}getFields(){if(this._fieldsCache)return this._fieldsCache;const e={};for(const t of Object.keys(this)){const s=this[t];s instanceof m.BaseField&&(e[t]=s)}if(!this._fieldsBound){for(const t of Object.values(e))t._parentBoId=this.meta._id;this._fieldsBound=!0}return this._fieldsCache=e,e}loadMetadata(e){this._expressionEngine.loadMetadata(e)}hasMetadata(){return this._expressionEngine.hasMetadata()}validateFieldExpression(e,t,s){return this._expressionEngine.hasMetadata()?this._expressionEngine.validateField(e,t,s):{valid:!0,errors:[]}}async get(e){const t=await n.api(this.meta._id).get(e);return new w(this,t)}async list(e){return(await n.api(this.meta._id).list(e)).Data.map(s=>new w(this,s))}async count(e){return(await n.api(this.meta._id).count(e)).Count}async create(e){const t=await n.api(this.meta._id).create(e);return new w(this,{...e,_id:t._id})}async update(e,t){return n.api(this.meta._id).update(e,t)}async delete(e){return n.api(this.meta._id).delete(e)}async draft(e){return n.api(this.meta._id).draft(e)}async draftInteraction(e){return n.api(this.meta._id).draftInteraction(e)}createItem(e){return new w(this,e??{})}async draftUpdate(e,t){return n.api(this.meta._id).draftUpdate(e,t)}async draftPatch(e,t){return n.api(this.meta._id).draftPatch(e,t)}async metric(e){return n.api(this.meta._id).metric(e)}async pivot(e){return n.api(this.meta._id).pivot(e)}async getUploadUrl(e,t,s){return n.api(this.meta._id).getUploadUrl(e,t,s)}async getDownloadUrl(e,t,s,a){return n.api(this.meta._id).getDownloadUrl(e,t,s,a)}async getDownloadUrls(e,t,s){return n.api(this.meta._id).getDownloadUrls(e,t,s)}async deleteAttachment(e,t,s){return n.api(this.meta._id).deleteAttachment(e,t,s)}}class z extends m.BaseField{constructor(e){super(e)}get integerPart(){var e;return((e=this._meta.Constraint)==null?void 0:e.IntegerPart)??9}get fractionPart(){var e;return(e=this._meta.Constraint)==null?void 0:e.FractionPart}validate(e){return e!=null&&(typeof e!="number"||isNaN(e))?{valid:!1,errors:[`${this.label} must be a valid number`]}:{valid:!0,errors:[]}}}class J extends m.BaseField{constructor(e){super(e)}validate(e){return e!=null&&typeof e!="boolean"?{valid:!1,errors:[`${this.label} must be a boolean`]}:{valid:!0,errors:[]}}}class k extends m.BaseField{constructor(e){super(e)}validate(e){if(e==null||e==="")return{valid:!0,errors:[]};if(typeof e!="string")return{valid:!1,errors:[`${this.label} must be a valid date string`]};if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return{valid:!1,errors:[`${this.label} must be in YYYY-MM-DD format`]};const t=new Date(e+"T00:00:00");return isNaN(t.getTime())?{valid:!1,errors:[`${this.label} is not a valid date`]}:{valid:!0,errors:[]}}}class G extends m.BaseField{constructor(e){super(e)}get options(){var t;return(((t=this._meta.Constraint)==null?void 0:t.Enum)??[]).map(s=>({value:s,label:s}))}validate(e){if(e==null||e==="")return{valid:!0,errors:[]};if(this.options.length===0)return{valid:!0,errors:[]};const t=this.options.map(s=>s.value);return t.includes(e)?{valid:!0,errors:[]}:{valid:!1,errors:[`${this.label} must be one of: ${t.join(", ")}`]}}async fetchOptions(e){if(!this._parentBoId)throw new Error(`Field ${this.id} not bound to a BDO. Cannot fetch options.`);return(await n.api(this._parentBoId).fetchField(e??"new",this.id)).map(s=>({value:s.Value,label:s.Label}))}}class H extends m.BaseField{constructor(e){super(e)}get referenceBdo(){var e,t;return((t=(e=this._meta.View)==null?void 0:e.DataObject)==null?void 0:t.Id)??""}get referenceFields(){var e;return((e=this._meta.View)==null?void 0:e.Fields)??["_id"]}get searchFields(){var e;return((e=this._meta.View)==null?void 0:e.Search)??[]}validate(e){if(e==null)return{valid:!0,errors:[]};if(typeof e!="object")return{valid:!1,errors:[`${this.label} must be a valid reference object`]};const t=e;return!("_id"in t)||typeof t._id!="string"?{valid:!1,errors:[`${this.label} must have a valid _id`]}:{valid:!0,errors:[]}}async fetchOptions(e){if(!this._parentBoId)throw new Error(`Field ${this.id} not bound to a BDO. Cannot fetch options.`);return n.api(this._parentBoId).fetchField(e??"new",this.id)}}class X extends m.BaseField{constructor(e){super(e)}get elementType(){return this._meta.Property}validate(e){return e!=null&&!Array.isArray(e)?{valid:!1,errors:[`${this.label} must be an array`]}:{valid:!0,errors:[]}}}class K extends m.BaseField{constructor(e){super(e)}get properties(){return this._meta.Property}validate(e){return e==null?{valid:!0,errors:[]}:typeof e!="object"||Array.isArray(e)?{valid:!1,errors:[`${this.label} must be a valid object`]}:{valid:!0,errors:[]}}}class O extends m.BaseField{constructor(e){super(e)}get format(){var e;return((e=this._meta.Constraint)==null?void 0:e.Format)??"Plain"}validate(e){return e!=null&&typeof e!="string"?{valid:!1,errors:[`${this.label} must be a string`]}:{valid:!0,errors:[]}}}class W extends m.BaseField{constructor(e){super(e)}validate(e){if(e==null)return{valid:!0,errors:[]};if(!Array.isArray(e))return{valid:!1,errors:[`${this.label} must be an array of file objects`]};for(const t of e)if(!t||typeof t!="object"||!t._id)return{valid:!1,errors:[`Each file in ${this.label} must have an _id`]};return{valid:!0,errors:[]}}}class Q extends m.BaseField{constructor(e){super(e)}validate(e){return e==null?{valid:!0,errors:[]}:typeof e!="object"||Array.isArray(e)?{valid:!1,errors:[`${this.label} must be a valid image object`]}:!e._id||!e.FileName?{valid:!1,errors:[`${this.label} must have _id and FileName`]}:{valid:!0,errors:[]}}}exports.BaseField=m.BaseField;exports.SystemField=C.SystemField;exports.ArrayField=X;exports.BaseBdo=Y;exports.BooleanField=J;exports.DateField=k;exports.DateTimeField=E;exports.FileField=W;exports.ImageField=Q;exports.NumberField=z;exports.ObjectField=K;exports.ReferenceField=H;exports.SelectField=G;exports.StringField=F;exports.TextAreaField=O;exports.TextField=O;exports.UserField=T;
|
|
1
|
+
"use strict";var U=Object.defineProperty;var B=(r,e,t)=>e in r?U(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var c=(r,e,t)=>B(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./client-BnVxSHAm.cjs"),m=require("./BaseField-Drp0-OxL.cjs"),C=require("./constants-QX2RX-wu.cjs"),D=new Set(["jpg","jpeg","png","gif","webp","bmp","tiff","tif","heic","heif"]),M=new Set(["jpg","jpeg","png","gif","webp","bmp","tiff","tif","heic","heif","mp4","mov","avi","webm","mkv","m4v","wmv","flv","pdf","doc","docx","xls","xlsx","ppt","pptx","txt","csv","zip"]);function x(r){if(!r.includes("."))return"";const e=r.split(".");return(e[e.length-1]??"").toLowerCase()}function S(r,e){const t=x(r),s=e==="Image"?D:M;if(!t||!s.has(t)){const a=[...s].sort().join(", ");throw new Error(`File "${r}" has unsupported extension "${t||"(none)"}". Supported for ${e} fields: ${a}`)}}class w{constructor(e,t){c(this,"_data");c(this,"_bdo");c(this,"_accessorCache",new Map);return this._bdo=e,this._data={...t},new Proxy(this,{get(s,a,i){return a==="validate"||a==="toJSON"||a==="_bdo"||a==="_data"||a==="_accessorCache"||a==="_getAccessor"||a==="_requireInstanceId"||typeof a=="symbol"?Reflect.get(s,a,i):a==="_id"?s._data._id:s._getAccessor(a)},set(s,a,i){return a==="_bdo"||a==="_data"||a==="_accessorCache"||a==="validate"||a==="toJSON"?!1:typeof a=="symbol"?Reflect.set(s,a,i):(s._data[a]=i,!0)},has(s,a){return a==="validate"||a==="toJSON"?!0:a in s._data||a in s._bdo.getFields()},ownKeys(s){return[...Object.keys(s._bdo.getFields()),"validate","toJSON"]},getOwnPropertyDescriptor(s,a){if(a==="validate"||a==="toJSON")return{configurable:!0,enumerable:!1,value:s[a]};const i=s._bdo.getFields();if(a in i||a in s._data)return{configurable:!0,enumerable:!0,get:()=>s._getAccessor(a)}}})}_requireInstanceId(){const e=this._data._id;if(!e)throw new Error("Cannot perform attachment operation: item has no _id. Save the item first.");return e}_getAccessor(e){if(this._accessorCache.has(e))return this._accessorCache.get(e);const s=this._bdo.getFields()[e],a=(s==null?void 0:s.meta)??{_id:e,Name:e,Type:"String"},i=(s==null?void 0:s.readOnly)??!1,u=()=>{if(s){const f=s.validate(this._data[e]);if(!f.valid)return f}return this._bdo.hasMetadata()?this._bdo.validateFieldExpression(e,this._data[e],this.toJSON()):{valid:!0,errors:[]}},h=f=>{const g=this._data[e];return g??f};let p;if(i?p={label:(s==null?void 0:s.label)??e,required:(s==null?void 0:s.required)??!1,readOnly:!0,defaultValue:s==null?void 0:s.defaultValue,meta:a,get:()=>this._data[e],getOrDefault:h,validate:u}:p={label:(s==null?void 0:s.label)??e,required:(s==null?void 0:s.required)??!1,readOnly:!1,defaultValue:s==null?void 0:s.defaultValue,meta:a,get:()=>this._data[e],getOrDefault:h,set:f=>{this._data[e]=f},validate:u},a.Type==="Image"||a.Type==="File"){const f=this._bdo.getBoId(),g=p;a.Type==="Image"?(g.getDownloadUrl=async o=>{const d=this._requireInstanceId(),_=this._data[e];if(!(_!=null&&_._id))throw new Error(`${e} has no image to download`);return n.api(f).getDownloadUrl(d,e,_._id,o)},i||(g.upload=async o=>{S(o.name,"Image");const d=this._requireInstanceId(),_={FileName:o.name,Size:o.size,FileExtension:x(o.name)},[l]=await n.api(f).getUploadUrl(d,e,[_]);await fetch(l.UploadUrl.URL,{method:"PUT",headers:{"Content-Type":l.ContentType},body:o});const v={_id:l._id,_name:l._name,FileName:l.FileName,FileExtension:l.FileExtension,Size:l.Size,ContentType:l.ContentType};return this._data[e]=v,v},g.deleteAttachment=async()=>{const o=this._requireInstanceId(),d=this._data[e];if(!(d!=null&&d._id))throw new Error(`${e} has no image to delete`);await n.api(f).deleteAttachment(o,e,d._id),this._data[e]=null})):(g.getDownloadUrl=async(o,d)=>{const _=this._requireInstanceId();return n.api(f).getDownloadUrl(_,e,o,d)},g.getDownloadUrls=async o=>{const d=this._requireInstanceId();return n.api(f).getDownloadUrls(d,e,o)},i||(g.upload=async o=>{for(const N of o)S(N.name,"File");const d=this._requireInstanceId(),_=o.map(N=>({FileName:N.name,Size:N.size,FileExtension:x(N.name)})),l=await n.api(f).getUploadUrl(d,e,_),v=await Promise.all(o.map(async(N,y)=>(await fetch(l[y].UploadUrl.URL,{method:"PUT",headers:{"Content-Type":l[y].ContentType},body:N}),{_id:l[y]._id,_name:l[y]._name,FileName:l[y].FileName,FileExtension:l[y].FileExtension,Size:l[y].Size,ContentType:l[y].ContentType}))),A=this._data[e]??[];return this._data[e]=[...A,...v],v},g.deleteAttachment=async o=>{const d=this._requireInstanceId();await n.api(f).deleteAttachment(d,e,o);const _=this._data[e]??[];this._data[e]=_.filter(l=>l._id!==o)}))}return this._accessorCache.set(e,p),p}validate(){const e=this._bdo.getFields(),t=[],s=this.toJSON();for(const[a,i]of Object.entries(e)){if(i.readOnly)continue;const u=this._data[a],h=i.validate(u);if(!h.valid){t.push(...h.errors);continue}if(this._bdo.hasMetadata()){const p=this._bdo.validateFieldExpression(a,u,s);p.valid||t.push(...p.errors)}}return{valid:t.length===0,errors:t}}toJSON(){return{...this._data}}}class F extends m.BaseField{constructor(e){super(e)}get length(){var e;return(e=this._meta.Constraint)==null?void 0:e.Length}validate(e){return e!=null&&typeof e!="string"?{valid:!1,errors:[`${this.label} must be a string`]}:{valid:!0,errors:[]}}}class E extends m.BaseField{constructor(e){super(e)}get precision(){var e;return((e=this._meta.Constraint)==null?void 0:e.Precision)??"Second"}validate(e){if(e==null||e==="")return{valid:!0,errors:[]};if(typeof e!="string")return{valid:!1,errors:[`${this.label} must be a valid date string`]};const t=new Date(e);return isNaN(t.getTime())?{valid:!1,errors:[`${this.label} is not a valid date`]}:{valid:!0,errors:[]}}}class T extends m.BaseField{constructor(e){super(e)}get businessEntity(){var e;return(e=this._meta.View)==null?void 0:e.BusinessEntity}validate(e){if(e==null)return{valid:!0,errors:[]};if(typeof e!="object")return{valid:!1,errors:[`${this.label} must be a valid user object`]};const t=e;return!("_id"in t)||typeof t._id!="string"?{valid:!1,errors:[`${this.label} must have a valid _id`]}:{valid:!0,errors:[]}}}const R={CONCAT:(...r)=>r.map(e=>String(e??"")).join(""),UPPER:r=>String(r??"").toUpperCase(),LOWER:r=>String(r??"").toLowerCase(),TRIM:r=>String(r??"").trim(),LENGTH:r=>String(r??"").length,SUBSTRING:(r,e,t)=>String(r??"").substring(e,t!==void 0?e+t:void 0),REPLACE:(r,e,t)=>String(r??"").replace(e,t),SUM:(...r)=>r.reduce((e,t)=>e+(Number(t)||0),0),AVG:(...r)=>{const e=r.filter(t=>t!=null&&!isNaN(Number(t)));return e.length===0?0:e.reduce((t,s)=>t+Number(s),0)/e.length},MIN:(...r)=>{const e=r.filter(t=>t!=null&&!isNaN(Number(t))).map(t=>Number(t));return e.length===0?0:Math.min(...e)},MAX:(...r)=>{const e=r.filter(t=>t!=null&&!isNaN(Number(t))).map(t=>Number(t));return e.length===0?0:Math.max(...e)},ABS:r=>Math.abs(Number(r)||0),ROUND:r=>Math.round(Number(r)||0),FLOOR:r=>Math.floor(Number(r)||0),CEIL:r=>Math.ceil(Number(r)||0),YEAR:r=>{const e=new Date(r);return isNaN(e.getTime())?0:e.getFullYear()},MONTH:r=>{const e=new Date(r);return isNaN(e.getTime())?0:e.getMonth()+1},DAY:r=>{const e=new Date(r);return isNaN(e.getTime())?0:e.getDate()},DATE_DIFF:(r,e)=>{const t=new Date(r),s=new Date(e);if(isNaN(t.getTime())||isNaN(s.getTime()))return 0;const a=Math.abs(t.getTime()-s.getTime());return Math.ceil(a/(1e3*60*60*24))},ADD_DAYS:(r,e)=>{const t=new Date(r);return isNaN(t.getTime())?new Date(NaN):(t.setDate(t.getDate()+e),t)},ADD_MONTHS:(r,e)=>{const t=new Date(r);return isNaN(t.getTime())?new Date(NaN):(t.setMonth(t.getMonth()+e),t)},IF:(r,e,t)=>r?e:t,UUID:()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})};function I(){const r=new Date;return{NOW:r,TODAY:new Date(r.getFullYear(),r.getMonth(),r.getDate()),CURRENT_USER:{Id:"",Email:"",FirstName:"",LastName:""}}}function b(r,e){var t;switch(r.Type){case"Literal":return r.Value;case"Identifier":return e.formValues[r.Name];case"SystemIdentifier":return $(r,e);case"BinaryExpression":return j(r,e);case"LogicalExpression":return V(r,e);case"CallExpression":return P(r,e);case"MemberExpression":return q(r,e);case"AssignmentExpression":return((t=r.Arguments)==null?void 0:t.length)===1?b(r.Arguments[0],e):void 0;default:throw new Error(`Unsupported expression type: ${r.Type}`)}}function $(r,e){const t=r.Name,s=e.systemValues[t];return r.Property?s&&typeof s=="object"?s[r.Property.Name]:void 0:s}function j(r,e){if(!r.Arguments||r.Arguments.length<2)throw new Error("BinaryExpression requires 2 arguments");const[t,s]=r.Arguments,a=b(t,e),i=b(s,e);switch(r.Operator){case"==":return a==i;case"!=":return a!=i;case"<":return Number(a)<Number(i);case"<=":return Number(a)<=Number(i);case">":return Number(a)>Number(i);case">=":return Number(a)>=Number(i);case"+":return Number(a)+Number(i);case"-":return Number(a)-Number(i);case"*":return Number(a)*Number(i);case"/":return Number(i)!==0?Number(a)/Number(i):0;case"%":return Number(a)%Number(i);default:throw new Error(`Unsupported binary operator: ${r.Operator}`)}}function V(r,e){if(!r.Arguments||r.Arguments.length===0)throw new Error("LogicalExpression requires at least 1 argument");const t=r.Arguments;switch(r.Operator){case"AND":return t.every(s=>!!b(s,e));case"OR":return t.some(s=>!!b(s,e));case"!":return!b(t[0],e);default:throw new Error(`Unsupported logical operator: ${r.Operator}`)}}function P(r,e){if(!r.Callee)throw new Error("CallExpression requires a Callee");const t=R[r.Callee];if(!t)throw new Error(`Unknown function: ${r.Callee}`);const s=(r.Arguments??[]).map(a=>b(a,e));return t(...s)}function q(r,e){var a,i;if(!((a=r.Arguments)!=null&&a.length))return;const t=b(r.Arguments[0],e),s=(i=r.Arguments[0].Property)==null?void 0:i.Name;return s&&t&&typeof t=="object"?t[s]:t}class L{constructor(){c(this,"fieldRules",new Map);c(this,"metadata",null)}loadMetadata(e){var t,s;this.metadata=e,this.fieldRules.clear();for(const[a,i]of Object.entries(e.Fields)){const u=[];if(i.Validation&&Array.isArray(i.Validation)){for(const h of i.Validation)if(typeof h=="object"&&h.ExpressionTree)u.push(h);else if(typeof h=="string"){const p=(s=(t=e.Rules)==null?void 0:t.Validation)==null?void 0:s[h];p&&u.push(p)}}u.length>0&&this.fieldRules.set(a,u)}}hasMetadata(){return this.metadata!==null}getFieldRules(e){return this.fieldRules.get(e)??[]}validateField(e,t,s){const a=this.fieldRules.get(e);if(!a||a.length===0)return{valid:!0,errors:[]};const i={formValues:{...s,[e]:t},systemValues:I()};for(const u of a)try{if(!b(u.ExpressionTree,i))return{valid:!1,errors:[u.Message||`Validation failed: ${u.Name||u.Id}`]}}catch(h){console.warn(`Expression evaluation failed for rule ${u.Id}:`,h)}return{valid:!0,errors:[]}}validateAll(e){const t=[];for(const s of this.fieldRules.keys()){const a=this.validateField(s,e[s],e);a.valid||t.push(...a.errors)}return{valid:t.length===0,errors:t}}}class Y{constructor(){c(this,"_id",new F({_id:"_id",Name:"ID",Type:"String",ReadOnly:!0}));c(this,"_created_at",new E({_id:"_created_at",Name:"Created At",Type:"DateTime",ReadOnly:!0}));c(this,"_modified_at",new E({_id:"_modified_at",Name:"Modified At",Type:"DateTime",ReadOnly:!0}));c(this,"_created_by",new T({_id:"_created_by",Name:"Created By",Type:"User",ReadOnly:!0}));c(this,"_modified_by",new T({_id:"_modified_by",Name:"Modified By",Type:"User",ReadOnly:!0}));c(this,"_version",new F({_id:"_version",Name:"Version",Type:"String",ReadOnly:!0}));c(this,"_m_version",new F({_id:"_m_version",Name:"Metadata Version",Type:"String",ReadOnly:!0}));c(this,"_fieldsBound",!1);c(this,"_fieldsCache",null);c(this,"_expressionEngine",new L)}getBoId(){return this.meta._id}getFields(){if(this._fieldsCache)return this._fieldsCache;const e={};for(const t of Object.keys(this)){const s=this[t];s instanceof m.BaseField&&(e[t]=s)}if(!this._fieldsBound){for(const t of Object.values(e))t._parentBoId=this.meta._id;this._fieldsBound=!0}return this._fieldsCache=e,e}loadMetadata(e){this._expressionEngine.loadMetadata(e)}hasMetadata(){return this._expressionEngine.hasMetadata()}validateFieldExpression(e,t,s){return this._expressionEngine.hasMetadata()?this._expressionEngine.validateField(e,t,s):{valid:!0,errors:[]}}async get(e){const t=await n.api(this.meta._id).get(e);return new w(this,t)}async list(e){return(await n.api(this.meta._id).list(e)).Data.map(s=>new w(this,s))}async count(e){return(await n.api(this.meta._id).count(e)).Count}async create(e){const t=await n.api(this.meta._id).create(e);return new w(this,{...e,_id:t._id})}async update(e,t){return n.api(this.meta._id).update(e,t)}async delete(e){return n.api(this.meta._id).delete(e)}async draft(e){return n.api(this.meta._id).draft(e)}async draftInteraction(e){return n.api(this.meta._id).draftInteraction(e)}createItem(e){return new w(this,e??{})}async draftUpdate(e,t){return n.api(this.meta._id).draftUpdate(e,t)}async draftPatch(e,t){return n.api(this.meta._id).draftPatch(e,t)}async metric(e){return n.api(this.meta._id).metric(e)}async pivot(e){return n.api(this.meta._id).pivot(e)}async getUploadUrl(e,t,s){return n.api(this.meta._id).getUploadUrl(e,t,s)}async getDownloadUrl(e,t,s,a){return n.api(this.meta._id).getDownloadUrl(e,t,s,a)}async getDownloadUrls(e,t,s){return n.api(this.meta._id).getDownloadUrls(e,t,s)}async deleteAttachment(e,t,s){return n.api(this.meta._id).deleteAttachment(e,t,s)}}class z extends m.BaseField{constructor(e){super(e)}get integerPart(){var e;return((e=this._meta.Constraint)==null?void 0:e.IntegerPart)??9}get fractionPart(){var e;return(e=this._meta.Constraint)==null?void 0:e.FractionPart}validate(e){return e!=null&&(typeof e!="number"||isNaN(e))?{valid:!1,errors:[`${this.label} must be a valid number`]}:{valid:!0,errors:[]}}}class J extends m.BaseField{constructor(e){super(e)}validate(e){return e!=null&&typeof e!="boolean"?{valid:!1,errors:[`${this.label} must be a boolean`]}:{valid:!0,errors:[]}}}class k extends m.BaseField{constructor(e){super(e)}validate(e){if(e==null||e==="")return{valid:!0,errors:[]};if(typeof e!="string")return{valid:!1,errors:[`${this.label} must be a valid date string`]};if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return{valid:!1,errors:[`${this.label} must be in YYYY-MM-DD format`]};const t=new Date(e+"T00:00:00");return isNaN(t.getTime())?{valid:!1,errors:[`${this.label} is not a valid date`]}:{valid:!0,errors:[]}}}class G extends m.BaseField{constructor(e){super(e)}get options(){var t;return(((t=this._meta.Constraint)==null?void 0:t.Enum)??[]).map(s=>({value:s,label:s}))}validate(e){if(e==null||e==="")return{valid:!0,errors:[]};if(this.options.length===0)return{valid:!0,errors:[]};const t=this.options.map(s=>s.value);return t.includes(e)?{valid:!0,errors:[]}:{valid:!1,errors:[`${this.label} must be one of: ${t.join(", ")}`]}}async fetchOptions(e){if(!this._parentBoId)throw new Error(`Field ${this.id} not bound to a BDO. Cannot fetch options.`);return(await n.api(this._parentBoId).fetchField(e??"new",this.id)).map(s=>({value:s.Value,label:s.Label}))}}class H extends m.BaseField{constructor(e){super(e)}get referenceBdo(){var e,t;return((t=(e=this._meta.View)==null?void 0:e.DataObject)==null?void 0:t.Id)??""}get referenceFields(){var e;return((e=this._meta.View)==null?void 0:e.Fields)??["_id"]}get searchFields(){var e;return((e=this._meta.View)==null?void 0:e.Search)??[]}validate(e){if(e==null)return{valid:!0,errors:[]};if(typeof e!="object")return{valid:!1,errors:[`${this.label} must be a valid reference object`]};const t=e;return!("_id"in t)||typeof t._id!="string"?{valid:!1,errors:[`${this.label} must have a valid _id`]}:{valid:!0,errors:[]}}async fetchOptions(e){if(!this._parentBoId)throw new Error(`Field ${this.id} not bound to a BDO. Cannot fetch options.`);return n.api(this._parentBoId).fetchField(e??"new",this.id)}}class X extends m.BaseField{constructor(e){super(e)}get elementType(){return this._meta.Property}validate(e){return e!=null&&!Array.isArray(e)?{valid:!1,errors:[`${this.label} must be an array`]}:{valid:!0,errors:[]}}}class K extends m.BaseField{constructor(e){super(e)}get properties(){return this._meta.Property}validate(e){return e==null?{valid:!0,errors:[]}:typeof e!="object"||Array.isArray(e)?{valid:!1,errors:[`${this.label} must be a valid object`]}:{valid:!0,errors:[]}}}class O extends m.BaseField{constructor(e){super(e)}get format(){var e;return((e=this._meta.Constraint)==null?void 0:e.Format)??"Plain"}validate(e){return e!=null&&typeof e!="string"?{valid:!1,errors:[`${this.label} must be a string`]}:{valid:!0,errors:[]}}}class W extends m.BaseField{constructor(e){super(e)}validate(e){if(e==null)return{valid:!0,errors:[]};if(!Array.isArray(e))return{valid:!1,errors:[`${this.label} must be an array of file objects`]};for(const t of e)if(!t||typeof t!="object"||!t._id)return{valid:!1,errors:[`Each file in ${this.label} must have an _id`]};return{valid:!0,errors:[]}}}class Q extends m.BaseField{constructor(e){super(e)}validate(e){return e==null?{valid:!0,errors:[]}:typeof e!="object"||Array.isArray(e)?{valid:!1,errors:[`${this.label} must be a valid image object`]}:!e._id||!e.FileName?{valid:!1,errors:[`${this.label} must have _id and FileName`]}:{valid:!0,errors:[]}}}exports.BaseField=m.BaseField;exports.SystemField=C.SystemField;exports.ArrayField=X;exports.BaseBdo=Y;exports.BooleanField=J;exports.DateField=k;exports.DateTimeField=E;exports.FileField=W;exports.ImageField=Q;exports.NumberField=z;exports.ObjectField=K;exports.ReferenceField=H;exports.SelectField=G;exports.StringField=F;exports.TextAreaField=O;exports.TextField=O;exports.UserField=T;
|
package/dist/bdo.mjs
CHANGED
|
@@ -3,7 +3,7 @@ var U = (r, e, t) => e in r ? S(r, e, { enumerable: !0, configurable: !0, writab
|
|
|
3
3
|
var c = (r, e, t) => U(r, typeof e != "symbol" ? e + "" : e, t);
|
|
4
4
|
import { a as i } from "./client-CMERmrC-.js";
|
|
5
5
|
import { B as f } from "./BaseField-B6da88U7.js";
|
|
6
|
-
import { d as se } from "./constants-
|
|
6
|
+
import { d as se } from "./constants-ConHc1oS.js";
|
|
7
7
|
const C = /* @__PURE__ */ new Set([
|
|
8
8
|
"jpg",
|
|
9
9
|
"jpeg",
|
|
@@ -30,7 +30,9 @@ const t = {
|
|
|
30
30
|
/** Minimum string length */
|
|
31
31
|
MinLength: "MinLength",
|
|
32
32
|
/** Maximum string length */
|
|
33
|
-
MaxLength: "MaxLength"
|
|
33
|
+
MaxLength: "MaxLength",
|
|
34
|
+
/** Exact length (array) */
|
|
35
|
+
Length: "Length"
|
|
34
36
|
}, n = {
|
|
35
37
|
/** All conditions must match */
|
|
36
38
|
And: "And",
|
|
@@ -41,8 +43,8 @@ const t = {
|
|
|
41
43
|
}, e = {
|
|
42
44
|
/** Literal constant value */
|
|
43
45
|
Constant: "Constant",
|
|
44
|
-
/** Reference another field */
|
|
45
|
-
|
|
46
|
+
/** Reference another BDO field */
|
|
47
|
+
BDOField: "BDOField",
|
|
46
48
|
/** Reference app variable */
|
|
47
49
|
AppVariable: "AppVariable"
|
|
48
50
|
}, o = {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const t={EQ:"EQ",NE:"NE",GT:"GT",GTE:"GTE",LT:"LT",LTE:"LTE",Between:"Between",NotBetween:"NotBetween",IN:"IN",NIN:"NIN",Empty:"Empty",NotEmpty:"NotEmpty",Contains:"Contains",NotContains:"NotContains",MinLength:"MinLength",MaxLength:"MaxLength",Length:"Length"},e={And:"And",Or:"Or",Not:"Not"},n={Constant:"Constant",BDOField:"BDOField",AppVariable:"AppVariable"},o={ASC:"ASC",DESC:"DESC"},i={Sum:"Sum",Avg:"Avg",Count:"Count",Max:"Max",Min:"Min",DistinctCount:"DistinctCount",BlankCount:"BlankCount",NotBlankCount:"NotBlankCount",Concat:"Concat",DistinctConcat:"DistinctConcat"},a={List:"List",Metric:"Metric",Pivot:"Pivot"},c={Create:"create",Update:"update"},r={Interactive:"interactive",NonInteractive:"non-interactive"},s={OnBlur:"onBlur",OnChange:"onChange",OnSubmit:"onSubmit",OnTouched:"onTouched",All:"all"},d={Loading:"loading",Authenticated:"authenticated",Unauthenticated:"unauthenticated"},u={Google:"google",Microsoft:"microsoft",GitHub:"github",Custom:"custom"},C={Id:"_id",CreatedAt:"_created_at",ModifiedAt:"_modified_at",CreatedBy:"_created_by",ModifiedBy:"_modified_by",Version:"_version",MergeVersion:"_m_version"},E={GET:"GET",POST:"POST",PATCH:"PATCH",DELETE:"DELETE"},p={SEARCH_DEBOUNCE_MS:300,PAGE_SIZE:10,PAGE:1,SEARCH_MAX_LENGTH:255},T={Date:"$__d__",DateTime:"$__dt__"},l={Success:"success"};exports.AuthProviderName=u;exports.AuthStatus=d;exports.ConditionOperator=t;exports.DateEncodingKey=T;exports.Defaults=p;exports.DeleteStatus=l;exports.FormOperation=c;exports.GroupOperator=e;exports.HttpMethod=E;exports.InteractionMode=r;exports.MetricType=i;exports.QueryType=a;exports.RHSType=n;exports.SortDirection=o;exports.SystemField=C;exports.ValidationMode=s;
|
package/dist/filter.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./useFilter-Bg0jvIL6.cjs"),e=require("./constants-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./useFilter-Bg0jvIL6.cjs"),e=require("./constants-QX2RX-wu.cjs");exports.isCondition=o.isCondition;exports.isConditionGroup=o.isConditionGroup;exports.useFilter=o.useFilter;exports.ConditionOperator=e.ConditionOperator;exports.FilterValueSource=e.RHSType;exports.GroupOperator=e.GroupOperator;
|
package/dist/filter.mjs
CHANGED
package/dist/form.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("./constants-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("./constants-QX2RX-wu.cjs"),M=require("react"),j=require("./index.esm-DuwT11sx.cjs"),w=require("@tanstack/react-query"),B=require("./metadata-BfJtHz84.cjs");function P(s,e){const r=[];if(s.required&&(e==null||e===""||Array.isArray(e)&&e.length===0))return r.push(`${s.label} is required`),{valid:!1,errors:r};if(e==null||e==="")return{valid:!0,errors:[]};if("length"in s&&typeof s.length=="number"&&typeof e=="string"&&e.length>s.length&&r.push(`${s.label} must be at most ${s.length} characters`),"integerPart"in s&&typeof e=="number"){const o=Math.floor(Math.abs(e)),c=s.integerPart??9;o.toString().length>c&&r.push(`${s.label} integer part must be at most ${c} digits`);const t=s.fractionPart;t!==void 0&&(e.toString().split(".")[1]??"").length>t&&r.push(`${s.label} can have at most ${t} decimal places`)}return r.length>0?{valid:!1,errors:r}:{valid:!0,errors:[]}}function C(s,e){return async(r,o,c)=>{var v;const t={},a=s.getFields(),m=(c==null?void 0:c.names)??Object.keys(a);for(const n of m){if(n==="_id"||(v=a[n])!=null&&v.readOnly)continue;const f=a[n];if(!f)continue;const d=r[n],u=f.validate(d);if(!u.valid&&u.errors.length>0){t[n]={type:"validate",message:u.errors[0]||`${n} is invalid`};continue}if((e==null?void 0:e.enableConstraintValidation)!==!1){const l=P(f,d);if(!l.valid&&l.errors.length>0){t[n]={type:"constraint",message:l.errors[0]};continue}}if(s.hasMetadata()){const l=s.validateFieldExpression(n,d,r);!l.valid&&l.errors.length>0&&(t[n]={type:"validate",message:l.errors[0]})}}return Object.keys(t).length===0?{values:r,errors:{}}:{values:{},errors:t}}}function J(s,e){const r=s.getFields(),o=new Map;return new Proxy({},{get(c,t){if(typeof t=="symbol")return;if(t==="_id")return e.getValues("_id");if(t==="toJSON")return()=>e.getValues();if(t==="validate")return()=>e.trigger();if(o.has(t))return o.get(t);const a=r[t],m=(a==null?void 0:a.meta)??{_id:t,Name:t,Type:"String"},v=(a==null?void 0:a.readOnly)??!1,n=()=>{if(!a)return{valid:!0,errors:[]};const u=e.getValues(t),l=a.validate(u);if(!l.valid)return l;const R=P(a,u);if(!R.valid)return R;if(s.hasMetadata()){const g=s.validateFieldExpression(t,u,e.getValues());if(!g.valid)return g}return{valid:!0,errors:[]}},f=u=>{const l=e.getValues(t);return l??u};if(!v){const u={label:(a==null?void 0:a.label)??t,required:(a==null?void 0:a.required)??!1,readOnly:!1,defaultValue:a==null?void 0:a.defaultValue,meta:m,get:()=>e.getValues(t),getOrDefault:f,set:l=>{e.setValue(t,l,{shouldDirty:!0,shouldTouch:!0,shouldValidate:!1})},validate:n};return o.set(t,u),u}const d={label:(a==null?void 0:a.label)??t,required:(a==null?void 0:a.required)??!1,readOnly:!0,defaultValue:a==null?void 0:a.defaultValue,meta:m,get:()=>e.getValues(t),getOrDefault:f,validate:n};return o.set(t,d),d},has(c,t){return typeof t=="symbol"?!1:t==="_id"||t==="toJSON"||t==="validate"?!0:t in r},ownKeys(c){return[...Object.keys(r),"_id","toJSON","validate"]},getOwnPropertyDescriptor(c,t){if(typeof t!="symbol")return{configurable:!0,enumerable:t!=="toJSON"&&t!=="validate"}}})}function F(s){const{bdo:e,recordId:r,operation:o,defaultValues:c,mode:t="onBlur",enableDraft:a=!1,enableConstraintValidation:m,enableExpressionValidation:v}=s,n=o??(r?"update":"create"),f=M.useMemo(()=>C(e,{enableConstraintValidation:m}),[e,m]),{data:d,isLoading:u,isFetching:l,error:R}=w.useQuery({queryKey:["form-record",e.meta._id,r],queryFn:async()=>(await e.get(r)).toJSON(),enabled:n==="update"&&!!r,staleTime:0}),{data:g}=w.useQuery({queryKey:["form-schema",e.meta._id],queryFn:()=>B.getBdoSchema(e.meta._id),staleTime:30*60*1e3,gcTime:60*60*1e3,enabled:v!==!1});M.useEffect(()=>{g!=null&&g.BDOBlob&&e.loadMetadata(g.BDOBlob)},[g,e]);const i=j.useForm({mode:t,resolver:f,defaultValues:c,values:n==="update"&&d?d:void 0}),$=M.useMemo(()=>J(e,i),[e,i]),h=e.getFields(),k=M.useCallback((S,y)=>{var b;const V=i.register(S,y);return(b=h[S])!=null&&b.readOnly?{...V,disabled:!0}:V},[i,h]),N=M.useCallback((S,y)=>i.handleSubmit(async(V,b)=>{try{const O={};if(n==="create")for(const[q,_]of Object.entries(V))h[q]&&!h[q].readOnly&&(O[q]=_);else{const q=i.formState.dirtyFields;for(const[_,T]of Object.entries(V))h[_]&&!h[_].readOnly&&q[_]&&(O[_]=T)}let x;n==="create"?x=await e.create(O):x=await e.update(r,O),S==null||S(x,b)}catch(O){y==null||y(O,b)}},(V,b)=>{y==null||y(V,b)}),[i,e,n,r,h]);return{item:$,bdo:e,operation:n,recordId:r,register:k,handleSubmit:N,watch:i.watch,setValue:i.setValue,getValues:i.getValues,reset:i.reset,trigger:i.trigger,control:i.control,formState:i.formState,errors:i.formState.errors,isDirty:i.formState.isDirty,isValid:i.formState.isValid,isSubmitting:i.formState.isSubmitting,isSubmitSuccessful:i.formState.isSubmitSuccessful,dirtyFields:i.formState.dirtyFields,isLoading:u,isFetching:l,loadError:R}}exports.FormOperation=D.FormOperation;exports.InteractionMode=D.InteractionMode;exports.ValidationMode=D.ValidationMode;exports.useForm=F;
|
package/dist/form.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as H, I as U, V as W } from "./constants-
|
|
1
|
+
import { F as H, I as U, V as W } from "./constants-ConHc1oS.js";
|
|
2
2
|
import { useMemo as q, useEffect as T, useCallback as M } from "react";
|
|
3
3
|
import { u as j } from "./index.esm-Cj63v5ny.js";
|
|
4
4
|
import { useQuery as w } from "@tanstack/react-query";
|
package/dist/table.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react"),L=require("@tanstack/react-query"),G=require("./client-BnVxSHAm.cjs"),C=require("./error-handling-CAoD0Kwb.cjs"),oe=require("./useFilter-Bg0jvIL6.cjs"),l=require("./constants-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react"),L=require("@tanstack/react-query"),G=require("./client-BnVxSHAm.cjs"),C=require("./error-handling-CAoD0Kwb.cjs"),oe=require("./useFilter-Bg0jvIL6.cjs"),l=require("./constants-QX2RX-wu.cjs");function ne(o){var A,D,R,z,M,P,Q,w;const[a,h]=r.useState({query:"",debouncedQuery:"",field:null}),c=r.useRef(null),j=300,I=()=>{var t,n;const e=(t=o.initialState)==null?void 0:t.sort;if(e&&e.length>0){const H=e[0],x=Object.keys(H)[0],T=(n=H[x])==null?void 0:n.toUpperCase();return{field:x,direction:T==="ASC"||T==="DESC"?T:"ASC"}}return{field:null,direction:null}},[s,b]=r.useState(I),[i,u]=r.useState({pageNo:((D=(A=o.initialState)==null?void 0:A.pagination)==null?void 0:D.pageNo)||1,pageSize:((z=(R=o.initialState)==null?void 0:R.pagination)==null?void 0:z.pageSize)||10}),d=oe.useFilter({conditions:(P=(M=o.initialState)==null?void 0:M.filter)==null?void 0:P.conditions,operator:((w=(Q=o.initialState)==null?void 0:Q.filter)==null?void 0:w.operator)||"And"});r.useEffect(()=>{u(e=>({...e,pageNo:1}))},[d.payload]);const g=r.useMemo(()=>{const e={};let t=d.payload;if(a.debouncedQuery&&a.field){const n={LHSField:a.field,Operator:"Contains",RHSValue:a.debouncedQuery,RHSType:"Constant"};t?t.Operator==="And"?t={...t,Condition:[...t.Condition||[],n]}:t={Operator:"And",Condition:[t,n]}:t={Operator:"And",Condition:[n]}}return t&&(e.Filter=t),e},[a.debouncedQuery,a.field,d.payload]),E=r.useMemo(()=>{const e={...g};return s.field&&s.direction&&(e.Sort=[{[String(s.field)]:s.direction}]),e.Page=i.pageNo,e.PageSize=i.pageSize,e},[g,s,i]),{data:f,isLoading:K,isFetching:U,error:q,refetch:O}=L.useQuery({queryKey:["table",o.source,E],queryFn:async()=>{try{const e=await G.api(o.source).list(E);return o.onSuccess&&o.onSuccess(e.Data),e}catch(e){throw o.onError&&o.onError(C.toError(e)),e}},staleTime:0,gcTime:30*1e3}),{data:S,isLoading:_,isFetching:B,error:F,refetch:k}=L.useQuery({queryKey:["table-count",o.source,g],queryFn:async()=>{try{return await G.api(o.source).count(g)}catch(e){throw o.onError&&o.onError(C.toError(e)),e}},staleTime:0,gcTime:30*1e3}),V=r.useMemo(()=>(f==null?void 0:f.Data)||[],[f]),p=r.useMemo(()=>(S==null?void 0:S.Count)||0,[S]),y=r.useMemo(()=>Math.ceil(p/i.pageSize),[p,i.pageSize]),J=r.useCallback(e=>{b(t=>{if(t.field===e){if(t.direction==="ASC")return{field:e,direction:"DESC"};if(t.direction==="DESC")return{field:null,direction:null}}return{field:e,direction:"ASC"}})},[]),W=r.useCallback(()=>{b({field:null,direction:null})},[]),X=r.useCallback((e,t)=>{b({field:e,direction:t})},[]),Y=r.useCallback((e,t)=>{if(t.length>255){console.warn("Search query exceeds maximum length of 255 characters");return}h(n=>({...n,query:t,field:e})),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{h(n=>({...n,debouncedQuery:t})),u(n=>({...n,pageNo:1}))},j)},[]),Z=r.useCallback(()=>{c.current&&clearTimeout(c.current),h({query:"",debouncedQuery:"",field:null}),u(e=>({...e,pageNo:1}))},[]);r.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]);const m=i.pageNo<y,N=i.pageNo>1,$=r.useCallback(()=>{m&&u(e=>({...e,pageNo:e.pageNo+1}))},[m]),v=r.useCallback(()=>{N&&u(e=>({...e,pageNo:e.pageNo-1}))},[N]),ee=r.useCallback(e=>{const t=Math.max(1,Math.min(e,y));u(n=>({...n,pageNo:t}))},[y]),te=r.useCallback(e=>{u(t=>({...t,pageSize:e,pageNo:1}))},[]),re=r.useCallback(async()=>{const[e]=await Promise.all([O(),k()]);return e.data||{Data:[]}},[O,k]);return{rows:V,totalItems:p,isLoading:K||_,isFetching:U||B,error:q?C.toError(q):F?C.toError(F):null,search:{query:a.query,field:a.field,set:Y,clear:Z},sort:{field:s.field,direction:s.direction,toggle:J,clear:W,set:X},filter:d,pagination:{pageNo:i.pageNo,pageSize:i.pageSize,totalPages:y,totalItems:p,canGoNext:m,canGoPrevious:N,goToNext:$,goToPrevious:v,goToPage:ee,setPageSize:te},refetch:re}}exports.ConditionOperator=l.ConditionOperator;exports.GroupOperator=l.GroupOperator;exports.RHSType=l.RHSType;exports.SortDirection=l.SortDirection;exports.TableDefaults=l.Defaults;exports.useTable=ne;
|
package/dist/table.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { useQuery as I } from "@tanstack/react-query";
|
|
|
3
3
|
import { a as K } from "./client-CMERmrC-.js";
|
|
4
4
|
import { t as h } from "./error-handling-CrhTtD88.js";
|
|
5
5
|
import { u as ae } from "./useFilter-DPNLKY3H.js";
|
|
6
|
-
import { C as ye, G as he, R as me, S as Ce, D as Ne } from "./constants-
|
|
6
|
+
import { C as ye, G as he, R as me, S as Ce, D as Ne } from "./constants-ConHc1oS.js";
|
|
7
7
|
function fe(r) {
|
|
8
8
|
var R, P, q, w, Q, x, H, L;
|
|
9
9
|
const [a, m] = E({
|
|
@@ -47,6 +47,8 @@ export declare const ConditionOperator: {
|
|
|
47
47
|
readonly MinLength: "MinLength";
|
|
48
48
|
/** Maximum string length */
|
|
49
49
|
readonly MaxLength: "MaxLength";
|
|
50
|
+
/** Exact length (array) */
|
|
51
|
+
readonly Length: "Length";
|
|
50
52
|
};
|
|
51
53
|
/**
|
|
52
54
|
* Group/Logical operators for combining conditions
|
|
@@ -79,13 +81,13 @@ export declare const GroupOperator: {
|
|
|
79
81
|
* { RHSType: RHSType.Constant, RHSValue: 100 }
|
|
80
82
|
*
|
|
81
83
|
* // Compare against another field
|
|
82
|
-
* { RHSType: RHSType.
|
|
84
|
+
* { RHSType: RHSType.BDOField, RHSValue: "otherField" }
|
|
83
85
|
*/
|
|
84
86
|
export declare const RHSType: {
|
|
85
87
|
/** Literal constant value */
|
|
86
88
|
readonly Constant: "Constant";
|
|
87
|
-
/** Reference another field */
|
|
88
|
-
readonly
|
|
89
|
+
/** Reference another BDO field */
|
|
90
|
+
readonly BDOField: "BDOField";
|
|
89
91
|
/** Reference app variable */
|
|
90
92
|
readonly AppVariable: "AppVariable";
|
|
91
93
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../sdk/types/constants.ts"],"names":[],"mappings":"AASA;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,iBAAiB;IAC5B,YAAY;;IAEZ,gBAAgB;;IAEhB,mBAAmB;;IAEnB,4BAA4B;;IAE5B,gBAAgB;;IAEhB,yBAAyB;;IAEzB,yBAAyB;;IAEzB,0BAA0B;;IAE1B,oBAAoB;;IAEpB,wBAAwB;;IAExB,0BAA0B;;IAE1B,yBAAyB;;IAEzB,gCAAgC;;IAEhC,wCAAwC;;IAExC,4BAA4B;;IAE5B,4BAA4B;;
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../sdk/types/constants.ts"],"names":[],"mappings":"AASA;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,iBAAiB;IAC5B,YAAY;;IAEZ,gBAAgB;;IAEhB,mBAAmB;;IAEnB,4BAA4B;;IAE5B,gBAAgB;;IAEhB,yBAAyB;;IAEzB,yBAAyB;;IAEzB,0BAA0B;;IAE1B,oBAAoB;;IAEpB,wBAAwB;;IAExB,0BAA0B;;IAE1B,yBAAyB;;IAEzB,gCAAgC;;IAEhC,wCAAwC;;IAExC,4BAA4B;;IAE5B,4BAA4B;;IAE5B,2BAA2B;;CAEnB,CAAC;AAEX;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,aAAa;IACxB,gCAAgC;;IAEhC,8BAA8B;;IAE9B,2BAA2B;;CAEnB,CAAC;AAEX;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,OAAO;IAClB,6BAA6B;;IAE7B,kCAAkC;;IAElC,6BAA6B;;CAErB,CAAC;AAMX;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa;IACxB,sBAAsB;;IAEtB,uBAAuB;;CAEf,CAAC;AAMX;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,UAAU;IACrB,oBAAoB;;IAEpB,wBAAwB;;IAExB,uBAAuB;;IAEvB,oBAAoB;;IAEpB,oBAAoB;;IAEpB,6BAA6B;;IAE7B,iCAAiC;;IAEjC,gCAAgC;;IAEhC,yBAAyB;;IAEzB,kCAAkC;;CAE1B,CAAC;AAMX;;GAEG;AACH,eAAO,MAAM,SAAS;IACpB,iBAAiB;;IAEjB,+BAA+B;;IAE/B,wBAAwB;;CAEhB,CAAC;AAMX;;;;;;;;;;GAUG;AACH,eAAO,MAAM,aAAa;IACxB,wBAAwB;;IAExB,6BAA6B;;CAErB,CAAC;AAEX;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,eAAe;IAC1B,2EAA2E;;IAE3E,iDAAiD;;CAEzC,CAAC;AAEX;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,cAAc;IACzB,iCAAiC;;IAEjC,yBAAyB;;IAEzB,8BAA8B;;IAE9B,6CAA6C;;IAE7C,kCAAkC;;CAE1B,CAAC;AAMX;;GAEG;AACH,eAAO,MAAM,YAAY;IACvB,6BAA6B;;IAE7B,4BAA4B;;IAE5B,oBAAoB;;IAEpB,oBAAoB;;IAEpB,sBAAsB;;IAEtB,0BAA0B;;IAE1B,+BAA+B;;IAE/B,2BAA2B;;IAE3B,4BAA4B;;IAE5B,0BAA0B;;IAE1B,kBAAkB;;IAElB,mBAAmB;;IAEnB,4BAA4B;;IAE5B,6BAA6B;;CAErB,CAAC;AAEX;;GAEG;AACH,eAAO,MAAM,aAAa;IACxB,iBAAiB;;IAEjB,mBAAmB;;IAEnB,kBAAkB;;IAElB,qBAAqB;;IAErB,kBAAkB;;IAElB,sBAAsB;;IAEtB,eAAe;;IAEf,sBAAsB;;IAEtB,sBAAsB;;IAEtB,sBAAsB;;IAEtB,sBAAsB;;IAEtB,uBAAuB;;CAEf,CAAC;AAEX;;GAEG;AACH,eAAO,MAAM,WAAW;IACtB,2CAA2C;;IAE3C,2CAA2C;;CAEnC,CAAC;AAMX;;;;;;;;;;GAUG;AACH,eAAO,MAAM,UAAU;IACrB,kCAAkC;;IAElC,wBAAwB;;IAExB,4BAA4B;;CAEpB,CAAC;AAEX;;GAEG;AACH,eAAO,MAAM,gBAAgB;;;;;CAKnB,CAAC;AAMX;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,WAAW;IACtB,kBAAkB;;IAElB,yBAAyB;;IAEzB,8BAA8B;;IAE9B,mBAAmB;;IAEnB,yBAAyB;;IAEzB,qBAAqB;;IAErB,oBAAoB;;CAEZ,CAAC;AAMX;;GAEG;AACH,eAAO,MAAM,UAAU;IACrB,kBAAkB;;IAElB,mBAAmB;;IAEnB,oBAAoB;;IAEpB,qBAAqB;;CAEb,CAAC;AAMX;;;;;;;GAOG;AACH,eAAO,MAAM,QAAQ;IACnB,gDAAgD;;IAEhD,6BAA6B;;IAE7B,sCAAsC;;IAEtC,kCAAkC;;CAE1B,CAAC;AAMX;;;;;;;;;;GAUG;AACH,eAAO,MAAM,eAAe;IAC1B,yDAAyD;;IAEzD,gEAAgE;;CAExD,CAAC;AAMX;;GAEG;AACH,eAAO,MAAM,YAAY;IACvB,0BAA0B;;CAElB,CAAC"}
|
package/docs/api.md
CHANGED
package/docs/useFilter.md
CHANGED
|
@@ -59,7 +59,7 @@ GroupOperator.Not // "Not"
|
|
|
59
59
|
|
|
60
60
|
// RHS types
|
|
61
61
|
RHSType.Constant // "Constant"
|
|
62
|
-
RHSType.
|
|
62
|
+
RHSType.BDOField // "BDOField"
|
|
63
63
|
RHSType.AppVariable // "AppVariable"
|
|
64
64
|
```
|
|
65
65
|
|
|
@@ -103,7 +103,7 @@ interface ConditionType<T = any> {
|
|
|
103
103
|
RHSValue: any;
|
|
104
104
|
|
|
105
105
|
// Value type (default: "Constant")
|
|
106
|
-
RHSType?: "Constant" | "
|
|
106
|
+
RHSType?: "Constant" | "BDOField" | "AppVariable";
|
|
107
107
|
}
|
|
108
108
|
|
|
109
109
|
// Condition group (can contain conditions or nested groups)
|
|
@@ -198,8 +198,9 @@ interface UseFilterReturnType<T = any> {
|
|
|
198
198
|
| Between, NotBetween | number, date, currency |
|
|
199
199
|
| IN, NIN | All types |
|
|
200
200
|
| Empty, NotEmpty | All types |
|
|
201
|
-
| Contains, NotContains | string
|
|
202
|
-
| MinLength, MaxLength | string
|
|
201
|
+
| Contains, NotContains | string, reference/user (with dot notation) |
|
|
202
|
+
| MinLength, MaxLength | string, array |
|
|
203
|
+
| Length | array |
|
|
203
204
|
|
|
204
205
|
## Basic Example
|
|
205
206
|
|
|
@@ -621,6 +622,174 @@ function EmptyFilters() {
|
|
|
621
622
|
|
|
622
623
|
---
|
|
623
624
|
|
|
625
|
+
## Filtering Reference & User Fields
|
|
626
|
+
|
|
627
|
+
Reference and User fields are stored as JSON objects (`{ _id, _name, ... }`). The backend automatically targets the `_id` sub-field when filtering these fields. User and Reference fields behave identically for filtering.
|
|
628
|
+
|
|
629
|
+
### Supported Operators
|
|
630
|
+
|
|
631
|
+
| Operator | Supported | Notes |
|
|
632
|
+
| --- | --- | --- |
|
|
633
|
+
| EQ, NE | Yes | Compares against `_id` by default |
|
|
634
|
+
| IN, NIN | Yes | List of IDs |
|
|
635
|
+
| Empty, NotEmpty | Yes | Checks if field is null/unset |
|
|
636
|
+
| Contains, NotContains | Only with dot notation | e.g., `"Vendor._name"` |
|
|
637
|
+
| GT, GTE, LT, LTE, Between | No | Raises backend error |
|
|
638
|
+
|
|
639
|
+
### Filter by ID (Default)
|
|
640
|
+
|
|
641
|
+
When filtering a Reference or User field, pass the `_id` string directly as `RHSValue`. The backend automatically compares against the `_id` sub-field.
|
|
642
|
+
|
|
643
|
+
```tsx
|
|
644
|
+
import { useMemo } from "react";
|
|
645
|
+
import { useFilter, ConditionOperator, RHSType } from "@ram_28/kf-ai-sdk/filter";
|
|
646
|
+
import { AdminCartItem } from "../bdo/admin/CartItem";
|
|
647
|
+
|
|
648
|
+
function ReferenceFilter() {
|
|
649
|
+
const cartItem = useMemo(() => new AdminCartItem(), []);
|
|
650
|
+
const filter = useFilter();
|
|
651
|
+
|
|
652
|
+
// Filter cart items by a specific product ID
|
|
653
|
+
const filterByProduct = (productId: string) => {
|
|
654
|
+
filter.addCondition({
|
|
655
|
+
Operator: ConditionOperator.EQ,
|
|
656
|
+
LHSField: cartItem.ProductInfo.id,
|
|
657
|
+
RHSValue: productId,
|
|
658
|
+
RHSType: RHSType.Constant,
|
|
659
|
+
});
|
|
660
|
+
};
|
|
661
|
+
|
|
662
|
+
// Filter by multiple product IDs
|
|
663
|
+
const filterByProducts = (productIds: string[]) => {
|
|
664
|
+
filter.addCondition({
|
|
665
|
+
Operator: ConditionOperator.IN,
|
|
666
|
+
LHSField: cartItem.ProductInfo.id,
|
|
667
|
+
RHSValue: productIds,
|
|
668
|
+
RHSType: RHSType.Constant,
|
|
669
|
+
});
|
|
670
|
+
};
|
|
671
|
+
|
|
672
|
+
// Filter unassigned items (reference is empty)
|
|
673
|
+
const filterUnlinked = () => {
|
|
674
|
+
filter.addCondition({
|
|
675
|
+
Operator: ConditionOperator.Empty,
|
|
676
|
+
LHSField: cartItem.ProductInfo.id,
|
|
677
|
+
RHSValue: null,
|
|
678
|
+
RHSType: RHSType.Constant,
|
|
679
|
+
});
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
return (
|
|
683
|
+
<div>
|
|
684
|
+
<button onClick={() => filterByProduct("PROD_001")}>
|
|
685
|
+
Filter by Product
|
|
686
|
+
</button>
|
|
687
|
+
<button onClick={() => filterByProducts(["PROD_001", "PROD_002"])}>
|
|
688
|
+
Filter by Multiple
|
|
689
|
+
</button>
|
|
690
|
+
<button onClick={filterUnlinked}>Unlinked Items</button>
|
|
691
|
+
</div>
|
|
692
|
+
);
|
|
693
|
+
}
|
|
694
|
+
```
|
|
695
|
+
|
|
696
|
+
### Filter by Name (Dot Notation)
|
|
697
|
+
|
|
698
|
+
Use dot notation in `LHSField` to filter on a nested sub-field like `_name`. This skips the default `_id` targeting and compares against the specified path.
|
|
699
|
+
|
|
700
|
+
```tsx
|
|
701
|
+
import { useMemo } from "react";
|
|
702
|
+
import { useFilter, ConditionOperator, RHSType } from "@ram_28/kf-ai-sdk/filter";
|
|
703
|
+
import { AdminCartItem } from "../bdo/admin/CartItem";
|
|
704
|
+
|
|
705
|
+
function ReferenceNameFilter() {
|
|
706
|
+
const cartItem = useMemo(() => new AdminCartItem(), []);
|
|
707
|
+
const filter = useFilter();
|
|
708
|
+
|
|
709
|
+
// Search product name within the reference field
|
|
710
|
+
const searchProductName = (name: string) => {
|
|
711
|
+
filter.addCondition({
|
|
712
|
+
Operator: ConditionOperator.Contains,
|
|
713
|
+
LHSField: `${cartItem.ProductInfo.id}._name`,
|
|
714
|
+
RHSValue: name,
|
|
715
|
+
RHSType: RHSType.Constant,
|
|
716
|
+
});
|
|
717
|
+
};
|
|
718
|
+
|
|
719
|
+
return (
|
|
720
|
+
<input
|
|
721
|
+
placeholder="Search by product name..."
|
|
722
|
+
onKeyDown={(e) => {
|
|
723
|
+
if (e.key === "Enter") {
|
|
724
|
+
searchProductName((e.target as HTMLInputElement).value);
|
|
725
|
+
}
|
|
726
|
+
}}
|
|
727
|
+
/>
|
|
728
|
+
);
|
|
729
|
+
}
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
### Filter System User Fields
|
|
733
|
+
|
|
734
|
+
System fields `_created_by` and `_modified_by` are User fields. Filter them the same way.
|
|
735
|
+
|
|
736
|
+
```tsx
|
|
737
|
+
import { useFilter, ConditionOperator, RHSType } from "@ram_28/kf-ai-sdk/filter";
|
|
738
|
+
|
|
739
|
+
function UserFieldFilter() {
|
|
740
|
+
const filter = useFilter();
|
|
741
|
+
|
|
742
|
+
// Filter by creator (using user's _id)
|
|
743
|
+
const filterByCreator = (userId: string) => {
|
|
744
|
+
filter.addCondition({
|
|
745
|
+
Operator: ConditionOperator.EQ,
|
|
746
|
+
LHSField: "_created_by",
|
|
747
|
+
RHSValue: userId,
|
|
748
|
+
RHSType: RHSType.Constant,
|
|
749
|
+
});
|
|
750
|
+
};
|
|
751
|
+
|
|
752
|
+
// Search by creator name
|
|
753
|
+
const searchByCreatorName = (name: string) => {
|
|
754
|
+
filter.addCondition({
|
|
755
|
+
Operator: ConditionOperator.Contains,
|
|
756
|
+
LHSField: "_created_by._name",
|
|
757
|
+
RHSValue: name,
|
|
758
|
+
RHSType: RHSType.Constant,
|
|
759
|
+
});
|
|
760
|
+
};
|
|
761
|
+
|
|
762
|
+
return (
|
|
763
|
+
<div>
|
|
764
|
+
<button onClick={() => filterByCreator("USR_001")}>My Items</button>
|
|
765
|
+
<input
|
|
766
|
+
placeholder="Search by creator..."
|
|
767
|
+
onKeyDown={(e) => {
|
|
768
|
+
if (e.key === "Enter") {
|
|
769
|
+
searchByCreatorName((e.target as HTMLInputElement).value);
|
|
770
|
+
}
|
|
771
|
+
}}
|
|
772
|
+
/>
|
|
773
|
+
</div>
|
|
774
|
+
);
|
|
775
|
+
}
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
### RHSValue Formats
|
|
779
|
+
|
|
780
|
+
The backend accepts multiple `RHSValue` formats for Reference/User fields:
|
|
781
|
+
|
|
782
|
+
| Format | Example | When to use |
|
|
783
|
+
| --- | --- | --- |
|
|
784
|
+
| String ID | `"PROD_001"` | Simplest — use when you have the ID |
|
|
785
|
+
| Object with `_id` | `{ _id: "PROD_001", _name: "Widget" }` | Backend extracts `_id` automatically |
|
|
786
|
+
| Array of IDs | `["PROD_001", "PROD_002"]` | With `IN` / `NIN` operators |
|
|
787
|
+
| Array of objects | `[{ _id: "PROD_001" }, { _id: "PROD_002" }]` | With `IN` / `NIN` — backend extracts each `_id` |
|
|
788
|
+
|
|
789
|
+
> **Tip:** Prefer passing the string ID directly. Passing the full object works but adds unnecessary payload size.
|
|
790
|
+
|
|
791
|
+
---
|
|
792
|
+
|
|
624
793
|
## Condition Groups
|
|
625
794
|
|
|
626
795
|
### AND Logic
|
|
@@ -1319,7 +1488,93 @@ Produces:
|
|
|
1319
1488
|
}
|
|
1320
1489
|
```
|
|
1321
1490
|
|
|
1322
|
-
> **Note:** The `RHSType` field defaults to `"Constant"` and is automatically added to the payload. Other possible values are `"
|
|
1491
|
+
> **Note:** The `RHSType` field defaults to `"Constant"` and is automatically added to the payload. Other possible values are `"BDOField"` (reference another BDO field) and `"AppVariable"` (reference an application variable).
|
|
1492
|
+
|
|
1493
|
+
### Reference Field (EQ)
|
|
1494
|
+
|
|
1495
|
+
```tsx
|
|
1496
|
+
import { ConditionOperator, RHSType } from "@ram_28/kf-ai-sdk/filter";
|
|
1497
|
+
|
|
1498
|
+
filter.addCondition({
|
|
1499
|
+
Operator: ConditionOperator.EQ,
|
|
1500
|
+
LHSField: cartItem.ProductInfo.id,
|
|
1501
|
+
RHSValue: "PROD_001",
|
|
1502
|
+
RHSType: RHSType.Constant,
|
|
1503
|
+
});
|
|
1504
|
+
```
|
|
1505
|
+
|
|
1506
|
+
Produces:
|
|
1507
|
+
|
|
1508
|
+
```json
|
|
1509
|
+
{
|
|
1510
|
+
"Operator": "And",
|
|
1511
|
+
"Condition": [
|
|
1512
|
+
{
|
|
1513
|
+
"Operator": "EQ",
|
|
1514
|
+
"LHSField": "ProductInfo",
|
|
1515
|
+
"RHSValue": "PROD_001",
|
|
1516
|
+
"RHSType": "Constant"
|
|
1517
|
+
}
|
|
1518
|
+
]
|
|
1519
|
+
}
|
|
1520
|
+
```
|
|
1521
|
+
|
|
1522
|
+
### Reference Field Nested Path (Contains)
|
|
1523
|
+
|
|
1524
|
+
```tsx
|
|
1525
|
+
filter.addCondition({
|
|
1526
|
+
Operator: ConditionOperator.Contains,
|
|
1527
|
+
LHSField: `${cartItem.ProductInfo.id}._name`,
|
|
1528
|
+
RHSValue: "Widget",
|
|
1529
|
+
RHSType: RHSType.Constant,
|
|
1530
|
+
});
|
|
1531
|
+
```
|
|
1532
|
+
|
|
1533
|
+
Produces:
|
|
1534
|
+
|
|
1535
|
+
```json
|
|
1536
|
+
{
|
|
1537
|
+
"Operator": "And",
|
|
1538
|
+
"Condition": [
|
|
1539
|
+
{
|
|
1540
|
+
"Operator": "Contains",
|
|
1541
|
+
"LHSField": "ProductInfo._name",
|
|
1542
|
+
"RHSValue": "Widget",
|
|
1543
|
+
"RHSType": "Constant"
|
|
1544
|
+
}
|
|
1545
|
+
]
|
|
1546
|
+
}
|
|
1547
|
+
```
|
|
1548
|
+
|
|
1549
|
+
### Field-to-Field Comparison (BDOField)
|
|
1550
|
+
|
|
1551
|
+
Use `RHSType.BDOField` to compare one field against another field instead of a constant value.
|
|
1552
|
+
|
|
1553
|
+
```tsx
|
|
1554
|
+
// Filter where Quantity exceeds Stock (field vs field)
|
|
1555
|
+
filter.addCondition({
|
|
1556
|
+
Operator: ConditionOperator.GT,
|
|
1557
|
+
LHSField: cartItem.Quantity.id,
|
|
1558
|
+
RHSValue: cartItem.Stock.id,
|
|
1559
|
+
RHSType: RHSType.BDOField,
|
|
1560
|
+
});
|
|
1561
|
+
```
|
|
1562
|
+
|
|
1563
|
+
Produces:
|
|
1564
|
+
|
|
1565
|
+
```json
|
|
1566
|
+
{
|
|
1567
|
+
"Operator": "And",
|
|
1568
|
+
"Condition": [
|
|
1569
|
+
{
|
|
1570
|
+
"Operator": "GT",
|
|
1571
|
+
"LHSField": "Quantity",
|
|
1572
|
+
"RHSValue": "Stock",
|
|
1573
|
+
"RHSType": "BDOField"
|
|
1574
|
+
}
|
|
1575
|
+
]
|
|
1576
|
+
}
|
|
1577
|
+
```
|
|
1323
1578
|
|
|
1324
1579
|
---
|
|
1325
1580
|
|
|
@@ -1337,7 +1592,7 @@ Only three RHSType values exist. Any other string causes TS2322.
|
|
|
1337
1592
|
|
|
1338
1593
|
// ✅ CORRECT — only these three values
|
|
1339
1594
|
{ RHSType: RHSType.Constant } // "Constant"
|
|
1340
|
-
{ RHSType: RHSType.
|
|
1595
|
+
{ RHSType: RHSType.BDOField } // "BDOField"
|
|
1341
1596
|
{ RHSType: RHSType.AppVariable } // "AppVariable"
|
|
1342
1597
|
```
|
|
1343
1598
|
|
|
@@ -1387,3 +1642,21 @@ const conditions: Omit<ConditionType, "id">[] = [
|
|
|
1387
1642
|
{ Operator: ConditionOperator.EQ, ... }
|
|
1388
1643
|
];
|
|
1389
1644
|
```
|
|
1645
|
+
|
|
1646
|
+
### 5. Filtering Reference/User fields without _id
|
|
1647
|
+
|
|
1648
|
+
The backend automatically targets `_id` when you filter a Reference or User field by name. Do NOT manually append `._id` unless you specifically want to bypass the backend's auto-extraction.
|
|
1649
|
+
|
|
1650
|
+
```typescript
|
|
1651
|
+
// ❌ WRONG — unnecessary, and disables auto-extraction of _id from objects
|
|
1652
|
+
{ LHSField: "ProductInfo._id", Operator: "EQ", RHSValue: { _id: "P1", _name: "Widget" } }
|
|
1653
|
+
|
|
1654
|
+
// ✅ CORRECT — backend auto-targets _id
|
|
1655
|
+
{ LHSField: "ProductInfo", Operator: "EQ", RHSValue: "P1" }
|
|
1656
|
+
|
|
1657
|
+
// ✅ CORRECT — backend extracts _id from the object
|
|
1658
|
+
{ LHSField: "ProductInfo", Operator: "EQ", RHSValue: { _id: "P1", _name: "Widget" } }
|
|
1659
|
+
|
|
1660
|
+
// ✅ CORRECT — dot notation for filtering by _name
|
|
1661
|
+
{ LHSField: "ProductInfo._name", Operator: "Contains", RHSValue: "Widget" }
|
|
1662
|
+
```
|
package/package.json
CHANGED
|
@@ -28,7 +28,7 @@ import type {
|
|
|
28
28
|
|
|
29
29
|
```typescript
|
|
30
30
|
const filter = useFilter({
|
|
31
|
-
|
|
31
|
+
operator: "And",
|
|
32
32
|
});
|
|
33
33
|
|
|
34
34
|
// Add a condition at root level
|
|
@@ -77,8 +77,8 @@ table.filter.clearAllConditions();
|
|
|
77
77
|
|
|
78
78
|
| Property | Type | Required | Default | Description |
|
|
79
79
|
|----------|------|----------|---------|-------------|
|
|
80
|
-
| `
|
|
81
|
-
| `
|
|
80
|
+
| `conditions` | `Array<ConditionType \| ConditionGroupType>` | No | `[]` | Filter conditions |
|
|
81
|
+
| `operator` | `ConditionGroupOperatorType` | No | `"And"` | Operator for combining conditions |
|
|
82
82
|
|
|
83
83
|
## Return Value
|
|
84
84
|
|
|
@@ -126,7 +126,7 @@ interface ConditionType {
|
|
|
126
126
|
Operator: ConditionOperatorType;
|
|
127
127
|
LHSField: string; // Field name to filter on
|
|
128
128
|
RHSValue: any; // Value to compare against
|
|
129
|
-
RHSType?: FilterRHSTypeType; // "Constant" | "
|
|
129
|
+
RHSType?: FilterRHSTypeType; // "Constant" | "BDOField" | "AppVariable"
|
|
130
130
|
}
|
|
131
131
|
```
|
|
132
132
|
|
|
@@ -271,6 +271,18 @@ const buildComplexFilter = () => {
|
|
|
271
271
|
};
|
|
272
272
|
```
|
|
273
273
|
|
|
274
|
+
### Field-to-Field Comparison (BDOField)
|
|
275
|
+
|
|
276
|
+
```typescript
|
|
277
|
+
// Filter where Quantity exceeds Stock (field vs field)
|
|
278
|
+
filter.addCondition({
|
|
279
|
+
Operator: "GT",
|
|
280
|
+
LHSField: "Quantity",
|
|
281
|
+
RHSValue: "Stock",
|
|
282
|
+
RHSType: "BDOField",
|
|
283
|
+
});
|
|
284
|
+
```
|
|
285
|
+
|
|
274
286
|
### Toggle Root Operator
|
|
275
287
|
|
|
276
288
|
```typescript
|
|
@@ -356,6 +368,63 @@ table.filter.hasConditions;
|
|
|
356
368
|
table.filter.payload;
|
|
357
369
|
```
|
|
358
370
|
|
|
371
|
+
## Filtering Reference & User Fields
|
|
372
|
+
|
|
373
|
+
Reference and User fields store `{ _id, _name, ... }` objects. Key rules:
|
|
374
|
+
|
|
375
|
+
- **Default targets `_id`**: Pass string ID as `RHSValue`, backend auto-compares against `_id`
|
|
376
|
+
- **Dot notation for nested paths**: Use `"FieldName._name"` in `LHSField` to filter by `_name` or other sub-fields
|
|
377
|
+
- **Supported operators**: `EQ`, `NE`, `IN`, `NIN`, `Empty`, `NotEmpty`
|
|
378
|
+
- **Contains/NotContains**: Only with dot notation (e.g., `"Vendor._name"`)
|
|
379
|
+
- **GT/GTE/LT/LTE/Between**: NOT supported — raises backend error
|
|
380
|
+
|
|
381
|
+
### Examples
|
|
382
|
+
|
|
383
|
+
```typescript
|
|
384
|
+
// Filter by reference ID
|
|
385
|
+
filter.addCondition({
|
|
386
|
+
Operator: "EQ",
|
|
387
|
+
LHSField: "ProductInfo", // field name, NOT "ProductInfo._id"
|
|
388
|
+
RHSValue: "PROD_001", // string ID directly
|
|
389
|
+
RHSType: "Constant",
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// Filter by multiple IDs
|
|
393
|
+
filter.addCondition({
|
|
394
|
+
Operator: "IN",
|
|
395
|
+
LHSField: "ProductInfo",
|
|
396
|
+
RHSValue: ["PROD_001", "PROD_002"],
|
|
397
|
+
RHSType: "Constant",
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
// Search by reference name (dot notation)
|
|
401
|
+
filter.addCondition({
|
|
402
|
+
Operator: "Contains",
|
|
403
|
+
LHSField: "ProductInfo._name", // dot notation for nested path
|
|
404
|
+
RHSValue: "Widget",
|
|
405
|
+
RHSType: "Constant",
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
// Filter system user field
|
|
409
|
+
filter.addCondition({
|
|
410
|
+
Operator: "EQ",
|
|
411
|
+
LHSField: "_created_by",
|
|
412
|
+
RHSValue: "USR_001",
|
|
413
|
+
RHSType: "Constant",
|
|
414
|
+
});
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
### RHSValue Formats
|
|
418
|
+
|
|
419
|
+
| Format | Example | When to use |
|
|
420
|
+
|--------|---------|-------------|
|
|
421
|
+
| String ID | `"PROD_001"` | Simplest — use when you have the ID |
|
|
422
|
+
| Object | `{ _id: "PROD_001", _name: "Widget" }` | Backend extracts `_id` automatically |
|
|
423
|
+
| Array of IDs | `["PROD_001", "PROD_002"]` | With IN/NIN operators |
|
|
424
|
+
| Array of objects | `[{ _id: "PROD_001" }]` | With IN/NIN — backend extracts each `_id` |
|
|
425
|
+
|
|
426
|
+
Prefer passing string IDs directly for simplicity.
|
|
427
|
+
|
|
359
428
|
## Key Behaviors
|
|
360
429
|
|
|
361
430
|
1. **Auto-generated IDs**: All conditions get unique IDs via `generateId()`
|
package/sdk/types/constants.ts
CHANGED
|
@@ -56,6 +56,8 @@ export const ConditionOperator = {
|
|
|
56
56
|
MinLength: "MinLength",
|
|
57
57
|
/** Maximum string length */
|
|
58
58
|
MaxLength: "MaxLength",
|
|
59
|
+
/** Exact length (array) */
|
|
60
|
+
Length: "Length",
|
|
59
61
|
} as const;
|
|
60
62
|
|
|
61
63
|
/**
|
|
@@ -90,13 +92,13 @@ export const GroupOperator = {
|
|
|
90
92
|
* { RHSType: RHSType.Constant, RHSValue: 100 }
|
|
91
93
|
*
|
|
92
94
|
* // Compare against another field
|
|
93
|
-
* { RHSType: RHSType.
|
|
95
|
+
* { RHSType: RHSType.BDOField, RHSValue: "otherField" }
|
|
94
96
|
*/
|
|
95
97
|
export const RHSType = {
|
|
96
98
|
/** Literal constant value */
|
|
97
99
|
Constant: "Constant",
|
|
98
|
-
/** Reference another field */
|
|
99
|
-
|
|
100
|
+
/** Reference another BDO field */
|
|
101
|
+
BDOField: "BDOField",
|
|
100
102
|
/** Reference app variable */
|
|
101
103
|
AppVariable: "AppVariable",
|
|
102
104
|
} as const;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const t={EQ:"EQ",NE:"NE",GT:"GT",GTE:"GTE",LT:"LT",LTE:"LTE",Between:"Between",NotBetween:"NotBetween",IN:"IN",NIN:"NIN",Empty:"Empty",NotEmpty:"NotEmpty",Contains:"Contains",NotContains:"NotContains",MinLength:"MinLength",MaxLength:"MaxLength"},e={And:"And",Or:"Or",Not:"Not"},n={Constant:"Constant",BOField:"BOField",AppVariable:"AppVariable"},o={ASC:"ASC",DESC:"DESC"},i={Sum:"Sum",Avg:"Avg",Count:"Count",Max:"Max",Min:"Min",DistinctCount:"DistinctCount",BlankCount:"BlankCount",NotBlankCount:"NotBlankCount",Concat:"Concat",DistinctConcat:"DistinctConcat"},a={List:"List",Metric:"Metric",Pivot:"Pivot"},c={Create:"create",Update:"update"},r={Interactive:"interactive",NonInteractive:"non-interactive"},s={OnBlur:"onBlur",OnChange:"onChange",OnSubmit:"onSubmit",OnTouched:"onTouched",All:"all"},d={Loading:"loading",Authenticated:"authenticated",Unauthenticated:"unauthenticated"},u={Google:"google",Microsoft:"microsoft",GitHub:"github",Custom:"custom"},C={Id:"_id",CreatedAt:"_created_at",ModifiedAt:"_modified_at",CreatedBy:"_created_by",ModifiedBy:"_modified_by",Version:"_version",MergeVersion:"_m_version"},E={GET:"GET",POST:"POST",PATCH:"PATCH",DELETE:"DELETE"},p={SEARCH_DEBOUNCE_MS:300,PAGE_SIZE:10,PAGE:1,SEARCH_MAX_LENGTH:255},T={Date:"$__d__",DateTime:"$__dt__"},l={Success:"success"};exports.AuthProviderName=u;exports.AuthStatus=d;exports.ConditionOperator=t;exports.DateEncodingKey=T;exports.Defaults=p;exports.DeleteStatus=l;exports.FormOperation=c;exports.GroupOperator=e;exports.HttpMethod=E;exports.InteractionMode=r;exports.MetricType=i;exports.QueryType=a;exports.RHSType=n;exports.SortDirection=o;exports.SystemField=C;exports.ValidationMode=s;
|