-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
datasheet.ot.service.ts
2376 lines (2232 loc) 路 96.2 KB
/
datasheet.ot.service.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
/**
* APITable <https://github.com/apitable/apitable>
* Copyright (C) 2022 APITable Ltd. <https://apitable.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {
CollaCommandName, Field, FieldType, IAttachmentValue, IComments, IField, IFieldMap, IFieldUpdatedMap, IJOTAction, IMeta, INodePermissions,
IObjectDeleteAction, IObjectInsertAction, IObjectReplaceAction, IOperation, IRecord, IRecordAlarm, IRecordCellValue, IRecordMeta, IReduxState,
IRemoteChangeset, isSameSet, IViewProperty, jot, OTActionName, ViewType,
} from '@apitable/core';
import { Injectable } from '@nestjs/common';
import * as Sentry from '@sentry/node';
import { DatasheetRecordAlarmBaseService } from 'database/alarm/datasheet.record.alarm.base.service';
import { EffectConstantName, ICommonData, IFieldData, IRestoreRecordInfo } from 'database/ot/interfaces/ot.interface';
import produce from 'immer';
import { chunk, intersection, isEmpty, pick, update } from 'lodash';
import { InjectLogger } from 'shared/common';
import { SourceTypeEnum } from 'shared/enums/changeset.source.type.enum';
import { CommonException, DatasheetException, OtException, PermissionException, ServerException } from 'shared/exception';
import { ExceptionUtil } from 'shared/exception/exception.util';
import { IdWorker } from 'shared/helpers';
import { IAuthHeader, IOpAttach, NodePermission } from 'shared/interfaces';
import { RestService } from 'shared/services/rest/rest.service';
import { EntityManager } from 'typeorm';
import { Logger } from 'winston';
import { DatasheetChangesetEntity } from '../../datasheet/entities/datasheet.changeset.entity';
import { WidgetEntity } from '../../widget/entities/widget.entity';
import { RecordMap } from '../../interfaces';
import { WidgetService } from '../../widget/services/widget.service';
import { DatasheetEntity } from 'database/datasheet/entities/datasheet.entity';
import { DatasheetMetaEntity } from 'database/datasheet/entities/datasheet.meta.entity';
import { DatasheetRecordEntity } from 'database/datasheet/entities/datasheet.record.entity';
import { RecordCommentEntity } from 'database/datasheet/entities/record.comment.entity';
import { DatasheetMetaService } from 'database/datasheet/services/datasheet.meta.service';
import { DatasheetRecordService } from 'database/datasheet/services/datasheet.record.service';
import { DatasheetService } from 'database/datasheet/services/datasheet.service';
import { RecordCommentService } from 'database/datasheet/services/record.comment.service';
@Injectable()
export class DatasheetOtService {
constructor(
@InjectLogger() private readonly logger: Logger,
private readonly recordCommentService: RecordCommentService,
private readonly recordService: DatasheetRecordService,
private readonly widgetService: WidgetService,
private readonly metaService: DatasheetMetaService,
private readonly restService: RestService,
// private readonly envConfigService: EnvConfigService,
private readonly recordAlarmService: DatasheetRecordAlarmBaseService,
private readonly datasheetService: DatasheetService,
) {}
private static isAttachField(cellValue: any): boolean {
return !!(cellValue && Array.isArray(cellValue) && cellValue[0]?.mimeType && cellValue[0]?.token);
}
/**
* Sets a value in a `Map<key, value[]>`.
*
* If the key exists, the value is appended to the value array, otherwise a new value array is created.
*/
private static setMapValIfExist(map: Map<any, any>, key: any, value: any) {
if (map.has(key)) {
const values = map.get(key);
values.push(value);
map.set(key, values);
} else {
map.set(key, [value]);
}
}
private static generateJotAction(name: OTActionName, path: string[], newValue: any, oldValue?: any): IJOTAction {
switch (name) {
case OTActionName.ObjectInsert:
return {
n: name,
p: path,
oi: newValue,
};
case OTActionName.ObjectReplace:
return {
n: name,
p: path,
od: oldValue,
oi: newValue,
};
default:
return {
n: OTActionName.ObjectInsert,
p: path,
oi: newValue,
};
}
}
createResultSet() {
return {
metaActions: [],
toCreateRecord: new Map<string, IRecordCellValue>(),
toDeleteRecordIds: [],
cleanFieldMap: new Map<string, FieldType>(),
cleanRecordCellMap: new Map<string, IFieldData[]>(),
replaceCellMap: new Map<string, IFieldData[]>(),
initFieldMap: new Map<number, IField[]>(),
toCorrectComment: new Map<string, { comment: IComments; index: number | string }[]>(),
fldOpInViewMap: new Map<string, boolean>(),
fldOpInRecMap: new Map<string, string>(),
toDeleteCommentIds: new Map<string, string[]>(),
deleteWidgetIds: [],
addWidgetIds: [],
spaceCapacityOverLimit: false,
auth: {},
attachCiteCollector: { nodeId: '', addToken: [], removeToken: [] }, // datasheet attachments capacity collector
datasheetId: '',
toCreateForeignDatasheetIdMap: new Map<string, string>(),
toDeleteForeignDatasheetIdMap: new Map<string, string>(),
toCreateLookUpProperties: [],
toDeleteLookUpProperties: [],
toChangeFormulaExpressions: [],
changeViewNumber: 0,
changeFieldNumber: 0,
toDeleteFieldIds: [],
temporaryFieldMap: {},
temporaryViews: [],
toUpdateCommentEmoji: new Map<string, { comment: IComments; emojiAction: boolean }[]>(),
linkActionMainDstId: undefined,
mainLinkDstPermissionMap: new Map<string, NodePermission>(),
toCreateAlarms: new Map<string, IRecordAlarm[]>(),
toDeleteAlarms: new Map<string, IRecordAlarm[]>(),
updatedAlarmIds: [],
addViews: [],
};
}
/**
* Analyze Operation, apply special handling accordingly
*/
async analyseOperates(
spaceId: string,
mainDatasheetId: string,
operation: IOperation[],
datasheetId: string,
permission: NodePermission,
getNodeRole: (dstId: string, auth: IAuthHeader) => Promise<INodePermissions>,
effectMap: Map<string, any>,
resultSet: { [key: string]: any },
auth: IAuthHeader,
sourceType?: SourceTypeEnum,
) {
resultSet.datasheetId = datasheetId;
resultSet.auth = auth;
resultSet.sourceType = sourceType;
resultSet.attachCiteCollector = { nodeId: datasheetId, addToken: [], removeToken: [] };
// Obtain capacity state
resultSet.spaceCapacityOverLimit = await this.restService.capacityOverLimit(auth, spaceId);
const meta = await this.getMetaDataByCache(datasheetId, effectMap);
const fieldMap = meta.fieldMap;
resultSet.temporaryFieldMap = fieldMap;
resultSet.temporaryViews = meta.views;
for (const { mainLinkDstId } of operation) {
const _condition = mainLinkDstId || mainDatasheetId;
const condition = auth.internal || datasheetId === _condition || sourceType === SourceTypeEnum.FORM;
const mainDstPermission = condition ? permission : await getNodeRole(_condition, auth);
resultSet.mainLinkDstPermissionMap.set(_condition, mainDstPermission);
}
resultSet.metaActions = operation.reduce<IJOTAction[]>((pre, cur) => {
// There are many logs during big data operation, commenting out this log is ok
if (this.logger.isDebugEnabled()) {
this.logger.debug(`[${datasheetId}] changeset OperationAction: ${JSON.stringify(cur.actions)}`);
}
const cmd = cur.cmd;
resultSet.linkActionMainDstId = cur.mainLinkDstId || mainDatasheetId;
for (const action of cur.actions) {
if (action.p[0] === 'meta') {
this.dealWithMeta(cmd, action, permission, resultSet);
pre.push(action);
} else {
// Collect attachment fields
this.handleAttachOpCite(action, resultSet, fieldMap);
this.dealWithRecordMap(cmd, action, permission, resultSet);
}
}
return pre;
}, []);
if (resultSet.addViews.length) {
const spaceUsages = await this.restService.getSpaceUsage(spaceId);
const subscribeInfo = await this.restService.getSpaceSubscription(spaceId);
let afterAddGanttViewCountInSpace = spaceUsages.ganttViewNums;
let afterAddCalendarCountInSpace = spaceUsages.calendarViewNums;
(resultSet.addViews as { type: ViewType }[]).forEach(view => {
if (view.type === ViewType.Gantt) {
afterAddGanttViewCountInSpace++;
return;
}
if (view.type === ViewType.Calendar) {
afterAddCalendarCountInSpace++;
return;
}
});
const checkGanttViewsNum = afterAddGanttViewCountInSpace !== spaceUsages.ganttViewNums;
const checkCalendarViewsNum = afterAddCalendarCountInSpace !== spaceUsages.calendarViewNums;
if (subscribeInfo.maxGanttViewsInSpace !== -1 && checkGanttViewsNum && afterAddGanttViewCountInSpace > subscribeInfo.maxGanttViewsInSpace) {
this.restService.createNotification(resultSet.auth, [
{
spaceId,
templateId: 'space_gantt_limit',
body: {
extras: {
usage: afterAddGanttViewCountInSpace,
specification: subscribeInfo.maxGanttViewsInSpace,
},
},
},
]);
throw new ServerException(
DatasheetException.getVIEW_ADD_LIMIT_FOR_GANTTMsg(subscribeInfo.maxGanttViewsInSpace, afterAddGanttViewCountInSpace),
);
}
if (
subscribeInfo.maxCalendarViewsInSpace !== -1 &&
checkCalendarViewsNum &&
afterAddCalendarCountInSpace > subscribeInfo.maxCalendarViewsInSpace
) {
this.restService.createNotification(resultSet.auth, [
{
spaceId,
templateId: 'space_calendar_limit',
body: {
extras: {
usage: afterAddCalendarCountInSpace,
specification: subscribeInfo.maxCalendarViewsInSpace,
},
},
},
]);
throw new ServerException(
DatasheetException.getVIEW_ADD_LIMIT_FOR_CALENDARMsg(subscribeInfo.maxCalendarViewsInSpace, afterAddCalendarCountInSpace),
);
}
}
if (resultSet.toCreateRecord.size) {
const currentRecordCountInDst = await this.metaService.getRowsNumByDstId(datasheetId);
const spaceUsages = await this.restService.getSpaceUsage(spaceId);
const subscribeInfo = await this.restService.getSpaceSubscription(spaceId);
const afterCreateCountInDst = Number(currentRecordCountInDst) + Number(resultSet.toCreateRecord.size);
const afterCreateCountInSpace = Number(spaceUsages.recordNums) + Number(resultSet.toCreateRecord.size);
if (subscribeInfo.maxRowsPerSheet >= 0 && afterCreateCountInDst > subscribeInfo.maxRowsPerSheet) {
const datasheetEntity = await this.datasheetService.getDatasheet(datasheetId);
this.restService.createNotification(resultSet.auth, [
{
spaceId,
templateId: 'datasheet_record_limit',
body: {
extras: {
usage: afterCreateCountInDst,
specification: subscribeInfo.maxRowsPerSheet,
nodeName: datasheetEntity!.dstName,
},
},
},
]);
throw new ServerException(DatasheetException.getRECORD_ADD_LIMIT_PER_DATASHEETMsg(subscribeInfo.maxRowsPerSheet, afterCreateCountInDst));
}
if (subscribeInfo.maxRowsInSpace >= 0 && afterCreateCountInSpace > subscribeInfo.maxRowsInSpace) {
this.restService.createNotification(resultSet.auth, [
{
spaceId,
templateId: 'space_record_limit',
body: {
extras: {
usage: afterCreateCountInSpace,
specification: subscribeInfo.maxRowsInSpace,
},
},
},
]);
throw new ServerException(DatasheetException.getRECORD_ADD_LIMIT_WITHIN_SPACEMsg(subscribeInfo.maxRowsInSpace, afterCreateCountInSpace));
}
const fieldMap = resultSet.temporaryFieldMap;
for (const [recordId, value] of resultSet.toCreateRecord.entries()) {
if (!Object.keys(value).length) {
continue;
}
const _value = {};
for (const fieldId in value) {
const field = fieldMap[fieldId];
if (!field) {
Sentry.captureMessage('Non-existent fields in data being written', {
extra: {
datasheetId,
fieldId,
},
});
continue;
}
// Send compute field writing error to Sentry, request is not interrupted
if (Field.bindContext(field, {} as IReduxState).isComputed) {
Sentry.captureMessage('ot service: writting compute field failed', {
extra: {
datasheetId,
field,
},
});
continue;
}
const { error } = Field.bindContext(field, {} as IReduxState).validateCellValue(value[fieldId]);
if (error) {
Sentry.captureMessage('Format error for data being written', {
extra: {
datasheetId,
error: JSON.stringify(error),
},
});
continue;
}
_value[fieldId] = value[fieldId];
}
resultSet.toCreateRecord.set(recordId, _value);
}
}
if (resultSet.replaceCellMap.size) {
const fieldMap = resultSet.temporaryFieldMap;
for (const [recordId, value] of resultSet.replaceCellMap.entries()) {
const _value = [];
for (const { fieldId, data } of value) {
const field = fieldMap[fieldId];
if (!field) {
Sentry.captureMessage('Non-existent fields in data being written', {
extra: {
datasheetId,
fieldId,
},
});
continue;
}
if (Field.bindContext(field, {} as IReduxState).isComputed) {
Sentry.captureMessage('ot service: writting compute field failed', {
extra: {
datasheetId,
field,
},
});
continue;
}
const { error } = Field.bindContext(field, {} as IReduxState).validateCellValue(data);
if (error) {
Sentry.captureMessage('Format error for data being written', {
extra: {
datasheetId,
error: JSON.stringify(error),
},
});
continue;
}
_value.push({ fieldId, data });
}
resultSet.replaceCellMap.set(recordId, _value);
}
}
// Validate view field operations without permission, if corresponds to created or deleted linked field
if (resultSet.fldOpInViewMap.size > 0) {
for (const [fieldId, isLi] of resultSet.fldOpInViewMap.entries()) {
if (isLi) {
if (!resultSet.toCreateForeignDatasheetIdMap.has(fieldId)) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
} else if (!resultSet.toDeleteForeignDatasheetIdMap.has(fieldId)) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
}
}
// Validate cell operations without edit permission, if is operation related to linking
if (resultSet.fldOpInRecMap.size > 0) {
for (const [fieldId, cmd] of resultSet.fldOpInRecMap.entries()) {
switch (cmd) {
// Delete linked field and update linked field
case 'DeleteField':
case 'SetFieldAttr':
if (!resultSet.toDeleteForeignDatasheetIdMap.has(fieldId)) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
break;
// Undo deleting linked field and undo updating linked field
case 'UNDO:DeleteField':
case 'UNDO:SetFieldAttr':
if (!resultSet.toCreateForeignDatasheetIdMap.has(fieldId)) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
break;
// Select, paste and fill in link reference and respective undo operations, validate if current column is link field
default:
// Take changeset with priority, avoid pushed after OP is merged, then load database metadata
if (resultSet.toCreateForeignDatasheetIdMap.has(fieldId) || resultSet.toDeleteForeignDatasheetIdMap.has(fieldId)) {
break;
}
if (meta?.fieldMap[fieldId]!.type !== FieldType.Link) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
}
}
}
// Not undo operation, create LookUp requires permission above readable of linked datasheet.
// If the target field set field permission, permission above readable of this field is also required.
if (resultSet.toCreateLookUpProperties.length > 0) {
for (const { cmd, relatedLinkFieldId, lookUpTargetFieldId, skipFieldPermission } of resultSet.toCreateLookUpProperties) {
if (skipFieldPermission || cmd === 'UNDO:DeleteField' || cmd === 'UNDO:SetFieldAttr') {
continue;
}
let foreignDatasheetId;
// Take changeset with priority, avoid pushed after OP is merged, then load database metadata
if (resultSet.toCreateForeignDatasheetIdMap.has(relatedLinkFieldId)) {
foreignDatasheetId = resultSet.toCreateForeignDatasheetIdMap.get(relatedLinkFieldId);
} else {
const meta = await this.getMetaDataByCache(datasheetId, effectMap);
const field = meta?.fieldMap[relatedLinkFieldId];
if (field?.type !== FieldType.Link) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
foreignDatasheetId = field.property.foreignDatasheetId;
}
const foreignPermission = await getNodeRole(foreignDatasheetId, auth) as NodePermission;
if (!foreignPermission.readable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
// Validate permissions of reference target field
const targetFieldPermission =
!foreignPermission.fieldPermissionMap ||
!foreignPermission.fieldPermissionMap[lookUpTargetFieldId] ||
foreignPermission.fieldPermissionMap[lookUpTargetFieldId]!.permission?.readable;
if (!targetFieldPermission) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
}
}
effectMap.set(EffectConstantName.MetaActions, resultSet.metaActions);
effectMap.set(EffectConstantName.AttachCite, resultSet.attachCiteCollector);
// If create record -> recordMeta in one op, and then modify this record,
// prevRecordMeta is necessary in terms of recordMeta
effectMap.set(EffectConstantName.RecordMetaMap, {});
return this.transaction;
}
/**
* Collect OP related to creating fields (including fields resulted by pasting)
*/
collectByAddField(cmd: string, action: IObjectInsertAction, permission: NodePermission, resultSet: { [key: string]: any }) {
const oiData = action.oi as IField;
resultSet.temporaryFieldMap[oiData.id] = oiData;
if (oiData.type === FieldType.Link) {
const mainDstId = resultSet.linkActionMainDstId;
if (!mainDstId) {
throw new ServerException(OtException.OPERATION_ABNORMAL);
}
// If this action is generated by current datasheet
const isSelfAction = mainDstId === resultSet.datasheetId;
if (isSelfAction) {
if (!permission.fieldCreatable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
} else {
if (oiData.property.foreignDatasheetId !== mainDstId) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
if (!resultSet.mainLinkDstPermissionMap.get(mainDstId)?.fieldCreatable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
// Operation of linked datasheet relating to creating link field, validate editable permission
if (!permission.editable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
}
const { foreignDatasheetId } = oiData.property;
this.logger.debug(`[${resultSet.datasheetId}] Create or copy link field -> linked datasheet [${foreignDatasheetId}]`);
resultSet.toCreateForeignDatasheetIdMap.set(oiData.id, foreignDatasheetId);
} else {
// Not creating linked field, check permission directly
if (!permission.fieldCreatable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
if (oiData.type === FieldType.AutoNumber) {
// Create AutoNumber field, needs to initialize value according to view
const { viewIdx, nextId } = oiData.property;
if (!nextId) {
DatasheetOtService.setMapValIfExist(resultSet.initFieldMap, viewIdx, oiData);
}
} else if (oiData.type === FieldType.LookUp) {
resultSet.toCreateLookUpProperties.push({ ...oiData.property, fieldId: oiData.id, cmd });
} else if (oiData.type === FieldType.Formula) {
resultSet.toChangeFormulaExpressions.push({ createExpression: oiData.property.expression, fieldId: oiData.id });
}
}
resultSet.changeFieldNumber++;
}
/**
* @description Collect op related to field change
* @param action
* @param permission
* @param resultSet
*/
collectByChangeField(cmd: string, action: IObjectReplaceAction, permission: NodePermission, resultSet: { [key: string]: any }) {
const oiData = action.oi as IField;
const odData = action.od as IField;
// Modify field name
if (oiData.name !== odData.name) {
if (!permission.fieldRenamable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
}
// Modify field description
if ('desc' in oiData && 'desc' in odData && oiData.desc !== odData.desc) {
if (!permission.fieldPropertyEditable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
}
// Modify field type
if (oiData.type !== odData.type) {
let skip = false;
// operations on linked datasheet
if (resultSet.linkActionMainDstId !== resultSet.datasheetId) {
// Since the database deleted link field, link field of linked datasheet is changed to text field,
// don't check permission
if (odData.type == FieldType.Link && odData.property.foreignDatasheetId === resultSet.linkActionMainDstId && oiData.type == FieldType.Text) {
skip = true;
} else if (oiData.type == FieldType.Link && oiData.property.foreignDatasheetId === resultSet.linkActionMainDstId && cmd.startsWith('UNDO:')) {
// Since the database undo deleting link field, original link field of linked datasheet changes back to link field,
// don't check permission
skip = true;
}
}
// Not related operation of linked datasheet, validate edit permission of field property (corresponds to manageable)
if (!skip && !permission.fieldPropertyEditable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
// Update field type in fieldMap, to facilitate later use of fieldMap
resultSet.temporaryFieldMap[oiData.id] = oiData;
// Deleted field type
switch (odData.type) {
case FieldType.Link:
const { foreignDatasheetId } = odData.property;
resultSet.toDeleteForeignDatasheetIdMap.set(odData.id, foreignDatasheetId);
break;
case FieldType.LookUp:
resultSet.toDeleteLookUpProperties.push({ ...odData.property, fieldId: odData.id });
break;
case FieldType.Formula:
resultSet.toChangeFormulaExpressions.push({ deleteExpression: odData.property.expression, fieldId: odData.id });
break;
case FieldType.LastModifiedBy:
// When modifier field is deleted, need collecting, later operations will not update deleted field.property.uuids
resultSet.cleanFieldMap.set(odData.id, odData.type);
break;
default:
break;
}
// Modified field type
switch (oiData.type) {
case FieldType.Link:
const { foreignDatasheetId } = oiData.property;
resultSet.toCreateForeignDatasheetIdMap.set(oiData.id, foreignDatasheetId);
break;
case FieldType.LookUp:
resultSet.toCreateLookUpProperties.push({ ...oiData.property, fieldId: oiData.id, cmd });
break;
case FieldType.Formula:
resultSet.toChangeFormulaExpressions.push({ createExpression: oiData.property.expression, fieldId: oiData.id });
break;
case FieldType.AutoNumber:
// Convert to AutoNumber field type, need to initialize value according to view
const { viewIdx, nextId } = oiData.property;
if (!nextId) {
DatasheetOtService.setMapValIfExist(resultSet.initFieldMap, viewIdx, oiData);
}
break;
default:
break;
}
} else {
// Type is the same, it is field property change, excludes special field operation
const allowEditFieldTypes = [FieldType.Member];
if (allowEditFieldTypes.includes(oiData.type)) {
// Special field requires permission above editable
this.checkCellValPermission(cmd, oiData.id, permission, resultSet);
} else if (oiData.type !== FieldType.CreatedBy) {
// Do not check permission of creator field under this condition, there is no point in checking permission
// due to field permission.
// Otherwise, check field property edit permission (corresponds to manageable)
if (!permission.fieldPropertyEditable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
}
resultSet.temporaryFieldMap[oiData.id] = oiData;
// Replace linked datasheet
if (oiData.type === FieldType.Link && odData.type === FieldType.Link) {
const oiForeignDatasheetId = oiData.property.foreignDatasheetId;
const odForeignDatasheetId = odData.property.foreignDatasheetId;
if (oiForeignDatasheetId === odForeignDatasheetId) {
return;
}
resultSet.toCreateForeignDatasheetIdMap.set(oiData.id, oiForeignDatasheetId);
resultSet.toDeleteForeignDatasheetIdMap.set(odData.id, odForeignDatasheetId);
}
// Replace datasheet query
if (oiData.type === FieldType.LookUp && odData.type === FieldType.LookUp) {
let skipFieldPermission = false;
if (
oiData.property.relatedLinkFieldId === odData.property.relatedLinkFieldId &&
oiData.property.lookUpTargetFieldId === odData.property.lookUpTargetFieldId
) {
// If neithor linking field of lookup field nor its target field changes, don't check permission,
// only check if referenced field set of lookup filtering condition have changed.
skipFieldPermission = true;
const oiReferFieldIds: string[] = [];
const odReferFieldIds: string[] = [];
oiData.property.filterInfo?.conditions.forEach(condition => oiReferFieldIds.push(condition.fieldId));
odData.property.filterInfo?.conditions.forEach(condition => odReferFieldIds.push(condition.fieldId));
// If referenced fields of filter condition are the same, no need to compute resource change
if (isSameSet(oiReferFieldIds, odReferFieldIds)) {
return;
}
}
resultSet.toCreateLookUpProperties.push({ ...oiData.property, fieldId: oiData.id, cmd, skipFieldPermission });
resultSet.toDeleteLookUpProperties.push({ ...odData.property, fieldId: odData.id });
}
// Replace formula
if (oiData.type === FieldType.Formula && odData.type === FieldType.Formula) {
if (oiData.property.expression === odData.property.expression) {
return;
}
resultSet.toChangeFormulaExpressions.push({
createExpression: oiData.property.expression,
deleteExpression: odData.property.expression,
fieldId: oiData.id,
});
}
}
}
/**
* Update op related to deleting field
*/
collectByDeleteField(action: IObjectDeleteAction, permission: NodePermission, resultSet: { [key: string]: any }) {
const odData = action.od as IField;
if (odData.type === FieldType.Link) {
const mainDstId = resultSet.linkActionMainDstId;
if (!mainDstId) {
throw new ServerException(OtException.OPERATION_ABNORMAL);
}
// If this action is generated by current datasheet
const isSelfAction = mainDstId === resultSet.datasheetId;
if (isSelfAction) {
if (!permission.fieldRemovable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
} else {
if (odData.property.foreignDatasheetId !== mainDstId) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
if (!resultSet.mainLinkDstPermissionMap.get(mainDstId)?.fieldRemovable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
// Operation on linked field creation related to linked datasheet, check editable permission
if (!permission.editable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
}
const { foreignDatasheetId } = odData.property;
this.logger.debug(`[${resultSet.datasheetId}] Delete linked field -> linked datasheet [${foreignDatasheetId}]`);
resultSet.toDeleteForeignDatasheetIdMap.set(odData.id, foreignDatasheetId);
} else {
if (!permission.fieldRemovable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
const specialFieldTypes = [FieldType.LastModifiedTime, FieldType.CreatedTime, FieldType.CreatedBy, FieldType.AutoNumber];
if (!specialFieldTypes.includes(odData.type)) {
// Collect deleted fields to clean up corresponding data in fieldUpdatedMap
resultSet.cleanFieldMap.set(odData.id, odData.type);
}
if (odData.type === FieldType.LookUp) {
resultSet.toDeleteLookUpProperties.push({ ...odData.property, fieldId: odData.id });
} else if (odData.type === FieldType.Formula) {
resultSet.toChangeFormulaExpressions.push({ deleteExpression: odData.property.expression, fieldId: odData.id });
}
}
resultSet.changeFieldNumber--;
resultSet.toDeleteFieldIds.push(odData.id);
}
collectByView(action: IJOTAction, permission: NodePermission, resultSet: { [key: string]: any }) {
// Operation of current table requires permission above editable
if (resultSet.datasheetId === resultSet.linkActionMainDstId) {
const view = resultSet.temporaryViews[action.p[2]!] as IViewProperty;
if (action.p.length === 3) {
// ====== New view(including copy view) ======
if ('li' in action) {
if (!permission.viewCreatable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
resultSet.addViews.push(action['li']);
return;
}
// ====== Delete view ======
if ('ld' in action) {
if (!permission.viewRemovable || view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== Move view ======
if ('lm' in action) {
if (!permission.viewMovable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
} else if (action.p.length > 3) {
switch (action.p[3]) {
case 'name':
// ====== View rename ======
if (!permission.viewRenamable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
case 'filterInfo':
// ====== View filters ======
if (!permission.viewFilterable || view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
case 'groupInfo':
// ====== View grouping ======
if (!permission.fieldGroupable || view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
case 'sortInfo':
// ====== View sorting ======
if (!permission.columnSortable || view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
case 'rowHeightLevel':
// ====== View row height ======
if (!permission.rowHighEditable || view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
case 'rows':
// ====== View property changes caused by record creation ======
if ('li' in action) {
if (!permission.rowCreatable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== View property changes caused by record deletion ======
if ('ld' in action) {
if (!permission.rowRemovable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== View property changes caused by record movement ======
if ('lm' in action) {
if (!permission.rowSortable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
break;
case 'columns':
// ====== Hide column ======
if ('li' in action && 'ld' in action && action.li.hidden != action.ld.hidden) {
if (!permission.columnHideable || view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== Field order ======
if ('lm' in action) {
if (!permission.fieldSortable || view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== Field creation impact on view settings ======
if ('li' in action && !('ld' in action)) {
if (!permission.fieldCreatable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== Field deletion impact on view settings ======
if (!('li' in action) && 'ld' in action) {
if (!permission.fieldRemovable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
if (action.p.length < 6) {
break;
}
// ====== Field width ======
if (action.p[5] === 'width') {
if (!permission.columnWidthEditable || view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== Field statistics bar ======
if (action.p[5] === 'statType') {
if (!permission.columnCountEditable || view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
break;
case 'style':
if (action.p.length < 5) {
break;
}
if (view?.lockInfo) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
// ====== View layout ======
if (action.p[4] === 'layoutType' || action.p[4] === 'isAutoLayout' || action.p[4] === 'cardCount') {
if (!permission.viewLayoutEditable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== View style ======
if (action.p[4] === 'isCoverFit' || action.p[4] === 'coverFieldId' || action.p[4] === 'isColNameVisible') {
if (!permission.viewStyleEditable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== View key field (kanban grouping field, gantt start & end datetime field) ======
if (action.p[4] === 'kanbanFieldId' || action.p[4] === 'startFieldId' || action.p[4] === 'endFieldId') {
if (!permission.viewKeyFieldEditable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
// ====== View color option ======
if (action.p[4] === 'colorOption') {
if (!permission.viewColorOptionEditable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
return;
}
break;
case 'lock':
// ====== View lock operation ======
const viewIndex = action.p[2]!;
if ('oi' in action) {
resultSet.temporaryViews[viewIndex] = {
...resultSet.temporaryViews[viewIndex],
lockInfo: action['oi'],
};
return;
}
if ('od' in action) {
delete resultSet.temporaryViews[viewIndex]['lockInfo'];
return;
}
return;
default:
break;
}
}
// Other operation that is not analyzed
if (!permission.editable) {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
} else {
// Operations on linked datasheet, requires editable permission
if (permission.editable) {
return;
}
// If no, maybe this datasheet delete linking fields two-way or undo this operation, causing
// columns change in view.
if (action.p[3] !== 'columns') {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
// Take a note to check outside later if fields exist corresponding to deleted or recovered deleted fields.
if ('li' in action) {
resultSet.fldOpInViewMap.set(action.li.fieldId, true);
} else if ('ld' in action) {
resultSet.fldOpInViewMap.set(action.ld.fieldId, false);
} else {
throw new ServerException(PermissionException.OPERATION_DENIED);
}
}
}
collectByAddWidgetIds(action: IJOTAction, resultSet: { [key: string]: any }) {
if (action.p.includes('widgets')) {
// Recover widget in widget panel
const addWidget = action['li'];
resultSet.addWidgetIds.push(addWidget.id);
return;
}
// Recover whole widget panel
const panel = action['li'];
const widgets: any[] = panel.widgets;
const ids = widgets.map(item => item.id);
resultSet.addWidgetIds.push(...ids);
}
collectByDeleteWidgetOrWidgetPanels(action: IJOTAction, resultSet: { [key: string]: any }) {
if (action.p.includes('widgets')) {
// Delete widget in widget panel
const deleteWidget = action['ld'];
resultSet.deleteWidgetIds.push(deleteWidget.id);
return;
}
// Delete whole widget panel
const panel = action['ld'];
const widgets: any[] = panel.widgets;
const ids = widgets.map(item => item.id);
resultSet.deleteWidgetIds.push(...ids);
}
/**
* Processes data Operation that are related to Meta
*
* @param action
* @param permission
* @param resultSet
*/
dealWithMeta(cmd: string, action: IJOTAction, permission: NodePermission, resultSet: { [key: string]: any }) {
if (action.p[1] === 'fieldMap') {
// ===== Field operation BEGIN =====
/**
* Field operation, check permission above manageable.
* Member field is special, value update requires updating field property, so don't intercept here,
* check by field type. Since Creation, update and deletion is fine-grained.
* Now begin fine-grained field permision checking
*/
// ====== New field(including copy field) ======
if ('oi' in action && !('od' in action)) {
// Create field or copy field
this.collectByAddField(cmd, action, permission, resultSet);
return;
}
// ====== Modify field ======
if ('oi' in action && 'od' in action) {
this.collectByChangeField(cmd, action, permission, resultSet);
return;
}
// ====== Delete field ======
if (!('oi' in action) && 'od' in action) {
this.collectByDeleteField(action, permission, resultSet);
return;
}