feat: geofence-based geographic targeting for programs#76
Conversation
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a robust geofence-based geographic targeting system for programs, allowing for precise and flexible definition of eligibility zones. It significantly enhances the underlying GIS infrastructure by adding support for complex geometric types and improving the reliability and user experience of map widgets. These changes collectively empower programs with more advanced spatial management tools and ensure a more secure and resilient mapping environment. Highlights
Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a major new feature for geofence-based geographic targeting, including a new spp_program_geofence module and extensive tests. It also enhances the spp_gis module by adding support for MultiPolygon and GeometryCollection, and crucially fixes a potential SQL injection vulnerability by using parameterized queries. The map widgets are improved by making the MapTiler API key optional with an OpenStreetMap fallback, and several pre-existing bugs related to WebGL context leaks and control stacking are fixed. The changes are well-structured and of high quality. I have a few suggestions to improve maintainability and robustness.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## 19.0 #76 +/- ##
==========================================
+ Coverage 71.68% 72.13% +0.44%
==========================================
Files 1010 1010
Lines 60072 61250 +1178
==========================================
+ Hits 43062 44181 +1119
- Misses 17010 17069 +59
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
|
Addressed Gemini review feedback in commit
Kept one medium suggestion as follow-up (optional): deduplicate identical OSM fallback style object between |
…operators
The Operator class only supported Point, LineString, and Polygon types
in domain queries. When shapely's unary_union creates a MultiPolygon
from non-overlapping polygons, the operator validation silently rejected
it, returning SQL("FALSE") and matching zero registrants.
Add ST_GeomFromGeoJSON path for complex geometry types that cannot be
easily constructed from coordinates.
New module that adds geofence-based geographic targeting to programs: - Program-level geofence_ids field on Overview tab - Geofence eligibility manager with hybrid two-tier spatial queries (GPS coordinates + administrative area fallback) - Preview button showing matched registrant count - Composable with other eligibility managers via AND logic
…ibility - Use gis_intersects instead of gis_within for Tier 1 spatial query; gis_within generates ST_Within(value, field) which is backwards for point-in-polygon checks, while gis_intersects is symmetric - Use disabled=None instead of disabled=False in domain (Datetime field) - Use fields.Datetime.now() for disabled test data (not Boolean True) - Use group_ids with Command.link() for Odoo 19 compatibility in tests
- Escape single quotes in create_from_geojson to prevent SQL injection - Make preview_count/preview_error regular fields instead of computed; spatial queries now only run when the Preview button is clicked - Use elif instead of two independent if statements for target_type - Simplify _import_registrants loop to list comprehension
…ent UI - Add fallback_area_type_id field to restrict Tier 2 area fallback to a specific administrative level (e.g. District), preventing overly broad matches from large provinces or regions - Add geofence list/form/search views with menu under Area top-level, so users can browse and manage geofences independently - Allow inline geofence creation from the program form - Add 3 tests for area type filter behavior
When no MapTiler API key is configured, the map widget now falls back to OpenStreetMap raster tiles instead of failing silently. This makes the GIS features work out of the box without requiring a third-party API key. Users who want vector tiles can still configure a MapTiler key.
…back - Fix WebGL context leak: destroy previous map before creating new one in renderMap() to prevent accumulating WebGL contexts on onPatched - Fix draw control stacking: remove previous MapboxDraw control before adding a new one in addDrawInteraction() - Fix removeSourceAndLayer: remove all three layer IDs (polygon, point, linestring) instead of the source ID which doesn't match any layer - Remove console.log debug statements from updateArea and onTrash - Remove hardcoded laos_farm.png placeholder popup on polygon click - Fix SQL injection in create_from_geojson: use SQL() with bound parameters instead of manual string escaping - Apply OSM raster tile fallback to gis_renderer (matching edit widget) - Guard GeocodingControl behind API key check in renderer - Fix early-return-in-loop in eligibility manager methods with ensure_one() - Log exceptions in preview instead of silently swallowing them - Use efficient set lookup for beneficiary exclusion - Use Command.set()/Command.clear() instead of tuple syntax in tests
The default system parameter value "YOUR_MAPTILER_API_KEY_HERE" was being returned as a valid key, causing 403 errors from MapTiler instead of falling back to OSM tiles.
renderMap() was overriding the OSM fallback style with a MapTiler style reference when defaultRaster was set, even without an API key. Guard the raster style override behind mapTilerKey check.
…nu order The GeoPolygonField edit widget requires a GIS view (ir.ui.view with type=gis) with data and raster layers to render the map. Without it, opening a geofence form raised "No GIS view defined". Also moved the Geofences menu item to sequence 200 so it appears last in the Area menu.
When renderMap() destroys the old map, the MapboxDraw control's internal map reference becomes null. Later, addDrawInteraction() tried to removeControl(this.draw) from the new map, but the draw control called this.map.off() on its now-null internal reference. Fix: set this.draw = null before map.remove() so addDrawInteraction skips the removeControl call for stale controls.
Move the Geographic Scope card from Overview to Configuration tab, matching the card-based UI pattern. Add geofence_ids field to the program creation wizard so geofences can be set during initial setup.
Existing geometry was added as a static map source/layer, making it non-interactive: shapes couldn't be clicked, selected, or edited. Now geometry is loaded into the MapboxDraw control via draw.add(), enabling click-to-select, vertex editing, and trash deletion. Also handles draw.delete event to clear the field value.
The tag_ids field on spp.gis.geofence was pointing to spp.vocabulary, which is a generic vocabulary model containing all tag categories (Country, Currency, etc.). Replace with a dedicated spp.gis.geofence.tag model so the tags dropdown only shows geofence-specific tags.
- Remove dead methods from field_gis_edit_map (onLoadMap, addSourceAndLayer,
addSource, addLayer, removeSourceAndLayer) no longer called after draw
refactor
- Fix event listener stacking in addDrawInteraction: store handler refs
and remove previous listeners before adding new ones, preventing
duplicate record.update() calls when onUIChange() is called
- Fix disabled registrant filter: use ("disabled", "=", False) for
consistency with DefaultEligibilityManager
46c90b6 to
8e77302
Compare
Add foundational components for OGC API - Processes (Part 1: Core): - spp.gis.process.job model for async job tracking with job_worker - Pydantic schemas for process list, description, execution, status - ProcessRegistry service with dynamic indicator enum from spp.indicator - Cron job for cleanup of stale/expired process jobs - ACL entries for the new model
- processes.py: GET /gis/ogc/processes, GET /gis/ogc/processes/{id},
POST /gis/ogc/processes/{id}/execution with sync/async support
- jobs.py: GET /gis/ogc/jobs, GET /gis/ogc/jobs/{id},
GET /gis/ogc/jobs/{id}/results, DELETE /gis/ogc/jobs/{id}
- Wire routers into FastAPI endpoint registry
- Update OGC conformance to declare Processes classes
- Add processes link to OGC landing page
- Refactor statistics endpoint to delegate to ProcessRegistry
Tests cover: - ProcessRegistry: list, describe, unknown ID, indicator enum, x-openspp-statistics - Pydantic schemas: ProcessSummary, ExecuteRequest, StatusInfo, JobList - spp.gis.process.job model: create, dismiss, stale cleanup, cron - Input validation: single/batch geometry, bare arrays, limits, proximity - HTTP integration: process list/describe, execution, async flow, job scoping, dismiss, conformance, landing page links
- Remove 'icon' field from test category creation (spp.metric.category does not have an icon field; Odoo 19 raises ValueError on unknown fields) - Fix Odoo False-vs-None for empty Text fields: use `message or None` in _build_status_info to prevent Pydantic ValidationError when job.message is False instead of None - Apply fix in both processes.py and jobs.py routers
- Restrict ACL: base.group_user gets read-only, base.group_system gets full CRUD (routers use sudo() for all mutations) - Add UNIQUE constraint on job_id field - Sanitize exception messages in job records to prevent leaking internals - Extract shared helpers (_helpers.py): build_status_info, check_gis_scope, get_base_url used by both processes and jobs routers - Extract process execution logic (process_execution.py): run_spatial_statistics, run_proximity_statistics used by both sync (router) and async (model) paths - Add safe int parsing for ir.config_parameter values with fallback defaults - Use SPATIAL_STATISTICS/PROXIMITY_STATISTICS constants instead of string literals
…OGC Processes Address consumer feedback from the QGIS plugin team: - Always include geometries_failed in batch summary responses (#1) - Always populate computed_at with current UTC timestamp, even for empty results (#2) - Add Retry-After: 5 header to async 201 responses and in-progress job status (#3/#8) - Track batch progress per-geometry via on_progress callback in job execution (#4) - Add x-openspp-batch-limit: 100 extension to spatial-statistics process description (#5)
chore: docker/postgres tuning, spp CLI enhancements, pre-commit + agent docs (re-land from #76)
…tion (from #76) Re-lands the PR #76 description scope: spp_gis complex-geometry operators (MultiPolygon/GeometryCollection + distance buffering), OSM fallback when no MapTiler key is configured, renderer/edit-widget lifecycle fixes, geofence uuid in GeoJSON output, the spp.gis.geofence.tag model, and the new spp_program_geofence module (geofence eligibility manager, program UI, creation wizard). Adds what the original PR lacked: a migration pair remapping existing vocabulary-based geofence tag links (release v19.0.2.0.0 schema) onto spp.gis.geofence.tag records — the rel table is reused, so legacy rows are parked pre-upgrade and restored post-upgrade. Includes regression tests.
…ion (from #76) Re-lands the spp_hazard severity->vocabulary change from reverted PR #76, together with the dependent adaptations in spp_drims, spp_drims_sl_demo and spp_hazard_programs, plus the two fixes the original PR lacked: - migrations/19.0.2.1.0/post-migration.py backfills severity_id / severity_override_id from the legacy 1-5 Selection columns for databases upgrading from v19.0.2.0.x (release Biliran ships the old schema). Mapping: 1->minor, 2->moderate, 3->severe, 4->severe, 5->extreme. - hazard_demo.xml incident-area records now use severity_override_id vocabulary refs; the stale severity_override field broke demo installs. Includes migration regression tests (mapping, area override, idempotency, unmapped values, fresh-install no-op).
…SQL CASE (from #76) Re-lands the spp_cel_domain portion of reverted PR #76: - SQL CASE support: to_sql_case compiler for CEL ternaries, case_when/ comparison builders, right-associative ternary parsing fix - Read-only smart operator label lookup (no record creation, no sudo during compilation) - Tests for the translation cache helpers tests/__init__.py was merged by hand to keep imports added by later security PRs (#251/#257/#223). Version bumped to 19.0.2.1.0 with a HISTORY entry.
… bundle schemas (from #76) Re-lands the spp_api_v2 portion of PR #76, which was reverted wholesale in d38ff9d. Restores the OpenAPI polymorphic schema utilities and app hook, the OAuth2 client-credentials security scheme in the auth middleware, the polymorphic BundleEntry.resource schema, and the OpenAPI contract tests, exactly as merged in 8bf9a3a. Bumps the module version to 19.0.2.1.0 with a matching HISTORY entry.
… module (from #76) Re-lands the PHL demo data portion of reverted PR #76: curated PHL geojson shapes and areas, demo data generator and area loader test updates, the prepare_phl_geodata.py preparation script, and the new spp_demo_phl_luzon module (Luzon demo areas + population weights). Files restored verbatim from the pre-revert merged state (8bf9a3a). spp_demo bumped to 19.0.2.1.0 with a HISTORY entry.
Every module carries a readme/HISTORY.md; the module was created in #76 without one. README.rst History section will be aligned to CI's renderer output in a follow-up commit.
…it + agent docs (from OpenSPP#76) Re-lands the infrastructure/tooling portion of PR OpenSPP#76, which was reverted wholesale in d38ff9d. Restores docker entrypoint/config, postgresql.conf, docker-compose tuning, spp CLI enhancements, pre-commit config, and agent docs (AGENTS.md, .agents skill) from the pre-revert merged state 8bf9a3a.
feat(spp_cel_domain): SQL CASE compiler, read-only smart-op lookup, translator cache tests (re-land from #76)
feat: geofence-based geographic targeting for programs (re-land from #76)
…hanges Softens the downstream impact of the severity -> CAP vocabulary migration (re-land from #76): - add a stored, computed severity_numeric (5=extreme .. 1=unknown, 0=unset) on spp.hazard.incident so downstream ordering/threshold logic can consume a numeric scale without resolving CAP vocabulary codes (mirrors the spp_drims incident-area mapping). - document the breaking changes in the changelog: the severity / severity_override removal+rename, the new spp_vocabulary dependency, and the model-level category_id / start_date required relaxation.
feat(spp_api_v2): OpenAPI polymorphic bodies, OAuth2 scheme in auth middleware, bundle schemas (re-land from #76)
feat(spp_demo): curated PHL geodata + spp_demo_phl_luzon demo module (re-land from #76)
feat(spp_metric_service): breakdown expansion + SQL column support (re-land from #76)
feat(spp_gis_report): metric disaggregation in GIS reports (re-land from #76)
Summary
spp_program_geofencemodule for geofence-based program targeting and eligibility management.spp_gisspatial operators to supportMultiPolygonandGeometryCollection.Follow-up Fixes From Review
MultiPolygon/GeometryCollection,(geojson, distance)now appliesST_Buffer(...)correctly instead of ignoring the distance operand.spp_program_geofenceforspp.gis.geofenceandspp.gis.geofence.tagfor Programs Viewer/Validator roles.groupsrestriction on the Geofences menu to avoid exposing menu items to users lacking read access.Notable Functional Additions
spp_program_geofencegeofence_idsandgeofence_count.spp.program.membership.manager.geofence) with:spp_gisST_GeomFromGeoJSON.YOUR_MAPTILER_API_KEY_HEREtreated as unconfigured).Test Plan
MultiPolygon/GeometryCollectionSQL generation.python3 -m py_compile spp_gis/operators.py spp_gis/tests/test_geo_fields.py./spp t ...is environment-blocked here (tomllibmissing in local Python, and fallback script depends onshuf).