@jsb188/app 1.1.3 → 1.1.5

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/utils/object.ts CHANGED
@@ -29,7 +29,7 @@ export function uniq(arr: Array<any>, fn?: (value: any, index: number, self: Arr
29
29
  * Remove undefined (and/or null) values from an object
30
30
  */
31
31
 
32
- export function removeUndefined(obj: Record<string, any>, removeNull?: boolean) {
32
+ export function removeUndefined<T>(obj: T, removeNull?: boolean) {
33
33
  for (const key in obj) {
34
34
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
35
35
  if (
@@ -37,7 +37,7 @@ export function removeUndefined(obj: Record<string, any>, removeNull?: boolean)
37
37
  (removeNull && obj[key] === null)
38
38
  ) {
39
39
  delete obj[key];
40
- } else if (typeof obj[key] === 'object') {
40
+ } else if (obj[key] && typeof obj[key] === 'object') {
41
41
  removeUndefined(obj[key], removeNull);
42
42
  }
43
43
  }
@@ -149,9 +149,9 @@ export function orderBy(
149
149
  * Group array by something
150
150
  */
151
151
 
152
- export function groupBy(arr: Array<any>, key: string) {
152
+ export function groupBy(arr: Array<any>, key: string | ((obj: any) => string)) {
153
153
  return arr.reduce((acc, obj) => {
154
- const group = obj[key];
154
+ const group = typeof key === 'function' ? key(obj) : obj[key];
155
155
  acc[group] = acc[group] || [];
156
156
  acc[group].push(obj);
157
157
  return acc;
@@ -268,83 +268,40 @@ export function intersection(arr1: Array<any>, arr2: Array<any>) {
268
268
  return arr1.filter((value) => arr2.includes(value));
269
269
  }
270
270
 
271
- /**
272
- * Get a nested value of an object at a property path
273
- *
274
- * @param obj - The object to get the value from
275
- * @param path - The property path as a string, e.g. 'a.b.c'
276
- */
277
-
278
- export function getNestedValue(obj: any, path: string): any {
279
- if (!obj || !path) {
280
- return undefined;
281
- }
282
- return path.split('.').reduce((o, key) => {
283
- if (o && typeof o === 'object' && key in o) {
284
- return o[key];
285
- }
286
- return undefined;
287
- }, obj);
288
- }
289
-
290
- /**
291
- * Append value to a nested object
292
- *
293
- * @param obj - The object to append to
294
- * @param path - The property path as a string, e.g. 'a.b.c'
295
- * @param value - The value to append
296
- */
297
-
298
- export function assignToNestedObject(obj: any, path: string, value: any) {
299
- if (!obj || !path) {
300
- return;
301
- }
302
- const keys = path.split('.');
303
- const lastKey = keys.pop();
304
- const nestedObj = keys.reduce((o, key) => {
305
- if (!o[key]) {
306
- o[key] = {};
307
- }
308
- return o[key];
309
- }, obj);
310
-
311
- if (lastKey) {
312
- if (typeof nestedObj === 'object' && nestedObj !== null) {
313
- nestedObj[lastKey] = value;
314
- } else {
315
- console.warn(`(!1) Cannot assign value to ${lastKey} because its reference is not an object.`);
316
- }
317
- }
318
-
319
- return obj;
320
- }
321
-
322
271
  /**
323
272
  * Group a collection and merge array fields
324
273
  * NOTE: Use this after a findAll() query with inner collections
325
274
  *
326
275
  * @param collections
327
276
  * @param innerCollectionNames
277
+ * @param innerCollectionDefaultValues - Use this to define Array or Object
328
278
  * @param primaryKeyName
329
279
  * @returns
330
280
  */
331
281
 
332
- export function groupCollections(collections: Array<any>, innerCollectionNames: string[], primaryKeyName = 'id'): any[] {
282
+ export function groupCollections(
283
+ collections: Array<any>,
284
+ innerCollectionNames: string[],
285
+ innerCollectionDefaultValues: Record<string, any> = {},
286
+ primaryKeyName = 'id',
287
+ ): any[] {
333
288
  return collections.reduce((acc, obj) => {
334
289
  const primaryKey = obj[primaryKeyName];
335
290
  const i = acc.findIndex((o: any) => o[primaryKeyName] === primaryKey);
336
291
 
337
292
  if (i === -1) {
338
293
  innerCollectionNames.forEach((name: string) => {
339
- const ref = getNestedValue(obj, name);
340
- if (!ref) {
341
- assignToNestedObject(obj, name, []);
294
+ const defaultValue = innerCollectionDefaultValues[name] || [];
295
+ const ref = getObject(obj, name);
296
+
297
+ if (ref) {
298
+ setObject(obj, name, Array.isArray(defaultValue) ? [ref] : ref);
342
299
  } else {
343
- assignToNestedObject(obj, name, [ref]);
300
+ setObject(obj, name, defaultValue);
344
301
  }
345
302
 
346
- // Old version, but this doesn't support merged array collections
347
- // if (!obj[name]) {
303
+ // Old version, but this doesn't support merged array collections
304
+ // if (!obj[name]) {
348
305
  // obj[name] = [];
349
306
  // } else {
350
307
  // obj[name] = [obj[name]];
@@ -354,16 +311,17 @@ export function groupCollections(collections: Array<any>, innerCollectionNames:
354
311
  acc.push(obj);
355
312
  } else {
356
313
  innerCollectionNames.forEach((name: string) => {
357
- const innerObj = getNestedValue(obj, name);
358
- const ref = getNestedValue(acc[i], name);
314
+ const defaultValue = innerCollectionDefaultValues[name] || [];
315
+ const innerObj = getObject(obj, name);
316
+ const ref = getObject(acc[i], name);
359
317
 
360
318
  if (!ref) {
361
- assignToNestedObject(acc[i], name, innerObj ? [innerObj] : []);
319
+ setObject(acc[i], name, innerObj && Array.isArray(innerObj) ? [innerObj] : (innerObj || defaultValue));
362
320
  } else if (innerObj && !ref.find((o: any) => o.id === innerObj.id)) {
363
- assignToNestedObject(acc[i], name, ref.concat(innerObj));
321
+ setObject(acc[i], name, Array.isArray(ref) ? ref.concat(innerObj) : innerObj);
364
322
  }
365
323
 
366
- // Old version, but this doesn't support merged array collections
324
+ // Old version, but this doesn't support merged array collections
367
325
  // const innerObj = obj[name];
368
326
  // if (!acc[i][name]) {
369
327
  // acc[i][name] = innerObj ? [innerObj] : [];
@@ -394,8 +352,28 @@ export function cloneArrayLike(obj: any) {
394
352
  return { ...obj };
395
353
  }
396
354
 
355
+ /**
356
+ * There's a lot of cases where Array[] are automatically converted to Array-like Objects by Javasript itself.
357
+ * For example, when using JS Map() or Set() with a medium to larget amount of data.
358
+ * This function checks if the object is an array-like Object, and returns a plain Object.
359
+ * @param obj - The object to check
360
+ * @returns - Returns a plain Object if the input is an array-like Object, otherwise returns the original object.
361
+ */
362
+
363
+ export function mapArrayLikeObjects(obj: any) {
364
+ if (
365
+ !Array.isArray(obj) && obj !== null && typeof obj === 'object' &&
366
+ Object.keys(obj).every((key, i) => key === i.toString())
367
+ ) {
368
+ return Object.values(obj);
369
+ }
370
+ return obj;
371
+ }
372
+
397
373
  /**
398
374
  * Check if Object is iterable
375
+ * @param obj - The object to check
376
+ * @returns - Returns true if the object is iterable, otherwise false
399
377
  */
400
378
 
401
379
  export function isIterable(obj: any) {
@@ -404,6 +382,8 @@ export function isIterable(obj: any) {
404
382
 
405
383
  /**
406
384
  * Get the last key from a JS Map
385
+ * @param map - The Map to get the last key from
386
+ * @returns - Returns the last key from the Map, or undefined if the Map is empty
407
387
  */
408
388
 
409
389
  export function getLastMapKey(map: Map<any, any>) {
@@ -415,6 +395,8 @@ export function getLastMapKey(map: Map<any, any>) {
415
395
 
416
396
  /**
417
397
  * Get the first key from a JS Map
398
+ * @param map - The Map to get the first key from
399
+ * @returns - Returns the first key from the Map, or undefined if the Map is empty
418
400
  */
419
401
 
420
402
  export function getFirstMapKey(map: Map<any, any>) {
@@ -423,3 +405,93 @@ export function getFirstMapKey(map: Map<any, any>) {
423
405
  }
424
406
  return Array.from(map.keys()).shift();
425
407
  }
408
+
409
+ /**
410
+ * Get value at path in an object
411
+ * @param obj - The object to get the value from
412
+ * @param path - The path to the value, e.g. 'a.b.c'
413
+ * @returns - Returns the value at the path, or undefined if the path does not exist
414
+ */
415
+
416
+ export function getObject(obj: any, path: string): any {
417
+ if (!obj || !path) {
418
+ return undefined;
419
+ }
420
+ return path.split('.').reduce((o, key) => {
421
+ if (o && typeof o === 'object' && key in o) {
422
+ return o[key];
423
+ }
424
+ return undefined;
425
+ }, obj);
426
+ }
427
+
428
+ /**
429
+ * Set value at path in an object
430
+ * @param obj - The object to set the value in
431
+ * @param path - The path to the value, e.g. 'a.b.c'
432
+ * @param value - The value to set
433
+ * @returns - Returns the modified object
434
+ */
435
+
436
+ export function setObject(obj: any, path: string, value: any): any {
437
+ if (!obj || !path) {
438
+ return obj;
439
+ }
440
+ const keys = path.split('.');
441
+ const lastKey = keys.pop();
442
+ const nestedObj = keys.reduce((o, key) => {
443
+ if (!o[key]) {
444
+ o[key] = {};
445
+ }
446
+ return o[key];
447
+ }, obj);
448
+
449
+ if (lastKey) {
450
+ if (typeof nestedObj === 'object' && nestedObj !== null) {
451
+ nestedObj[lastKey] = value;
452
+ } else {
453
+ console.warn(`(!1) Cannot assign value to ${lastKey} because its reference is not an object.`);
454
+ }
455
+ }
456
+
457
+ return obj;
458
+ }
459
+
460
+ /**
461
+ * Check if namespace exists in an object
462
+ * @param obj - The object to check
463
+ * @param namespace - The namespace to check, e.g. 'a.b.c'
464
+ * @returns - Returns true if the namespace exists, otherwise false
465
+ */
466
+
467
+ export function hasObject(obj: any, namespace: string): boolean {
468
+ if (!obj || !namespace) {
469
+ return false;
470
+ }
471
+ return namespace.split('.').every((key) => {
472
+ if (obj && typeof obj === 'object' && key in obj) {
473
+ obj = obj[key];
474
+ return true;
475
+ }
476
+ return false;
477
+ });
478
+ }
479
+
480
+ /**
481
+ * Sort an Object by keys alphabetically
482
+ * @param obj - The object to sort
483
+ * @returns - Returns a new object with keys sorted alphabetically
484
+ */
485
+
486
+ export function sortObjectByKeys(obj: Record<string, any>): Record<string, any> {
487
+ if (!obj || typeof obj !== 'object') {
488
+ return obj;
489
+ }
490
+
491
+ const sortedKeys = Object.keys(obj).sort();
492
+ const sortedObj: Record<string, any> = {};
493
+ for (const key of sortedKeys) {
494
+ sortedObj[key] = obj[key];
495
+ }
496
+ return sortedObj;
497
+ }
@@ -0,0 +1,102 @@
1
+ import { OrganizationRelData, OrganizationRelGQLData } from '../types/organization.d';
2
+
3
+ // Placeholder to match Server import
4
+ type ViewerOrganization = any;
5
+
6
+ const PERMISSION_TO_INT = {
7
+ NONE: 0,
8
+ READ: 1,
9
+ WRITE: 2,
10
+ MANAGE: 3,
11
+ };
12
+
13
+ const INT_TO_PERMISSION = Object.keys(PERMISSION_TO_INT);
14
+
15
+ /**
16
+ * Get default permissions by role
17
+ */
18
+
19
+ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQLData | OrganizationRelData | ViewerOrganization) {
20
+ const role = orgRel?.role || 'MEMBER';
21
+ const acl: Record<string, any> = { ...orgRel?.acl };
22
+
23
+ for (const key in acl) {
24
+ if (typeof acl[key] === 'number') {
25
+ acl[key] = INT_TO_PERMISSION[acl[key]] || 'NONE';
26
+ }
27
+ }
28
+
29
+ // Also keep this synced with [resolvers/organizationTypeResolvers.ts]
30
+
31
+ // 0 = "NONE"
32
+ // 1 = "READ"
33
+ // 2 = "WRITE"
34
+ // 3 = "MANAGE"
35
+
36
+ switch (role) {
37
+ case 'ADMIN':
38
+ case 'OWNER':
39
+ return {
40
+ billing: acl.billing || 'MANAGE',
41
+ digests: acl.digests || 'MANAGE', // 2/3 = receive digests, 1 = only see from web app
42
+ logs: acl.logs || 'MANAGE', // "READ" for logs does nothing
43
+ viewData: acl.viewData || 'MANAGE', // This blocks access from users being able to read other people's logs
44
+ members: acl.members || 'MANAGE',
45
+ finances: acl.finances || 'MANAGE',
46
+ settings: acl.settings || 'MANAGE',
47
+ integrations: acl.integrations || 'MANAGE',
48
+ reminders: acl.reminders || 'MANAGE',
49
+ };
50
+ case 'MANAGER':
51
+ return {
52
+ billing: acl.billing || 'READ',
53
+ digests: acl.digests || 'WRITE', // 2/3 = receive digests, 1 = only see from web app
54
+ logs: acl.logs || 'MANAGE', // "READ" for logs does nothing
55
+ viewData: acl.viewData || 'MANAGE', // This blocks access from users being able to read other people's logs
56
+ members: acl.members || 'WRITE',
57
+ finances: acl.finances || 'READ',
58
+ settings: acl.settings || 'READ',
59
+ integrations: acl.integrations || 'NONE',
60
+ reminders: acl.reminders || 'MANAGE',
61
+ };
62
+ case 'MEMBER':
63
+ default:
64
+ }
65
+
66
+ return {
67
+ billing: acl.billing || 'NONE',
68
+ digests: acl.digests || 'NONE', // 2/3 = receive digests, 1 = only see from web app
69
+ logs: acl.logs || 'WRITE', // "READ" for logs does nothing
70
+ viewData: acl.viewData || 'NONE', // This blocks access from users being able to read other people's logs
71
+ members: acl.members || 'READ',
72
+ finances: acl.finances || 'NONE',
73
+ settings: acl.settings || 'READ',
74
+ integrations: acl.integrations || 'NONE',
75
+ reminders: acl.reminders || 'WRITE',
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Check if this account's ACL has required permissions for an action
81
+ */
82
+
83
+ export type ACLPermissionCheck = 'READ' | 'WRITE' | 'MANAGE';
84
+ export type PermissionCheckFor = keyof ReturnType<typeof getDefaultPermissionsByRole>;
85
+
86
+ export function checkACLPermission(
87
+ orgRel: OrganizationRelGQLData | OrganizationRelData | ViewerOrganization,
88
+ check: PermissionCheckFor,
89
+ requiredPermission: ACLPermissionCheck,
90
+ ): boolean | null {
91
+ if (!orgRel) {
92
+ return null;
93
+ }
94
+
95
+ const acl = getDefaultPermissionsByRole(orgRel);
96
+
97
+ const requiredInt = PERMISSION_TO_INT[requiredPermission] || 4; // If invalid, it will always return false
98
+ const permission = acl[check] as ACLPermissionCheck;
99
+ const acccountPermissionInt = PERMISSION_TO_INT[permission] || 0; // If invalid, it will always return false
100
+
101
+ return acccountPermissionInt >= requiredInt;
102
+ }
package/utils/string.ts CHANGED
@@ -42,17 +42,16 @@ export function shortenToSpace(
42
42
  */
43
43
 
44
44
  export function guessFirstName(str: string, len: number = 40): string {
45
-
46
- let shortened = str?.replace(/^(a|an|the|da|de|that|there|this|than|then)\b/i, '')?.trim() || '';
47
- const spaceIx = shortened.indexOf(' ');
45
+ let shortened = str?.replace(/^(a|an|the|da|de|that|there|this|than|then)\b/i, '')?.trim() || '';
46
+ const spaceIx = shortened.indexOf(' ');
48
47
 
49
48
  if (spaceIx >= 0) {
50
- shortened = shortened.substring(0, spaceIx + 1);
51
- }
49
+ shortened = shortened.substring(0, spaceIx + 1);
50
+ }
52
51
 
53
- if (len < shortened.length) {
54
- shortened = shortened.substring(0, len);
55
- }
52
+ if (len < shortened.length) {
53
+ shortened = shortened.substring(0, len);
54
+ }
56
55
 
57
56
  const articleReplacedEnd = shortened.replace(
58
57
  /\b(a|an|the|da|de|that|there|this|than|then)$/i,
@@ -60,7 +59,7 @@ export function guessFirstName(str: string, len: number = 40): string {
60
59
  );
61
60
 
62
61
  if (articleReplacedEnd.length < 5) {
63
- return shortened;
62
+ return shortened.trim();
64
63
  }
65
64
 
66
65
  return articleReplacedEnd.trim();
@@ -107,6 +106,7 @@ export function convertToInternationalPhone(str: string) {
107
106
  /**
108
107
  * Check if phone number
109
108
  * @returns TRUE if starts with + and has 7-15 digits
109
+ * NOTE: This will convert phone-like strings to international format
110
110
  */
111
111
 
112
112
  export function isPhone(str: string, doNotConvertInternational: boolean = false) {
@@ -327,3 +327,49 @@ export function textWithBrackets(
327
327
  }
328
328
  return `${text} ${brackets[0].trimStart()}${bText}${brackets[1].trimEnd()}`;
329
329
  }
330
+
331
+ /**
332
+ * Remove all line breaks and spaces from String
333
+ * NOTE: This is designed to remove garbage string from OpenAI text generation
334
+ *
335
+ * @param str - String to clean
336
+ * @returns Cleaned string without line breaks and spaces
337
+ */
338
+
339
+ export function removeGeneratedTextGarbage(str: string) {
340
+ if (!str || typeof str !== 'string') {
341
+ return '';
342
+ }
343
+ // Remove all line breaks and spaces
344
+ return str.replace(/[\n\r\s]+/g, ' ').trim();
345
+ }
346
+
347
+ /**
348
+ * Escape values not allowed in CSV column
349
+ * @param value String value to escape
350
+ * @returns Escaped string value
351
+ */
352
+
353
+ export function escapeCSVValue(value: string): string {
354
+ if (/[",\n]/.test(value)) {
355
+ return `"${value.replace(/"/g, '""')}"`;
356
+ }
357
+ return value;
358
+ }
359
+
360
+ /**
361
+ * Convert Intl phone format to a readable format.
362
+ * Example: "+1 (555) 123-4567"
363
+ */
364
+
365
+ export function formatPhoneNumber(phone: string): string {
366
+ const match = phone.match(/(\d{3})(\d{3})(\d{4})$/);
367
+ if (match) {
368
+ const [, area, first, second] = match;
369
+ const countryCode = phone.substring(0, phone.length - area.length - first.length - second.length);
370
+ // NOTE: This does not account for non North American (+1) phone numbers
371
+ return `${countryCode} (${area}) ${first}-${second}`;
372
+ }
373
+
374
+ return phone;
375
+ }