Skip to content

Commit

Permalink
feat: get information when edit site
Browse files Browse the repository at this point in the history
- Get all fields from specific site.json into editform
- Fix problem redirection if edit object site

- WIP : check how to update specific fields from object
- WIP : check how to manage listOption types site when reload or when
  come back into component after first init

Reviewed-by: andriac
[Refs_ticket]: #5 , #6
  • Loading branch information
andriacap committed Apr 18, 2023
1 parent 774fbe5 commit 6f66ab8
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 76 deletions.
10 changes: 8 additions & 2 deletions backend/gn_module_monitoring/monitoring/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,17 @@ class MonitoringSite(MonitoringObjectGeom):

def preprocess_data(self, data):
type_site_ids = [type_site.id_nomenclature_type_site for type_site in self._model.types_site]
if len(data['types_site']) >0 :
if len(data['types_site']) >0 and all(isinstance(x,int) for x in data['types_site']):
for id_type_site in data['types_site']:
if int(id_type_site) not in type_site_ids:
type_site_ids.append(id_type_site)
#TODO: A enlever une fois qu'on aura enelever le champ "id_nomenclature_type_site" du model et de la bdd
data["id_nomenclature_type_site"]=data["types_site"][0]
else :
for item in data['types_site']:
if int(item['id_nomenclature_type_site']) not in type_site_ids:
type_site_ids.append(id_type_site)
data["id_nomenclature_type_site"]=data["types_site"][0]['id_nomenclature_type_site']
#TODO: A enlever une fois qu'on aura enelever le champ "id_nomenclature_type_site" du model et de la bdd


data['types_site'] = type_site_ids
14 changes: 13 additions & 1 deletion backend/gn_module_monitoring/routes/site.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from gn_module_monitoring.config.repositories import get_config
from gn_module_monitoring.monitoring.models import BibTypeSite, TMonitoringSites, TNomenclatures
from gn_module_monitoring.monitoring.schemas import BibTypeSiteSchema, MonitoringSitesSchema
from gn_module_monitoring.routes.sites_groups import create_or_update_object_api
from gn_module_monitoring.utils.routes import (
create_or_update_object_api_sites_sites_group,
filter_params,
Expand Down Expand Up @@ -128,3 +127,16 @@ def post_sites():
customConfig.update(post_data["dataComplement"][keys]["config"])
get_config(module_code, force=True, customSpecConfig=customConfig)
return create_or_update_object_api_sites_sites_group(module_code, object_type), 201


@blueprint.route("/sites/<int:_id>", methods=["PATCH"])
def pacth_sites(_id):
module_code = "generic"
object_type = "site"
customConfig = dict()
post_data = dict(request.get_json())
for keys in post_data["dataComplement"].keys():
if "config" in post_data["dataComplement"][keys]:
customConfig.update(post_data["dataComplement"][keys]["config"])
get_config(module_code, force=True, customSpecConfig=customConfig)
return create_or_update_object_api_sites_sites_group(module_code, object_type, _id), 201
44 changes: 0 additions & 44 deletions backend/gn_module_monitoring/routes/sites_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,47 +103,3 @@ def handle_validation_error(error):
status_code=422,
payload=error.data,
).to_dict()


# TODO: OPTIMIZE in order to adapt to new monitoring module (entry by sites_groups)


def create_or_update_object_api(module_code, object_type, id=None):
"""
route pour la création ou la modification d'un objet
si id est renseigné, c'est une création (PATCH)
sinon c'est une modification (POST)
:param module_code: reference le module concerne
:param object_type: le type d'object (site, visit, obervation)
:param id : l'identifiant de l'object (de id_base_site pour site)
:type module_code: str
:type object_type: str
:type id: int
:return: renvoie l'object crée ou modifié
:rtype: dict
"""
depth = to_int(request.args.get("depth", 1))

# recupération des données post
post_data = dict(request.get_json())
if module_code != "generic":
module = get_module("module_code", module_code)
else:
module = {"id_module": "generic"}
#TODO : A enlever une fois que le post_data contiendra geometry et type depuis le front
if object_type == "site":
post_data["geometry"]={'type':'Point', 'coordinates':[2.5,50]}
post_data["type"]='Feature'
# on rajoute id_module s'il n'est pas renseigné par défaut ??
if "id_module" not in post_data["properties"]:
module["id_module"] = "generic"
post_data["properties"]["id_module"] = module["id_module"]
else:
post_data["properties"]["id_module"] = module["id_module"]

return (
monitoring_g_definitions.monitoring_object_instance(module_code, object_type, id)
.create_or_update(post_data)
.serialize(depth)
)
2 changes: 1 addition & 1 deletion backend/gn_module_monitoring/utils/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def create_or_update_object_api_sites_sites_group(module_code, object_type, id=N
module["id_module"] = "generic"
post_data["properties"]["id_module"] = module["id_module"]
else:
post_data["properties"]["id_module"] = module.id_module
post_data["properties"]["id_module"] = module["id_module"]

return (
monitoring_g_definitions.monitoring_object_instance(module_code, object_type, id)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ export class MonitoringFormComponentG implements OnInit {
) {}

ngOnInit() {
// TODO: Avoid two subscribes one inside other (code test above doesn't work. When add type site the observable currentdata is not recall)
this._formService.currentData
.pipe(
tap((data) => {
Expand Down Expand Up @@ -272,7 +271,10 @@ export class MonitoringFormComponentG implements OnInit {
const urlPathDetail = [this.obj.urlRelative].concat(urlSegment).join('/');
this.objChanged.emit(this.obj);
this.bEditChange.emit(false);
this._router.navigateByUrl(urlPathDetail);
if (this.obj.urlRelative){
this._router.navigateByUrl(urlPathDetail);
}

}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
></btn-select>
<pnx-monitoring-form-g
[objForm]="form"
#subscritionObjConfig
[obj]="site"
(objChanged)="onObjChanged($event)"
*ngIf="bEdit"
Expand All @@ -25,7 +24,6 @@
*ngIf="!bEdit"
[(bEdit)]="bEdit"
[newParentType]="objParent"
[objectType]="objectType"
[(bEdit)]="bEdit"
[selectedObj]="site"
></pnx-monitoring-properties-g>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { Component, Input, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable, forkJoin } from 'rxjs';
Expand All @@ -12,7 +12,7 @@ import { SitesService, VisitsService } from '../../services/api-geom.service';
import { GeoJSONService } from '../../services/geojson.service';
import { ObjectService } from '../../services/object.service';
import { JsonData } from '../../types/jsondata';
import { FormService } from '@geonature_common/form/form.service';
import { FormService } from '../../services/form.service';
import { MonitoringFormComponentG } from '../monitoring-form-g/monitoring-form.component-g';

@Component({
Expand All @@ -21,13 +21,10 @@ import { MonitoringFormComponentG } from '../monitoring-form-g/monitoring-form.c
styleUrls: ['./monitoring-visits.component.css'],
})
export class MonitoringVisitsComponent extends MonitoringGeomComponent implements OnInit {
@ViewChild('subscritionObjConfig')
monitoringFormComponentG: MonitoringFormComponentG;
site: ISite;
@Input() visits: IVisit[];
@Input() page: IPage;
// colsname: typeof columnNameVisit = columnNameVisit;
objectType: string;
@Input() bEdit: boolean;
form: FormGroup;
colsname: {};
Expand All @@ -41,6 +38,8 @@ export class MonitoringVisitsComponent extends MonitoringGeomComponent implement
placeholderText: string = 'Sélectionnez les types de site';
id_sites_group: number;
types_site: string[];
config: JsonData;
// urlRelative: string;


constructor(
Expand All @@ -56,35 +55,42 @@ export class MonitoringVisitsComponent extends MonitoringGeomComponent implement
) {
super();
this.getAllItemsCallback = this.getVisits;
this.objectType = 'sites';
// this.objectType = 'sites';
}

ngOnInit() {
// this.urlRelative = this.removeLastPart(this._Activatedroute.snapshot['_routerState'].url);
this.funcInitValues = this.initValueToSend.bind(this)
this.funcToFilt = this.partialfuncToFilt.bind(this);
this.form = this._formBuilder.group({});
this._objService.changeObjectTypeParent(this._sites_service.objectObs, true);
this._objService.currentObjectTypeParent.subscribe((objParent) => (this.objParent = objParent));

this._objService.changeObjectType(this._visits_service.objectObs);
this.initSiteVisit()

}

initSiteVisit(){
this._Activatedroute.params
.pipe(
map((params) => params['id'] as number),
mergeMap((id: number) =>
forkJoin({
site: this._sites_service.getById(id),
visits: this._visits_service.get(1, this.limit, {
id_base_site: id,
}),
})
)
.pipe(
map((params) => params['id'] as number),
mergeMap((id: number) =>
forkJoin({
site: this._sites_service.getById(id),
visits: this._visits_service.get(1, this.limit, {
id_base_site: id,
}),
})
)
.subscribe((data: { site: ISite; visits: IPaginated<IVisit> }) => {
this.site = data.site;
this.setVisits(data.visits);
this.baseFilters = { id_base_site: this.site.id_base_site };
});
this.isInitialValues = true;
)
.subscribe((data: { site: ISite; visits: IPaginated<IVisit> }) => {
this._objService.changeSelectedObj(data.site, true);
this.site = data.site;
this.setVisits(data.visits);
this.baseFilters = { id_base_site: this.site.id_base_site };
});
this.isInitialValues = true;
}

getVisits(page: number, filters: JsonData) {
Expand Down Expand Up @@ -121,8 +127,9 @@ export class MonitoringVisitsComponent extends MonitoringGeomComponent implement
}

onSendConfig(config: JsonData): void {
config = this.addTypeSiteListIds(config);
this.monitoringFormComponentG.getConfigFromBtnSelect(config);
this.config = this.addTypeSiteListIds(config);
this.updateForm()
// this.monitoringFormComponentG.getConfigFromBtnSelect(this.config);
}

addTypeSiteListIds(config: JsonData): JsonData {
Expand All @@ -140,4 +147,30 @@ export class MonitoringVisitsComponent extends MonitoringGeomComponent implement
initValueToSend(){
return this.site['types_site']
}

updateForm(){
this.site['specific'] = {};
this.site['dataComplement'] = {};
for (const key in this.config) {
if (this.config[key].config != undefined) {
if (Object.keys(this.config[key].config).length !== 0) {
Object.assign(this.site['specific'], this.config[key].config.specific);
}
}
}
for(var k in this.site.data) this.site[k]=this.site.data[k];
Object.assign(this.site['dataComplement'].dataComplement, this.config);

this._formService.changeDataSub(this.site,
this.objParent.objectType,
this.objParent.endPoint);
}

// removeLastPart(url: string): string {
// return url.slice(0, url.lastIndexOf('/'));
// }

onObjChanged($event) {
this.initSiteVisit();
}
}

0 comments on commit 6f66ab8

Please sign in to comment.