argos/dmp-frontend/src/app/ui/admin/description-template/editor/description-template-editor...

1657 lines
57 KiB
TypeScript
Raw Normal View History

2023-10-31 10:19:52 +01:00
import { Component, OnInit, QueryList, ViewChild } from '@angular/core';
2023-11-24 17:42:23 +01:00
import { FormArray, FormControl, UntypedFormArray, UntypedFormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { EnumUtils } from '@app/core/services/utilities/enum-utils.service';
// import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
2023-10-31 10:19:52 +01:00
import { CdkStep, StepperSelectionEvent } from '@angular/cdk/stepper';
import { DatePipe } from '@angular/common';
2023-10-31 10:19:52 +01:00
import { MatStepper } from '@angular/material/stepper';
import { DescriptionTemplateStatus } from '@app/core/common/enum/description-template-status';
import { IsActive } from '@app/core/common/enum/is-active.enum';
import { AppPermission } from '@app/core/common/enum/permission.enum';
2023-12-29 16:04:16 +01:00
import { UserDescriptionTemplateRole } from '@app/core/common/enum/user-description-template-role';
import { DescriptionTemplate } from '@app/core/model/description-template/description-template';
2023-10-31 10:19:52 +01:00
import { DescriptionTemplatePersist } from '@app/core/model/description-template/description-template-persist';
import { LanguageInfo } from '@app/core/model/language-info';
2023-11-24 17:42:23 +01:00
import { User } from '@app/core/model/user/user';
import { AuthService } from '@app/core/services/auth/auth.service';
2023-10-31 10:19:52 +01:00
import { LanguageInfoService } from '@app/core/services/culture/language-info-service';
import { DescriptionTemplateTypeService } from '@app/core/services/description-template-type/description-template-type.service';
import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service';
import { LoggingService } from '@app/core/services/logging/logging-service';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
2023-11-24 17:42:23 +01:00
import { UserService } from '@app/core/services/user/user.service';
import { FileUtils } from '@app/core/services/utilities/file-utils.service';
import { QueryParamsService } from '@app/core/services/utilities/query-params.service';
import { BaseEditor } from '@common/base/base-editor';
import { FormService } from '@common/forms/form-service';
import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component';
import { HttpErrorHandlingService } from '@common/modules/errors/error-handling/http-error-handling.service';
import { FilterService } from '@common/modules/text-filter/filter-service';
import { Guid } from '@common/types/guid';
import { TranslateService } from '@ngx-translate/core';
2023-12-29 16:04:16 +01:00
import { map, takeUntil } from 'rxjs/operators';
2023-10-31 10:19:52 +01:00
import { GENERAL_ANIMATIONS, STEPPER_ANIMATIONS } from './animations/animations';
2023-11-24 17:42:23 +01:00
import { DescriptionTemplateEditorModel, DescriptionTemplateFieldEditorModel, DescriptionTemplateFieldSetEditorModel, DescriptionTemplatePageEditorModel, DescriptionTemplateSectionEditorModel, UserDescriptionTemplateEditorModel } from './description-template-editor.model';
import { DescriptionTemplateEditorResolver } from './description-template-editor.resolver';
import { DescriptionTemplateEditorService } from './description-template-editor.service';
2023-10-31 10:19:52 +01:00
import { NewEntryType, ToCEntry, ToCEntryType } from './table-of-contents/description-template-table-of-contents-entry';
@Component({
selector: 'app-description-template-editor-component',
templateUrl: 'description-template-editor.component.html',
styleUrls: ['./description-template-editor.component.scss'],
2023-10-31 10:19:52 +01:00
animations: [...STEPPER_ANIMATIONS, ...GENERAL_ANIMATIONS],
providers: [DescriptionTemplateEditorService]
})
export class DescriptionTemplateEditorComponent extends BaseEditor<DescriptionTemplateEditorModel, DescriptionTemplate> implements OnInit {
2023-10-31 10:19:52 +01:00
@ViewChild('stepper') stepper: MatStepper;
isNew = true;
isDeleted = false;
formGroup: UntypedFormGroup = null;
2023-11-24 17:42:23 +01:00
item: DescriptionTemplate;
showInactiveDetails = false;
2023-10-31 10:19:52 +01:00
availableLanguages: LanguageInfo[] = this.languageInfoService.getLanguageInfoValues();
isNewVersion = false;
isClone = false;
steps: QueryList<CdkStep>;
toCEntries: ToCEntry[];
selectedTocEntry: ToCEntry;
colorizeInvalid: boolean = false;
2023-11-24 17:42:23 +01:00
tocEntryEnumValues = ToCEntryType;
usersMap: Map<Guid, User> = new Map<Guid, User>();
userFormControl = new FormControl();
2023-10-31 10:19:52 +01:00
// selectedSystemFields: Array<DescriptionTemplateSystemFieldType> = [];
// descriptionTemplateSectionFieldCategory = DescriptionTemplateSectionFieldCategory;
// descriptionTemplateSystemFieldType = DescriptionTemplateSystemFieldType;
// public descriptionTemplateSystemFieldTypeEnum = this.enumUtils.getEnumValues(DescriptionTemplateSystemFieldType);
// descriptionTemplateExtraFieldDataType = DescriptionTemplateExtraFieldDataType;
// public descriptionTemplateExtraFieldDataTypeEnum = this.enumUtils.getEnumValues(DescriptionTemplateExtraFieldDataType);
// blueprintsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
// filterFn: this.filterDescriptionTempaltes.bind(this),
// initialItems: (excludedItems: any[]) => this.filterDescriptionTempaltes('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
// displayFn: (item: DatasetProfileModel) => item.label,
// titleFn: (item: DatasetProfileModel) => item.label,
// subtitleFn: (item: DatasetProfileModel) => item.description,
// popupItemActionIcon: 'visibility'
// };
protected get canDelete(): boolean {
return !this.isDeleted && !this.isNew && this.hasPermission(this.authService.permissionEnum.DeleteDescriptionTemplate);
}
protected get canSave(): boolean {
return !this.isDeleted && this.hasPermission(this.authService.permissionEnum.EditDescriptionTemplate);
}
protected get canFinalize(): boolean {
return !this.isDeleted && this.hasPermission(this.authService.permissionEnum.EditDescriptionTemplate);
}
private hasPermission(permission: AppPermission): boolean {
return this.authService.hasPermission(permission) || this.editorModel?.permissions?.includes(permission);
}
constructor(
// BaseFormEditor injected dependencies
protected dialog: MatDialog,
protected language: TranslateService,
protected formService: FormService,
protected router: Router,
protected uiNotificationService: UiNotificationService,
protected httpErrorHandlingService: HttpErrorHandlingService,
protected filterService: FilterService,
protected datePipe: DatePipe,
protected route: ActivatedRoute,
protected queryParamsService: QueryParamsService,
// Rest dependencies. Inject any other needed deps here:
public authService: AuthService,
public enumUtils: EnumUtils,
private descriptionTemplateService: DescriptionTemplateService,
2023-10-31 10:19:52 +01:00
public descriptionTemplateTypeService: DescriptionTemplateTypeService,
private logger: LoggingService,
private descriptionTemplateEditorService: DescriptionTemplateEditorService,
private fileUtils: FileUtils,
private matomoService: MatomoService,
2023-11-24 17:42:23 +01:00
private languageInfoService: LanguageInfoService,
public userService: UserService
) {
super(dialog, language, formService, router, uiNotificationService, httpErrorHandlingService, filterService, datePipe, route, queryParamsService);
}
ngOnInit(): void {
this.matomoService.trackPageView('Admin: DMP Blueprints');
super.ngOnInit();
}
getItem(itemId: Guid, successFunction: (item: DescriptionTemplate) => void) {
this.descriptionTemplateService.getSingle(itemId, DescriptionTemplateEditorResolver.lookupFields())
.pipe(map(data => data as DescriptionTemplate), takeUntil(this._destroyed))
.subscribe(
data => successFunction(data),
error => this.onCallbackError(error)
);
}
prepareForm(data: DescriptionTemplate) {
try {
this.editorModel = data ? new DescriptionTemplateEditorModel().fromModel(data) : new DescriptionTemplateEditorModel();
2023-11-24 17:42:23 +01:00
this.item = data;
// Add user info to Map, to present them.
2023-12-29 16:04:16 +01:00
(this.item?.users ?? []).forEach(obj => { this.usersMap.set(obj.user.id, obj.user); });
this.isDeleted = data ? data.isActive === IsActive.Inactive : false;
this.buildForm();
2023-10-31 10:19:52 +01:00
setTimeout(() => {
this.steps = this.stepper.steps;
});
this._initializeToCEntries();
} catch (error) {
2023-11-24 17:42:23 +01:00
console.error(error);
this.logger.error('Could not parse descriptionTemplate item: ' + data + error);
this.uiNotificationService.snackBarNotification(this.language.instant('COMMONS.ERRORS.DEFAULT'), SnackBarNotificationLevel.Error);
}
}
buildForm() {
this.formGroup = this.editorModel.buildForm(null, this.isDeleted || !this.authService.hasPermission(AppPermission.EditDescriptionTemplate));
//this.selectedSystemFields = this.selectedSystemFieldDisabled();
this.descriptionTemplateEditorService.setValidationErrorModel(this.editorModel.validationErrorModel);
DescriptionTemplateEditorModel.reApplyDefinitionValidators({
formGroup: this.formGroup,
validationErrorModel: this.editorModel.validationErrorModel
});
2024-01-25 19:55:42 +01:00
if (this.editorModel.status == DescriptionTemplateStatus.Finalized || this.isDeleted) {
this.formGroup.disable();
}
}
refreshData(): void {
this.getItem(this.editorModel.id, (data: DescriptionTemplate) => this.prepareForm(data));
}
refreshOnNavigateToData(id?: Guid): void {
this.formGroup.markAsPristine();
let route = [];
if (id === null) {
route.push('../..');
} else if (this.isNew) {
route.push('../' + id);
} else {
route.push('..');
}
this.router.navigate(route, { queryParams: { 'lookup': this.queryParamsService.serializeLookup(this.lookupParams), 'lv': ++this.lv }, replaceUrl: true, relativeTo: this.route });
}
persistEntity(onSuccess?: (response) => void): void {
const formData = this.formService.getValue(this.formGroup.value) as DescriptionTemplatePersist;
this.descriptionTemplateService.persist(formData)
.pipe(takeUntil(this._destroyed)).subscribe(
complete => onSuccess ? onSuccess(complete) : this.onCallbackSuccess(complete),
error => this.onCallbackError(error)
);
}
formSubmit(): void {
this.formService.touchAllFormFields(this.formGroup);
// if (!this.isFormValid()) {
// return;
// }
this.persistEntity();
}
public delete() {
const value = this.formGroup.value;
if (value.id) {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
maxWidth: '300px',
data: {
message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.DELETE-ITEM'),
confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'),
cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL')
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
if (result) {
this.descriptionTemplateService.delete(value.id).pipe(takeUntil(this._destroyed))
.subscribe(
complete => this.onCallbackSuccess(),
error => this.onCallbackError(error)
);
}
});
}
}
clearErrorModel() {
this.editorModel.validationErrorModel.clear();
this.formService.validateAllFormFields(this.formGroup);
}
2023-11-24 17:42:23 +01:00
//
//
// Description Template User
//
//
addUser(user: User) {
console.log(user);
const newUser: UserDescriptionTemplateEditorModel = new UserDescriptionTemplateEditorModel();
newUser.userId = user.id;
newUser.role = UserDescriptionTemplateRole.Owner;
this.usersMap.set(user.id, user);
(this.formGroup.get('users') as FormArray).push(newUser.buildForm());
this.userFormControl.reset();
}
removeUser(index: number) {
(this.formGroup.get('users') as FormArray).controls.splice(index, 1);
this.formGroup.get('users').updateValueAndValidity();
}
2023-12-29 16:04:16 +01:00
verifyAndRemoveUser(index: number) {
2023-11-24 17:42:23 +01:00
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
restoreFocus: false,
data: {
message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.DELETE-ITEM'),
confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'),
cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
isDeleteConfirmation: true
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(approve => {
if (approve) {
this.removeUser(index);
}
});
}
2023-10-31 10:19:52 +01:00
//
//
// Stepper
//
//
onMatStepperSelectionChange(event: StepperSelectionEvent) {
if (event.selectedIndex === (this.steps.length - 1)) {//preview selected
// this.generatePreviewForm();//TODO LAZY LOADING IN THE TEMPLATE
// this.getPreview();
} else {
// this.previewForm = null;
// this.formGroup = null;
}
this.formGroup.markAsUntouched();
}
isStepCompleted(stepIndex: number) {
let stepCompleted = false;
this.steps.forEach((step, index) => {
if (stepIndex === index) {
stepCompleted = step.completed;
}
});
return stepCompleted;
}
isStepUnlocked(stepIndex: number): boolean {
if (stepIndex === 0) return true;
if (stepIndex < 0) return false;
//if previous step is valid then unlock
let stepUnlocked: boolean = false;
if (!this.isStepUnlocked(stepIndex - 1)) return false;
this.steps.forEach((step, index) => {
if (index + 1 == stepIndex) {//previous step
if (step.completed) {
stepUnlocked = true;
}
}
});
return stepUnlocked;
}
validateStep(selectedIndex) {
if (selectedIndex === 1) {//form description
if (this.formGroup.invalid) {
this.checkFormValidation();
}
}
}
//
//
// Table of Contents
//
//
private _initializeToCEntries() {
const tocentries = this.refreshToCEntries();//tocentries are sorted based on their ordinal value
this._updateOrdinals(tocentries);
if (tocentries && tocentries.length) {
this.selectedTocEntry = tocentries[0];
}
//Checking invalid visibilty RULES
const fieldsetEntries = this._getAllFieldSets(this.toCEntries);
const fieldSetHavingInvalidVisibilityRules: ToCEntry[] = fieldsetEntries
.filter(entry => {
const fieldsFormGroup = entry.form.get('fields');
const invalid = (fieldsFormGroup as UntypedFormArray).controls.filter(field => {
return this.hasInvalidVisibilityRule(field as UntypedFormGroup);
});
if (invalid && invalid.length) {
return true;
}
return false;
});
if (fieldSetHavingInvalidVisibilityRules.length) {
const occurences = fieldSetHavingInvalidVisibilityRules.map(record => record.numbering).join(' , ');
this.dialog.open(ConfirmationDialogComponent, {
data: {
2023-11-24 17:42:23 +01:00
message: this.language.instant('DESCRIPTION-TEMPLATE-EDITOR.ERRORS.INVALID-VISIBILITY-RULES.MESSAGE-START') + occurences + this.language.instant('DESCRIPTION-TEMPLATE-EDITOR.ERRORS.INVALID-VISIBILITY-RULES.MESSAGE-END'),
confirmButton: this.language.instant('DESCRIPTION-TEMPLATE-EDITOR.ERRORS.INVALID-VISIBILITY-RULES.CONFIRM-YES'),
cancelButton: this.language.instant('DESCRIPTION-TEMPLATE-EDITOR.ERRORS.INVALID-VISIBILITY-RULES.CONFIRM-NO')
2023-10-31 10:19:52 +01:00
},
maxWidth: '30em'
})
.afterClosed()
.subscribe(confirm => {
if (confirm) {
this.removeFieldSetVisibilityRules(fieldSetHavingInvalidVisibilityRules);
2023-11-24 17:42:23 +01:00
this.uiNotificationService.snackBarNotification(this.language.instant('DESCRIPTION-TEMPLATE-EDITOR.ERRORS.INVALID-VISIBILITY-RULES.REMOVE-SUCCESS'), SnackBarNotificationLevel.Success);
2023-10-31 10:19:52 +01:00
} else {
console.log('User not confirmed');
}
})
}
}
private refreshToCEntries(): ToCEntry[] {
this.toCEntries = this.getTocEntries();
//update selected tocentry
if (this.selectedTocEntry) {
this.selectedTocEntry = this._findTocEntryById(this.selectedTocEntry.id, this.toCEntries);
}
return this.toCEntries;
}
/**
* Updates entries ordinal form value
* based on the index they have on the tocentry array.
* Tocentries that are on the same level have distinct ordinal value
*
* @param tocentries
*
*/
private _updateOrdinals(tocentries: ToCEntry[]) {
if (!tocentries || !tocentries.length) return;
tocentries.forEach((e, idx) => {
const ordinalControl = e.form.get('ordinal');
if (ordinalControl) {
ordinalControl.setValue(idx);
ordinalControl.updateValueAndValidity();
}
this._updateOrdinals(e.subEntries);
});
}
getTocEntries(): ToCEntry[] {
if (this.formGroup == null) { return []; }
const result: ToCEntry[] = [];
//build parent pages
2023-11-24 17:42:23 +01:00
(this.formGroup.get('definition').get('pages') as UntypedFormArray).controls.forEach((pageElement, i) => {
2023-10-31 10:19:52 +01:00
result.push({
id: pageElement.get('id').value,
label: pageElement.get('title').value,
type: ToCEntryType.Page,
form: pageElement,
numbering: (i + 1).toString(),
subEntriesType: ToCEntryType.Section
} as ToCEntry)
});
// build first level sections
2023-11-24 17:42:23 +01:00
(this.formGroup.get('definition').get('sections') as UntypedFormArray).controls.forEach((sectionElement, i) => {
2023-10-31 10:19:52 +01:00
const currentSectionPageId = sectionElement.get('page').value;
const pageToAdd = result.filter(x => x.id == currentSectionPageId)[0];
if (pageToAdd.subEntries == null) pageToAdd.subEntries = [];
const item = {
id: sectionElement.get('id').value,
label: sectionElement.get('title').value,
type: ToCEntryType.Section,
form: sectionElement,
numbering: pageToAdd.numbering + '.' + (pageToAdd.subEntries.length + 1)
} as ToCEntry;
const sectionItems = this.populateSections(sectionElement.get('sections') as UntypedFormArray, item.numbering);
const fieldSetItems = this.populateFieldSets(sectionElement.get('fieldSets') as UntypedFormArray, item.numbering);
if (sectionItems != null) {
item.subEntries = sectionItems;
item.subEntriesType = ToCEntryType.Section;
}
if (fieldSetItems != null) {
if (item.subEntries == null) {
item.subEntries = fieldSetItems;
} else {
item.subEntries.push(...fieldSetItems);
}
item.subEntriesType = ToCEntryType.FieldSet;
}
pageToAdd.subEntries.push(item);
});
this._sortToCentries(result);//ordeby ordinal
this._updateNumbering(result, '');//update nubering if needed
return result;
}
private populateSections(sections: UntypedFormArray, existingNumbering: string): ToCEntry[] {
if (sections == null || sections.controls == null || sections.controls.length == 0) { return null; }
const result: ToCEntry[] = [];
sections.controls.forEach((sectionElement, i) => {
const item = {
id: sectionElement.get('id').value,
label: sectionElement.get('title').value,
type: ToCEntryType.Section,
form: sectionElement,
numbering: existingNumbering + '.' + (i + 1)
} as ToCEntry;
const sectionItems = this.populateSections(sectionElement.get('sections') as UntypedFormArray, item.numbering);
const fieldSetItems = this.populateFieldSets(sectionElement.get('fieldSets') as UntypedFormArray, item.numbering);
if (sectionItems != null) {
item.subEntries = sectionItems;
item.subEntriesType = ToCEntryType.Section;
}
if (fieldSetItems != null) {
if (item.subEntries == null) {
item.subEntries = fieldSetItems;
} else {
item.subEntries.push(...fieldSetItems);
}
item.subEntriesType = ToCEntryType.FieldSet;
}
result.push(item);
});
return result;
}
private populateFieldSets(fieldSets: UntypedFormArray, existingNumbering: string): ToCEntry[] {
if (fieldSets == null || fieldSets.controls == null || fieldSets.controls.length == 0) { return null; }
const result: ToCEntry[] = [];
fieldSets.controls.forEach((fieldSetElement, i) => {
result.push({
id: fieldSetElement.get('id').value,
label: fieldSetElement.get('title').value,
type: ToCEntryType.FieldSet,
//subEntries: this.populateSections((fieldSetElement.get('fieldSets') as FormArray), existingNumbering + '.' + i),
form: fieldSetElement,
numbering: existingNumbering + '.' + (i + 1)
} as ToCEntry)
});
return result;
}
private _findTocEntryById(id: string, tocentries: ToCEntry[]): ToCEntry {
if (!tocentries || !tocentries.length) {
return null;
}
let tocEntryFound = tocentries.find(entry => entry.id === id);
if (tocEntryFound) {
return tocEntryFound;
}
for (let entry of tocentries) {
const result = this._findTocEntryById(id, entry.subEntries);
if (result) {
tocEntryFound = result;
break;
}
}
return tocEntryFound ? tocEntryFound : null;
}
private reaplyValidators(){
DescriptionTemplateEditorModel.reApplyDefinitionValidators(
{
formGroup: this.formGroup,
validationErrorModel: this.editorModel.validationErrorModel
}
);
}
2023-10-31 10:19:52 +01:00
addNewEntry(tce: NewEntryType) {
2023-10-31 10:19:52 +01:00
const parent = tce.parent;
//define entry type
switch (tce.childType) {
case ToCEntryType.Page:
2023-11-24 17:42:23 +01:00
const pagesArray = (this.formGroup.get('definition').get('pages') as UntypedFormArray);
2023-10-31 10:19:52 +01:00
const page: DescriptionTemplatePageEditorModel = new DescriptionTemplatePageEditorModel(this.editorModel.validationErrorModel);
2023-12-20 08:20:38 +01:00
page.id = Guid.create().toString();
2023-10-31 10:19:52 +01:00
if (isNaN(pagesArray.length)) { page.ordinal = 0; } else { page.ordinal = pagesArray.length; }
const pageForm = page.buildForm({ rootPath: 'definition.pages[' + pagesArray.length + '].' });
2023-10-31 10:19:52 +01:00
// this.dataModel.pages.push(page);
pagesArray.push(pageForm);
// this.form.updateValueAndValidity();
this.refreshToCEntries();
this.selectedTocEntry = this._findTocEntryById(pageForm.get('id').value, this.toCEntries);
break;
case ToCEntryType.Section:
const section: DescriptionTemplateSectionEditorModel = new DescriptionTemplateSectionEditorModel(this.editorModel.validationErrorModel);
2023-12-20 08:20:38 +01:00
section.id = Guid.create().toString();
2023-10-31 10:19:52 +01:00
let sectionsArray: UntypedFormArray;
if (parent.type === ToCEntryType.Page) {//FIRST LEVEL SECTION
2023-11-24 17:42:23 +01:00
sectionsArray = this.formGroup.get('definition').get('sections') as UntypedFormArray;
2023-10-31 10:19:52 +01:00
section.page = parent.id;
try {
const max = sectionsArray.controls.filter(control => control.get('page').value === parent.id)
.map(control => control.get('ordinal').value)
.reduce((a, b) => Math.max(a, b));
section.ordinal = max + 1;
} catch {
section.ordinal = sectionsArray.length;
}
sectionsArray.push(section.buildForm({ rootPath: 'definition.sections[' + sectionsArray.length + '].' }));
2023-10-31 10:19:52 +01:00
// this.form.updateValueAndValidity();
} else if (parent.type == ToCEntryType.Section) { //SUBSECTION OF SECTION
sectionsArray = parent.form.get('sections') as UntypedFormArray;
//adding page parent MAYBE NOT NEEDED
section.page = parent.form.get('page').value;
try {
const maxOrdinal = sectionsArray.controls.map(control => control.get('ordinal').value).reduce((a, b) => Math.max(a, b));
section.ordinal = maxOrdinal + 1;
} catch {
section.ordinal = sectionsArray.length;
}
sectionsArray.push(section.buildForm({ rootPath: 'definition.sections[' + sectionsArray.length + '].' }));
2023-10-31 10:19:52 +01:00
// (child.form.parent as FormArray).push(section.buildForm());
} else {
console.error('Section can only be child of a page or another section');
}
const sectionAdded = sectionsArray.at(sectionsArray.length - 1) as UntypedFormGroup;
// sectionAdded.setValidators(this.customEditorValidators.sectionHasAtLeastOneChildOf('fieldSets','sections'));
// sectionAdded.updateValueAndValidity();
this.refreshToCEntries();
this.selectedTocEntry = this._findTocEntryById(sectionAdded.get('id').value, this.toCEntries);
break;
case ToCEntryType.FieldSet:
let sectionIndex = -1;
const sections = (this.formGroup.get('definition').get('sections') as UntypedFormArray);
for (let i = 0; i < sections.length; i++) {
2023-10-31 10:19:52 +01:00
let section = sections.at(i);
2023-10-31 10:19:52 +01:00
let sectionId = section.get('id').value;
if (sectionId == parent.id) {
sectionIndex = i;
break;
}
}
if(sectionIndex > -1 ){
//create one field form fieldset
const field: DescriptionTemplateFieldEditorModel = new DescriptionTemplateFieldEditorModel(this.editorModel.validationErrorModel);
field.id = Guid.create().toString();
field.ordinal = 0;//first filed in the fields list
// const fieldForm = field.buildForm();
// fieldForm.setValidators(this.customFieldValidator());
// fieldForm.get('viewStyle').get('renderStyle').setValidators(Validators.required);
// fieldSet.fields.push(field);
// field.ordinal = fieldSet.fields.length-1;
const fieldSetsArray = parent.form.get('fieldSets') as UntypedFormArray
const fieldForm = field.buildForm({ rootPath: 'definition.sections[' + sectionIndex + '].fieldSets[' + fieldSetsArray.length + '].fields['+ 0 + '].'});
//give fieldset id and ordinal
const fieldSet: DescriptionTemplateFieldSetEditorModel = new DescriptionTemplateFieldSetEditorModel(this.editorModel.validationErrorModel);
const fieldSetId = Guid.create().toString();
fieldSet.id = fieldSetId;
try {
const maxOrdinal = fieldSetsArray.controls.map(control => control.get('ordinal').value).reduce((a, b) => Math.max(a, b));
fieldSet.ordinal = maxOrdinal + 1;
} catch {
fieldSet.ordinal = fieldSetsArray.length;
}
const fieldsetForm = fieldSet.buildForm({ rootPath: 'definition.sections[' + sectionIndex + '].fieldSets[' + fieldSetsArray.length + '].'});
2023-10-31 10:19:52 +01:00
(fieldsetForm.get('fields') as UntypedFormArray).push(fieldForm);
fieldSetsArray.push(fieldsetForm);
2023-10-31 10:19:52 +01:00
this.refreshToCEntries();
this.selectedTocEntry = this._findTocEntryById(fieldSetId.toString(), this.toCEntries);
// fieldForm.updateValueAndValidity();
2023-10-31 10:19:52 +01:00
break;
}
2023-10-31 10:19:52 +01:00
default:
break;
}
this.formGroup.updateValueAndValidity();
}
onRemoveEntry(tce: ToCEntry) {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
restoreFocus: false,
data: {
message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.DELETE-ITEM'),
confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'),
cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
isDeleteConfirmation: true
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
if (result) {
this._deleteEntry(tce);
}
});
}
private _deleteEntry(tce: ToCEntry) {
//define entry type
switch (tce.type) {
case ToCEntryType.Page:
2023-11-24 17:42:23 +01:00
const pages = this.formGroup.get('definition').get('pages') as UntypedFormArray;
2023-10-31 10:19:52 +01:00
let pageIndex = -1;
//get the index
for (let i = 0; i < pages.length; i++) {
let page = pages.at(i) as UntypedFormGroup;
if (page.controls.id.value === tce.id) {
pageIndex = i;
break;
}
}
if (pageIndex >= 0) {
//remove page
this._updateSelectedItem(tce);
pages.removeAt(pageIndex);
//clean up sections of removed page
2023-11-24 17:42:23 +01:00
const sections = (this.formGroup.get('definition').get('sections') as UntypedFormArray);
2023-10-31 10:19:52 +01:00
const sectionsIndexToBeRemoved = [];
sections.controls.forEach((section, idx) => {
if (section.get('page').value === tce.id) {
sectionsIndexToBeRemoved.push(idx);
}
});
if (sectionsIndexToBeRemoved.length) {
sectionsIndexToBeRemoved.reverse().forEach(index => {
sections.removeAt(index);
});
}
//update page ordinals
for (let i = 0; i < pages.length; i++) {
pages.at(i).get('ordinal').patchValue(i);
}
this.reaplyValidators();
2023-10-31 10:19:52 +01:00
//update validity
// this.form.controls.sections.updateValueAndValidity();
}
break;
case ToCEntryType.Section:
//FIRST LEVEL SECTION CASE
let index = -1;
2023-11-24 17:42:23 +01:00
const sections = (this.formGroup.get('definition').get('sections') as UntypedFormArray);
2023-10-31 10:19:52 +01:00
for (let i = 0; i < sections.length; i++) {
let section = sections.at(i);
let sectionId = section.get('id').value;
if (sectionId == tce.id) {
index = i;
break;
}
}
if (index >= 0) { //section found
2023-11-24 17:42:23 +01:00
const sections = (this.formGroup.get('definition').get('sections') as UntypedFormArray);
2023-10-31 10:19:52 +01:00
//remove section
this._updateSelectedItem(tce);
sections.removeAt(index);
//update ordinal
for (let i = 0; i < sections.length; i++) {
sections.at(i).get('ordinal').patchValue(i);
}
} else {//NOT FOUND IN FIRST LEVEL CASE
//LOOK FOR SUBSECTION CASE
let parentFormArray = tce.form.parent as UntypedFormArray;
for (let i = 0; i < parentFormArray.length; i++) {
let section = parentFormArray.at(i);
if (section.get('id').value == tce.id) {
index = i;
break;
}
}
if (index >= 0) {
this._updateSelectedItem(tce);
parentFormArray.removeAt(index);
//update odrinal
for (let i = 0; i < parentFormArray.length; i++) {
parentFormArray.at(i).get('ordinal').patchValue(i);
}
}
}
this.reaplyValidators();
2023-10-31 10:19:52 +01:00
break;
case ToCEntryType.FieldSet:
const parentFormArray = tce.form.parent as UntypedFormArray;
let idx = -1;
for (let i = 0; i < parentFormArray.length; i++) {
let inspectingField = parentFormArray.at(i);
if (inspectingField.get('id').value === tce.id) {
//fieldset found
idx = i;
break;
}
}
if (idx >= 0) {//fieldset found
this._updateSelectedItem(tce);
parentFormArray.removeAt(idx);
//patching order
for (let i = 0; i < parentFormArray.length; i++) {
parentFormArray.at(i).get('ordinal').patchValue(i);
}
this.reaplyValidators();
2023-10-31 10:19:52 +01:00
}
break;
default:
break;
}
//in case selectedtocentrhy is child of the removed element
// this.refreshToCEntries();
this.onDataNeedsRefresh();
this.formGroup.updateValueAndValidity();
}
private _updateSelectedItem(tce: ToCEntry) {
if (this.selectedTocEntry) {
if (this.tocEntryIsChildOf(this.selectedTocEntry, tce)) {
if (this.selectedTocEntry.type == ToCEntryType.Page) {
this.selectedTocEntry = null;
} else {
//if first level section
2023-11-24 17:42:23 +01:00
const firstLevelSections = (this.formGroup.get('definition').get('sections') as UntypedFormArray);
2023-10-31 10:19:52 +01:00
let isFirstLevel: boolean = false;
firstLevelSections.controls.forEach(section => {
if (section.get('id').value === tce.id) {
isFirstLevel = true;
}
});
let parentId = null;
if (isFirstLevel) {
parentId = tce.form.get('page').value;
} else {
parentId = tce.form.parent.parent.get('id').value
}
// const parentId = tce.form.parent.parent.get('id').value;
if (parentId) {
const tocentries = this.getTocEntries();
const parent = this._findTocEntryById(parentId, tocentries);
if (parent) {
this.selectedTocEntry = parent;
} else {
this.selectedTocEntry = null;
}
} else {
this.selectedTocEntry = null;
}
}
}
}
}
tocEntryIsChildOf(testingChild: ToCEntry, parent: ToCEntry): boolean {
if (!testingChild || !parent) return false;
if (testingChild.id == parent.id) { return true; }
if (parent.subEntries) {
let childFound: boolean = false;
parent.subEntries.forEach(subEntry => {
if (this.tocEntryIsChildOf(testingChild, subEntry)) {
childFound = true;
return true;
}
})
return childFound;
}
return false;
}
onDataNeedsRefresh(params?) {
const tocentries = this.refreshToCEntries();
if (params && params.draggedItemId) {
if (params.draggedItemId) {
this.displayItem(this._findTocEntryById(params.draggedItemId, tocentries));
}
}
this.formGroup.markAsDirty();
}
displayItem(entry: ToCEntry): void {
this.selectedTocEntry = entry;
}
/**
* Get all filedsets in a tocentry array;
* @param entries Tocentries to search in
* @returns The tocentries that are Fieldsets provided in the entries
*/
private _getAllFieldSets(entries: ToCEntry[]): ToCEntry[] {
const fieldsets: ToCEntry[] = [];
if (!entries || !entries.length) return fieldsets;
entries.forEach(e => {
if (e.type === ToCEntryType.FieldSet) {
fieldsets.push(e);
} else {
fieldsets.push(...this._getAllFieldSets(e.subEntries));
}
});
return fieldsets;
}
private _sortToCentries(entries: ToCEntry[]) {
if (!entries || !entries.length) return;
entries.sort(this._compareOrdinals);
entries.forEach(e => {
this._sortToCentries(e.subEntries)
});
}
private _compareOrdinals(a, b) {
const aValue = a.form.get('ordinal').value as number;
const bValue = b.form.get('ordinal').value as number;
// if(!aValue || !bValue) return 0;
return aValue - bValue;
}
private _updateNumbering(entries: ToCEntry[], parentNumbering: string) {
if (!entries || !entries.length) return;
let prefix = '';
if (parentNumbering.length) {
prefix = parentNumbering + '.';
}
entries.forEach((entry, index) => {
const numbering = prefix + (index + 1);
entry.numbering = numbering;
this._updateNumbering(entry.subEntries, numbering);
})
}
//
//
// Visibility Rules
//
//
private hasInvalidVisibilityRule(field: UntypedFormGroup): boolean {
2023-11-24 17:42:23 +01:00
// const renderStyle = field.get('viewStyle').get('renderStyle').value;
// if (renderStyle && ![
// DatasetProfileFieldViewStyle.TextArea,
// DatasetProfileFieldViewStyle.RichTextArea,
// DatasetProfileFieldViewStyle.Upload,
// DatasetProfileFieldViewStyle.FreeText,
// DatasetProfileFieldViewStyle.BooleanDecision,
// DatasetProfileFieldViewStyle.RadioBox,
// DatasetProfileFieldViewStyle.CheckBox,
// DatasetProfileFieldViewStyle.DatePicker,
// DatasetProfileFieldViewStyle.ComboBox,
// ].includes(renderStyle)) {
2024-01-30 18:27:55 +01:00
// if (((renderStyle === DatasetProfileFieldViewStyle) && (field.get('data').get('type').value === DatasetProfileComboBoxType.Select))) {
2023-11-24 17:42:23 +01:00
// return false;
// }
// try {
// if (field.get('visible').get('rules').value.length) {
// return true;
// }
// return false;
// } catch {
// return false;
// }
// } else {
return false;
// }
2023-10-31 10:19:52 +01:00
}
private removeFieldSetVisibilityRules(fieldsets: ToCEntry[]) {
if (!fieldsets || !fieldsets.length) return;
fieldsets.forEach(fieldset => {
if (fieldset.type != ToCEntryType.FieldSet) {
return;
}
const fields = fieldset.form.get('fields') as UntypedFormArray;
fields.controls.forEach(fieldControl => {
if (this.hasInvalidVisibilityRule(fieldControl as UntypedFormGroup)) {
try {
(fieldControl.get('visible').get('rules') as UntypedFormArray).clear();
} catch { }
}
})
})
}
//
//
// Other
//
//
scrollOnTop() {
try {
const topPage = document.getElementById('main-content');
topPage.scrollIntoView({ behavior: 'smooth' });
2023-11-24 17:42:23 +01:00
} catch (e) {
console.log(e);
2023-10-31 10:19:52 +01:00
console.log('coulnd not scroll');
}
}
2023-12-29 16:04:16 +01:00
get numOfPages() {
2024-01-30 18:27:55 +01:00
return (<UntypedFormArray>this.formGroup.get('definition').get('pages'))?.length;
2023-11-24 17:42:23 +01:00
}
2023-10-31 10:19:52 +01:00
checkFormValidation() {
this.colorizeInvalid = true;
// this.printMyErrors(this.form);
}
2023-11-24 17:42:23 +01:00
get progressStyle() {
// return {'transform': 'translateX('+this.barPercentage+'%) skewX(-25deg)'}
const diff = 3;
return {
'clip-path': `polygon(0 0, ${Math.round(this.barPercentage + diff)}% 0, ${Math.round(this.barPercentage)}% 100%, 0 100%)`
}
}
get barPercentage() {
if (!this.stepper || !this.steps) {
return 0;
}
const selectedIndex = this.stepper.selectedIndex + 1;
return (selectedIndex / this.stepper.steps.length) * 100;
}
// //
// //
// // Sections
// //
// //
// addSection(): void {
// const section: DescriptionTemplateDefinitionSectionEditorModel = new DescriptionTemplateDefinitionSectionEditorModel();
// section.id = Guid.create();
// section.ordinal = (this.formGroup.get('definition').get('sections') as FormArray).controls.length + 1;
// section.hasTemplates = false;
// (this.formGroup.get('definition').get('sections') as FormArray).push(section.buildForm()); //TODO: dtziotzios validation path
// }
// removeSection(sectionIndex: number): void {
// (this.formGroup.get('definition').get('sections') as FormArray).removeAt(sectionIndex);
// (this.formGroup.get('definition').get('sections') as FormArray).controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// dropSections(event: CdkDragDrop<string[]>) {
// const sectionsFormArray = (this.formGroup.get('definition').get('sections') as FormArray);
// moveItemInArray(sectionsFormArray.controls, event.previousIndex, event.currentIndex);
// sectionsFormArray.updateValueAndValidity();
// sectionsFormArray.controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// //
// //
// // Fields
// //
// //
// systemFieldDisabled(systemField: DescriptionTemplateSystemFieldType) {
// return (this.formGroup.get('definition').get('sections') as FormArray)?.controls.some(x => (x.get('fields') as FormArray).controls.some(y => (y as UntypedFormGroup).get('systemFieldType')?.value === systemField));
// // for (let section in (this.formGroup.get('definition').get('sections')as FormArray)?.controls) {
// // if (i != sectionIndex) {
// // for (let f of this.fieldsArray(i).controls) {
// // if ((f.get('category').value == FieldCategory.SYSTEM || f.get('category').value == DescriptionTemplateSectionFieldCategory.SYSTEM) && f.get('type').value == systemField) {
// // return true;
// // }
// // }
// // }
// // i++;
// // }
// // return false;
// }
// selectedSystemFieldDisabled(): Array<DescriptionTemplateSystemFieldType> {
// return (this.formGroup.get('definition').get('sections') as FormArray)?.controls.flatMap(x => (x.get('fields') as FormArray).controls.map(y => (y as UntypedFormGroup).get('systemFieldType')?.value as DescriptionTemplateSystemFieldType));
// }
// addSystemField(sectionIndex: number, systemFieldType: DescriptionTemplateSystemFieldType): void {
// const field: FieldInSectionEditorModel = new FieldInSectionEditorModel();
// field.id = Guid.create();
// field.ordinal = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).length + 1;
// field.category = DescriptionTemplateSectionFieldCategory.SYSTEM;
// field.systemFieldType = systemFieldType;
// field.required = (systemFieldType == DescriptionTemplateSystemFieldType.TEXT || systemFieldType == DescriptionTemplateSystemFieldType.HTML_TEXT) ? true : false;
// ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).push(field.buildForm()); //TODO: dtziotzios validation path
// }
// removeSystemField(sectionIndex: number, fieldIndex: number): void {
// const formArray = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray);
// formArray.removeAt(fieldIndex);
// formArray.controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// addExtraField(sectionIndex: number): void {
// const field: FieldInSectionEditorModel = new FieldInSectionEditorModel();
// field.id = Guid.create();
// field.ordinal = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).length + 1;
// field.category = DescriptionTemplateSectionFieldCategory.EXTRA;
// ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).push(field.buildForm()); //TODO: dtziotzios validation path
// }
// removeExtraField(sectionIndex: number, fieldIndex: number): void {
// const formArray = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray);
// formArray.removeAt(fieldIndex);
// formArray.controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// dropFields(event: CdkDragDrop<string[]>, sectionIndex: number) {
// const fieldsFormArray = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray);
// moveItemInArray(fieldsFormArray.controls, event.previousIndex, event.currentIndex);
// fieldsFormArray.updateValueAndValidity();
// fieldsFormArray.controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// //
// //
// // Autocomplete configuration
// //
// //
// filterDescriptionTempaltes(value: string): Observable<DatasetProfileModel[]> {
// const request = new DataTableRequest<DatasetProfileCriteria>(null, null, { fields: ['+label'] });
// const criteria = new DatasetProfileCriteria();
// criteria.like = value;
// request.criteria = criteria;
// return this.dmpService.searchDescriptionTemplates(request);
// }
// onRemoveDescritionTemplate(event, sectionIndex: number) {
// const descriptionTemplateFormArray = (this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('descriptionTemplates') as FormArray;
// const foundIndex = descriptionTemplateFormArray.controls.findIndex(blueprint => blueprint.get('descriptionTemplateId').value === event.id);
// if (foundIndex !== -1) {
// descriptionTemplateFormArray.removeAt(foundIndex);
// }
// }
// onSelectDescritionTemplate(item, sectionIndex) {
// const descriptionTemplate: DescriptionTemplatesInSectionEditorModel = new DescriptionTemplatesInSectionEditorModel();
// descriptionTemplate.id = Guid.create();
// descriptionTemplate.descriptionTemplateId = item.id;
// descriptionTemplate.label = item.label;
// ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('descriptionTemplates') as FormArray).push(descriptionTemplate.buildForm()); //TODO: dtziotzios validation path
// }
// ngAfterViewInit() {
// this.route.params
// .pipe(takeUntil(this._destroyed))
// .subscribe((params: Params) => {
// this.descriptionTemplateId = params['id'];
// const cloneId = params['cloneid'];
// if (this.descriptionTemplateId != null) {
// this.isNew = false;
// this.descriptionTemplateService.getSingleBlueprint(this.descriptionTemplateId).pipe(map(data => data as any))
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.descriptionTemplateEditor = new DescriptionTemplateEditor().fromModel(data);
// this.formGroup = this.descriptionTemplateEditor.buildForm();
// this.buildSystemFields();
// this.fillDescriptionTemplatesInMultAutocomplete();
// if (this.descriptionTemplateEditor.status == DescriptionTemplateStatus.Finalized) {
// this.formGroup.disable();
// this.viewOnly = true
// }
// // this.breadCrumbs = observableOf([{
// // parentComponentName: 'DescriptionTemplateListingComponent',
// // label: this.language.instant('NAV-BAR.TEMPLATE'),
// // url: '/description-templates/' + this.descriptionTemplateId
// // }]);
// });
// } else if (cloneId != null) {
// this.isClone = true;
// this.descriptionTemplateService.clone(cloneId).pipe(map(data => data as any), takeUntil(this._destroyed))
// .subscribe(
// data => {
// this.descriptionTemplateEditor = new DescriptionTemplateEditor().fromModel(data);
// this.descriptionTemplateEditor.id = null;
// this.descriptionTemplateEditor.status = DescriptionTemplateStatus.Draft;
// this.formGroup = this.descriptionTemplateEditor.buildForm();
// this.buildSystemFields();
// this.fillDescriptionTemplatesInMultAutocomplete();
// },
// error => this.onCallbackError(error)
// );
// } else {
// this.descriptionTemplateEditorModel = new DescriptionTemplateEditorModel();
// this.descriptionTemplateEditor = new DescriptionTemplateEditor();
// setTimeout(() => {
// // this.formGroup = this.descriptionTemplateModel.buildForm();
// // this.addField();
// this.descriptionTemplateEditor.status = DescriptionTemplateStatus.Draft;
// this.formGroup = this.descriptionTemplateEditor.buildForm();
// });
// // this.breadCrumbs = observableOf([{
// // parentComponentName: 'DescriptionTemplateListingComponent',
// // label: this.language.instant('NAV-BAR.TEMPLATE'),
// // url: '/description-templates/' + this.descriptionTemplateId
// // }]);
// }
// });
// }
// buildSystemFields() {
// const sections = this.sectionsArray().controls.length;
// for (let i = 0; i < sections; i++) {
// let systemFieldsInSection = new Array();
// this.fieldsArray(i).controls.forEach((field) => {
// if ((field.get('category').value == FieldCategory.SYSTEM || field.get('category').value == DescriptionTemplateSectionFieldCategory.SYSTEM)) {
// systemFieldsInSection.push(this.fieldList.find(f => f.type == field.get('type').value).type);
// }
// })
// this.systemFieldListPerSection.push(systemFieldsInSection);
// }
// }
// fillDescriptionTemplatesInMultAutocomplete() {
// const sections = this.sectionsArray().controls.length;
// for (let i = 0; i < sections; i++) {
// let descriptionTemplatesInSection = new Array<DatasetProfileModel>();
// this.descriptionTemplatesArray(i).controls.forEach((template) => {
// descriptionTemplatesInSection.push({ id: template.value.descriptionTemplateId, label: template.value.label, description: "" });
// })
// this.descriptionTemplatesPerSection.push(descriptionTemplatesInSection);
// }
// }
// checkForProfiles(event, sectionIndex: number) {
// if (event.checked === false) {
// this.descriptionTemplatesPerSection[sectionIndex] = new Array<DatasetProfileModel>();
// this.descriptionTemplatesArray(sectionIndex).clear();
// }
// }
// sectionsArray(): UntypedFormArray {
// //return this.descriptionTemplatesFormGroup.get('sections') as FormArray;
// return this.formGroup.get('definition').get('sections') as UntypedFormArray;
// }
// fieldsArray(sectionIndex: number): UntypedFormArray {
// return this.sectionsArray().at(sectionIndex).get('fields') as UntypedFormArray;
// }
// removeField(sectionIndex: number, fieldIndex: number): void {
// this.fieldsArray(sectionIndex).removeAt(fieldIndex);
// }
// systemFieldsArray(sectionIndex: number): UntypedFormArray {
// return this.sectionsArray().at(sectionIndex).get('systemFields') as UntypedFormArray;
// }
// initSystemField(systemField?: SystemFieldType): UntypedFormGroup {
// return this.fb.group({
// id: this.fb.control(Guid.create().toString()),
// type: this.fb.control(systemField),
// label: this.fb.control(''),
// placeholder: this.fb.control(''),
// description: this.fb.control(''),
// required: this.fb.control(true),
// ordinal: this.fb.control('')
// });
// }
// addSystemField(sectionIndex: number, systemField?: SystemFieldType): void {
// this.addField(sectionIndex, FieldCategory.SYSTEM, systemField);
// }
// transfromEnumToString(type: SystemFieldType): string {
// return this.fieldList.find(f => f.type == type).label;
// }
// selectedFieldType(type: SystemFieldType, sectionIndex: number): void {
// let index = this.systemFieldListPerSection[sectionIndex].indexOf(type);
// if (index == -1) {
// this.systemFieldListPerSection[sectionIndex].push(type);
// this.addSystemField(sectionIndex, type);
// }
// else {
// this.systemFieldListPerSection[sectionIndex].splice(index, 1);
// this.removeSystemField(sectionIndex, type);
// }
// }
// descriptionTemplatesArray(sectionIndex: number): UntypedFormArray {
// return this.sectionsArray().at(sectionIndex).get('descriptionTemplates') as UntypedFormArray;
// }
// addDescriptionTemplate(descriptionTemplate, sectionIndex: number): void {
// this.descriptionTemplatesArray(sectionIndex).push(this.fb.group({
// label: this.fb.control(descriptionTemplate.value)
// }));
// }
// removeDescriptionTemplate(sectionIndex: number, templateIndex: number): void {
// this.descriptionTemplatesArray(sectionIndex).removeAt(templateIndex);
// }
// extraFieldsArray(sectionIndex: number): UntypedFormArray {
// return this.sectionsArray().at(sectionIndex).get('extraFields') as UntypedFormArray;
// }
// getExtraFieldTypes(): Number[] {
// let keys: string[] = Object.keys(ExtraFieldType);
// keys = keys.slice(0, keys.length / 2);
// const values: Number[] = keys.map(Number);
// return values;
// }
// getExtraFieldTypeValue(extraFieldType: ExtraFieldType): string {
// switch (extraFieldType) {
// case ExtraFieldType.TEXT: return 'Text';
// case ExtraFieldType.RICH_TEXT: return 'Rich Text';
// case ExtraFieldType.DATE: return 'Date';
// case ExtraFieldType.NUMBER: return 'Number';
// }
// }
// moveItemInFormArray(formArray: UntypedFormArray, fromIndex: number, toIndex: number): void {
// const dir = toIndex > fromIndex ? 1 : -1;
// const item = formArray.at(fromIndex);
// for (let i = fromIndex; i * dir < toIndex * dir; i = i + dir) {
// const current = formArray.at(i + dir);
// formArray.setControl(i, current);
// }
// formArray.setControl(toIndex, item);
// }
// // clearForm(): void{
// // this.descriptionTemplatesFormGroup.reset();
// // }
// // onPreviewTemplate(event, sectionIndex: number) {
// // const dialogRef = this.dialog.open(DatasetPreviewDialogComponent, {
// // width: '590px',
// // minHeight: '200px',
// // restoreFocus: false,
// // data: {
// // template: event
// // },
// // panelClass: 'custom-modalbox'
// // });
// // dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
// // if (result) {
// // let blueprints = this.sectionsArray().at(sectionIndex).get('descriptionTemplates').value;//this.formGroup.get('blueprints').value;
// // const blueprint: DescriptionTemplatesInSectionEditor = new DescriptionTemplatesInSectionEditor();
// // blueprint.id = Guid.create().toString();
// // blueprint.descriptionTemplateId = event.id;
// // blueprint.label = event.label;
// // blueprints.push(blueprint.buildForm());
// // this.sectionsArray().at(sectionIndex).get('descriptionTemplates').setValue(blueprints);//this.formGroup.get('blueprints').setValue(blueprints);
// // this.blueprintsAutoCompleteConfiguration = {
// // filterFn: this.filterProfiles.bind(this),
// // initialItems: (excludedItems: any[]) => this.filterProfiles('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
// // displayFn: (item) => item['label'],
// // titleFn: (item) => item['label'],
// // subtitleFn: (item) => item['description'],
// // popupItemActionIcon: 'visibility'
// // };
// // }
// // });
// // }
// checkValidity() {
// this.formService.touchAllFormFields(this.formGroup);
// if (!this.isFormValid()) { return false; }
// let errorMessages = [];
// if (!this.hasTitle()) {
// errorMessages.push("Title should be set.");
// }
// if (!this.hasDescription()) {
// errorMessages.push("Description should be set.");
// }
// if (!this.hasDescriptionTemplates()) {
// errorMessages.push("At least one section should have description templates.");
// }
// if (errorMessages.length > 0) {
// this.showValidationErrorsDialog(undefined, errorMessages);
// return false;
// }
// return true;
// }
// formSubmit(): void {
// if (this.checkValidity())
// this.onSubmit();
// }
// public isFormValid() {
// return this.formGroup.valid;
// }
// hasTitle(): boolean {
// const descriptionTemplate: DescriptionTemplatePersist = this.formGroup.value;
// return descriptionTemplate.definition.sections.some(section => section.fields.some(field => (field.category === DescriptionTemplateSectionFieldCategory.SYSTEM || field.category as unknown === DescriptionTemplateSectionFieldCategory.SYSTEM) && field.systemFieldType === DescriptionTemplateSystemFieldType.TEXT));
// }
// hasDescription(): boolean {
// const descriptionTemplate: DescriptionTemplatePersist = this.formGroup.value;
// return descriptionTemplate.definition.sections.some(section => section.fields.some(field => (field.category === DescriptionTemplateSectionFieldCategory.SYSTEM || field.category as unknown === DescriptionTemplateSectionFieldCategory.SYSTEM) && field.systemFieldType === DescriptionTemplateSystemFieldType.HTML_TEXT));
// }
// hasDescriptionTemplates(): boolean {
// const descriptionTemplate: DescriptionTemplatePersist = this.formGroup.value;
// return descriptionTemplate.definition.sections.some(section => section.hasTemplates == true);
// }
// private showValidationErrorsDialog(projectOnly?: boolean, errmess?: string[]) {
// const dialogRef = this.dialog.open(FormValidationErrorsDialogComponent, {
// disableClose: true,
// autoFocus: false,
// restoreFocus: false,
// data: {
// errorMessages: errmess,
// projectOnly: projectOnly
// },
// });
// }
// onSubmit(): void {
// this.descriptionTemplateService.createBlueprint(this.formGroup.value)
// .pipe(takeUntil(this._destroyed))
// .subscribe(
// complete => this.onCallbackSuccess(),
// error => this.onCallbackError(error)
// );
// }
// onCallbackSuccess(): void {
// this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
// this.router.navigate(['/description-templates']);
// }
// onCallbackError(errorResponse: any) {
// this.setErrorModel(errorResponse.error);
// this.formService.validateAllFormFields(this.formGroup);
// }
// public setErrorModel(validationErrorModel: ValidationErrorModel) {
// Object.keys(validationErrorModel).forEach(item => {
// (<any>this.descriptionTemplateEditor.validationErrorModel)[item] = (<any>validationErrorModel)[item];
// });
// }
public cancel(): void {
this.router.navigate(['/description-templates']);
}
// // addField() {
// // (<FormArray>this.formGroup.get('definition').get('fields')).push(new DescriptionTemplateFieldEditorModel().buildForm());
// // }
// // removeField(index: number) {
// // (<FormArray>this.formGroup.get('definition').get('fields')).controls.splice(index, 1);
// // }
// getDescriptionTemplateFieldDataTypeValues(): Number[] {
// let keys: string[] = Object.keys(DescriptionTemplateFieldDataType);
// keys = keys.slice(0, keys.length / 2);
// const values: Number[] = keys.map(Number);
// return values;
// }
// getDescriptionTemplateFieldDataTypeWithLanguage(fieldType: DescriptionTemplateFieldDataType): string {
// let result = '';
// this.language.get(this.enumUtils.toDescriptionTemplateFieldDataTypeString(fieldType))
// .pipe(takeUntil(this._destroyed))
// .subscribe((value: string) => {
// result = value;
// });
// return result;
// }
// getDescriptionTemplateFieldTypeValues(): Number[] {
// let keys: string[] = Object.keys(DescriptionTemplateType);
// keys = keys.slice(0, keys.length / 2);
// const values: Number[] = keys.map(Number);
// return values;
// }
// getDescriptionTemplateFieldTypeWithLanguage(blueprintType: DescriptionTemplateType): string {
// let result = '';
// this.language.get(this.enumUtils.toDescriptionTemplateTypeString(blueprintType))
// .pipe(takeUntil(this._destroyed))
// .subscribe((value: string) => {
// result = value;
// });
// return result;
// }
// delete() {
// this.dialog.open(ConfirmationDialogComponent, {
// data: {
// isDeleteConfirmation: true,
// confirmButton: this.language.instant('DESCRIPTION-TEMPLATE-EDITOR.CONFIRM-DELETE-DIALOG.CONFIRM-BUTTON'),
// cancelButton: this.language.instant("DESCRIPTION-TEMPLATE-EDITOR.CONFIRM-DELETE-DIALOG.CANCEL-BUTTON"),
// message: this.language.instant("DESCRIPTION-TEMPLATE-EDITOR.CONFIRM-DELETE-DIALOG.MESSAGE")
// }
// })
// .afterClosed()
// .subscribe(
// confirmed => {
// if (confirmed) {
// if (this.formGroup.get('status').value == DescriptionTemplateStatus.Draft) {
// // this.formGroup.get('status').setValue(DescriptionTemplateStatus.Deleted);
// this.descriptionTemplateService.createBlueprint(this.formGroup.value)
// .pipe(takeUntil(this._destroyed))
// .subscribe(
// complete => this.onCallbackSuccess(),
// error => this.onCallbackError(error)
// );
// }
// else {
// // this.descriptionTemplateService.delete(this.descriptionTemplateId)
// // .pipe(takeUntil(this._destroyed))
// // .subscribe(
// // complete => this.onCallbackSuccess(),
// // error => {
// // if (error.error.statusCode == 674) {
// // this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DESCRIPTION-TEMPLATE-DELETE'), SnackBarNotificationLevel.Error);
// // } else {
// // this.uiNotificationService.snackBarNotification(this.language.instant(error.message), SnackBarNotificationLevel.Error);
// // }
// // }
// // );
// }
// }
// }
// )
// }
2023-10-31 10:19:52 +01:00
// finalize() {
// if (this.checkValidity()) {
// this.formGroup.get('status').setValue(DescriptionTemplateStatus.Finalized);
// this.formSubmit();
// }
// }
2023-10-31 10:19:52 +01:00
// downloadXML(): void {
// const blueprintId = this.formGroup.get('id').value;
// if (blueprintId == null) return;
// this.descriptionTemplateService.downloadXML(blueprintId)
// .pipe(takeUntil(this._destroyed))
// .subscribe(response => {
// const blob = new Blob([response.body], { type: 'application/xml' });
// const filename = this.fileUtils.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
2023-10-31 10:19:52 +01:00
// FileSaver.saveAs(blob, filename);
// });
// }
}