diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DescriptionTemplateTypeDaoImpl.java b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DescriptionTemplateTypeDaoImpl.java index 2f0cac2f2..f93afb383 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DescriptionTemplateTypeDaoImpl.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/dao/entities/DescriptionTemplateTypeDaoImpl.java @@ -3,7 +3,6 @@ package eu.eudat.data.dao.entities; import eu.eudat.data.dao.DatabaseAccess; import eu.eudat.data.dao.databaselayer.service.DatabaseService; import eu.eudat.data.entities.DescriptionTemplateType; -import eu.eudat.data.entities.EntityDoi; import eu.eudat.queryable.QueryableList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; @@ -23,7 +22,12 @@ public class DescriptionTemplateTypeDaoImpl extends DatabaseAccess builder.equal(root.get("name"), name)).getSingle(); + try { + return this.getDatabaseService().getQueryable(DescriptionTemplateType.class).where((builder, root) -> builder.equal(root.get("name"), name)).getSingle(); + } + catch(Exception e){ + return null; + } } @Override @@ -44,7 +48,7 @@ public class DescriptionTemplateTypeDaoImpl extends DatabaseAccess asQueryable() { - return this.getDatabaseService().getQueryable(DescriptionTemplateType.class); + return this.getDatabaseService().getQueryable(DescriptionTemplateType.class).where((builder, root) -> builder.notEqual((root.get("status")), DescriptionTemplateType.Status.DELETED.getValue())); } @Async diff --git a/dmp-backend/data/src/main/java/eu/eudat/data/entities/DescriptionTemplateType.java b/dmp-backend/data/src/main/java/eu/eudat/data/entities/DescriptionTemplateType.java index e4d8d6257..40a755c2f 100644 --- a/dmp-backend/data/src/main/java/eu/eudat/data/entities/DescriptionTemplateType.java +++ b/dmp-backend/data/src/main/java/eu/eudat/data/entities/DescriptionTemplateType.java @@ -11,6 +11,32 @@ import java.util.UUID; @Table(name = "\"DescriptionTemplateType\"") public class DescriptionTemplateType implements DataEntity { + public enum Status { + SAVED((short) 0), FINALIZED((short) 1), DELETED((short) 99); + + private short value; + + private Status(short value) { + this.value = value; + } + public short getValue() { + return value; + } + + public static Status fromInteger(int value) { + switch (value) { + case 0: + return SAVED; + case 1: + return FINALIZED; + case 99: + return DELETED; + default: + throw new RuntimeException("Unsupported Description Template Type Status"); + } + } + } + @Id @GeneratedValue @GenericGenerator(name = "uuid2", strategy = "uuid2") @@ -20,6 +46,9 @@ public class DescriptionTemplateType implements DataEntity> createOrUpdate(@RequestBody String type, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { - this.descriptionTemplateTypeManager.create(type); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); + ResponseEntity> create(@RequestBody DescriptionTemplateTypeModel type, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + try { + this.descriptionTemplateTypeManager.create(type); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); + } + catch(DescriptionTemplatesWithTypeException e){ + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); + } + } + + @Transactional + @RequestMapping(method = RequestMethod.POST, value = {"update"}, produces = "application/json") + public @ResponseBody + ResponseEntity> update(@RequestBody DescriptionTemplateTypeModel type, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + try { + this.descriptionTemplateTypeManager.update(type); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Updated")); + } + catch(DescriptionTemplatesWithTypeException e){ + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); + } } @RequestMapping(method = RequestMethod.GET, value = {"get"}, produces = "application/json") public @ResponseBody - ResponseEntity>> get(@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { - DataTableData dataTable = this.descriptionTemplateTypeManager.get(); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + ResponseEntity>> get(@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + DataTableData dataTable = this.descriptionTemplateTypeManager.get(); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); + } + + @RequestMapping(method = RequestMethod.GET, value = {"get/{id}"}, produces = "application/json") + public @ResponseBody + ResponseEntity> getSingle(@PathVariable(value = "id") UUID id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { + try { + DescriptionTemplateTypeModel typeModel = this.descriptionTemplateTypeManager.getSingle(id); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).payload(typeModel)); + } + catch(DescriptionTemplatesWithTypeException e){ + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage())); + } } @Transactional @RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json") public @ResponseBody - ResponseEntity> delete(@PathVariable(value = "id") UUID id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { + ResponseEntity> delete(@PathVariable(value = "id") UUID id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { try{ this.descriptionTemplateTypeManager.delete(id); - return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted")); + return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted")); } catch(DescriptionTemplatesWithTypeException e){ - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.UNSUCCESS_DELETE).message(e.getMessage())); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.UNSUCCESS_DELETE).message(e.getMessage())); } } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DescriptionTemplateTypeManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DescriptionTemplateTypeManager.java index 046c7bebd..1dda78fdb 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DescriptionTemplateTypeManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/DescriptionTemplateTypeManager.java @@ -4,6 +4,7 @@ import eu.eudat.data.entities.DescriptionTemplateType; import eu.eudat.exceptions.descriptiontemplate.DescriptionTemplatesWithTypeException; import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.operations.DatabaseRepository; +import eu.eudat.models.data.descriptiontemplatetype.DescriptionTemplateTypeModel; import eu.eudat.models.data.helpers.common.DataTableData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,6 +13,7 @@ import org.springframework.stereotype.Component; import java.util.List; import java.util.UUID; +import java.util.stream.Collectors; @Component public class DescriptionTemplateTypeManager { @@ -27,31 +29,52 @@ public class DescriptionTemplateTypeManager { this.databaseRepository = databaseRepository; } - public DataTableData get() { + public DataTableData get() { List types = this.databaseRepository.getDescriptionTemplateTypeDao().asQueryable().toList(); - DataTableData dataTableData = new DataTableData<>(); - dataTableData.setData(types); - dataTableData.setTotalCount((long) types.size()); + List typesModelList = types.stream().map(type -> new DescriptionTemplateTypeModel().fromDataModel(type)).collect(Collectors.toList()); + DataTableData dataTableData = new DataTableData<>(); + dataTableData.setData(typesModelList); + dataTableData.setTotalCount((long) typesModelList.size()); return dataTableData; } - public DescriptionTemplateType create(String name) { - DescriptionTemplateType type = this.databaseRepository.getDescriptionTemplateTypeDao().findFromName(name); - if (type == null) { - type = new DescriptionTemplateType(); - type.setId(UUID.randomUUID()); - type.setName(name); - this.databaseRepository.getDescriptionTemplateTypeDao().createOrUpdate(type); + public DescriptionTemplateTypeModel getSingle(UUID id) throws Exception { + DescriptionTemplateType type = this.databaseRepository.getDescriptionTemplateTypeDao().find(id); + if (type != null) { + return new DescriptionTemplateTypeModel().fromDataModel(type); + } + else { + throw new DescriptionTemplatesWithTypeException("No description template type found with this id"); + } + } + + public void create(DescriptionTemplateTypeModel type) throws Exception { + DescriptionTemplateType existed = this.databaseRepository.getDescriptionTemplateTypeDao().findFromName(type.getName()); + if (existed == null) { + this.databaseRepository.getDescriptionTemplateTypeDao().createOrUpdate(type.toDataModel()); + } + else { + throw new DescriptionTemplatesWithTypeException("There is already a description template type with that name."); + } + } + + public void update(DescriptionTemplateTypeModel type) throws Exception { + DescriptionTemplateType existed = this.databaseRepository.getDescriptionTemplateTypeDao().findFromName(type.getName()); + if (existed != null) { + this.databaseRepository.getDescriptionTemplateTypeDao().createOrUpdate(type.toDataModel()); + } + else { + throw new DescriptionTemplatesWithTypeException("No description template type found."); } - return type; } public void delete(UUID id) throws DescriptionTemplatesWithTypeException { DescriptionTemplateType type = this.databaseRepository.getDescriptionTemplateTypeDao().find(id); if (type != null) { - Long descriptionsWithType = this.databaseRepository.getDatasetProfileDao().countWithType(type.getId()); + Long descriptionsWithType = this.databaseRepository.getDatasetProfileDao().countWithType(type); if(descriptionsWithType == 0) { - this.databaseRepository.getDescriptionTemplateTypeDao().delete(type); + type.setStatus(DescriptionTemplateType.Status.DELETED.getValue()); + this.databaseRepository.getDescriptionTemplateTypeDao().createOrUpdate(type); } else{ throw new DescriptionTemplatesWithTypeException("This type can not deleted, because Descriptions are associated with it"); diff --git a/dmp-backend/web/src/main/java/eu/eudat/models/data/descriptiontemplatetype/DescriptionTemplateTypeModel.java b/dmp-backend/web/src/main/java/eu/eudat/models/data/descriptiontemplatetype/DescriptionTemplateTypeModel.java new file mode 100644 index 000000000..272d405e1 --- /dev/null +++ b/dmp-backend/web/src/main/java/eu/eudat/models/data/descriptiontemplatetype/DescriptionTemplateTypeModel.java @@ -0,0 +1,56 @@ +package eu.eudat.models.data.descriptiontemplatetype; + +import eu.eudat.data.entities.DescriptionTemplateType; +import eu.eudat.models.DataModel; + +import java.util.UUID; + +public class DescriptionTemplateTypeModel implements DataModel { + + private UUID id; + private String name; + private short status; + + public UUID getId() { + return id; + } + public void setId(UUID id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public short getStatus() { + return status; + } + public void setStatus(short status) { + this.status = status; + } + + @Override + public DescriptionTemplateTypeModel fromDataModel(DescriptionTemplateType entity) { + this.id = entity.getId(); + this.name = entity.getName(); + this.status = entity.getStatus(); + return this; + } + + @Override + public DescriptionTemplateType toDataModel() throws Exception { + DescriptionTemplateType descriptionTemplateType = new DescriptionTemplateType(); + descriptionTemplateType.setId(this.id); + descriptionTemplateType.setName(this.name); + descriptionTemplateType.setStatus(this.status); + return descriptionTemplateType; + } + + @Override + public String getHint() { + return null; + } +} diff --git a/dmp-db-scema/main/data-dump.sql b/dmp-db-scema/main/data-dump.sql index df53ce588..f2c09c5d9 100644 --- a/dmp-db-scema/main/data-dump.sql +++ b/dmp-db-scema/main/data-dump.sql @@ -20,6 +20,6 @@ UPDATE public."DMP" UPDATE public."DescriptionTemplate" SET "Language"='en'; -INSERT INTO public."DescriptionTemplateType"("ID", "Name") VALUES (uuid_generate_v4(), 'Dataset'); +INSERT INTO public."DescriptionTemplateType"("ID", "Name", "Status") VALUES (uuid_generate_v4(), 'Dataset', 1); INSERT INTO public."DBVersion" VALUES ('DMPDB', '00.00.007', '2020-10-27 13:40:00.000000+03', now(), 'Add userstatus on UserInfo table'); \ No newline at end of file diff --git a/dmp-db-scema/main/dmp-dump.sql b/dmp-db-scema/main/dmp-dump.sql index eb4a61049..4e09de7e5 100644 --- a/dmp-db-scema/main/dmp-dump.sql +++ b/dmp-db-scema/main/dmp-dump.sql @@ -307,7 +307,8 @@ ALTER TABLE public."DatasetExternalDataset" OWNER TO :POSTGRES_USER; CREATE TABLE public."DescriptionTemplateType" ( "ID" uuid DEFAULT public.uuid_generate_v4() NOT NULL, - "Name" character varying(250) NOT NULL + "Name" character varying(250) NOT NULL, + "Status" smallint DEFAULT 0 NOT NULL ); diff --git a/dmp-db-scema/updates/00.00.013_Add_Description_Template_Type_table.sql b/dmp-db-scema/updates/00.00.013_Add_Description_Template_Type_table.sql index 91890f9f0..2df4e63a1 100644 --- a/dmp-db-scema/updates/00.00.013_Add_Description_Template_Type_table.sql +++ b/dmp-db-scema/updates/00.00.013_Add_Description_Template_Type_table.sql @@ -9,6 +9,7 @@ CREATE TABLE public."DescriptionTemplateType" ( "ID" uuid NOT NULL, "Name" character varying(250) NOT NULL, + "Status" smallint DEFAULT 0 NOT NULL, CONSTRAINT "DescriptionTemplateType_pkey" PRIMARY KEY ("ID") ); diff --git a/dmp-db-scema/updates/00.00.014_Rename_DatasetProfile_and_add_Type_column.sql b/dmp-db-scema/updates/00.00.014_Rename_DatasetProfile_and_add_Type_column.sql index 8917c5d8c..1be73da3c 100644 --- a/dmp-db-scema/updates/00.00.014_Rename_DatasetProfile_and_add_Type_column.sql +++ b/dmp-db-scema/updates/00.00.014_Rename_DatasetProfile_and_add_Type_column.sql @@ -10,8 +10,8 @@ RENAME TO "DescriptionTemplate"; ALTER TABLE public."DescriptionTemplate" ADD COLUMN "Type" uuid; -INSERT INTO public."DescriptionTemplateType" ("ID", "Name") -VALUES ('709a8400-10ca-11ee-be56-0242ac120002', 'Dataset'); +INSERT INTO public."DescriptionTemplateType" ("ID", "Name", "Status") +VALUES ('709a8400-10ca-11ee-be56-0242ac120002', 'Dataset', 1); UPDATE public."DescriptionTemplate" SET ("Type") = '709a8400-10ca-11ee-be56-0242ac120002'; diff --git a/dmp-frontend/src/app/core/common/enum/description-template-type-status.ts b/dmp-frontend/src/app/core/common/enum/description-template-type-status.ts new file mode 100644 index 000000000..e41dc95b9 --- /dev/null +++ b/dmp-frontend/src/app/core/common/enum/description-template-type-status.ts @@ -0,0 +1,5 @@ +export enum DescriptionTemplateTypeStatus { + Draft = 0, + Finalized = 1, + Deleted = 99 +} \ No newline at end of file diff --git a/dmp-frontend/src/app/core/model/description-template-type/description-template-type.ts b/dmp-frontend/src/app/core/model/description-template-type/description-template-type.ts index 08f9df8a8..1b2812e09 100644 --- a/dmp-frontend/src/app/core/model/description-template-type/description-template-type.ts +++ b/dmp-frontend/src/app/core/model/description-template-type/description-template-type.ts @@ -1,4 +1,5 @@ export interface DescriptionTemplateType { id: string; name: string; + status: number; } \ No newline at end of file diff --git a/dmp-frontend/src/app/core/services/description-template-type/description-template-type.service.ts b/dmp-frontend/src/app/core/services/description-template-type/description-template-type.service.ts index dc6859f30..a40b02569 100644 --- a/dmp-frontend/src/app/core/services/description-template-type/description-template-type.service.ts +++ b/dmp-frontend/src/app/core/services/description-template-type/description-template-type.service.ts @@ -20,8 +20,16 @@ export class DescriptionTemplateTypeService { return this.http.get>(this.actionUrl + 'get', { headers: this.headers }); } - createType(name: string): Observable { - return this.http.post(this.actionUrl + 'create', name, { headers: this.headers }); + getSingle(id: string): Observable { + return this.http.get(this.actionUrl + 'get/' + id, { headers: this.headers }); + } + + createType(type: DescriptionTemplateType): Observable { + return this.http.post(this.actionUrl + 'create', type, { headers: this.headers }); + } + + updateType(type: DescriptionTemplateType): Observable { + return this.http.post(this.actionUrl + 'update', type, { headers: this.headers }); } deleteType(id: string): Observable { diff --git a/dmp-frontend/src/app/ui/admin/dataset-profile/editor/dataset-profile-editor.component.ts b/dmp-frontend/src/app/ui/admin/dataset-profile/editor/dataset-profile-editor.component.ts index 7892340cc..904ab51ad 100644 --- a/dmp-frontend/src/app/ui/admin/dataset-profile/editor/dataset-profile-editor.component.ts +++ b/dmp-frontend/src/app/ui/admin/dataset-profile/editor/dataset-profile-editor.component.ts @@ -47,6 +47,7 @@ import { MatInput } from '@angular/material/input'; import { CheckDeactivateBaseComponent } from '@app/library/deactivate/deactivate.component'; import { DescriptionTemplateTypeService } from '@app/core/services/description-template-type/description-template-type.service'; import { DescriptionTemplateType } from '@app/core/model/description-template-type/description-template-type'; +import { DescriptionTemplateTypeStatus } from '@app/core/common/enum/description-template-type-status'; const skipDisable: any[] = require('../../../../../assets/resources/skipDisable.json'); @@ -608,7 +609,7 @@ export class DatasetProfileEditorComponent extends CheckDeactivateBaseComponent getDescriptionTemplateTypes(): DescriptionTemplateType[] { this.descriptionTemplateTypeService.getTypes().pipe(takeUntil(this._destroyed)) .subscribe(types => { - this.descriptionTemplateTypes = types.data; + this.descriptionTemplateTypes = types.data.filter(type => type.status === DescriptionTemplateTypeStatus.Finalized); }); return this.descriptionTemplateTypes; } diff --git a/dmp-frontend/src/app/ui/admin/description-types/description-types.module.ts b/dmp-frontend/src/app/ui/admin/description-types/description-types.module.ts index 1a91c9cee..2871d2c57 100644 --- a/dmp-frontend/src/app/ui/admin/description-types/description-types.module.ts +++ b/dmp-frontend/src/app/ui/admin/description-types/description-types.module.ts @@ -4,6 +4,7 @@ import { DescriptionTypesRoutingModule } from './description-types.routing'; import { DescriptionTypesComponent } from './listing/description-types.component'; import { CommonUiModule } from '@common/ui/common-ui.module'; import { DescriptionTypeEditorComponent } from './editor/description-type-editor.component'; +import { CommonFormsModule } from '@common/forms/common-forms.module'; @NgModule({ declarations: [ @@ -13,6 +14,7 @@ import { DescriptionTypeEditorComponent } from './editor/description-type-editor imports: [ CommonModule, CommonUiModule, + CommonFormsModule, DescriptionTypesRoutingModule ] }) diff --git a/dmp-frontend/src/app/ui/admin/description-types/editor/description-type-editor.component.html b/dmp-frontend/src/app/ui/admin/description-types/editor/description-type-editor.component.html index d55b295fc..6c818cfab 100644 --- a/dmp-frontend/src/app/ui/admin/description-types/editor/description-type-editor.component.html +++ b/dmp-frontend/src/app/ui/admin/description-types/editor/description-type-editor.component.html @@ -24,7 +24,9 @@
- +
diff --git a/dmp-frontend/src/app/ui/admin/description-types/editor/description-type-editor.component.ts b/dmp-frontend/src/app/ui/admin/description-types/editor/description-type-editor.component.ts index 118a226df..b430fc263 100644 --- a/dmp-frontend/src/app/ui/admin/description-types/editor/description-type-editor.component.ts +++ b/dmp-frontend/src/app/ui/admin/description-types/editor/description-type-editor.component.ts @@ -1,10 +1,15 @@ -import { AfterViewInit, Component } from '@angular/core'; +import { AfterViewInit, Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; -import { Router } from '@angular/router'; +import { ActivatedRoute, ParamMap, Router } from '@angular/router'; +import { DescriptionTemplateTypeStatus } from '@app/core/common/enum/description-template-type-status'; +import { DescriptionTemplateType } from '@app/core/model/description-template-type/description-template-type'; import { DescriptionTemplateTypeService } from '@app/core/services/description-template-type/description-template-type.service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; import { BaseComponent } from '@common/base/base.component'; import { FormService } from '@common/forms/form-service'; +import { BackendErrorValidator } from '@common/forms/validation/custom-validator'; +import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model'; +import { ValidationContext } from '@common/forms/validation/validation-context'; import { TranslateService } from '@ngx-translate/core'; import { takeUntil } from 'rxjs/operators'; @@ -13,25 +18,52 @@ import { takeUntil } from 'rxjs/operators'; templateUrl: './description-type-editor.component.html', styleUrls: ['./description-type-editor.component.scss'] }) -export class DescriptionTypeEditorComponent extends BaseComponent implements AfterViewInit { +export class DescriptionTypeEditorComponent extends BaseComponent implements OnInit { formGroup: FormGroup = null; - descriptionTypeModel: DescriptionTypeEditorModel + descriptionTypeModel: DescriptionTypeEditorModel; + + isNew = true; + viewOnly = false; + descriptionTemplateTypeId: string; constructor( private descriptionTemplateTypeService: DescriptionTemplateTypeService, private formService: FormService, private uiNotificationService: UiNotificationService, private language: TranslateService, + private route: ActivatedRoute, private router: Router ) { super(); } - ngAfterViewInit(): void { - this.descriptionTypeModel = new DescriptionTypeEditorModel(); - setTimeout(() => { - this.formGroup = this.descriptionTypeModel.buildForm(); + ngOnInit(): void { + this.route.paramMap.pipe(takeUntil(this._destroyed)).subscribe((paramMap: ParamMap) => { + this.descriptionTemplateTypeId = paramMap.get('id'); + + if (this.descriptionTemplateTypeId != null) { + this.isNew = false; + this.descriptionTemplateTypeService.getSingle(this.descriptionTemplateTypeId) + .pipe(takeUntil(this._destroyed)).subscribe( + type => { + this.descriptionTypeModel = new DescriptionTypeEditorModel().fromModel(type); + if(this.descriptionTypeModel.status === DescriptionTemplateTypeStatus.Finalized){ + this.formGroup = this.descriptionTypeModel.buildForm(null, true); + this.viewOnly = true; + } + else{ + this.formGroup = this.descriptionTypeModel.buildForm(); + } + }, + error => this.uiNotificationService.snackBarNotification(error.message, SnackBarNotificationLevel.Error) + ); + } + else { + this.descriptionTypeModel = new DescriptionTypeEditorModel(); + this.descriptionTypeModel.status = DescriptionTemplateTypeStatus.Draft; + this.formGroup = this.descriptionTypeModel.buildForm(); + } }); } @@ -45,27 +77,53 @@ export class DescriptionTypeEditorComponent extends BaseComponent implements Aft return this.formGroup.valid; } - onSubmit(): void { - console.log(this.formGroup.value); - this.descriptionTemplateTypeService.createType(this.formGroup.value) - .pipe(takeUntil(this._destroyed)) - .subscribe( - complete => this.onCallbackSuccess(), - error => this.onCallbackError(error) - ); + finalize() { + this.formGroup.get('status').setValue(DescriptionTemplateTypeStatus.Finalized); + this.onSubmit(); } - onCallbackSuccess(): void { - this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION'), SnackBarNotificationLevel.Success); + onSubmit(): void { + if(this.isNew){ + this.descriptionTemplateTypeService.createType(this.formGroup.value) + .pipe(takeUntil(this._destroyed)) + .subscribe( + complete => this.onCallbackSuccess(true), + error => this.onCallbackError(error) + ); + } + else{ + this.descriptionTemplateTypeService.updateType(this.formGroup.value) + .pipe(takeUntil(this._destroyed)) + .subscribe( + complete => this.onCallbackSuccess(false), + error => this.onCallbackError(error) + ); + } + } + + onCallbackSuccess(creation: boolean): void { + if(creation){ + this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION'), SnackBarNotificationLevel.Success); + } + else{ + this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success); + } this.router.navigate(['/description-types']); } onCallbackError(errorResponse: any) { - // this.setErrorModel(errorResponse.error); - // this.formService.validateAllFormFields(this.formGroup); + this.setErrorModel(errorResponse.error); + this.formService.validateAllFormFields(this.formGroup); + this.uiNotificationService.snackBarNotification(errorResponse.error.message, SnackBarNotificationLevel.Error); } - public cancel(): void { + public setErrorModel(validationErrorModel: ValidationErrorModel) { + Object.keys(validationErrorModel).forEach(item => { + (this.descriptionTypeModel.validationErrorModel)[item] = (validationErrorModel)[item]; + }); + } + + public cancel(): void { this.router.navigate(['/description-types']); } @@ -74,12 +132,30 @@ export class DescriptionTypeEditorComponent extends BaseComponent implements Aft export class DescriptionTypeEditorModel { public id: string; public name: string; + public status: DescriptionTemplateTypeStatus; + public validationErrorModel: ValidationErrorModel = new ValidationErrorModel(); - buildForm(): FormGroup { + fromModel(item: DescriptionTemplateType): DescriptionTypeEditorModel { + this.id = item.id; + this.name = item.name; + this.status = item.status; + return this; + } + + buildForm(context: ValidationContext = null, disabled: boolean = false): FormGroup { + if (context == null) { context = this.createValidationContext(); } const formGroup = new FormBuilder().group({ id: [this.id], - name: [this.name, Validators.required], + name: [{ value: this.name, disabled: disabled }, context.getValidation('name').validators], + status: [{ value: this.status, disabled: disabled }, context.getValidation('status').validators] }); return formGroup; } + + createValidationContext(): ValidationContext { + const baseContext: ValidationContext = new ValidationContext(); + baseContext.validation.push({ key: 'name', validators: [Validators.required, BackendErrorValidator(this.validationErrorModel, 'name')] }); + baseContext.validation.push({ key: 'status', validators: [Validators.required, BackendErrorValidator(this.validationErrorModel, 'status')] }); + return baseContext; + } } diff --git a/dmp-frontend/src/app/ui/admin/description-types/listing/description-types.component.html b/dmp-frontend/src/app/ui/admin/description-types/listing/description-types.component.html index bebfd44bc..27311bafe 100644 --- a/dmp-frontend/src/app/ui/admin/description-types/listing/description-types.component.html +++ b/dmp-frontend/src/app/ui/admin/description-types/listing/description-types.component.html @@ -28,7 +28,7 @@ {{'DESCRIPTION-TYPES-LISTING.COLUMNS.STATUS' | translate}} -
{{ 'DATASET-PROFILE-STATUS.FINALIZED' | translate}}
+
{{parseStatus(row.status) | translate}}
@@ -41,10 +41,10 @@ - + - + diff --git a/dmp-frontend/src/app/ui/admin/description-types/listing/description-types.component.ts b/dmp-frontend/src/app/ui/admin/description-types/listing/description-types.component.ts index d86fbbac9..99c79b984 100644 --- a/dmp-frontend/src/app/ui/admin/description-types/listing/description-types.component.ts +++ b/dmp-frontend/src/app/ui/admin/description-types/listing/description-types.component.ts @@ -4,6 +4,8 @@ import { Component, OnInit, ViewChild } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; +import { Router } from '@angular/router'; +import { DescriptionTemplateType } from '@app/core/model/description-template-type/description-template-type'; import { DescriptionTemplateTypeService } from '@app/core/services/description-template-type/description-template-type.service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; import { BaseComponent } from '@common/base/base.component'; @@ -25,11 +27,17 @@ export class DescriptionTypesComponent extends BaseComponent implements OnInit { dataSource: DescriptionTypesDataSource | null; displayedColumns: String[] = ['label', 'status', 'delete']; + statuses = [ + { value: '0', viewValue: 'DESCRIPTION-TYPES-LISTING.STATUS.DRAFT' }, + { value: '1', viewValue: 'DESCRIPTION-TYPES-LISTING.STATUS.FINALIZED' } + ]; + constructor( private descriptionTemplateTypeService: DescriptionTemplateTypeService, private dialog: MatDialog, private language: TranslateService, - private uiNotificationService: UiNotificationService + private uiNotificationService: UiNotificationService, + private router: Router ) { super(); } @@ -42,6 +50,19 @@ export class DescriptionTypesComponent extends BaseComponent implements OnInit { this.dataSource = new DescriptionTypesDataSource(this.descriptionTemplateTypeService, this._paginator, this.sort/*, this.criteria*/); } + rowClick(rowId: String) { + this.router.navigate(['description-types/' + rowId]); + } + + parseStatus(value: number): string{ + const stringVal = value.toString() + try{ + return this.statuses.find(status => status.value === stringVal).viewValue; + }catch{ + return stringVal; + } + } + deleteTemplate(id: string){ if(id){ const dialogRef = this.dialog.open(ConfirmationDialogComponent, { @@ -56,25 +77,22 @@ export class DescriptionTypesComponent extends BaseComponent implements OnInit { dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { if (result) { - // this.descriptionTemplateTypeService.deleteType(id) - // .pipe(takeUntil(this._destroyed)) - // .subscribe( - // complete => { - // this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-DATASET-PROFILE-DELETE'), SnackBarNotificationLevel.Success); - // this.refresh(); - // }, - // error => { - // this.onCallbackError(error); - // if (error.error.statusCode == 674) { - // this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DATASET-PROFILE-DELETE'), SnackBarNotificationLevel.Error); - // } else { - // this.uiNotificationService.snackBarNotification(this.language.instant(error.message), SnackBarNotificationLevel.Error); - // } - // } - // ); - - this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DESCRIPTION-TEMPLATE-TYPE-DELETE'), SnackBarNotificationLevel.Error); - this.refresh(); + this.descriptionTemplateTypeService.deleteType(id) + .pipe(takeUntil(this._destroyed)) + .subscribe( + complete => { + this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-DATASET-PROFILE-DELETE'), SnackBarNotificationLevel.Success); + this.refresh(); + }, + error => { + this.onCallbackError(error); + if (error.error.statusCode == 674) { + this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DATASET-PROFILE-DELETE'), SnackBarNotificationLevel.Error); + } else { + this.uiNotificationService.snackBarNotification(this.language.instant(error.message), SnackBarNotificationLevel.Error); + } + } + ); } }); @@ -96,55 +114,38 @@ export class DescriptionTypesComponent extends BaseComponent implements OnInit { } -export interface DescriptionTemplateTypeListingModel { - id: string; - name: string; - status: number; -} - -export class DescriptionTypesDataSource extends DataSource { +export class DescriptionTypesDataSource extends DataSource { totalCount = 0; constructor( private _service: DescriptionTemplateTypeService, private _paginator: MatPaginator, - private _sort: MatSort//, - //private _criteria: DmpProfileCriteriaComponent + private _sort: MatSort ) { super(); } - connect(): Observable { + connect(): Observable { const displayDataChanges = [ this._paginator.page //this._sort.matSortChange ]; - // return observableMerge(...displayDataChanges).pipe( - // startWith(null), - // switchMap(() => { - // // const startIndex = this._paginator.pageIndex * this._paginator.pageSize; - // // let fields: Array = new Array(); - // // if (this._sort.active) { fields = this._sort.direction === 'asc' ? ['+' + this._sort.active] : ['-' + this._sort.active]; } - // // const request = new DataTableRequest(startIndex, this._paginator.pageSize, { fields: fields }); - // // request.criteria = this._criteria.criteria; - // // return this._service.getPaged(request); - - // return this._service.getTypes(); - // }), - // map(result => { - // return result; - // }), - // map(result => { - // // if (!result) { return []; } - // // if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; } - // // return result.data; - // return result; - // })); - - return of([{id: '1234', name: 'Dataset', status: 0}]); + return observableMerge(...displayDataChanges).pipe( + startWith(null), + switchMap(() => { + return this._service.getTypes(); + }), + map(result => { + return result; + }), + map(result => { + if (!result) { return []; } + if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; } + return result.data; + })); } disconnect() { diff --git a/dmp-frontend/src/assets/i18n/en.json b/dmp-frontend/src/assets/i18n/en.json index e8a8b7b74..112291d9d 100644 --- a/dmp-frontend/src/assets/i18n/en.json +++ b/dmp-frontend/src/assets/i18n/en.json @@ -960,6 +960,10 @@ "NAME": "Name", "STATUS": "Status" }, + "STATUS":{ + "DRAFT": "Draft", + "FINALIZED": "Finalized" + }, "ACTIONS": { "DELETE": "Delete" } @@ -987,6 +991,7 @@ }, "ACTIONS": { "SAVE": "Save", + "FINALIZE": "Finalize", "CANCEL": "Cancel" } },