@memberjunction/graphql-dataprovider 2.13.1 → 2.13.3

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,12 @@
1
- "use strict";var _=Object.defineProperty;var g=(I,e)=>_(I,"name",{value:e,configurable:!0});var R=require("graphql-request"),y=require("@memberjunction/core"),U=require("@memberjunction/core-entities"),q=require("@tempfix/idb"),Q=require("rxjs"),B=require("graphql-ws"),M=require("@memberjunction/global");const $=class ${constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const s in e)s in this._fieldMap&&(e[this._fieldMap[s]]=e[s],delete e[s]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([s,a])=>a===e)?.[0]??e}ReverseMapFields(e){const s=Object.fromEntries(Object.entries(this._fieldMap).map(([a,t])=>[t,a]));for(const a in e)a in s&&(e[s[a]]=e[a],delete e[a]);return e}};g($,"FieldMapper");let h=$;const x=class x extends y.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,s,a,t,r,c,i){super({Token:e,URL:s,WSURL:a,RefreshTokenFunction:t},r,c,i)}};g(x,"GraphQLProviderConfigData");let V=x;const d=class d extends y.ProviderBase{constructor(){super(...arguments),this._innerCurrentUserQueryString=`CurrentUser {
1
+ "use strict";var M=Object.defineProperty;var E=(I,e)=>M(I,"name",{value:e,configurable:!0});var w=require("graphql-request"),d=require("@memberjunction/core"),x=require("@memberjunction/core-entities"),q=require("@tempfix/idb"),Q=require("rxjs"),k=require("graphql-ws"),B=require("uuid"),U=require("@memberjunction/global");const $=class ${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($,"FieldMapper");let N=$;const G=class G extends d.ProviderConfigDataBase{get Token(){return this.Data.Token}set Token(e){this.Data.Token=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){super({Token:e,URL:a,WSURL:s,RefreshTokenFunction:t},r,c,n)}};E(G,"GraphQLProviderConfigData");let V=G;const h=class h extends d.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
2
2
  ${this.userInfoString()}
3
3
  UserRoles_UserIDArray {
4
4
  ${this.userRoleInfoString()}
5
5
  }
6
6
  }
7
- `,this._currentUserQuery=R.gql`query CurrentUserAndRoles {
7
+ `,this._currentUserQuery=w.gql`query CurrentUserAndRoles {
8
8
  ${this._innerCurrentUserQueryString}
9
- }`,this._wsClient=null,this._pushStatusRequests=[]}get ConfigData(){return d._configData}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}GenerateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var s=Math.random()*16|0,a=e==="x"?s:s&3|8;return a.toString(16)})}async Config(e){try{return d._sessionId===void 0&&(d._sessionId=this.GenerateUUID()),d._configData=e,d._client||(d._client=d.CreateNewGraphQLClient(e.URL,e.Token,d._sessionId)),super.Config(e)}catch(s){throw y.LogError(s),s}}get sessionId(){return d._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await d.ExecuteGQL(this._currentUserQuery,null);if(e){const s=this.ConvertBackToMJFields(e.CurrentUser),a=s.UserRoles_UserIDArray.map(t=>this.ConvertBackToMJFields(t));return s.UserRoles_UserIDArray=a,new y.UserInfo(this,{...s,UserRoles:a})}}async RunReport(e,s){const a=R.gql`
9
+ }`,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")}GenerateUUID(){return B.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)):(h.Instance._sessionId===void 0&&(h.Instance._sessionId=s),h.Instance._configData=e,h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId))),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=w.gql`
10
10
  query GetReportDataQuery ($ReportID: String!) {
11
11
  GetReportData(ReportID: $ReportID) {
12
12
  Success
@@ -15,7 +15,7 @@
15
15
  ExecutionTime
16
16
  ErrorMessage
17
17
  }
18
- }`,t=await d.ExecuteGQL(a,{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,s){const a=R.gql`
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=w.gql`
19
19
  query GetQueryDataQuery ($QueryID: String!) {
20
20
  GetQueryData(QueryID: $QueryID) {
21
21
  Success
@@ -24,11 +24,11 @@
24
24
  ExecutionTime
25
25
  ErrorMessage
26
26
  }
27
- }`,t=await d.ExecuteGQL(a,{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,s){try{let a="",t="";if(e){const r={};let c,i;if(e.ViewEntity)i=e.ViewEntity,c=i.Entity;else{const{entityName:o,v:l}=await this.getEntityNameAndUserView(e,s);i=l,c=o}const n=this.Entities.find(o=>o.Name===c);if(!n)throw new Error(`Entity ${c} not found in metadata`);let f=!1;e.ViewID?(a=`Run${n.ClassName}ViewByID`,t="RunViewByIDInput",r.ViewID=e.ViewID):e.ViewName?(a=`Run${n.ClassName}ViewByName`,t="RunViewByNameInput",r.ViewName=e.ViewName):(f=!0,a=`Run${n.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 w=this.getViewRunTimeFieldList(n,i,e,f),m=R.gql`
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:l}=await this.getEntityNameAndUserView(e,a);n=l,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=w.gql`
28
28
  query RunViewQuery ($input: ${t}!) {
29
- ${a}(input: $input) {
29
+ ${s}(input: $input) {
30
30
  Results {
31
- ${w.join(`
31
+ ${f.join(`
32
32
  `)}
33
33
  }
34
34
  UserViewRunID
@@ -38,7 +38,7 @@
38
38
  Success
39
39
  ErrorMessage
40
40
  }
41
- }`,u=await d.ExecuteGQL(m,{input:r});if(u&&u[a]){const o=u[a].Results;if(o&&o.length>0){const l=n.Fields.filter(p=>p.CodeName!==p.Name&&p.CodeName!==void 0);o.forEach(p=>{this.ConvertBackToMJFields(p),l.forEach(D=>{p[D.Name]=p[D.CodeName]})})}return u[a]}}else throw"No parameters passed to RunView";return null}catch(a){throw y.LogError(a),a}}async RunViews(e,s){try{let a=[],t=[],r=[];for(const n of e){let f="",w="";const m={};let u=null,o=null;if(n.ViewEntity)o=n.ViewEntity,u=o.Get("Entity");else{const{entityName:D,v:E}=await this.getEntityNameAndUserView(n,s);o=E,u=D}const l=this.Entities.find(D=>D.Name===u);if(!l)throw new Error(`Entity ${u} not found in metadata`);t.push(l);let p=!1;n.ViewID?(f=`Run${l.ClassName}ViewByID`,w="RunViewByIDInput",m.ViewID=n.ViewID):n.ViewName?(f=`Run${l.ClassName}ViewByName`,w="RunViewByNameInput",m.ViewName=n.ViewName):(p=!0,f=`Run${l.ClassName}DynamicView`,w="RunDynamicViewInput",m.EntityName=n.EntityName),m.ExtraFilter=n.ExtraFilter||"",m.OrderBy=n.OrderBy||"",m.UserSearchString=n.UserSearchString||"",m.Fields=n.Fields,m.IgnoreMaxRows=n.IgnoreMaxRows||!1,m.MaxRows=n.MaxRows||0,m.ForceAuditLog=n.ForceAuditLog||!1,m.ResultType=n.ResultType||"simple",n.AuditLogDescription&&n.AuditLogDescription.length>0&&(m.AuditLogDescription=n.AuditLogDescription),p||(m.ExcludeUserViewRunID=n.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=n.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=n.OverrideExcludeFilter||"",m.SaveViewResults=n.SaveViewResults||!1),a.push(m),r.push(...this.getViewRunTimeFieldList(l,o,n,p))}const c=R.gql`
41
+ }`,u=await this.ExecuteGQL(y,{input:r});if(u&&u[s]){const o=u[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(R=>{m[R.Name]=m[R.CodeName]})})}return u[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 u=null,o=null;if(i.ViewEntity)o=i.ViewEntity,u=o.Get("Entity");else{const{entityName:R,v:D}=await this.getEntityNameAndUserView(i,a);o=D,u=R}const l=this.Entities.find(R=>R.Name===u);if(!l)throw new Error(`Entity ${u} not found in metadata`);t.push(l);let m=!1;i.ViewID?(p=`Run${l.ClassName}ViewByID`,f="RunViewByIDInput",y.ViewID=i.ViewID):i.ViewName?(p=`Run${l.ClassName}ViewByName`,f="RunViewByNameInput",y.ViewName=i.ViewName):(m=!0,p=`Run${l.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(l,o,i,m))}const c=w.gql`
42
42
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
43
43
  RunViews(input: $input) {
44
44
  Results {
@@ -53,7 +53,7 @@
53
53
  Success
54
54
  ErrorMessage
55
55
  }
56
- }`,i=await d.ExecuteGQL(c,{input:a});if(i&&i.RunViews){const n=i.RunViews;for(const[f,w]of n.entries())w.Results=w.Results.map(m=>{let u=JSON.parse(m.Data);return this.ConvertBackToMJFields(u),u});return n}return null}catch(a){throw y.LogError(a),a}}async getEntityNameAndUserView(e,s){let a,t;if(e.EntityName)a=e.EntityName;else if(e.ViewID)t=await U.ViewInfo.GetViewEntity(e.ViewID,s),a=t.Entity;else if(e.ViewName)t=await U.ViewInfo.GetViewEntityByName(e.ViewName,s),a=t.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:a,v:t}}getViewRunTimeFieldList(e,s,a,t){const r=[],c=new h;if(a.Fields){for(const i of e.PrimaryKeys)a.Fields.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&r.push(i.Name);a.Fields.forEach(i=>{r.push(c.MapFieldName(i))})}else if(t)e.Fields.forEach(i=>{i.IsBinaryFieldType||r.push(c.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)r.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&r.push(i.Name);s.Columns.forEach(i=>{i.hidden===!1&&!r.find(n=>n.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&r.push(c.MapFieldName(i.EntityField.CodeName))})}return r}get ProviderType(){return y.ProviderType.Network}async GetRecordChanges(e,s){try{const a={EntityName:"Record Changes",ExtraFilter:`RecordID = '${s.Values()}' AND Entity = '${e}'`},t=await this.RunView(a);return t?t.Results.sort((r,c)=>r.ChangedAt>c.ChangedAt?-1:1):null}catch(a){throw y.LogError(a),a}}async GetRecordDependencies(e,s){try{const a=R.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
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 u=JSON.parse(y.Data);return this.ConvertBackToMJFields(u),u});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 x.ViewInfo.GetViewEntity(e.ViewID,a),s=t.Entity;else if(e.ViewName)t=await x.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=w.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
57
57
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
58
58
  EntityName
59
59
  RelatedEntityName
@@ -65,7 +65,7 @@
65
65
  }
66
66
  }
67
67
  }
68
- }`,t={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}};return(await d.ExecuteGQL(a,t))?.GetRecordDependencies}catch(a){throw y.LogError(a),a}}ensureKeyValuePairValueIsString(e){return e.map(s=>({FieldName:s.FieldName,Value:s.Value.toString()}))}async GetRecordDuplicates(e,s){if(!e)return null;const a=R.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
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=w.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
69
69
  GetRecordDuplicates(params: $params) {
70
70
  Status
71
71
  ErrorMessage
@@ -87,7 +87,7 @@
87
87
  }
88
88
  }
89
89
  }
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 d.ExecuteGQL(a,{params:t});if(r&&r.GetRecordDuplicates)return r.GetRecordDuplicates}async MergeRecords(e){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=R.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
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=w.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
91
91
  MergeRecords(request: $request) {
92
92
  Success
93
93
  OverallStatus
@@ -104,32 +104,32 @@
104
104
  Message
105
105
  }
106
106
  }
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 d.ExecuteGQL(a,{request:t}))?.MergeRecords}catch(a){return y.LogError(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,s,a){const t=new y.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(u=>({FieldName:u.CodeName,Value:u.Value})),e.ResultHistory.push(t);const i=`${c}${e.EntityInfo.ClassName}`,n=e.Fields.filter(u=>!u.ReadOnly||u.IsPrimaryKey&&e.IsSaved),f=new h,w=` ${i}(input: $input) {
108
- ${e.Fields.map(u=>f.MapFieldName(u.CodeName)).join(`
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(u=>({FieldName:u.CodeName,Value:u.Value})),e.ResultHistory.push(t);const n=`${c}${e.EntityInfo.ClassName}`,i=e.Fields.filter(u=>!u.ReadOnly||u.IsPrimaryKey&&e.IsSaved),p=new N,f=` ${n}(input: $input) {
108
+ ${e.Fields.map(u=>p.MapFieldName(u.CodeName)).join(`
109
109
  `)}
110
- }`,m=R.gql`mutation ${c}${e.EntityInfo.ClassName} ($input: ${i}Input!) {
111
- ${w}
110
+ }`,y=w.gql`mutation ${c}${e.EntityInfo.ClassName} ($input: ${n}Input!) {
111
+ ${f}
112
112
  }
113
- `;for(let u=0;u<n.length;u++){const o=n[u];let l=o.Value;l&&o.EntityFieldInfo.TSType===y.EntityFieldTSType.Date&&(l=l.getTime()),l&&o.EntityFieldInfo.TSType===y.EntityFieldTSType.Boolean&&typeof l!="boolean"&&(l=parseInt(l)!==0),l===null&&o.EntityFieldInfo.AllowsNull===!1&&(o.EntityFieldInfo.DefaultValue!==null?l=o.EntityFieldInfo.DefaultValue:o.FieldType===y.EntityFieldTSType.Number||o.FieldType===y.EntityFieldTSType.Boolean?l=0:l=""),r.input[o.CodeName]=l}if(c.trim().toLowerCase()==="update"&&a.SkipOldValuesCheck===!1){const u=[];e.Fields.forEach(o=>{let l=null;o.OldValue!==null&&o.OldValue!==void 0&&(o.EntityFieldInfo.TSType===y.EntityFieldTSType.Date?l=o.OldValue.getTime().toString():o.EntityFieldInfo.TSType===y.EntityFieldTSType.Boolean?l=o.OldValue===!0?"1":"0":typeof o.OldValue!="string"?l=o.OldValue.toString():l=o.OldValue),u.push({Key:o.CodeName,Value:l})}),r.input.OldValues___=u}if(e.TransactionGroup)return new Promise((u,o)=>{const l=[{varName:"input",inputType:i+"Input!"}];e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new y.TransactionItem(e,w,r,{mutationName:i,mutationInputTypes:l},(p,D)=>{t.EndedAt=new Date,D&&p?(t.Success=!0,u(this.ConvertBackToMJFields(p))):(t.Success=!1,t.Message="Transaction failed",o())}))});{const u=await d.ExecuteGQL(m,r);if(u&&u[c+e.EntityInfo.ClassName])return t.Success=!0,t.EndedAt=new Date,this.ConvertBackToMJFields(u[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,y.LogError(r),null}}async Load(e,s,a=null,t){try{const r={};let c="",i="";for(let u=0;u<s.KeyValuePairs.length;u++){const o=e.Fields.find(D=>D.Name.trim().toLowerCase()===s.KeyValuePairs[u].FieldName.trim().toLowerCase()).EntityFieldInfo,l=s.GetValueByIndex(u),p=o.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${o.CodeName}: ${p}!`,c.length>0&&(c+=", "),c+=`${o.CodeName}: $${o.CodeName}`,o.TSType===y.EntityFieldTSType.Number){if(isNaN(s.GetValueByIndex(u)))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 n=a&&a.length>0?this.getRelatedEntityString(e.EntityInfo,a):"",f=new h,w=R.gql`query Single${e.EntityInfo.ClassName}${n.length>0?"Full":""} (${i}) {
113
+ `;for(let u=0;u<i.length;u++){const o=i[u];let l=o.Value;l&&o.EntityFieldInfo.TSType===d.EntityFieldTSType.Date&&(l=l.getTime()),l&&o.EntityFieldInfo.TSType===d.EntityFieldTSType.Boolean&&typeof l!="boolean"&&(l=parseInt(l)!==0),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(c.trim().toLowerCase()==="update"&&s.SkipOldValuesCheck===!1){const u=[];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),u.push({Key:o.CodeName,Value:l})}),r.input.OldValues___=u}if(e.TransactionGroup)return new Promise((u,o)=>{const l=[{varName:"input",inputType:n+"Input!"}];e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new d.TransactionItem(e,f,r,{mutationName:n,mutationInputTypes:l},(m,R)=>{t.EndedAt=new Date,R&&m?(t.Success=!0,u(this.ConvertBackToMJFields(m))):(t.Success=!1,t.Message="Transaction failed",o())}))});{const u=await this.ExecuteGQL(y,r);if(u&&u[c+e.EntityInfo.ClassName])return t.Success=!0,t.EndedAt=new Date,this.ConvertBackToMJFields(u[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 u=0;u<a.KeyValuePairs.length;u++){const o=e.Fields.find(R=>R.Name.trim().toLowerCase()===a.KeyValuePairs[u].FieldName.trim().toLowerCase()).EntityFieldInfo,l=a.GetValueByIndex(u),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(u)))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):"",p=new N,f=w.gql`query Single${e.EntityInfo.ClassName}${i.length>0?"Full":""} (${n}) {
114
114
  ${e.EntityInfo.ClassName}(${c}) {
115
115
  ${e.Fields.filter(u=>!u.EntityFieldInfo.IsBinaryFieldType).map(u=>u.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?u.CodeName.replace("__mj_","_mj__"):u.CodeName).join(`
116
116
  `)}
117
- ${n}
117
+ ${i}
118
118
  }
119
119
  }
120
- `,m=await d.ExecuteGQL(w,r);return m&&m[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(m[e.EntityInfo.ClassName]):null}catch(r){return y.LogError(r),null}}ConvertBackToMJFields(e){return new h().ReverseMapFields(e),e}getRelatedEntityString(e,s){let a="";for(let t=0;t<e.RelatedEntities.length;t++)if(s.indexOf(e.RelatedEntities[t].RelatedEntity)>=0){const r=e.RelatedEntities[t],c=this.Entities.find(n=>n.ID===r.RelatedEntityID);let i="";r.Type.toLowerCase().trim()==="many to many"?i=`${r.RelatedEntityCodeName}_${r.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${r.RelatedEntityCodeName}_${r.RelatedEntityJoinField.replace(/\s/g,"")}`,a+=`
121
- ${i} {
122
- ${c.Fields.map(n=>n.CodeName).join(`
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+=`
121
+ ${n} {
122
+ ${c.Fields.map(i=>i.CodeName).join(`
123
123
  `)}
124
124
  }
125
- `}return a}async Delete(e,s,a){const t=new y.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 i="",n="",f="";for(let o of e.PrimaryKey.KeyValuePairs){const l=e.Fields.find(p=>p.Name.trim().toLowerCase()===o.FieldName.trim().toLowerCase());r[l.CodeName]=l.Value,c.push({varName:l.CodeName,inputType:l.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${l.CodeName}: $${l.CodeName}`,n.length>0&&(n+=", "),n+=`$${l.CodeName}: ${l.EntityFieldInfo.GraphQLType}!`,f.length>0&&(f+=`
126
- `),f+=`${l.CodeName}`}c.push({varName:"options___",inputType:"DeleteOptionsInput!"}),r.options___=s||{SkipEntityAIActions:!1,SkipEntityActions:!1};const w="Delete"+e.EntityInfo.ClassName,m=R.gql`${w}(${i}, options___: $options___) {
127
- ${f}
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 l=e.Fields.find(m=>m.Name.trim().toLowerCase()===o.FieldName.trim().toLowerCase());r[l.CodeName]=l.Value,c.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}!`,p.length>0&&(p+=`
126
+ `),p+=`${l.CodeName}`}c.push({varName:"options___",inputType:"DeleteOptionsInput!"}),r.options___=a||{SkipEntityAIActions:!1,SkipEntityActions:!1};const f="Delete"+e.EntityInfo.ClassName,y=w.gql`${f}(${n}, options___: $options___) {
127
+ ${p}
128
128
  }
129
- `,u=R.gql`mutation ${w} (${n}, $options___: DeleteOptionsInput!) {
130
- ${m}
129
+ `,u=w.gql`mutation ${f} (${i}, $options___: DeleteOptionsInput!) {
130
+ ${y}
131
131
  }
132
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),new Promise((o,l)=>{e.TransactionGroup.AddTransaction(new y.TransactionItem(e,m,r,{mutationName:w,mutationInputTypes:c},(p,D)=>{if(t.EndedAt=new Date,D&&p){let E=!0;for(const P of e.PrimaryKey.KeyValuePairs)P.Value!==p[P.FieldName]&&(E=!1);E?(t.Success=!0,o(!0)):(t.Success=!1,t.Message="Transaction failed to commit",l())}else t.Success=!1,t.Message="Transaction failed to commit",l()}))});{const o=await d.ExecuteGQL(u,r);if(o&&o[w]){const l=o[w];for(let p of e.PrimaryKey.KeyValuePairs){let D=l[p.FieldName],E=p.Value;if(typeof E=="number"&&(E=E.toString()),typeof D=="number"&&(D=D.toString()),E!==D)throw new Error(`Primary key value mismatch in server Delete response. Field: ${p.FieldName}, Original: ${E}, 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,y.LogError(r),!1}}async GetDatasetByName(e,s){const a=R.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
132
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),new Promise((o,l)=>{e.TransactionGroup.AddTransaction(new d.TransactionItem(e,y,r,{mutationName:f,mutationInputTypes:c},(m,R)=>{if(t.EndedAt=new Date,R&&m){let D=!0;for(const P of e.PrimaryKey.KeyValuePairs)P.Value!==m[P.FieldName]&&(D=!1);D?(t.Success=!0,o(!0)):(t.Success=!1,t.Message="Transaction failed to commit",l())}else t.Success=!1,t.Message="Transaction failed to commit",l()}))});{const o=await this.ExecuteGQL(u,r);if(o&&o[f]){const l=o[f];for(let m of e.PrimaryKey.KeyValuePairs){let R=l[m.FieldName],D=m.Value;if(typeof D=="number"&&(D=D.toString()),typeof R=="number"&&(R=R.toString()),D!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${m.FieldName}, Original: ${D}, Returned: ${R}`)}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=w.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
133
133
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
134
134
  DatasetID
135
135
  DatasetName
@@ -138,7 +138,7 @@
138
138
  LatestUpdateDate
139
139
  Results
140
140
  }
141
- }`,t=await d.ExecuteGQL(a,{DatasetName:e,ItemFilters:s});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,s){const a=R.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
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=w.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
142
142
  GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
143
143
  DatasetID
144
144
  DatasetName
@@ -147,22 +147,22 @@
147
147
  LatestUpdateDate
148
148
  EntityUpdateDates
149
149
  }
150
- }`,t=await d.ExecuteGQL(a,{DatasetName:e,ItemFilters:s});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}async GetRecordFavoriteStatus(e,s,a){if(!a.Validate().IsValid)return!1;const r=this.Entities.find(n=>n.Name===s);if(!r)throw new Error(`Entity ${s} not found in metadata`);const c=R.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
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=w.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
151
151
  GetRecordFavoriteStatus(params: $params) {
152
152
  Success
153
153
  IsFavorite
154
154
  }
155
- }`,i=await d.ExecuteGQL(c,{params:{UserID:e,EntityID:r.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,s,a,t,r){const c=this.Entities.find(f=>f.Name===s);if(!c)throw new Error(`Entity ${s} not found in metadata`);const i=R.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
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=w.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
156
156
  SetRecordFavoriteStatus(params: $params){
157
157
  Success
158
158
  }
159
- }`,n=await d.ExecuteGQL(i,{params:{UserID:e,EntityID:c.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(a.KeyValuePairs)},IsFavorite:t}});if(n&&n.SetRecordFavoriteStatus!==null)return n.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,s){if(!e||!s||s.KeyValuePairs?.length===0)return null;const a=R.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
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=w.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
160
160
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
161
161
  Success
162
162
  Status
163
163
  RecordName
164
164
  }
165
- }`,t=await d.ExecuteGQL(a,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.KeyValuePairs)}});if(t&&t.GetEntityRecordName&&t.GetEntityRecordName.Success)return t.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const s=R.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
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=w.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
166
166
  GetEntityRecordNames(info: $info) {
167
167
  Success
168
168
  Status
@@ -175,18 +175,18 @@
175
175
  EntityName
176
176
  RecordName
177
177
  }
178
- }`,a=await d.ExecuteGQL(s,{info:e.map(t=>({EntityName:t.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.CompositeKey.KeyValuePairs)}}))});if(a&&a.GetEntityRecordNames)return a.GetEntityRecordNames}static async ExecuteGQL(e,s,a=!0){try{return await d._client.request(e,s)}catch(t){if(t&&t.response&&t.response.errors?.length>0)if(t.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(a)return await d.RefreshToken(),await d.ExecuteGQL(e,s,!1);throw y.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),t}else throw t;else throw y.LogError(t),t}}static async RefreshToken(){if(d._configData.Data.RefreshTokenFunction){const e=await d._configData.Data.RefreshTokenFunction();if(e)d._configData.Token=e,d._client=this.CreateNewGraphQLClient(d._configData.URL,d._configData.Token,d._sessionId);else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static CreateNewGraphQLClient(e,s,a){return new R.GraphQLClient(e,{headers:{authorization:"Bearer "+s,"x-session-id":a}})}userInfoString(){return this.infoString(new y.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new y.UserRoleInfo(null))}infoString(e){let s="";const a=Object.keys(e);for(const t of a)t.startsWith("__mj_")?s+=t.replace("__mj_","_mj__")+`
179
- `:t.startsWith("_")||(s+=t+`
180
- `);return s}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new C),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=B.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const s=this._pushStatusRequests.find(r=>r.sessionId===e);if(s)return s.observable;const a=R.gql`subscription StatusUpdates($sessionId: String!) {
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 h.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);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,a,s){return new w.GraphQLClient(e,{headers:{authorization:"Bearer "+a,"x-session-id":s}})}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
+ `:t.startsWith("_")||(a+=t+`
180
+ `);return a}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new C),this._localStorageProvider}get Metadata(){return this}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=k.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=w.gql`subscription StatusUpdates($sessionId: String!) {
181
181
  statusUpdates(sessionId: $sessionId) {
182
182
  date
183
183
  message
184
184
  sessionId
185
185
  }
186
186
  }
187
- `,t=new Q.Observable(r=>(this._wsClient.subscribe({query:a,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(d,"GraphQLDataProvider");let S=d;const v=class v{constructor(){this._localStorage={}}async getItem(e){return new Promise(s=>{this._localStorage.hasOwnProperty(e)?s(this._localStorage[e]):s(null)})}async setItem(e,s){return new Promise(a=>{this._localStorage[e]=s,a()})}async remove(e){return new Promise(s=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],s()})}};g(v,"BrowserStorageProviderBase");let F=v;const k="MJ_Metadata",N="Metadata_KVPairs",G=class G extends F{constructor(){super(),this.dbPromise=q.openDB(k,1,{upgrade(e){e.objectStoreNames.contains(N)||e.createObjectStore(N)}})}async setItem(e,s){const t=(await this.dbPromise).transaction(N,"readwrite");await t.objectStore(N).put(s,e),await t.done}async getItem(e){return await(await this.dbPromise).transaction(N).objectStore(N).get(e)}async remove(e){const a=(await this.dbPromise).transaction(N,"readwrite");await a.objectStore(N).delete(e),await a.done}};g(G,"BrowserIndexedDBStorageProvider");let C=G;const L=class L extends y.TransactionGroupBase{async HandleSubmit(e){let s="",a="";const t={};for(let i=0;i<e.length;i++){const n=e[i];let f=n.Instruction;if(n.Vars){const w=Object.keys(n.Vars);for(let m=0;m<w.length;m++){const u=w[m],o=`${u}_${i}`;t[o]=n.Vars[u];const l=new RegExp("\\$"+u,"g");f=f.replace(l,"$"+o);const p=n.ExtraData.mutationInputTypes.find(D=>D.varName===u)?.inputType;a+=`$${o}: ${p}
188
- `}}s+=`mutation_${i}: `+f+`
189
- `}s=`mutation TransactionGroup(${a}){
190
- `+s+`
191
- }`;const r=await S.ExecuteGQL(s,t),c=[];for(let i=0;i<e.length;i++){const n=r[`mutation_${i}`],f=e[i];c.push(new y.TransactionResult(f,n,n!==null))}return c}};g(L,"GraphQLTransactionGroup");let T=L;async function K(I){const e=new S;return y.BaseEntity.Provider=e,y.Metadata.Provider=e,y.RunView.Provider=e,y.RunReport.Provider=e,y.RunQuery.Provider=e,await e.Config(I),M.MJGlobal.Instance.RaiseEvent({event:M.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}g(K,"setupGraphQLClient"),Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return R.gql}}),exports.FieldMapper=h,exports.GraphQLDataProvider=S,exports.GraphQLProviderConfigData=V,exports.setupGraphQLClient=K;
187
+ `,t=new Q.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}};E(h,"GraphQLDataProvider");let S=h;const v=class v{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(v,"BrowserStorageProviderBase");let F=v;const A="MJ_Metadata",g="Metadata_KVPairs",_=class _ extends F{constructor(){super(),this.dbPromise=q.openDB(A,1,{upgrade(e){e.objectStoreNames.contains(g)||e.createObjectStore(g)}})}async setItem(e,a){const t=(await this.dbPromise).transaction(g,"readwrite");await t.objectStore(g).put(a,e),await t.done}async getItem(e){return await(await this.dbPromise).transaction(g).objectStore(g).get(e)}async remove(e){const s=(await this.dbPromise).transaction(g,"readwrite");await s.objectStore(g).delete(e),await s.done}};E(_,"BrowserIndexedDBStorageProvider");let C=_;const L=class L extends d.TransactionGroupBase{constructor(e){super()}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 u=f[y],o=`${u}_${n}`;t[o]=i.Vars[u];const l=new RegExp("\\$"+u,"g");p=p.replace(l,"$"+o);const m=i.ExtraData.mutationInputTypes.find(R=>R.varName===u)?.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}};E(L,"GraphQLTransactionGroup");let T=L;async function K(I){const e=new S;return d.BaseEntity.Provider=e,d.Metadata.Provider=e,d.RunView.Provider=e,d.RunReport.Provider=e,d.RunQuery.Provider=e,await e.Config(I),U.MJGlobal.Instance.RaiseEvent({event:U.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}E(K,"setupGraphQLClient"),Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return w.gql}}),exports.FieldMapper=N,exports.GraphQLDataProvider=S,exports.GraphQLProviderConfigData=V,exports.setupGraphQLClient=K;
192
192
  //# sourceMappingURL=index.cjs.map