@memberjunction/graphql-dataprovider 2.24.0 → 2.25.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,12 +1,20 @@
1
- "use strict";var ue=Object.defineProperty;var g=(R,e)=>ue(R,"name",{value:e,configurable:!0});var h=require("graphql-request"),d=require("@memberjunction/core"),ne=require("@memberjunction/core-entities"),le=require("@tempfix/idb"),ce=require("rxjs"),de=require("graphql-ws"),ye=require("uuid"),V=require("@memberjunction/global");const K=class K{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const a in e)a in this._fieldMap&&(e[this._fieldMap[a]]=e[a],delete e[a]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([a,s])=>s===e)?.[0]??e}ReverseMapFields(e){const a=Object.fromEntries(Object.entries(this._fieldMap).map(([s,t])=>[t,s]));for(const s in e)s in a&&(e[a[s]]=e[s],delete e[s]);return e}};g(K,"FieldMapper");let N=K;const B=class B extends d.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,a,s,t,r,c,n,i){super({Token:e,URL:a,WSURL:s,MJAPIKey:i,RefreshTokenFunction:t},r,c,n)}};g(B,"GraphQLProviderConfigData");let C=B;const E=class E extends d.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
1
+ "use strict";var oe=Object.defineProperty;var E=(w,e)=>oe(w,"name",{value:e,configurable:!0});var p=require("graphql-request"),d=require("@memberjunction/core"),ie=require("@memberjunction/core-entities"),ue=require("@tempfix/idb"),le=require("rxjs"),ce=require("graphql-ws"),de=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 a in e)a in this._fieldMap&&(e[this._fieldMap[a]]=e[a],delete e[a]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([a,s])=>s===e)?.[0]??e}ReverseMapFields(e){const a=Object.fromEntries(Object.entries(this._fieldMap).map(([s,t])=>[t,s]));for(const s in e)s in a&&(e[a[s]]=e[s],delete e[s]);return e}};E(O,"FieldMapper");let S=O;const B=class B extends d.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=p.gql`
2
+ mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
+ ExecuteTransactionGroup(group: $group) {
4
+ Success
5
+ ErrorMessages
6
+ ResultsJSON
7
+ }
8
+ }
9
+ `,a=[];for(const r of this.PendingTransactions)a.push({EntityName:r.BaseEntity.EntityInfo.Name,EntityObjectJSON:await r.BaseEntity.GetDataObjectJSON(),OperationType:r.OperationType});const s={group:{Items:a,Variables:this.Variables.map(r=>({Name:r.Name,ItemIndex:this.MapVariableEntityObjectToPosition(r),FieldName:r.FieldName,Type:r.Type}))}},t=await this._provider.ExecuteGQL(e,s);if(t&&t.ExecuteTransactionGroup){const r=t.ExecuteTransactionGroup,u=[];for(let n=0;n<this.PendingTransactions.length;n++){const i=r.ResultsJSON[n],f=I.SafeJSONParse(i),h=this.PendingTransactions[n];u.push(new d.TransactionResult(h,f,f!==null))}return u}else throw new Error("Failed to execute transaction group")}};E(B,"GraphQLTransactionGroup");let V=B;const k=class k extends d.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,a,s,t,r,u,n,i){super({Token:e,URL:a,WSURL:s,MJAPIKey:i,RefreshTokenFunction:t},r,u,n)}};E(k,"GraphQLProviderConfigData");let F=k;const D=class D extends d.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
2
10
  ${this.userInfoString()}
3
11
  UserRoles_UserIDArray {
4
12
  ${this.userRoleInfoString()}
5
13
  }
6
14
  }
7
- `,this._currentUserQuery=h.gql`query CurrentUserAndRoles {
15
+ `,this._currentUserQuery=p.gql`query CurrentUserAndRoles {
8
16
  ${this._innerCurrentUserQueryString}
9
- }`,this._wsClient=null,this._pushStatusRequests=[],E._instance||(E._instance=this)}static get Instance(){return E._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 ye.v4()}get LocalStoragePrefix(){return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async Config(e,a){try{const s=this.GenerateUUID();return a?(this._sessionId=s,this._configData=e,this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey)):(E.Instance._sessionId===void 0&&(E.Instance._sessionId=s),E.Instance._configData=e,E.Instance._client||(E.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,E.Instance._sessionId,e.MJAPIKey))),super.Config(e)}catch(s){throw d.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 a=this.ConvertBackToMJFields(e.CurrentUser),s=a.UserRoles_UserIDArray.map(t=>this.ConvertBackToMJFields(t));return a.UserRoles_UserIDArray=s,new d.UserInfo(this,{...a,UserRoles:s})}}async RunReport(e,a){const s=h.gql`
17
+ }`,this._wsClient=null,this._pushStatusRequests=[],D._instance||(D._instance=this)}static get Instance(){return D._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(){return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async Config(e,a){try{const s=this.GenerateUUID();return a?(this._sessionId=s,this._configData=e,this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey)):(D.Instance._sessionId===void 0&&(D.Instance._sessionId=s),D.Instance._configData=e,D.Instance._client||(D.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,D.Instance._sessionId,e.MJAPIKey))),super.Config(e)}catch(s){throw d.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 a=this.ConvertBackToMJFields(e.CurrentUser),s=a.UserRoles_UserIDArray.map(t=>this.ConvertBackToMJFields(t));return a.UserRoles_UserIDArray=s,new d.UserInfo(this,{...a,UserRoles:s})}}async RunReport(e,a){const s=p.gql`
10
18
  query GetReportDataQuery ($ReportID: String!) {
11
19
  GetReportData(ReportID: $ReportID) {
12
20
  Success
@@ -15,7 +23,7 @@
15
23
  ExecutionTime
16
24
  ErrorMessage
17
25
  }
18
- }`,t=await this.ExecuteGQL(s,{ReportID:e.ReportID});if(t&&t.GetReportData)return{ReportID:e.ReportID,Success:t.GetReportData.Success,Results:JSON.parse(t.GetReportData.Results),RowCount:t.GetReportData.RowCount,ExecutionTime:t.GetReportData.ExecutionTime,ErrorMessage:t.GetReportData.ErrorMessage}}async RunQuery(e,a){const s=h.gql`
26
+ }`,t=await this.ExecuteGQL(s,{ReportID:e.ReportID});if(t&&t.GetReportData)return{ReportID:e.ReportID,Success:t.GetReportData.Success,Results:JSON.parse(t.GetReportData.Results),RowCount:t.GetReportData.RowCount,ExecutionTime:t.GetReportData.ExecutionTime,ErrorMessage:t.GetReportData.ErrorMessage}}async RunQuery(e,a){const s=p.gql`
19
27
  query GetQueryDataQuery ($QueryID: String!) {
20
28
  GetQueryData(QueryID: $QueryID) {
21
29
  Success
@@ -24,11 +32,11 @@
24
32
  ExecutionTime
25
33
  ErrorMessage
26
34
  }
27
- }`,t=await this.ExecuteGQL(s,{QueryID:e.QueryID});if(t&&t.GetQueryData)return{QueryID:e.QueryID,Success:t.GetQueryData.Success,Results:JSON.parse(t.GetQueryData.Results),RowCount:t.GetQueryData.RowCount,ExecutionTime:t.GetQueryData.ExecutionTime,ErrorMessage:t.GetQueryData.ErrorMessage}}async RunView(e,a){try{let s="",t="";if(e){const r={};let c,n;if(e.ViewEntity)n=e.ViewEntity,c=n.Entity;else{const{entityName:o,v:u}=await this.getEntityNameAndUserView(e,a);n=u,c=o}const i=this.Entities.find(o=>o.Name===c);if(!i)throw new Error(`Entity ${c} not found in metadata`);let p=!1;e.ViewID?(s=`Run${i.ClassName}ViewByID`,t="RunViewByIDInput",r.ViewID=e.ViewID):e.ViewName?(s=`Run${i.ClassName}ViewByName`,t="RunViewByNameInput",r.ViewName=e.ViewName):(p=!0,s=`Run${i.ClassName}DynamicView`,t="RunDynamicViewInput",r.EntityName=e.EntityName),r.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",r.OrderBy=e.OrderBy?e.OrderBy:"",r.UserSearchString=e.UserSearchString?e.UserSearchString:"",r.Fields=e.Fields,r.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,r.MaxRows=e.MaxRows?e.MaxRows:0,r.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,r.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(r.AuditLogDescription=e.AuditLogDescription),p||(r.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",r.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,r.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",r.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const f=this.getViewRunTimeFieldList(i,n,e,p),y=h.gql`
35
+ }`,t=await this.ExecuteGQL(s,{QueryID:e.QueryID});if(t&&t.GetQueryData)return{QueryID:e.QueryID,Success:t.GetQueryData.Success,Results:JSON.parse(t.GetQueryData.Results),RowCount:t.GetQueryData.RowCount,ExecutionTime:t.GetQueryData.ExecutionTime,ErrorMessage:t.GetQueryData.ErrorMessage}}async RunView(e,a){try{let s="",t="";if(e){const r={};let u,n;if(e.ViewEntity)n=e.ViewEntity,u=n.Entity;else{const{entityName:o,v:l}=await this.getEntityNameAndUserView(e,a);n=l,u=o}const i=this.Entities.find(o=>o.Name===u);if(!i)throw new Error(`Entity ${u} not found in metadata`);let f=!1;e.ViewID?(s=`Run${i.ClassName}ViewByID`,t="RunViewByIDInput",r.ViewID=e.ViewID):e.ViewName?(s=`Run${i.ClassName}ViewByName`,t="RunViewByNameInput",r.ViewName=e.ViewName):(f=!0,s=`Run${i.ClassName}DynamicView`,t="RunDynamicViewInput",r.EntityName=e.EntityName),r.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",r.OrderBy=e.OrderBy?e.OrderBy:"",r.UserSearchString=e.UserSearchString?e.UserSearchString:"",r.Fields=e.Fields,r.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,r.MaxRows=e.MaxRows?e.MaxRows:0,r.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,r.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(r.AuditLogDescription=e.AuditLogDescription),f||(r.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",r.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,r.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",r.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const h=this.getViewRunTimeFieldList(i,n,e,f),y=p.gql`
28
36
  query RunViewQuery ($input: ${t}!) {
29
37
  ${s}(input: $input) {
30
38
  Results {
31
- ${f.join(`
39
+ ${h.join(`
32
40
  `)}
33
41
  }
34
42
  UserViewRunID
@@ -38,7 +46,7 @@
38
46
  Success
39
47
  ErrorMessage
40
48
  }
41
- }`,l=await this.ExecuteGQL(y,{input:r});if(l&&l[s]){const o=l[s].Results;if(o&&o.length>0){const u=i.Fields.filter(m=>m.CodeName!==m.Name&&m.CodeName!==void 0);o.forEach(m=>{this.ConvertBackToMJFields(m),u.forEach(D=>{m[D.Name]=m[D.CodeName]})})}return l[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw d.LogError(s),s}}async RunViews(e,a){try{let s=[],t=[],r=[];for(const i of e){let p="",f="";const y={};let l=null,o=null;if(i.ViewEntity)o=i.ViewEntity,l=o.Get("Entity");else{const{entityName:D,v:w}=await this.getEntityNameAndUserView(i,a);o=w,l=D}const u=this.Entities.find(D=>D.Name===l);if(!u)throw new Error(`Entity ${l} not found in metadata`);t.push(u);let m=!1;i.ViewID?(p=`Run${u.ClassName}ViewByID`,f="RunViewByIDInput",y.ViewID=i.ViewID):i.ViewName?(p=`Run${u.ClassName}ViewByName`,f="RunViewByNameInput",y.ViewName=i.ViewName):(m=!0,p=`Run${u.ClassName}DynamicView`,f="RunDynamicViewInput",y.EntityName=i.EntityName),y.ExtraFilter=i.ExtraFilter||"",y.OrderBy=i.OrderBy||"",y.UserSearchString=i.UserSearchString||"",y.Fields=i.Fields,y.IgnoreMaxRows=i.IgnoreMaxRows||!1,y.MaxRows=i.MaxRows||0,y.ForceAuditLog=i.ForceAuditLog||!1,y.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(y.AuditLogDescription=i.AuditLogDescription),m||(y.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=i.OverrideExcludeFilter||"",y.SaveViewResults=i.SaveViewResults||!1),s.push(y),r.push(...this.getViewRunTimeFieldList(u,o,i,m))}const c=h.gql`
49
+ }`,c=await this.ExecuteGQL(y,{input:r});if(c&&c[s]){const o=c[s].Results;if(o&&o.length>0){const l=i.Fields.filter(m=>m.CodeName!==m.Name&&m.CodeName!==void 0);o.forEach(m=>{this.ConvertBackToMJFields(m),l.forEach(g=>{m[g.Name]=m[g.CodeName]})})}return c[s]}}else throw"No parameters passed to RunView";return null}catch(s){throw d.LogError(s),s}}async RunViews(e,a){try{let s=[],t=[],r=[];for(const i of e){let f="",h="";const y={};let c=null,o=null;if(i.ViewEntity)o=i.ViewEntity,c=o.Get("Entity");else{const{entityName:g,v:N}=await this.getEntityNameAndUserView(i,a);o=N,c=g}const l=this.Entities.find(g=>g.Name===c);if(!l)throw new Error(`Entity ${c} not found in metadata`);t.push(l);let m=!1;i.ViewID?(f=`Run${l.ClassName}ViewByID`,h="RunViewByIDInput",y.ViewID=i.ViewID):i.ViewName?(f=`Run${l.ClassName}ViewByName`,h="RunViewByNameInput",y.ViewName=i.ViewName):(m=!0,f=`Run${l.ClassName}DynamicView`,h="RunDynamicViewInput",y.EntityName=i.EntityName),y.ExtraFilter=i.ExtraFilter||"",y.OrderBy=i.OrderBy||"",y.UserSearchString=i.UserSearchString||"",y.Fields=i.Fields,y.IgnoreMaxRows=i.IgnoreMaxRows||!1,y.MaxRows=i.MaxRows||0,y.ForceAuditLog=i.ForceAuditLog||!1,y.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(y.AuditLogDescription=i.AuditLogDescription),m||(y.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",y.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,y.OverrideExcludeFilter=i.OverrideExcludeFilter||"",y.SaveViewResults=i.SaveViewResults||!1),s.push(y),r.push(...this.getViewRunTimeFieldList(l,o,i,m))}const u=p.gql`
42
50
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
43
51
  RunViews(input: $input) {
44
52
  Results {
@@ -53,7 +61,7 @@
53
61
  Success
54
62
  ErrorMessage
55
63
  }
56
- }`,n=await this.ExecuteGQL(c,{input:s});if(n&&n.RunViews){const i=n.RunViews;for(const[p,f]of i.entries())f.Results=f.Results.map(y=>{let l=JSON.parse(y.Data);return this.ConvertBackToMJFields(l),l});return i}return null}catch(s){throw d.LogError(s),s}}async getEntityNameAndUserView(e,a){let s,t;if(e.EntityName)s=e.EntityName;else if(e.ViewID)t=await ne.ViewInfo.GetViewEntity(e.ViewID,a),s=t.Entity;else if(e.ViewName)t=await ne.ViewInfo.GetViewEntityByName(e.ViewName,a),s=t.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:t}}getViewRunTimeFieldList(e,a,s,t){const r=[],c=new N;if(s.Fields){for(const n of e.PrimaryKeys)s.Fields.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&r.push(n.Name);s.Fields.forEach(n=>{r.push(c.MapFieldName(n))})}else if(t)e.Fields.forEach(n=>{n.IsBinaryFieldType||r.push(c.MapFieldName(n.CodeName))});else{for(const n of e.PrimaryKeys)r.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&r.push(n.Name);a.Columns.forEach(n=>{n.hidden===!1&&!r.find(i=>i.trim().toLowerCase()===n.EntityField?.Name.trim().toLowerCase())&&n.EntityField&&r.push(c.MapFieldName(n.EntityField.CodeName))})}return r}get ProviderType(){return d.ProviderType.Network}async GetRecordChanges(e,a){try{const s={EntityName:"Record Changes",ExtraFilter:`RecordID = '${a.Values()}' AND Entity = '${e}'`},t=await this.RunView(s);return t?t.Results.sort((r,c)=>r.ChangedAt>c.ChangedAt?-1:1):null}catch(s){throw d.LogError(s),s}}async GetRecordDependencies(e,a){try{const s=h.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
64
+ }`,n=await this.ExecuteGQL(u,{input:s});if(n&&n.RunViews){const i=n.RunViews;for(const[f,h]of i.entries())h.Results=h.Results.map(y=>{let c=JSON.parse(y.Data);return this.ConvertBackToMJFields(c),c});return i}return null}catch(s){throw d.LogError(s),s}}async getEntityNameAndUserView(e,a){let s,t;if(e.EntityName)s=e.EntityName;else if(e.ViewID)t=await ie.ViewInfo.GetViewEntity(e.ViewID,a),s=t.Entity;else if(e.ViewName)t=await ie.ViewInfo.GetViewEntityByName(e.ViewName,a),s=t.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:s,v:t}}getViewRunTimeFieldList(e,a,s,t){const r=[],u=new S;if(s.Fields){for(const n of e.PrimaryKeys)s.Fields.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&r.push(n.Name);s.Fields.forEach(n=>{r.push(u.MapFieldName(n))})}else if(t)e.Fields.forEach(n=>{n.IsBinaryFieldType||r.push(u.MapFieldName(n.CodeName))});else{for(const n of e.PrimaryKeys)r.find(i=>i.trim().toLowerCase()===n.Name.toLowerCase())===void 0&&r.push(n.Name);a.Columns.forEach(n=>{n.hidden===!1&&!r.find(i=>i.trim().toLowerCase()===n.EntityField?.Name.trim().toLowerCase())&&n.EntityField&&r.push(u.MapFieldName(n.EntityField.CodeName))})}return r}get ProviderType(){return d.ProviderType.Network}async GetRecordChanges(e,a){try{const s={EntityName:"Record Changes",ExtraFilter:`RecordID = '${a.Values()}' AND Entity = '${e}'`},t=await this.RunView(s);return t?t.Results.sort((r,u)=>r.ChangedAt>u.ChangedAt?-1:1):null}catch(s){throw d.LogError(s),s}}async GetRecordDependencies(e,a){try{const s=p.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
57
65
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
58
66
  EntityName
59
67
  RelatedEntityName
@@ -65,7 +73,7 @@
65
73
  }
66
74
  }
67
75
  }
68
- }`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}};return(await this.ExecuteGQL(s,t))?.GetRecordDependencies}catch(s){throw d.LogError(s),s}}ensureKeyValuePairValueIsString(e){return e.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()}))}async GetRecordDuplicates(e,a){if(!e)return null;const s=h.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
76
+ }`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}};return(await this.ExecuteGQL(s,t))?.GetRecordDependencies}catch(s){throw d.LogError(s),s}}ensureKeyValuePairValueIsString(e){return e.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()}))}async GetRecordDuplicates(e,a){if(!e)return null;const s=p.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
69
77
  GetRecordDuplicates(params: $params) {
70
78
  Status
71
79
  ErrorMessage
@@ -87,7 +95,7 @@
87
95
  }
88
96
  }
89
97
  }
90
- }`;let t={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(c=>c.Copy())};const r=await this.ExecuteGQL(s,{params:t});if(r&&r.GetRecordDuplicates)return r.GetRecordDuplicates}async MergeRecords(e){const a=this.Entities.find(s=>s.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!a||!a.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const s=h.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
98
+ }`;let t={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(u=>u.Copy())};const r=await this.ExecuteGQL(s,{params:t});if(r&&r.GetRecordDuplicates)return r.GetRecordDuplicates}async MergeRecords(e){const a=this.Entities.find(s=>s.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!a||!a.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const s=p.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
91
99
  MergeRecords(request: $request) {
92
100
  Success
93
101
  OverallStatus
@@ -104,32 +112,32 @@
104
112
  Message
105
113
  }
106
114
  }
107
- }`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(c=>({FieldName:c.FieldName,Value:c.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(c=>c.Copy())};return(await this.ExecuteGQL(s,{request:t}))?.MergeRecords}catch(s){return d.LogError(s),{Success:!1,OverallStatus:s&&s.message?s.message:s,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,a,s){const t=new d.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const r={input:{}},c=e.IsSaved?"Update":"Create";t.StartedAt=new Date,t.Type=e.IsSaved?"update":"create",t.OriginalValues=e.Fields.map(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(t);const n=`${c}${e.EntityInfo.ClassName}`,i=e.Fields.filter(l=>!l.ReadOnly||l.IsPrimaryKey&&e.IsSaved),p=new N,f=` ${n}(input: $input) {
108
- ${e.Fields.map(l=>p.MapFieldName(l.CodeName)).join(`
115
+ }`,t={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(u=>({FieldName:u.FieldName,Value:u.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(u=>u.Copy())};return(await this.ExecuteGQL(s,{request:t}))?.MergeRecords}catch(s){return d.LogError(s),{Success:!1,OverallStatus:s&&s.message?s.message:s,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,a,s){const t=new d.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const r={input:{}},u=e.IsSaved?"Update":"Create";t.StartedAt=new Date,t.Type=e.IsSaved?"update":"create",t.OriginalValues=e.Fields.map(c=>({FieldName:c.CodeName,Value:c.Value})),e.ResultHistory.push(t);const n=`${u}${e.EntityInfo.ClassName}`,i=e.Fields.filter(c=>!c.ReadOnly||c.IsPrimaryKey&&e.IsSaved),f=new S,h=` ${n}(input: $input) {
116
+ ${e.Fields.map(c=>f.MapFieldName(c.CodeName)).join(`
109
117
  `)}
110
- }`,y=h.gql`mutation ${c}${e.EntityInfo.ClassName} ($input: ${n}Input!) {
111
- ${f}
118
+ }`,y=p.gql`mutation ${u}${e.EntityInfo.ClassName} ($input: ${n}Input!) {
119
+ ${h}
112
120
  }
113
- `;for(let l=0;l<i.length;l++){const o=i[l];let u=o.Value;if(u)switch(o.EntityFieldInfo.TSType){case d.EntityFieldTSType.Date:u=u.getTime();break;case d.EntityFieldTSType.Boolean:typeof u!="boolean"&&(u=parseInt(u)!==0);break;case d.EntityFieldTSType.Number:if(typeof u!="number"){const m=Number(u);isNaN(m)||(u=m)}break}u===null&&o.EntityFieldInfo.AllowsNull===!1&&(o.EntityFieldInfo.DefaultValue!==null?u=o.EntityFieldInfo.DefaultValue:o.FieldType===d.EntityFieldTSType.Number||o.FieldType===d.EntityFieldTSType.Boolean?u=0:u=""),r.input[o.CodeName]=u}if(c.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const l=[];e.Fields.forEach(o=>{let u=null;o.OldValue!==null&&o.OldValue!==void 0&&(o.EntityFieldInfo.TSType===d.EntityFieldTSType.Date?u=o.OldValue.getTime().toString():o.EntityFieldInfo.TSType===d.EntityFieldTSType.Boolean?u=o.OldValue===!0?"1":"0":typeof o.OldValue!="string"?u=o.OldValue.toString():u=o.OldValue),l.push({Key:o.CodeName,Value:u})}),r.input.OldValues___=l}if(e.TransactionGroup)return new Promise((l,o)=>{const u=[{varName:"input",inputType:n+"Input!"}];e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new d.TransactionItem(e,f,r,{mutationName:n,mutationInputTypes:u},(m,D)=>{t.EndedAt=new Date,D&&m?(t.Success=!0,l(this.ConvertBackToMJFields(m))):(t.Success=!1,t.Message="Transaction failed",o())}))});{const l=await this.ExecuteGQL(y,r);if(l&&l[c+e.EntityInfo.ClassName])return t.Success=!0,t.EndedAt=new Date,this.ConvertBackToMJFields(l[c+e.EntityInfo.ClassName]);throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(r){return t.Success=!1,t.EndedAt=new Date,t.Message=r.response?.errors?.length>0?r.response.errors[0].message:r.message,d.LogError(r),null}}async Load(e,a,s=null,t){try{const r={};let c="",n="";for(let l=0;l<a.KeyValuePairs.length;l++){const o=e.Fields.find(D=>D.Name.trim().toLowerCase()===a.KeyValuePairs[l].FieldName.trim().toLowerCase()).EntityFieldInfo,u=a.GetValueByIndex(l),m=o.GraphQLType;if(n.length>0&&(n+=", "),n+=`$${o.CodeName}: ${m}!`,c.length>0&&(c+=", "),c+=`${o.CodeName}: $${o.CodeName}`,o.TSType===d.EntityFieldTSType.Number){if(isNaN(a.GetValueByIndex(l)))throw new Error(`Primary Key value ${u} (${o.Name}) is not a valid number`);r[o.CodeName]=parseInt(u)}else r[o.CodeName]=u}const i=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",p=new N,f=h.gql`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${n}) {
114
- ${e.EntityInfo.ClassName}(${c}) {
115
- ${e.Fields.filter(l=>!l.EntityFieldInfo.IsBinaryFieldType).map(l=>l.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?l.CodeName.replace("__mj_","_mj__"):l.CodeName).join(`
121
+ `;for(let c=0;c<i.length;c++){const o=i[c];let l=o.Value;if(l)switch(o.EntityFieldInfo.TSType){case d.EntityFieldTSType.Date:l=l.getTime();break;case d.EntityFieldTSType.Boolean:typeof l!="boolean"&&(l=parseInt(l)!==0);break;case d.EntityFieldTSType.Number:if(typeof l!="number"){const m=Number(l);isNaN(m)||(l=m)}break}l===null&&o.EntityFieldInfo.AllowsNull===!1&&(o.EntityFieldInfo.DefaultValue!==null?l=o.EntityFieldInfo.DefaultValue:o.FieldType===d.EntityFieldTSType.Number||o.FieldType===d.EntityFieldTSType.Boolean?l=0:l=""),r.input[o.CodeName]=l}if(u.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const c=[];e.Fields.forEach(o=>{let l=null;o.OldValue!==null&&o.OldValue!==void 0&&(o.EntityFieldInfo.TSType===d.EntityFieldTSType.Date?l=o.OldValue.getTime().toString():o.EntityFieldInfo.TSType===d.EntityFieldTSType.Boolean?l=o.OldValue===!0?"1":"0":typeof o.OldValue!="string"?l=o.OldValue.toString():l=o.OldValue),c.push({Key:o.CodeName,Value:l})}),r.input.OldValues___=c}if(e.TransactionGroup){const c=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new d.TransactionItem(e,t.Type==="create"?"Create":"Update",h,r,{mutationName:n,mutationInputTypes:c},(o,l)=>{t.EndedAt=new Date,l&&o?(t.Success=!0,t.NewValues=this.ConvertBackToMJFields(o)):(t.Success=!1,t.Message="Transaction failed")})),!0}else{const c=await this.ExecuteGQL(y,r);if(c&&c[u+e.EntityInfo.ClassName])return t.Success=!0,t.EndedAt=new Date,t.NewValues=this.ConvertBackToMJFields(c[u+e.EntityInfo.ClassName]),t.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(r){return t.Success=!1,t.EndedAt=new Date,t.Message=r.response?.errors?.length>0?r.response.errors[0].message:r.message,d.LogError(r),null}}async Load(e,a,s=null,t){try{const r={};let u="",n="";for(let c=0;c<a.KeyValuePairs.length;c++){const o=e.Fields.find(g=>g.Name.trim().toLowerCase()===a.KeyValuePairs[c].FieldName.trim().toLowerCase()).EntityFieldInfo,l=a.GetValueByIndex(c),m=o.GraphQLType;if(n.length>0&&(n+=", "),n+=`$${o.CodeName}: ${m}!`,u.length>0&&(u+=", "),u+=`${o.CodeName}: $${o.CodeName}`,o.TSType===d.EntityFieldTSType.Number){if(isNaN(a.GetValueByIndex(c)))throw new Error(`Primary Key value ${l} (${o.Name}) is not a valid number`);r[o.CodeName]=parseInt(l)}else r[o.CodeName]=l}const i=s&&s.length>0?this.getRelatedEntityString(e.EntityInfo,s):"",f=new S,h=p.gql`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${n}) {
122
+ ${e.EntityInfo.ClassName}(${u}) {
123
+ ${e.Fields.filter(c=>!c.EntityFieldInfo.IsBinaryFieldType).map(c=>c.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?c.CodeName.replace("__mj_","_mj__"):c.CodeName).join(`
116
124
  `)}
117
125
  ${i}
118
126
  }
119
127
  }
120
- `,y=await this.ExecuteGQL(f,r);return y&&y[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(y[e.EntityInfo.ClassName]):null}catch(r){return d.LogError(r),null}}ConvertBackToMJFields(e){return new N().ReverseMapFields(e),e}getRelatedEntityString(e,a){let s="";for(let t=0;t<e.RelatedEntities.length;t++)if(a.indexOf(e.RelatedEntities[t].RelatedEntity)>=0){const r=e.RelatedEntities[t],c=this.Entities.find(i=>i.ID===r.RelatedEntityID);let n="";r.Type.toLowerCase().trim()==="many to many"?n=`${r.RelatedEntityCodeName}_${r.JoinEntityJoinField.replace(/\s/g,"")}`:n=`${r.RelatedEntityCodeName}_${r.RelatedEntityJoinField.replace(/\s/g,"")}`,s+=`
128
+ `,y=await this.ExecuteGQL(h,r);return y&&y[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(y[e.EntityInfo.ClassName]):null}catch(r){return d.LogError(r),null}}ConvertBackToMJFields(e){return new S().ReverseMapFields(e),e}getRelatedEntityString(e,a){let s="";for(let t=0;t<e.RelatedEntities.length;t++)if(a.indexOf(e.RelatedEntities[t].RelatedEntity)>=0){const r=e.RelatedEntities[t],u=this.Entities.find(i=>i.ID===r.RelatedEntityID);let n="";r.Type.toLowerCase().trim()==="many to many"?n=`${r.RelatedEntityCodeName}_${r.JoinEntityJoinField.replace(/\s/g,"")}`:n=`${r.RelatedEntityCodeName}_${r.RelatedEntityJoinField.replace(/\s/g,"")}`,s+=`
121
129
  ${n} {
122
- ${c.Fields.map(i=>i.CodeName).join(`
130
+ ${u.Fields.map(i=>i.CodeName).join(`
123
131
  `)}
124
132
  }
125
- `}return s}async Delete(e,a,s){const t=new d.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),t.StartedAt=new Date,t.Type="delete",t.OriginalValues=e.Fields.map(o=>({FieldName:o.CodeName,Value:o.Value})),e.ResultHistory.push(t);const r={},c=[];let n="",i="",p="";for(let o of e.PrimaryKey.KeyValuePairs){const u=e.Fields.find(m=>m.Name.trim().toLowerCase()===o.FieldName.trim().toLowerCase());r[u.CodeName]=u.Value,c.push({varName:u.CodeName,inputType:u.EntityFieldInfo.GraphQLType+"!"}),n.length>0&&(n+=", "),n+=`${u.CodeName}: $${u.CodeName}`,i.length>0&&(i+=", "),i+=`$${u.CodeName}: ${u.EntityFieldInfo.GraphQLType}!`,p.length>0&&(p+=`
126
- `),p+=`${u.CodeName}`}c.push({varName:"options___",inputType:"DeleteOptionsInput!"}),r.options___=a||{SkipEntityAIActions:!1,SkipEntityActions:!1};const f="Delete"+e.EntityInfo.ClassName,y=h.gql`${f}(${n}, options___: $options___) {
127
- ${p}
133
+ `}return s}async Delete(e,a,s){const t=new d.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),t.StartedAt=new Date,t.Type="delete",t.OriginalValues=e.Fields.map(o=>({FieldName:o.CodeName,Value:o.Value})),e.ResultHistory.push(t);const r={},u=[];let n="",i="",f="";for(let o of e.PrimaryKey.KeyValuePairs){const l=e.Fields.find(m=>m.Name.trim().toLowerCase()===o.FieldName.trim().toLowerCase());r[l.CodeName]=l.Value,u.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}!`,f.length>0&&(f+=`
134
+ `),f+=`${l.CodeName}`}u.push({varName:"options___",inputType:"DeleteOptionsInput!"}),r.options___=a||{SkipEntityAIActions:!1,SkipEntityActions:!1};const h="Delete"+e.EntityInfo.ClassName,y=p.gql`${h}(${n}, options___: $options___) {
135
+ ${f}
128
136
  }
129
- `,l=h.gql`mutation ${f} (${i}, $options___: DeleteOptionsInput!) {
137
+ `,c=p.gql`mutation ${h} (${i}, $options___: DeleteOptionsInput!) {
130
138
  ${y}
131
139
  }
132
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),new Promise((o,u)=>{e.TransactionGroup.AddTransaction(new d.TransactionItem(e,y,r,{mutationName:f,mutationInputTypes:c},(m,D)=>{if(t.EndedAt=new Date,D&&m){let w=!0;for(const ie of e.PrimaryKey.KeyValuePairs)ie.Value!==m[ie.FieldName]&&(w=!1);w?(t.Success=!0,o(!0)):(t.Success=!1,t.Message="Transaction failed to commit",u())}else t.Success=!1,t.Message="Transaction failed to commit",u()}))});{const o=await this.ExecuteGQL(l,r);if(o&&o[f]){const u=o[f];for(let m of e.PrimaryKey.KeyValuePairs){let D=u[m.FieldName],w=m.Value;if(typeof w=="number"&&(w=w.toString()),typeof D=="number"&&(D=D.toString()),w!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${m.FieldName}, Original: ${w}, Returned: ${D}`)}return t.Success=!0,t.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(r){return t.EndedAt=new Date,t.Success=!1,t.Message=r.response?.errors?.length>0?r.response.errors[0].message:r.message,d.LogError(r),!1}}async GetDatasetByName(e,a){const s=h.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
140
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new d.TransactionItem(e,"Delete",y,r,{mutationName:h,mutationInputTypes:u},(o,l)=>{if(t.EndedAt=new Date,l&&o){let m=!0;for(const g of e.PrimaryKey.KeyValuePairs)g.Value!==o[g.FieldName]&&(m=!1);m?t.Success=!0:(t.Success=!1,t.Message="Transaction failed to commit")}else t.Success=!1,t.Message="Transaction failed to commit"})),!0;{const o=await this.ExecuteGQL(c,r);if(o&&o[h]){const l=o[h];for(let m of e.PrimaryKey.KeyValuePairs){let g=l[m.FieldName],N=m.Value;if(typeof N=="number"&&(N=N.toString()),typeof g=="number"&&(g=g.toString()),N!==g)throw new Error(`Primary key value mismatch in server Delete response. Field: ${m.FieldName}, Original: ${N}, Returned: ${g}`)}return t.Success=!0,t.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(r){return t.EndedAt=new Date,t.Success=!1,t.Message=r.response?.errors?.length>0?r.response.errors[0].message:r.message,d.LogError(r),!1}}async GetDatasetByName(e,a){const s=p.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
133
141
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
134
142
  DatasetID
135
143
  DatasetName
@@ -138,7 +146,7 @@
138
146
  LatestUpdateDate
139
147
  Results
140
148
  }
141
- }`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:a});return t&&t.GetDatasetByName&&t.GetDatasetByName.Success?{DatasetID:t.GetDatasetByName.DatasetID,DatasetName:t.GetDatasetByName.DatasetName,Success:t.GetDatasetByName.Success,Status:t.GetDatasetByName.Status,LatestUpdateDate:new Date(t.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(t.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,a){const s=h.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
149
+ }`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:a});return t&&t.GetDatasetByName&&t.GetDatasetByName.Success?{DatasetID:t.GetDatasetByName.DatasetID,DatasetName:t.GetDatasetByName.DatasetName,Success:t.GetDatasetByName.Success,Status:t.GetDatasetByName.Status,LatestUpdateDate:new Date(t.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(t.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,a){const s=p.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
142
150
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
143
151
  DatasetID
144
152
  DatasetName
@@ -147,22 +155,22 @@
147
155
  LatestUpdateDate
148
156
  EntityUpdateDates
149
157
  }
150
- }`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:a});return t&&t.GetDatasetStatusByName&&t.GetDatasetStatusByName.Success?{DatasetID:t.GetDatasetStatusByName.DatasetID,DatasetName:t.GetDatasetStatusByName.DatasetName,Success:t.GetDatasetStatusByName.Success,Status:t.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(t.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(t.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new T(this)}async GetRecordFavoriteStatus(e,a,s){if(!s.Validate().IsValid)return!1;const r=this.Entities.find(i=>i.Name===a);if(!r)throw new Error(`Entity ${a} not found in metadata`);const c=h.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
158
+ }`,t=await this.ExecuteGQL(s,{DatasetName:e,ItemFilters:a});return t&&t.GetDatasetStatusByName&&t.GetDatasetStatusByName.Success?{DatasetID:t.GetDatasetStatusByName.DatasetID,DatasetName:t.GetDatasetStatusByName.DatasetName,Success:t.GetDatasetStatusByName.Success,Status:t.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(t.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(t.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new V(this)}async GetRecordFavoriteStatus(e,a,s){if(!s.Validate().IsValid)return!1;const r=this.Entities.find(i=>i.Name===a);if(!r)throw new Error(`Entity ${a} not found in metadata`);const u=p.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
151
159
  GetRecordFavoriteStatus(params: $params) {
152
160
  Success
153
161
  IsFavorite
154
162
  }
155
- }`,n=await this.ExecuteGQL(c,{params:{UserID:e,EntityID:r.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}}});if(n&&n.GetRecordFavoriteStatus&&n.GetRecordFavoriteStatus.Success)return n.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,a,s,t,r){const c=this.Entities.find(p=>p.Name===a);if(!c)throw new Error(`Entity ${a} not found in metadata`);const n=h.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
163
+ }`,n=await this.ExecuteGQL(u,{params:{UserID:e,EntityID:r.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}}});if(n&&n.GetRecordFavoriteStatus&&n.GetRecordFavoriteStatus.Success)return n.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,a,s,t,r){const u=this.Entities.find(f=>f.Name===a);if(!u)throw new Error(`Entity ${a} not found in metadata`);const n=p.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
156
164
  SetRecordFavoriteStatus(params: $params){
157
165
  Success
158
166
  }
159
- }`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:c.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)},IsFavorite:t}});if(i&&i.SetRecordFavoriteStatus!==null)return i.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,a){if(!e||!a||a.KeyValuePairs?.length===0)return null;const s=h.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
167
+ }`,i=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:u.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)},IsFavorite:t}});if(i&&i.SetRecordFavoriteStatus!==null)return i.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,a){if(!e||!a||a.KeyValuePairs?.length===0)return null;const s=p.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
160
168
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
161
169
  Success
162
170
  Status
163
171
  RecordName
164
172
  }
165
- }`,t=await this.ExecuteGQL(s,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}});if(t&&t.GetEntityRecordName&&t.GetEntityRecordName.Success)return t.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const a=h.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
173
+ }`,t=await this.ExecuteGQL(s,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}});if(t&&t.GetEntityRecordName&&t.GetEntityRecordName.Success)return t.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const a=p.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
166
174
  GetEntityRecordNames(info: $info) {
167
175
  Success
168
176
  Status
@@ -175,27 +183,23 @@
175
183
  EntityName
176
184
  RecordName
177
185
  }
178
- }`,s=await this.ExecuteGQL(a,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(s&&s.GetEntityRecordNames)return s.GetEntityRecordNames}static async ExecuteGQL(e,a,s=!0){return E.Instance.ExecuteGQL(e,a,s)}async ExecuteGQL(e,a,s=!0){try{return await this._client.request(e,a)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(s)return await this.RefreshToken(),await this.ExecuteGQL(e,a,!1);throw d.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw d.LogError(t),t}}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 E.Instance.RefreshToken()}CreateNewGraphQLClient(e,a,s,t){const r={"x-session-id":s};return a&&(r.authorization="Bearer "+a),t&&(r["x-mj-api-key"]=t),new h.GraphQLClient(e,{headers:r})}userInfoString(){return this.infoString(new d.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new d.UserRoleInfo(null))}infoString(e){let a="";const s=Object.keys(e);for(const t of s)t.startsWith("__mj_")?a+=t.replace("__mj_","_mj__")+`
186
+ }`,s=await this.ExecuteGQL(a,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(s&&s.GetEntityRecordNames)return s.GetEntityRecordNames}static async ExecuteGQL(e,a,s=!0){return D.Instance.ExecuteGQL(e,a,s)}async ExecuteGQL(e,a,s=!0){try{return await this._client.request(e,a)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(s)return await this.RefreshToken(),await this.ExecuteGQL(e,a,!1);throw d.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw d.LogError(t),t}}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 D.Instance.RefreshToken()}CreateNewGraphQLClient(e,a,s,t){const r={"x-session-id":s};return a&&(r.authorization="Bearer "+a),t&&(r["x-mj-api-key"]=t),new p.GraphQLClient(e,{headers:r})}userInfoString(){return this.infoString(new d.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new d.UserRoleInfo(null))}infoString(e){let a="";const s=Object.keys(e);for(const t of s)t.startsWith("__mj_")?a+=t.replace("__mj_","_mj__")+`
179
187
  `:t.startsWith("_")||(a+=t+`
180
- `);return a}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new G),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=de.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const a=this._pushStatusRequests.find(r=>r.sessionId===e);if(a)return a.observable;const s=h.gql`subscription StatusUpdates($sessionId: String!) {
188
+ `);return a}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new G),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=ce.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const a=this._pushStatusRequests.find(r=>r.sessionId===e);if(a)return a.observable;const s=p.gql`subscription StatusUpdates($sessionId: String!) {
181
189
  statusUpdates(sessionId: $sessionId) {
182
190
  date
183
191
  message
184
192
  sessionId
185
193
  }
186
194
  }
187
- `,t=new ce.Observable(r=>(this._wsClient.subscribe({query:s,variables:{sessionId:e}},{next:c=>r.next(c.data.statusUpdates),error:c=>r.error(c),complete:()=>r.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:t}),t}};g(E,"GraphQLDataProvider");let I=E;const O=class O{constructor(){this._localStorage={}}async getItem(e){return new Promise(a=>{this._localStorage.hasOwnProperty(e)?a(this._localStorage[e]):a(null)})}async setItem(e,a){return new Promise(s=>{this._localStorage[e]=a,s()})}async remove(e){return new Promise(a=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],a()})}};g(O,"BrowserStorageProviderBase");let F=O;const me="MJ_Metadata",S="Metadata_KVPairs",b=class b extends F{constructor(){super(),this.dbPromise=le.openDB(me,1,{upgrade(e){e.objectStoreNames.contains(S)||e.createObjectStore(S)}})}async setItem(e,a){const t=(await this.dbPromise).transaction(S,"readwrite");await t.objectStore(S).put(a,e),await t.done}async getItem(e){return await(await this.dbPromise).transaction(S).objectStore(S).get(e)}async remove(e){const s=(await this.dbPromise).transaction(S,"readwrite");await s.objectStore(S).delete(e),await s.done}};g(b,"BrowserIndexedDBStorageProvider");let G=b;const J=class J extends d.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(e){let a="",s="";const t={};for(let n=0;n<e.length;n++){const i=e[n];let p=i.Instruction;if(i.Vars){const f=Object.keys(i.Vars);for(let y=0;y<f.length;y++){const l=f[y],o=`${l}_${n}`;t[o]=i.Vars[l];const u=new RegExp("\\$"+l,"g");p=p.replace(u,"$"+o);const m=i.ExtraData.mutationInputTypes.find(D=>D.varName===l)?.inputType;s+=`$${o}: ${m}
188
- `}}a+=`mutation_${n}: `+p+`
189
- `}a=`mutation TransactionGroup(${s}){
190
- `+a+`
191
- }`;const r=await this._provider.ExecuteGQL(a,t),c=[];for(let n=0;n<e.length;n++){const i=r[`mutation_${n}`],p=e[n];c.push(new d.TransactionResult(p,i,i!==null))}return c}};g(J,"GraphQLTransactionGroup");let T=J;async function pe(R){const e=new I;return d.SetProvider(e),await e.Config(R),V.MJGlobal.Instance.RaiseEvent({event:V.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}g(pe,"setupGraphQLClient");const j=class j{};g(j,"SyncRolesAndUsersResult");let $=j;const W=class W{};g(W,"RoleInput");let L=W;const z=class z{};g(z,"UserInput");let v=z;const H=class H{};g(H,"RolesAndUsersInput");let _=H;var oe=(R=>(R.Create="Create",R.Update="Update",R.CreateOrUpdate="CreateOrUpdate",R.Delete="Delete",R.DeleteWithFilter="DeleteWithFilter",R))(oe||{});const X=class X{};g(X,"ActionItemInput");let U=X;const Z=class Z{constructor(){this.Results=[]}};g(Z,"SyncDataResult");let P=Z;const Y=class Y{};g(Y,"ActionItemOutput");let M=Y;const ee=class ee{get Client(){return this._client}constructor(e,a,s,t){const r={"x-session-id":s};a&&(r.authorization="Bearer "+a),t&&(r["x-mj-api-key"]=t),this._client=new h.GraphQLClient(e,{headers:r})}async GetData(e,a){try{const t=await this.Client.request(`query GetData($input: GetDataInputType!) {
195
+ `,t=new le.Observable(r=>(this._wsClient.subscribe({query:s,variables:{sessionId:e}},{next:u=>r.next(u.data.statusUpdates),error:u=>r.error(u),complete:()=>r.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:t}),t}};E(D,"GraphQLDataProvider");let C=D;const b=class b{constructor(){this._localStorage={}}async getItem(e){return new Promise(a=>{this._localStorage.hasOwnProperty(e)?a(this._localStorage[e]):a(null)})}async setItem(e,a){return new Promise(s=>{this._localStorage[e]=a,s()})}async remove(e){return new Promise(a=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],a()})}};E(b,"BrowserStorageProviderBase");let T=b;const ye="MJ_Metadata",R="Metadata_KVPairs",J=class J extends T{constructor(){super(),this.dbPromise=ue.openDB(ye,1,{upgrade(e){e.objectStoreNames.contains(R)||e.createObjectStore(R)}})}async setItem(e,a){const t=(await this.dbPromise).transaction(R,"readwrite");await t.objectStore(R).put(a,e),await t.done}async getItem(e){return await(await this.dbPromise).transaction(R).objectStore(R).get(e)}async remove(e){const s=(await this.dbPromise).transaction(R,"readwrite");await s.objectStore(R).delete(e),await s.done}};E(J,"BrowserIndexedDBStorageProvider");let G=J;async function me(w){const e=new C;return d.SetProvider(e),await e.Config(w),I.MJGlobal.Instance.RaiseEvent({event:I.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}E(me,"setupGraphQLClient");const j=class j{};E(j,"SyncRolesAndUsersResult");let $=j;const W=class W{};E(W,"RoleInput");let L=W;const z=class z{};E(z,"UserInput");let v=z;const H=class H{};E(H,"RolesAndUsersInput");let _=H;var ne=(w=>(w.Create="Create",w.Update="Update",w.CreateOrUpdate="CreateOrUpdate",w.Delete="Delete",w.DeleteWithFilter="DeleteWithFilter",w))(ne||{});const X=class X{};E(X,"ActionItemInput");let P=X;const Z=class Z{constructor(){this.Results=[]}};E(Z,"SyncDataResult");let U=Z;const Y=class Y{};E(Y,"ActionItemOutput");let M=Y;const ee=class ee{get Client(){return this._client}constructor(e,a,s,t){const r={"x-session-id":s};a&&(r.authorization="Bearer "+a),t&&(r["x-mj-api-key"]=t),this._client=new p.GraphQLClient(e,{headers:r})}async GetData(e,a){try{const t=await this.Client.request(`query GetData($input: GetDataInputType!) {
192
196
  GetData(input: $input) {
193
197
  Success
194
198
  ErrorMessages
195
199
  Queries
196
200
  Results
197
201
  }
198
- }`,{input:{Queries:e,Token:"nope"}});return t&&t.GetData?{Success:t.GetData.Success,Results:t.GetData.Results.map(r=>r?V.SafeJSONParse(r):null),ErrorMessages:t.GetData.ErrorMessages,Queries:t.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:t.GetData?.ErrorMessages??["Unknown error"],Queries:t.GetData?.Queries??e}}catch(s){const t=`GraphQLSystemUserClient::GetData - Error getting geta - ${s}`;return d.LogError(t),{Success:!1,Results:[],ErrorMessages:[t],Queries:e}}}async GetAllRemoteEntities(){try{const a=await this.Client.request(`query GetAllEntities {
202
+ }`,{input:{Queries:e,Token:"nope"}});return t&&t.GetData?{Success:t.GetData.Success,Results:t.GetData.Results.map(r=>r?I.SafeJSONParse(r):null),ErrorMessages:t.GetData.ErrorMessages,Queries:t.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:t.GetData?.ErrorMessages??["Unknown error"],Queries:t.GetData?.Queries??e}}catch(s){const t=`GraphQLSystemUserClient::GetData - Error getting geta - ${s}`;return d.LogError(t),{Success:!1,Results:[],ErrorMessages:[t],Queries:e}}}async GetAllRemoteEntities(){try{const a=await this.Client.request(`query GetAllEntities {
199
203
  GetAllEntities {
200
204
  Success
201
205
  ErrorMessage
@@ -246,5 +250,5 @@
246
250
  SyncRolesAndUsers(data: $data) {
247
251
  Success
248
252
  }
249
- }`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(a){return d.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${a}`),{Success:!1}}}};g(ee,"GraphQLSystemUserClient");let x=ee;const te=class te{};g(te,"GetDataOutput");let q=te;const se=class se{};g(se,"SimpleRemoteEntityOutput");let Q=se;const ae=class ae{};g(ae,"SimpleRemoteEntity");let A=ae;const re=class re{};g(re,"SimpleRemoteEntityField");let k=re;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return h.gql}}),exports.ActionItemInput=U,exports.ActionItemOutput=M,exports.FieldMapper=N,exports.GetDataOutput=q,exports.GraphQLDataProvider=I,exports.GraphQLProviderConfigData=C,exports.GraphQLSystemUserClient=x,exports.RoleInput=L,exports.RolesAndUsersInput=_,exports.SimpleRemoteEntity=A,exports.SimpleRemoteEntityField=k,exports.SimpleRemoteEntityOutput=Q,exports.SyncDataAction=oe,exports.SyncDataResult=P,exports.SyncRolesAndUsersResult=$,exports.UserInput=v,exports.setupGraphQLClient=pe;
253
+ }`,{data:e});return s&&s.SyncRolesAndUsers?s.SyncRolesAndUsers:{Success:!1}}catch(a){return d.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${a}`),{Success:!1}}}};E(ee,"GraphQLSystemUserClient");let x=ee;const te=class te{};E(te,"GetDataOutput");let q=te;const se=class se{};E(se,"SimpleRemoteEntityOutput");let Q=se;const ae=class ae{};E(ae,"SimpleRemoteEntity");let A=ae;const re=class re{};E(re,"SimpleRemoteEntityField");let K=re;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return p.gql}}),exports.ActionItemInput=P,exports.ActionItemOutput=M,exports.FieldMapper=S,exports.GetDataOutput=q,exports.GraphQLDataProvider=C,exports.GraphQLProviderConfigData=F,exports.GraphQLSystemUserClient=x,exports.GraphQLTransactionGroup=V,exports.RoleInput=L,exports.RolesAndUsersInput=_,exports.SimpleRemoteEntity=A,exports.SimpleRemoteEntityField=K,exports.SimpleRemoteEntityOutput=Q,exports.SyncDataAction=ne,exports.SyncDataResult=U,exports.SyncRolesAndUsersResult=$,exports.UserInput=v,exports.setupGraphQLClient=me;
250
254
  //# sourceMappingURL=index.cjs.map