@simitgroup/simpleapp-generator 1.6.6-j-alpha → 1.6.6-k.1-alpha

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.
Files changed (158) hide show
  1. package/ReleaseNote.md +3 -2
  2. package/dist/buildinschemas/docnoformat.js +6 -6
  3. package/dist/buildinschemas/docnoformat.js.map +1 -1
  4. package/dist/buildinschemas/documentevent.js +1 -1
  5. package/dist/buildinschemas/documentevent.js.map +1 -1
  6. package/dist/buildinschemas/organization.js +1 -1
  7. package/dist/buildinschemas/organization.js.map +1 -1
  8. package/dist/buildinschemas/tenant.js +1 -1
  9. package/dist/buildinschemas/tenant.js.map +1 -1
  10. package/dist/buildinschemas/user.js +2 -2
  11. package/dist/buildinschemas/user.js.map +1 -1
  12. package/dist/framework.d.ts.map +1 -1
  13. package/dist/framework.js +2 -0
  14. package/dist/framework.js.map +1 -1
  15. package/dist/generate.d.ts.map +1 -1
  16. package/dist/generate.js +21 -20
  17. package/dist/generate.js.map +1 -1
  18. package/dist/processors/jrxmlbuilder.js +3 -3
  19. package/dist/processors/jrxmlbuilder.js.map +1 -1
  20. package/dist/processors/jsonschemabuilder.d.ts.map +1 -1
  21. package/dist/processors/jsonschemabuilder.js +17 -10
  22. package/dist/processors/jsonschemabuilder.js.map +1 -1
  23. package/dist/type.d.ts +1 -1
  24. package/dist/type.d.ts.map +1 -1
  25. package/package.json +1 -2
  26. package/reset-install.sh +3 -0
  27. package/src/buildinschemas/docnoformat.ts +6 -6
  28. package/src/buildinschemas/documentevent.ts +1 -1
  29. package/src/buildinschemas/organization.ts +1 -1
  30. package/src/buildinschemas/tenant.ts +1 -1
  31. package/src/buildinschemas/user.ts +2 -2
  32. package/src/framework.ts +2 -1
  33. package/src/generate.ts +22 -20
  34. package/src/processors/jrxmlbuilder.ts +3 -3
  35. package/src/processors/jsonschemabuilder.ts +27 -14
  36. package/src/type.ts +1 -1
  37. package/templates/basic/nuxt/simpleapp.generate.client.ts.eta +3 -3
  38. package/templates/nest/.gitignore.eta +4 -5
  39. package/templates/nest/src/{app.module.ts.eta → app.module.ts._eta} +2 -2
  40. package/templates/nest/src/{main.ts.eta → main.ts._eta} +2 -2
  41. package/templates/nest/src/printapi/printapi.service.ts.eta +7 -8
  42. package/templates/nest/src/simpleapp/.gitignore.eta +1 -1
  43. package/templates/nest/src/simpleapp/additional.module.ts._eta +13 -0
  44. package/templates/nest/src/simpleapp/generate/commons/audittrail.service.ts.eta +2 -2
  45. package/templates/nest/src/simpleapp/generate/commons/customkeycloa.guard.ts.eta +14 -12
  46. package/templates/nest/src/simpleapp/generate/commons/customkeycloak.guard.ts.eta +36 -42
  47. package/templates/nest/src/simpleapp/generate/commons/docnogenerator.service.ts.eta +6 -3
  48. package/templates/nest/src/simpleapp/generate/commons/encryption.static.ts.eta +56 -61
  49. package/templates/nest/src/simpleapp/generate/commons/middlewares/tenant.middleware.ts.eta +65 -88
  50. package/templates/nest/src/simpleapp/generate/commons/robotuser.service.ts.eta +10 -9
  51. package/templates/nest/src/simpleapp/generate/commons/roles/roles.guard.ts.eta +10 -3
  52. package/templates/nest/src/simpleapp/generate/commons/runwebhook.service.ts.eta +41 -39
  53. package/templates/nest/src/simpleapp/generate/commons/user.context.ts.eta +439 -293
  54. package/templates/nest/src/simpleapp/generate/processors/autoinc.processor.ts.eta +20 -5
  55. package/templates/nest/src/simpleapp/generate/processors/simpleapp.processor.ts.eta +437 -40
  56. package/templates/nest/src/simpleapp/profile/{profile.controller.ts.eta → profile.controller.ts._eta} +2 -2
  57. package/templates/nest/src/simpleapp/profile/{profile.service.ts.eta → profile.service.ts._eta} +2 -2
  58. package/templates/nest/src/simpleapp/simpleapp.module.ts.eta +19 -15
  59. package/templates/nuxt/components/button/ButtonMultiple.vue._eta +1 -1
  60. package/templates/nuxt/components/calendar/{CalendarByResource.vue.eta → CalendarByResource.vue._eta} +2 -2
  61. package/templates/nuxt/components/calendar/{CalendarInput.vue.eta → CalendarInput.vue._eta} +2 -2
  62. package/templates/nuxt/components/calendar/{CalendarSmall.vue.eta → CalendarSmall.vue._eta} +6 -0
  63. package/templates/nuxt/components/debug/{DebugDocumentData.vue.eta → DebugDocumentData.vue._eta} +2 -2
  64. package/templates/nuxt/components/form/{FormDocnoformat.vue.eta → FormDocnoformat.vue._eta} +2 -1
  65. package/templates/nuxt/components/form/user/{FormUserPermission.vue.eta → FormUserPermission.vue._eta} +6 -0
  66. package/templates/nuxt/components/header/{HeaderBreadcrumb.vue.eta → HeaderBreadcrumb.vue._eta} +2 -2
  67. package/templates/nuxt/components/header/button/{HeaderButtonProfile.vue.eta → HeaderButtonProfile.vue._eta} +2 -2
  68. package/templates/nuxt/components/header/button/task/{HeaderButtonTaskList.vue.eta → HeaderButtonTaskList.vue._eta} +2 -2
  69. package/templates/nuxt/components/image/ImageAvatar.vue.eta +29 -30
  70. package/templates/nuxt/components/image/ImageOrganization.vue.eta +15 -9
  71. package/templates/nuxt/components/image/ImageToBase64Uploader.vue.eta +28 -18
  72. package/templates/nuxt/components/list/{ListDocumentTable.vue.eta → ListDocumentTable.vue._eta} +2 -2
  73. package/templates/nuxt/components/list/{ListItem.vue.eta → ListItem.vue._eta} +2 -2
  74. package/templates/nuxt/components/list/{ListMessages.vue.eta → ListMessages.vue._eta} +6 -0
  75. package/templates/nuxt/components/list/{ListView.vue.eta → ListView.vue._eta} +2 -2
  76. package/templates/nuxt/components/overlay/{OverlayPanelWithToolBar.vue.eta → OverlayPanelWithToolBar.vue._eta} +2 -2
  77. package/templates/nuxt/components/overlay/{OverlaySideBarCrud.vue.eta → OverlaySideBarCrud.vue._eta} +2 -2
  78. package/templates/nuxt/components/overlay/{OverlayViewer.vue.eta → OverlayViewer.vue._eta} +2 -2
  79. package/templates/nuxt/components/page/{PageDocList.vue.eta → PageDocList.vue._eta} +2 -2
  80. package/templates/nuxt/components/renderer/{RendererDateTime.vue.eta → RendererDateTime.vue._eta} +2 -2
  81. package/templates/nuxt/components/renderer/{RendererDocHistories.vue.eta → RendererDocHistories.vue._eta} +6 -0
  82. package/templates/nuxt/components/renderer/{RendererForeignKey.vue.eta → RendererForeignKey.vue._eta} +2 -2
  83. package/templates/nuxt/components/renderer/{RendererLink.vue.eta → RendererLink.vue._eta} +2 -2
  84. package/templates/nuxt/components/renderer/{RendererTime.vue.eta → RendererTime.vue._eta} +2 -2
  85. package/templates/nuxt/components/renderer/{RendererViewer.vue.eta → RendererViewer.vue._eta} +2 -2
  86. package/templates/nuxt/components/select/{SelectTemplate.vue.eta → SelectTemplate.vue._eta} +2 -2
  87. package/templates/nuxt/components/session/{SessionBlock.vue.eta → SessionBlock.vue._eta} +2 -2
  88. package/templates/nuxt/components/simpleApp/SimpleAppAutocomplete.vue.eta +55 -55
  89. package/templates/nuxt/components/simpleApp/SimpleAppCalendarInput.vue.eta +13 -11
  90. package/templates/nuxt/components/simpleApp/SimpleAppChildrenList.vue.eta +6 -3
  91. package/templates/nuxt/components/simpleApp/SimpleAppDocumentNo.vue.eta +32 -27
  92. package/templates/nuxt/components/simpleApp/SimpleAppFieldContainer.vue.eta +19 -28
  93. package/templates/nuxt/components/simpleApp/SimpleAppInput.vue.eta +114 -105
  94. package/templates/nuxt/components/simpleApp/SimpleAppInputTable.vue.eta +3 -3
  95. package/templates/nuxt/components/simpleApp/SimpleAppJsonSchemaForm.vue.eta +1 -1
  96. package/templates/nuxt/components/simpleApp/SimpleAppUserPicker.vue.eta +10 -12
  97. package/templates/nuxt/components/table/{TableDocuments.vue.eta → TableDocuments.vue._eta} +2 -2
  98. package/templates/nuxt/components/user/{UserButtonPermissionInfo.vue.eta → UserButtonPermissionInfo.vue._eta} +2 -2
  99. package/templates/nuxt/components/user/{UserInvitation.vue.eta → UserInvitation.vue._eta} +2 -2
  100. package/templates/nuxt/components/user/{UserProfileListItem.vue.eta → UserProfileListItem.vue._eta} +2 -2
  101. package/templates/nuxt/components/user/{UserTenantPicker.vue.eta → UserTenantPicker.vue._eta} +2 -2
  102. package/templates/nuxt/composables/getOpenApi.generate.ts.eta +11 -3
  103. package/templates/nuxt/composables/getUserStore.generate.ts.eta +1 -1
  104. package/templates/nuxt/composables/graphquery.generate.ts.eta +1 -1
  105. package/templates/nuxt/composables/recently.generate.ts.eta +0 -1
  106. package/templates/nuxt/composables/stringHelper.generate.ts.eta +5 -2
  107. package/templates/nuxt/pages/[xorg]/docnoformat/[id].vue.eta +0 -1
  108. package/templates/nuxt/pages/[xorg]/{docnoformat.vue.eta → docnoformat.vue._eta} +1 -0
  109. package/templates/nuxt/pages/[xorg]/organization/[id].vue.eta +13 -9
  110. package/templates/nuxt/pages/[xorg]/organization/new.vue.eta +10 -12
  111. package/templates/nuxt/pages/[xorg]/{user.vue.eta → user.vue._eta} +2 -2
  112. package/templates/nuxt/pages/{profile.vue.eta → profile.vue._eta} +2 -2
  113. package/templates/nuxt/plugins/10.simpleapp-event.ts.eta +6 -0
  114. package/templates/nuxt/plugins/20.simpleapp-userstore.ts.eta +89 -12
  115. package/templates/nuxt/plugins/40.pusher.ts.eta +6 -9
  116. package/templates/nuxt/providers/my-provider.ts.eta +1 -1
  117. package/templates/nuxt/server/api/profile/[...].ts.eta +4 -3
  118. package/templates/nuxt/simpleapp/generate/clients/SimpleAppClient.ts.eta +8 -4
  119. package/templates/nuxt/types/schema.ts.eta +1 -1
  120. package/templates/nuxt/types/user.ts.eta +6 -1
  121. package/templates/project/jsonschemas/appintegration.json_eta +227 -0
  122. package/templates/project/sharelibs/validate.ts.eta +1 -1
  123. package/dist/buildinschemas/message.d.ts +0 -3
  124. package/dist/buildinschemas/message.d.ts.map +0 -1
  125. package/dist/buildinschemas/message.js +0 -34
  126. package/dist/buildinschemas/message.js.map +0 -1
  127. package/dist/buildinschemas/webhookhistory.d.ts +0 -3
  128. package/dist/buildinschemas/webhookhistory.d.ts.map +0 -1
  129. package/dist/buildinschemas/webhookhistory.js +0 -44
  130. package/dist/buildinschemas/webhookhistory.js.map +0 -1
  131. package/dist/createproject.js +0 -138
  132. package/dist/createproject.js.map +0 -1
  133. package/dist/generate-allow-changebackend.js +0 -305
  134. package/dist/generate-allow-changebackend.js.map +0 -1
  135. package/dist/index2.js +0 -118
  136. package/dist/index2.js.map +0 -1
  137. package/dist/installdependency.js +0 -20
  138. package/dist/installdependency.js.map +0 -1
  139. package/dist/installnest.js +0 -2
  140. package/dist/installnest.js.map +0 -1
  141. package/dist/installnuxt.js +0 -2
  142. package/dist/installnuxt.js.map +0 -1
  143. package/dist/processors/groupsbuilder.js +0 -2
  144. package/dist/processors/groupsbuilder.js.map +0 -1
  145. package/dist/schematype/baseschema.js +0 -25
  146. package/dist/schematype/baseschema.js.map +0 -1
  147. package/dist/schematype/default.js +0 -2
  148. package/dist/schematype/default.js.map +0 -1
  149. package/dist/schematype/index.js +0 -12
  150. package/dist/schematype/index.js.map +0 -1
  151. package/dist/schematype/primarymasterdata.js +0 -38
  152. package/dist/schematype/primarymasterdata.js.map +0 -1
  153. package/dist/schematype/simple.js +0 -24
  154. package/dist/schematype/simple.js.map +0 -1
  155. package/dist/schematype/simplemasterdata.js +0 -31
  156. package/dist/schematype/simplemasterdata.js.map +0 -1
  157. package/dist/schematype/transaction.js +0 -74
  158. package/dist/schematype/transaction.js.map +0 -1
@@ -1,173 +1,220 @@
1
1
  /**
2
2
  * This file was automatically generated by simpleapp generator. Every
3
3
  * MODIFICATION OVERRIDE BY GENERATEOR
4
- * last change 2024-01-01
5
- * Author: Ks Tan
6
- * permission design
7
- * 1. during sign in, user can pick run as what group user
4
+ * Permission design
5
+ * 1. During sign in, user can pick run as what group user
8
6
  * 2.
9
7
  */
10
- import {
11
- Injectable,
12
- Scope,
13
- Inject,
14
- Logger,
15
- BadRequestException,
16
- ForbiddenException,
17
- } from '@nestjs/common';
18
- import { Model, model, connect, PipelineStage } from 'mongoose';
19
- import { ModifiedCollection, ModifiedRecords } from '../types';
20
- import _, { isNumber } from 'lodash';
21
- import { Module } from '@nestjs/common';
8
+ import Base64URL from '@darkwolf/base64url';
9
+ import { BadRequestException, ForbiddenException, Injectable, Logger, Scope } from '@nestjs/common';
22
10
  import * as jwt from 'jsonwebtoken';
11
+ import { ClientSession, Model, PipelineStage } from 'mongoose';
12
+ import { Branch, Organization, Permission, Tenant, TenantClientSetting, User, Appintegration } from 'src/simpleapp/generate/types';
13
+ import { ProfileUserBranch, ProfileUserInvites } from '../../profile/profile.types';
14
+ import { ModifiedRecords } from '../types';
23
15
  import { Role } from './roles/roles.enum';
24
16
  import * as rolegroups from './roles/roles.group';
25
- import { UserService } from './../../services/user.service';
26
- import { InjectModel } from '@nestjs/mongoose';
27
- const Base64URL = require('@darkwolf/base64url');
28
- import { UserMongoSchema } from './../models/user.model';
29
- // import { User } from './../types/user.type';
30
- import {
31
- TenantClientSetting,
32
- Permission,
33
- User,
34
- } from 'src/simpleapp/generate/types';
35
- // import { Permission } from './../types/perm.type';
36
- import {
37
- ProfileUserBranch,
38
- ProfileUserInvites,
39
- } from '../../profile/profile.types';
40
-
41
- import { ClientSession } from 'mongoose';
42
17
 
43
18
  @Injectable({ scope: Scope.REQUEST })
44
19
  export class UserContext {
45
20
  protected sessionId: string = crypto.randomUUID();
46
- protected logger = new Logger();
21
+
22
+ protected logger = new Logger(this.constructor.name);
23
+
47
24
  protected uid: string = '';
25
+
48
26
  protected _id: string = '';
27
+
49
28
  protected uname: string = '';
29
+
50
30
  protected email: string = '';
31
+
51
32
  protected fullname: string = '';
33
+
52
34
  protected xOrg: string = '';
35
+
53
36
  protected tenantId: number = 0;
37
+
54
38
  protected orgId: number = 0;
39
+
55
40
  protected orgRecordId: string = '';
41
+
56
42
  protected branchRecordId: string = '';
43
+
57
44
  protected branchId: number = 0;
58
- protected ssoACL: any = {};
45
+
46
+ protected ssoACL: Record<string, { roles: string[] }> = {};
47
+
59
48
  protected token: string = '';
49
+
60
50
  protected refreshtoken: string = '';
61
- //guest access token obtain from header 'x-guest-accesstoken', during use x-api-key/x-api-secret
62
- protected guestToken?: string='';
63
- protected guestInfo:{uid:string,uname:string,fullname:string,email:string} = {uid:'',uname:'',fullname:'',email:''}
51
+
52
+ // Guest access token obtain from header 'x-guest-accesstoken', during use x-apikey / x-apisecret
53
+ protected guestToken?: string = '';
54
+
55
+ protected guestInfo: {
56
+ uid: string;
57
+ uname: string;
58
+ fullname: string;
59
+ email: string;
60
+ } = { uid: '', uname: '', fullname: '', email: '' };
61
+
64
62
  protected groups: string[] = [];
63
+
65
64
  protected branchCode: string = '';
65
+
66
66
  protected branchName: string = '';
67
+
67
68
  protected orgCode: string = '';
69
+
68
70
  protected orgName: string = '';
71
+
69
72
  protected timeZone: string = '';
73
+
70
74
  protected country: string = '';
75
+
71
76
  protected offsetMinute: number = 0;
77
+
72
78
  protected currency: string = '';
73
- protected branches: any[] = [];
79
+
80
+ protected branches: (Permission & { branch: Branch[] })[] = [];
81
+
74
82
  protected lastActivity: string = new Date().toISOString();
75
- protected invites: any[] = []; //User + field tenant:Tenant[]
76
- protected roles: string[] = [];
77
- protected moreProps: any[] = [];
83
+
84
+ protected invites: (ProfileUserInvites & { tenant: Tenant[] })[] = [];
85
+
86
+ protected roles: Role[] = [];
87
+
88
+ protected moreProps: Record<string, any> = {};
89
+
90
+ protected package: string = '';
91
+
78
92
  protected clientSetting: TenantClientSetting = {
79
93
  auditTrail: false,
80
94
  support: false,
81
95
  webhook: false,
96
+ disableClassReminder: false,
82
97
  };
98
+
83
99
  private dbsession: ClientSession;
100
+
84
101
  protected modifiedRecords: ModifiedRecords = {
85
102
  createds: {},
86
103
  updateds: {},
87
104
  deleteds: {},
88
105
  };
89
106
 
107
+ protected appintegration: {
108
+ simbiz6: boolean;
109
+ einvoice: boolean;
110
+ } = { simbiz6: false, einvoice: false };
111
+
90
112
  constructor(
91
- private readonly usermodel: Model<User>,
92
- private readonly permmodel: Model<Permission>,
93
- // private dbsession: ClientSession,
113
+ private readonly userModel: Model<User>,
114
+ private readonly permModel: Model<Permission>,
115
+ private readonly appModel: Model<Appintegration>,
94
116
  ) {}
95
117
 
96
118
  setDBSession = (dbsession: ClientSession) => {
97
119
  this.dbsession = dbsession;
98
120
  };
121
+
99
122
  getDBSession = (): ClientSession => this.dbsession;
123
+
100
124
  getId = () => this._id;
125
+
101
126
  getUid = () => this.uid;
127
+
102
128
  getUname = () => this.uname;
129
+
103
130
  getFullname = () => this.fullname;
131
+
104
132
  getTenantId = () => this.tenantId;
133
+
105
134
  getOrgId = () => this.orgId;
135
+
106
136
  getOrgRecordId = () => this.orgRecordId;
137
+
138
+ getBranchRecordId = () => this.branchRecordId;
139
+
107
140
  getBranchId = () => this.branchId;
141
+
142
+ getBranchName = () => this.branchName;
143
+
108
144
  getClientSetting = () => this.clientSetting;
145
+
109
146
  getBranchCode = () => this.branchCode;
147
+
110
148
  getEmail = () => this.email;
149
+
111
150
  getTimeZone = () => this.timeZone;
151
+
112
152
  getCountry = () => this.country;
153
+
113
154
  getOffsetMinute = () => this.offsetMinute;
155
+
114
156
  getGroups = () => this.groups;
157
+
115
158
  getCurrency = () => this.currency;
159
+
116
160
  getGuestInfo = () => this.guestInfo;
161
+
117
162
  getMoreProps = () => this.moreProps;
163
+
164
+ getPackage = () => this.package;
165
+
118
166
  getRoles = () => this.roles;
167
+
119
168
  getModifieds = () => this.modifiedRecords;
169
+
120
170
  getBranches = (): ProfileUserBranch[] => {
121
- // this.branches;
122
171
  const data: ProfileUserBranch[] = [];
123
172
 
124
173
  if (Array.isArray(this.branches)) {
125
174
  for (let i = 0; i < this.branches.length; i++) {
126
- const b = this.branches[i];
175
+ const branches = this.branches[i];
127
176
  data.push({
128
- _id: b._id,
129
- branch: b.branch[0],
130
- groups: b.groups,
131
- xOrg: this.generateXorg(b.tenantId, b.orgId, b.branchId),
177
+ _id: branches._id,
178
+ branch: branches.branch[0],
179
+ groups: branches.groups,
180
+ xOrg: this.generateXOrg(branches.tenantId, branches.orgId, branches.branchId),
132
181
  });
133
182
  }
134
183
  }
135
184
  return data;
136
185
  };
137
- getInvites = (): ProfileUserInvites[] => {
138
- // const usermodel = model<User>('user',UserMongoSchema,'user')
139
186
 
187
+ getInvites = (): ProfileUserInvites[] => {
140
188
  const data: ProfileUserInvites[] = [];
141
189
  if (this.invites) {
142
- // console.log("getInvites",res)
143
190
  for (let i = 0; i < this.invites.length; i++) {
144
- const r = this.invites[0];
145
-
191
+ const invite = this.invites[i];
146
192
  data.push({
147
- _id: r._id,
148
- email: r.email,
149
- tenantId: r.tenantId,
193
+ _id: invite._id,
194
+ email: invite.email,
195
+ tenantId: invite.tenantId,
150
196
  fullName: '',
151
- tenantName: r.tenant[0].tenantName,
152
- created: r.created,
197
+ tenantName: invite.tenant[0].tenantName,
198
+ created: invite.created,
153
199
  });
154
200
  }
155
201
  }
156
202
  return data;
157
203
  };
158
- setCurrentUserInfo = async (tokenstr: string, xorg) => {
159
- this.setXorg(xorg);
204
+
205
+ setCurrentUserInfo = async (tokenstr: string, xOrg: string) => {
206
+ this.setXOrg(xOrg);
160
207
  await this.setUserToken(tokenstr);
161
208
  };
162
209
 
163
210
  /**
164
- * obtain user profile filter by uid,tenantId,orgId,branchId
211
+ * Obtain user profile filter by uid, tenantId, orgId, branchId
165
212
  * @returns Promise<User|undefined>
166
213
  */
167
- obtainProfileFromDb = async (): Promise<User | undefined> => {
214
+ obtainProfileFromDB = async (): Promise<UserProfile | undefined> => {
168
215
  const filter = { $match: { uid: this.uid, tenantId: this.tenantId } };
169
216
 
170
- const joinpermission: PipelineStage = {
217
+ const joinPermission: PipelineStage = {
171
218
  $lookup: {
172
219
  from: 'permission',
173
220
  localField: '_id',
@@ -176,7 +223,6 @@ export class UserContext {
176
223
  pipeline: [
177
224
  {
178
225
  $match: {
179
- // userId:this.getId(),
180
226
  tenantId: this.tenantId,
181
227
  orgId: this.orgId,
182
228
  branchId: this.branchId,
@@ -222,129 +268,111 @@ export class UserContext {
222
268
  const pipeline: PipelineStage[] = [filter];
223
269
 
224
270
  if (this.tenantId > 0) {
225
- pipeline.push(joinpermission);
271
+ pipeline.push(joinPermission);
226
272
  pipeline.push({ $unwind: '$permissions' });
227
273
  }
228
- // console.log("obtainProfileFromDbobtainProfileFromDb ",pipeline)
229
- // const users = await usermodel.find(filter)
230
- const users = await this.usermodel.aggregate(pipeline);
231
- this.logger.verbose(
232
- `aggregate user profile from database`,
233
- 'obtainProfileFromDb',
234
- );
235
- this.logger.verbose(pipeline, 'obtainProfileFromDb x');
236
- this.logger.verbose(users, 'obtainProfileFromDb');
237
- // console.log("obtainProfileFromDbobtainProfileFromDb ",users)
238
- if (users && users.length > 0) {
239
- const userinfo = users[0];
240
-
241
- //console.log(userinfo)
242
- if (this.tenantId > 0) {
243
- const myperm = userinfo.permissions;
244
-
245
- if (myperm && myperm.groups) {
246
- userinfo.groups = myperm.groups;
247
- userinfo.roles = [Role.Everyone, Role.User] as Role[];
248
- for (let g = 0; g < userinfo.groups.length; g++) {
249
- const roles: Role[] = rolegroups[userinfo.groups[g]]();
250
- for (let r = 0; r < roles.length; r++) {
251
- if (!userinfo.roles.includes(roles[r]))
252
- userinfo.roles.push(roles[r]);
274
+
275
+ const userProfiles: UserProfile[] = await this.userModel.aggregate(pipeline);
276
+ if (!userProfiles || userProfiles.length === 0) {
277
+ return undefined;
278
+ }
279
+
280
+ const userProfile = userProfiles[0];
281
+
282
+ if (this.tenantId > 0) {
283
+ const userPermissions = userProfile.permissions;
284
+
285
+ if (userPermissions && userPermissions.groups) {
286
+ userProfile.groups = userPermissions.groups;
287
+ userProfile.roles = [Role.Everyone, Role.User] as Role[];
288
+ for (let g = 0; g < userProfile.groups.length; g++) {
289
+ const roles: Role[] = (<() => Role[]>rolegroups[userProfile.groups[g]])();
290
+ for (let r = 0; r < roles.length; r++) {
291
+ if (!userProfile.roles.includes(roles[r])) {
292
+ userProfile.roles.push(roles[r]);
253
293
  }
254
294
  }
255
-
256
- userinfo.branchRecordId = myperm.currentbranch._id;
257
- userinfo.branchCode = myperm.currentbranch.branchCode;
258
- userinfo.branchName = myperm.currentbranch.branchName;
259
- userinfo.orgRecordId = myperm.currentorg._id;
260
- userinfo.orgCode = myperm.currentorg.orgCode;
261
- userinfo.orgName = myperm.currentorg.orgName;
262
- userinfo.timeZone = myperm.currentorg.timeZone;
263
- userinfo.currency = myperm.currentorg.currency;
264
- userinfo.country = myperm.currentorg.country;
265
- userinfo.offsetMinute = myperm.currentorg.offsetMinute;
266
- userinfo.clientSetting = myperm.currentTenant.clientSetting;
267
295
  }
268
- } else {
269
- userinfo.groups = [];
296
+ if (userPermissions.currentTenant.owner.uid == userProfile.uid) {
297
+ userProfile.roles.push(Role.TenantOwner);
298
+ }
299
+ userProfile.tenantRecordId = userPermissions.currentTenant._id;
300
+ userProfile.package = userPermissions.currentTenant.package;
301
+ userProfile.branchRecordId = userPermissions.currentbranch._id;
302
+ userProfile.branchCode = userPermissions.currentbranch.branchCode;
303
+ userProfile.branchName = userPermissions.currentbranch.branchName;
304
+ userProfile.orgRecordId = userPermissions.currentorg._id;
305
+ userProfile.orgCode = userPermissions.currentorg.orgCode;
306
+ userProfile.orgName = userPermissions.currentorg.orgName;
307
+ userProfile.timeZone = userPermissions.currentorg.timeZone;
308
+ userProfile.currency = userPermissions.currentorg.currency;
309
+ userProfile.country = userPermissions.currentorg.country;
310
+ userProfile.offsetMinute = userPermissions.currentorg.offsetMinute;
311
+ userProfile.clientSetting = userPermissions.currentTenant.clientSetting;
270
312
  }
271
-
272
- const currentitme = new Date(this.lastActivity).getTime();
273
-
274
- const dblastactivity = userinfo.lastActivity ?? '2000-01-01T00:00:00Z';
275
- const lastvisit = new Date(dblastactivity).getTime() ?? 0;
276
- return userinfo;
277
313
  } else {
278
- return undefined;
314
+ userProfile.groups = [];
279
315
  }
316
+
317
+ return userProfile;
280
318
  };
319
+
281
320
  getUserToken = () => this.token;
282
- setUserToken = async (tokenstr: string) => {
283
- //define token info
284
- const tokeninfo = jwt.decode(tokenstr);
285
- this.token = tokenstr;
321
+
322
+ setUserToken = async (tokenStr: string) => {
323
+ this.logger.debug(`===setUserToken===`);
324
+ // Define token info
325
+ const tokeninfo: jwt.JwtPayload = jwt.decode(tokenStr) as jwt.JwtPayload;
326
+ this.token = tokenStr;
286
327
  this.uid = tokeninfo?.sub ?? '';
287
- this.email = tokeninfo?.email ?? '';
288
- this.uname = tokeninfo?.preferred_username ?? '';
289
- this.fullname = tokeninfo?.name ?? '';
290
- this.ssoACL = tokeninfo?.resource_access ?? [];
291
- this.logger.verbose(`set token ${this.uid}`);
292
- //read current user from db
293
- // console.log("Set User token")
294
- // console.log("await this.obtainProfileFromDb()")
295
- const userinfo = await this.obtainProfileFromDb();
296
- this.logger.verbose(userinfo, 'obtainProfileFromDb result');
297
- if (userinfo) {
298
- this.logger.debug(
299
- `${this.uid} user exists in tenant (${this.tenantId})`,
300
- 'setUserToken',
301
- );
302
-
303
- this._id = userinfo._id.toString();
304
- this.branchCode = userinfo['branchCode'] ?? '';
305
- this.branchName = userinfo['branchName'] ?? '';
306
- this.orgCode = userinfo['orgCode'] ?? '';
307
- this.orgName = userinfo['orgName'] ?? '';
308
- this.timeZone = userinfo['timeZone'] ?? '';
309
- this.currency = userinfo['currency'] ?? '';
310
- this.country = userinfo['country'] ?? '';
311
- this.offsetMinute = userinfo['offsetMinute'] ?? '';
312
- this.orgRecordId = userinfo['orgRecordId'] ?? '';
313
- this.branchRecordId = userinfo['branchRecordId'] ?? '';
314
- this.groups = userinfo['groups'] ?? [];
315
- this.clientSetting = userinfo['clientSetting'] ?? {};
316
- this.roles = userinfo['roles'] ?? [Role.Everyone, Role.User];
317
- this.moreProps = this.setMoreProps(userinfo);
328
+ this.email = <string>tokeninfo?.email ?? '';
329
+ this.uname = <string>tokeninfo?.preferred_username ?? '';
330
+ this.fullname = <string>tokeninfo?.name ?? '';
331
+ this.ssoACL = <Record<string, { roles: string[] }>>tokeninfo?.resource_access ?? {};
332
+ this.logger.debug(`User found ${this.uid}`);
333
+
334
+ const userProfile = await this.obtainProfileFromDB();
335
+ if (userProfile) {
336
+ this.logger.debug(`User ${this.uid} exists in tenant (${this.tenantId})`);
337
+
338
+ this._id = userProfile._id.toString();
339
+ this.branchCode = userProfile['branchCode'] ?? '';
340
+ this.branchName = userProfile['branchName'] ?? '';
341
+ this.orgCode = userProfile['orgCode'] ?? '';
342
+ this.orgName = userProfile['orgName'] ?? '';
343
+ this.timeZone = userProfile['timeZone'] ?? '';
344
+ this.currency = userProfile['currency'] ?? '';
345
+ this.country = userProfile['country'] ?? '';
346
+ this.offsetMinute = userProfile['offsetMinute'] ?? 0;
347
+ this.orgRecordId = userProfile['orgRecordId'] ?? '';
348
+ this.branchRecordId = userProfile['branchRecordId'] ?? '';
349
+ this.groups = userProfile['groups'] ?? [];
350
+ this.clientSetting = userProfile['clientSetting'] ?? {};
351
+ this.roles = userProfile['roles'] ?? [Role.Everyone, Role.User];
352
+ this.moreProps = this.setMoreProps(userProfile);
353
+ this.package = userProfile['package'];
354
+ this.appintegration = await this.setAppIntegration();
318
355
  } else {
319
- this.logger.debug(`Set unknown id of current user`, 'setUserToken');
320
- // this.group = ''
321
- // this.tenantId=0
322
- // this.orgId=0
323
- // this.orgCode=0
356
+ this.logger.debug(`User ${this.uid} not exists in tenant (${this.tenantId})`);
357
+ this.logger.debug(`Set unknown id of current user`);
324
358
  this.roles = [Role.Everyone, Role.Unknown];
325
359
  }
326
- this.logger.debug(
327
- `${this.uid} have _id (${this.getId()}), group (${
328
- this.groups
329
- }) and role (${this.getRoles()})`,
330
- );
331
360
 
332
361
  if (this.isRealmAdmin() && !this.roles.includes(Role.SuperAdmin)) {
333
362
  this.roles.push(Role.SuperAdmin);
334
363
  }
335
- this.logger.verbose(this);
364
+
365
+ this.logger.verbose(`User ${this.uid} have _id (${this.getId()}), groups (${this.groups.join(',')}) and roles (${this.getRoles().join(',')}).`);
336
366
  };
337
367
 
338
- generateXorg = (
339
- tenantId: number,
340
- orgId: number,
341
- branchId: number,
342
- ): string => {
368
+ generateXOrg = (tenantId: number, orgId: number, branchId: number): string => {
343
369
  return Base64URL.encodeText(`${tenantId}-${orgId}-${branchId}`);
344
370
  };
371
+
345
372
  getInfo = () => {
346
373
  return this;
347
374
  };
375
+
348
376
  getBranchFilter = () => {
349
377
  return {
350
378
  tenantId: this.tenantId,
@@ -352,63 +380,74 @@ export class UserContext {
352
380
  branchId: this.branchId,
353
381
  };
354
382
  };
383
+
355
384
  getTenantFilter = () => {
356
385
  return { tenantId: this.tenantId };
357
386
  };
387
+
358
388
  getOrgFilter = () => {
359
389
  return {
360
390
  tenantId: this.tenantId,
361
391
  orgId: this.orgId,
362
392
  };
363
393
  };
394
+
364
395
  getWorkflowTaskFilter() {
365
396
  return {
366
397
  'data.tenantId': this.tenantId,
367
398
  'assignments.assignee': this.getUid(),
368
- // 'assignments.assignee': User.getInstance().getUid(),
369
399
  };
370
400
  }
401
+
402
+ getCreateFilterWithId = () => {
403
+ return {
404
+ createdBy: this.uid,
405
+ updatedBy: this.uid,
406
+ created: new Date().toISOString(),
407
+ updated: new Date().toISOString(),
408
+ };
409
+ };
410
+
371
411
  getCreateFilter = () => {
372
- const u = this;
373
412
  return {
374
- tenantId: u.tenantId,
375
- orgId: u.orgId,
376
- branchId: u.branchId,
377
- createdBy: u.uid,
378
- updatedBy: u.uid,
413
+ tenantId: this.tenantId,
414
+ orgId: this.orgId,
415
+ branchId: this.branchId,
416
+ createdBy: this.uid,
417
+ updatedBy: this.uid,
379
418
  created: new Date().toISOString(),
380
419
  updated: new Date().toISOString(),
381
420
  };
382
421
  };
422
+
383
423
  getUpdateFilter = () => {
384
- const u = this;
385
424
  return {
386
- updatedBy: u.uid,
425
+ updatedBy: this.uid,
387
426
  updated: new Date().toISOString(),
388
427
  };
389
428
  };
429
+
390
430
  setCurrentTenant(tenantId: number, orgId: number, branchId: number) {
391
431
  this.tenantId = tenantId;
392
432
  this.orgId = orgId;
393
433
  this.branchId = branchId;
394
434
  }
395
- getXorg = () => this.xOrg;
396
- setXorg = (xorg) => {
397
- this.xOrg = xorg;
435
+
436
+ getXOrg = () => this.xOrg;
437
+
438
+ setXOrg = (xOrg: string) => {
439
+ this.xOrg = xOrg;
398
440
  try {
399
- const decodedText: string = Base64URL.decodeText(xorg);
400
- const x = decodedText.includes('/')
401
- ? decodedText.split('/')
402
- : decodedText.split('-');
403
-
404
- const x1 = Number(x[0]);
405
- const x2 = Number(x[1]);
406
- const x3 = Number(x[2]);
407
- if (x.length == 3 && !isNaN(x1) && !isNaN(x2) && !isNaN(x3)) {
408
- const u = this;
409
- u.tenantId = x1;
410
- u.orgId = x2;
411
- u.branchId = x3;
441
+ const decodedText: string = Base64URL.decodeText(xOrg);
442
+ const xOrgRealm = decodedText.includes('/') ? decodedText.split('/') : decodedText.split('-');
443
+
444
+ const value1 = Number(xOrgRealm[0]);
445
+ const value2 = Number(xOrgRealm[1]);
446
+ const value3 = Number(xOrgRealm[2]);
447
+ if (xOrgRealm.length == 3 && !isNaN(value1) && !isNaN(value2) && !isNaN(value3)) {
448
+ this.tenantId = value1;
449
+ this.orgId = value2;
450
+ this.branchId = value3;
412
451
  } else {
413
452
  throw new BadRequestException('invalidXorg');
414
453
  }
@@ -417,8 +456,9 @@ export class UserContext {
417
456
  }
418
457
  };
419
458
 
420
- async getUserInfo() {
421
- // obtain basic user info
459
+ async getUserInfo(): Promise<UserInfo> {
460
+ this.logger.debug('===getUserInfo===');
461
+
422
462
  const userinfo = {
423
463
  _id: this.getId(),
424
464
  sessionId: this.sessionId,
@@ -441,19 +481,19 @@ export class UserContext {
441
481
  groups: this.groups,
442
482
  roles: this.getRoles(),
443
483
  branches: this.getBranches(),
444
- invites: await this.getInvites(),
484
+ invites: this.getInvites(),
445
485
  moreProps: this.getMoreProps(),
486
+ appintegration: this.getAppIntegration(),
446
487
  };
447
- this.logger.debug(userinfo, 'init getUserInfo()');
448
488
 
449
489
  if (this.getId() != '') {
450
- this.logger.debug(userinfo, 'obtain permissions and invitations');
490
+ this.logger.verbose('User Info: ' + JSON.stringify(userinfo));
451
491
  const filter: PipelineStage = {
452
492
  $match: {
453
493
  uid: this.uid,
454
494
  tenantId: this.tenantId,
455
495
  },
456
- } as PipelineStage;
496
+ };
457
497
  const permission: PipelineStage = {
458
498
  $lookup: {
459
499
  from: 'permission',
@@ -461,7 +501,6 @@ export class UserContext {
461
501
  foreignField: 'userId',
462
502
  as: 'permissions',
463
503
  pipeline: [
464
- // {$match:{userId: this.getId(),},},
465
504
  {
466
505
  $lookup: {
467
506
  from: 'branch',
@@ -473,7 +512,7 @@ export class UserContext {
473
512
  ],
474
513
  },
475
514
  };
476
- const lookupinvitation: PipelineStage = {
515
+ const lookupInvitation: PipelineStage = {
477
516
  $lookup: {
478
517
  from: 'user',
479
518
  localField: 'email',
@@ -493,28 +532,30 @@ export class UserContext {
493
532
  },
494
533
  };
495
534
 
496
- const pipeline: PipelineStage[] = [filter, permission, lookupinvitation];
497
- this.logger.debug(pipeline, 'getUserInfo');
498
- // // // const users = await usermodel.find(filter)
499
- const users = await this.usermodel.aggregate(pipeline);
500
- this.logger.debug(users, 'users from aggregate');
535
+ const pipeline: PipelineStage[] = [filter, permission, lookupInvitation];
536
+ this.logger.verbose('User Info Pipeline: ' + JSON.stringify(pipeline));
537
+
538
+ const userInvitationsAndPermissions: Array<{
539
+ invites?: (ProfileUserInvites & { tenant: Tenant[] })[];
540
+ permissions?: (Permission & { branch: Branch[] })[];
541
+ }> = await this.userModel.aggregate(pipeline);
542
+
543
+ this.logger.verbose('User invitations & permissions data: ' + JSON.stringify(userInvitationsAndPermissions));
544
+
545
+ this.invites = userInvitationsAndPermissions[0].invites;
546
+ this.branches = userInvitationsAndPermissions[0].permissions;
501
547
 
502
- this.invites = users[0].invites;
503
- this.branches = users[0].permissions;
504
- this.logger.verbose(users, 'getUserInfo');
505
548
  userinfo.branches = this.getBranches();
506
549
  userinfo.invites = this.getInvites();
507
- // this.logger.debug(`getUserInfo result ${userinfo}`)
508
550
  } else if (this.getTenantId() > 0) {
509
- throw new ForbiddenException(`userNotExistInTenant`, 'access deny');
551
+ throw new ForbiddenException(`userNotExistInTenant`, 'Access Deny');
510
552
  }
511
553
 
512
554
  return userinfo;
513
555
  }
556
+
514
557
  async decideInvitation(id: string, decision: string): Promise<boolean> {
515
- // const usermodel = model<User>('user',UserMongoSchema,'user')
516
- const res = await this.usermodel.findById(id);
517
- // console.log("find invitation:",res)
558
+ const res = await this.userModel.findById(id);
518
559
  if (!res.uid) {
519
560
  res.uid = this.getUid();
520
561
  res.fullName = this.fullname;
@@ -523,19 +564,13 @@ export class UserContext {
523
564
  if (decision == 'accept') {
524
565
  const result = await res.save({ session: this.dbsession });
525
566
  this.logger.log(result, 'accept invitation 1');
526
- //set permission of all user under this.user_id
527
- const updateresult = await this.permmodel
528
- .updateMany({ uid: '', userId: res._id }, { uid: this.getUid() })
529
- .session(this.dbsession);
567
+ // Set permission of all user under this.user_id
568
+ const updateresult = await this.permModel.updateMany({ uid: '', user_id: res._id }, { uid: this.getUid() }).session(this.dbsession);
530
569
  this.logger.log(updateresult, 'update all permission');
531
570
  return true;
532
571
  } else {
533
- const deleteresult = await this.usermodel
534
- .deleteOne({ _id: id })
535
- .session(this.dbsession);
536
- await this.permmodel
537
- .deleteMany({ uid: '', userId: res._id })
538
- .session(this.dbsession);
572
+ await this.userModel.deleteOne({ _id: id }).session(this.dbsession);
573
+ await this.permModel.deleteMany({ uid: '', user_id: res._id }).session(this.dbsession);
539
574
  return true;
540
575
  }
541
576
  } else {
@@ -544,18 +579,14 @@ export class UserContext {
544
579
  }
545
580
 
546
581
  isRealmAdmin = () => {
547
- const o = this.ssoACL;
582
+ const ssoACL = this.ssoACL;
548
583
  const ssoclient = process.env.OAUTH2_CLIENTID;
549
584
  const adminRole = process.env.OAUTH2_ADMINROLE;
550
585
  const adminemails = process.env.ADMIN_EMAIL.split(',');
551
- // return false
586
+
552
587
  if (adminemails.includes(this.getEmail())) {
553
588
  return true;
554
- } else if (
555
- o[ssoclient] &&
556
- o[ssoclient]['roles'] &&
557
- o[ssoclient]['roles'] == adminRole
558
- ) {
589
+ } else if (ssoACL[ssoclient] && ssoACL[ssoclient]['roles'] && ssoACL[ssoclient]['roles'].includes(adminRole)) {
559
590
  return true;
560
591
  } else {
561
592
  return false;
@@ -563,23 +594,19 @@ export class UserContext {
563
594
  };
564
595
 
565
596
  searchInsertedRecordId(collection: string, _id: string) {
566
- if (!this.modifiedRecords.createds[collection]) return undefined;
567
- return this.modifiedRecords.createds[collection].find(
568
- (item) => item === _id,
569
- );
597
+ if (!this.modifiedRecords.createds[collection]) {
598
+ return undefined;
599
+ }
600
+ return this.modifiedRecords.createds[collection].find((item) => item === _id);
570
601
  }
571
- searchDeletedRecordId(collection: string, _id: string) {
572
- console.log('check is deleted: ', collection, _id);
573
- const deletedlist = this.modifiedRecords.deleteds[collection];
574
602
 
575
- if (deletedlist) {
576
- return this.modifiedRecords.deleteds[collection].find(
577
- (item) => item === _id,
578
- );
579
- } else {
603
+ searchDeletedRecordId(collection: string, _id: string) {
604
+ if (!this.modifiedRecords.deleteds[collection]) {
580
605
  return undefined;
581
606
  }
607
+ return this.modifiedRecords.deleteds[collection].find((item) => item === _id);
582
608
  }
609
+
583
610
  addInsertedRecordId(collection: string, _id: string) {
584
611
  if (this.modifiedRecords.createds[collection]) {
585
612
  this.modifiedRecords.createds[collection].push(_id);
@@ -587,6 +614,7 @@ export class UserContext {
587
614
  this.modifiedRecords.createds[collection] = [_id];
588
615
  }
589
616
  }
617
+
590
618
  addUpdatedRecordId(collection: string, _id: string) {
591
619
  if (this.modifiedRecords.updateds[collection]) {
592
620
  this.modifiedRecords.updateds[collection].push(_id);
@@ -594,6 +622,7 @@ export class UserContext {
594
622
  this.modifiedRecords.updateds[collection] = [_id];
595
623
  }
596
624
  }
625
+
597
626
  addDeletedRecordId(collection: string, _id: string) {
598
627
  if (this.modifiedRecords.deleteds[collection]) {
599
628
  this.modifiedRecords.deleteds[collection].push(_id);
@@ -602,16 +631,9 @@ export class UserContext {
602
631
  }
603
632
  }
604
633
 
605
- async getAllTenants() {
606
- const results = [];
634
+ async getAllTenants(): Promise<UserTenant[]> {
635
+ const results: UserTenant[] = [];
607
636
  if (this.getId() != '') {
608
- const filteruser: PipelineStage = {
609
- $match: {
610
- uid: this.uid,
611
- tenantId: { $gt: 0 },
612
- },
613
- } as PipelineStage;
614
-
615
637
  const permission: PipelineStage = {
616
638
  $lookup: {
617
639
  from: 'permission',
@@ -640,7 +662,6 @@ export class UserContext {
640
662
  ],
641
663
  },
642
664
  };
643
-
644
665
  const pipelines: PipelineStage[] = [
645
666
  { $match: { uid: this.uid, tenantId: { $gt: 0 } } },
646
667
  {
@@ -653,22 +674,25 @@ export class UserContext {
653
674
  },
654
675
  permission,
655
676
  ];
656
- // const users=[]
657
- // this.logger.warn(pipelines, 'pipelines');
658
- const users = await this.usermodel.aggregate(pipelines);
659
-
660
- if (users) {
661
- const activeusers = users.filter((u) => {
662
- // console.log(u.active,'===',true, ' && ',u.tenant[0].active,'===',true)
663
- return u.active === true && u.tenant[0].active === true;
677
+
678
+ const userTenants: Array<
679
+ User & {
680
+ tenant: Tenant[];
681
+ permissions: Array<Permission & { org: Organization; branch: Branch }>;
682
+ }
683
+ > = await this.userModel.aggregate(pipelines);
684
+
685
+ if (userTenants) {
686
+ const activeUserTenants = userTenants.filter((userTenant) => {
687
+ return userTenant.active === true && userTenant.tenant[0].active === true;
664
688
  });
665
- // return activeusers
666
- activeusers.forEach((u) => {
667
- const permissions = u.permissions
668
- .filter((item: any) => {
689
+
690
+ activeUserTenants.forEach((activeUserTenant) => {
691
+ const permissions = activeUserTenant.permissions
692
+ .filter((item) => {
669
693
  return item.org.active && item.branch.active;
670
694
  })
671
- .map((item: any) => {
695
+ .map((item) => {
672
696
  return {
673
697
  _id: item._id,
674
698
  orgId: item.orgId,
@@ -679,15 +703,15 @@ export class UserContext {
679
703
  orgName: item.org.orgName,
680
704
  branchCode: item.branch.branchCode,
681
705
  branchName: item.branch.branchName,
682
- xOrg: this.generateXorg(u.tenantId, item.orgId, item.branchId),
706
+ xOrg: this.generateXOrg(activeUserTenant.tenantId, item.orgId, item.branchId),
683
707
  };
684
708
  });
685
709
 
686
710
  results.push({
687
- _id: u._id,
688
- fullname: u.fullname,
689
- tenantId: u.tenantId,
690
- tenantName: u.tenant[0].tenantName,
711
+ _id: activeUserTenant._id,
712
+ fullName: activeUserTenant.fullName,
713
+ tenantId: activeUserTenant.tenantId,
714
+ tenantName: activeUserTenant.tenant[0].tenantName,
691
715
  permissions: permissions,
692
716
  });
693
717
  });
@@ -696,37 +720,55 @@ export class UserContext {
696
720
  return results;
697
721
  }
698
722
 
699
- setAsStaticUser = (
700
- uid: string,
701
- uname: string,
702
- name: string,
703
- email: string,
704
- xorg:string
705
- ) => {
706
- //define token info
723
+
724
+ setAsStaticUser = (uid: string, uname: string, name: string, email: string, xorg: string) => {
725
+ // Define token info
707
726
  this.token = '';
708
727
  this.uid = uid;
709
728
  this.email = email;
710
729
  this.uname = uname;
711
730
  this.fullname = name;
712
- this.ssoACL = '';
713
- this.roles = [Role.Everyone, Role.User,Role.SuperUser];
714
- this.setXorg(xorg);
731
+ this.ssoACL = {};
732
+ this.roles = [Role.Everyone, Role.User, Role.SuperUser];
733
+ this.setXOrg(xorg);
715
734
  };
716
735
 
717
- setGuestToken(tokenstr:string){
718
- const tokeninfo = jwt.decode(tokenstr);
736
+ setGuestToken(tokenStr: string) {
737
+ const tokeninfo: jwt.JwtPayload = jwt.decode(tokenStr) as jwt.JwtPayload;
719
738
  this.guestInfo.uid = tokeninfo?.sub ?? '';
720
- this.guestInfo.email = tokeninfo?.email ?? '';
721
- this.guestInfo.uname = tokeninfo?.preferred_username ?? '';
722
- this.guestInfo.fullname = tokeninfo?.name ?? '';
723
-
739
+ this.guestInfo.email = <string>tokeninfo?.email ?? '';
740
+ this.guestInfo.uname = <string>tokeninfo?.preferred_username ?? '';
741
+ this.guestInfo.fullname = <string>tokeninfo?.name ?? '';
742
+ }
743
+
744
+ getAppIntegration = () => this.appintegration;
745
+
746
+ async setAppIntegration() {
747
+ const extension: PipelineStage[] = [
748
+ {
749
+ $match: {
750
+ branchId: this.getBranchId(),
751
+ tenantId: this.getTenantId(),
752
+ active: true,
753
+ },
754
+ },
755
+ ];
756
+
757
+ const appintegration = await this.appModel.aggregate(extension);
758
+ if (appintegration && appintegration.length > 0) {
759
+ appintegration.forEach((item) => {
760
+ if (item.appId === 'simbiz6') this.appintegration.simbiz6 = true;
761
+ if (item.appId === 'einvoice') this.appintegration.einvoice = true;
762
+ });
724
763
  }
764
+ return this.appintegration;
765
+
766
+ }
725
767
  /**
726
- * define additional properties from user into moreProps
768
+ * Define additional properties from user into moreProps
727
769
  */
728
- setMoreProps(userinfo: any) {
729
- const allprops = Object.keys(userinfo);
770
+ setMoreProps(userProfile: UserProfile): Record<string, any> {
771
+ const allprops = Object.keys(userProfile);
730
772
  const excludekeys = [
731
773
  'created',
732
774
  'createdBy',
@@ -754,22 +796,126 @@ export class UserContext {
754
796
  'uid',
755
797
  'orgRecordId',
756
798
  ];
757
- let data: any = {};
799
+ const data: Record<string, any> = {};
758
800
  for (let i = 0; i < allprops.length; i++) {
759
801
  const key = allprops[i];
760
802
  if (!excludekeys.includes(key)) {
761
- data[key] = userinfo[key];
803
+ data[key] = userProfile[key];
762
804
  }
763
805
  }
806
+
807
+ if (!data['package']) {
808
+ data['package'] = 'free';
809
+ }
764
810
  return data;
765
811
  }
766
812
 
813
+ isOnlyExecutive = () => {
814
+ return this.groups.includes(Role.Executive) && this.groups.length == 1;
815
+ };
816
+
767
817
  offsetDate(date: string): string {
768
818
  const timestamp = new Date(date).getTime();
769
819
  const offsets = this.getOffsetMinute() * 60000;
770
- const isodate =
771
- new Date(timestamp + offsets).toISOString().split('.')[0] + 'Z';
772
- // console.log("Generate schedule ",date,":",appuser.getOffsetMinute()," => ",isodate)
820
+ const isodate = new Date(timestamp + offsets).toISOString().split('.')[0] + 'Z';
821
+ return isodate;
822
+ }
823
+
824
+ getUserDate(date: string): string {
825
+ const timestamp = new Date(date).getTime();
826
+ const offsets = this.getOffsetMinute() * 60000;
827
+ const isodate = new Date(timestamp + -offsets).toISOString().split('.')[0] + 'Z';
773
828
  return isodate;
774
829
  }
775
830
  }
831
+
832
+ /**
833
+ * Define a type for userinfo
834
+ */
835
+ type UserProfile = {
836
+ _id: string;
837
+ uid: string;
838
+ email: string;
839
+ uname: string;
840
+ fullname: string;
841
+ groups: string[];
842
+ roles: Role[];
843
+ tenantRecordId?: string;
844
+ package?: string;
845
+ branchRecordId?: string;
846
+ branchCode?: string;
847
+ branchName?: string;
848
+ orgRecordId?: string;
849
+ orgCode?: string;
850
+ orgName?: string;
851
+ timeZone?: string;
852
+ currency?: string;
853
+ country?: string;
854
+ offsetMinute?: number;
855
+ clientSetting?: TenantClientSetting;
856
+ lastActivity?: string;
857
+ permissions: {
858
+ _id: string;
859
+ tenantId: number;
860
+ orgId: number;
861
+ branchId: number;
862
+ groups: string[];
863
+ currentbranch: {
864
+ _id: string;
865
+ branchCode: string;
866
+ branchName: string;
867
+ active: boolean;
868
+ };
869
+ currentorg: {
870
+ _id: string;
871
+ orgCode: string;
872
+ orgName: string;
873
+ timeZone: string;
874
+ currency: string;
875
+ country: string;
876
+ offsetMinute: number;
877
+ active: boolean;
878
+ };
879
+ currentTenant: {
880
+ _id: string;
881
+ tenantName: string;
882
+ package: string;
883
+ clientSetting: TenantClientSetting;
884
+ owner: {
885
+ uid: string;
886
+ };
887
+ active: boolean;
888
+ };
889
+ };
890
+ };
891
+
892
+ type UserInfo = {
893
+ _id: string;
894
+ sessionId: string;
895
+ tenantId: number;
896
+ orgId: number;
897
+ orgRecordId: string;
898
+ branchRecordId: string;
899
+ branchId: number;
900
+ branchCode: string;
901
+ branchName: string;
902
+ orgCode: string;
903
+ orgName: string;
904
+ timeZone: string;
905
+ currency: string;
906
+ country: string;
907
+ offsetMinute: number;
908
+ email: string;
909
+ uid: string;
910
+ fullName: string;
911
+ groups: string[];
912
+ roles: Role[];
913
+ branches: ProfileUserBranch[];
914
+ invites: ProfileUserInvites[];
915
+ moreProps: Record<string, any>;
916
+ };
917
+
918
+ type UserTenant = User & {
919
+ tenantName: string;
920
+ permissions: Permission[];
921
+ };