Merge branch 'dmp-refactoring' of https://code-repo.d4science.org/MaDgiK-CITE/argos into dmp-refactoring

This commit is contained in:
Diamantis Tziotzios 2024-03-27 18:49:03 +02:00
commit 4d50aefacd
29 changed files with 1092 additions and 547 deletions

View File

@ -23,17 +23,15 @@ public class TransformerProperties {
private final String url; private final String url;
private final String transformerId; private final String transformerId;
private final List<String> codes;
private final String issuerUrl; private final String issuerUrl;
private final String clientId; private final String clientId;
private final String clientSecret; private final String clientSecret;
private final String scope; private final String scope;
@ConstructorBinding @ConstructorBinding
public TransformerSource(String url, String transformerId, List<String> codes, String issuerUrl, String clientId, String clientSecret, String scope) { public TransformerSource(String url, String transformerId, String issuerUrl, String clientId, String clientSecret, String scope) {
this.url = url; this.url = url;
this.transformerId = transformerId; this.transformerId = transformerId;
this.codes = codes;
this.issuerUrl = issuerUrl; this.issuerUrl = issuerUrl;
this.clientId = clientId; this.clientId = clientId;
this.clientSecret = clientSecret; this.clientSecret = clientSecret;
@ -60,10 +58,6 @@ public class TransformerProperties {
return scope; return scope;
} }
public List<String> getCodes() {
return codes;
}
public String getTransformerId() { public String getTransformerId() {
return transformerId; return transformerId;
} }

View File

@ -68,6 +68,7 @@ public class RuleBuilder extends BaseBuilder<Rule, RuleEntity> {
List<Rule> models = new ArrayList<>(); List<Rule> models = new ArrayList<>();
for (RuleEntity d : data) { for (RuleEntity d : data) {
Rule m = new Rule(); Rule m = new Rule();
if (fields.hasField(this.asIndexer(Rule._target))) m.setTarget(d.getTarget());
if (fields.hasField(this.asIndexer(Rule._dateValue)) && FieldType.isDateType(fieldType)) m.setDateValue(d.getDateValue()); if (fields.hasField(this.asIndexer(Rule._dateValue)) && FieldType.isDateType(fieldType)) m.setDateValue(d.getDateValue());
if (fields.hasField(this.asIndexer(Rule._textValue)) && FieldType.isTextType(fieldType)) m.setTextValue(d.getTextValue()); if (fields.hasField(this.asIndexer(Rule._textValue)) && FieldType.isTextType(fieldType)) m.setTextValue(d.getTextValue());
if (fields.hasField(this.asIndexer(Rule._textListValue)) && FieldType.isTextListType(fieldType)) m.setTextListValue(d.getTextListValue()); if (fields.hasField(this.asIndexer(Rule._textListValue)) && FieldType.isTextListType(fieldType)) m.setTextListValue(d.getTextListValue());

View File

@ -360,8 +360,7 @@ public class VisibilityServiceImpl implements VisibilityService {
} }
else if (eu.eudat.commons.enums.FieldType.isReferenceType(fieldType)) { else if (eu.eudat.commons.enums.FieldType.isReferenceType(fieldType)) {
return rule.getTextListValue() != null && return rule.getTextListValue() != null &&
new HashSet<>(field.getTextListValue()).containsAll(rule.getTextListValue()) && new HashSet<>(field.getTextListValue()).containsAll(rule.getTextListValue());
new HashSet<>(rule.getTextListValue()).containsAll(field.getTextListValue());
} }
else if (eu.eudat.commons.enums.FieldType.isDateType(fieldType) && field.getDateValue() != null) return field.getDateValue().equals(rule.getDateValue()); else if (eu.eudat.commons.enums.FieldType.isDateType(fieldType) && field.getDateValue() != null) return field.getDateValue().equals(rule.getDateValue());
else if (eu.eudat.commons.enums.FieldType.isExternalIdentifierType(fieldType) && field.getExternalIdentifier() != null) { else if (eu.eudat.commons.enums.FieldType.isExternalIdentifierType(fieldType) && field.getExternalIdentifier() != null) {

View File

@ -2,14 +2,12 @@ transformer:
sources: sources:
- url: http://dev04.local.cite.gr:55330/file/docx - url: http://dev04.local.cite.gr:55330/file/docx
transformerId: docx-file-transformer transformerId: docx-file-transformer
codes: [ docx, pdf ]
issuer-url: ${IDP_ISSUER_URI_TOKEN} issuer-url: ${IDP_ISSUER_URI_TOKEN}
client-id: ${IDP_APIKEY_CLIENT_ID} client-id: ${IDP_APIKEY_CLIENT_ID}
client-secret: ${IDP_APIKEY_CLIENT_SECRET} client-secret: ${IDP_APIKEY_CLIENT_SECRET}
scope: ${IDP_APIKEY_SCOPE} scope: ${IDP_APIKEY_SCOPE}
- url: http://dev04.local.cite.gr:55330/file/rdajson - url: http://dev04.local.cite.gr:55330/file/rdajson
transformerId: rda-file-transformer transformerId: rda-file-transformer
codes: [ json ]
issuer-url: ${IDP_ISSUER_URI_TOKEN} issuer-url: ${IDP_ISSUER_URI_TOKEN}
client-id: ${IDP_APIKEY_CLIENT_ID} client-id: ${IDP_APIKEY_CLIENT_ID}
client-secret: ${IDP_APIKEY_CLIENT_SECRET} client-secret: ${IDP_APIKEY_CLIENT_SECRET}

View File

@ -5,6 +5,7 @@ import { DescriptionTemplateStatus } from "@app/core/common/enum/description-tem
import { UserDescriptionTemplateRole } from "@app/core/common/enum/user-description-template-role"; import { UserDescriptionTemplateRole } from "@app/core/common/enum/user-description-template-role";
import { BaseEntityPersist } from "@common/base/base-entity.model"; import { BaseEntityPersist } from "@common/base/base-entity.model";
import { Guid } from "@common/types/guid"; import { Guid } from "@common/types/guid";
import { ReferencePersist } from "../reference/reference";
export interface DescriptionTemplatePersist extends BaseEntityPersist { export interface DescriptionTemplatePersist extends BaseEntityPersist {
@ -82,7 +83,9 @@ export interface DescriptionTemplateFieldPersist {
export interface DescriptionTemplateRulePersist { export interface DescriptionTemplateRulePersist {
target: string; target: string;
value: string; textValue: string;
textListValue: string[];
dateValue: Date;
} }
export interface DescriptionTemplateMultiplicityPersist { export interface DescriptionTemplateMultiplicityPersist {

View File

@ -8,6 +8,7 @@ import { Guid } from "@common/types/guid";
import { DescriptionTemplateType } from "../description-template-type/description-template-type"; import { DescriptionTemplateType } from "../description-template-type/description-template-type";
import { ReferenceType } from "../reference-type/reference-type"; import { ReferenceType } from "../reference-type/reference-type";
import { User } from "../user/user"; import { User } from "../user/user";
import { Reference } from "../reference/reference";
export interface DescriptionTemplate extends BaseEntity { export interface DescriptionTemplate extends BaseEntity {
@ -78,7 +79,9 @@ export interface DescriptionTemplateField {
export interface DescriptionTemplateRule { export interface DescriptionTemplateRule {
target: string; target: string;
value: string; textValue: string;
textListValue: string[];
dateValue: Date;
} }
export interface DescriptionTemplateMultiplicity { export interface DescriptionTemplateMultiplicity {

View File

@ -67,7 +67,7 @@ export class DescriptionTemplatePreviewDialogComponent extends BaseComponent imp
buildForm() { buildForm() {
this.formGroup = this.editorModel.buildForm(null, true); this.formGroup = this.editorModel.buildForm(null, true);
this.visibilityRulesService.buildVisibilityRules(this.visibilityRulesService.getVisibilityRulesFromDescriptionTempalte(this.descriptionTemplate), this.formGroup); this.visibilityRulesService.setContext(this.descriptionTemplate.definition, this.formGroup.get('properties'));
} }
select(): void { select(): void {

View File

@ -881,7 +881,9 @@ export class DescriptionTemplateFieldEditorModel implements DescriptionTemplateF
export class DescriptionTemplateRuleEditorModel implements DescriptionTemplateRulePersist { export class DescriptionTemplateRuleEditorModel implements DescriptionTemplateRulePersist {
target: string; target: string;
value: string; textValue: string;
textListValue: string[];
dateValue: Date;
protected formBuilder: UntypedFormBuilder = new UntypedFormBuilder(); protected formBuilder: UntypedFormBuilder = new UntypedFormBuilder();
@ -889,10 +891,12 @@ export class DescriptionTemplateRuleEditorModel implements DescriptionTemplateRu
public validationErrorModel: ValidationErrorModel = new ValidationErrorModel() public validationErrorModel: ValidationErrorModel = new ValidationErrorModel()
) { } ) { }
fromModel(item: DescriptionTemplateRule): DescriptionTemplateRuleEditorModel { fromModel(item: DescriptionTemplateRule | DescriptionTemplateRuleEditorModel): DescriptionTemplateRuleEditorModel {
if (item) { if (item) {
this.target = item.target; this.target = item.target;
this.value = item.value; this.textValue = item.textValue;
this.textListValue = item.textListValue;
this.dateValue = item.dateValue;
} }
return this; return this;
} }
@ -912,7 +916,9 @@ export class DescriptionTemplateRuleEditorModel implements DescriptionTemplateRu
return this.formBuilder.group({ return this.formBuilder.group({
target: [{ value: this.target, disabled: disabled }, context.getValidation('target').validators], target: [{ value: this.target, disabled: disabled }, context.getValidation('target').validators],
value: [{ value: this.value, disabled: disabled }, context.getValidation('value').validators] textValue: [{ value: this.textValue, disabled: disabled }, context.getValidation('textValue').validators],
textListValue: [{ value: this.textListValue, disabled: disabled }, context.getValidation('textListValue').validators],
dateValue: [{ value: this.dateValue, disabled: disabled }, context.getValidation('dateValue').validators]
}); });
} }
@ -925,7 +931,9 @@ export class DescriptionTemplateRuleEditorModel implements DescriptionTemplateRu
const baseContext: ValidationContext = new ValidationContext(); const baseContext: ValidationContext = new ValidationContext();
const baseValidationArray: Validation[] = new Array<Validation>(); const baseValidationArray: Validation[] = new Array<Validation>();
baseValidationArray.push({ key: 'target', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}target`)] }); baseValidationArray.push({ key: 'target', validators: [BackendErrorValidator(validationErrorModel, `${rootPath}target`)] });
baseValidationArray.push({ key: 'value', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}value`)] }); baseValidationArray.push({ key: 'textValue', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}textValue`)] });
baseValidationArray.push({ key: 'textListValue', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}textListValue`)] });
baseValidationArray.push({ key: 'dateValue', validators: [Validators.required, BackendErrorValidator(validationErrorModel, `${rootPath}dateValue`)] });
baseContext.validation = baseValidationArray; baseContext.validation = baseValidationArray;
return baseContext; return baseContext;

View File

@ -3,6 +3,7 @@ import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { DescriptionTemplateType } from '@app/core/model/description-template-type/description-template-type'; import { DescriptionTemplateType } from '@app/core/model/description-template-type/description-template-type';
import { DescriptionTemplate, DescriptionTemplateBaseFieldData, DescriptionTemplateDefinition, DescriptionTemplateExternalDatasetData, DescriptionTemplateField, DescriptionTemplateFieldSet, DescriptionTemplateLabelAndMultiplicityData, DescriptionTemplateMultiplicity, DescriptionTemplatePage, DescriptionTemplateReferenceTypeData, DescriptionTemplateRule, DescriptionTemplateSection, DescriptionTemplateSelectData, DescriptionTemplateSelectOption, DescriptionTemplateUploadData, DescriptionTemplateUploadOption, UserDescriptionTemplate } from '@app/core/model/description-template/description-template'; import { DescriptionTemplate, DescriptionTemplateBaseFieldData, DescriptionTemplateDefinition, DescriptionTemplateExternalDatasetData, DescriptionTemplateField, DescriptionTemplateFieldSet, DescriptionTemplateLabelAndMultiplicityData, DescriptionTemplateMultiplicity, DescriptionTemplatePage, DescriptionTemplateReferenceTypeData, DescriptionTemplateRule, DescriptionTemplateSection, DescriptionTemplateSelectData, DescriptionTemplateSelectOption, DescriptionTemplateUploadData, DescriptionTemplateUploadOption, UserDescriptionTemplate } from '@app/core/model/description-template/description-template';
import { ReferenceType } from '@app/core/model/reference-type/reference-type'; import { ReferenceType } from '@app/core/model/reference-type/reference-type';
import { Reference } from '@app/core/model/reference/reference';
import { User } from '@app/core/model/user/user'; import { User } from '@app/core/model/user/user';
import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service'; import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service';
import { BreadcrumbService } from '@app/ui/misc/breadcrumb/breadcrumb.service'; import { BreadcrumbService } from '@app/ui/misc/breadcrumb/breadcrumb.service';
@ -66,7 +67,9 @@ export class DescriptionTemplateEditorResolver extends BaseEditorResolver {
[nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.validations)].join('.'), [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.validations)].join('.'),
[nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.target)].join('.'), [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.target)].join('.'),
[nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.value)].join('.'), [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.textValue)].join('.'),
[nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.textListValue)].join('.'),
[nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.dateValue)].join('.'),
[nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateBaseFieldData>(x => x.label)].join('.'), [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateBaseFieldData>(x => x.label)].join('.'),
[nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateBaseFieldData>(x => x.fieldType)].join('.'), [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateBaseFieldData>(x => x.fieldType)].join('.'),
[nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateSelectData>(x => x.multipleSelect)].join('.'), [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateSelectData>(x => x.multipleSelect)].join('.'),

View File

@ -570,7 +570,7 @@ export class DescriptionEditorComponent extends BaseEditor<DescriptionEditorMode
permissionPerSection => { permissionPerSection => {
const canedit = permissionPerSection && permissionPerSection[this.item.dmpDescriptionTemplate.sectionId.toString()] && permissionPerSection[this.item.dmpDescriptionTemplate.sectionId.toString()].some(x => x === AppPermission.EditDescription); const canedit = permissionPerSection && permissionPerSection[this.item.dmpDescriptionTemplate.sectionId.toString()] && permissionPerSection[this.item.dmpDescriptionTemplate.sectionId.toString()].some(x => x === AppPermission.EditDescription);
this.formGroup = this.editorModel.buildForm(null, this.isDeleted || !canedit); this.formGroup = this.editorModel.buildForm(null, this.isDeleted || !canedit);
//this.visibilityRulesService.buildVisibilityRules(this.visibilityRulesService.getVisibilityRulesFromDescriptionTempalte(this.item.descriptionTemplate), this.formGroup); if (this.item.descriptionTemplate?.definition) this.visibilityRulesService.setContext(this.item.descriptionTemplate.definition, this.formGroup.get('properties'));
// this.selectedSystemFields = this.selectedSystemFieldDisabled(); // this.selectedSystemFields = this.selectedSystemFieldDisabled();
this.descriptionEditorService.setValidationErrorModel(this.editorModel.validationErrorModel); this.descriptionEditorService.setValidationErrorModel(this.editorModel.validationErrorModel);
@ -621,7 +621,7 @@ export class DescriptionEditorComponent extends BaseEditor<DescriptionEditorMode
return; return;
} }
// this.persistEntity(); this.persistEntity();
} }
public delete() { public delete() {
@ -795,6 +795,7 @@ export class DescriptionEditorComponent extends BaseEditor<DescriptionEditorMode
this.descriptionTemplateService.getSingle(descriptionTemplateId, DescriptionEditorResolver.descriptionTemplateLookupFields()).pipe(takeUntil(this._destroyed)).subscribe(descriptionTemplate => { this.descriptionTemplateService.getSingle(descriptionTemplateId, DescriptionEditorResolver.descriptionTemplateLookupFields()).pipe(takeUntil(this._destroyed)).subscribe(descriptionTemplate => {
this.editorModel.properties = new DescriptionPropertyDefinitionEditorModel(this.editorModel.validationErrorModel).fromModel(null, descriptionTemplate, null); this.editorModel.properties = new DescriptionPropertyDefinitionEditorModel(this.editorModel.validationErrorModel).fromModel(null, descriptionTemplate, null);
this.formGroup.setControl('properties', this.editorModel.buildProperties()); this.formGroup.setControl('properties', this.editorModel.buildProperties());
this.item.descriptionTemplate = descriptionTemplate; this.item.descriptionTemplate = descriptionTemplate;
@ -802,6 +803,8 @@ export class DescriptionEditorComponent extends BaseEditor<DescriptionEditorMode
const sectionId = this.item.dmpDescriptionTemplate.sectionId; const sectionId = this.item.dmpDescriptionTemplate.sectionId;
this.item.dmpDescriptionTemplate = this.item.dmp.dmpDescriptionTemplates.find(x => x.sectionId == sectionId && x.descriptionTemplateGroupId == descriptionTemplate.groupId); this.item.dmpDescriptionTemplate = this.item.dmp.dmpDescriptionTemplates.find(x => x.sectionId == sectionId && x.descriptionTemplateGroupId == descriptionTemplate.groupId);
this.formGroup.get('dmpDescriptionTemplateId').setValue(this.item.dmpDescriptionTemplate.id); this.formGroup.get('dmpDescriptionTemplateId').setValue(this.item.dmpDescriptionTemplate.id);
if (descriptionTemplate.definition) this.visibilityRulesService.setContext(this.item.descriptionTemplate.definition, this.formGroup.get('properties'));
}); });
// this.formGroup.removeControl('descriptionProfileDefinition'); // this.formGroup.removeControl('descriptionProfileDefinition');
// this.getDefinition(profiledId); // this.getDefinition(profiledId);

View File

@ -120,7 +120,9 @@ export class DescriptionEditorResolver extends BaseEditorResolver {
(prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.defaultValue)].join('.'), (prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.defaultValue)].join('.'),
(prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.validations)].join('.'), (prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.validations)].join('.'),
(prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.target)].join('.'), (prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.target)].join('.'),
(prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.value)].join('.'), (prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.textValue)].join('.'),
(prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.textListValue)].join('.'),
(prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.visibilityRules), nameof<DescriptionTemplateRule>(x => x.dateValue)].join('.'),
(prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateBaseFieldData>(x => x.label)].join('.'), (prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateBaseFieldData>(x => x.label)].join('.'),
(prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateBaseFieldData>(x => x.fieldType)].join('.'), (prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateBaseFieldData>(x => x.fieldType)].join('.'),
(prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateSelectData>(x => x.options), nameof<DescriptionTemplateSelectOption>(x => x.label)].join('.'), (prefix ? prefix + '.' : '') + [nameof<DescriptionTemplate>(x => x.definition), nameof<DescriptionTemplateDefinition>(x => x.pages), nameof<DescriptionTemplatePage>(x => x.sections), nameof<DescriptionTemplateSection>(x => x.fieldSets), nameof<DescriptionTemplateFieldSet>(x => x.fields), nameof<DescriptionTemplateField>(x => x.data), nameof<DescriptionTemplateSelectData>(x => x.options), nameof<DescriptionTemplateSelectOption>(x => x.label)].join('.'),

View File

@ -13,10 +13,10 @@
</div> </div>
<div *ngIf="!fieldSet?.multiplicity?.tableView" class="col-12"> <div *ngIf="!fieldSet?.multiplicity?.tableView" class="col-12">
<div class="row" *ngFor="let fieldSetItemPropertiesControl of propertiesFormGroup?.get('items')?.controls"> <div class="row" *ngFor="let fieldSetItemPropertiesControl of propertiesFormGroup?.get('items')?.controls">
<div class="col"> <div class="col" *ngIf="visibilityRulesService.isVisibleMap[fieldSet.id + '_' + fieldSetItemPropertiesControl.get('ordinal').value]">
<div class="row"> <div class="row">
<div *ngFor="let field of fieldSet.fields; let i = index;" class="col-12 compositeField"> <div *ngFor="let field of fieldSet.fields; let i = index;" class="col-12 compositeField">
<ng-container> <ng-container *ngIf="visibilityRulesService.isVisibleMap[field.id + '_' + fieldSetItemPropertiesControl.get('ordinal').value]">
<div class="row"> <div class="row">
<h5 *ngIf="placeholderTitle" class="col-auto font-weight-bold">{{field.label}}</h5> <h5 *ngIf="placeholderTitle" class="col-auto font-weight-bold">{{field.label}}</h5>
</div> </div>
@ -47,8 +47,13 @@
<th *ngFor="let field of fieldSet.fields; let i = index;" class="text-wrap">{{field.data?.label}}</th> <th *ngFor="let field of fieldSet.fields; let i = index;" class="text-wrap">{{field.data?.label}}</th>
<th class="actions"></th> <th class="actions"></th>
</tr> </tr>
<tr *ngFor="let fieldSetItemPropertiesControl of propertiesFormGroup?.get('items')?.controls; let j = index"> <ng-container *ngFor="let fieldSetItemPropertiesControl of propertiesFormGroup?.get('items')?.controls; let j = index">
<td *ngFor="let field of fieldSet.fields;" class="text-wrap">{{fieldSetItemPropertiesControl.get('fields').get(field.id).get('value').getRawValue()}}</td> <tr *ngIf="visibilityRulesService.isVisibleMap[fieldSet.id + '_' + fieldSetItemPropertiesControl.get('ordinal').value]">
<td *ngFor="let field of fieldSet.fields;" class="text-wrap">
<ng-container *ngIf="visibilityRulesService.isVisibleMap[field.id + '_' + fieldSetItemPropertiesControl.get('ordinal').value]">
{{fieldSetItemPropertiesControl.get('fields').get(field.id).get('value').getRawValue()}}
</ng-container>
</td>
<td class="actions"> <td class="actions">
<button mat-icon-button type="button" class="deleteBtn btn-sm" (click)="editTableMultiplicityFieldInDialog(j)" [disabled]="fieldSetItemPropertiesControl.disabled"> <button mat-icon-button type="button" class="deleteBtn btn-sm" (click)="editTableMultiplicityFieldInDialog(j)" [disabled]="fieldSetItemPropertiesControl.disabled">
<mat-icon>edit</mat-icon> <mat-icon>edit</mat-icon>
@ -58,6 +63,8 @@
</button> </button>
</td> </td>
</tr> </tr>
</ng-container>
<tr *ngIf="(fieldSet.multiplicity.max - 1) > propertiesFormGroup?.get('items')?.controls.length"> <tr *ngIf="(fieldSet.multiplicity.max - 1) > propertiesFormGroup?.get('items')?.controls.length">
<td [colSpan]="fieldSet.fields.length + 1" class="text-center"> <td [colSpan]="fieldSet.fields.length + 1" class="text-center">
<span class="d-inline-flex align-items-center" [ngClass]="propertiesFormGroup.disabled ? '' : 'pointer'" (click)="addMultiplicityField()"> <span class="d-inline-flex align-items-center" [ngClass]="propertiesFormGroup.disabled ? '' : 'pointer'" (click)="addMultiplicityField()">

View File

@ -17,7 +17,7 @@ import { VisibilityRulesService } from '@app/ui/description/editor/description-f
import { BaseComponent } from '@common/base/base.component'; import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators'; import { distinctUntilChanged, map, takeUntil } from 'rxjs/operators';
@Component({ @Component({
selector: 'app-description-form-field', selector: 'app-description-form-field',
@ -204,21 +204,14 @@ export class DescriptionFormFieldComponent extends BaseComponent implements OnIn
// this.form = this.visibilityRulesService.getFormGroup(this.field.id); // this.form = this.visibilityRulesService.getFormGroup(this.field.id);
//TODO: refactor //TODO: refactor
// this.propertiesFormGroup.get(this.field.id).get('value').valueChanges this.propertiesFormGroup.get(this.field.id).valueChanges
// .pipe( .pipe(
// takeUntil(this._destroyed), takeUntil(this._destroyed),
// distinctUntilChanged() distinctUntilChanged()
// ) )
// .subscribe(item => { .subscribe(item => {
// // if (this.field?.data?.fieldType === DescriptionTemplateFieldType.ComboBox && this.form.get('data').value.type === DatasetProfileComboBoxType.Select && this.form.get('data').value.multipleSelect) { this.visibilityRulesService.updateVisibilityForSource(this.field?.id);
// // item.forEach(element => { });
// // this.visibilityRulesService.updateValueAndVisibility(this.field?.id, element);
// // });
// // } else {
// this.visibilityRulesService.updateValueAndVisibility(this.field?.id, item);
// // }
// });
} }
// _optionRemove(event) { // _optionRemove(event) {

View File

@ -11,7 +11,7 @@
<h6 class='panel-desc' *ngIf="section.description" [innerHTML]="section.description"></h6> <h6 class='panel-desc' *ngIf="section.description" [innerHTML]="section.description"></h6>
</mat-panel-description> </mat-panel-description>
<div *ngFor="let fieldSet of section.fieldSets; let i = index;" class="col-12" [id]="fieldSet.id" (click)="onAskedToScroll($event, fieldSet.id)"> <div *ngFor="let fieldSet of section.fieldSets; let i = index;" class="col-12" [id]="fieldSet.id" (click)="onAskedToScroll($event, fieldSet.id)">
<div class="row"> <div class="row" *ngIf="visibilityRulesService.isVisibleMap[fieldSet.id] ?? true">
<div class="col-12"> <div class="col-12">
<div class="row"> <div class="row">
<app-description-form-field-set class="align-self-center col" <app-description-form-field-set class="align-self-center col"
@ -29,7 +29,7 @@
<div *ngIf="section?.sections?.length > 0" class="col-12"> <div *ngIf="section?.sections?.length > 0" class="col-12">
<ng-container *ngFor="let innerSection of section.sections; let j = index;"> <ng-container *ngFor="let innerSection of section.sections; let j = index;">
<div class="row"> <div class="row" *ngIf="visibilityRulesService.isVisibleMap[innerSection.id]">
<app-description-form-section class="col-12" [section]="innerSection" [path]="path+'.'+(j+1)" [pathName]="pathName+'.sections.'+j" (askedToScroll)="onAskedToScroll($event)" [propertiesFormGroup]="propertiesFormGroup" [descriptionId]="descriptionId" [visibilityRulesService]="visibilityRulesService" [linkToScroll]="subsectionLinkToScroll"></app-description-form-section> <app-description-form-section class="col-12" [section]="innerSection" [path]="path+'.'+(j+1)" [pathName]="pathName+'.sections.'+j" (askedToScroll)="onAskedToScroll($event)" [propertiesFormGroup]="propertiesFormGroup" [descriptionId]="descriptionId" [visibilityRulesService]="visibilityRulesService" [linkToScroll]="subsectionLinkToScroll"></app-description-form-section>
</div> </div>
</ng-container> </ng-container>

View File

@ -14,7 +14,7 @@
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<ng-container *ngFor="let section of page.sections; let i = index;"> <ng-container *ngFor="let section of page.sections; let i = index;">
<div class="row"> <div class="row" *ngIf="visibilityRulesService.isVisibleMap[section.id]">
<app-description-form-section class="col-12" [section]="section" [path]="(z+1)+'.'+(i+1)" [pathName]="'pages.'+z+'.sections.'+i" [propertiesFormGroup]="propertiesFormGroup" [descriptionId]="descriptionId" [visibilityRulesService]="visibilityRulesService" (askedToScroll)="onAskedToScroll(expansionPanel, $event)" [linkToScroll]="linkToScroll" [validationErrorModel]="validationErrorModel"></app-description-form-section> <app-description-form-section class="col-12" [section]="section" [path]="(z+1)+'.'+(i+1)" [pathName]="'pages.'+z+'.sections.'+i" [propertiesFormGroup]="propertiesFormGroup" [descriptionId]="descriptionId" [visibilityRulesService]="visibilityRulesService" (askedToScroll)="onAskedToScroll(expansionPanel, $event)" [linkToScroll]="linkToScroll" [validationErrorModel]="validationErrorModel"></app-description-form-section>
</div> </div>
</ng-container> </ng-container>

View File

@ -4,10 +4,10 @@ import { MatExpansionPanel } from '@angular/material/expansion';
import { DescriptionTemplate, DescriptionTemplateSection } from '@app/core/model/description-template/description-template'; import { DescriptionTemplate, DescriptionTemplateSection } from '@app/core/model/description-template/description-template';
import { BaseComponent } from '@common/base/base.component'; import { BaseComponent } from '@common/base/base.component';
import { LinkToScroll } from '../table-of-contents/table-of-contents.component'; import { LinkToScroll } from '../table-of-contents/table-of-contents.component';
import { Rule } from './visibility-rules/models/rule';
import { VisibilityRulesService } from './visibility-rules/visibility-rules.service'; import { VisibilityRulesService } from './visibility-rules/visibility-rules.service';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model'; import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { Guid } from '@common/types/guid'; import { Guid } from '@common/types/guid';
import { RuleWithTarget } from './visibility-rules/models/rule';
@Component({ @Component({
selector: 'app-description-form', selector: 'app-description-form',
@ -24,7 +24,6 @@ export class DescriptionFormComponent extends BaseComponent implements OnInit, A
// @ViewChild('stepper', { static: false }) stepper: MatStepper; // @ViewChild('stepper', { static: false }) stepper: MatStepper;
@Input() path: string; @Input() path: string;
@Input() visibilityRules: Rule[] = [];
@Input() datasetDescription: String; @Input() datasetDescription: String;
@Input() linkToScroll: LinkToScroll; @Input() linkToScroll: LinkToScroll;
@Output() formChanged: EventEmitter<any> = new EventEmitter(); @Output() formChanged: EventEmitter<any> = new EventEmitter();
@ -34,7 +33,6 @@ export class DescriptionFormComponent extends BaseComponent implements OnInit, A
@Input() TOCENTRY_ID_PREFIX = ""; @Input() TOCENTRY_ID_PREFIX = "";
@Output() visibilityRulesInstance = new EventEmitter<VisibilityRulesService>();
@Input() validationErrorModel: ValidationErrorModel; @Input() validationErrorModel: ValidationErrorModel;
// public hiddenEntriesIds: string[] = []; // public hiddenEntriesIds: string[] = [];

View File

@ -1,5 +1,19 @@
export class Rule { import { DescriptionTemplateField, DescriptionTemplateRule } from "@app/core/model/description-template/description-template";
sourceField: string;
targetField: string; export class RuleWithTarget {
requiredValue: any; source: string;
target: string;
textValue: string;
textListValue: string[];
dateValue: Date;
field: DescriptionTemplateField;
public constructor(source: string, rule: DescriptionTemplateRule , fieldEntity: DescriptionTemplateField) {
this.target = rule.target;
this.source = source;
this.field = fieldEntity;
this.textValue = rule.textValue;
this.textListValue = rule.textListValue;
this.dateValue = rule.dateValue;
}
} }

View File

@ -1,4 +0,0 @@
export class VisibilityRuleSource {
public sourceControlId: string;
public sourceControlValue: string;
}

View File

@ -1,6 +0,0 @@
import { VisibilityRuleSource } from "./visibility-rule-source";
export class VisibilityRule {
public targetControlId: string;
public sourceVisibilityRules: Array<VisibilityRuleSource>;
}

View File

@ -1,47 +0,0 @@
import { Rule } from "./rule";
import { VisibilityRule } from "./visibility-rule";
export class VisibilityRulesContext {
public rules: Array<VisibilityRule> = new Array();
constructor() { }
public getRulesFromKey(id: string): VisibilityRule {
for (let i = 0; i < this.rules.length; i++) {
if (id === this.rules[i].targetControlId) { return this.rules[i]; }
}
return null;
}
public buildVisibilityRuleContext(items: Array<Rule>) {
items.forEach(item => {
this.addToVisibilityRulesContext(item);
});
}
public addToVisibilityRulesContext(item: Rule): void {
for (let i = 0; i < this.rules.length; i++) {
if (this.rules[i].targetControlId === item.targetField) {
const newRule = { sourceControlId: item.sourceField, sourceControlValue: item.requiredValue };
const ruleExists = this.rules[i].sourceVisibilityRules.find(x => {
return Object.keys(x).reduce((exact, key) => {
if (!exact) return false;
return x[key] === newRule[key];
}, true);
})
if (!ruleExists) {
this.rules[i].sourceVisibilityRules.push(newRule);
}
return;
}
}
const newVisibilityRuleArray = [({ sourceControlId: item.sourceField, sourceControlValue: item.requiredValue })];
this.rules.push({ targetControlId: item.targetField, sourceVisibilityRules: newVisibilityRuleArray });
return;
}
}

View File

@ -0,0 +1,456 @@
// import { ApplicationRef, Injectable, NgZone } from '@angular/core';
// import { AbstractControl, UntypedFormArray, UntypedFormGroup } from '@angular/forms';
// import { isNumeric } from '@app/utilities/enhancers/utils';
// import { Observable, Subject } from 'rxjs';
// import { VisibilityRule } from './models/visibility-rule';
// import { VisibilityRuleSource } from './models/visibility-rule-source';
// import { VisibilityRulesContext } from './models/visibility-rules-context';
// import { DescriptionTemplate, DescriptionTemplatePage, DescriptionTemplateSection } from '@app/core/model/description-template/description-template';
// import { Rule } from './models/rule';
// @Injectable()
// export class VisibilityRulesService {
// private readonly VISIBILITY_RULE_LOGIC: 'OR' | 'AND' = 'OR';
// private readonly DEFAULTVISIBILITY = false;
// private visibilityRuleContext: VisibilityRulesContext;
// private form: AbstractControl;
// public isVisibleMap: { [key: string]: boolean } = {};
// private elementVisibilityMapSubject = new Subject<{ [key: string]: boolean }>();
// private elementComputationalMap = new Map<String, Map<String, boolean>>(); /// keep saved the values of each form control validity value
// private _changeMade$ = new Subject<void>();
// // get isVisibleMap(): MapWithDefault {
// // // console.log('isVisibleMap');
// // return this.elementVisibilityMap;
// // }; /// keep saved the values of each form control validity value
// constructor(
// public applicationReference: ApplicationRef,
// public ngZone: NgZone
// ) {
// }
// getElementVisibilityMapObservable(): Observable<{ [key: string]: boolean }> {
// // this.isVisibleMap
// // console.log('getElementVisibilityMapObservable: ');
// return this.elementVisibilityMapSubject.asObservable();
// }
// public checkElementVisibility(id: string): boolean {
// //console.log('checkElementVisibility: ' + id);
// return true;
// // if (this.visibilityRuleContext.rules.filter(item => item.targetControlId === id).length === 0) { return true; }
// // console.log(this.elementVisibilityMap.has(id) ? this.elementVisibilityMap.get(id) : false);
// // return this.elementVisibilityMap.has(id) ? this.elementVisibilityMap.get(id) : false;
// }
// public buildVisibilityRules(item: Array<Rule>, form: AbstractControl) {
// this.visibilityRuleContext = new VisibilityRulesContext();
// this.visibilityRuleContext.buildVisibilityRuleContext(item || []);
// this.form = form;
// this.resetVisibilityRules();
// }
// public updateValueAndVisibility(id: string, value: any) {
// //console.log('updateValueAndVisibility: ' + id + ' value: ' + value);
// const visibilityRules = this.visibilityRuleContext.rules.filter(item => item.sourceVisibilityRules.filter(source => source.sourceControlId === id).length > 0);
// if (visibilityRules.length > 0) {
// visibilityRules.forEach(item => this.evaluateVisibility(item, value, id));
// this.elementVisibilityMapSubject.next(this.isVisibleMap);
// }
// }
// private evaluateVisibility(visibilityRule: VisibilityRule, value: any, sourceId: string) {// source controlId is the same
// //console.log('evaluateVisibility: ' + visibilityRule + ' value: ' + value + ' sourceId: ' + sourceId);
// const targetId = visibilityRule.targetControlId;
// const visibilityMap = this.elementComputationalMap.get(targetId) ? this.elementComputationalMap.get(targetId) : new Map<String, boolean>();
// if (value instanceof Array) {
// const parsedSourceControlValues = visibilityRule.sourceVisibilityRules.map(e => this.parseValue(e.sourceControlValue));
// const parsedValues = value.map(e => this.parseValue(e));
// const isVisible = parsedValues.map(v => parsedSourceControlValues.includes(v)).reduce((acc, current) => acc || current, false);
// // if(isVisible){
// // this._emitChangesIfNeeded(visibilityRule.targetControlId, true);
// // this.elementVisibilityMap.set(visibilityRule.targetControlId, true);
// // return;
// // }
// visibilityMap.set(sourceId, isVisible);
// } else {
// const visibilityDependencySource = visibilityRule.sourceVisibilityRules.filter(x => x.sourceControlId === sourceId);
// const shouldBeVisible = visibilityDependencySource.reduce((isVisible, x) => {
// const shouldBeHidden = value !== null && (this.parseValue(value) !== this.parseValue(x.sourceControlValue));
// return this.VISIBILITY_RULE_LOGIC === 'OR' ? (isVisible || !shouldBeHidden) : (isVisible && !shouldBeHidden);
// // if(value !== null && )
// }, this.VISIBILITY_RULE_LOGIC === 'AND');
// visibilityMap.set(sourceId, shouldBeVisible);
// }
// this.elementComputationalMap.set(targetId, visibilityMap);// unnessecary
// const isVisible = this._computeVisibility(targetId);
// this._emitChangesIfNeeded(targetId, isVisible);
// const previousVisibility = this.isVisibleMap[targetId];
// this.isVisibleMap[targetId] = isVisible;
// if (!isVisible && previousVisibility !== isVisible) {
// this.resetControlWithId(this.form, targetId);
// }
// // for (let i = 0; i < visibilityRule.sourceVisibilityRules.length; i++) {
// // if (value != null && (this.parseValue(value) !== this.parseValue(visibilityRule.sourceVisibilityRules[i].sourceControlValue))) {
// // this._emitChangesIfNeeded(visibilityRule.targetControlId, false);
// // this.elementVisibilityMap.set(visibilityRule.targetControlId, false);
// // this.resetControlWithId(this.form, visibilityRule.targetControlId);
// // //this.updateValueAndVisibility(visibilityRule.targetControlId, null);
// // // this.clearValues(targetPathKey);
// // return;
// // }
// // }
// // this._emitChangesIfNeeded(visibilityRule.targetControlId, true);
// // this.elementVisibilityMap.set(visibilityRule.targetControlId, true);
// // this.updateValueAndVisibility(visibilityRule.targetControlId, null);
// }
// private _computeVisibility(targetId: string): boolean {
// //console.log('_computeVisibility: ' + targetId);
// const visibilityMap = this.elementComputationalMap.get(targetId);
// const values = visibilityMap.values();
// let currentVal = values.next();
// let visibilityValues: boolean[] = [];
// while (!currentVal.done) {
// visibilityValues.push(currentVal.value);
// currentVal = values.next();
// }
// if (visibilityValues.length) {
// return visibilityValues.reduce((r, c) => {
// if (this.VISIBILITY_RULE_LOGIC === 'OR') {
// return r || c;
// } else {
// return r && c;
// }
// }, visibilityValues[0]);
// }
// return this.DEFAULTVISIBILITY;
// }
// private resetVisibilityRules() {
// //console.log('resetVisibilityRules: ');
// this.isVisibleMap = {};
// this.elementComputationalMap.clear();
// this.elementComputationalMap = new Map<String, Map<String, boolean>>();
// this._populateComputationMap(); /// !IMPORTANT FOR THE AND LOGIC
// this._changeMade$.next();
// }
// private _populateComputationMap(): void {
// //console.log('_populateComputationMap: ');
// // this.visibilityRuleContext.rules.forEach(rule => {
// // const targetId = rule.targetControlId;
// // const visibilityMap = this.elementComputationalMap.get(targetId) ? this.elementComputationalMap.get(targetId) : new Map<String, boolean>();
// // rule.sourceVisibilityRules.forEach(vr => {
// // visibilityMap.set(vr.sourceControlId, this.DEFAULTVISIBILITY);
// // });
// // this.elementComputationalMap.set(targetId, visibilityMap);
// // });
// }
// parseValue(value: any) {
// if (typeof value === 'string') {
// if (isNumeric(value)) { return value; }
// else if (value === 'true') {
// return true;
// }
// else if (value === 'false') {
// return false;
// }
// else { return this.translate(value); }
// } else { return value; }
// }
// search(path, obj, target) {
// for (const k in obj) {
// if (obj.hasOwnProperty(k)) {
// if (obj[k] === target) {
// return path + '.' + k;
// } else if (typeof obj[k] === 'object') {
// const result = this.search(path + '.' + k, obj[k], target);
// if (result) {
// return result;
// }
// }
// }
// }
// return false;
// }
// scanIfChildsOfCompositeFieldHasVisibleItems(compositeFieldParent: UntypedFormGroup): boolean {
// // console.log('scanIfChildsOfCompositeFieldHasVisibleItems: ' + compositeFieldParent);
// //TODO: implement this
// return true;
// // let isVisible = false;
// // (<UntypedFormArray>(compositeFieldParent.get('fields'))).controls.forEach(element => {
// // if (this.checkElementVisibility(element.get('id').value)) {
// // isVisible = true;
// // }
// // });
// // return isVisible;
// }
// private translate(item: any) {
// try {
// return JSON.parse(item).value;
// } catch (error) {
// return item;
// }
// }
// private resetControlWithId(formControl: AbstractControl, id: string) {
// //'resetControlWithId: ' + id);
// //TODO: implement this
// // if (formControl instanceof UntypedFormGroup) {
// // if ((formControl as UntypedFormGroup).contains('id') && (formControl as UntypedFormGroup).contains('value') && (formControl as UntypedFormGroup).get('id').value === id) {
// // this.resetFieldFormGroup(formControl);
// // } if ((formControl as UntypedFormGroup).contains('id') && (formControl as UntypedFormGroup).contains('fields') && (formControl as UntypedFormGroup).get('id').value === id) {
// // this.resetCompositeFieldFormGroup(formControl);
// // } else {
// // Object.keys(formControl.controls).forEach(item => {
// // const control = formControl.get(item);
// // this.resetControlWithId(control, id);
// // });
// // }
// // } else if (formControl instanceof UntypedFormArray) {
// // formControl.controls.forEach(item => {
// // this.resetControlWithId(item, id);
// // });
// // }
// }
// private resetFieldFormGroup(formGroup: UntypedFormGroup) {
// //console.log('resetFieldFormGroup: ' + formGroup);
// //TODO: implement this
// // const renderStyle = formGroup.getRawValue().viewStyle.renderStyle;
// // if (renderStyle === DatasetProfileFieldViewStyle.Validation || renderStyle === DatasetProfileFieldViewStyle.DatasetIdentifier) {
// // formGroup.get('value').setValue({ identifier: '', type: '' });
// // } else {
// // formGroup.get('value').setValue(formGroup.get('defaultValue').value ? this.parseValue(formGroup.get('defaultValue').value.value) : undefined);
// // }
// }
// private resetCompositeFieldFormGroup(formGroup: UntypedFormGroup) {
// //console.log('resetCompositeFieldFormGroup: ' + formGroup);
// //TODO: implement this
// // (formGroup.get('fields') as UntypedFormArray).controls.forEach((element: UntypedFormGroup) => {
// // this.resetFieldFormGroup(element);
// // });
// // (formGroup.get('multiplicityItems') as UntypedFormArray).controls.splice(0);
// }
// private _emitChangesIfNeeded(id: string, valueToBeSet: boolean) {
// if (this.isVisibleMap[id]) {
// if (this.isVisibleMap[id] != valueToBeSet) {
// this._changeMade$.next();
// }
// } else {
// this._changeMade$.next();
// }
// }
// public get visibilityChange() {
// return this._changeMade$.asObservable();
// }
// public getVisibilityDependency(targetId: string): VisibilityRuleSource[] | null {
// //console.log('getVisibilityDependency: ' + targetId);
// return this.visibilityRuleContext.rules.reduce((hasDependency, rule) => {
// if (hasDependency) return hasDependency;
// if (rule.targetControlId === targetId) {
// return rule.sourceVisibilityRules;
// }
// return null;
// }, null) as VisibilityRuleSource[];
// }
// public getVisibilityTargets(sourceId: string): string[] {
// console.log('getVisibilityTargets: ' + sourceId);
// return this.visibilityRuleContext.rules.filter(x => {
// const result = x.sourceVisibilityRules.filter(y => y.sourceControlId === sourceId);
// return result.length;
// }).map(x => x.targetControlId);
// }
// // public appendVisibilityRule(rule: VisibilityRule): void{
// // const existingTargetRule = this.visibilityRuleContext.rules.find( r => r.targetControlId === rule.targetControlId);
// // if(existingTargetRule){
// // rule.sourceVisibilityRules.forEach(svr =>{
// // existingTargetRule.sourceVisibilityRules.push(svr);
// // });
// // }else{
// // this.visibilityRuleContext.rules.push(rule);
// // }
// // }
// //removes rule that has the specific id either as a source either as a target
// public removeAllIdReferences(id: string): void {
// //console.log('removeAllIdReferences: ' + id);
// // * Remove from visibility rues and visibility rules context
// //remove as a target
// const temp = this.visibilityRuleContext.rules.map((x, i) => (x.targetControlId === id) ? i : null);
// const indexes = temp.filter(x => x !== null);
// indexes.reverse().forEach(index => this.visibilityRuleContext.rules.splice(index, 1));
// this.isVisibleMap[id] = undefined;
// //remove as a source
// const tbd = this.visibilityRuleContext.rules.reduce((to_be_deleted, rule, ruleIdx) => {
// const idxs = rule.sourceVisibilityRules.map((x, i) => (x.sourceControlId === id) ? i : null).filter(x => x !== null);
// idxs.reverse().forEach(index => rule.sourceVisibilityRules.splice(index, 1));
// if (!rule.sourceVisibilityRules.length) {
// to_be_deleted.push(ruleIdx);
// }
// return to_be_deleted
// }, []);
// //clean up empty
// tbd.reverse().forEach(index => {
// this.visibilityRuleContext.rules.splice(index, 1);
// });
// // * Remove from computational map
// // as a target
// if (this.elementComputationalMap.get(id)) {
// this.elementComputationalMap.delete(id);
// }
// // as a source
// const keyIterator = this.elementComputationalMap.keys();
// let currentKey = keyIterator.next();
// while (!currentKey.done) {
// const currentVals = this.elementComputationalMap.get(currentKey.value);
// currentVals.delete(id);
// currentKey = keyIterator.next();
// }
// }
// public addNewRule(rule: Rule, currentVisibility = this.DEFAULTVISIBILITY): void {
// //console.log('addNewRule: ' + rule + ' currentVisibility: ' + currentVisibility);
// const targetId = rule.targetField;
// const sourceId = rule.sourceField;
// this.visibilityRuleContext.addToVisibilityRulesContext(rule);
// let visibilityMap = this.elementComputationalMap.get(targetId);
// if (!visibilityMap) {
// visibilityMap = new Map<String, boolean>();
// this.elementComputationalMap.set(targetId, visibilityMap);
// }
// visibilityMap.set(sourceId, currentVisibility);
// const isVisible = this._computeVisibility(targetId);
// this._emitChangesIfNeeded(targetId, isVisible);
// this.isVisibleMap[targetId] = isVisible;
// this.elementVisibilityMapSubject.next(this.isVisibleMap);
// }
// /**
// * Check what sourceId hides or shows the target field
// * return true if no rule found
// */
// public checkTargetVisibilityProvidedBySource(sourceId: string, targetId: string): boolean {
// //console.log('checkTargetVisibilityProvidedBySource: ' + sourceId + ' targetId: ' + targetId);
// const computationalMap = this.elementComputationalMap.get(targetId);
// if (computationalMap) {
// return !!computationalMap.get(sourceId);
// }
// return true;
// }
// public getVisibilityRulesFromDescriptionTempalte(descriptionTemplate: DescriptionTemplate): Rule[] {
// //console.log('getVisibilityRulesFromDescriptionTempalte: ' + descriptionTemplate);
// const result: Rule[] = this.getVisibilityRulesFromDescriptionTempalteSections(descriptionTemplate?.definition?.pages);
// return result;
// }
// public getVisibilityRulesFromDescriptionTempalteSections(pages: DescriptionTemplatePage[]): Rule[] {
// //console.log('getVisibilityRulesFromDescriptionTempalteSections: ' + sections);
// const result: Rule[] = [];
// pages.forEach(page => {
// page?.sections?.forEach(section => {
// if (section.sections != null) { result.push(...this.getVisibilityRulesFromDescriptionTempalteSections(section.sections)); };
// section?.fieldSets?.forEach(fieldSet => {
// fieldSet?.fields?.forEach(field => {
// field.visibilityRules?.forEach(visibilityRule => {
// result.push({
// sourceField: field.id.toString(),
// targetField: visibilityRule.target,
// dateValue: visibilityRule.dateValue,
// textValue: visibilityRule.textValue,
// textListValue: visibilityRule.textListValue
// })
// });
// });
// });
// });
// });
// return result;
// }
// }
// class MapWithDefault extends Map<string, boolean> {
// get(key) {
// //console.log('MapWithDefault');
// if (!this.has(key)) {
// this.set(key, true);
// }
// return super.get(key);
// }
// }

View File

@ -1,454 +1,577 @@
import { ApplicationRef, Injectable, NgZone } from '@angular/core'; import { Injectable } from '@angular/core';
import { AbstractControl, UntypedFormArray, UntypedFormGroup } from '@angular/forms'; import { AbstractControl } from '@angular/forms';
import { isNumeric } from '@app/utilities/enhancers/utils';
import { Observable, Subject } from 'rxjs'; import { Observable, Subject } from 'rxjs';
import { VisibilityRule } from './models/visibility-rule'; import { DescriptionTemplateDefinition, DescriptionTemplateField, DescriptionTemplateFieldSet, DescriptionTemplatePage, DescriptionTemplateSection } from '@app/core/model/description-template/description-template';
import { VisibilityRuleSource } from './models/visibility-rule-source'; import { RuleWithTarget } from './models/rule';
import { VisibilityRulesContext } from './models/visibility-rules-context'; import { FormService } from '@common/forms/form-service';
import { DescriptionTemplate, DescriptionTemplatePage, DescriptionTemplateSection } from '@app/core/model/description-template/description-template'; import { DescriptionFieldPersist, DescriptionPropertyDefinitionFieldSetPersist, DescriptionPropertyDefinitionPersist } from '@app/core/model/description/description';
import { Rule } from './models/rule'; import { DescriptionTemplateFieldType } from '@app/core/common/enum/description-template-field-type';
@Injectable() @Injectable()
export class VisibilityRulesService { export class VisibilityRulesService {
private readonly VISIBILITY_RULE_LOGIC: 'OR' | 'AND' = 'OR';
private readonly DEFAULTVISIBILITY = false;
private visibilityRuleContext: VisibilityRulesContext;
private form: AbstractControl; private form: AbstractControl;
private definition: DescriptionTemplateDefinition;
private rulesBySources: Map<String, RuleWithTarget[]> ;
public isVisibleMap: { [key: string]: boolean } = null;
private _isVisibleMap: { [key: string]: boolean } = null;
public isVisibleMap: { [key: string]: boolean } = {}; private allDescriptionTemplateFields: DescriptionTemplateField[] = null;
private allDescriptionTemplateFieldSets: DescriptionTemplateFieldSet[] = null;
private elementVisibilityMapSubject = new Subject<{ [key: string]: boolean }>();
private elementComputationalMap = new Map<String, Map<String, boolean>>(); /// keep saved the values of each form control validity value
private _changeMade$ = new Subject<void>();
// get isVisibleMap(): MapWithDefault {
// // console.log('isVisibleMap');
// return this.elementVisibilityMap;
// }; /// keep saved the values of each form control validity value
constructor( constructor(
public applicationReference: ApplicationRef, protected formService: FormService
public ngZone: NgZone
) { ) {
} }
getElementVisibilityMapObservable(): Observable<{ [key: string]: boolean }> { public setContext(definition: DescriptionTemplateDefinition, form: AbstractControl) {
// this.isVisibleMap this.definition = definition;
// console.log('getElementVisibilityMapObservable: ');
return this.elementVisibilityMapSubject.asObservable();
}
public checkElementVisibility(id: string): boolean {
//console.log('checkElementVisibility: ' + id);
return true;
// if (this.visibilityRuleContext.rules.filter(item => item.targetControlId === id).length === 0) { return true; }
// console.log(this.elementVisibilityMap.has(id) ? this.elementVisibilityMap.get(id) : false);
// return this.elementVisibilityMap.has(id) ? this.elementVisibilityMap.get(id) : false;
}
public buildVisibilityRules(item: Array<Rule>, form: AbstractControl) {
this.visibilityRuleContext = new VisibilityRulesContext();
this.visibilityRuleContext.buildVisibilityRuleContext(item || []);
this.form = form; this.form = form;
this.resetVisibilityRules(); this.allDescriptionTemplateFields = null;
this.allDescriptionTemplateFieldSets = null;
this.rulesBySources = null;
this._isVisibleMap = null;
this.calculateVisibility();
} }
public updateValueAndVisibility(id: string, value: any) { public buildVisibilityKey(id: string, ordinal: number | null): string {
//console.log('updateValueAndVisibility: ' + id + ' value: ' + value); if (ordinal == null) return id;
const visibilityRules = this.visibilityRuleContext.rules.filter(item => item.sourceVisibilityRules.filter(source => source.sourceControlId === id).length > 0); else return id + "_" + ordinal;
if (visibilityRules.length > 0) { }
visibilityRules.forEach(item => this.evaluateVisibility(item, value, id));
this.elementVisibilityMapSubject.next(this.isVisibleMap); public isVisible(id: string, ordinal: number | null): boolean {
this.calculateVisibility();
const fieldKey = this.buildVisibilityKey(id, ordinal);
return this.isVisibleMap[fieldKey] ?? false;
}
public getVisibilityStates(): { [key: string]: boolean } {
this.calculateVisibility();
return this.isVisibleMap;
}
public updateVisibilityForSource(id: string) {
const visibilityRules = this.rulesBySources.has(id) ? this.rulesBySources.get(id) : null;
if (visibilityRules && visibilityRules.length > 0) {
this.reloadVisibility();
} }
} }
private evaluateVisibility(visibilityRule: VisibilityRule, value: any, sourceId: string) {// source controlId is the same public reloadVisibility() {
//console.log('evaluateVisibility: ' + visibilityRule + ' value: ' + value + ' sourceId: ' + sourceId); this.rulesBySources = null;
this._isVisibleMap = null;
this.calculateVisibility();
}
const targetId = visibilityRule.targetControlId; private calculateVisibility(){
const visibilityMap = this.elementComputationalMap.get(targetId) ? this.elementComputationalMap.get(targetId) : new Map<String, boolean>(); if (this._isVisibleMap != null) return;
if (this.definition == null || this.form == null) return;
this.initRules();
const propertyDefinition: DescriptionPropertyDefinitionPersist = this.formService.getValue(this.form.getRawValue()) as DescriptionPropertyDefinitionPersist;
if (value instanceof Array) { this.buildTargetVisibility(propertyDefinition);
this.expandVisibilityToChildren(propertyDefinition);
this.setDefaultVisibilityForNotCaclucted(propertyDefinition);
this.hideParentIfAllChildrenAreHidden(propertyDefinition);
this.ensureFieldSetVisibility(propertyDefinition);
this.isVisibleMap = this._isVisibleMap;
}
const parsedSourceControlValues = visibilityRule.sourceVisibilityRules.map(e => this.parseValue(e.sourceControlValue)); private initRules(){
const parsedValues = value.map(e => this.parseValue(e)); if (this.definition == null || this.form == null) return;
if (this.rulesBySources != null) return;
this.rulesBySources = new Map();
const isVisible = parsedValues.map(v => parsedSourceControlValues.includes(v)).reduce((acc, current) => acc || current, false); const fields: DescriptionTemplateField[] = this.getAllDescriptionTemplateDefinitionFields(this.definition);
for (let i = 0; i < fields.length; i++) {
const fieldEntity = fields[i];
if (fieldEntity.visibilityRules != null && fieldEntity.visibilityRules.length > 0) {
for (let j = 0; j < fieldEntity.visibilityRules.length; j++) {
const rule = fieldEntity.visibilityRules[j];
if (!this.rulesBySources.has(fieldEntity.id)) this.rulesBySources.set(fieldEntity.id, []);
const ruleWithTarget: RuleWithTarget = new RuleWithTarget(fieldEntity.id, rule, fieldEntity);
this.rulesBySources.get(fieldEntity.id).push(ruleWithTarget);
}
}
}
}
private getDescriptionTemplateDefinitionFieldById(definition: DescriptionTemplateDefinition, fieldId: string): DescriptionTemplateField[] {
const fields: DescriptionTemplateField[] = this.getAllDescriptionTemplateDefinitionFields(definition);
return fields.filter(x=> x.id == fieldId);
}
// if(isVisible){ private getAllDescriptionTemplateDefinitionFields(definition: DescriptionTemplateDefinition): DescriptionTemplateField[] {
// this._emitChangesIfNeeded(visibilityRule.targetControlId, true); if (this.allDescriptionTemplateFields != null) return this.allDescriptionTemplateFields;
// this.elementVisibilityMap.set(visibilityRule.targetControlId, true);
// return;
// }
visibilityMap.set(sourceId, isVisible);
let fields: DescriptionTemplateField[] = [];
if (definition.pages == null) return fields;
for (let i = 0; i < definition.pages.length; i++) {
const item = definition.pages[i];
fields = [...fields, ...this.getAllDescriptionTemplatePageFields(item)];
}
this.allDescriptionTemplateFields = fields;
return this.allDescriptionTemplateFields;
}
private getAllDescriptionTemplatePageFields(definition: DescriptionTemplatePage): DescriptionTemplateField[] {
let fields: DescriptionTemplateField[] = [];
if (definition.sections == null) return fields;
for (let i = 0; i < definition.sections.length; i++) {
const item = definition.sections[i];
fields = [...fields, ...this.getAllDescriptionTemplateSectionFields(item)];
}
return fields;
}
private getAllDescriptionTemplateSectionFields(definition: DescriptionTemplateSection): DescriptionTemplateField[] {
let fields: DescriptionTemplateField[] = [];
if (definition.sections != null) {
for (let i = 0; i < definition.sections.length; i++) {
const item = definition.sections[i];
fields = [...fields, ...this.getAllDescriptionTemplateSectionFields(item)];
}
}
if (definition.fieldSets != null) {
for (let i = 0; i < definition.fieldSets.length; i++) {
const item = definition.fieldSets[i];
fields = [...fields, ...this.getAllDescriptionTemplateFieldSetFields(item)];
}
}
return fields;
}
private getAllDescriptionTemplateFieldSetFields(definition: DescriptionTemplateFieldSet): DescriptionTemplateField[] {
return definition.fields == null ? [] : definition.fields;
}
private getDescriptionTemplateDefinitionFieldSetById(definition: DescriptionTemplateDefinition, fieldSetId: string): DescriptionTemplateFieldSet[] {
const fieldSets: DescriptionTemplateFieldSet[] = this.getAllDescriptionTemplateDefinitionFieldSets(definition);
return fieldSets.filter(x=> x.id == fieldSetId);
}
private getAllDescriptionTemplateDefinitionFieldSets(definition: DescriptionTemplateDefinition): DescriptionTemplateFieldSet[] {
if (this.allDescriptionTemplateFieldSets != null) return this.allDescriptionTemplateFieldSets;
let fieldSets: DescriptionTemplateFieldSet[] = [];
if (definition.pages == null) return fieldSets;
for (let i = 0; i < definition.pages.length; i++) {
const item = definition.pages[i];
fieldSets = [...fieldSets, ...this.getAllDescriptionTemplatePageFieldSets(item)];
}
this.allDescriptionTemplateFieldSets = fieldSets;
return this.allDescriptionTemplateFieldSets;
}
private getAllDescriptionTemplatePageFieldSets(definition: DescriptionTemplatePage): DescriptionTemplateFieldSet[] {
let fieldSets: DescriptionTemplateFieldSet[] = [];
if (definition.sections == null) return fieldSets;
for (let i = 0; i < definition.sections.length; i++) {
const item = definition.sections[i];
fieldSets = [...fieldSets, ...this.getAllDescriptionTemplateSectionFieldSets(item)];
}
return fieldSets;
}
private getAllDescriptionTemplateSectionFieldSets(definition: DescriptionTemplateSection): DescriptionTemplateFieldSet[] {
let fieldSets: DescriptionTemplateFieldSet[] = [];
if (definition.sections != null) {
for (let i = 0; i < definition.sections.length; i++) {
const item = definition.sections[i];
fieldSets = [...fieldSets, ...this.getAllDescriptionTemplateSectionFieldSets(item)];
}
}
if (definition.fieldSets != null) {
for (let i = 0; i < definition.fieldSets.length; i++) {
const item = definition.fieldSets[i];
fieldSets = [...fieldSets, ...definition.fieldSets];
}
}
return fieldSets;
}
private buildTargetVisibility(propertyDefinition: DescriptionPropertyDefinitionPersist){
this._isVisibleMap = {};
this.rulesBySources.forEach((ruleForSource: RuleWithTarget[], ruleForSourceKey: string) => {
for (let i = 0; i < ruleForSource.length; i++) {
const rule = ruleForSource[i];
if (propertyDefinition.fieldSets != null) {
new Map(Object.entries(propertyDefinition.fieldSets)).forEach((propertyDefinitionFieldSet: DescriptionPropertyDefinitionFieldSetPersist, propertyDefinitionFieldSetKey: string) => {
if (propertyDefinitionFieldSet.items != null && propertyDefinitionFieldSet.items.length > 0) {
for (let j = 0; j < propertyDefinitionFieldSet.items.length; j++) {
const definitionFieldSetItem = propertyDefinitionFieldSet.items[j];
if (definitionFieldSetItem?.fields != null) {
const fieldsMap = new Map(Object.entries(definitionFieldSetItem.fields));
fieldsMap.forEach((field: DescriptionFieldPersist, key: string) => {
if (rule.source == key){
if (fieldsMap.has(rule.target)){ //Rule applies only for current multiple item
const fieldKey = this.buildVisibilityKey(rule.target, definitionFieldSetItem.ordinal);
const currentState = this._isVisibleMap[fieldKey] ?? false;
this._isVisibleMap[fieldKey] = currentState || this.ruleIsTrue(rule, field);
//console.log(fieldKey + " " + this._isVisibleMap[fieldKey] + " " + field.textListValue);
} else if (this.getDescriptionTemplateDefinitionFieldById(this.definition, rule.target).length > 0 || this.getDescriptionTemplateDefinitionFieldSetById(this.definition, rule.target).length > 0) { //Rule applies to different fieldset, so we apply for all multiple items
const ordinals: number[] = this.getKeyOrdinals(rule.target, propertyDefinition);
for (let k = 0; k < ordinals.length; k++) {
const ordinal = ordinals[j];
const fieldKey = this.buildVisibilityKey(rule.target, ordinal);
const currentState = this._isVisibleMap[fieldKey] ?? false;
this._isVisibleMap[fieldKey] = currentState || this.ruleIsTrue(rule, field);
}
} else { } else {
const visibilityDependencySource = visibilityRule.sourceVisibilityRules.filter(x => x.sourceControlId === sourceId); const fieldKey = this.buildVisibilityKey(rule.target, null); //Ordinal is null if target not on field
const currentState = this._isVisibleMap[fieldKey] ?? false;
const shouldBeVisible = visibilityDependencySource.reduce((isVisible, x) => { this._isVisibleMap[fieldKey] = currentState || this.ruleIsTrue(rule, field);
}
const shouldBeHidden = value !== null && (this.parseValue(value) !== this.parseValue(x.sourceControlValue)); }
return this.VISIBILITY_RULE_LOGIC === 'OR' ? (isVisible || !shouldBeHidden) : (isVisible && !shouldBeHidden); });
// if(value !== null && ) }
}, this.VISIBILITY_RULE_LOGIC === 'AND'); }
visibilityMap.set(sourceId, shouldBeVisible); }
});
}
}
});
} }
private getKeyOrdinals(key: string, propertyDefinition: DescriptionPropertyDefinitionPersist): number[]{
this.elementComputationalMap.set(targetId, visibilityMap);// unnessecary let ordinals = [];
if (propertyDefinition.fieldSets != null) {
new Map(Object.entries(propertyDefinition.fieldSets)).forEach((propertyDefinitionFieldSet: DescriptionPropertyDefinitionFieldSetPersist, propertyDefinitionFieldSetKey: string) => {
const isVisible = this._computeVisibility(targetId); if (propertyDefinitionFieldSetKey == key) {
this._emitChangesIfNeeded(targetId, isVisible); ordinals = propertyDefinitionFieldSet.items?.map(x => x.ordinal) ?? [];
const previousVisibility = this.isVisibleMap[targetId]; return ordinals;
this.isVisibleMap[targetId] = isVisible; }
if (propertyDefinitionFieldSet.items != null && propertyDefinitionFieldSet.items.length > 0) {
if (!isVisible && previousVisibility !== isVisible) { for (let i = 0; i < propertyDefinitionFieldSet.items.length; i++) {
this.resetControlWithId(this.form, targetId); const definitionFieldSetItem = propertyDefinitionFieldSet.items[i];
if (definitionFieldSetItem?.fields != null) {
new Map(Object.entries(definitionFieldSetItem.fields)).forEach((field: DescriptionFieldPersist, fieldKey: string) => {
if (fieldKey == key) ordinals = propertyDefinitionFieldSet.items?.map(x=> x.ordinal) ?? [];
});
if (ordinals != null && ordinals.length > 0) return ordinals;
}
}
}
});
}
return ordinals;
} }
private ruleIsTrue(rule: RuleWithTarget, field: DescriptionFieldPersist) :boolean{
// for (let i = 0; i < visibilityRule.sourceVisibilityRules.length; i++) { if (field != null){
// if (value != null && (this.parseValue(value) !== this.parseValue(visibilityRule.sourceVisibilityRules[i].sourceControlValue))) { const fieldType: DescriptionTemplateFieldType = rule.field != null && rule.field.data != null ? rule.field.data.fieldType : DescriptionTemplateFieldType.FREE_TEXT;
// this._emitChangesIfNeeded(visibilityRule.targetControlId, false); if ([DescriptionTemplateFieldType.FREE_TEXT, DescriptionTemplateFieldType.CHECK_BOX, DescriptionTemplateFieldType.TEXT_AREA,
// this.elementVisibilityMap.set(visibilityRule.targetControlId, false); DescriptionTemplateFieldType.RICH_TEXT_AREA, DescriptionTemplateFieldType.UPLOAD, DescriptionTemplateFieldType.BOOLEAN_DECISION,
// this.resetControlWithId(this.form, visibilityRule.targetControlId); DescriptionTemplateFieldType.RADIO_BOX, DescriptionTemplateFieldType.CURRENCY, DescriptionTemplateFieldType.SELECT].includes(fieldType) && field.textValue != null && field.textValue.length > 0) {
// //this.updateValueAndVisibility(visibilityRule.targetControlId, null); if (DescriptionTemplateFieldType.UPLOAD == fieldType){
// // this.clearValues(targetPathKey); return false; //not apply visibility logic
// return;
// }
// }
// this._emitChangesIfNeeded(visibilityRule.targetControlId, true);
// this.elementVisibilityMap.set(visibilityRule.targetControlId, true);
// this.updateValueAndVisibility(visibilityRule.targetControlId, null);
}
private _computeVisibility(targetId: string): boolean {
//console.log('_computeVisibility: ' + targetId);
const visibilityMap = this.elementComputationalMap.get(targetId);
const values = visibilityMap.values();
let currentVal = values.next();
let visibilityValues: boolean[] = [];
while (!currentVal.done) {
visibilityValues.push(currentVal.value);
currentVal = values.next();
}
if (visibilityValues.length) {
return visibilityValues.reduce((r, c) => {
if (this.VISIBILITY_RULE_LOGIC === 'OR') {
return r || c;
} else { } else {
return r && c; return field.textValue == rule.textValue;
}
}, visibilityValues[0]);
}
return this.DEFAULTVISIBILITY;
}
private resetVisibilityRules() {
//console.log('resetVisibilityRules: ');
this.isVisibleMap = {};
this.elementComputationalMap.clear();
this.elementComputationalMap = new Map<String, Map<String, boolean>>();
this._populateComputationMap(); /// !IMPORTANT FOR THE AND LOGIC
this._changeMade$.next();
}
private _populateComputationMap(): void {
//console.log('_populateComputationMap: ');
// this.visibilityRuleContext.rules.forEach(rule => {
// const targetId = rule.targetControlId;
// const visibilityMap = this.elementComputationalMap.get(targetId) ? this.elementComputationalMap.get(targetId) : new Map<String, boolean>();
// rule.sourceVisibilityRules.forEach(vr => {
// visibilityMap.set(vr.sourceControlId, this.DEFAULTVISIBILITY);
// });
// this.elementComputationalMap.set(targetId, visibilityMap);
// });
}
parseValue(value: any) {
if (typeof value === 'string') {
if (isNumeric(value)) { return value; }
else if (value === 'true') {
return true;
}
else if (value === 'false') {
return false;
}
else { return this.translate(value); }
} else { return value; }
}
search(path, obj, target) {
for (const k in obj) {
if (obj.hasOwnProperty(k)) {
if (obj[k] === target) {
return path + '.' + k;
} else if (typeof obj[k] === 'object') {
const result = this.search(path + '.' + k, obj[k], target);
if (result) {
return result;
} }
} }
else if ([DescriptionTemplateFieldType.SELECT, DescriptionTemplateFieldType.TAGS, DescriptionTemplateFieldType.INTERNAL_ENTRIES_DMPS,
DescriptionTemplateFieldType.INTERNAL_ENTRIES_DESCRIPTIONS].includes(fieldType) && field.textListValue != null && field.textListValue.length > 0) {
return rule.textListValue != null &&
rule.textListValue.every(x=> field.textListValue.includes(x));
}
else if (DescriptionTemplateFieldType.REFERENCE_TYPES == fieldType) {
return false; //not implemented visibility logic
}
else if (DescriptionTemplateFieldType.DATE_PICKER == fieldType && field.dateValue != null) return field.dateValue == rule.dateValue;
else if ([DescriptionTemplateFieldType.VALIDATION, DescriptionTemplateFieldType.DATASET_IDENTIFIER].includes(fieldType) && field.externalIdentifier != null) {
return false; //not implemented visibility logic
} }
} }
return false; return false;
} }
scanIfChildsOfCompositeFieldHasVisibleItems(compositeFieldParent: UntypedFormGroup): boolean { private expandVisibilityToChildren(propertyDefinition: DescriptionPropertyDefinitionPersist){
// console.log('scanIfChildsOfCompositeFieldHasVisibleItems: ' + compositeFieldParent); if (this.definition?.pages == null) return;
for (let i = 0; i < this.definition?.pages.length; i++) {
//TODO: implement this const pageEntity = this.definition?.pages[i];
return true; const fieldKey = this.buildVisibilityKey(pageEntity.id, null);
// let isVisible = false; const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
// (<UntypedFormArray>(compositeFieldParent.get('fields'))).controls.forEach(element => { this.expandPageVisibility(pageEntity, propertyDefinition, currentValue);
// if (this.checkElementVisibility(element.get('id').value)) {
// isVisible = true;
// }
// });
// return isVisible;
}
private translate(item: any) {
try {
return JSON.parse(item).value;
} catch (error) {
return item;
} }
} }
private resetControlWithId(formControl: AbstractControl, id: string) { private expandPageVisibility(pageEntity : DescriptionTemplatePage, propertyDefinition: DescriptionPropertyDefinitionPersist, parentVisibility : boolean | null){
//'resetControlWithId: ' + id); if (pageEntity.sections == null) return;
//TODO: implement this for (let i = 0; i < pageEntity.sections.length; i++) {
// if (formControl instanceof UntypedFormGroup) { const sectionEntity = pageEntity.sections[i];
// if ((formControl as UntypedFormGroup).contains('id') && (formControl as UntypedFormGroup).contains('value') && (formControl as UntypedFormGroup).get('id').value === id) { const fieldKey = this.buildVisibilityKey(sectionEntity.id, null);
// this.resetFieldFormGroup(formControl); const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
// } if ((formControl as UntypedFormGroup).contains('id') && (formControl as UntypedFormGroup).contains('fields') && (formControl as UntypedFormGroup).get('id').value === id) { if (currentValue != null){
// this.resetCompositeFieldFormGroup(formControl); if (parentVisibility != null && !parentVisibility) { //Parent is hidden so all childs should be hidden
// } else { this._isVisibleMap[fieldKey] = false;
// Object.keys(formControl.controls).forEach(item => { this.expandSectionVisibility(sectionEntity, propertyDefinition, currentValue);
// const control = formControl.get(item); } else {
// this.resetControlWithId(control, id); this.expandSectionVisibility(sectionEntity, propertyDefinition, currentValue);
// });
// }
// } else if (formControl instanceof UntypedFormArray) {
// formControl.controls.forEach(item => {
// this.resetControlWithId(item, id);
// });
// }
}
private resetFieldFormGroup(formGroup: UntypedFormGroup) {
//console.log('resetFieldFormGroup: ' + formGroup);
//TODO: implement this
// const renderStyle = formGroup.getRawValue().viewStyle.renderStyle;
// if (renderStyle === DatasetProfileFieldViewStyle.Validation || renderStyle === DatasetProfileFieldViewStyle.DatasetIdentifier) {
// formGroup.get('value').setValue({ identifier: '', type: '' });
// } else {
// formGroup.get('value').setValue(formGroup.get('defaultValue').value ? this.parseValue(formGroup.get('defaultValue').value.value) : undefined);
// }
}
private resetCompositeFieldFormGroup(formGroup: UntypedFormGroup) {
//console.log('resetCompositeFieldFormGroup: ' + formGroup);
//TODO: implement this
// (formGroup.get('fields') as UntypedFormArray).controls.forEach((element: UntypedFormGroup) => {
// this.resetFieldFormGroup(element);
// });
// (formGroup.get('multiplicityItems') as UntypedFormArray).controls.splice(0);
}
private _emitChangesIfNeeded(id: string, valueToBeSet: boolean) {
if (this.isVisibleMap[id]) {
if (this.isVisibleMap[id] != valueToBeSet) {
this._changeMade$.next();
} }
} else { } else {
this._changeMade$.next(); if (parentVisibility != null) this._isVisibleMap[fieldKey] = parentVisibility;
this.expandSectionVisibility(sectionEntity, propertyDefinition, parentVisibility);
} }
} }
public get visibilityChange() {
return this._changeMade$.asObservable();
} }
public getVisibilityDependency(targetId: string): VisibilityRuleSource[] | null { private expandSectionVisibility(sectionEntity: DescriptionTemplateSection, propertyDefinition: DescriptionPropertyDefinitionPersist, parentVisibility : boolean | null){
//console.log('getVisibilityDependency: ' + targetId); if (sectionEntity.sections != null) {
return this.visibilityRuleContext.rules.reduce((hasDependency, rule) => { for (let i = 0; i < sectionEntity.sections.length; i++) {
if (hasDependency) return hasDependency; const subSectionEntity = sectionEntity.sections[i];
const fieldKey = this.buildVisibilityKey(subSectionEntity.id, null);
if (rule.targetControlId === targetId) { const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
return rule.sourceVisibilityRules; if (currentValue != null){
if (parentVisibility != null && !parentVisibility) { //Parent is hidden so all childs should be hidden
this._isVisibleMap[fieldKey] = false;
this.expandSectionVisibility(subSectionEntity, propertyDefinition, currentValue);
} else {
this.expandSectionVisibility(subSectionEntity, propertyDefinition, currentValue);
} }
} else {
return null; if (parentVisibility != null) this._isVisibleMap[fieldKey] = parentVisibility;
}, null) as VisibilityRuleSource[]; this.expandSectionVisibility(subSectionEntity, propertyDefinition, parentVisibility);
} }
public getVisibilityTargets(sourceId: string): string[] {
console.log('getVisibilityTargets: ' + sourceId);
return this.visibilityRuleContext.rules.filter(x => {
const result = x.sourceVisibilityRules.filter(y => y.sourceControlId === sourceId);
return result.length;
}).map(x => x.targetControlId);
} }
// public appendVisibilityRule(rule: VisibilityRule): void{
// const existingTargetRule = this.visibilityRuleContext.rules.find( r => r.targetControlId === rule.targetControlId);
// if(existingTargetRule){
// rule.sourceVisibilityRules.forEach(svr =>{
// existingTargetRule.sourceVisibilityRules.push(svr);
// });
// }else{
// this.visibilityRuleContext.rules.push(rule);
// }
// }
//removes rule that has the specific id either as a source either as a target
public removeAllIdReferences(id: string): void {
//console.log('removeAllIdReferences: ' + id);
// * Remove from visibility rues and visibility rules context
//remove as a target
const temp = this.visibilityRuleContext.rules.map((x, i) => (x.targetControlId === id) ? i : null);
const indexes = temp.filter(x => x !== null);
indexes.reverse().forEach(index => this.visibilityRuleContext.rules.splice(index, 1));
this.isVisibleMap[id] = undefined;
//remove as a source
const tbd = this.visibilityRuleContext.rules.reduce((to_be_deleted, rule, ruleIdx) => {
const idxs = rule.sourceVisibilityRules.map((x, i) => (x.sourceControlId === id) ? i : null).filter(x => x !== null);
idxs.reverse().forEach(index => rule.sourceVisibilityRules.splice(index, 1));
if (!rule.sourceVisibilityRules.length) {
to_be_deleted.push(ruleIdx);
} }
return to_be_deleted if (sectionEntity.fieldSets != null) {
}, []);
for (let i = 0; i < sectionEntity.fieldSets.length; i++) {
//clean up empty const fieldSetEntity = sectionEntity.fieldSets[i];
tbd.reverse().forEach(index => { const fieldSetsMap = propertyDefinition.fieldSets != null ? new Map(Object.entries(propertyDefinition.fieldSets)) : null;
this.visibilityRuleContext.rules.splice(index, 1); if (fieldSetsMap != null && fieldSetsMap.has(fieldSetEntity.id)) {
}); const propertyDefinitionFieldSet = fieldSetsMap.get(fieldSetEntity.id)
if (propertyDefinitionFieldSet.items != null && propertyDefinitionFieldSet.items.length > 0) {
for (let j = 0; j < propertyDefinitionFieldSet.items.length; j++) {
const definitionFieldSetItem = propertyDefinitionFieldSet.items[j];
// * Remove from computational map const fieldKey = this.buildVisibilityKey(fieldSetEntity.id, definitionFieldSetItem.ordinal);
const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
// as a target if (currentValue != null){
if (this.elementComputationalMap.get(id)) { if (parentVisibility != null && !parentVisibility) { //Parent is hidden so all childs should be hidden
this.elementComputationalMap.delete(id); this._isVisibleMap[fieldKey] = false;
this.expandFieldSetVisibility(fieldSetEntity, currentValue, definitionFieldSetItem.ordinal);
} else {
this.expandFieldSetVisibility(fieldSetEntity, currentValue, definitionFieldSetItem.ordinal);
}
} else {
if (parentVisibility != null) this._isVisibleMap[fieldKey] = parentVisibility;
this.expandFieldSetVisibility(fieldSetEntity, parentVisibility, definitionFieldSetItem.ordinal);
}
}
}
}
} }
// as a source
const keyIterator = this.elementComputationalMap.keys();
let currentKey = keyIterator.next();
while (!currentKey.done) {
const currentVals = this.elementComputationalMap.get(currentKey.value);
currentVals.delete(id);
currentKey = keyIterator.next();
} }
} }
private expandFieldSetVisibility(fieldSetEntity: DescriptionTemplateFieldSet, parentVisibility: boolean | null, ordinal: number){
public addNewRule(rule: Rule, currentVisibility = this.DEFAULTVISIBILITY): void { if (fieldSetEntity.fields != null) {
//console.log('addNewRule: ' + rule + ' currentVisibility: ' + currentVisibility); for (let i = 0; i < fieldSetEntity.fields.length; i++) {
const fieldEntity = fieldSetEntity.fields[i];
const targetId = rule.targetField; const fieldKey = this.buildVisibilityKey(fieldEntity.id, ordinal);
const sourceId = rule.sourceField; const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
this.visibilityRuleContext.addToVisibilityRulesContext(rule); if (currentValue != null){
if (parentVisibility != null && !parentVisibility) { //Parent is hidden so all childs should be hidden
this._isVisibleMap[fieldKey] = false;
let visibilityMap = this.elementComputationalMap.get(targetId); }
} else if (parentVisibility != null){
if (!visibilityMap) { this._isVisibleMap[fieldKey] = parentVisibility;
visibilityMap = new Map<String, boolean>(); }
this.elementComputationalMap.set(targetId, visibilityMap); }
}
} }
visibilityMap.set(sourceId, currentVisibility); private setDefaultVisibilityForNotCaclucted(propertyDefinition: DescriptionPropertyDefinitionPersist) {
const isVisible = this._computeVisibility(targetId); if (this.definition?.pages == null) return;
for (let i = 0; i < this.definition?.pages.length; i++) {
this._emitChangesIfNeeded(targetId, isVisible); const pageEntity = this.definition?.pages[i];
this.isVisibleMap[targetId] = isVisible; const fieldKey = this.buildVisibilityKey(pageEntity.id, null);
this.elementVisibilityMapSubject.next(this.isVisibleMap); const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
if (currentValue == null) this._isVisibleMap[fieldKey] = true;
this.setDefaultPageVisibility(pageEntity, propertyDefinition);
}
} }
private setDefaultPageVisibility(pageEntity: DescriptionTemplatePage, propertyDefinition: DescriptionPropertyDefinitionPersist) {
/** if (pageEntity.sections == null) return;
* Check what sourceId hides or shows the target field for (let i = 0; i < pageEntity.sections.length; i++) {
* return true if no rule found const sectionEntity = pageEntity.sections[i];
*/ const fieldKey = this.buildVisibilityKey(sectionEntity.id, null);
public checkTargetVisibilityProvidedBySource(sourceId: string, targetId: string): boolean { const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
//console.log('checkTargetVisibilityProvidedBySource: ' + sourceId + ' targetId: ' + targetId); if (currentValue == null){
this._isVisibleMap[fieldKey] = true;
const computationalMap = this.elementComputationalMap.get(targetId); this.setDefaultSectionVisibility(sectionEntity, propertyDefinition);
if (computationalMap) { }
return !!computationalMap.get(sourceId); }
} }
private setDefaultSectionVisibility(sectionEntity: DescriptionTemplateSection, propertyDefinition: DescriptionPropertyDefinitionPersist) {
if (sectionEntity.sections != null) {
for (let i = 0; i < sectionEntity.sections.length; i++) {
const subSectionEntity = sectionEntity.sections[i];
const fieldKey = this.buildVisibilityKey(subSectionEntity.id, null);
const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
if (currentValue == null){
this._isVisibleMap[fieldKey] = true;
this.setDefaultSectionVisibility(subSectionEntity, propertyDefinition);
}
}
}
if (sectionEntity.fieldSets != null) {
for (let i = 0; i < sectionEntity.fieldSets.length; i++) {
const fieldSetEntity = sectionEntity.fieldSets[i];
const fieldSetsMap = propertyDefinition.fieldSets != null ? new Map(Object.entries(propertyDefinition.fieldSets)) : null;
if (fieldSetsMap != null && fieldSetsMap.has(fieldSetEntity.id)) {
const propertyDefinitionFieldSet = fieldSetsMap.get(fieldSetEntity.id)
if (propertyDefinitionFieldSet.items != null && propertyDefinitionFieldSet.items.length > 0) {
for (let j = 0; j < propertyDefinitionFieldSet.items.length; j++) {
const definitionFieldSetItem = propertyDefinitionFieldSet.items[j];
const fieldKey = this.buildVisibilityKey(fieldSetEntity.id, definitionFieldSetItem.ordinal);
const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
if (currentValue == null){
this._isVisibleMap[fieldKey] = true;
this.setDefaultFieldSetVisibility(fieldSetEntity, definitionFieldSetItem.ordinal);
}
}
}
}
}
}
}
private setDefaultFieldSetVisibility(fieldSetEntity: DescriptionTemplateFieldSet, ordinal: number){
if (fieldSetEntity.fields != null) {
for (let i = 0; i < fieldSetEntity.fields.length; i++) {
const fieldEntity = fieldSetEntity.fields[i];
const fieldKey = this.buildVisibilityKey(fieldEntity.id, ordinal);
const currentValue: boolean | null = this._isVisibleMap[fieldKey] ?? null;
if (currentValue == null){
this._isVisibleMap[fieldKey] = true;
}
}
}
}
private hideParentIfAllChildrenAreHidden(propertyDefinition: DescriptionPropertyDefinitionPersist) {
if (this.definition?.pages == null) return;
for (let i = 0; i < this.definition?.pages.length; i++) {
const pageEntity = this.definition?.pages[i];
const fieldKey = this.buildVisibilityKey(pageEntity.id, null);
const isCurrentHidden = this.isHiddenPageVisibilityIfAllChildrenIsHidden(pageEntity, propertyDefinition);
if (isCurrentHidden && (this._isVisibleMap[fieldKey] ?? true)) {
this._isVisibleMap[fieldKey] = false;
}
}
}
private isHiddenPageVisibilityIfAllChildrenIsHidden(pageEntity: DescriptionTemplatePage, propertyDefinition: DescriptionPropertyDefinitionPersist): boolean{
let isHidden = true;
if (pageEntity?.sections == null) return;
for (let i = 0; i < pageEntity.sections.length; i++) {
const sectionEntity = pageEntity.sections[i];
const fieldKey = this.buildVisibilityKey(sectionEntity.id, null);
const isCurrentHidden = this.isHiddenSectionIfAllChildrenIsHidden(sectionEntity, propertyDefinition);
if (isCurrentHidden && (this._isVisibleMap[fieldKey] ?? true)) {
this._isVisibleMap[fieldKey] = false;
}
isHidden = isHidden && isCurrentHidden;
}
return isHidden;
}
private isHiddenSectionIfAllChildrenIsHidden(sectionEntity: DescriptionTemplateSection, propertyDefinition: DescriptionPropertyDefinitionPersist): boolean{
let isHidden = true;
if (sectionEntity.sections != null) {
for (let i = 0; i < sectionEntity.sections.length; i++) {
const subSectionEntity = sectionEntity.sections[i];
const fieldKey = this.buildVisibilityKey(subSectionEntity.id, null);
const isCurrentHidden = this.isHiddenSectionIfAllChildrenIsHidden(subSectionEntity, propertyDefinition);
if (isCurrentHidden && (this._isVisibleMap[fieldKey] ?? true)) {
this._isVisibleMap[fieldKey] = false;
}
isHidden = isHidden && isCurrentHidden;
}
}
if (sectionEntity.fieldSets != null) {
for (let i = 0; i < sectionEntity.fieldSets.length; i++) {
const fieldSetEntity = sectionEntity.fieldSets[i];
const fieldSetsMap = propertyDefinition.fieldSets != null ? new Map(Object.entries(propertyDefinition.fieldSets)) : null;
if (fieldSetsMap != null && fieldSetsMap.has(fieldSetEntity.id)) {
const propertyDefinitionFieldSet = fieldSetsMap.get(fieldSetEntity.id)
if (propertyDefinitionFieldSet.items != null && propertyDefinitionFieldSet.items.length > 0) {
for (let j = 0; j < propertyDefinitionFieldSet.items.length; j++) {
const definitionFieldSetItem = propertyDefinitionFieldSet.items[j];
const fieldKey = this.buildVisibilityKey(fieldSetEntity.id, definitionFieldSetItem.ordinal);
const isCurrentHidden = this.isHiddenFieldSetIfAllChildrenIsHidden(fieldSetEntity, definitionFieldSetItem.ordinal);
if (isCurrentHidden && (this._isVisibleMap[fieldKey] ?? true)) {
this._isVisibleMap[fieldKey] = false;
}
isHidden = isHidden && isCurrentHidden;
}
}
}
}
}
return isHidden;
}
private isHiddenFieldSetIfAllChildrenIsHidden(fieldSetEntity: DescriptionTemplateFieldSet, ordinal: number): boolean{
let isHidden = true;
if (fieldSetEntity.fields != null) {
for (let i = 0; i < fieldSetEntity.fields.length; i++) {
const fieldEntity = fieldSetEntity.fields[i];
const fieldKey = this.buildVisibilityKey(fieldEntity.id, ordinal);
const currentValue: boolean | null = (this._isVisibleMap[fieldKey] ?? true);
isHidden = isHidden && !currentValue;
}
return isHidden;
}
return true; return true;
} }
public getVisibilityRulesFromDescriptionTempalte(descriptionTemplate: DescriptionTemplate): Rule[] { private ensureFieldSetVisibility(propertyDefinition: DescriptionPropertyDefinitionPersist) {
//console.log('getVisibilityRulesFromDescriptionTempalte: ' + descriptionTemplate); if (this.definition?.pages == null) return;
const result: Rule[] = this.getVisibilityRulesFromDescriptionTempalteSections(descriptionTemplate?.definition?.pages); for (let i = 0; i < this.definition?.pages.length; i++) {
return result; const pageEntity = this.definition?.pages[i];
} this.ensurePageFieldSetVisibility(pageEntity, propertyDefinition);
public getVisibilityRulesFromDescriptionTempalteSections(pages: DescriptionTemplatePage[]): Rule[] {
//console.log('getVisibilityRulesFromDescriptionTempalteSections: ' + sections);
const result: Rule[] = [];
pages.forEach(page => {
page?.sections?.forEach(section => {
if (section.sections != null) { result.push(...this.getVisibilityRulesFromDescriptionTempalteSections(section.sections)); };
section?.fieldSets?.forEach(fieldSet => {
fieldSet?.fields?.forEach(field => {
field.visibilityRules?.forEach(visibilityRule => {
result.push({
sourceField: field.id.toString(),
targetField: visibilityRule.target,
requiredValue: visibilityRule.value
})
});
});
});
});
});
return result;
} }
} }
class MapWithDefault extends Map<string, boolean> { private ensurePageFieldSetVisibility(pageEntity: DescriptionTemplatePage, propertyDefinition: DescriptionPropertyDefinitionPersist){
get(key) { if (pageEntity?.sections == null) return;
//console.log('MapWithDefault'); for (let i = 0; i < pageEntity.sections.length; i++) {
if (!this.has(key)) { const sectionEntity = pageEntity.sections[i];
this.set(key, true); this.ensureSectionFieldSetVisibility(sectionEntity, propertyDefinition);
} }
return super.get(key); }
private ensureSectionFieldSetVisibility(sectionEntity: DescriptionTemplateSection, propertyDefinition: DescriptionPropertyDefinitionPersist){
if (sectionEntity.sections != null) {
for (let i = 0; i < sectionEntity.sections.length; i++) {
const subSectionEntity = sectionEntity.sections[i];
this.ensureSectionFieldSetVisibility(subSectionEntity, propertyDefinition);
}
}
if (sectionEntity.fieldSets != null) {
for (let i = 0; i < sectionEntity.fieldSets.length; i++) {
const fieldSetEntity = sectionEntity.fieldSets[i];
let isHidden = true;
const fieldSetsMap = propertyDefinition.fieldSets != null ? new Map(Object.entries(propertyDefinition.fieldSets)) : null;
if (fieldSetsMap != null && fieldSetsMap.has(fieldSetEntity.id)) {
const propertyDefinitionFieldSet = fieldSetsMap.get(fieldSetEntity.id)
if (propertyDefinitionFieldSet.items != null && propertyDefinitionFieldSet.items.length > 0) {
for (let j = 0; j < propertyDefinitionFieldSet.items.length; j++) {
const definitionFieldSetItem = propertyDefinitionFieldSet.items[j];
const fieldKey = this.buildVisibilityKey(fieldSetEntity.id, definitionFieldSetItem.ordinal);
const isCurrentHidden = !this._isVisibleMap[fieldKey] ?? false;
isHidden = isHidden && isCurrentHidden;
}
}
}
const globalFieldSetKey = this.buildVisibilityKey(fieldSetEntity.id, null);
this._isVisibleMap[globalFieldSetKey] = !isHidden;
}
}
} }
} }

View File

@ -147,7 +147,7 @@ export class TableOfContentsInternal implements OnInit {
} }
if (entry.type === this.tocEntryTypeEnum.FieldSet) { if (entry.type === this.tocEntryTypeEnum.FieldSet) {
const id = entry.id; const id = entry.id;
if (!(this.visibilityRulesService.isVisibleMap[id.toString()] ?? true)) { if (!(this.visibilityRulesService.isVisibleMap[id.toString()])) {
return false; return false;
} }
// const fieldsArray = entry.form.get('fields') as UntypedFormArray; // const fieldsArray = entry.form.get('fields') as UntypedFormArray;

View File

@ -83,9 +83,9 @@ export class TableOfContentsComponent extends BaseComponent implements OnInit, O
if (this.descriptionTemplate) { if (this.descriptionTemplate) {
this.tocentries = this.getTocEntries(this.descriptionTemplate); this.tocentries = this.getTocEntries(this.descriptionTemplate);
// if (this.visibilityRulesService) { if (this.visibilityRulesService) {
// this.hiddenEntries = this._findHiddenEntries(this.tocentries); this.hiddenEntries = this._findHiddenEntries(this.tocentries);
// } }
} else { } else {
@ -157,15 +157,9 @@ export class TableOfContentsComponent extends BaseComponent implements OnInit, O
const invisibleEntries: string[] = [] const invisibleEntries: string[] = []
tocentries.forEach(entry => { tocentries.forEach(entry => {
if (entry.type === ToCEntryType.FieldSet) { if (entry.type === ToCEntryType.FieldSet) {
const isVisible = this.visibilityRulesService.isVisibleMap[entry.id.toString()] ?? true; const isVisible = this.visibilityRulesService.isVisibleMap[entry.id.toString()];
if (!isVisible) { if (!isVisible) {
invisibleEntries.push(entry.id.toString()); invisibleEntries.push(entry.id.toString());
} else {
//check field inputs
const oneFieldAtLeastIsVisible = entry.subEntries.some(field => this.visibilityRulesService.isVisibleMap[field.id.toString()] ?? true);
if (!oneFieldAtLeastIsVisible) {
invisibleEntries.push(entry.id.toString());
}
} }
} else { } else {
const hiddenEntries = this._findHiddenEntries(entry.subEntries); const hiddenEntries = this._findHiddenEntries(entry.subEntries);
@ -214,15 +208,15 @@ export class TableOfContentsComponent extends BaseComponent implements OnInit, O
if (!this.visibilityRulesService) return; if (!this.visibilityRulesService) return;
this._visibilityRulesSubscription = this.visibilityRulesService.visibilityChange // this._visibilityRulesSubscription = this.visibilityRulesService.visibilityChange
.pipe(takeUntil(this._destroyed)) // .pipe(takeUntil(this._destroyed))
.pipe(debounceTime(200)) // .pipe(debounceTime(200))
.subscribe(_ => { // .subscribe(_ => {
if (this.hasFocus) { // if (this.hasFocus) {
this._resetObserver(); // this._resetObserver();
// this.hiddenEntries = this._findHiddenEntries(this.tocentries); // // this.hiddenEntries = this._findHiddenEntries(this.tocentries);
} // }
}); // });
// this.hiddenEntries = this._findHiddenEntries(this.tocentries); // this.hiddenEntries = this._findHiddenEntries(this.tocentries);
} }
// if (!this.isActive && this.links && this.links.length > 0) { // if (!this.isActive && this.links && this.links.length > 0) {

View File

@ -78,10 +78,10 @@ export class DmpInvitationDialogComponent extends BaseComponent implements OnIni
} }
onCallbackSuccess(): void { onCallbackSuccess(): void {
this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.INVITATION-DIALOG.SUCCESS'), SnackBarNotificationLevel.Success); this.uiNotificationService.snackBarNotification(this.language.instant('DMP-USER-INVITATION-DIALOG.SUCCESS'), SnackBarNotificationLevel.Success);
} }
onCallbackError(errorResponse: any) { onCallbackError(errorResponse: any) {
this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.INVITATION-DIALOG.ERROR'), SnackBarNotificationLevel.Error); this.uiNotificationService.snackBarNotification(this.language.instant('DMP-USER-INVITATION-DIALOG.ERROR'), SnackBarNotificationLevel.Error);
} }
} }

View File

@ -1391,7 +1391,9 @@
"TITLE": "Invite authors", "TITLE": "Invite authors",
"ACTIONS": { "ACTIONS": {
"INVITE": "Invite" "INVITE": "Invite"
} },
"SUCCESS": "Invitation Success",
"ERROR": "Invitation Error"
}, },
"DMP-BLUEPRINT-LISTING": { "DMP-BLUEPRINT-LISTING": {
"TITLE": "Plan Blueprints", "TITLE": "Plan Blueprints",

View File

@ -169,6 +169,7 @@ public class DescriptionTemplateXmlMigrationService {
data.setOrdinal(persist.getOrdinal()); data.setOrdinal(persist.getOrdinal());
data.setNumbering(persist.getNumbering()); data.setNumbering(persist.getNumbering());
data.setTitle(persist.getTitle()); data.setTitle(persist.getTitle());
data.setDescription(persist.getDescription());
data.setExtendedDescription(persist.getExtendedDescription()); data.setExtendedDescription(persist.getExtendedDescription());
data.setAdditionalInformation(persist.getAdditionalInformation()); data.setAdditionalInformation(persist.getAdditionalInformation());
data.setHasCommentField(persist.getHasCommentField()); data.setHasCommentField(persist.getHasCommentField());