[ADF-3797] Task management view - Task with Form (#4534)

* [ADF-4248] Created form cloud service

* [ADF-4248] Created form cloud model

* [ADF-4248] Created new cloud form

* [ADF-4248] Exported cloud from module

* [ADF-4248] Added form saving feature

* [ADF-4248] Added form to task details

* [ADF-4248] Added services to save form

* [ADF-4248] Added data support

* [ADF-4248] Added outcome support in form model

* [ADF-4248] Modified demo component to show form

* [ADF-4248] Copied tests

* [ADF-4248] Added form parsing service

* [ADF-4248] Added form cloud demo

* [ADF-4248] Added form input to fom-cloud

* [ADF-4248] Added tests for form cloud model

* [ADF-4248] Improved form model json parsing

* [ADF-4248]  Added test for form could

* [ADF-4248] Refactored types in the form model

* [ADF-4248] Improved tests

* [ADF-4248] Added tests for form cloud service

* [ADF-4248] Added tests for form services

* [ADF-4248] Refactored form services

* [ADF-4248] Handled form events in demo shell

* [ADF-4248] Improved form value parsing

* [ADF-4248] Added form-cloud demo to routing

* [ADF-4248] Added field validation without handler

* [ADF-4248] Added task variable model

* [ADF-4248] Added adf-cloud prefix to css classes

* [ADF-4248] Translated name of nameless task

* [ADF-4248] Added docs for cloud form component

* [ADF-4248] Added docs for cloud form service

* create base component

* [ADF-4248] Created formBase and formModelbase

* [ADF-4248] Used base classes in cloud package

* Update form-cloud.component.md

* Update form-cloud.service.md

* [ADF-4248] Created form cloud service

* [ADF-4248] Created form cloud model

* [ADF-4248] Created new cloud form

* [ADF-4248] Exported cloud from module

* [ADF-4248] Added form saving feature

* [ADF-4248] Added form to task details

* [ADF-4248] Added services to save form

* [ADF-4248] Added data support

* [ADF-4248] Added outcome support in form model

* [ADF-4248] Modified demo component to show form

* [ADF-4248] Copied tests

* [ADF-4248] Added form parsing service

* [ADF-4248] Added form cloud demo

* [ADF-4248] Added form input to fom-cloud

* [ADF-4248] Added tests for form cloud model

* [ADF-4248] Improved form model json parsing

* [ADF-4248]  Added test for form could

* [ADF-4248] Refactored types in the form model

* [ADF-4248] Improved tests

* [ADF-4248] Added tests for form cloud service

* [ADF-4248] Added tests for form services

* [ADF-4248] Refactored form services

* [ADF-4248] Handled form events in demo shell

* [ADF-4248] Improved form value parsing

* [ADF-4248] Added form-cloud demo to routing

* [ADF-4248] Added field validation without handler

* [ADF-4248] Added task variable model

* [ADF-4248] Added adf-cloud prefix to css classes

* [ADF-4248] Translated name of nameless task

* [ADF-4248] Added docs for cloud form component

* [ADF-4248] Added docs for cloud form service

* create base component

* [ADF-4248] Created formBase and formModelbase

* [ADF-4248] Used base classes in cloud package

* [ADF-4248] Moved documentation to process services

* [ADF-4248] Removed duplicate import

* [ADF-4248] Fixed wrong imports

* [ADF-4248] Renamed form renderer input

* [ADF-4248] Show translated name for nameless form

* Enable the uploadWidget

* Make the form great again!

* Move the class style on the parent

* Fix the debugMode
This commit is contained in:
Deepak Paul
2019-04-10 21:40:56 +05:30
committed by Eugenio Romano
parent 61ee1f1d53
commit 558ee4c031
76 changed files with 5029 additions and 450 deletions

View File

@@ -0,0 +1,46 @@
<div *ngIf="!hasForm()">
<ng-content select="[empty-form]">
</ng-content>
</div>
<div *ngIf="hasForm()" class="adf-form-container">
<mat-card>
<mat-card-header>
<mat-card-title>
<h4>
<div *ngIf="showValidationIcon" class="adf-form-validation-button">
<i id="adf-valid-form-icon" class="material-icons"
*ngIf="form.isValid; else no_valid_form">check_circle</i>
<ng-template #no_valid_form>
<i id="adf-invalid-form-icon" class="material-icons adf-invalid-color">error</i>
</ng-template>
</div>
<div *ngIf="showRefreshButton" class="adf-form-reload-button">
<button mat-icon-button (click)="onRefreshClicked()">
<mat-icon>refresh</mat-icon>
</button>
</div>
<span *ngIf="isTitleEnabled()" class="adf-form-title">
{{form.taskName}}
<ng-container *ngIf="!form.taskName">
{{'FORM.FORM_RENDERER.NAMELESS_TASK' | translate}}
</ng-container>
</span>
</h4>
</mat-card-title>
</mat-card-header>
<mat-card-content>
<adf-form-renderer [formDefinition]="form">
</adf-form-renderer>
</mat-card-content>
<mat-card-actions *ngIf="form.hasOutcomes()" class="adf-form-mat-card-actions">
<button [id]="'adf-form-'+ outcome.name | formatSpace" *ngFor="let outcome of form.outcomes"
[color]="getColorForOutcome(outcome.name)" mat-button [disabled]="!isOutcomeButtonEnabled(outcome)"
[class.adf-form-hide-button]="!isOutcomeButtonVisible(outcome, form.readOnly)"
(click)="onOutcomeClicked(outcome)">
{{outcome.name | translate | uppercase }}
</button>
</mat-card-actions>
</mat-card>
</div>

View File

@@ -0,0 +1,753 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { SimpleChange } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
import { FormFieldModel, FormFieldTypes, FormOutcomeEvent, FormOutcomeModel, LogService, WidgetVisibilityService } from '@alfresco/adf-core';
import { FormCloudService } from '../services/form-cloud.service';
import { FormCloudComponent } from './form-cloud.component';
import { FormCloud } from '../models/form-cloud.model';
import { cloudFormMock } from '../mocks/cloud-form.mock';
describe('FormCloudComponent', () => {
let formService: FormCloudService;
let formComponent: FormCloudComponent;
let visibilityService: WidgetVisibilityService;
let logService: LogService;
beforeEach(() => {
logService = new LogService(null);
visibilityService = new WidgetVisibilityService(null, logService);
spyOn(visibilityService, 'refreshVisibility').and.stub();
formService = new FormCloudService(null, null, logService);
formComponent = new FormCloudComponent(formService, visibilityService);
});
it('should check form', () => {
expect(formComponent.hasForm()).toBeFalsy();
formComponent.form = new FormCloud();
expect(formComponent.hasForm()).toBeTruthy();
});
it('should allow title if showTitle is true', () => {
const formModel = new FormCloud();
formComponent.form = formModel;
expect(formComponent.showTitle).toBeTruthy();
expect(formComponent.isTitleEnabled()).toBeTruthy();
});
it('should not allow title if showTitle is false', () => {
const formModel = new FormCloud();
formComponent.form = formModel;
formComponent.showTitle = false;
expect(formComponent.isTitleEnabled()).toBeFalsy();
});
it('should return primary color for complete button', () => {
expect(formComponent.getColorForOutcome('COMPLETE')).toBe('primary');
});
it('should not enable outcome button when model missing', () => {
expect(formComponent.isOutcomeButtonVisible(null, false)).toBeFalsy();
});
it('should enable custom outcome buttons', () => {
const formModel = new FormCloud();
formComponent.form = formModel;
const outcome = new FormOutcomeModel(<any> formModel, { id: 'action1', name: 'Action 1' });
expect(formComponent.isOutcomeButtonVisible(outcome, formComponent.form.readOnly)).toBeTruthy();
});
it('should allow controlling [complete] button visibility', () => {
const formModel = new FormCloud();
formComponent.form = formModel;
const outcome = new FormOutcomeModel(<any> formModel, { id: '$save', name: FormOutcomeModel.SAVE_ACTION });
formComponent.showSaveButton = true;
expect(formComponent.isOutcomeButtonVisible(outcome, formComponent.form.readOnly)).toBeTruthy();
formComponent.showSaveButton = false;
expect(formComponent.isOutcomeButtonVisible(outcome, formComponent.form.readOnly)).toBeFalsy();
});
it('should show only [complete] button with readOnly form ', () => {
const formModel = new FormCloud();
formModel.readOnly = true;
formComponent.form = formModel;
const outcome = new FormOutcomeModel(<any> formModel, { id: '$complete', name: FormOutcomeModel.COMPLETE_ACTION });
formComponent.showCompleteButton = true;
expect(formComponent.isOutcomeButtonVisible(outcome, formComponent.form.readOnly)).toBeTruthy();
});
it('should not show [save] button with readOnly form ', () => {
const formModel = new FormCloud();
formModel.readOnly = true;
formComponent.form = formModel;
const outcome = new FormOutcomeModel(<any> formModel, { id: '$save', name: FormOutcomeModel.SAVE_ACTION });
formComponent.showSaveButton = true;
expect(formComponent.isOutcomeButtonVisible(outcome, formComponent.form.readOnly)).toBeFalsy();
});
it('should show [custom-outcome] button with readOnly form and selected custom-outcome', () => {
const formModel = new FormCloud({formRepresentation: {formDefinition: {selectedOutcome: 'custom-outcome'}}});
formModel.readOnly = true;
formComponent.form = formModel;
let outcome = new FormOutcomeModel(<any> formModel, { id: '$customoutome', name: 'custom-outcome' });
formComponent.showCompleteButton = true;
formComponent.showSaveButton = true;
expect(formComponent.isOutcomeButtonVisible(outcome, formComponent.form.readOnly)).toBeTruthy();
outcome = new FormOutcomeModel(<any> formModel, { id: '$customoutome2', name: 'custom-outcome2' });
expect(formComponent.isOutcomeButtonVisible(outcome, formComponent.form.readOnly)).toBeFalsy();
});
it('should allow controlling [save] button visibility', () => {
const formModel = new FormCloud();
formModel.readOnly = false;
formComponent.form = formModel;
const outcome = new FormOutcomeModel(<any> formModel, { id: '$save', name: FormOutcomeModel.COMPLETE_ACTION });
formComponent.showCompleteButton = true;
expect(formComponent.isOutcomeButtonVisible(outcome, formComponent.form.readOnly)).toBeTruthy();
formComponent.showCompleteButton = false;
expect(formComponent.isOutcomeButtonVisible(outcome, formComponent.form.readOnly)).toBeFalsy();
});
it('should load form on refresh', () => {
spyOn(formComponent, 'loadForm').and.stub();
formComponent.onRefreshClicked();
expect(formComponent.loadForm).toHaveBeenCalled();
});
it('should get task variables if a task form is rendered', () => {
spyOn(formService, 'getTaskForm').and.callFake((currentTaskId) => {
return new Observable((observer) => {
observer.next({ formRepresentation: { taskId: currentTaskId }});
observer.complete();
});
});
spyOn(formService, 'getTaskVariables').and.returnValue(of({}));
spyOn(formService, 'getTask').and.callFake((currentTaskId) => {
return new Observable((observer) => {
observer.next({ formRepresentation: { taskId: currentTaskId }});
observer.complete();
});
});
const taskId = '123';
const appName = 'test-app';
formComponent.appName = appName;
formComponent.taskId = taskId;
formComponent.loadForm();
expect(formService.getTaskVariables).toHaveBeenCalledWith(appName, taskId);
});
it('should not get task variables and form if task id is not specified', () => {
spyOn(formService, 'getTaskForm').and.callFake((currentTaskId) => {
return new Observable((observer) => {
observer.next({ taskId: currentTaskId });
observer.complete();
});
});
spyOn(formService, 'getTaskVariables').and.returnValue(of({}));
formComponent.appName = 'test-app';
formComponent.taskId = null;
formComponent.loadForm();
expect(formService.getTaskForm).not.toHaveBeenCalled();
expect(formService.getTaskVariables).not.toHaveBeenCalled();
});
it('should get form definition by form id on load', () => {
spyOn(formComponent, 'getFormById').and.stub();
const formId = '123';
const appName = 'test-app';
formComponent.appName = appName;
formComponent.formId = formId;
formComponent.loadForm();
expect(formComponent.getFormById).toHaveBeenCalledWith(appName, formId);
});
it('should refresh visibility when the form is loaded', () => {
spyOn(formService, 'getForm').and.returnValue(of({formRepresentation: {formDefinition: {}}}));
const formId = '123';
const appName = 'test-app';
formComponent.appName = appName;
formComponent.formId = formId;
formComponent.loadForm();
expect(formService.getForm).toHaveBeenCalledWith(appName, formId);
expect(visibilityService.refreshVisibility).toHaveBeenCalled();
});
it('should reload form by task id on binding changes', () => {
spyOn(formComponent, 'getFormByTaskId').and.stub();
const taskId = '<task id>';
const appName = 'test-app';
formComponent.appName = appName;
const change = new SimpleChange(null, taskId, true);
formComponent.ngOnChanges({ 'taskId': change });
expect(formComponent.getFormByTaskId).toHaveBeenCalledWith(appName, taskId);
});
it('should reload form definition by form id on binding changes', () => {
spyOn(formComponent, 'getFormById').and.stub();
const formId = '123';
const appName = 'test-app';
formComponent.appName = appName;
const change = new SimpleChange(null, formId, true);
formComponent.ngOnChanges({ 'formId': change });
expect(formComponent.getFormById).toHaveBeenCalledWith(appName, formId);
});
it('should not get form on load', () => {
spyOn(formComponent, 'getFormByTaskId').and.stub();
spyOn(formComponent, 'getFormById').and.stub();
formComponent.taskId = null;
formComponent.formId = null;
formComponent.loadForm();
expect(formComponent.getFormByTaskId).not.toHaveBeenCalled();
expect(formComponent.getFormById).not.toHaveBeenCalled();
});
it('should not reload form on unrelated binding changes', () => {
spyOn(formComponent, 'getFormByTaskId').and.stub();
spyOn(formComponent, 'getFormById').and.stub();
formComponent.ngOnChanges({ 'tag': new SimpleChange(null, 'hello world', false) });
expect(formComponent.getFormByTaskId).not.toHaveBeenCalled();
expect(formComponent.getFormById).not.toHaveBeenCalled();
});
it('should complete form on custom outcome click', () => {
const formModel = new FormCloud();
const outcomeName = 'Custom Action';
const outcome = new FormOutcomeModel(<any> formModel, { id: 'custom1', name: outcomeName });
let saved = false;
formComponent.form = formModel;
formComponent.formSaved.subscribe((v) => saved = true);
spyOn(formComponent, 'completeTaskForm').and.stub();
const result = formComponent.onOutcomeClicked(outcome);
expect(result).toBeTruthy();
expect(saved).toBeTruthy();
expect(formComponent.completeTaskForm).toHaveBeenCalledWith(outcomeName);
});
it('should save form on [save] outcome click', () => {
const formModel = new FormCloud();
const outcome = new FormOutcomeModel(<any> formModel, {
id: FormCloudComponent.SAVE_OUTCOME_ID,
name: 'Save',
isSystem: true
});
formComponent.form = formModel;
spyOn(formComponent, 'saveTaskForm').and.stub();
const result = formComponent.onOutcomeClicked(outcome);
expect(result).toBeTruthy();
expect(formComponent.saveTaskForm).toHaveBeenCalled();
});
it('should complete form on [complete] outcome click', () => {
const formModel = new FormCloud();
const outcome = new FormOutcomeModel(<any> formModel, {
id: FormCloudComponent.COMPLETE_OUTCOME_ID,
name: 'Complete',
isSystem: true
});
formComponent.form = formModel;
spyOn(formComponent, 'completeTaskForm').and.stub();
const result = formComponent.onOutcomeClicked(outcome);
expect(result).toBeTruthy();
expect(formComponent.completeTaskForm).toHaveBeenCalled();
});
it('should emit form saved event on custom outcome click', () => {
const formModel = new FormCloud();
const outcome = new FormOutcomeModel(<any> formModel, {
id: FormCloudComponent.CUSTOM_OUTCOME_ID,
name: 'Custom',
isSystem: true
});
let saved = false;
formComponent.form = formModel;
formComponent.formSaved.subscribe((v) => saved = true);
const result = formComponent.onOutcomeClicked(outcome);
expect(result).toBeTruthy();
expect(saved).toBeTruthy();
});
it('should do nothing when clicking outcome for readonly form', () => {
const formModel = new FormCloud();
const outcomeName = 'Custom Action';
const outcome = new FormOutcomeModel(<any> formModel, { id: 'custom1', name: outcomeName });
formComponent.form = formModel;
spyOn(formComponent, 'completeTaskForm').and.stub();
expect(formComponent.onOutcomeClicked(outcome)).toBeTruthy();
formComponent.readOnly = true;
expect(formComponent.onOutcomeClicked(outcome)).toBeFalsy();
});
it('should require outcome model when clicking outcome', () => {
formComponent.form = new FormCloud();
formComponent.readOnly = false;
expect(formComponent.onOutcomeClicked(null)).toBeFalsy();
});
it('should require loaded form when clicking outcome', () => {
const formModel = new FormCloud();
const outcomeName = 'Custom Action';
const outcome = new FormOutcomeModel(<any> formModel, { id: 'custom1', name: outcomeName });
formComponent.readOnly = false;
formComponent.form = null;
expect(formComponent.onOutcomeClicked(outcome)).toBeFalsy();
});
it('should not execute unknown system outcome', () => {
const formModel = new FormCloud();
const outcome = new FormOutcomeModel(<any> formModel, { id: 'unknown', name: 'Unknown', isSystem: true });
formComponent.form = formModel;
expect(formComponent.onOutcomeClicked(outcome)).toBeFalsy();
});
it('should require custom action name to complete form', () => {
const formModel = new FormCloud();
let outcome = new FormOutcomeModel(<any> formModel, { id: 'custom' });
formComponent.form = formModel;
expect(formComponent.onOutcomeClicked(outcome)).toBeFalsy();
outcome = new FormOutcomeModel(<any> formModel, { id: 'custom', name: 'Custom' });
spyOn(formComponent, 'completeTaskForm').and.stub();
expect(formComponent.onOutcomeClicked(outcome)).toBeTruthy();
});
it('should fetch and parse form by task id', (done) => {
const appName = 'test-app';
const taskId = '456';
spyOn(formService, 'getTask').and.returnValue(of({}));
spyOn(formService, 'getTaskVariables').and.returnValue(of({}));
spyOn(formService, 'getTaskForm').and.returnValue(of({formRepresentation: {taskId: taskId, formDefinition: {selectedOutcome: 'custom-outcome'}}}));
formComponent.formLoaded.subscribe(() => {
expect(formService.getTaskForm).toHaveBeenCalledWith(appName, taskId);
expect(formComponent.form).toBeDefined();
expect(formComponent.form.taskId).toBe(taskId);
done();
});
formComponent.appName = appName;
formComponent.taskId = taskId;
formComponent.loadForm();
});
it('should handle error when getting form by task id', (done) => {
const error = 'Some error';
spyOn(formService, 'getTask').and.returnValue(of({}));
spyOn(formService, 'getTaskVariables').and.returnValue(of({}));
spyOn(formComponent, 'handleError').and.stub();
spyOn(formService, 'getTaskForm').and.callFake(() => {
return throwError(error);
});
formComponent.getFormByTaskId('test-app', '123').then((_) => {
expect(formComponent.handleError).toHaveBeenCalledWith(error);
done();
});
});
it('should fetch and parse form definition by id', (done) => {
spyOn(formService, 'getForm').and.callFake((currentAppName, currentFormId) => {
return new Observable((observer) => {
observer.next({ formRepresentation: {id: currentFormId, formDefinition: {}}});
observer.complete();
});
});
const appName = 'test-app';
const formId = '456';
formComponent.formLoaded.subscribe(() => {
expect(formComponent.form).toBeDefined();
expect(formComponent.form.id).toBe(formId);
done();
});
formComponent.appName = appName;
formComponent.formId = formId;
formComponent.loadForm();
});
it('should handle error when getting form by definition id', () => {
const error = 'Some error';
spyOn(formComponent, 'handleError').and.stub();
spyOn(formService, 'getForm').and.callFake(() => throwError(error));
formComponent.getFormById('test-app', '123');
expect(formComponent.handleError).toHaveBeenCalledWith(error);
});
it('should save task form and raise corresponding event', () => {
spyOn(formService, 'saveTaskForm').and.callFake(() => {
return new Observable((observer) => {
observer.next();
observer.complete();
});
});
let saved = false;
let savedForm = null;
formComponent.formSaved.subscribe((form) => {
saved = true;
savedForm = form;
});
const taskId = '123-223';
const appName = 'test-app';
const formModel = new FormCloud({
formRepresentation: {
id: '23',
taskId: taskId,
formDefinition: {
fields: [
{ id: 'field1' },
{ id: 'field2' }
]
}
}
});
formComponent.form = formModel;
formComponent.taskId = taskId;
formComponent.appName = appName;
formComponent.saveTaskForm();
expect(formService.saveTaskForm).toHaveBeenCalledWith(appName, formModel.taskId, formModel.id, formModel.values);
expect(saved).toBeTruthy();
expect(savedForm).toEqual(formModel);
});
it('should handle error during form save', () => {
const error = 'Error';
spyOn(formService, 'saveTaskForm').and.callFake(() => throwError(error));
spyOn(formComponent, 'handleError').and.stub();
const taskId = '123-223';
const appName = 'test-app';
const formModel = new FormCloud({
formRepresentation: {
id: '23',
taskId: taskId,
formDefinition: {
fields: [
{ id: 'field1' },
{ id: 'field2' }
]
}
}
});
formComponent.form = formModel;
formComponent.taskId = taskId;
formComponent.appName = appName;
formComponent.saveTaskForm();
expect(formComponent.handleError).toHaveBeenCalledWith(error);
});
it('should require form with appName and taskId to save', () => {
spyOn(formService, 'saveTaskForm').and.stub();
formComponent.form = null;
formComponent.saveTaskForm();
formComponent.form = new FormCloud();
formComponent.appName = 'test-app';
formComponent.saveTaskForm();
formComponent.appName = null;
formComponent.taskId = '123';
formComponent.saveTaskForm();
expect(formService.saveTaskForm).not.toHaveBeenCalled();
});
it('should require form with appName and taskId to complete', () => {
spyOn(formService, 'completeTaskForm').and.stub();
formComponent.form = null;
formComponent.completeTaskForm('save');
formComponent.form = new FormCloud();
formComponent.appName = 'test-app';
formComponent.completeTaskForm('complete');
formComponent.appName = null;
formComponent.taskId = '123';
formComponent.completeTaskForm('complete');
expect(formService.completeTaskForm).not.toHaveBeenCalled();
});
it('should complete form and raise corresponding event', () => {
spyOn(formService, 'completeTaskForm').and.callFake(() => {
return new Observable((observer) => {
observer.next();
observer.complete();
});
});
const outcome = 'complete';
let completed = false;
formComponent.formCompleted.subscribe(() => completed = true);
const taskId = '123-223';
const appName = 'test-app';
const formModel = new FormCloud({
formRepresentation: {
id: '23',
taskId: taskId,
formDefinition: {
fields: [
{ id: 'field1' },
{ id: 'field2' }
]
}
}
});
formComponent.form = formModel;
formComponent.taskId = taskId;
formComponent.appName = appName;
formComponent.completeTaskForm(outcome);
expect(formService.completeTaskForm).toHaveBeenCalledWith(appName, formModel.taskId, formModel.id, formModel.values, outcome);
expect(completed).toBeTruthy();
});
it('should require json to parse form', () => {
expect(formComponent.parseForm(null)).toBeNull();
});
it('should parse form from json', () => {
const form = formComponent.parseForm({
formRepresentation: {
id: '1',
formDefinition: {
fields: [
{ id: 'field1', type: FormFieldTypes.CONTAINER }
]
}
}
});
expect(form).toBeDefined();
expect(form.id).toBe('1');
expect(form.fields.length).toBe(1);
expect(form.fields[0].id).toBe('field1');
});
it('should provide outcomes for form definition', () => {
spyOn(formComponent, 'getFormDefinitionOutcomes').and.callThrough();
const form = formComponent.parseForm({ formRepresentation: { id: 1, formDefinition: {}}});
expect(formComponent.getFormDefinitionOutcomes).toHaveBeenCalledWith(form);
});
it('should prevent default outcome execution', () => {
const outcome = new FormOutcomeModel(<any> new FormCloud(), {
id: FormCloudComponent.CUSTOM_OUTCOME_ID,
name: 'Custom'
});
formComponent.form = new FormCloud();
formComponent.executeOutcome.subscribe((event: FormOutcomeEvent) => {
expect(event.outcome).toBe(outcome);
event.preventDefault();
expect(event.defaultPrevented).toBeTruthy();
});
const result = formComponent.onOutcomeClicked(outcome);
expect(result).toBeFalsy();
});
it('should not prevent default outcome execution', () => {
const outcome = new FormOutcomeModel(<any> new FormCloud(), {
id: FormCloudComponent.CUSTOM_OUTCOME_ID,
name: 'Custom'
});
formComponent.form = new FormCloud();
formComponent.executeOutcome.subscribe((event: FormOutcomeEvent) => {
expect(event.outcome).toBe(outcome);
expect(event.defaultPrevented).toBeFalsy();
});
spyOn(formComponent, 'completeTaskForm').and.callThrough();
const result = formComponent.onOutcomeClicked(outcome);
expect(result).toBeTruthy();
expect(formComponent.completeTaskForm).toHaveBeenCalledWith(outcome.name);
});
it('should check visibility only if field with form provided', () => {
formComponent.checkVisibility(null);
expect(visibilityService.refreshVisibility).not.toHaveBeenCalled();
let field = new FormFieldModel(null);
formComponent.checkVisibility(field);
expect(visibilityService.refreshVisibility).not.toHaveBeenCalled();
field = new FormFieldModel(<any> new FormCloud());
formComponent.checkVisibility(field);
expect(visibilityService.refreshVisibility).toHaveBeenCalledWith(field.form);
});
it('should disable outcome buttons for readonly form', () => {
const formModel = new FormCloud();
formModel.readOnly = true;
formComponent.form = formModel;
const outcome = new FormOutcomeModel(<any> new FormCloud(), {
id: FormCloudComponent.CUSTOM_OUTCOME_ID,
name: 'Custom'
});
expect(formComponent.isOutcomeButtonEnabled(outcome)).toBeFalsy();
});
it('should require outcome to eval button state', () => {
formComponent.form = new FormCloud();
expect(formComponent.isOutcomeButtonEnabled(null)).toBeFalsy();
});
it('should disable complete outcome button when disableCompleteButton is true', () => {
const formModel = new FormCloud();
formComponent.form = formModel;
formComponent.disableCompleteButton = true;
expect(formModel.isValid).toBeTruthy();
const completeOutcome = formComponent.form.outcomes.find((outcome) => outcome.name === FormOutcomeModel.COMPLETE_ACTION);
expect(formComponent.isOutcomeButtonEnabled(completeOutcome)).toBeFalsy();
});
it('should disable start process outcome button when disableStartProcessButton is true', () => {
const formModel = new FormCloud();
formComponent.form = formModel;
formComponent.disableStartProcessButton = true;
expect(formModel.isValid).toBeTruthy();
const startProcessOutcome = formComponent.form.outcomes.find((outcome) => outcome.name === FormOutcomeModel.START_PROCESS_ACTION);
expect(formComponent.isOutcomeButtonEnabled(startProcessOutcome)).toBeFalsy();
});
it('should raise [executeOutcome] event for formService', (done) => {
formComponent.executeOutcome.subscribe(() => {
done();
});
const outcome = new FormOutcomeModel(<any> new FormCloud(), {
id: FormCloudComponent.CUSTOM_OUTCOME_ID,
name: 'Custom'
});
formComponent.form = new FormCloud();
formComponent.onOutcomeClicked(outcome);
});
it('should refresh form values when data is changed', () => {
formComponent.form = new FormCloud(JSON.parse(JSON.stringify(cloudFormMock)));
let formFields = formComponent.form.getFormFields();
let labelField = formFields.find((field) => field.id === 'text1');
let radioField = formFields.find((field) => field.id === 'number1');
expect(labelField.value).toBeNull();
expect(radioField.value).toBeUndefined();
const formValues: any[] = [{name: 'text1', value: 'test'}, {name: 'number1', value: 23}];
const change = new SimpleChange(null, formValues, false);
formComponent.data = formValues;
formComponent.ngOnChanges({ 'data': change });
formFields = formComponent.form.getFormFields();
labelField = formFields.find((field) => field.id === 'text1');
radioField = formFields.find((field) => field.id === 'number1');
expect(labelField.value).toBe('test');
expect(radioField.value).toBe(23);
});
it('should refresh radio buttons value when id is given to data', () => {
formComponent.form = new FormCloud(JSON.parse(JSON.stringify(cloudFormMock)));
let formFields = formComponent.form.getFormFields();
let radioFieldById = formFields.find((field) => field.id === 'radiobuttons1');
const formValues: any[] = [{name: 'radiobuttons1', value: 'option_2'}];
const change = new SimpleChange(null, formValues, false);
formComponent.data = formValues;
formComponent.ngOnChanges({ 'data': change });
formFields = formComponent.form.getFormFields();
radioFieldById = formFields.find((field) => field.id === 'radiobuttons1');
expect(radioFieldById.value).toBe('option_2');
});
});

View File

@@ -0,0 +1,296 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
Component, EventEmitter, Input, OnChanges,
Output, SimpleChanges
} from '@angular/core';
import { Observable, of, forkJoin } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { FormBaseComponent, FormFieldModel, FormOutcomeEvent, FormOutcomeModel, WidgetVisibilityService } from '@alfresco/adf-core';
import { FormCloudService } from '../services/form-cloud.service';
import { FormCloud } from '../models/form-cloud.model';
import { TaskVariableCloud } from '../models/task-variable-cloud.model';
@Component({
selector: 'adf-cloud-form',
templateUrl: './form-cloud.component.html'
})
export class FormCloudComponent extends FormBaseComponent implements OnChanges {
/** App id to fetch corresponding form and values. */
@Input()
appName: string;
/** Task id to fetch corresponding form and values. */
@Input()
formId: string;
/** Underlying form model instance. */
@Input()
form: FormCloud;
/** Task id to fetch corresponding form and values. */
@Input()
taskId: string;
/** Custom form values map to be used with the rendered form. */
@Input()
data: TaskVariableCloud[];
/** Emitted when the form is submitted with the `Save` or custom outcomes. */
@Output()
formSaved: EventEmitter<FormCloud> = new EventEmitter<FormCloud>();
/** Emitted when the form is submitted with the `Complete` outcome. */
@Output()
formCompleted: EventEmitter<FormCloud> = new EventEmitter<FormCloud>();
/** Emitted when the form is loaded or reloaded. */
@Output()
formLoaded: EventEmitter<FormCloud> = new EventEmitter<FormCloud>();
/** Emitted when form values are refreshed due to a data property change. */
@Output()
formDataRefreshed: EventEmitter<FormCloud> = new EventEmitter<FormCloud>();
protected subscriptions: Subscription[] = [];
nodeId: string;
constructor(protected formService: FormCloudService,
protected visibilityService: WidgetVisibilityService) {
super();
}
ngOnChanges(changes: SimpleChanges) {
const appName = changes['appName'];
if (appName && appName.currentValue) {
if (this.taskId) {
this.getFormDefinitionWithFolderTask(this.appName, this.taskId);
} else if (this.formId) {
this.getFormById(appName.currentValue, this.formId);
}
return;
}
const formId = changes['formId'];
if (formId && formId.currentValue && this.appName) {
this.getFormById(this.appName, formId.currentValue);
return;
}
const taskId = changes['taskId'];
if (taskId && taskId.currentValue && this.appName) {
this.getFormByTaskId(this.appName, taskId.currentValue);
return;
}
const data = changes['data'];
if (data && data.currentValue) {
this.refreshFormData();
return;
}
}
/**
* Invoked when user clicks form refresh button.
*/
onRefreshClicked() {
this.loadForm();
}
loadForm() {
if (this.appName && this.taskId) {
this.getFormByTaskId(this.appName, this.taskId);
} else if (this.appName && this.formId) {
this.getFormById(this.appName, this.formId);
}
}
findProcessVariablesByTaskId(appName: string, taskId: string): Observable<any> {
return this.formService.getTask(appName, taskId).pipe(
switchMap((task: any) => {
if (this.isAProcessTask(task)) {
return this.formService.getTaskVariables(appName, taskId);
} else {
return of({});
}
})
);
}
isAProcessTask(taskRepresentation) {
return taskRepresentation.processDefinitionId && taskRepresentation.processDefinitionDeploymentId !== 'null';
}
getFormByTaskId(appName, taskId: string): Promise<FormCloud> {
return new Promise<FormCloud>((resolve, reject) => {
forkJoin(this.formService.getTaskForm(appName, taskId),
this.formService.getTaskVariables(appName, taskId))
.subscribe(
(data) => {
this.data = data[1];
const parsedForm = this.parseForm(data[0]);
this.visibilityService.refreshVisibility(<any> parsedForm);
parsedForm.validateForm();
this.form = parsedForm;
this.form.nodeId = this.nodeId;
this.onFormLoaded(this.form);
resolve(this.form);
},
(error) => {
this.handleError(error);
// reject(error);
resolve(null);
}
);
});
}
async getFormDefinitionWithFolderTask(appName: string, taskId: string) {
await this.getFolderTask(appName, taskId);
await this.getFormByTaskId(appName, taskId);
}
async getFolderTask(appName: string, taskId: string) {
this.nodeId = await this.formService.getProcessStorageFolderTask(appName, taskId).toPromise();
}
getFormById(appName: string, formId: string) {
this.formService
.getForm(appName, formId)
.subscribe(
(form) => {
const parsedForm = this.parseForm(form);
this.visibilityService.refreshVisibility(<any> parsedForm);
parsedForm.validateForm();
this.form = parsedForm;
this.form.nodeId = this.nodeId;
this.onFormLoaded(this.form);
},
(error) => {
this.handleError(error);
}
);
}
saveTaskForm() {
if (this.form && this.appName && this.taskId) {
this.formService
.saveTaskForm(this.appName, this.taskId, this.form.id, this.form.values)
.subscribe(
() => {
this.onTaskSaved(this.form);
},
(error) => this.onTaskSavedError(this.form, error)
);
}
}
completeTaskForm(outcome?: string) {
if (this.form && this.appName && this.taskId) {
this.formService
.completeTaskForm(this.appName, this.taskId, this.form.id, this.form.values, outcome)
.subscribe(
() => {
this.onTaskCompleted(this.form);
},
(error) => this.onTaskCompletedError(this.form, error)
);
}
}
parseForm(json: any): FormCloud {
if (json) {
const form = new FormCloud(json, this.data, this.readOnly, this.formService);
if (!json.formRepresentation.formDefinition || !json.formRepresentation.formDefinition.fields) {
form.outcomes = this.getFormDefinitionOutcomes(form);
}
if (this.fieldValidators && this.fieldValidators.length > 0) {
form.fieldValidators = this.fieldValidators;
}
return form;
}
return null;
}
/**
* Get custom set of outcomes for a Form Definition.
* @param form Form definition model.
*/
getFormDefinitionOutcomes(form: FormCloud): FormOutcomeModel[] {
return [
new FormOutcomeModel(<any> form, { id: '$save', name: FormOutcomeModel.SAVE_ACTION, isSystem: true })
];
}
checkVisibility(field: FormFieldModel) {
if (field && field.form) {
this.visibilityService.refreshVisibility(field.form);
}
}
private refreshFormData() {
this.form = this.parseForm(this.form.json);
this.onFormLoaded(this.form);
this.onFormDataRefreshed(this.form);
}
protected onFormLoaded(form: FormCloud) {
this.formLoaded.emit(form);
}
protected onFormDataRefreshed(form: FormCloud) {
this.formDataRefreshed.emit(form);
}
protected onTaskSaved(form: FormCloud) {
this.formSaved.emit(form);
}
protected onTaskSavedError(form: FormCloud, error: any) {
this.handleError(error);
}
protected onTaskCompleted(form: FormCloud) {
this.formCompleted.emit(form);
}
protected onTaskCompletedError(form: FormCloud, error: any) {
this.handleError(error);
}
protected onExecuteOutcome(outcome: FormOutcomeModel): boolean {
const args = new FormOutcomeEvent(outcome);
if (args.defaultPrevented) {
return false;
}
this.executeOutcome.emit(args);
if (args.defaultPrevented) {
return false;
}
return true;
}
protected storeFormAsMetadata() {
}
}

View File

@@ -0,0 +1,40 @@
<div class="adf-upload-widget {{field.className}}"
[class.adf-invalid]="!field.isValid"
[class.adf-readonly]="field.readOnly">
<label class="adf-label" [attr.for]="field.id">{{field.name}}<span *ngIf="isRequired()">*</span></label>
<div class="adf-upload-widget-container">
<div>
<mat-list *ngIf="hasFile">
<mat-list-item class="adf-upload-files-row" *ngFor="let file of field.value">
<img mat-list-icon class="adf-upload-widget__icon"
[id]="'file-'+file.id+'-icon'"
[src]="getIcon(file.mimeType)"
[alt]="mimeTypeIcon"
(click)="fileClicked(file)"
(keyup.enter)="fileClicked(file)"
role="button"
tabindex="0"/>
<span matLine id="{{'file-'+file.id}}" (click)="fileClicked(file)" (keyup.enter)="fileClicked(file)"
role="button" tabindex="0" class="adf-file">{{file.name}}</span>
<button *ngIf="!field.readOnly" mat-icon-button [id]="'file-'+file.id+'-remove'"
(click)="removeFile(file);" (keyup.enter)="removeFile(file);">
<mat-icon class="mat-24">highlight_off</mat-icon>
</button>
</mat-list-item>
</mat-list>
</div>
<div class="button-row" *ngIf="(!hasFile || multipleOption) && !field.readOnly">
<a mat-raised-button color="primary">
{{ 'FORM.FIELD.UPLOAD' | translate }}<mat-icon>file_upload</mat-icon>
<input #uploadFiles
[multiple]="multipleOption"
type="file"
[id]="field.id"
(change)="onFileChanged($event)"/>
</a>
</div>
</div>
<error-widget [error]="field.validationSummary"></error-widget>
<error-widget *ngIf="isInvalidFieldRequired()" required="{{ 'FORM.FIELD.REQUIRED' | translate }}"></error-widget>
</div>

View File

@@ -0,0 +1,135 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* tslint:disable:component-selector */
import { Component, ElementRef, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { Observable, from } from 'rxjs';
import { mergeMap, map } from 'rxjs/operators';
import { WidgetComponent, baseHost, LogService, FormService, ThumbnailService } from '@alfresco/adf-core';
import { FormCloudService } from '../services/form-cloud.service';
@Component({
selector: 'upload-cloud-widget',
templateUrl: './upload-cloud.widget.html',
styleUrls: ['./upload-cloud.widget.scss'],
host: baseHost,
encapsulation: ViewEncapsulation.None
})
export class UploadCloudWidgetComponent extends WidgetComponent implements OnInit {
hasFile: boolean;
displayText: string;
multipleOption: string = '';
mimeTypeIcon: string;
@ViewChild('uploadFiles')
fileInput: ElementRef;
constructor(public formService: FormService,
private thumbnailService: ThumbnailService,
private formCloudService: FormCloudService,
private logService: LogService) {
super(formService);
}
ngOnInit() {
if (this.field &&
this.field.value &&
this.field.value.length > 0) {
this.hasFile = true;
}
this.getMultipleFileParam();
}
removeFile(file: any) {
if (this.field) {
this.removeElementFromList(file);
}
}
onFileChanged(event: any) {
const files = event.target.files;
let filesSaved = [];
if (this.field.json.value) {
filesSaved = [...this.field.json.value];
}
if (files && files.length > 0) {
from(files)
.pipe(mergeMap((file) => this.uploadRawContent(file)))
.subscribe(
(res) => filesSaved.push(res),
(error) => this.logService.error(`Error uploading file. See console output for more details. ${error}` ),
() => {
this.field.form.values[this.field.id] = filesSaved;
this.hasFile = true;
}
);
}
}
getIcon(mimeType) {
return this.thumbnailService.getMimeTypeIcon(mimeType);
}
private uploadRawContent(file): Observable<any> {
return this.formCloudService.createTemporaryRawRelatedContent(file, this.field.form.nodeId)
.pipe(
map((response: any) => {
this.logService.info(response);
return { nodeId : response.id};
})
);
}
getMultipleFileParam() {
if (this.field &&
this.field.params &&
this.field.params.multiple) {
this.multipleOption = this.field.params.multiple ? 'multiple' : '';
}
}
private removeElementFromList(file) {
const index = this.field.value.indexOf(file);
// remove from content too
if (index !== -1) {
this.field.value.splice(index, 1);
this.field.json.value = this.field.value;
this.field.updateForm();
}
this.hasFile = this.field.value.length > 0;
this.resetFormValueWithNoFiles();
}
private resetFormValueWithNoFiles() {
if (this.field.value.length === 0) {
this.field.value = [];
this.field.json.value = [];
}
}
fileClicked(contentLinkModel: any): void {
}
}

View File

@@ -0,0 +1,47 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FlexLayoutModule } from '@angular/flex-layout';
import { TemplateModule, FormBaseModule, PipeModule, CoreModule } from '@alfresco/adf-core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormCloudComponent } from './components/form-cloud.component';
import { UploadCloudWidgetComponent } from './components/upload-cloud.widget';
import { MaterialModule } from '../material.module';
@NgModule({
imports: [
CommonModule,
PipeModule,
TemplateModule,
FlexLayoutModule,
MaterialModule,
FormsModule,
ReactiveFormsModule,
FormBaseModule,
CoreModule
],
declarations: [FormCloudComponent, UploadCloudWidgetComponent],
entryComponents: [
UploadCloudWidgetComponent
],
exports: [
FormCloudComponent, UploadCloudWidgetComponent
]
})
export class FormCloudModule { }

View File

@@ -0,0 +1,686 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const cloudFormMock = {
'formRepresentation': {
'id': 'form-b661635a-dc3e-4557-914a-3498ed47189c',
'name': 'form-with-all-fields',
'description': '',
'version': 0,
'formDefinition': {
'tabs': [],
'fields': [
{
'fieldType': 'ContainerRepresentation',
'id': '26b10e64-0403-4686-a75b-0d45279ce3a8',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'text1',
'name': 'Text1',
'type': 'text',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': null,
'minLength': 0,
'maxLength': 0,
'minValue': null,
'maxValue': null,
'regexPattern': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'text2',
'name': 'Text2',
'type': 'text',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': null,
'minLength': 0,
'maxLength': 0,
'minValue': null,
'maxValue': null,
'regexPattern': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': '69c1390a-8d8d-423c-8efb-8e43401efa42',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'multilinetext1',
'name': 'Multiline text1',
'type': 'multi-line-text',
'overrideId': false,
'colspan': 1,
'placeholder': null,
'minLength': 0,
'maxLength': 0,
'regexPattern': null,
'required': false,
'readOnly': true,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'multilinetext2',
'name': 'Multiline text2',
'type': 'multi-line-text',
'overrideId': false,
'colspan': 1,
'placeholder': null,
'minLength': 0,
'maxLength': 0,
'regexPattern': null,
'required': false,
'readOnly': true,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': 'df046463-2d65-4388-9ee1-0e1517985215',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'number1',
'overrideId': false,
'name': 'Number1',
'type': 'integer',
'colspan': 1,
'placeholder': null,
'readOnly': true,
'minValue': null,
'maxValue': null,
'required': false,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'number2',
'overrideId': false,
'name': 'Number2',
'type': 'integer',
'colspan': 1,
'placeholder': null,
'readOnly': true,
'minValue': null,
'maxValue': null,
'required': false,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': '9672cc7b-1959-49c9-96be-3816e57bdfc1',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'checkbox1',
'name': 'Checkbox1',
'type': 'boolean',
'required': false,
'readOnly': true,
'colspan': 1,
'overrideId': false,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'checkbox2',
'name': 'Checkbox2',
'type': 'boolean',
'required': false,
'readOnly': true,
'colspan': 1,
'overrideId': false,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': '054d193e-a899-4494-9a3e-b489315b7d57',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'dropdown1',
'name': 'Dropdown1',
'type': 'dropdown',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': null,
'optionType': 'manual',
'options': [],
'endpoint': null,
'requestHeaders': null,
'restUrl': null,
'restResponsePath': null,
'restIdProperty': null,
'restLabelProperty': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'dropdown2',
'name': 'Dropdown2',
'type': 'dropdown',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': null,
'optionType': 'manual',
'options': [],
'endpoint': null,
'requestHeaders': null,
'restUrl': null,
'restResponsePath': null,
'restIdProperty': null,
'restLabelProperty': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': '1f8f0b66-e022-4667-91b4-bbbf2ddc36fb',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'amount1',
'name': 'Amount1',
'type': 'amount',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': '123',
'minValue': null,
'maxValue': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
},
'enableFractions': false,
'currency': '$'
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'amount2',
'name': 'Amount2',
'type': 'amount',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': '123',
'minValue': null,
'maxValue': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
},
'enableFractions': false,
'currency': '$'
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': '541a368b-67ee-4a7c-ae7e-232c050b9e24',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'date1',
'name': 'Date1',
'type': 'date',
'overrideId': false,
'required': false,
'readOnly': true,
'colspan': 1,
'placeholder': null,
'minValue': null,
'maxValue': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
},
'dateDisplayFormat': 'D-M-YYYY'
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'date2',
'name': 'Date2',
'type': 'date',
'overrideId': false,
'required': false,
'readOnly': true,
'colspan': 1,
'placeholder': null,
'minValue': null,
'maxValue': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
},
'dateDisplayFormat': 'D-M-YYYY'
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': 'e79cb7e2-3dc1-4c79-8158-28662c28a9f3',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'radiobuttons1',
'name': 'Radio buttons1',
'type': 'radio-buttons',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': null,
'optionType': 'manual',
'options': [
{
'id': 'option_1',
'name': 'Option 1'
},
{
'id': 'option_2',
'name': 'Option 2'
}
],
'endpoint': null,
'requestHeaders': null,
'restUrl': null,
'restResponsePath': null,
'restIdProperty': null,
'restLabelProperty': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'radiobuttons2',
'name': 'Radio buttons2',
'type': 'radio-buttons',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': null,
'optionType': 'manual',
'options': [
{
'id': 'option_1',
'name': 'Option 1'
},
{
'id': 'option_2',
'name': 'Option 2'
}
],
'endpoint': null,
'requestHeaders': null,
'restUrl': null,
'restResponsePath': null,
'restIdProperty': null,
'restLabelProperty': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': '7c01ed35-be86-4be7-9c28-ed640a5a2ae1',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'AttachFileFieldRepresentation',
'id': 'attachfile1',
'name': 'Attach file1',
'type': 'upload',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2,
'fileSource': {
'serviceId': 'all-file-sources',
'name': 'All file sources'
},
'multiple': false,
'link': false
}
}
],
'2': [
{
'fieldType': 'AttachFileFieldRepresentation',
'id': 'attachfile2',
'name': 'Attach file2',
'type': 'upload',
'value': null,
'required': false,
'readOnly': true,
'overrideId': false,
'colspan': 1,
'placeholder': null,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2,
'fileSource': {
'serviceId': 'all-file-sources',
'name': 'All file sources'
},
'multiple': false,
'link': false
}
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': '07b13b96-d469-4a1e-8a9a-9bb957c68869',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'displayvalue1',
'name': 'Display value1',
'type': 'readonly',
'value': 'No field selected',
'readOnly': true,
'required': false,
'overrideId': false,
'colspan': 1,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2,
'field': {
'id': 'displayvalue',
'name': 'Display value',
'type': 'text'
}
}
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'displayvalue2',
'name': 'Display value2',
'type': 'readonly',
'value': 'No field selected',
'readOnly': true,
'required': false,
'overrideId': false,
'colspan': 1,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2,
'field': {
'id': 'displayvalue',
'name': 'Display value',
'type': 'text'
}
}
}
]
}
},
{
'fieldType': 'ContainerRepresentation',
'id': '1576ef25-c842-494c-ab84-265a1e3bf68d',
'name': 'Label',
'type': 'container',
'tab': null,
'numberOfColumns': 2,
'fields': {
'1': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'displaytext1',
'name': 'Display text1',
'type': 'readonly-text',
'value': 'Display text as part of the form',
'readOnly': true,
'required': false,
'overrideId': false,
'colspan': 1,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
],
'2': [
{
'fieldType': 'FormFieldRepresentation',
'id': 'displaytext2',
'name': 'Display text2',
'type': 'readonly-text',
'value': 'Display text as part of the form',
'readOnly': true,
'required': false,
'overrideId': false,
'colspan': 1,
'visibilityCondition': null,
'params': {
'existingColspan': 1,
'maxColspan': 2
}
}
]
}
}
],
'outcomes': [],
'javascriptEvents': [],
'className': '',
'style': '',
'customFieldTemplates': {},
'metadata': {},
'variables': [
{
'name': 'FormVarStr',
'type': 'string',
'value': ''
},
{
'name': 'FormVarInt',
'type': 'integer',
'value': ''
},
{
'name': 'FormVarBool',
'type': 'boolean',
'value': ''
},
{
'name': 'FormVarDate',
'type': 'date',
'value': ''
},
{
'name': 'NewVar',
'type': 'string',
'value': ''
}
],
'customFieldsValueInfo': {},
'gridsterForm': false
}
},
'processScopeIdentifiers': []
};

View File

@@ -0,0 +1,233 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FormCloudService } from '../services/form-cloud.service';
import { FormCloud } from './form-cloud.model';
import { TabModel, FormFieldModel, ContainerModel, FormOutcomeModel, FormFieldTypes } from '@alfresco/adf-core';
describe('FormCloud', () => {
let formCloudService: FormCloudService;
beforeEach(() => {
formCloudService = new FormCloudService(null, null, null);
});
it('should store original json', () => {
const json = {formRepresentation: {formDefinition: {}}};
const form = new FormCloud(json);
expect(form.json).toBe(json);
});
it('should setup properties with json', () => {
const json = {formRepresentation: {
id: '<id>',
name: '<name>',
taskId: '<task-id>',
taskName: '<task-name>'
}};
const form = new FormCloud(json);
Object.keys(json).forEach((key) => {
expect(form[key]).toEqual(form[key]);
});
});
it('should take form name when task name is missing', () => {
const json = {formRepresentation: {
id: '<id>',
name: '<name>',
formDefinition: {}
}};
const form = new FormCloud(json);
expect(form.taskName).toBe(json.formRepresentation.name);
});
it('should set readonly state from params', () => {
const form = new FormCloud({}, null, true);
expect(form.readOnly).toBeTruthy();
});
it('should check tabs', () => {
const form = new FormCloud();
form.tabs = null;
expect(form.hasTabs()).toBeFalsy();
form.tabs = [];
expect(form.hasTabs()).toBeFalsy();
form.tabs = [new TabModel(null)];
expect(form.hasTabs()).toBeTruthy();
});
it('should check fields', () => {
const form = new FormCloud();
form.fields = null;
expect(form.hasFields()).toBeFalsy();
form.fields = [];
expect(form.hasFields()).toBeFalsy();
const field = new FormFieldModel(<any> form);
form.fields = [new ContainerModel(field)];
expect(form.hasFields()).toBeTruthy();
});
it('should check outcomes', () => {
const form = new FormCloud();
form.outcomes = null;
expect(form.hasOutcomes()).toBeFalsy();
form.outcomes = [];
expect(form.hasOutcomes()).toBeFalsy();
form.outcomes = [new FormOutcomeModel(null)];
expect(form.hasOutcomes()).toBeTruthy();
});
it('should parse tabs', () => {
const json = {formRepresentation: {formDefinition: {
tabs: [
{ id: 'tab1' },
{ id: 'tab2' }
]
}}};
const form = new FormCloud(json);
expect(form.tabs.length).toBe(2);
expect(form.tabs[0].id).toBe('tab1');
expect(form.tabs[1].id).toBe('tab2');
});
it('should parse fields', () => {
const json = {formRepresentation: {formDefinition: {
fields: [
{
id: 'field1',
type: FormFieldTypes.CONTAINER
},
{
id: 'field2',
type: FormFieldTypes.CONTAINER
}
]
}}};
const form = new FormCloud(json);
expect(form.fields.length).toBe(2);
expect(form.fields[0].id).toBe('field1');
expect(form.fields[1].id).toBe('field2');
});
it('should convert missing fields to empty collection', () => {
const json = {formRepresentation: {formDefinition: {
fields: null
}}};
const form = new FormCloud(json);
expect(form.fields).toBeDefined();
expect(form.fields.length).toBe(0);
});
it('should put fields into corresponding tabs', () => {
const json = {formRepresentation: {formDefinition: {
tabs: [
{ id: 'tab1' },
{ id: 'tab2' }
],
fields: [
{ id: 'field1', tab: 'tab1', type: FormFieldTypes.CONTAINER },
{ id: 'field2', tab: 'tab2', type: FormFieldTypes.CONTAINER },
{ id: 'field3', tab: 'tab1', type: FormFieldTypes.DYNAMIC_TABLE },
{ id: 'field4', tab: 'missing-tab', type: FormFieldTypes.DYNAMIC_TABLE }
]
}}};
const form = new FormCloud(json);
expect(form.tabs.length).toBe(2);
expect(form.fields.length).toBe(4);
const tab1 = form.tabs[0];
expect(tab1.fields.length).toBe(2);
expect(tab1.fields[0].id).toBe('field1');
expect(tab1.fields[1].id).toBe('field3');
const tab2 = form.tabs[1];
expect(tab2.fields.length).toBe(1);
expect(tab2.fields[0].id).toBe('field2');
});
it('should create standard form outcomes', () => {
const json = {formRepresentation: {formDefinition: {
fields: [
{ id: 'container1' }
]
}}};
const form = new FormCloud(json);
expect(form.outcomes.length).toBe(3);
expect(form.outcomes[0].id).toBe(FormCloud.SAVE_OUTCOME);
expect(form.outcomes[0].isSystem).toBeTruthy();
expect(form.outcomes[1].id).toBe(FormCloud.COMPLETE_OUTCOME);
expect(form.outcomes[1].isSystem).toBeTruthy();
expect(form.outcomes[2].id).toBe(FormCloud.START_PROCESS_OUTCOME);
expect(form.outcomes[2].isSystem).toBeTruthy();
});
it('should create outcomes only when fields available', () => {
const json = {formRepresentation: {formDefinition: {
fields: null
}}};
const form = new FormCloud(json);
expect(form.outcomes.length).toBe(0);
});
it('should use custom form outcomes', () => {
const json = {formRepresentation: {formDefinition: {
fields: [
{ id: 'container1' }
]},
outcomes: [
{ id: 'custom-1', name: 'custom 1' }
]
}};
const form = new FormCloud(json);
expect(form.outcomes.length).toBe(2);
expect(form.outcomes[0].id).toBe(FormCloud.SAVE_OUTCOME);
expect(form.outcomes[0].isSystem).toBeTruthy();
expect(form.outcomes[1].id).toBe('custom-1');
expect(form.outcomes[1].isSystem).toBeFalsy();
});
it('should get field by id', () => {
const form = new FormCloud({}, null, false, formCloudService);
const field: any = { id: 'field1' };
spyOn(form, 'getFormFields').and.returnValue([field]);
const result = form.getFieldById('field1');
expect(result).toBe(field);
});
});

View File

@@ -0,0 +1,247 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
TabModel, FormWidgetModel, FormOutcomeModel, FormValues,
FormWidgetModelCache, FormFieldModel, ContainerModel, FormFieldTypes,
ValidateFormFieldEvent, FormFieldValidator, FormFieldTemplates } from '@alfresco/adf-core';
import { FormCloudService } from '../services/form-cloud.service';
import { TaskVariableCloud } from './task-variable-cloud.model';
export class FormCloud {
static SAVE_OUTCOME: string = '$save';
static COMPLETE_OUTCOME: string = '$complete';
static START_PROCESS_OUTCOME: string = '$startProcess';
readonly id: string;
nodeId: string;
readonly name: string;
readonly taskId: string;
readonly taskName: string;
private _isValid: boolean = true;
get isValid(): boolean {
return this._isValid;
}
readonly selectedOutcome: string;
readonly json: any;
readOnly: boolean;
processDefinitionId: any;
className: string;
values: FormValues = {};
tabs: TabModel[] = [];
fields: FormWidgetModel[] = [];
outcomes: FormOutcomeModel[] = [];
customFieldTemplates: FormFieldTemplates = {};
fieldValidators: FormFieldValidator[] = [];
constructor(json?: any, formData?: TaskVariableCloud[], readOnly: boolean = false, protected formService?: FormCloudService) {
this.readOnly = readOnly;
if (json && json.formRepresentation && json.formRepresentation.formDefinition) {
this.json = json;
this.id = json.formRepresentation.id;
this.name = json.formRepresentation.name;
this.taskId = json.formRepresentation.taskId;
this.taskName = json.formRepresentation.taskName || json.formRepresentation.name;
this.processDefinitionId = json.formRepresentation.processDefinitionId;
this.customFieldTemplates = json.formRepresentation.formDefinition.customFieldTemplates || {};
this.selectedOutcome = json.formRepresentation.formDefinition.selectedOutcome || {};
this.className = json.formRepresentation.formDefinition.className || '';
const tabCache: FormWidgetModelCache<TabModel> = {};
this.tabs = (json.formRepresentation.formDefinition.tabs || []).map((t) => {
const model = new TabModel(<any> this, t);
tabCache[model.id] = model;
return model;
});
this.fields = this.parseRootFields(json);
if (formData) {
this.loadData(formData);
}
for (let i = 0; i < this.fields.length; i++) {
const field = this.fields[i];
if (field.tab) {
const tab = tabCache[field.tab];
if (tab) {
tab.fields.push(field);
}
}
}
if (json.formRepresentation.formDefinition.fields) {
const saveOutcome = new FormOutcomeModel(<any> this, {
id: FormCloud.SAVE_OUTCOME,
name: 'SAVE',
isSystem: true
});
const completeOutcome = new FormOutcomeModel(<any> this, {
id: FormCloud.COMPLETE_OUTCOME,
name: 'COMPLETE',
isSystem: true
});
const startProcessOutcome = new FormOutcomeModel(<any> this, {
id: FormCloud.START_PROCESS_OUTCOME,
name: 'START PROCESS',
isSystem: true
});
const customOutcomes = (json.formRepresentation.outcomes || []).map((obj) => new FormOutcomeModel(<any> this, obj));
this.outcomes = [saveOutcome].concat(
customOutcomes.length > 0 ? customOutcomes : [completeOutcome, startProcessOutcome]
);
}
}
this.validateForm();
}
hasTabs(): boolean {
return this.tabs && this.tabs.length > 0;
}
hasFields(): boolean {
return this.fields && this.fields.length > 0;
}
hasOutcomes(): boolean {
return this.outcomes && this.outcomes.length > 0;
}
getFieldById(fieldId: string): FormFieldModel {
return this.getFormFields().find((field) => field.id === fieldId);
}
onFormFieldChanged(field: FormFieldModel) {
this.validateField(field);
}
getFormFields(): FormFieldModel[] {
const formFields: FormFieldModel[] = [];
for (let i = 0; i < this.fields.length; i++) {
const field = this.fields[i];
if (field instanceof ContainerModel) {
const container = <ContainerModel> field;
formFields.push(container.field);
container.field.columns.forEach((column) => {
formFields.push(...column.fields);
});
}
}
return formFields;
}
markAsInvalid() {
this._isValid = false;
}
validateForm() {
const errorsField: FormFieldModel[] = [];
const fields = this.getFormFields();
for (let i = 0; i < fields.length; i++) {
if (!fields[i].validate()) {
errorsField.push(fields[i]);
}
}
this._isValid = errorsField.length > 0 ? false : true;
}
/**
* Validates a specific form field, triggers form validation.
*
* @param field Form field to validate.
* @memberof FormCloud
*/
validateField(field: FormFieldModel) {
if (!field) {
return;
}
const validateFieldEvent = new ValidateFormFieldEvent(<any> this, field);
if (!validateFieldEvent.isValid) {
this._isValid = false;
return;
}
if (validateFieldEvent.defaultPrevented) {
return;
}
if (!field.validate()) {
this._isValid = false;
}
this.validateForm();
}
// Activiti supports 3 types of root fields: container|group|dynamic-table
private parseRootFields(json: any): FormWidgetModel[] {
let fields = [];
if (json.formRepresentation.fields) {
fields = json.formRepresentation.fields;
} else if (json.formRepresentation.formDefinition && json.formRepresentation.formDefinition.fields) {
fields = json.formRepresentation.formDefinition.fields;
}
const formWidgetModel: FormWidgetModel[] = [];
for (const field of fields) {
if (field.type === FormFieldTypes.DISPLAY_VALUE) {
// workaround for dynamic table on a completed/readonly form
if (field.params) {
const originalField = field.params['field'];
if (originalField.type === FormFieldTypes.DYNAMIC_TABLE) {
formWidgetModel.push(new ContainerModel(new FormFieldModel(<any> this, field)));
}
}
} else {
formWidgetModel.push(new ContainerModel(new FormFieldModel(<any> this, field)));
}
}
return formWidgetModel;
}
// Loads external data and overrides field values
// Typically used when form definition and form data coming from different sources
private loadData(formData: TaskVariableCloud[]) {
for (const field of this.getFormFields()) {
const fieldValue = formData.find((value) => { return value.name === field.id; });
if (fieldValue) {
field.json.value = fieldValue.value;
field.value = field.parseValue(field.json);
}
}
}
}

View File

@@ -0,0 +1,25 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export class TaskVariableCloud {
name: string;
value: any;
constructor(obj) {
this.name = obj.name || null;
this.value = obj.value || null;
}
}

View File

@@ -0,0 +1,22 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export * from './models/form-cloud.model';
export * from './models/task-variable-cloud.model';
export * from './components/form-cloud.component';
export * from './components/upload-cloud.widget';
export * from './services/form-cloud.service';

View File

@@ -0,0 +1,162 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { FormCloudService } from './form-cloud.service';
import { AlfrescoApiService, CoreModule, setupTestBed, AppConfigService, AppConfigServiceMock } from '@alfresco/adf-core';
import { of } from 'rxjs';
declare let jasmine: any;
const responseBody = {
entry:
{ id: 'id', name: 'name', formKey: 'form-key' }
};
const alfrescoApiServiceStub = {
getInstance() { },
load() { }
};
const oauth2Auth = jasmine.createSpyObj('oauth2Auth', ['callCustomApi']);
describe('Form Cloud service', () => {
let service: FormCloudService;
let apiService: AlfrescoApiService;
const appName = 'app-name';
const taskId = 'task-id';
setupTestBed({
imports: [
NoopAnimationsModule,
CoreModule.forRoot()
],
providers: [
FormCloudService,
{ provide: AlfrescoApiService, useValue: alfrescoApiServiceStub },
{ provide: AppConfigService, useClass: AppConfigServiceMock }
]
});
beforeEach(() => {
service = TestBed.get(FormCloudService);
apiService = TestBed.get(AlfrescoApiService);
spyOn(apiService, 'getInstance').and.returnValue({ oauth2Auth: oauth2Auth });
});
describe('Form tests', () => {
it('should fetch and parse form', (done) => {
const formId = 'form-id';
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ formRepresentation: { id: formId, name: 'task-form', taskId: 'task-id' } }));
service.getForm(appName, formId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.formRepresentation.id).toBe(formId);
expect(result.formRepresentation.name).toBe('task-form');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
done();
});
});
it('should parse valid form json ', () => {
const formId = 'form-id';
const json = { formRepresentation: { id: formId, name: 'task-form', taskId: 'task-id', formDefinition: {} } };
const result = service.parseForm(json);
expect(result).toBeDefined();
expect(result.id).toBe(formId);
expect(result.name).toBe('task-form');
});
});
describe('Task tests', () => {
it('should fetch and parse task', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody));
service.getTask(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.id).toBe(responseBody.entry.id);
expect(result.name).toBe(responseBody.entry.name);
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/rb/v1/tasks/${taskId}`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
done();
});
});
it('should fetch task variables', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve({ content: { name: 'abc' } }));
service.getTaskVariables(appName, taskId).subscribe((result: any) => {
expect(result).toBeDefined();
expect(result.name).toBe('abc');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/rb/v1/tasks/${taskId}/variables`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('GET');
done();
});
});
it('should fetch task form', (done) => {
spyOn(service, 'getTask').and.returnValue(of(responseBody.entry));
spyOn(service, 'getForm').and.returnValue(of({ formRepresentation: { name: 'task-form' } }));
service.getTaskForm(appName, taskId).subscribe((result) => {
expect(result).toBeDefined();
expect(result.formRepresentation.name).toBe('task-form');
expect(result.formRepresentation.taskId).toBe(responseBody.entry.id);
expect(result.formRepresentation.taskName).toBe(responseBody.entry.name);
done();
});
});
it('should save task form', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody));
const formId = 'form-id';
service.saveTaskForm(appName, taskId, formId, {}).subscribe((result: any) => {
expect(result).toBeDefined();
expect(result.id).toBe('id');
expect(result.name).toBe('name');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}/save`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('POST');
done();
});
});
it('should complete task form', (done) => {
oauth2Auth.callCustomApi.and.returnValue(Promise.resolve(responseBody));
const formId = 'form-id';
service.completeTaskForm(appName, taskId, formId, {}, '').subscribe((result: any) => {
expect(result).toBeDefined();
expect(result.id).toBe('id');
expect(result.name).toBe('name');
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[0].endsWith(`${appName}/form/v1/forms/${formId}/submit`)).toBeTruthy();
expect(oauth2Auth.callCustomApi.calls.mostRecent().args[1]).toBe('POST');
done();
});
});
});
});

View File

@@ -0,0 +1,232 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Injectable } from '@angular/core';
import { AlfrescoApiService, LogService, FormValues, AppConfigService, FormOutcomeModel } from '@alfresco/adf-core';
import { throwError, Observable, from } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { TaskDetailsCloudModel } from '../../task/start-task/models/task-details-cloud.model';
import { SaveFormRepresentation, CompleteFormRepresentation } from '@alfresco/js-api';
import { FormCloud } from '../models/form-cloud.model';
import { TaskVariableCloud } from '../models/task-variable-cloud.model';
@Injectable({
providedIn: 'root'
})
export class FormCloudService {
contentTypes = ['application/json']; accepts = ['application/json']; returnType = Object;
constructor(
private apiService: AlfrescoApiService,
private appConfigService: AppConfigService,
private logService: LogService
) {}
getTaskForm(appName: string, taskId: string): Observable<any> {
return this.getTask(appName, taskId).pipe(
switchMap((task: TaskDetailsCloudModel) => {
return this.getForm(appName, task.formKey).pipe(
map((form: any) => {
form.formRepresentation.taskId = task.id;
form.formRepresentation.taskName = task.name;
form.formRepresentation.processDefinitionId = task.processDefinitionId;
form.formRepresentation.processInstanceId = task.processInstanceId;
return form;
})
);
})
);
}
saveTaskForm(appName: string, taskId: string, formId: string, formValues: FormValues): Observable<TaskDetailsCloudModel> {
const apiUrl = this.buildSaveFormUrl(appName, formId);
const saveFormRepresentation = <SaveFormRepresentation> { values: formValues, taskId: taskId };
return from(this.apiService
.getInstance()
.oauth2Auth.callCustomApi(apiUrl, 'POST',
null, null, null,
null, saveFormRepresentation,
this.contentTypes, this.accepts,
this.returnType, null, null)
).pipe(
map((res: any) => {
return new TaskDetailsCloudModel(res.entry);
}),
catchError((err) => this.handleError(err))
);
}
createTemporaryRawRelatedContent(file, nodeId): Observable<any> {
const apiUrl = this.buildUploadUrl(nodeId);
return from(this.apiService
.getInstance()
.oauth2Auth.callCustomApi(apiUrl, 'POST',
null, null, null,
{ filedata: file, nodeType: 'cm:content' }, null,
['multipart/form-data'], this.accepts,
this.returnType, null, null)
).pipe(
map((res: any) => {
return (res.entry);
}),
catchError((err) => this.handleError(err))
);
}
completeTaskForm(appName: string, taskId: string, formId: string, formValues: FormValues, outcome: string): Observable<TaskDetailsCloudModel> {
const apiUrl = this.buildSubmitFormUrl(appName, formId);
const completeFormRepresentation: any = <CompleteFormRepresentation> { values: formValues, taskId: taskId };
if (outcome) {
completeFormRepresentation.outcome = outcome;
}
return from(this.apiService
.getInstance()
.oauth2Auth.callCustomApi(apiUrl, 'POST',
null, null, null,
null, completeFormRepresentation,
this.contentTypes, this.accepts,
this.returnType, null, null)
).pipe(
map((res: any) => {
return new TaskDetailsCloudModel(res.entry);
}),
catchError((err) => this.handleError(err))
);
}
getTask(appName: string, taskId: string): Observable<TaskDetailsCloudModel> {
const apiUrl = this.buildGetTaskUrl(appName, taskId);
return from(this.apiService
.getInstance()
.oauth2Auth.callCustomApi(apiUrl, 'GET',
null, null, null,
null, null,
this.contentTypes, this.accepts,
this.returnType, null, null)
).pipe(
map((res: any) => {
return new TaskDetailsCloudModel(res.entry);
}),
catchError((err) => this.handleError(err))
);
}
getProcessStorageFolderTask(appName: string, taskId: string): Observable<any> {
const apiUrl = this.buildFolderTask(appName, taskId);
return from(this.apiService
.getInstance()
.oauth2Auth.callCustomApi(apiUrl, 'GET',
null, null, null,
null, null,
this.contentTypes, this.accepts,
this.returnType, null, null)
).pipe(
map((res: any) => {
return res.nodeId;
}),
catchError((err) => this.handleError(err))
);
}
getTaskVariables(appName: string, taskId: string): Observable<TaskVariableCloud[]> {
const apiUrl = this.buildGetTaskVariablesUrl(appName, taskId);
return from(this.apiService
.getInstance()
.oauth2Auth.callCustomApi(apiUrl, 'GET',
null, null, null,
null, null,
this.contentTypes, this.accepts,
this.returnType, null, null)
).pipe(
map((res: any) => {
return <TaskVariableCloud[]> res.content;
}),
catchError((err) => this.handleError(err))
);
}
getForm(appName: string, taskId: string): Observable<any> {
const apiUrl = this.buildGetFormUrl(appName, taskId);
const bodyParam = {}, pathParams = {}, queryParams = {}, headerParams = {},
formParams = {};
return from(
this.apiService
.getInstance()
.oauth2Auth.callCustomApi(
apiUrl, 'GET', pathParams, queryParams,
headerParams, formParams, bodyParam,
this.contentTypes, this.accepts, this.returnType, null, null)
).pipe(
catchError((err) => this.handleError(err))
);
}
parseForm(json: any, data?: TaskVariableCloud[], readOnly: boolean = false): FormCloud {
if (json) {
const form = new FormCloud(json, data, readOnly, this);
if (!json.fields) {
form.outcomes = [
new FormOutcomeModel(<any> form, {
id: '$save',
name: FormOutcomeModel.SAVE_ACTION,
isSystem: true
})
];
}
return form;
}
return null;
}
private buildGetTaskUrl(appName: string, taskId: string): string {
return `${this.appConfigService.get('bpmHost')}/${appName}/rb/v1/tasks/${taskId}`;
}
private buildGetFormUrl(appName: string, formId: string): string {
return `${this.appConfigService.get('bpmHost')}/${appName}/form/v1/forms/${formId}`;
}
private buildSaveFormUrl(appName: string, formId: string): string {
return `${this.appConfigService.get('bpmHost')}/${appName}/form/v1/forms/${formId}/save`;
}
private buildUploadUrl(nodeId: string): string {
return `${this.appConfigService.get('ecmHost')}/alfresco/api/-default-/public/alfresco/versions/1/nodes/${nodeId}/children`;
}
private buildSubmitFormUrl(appName: string, formId: string): string {
return `${this.appConfigService.get('bpmHost')}/${appName}/form/v1/forms/${formId}/submit`;
}
private buildGetTaskVariablesUrl(appName: string, taskId: string): string {
return `${this.appConfigService.get('bpmHost')}/${appName}/rb/v1/tasks/${taskId}/variables`;
}
private buildFolderTask(appName: string, taskId: string): string {
return `${this.appConfigService.get('bpmHost')}/${appName}/process-storage/v1/folders/tasks/${taskId}`;
}
private handleError(error: any) {
this.logService.error(error);
return throwError(error || 'Server error');
}
}

View File

@@ -20,7 +20,7 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { FlexLayoutModule } from '@angular/flex-layout';
import { TemplateModule, FormModule, PipeModule, CoreModule } from '@alfresco/adf-core';
import { TemplateModule, PipeModule, CoreModule } from '@alfresco/adf-core';
import { MaterialModule } from '../material.module';
import { GroupCloudComponent } from './components/group-cloud.component';
import { InitialGroupNamePipe } from './pipe/group-initial.pipe';
@@ -34,7 +34,6 @@ import { InitialGroupNamePipe } from './pipe/group-initial.pipe';
MaterialModule,
FormsModule,
ReactiveFormsModule,
FormModule,
CoreModule
],
declarations: [GroupCloudComponent, InitialGroupNamePipe],

View File

@@ -21,6 +21,7 @@ import { AppListCloudModule } from './app/app-list-cloud.module';
import { TaskCloudModule } from './task/task-cloud.module';
import { ProcessCloudModule } from './process/process-cloud.module';
import { GroupCloudModule } from './group/group-cloud.module';
import { FormCloudModule } from './form/form-cloud.module';
@NgModule({
imports: [
@@ -28,7 +29,8 @@ import { GroupCloudModule } from './group/group-cloud.module';
AppListCloudModule,
ProcessCloudModule,
TaskCloudModule,
GroupCloudModule
GroupCloudModule,
FormCloudModule
],
providers: [
{
@@ -44,7 +46,8 @@ import { GroupCloudModule } from './group/group-cloud.module';
AppListCloudModule,
ProcessCloudModule,
TaskCloudModule,
GroupCloudModule
GroupCloudModule,
FormCloudModule
]
})
export class ProcessServicesCloudModule { }

View File

@@ -20,7 +20,7 @@ import { ProcessFiltersCloudModule } from './process-filters/process-filters-clo
import { ProcessListCloudModule } from './process-list/process-list-cloud.module';
import { StartProcessCloudModule } from './start-process/start-process-cloud.module';
import { CoreModule } from '@alfresco/adf-core';
import { ProcessHeaderCloudModule } from './process-header/public-api';
import { ProcessHeaderCloudModule } from './process-header/process-header-cloud.module';
@NgModule({
imports: [

View File

@@ -17,7 +17,7 @@
import { Component, Input, OnChanges } from '@angular/core';
import { CardViewItem, CardViewTextItemModel, TranslationService, AppConfigService, CardViewDateItemModel, CardViewBaseItemModel } from '@alfresco/adf-core';
import { ProcessInstanceCloud } from '../../start-process/public-api';
import { ProcessInstanceCloud } from '../../start-process/models/process-instance-cloud.model';
import { ProcessHeaderCloudService } from '../services/process-header-cloud.service';
@Component({

View File

@@ -19,7 +19,7 @@ import { AlfrescoApiService, LogService, AppConfigService } from '@alfresco/adf-
import { Injectable } from '@angular/core';
import { Observable, from, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { ProcessInstanceCloud } from '../../start-process/public-api';
import { ProcessInstanceCloud } from '../../start-process/models/process-instance-cloud.model';
@Injectable({
providedIn: 'root'

View File

@@ -31,7 +31,7 @@ import {
UserPreferenceValues
} from '@alfresco/adf-core';
import { PeopleCloudComponent } from './people-cloud/people-cloud.component';
import { GroupCloudComponent } from '../../../../lib/group/public-api';
import { GroupCloudComponent } from '../../../../lib/group/components/group-cloud.component';
@Component({
selector: 'adf-cloud-start-task',

View File

@@ -19,7 +19,7 @@ import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MaterialModule } from '../../material.module';
import { TemplateModule, FormModule, PipeModule, CoreModule } from '@alfresco/adf-core';
import { TemplateModule, PipeModule, CoreModule } from '@alfresco/adf-core';
import { StartTaskCloudComponent } from './components/start-task-cloud.component';
import { StartTaskCloudService } from './services/start-task-cloud.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@@ -36,7 +36,6 @@ import { GroupCloudModule } from '../../group/group-cloud.module';
FormsModule,
ReactiveFormsModule,
GroupCloudModule,
FormModule,
GroupCloudModule,
CoreModule
],

View File

@@ -21,7 +21,7 @@ import { CommonModule } from '@angular/common';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MaterialModule } from '../../../material.module';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TemplateModule, TranslateLoaderService, FormModule, PipeModule } from '@alfresco/adf-core';
import { TemplateModule, TranslateLoaderService, PipeModule } from '@alfresco/adf-core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { StartTaskCloudModule } from '../start-task-cloud.module';
@@ -41,7 +41,6 @@ import { StartTaskCloudModule } from '../start-task-cloud.module';
MaterialModule,
FormsModule,
ReactiveFormsModule,
FormModule,
PipeModule,
StartTaskCloudModule
]

View File

@@ -22,3 +22,4 @@ export * from './lib/process/public-api';
export * from './lib/task/public-api';
export * from './lib/group/public-api';
export * from './lib/services/public-api';
export * from './lib/form/public-api';