Repository navigation
fix(query_helper): patch date filter & sends 422 invalid date ops (BDMS-1523) #1064
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: staging
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,12 +14,15 @@ | |
| # limitations under the License. | ||
| # =============================================================================== | ||
| import json | ||
| from datetime import date, datetime, time, timedelta, timezone | ||
| from typing import Any | ||
|
|
||
| from fastapi import HTTPException | ||
| from fastapi_pagination.ext.sqlalchemy import paginate | ||
| from sqlalchemy import ( | ||
| Column, | ||
| Date, | ||
| DateTime, | ||
| Float, | ||
| Integer, | ||
| Select, | ||
|
|
@@ -31,6 +34,7 @@ | |
| func, | ||
| not_, | ||
| nulls_last, | ||
| or_, | ||
| select, | ||
| ) | ||
| from sqlalchemy.orm import DeclarativeBase, Session | ||
|
|
@@ -190,6 +194,102 @@ def _python_type(column: Any): | |
| return None | ||
|
|
||
|
|
||
| def _parse_json_filter_date(value: Any) -> date: | ||
| """Parse the date-only formats accepted by Refine JSON filters.""" | ||
| if not isinstance(value, str): | ||
| raise HTTPException( | ||
| status_code=422, | ||
| detail="Date filter values must use MM/DD/YYYY or YYYY-MM-DD", | ||
| ) | ||
|
|
||
| normalized = value.strip() | ||
| for date_format in ("%m/%d/%Y", "%Y-%m-%d"): | ||
| try: | ||
| return datetime.strptime(normalized, date_format).date() | ||
| except ValueError: | ||
| continue | ||
|
|
||
| raise HTTPException( | ||
| status_code=422, | ||
| detail="Date filter values must use MM/DD/YYYY or YYYY-MM-DD", | ||
| ) | ||
|
|
||
|
|
||
| def _apply_date_filter_clause( | ||
| sql: Select[Any], column: Any, operator: str, value: Any | ||
| ) -> Select[Any]: | ||
| """Apply a date-only filter to a DATE or timestamp column. | ||
| DateTime columns use UTC calendar-day bounds. This makes ``eq`` match all | ||
| timestamps on the requested date instead of only timestamps at midnight. | ||
| """ | ||
| if operator not in {"eq", "ne", "gt", "gte", "lt", "lte", "in"}: | ||
| raise HTTPException( | ||
| status_code=400, | ||
| detail=f"Unsupported filter operator {operator!r}", | ||
| ) | ||
|
|
||
| if operator == "in": | ||
| if not isinstance(value, (list, tuple)): | ||
| raise HTTPException( | ||
| status_code=400, | ||
| detail="Operator in requires an array value", | ||
| ) | ||
| dates = [_parse_json_filter_date(item) for item in value] | ||
| else: | ||
| dates = [_parse_json_filter_date(value)] | ||
|
|
||
| if not dates: | ||
| return sql.where(column.in_([])) | ||
|
|
||
| if isinstance(column.type, DateTime): | ||
| ranges = [] | ||
| for filter_date in dates: | ||
| start = datetime.combine(filter_date, time.min, timezone.utc) | ||
| end = start + timedelta(days=1) | ||
|
Comment on lines
+248
to
+249
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a timezone mismatch between how the wells grid displays
Because of this, any record created after 6:00 PM MDT (or 5:00 PM MST) has a UTC date one day later than the date the grid shows. For example, a well created at 7:00 PM MDT on Oct 5 displays as Although the Notes call out UTC days, this mismatch between visible column values and filter results is likely to cause user confusion and bug reports about "missing" records. Could we use |
||
| ranges.append((start, end)) | ||
|
|
||
| if operator == "eq": | ||
| start, end = ranges[0] | ||
| return sql.where(and_(column >= start, column < end)) | ||
| if operator == "ne": | ||
| start, end = ranges[0] | ||
| return sql.where(or_(column < start, column >= end)) | ||
| if operator == "gt": | ||
| return sql.where(column >= ranges[0][1]) | ||
| if operator == "gte": | ||
| return sql.where(column >= ranges[0][0]) | ||
| if operator == "lt": | ||
| return sql.where(column < ranges[0][0]) | ||
| if operator == "lte": | ||
| return sql.where(column < ranges[0][1]) | ||
| if operator == "in": | ||
| predicates = [] | ||
| for start, end in ranges: | ||
| predicates.append(and_(column >= start, column < end)) | ||
| return sql.where(or_(*predicates)) | ||
|
|
||
| if operator == "eq": | ||
| return sql.where(column == dates[0]) | ||
| if operator == "ne": | ||
| return sql.where(column != dates[0]) | ||
| if operator == "gt": | ||
| return sql.where(column > dates[0]) | ||
| if operator == "gte": | ||
| return sql.where(column >= dates[0]) | ||
| if operator == "lt": | ||
| return sql.where(column < dates[0]) | ||
| if operator == "lte": | ||
| return sql.where(column <= dates[0]) | ||
| if operator == "in": | ||
| return sql.where(column.in_(dates)) | ||
|
|
||
| raise HTTPException( | ||
| status_code=400, | ||
| detail=f"Unsupported filter operator {operator!r}", | ||
| ) | ||
|
|
||
|
|
||
| def _apply_thing_derived_status_filter( | ||
| sql: Select[Any], | ||
| thing_table: type, | ||
|
|
@@ -874,6 +974,7 @@ def _apply_json_filter_clause( | |
|
|
||
| py_t = _python_type(column) | ||
| is_string = py_t is str or isinstance(column.type, (String, Text)) | ||
| is_date = isinstance(column.type, (Date, DateTime)) | ||
|
|
||
| if operator == "contains": | ||
| if not is_string: | ||
|
|
@@ -907,6 +1008,9 @@ def _apply_json_filter_clause( | |
| ) | ||
| return sql.where(column.ilike(f"%{value}")) | ||
|
|
||
| if is_date and operator not in {"null", "nnull"}: | ||
| return _apply_date_filter_clause(sql, column, operator, value) | ||
|
Comment on lines
+1011
to
+1012
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because this branch runs on every
Either way, adding a test that filters |
||
|
|
||
| if operator == "eq": | ||
| if py_t is float: | ||
| return sql.where(column == float(value)) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,15 +24,15 @@ | |
| viewer_function, | ||
| amp_viewer_function, | ||
| ) | ||
| from datetime import date, timezone | ||
| from datetime import date, datetime, timezone | ||
| from db import MeasuringPointHistory, StatusHistory, Thing, ThingIdLink, WellScreen | ||
| from db.engine import session_ctx | ||
| from main import app | ||
| from schemas import DT_FMT | ||
| from schemas.location import LocationResponse | ||
| from schemas.thing import UpdateWell, ValidateWell | ||
| from services.water_level_csv import bulk_upload_water_levels | ||
| from sqlalchemy import delete | ||
| from sqlalchemy import delete, update | ||
| from tests import ( | ||
| client, | ||
| override_authentication, | ||
|
|
@@ -985,6 +985,128 @@ def test_get_water_wells_filter_contacts_nnull(water_well_thing, contact): | |
| assert water_well_thing.id in ids | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| def dated_water_well(water_well_thing): | ||
| """Give the shared well deterministic date and non-midnight timestamps.""" | ||
| with session_ctx() as session: | ||
| session.execute( | ||
| update(Thing) | ||
| .where(Thing.id == water_well_thing.id) | ||
| .values( | ||
| first_visit_date=date(2026, 8, 10), | ||
| well_completion_date=date(2023, 6, 6), | ||
| created_at=datetime(2026, 10, 5, 14, 30, tzinfo=timezone.utc), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since the fixture sets I ran the new date tests against staging's |
||
| ) | ||
| ) | ||
| session.commit() | ||
| return water_well_thing | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "field, value", | ||
| [ | ||
| ("first_visit_date", "08/10/2026"), | ||
| ("well_completion_date", "06/06/2023"), | ||
| ], | ||
| ) | ||
| @pytest.mark.parametrize( | ||
| ("operator", "expected"), | ||
| [ | ||
| ("eq", True), | ||
| ("ne", False), | ||
| ("gt", False), | ||
| ("gte", True), | ||
| ("lt", False), | ||
| ("lte", True), | ||
| ], | ||
| ) | ||
| def test_get_water_wells_filter_date_columns_all_comparisons( | ||
| dated_water_well, field, value, operator, expected | ||
| ): | ||
| fl = json.dumps({"field": field, "operator": operator, "value": value}) | ||
| response = client.get("/thing/water-well", params=[("filter", fl)]) | ||
|
|
||
| assert response.status_code == 200 | ||
| ids = [item["id"] for item in response.json()["items"]] | ||
| assert (dated_water_well.id in ids) is expected | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("operator", "expected"), | ||
| [ | ||
| ("eq", True), | ||
| ("ne", False), | ||
| ("gt", False), | ||
| ("gte", True), | ||
| ("lt", False), | ||
| ("lte", True), | ||
| ], | ||
| ) | ||
| def test_get_water_wells_filter_created_at_by_calendar_day( | ||
| dated_water_well, operator, expected | ||
| ): | ||
| fl = json.dumps( | ||
| {"field": "created_at", "operator": operator, "value": "10/05/2026"} | ||
| ) | ||
| response = client.get("/thing/water-well", params=[("filter", fl)]) | ||
|
|
||
| assert response.status_code == 200 | ||
| ids = [item["id"] for item in response.json()["items"]] | ||
| assert (dated_water_well.id in ids) is expected | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "field, value", | ||
| [ | ||
| ("first_visit_date", ["2026-08-10"]), | ||
| ("well_completion_date", ["06/06/2023"]), | ||
| ("created_at", ["2026-10-05"]), | ||
| ], | ||
| ) | ||
| def test_get_water_wells_filter_date_columns_in( | ||
| dated_water_well, | ||
| field, | ||
| value, | ||
| ): | ||
| fl = json.dumps({"field": field, "operator": "in", "value": value}) | ||
| response = client.get("/thing/water-well", params=[("filter", fl)]) | ||
|
|
||
| assert response.status_code == 200 | ||
| ids = [item["id"] for item in response.json()["items"]] | ||
| assert dated_water_well.id in ids | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("operator", "expected"), | ||
| [("null", False), ("nnull", True)], | ||
| ) | ||
| def test_get_water_wells_filter_date_columns_keep_null_operators( | ||
| dated_water_well, operator, expected | ||
| ): | ||
| filter_spec = { | ||
| "field": "first_visit_date", | ||
| "operator": operator, | ||
| "value": True, | ||
| } | ||
| fl = json.dumps(filter_spec) | ||
| response = client.get("/thing/water-well", params=[("filter", fl)]) | ||
|
|
||
| assert response.status_code == 200 | ||
| ids = [item["id"] for item in response.json()["items"]] | ||
| assert (dated_water_well.id in ids) is expected | ||
|
|
||
|
|
||
| def test_get_water_wells_filter_date_columns_reject_invalid_date( | ||
| dated_water_well, | ||
| ): | ||
| fl = json.dumps( | ||
| {"field": "first_visit_date", "operator": "eq", "value": "2026/08/10"} | ||
| ) | ||
| response = client.get("/thing/water-well", params=[("filter", fl)]) | ||
|
|
||
| assert response.status_code == 422 | ||
|
|
||
|
|
||
| def test_get_water_wells_filter_groups_eq_by_id(group, water_well_thing): | ||
| fl = json.dumps( | ||
| {"field": "groups", "operator": "eq", "value": str(group.id)}, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor comment, but neither 422 message (here or at line 214) includes the field name, so a caller sending multiple
filterparams can't tell which one failed. Could_apply_json_filter_clausepassfieldthrough_apply_date_filter_clauseso we can include it in the error?Also minor, but worth noting, is
nullhandling. Rejecting all non-string values meanseqwithnullnow returns a 422 rather thanIS NULL. The UI sendsnull/nnullfor empty checks, so current callers shouldn't be affected; just flagging the behavior change.