OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Move more form logic into the base changeset
Oliver Günther1fff1312cfdf
diff --git a/frontend/src/app/components/wp-edit-form/work-package-editing-service.ts b/frontend/src/app/components/wp-edit-form/work-package-editing-service.tsindex d181a27ec41..e17ee3596cb 100644--- a/frontend/src/app/components/wp-edit-form/work-package-editing-service.ts+++ b/frontend/src/app/components/wp-edit-form/work-package-editing-service.ts@@ -39,8 +39,8 @@ import {Subject} from "rxjs";import {FormResource} from "core-app/modules/hal/resources/form-resource";import {ChangeMap} from "core-app/modules/fields/changeset/changeset";-class WPChangesStates extends StatesGroup {- name = 'WP-Changesets';+class ChangesetStates extends StatesGroup {+ name = 'Changesets';changesets = multiInput<WorkPackageChangeset>();@@ -94,7 +94,7 @@ export class WorkPackageEditingService extends StateCacheService<WorkPackageChanpublic comittedChanges = new Subject<WorkPackageChangesetCommit>();/** State group of changes to wrap */- private stateGroup = new WPChangesStates();+ private stateGroup = new ChangesetStates();constructor(readonly injector:Injector,readonly wpActivity:WorkPackagesActivityService,@@ -151,7 +151,7 @@ export class WorkPackageEditingService extends StateCacheService<WorkPackageChan*/public reset(change:WorkPackageChangeset) {change.clear();- this.clearSome(change.workPackageId);+ this.clearSome(change.id);}/**diff --git a/frontend/src/app/components/wp-edit/work-package-changeset.ts b/frontend/src/app/components/wp-edit/work-package-changeset.tsindex 10420f27b0f..9186a194c87 100644--- a/frontend/src/app/components/wp-edit/work-package-changeset.ts+++ b/frontend/src/app/components/wp-edit/work-package-changeset.ts@@ -1,75 +1,10 @@-/**- * Temporary class living while a work package is being edited- * Maintains references to:- * - The source work package (a pristine base)- * - The open set of changes (a changeset object)- * - The current form (due to temporary type/project changes)- *- * Provides access to:- * - A projected work package resource with all changes applied- */-import {FormResource} from "core-app/modules/hal/resources/form-resource";import {WorkPackageResource} from "core-app/modules/hal/resources/work-package-resource";-import {HalResource} from "core-app/modules/hal/resources/hal-resource";-import {debugLog} from "core-app/helpers/debug_output";-import {IFieldSchema} from "core-app/modules/fields/field.base";-import {InputState} from "reactivestates";import {ResourceChangeset} from "core-app/modules/fields/changeset/resource-changeset";export class WorkPackageChangeset extends ResourceChangeset<WorkPackageResource> {- /** Reference and load promise for the current form */- private wpFormPromise:Promise<FormResource>|null;-- /** Flag whether this is currently being saved */- public inFlight = false;-- constructor(public pristineResource:WorkPackageResource,- public readonly state?:InputState<WorkPackageChangeset>,- form?:FormResource) {- super(pristineResource, form);- }-- /**- * Push the change to the editing state to notify others.- * This will happen internally on work-package wide changes- *- * (type, project changes)- */- public push() {- if (this.state) {- this.state.putValue(this);- }- }-- /**- * Retrieve the editing value for the given attribute- *- * @param {string} key The attribute to read- * @return {any} Either the value from the overriden change, or the default value- */- public value(key:string) {- // Overridden value by user?- if (this.changeset.contains(key)) {- return this.changeset.get(key);- }-- // Return whatever is on the base.- return this.pristineResource[key];- }-- /**- * Return whether the given value exists,- * even if its undefined.- *- * @param key- */- public valueExists(key:string):boolean {- return this.changeset.contains(key) || this.pristineResource.hasOwnProperty(key);- }-public setValue(key:string, val:any) {- this.changeset.set(key, val);+ super.setValue(key, val);// Update the form for fields that may alter the form itself// when the work package is new. Otherwise, the save request afterwards@@ -79,226 +14,25 @@ export class WorkPackageChangeset extends ResourceChangeset<WorkPackageResource>}}- /**- * Revert all edits on the resource- */- public clear() {- super.clear();- this.state && this.state.clear();- }+ protected applyChanges(payload:any):any {+ // Explicitly delete the description if it was not set by the user.+ // if it was set by the user, #applyChanges will set it again.+ // Otherwise, the backend will set it for us.+ delete payload.description;- /**- * Returns the work package being edited- */- public get workPackageId():string {- return this.pristineResource.id!.toString();+ return super.applyChanges(payload);}- /**- * Return whether the element is writable- * given the current best schema.- *- * @param key- */- public isWritable(key:string) {- const fieldSchema = this.schema[key] as IFieldSchema|null;- return fieldSchema && fieldSchema.writable;- }-- /**- * Return the best humanized name for this attribute- * @param attribute- */- public humanName(attribute:string):string {- return _.get(this.schema, `${attribute}.name`, attribute);- }--- /**- * Build the request attributes against the fresh form- */- public buildRequestPayload():Promise<[FormResource, Object]> {- return this- .updateForm()- .then(form => [form, this.buildPayloadFromChanges()]) as Promise<[FormResource, Object]>;- }-- /**- * Returns the current work package form.- * This may be different from the base form when project or type is changed.- */- public getForm():Promise<FormResource> {- if (!this.form) {- return this.updateForm();- } else {- return Promise.resolve(this.form);- }- }-- public getSchemaName(attribute:string):string {- return this.projectedResource.getSchemaName(attribute);- }-- /**- * Update the form resource from the API.- */- private updateForm():Promise<FormResource> {- let payload = this.buildPayloadFromChanges();-- if (!this.wpFormPromise) {- this.wpFormPromise = this.pristineResource.$links- .update(payload)- .then((form:FormResource) => {- this.wpFormPromise = null;- this.form = form;- this.setNewDefaults(form);- this.push();- return form;- })- .catch((error:any) => {- this.wpFormPromise = null;- this.form = null;- throw error;- }) as Promise<FormResource>;+ protected setNewDefaultFor(key:string, val:unknown) {+ // Special handling for taking over the description+ // to the pristine resource+ if (key === 'description' && this.pristineResource.isNew) {+ this.pristineResource.description = val;+ return;}- return this.wpFormPromise;+ super.setNewDefaultFor(key, val);}- /**- * Create the payload from the current changes, and extend it with the current lock version.- * -- This is the place to add additional logic when the lockVersion changed in between --- */- private buildPayloadFromChanges() {- let payload;-- if (this.pristineResource.isNew) {- // If the work package is new, we need to pass the entire form payload- // to let all default values be transmitted (type, status, etc.)- if (this.form) {- payload = this.form.payload.$source;- } else {- payload = this.pristineResource.$source;- }-- // Add attachments to be assigned.- // They will already be created on the server but now- // we need to claim them for the newly created work package.- payload['_links']['attachments'] = this.pristineResource- .attachments- .elements- .map((a:HalResource) => {- return { href: a.href };- });-- // Explicitly delete the description if it was not set by the user.- // if it was set by the user, #applyChanges will set it again.- // Otherwise, the backend will set it for us.- delete payload.description;-- } else {- // Otherwise, simply use the bare minimum, which is the lock version.- payload = this.minimalPayload;- }-- return this.applyChanges(payload);- }-- private get minimalPayload() {- return { lockVersion: this.pristineResource.lockVersion, _links: {} };- }-- /**- * Merge the current changes into the payload resource.- *- * @param {plainPayload:unknown} A set of attributes to merge into the payload- * @return {any}- */- private applyChanges(plainPayload:any) {- // Fall back to the last known state of the work package should the form not be loaded.- let reference = this.pristineResource.$source;- if (this.form) {- reference = this.form.payload.$source;- }-- _.each(this.changeset.all, (val:unknown, key:string) => {- const fieldSchema:IFieldSchema|undefined = this.schema[key];- if (!(typeof (fieldSchema) === 'object' && fieldSchema.writable)) {- debugLog(`Trying to write ${key} but is not writable in schema`);- return;- }-- // Override in _links if it is a linked property- if (reference._links[key]) {- plainPayload._links[key] = this.getLinkedValue(val, fieldSchema);- } else {- plainPayload[key] = val;- }- });-- return plainPayload;- }-- /**- * Extract the link(s) in the given changed value- */- private getLinkedValue(val:any, fieldSchema:IFieldSchema) {- // Links should always be nullified as { href: null }, but- // this wasn't always the case, so ensure null values are returned as such.- if (_.isNil(val)) {- return { href: null };- }-- // Test if we either have a CollectionResource or a HAL array,- // or a single hal value.- let isArrayType = (fieldSchema.type || '').startsWith('[]');- let isArray = false;-- if (val.forEach || val.elements) {- isArray = true;- }-- if (isArray && isArrayType) {- let links:{ href:string }[] = [];-- if (val) {- let elements = (val.forEach && val) || val.elements;-- elements.forEach((link:{ href:string }) => {- if (link.href) {- links.push({ href: link.href });- }- });- }-- return links;- } else {- return { href: _.get(val, 'href', null) };- }- }-- /**- * When changing type or project, new custom fields may be present- * that we need to set.- */- private setNewDefaults(form:FormResource) {- _.each(form.payload, (val:unknown, key:string) => {- const fieldSchema:IFieldSchema|undefined = this.schema[key];- if (!(typeof (fieldSchema) === 'object' && fieldSchema.writable)) {- return;- }-- // Special handling for taking over the description- // to the pristine resource- if (key === 'description' && this.pristineResource.isNew) {- this.pristineResource.description = val;- }-- if (!this.valueExists(key)) {- debugLog("Taking over default value from form for " + key);- this.setValue(key, val);- }- });- }}diff --git a/frontend/src/app/modules/fields/changeset/resource-changeset.ts b/frontend/src/app/modules/fields/changeset/resource-changeset.tsindex 5aea5e8ba31..0a0bd440ddc 100644--- a/frontend/src/app/modules/fields/changeset/resource-changeset.ts+++ b/frontend/src/app/modules/fields/changeset/resource-changeset.ts@@ -2,11 +2,31 @@ import {SchemaResource} from "core-app/modules/hal/resources/schema-resource";import {FormResource} from "core-app/modules/hal/resources/form-resource";import {HalResource} from "core-app/modules/hal/resources/hal-resource";import {ChangeMap, Changeset} from "core-app/modules/fields/changeset/changeset";+import {WorkPackageResource} from "core-app/modules/hal/resources/work-package-resource";+import {InputState} from "reactivestates";+import {IFieldSchema} from "core-app/modules/fields/field.base";+import {debugLog} from "core-app/helpers/debug_output";-export abstract class ResourceChangeset<T extends HalResource|{ [key:string]:unknown; }> {+/**+ * Temporary class living while a resource is being edited+ * Maintains references to:+ * - The source resource (a pristine base)+ * - The open set of changes (a changeset object)+ * - The current form (due to temporary type/project changes)+ *+ * Provides access to:+ * - The projected resource with all changes applied as properties+ */+export class ResourceChangeset<T extends HalResource|{ [key:string]:unknown; }> {/** Maintain a single change set while editing */protected changeset = new Changeset();+ /** Reference and load promise for the current form */+ private formPromise:Promise<FormResource>|null;++ /** Flag whether this is currently being saved */+ public inFlight = false;+/** The projected resource, which will proxy values from the change set */public projectedResource = new Proxy(this.pristineResource,@@ -19,10 +39,76 @@ export abstract class ResourceChangeset<T extends HalResource|{ [key:string]:unk});- public form:FormResource|null;+ constructor(public pristineResource:T,+ public readonly state?:InputState<ResourceChangeset<T>>,+ public form:FormResource|null = null) {+ }++ /**+ * Push the change to the editing state to notify others.+ * This will happen internally on resource wide changes+ */+ public push() {+ if (this.state) {+ this.state.putValue(this);+ }+ }++ /**+ * Build the request attributes against the fresh form+ */+ public buildRequestPayload():Promise<[FormResource, Object]> {+ return this+ .updateForm()+ .then(form => [form, this.buildPayloadFromChanges()]) as Promise<[FormResource, Object]>;+ }++++ /**+ * Returns the current work package form.+ * This may be different from the base form when project or type is changed.+ */+ public getForm():Promise<FormResource> {+ if (!this.form) {+ return this.updateForm();+ } else {+ return Promise.resolve(this.form);+ }+ }++ public getSchemaName(attribute:string):string {+ if (this.projectedResource.getSchemaName) {+ return this.projectedResource.getSchemaName(attribute);+ } else {+ return attribute;+ }+ }++ /**+ * Update the form resource from the API.+ */+ protected updateForm():Promise<FormResource> {+ let payload = this.buildPayloadFromChanges();++ if (!this.formPromise) {+ this.formPromise = this.pristineResource.$links+ .update(payload)+ .then((form:FormResource) => {+ this.formPromise = null;+ this.form = form;+ this.setNewDefaults(form);+ this.push();+ return form;+ })+ .catch((error:any) => {+ this.formPromise = null;+ this.form = null;+ throw error;+ }) as Promise<FormResource>;+ }- constructor(public pristineResource:T, form?:FormResource) {- this.form = form || null;+ return this.formPromise;}/**@@ -32,6 +118,20 @@ export abstract class ResourceChangeset<T extends HalResource|{ [key:string]:unkreturn this.changeset.changed.length === 0;}+ /**+ * Return the ID of the resource we're editing+ */+ public get id():string {+ return this.pristineResource.id as string;+ }++ /**+ * Return the HAL href of the resource we're editing+ */+ public get href():string {+ return this.pristineResource.href as string;+ }+/*** Return a shallow copy of the changes*/@@ -46,6 +146,25 @@ export abstract class ResourceChangeset<T extends HalResource|{ [key:string]:unkreturn this.changeset.changed;}+ /**+ * Return whether the element is writable+ * given the current best schema.+ *+ * @param key+ */+ public isWritable(key:string) {+ const fieldSchema = this.schema[key] as IFieldSchema|null;+ return fieldSchema && fieldSchema.writable;+ }++ /**+ * Return the best humanized name for this attribute+ * @param attribute+ */+ public humanName(attribute:string):string {+ return _.get(this.schema, `${attribute}.name`, attribute);+ }+/*** Returns whether the given attribute was changed*/@@ -73,22 +192,31 @@ export abstract class ResourceChangeset<T extends HalResource|{ [key:string]:unk* @return {any} Either the value from the overriden change, or the default value*/public value(key:string) {- if (this.isOverridden(key)) {+ // Overridden value by user?+ if (this.changeset.contains(key)) {return this.changeset.get(key);- } else {- return this.pristineResource[key];}++ // Return whatever is on the base.+ return this.pristineResource[key];}- public setValue(key:string, val:any) {- this.changeset.set(key, val);+ /**+ * Return whether the given value exists,+ * even if its undefined.+ *+ * @param key+ */+ public valueExists(key:string):boolean {+ return this.changeset.contains(key) || this.pristineResource.hasOwnProperty(key);}- public getSchemaName(attribute:string):string {- return attribute;+ public setValue(key:string, val:any) {+ this.changeset.set(key, val);}public clear() {+ this.state && this.state.clear();this.changeset.clear();this.form = null;}@@ -118,4 +246,136 @@ export abstract class ResourceChangeset<T extends HalResource|{ [key:string]:unkpublic get schema():SchemaResource {return (this.form || this.pristineResource).schema;}++ protected get minimalPayload() {+ return { lockVersion: this.pristineResource.lockVersion, _links: {} };+ }++ /**+ * Merge the current changes into the payload resource.+ *+ * @param {plainPayload:unknown} A set of attributes to merge into the payload+ * @return {any}+ */+ protected applyChanges(plainPayload:any) {+ // Fall back to the last known state of the HalResource should the form not be loaded.+ let reference = this.pristineResource.$source;+ if (this.form) {+ reference = this.form.payload.$source;+ }++ _.each(this.changeset.all, (val:unknown, key:string) => {+ const fieldSchema:IFieldSchema|undefined = this.schema[key];+ if (!(typeof (fieldSchema) === 'object' && fieldSchema.writable)) {+ debugLog(`Trying to write ${key} but is not writable in schema`);+ return;+ }++ // Override in _links if it is a linked property+ if (reference._links[key]) {+ plainPayload._links[key] = this.getLinkedValue(val, fieldSchema);+ } else {+ plainPayload[key] = val;+ }+ });++ return plainPayload;+ }++ /**+ * Create the payload from the current changes, and extend it with the current lock version.+ * -- This is the place to add additional logic when the lockVersion changed in between --+ */+ protected buildPayloadFromChanges() {+ let payload;++ if (this.pristineResource.isNew) {+ // If the resource is new, we need to pass the entire form payload+ // to let all default values be transmitted (type, status, etc.)+ if (this.form) {+ payload = this.form.payload.$source;+ } else {+ payload = this.pristineResource.$source;+ }++ // Add attachments to be assigned.+ // They will already be created on the server but now+ // we need to claim them for the newly created work package.+ payload['_links']['attachments'] = this.pristineResource+ .attachments+ .elements+ .map((a:HalResource) => {+ return { href: a.href };+ });++ } else {+ // Otherwise, simply use the bare minimum+ payload = this.minimalPayload;+ }++ return this.applyChanges(payload);+ }++ /**+ * Extract the link(s) in the given changed value+ */+ protected getLinkedValue(val:any, fieldSchema:IFieldSchema) {+ // Links should always be nullified as { href: null }, but+ // this wasn't always the case, so ensure null values are returned as such.+ if (_.isNil(val)) {+ return { href: null };+ }++ // Test if we either have a CollectionResource or a HAL array,+ // or a single hal value.+ let isArrayType = (fieldSchema.type || '').startsWith('[]');+ let isArray = false;++ if (val.forEach || val.elements) {+ isArray = true;+ }++ if (isArray && isArrayType) {+ let links:{ href:string }[] = [];++ if (val) {+ let elements = (val.forEach && val) || val.elements;++ elements.forEach((link:{ href:string }) => {+ if (link.href) {+ links.push({ href: link.href });+ }+ });+ }++ return links;+ } else {+ return { href: _.get(val, 'href', null) };+ }+ }++ /**+ * When changing type or project, new custom fields may be present+ * that we need to set.+ */+ protected setNewDefaults(form:FormResource) {+ _.each(form.payload, (val:unknown, key:string) => {+ const fieldSchema:IFieldSchema|undefined = this.schema[key];+ if (!(typeof (fieldSchema) === 'object' && fieldSchema.writable)) {+ return;+ }++ this.setNewDefaultFor(key, val);+ });+ }++ /**+ * Set the default for the given attribute+ */+ protected setNewDefaultFor(key:string, val:unknown) {+ if (!this.valueExists(key)) {+ debugLog("Taking over default value from form for " + key);+ this.setValue(key, val);+ }+ }}diff --git a/frontend/src/app/modules/fields/edit/edit-field.component.ts b/frontend/src/app/modules/fields/edit/edit-field.component.tsindex 87ebfc4fad9..92312d92fff 100644--- a/frontend/src/app/modules/fields/edit/edit-field.component.ts+++ b/frontend/src/app/modules/fields/edit/edit-field.component.ts@@ -65,7 +65,7 @@ export abstract class EditFieldComponent extends Field implements OnInit, OnDestconstructor(readonly I18n:I18nService,readonly elementRef:ElementRef,- @Inject(OpEditingPortalChangesetToken) protected change:WorkPackageChangeset,+ @Inject(OpEditingPortalChangesetToken) protected change:ResourceChangeset<HalResource>,@Inject(OpEditingPortalSchemaToken) public schema:IFieldSchema,@Inject(OpEditingPortalHandlerToken) readonly handler:EditFieldHandler,readonly cdRef:ChangeDetectorRef,