Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions services/query_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -31,6 +34,7 @@
func,
not_,
nulls_last,
or_,
select,
)
from sqlalchemy.orm import DeclarativeBase, Session
Expand Down Expand Up @@ -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",
)
Comment on lines +199 to +203

Copy link
Copy Markdown
Contributor

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 filter params can't tell which one failed. Could _apply_json_filter_clause pass field through _apply_date_filter_clause so we can include it in the error?

Also minor, but worth noting, is null handling. Rejecting all non-string values means eq with null now returns a 422 rather than IS NULL. The UI sends null/nnull for empty checks, so current callers shouldn't be affected; just flagging the behavior change.


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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a timezone mismatch between how the wells grid displays created_at and how this filter evaluates it:

  • Grid display: Uses formatAppDate with APP_TIMEZONE (which defaults to America/Denver).
  • Filter: Uses UTC day bounds.

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 "Oct 5, 2026" in the grid, yet filtering for 10/05/2026 doesn't return it and filtering for 10/06/2026 does.

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 America/Denver day bounds here to match the grid, or link a follow-up ticket if UTC is intentional for now?

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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because this branch runs on every Date and DateTime column for routes using order_sort_filter (including Observation.observation_datetime, Sample.sample_date, and created_at across models), it also handles the ISO timestamp filters sent by the UI, and currently rejects them.
In OcotilloUI, observation/list.tsx defines observation_datetime and created_at as type: 'dateTime', and thing-id-link/list.tsx does the same for created_at. Since the data provider serializes filters with JSON.stringify, the API receives ISO 8601 strings like "2026-08-10T06:00:00.000Z". Previously, these requests failed in Postgres (operator does not exist: timestamp with time zone >= character varying), and now _parse_json_filter_date rejects them with a 422. While this isn't a regression, those filters still don't work, and this is the exact code path that could fix them.
Two ways we could handle this:

  1. Update _parse_json_filter_date to accept ISO 8601 datetimes (preserving calendar-day comparisons for date-only values and using exact comparisons for full datetimes), which would also fix the date filters in the observation and thing ID link grids.
  2. Leave this PR as is and open a follow-up ticket for ISO datetime support.

Either way, adding a test that filters /observation/groundwater-level by observation_datetime with an ISO timestamp would cover this case.


if operator == "eq":
if py_t is float:
return sql.where(column == float(value))
Expand Down
126 changes: 124 additions & 2 deletions tests/test_thing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the fixture sets created_at to 14:30 UTC—9.5 hours away from either day boundary—these tests would still pass even if the day bounds were shifted by several hours. Off-by-a-few-hours bugs only show up near midnight, so adding a test case around 23:30 or 00:30 UTC would verify that the boundaries themselves are accurate.

I ran the new date tests against staging's query_helper.py and confirmed they all fail there except null/nnull, so the suite is definitely exercising the new behavior.

)
)
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)},
Expand Down
Loading