From 73159ce4a2381e75851222c403f7c33a1b013531 Mon Sep 17 00:00:00 2001 From: "mathias.chouet" <mathias.chouet@irstea.fr> Date: Tue, 26 Feb 2019 12:28:48 +0100 Subject: [PATCH] =?UTF-8?q?Refonte=20syst=C3=A8me=20de=20structures=20en?= =?UTF-8?q?=20parall=C3=A8le:=20premier=20jet=20Fix=20#144?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit possibilité d'instancier un fieldset dans un fieldset-container avec un Nub existant (Structure) les Nub Structure ne sont plus stockés en session simplification de l'ajout / suppression de Structure dans un fieldset-container --- src/app/app.component.ts | 2 + .../fieldset-container.component.ts | 10 ++-- .../calculator.component.ts | 15 ++---- .../param-link/param-link.component.ts | 1 - .../concrete/form-parallel-structures.ts | 53 +++++++++++++++---- .../formulaire/definition/form-definition.ts | 23 ++++---- src/app/formulaire/fieldset-container.ts | 5 +- src/app/formulaire/fieldset-template.ts | 9 ++-- src/app/formulaire/fieldset.ts | 19 +++++-- .../services/formulaire/formulaire.service.ts | 49 ++++++++--------- src/app/services/param/param.service.ts | 14 ----- 11 files changed, 110 insertions(+), 90 deletions(-) diff --git a/src/app/app.component.ts b/src/app/app.component.ts index d70c14882..02ecfc782 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -384,6 +384,8 @@ export class AppComponent implements OnInit, OnDestroy, Observer { const form = this.formulaireService.getFormulaireFromId(c.uid); this.formulaireService.requestCloseForm(form.uid); } + // just to be sure, get rid of any Nub possibly stuck in session without any form attached + Session.getInstance().clearSession(); } }); } diff --git a/src/app/components/fieldset-container/fieldset-container.component.ts b/src/app/components/fieldset-container/fieldset-container.component.ts index 75caa880f..15ca4d3e3 100644 --- a/src/app/components/fieldset-container/fieldset-container.component.ts +++ b/src/app/components/fieldset-container/fieldset-container.component.ts @@ -68,7 +68,7 @@ export class FieldsetContainerComponent implements DoCheck, AfterViewInit { } } - private onFielsetListChange() { + private onFieldsetListChange() { // affichage des boutons ajouter, supprimer, monter, descendre this._fieldsetComponents.forEach(fs => fs.showButtons = true); @@ -100,8 +100,8 @@ export class FieldsetContainerComponent implements DoCheck, AfterViewInit { } public ngAfterViewInit() { - this.onFielsetListChange(); - this._fieldsetComponents.changes.subscribe(_ => this.onFielsetListChange()); + this.onFieldsetListChange(); + this._fieldsetComponents.changes.subscribe(_ => this.onFieldsetListChange()); } /* @@ -131,13 +131,13 @@ export class FieldsetContainerComponent implements DoCheck, AfterViewInit { // accumulator (valeur précédente du résultat) acc, // currentValue (élément courant dans le tableau) - fielset, + fieldset, // currentIndex (indice courant dans le tableau) currIndex, // array (tableau parcouru) array ) => { - return acc && fielset.isValid; + return acc && fieldset.isValid; } // valeur initiale , this._fieldsetComponents.length > 0); diff --git a/src/app/components/generic-calculator/calculator.component.ts b/src/app/components/generic-calculator/calculator.component.ts index ebf3722c8..4ca3d3bd4 100644 --- a/src/app/components/generic-calculator/calculator.component.ts +++ b/src/app/components/generic-calculator/calculator.component.ts @@ -1,7 +1,7 @@ import { Component, OnInit, DoCheck, OnDestroy, ViewChild, ViewChildren, QueryList, AfterViewChecked } from "@angular/core"; import { ActivatedRoute, Router } from "@angular/router"; -import { Observer, Session } from "jalhyd"; +import { Observer, Session, ParallelStructure } from "jalhyd"; import { FormulaireService } from "../../services/formulaire/formulaire.service"; import { I18nService } from "../../services/internationalisation/internationalisation.service"; @@ -209,17 +209,6 @@ export class GenericCalculatorComponent extends BaseComponent implements OnInit, this.formulaireService.requestCloseForm(this._formulaire.uid); } - /** - * met à jour l'interface - */ - // private updateUI() { - // // this.appRef.tick(); - // // this.changeDetectorRef.detectChanges(); // provoque une détection des changements dans les contrôles - // // if (!this.changeDetectorRef['destroyed']) // pour éviter l'erreur "Attempt to use a destroyed view: detectChanges" - // // this.changeDetectorRef.detectChanges(); - // this.changeDetectorRef.markForCheck(); - // } - /** * relit les valeurs dans l'interface et met à jour les NgParameter */ @@ -413,10 +402,12 @@ export class GenericCalculatorComponent extends BaseComponent implements OnInit, * Duplicates the current calculator form */ public cloneCalculator() { + // console.log("__Nubs en session avt", Session.getInstance()["_nubs"].length); const serialisedNub: string = this._formulaire.currentNub.serialise({ title: this._formulaire.calculatorName }); const nubPointer = Session.getInstance().unserialiseSingleNub(serialisedNub); this.formulaireService.createFormulaire(nubPointer.nub.calcType, nubPointer.nub, nubPointer.meta.title).then((f) => { this.router.navigate(["/calculator", f.uid]); }); + // console.log("__Nubs en session apr", Session.getInstance()["_nubs"].length); } } diff --git a/src/app/components/param-link/param-link.component.ts b/src/app/components/param-link/param-link.component.ts index 0a11c36f6..2ef78c3ab 100644 --- a/src/app/components/param-link/param-link.component.ts +++ b/src/app/components/param-link/param-link.component.ts @@ -167,7 +167,6 @@ export class ParamLinkComponent implements OnChanges, Observer, OnDestroy { public updateParamList() { // liste des paramètres liables - if (this.param.valueMode === ParamValueMode.LINK) { this._linkableParams = this._formService.filterLinkableValues(this._formService.getLinkableValues(this.param)); } else { diff --git a/src/app/formulaire/definition/concrete/form-parallel-structures.ts b/src/app/formulaire/definition/concrete/form-parallel-structures.ts index 37bbdc962..c4a773fce 100644 --- a/src/app/formulaire/definition/concrete/form-parallel-structures.ts +++ b/src/app/formulaire/definition/concrete/form-parallel-structures.ts @@ -1,4 +1,4 @@ -import { Structure, Nub, ParallelStructure, StructureType, LoiDebit, StructureProperties, Props } from "jalhyd"; +import { Structure, Nub, ParallelStructure, StructureType, LoiDebit, StructureProperties, Props, Session } from "jalhyd"; import { FormulaireDefinition } from "../form-definition"; import { CalculatorResults } from "../../../results/calculator-results"; @@ -51,8 +51,7 @@ export class FormulaireParallelStructure extends FormulaireDefinition { params["structureType"] = templ.defaultStructTypeFromConfig; params["loiDebit"] = templ.defaultLoiDebitFromConfig; - // specify the parent Nub to check admissible laws - return this.createNub(new Props(params), this.currentNub as ParallelStructure); + return this.createStructure(new Props(params)); } /** @@ -68,14 +67,48 @@ export class FormulaireParallelStructure extends FormulaireDefinition { return this.currentNub as ParallelStructure; } - public createFieldset(parent: FormulaireNode, json: {}, data?: {}): FieldSet { + /** + * Asks JaLHyd to create a Structure Nub as a child of the current Calculator Module + * and return it; does not store it in the Session (for Structures, not for Calculator Modules) + * @param p properties for the new Nub + */ + protected createStructure(p: Props): Structure { + return Session.getInstance().createNub(p, this.currentNub as ParallelStructure) as Structure; + } + + /** + * Replaces the current Nub in the current calculator module, with a new one built with properties "params" + * @param params properties to build the new Nub (calcType, loiDebit...) + */ + protected replaceNub(sn: Structure, params: Props): Nub { + const parent = (this.currentNub as ParallelStructure); + const newStructure = this.createStructure(params); + parent.replaceStructureInplace(sn, newStructure); + return newStructure; + } + + /** + * Deleted the given child Nub in the current calculator module + * @param params properties to build the new Nub (calcType, loiDebit...) + */ + protected deleteNub(sn: Structure) { + const parent = (this.currentNub as ParallelStructure); + parent.deleteStructure(parent.getIndexForStructure(sn)); + } + + public createFieldset(parent: FormulaireNode, json: {}, data?: {}, nub?: Nub): FieldSet { if (json["calcType"] === "Structure") { // indice après lequel insérer le nouveau FieldSet const after = data["after"]; const res: FieldSet = new FieldSet(parent); - const sn = this.createStructNub(data["template"]); - this.addStructureNub(sn as Structure, after); + let sn: Nub; + if (nub) { // use existing Nub (build interface based on model) + sn = nub; + } else { + sn = this.createStructNub(data["template"]); + this.addStructureNub(sn as Structure, after); + } res.setNub(sn, false); if (after !== undefined) { @@ -139,12 +172,14 @@ export class FormulaireParallelStructure extends FormulaireDefinition { } public removeFieldset(fs: FieldSet) { + // console.log("==> FormParallelStructures removeFieldset", fs.uid); if (fs.nub instanceof Structure) { - // suppression du nub - this._paramService.deleteNub(fs.nub); + // suppression du sous-nub dans le Nub parent + this.deleteNub(fs.nub); // suppression du fieldset this.fieldsetContainer.removeFieldset(fs); + // console.log("====> nb struct dans le parent après", (this.currentNub as ParallelStructure).structures.length); this.resetResults(); } else { super.removeFieldset(fs); } @@ -361,7 +396,7 @@ export class FormulaireParallelStructure extends FormulaireDefinition { switch (sender.id) { case "fs_ouvrage": const props = this.adjustProperties(sender, data["name"], data["value"]); - const newNub = this.replaceNub(sender.nub, props, this.currentNub as ParallelStructure); + const newNub = this.replaceNub((sender.nub as Structure), props); sender.setNub(newNub); this.reset(); break; diff --git a/src/app/formulaire/definition/form-definition.ts b/src/app/formulaire/definition/form-definition.ts index 359709ca1..b70997fea 100644 --- a/src/app/formulaire/definition/form-definition.ts +++ b/src/app/formulaire/definition/form-definition.ts @@ -110,24 +110,24 @@ export abstract class FormulaireDefinition extends FormulaireNode implements Obs } /** - * Asks the ParamService to create a Nub + * Asks JaLHyd to create a Nub and keep in in the Session (for Calculator Modules, not for Structures) * @param p properties for the new Nub * @param parentNub optional parent Nub when creating a Structure Nub, for admissible laws check */ - protected createNub(p: Props, parentNub?: ParallelStructure): Nub { - return this._paramService.createNub(p, parentNub); + protected createNub(p: Props): Nub { + return Session.getInstance().createSessionNub(p); } - protected replaceCurrentNub(params: Props, parentNub?: ParallelStructure) { - this.currentNub = Session.getInstance().replaceNub(this._currentNub, params, parentNub); + protected replaceCurrentNub(params: Props) { + this.currentNub = Session.getInstance().replaceNub(this._currentNub, params); } - protected replaceNub(sn: Nub, params: Props, parentNub?: ParallelStructure): Nub { - return Session.getInstance().replaceNub(sn, params, parentNub); + protected replaceNub(sn: Nub, params: Props): Nub { + return Session.getInstance().replaceNub(sn, params); } protected deleteNub(sn: Nub) { - this._paramService.deleteNub(sn); + Session.getInstance().deleteNub(sn); } protected initParse() { @@ -151,7 +151,7 @@ export abstract class FormulaireDefinition extends FormulaireNode implements Obs public afterParseFieldset(fs: FieldSet) { } - public createFieldset(parent: FormulaireNode, json: {}, data?: {}): FieldSet { + public createFieldset(parent: FormulaireNode, json: {}, data?: {}, nub?: Nub): FieldSet { const res: FieldSet = new FieldSet(parent); res.setNub(this._currentNub, false); this.kids.push(res); @@ -175,8 +175,8 @@ export abstract class FormulaireDefinition extends FormulaireNode implements Obs public removeFieldset(fs: FieldSet) { } - private parse_fieldset(json: {}) { - const fs = this.createFieldset(this, json); + private parse_fieldset(json: {}, nub?: Nub) { + const fs = this.createFieldset(this, json, undefined, nub); fs.parseConfig(json); this.afterParseFieldset(fs); } @@ -491,7 +491,6 @@ export abstract class FormulaireDefinition extends FormulaireNode implements Obs * @param uidMap table de correspondance uid dans le fichier de conf <-> uid en mémoire */ public updateParamsLinks(json: {}, uidMap: {}[]) { - console.log("++ UPDATE PARAMS LINKS (form definition) ++"); for (const ks in json) { switch (ks) { case "elements": diff --git a/src/app/formulaire/fieldset-container.ts b/src/app/formulaire/fieldset-container.ts index 38f5bdb34..b94eac578 100644 --- a/src/app/formulaire/fieldset-container.ts +++ b/src/app/formulaire/fieldset-container.ts @@ -3,6 +3,7 @@ import { FieldSet } from "./fieldset"; import { FieldsetTemplate } from "./fieldset-template"; import { StringMap } from "../stringmap"; import { FormulaireNode } from "./formulaire-node"; +import { Nub } from "jalhyd"; export class FieldsetContainer extends FormulaireElement { private _templates: FieldsetTemplate[]; @@ -75,10 +76,10 @@ export class FieldsetContainer extends FormulaireElement { * @param templateIndex indice du template dans la liste * @param after insère le nouveau FieldSet après cette position, à la fin sinon */ - public addFromTemplate(templateIndex: number, after?: number): FieldSet { + public addFromTemplate(templateIndex: number, after?: number, nub?: Nub): FieldSet { const templ: FieldsetTemplate = this._templates[templateIndex]; - const inst: FieldSet = templ.instantiateTemplate(this, after); + const inst: FieldSet = templ.instantiateTemplate(this, after, nub); this.updateLocalisation(); diff --git a/src/app/formulaire/fieldset-template.ts b/src/app/formulaire/fieldset-template.ts index 3b12fa0d1..1a47ec12d 100644 --- a/src/app/formulaire/fieldset-template.ts +++ b/src/app/formulaire/fieldset-template.ts @@ -1,5 +1,5 @@ import { FieldSet } from "./fieldset"; -import { CalculatorType, ComputeNodeType, StructureType, LoiDebit } from "jalhyd"; +import { CalculatorType, ComputeNodeType, StructureType, LoiDebit, Nub } from "jalhyd"; import { FormulaireDefinition } from "./definition/form-definition"; import { FieldsetContainer } from "./fieldset-container"; @@ -40,11 +40,12 @@ export class FieldsetTemplate { /** * crée une instance de Fieldset et l'ajoute dans un conteneur * @param cont conteneur - * @param at position à laquelle on ajoute le nouveau FieldSet + * @param after position à laquelle on ajoute le nouveau FieldSet + * @param nub Nub existant à injecter dans le Fieldset */ - public instantiateTemplate(cont: FieldsetContainer, after: number): FieldSet { + public instantiateTemplate(cont: FieldsetContainer, after: number, nub?: Nub): FieldSet { const parentForm = cont.parent as FormulaireDefinition; - const res = parentForm.createFieldset(cont, this._jsonConfig, { "template": this, "after": after }); + const res = parentForm.createFieldset(cont, this._jsonConfig, { "template": this, "after": after }, nub); res.parseConfig(this._jsonConfig); parentForm.afterParseFieldset(res); return res; diff --git a/src/app/formulaire/fieldset.ts b/src/app/formulaire/fieldset.ts index 8138991f9..489d736ea 100644 --- a/src/app/formulaire/fieldset.ts +++ b/src/app/formulaire/fieldset.ts @@ -133,6 +133,7 @@ export class FieldSet extends FormulaireElement implements Observer { * @param default_radio_config config du radio fixé/à varier/à calculer */ private parse_input(json: {}, default_radio_config: string): NgParameter { + // console.log("parsing input", json); const input_id: string = json["id"]; const paramService: ParamService = ServiceFactory.instance.paramService; @@ -211,7 +212,7 @@ export class FieldSet extends FormulaireElement implements Observer { } /** - * @param createOrUpdate true pour forcer la création d'un Nub + * @TODO WTF ? */ private updateFields() { this.clearFields(); @@ -254,6 +255,10 @@ export class FieldSet extends FormulaireElement implements Observer { this.applyDependencies(); } + /** + * Set fieldset properties fron config file, unless config is already set (ex: structureType + * and loiDebit when deserialising existing structures) + */ public parseConfig(json: {}, data?: {}) { this._jsonConfig = json; @@ -261,19 +266,23 @@ export class FieldSet extends FormulaireElement implements Observer { const parentForm = this.parentForm as FormulaireDefinition; const ct: string = json["calcType"]; - const calc_type: CalculatorType = ct ? CalculatorType[ct] : parentForm.calculatorType; + const currentCt = this.properties.getPropValue("calcType"); + const calc_type: CalculatorType = currentCt ? currentCt : (ct ? CalculatorType[ct] : parentForm.calculatorType); this.setPropValue("calcType", calc_type); const dnt: string = json["defaultNodeType"]; - const node_type: ComputeNodeType = dnt ? ComputeNodeType[dnt] : parentForm.nodeType; + const currentNt = this.properties.getPropValue("nodeType"); + const node_type: ComputeNodeType = currentNt ? currentNt : (dnt ? ComputeNodeType[dnt] : parentForm.nodeType); this.setPropValue("nodeType", node_type); const st: string = json["defaultStructType"]; - if (st) { + const currentSt = this.properties.getPropValue("structureType"); + if (st && ! currentSt) { this.setPropValue("structureType", StructureType[st]); } const ld: string = json["defaultLoiDebit"]; - if (ld) { + const currentLd = this.properties.getPropValue("loiDebit"); + if (ld && ! currentLd) { this.setPropValue("loiDebit", LoiDebit[ld]); } diff --git a/src/app/services/formulaire/formulaire.service.ts b/src/app/services/formulaire/formulaire.service.ts index 4da19c45e..842b8bdd0 100644 --- a/src/app/services/formulaire/formulaire.service.ts +++ b/src/app/services/formulaire/formulaire.service.ts @@ -3,7 +3,7 @@ import { Injectable } from "@angular/core"; import { decode } from "he"; import { saveAs } from "file-saver"; -import { CalculatorType, EnumEx, Observable, ParamDefinition, Session, Nub } from "jalhyd"; +import { CalculatorType, EnumEx, Observable, ParamDefinition, Session, Nub, ParallelStructure } from "jalhyd"; import { HttpService } from "../../services/http/http.service"; import { I18nService } from "../../services/internationalisation/internationalisation.service"; @@ -20,6 +20,7 @@ import { FormulaireCourbeRemous } from "../../formulaire/definition/concrete/for import { FormulaireRegimeUniforme } from "../../formulaire/definition/concrete/form-regime-uniforme"; import { FormulaireParallelStructure } from "../../formulaire/definition/concrete/form-parallel-structures"; import { NgParameter } from "../../formulaire/ngparam"; +import { FieldsetContainer } from "../..//formulaire/fieldset-container"; @Injectable() export class FormulaireService extends Observable { @@ -81,20 +82,6 @@ export class FormulaireService extends Observable { }); } - /** - * retourne true si l'uid passé en paramètre est déjà utilisé par un formulaire - * @param uid uid à tester - */ - private formUIDAlreadyUsed(uid: string): boolean { - let alreadyUsed = false; - for (const f of this._formulaires) { - if (f.uid === uid) { - alreadyUsed = true; - } - } - return alreadyUsed; - } - public updateLocalisation() { for (const c of EnumEx.getValues(CalculatorType)) { const prom: Promise<StringMap> = this.loadLocalisation(c); @@ -187,6 +174,16 @@ export class FormulaireService extends Observable { f.calculatorName = decode(this.getLocalisedTitleFromCalculatorType(ct)); } f.parseConfig(); + // add fieldsets for existing structures if needed + if (f.currentNub instanceof ParallelStructure) { + for (s of f.currentNub.structures) { + for (const e of f.allFormElements) { + if (e instanceof FieldsetContainer) { // @TODO manage many containers one day + e.addFromTemplate(0, undefined, s); + } + } + } + } return this.loadUpdateFormulaireLocalisation(f); }).then(fi => { fi.applyDependencies(); @@ -312,9 +309,14 @@ export class FormulaireService extends Observable { } } + /** + * Supprime le formulaire ciblé, et demande à JaLHyd d'effacer son Nub de la Session + * @param uid formulaire à supprimer + */ public requestCloseForm(uid: string) { const form = this.getFormulaireFromId(uid); - if (form !== undefined) { + const nub = form.currentNub; + if (form) { this._formulaires = this._formulaires.filter(f => f.uid !== uid); this.notifyObservers({ @@ -322,6 +324,9 @@ export class FormulaireService extends Observable { "form": form }); } + if (nub) { + Session.getInstance().deleteNub(nub); + } } public get currentFormId() { @@ -452,14 +457,12 @@ export class FormulaireService extends Observable { /** * MAJ des liens entre paramètres lors de la désérialisation */ - - private updateParamsLinks(json: {}, formInfos: any[], oldFormCount: number) { + /* private updateParamsLinks(json: {}, formInfos: any[], oldFormCount: number) { // table de correspondance des uid fichier <-> objets mémoire // forme : tableau d'objets de la forme : // { "type" : <type de l'objet. "form" pour formulaire>, // "old": <uid dans le fichier>, // "new": <uid de l'objet mémoire>} - const uidMap = []; for (const ks in json) { switch (ks) { @@ -477,9 +480,7 @@ export class FormulaireService extends Observable { } } } - // MAJ liens - for (const ks in json) { switch (ks) { case "elements": @@ -496,7 +497,7 @@ export class FormulaireService extends Observable { throw new Error(`session file : invalid key '${ks}' in session object`); } } - } + } */ /** * @returns liste des valeurs liables à un paramètre sous la forme d'un tableau d'objets @@ -505,16 +506,13 @@ export class FormulaireService extends Observable { */ public getLinkableValues(p: NgParameter): any[] { const res: any[] = []; - if (p !== undefined) { for (const f of this._formulaires) { // nub associé au formulaire const sn = f.currentNub; - try { // on vérifie que le paramètre en entrée appartient au nub const np = sn.getParameter(p.symbol); - // si oui, on demande à exclure des valeurs retournées le résultat du même nom que le paramètre const exclude = np !== undefined ? p.paramDefinition.uid === np.uid : false; // valeurs liables @@ -528,7 +526,6 @@ export class FormulaireService extends Observable { } } } - return res; } diff --git a/src/app/services/param/param.service.ts b/src/app/services/param/param.service.ts index 08744b408..d34637e7c 100644 --- a/src/app/services/param/param.service.ts +++ b/src/app/services/param/param.service.ts @@ -95,18 +95,4 @@ export class ParamService { return p; } - - /** - * Asks the JaLHyd Session to create a Nub - * @param p properties for the new Nub - * @param parentNub optional parent Nub when creating a Structure Nub, for checking admissible laws - */ - public createNub(p: Props, parentNub?: ParallelStructure): Nub { - const truc = Session.getInstance().createSessionNub(p, parentNub); - return truc; - } - - public deleteNub(sn: Nub) { - Session.getInstance().deleteNub(sn); - } } -- GitLab