add status to description template types, fix bugs in editor/listing

This commit is contained in:
Bernaldo Mihasi 2023-09-11 08:40:03 +03:00
parent 3564cc16ff
commit cd80e78e40
19 changed files with 367 additions and 114 deletions

View File

@ -3,7 +3,6 @@ package eu.eudat.data.dao.entities;
import eu.eudat.data.dao.DatabaseAccess; import eu.eudat.data.dao.DatabaseAccess;
import eu.eudat.data.dao.databaselayer.service.DatabaseService; import eu.eudat.data.dao.databaselayer.service.DatabaseService;
import eu.eudat.data.entities.DescriptionTemplateType; import eu.eudat.data.entities.DescriptionTemplateType;
import eu.eudat.data.entities.EntityDoi;
import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.QueryableList;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
@ -23,7 +22,12 @@ public class DescriptionTemplateTypeDaoImpl extends DatabaseAccess<DescriptionTe
@Override @Override
public DescriptionTemplateType findFromName(String name){ public DescriptionTemplateType findFromName(String name){
return this.getDatabaseService().getQueryable(DescriptionTemplateType.class).where((builder, root) -> 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 @Override
@ -44,7 +48,7 @@ public class DescriptionTemplateTypeDaoImpl extends DatabaseAccess<DescriptionTe
@Override @Override
public QueryableList<DescriptionTemplateType> asQueryable() { public QueryableList<DescriptionTemplateType> 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 @Async

View File

@ -11,6 +11,32 @@ import java.util.UUID;
@Table(name = "\"DescriptionTemplateType\"") @Table(name = "\"DescriptionTemplateType\"")
public class DescriptionTemplateType implements DataEntity<DescriptionTemplateType, UUID> { public class DescriptionTemplateType implements DataEntity<DescriptionTemplateType, UUID> {
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 @Id
@GeneratedValue @GeneratedValue
@GenericGenerator(name = "uuid2", strategy = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2")
@ -20,6 +46,9 @@ public class DescriptionTemplateType implements DataEntity<DescriptionTemplateTy
@Column(name = "\"Name\"", nullable = false) @Column(name = "\"Name\"", nullable = false)
private String name; private String name;
@Column(name = "\"Status\"", nullable = false)
private Short status;
public UUID getId() { public UUID getId() {
return id; return id;
} }
@ -34,9 +63,17 @@ public class DescriptionTemplateType implements DataEntity<DescriptionTemplateTy
this.name = name; this.name = name;
} }
public Short getStatus() {
return status;
}
public void setStatus(Short status) {
this.status = status;
}
@Override @Override
public void update(DescriptionTemplateType entity) { public void update(DescriptionTemplateType entity) {
this.name = entity.name; this.name = entity.name;
this.status = entity.status;
} }
@Override @Override

View File

@ -1,10 +1,10 @@
package eu.eudat.controllers; package eu.eudat.controllers;
import eu.eudat.data.entities.DescriptionTemplateType;
import eu.eudat.exceptions.descriptiontemplate.DescriptionTemplatesWithTypeException; import eu.eudat.exceptions.descriptiontemplate.DescriptionTemplatesWithTypeException;
import eu.eudat.logic.managers.DescriptionTemplateTypeManager; import eu.eudat.logic.managers.DescriptionTemplateTypeManager;
import eu.eudat.logic.security.claims.ClaimedAuthorities; import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.descriptiontemplatetype.DescriptionTemplateTypeModel;
import eu.eudat.models.data.helpers.common.DataTableData; import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem; import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal; import eu.eudat.models.data.security.Principal;
@ -36,28 +36,58 @@ public class DescriptionTemplateTypeController extends BaseController {
@Transactional @Transactional
@RequestMapping(method = RequestMethod.POST, value = {"create"}, produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"create"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DescriptionTemplateType>> createOrUpdate(@RequestBody String type, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { ResponseEntity<ResponseItem<DescriptionTemplateTypeModel>> create(@RequestBody DescriptionTemplateTypeModel type, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
this.descriptionTemplateTypeManager.create(type); try {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DescriptionTemplateType>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created")); this.descriptionTemplateTypeManager.create(type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DescriptionTemplateTypeModel>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created"));
}
catch(DescriptionTemplatesWithTypeException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DescriptionTemplateTypeModel>().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage()));
}
}
@Transactional
@RequestMapping(method = RequestMethod.POST, value = {"update"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DescriptionTemplateTypeModel>> update(@RequestBody DescriptionTemplateTypeModel type, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
try {
this.descriptionTemplateTypeManager.update(type);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DescriptionTemplateTypeModel>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Updated"));
}
catch(DescriptionTemplatesWithTypeException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DescriptionTemplateTypeModel>().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage()));
}
} }
@RequestMapping(method = RequestMethod.GET, value = {"get"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"get"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataTableData<DescriptionTemplateType>>> get(@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception { ResponseEntity<ResponseItem<DataTableData<DescriptionTemplateTypeModel>>> get(@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
DataTableData<DescriptionTemplateType> dataTable = this.descriptionTemplateTypeManager.get(); DataTableData<DescriptionTemplateTypeModel> dataTable = this.descriptionTemplateTypeManager.get();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DescriptionTemplateType>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DescriptionTemplateTypeModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
}
@RequestMapping(method = RequestMethod.GET, value = {"get/{id}"}, produces = "application/json")
public @ResponseBody
ResponseEntity<ResponseItem<DescriptionTemplateTypeModel>> 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<DescriptionTemplateTypeModel>().status(ApiMessageCode.NO_MESSAGE).payload(typeModel));
}
catch(DescriptionTemplatesWithTypeException e){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem<DescriptionTemplateTypeModel>().status(ApiMessageCode.ERROR_MESSAGE).message(e.getMessage()));
}
} }
@Transactional @Transactional
@RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json") @RequestMapping(method = RequestMethod.DELETE, value = {"/delete/{id}"}, produces = "application/json")
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DescriptionTemplateType>> delete(@PathVariable(value = "id") UUID id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception { ResponseEntity<ResponseItem<DescriptionTemplateTypeModel>> delete(@PathVariable(value = "id") UUID id, @ClaimedAuthorities(claims = {ADMIN}) Principal principal) throws Exception {
try{ try{
this.descriptionTemplateTypeManager.delete(id); this.descriptionTemplateTypeManager.delete(id);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DescriptionTemplateType>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted")); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DescriptionTemplateTypeModel>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted"));
} }
catch(DescriptionTemplatesWithTypeException e){ catch(DescriptionTemplatesWithTypeException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DescriptionTemplateType>().status(ApiMessageCode.UNSUCCESS_DELETE).message(e.getMessage())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DescriptionTemplateTypeModel>().status(ApiMessageCode.UNSUCCESS_DELETE).message(e.getMessage()));
} }
} }

View File

@ -4,6 +4,7 @@ import eu.eudat.data.entities.DescriptionTemplateType;
import eu.eudat.exceptions.descriptiontemplate.DescriptionTemplatesWithTypeException; import eu.eudat.exceptions.descriptiontemplate.DescriptionTemplatesWithTypeException;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository; import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.models.data.descriptiontemplatetype.DescriptionTemplateTypeModel;
import eu.eudat.models.data.helpers.common.DataTableData; import eu.eudat.models.data.helpers.common.DataTableData;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -12,6 +13,7 @@ import org.springframework.stereotype.Component;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors;
@Component @Component
public class DescriptionTemplateTypeManager { public class DescriptionTemplateTypeManager {
@ -27,31 +29,52 @@ public class DescriptionTemplateTypeManager {
this.databaseRepository = databaseRepository; this.databaseRepository = databaseRepository;
} }
public DataTableData<DescriptionTemplateType> get() { public DataTableData<DescriptionTemplateTypeModel> get() {
List<DescriptionTemplateType> types = this.databaseRepository.getDescriptionTemplateTypeDao().asQueryable().toList(); List<DescriptionTemplateType> types = this.databaseRepository.getDescriptionTemplateTypeDao().asQueryable().toList();
DataTableData<DescriptionTemplateType> dataTableData = new DataTableData<>(); List<DescriptionTemplateTypeModel> typesModelList = types.stream().map(type -> new DescriptionTemplateTypeModel().fromDataModel(type)).collect(Collectors.toList());
dataTableData.setData(types); DataTableData<DescriptionTemplateTypeModel> dataTableData = new DataTableData<>();
dataTableData.setTotalCount((long) types.size()); dataTableData.setData(typesModelList);
dataTableData.setTotalCount((long) typesModelList.size());
return dataTableData; return dataTableData;
} }
public DescriptionTemplateType create(String name) { public DescriptionTemplateTypeModel getSingle(UUID id) throws Exception {
DescriptionTemplateType type = this.databaseRepository.getDescriptionTemplateTypeDao().findFromName(name); DescriptionTemplateType type = this.databaseRepository.getDescriptionTemplateTypeDao().find(id);
if (type == null) { if (type != null) {
type = new DescriptionTemplateType(); return new DescriptionTemplateTypeModel().fromDataModel(type);
type.setId(UUID.randomUUID()); }
type.setName(name); else {
this.databaseRepository.getDescriptionTemplateTypeDao().createOrUpdate(type); 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 { public void delete(UUID id) throws DescriptionTemplatesWithTypeException {
DescriptionTemplateType type = this.databaseRepository.getDescriptionTemplateTypeDao().find(id); DescriptionTemplateType type = this.databaseRepository.getDescriptionTemplateTypeDao().find(id);
if (type != null) { if (type != null) {
Long descriptionsWithType = this.databaseRepository.getDatasetProfileDao().countWithType(type.getId()); Long descriptionsWithType = this.databaseRepository.getDatasetProfileDao().countWithType(type);
if(descriptionsWithType == 0) { if(descriptionsWithType == 0) {
this.databaseRepository.getDescriptionTemplateTypeDao().delete(type); type.setStatus(DescriptionTemplateType.Status.DELETED.getValue());
this.databaseRepository.getDescriptionTemplateTypeDao().createOrUpdate(type);
} }
else{ else{
throw new DescriptionTemplatesWithTypeException("This type can not deleted, because Descriptions are associated with it"); throw new DescriptionTemplatesWithTypeException("This type can not deleted, because Descriptions are associated with it");

View File

@ -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<DescriptionTemplateType, DescriptionTemplateTypeModel> {
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;
}
}

View File

@ -20,6 +20,6 @@ UPDATE public."DMP"
UPDATE public."DescriptionTemplate" UPDATE public."DescriptionTemplate"
SET "Language"='en'; 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'); INSERT INTO public."DBVersion" VALUES ('DMPDB', '00.00.007', '2020-10-27 13:40:00.000000+03', now(), 'Add userstatus on UserInfo table');

View File

@ -307,7 +307,8 @@ ALTER TABLE public."DatasetExternalDataset" OWNER TO :POSTGRES_USER;
CREATE TABLE public."DescriptionTemplateType" ( CREATE TABLE public."DescriptionTemplateType" (
"ID" uuid DEFAULT public.uuid_generate_v4() NOT NULL, "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
); );

View File

@ -9,6 +9,7 @@ CREATE TABLE public."DescriptionTemplateType"
( (
"ID" uuid NOT NULL, "ID" uuid NOT NULL,
"Name" character varying(250) NOT NULL, "Name" character varying(250) NOT NULL,
"Status" smallint DEFAULT 0 NOT NULL,
CONSTRAINT "DescriptionTemplateType_pkey" PRIMARY KEY ("ID") CONSTRAINT "DescriptionTemplateType_pkey" PRIMARY KEY ("ID")
); );

View File

@ -10,8 +10,8 @@ RENAME TO "DescriptionTemplate";
ALTER TABLE public."DescriptionTemplate" ALTER TABLE public."DescriptionTemplate"
ADD COLUMN "Type" uuid; ADD COLUMN "Type" uuid;
INSERT INTO public."DescriptionTemplateType" ("ID", "Name") INSERT INTO public."DescriptionTemplateType" ("ID", "Name", "Status")
VALUES ('709a8400-10ca-11ee-be56-0242ac120002', 'Dataset'); VALUES ('709a8400-10ca-11ee-be56-0242ac120002', 'Dataset', 1);
UPDATE public."DescriptionTemplate" SET ("Type") = '709a8400-10ca-11ee-be56-0242ac120002'; UPDATE public."DescriptionTemplate" SET ("Type") = '709a8400-10ca-11ee-be56-0242ac120002';

View File

@ -0,0 +1,5 @@
export enum DescriptionTemplateTypeStatus {
Draft = 0,
Finalized = 1,
Deleted = 99
}

View File

@ -1,4 +1,5 @@
export interface DescriptionTemplateType { export interface DescriptionTemplateType {
id: string; id: string;
name: string; name: string;
status: number;
} }

View File

@ -20,8 +20,16 @@ export class DescriptionTemplateTypeService {
return this.http.get<DataTableData<DescriptionTemplateType>>(this.actionUrl + 'get', { headers: this.headers }); return this.http.get<DataTableData<DescriptionTemplateType>>(this.actionUrl + 'get', { headers: this.headers });
} }
createType(name: string): Observable<DescriptionTemplateType> { getSingle(id: string): Observable<DescriptionTemplateType> {
return this.http.post<DescriptionTemplateType>(this.actionUrl + 'create', name, { headers: this.headers }); return this.http.get<DescriptionTemplateType>(this.actionUrl + 'get/' + id, { headers: this.headers });
}
createType(type: DescriptionTemplateType): Observable<DescriptionTemplateType> {
return this.http.post<DescriptionTemplateType>(this.actionUrl + 'create', type, { headers: this.headers });
}
updateType(type: DescriptionTemplateType): Observable<DescriptionTemplateType> {
return this.http.post<DescriptionTemplateType>(this.actionUrl + 'update', type, { headers: this.headers });
} }
deleteType(id: string): Observable<DescriptionTemplateType> { deleteType(id: string): Observable<DescriptionTemplateType> {

View File

@ -47,6 +47,7 @@ import { MatInput } from '@angular/material/input';
import { CheckDeactivateBaseComponent } from '@app/library/deactivate/deactivate.component'; import { CheckDeactivateBaseComponent } from '@app/library/deactivate/deactivate.component';
import { DescriptionTemplateTypeService } from '@app/core/services/description-template-type/description-template-type.service'; 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 { 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'); const skipDisable: any[] = require('../../../../../assets/resources/skipDisable.json');
@ -608,7 +609,7 @@ export class DatasetProfileEditorComponent extends CheckDeactivateBaseComponent
getDescriptionTemplateTypes(): DescriptionTemplateType[] { getDescriptionTemplateTypes(): DescriptionTemplateType[] {
this.descriptionTemplateTypeService.getTypes().pipe(takeUntil(this._destroyed)) this.descriptionTemplateTypeService.getTypes().pipe(takeUntil(this._destroyed))
.subscribe(types => { .subscribe(types => {
this.descriptionTemplateTypes = types.data; this.descriptionTemplateTypes = types.data.filter(type => type.status === DescriptionTemplateTypeStatus.Finalized);
}); });
return this.descriptionTemplateTypes; return this.descriptionTemplateTypes;
} }

View File

@ -4,6 +4,7 @@ import { DescriptionTypesRoutingModule } from './description-types.routing';
import { DescriptionTypesComponent } from './listing/description-types.component'; import { DescriptionTypesComponent } from './listing/description-types.component';
import { CommonUiModule } from '@common/ui/common-ui.module'; import { CommonUiModule } from '@common/ui/common-ui.module';
import { DescriptionTypeEditorComponent } from './editor/description-type-editor.component'; import { DescriptionTypeEditorComponent } from './editor/description-type-editor.component';
import { CommonFormsModule } from '@common/forms/common-forms.module';
@NgModule({ @NgModule({
declarations: [ declarations: [
@ -13,6 +14,7 @@ import { DescriptionTypeEditorComponent } from './editor/description-type-editor
imports: [ imports: [
CommonModule, CommonModule,
CommonUiModule, CommonUiModule,
CommonFormsModule,
DescriptionTypesRoutingModule DescriptionTypesRoutingModule
] ]
}) })

View File

@ -24,7 +24,9 @@
</div> </div>
<div class="col"></div> <div class="col"></div>
<div class="col-auto"> <div class="col-auto">
<button mat-button class="action-btn" type="submit" [disabled]="!formGroup.valid"> <button mat-button *ngIf="formGroup.get('status').value!=1" class="action-btn" (click)="finalize()"
[disabled]="!this.isFormValid()" type="button">{{'DESCRIPTION-TYPE-EDITOR.ACTIONS.FINALIZE' | translate }}</button>
<button mat-button class="action-btn ml-3" type="submit" [disabled]="!this.isFormValid() || viewOnly">
{{'DESCRIPTION-TYPE-EDITOR.ACTIONS.SAVE' | translate}} {{'DESCRIPTION-TYPE-EDITOR.ACTIONS.SAVE' | translate}}
</button> </button>
</div> </div>

View File

@ -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 { 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 { DescriptionTemplateTypeService } from '@app/core/services/description-template-type/description-template-type.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { BaseComponent } from '@common/base/base.component'; import { BaseComponent } from '@common/base/base.component';
import { FormService } from '@common/forms/form-service'; 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 { TranslateService } from '@ngx-translate/core';
import { takeUntil } from 'rxjs/operators'; import { takeUntil } from 'rxjs/operators';
@ -13,25 +18,52 @@ import { takeUntil } from 'rxjs/operators';
templateUrl: './description-type-editor.component.html', templateUrl: './description-type-editor.component.html',
styleUrls: ['./description-type-editor.component.scss'] styleUrls: ['./description-type-editor.component.scss']
}) })
export class DescriptionTypeEditorComponent extends BaseComponent implements AfterViewInit { export class DescriptionTypeEditorComponent extends BaseComponent implements OnInit {
formGroup: FormGroup = null; formGroup: FormGroup = null;
descriptionTypeModel: DescriptionTypeEditorModel descriptionTypeModel: DescriptionTypeEditorModel;
isNew = true;
viewOnly = false;
descriptionTemplateTypeId: string;
constructor( constructor(
private descriptionTemplateTypeService: DescriptionTemplateTypeService, private descriptionTemplateTypeService: DescriptionTemplateTypeService,
private formService: FormService, private formService: FormService,
private uiNotificationService: UiNotificationService, private uiNotificationService: UiNotificationService,
private language: TranslateService, private language: TranslateService,
private route: ActivatedRoute,
private router: Router private router: Router
) { ) {
super(); super();
} }
ngAfterViewInit(): void { ngOnInit(): void {
this.descriptionTypeModel = new DescriptionTypeEditorModel(); this.route.paramMap.pipe(takeUntil(this._destroyed)).subscribe((paramMap: ParamMap) => {
setTimeout(() => { this.descriptionTemplateTypeId = paramMap.get('id');
this.formGroup = this.descriptionTypeModel.buildForm();
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; return this.formGroup.valid;
} }
onSubmit(): void { finalize() {
console.log(this.formGroup.value); this.formGroup.get('status').setValue(DescriptionTemplateTypeStatus.Finalized);
this.descriptionTemplateTypeService.createType(this.formGroup.value) this.onSubmit();
.pipe(takeUntil(this._destroyed))
.subscribe(
complete => this.onCallbackSuccess(),
error => this.onCallbackError(error)
);
} }
onCallbackSuccess(): void { onSubmit(): void {
this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION'), SnackBarNotificationLevel.Success); 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']); this.router.navigate(['/description-types']);
} }
onCallbackError(errorResponse: any) { onCallbackError(errorResponse: any) {
// this.setErrorModel(errorResponse.error); this.setErrorModel(errorResponse.error);
// this.formService.validateAllFormFields(this.formGroup); 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 => {
(<any>this.descriptionTypeModel.validationErrorModel)[item] = (<any>validationErrorModel)[item];
});
}
public cancel(): void {
this.router.navigate(['/description-types']); this.router.navigate(['/description-types']);
} }
@ -74,12 +132,30 @@ export class DescriptionTypeEditorComponent extends BaseComponent implements Aft
export class DescriptionTypeEditorModel { export class DescriptionTypeEditorModel {
public id: string; public id: string;
public name: 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({ const formGroup = new FormBuilder().group({
id: [this.id], 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; 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;
}
} }

View File

@ -28,7 +28,7 @@
<ng-container cdkColumnDef="status"> <ng-container cdkColumnDef="status">
<mat-header-cell *matHeaderCellDef mat-sort-header="status">{{'DESCRIPTION-TYPES-LISTING.COLUMNS.STATUS' | <mat-header-cell *matHeaderCellDef mat-sort-header="status">{{'DESCRIPTION-TYPES-LISTING.COLUMNS.STATUS' |
translate}}</mat-header-cell> translate}}</mat-header-cell>
<mat-cell *matCellDef="let row"> <div [ngClass]="['status-chip',getStatusClass(row.status)]">{{ 'DATASET-PROFILE-STATUS.FINALIZED' | translate}}</div></mat-cell> <mat-cell *matCellDef="let row"> <div [ngClass]="['status-chip',getStatusClass(row.status)]">{{parseStatus(row.status) | translate}}</div></mat-cell>
</ng-container> </ng-container>
<ng-container cdkColumnDef="delete"> <ng-container cdkColumnDef="delete">
@ -41,10 +41,10 @@
</ng-container> </ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row> <mat-row *matRowDef="let row; columns: displayedColumns" (click)="rowClick(row.id)"></mat-row>
</mat-table> </mat-table>
<mat-paginator #paginator [length]="1" [pageSizeOptions]="[10, 25, 100]"> <mat-paginator #paginator [length]="dataSource?.totalCount" [pageSizeOptions]="[10, 25, 100]">
</mat-paginator> </mat-paginator>
</div> </div>
</div> </div>

View File

@ -4,6 +4,8 @@ import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator'; import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort'; 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 { DescriptionTemplateTypeService } from '@app/core/services/description-template-type/description-template-type.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service'; import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { BaseComponent } from '@common/base/base.component'; import { BaseComponent } from '@common/base/base.component';
@ -25,11 +27,17 @@ export class DescriptionTypesComponent extends BaseComponent implements OnInit {
dataSource: DescriptionTypesDataSource | null; dataSource: DescriptionTypesDataSource | null;
displayedColumns: String[] = ['label', 'status', 'delete']; displayedColumns: String[] = ['label', 'status', 'delete'];
statuses = [
{ value: '0', viewValue: 'DESCRIPTION-TYPES-LISTING.STATUS.DRAFT' },
{ value: '1', viewValue: 'DESCRIPTION-TYPES-LISTING.STATUS.FINALIZED' }
];
constructor( constructor(
private descriptionTemplateTypeService: DescriptionTemplateTypeService, private descriptionTemplateTypeService: DescriptionTemplateTypeService,
private dialog: MatDialog, private dialog: MatDialog,
private language: TranslateService, private language: TranslateService,
private uiNotificationService: UiNotificationService private uiNotificationService: UiNotificationService,
private router: Router
) { ) {
super(); super();
} }
@ -42,6 +50,19 @@ export class DescriptionTypesComponent extends BaseComponent implements OnInit {
this.dataSource = new DescriptionTypesDataSource(this.descriptionTemplateTypeService, this._paginator, this.sort/*, this.criteria*/); 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){ deleteTemplate(id: string){
if(id){ if(id){
const dialogRef = this.dialog.open(ConfirmationDialogComponent, { 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 => { dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
if (result) { if (result) {
// this.descriptionTemplateTypeService.deleteType(id) this.descriptionTemplateTypeService.deleteType(id)
// .pipe(takeUntil(this._destroyed)) .pipe(takeUntil(this._destroyed))
// .subscribe( .subscribe(
// complete => { complete => {
// this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-DATASET-PROFILE-DELETE'), SnackBarNotificationLevel.Success); this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-DATASET-PROFILE-DELETE'), SnackBarNotificationLevel.Success);
// this.refresh(); this.refresh();
// }, },
// error => { error => {
// this.onCallbackError(error); this.onCallbackError(error);
// if (error.error.statusCode == 674) { if (error.error.statusCode == 674) {
// this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DATASET-PROFILE-DELETE'), SnackBarNotificationLevel.Error); this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DATASET-PROFILE-DELETE'), SnackBarNotificationLevel.Error);
// } else { } else {
// this.uiNotificationService.snackBarNotification(this.language.instant(error.message), SnackBarNotificationLevel.Error); 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();
} }
}); });
@ -96,55 +114,38 @@ export class DescriptionTypesComponent extends BaseComponent implements OnInit {
} }
export interface DescriptionTemplateTypeListingModel { export class DescriptionTypesDataSource extends DataSource<DescriptionTemplateType> {
id: string;
name: string;
status: number;
}
export class DescriptionTypesDataSource extends DataSource<DescriptionTemplateTypeListingModel> {
totalCount = 0; totalCount = 0;
constructor( constructor(
private _service: DescriptionTemplateTypeService, private _service: DescriptionTemplateTypeService,
private _paginator: MatPaginator, private _paginator: MatPaginator,
private _sort: MatSort//, private _sort: MatSort
//private _criteria: DmpProfileCriteriaComponent
) { ) {
super(); super();
} }
connect(): Observable<DescriptionTemplateTypeListingModel[]> { connect(): Observable<DescriptionTemplateType[]> {
const displayDataChanges = [ const displayDataChanges = [
this._paginator.page this._paginator.page
//this._sort.matSortChange //this._sort.matSortChange
]; ];
// return observableMerge(...displayDataChanges).pipe( return observableMerge(...displayDataChanges).pipe(
// startWith(null), startWith(null),
// switchMap(() => { switchMap(() => {
// // const startIndex = this._paginator.pageIndex * this._paginator.pageSize; return this._service.getTypes();
// // let fields: Array<string> = new Array(); }),
// // if (this._sort.active) { fields = this._sort.direction === 'asc' ? ['+' + this._sort.active] : ['-' + this._sort.active]; } map(result => {
// // const request = new DataTableRequest<DmpProfileCriteria>(startIndex, this._paginator.pageSize, { fields: fields }); return result;
// // request.criteria = this._criteria.criteria; }),
// // return this._service.getPaged(request); map(result => {
if (!result) { return []; }
// return this._service.getTypes(); if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
// }), return result.data;
// 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}]);
} }
disconnect() { disconnect() {

View File

@ -960,6 +960,10 @@
"NAME": "Name", "NAME": "Name",
"STATUS": "Status" "STATUS": "Status"
}, },
"STATUS":{
"DRAFT": "Draft",
"FINALIZED": "Finalized"
},
"ACTIONS": { "ACTIONS": {
"DELETE": "Delete" "DELETE": "Delete"
} }
@ -987,6 +991,7 @@
}, },
"ACTIONS": { "ACTIONS": {
"SAVE": "Save", "SAVE": "Save",
"FINALIZE": "Finalize",
"CANCEL": "Cancel" "CANCEL": "Cancel"
} }
}, },