Skip to content

Commit

Permalink
feat: get back work visitcomponent
Browse files Browse the repository at this point in the history
get back work from feat/visit to use visitcomponent
but adapted to current branch

[Refs_ticket]: #5 , #6
  • Loading branch information
andriacap authored and Maxime Vergez committed Apr 14, 2023
1 parent ecf00e1 commit 23350af
Show file tree
Hide file tree
Showing 17 changed files with 440 additions and 13 deletions.
15 changes: 12 additions & 3 deletions backend/gn_module_monitoring/monitoring/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,13 @@ class TMonitoringObservations(TObservations):


@serializable
class TMonitoringVisits(TBaseVisits):
class TMonitoringVisits(TBaseVisits, GenericModel):
__tablename__ = "t_visit_complements"
__table_args__ = {"schema": "gn_monitoring"}
__mapper_args__ = {
'polymorphic_identity': 'monitoring_visit',
}

query_class = MonitoringQuery
id_base_visit = DB.Column(
DB.ForeignKey('gn_monitoring.t_base_visits.id_base_visit'),
nullable=False,
Expand Down Expand Up @@ -220,8 +220,17 @@ class TMonitoringVisits(TBaseVisits):
)


module = DB.relationship(
TModules,
lazy="select",
primaryjoin=(TModules.id_module == TBaseVisits.id_module),
foreign_keys=[TModules.id_module],
uselist=False,
)


@geoserializable(geoCol="geom", idCol="id_base_site")
class TMonitoringSites(TBaseSites):
class TMonitoringSites(TBaseSites, GenericModel):

__tablename__ = 't_site_complements'
__table_args__ = {'schema': 'gn_monitoring'}
Expand Down
17 changes: 15 additions & 2 deletions backend/gn_module_monitoring/monitoring/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import geojson
from geonature.utils.env import MA
from marshmallow import Schema, fields, validate
from geonature.core.gn_commons.schemas import MediaSchema
from geonature.core.gn_commons.schemas import MediaSchema, ModuleSchema

from gn_module_monitoring.monitoring.models import (
BibTypeSite,
TMonitoringSites,
TMonitoringSitesGroups,
TMonitoringVisits
)


Expand Down Expand Up @@ -51,11 +52,14 @@ class Meta:
exclude = ("geom_geojson", "geom")

geometry = fields.Method("serialize_geojson", dump_only=True)
pk = fields.Method("set_pk",dump_only=True)

def serialize_geojson(self, obj):
if obj.geom is not None:
return geojson.dumps(obj.as_geofeature().get("geometry"))


def set_pk(self,obj):
return self.Meta.model.get_id()

class BibTypeSiteSchema(MA.SQLAlchemyAutoSchema):
label = fields.Method("get_label_from_type_site")
Expand All @@ -69,3 +73,12 @@ class Meta:
model = BibTypeSite
include_fk = True
load_instance = True

class MonitoringVisitsSchema(MA.SQLAlchemyAutoSchema):
class Meta:
model = TMonitoringVisits
pk = fields.Method("set_pk",dump_only=True)
module = MA.Nested(ModuleSchema)

def set_pk(self,obj):
return self.Meta.model.get_id()
35 changes: 35 additions & 0 deletions backend/gn_module_monitoring/routes/visit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from flask import request
from sqlalchemy.orm import joinedload
from werkzeug.datastructures import MultiDict

from gn_module_monitoring.blueprint import blueprint
from gn_module_monitoring.monitoring.models import TMonitoringVisits
from gn_module_monitoring.monitoring.schemas import MonitoringVisitsSchema
from gn_module_monitoring.utils.routes import (
filter_params,
get_limit_page,
get_sort,
paginate,
sort,
)

# Retrieves visits that do not depend on modules


@blueprint.route("/visits", methods=["GET"])
def get_visits():
params = MultiDict(request.args)
limit, page = get_limit_page(params=params)
sort_label, sort_dir = get_sort(
params=params, default_sort="id_base_visit", default_direction="desc"
)
query = TMonitoringVisits.query.options(joinedload(TMonitoringVisits.module))
query = filter_params(query=TMonitoringVisits.query, params=params)
query = sort(query=query, sort=sort_label, sort_dir=sort_dir)

return paginate(
query=query,
schema=MonitoringVisitsSchema,
limit=limit,
page=page,
)
27 changes: 27 additions & 0 deletions backend/gn_module_monitoring/tests/fixtures/visit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import datetime

import pytest
from geonature.tests.fixtures import datasets
from geonature.utils.env import db

from gn_module_monitoring.monitoring.models import TMonitoringVisits


@pytest.fixture
def visits(module, users, types_site, sites, datasets):
now = datetime.datetime.now()
dataset = datasets["orphan_dataset"]
db_visits = []
for site in sites.values():
db_visits.append(
TMonitoringVisits(
id_base_site=site.id_base_site,
id_module=module.id_module,
id_dataset=dataset.id_dataset,
visit_date_min=now,
)
)
with db.session.begin_nested():
db.session.add_all(db_visits)

return db_visits
6 changes: 6 additions & 0 deletions frontend/app/class/monitoring-visit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export enum columnNameVisit {
id_module = "Protocol ID",
visit_date_max = "Date max",
visit_date_min = "Date min",
nb_observations = "Nb. observations",
}
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<btn-select
(sendobject)="onSendConfig($event)"
[titleBtn]="titleBtn"
[placeholderText]="placeholderText"
[callBackFunction]="funcToFilt"
[paramToFilt]="paramToFilt"
></btn-select>
<div>
<pnx-monitoring-form-g
[objForm]="form"
#subscritionObjConfig
></pnx-monitoring-form-g>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormService } from "../../services/form.service";
import { FormGroup, FormBuilder } from "@angular/forms";
import { ISite } from "../../interfaces/geom";
import { SitesService } from "../../services/api-geom.service";
import { Observable, forkJoin, of } from "rxjs";
import { concatMap, map, mergeMap } from "rxjs/operators";
import { IobjObs, ObjDataType } from "../../interfaces/objObs";
import { MonitoringFormComponentG } from "../monitoring-form-g/monitoring-form.component-g";
import { ObjectService } from "../../services/object.service";
import { JsonData } from "../../types/jsondata";
import { endPoints } from "../../enum/endpoints";

@Component({
selector: "monitoring-sites-edit",
templateUrl: "./monitoring-sites-edit.component.html",
styleUrls: ["./monitoring-sites-edit.component.css"],
})
export class MonitoringSitesEditComponent implements OnInit {
site: ISite;
form: FormGroup;
paramToFilt: string = "label";
funcToFilt: Function;
titleBtn: string = "Choix des types de sites";
placeholderText: string = "Sélectionnez les types de site";
id_sites_group:number;
types_site:string[];
@ViewChild("subscritionObjConfig")
monitoringFormComponentG: MonitoringFormComponentG;
objToCreate: IobjObs<ObjDataType>;

constructor(
private _formService: FormService,
private _formBuilder: FormBuilder,
private siteService: SitesService,
private _Activatedroute: ActivatedRoute,
private _objService:ObjectService
) {}

ngOnInit() {

// let $obs1 = this._objService.currentObjSelected
// let $obs2 = this._objService.currentObjectType
// forkJoin([$obs1,$obs2]).subscribe( results =>{
// console.log(results[0])
// let objParent = results[0]
// let objChild = results[1]
// this.id_sites_group = objParent.id_sites_group
// this._formService.dataToCreate({ module: "generic", objectType: "site", id_sites_group : this.id_sites_group, id_relationship: ['id_sites_group','types_site'],endPoint:endPoints.sites,objSelected:objChild.objectType});
// this.form = this._formBuilder.group({});
// this.funcToFilt = this.partialfuncToFilt.bind(this);
// }
// )



this._objService.currentObjSelected.subscribe((objParent) => {
this.id_sites_group = objParent.id_sites_group
this._formService.dataToCreate({ module: "generic", objectType: "site", id_sites_group : this.id_sites_group, id_relationship: ['id_sites_group','types_site'],endPoint:endPoints.sites,objSelected:objParent.objectType});
this.form = this._formBuilder.group({});
this.funcToFilt = this.partialfuncToFilt.bind(this);
})

// this._Activatedroute.params
// .pipe(
// map((params) => params["id"] as number))
// .subscribe(
// (id_site_group) => {
// console.log(id_site_group)
// this.id_sites_group = id_site_group
// this._formService.dataToCreate({ module: "generic", objectType: "site", id_sites_group : this.id_sites_group });
// this.form = this._formBuilder.group({});
// this.funcToFilt = this.partialfuncToFilt.bind(this);
// }
// );

}



partialfuncToFilt(
pageNumber: number,
limit: number,
valueToFilter: string
): Observable<any> {
return this.siteService.getTypeSites(pageNumber, limit, {
label_fr: valueToFilter,
sort_dir: "desc",
});
}

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

addTypeSiteListIds(config:JsonData):JsonData{
if (config && config.length !=0){
config["types_site"]=[]
for (const key in config ){
if ('id_nomenclature_type_site' in config[key]) {
config["types_site"].push(config[key]['id_nomenclature_type_site']);
}
}

}
return config
}
}
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!-- IF prefered observable compare to ngOnChanges we can remove rows and colsname-->
<div>
<pnx-monitoring-properties-g [objectType]="objectType" *ngIf="!bEdit" [(bEdit)]="bEdit" [selectedObj]="site">
</pnx-monitoring-properties-g>
<pnx-monitoring-datatable-g [rows]="visits" [colsname]="colsname" (onSort)="setSort($event)" [page]="page"
(onFilter)="setFilter($event)" (onSetPage)="setPage($event)" [obj]="visits"
(onDetailsRow)="seeDetails($event)"></pnx-monitoring-datatable-g>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { Component, OnInit,Input } from "@angular/core";
import { forkJoin } from "rxjs";
import { map, mergeMap } from "rxjs/operators";
import { Router, ActivatedRoute } from "@angular/router";
import { GeoJSONService } from "../../services/geojson.service";
import { MonitoringGeomComponent } from "../../class/monitoring-geom-component";
import { SitesService, VisitsService } from "../../services/api-geom.service";
import { ISite } from "../../interfaces/geom";
import { IVisit } from "../../interfaces/visit";
import { IPage, IPaginated } from "../../interfaces/page";
import { columnNameVisit } from "../../class/monitoring-visit";
import { JsonData } from "../../types/jsondata";
import { ObjDataType } from "../../interfaces/objObs";

@Component({
selector: "monitoring-visits",
templateUrl: "./monitoring-visits.component.html",
styleUrls: ["./monitoring-visits.component.css"],
})
export class MonitoringVisitsComponent
extends MonitoringGeomComponent
implements OnInit
{
site: ISite;
@Input() visits: IVisit[];
@Input() page: IPage;
// colsname: typeof columnNameVisit = columnNameVisit;
objectType: string;
bEdit: boolean;
@Input() colsname;

constructor(
private _sites_service: SitesService,
private _visits_service: VisitsService,
public geojsonService: GeoJSONService,
private router: Router,
private _Activatedroute: ActivatedRoute
) {
super();
this.getAllItemsCallback = this.getVisits;
this.objectType = "sites";
}

ngOnInit() {
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,
}),
})
)
)
.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 };
});
}

getVisits(page: number, filters: JsonData) {
this._visits_service
.get(page, this.limit, filters)
.subscribe((visits:IPaginated<IVisit>) => this.setVisits(visits));
}

setVisits(visits) {
this.visits = visits.items;
this.page = {
page: visits.page - 1,
count: visits.count,
limit: visits.limit,
};
this.colsname = this._visits_service.objectObs.dataTable.colNameObj;
}

seeDetails($event) {
this.router.navigate([
`monitorings/object/${$event.module.module_code}/visit/${$event.id_base_visit}`,
]);
}
}
1 change: 1 addition & 0 deletions frontend/app/enum/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
export enum endPoints {
sites_groups = "sites_groups",
sites = "sites",
visits = "visits",
}
Loading

0 comments on commit 23350af

Please sign in to comment.