/
shared-ui-utils.ts
1427 lines (1329 loc) · 46.9 KB
/
shared-ui-utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { logger } from '@jetstream/shared/client-logger';
import { HTTP } from '@jetstream/shared/constants';
import {
anonymousApex,
bulkApiGetJob,
checkMetadataResults,
checkMetadataRetrieveResults,
checkMetadataRetrieveResultsAndDeployToTarget,
} from '@jetstream/shared/data';
import { delay, ensureBoolean, NOOP, orderObjectsBy, REGEX } from '@jetstream/shared/utils';
import {
AndOr,
BulkJobWithBatches,
ChangeSet,
DeployOptions,
DeployResult,
ErrorResult,
ExpressionConditionRowSelectedItems,
ExpressionConditionType,
ExpressionGroupType,
ExpressionType,
ListItem,
MapOf,
Maybe,
MimeType,
Nullable,
PermissionSetRecord,
PermissionSetWithProfileRecord,
PositionAll,
QueryFieldWithPolymorphic,
QueryFilterOperator,
RetrieveResult,
SalesforceOrgUi,
SalesforceOrgUiType,
UseReducerFetchAction,
UseReducerFetchState,
} from '@jetstream/types';
import parseISO from 'date-fns/parseISO';
import { saveAs } from 'file-saver';
import type { Field } from 'jsforce';
import safeGet from 'lodash/get';
import isFunction from 'lodash/isFunction';
import isUndefined from 'lodash/isUndefined';
import isNil from 'lodash/isNil';
import isString from 'lodash/isString';
import numeral from 'numeral';
import { parse as parseCsv, unparse, unparse as unparseCsv, UnparseConfig } from 'papaparse';
import {
LiteralType,
Operator,
ValueCondition,
ValueWithDateLiteralCondition,
WhereClause,
WhereClauseWithRightCondition,
} from 'soql-parser-js';
import { Placement as tippyPlacement } from 'tippy.js';
import * as XLSX from 'xlsx';
import { isRelationshipField } from './shared-ui-data-utils';
export function formatNumber(number?: number) {
return numeral(number || 0).format('0,0');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function parseQueryParams<T = any>(queryString: string): T {
const pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
return pairs.reduce((query: Partial<T>, currPair) => {
const [key, value] = currPair.split('=');
query[decodeURIComponent(key)] = decodeURIComponent(value || '');
return query;
}, {}) as T;
}
export function parseCookie<T>(cookieName: string): T | null {
const cookieStrRegex: RegExpExecArray | null = RegExp(`${cookieName}[^;]+`).exec(document.cookie);
const cookieStr = decodeURIComponent(cookieStrRegex ? cookieStrRegex.toString().replace(/^[^=]+./, '') : '');
if (cookieStr.startsWith('j:')) {
try {
return JSON.parse(cookieStr.slice(2));
} catch (ex) {
this.log.warn('Could not parse cookie');
return null;
}
}
return null;
}
export function eraseCookies() {
document.cookie.split(';').forEach((cookie) => {
const [name] = cookie.trim().split('=');
document.cookie = `${name}=; expires=${Number(new Date())}; domain=${document.domain}; path=/`;
});
}
type FieldAccumulator<T> = {
id: Nullable<T>;
name: Nullable<T>;
remaining: T[];
};
export function sortQueryFields(fields: Field[]): Field[] {
// partition name and id field out, then append to front
const reducedFields = orderObjectsBy(fields, 'label').reduce(
(out: FieldAccumulator<Field>, field) => {
if (field.name === 'Id') {
out.id = field;
} else if (field.name === 'Name') {
out.name = field;
} else {
out.remaining.push(field);
}
return out;
},
{
id: null,
name: null,
remaining: [],
}
);
const firstItems: Field[] = [];
if (reducedFields.id) {
firstItems.push(reducedFields.id);
}
if (reducedFields.name) {
firstItems.push(reducedFields.name);
}
return firstItems.concat(reducedFields.remaining);
}
export function sortQueryFieldsStr(fields: string[]): string[] {
// partition name and id field out, then append to front
const reducedFields = fields.reduce(
(out: FieldAccumulator<string>, field) => {
if (field === 'Id') {
out.id = field;
} else if (field === 'Name') {
out.name = field;
} else {
out.remaining.push(field);
}
return out;
},
{
id: null,
name: null,
remaining: [],
}
);
const firstItems: string[] = [];
if (reducedFields.id) {
firstItems.push(reducedFields.id);
}
if (reducedFields.name) {
firstItems.push(reducedFields.name);
}
return firstItems.concat(reducedFields.remaining);
}
/**
* Sort fields, Id and Name are first, then remaining fields
* Relationship fields will always sort in order with the current relationship level
* This is required to ensure that TYPEOF fields are processed accurately
*
* USAGE:
* [{...}].sort(sortQueryFieldsPolymorphicComparable)
*
* NOTE: this is slow algorithm as it is recursive through relationships
* But the input values is not extremely high, so it should be ok
*
* May be worth investing in some optimization
*/
export function sortQueryFieldsPolymorphicComparable(field1: QueryFieldWithPolymorphic, field2: QueryFieldWithPolymorphic): number {
const a = `${field1.field || ''}`.toLocaleLowerCase();
const aParts = a.split('.');
const b = `${field2.field || ''}`.toLocaleLowerCase();
const bParts = b.split('.');
if (a === b) {
return 0;
} else if (a === 'id') {
return -1;
} else if (b === 'id') {
return 1;
} else if (a === 'name') {
return -1;
} else if (b === 'name') {
return 1;
} else if (aParts.length === 1 || bParts.length === 1) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
} else {
// has related fields, remove first element and sort based on remaining parts
const aRoot = aParts.shift();
const bRoot = bParts.shift();
if (aRoot === bRoot) {
return sortQueryFieldsPolymorphicComparable(
{ field: aParts.join('.'), polymorphicObj: field1.polymorphicObj },
{ field: bParts.join('.'), polymorphicObj: field2.polymorphicObj }
);
} else {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
}
}
}
export function polyfillFieldDefinition(field: Field): string {
const autoNumber: boolean = field.autoNumber;
const { type, calculated, calculatedFormula, externalId, nameField, extraTypeInfo, length, precision, referenceTo, scale } = field;
let prefix = '';
let suffix = '';
let value = '';
if (calculated && calculatedFormula) {
prefix = 'Formula(';
suffix = ')';
} else if (calculated) {
prefix = 'Roll-Up Summary(';
suffix = ')';
} else if (externalId) {
suffix = ' (External Id)';
}
if (type === 'id') {
value = `Lookup()`;
} else if (autoNumber) {
value = `Auto Number`;
} else if (nameField) {
value = 'Name';
} else if (type === 'textarea' && extraTypeInfo === 'plaintextarea') {
value = `${length > 255 ? 'Long ' : ''}Text Area(${length})`;
} else if (type === 'textarea' && extraTypeInfo === 'richtextarea') {
value = `Rich Text Area(${length})`;
} else if (isRelationshipField(field)) {
// includes text/reference if referenceTo has data
value = `Lookup(${(referenceTo || []).join(',')})`;
} else if (type === 'string') {
value = `Text(${length})`;
} else if (type === 'boolean') {
value = 'Checkbox';
} else if (type === 'datetime') {
value = 'Date/Time';
} else if (type === 'currency') {
value = `Currency(${precision}, ${scale})`;
} else if (calculated && !calculatedFormula && !autoNumber) {
value = `Number`;
} else if (type === 'double' || type === 'int') {
if (calculated) {
value = `Number`;
} else {
value = `Number(${precision}, ${scale})`;
}
} else if (type === 'encryptedstring') {
value = `Text (Encrypted)(${length})`;
} else if (type === 'location') {
value = 'Geolocation';
} else if (type === 'percent') {
value = `Percent(${precision}, ${scale})`;
} else if (type === 'url') {
value = `URL(${length})`;
} else {
// Address, Email, Date, Time, picklist, phone
value = `${type[0].toUpperCase()}${type.substring(1)}`;
}
return `${prefix}${value}${suffix}`;
}
/**
* Prepares excel file
* @param data Array of objects for one sheet, or map of multiple objects where the key is sheet name
* @param header Array of strings id data is array, or map of strings[] where the key matches the sheet name This will be auto-detected if not provided
* @param [defaultSheetName]
* @returns excel file
*/
export function prepareExcelFile(data: any[], header?: string[], defaultSheetName?: string): ArrayBuffer;
export function prepareExcelFile(data: MapOf<any[]>, header?: MapOf<string[]>, defaultSheetName?: void): ArrayBuffer;
export function prepareExcelFile(data: any, header: any, defaultSheetName: any = 'Records'): ArrayBuffer {
const workbook = XLSX.utils.book_new();
if (Array.isArray(data)) {
header = header || Object.keys(data[0]);
const worksheet = XLSX.utils.aoa_to_sheet(convertArrayOfObjectToArrayOfArray(data, header as string[]));
XLSX.utils.book_append_sheet(workbook, worksheet, defaultSheetName);
} else {
Object.keys(data).forEach((sheetName) => {
if (data[sheetName].length > 0) {
let currentHeader = header && header[sheetName];
let isArrayOfArray = false;
if (!currentHeader) {
if (Array.isArray(data[sheetName][0])) {
isArrayOfArray = true;
} else {
currentHeader = Object.keys(data[sheetName][0]);
}
}
XLSX.utils.book_append_sheet(
workbook,
XLSX.utils.aoa_to_sheet(isArrayOfArray ? data[sheetName] : convertArrayOfObjectToArrayOfArray(data[sheetName], currentHeader)),
sheetName
);
}
});
}
return excelWorkbookToArrayBuffer(workbook);
}
export function excelWorkbookToArrayBuffer(workbook: XLSX.WorkBook): ArrayBuffer {
// https://github.com/sheetjs/sheetjs#writing-options
const workbookArrayBuffer: ArrayBuffer = XLSX.write(workbook, {
bookType: 'xlsx',
bookSST: false,
type: 'array', // ArrayBuffer
});
return workbookArrayBuffer;
}
export function prepareCsvFile(data: MapOf<string>[], header: string[]): string {
return unparse(
{
data,
fields: header,
},
{ header: true, quotes: true, delimiter: detectDelimiter() }
);
}
/**
* Helper method to allow auto-detecting column widths for excel export
*/
export function getMaxWidthFromColumnContent(data: string[][], skipRows: Set<number> = new Set(), defaultIfSkipped = 15): XLSX.ColInfo[] {
const output: number[] = [];
data.forEach((row, rowIdx) => {
row.forEach((col, i) => {
if (skipRows.has(rowIdx)) {
output[i] = defaultIfSkipped;
return;
}
const width = `${col || ''}`.length;
output[i] = output[i] || 0;
output[i] = output[i] > width ? output[i] : width;
});
});
return output.map((width): XLSX.ColInfo => ({ width: width + 2 }));
}
export function getFilename(org: SalesforceOrgUi, parts: string[]) {
return `${parts.join('-')}-${org.username}-${new Date().getTime()}`.replace(REGEX.SAFE_FILENAME, '_');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function saveFile(content: any, filename: string, type: MimeType) {
const blob = new Blob([content], { type });
saveAs(blob, filename);
}
export function base64ToArrayBuffer(base64: string) {
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;
}
export function convertTippyPlacementToSlds(placement: tippyPlacement): PositionAll | null {
switch (placement) {
case 'left':
return 'right';
case 'left-start':
return 'right-bottom';
case 'left-end':
return 'right-top';
case 'right':
return 'left';
case 'right-start':
return 'left-bottom';
case 'right-end':
return 'left-top';
case 'top':
return 'bottom';
case 'top-start':
return 'bottom-right';
case 'top-end':
return 'bottom-left';
case 'bottom':
return 'top';
case 'bottom-start':
return 'top-right';
case 'bottom-end':
return 'top-left';
default:
return null;
}
}
function queryFilterHasValueValue(row: ExpressionConditionType) {
const hasValue = Array.isArray(row.selected.value) ? row.selected.value.length : !!row.selected.value;
return (
row.selected.operator &&
row.selected.resource &&
(hasValue || row.selected.operator === 'isNull' || row.selected.operator === 'isNotNull')
);
}
// did not want to have circular imports
function isExpressionConditionType(value: any): value is ExpressionConditionType {
return !Array.isArray(value.rows);
}
export function convertFiltersToWhereClause(filters: ExpressionType): WhereClause | undefined {
if (!filters) {
return;
}
logger.log({ filters });
// Process all where clauses
const whereClauses = filters.rows.reduce((whereClauses: WhereClause[], row, i) => {
if (isExpressionConditionType(row)) {
if (queryFilterHasValueValue(row)) {
buildExpressionConditionWhereClause(whereClauses, row, filters.action);
}
} else {
const group = { ...row };
group.rows = group.rows.filter(queryFilterHasValueValue);
if (group.rows.length > 0) {
buildExpressionGroupConditionWhereClause(whereClauses, group, filters.action);
}
}
return whereClauses;
}, []);
if (!whereClauses.length) {
return;
}
// combine all where clauses
const rootClause = whereClauses[0];
whereClauses.reduce((whereClause: WhereClauseWithRightCondition, currWhereClause, i) => {
if (whereClause) {
whereClause.right = currWhereClause;
// use current operator as the prior operator (e.x. AND on this item applies to the prior item and this item)
// whereClauses[i - 1].operator = currWhereClause.operator;
}
// if (i === whereClauses.length && currWhereClause.operator) {
// currWhereClause.operator = undefined;
// }
return currWhereClause;
});
return rootClause;
}
export function getOperatorFromWhereClause(operator: Operator, value: string, hasNegation = false): QueryFilterOperator {
operator = (operator?.toUpperCase() as Operator) || operator;
switch (operator) {
case '=':
if (value?.toLowerCase() === 'null') {
return 'isNull';
}
return 'eq';
case '!=':
if (value?.toLowerCase() === 'null') {
return 'isNotNull';
}
return 'ne';
case '<=':
return 'lte';
case '>=':
return 'gte';
case '>':
return 'gt';
case '<':
return 'lt';
case 'LIKE':
if ((value.startsWith('%') && value.endsWith('%')) || (value.startsWith(`'%`) && value.endsWith(`%'`))) {
return hasNegation ? 'doesNotContain' : 'contains';
} else if (value.startsWith('%') || value.startsWith(`'%`)) {
return hasNegation ? 'doesNotEndWith' : 'endsWith';
} else {
return hasNegation ? 'doesNotStartWith' : 'startsWith';
}
case 'IN':
return 'in';
case 'NOT IN':
return 'notIn';
case 'INCLUDES':
return 'includes';
case 'EXCLUDES':
return 'excludes';
default:
return 'eq';
}
}
/**
* Build where clauses from filter rows
*/
function buildExpressionConditionWhereClause(whereClauses: WhereClause[], row: ExpressionConditionType, action: AndOr): WhereClause[] {
// REGULAR WHERE CLAUSE
if (isNegationOperator(row.selected.operator)) {
whereClauses.push({
left: { openParen: 1 },
operator: 'NOT',
});
whereClauses.push({
left: {
operator: convertQueryFilterOperator(row.selected.operator),
logicalPrefix: isNegationOperator(row.selected.operator) ? 'NOT' : undefined,
field: row.selected.resource,
value: getValue(row.selected.operator, row.selected.value),
literalType: getLiteralType(row.selected),
closeParen: 1,
} as ValueCondition | ValueWithDateLiteralCondition,
operator: action,
});
} else {
// REGULAR WHERE CLAUSE
whereClauses.push({
left: {
operator: convertQueryFilterOperator(row.selected.operator),
logicalPrefix: isNegationOperator(row.selected.operator) ? 'NOT' : undefined,
field: row.selected.resource,
value: getValue(row.selected.operator, row.selected.value),
literalType: getLiteralType(row.selected),
} as ValueCondition | ValueWithDateLiteralCondition,
operator: action,
});
}
return whereClauses;
}
function buildExpressionGroupConditionWhereClause(
whereClauses: WhereClause[],
group: ExpressionGroupType,
parentAction: AndOr
): WhereClause[] {
const tempWhereClauses: WhereClauseWithRightCondition[] = [];
group.rows.forEach((row, i) => {
const whereClause: Partial<WhereClauseWithRightCondition> = {
left: {
operator: convertQueryFilterOperator(row.selected.operator),
logicalPrefix: isNegationOperator(row.selected.operator) ? 'NOT' : undefined,
field: row.selected.resource,
value: getValue(row.selected.operator, row.selected.value),
literalType: getLiteralType(row.selected),
} as ValueCondition | ValueWithDateLiteralCondition,
// for final row, use the parent action as the operator so that the next filter does not get the group's operator
operator: i === group.rows.length - 1 ? parentAction : group.action,
};
// Add additional where clause
if (isNegationOperator(row.selected.operator)) {
const negationCondition: Partial<WhereClauseWithRightCondition> = {
left: { openParen: 1 },
operator: 'NOT',
};
(whereClause.left as ValueCondition | ValueWithDateLiteralCondition).closeParen = 1;
tempWhereClauses.push(negationCondition as WhereClauseWithRightCondition);
whereClauses.push(negationCondition as WhereClause);
}
tempWhereClauses.push(whereClause as WhereClauseWithRightCondition);
whereClauses.push(whereClause as WhereClause);
});
if (tempWhereClauses[0].left.openParen) {
tempWhereClauses[0].left.openParen += 1;
} else {
tempWhereClauses[0].left.openParen = 1;
}
const currentLeft = tempWhereClauses[tempWhereClauses.length - 1].left as ValueCondition | ValueWithDateLiteralCondition;
if (currentLeft.closeParen) {
currentLeft.closeParen += 1;
} else {
currentLeft.closeParen = 1;
}
return whereClauses;
}
export function isNegationOperator(operator: Maybe<QueryFilterOperator>): boolean {
switch (operator) {
case 'doesNotContain':
case 'doesNotStartWith':
case 'doesNotEndWith':
return true;
default:
return false;
}
}
function getValue(operator: Maybe<QueryFilterOperator>, value: string | string[]): string | string[] {
value = value || '';
value = Array.isArray(value) ? value.map(escapeSoqlString) : escapeSoqlString(value);
switch (operator) {
case 'contains':
case 'doesNotContain':
return `%${value}%`;
case 'startsWith':
case 'doesNotStartWith':
return `${value}%`;
case 'endsWith':
case 'doesNotEndWith':
return `%${value}`;
case 'isNull':
case 'isNotNull':
return `NULL`;
case 'in':
case 'notIn':
case 'includes':
case 'excludes':
return Array.isArray(value)
? value
: value
.split('\n')
.map((value) => value.trim())
.filter((item) => item !== '');
default:
return value;
}
}
export function escapeSoqlString(value: string) {
if (!value) {
return value;
}
// https://github.com/packagestats/sql-escape/blob/master/index.js
// return value.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, (char) => {
return value.replace(/['\\\%]/g, (char) => {
// prepends a backslash to backslash, percent, and double/single quotes
return '\\' + char;
});
}
export function unescapeSoqlString(value: string) {
if (!value) {
return value;
}
return value
.replace(REGEX.ESCAPED_SINGLE_QUOTE, `'`)
.replace(REGEX.ESCAPED_PERCENT_QUOTE, `%`)
.replace(REGEX.ESCAPED_BACKSLASH_QUOTE, `\\`);
}
function getLiteralType(selected: ExpressionConditionRowSelectedItems): LiteralType {
const field: Field = safeGet(selected, 'resourceMeta.metadata');
if (selected.operator === 'isNull' || selected.operator === 'isNotNull') {
return 'NULL';
}
if (field) {
switch (field.type) {
case 'boolean':
return 'BOOLEAN';
case 'double':
case 'currency':
case 'percent':
return 'DECIMAL';
case 'int':
return 'INTEGER';
case 'date':
if (selected.resourceType === 'SELECT') {
return 'DATE_LITERAL';
}
return 'DATE';
case 'datetime':
if (selected.resourceType === 'SELECT') {
return 'DATE_LITERAL';
}
return 'DATETIME';
default:
return 'STRING';
}
}
return 'STRING';
}
function convertQueryFilterOperator(operator: Maybe<QueryFilterOperator>): Operator {
switch (operator) {
case 'eq':
case 'isNull':
return '=';
case 'ne':
case 'isNotNull':
return '!=';
case 'lt':
return '<';
case 'lte':
return '<=';
case 'gt':
return '>';
case 'gte':
return '>=';
case 'in':
return 'IN';
case 'notIn':
return 'NOT IN';
case 'includes':
return 'INCLUDES';
case 'excludes':
return 'EXCLUDES';
case 'contains':
case 'doesNotContain':
case 'startsWith':
case 'doesNotStartWith':
case 'endsWith':
case 'doesNotEndWith':
return 'LIKE';
default:
return '=';
}
}
/**
* Generate authentication in the url from a salesforce
* @param org
*/
export function getOrgUrlParams(org: SalesforceOrgUi, additionalParams: { [param: string]: string } = {}): string {
const params = {
...additionalParams,
[HTTP.HEADERS.X_SFDC_ID]: org?.uniqueId || '',
};
return Object.keys(params)
.map((key) => `${key}=${encodeURIComponent(params[key])}`)
.join('&');
}
export function getOrgType(org: Maybe<SalesforceOrgUi>): SalesforceOrgUiType | undefined {
if (org?.uniqueId) {
if (org.orgIsSandbox) {
return 'Sandbox';
}
return org.orgOrganizationType === 'Developer Edition' ? 'Developer' : 'Production';
}
return undefined;
}
// TODO: add support for N date literals
export function getDateLiteralListItems(): ListItem<string, { hasUserInput: boolean }>[] {
return [
{ id: 'YESTERDAY', label: 'YESTERDAY', value: 'YESTERDAY', meta: { hasUserInput: false } },
{ id: 'TODAY', label: 'TODAY', value: 'TODAY', meta: { hasUserInput: false } },
{ id: 'TOMORROW', label: 'TOMORROW', value: 'TOMORROW', meta: { hasUserInput: false } },
{ id: 'LAST_WEEK', label: 'LAST_WEEK', value: 'LAST_WEEK', meta: { hasUserInput: false } },
{ id: 'THIS_WEEK', label: 'THIS_WEEK', value: 'THIS_WEEK', meta: { hasUserInput: false } },
{ id: 'NEXT_WEEK', label: 'NEXT_WEEK', value: 'NEXT_WEEK', meta: { hasUserInput: false } },
{ id: 'LAST_MONTH', label: 'LAST_MONTH', value: 'LAST_MONTH', meta: { hasUserInput: false } },
{ id: 'THIS_MONTH', label: 'THIS_MONTH', value: 'THIS_MONTH', meta: { hasUserInput: false } },
{ id: 'NEXT_MONTH', label: 'NEXT_MONTH', value: 'NEXT_MONTH', meta: { hasUserInput: false } },
{ id: 'LAST_90_DAYS', label: 'LAST_90_DAYS', value: 'LAST_90_DAYS', meta: { hasUserInput: false } },
{ id: 'NEXT_90_DAYS', label: 'NEXT_90_DAYS', value: 'NEXT_90_DAYS', meta: { hasUserInput: false } },
// { id: 'LAST_N_DAYS:n', label: 'LAST_N_DAYS:n', value: 'LAST_N_DAYS:n', meta: { hasUserInput: true } },
// { id: 'NEXT_N_DAYS:n', label: 'NEXT_N_DAYS:n', value: 'NEXT_N_DAYS:n', meta: { hasUserInput: true } },
// { id: 'NEXT_N_WEEKS:n', label: 'NEXT_N_WEEKS:n', value: 'NEXT_N_WEEKS:n', meta: { hasUserInput: true } },
// { id: 'LAST_N_WEEKS:n', label: 'LAST_N_WEEKS:n', value: 'LAST_N_WEEKS:n', meta: { hasUserInput: true } },
// { id: 'NEXT_N_MONTHS:n', label: 'NEXT_N_MONTHS:n', value: 'NEXT_N_MONTHS:n', meta: { hasUserInput: true } },
// { id: 'LAST_N_MONTHS:n', label: 'LAST_N_MONTHS:n', value: 'LAST_N_MONTHS:n', meta: { hasUserInput: true } },
{ id: 'THIS_QUARTER', label: 'THIS_QUARTER', value: 'THIS_QUARTER', meta: { hasUserInput: false } },
{ id: 'LAST_QUARTER', label: 'LAST_QUARTER', value: 'LAST_QUARTER', meta: { hasUserInput: false } },
{ id: 'NEXT_QUARTER', label: 'NEXT_QUARTER', value: 'NEXT_QUARTER', meta: { hasUserInput: false } },
// { id: 'NEXT_N_QUARTERS:n', label: 'NEXT_N_QUARTERS:n', value: 'NEXT_N_QUARTERS:n', meta: { hasUserInput: true } },
// { id: 'LAST_N_QUARTERS:n', label: 'LAST_N_QUARTERS:n', value: 'LAST_N_QUARTERS:n', meta: { hasUserInput: true } },
{ id: 'THIS_YEAR', label: 'THIS_YEAR', value: 'THIS_YEAR', meta: { hasUserInput: false } },
{ id: 'LAST_YEAR', label: 'LAST_YEAR', value: 'LAST_YEAR', meta: { hasUserInput: false } },
{ id: 'NEXT_YEAR', label: 'NEXT_YEAR', value: 'NEXT_YEAR', meta: { hasUserInput: false } },
// { id: 'NEXT_N_YEARS:n', label: 'NEXT_N_YEARS:n', value: 'NEXT_N_YEARS:n', meta: { hasUserInput: true } },
// { id: 'LAST_N_YEARS:n', label: 'LAST_N_YEARS:n', value: 'LAST_N_YEARS:n', meta: { hasUserInput: true } },
{ id: 'THIS_FISCAL_QUARTER', label: 'THIS_FISCAL_QUARTER', value: 'THIS_FISCAL_QUARTER', meta: { hasUserInput: false } },
{ id: 'LAST_FISCAL_QUARTER', label: 'LAST_FISCAL_QUARTER', value: 'LAST_FISCAL_QUARTER', meta: { hasUserInput: false } },
{ id: 'NEXT_FISCAL_QUARTER', label: 'NEXT_FISCAL_QUARTER', value: 'NEXT_FISCAL_QUARTER', meta: { hasUserInput: false } },
// { id: 'NEXT_N_FISCAL_QUARTERS:n', label: 'NEXT_N_FISCAL_QUARTERS:n', value: 'NEXT_N_FISCAL_QUARTERS:n', meta: { hasUserInput: true } },
// { id: 'LAST_N_FISCAL_QUARTERS:n', label: 'LAST_N_FISCAL_QUARTERS:n', value: 'LAST_N_FISCAL_QUARTERS:n', meta: { hasUserInput: true } },
{ id: 'THIS_FISCAL_YEAR', label: 'THIS_FISCAL_YEAR', value: 'THIS_FISCAL_YEAR', meta: { hasUserInput: false } },
{ id: 'LAST_FISCAL_YEAR', label: 'LAST_FISCAL_YEAR', value: 'LAST_FISCAL_YEAR', meta: { hasUserInput: false } },
{ id: 'NEXT_FISCAL_YEAR', label: 'NEXT_FISCAL_YEAR', value: 'NEXT_FISCAL_YEAR', meta: { hasUserInput: false } },
// { id: 'NEXT_N_FISCAL_YEARS:n', label: 'NEXT_N_FISCAL_YEARS:n', value: 'NEXT_N_FISCAL_YEARS:n', meta: { hasUserInput: true } },
// { id: 'LAST_N_FISCAL_YEARS:n', label: 'LAST_N_FISCAL_YEARS:n', value: 'LAST_N_FISCAL_YEARS:n', meta: { hasUserInput: true } },
];
}
export const DATE_LITERALS_SET = new Set(getDateLiteralListItems().map((item) => item.value));
export function getBooleanListItems(): ListItem[] {
return [
{ id: 'TRUE', label: 'True', value: 'True' },
{ id: 'FALSE', label: 'False', value: 'False' },
];
}
export function getPicklistListItems(field: Field): ListItem[] {
return (field.picklistValues || []).map((item) => ({
id: item.value,
label: item.label || item.value,
value: item.value,
}));
}
/// START ADD ORG ////
let windowRef: Maybe<Window>;
let addOrgCallbackFn: (org: SalesforceOrgUi) => void;
function handleWindowEvent(event: MessageEvent) {
if (isString(event.data)) {
try {
const org: SalesforceOrgUi = JSON.parse(event.data);
org.orgIsSandbox = ensureBoolean(org.orgIsSandbox);
// ensure from our origin // FIXME:
logger.log({ org });
if (addOrgCallbackFn) {
addOrgCallbackFn(org);
}
if (windowRef) {
windowRef.close();
window.removeEventListener('message', handleWindowEvent);
}
} catch (ex) {
// TODO: tell user there was a problem
}
}
}
export function addOrg(
options: { serverUrl: string; loginUrl: string; replaceOrgUniqueId?: string },
callback: (org: SalesforceOrgUi) => void
) {
const { serverUrl, loginUrl, replaceOrgUniqueId } = options;
addOrgCallbackFn = callback;
window.removeEventListener('message', handleWindowEvent);
const strWindowFeatures = 'toolbar=no, menubar=no, width=1025, height=700';
let url = `${serverUrl}/oauth/sfdc/auth?`;
url += `loginUrl=${encodeURIComponent(loginUrl)}`;
url += `&clientUrl=${encodeURIComponent(document.location.origin)}`;
if (replaceOrgUniqueId) {
url += `&replaceOrgUniqueId=${encodeURIComponent(replaceOrgUniqueId)}`;
}
windowRef = window.open(url, 'Add Salesforce Org', strWindowFeatures);
window.addEventListener('message', handleWindowEvent, false);
}
/// END ADD ORG ////
export function hasFeatureFlagAccess(featureFlags: Set<string>, flag: string) {
if (featureFlags.has('all')) {
return true;
}
return featureFlags.has(flag);
}
const DEFAULT_INTERVAL_5_SEC = 5000;
const DEFAULT_MAX_ATTEMPTS = 500;
// number of attempts before checking less often
const BACK_OFF_INTERVAL = 25;
export function checkIfBulkApiJobIsDone(jobInfo: BulkJobWithBatches, totalBatches: number) {
if (jobInfo.state === 'Failed' || jobInfo.state === 'Aborted') {
return true;
}
return (
jobInfo.batches.length > 0 &&
jobInfo.batches.length === totalBatches &&
jobInfo.batches.every((batch) => batch.state === 'Completed' || batch.state === 'Failed' || batch.state === 'NotProcessed')
);
}
// TODO: This was built, but ended up not being used yet - should be useful in the future
export async function pollBulkApiJobUntilDone(
selectedOrg: SalesforceOrgUi,
jobInfo: BulkJobWithBatches,
totalBatches: number,
options?: { interval?: number; maxAttempts?: number; onChecked?: (jobInfo: BulkJobWithBatches) => void }
): Promise<BulkJobWithBatches> {
let { interval, maxAttempts, onChecked } = options || {};
interval = interval || DEFAULT_INTERVAL_5_SEC;
maxAttempts = maxAttempts || DEFAULT_MAX_ATTEMPTS;
onChecked = isFunction(onChecked) ? onChecked : NOOP;
let attempts = 0;
let done = false;
let jobInfoWithBatches: BulkJobWithBatches = jobInfo;
while (!done && attempts <= maxAttempts) {
await delay(interval);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
jobInfoWithBatches = await bulkApiGetJob(selectedOrg, jobInfo.id!);
logger.log({ jobInfoWithBatches });
onChecked(jobInfoWithBatches);
done = checkIfBulkApiJobIsDone(jobInfoWithBatches, totalBatches);
attempts++;
// back off checking if it is taking a long time
if (attempts % BACK_OFF_INTERVAL === 0) {
interval += DEFAULT_INTERVAL_5_SEC;
}
}
if (!done) {
throw new Error('Timed out while waiting for the job to finish, check Salesforce for results.');
}
return jobInfoWithBatches;
}
/**
*
* @param selectedOrg
* @param id
* @param options Defaults below
* includeDetails = false
* interval = 2000
* maxAttempts = 100
*/
export async function pollMetadataResultsUntilDone(
selectedOrg: SalesforceOrgUi,
id: string,
options?: { includeDetails?: boolean; interval?: number; maxAttempts?: number; onChecked?: (deployResults: DeployResult) => void }
) {
let { includeDetails, interval, maxAttempts, onChecked } = options || {};
includeDetails = includeDetails || false;
interval = interval || DEFAULT_INTERVAL_5_SEC;
maxAttempts = maxAttempts || DEFAULT_MAX_ATTEMPTS;
onChecked = isFunction(onChecked) ? onChecked : NOOP;
let attempts = 0;
let done = false;
let deployResults: DeployResult = {} as DeployResult;
while (!done && attempts <= maxAttempts) {
await delay(interval);
deployResults = await checkMetadataResults(selectedOrg, id, includeDetails);
logger.log({ deployResults });
onChecked(deployResults);
done = deployResults.done;
attempts++;
// back off checking if it is taking a long time
if (attempts % BACK_OFF_INTERVAL === 0) {
interval += DEFAULT_INTERVAL_5_SEC;
}
}
if (!done) {
throw new Error('Timed out while checking for metadata results, check Salesforce for results.');
}
return deployResults;
}
/**
*
* @param selectedOrg
* @param id
* @param options
* @returns
*/
export async function pollRetrieveMetadataResultsUntilDone(
selectedOrg: SalesforceOrgUi,
id: string,
options?: { interval?: number; maxAttempts?: number; onChecked?: (retrieveResults: RetrieveResult) => void; isCancelled?: () => boolean }
) {
let { interval, maxAttempts, onChecked } = options || {};
interval = interval || DEFAULT_INTERVAL_5_SEC;
maxAttempts = maxAttempts || DEFAULT_MAX_ATTEMPTS;
onChecked = isFunction(onChecked) ? onChecked : NOOP;
const isCancelled = options?.isCancelled || (() => false);
let attempts = 0;
let done = false;
let retrieveResults: RetrieveResult = {} as RetrieveResult;
while (!done && attempts <= maxAttempts) {
await delay(interval);
if (isCancelled && isCancelled()) {
throw new Error('Job cancelled');
}
retrieveResults = await checkMetadataRetrieveResults(selectedOrg, id);
logger.log({ retrieveResults });
onChecked(retrieveResults);
done = retrieveResults.done;
attempts++;
// back off checking if it is taking a long time
if (attempts % BACK_OFF_INTERVAL === 0) {
interval += DEFAULT_INTERVAL_5_SEC;
}
if (isCancelled && isCancelled()) {
throw new Error('Job cancelled');
}
}
if (!done) {
throw new Error('Timed out while checking for metadata results, check Salesforce for results.');
}
return retrieveResults;
}
/**
* Retrieve and deploy to second org once results are ready
* @param selectedOrg
* @param targetOrg
* @param id
* @param options
*/
export async function pollAndDeployMetadataResultsWhenReady(
selectedOrg: SalesforceOrgUi,
targetOrg: SalesforceOrgUi,
id: string,
options?: {