@memberjunction/graphql-dataprovider 2.52.0 → 2.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ye=Object.defineProperty;var f=(R,e)=>ye(R,"name",{value:e,configurable:!0});var m=require("graphql-request"),y=require("@memberjunction/core"),oe=require("@memberjunction/core-entities"),de=require("@tempfix/idb"),ue=require("rxjs"),le=require("graphql-ws"),me=require("uuid"),I=require("@memberjunction/global");const O=class O{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,a])=>[a,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(O,"FieldMapper");let N=O;const b=class b extends y.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m.gql`
1
+ "use strict";var ye=Object.defineProperty;var R=(f,e)=>ye(f,"name",{value:e,configurable:!0});var d=require("graphql-request"),c=require("@memberjunction/core"),oe=require("@memberjunction/core-entities"),me=require("@tempfix/idb"),ue=require("rxjs"),le=require("graphql-ws"),de=require("uuid"),N=require("@memberjunction/global");const O=class O{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};R(O,"FieldMapper");let I=O;const b=class b extends c.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=d.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,15 +6,15 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const s of this.PendingTransactions)t.push({EntityName:s.BaseEntity.EntityInfo.Name,EntityObjectJSON:await s.BaseEntity.GetDataObjectJSON(),OperationType:s.OperationType});const r={group:{Items:t,Variables:this.Variables.map(s=>({Name:s.Name,ItemIndex:this.MapVariableEntityObjectToPosition(s),FieldName:s.FieldName,Type:s.Type}))}},a=await this._provider.ExecuteGQL(e,r);if(a&&a.ExecuteTransactionGroup){const s=a.ExecuteTransactionGroup,o=[];for(let n=0;n<this.PendingTransactions.length;n++){const i=s.ResultsJSON[n],h=I.SafeJSONParse(i),g=this.PendingTransactions[n];o.push(new y.TransactionResult(g,h,h!==null))}return o}else throw new Error("Failed to execute transaction group")}};f(b,"GraphQLTransactionGroup");let C=b;const k=class k extends y.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,a,s,o,n,i){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,RefreshTokenFunction:a},s,o,n)}};f(k,"GraphQLProviderConfigData");let G=k;const p=class p extends y.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
9
+ `,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,o=[];for(let n=0;n<this.PendingTransactions.length;n++){const i=a.ResultsJSON[n],g=N.SafeJSONParse(i),E=this.PendingTransactions[n];o.push(new c.TransactionResult(E,g,g!==null))}return o}else throw new Error("Failed to execute transaction group")}};R(b,"GraphQLTransactionGroup");let C=b;const k=class k extends c.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,o,n,i){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,RefreshTokenFunction:s},a,o,n)}};R(k,"GraphQLProviderConfigData");let G=k;const h=class h extends c.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
10
10
  ${this.userInfoString()}
11
11
  UserRoles_UserIDArray {
12
12
  ${this.userRoleInfoString()}
13
13
  }
14
14
  }
15
- `,this._currentUserQuery=m.gql`query CurrentUserAndRoles {
15
+ `,this._currentUserQuery=d.gql`query CurrentUserAndRoles {
16
16
  ${this._innerCurrentUserQueryString}
17
- }`,this._wsClient=null,this._pushStatusRequests=[],p._instance||(p._instance=this)}static get Instance(){return p._instance}get ConfigData(){return this._configData}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return me.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r){try{return t?(this._configData=e,this._sessionId=await this.GetPreferredUUID(r),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(p.Instance._configData=e,p.Instance._sessionId===void 0&&(p.Instance._sessionId=await this.GetPreferredUUID(r)),p.Instance._client||(p.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,p.Instance._sessionId,e.MJAPIKey)),await p.Instance.SaveStoredSessionID(p.Instance._sessionId)),super.Config(e)}catch(a){throw y.LogError(a),a}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(a=>this.ConvertBackToMJFields(a));return t.UserRoles_UserIDArray=r,new y.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m.gql`
17
+ }`,this._wsClient=null,this._pushStatusRequests=[],h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return de.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r){try{return t?(this._configData=e,this._sessionId=await this.GetPreferredUUID(r),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(r)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId)),super.Config(e)}catch(s){throw c.LogError(s),s}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new c.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=d.gql`
18
18
  query GetReportDataQuery ($ReportID: String!) {
19
19
  GetReportData(ReportID: $ReportID) {
20
20
  Success
@@ -23,30 +23,30 @@
23
23
  ExecutionTime
24
24
  ErrorMessage
25
25
  }
26
- }`,a=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(a&&a.GetReportData)return{ReportID:e.ReportID,Success:a.GetReportData.Success,Results:JSON.parse(a.GetReportData.Results),RowCount:a.GetReportData.RowCount,ExecutionTime:a.GetReportData.ExecutionTime,ErrorMessage:a.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryName,t);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryName,t);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,a){const s=m.gql`
26
+ }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryName,t);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryName,t);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s){const a=d.gql`
27
27
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryName: String) {
28
28
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryName: $CategoryName) {
29
29
  ${this.QueryReturnFieldList}
30
30
  }
31
31
  }
32
- `,o={QueryID:e};t!==void 0&&(o.CategoryID=t),r!==void 0&&(o.CategoryName=r);const n=await this.ExecuteGQL(s,o);if(n&&n.GetQueryData)return this.TransformQueryPayload(n.GetQueryData)}async RunQueryByName(e,t,r,a){const s=m.gql`
32
+ `,o={QueryID:e};t!==void 0&&(o.CategoryID=t),r!==void 0&&(o.CategoryName=r);const n=await this.ExecuteGQL(a,o);if(n&&n.GetQueryData)return this.TransformQueryPayload(n.GetQueryData)}async RunQueryByName(e,t,r,s){const a=d.gql`
33
33
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryName: String) {
34
34
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryName: $CategoryName) {
35
35
  ${this.QueryReturnFieldList}
36
36
  }
37
37
  }
38
- `,o={QueryName:e,CategoryID:t,CategoryName:r},n=await this.ExecuteGQL(s,o);if(n&&n.GetQueryDataByName)return this.TransformQueryPayload(n.GetQueryDataByName)}get QueryReturnFieldList(){return`
38
+ `,o={QueryName:e,CategoryID:t,CategoryName:r},n=await this.ExecuteGQL(a,o);if(n&&n.GetQueryDataByName)return this.TransformQueryPayload(n.GetQueryDataByName)}get QueryReturnFieldList(){return`
39
39
  Success
40
40
  QueryID
41
41
  QueryName
42
42
  Results
43
43
  RowCount
44
44
  ExecutionTime
45
- ErrorMessage`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage}}catch(t){return y.LogError(`Error transforming query payload: ${t}`),null}}async RunView(e,t){try{let r="",a="";if(e){const s={};let o,n;if(e.ViewEntity)n=e.ViewEntity,o=n.Entity;else{const{entityName:u,v:l}=await this.getEntityNameAndUserView(e,t);n=l,o=u}const i=this.Entities.find(u=>u.Name===o);if(!i)throw new Error(`Entity ${o} not found in metadata`);let h=!1;e.ViewID?(r=`Run${i.ClassName}ViewByID`,a="RunViewByIDInput",s.ViewID=e.ViewID):e.ViewName?(r=`Run${i.ClassName}ViewByName`,a="RunViewByNameInput",s.ViewName=e.ViewName):(h=!0,r=`Run${i.ClassName}DynamicView`,a="RunDynamicViewInput",s.EntityName=e.EntityName),s.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",s.OrderBy=e.OrderBy?e.OrderBy:"",s.UserSearchString=e.UserSearchString?e.UserSearchString:"",s.Fields=e.Fields,s.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,s.MaxRows=e.MaxRows?e.MaxRows:0,s.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,s.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(s.AuditLogDescription=e.AuditLogDescription),h||(s.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",s.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,s.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",s.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const g=this.getViewRunTimeFieldList(i,n,e,h),d=m.gql`
46
- query RunViewQuery ($input: ${a}!) {
45
+ ErrorMessage`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage}}catch(t){return c.LogError(`Error transforming query payload: ${t}`),null}}async RunView(e,t){try{let r="",s="";if(e){const a={};let o,n;if(e.ViewEntity)n=e.ViewEntity,o=n.Entity;else{const{entityName:u,v:l}=await this.getEntityNameAndUserView(e,t);n=l,o=u}const i=this.Entities.find(u=>u.Name===o);if(!i)throw new Error(`Entity ${o} not found in metadata`);let g=!1;e.ViewID?(r=`Run${i.ClassName}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${i.ClassName}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(g=!0,r=`Run${i.ClassName}DynamicView`,s="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,a.MaxRows=e.MaxRows?e.MaxRows:0,a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),g||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const E=this.getViewRunTimeFieldList(i,n,e,g),m=d.gql`
46
+ query RunViewQuery ($input: ${s}!) {
47
47
  ${r}(input: $input) {
48
48
  Results {
49
- ${g.join(`
49
+ ${E.join(`
50
50
  `)}
51
51
  }
52
52
  UserViewRunID
@@ -56,7 +56,7 @@
56
56
  Success
57
57
  ErrorMessage
58
58
  }
59
- }`,c=await this.ExecuteGQL(d,{input:s});if(c&&c[r]){const u=c[r].Results;if(u&&u.length>0){const l=i.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);u.forEach(D=>{this.ConvertBackToMJFields(D),l.forEach(E=>{D[E.Name]=D[E.CodeName]})})}return c[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw y.LogError(r),r}}async RunViews(e,t){try{let r=[],a=[],s=[];for(const i of e){let h="",g="";const d={};let c=null,u=null;if(i.ViewEntity)u=i.ViewEntity,c=u.Get("Entity");else{const{entityName:E,v:S}=await this.getEntityNameAndUserView(i,t);u=S,c=E}const l=this.Entities.find(E=>E.Name===c);if(!l)throw new Error(`Entity ${c} not found in metadata`);a.push(l);let D=!1;i.ViewID?(h=`Run${l.ClassName}ViewByID`,g="RunViewByIDInput",d.ViewID=i.ViewID):i.ViewName?(h=`Run${l.ClassName}ViewByName`,g="RunViewByNameInput",d.ViewName=i.ViewName):(D=!0,h=`Run${l.ClassName}DynamicView`,g="RunDynamicViewInput",d.EntityName=i.EntityName),d.ExtraFilter=i.ExtraFilter||"",d.OrderBy=i.OrderBy||"",d.UserSearchString=i.UserSearchString||"",d.Fields=i.Fields,d.IgnoreMaxRows=i.IgnoreMaxRows||!1,d.MaxRows=i.MaxRows||0,d.ForceAuditLog=i.ForceAuditLog||!1,d.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(d.AuditLogDescription=i.AuditLogDescription),D||(d.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",d.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,d.OverrideExcludeFilter=i.OverrideExcludeFilter||"",d.SaveViewResults=i.SaveViewResults||!1),r.push(d),s.push(...this.getViewRunTimeFieldList(l,u,i,D))}const o=m.gql`
59
+ }`,y=await this.ExecuteGQL(m,{input:a});if(y&&y[r]){const u=y[r].Results;if(u&&u.length>0){const l=i.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);u.forEach(D=>{this.ConvertBackToMJFields(D),l.forEach(S=>{D[S.Name]=D[S.CodeName]})})}return y[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async RunViews(e,t){try{let r=[],s=[],a=[];for(const i of e){let g="",E="";const m={};let y=null,u=null;if(i.ViewEntity)u=i.ViewEntity,y=u.Get("Entity");else{const{entityName:S,v:p}=await this.getEntityNameAndUserView(i,t);u=p,y=S}const l=this.Entities.find(S=>S.Name===y);if(!l)throw new Error(`Entity ${y} not found in metadata`);s.push(l);let D=!1;i.ViewID?(g=`Run${l.ClassName}ViewByID`,E="RunViewByIDInput",m.ViewID=i.ViewID):i.ViewName?(g=`Run${l.ClassName}ViewByName`,E="RunViewByNameInput",m.ViewName=i.ViewName):(D=!0,g=`Run${l.ClassName}DynamicView`,E="RunDynamicViewInput",m.EntityName=i.EntityName),m.ExtraFilter=i.ExtraFilter||"",m.OrderBy=i.OrderBy||"",m.UserSearchString=i.UserSearchString||"",m.Fields=i.Fields,m.IgnoreMaxRows=i.IgnoreMaxRows||!1,m.MaxRows=i.MaxRows||0,m.ForceAuditLog=i.ForceAuditLog||!1,m.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(m.AuditLogDescription=i.AuditLogDescription),D||(m.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=i.OverrideExcludeFilter||"",m.SaveViewResults=i.SaveViewResults||!1),r.push(m),a.push(...this.getViewRunTimeFieldList(l,u,i,D))}const o=d.gql`
60
60
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
61
61
  RunViews(input: $input) {
62
62
  Results {
@@ -71,7 +71,7 @@
71
71
  Success
72
72
  ErrorMessage
73
73
  }
74
- }`,n=await this.ExecuteGQL(o,{input:r});if(n&&n.RunViews){const i=n.RunViews;for(const[h,g]of i.entries())g.Results=g.Results.map(d=>{let c=JSON.parse(d.Data);return this.ConvertBackToMJFields(c),c});return i}return null}catch(r){throw y.LogError(r),r}}async getEntityNameAndUserView(e,t){let r,a;if(e.EntityName)r=e.EntityName;else if(e.ViewID)a=await oe.ViewInfo.GetViewEntity(e.ViewID,t),r=a.Entity;else if(e.ViewName)a=await oe.ViewInfo.GetViewEntityByName(e.ViewName,t),r=a.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:a}}getViewRunTimeFieldList(e,t,r,a){const s=[],o=new N;if(r.Fields){for(const n of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&s.push(n.Name);r.Fields.forEach(n=>{s.push(o.MapFieldName(n))})}else if(a)e.Fields.forEach(n=>{n.IsBinaryFieldType||s.push(o.MapFieldName(n.CodeName))});else{for(const n of e.PrimaryKeys)s.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&s.push(n.Name);t.Columns.forEach(n=>{n.hidden===!1&&!s.find(i=>i.trim().toLowerCase()===n.EntityField?.Name.trim().toLowerCase())&&n.EntityField&&s.push(o.MapFieldName(n.EntityField.CodeName))})}return s}get ProviderType(){return y.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},a=await this.RunView(r);return a?a.Results.sort((s,o)=>s.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw y.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=m.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
74
+ }`,n=await this.ExecuteGQL(o,{input:r});if(n&&n.RunViews){const i=n.RunViews;for(const[g,E]of i.entries())E.Results=E.Results.map(m=>{let y=JSON.parse(m.Data);return this.ConvertBackToMJFields(y),y});return i}return null}catch(r){throw c.LogError(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await oe.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await oe.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const a=[],o=new I;if(r.Fields){for(const n of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&a.push(n.Name);r.Fields.forEach(n=>{a.push(o.MapFieldName(n))})}else if(s)e.Fields.forEach(n=>{n.IsBinaryFieldType||a.push(o.MapFieldName(n.CodeName))});else{for(const n of e.PrimaryKeys)a.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&a.push(n.Name);t.Columns.forEach(n=>{n.hidden===!1&&!a.find(i=>i.trim().toLowerCase()===n.EntityField?.Name.trim().toLowerCase())&&n.EntityField&&a.push(o.MapFieldName(n.EntityField.CodeName))})}return a}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((a,o)=>a.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=d.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
75
75
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
76
76
  EntityName
77
77
  RelatedEntityName
@@ -83,7 +83,7 @@
83
83
  }
84
84
  }
85
85
  }
86
- }`,a={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,a))?.GetRecordDependencies}catch(r){throw y.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=m.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
86
+ }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw c.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=d.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
87
87
  GetRecordDuplicates(params: $params) {
88
88
  Status
89
89
  ErrorMessage
@@ -105,7 +105,7 @@
105
105
  }
106
106
  }
107
107
  }
108
- }`;let a={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const s=await this.ExecuteGQL(r,{params:a});if(s&&s.GetRecordDuplicates)return s.GetRecordDuplicates}async MergeRecords(e){const t=this.Entities.find(r=>r.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!t||!t.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const r=m.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
108
+ }`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const a=await this.ExecuteGQL(r,{params:s});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e){const t=this.Entities.find(r=>r.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!t||!t.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const r=d.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
109
109
  MergeRecords(request: $request) {
110
110
  Success
111
111
  OverallStatus
@@ -122,32 +122,32 @@
122
122
  Message
123
123
  }
124
124
  }
125
- }`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(r,{request:a}))?.MergeRecords}catch(r){return y.LogError(r),{Success:!1,OverallStatus:r&&r.message?r.message:r,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const a=new y.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const s={input:{}},o=e.IsSaved?"Update":"Create";a.StartedAt=new Date,a.Type=e.IsSaved?"update":"create",a.OriginalValues=e.Fields.map(c=>({FieldName:c.CodeName,Value:c.Value})),e.ResultHistory.push(a);const n=`${o}${e.EntityInfo.ClassName}`,i=e.Fields.filter(c=>!c.ReadOnly||c.IsPrimaryKey&&e.IsSaved),h=new N,g=` ${n}(input: $input) {
126
- ${e.Fields.map(c=>h.MapFieldName(c.CodeName)).join(`
125
+ }`,s={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(r,{request:s}))?.MergeRecords}catch(r){return c.LogError(r),{Success:!1,OverallStatus:r&&r.message?r.message:r,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const a={input:{}},o=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const n=`${o}${e.EntityInfo.ClassName}`,i=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),g=new I,E=` ${n}(input: $input) {
126
+ ${e.Fields.map(y=>g.MapFieldName(y.CodeName)).join(`
127
127
  `)}
128
- }`,d=m.gql`mutation ${o}${e.EntityInfo.ClassName} ($input: ${n}Input!) {
129
- ${g}
128
+ }`,m=d.gql`mutation ${o}${e.EntityInfo.ClassName} ($input: ${n}Input!) {
129
+ ${E}
130
130
  }
131
- `;for(let c=0;c<i.length;c++){const u=i[c];let l=u.Value;if(l)switch(u.EntityFieldInfo.TSType){case y.EntityFieldTSType.Date:l=l.getTime();break;case y.EntityFieldTSType.Boolean:typeof l!="boolean"&&(l=parseInt(l)!==0);break;case y.EntityFieldTSType.Number:if(typeof l!="number"){const D=Number(l);isNaN(D)||(l=D)}break}l===null&&u.EntityFieldInfo.AllowsNull===!1&&(u.EntityFieldInfo.DefaultValue!==null?l=u.EntityFieldInfo.DefaultValue:u.FieldType===y.EntityFieldTSType.Number||u.FieldType===y.EntityFieldTSType.Boolean?l=0:l=""),s.input[u.CodeName]=l}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const c=[];e.Fields.forEach(u=>{let l=null;u.OldValue!==null&&u.OldValue!==void 0&&(u.EntityFieldInfo.TSType===y.EntityFieldTSType.Date?l=u.OldValue.getTime().toString():u.EntityFieldInfo.TSType===y.EntityFieldTSType.Boolean?l=u.OldValue===!0?"1":"0":typeof u.OldValue!="string"?l=u.OldValue.toString():l=u.OldValue),c.push({Key:u.CodeName,Value:l})}),s.input.OldValues___=c}if(e.TransactionGroup){const c=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new y.TransactionItem(e,a.Type==="create"?"Create":"Update",g,s,{mutationName:n,mutationInputTypes:c},(u,l)=>{a.EndedAt=new Date,l&&u?(a.Success=!0,a.NewValues=this.ConvertBackToMJFields(u)):(a.Success=!1,a.Message="Transaction failed")})),!0}else{const c=await this.ExecuteGQL(d,s);if(c&&c[o+e.EntityInfo.ClassName])return a.Success=!0,a.EndedAt=new Date,a.NewValues=this.ConvertBackToMJFields(c[o+e.EntityInfo.ClassName]),a.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(s){return a.Success=!1,a.EndedAt=new Date,a.Message=s.response?.errors?.length>0?s.response.errors[0].message:s.message,y.LogError(s),null}}async Load(e,t,r=null,a){try{const s={};let o="",n="";for(let c=0;c<t.KeyValuePairs.length;c++){const u=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[c].FieldName.trim().toLowerCase()).EntityFieldInfo,l=t.GetValueByIndex(c),D=u.GraphQLType;if(n.length>0&&(n+=", "),n+=`$${u.CodeName}: ${D}!`,o.length>0&&(o+=", "),o+=`${u.CodeName}: $${u.CodeName}`,u.TSType===y.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(c)))throw new Error(`Primary Key value ${l} (${u.Name}) is not a valid number`);s[u.CodeName]=parseInt(l)}else s[u.CodeName]=l}const i=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",h=new N,g=m.gql`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${n}) {
131
+ `;for(let y=0;y<i.length;y++){const u=i[y];let l=u.Value;if(l)switch(u.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:l=l.getTime();break;case c.EntityFieldTSType.Boolean:typeof l!="boolean"&&(l=parseInt(l)!==0);break;case c.EntityFieldTSType.Number:if(typeof l!="number"){const D=Number(l);isNaN(D)||(l=D)}break}l===null&&u.EntityFieldInfo.AllowsNull===!1&&(u.EntityFieldInfo.DefaultValue!==null?l=u.EntityFieldInfo.DefaultValue:u.FieldType===c.EntityFieldTSType.Number||u.FieldType===c.EntityFieldTSType.Boolean?l=0:l=""),a.input[u.CodeName]=l}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(u=>{let l=null;u.OldValue!==null&&u.OldValue!==void 0&&(u.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?l=u.OldValue.getTime().toString():u.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?l=u.OldValue===!0?"1":"0":typeof u.OldValue!="string"?l=u.OldValue.toString():l=u.OldValue),y.push({Key:u.CodeName,Value:l})}),a.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",E,a,{mutationName:n,mutationInputTypes:y},(u,l)=>{s.EndedAt=new Date,l&&u?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(u)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(m,a);if(y&&y[o+e.EntityInfo.ClassName])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[o+e.EntityInfo.ClassName]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,c.LogError(a),null}}async Load(e,t,r=null,s){try{const a={};let o="",n="";for(let y=0;y<t.KeyValuePairs.length;y++){const u=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,l=t.GetValueByIndex(y),D=u.GraphQLType;if(n.length>0&&(n+=", "),n+=`$${u.CodeName}: ${D}!`,o.length>0&&(o+=", "),o+=`${u.CodeName}: $${u.CodeName}`,u.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${l} (${u.Name}) is not a valid number`);a[u.CodeName]=parseInt(l)}else a[u.CodeName]=l}const i=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",g=new I,E=d.gql`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${n}) {
132
132
  ${e.EntityInfo.ClassName}(${o}) {
133
- ${e.Fields.filter(c=>!c.EntityFieldInfo.IsBinaryFieldType).map(c=>c.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?c.CodeName.replace("__mj_","_mj__"):c.CodeName).join(`
133
+ ${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
134
134
  `)}
135
135
  ${i}
136
136
  }
137
137
  }
138
- `,d=await this.ExecuteGQL(g,s);return d&&d[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(d[e.EntityInfo.ClassName]):null}catch(s){return y.LogError(s),null}}ConvertBackToMJFields(e){return new N().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let a=0;a<e.RelatedEntities.length;a++)if(t.indexOf(e.RelatedEntities[a].RelatedEntity)>=0){const s=e.RelatedEntities[a],o=this.Entities.find(i=>i.ID===s.RelatedEntityID);let n="";s.Type.toLowerCase().trim()==="many to many"?n=`${s.RelatedEntityCodeName}_${s.JoinEntityJoinField.replace(/\s/g,"")}`:n=`${s.RelatedEntityCodeName}_${s.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
138
+ `,m=await this.ExecuteGQL(E,a);return m&&m[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(m[e.EntityInfo.ClassName]):null}catch(a){return c.LogError(a),null}}ConvertBackToMJFields(e){return new I().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const a=e.RelatedEntities[s],o=this.Entities.find(i=>i.ID===a.RelatedEntityID);let n="";a.Type.toLowerCase().trim()==="many to many"?n=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:n=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
139
139
  ${n} {
140
140
  ${o.Fields.map(i=>i.CodeName).join(`
141
141
  `)}
142
142
  }
143
- `}return r}async Delete(e,t,r){const a=new y.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),a.StartedAt=new Date,a.Type="delete",a.OriginalValues=e.Fields.map(u=>({FieldName:u.CodeName,Value:u.Value})),e.ResultHistory.push(a);const s={},o=[];let n="",i="",h="";for(let u of e.PrimaryKey.KeyValuePairs){const l=e.Fields.find(D=>D.Name.trim().toLowerCase()===u.FieldName.trim().toLowerCase());s[l.CodeName]=l.Value,o.push({varName:l.CodeName,inputType:l.EntityFieldInfo.GraphQLType+"!"}),n.length>0&&(n+=", "),n+=`${l.CodeName}: $${l.CodeName}`,i.length>0&&(i+=", "),i+=`$${l.CodeName}: ${l.EntityFieldInfo.GraphQLType}!`,h.length>0&&(h+=`
144
- `),h+=`${l.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),s.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+e.EntityInfo.ClassName,d=m.gql`${g}(${n}, options___: $options___) {
145
- ${h}
143
+ `}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(u=>({FieldName:u.CodeName,Value:u.Value})),e.ResultHistory.push(s);const a={},o=[];let n="",i="",g="";for(let u of e.PrimaryKey.KeyValuePairs){const l=e.Fields.find(D=>D.Name.trim().toLowerCase()===u.FieldName.trim().toLowerCase());a[l.CodeName]=l.Value,o.push({varName:l.CodeName,inputType:l.EntityFieldInfo.GraphQLType+"!"}),n.length>0&&(n+=", "),n+=`${l.CodeName}: $${l.CodeName}`,i.length>0&&(i+=", "),i+=`$${l.CodeName}: ${l.EntityFieldInfo.GraphQLType}!`,g.length>0&&(g+=`
144
+ `),g+=`${l.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const E="Delete"+e.EntityInfo.ClassName,m=d.gql`${E}(${n}, options___: $options___) {
145
+ ${g}
146
146
  }
147
- `,c=m.gql`mutation ${g} (${i}, $options___: DeleteOptionsInput!) {
148
- ${d}
147
+ `,y=d.gql`mutation ${E} (${i}, $options___: DeleteOptionsInput!) {
148
+ ${m}
149
149
  }
150
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new y.TransactionItem(e,"Delete",d,s,{mutationName:g,mutationInputTypes:o},(u,l)=>{if(a.EndedAt=new Date,l&&u){let D=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==u[E.FieldName]&&(D=!1);D?a.Success=!0:(a.Success=!1,a.Message="Transaction failed to commit")}else a.Success=!1,a.Message="Transaction failed to commit"})),!0;{const u=await this.ExecuteGQL(c,s);if(u&&u[g]){const l=u[g];for(let D of e.PrimaryKey.KeyValuePairs){let E=l[D.FieldName],S=D.Value;if(typeof S=="number"&&(S=S.toString()),typeof E=="number"&&(E=E.toString()),S!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${D.FieldName}, Original: ${S}, Returned: ${E}`)}return a.Success=!0,a.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(s){return a.EndedAt=new Date,a.Success=!1,a.Message=s.response?.errors?.length>0?s.response.errors[0].message:s.message,y.LogError(s),!1}}async GetDatasetByName(e,t){const r=m.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
150
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",m,a,{mutationName:E,mutationInputTypes:o},(u,l)=>{if(s.EndedAt=new Date,l&&u){let D=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==u[S.FieldName]&&(D=!1);D?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const u=await this.ExecuteGQL(y,a);if(u&&u[E]){const l=u[E];for(let D of e.PrimaryKey.KeyValuePairs){let S=l[D.FieldName],p=D.Value;if(typeof p=="number"&&(p=p.toString()),typeof S=="number"&&(S=S.toString()),p!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${D.FieldName}, Original: ${p}, Returned: ${S}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,c.LogError(a),!1}}async GetDatasetByName(e,t){const r=d.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
151
151
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
152
152
  DatasetID
153
153
  DatasetName
@@ -156,7 +156,7 @@
156
156
  LatestUpdateDate
157
157
  Results
158
158
  }
159
- }`,a=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return a&&a.GetDatasetByName&&a.GetDatasetByName.Success?{DatasetID:a.GetDatasetByName.DatasetID,DatasetName:a.GetDatasetByName.DatasetName,Success:a.GetDatasetByName.Success,Status:a.GetDatasetByName.Status,LatestUpdateDate:new Date(a.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(a.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=m.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
159
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=d.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
160
160
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
161
161
  DatasetID
162
162
  DatasetName
@@ -165,22 +165,22 @@
165
165
  LatestUpdateDate
166
166
  EntityUpdateDates
167
167
  }
168
- }`,a=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return a&&a.GetDatasetStatusByName&&a.GetDatasetStatusByName.Success?{DatasetID:a.GetDatasetStatusByName.DatasetID,DatasetName:a.GetDatasetStatusByName.DatasetName,Success:a.GetDatasetStatusByName.Success,Status:a.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(a.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(a.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new C(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const s=this.Entities.find(i=>i.Name===t);if(!s)throw new Error(`Entity ${t} not found in metadata`);const o=m.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
168
+ }`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new C(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(i=>i.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const o=d.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
169
169
  GetRecordFavoriteStatus(params: $params) {
170
170
  Success
171
171
  IsFavorite
172
172
  }
173
- }`,n=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:s.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(n&&n.GetRecordFavoriteStatus&&n.GetRecordFavoriteStatus.Success)return n.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,a,s){const o=this.Entities.find(h=>h.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const n=m.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
173
+ }`,n=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(n&&n.GetRecordFavoriteStatus&&n.GetRecordFavoriteStatus.Success)return n.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const o=this.Entities.find(g=>g.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const n=d.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
174
174
  SetRecordFavoriteStatus(params: $params){
175
175
  Success
176
176
  }
177
- }`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:a}});if(i&&i.SetRecordFavoriteStatus!==null)return i.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=m.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
177
+ }`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(i&&i.SetRecordFavoriteStatus!==null)return i.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=d.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
178
178
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
179
179
  Success
180
180
  Status
181
181
  RecordName
182
182
  }
183
- }`,a=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(a&&a.GetEntityRecordName&&a.GetEntityRecordName.Success)return a.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=m.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
183
+ }`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=d.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
184
184
  GetEntityRecordNames(info: $info) {
185
185
  Success
186
186
  Status
@@ -193,35 +193,35 @@
193
193
  EntityName
194
194
  RecordName
195
195
  }
196
- }`,r=await this.ExecuteGQL(t,{info:e.map(a=>({EntityName:a.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=m.gql`query GetDataContextData ($DataContextID: String!) {
196
+ }`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=d.gql`query GetDataContextData ($DataContextID: String!) {
197
197
  GetDataContextData(DataContextID: $DataContextID) {
198
198
  Success
199
199
  ErrorMessages
200
200
  Results
201
201
  }
202
- }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(a=>JSON.parse(a));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw y.LogError(t),t}}async GetDataContextItemData(e){try{const t=m.gql`query GetDataContextItemData ($DataContextItemID: String!) {
202
+ }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}async GetDataContextItemData(e){try{const t=d.gql`query GetDataContextItemData ($DataContextItemID: String!) {
203
203
  GetDataContextItemData(DataContextItemID: $DataContextItemID) {
204
204
  Success
205
205
  ErrorMessage
206
206
  Result
207
207
  }
208
- }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw y.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return p.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(a){if(a&&a.response&&a.response.errors?.length>0)if(a.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw y.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),a}else throw a;else throw y.LogError(a),a}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return p.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,a){const s={"x-session-id":r};return t&&(s.authorization="Bearer "+t),a&&(s["x-mj-api-key"]=a),new m.GraphQLClient(e,{headers:s})}userInfoString(){return this.infoString(new y.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new y.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const a of r)a.startsWith("__mj_")?t+=a.replace("__mj_","_mj__")+`
209
- `:a.startsWith("_")||(t+=a+`
210
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new T),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=le.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new ue.Observable(r=>{const a=this._wsClient.subscribe({query:e,variables:t},{next:s=>{r.next(s.data)},error:s=>{r.error(s)},complete:()=>{r.complete()}});return()=>{a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=le.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(s=>s.sessionId===e);if(t)return t.observable;const r=m.gql`subscription StatusUpdates($sessionId: String!) {
208
+ }`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new d.GraphQLClient(e,{headers:a})}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
209
+ `:s.startsWith("_")||(t+=s+`
210
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new T),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=le.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new ue.Observable(r=>{const s=this._wsClient.subscribe({query:e,variables:t},{next:a=>{r.next(a.data)},error:a=>{r.error(a)},complete:()=>{r.complete()}});return()=>{s()}})}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=le.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(a=>a.sessionId===e);if(t)return t.observable;const r=d.gql`subscription StatusUpdates($sessionId: String!) {
211
211
  statusUpdates(sessionId: $sessionId) {
212
212
  date
213
213
  message
214
214
  sessionId
215
215
  }
216
216
  }
217
- `,a=new ue.Observable(s=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:o=>s.next(o.data.statusUpdates),error:o=>s.error(o),complete:()=>s.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:a}),a}};f(p,"GraphQLDataProvider");let V=p;const J=class J{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(J,"BrowserStorageProviderBase");let F=J;const De="MJ_Metadata",w="Metadata_KVPairs",j=class j extends F{constructor(){super(),this.dbPromise=de.openDB(De,1,{upgrade(e){e.objectStoreNames.contains(w)||e.createObjectStore(w)}})}async setItem(e,t){const a=(await this.dbPromise).transaction(w,"readwrite");await a.objectStore(w).put(t,e),await a.done}async getItem(e){return await(await this.dbPromise).transaction(w).objectStore(w).get(e)}async remove(e){const r=(await this.dbPromise).transaction(w,"readwrite");await r.objectStore(w).delete(e),await r.done}};f(j,"BrowserIndexedDBStorageProvider");let T=j;async function he(R){const e=new V;return y.SetProvider(e),await e.Config(R),I.MJGlobal.Instance.RaiseEvent({event:I.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(he,"setupGraphQLClient");const W=class W{};f(W,"SyncRolesAndUsersResult");let $=W;const z=class z{};f(z,"RoleInput");let L=z;const H=class H{};f(H,"UserInput");let v=H;const X=class X{};f(X,"RolesAndUsersInput");let P=X;var ce=(R=>(R.Create="Create",R.Update="Update",R.CreateOrUpdate="CreateOrUpdate",R.Delete="Delete",R.DeleteWithFilter="DeleteWithFilter",R))(ce||{});const Z=class Z{};f(Z,"ActionItemInput");let x=Z;const Y=class Y{constructor(){this.Results=[]}};f(Y,"SyncDataResult");let A=Y;const ee=class ee{};f(ee,"ActionItemOutput");let M=ee;const te=class te{get Client(){return this._client}constructor(e,t,r,a){const s={"x-session-id":r};t&&(s.authorization="Bearer "+t),a&&(s["x-mj-api-key"]=a),this._client=new m.GraphQLClient(e,{headers:s})}async GetData(e,t){try{const a=await this.Client.request(`query GetData($input: GetDataInputType!) {
217
+ `,s=new ue.Observable(a=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:o=>a.next(o.data.statusUpdates),error:o=>a.error(o),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:s}),s}};R(h,"GraphQLDataProvider");let V=h;const J=class J{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};R(J,"BrowserStorageProviderBase");let $=J;const De="MJ_Metadata",w="Metadata_KVPairs",j=class j extends ${constructor(){super(),this.dbPromise=me.openDB(De,1,{upgrade(e){e.objectStoreNames.contains(w)||e.createObjectStore(w)}})}async setItem(e,t){const s=(await this.dbPromise).transaction(w,"readwrite");await s.objectStore(w).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction(w).objectStore(w).get(e)}async remove(e){const r=(await this.dbPromise).transaction(w,"readwrite");await r.objectStore(w).delete(e),await r.done}};R(j,"BrowserIndexedDBStorageProvider");let T=j;async function ge(f){const e=new V;return c.SetProvider(e),await e.Config(f),N.MJGlobal.Instance.RaiseEvent({event:N.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}R(ge,"setupGraphQLClient");const W=class W{};R(W,"SyncRolesAndUsersResult");let F=W;const z=class z{};R(z,"RoleInput");let U=z;const H=class H{};R(H,"UserInput");let L=H;const X=class X{};R(X,"RolesAndUsersInput");let Q=X;var ce=(f=>(f.Create="Create",f.Update="Update",f.CreateOrUpdate="CreateOrUpdate",f.Delete="Delete",f.DeleteWithFilter="DeleteWithFilter",f))(ce||{});const Z=class Z{};R(Z,"ActionItemInput");let v=Z;const Y=class Y{constructor(){this.Results=[]}};R(Y,"SyncDataResult");let x=Y;const ee=class ee{};R(ee,"ActionItemOutput");let P=ee;const te=class te{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new d.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
218
218
  GetData(input: $input) {
219
219
  Success
220
220
  ErrorMessages
221
221
  Queries
222
222
  Results
223
223
  }
224
- }`,{input:{Queries:e,Token:"nope"}});return a&&a.GetData?{Success:a.GetData.Success,Results:a.GetData.Results.map(s=>s?I.SafeJSONParse(s):null),ErrorMessages:a.GetData.ErrorMessages,Queries:a.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:a.GetData?.ErrorMessages??["Unknown error"],Queries:a.GetData?.Queries??e}}catch(r){const a=`GraphQLSystemUserClient::GetData - Error getting geta - ${r}`;return y.LogError(a),{Success:!1,Results:[],ErrorMessages:[a],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
224
+ }`,{input:{Queries:e,Token:"nope"}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?N.SafeJSONParse(a):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){const s=`GraphQLSystemUserClient::GetData - Error getting geta - ${r}`;return c.LogError(s),{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
225
225
  GetAllEntities {
226
226
  Success
227
227
  ErrorMessage
@@ -244,7 +244,7 @@
244
244
  }
245
245
  }
246
246
  }
247
- }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return y.LogError(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
247
+ }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return c.LogError(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
248
248
  SyncData(items: $items) {
249
249
  Success
250
250
  Results {
@@ -268,11 +268,87 @@
268
268
  RecordJSON
269
269
  }
270
270
  }
271
- }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return y.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
271
+ }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return c.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
272
272
  SyncRolesAndUsers(data: $data) {
273
273
  Success
274
274
  }
275
- }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return y.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}};f(te,"GraphQLSystemUserClient");let U=te;const re=class re{};f(re,"GetDataOutput");let _=re;const ae=class ae{};f(ae,"SimpleRemoteEntityOutput");let Q=ae;const se=class se{};f(se,"SimpleRemoteEntity");let q=se;const ne=class ne{};f(ne,"SimpleRemoteEntityField");let K=ne;const ie=class ie{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const a=this.serializeActionParameters(t),s=this.createActionVariables(e,a,r),o=await this.executeActionMutation(s);return this.processActionResult(o,t)}catch(a){return this.handleActionError(a,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=m.gql`
275
+ }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return c.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByNameSystemUser(e){try{const r=await this.Client.request(`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
276
+ RunViewByNameSystemUser(input: $input) {
277
+ Results {
278
+ ID
279
+ EntityID
280
+ Data
281
+ }
282
+ UserViewRunID
283
+ RowCount
284
+ TotalRowCount
285
+ ExecutionTime
286
+ ErrorMessage
287
+ Success
288
+ }
289
+ }`,{input:e});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByIDSystemUser(e){try{const r=await this.Client.request(`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
290
+ RunViewByIDSystemUser(input: $input) {
291
+ Results {
292
+ ID
293
+ EntityID
294
+ Data
295
+ }
296
+ UserViewRunID
297
+ RowCount
298
+ TotalRowCount
299
+ ExecutionTime
300
+ ErrorMessage
301
+ Success
302
+ }
303
+ }`,{input:e});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicViewSystemUser(e){try{const r=await this.Client.request(`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
304
+ RunDynamicViewSystemUser(input: $input) {
305
+ Results {
306
+ ID
307
+ EntityID
308
+ Data
309
+ }
310
+ UserViewRunID
311
+ RowCount
312
+ TotalRowCount
313
+ ExecutionTime
314
+ ErrorMessage
315
+ Success
316
+ }
317
+ }`,{input:e});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewsSystemUser(e){try{const r=await this.Client.request(`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
318
+ RunViewsSystemUser(input: $input) {
319
+ Results {
320
+ ID
321
+ EntityID
322
+ Data
323
+ }
324
+ UserViewRunID
325
+ RowCount
326
+ TotalRowCount
327
+ ExecutionTime
328
+ ErrorMessage
329
+ Success
330
+ }
331
+ }`,{input:e});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryDataSystemUser(e,t,r){try{const a=await this.Client.request(`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryName: String) {
332
+ GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryName: $CategoryName) {
333
+ QueryID
334
+ QueryName
335
+ Success
336
+ Results
337
+ RowCount
338
+ ExecutionTime
339
+ ErrorMessage
340
+ }
341
+ }`,{QueryID:e,CategoryID:t,CategoryName:r});return a&&a.GetQueryDataSystemUser?{...a.GetQueryDataSystemUser,Results:a.GetQueryDataSystemUser.Results?N.SafeJSONParse(a.GetQueryDataSystemUser.Results):null}:{QueryID:e,QueryName:"",Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(s){return c.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${s}`),{QueryID:e,QueryName:"",Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:s.toString()}}}async GetQueryDataByNameSystemUser(e,t,r){try{const a=await this.Client.request(`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryName: String) {
342
+ GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryName: $CategoryName) {
343
+ QueryID
344
+ QueryName
345
+ Success
346
+ Results
347
+ RowCount
348
+ ExecutionTime
349
+ ErrorMessage
350
+ }
351
+ }`,{QueryName:e,CategoryID:t,CategoryName:r});return a&&a.GetQueryDataByNameSystemUser?{...a.GetQueryDataByNameSystemUser,Results:a.GetQueryDataByNameSystemUser.Results?N.SafeJSONParse(a.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e,Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(s){return c.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${s}`),{QueryID:"",QueryName:e,Success:!1,Results:null,RowCount:0,ExecutionTime:0,ErrorMessage:s.toString()}}}};R(te,"GraphQLSystemUserClient");let M=te;const re=class re{};R(re,"GetDataOutput");let q=re;const se=class se{};R(se,"SimpleRemoteEntityOutput");let A=se;const ae=class ae{};R(ae,"SimpleRemoteEntity");let _=ae;const ne=class ne{};R(ne,"SimpleRemoteEntityField");let B=ne;const ie=class ie{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),o=await this.executeActionMutation(a);return this.processActionResult(o,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=d.gql`
276
352
  mutation RunAction($input: RunActionInput!) {
277
353
  RunAction(input: $input) {
278
354
  Success
@@ -281,7 +357,7 @@
281
357
  ResultData
282
358
  }
283
359
  }
284
- `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(a){y.LogError(`Failed to parse action result data: ${a}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return y.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=m.gql`
360
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){c.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return c.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=d.gql`
285
361
  mutation RunEntityAction($input: EntityActionInput!) {
286
362
  RunEntityAction(input: $input) {
287
363
  Success
@@ -289,5 +365,5 @@
289
365
  ResultData
290
366
  }
291
367
  }
292
- `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){y.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return y.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(ie,"GraphQLActionClient");let B=ie;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return m.gql}}),exports.ActionItemInput=x,exports.ActionItemOutput=M,exports.FieldMapper=N,exports.GetDataOutput=_,exports.GraphQLActionClient=B,exports.GraphQLDataProvider=V,exports.GraphQLProviderConfigData=G,exports.GraphQLSystemUserClient=U,exports.GraphQLTransactionGroup=C,exports.RoleInput=L,exports.RolesAndUsersInput=P,exports.SimpleRemoteEntity=q,exports.SimpleRemoteEntityField=K,exports.SimpleRemoteEntityOutput=Q,exports.SyncDataAction=ce,exports.SyncDataResult=A,exports.SyncRolesAndUsersResult=$,exports.UserInput=v,exports.setupGraphQLClient=he;
368
+ `;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};R(ie,"GraphQLActionClient");let K=ie;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return d.gql}}),exports.ActionItemInput=v,exports.ActionItemOutput=P,exports.FieldMapper=I,exports.GetDataOutput=q,exports.GraphQLActionClient=K,exports.GraphQLDataProvider=V,exports.GraphQLProviderConfigData=G,exports.GraphQLSystemUserClient=M,exports.GraphQLTransactionGroup=C,exports.RoleInput=U,exports.RolesAndUsersInput=Q,exports.SimpleRemoteEntity=_,exports.SimpleRemoteEntityField=B,exports.SimpleRemoteEntityOutput=A,exports.SyncDataAction=ce,exports.SyncDataResult=x,exports.SyncRolesAndUsersResult=F,exports.UserInput=L,exports.setupGraphQLClient=ge;
293
369
  //# sourceMappingURL=index.cjs.map