@@ -190,6 +190,77 @@ def test_latest_tds_uses_latest_timestamp_within_same_day(water_well_thing):
190190 session .commit ()
191191
192192
193+ def test_ogc_normalized_major_chemistry_uses_latest_per_analyte (water_well_thing ):
194+ with session_ctx () as session :
195+ csi = NMA_Chemistry_SampleInfo (
196+ thing_id = water_well_thing .id ,
197+ nma_sample_point_id = "MAJOR-NORM-01" ,
198+ collection_date = datetime (2024 , 3 , 1 , 10 , 0 , 0 ),
199+ )
200+ session .add (csi )
201+ session .flush ()
202+
203+ # Older calcium result
204+ calcium_old = NMA_MajorChemistry (
205+ chemistry_sample_info_id = csi .id ,
206+ analyte = "Ca" ,
207+ symbol = "" ,
208+ sample_value = 80.0 ,
209+ units = "mg/L" ,
210+ analysis_date = datetime (2024 , 3 , 1 , 9 , 0 , 0 ),
211+ )
212+ # Newer calcium result that should win for calcium + calcium_units
213+ calcium_new = NMA_MajorChemistry (
214+ chemistry_sample_info_id = csi .id ,
215+ analyte = "Ca" ,
216+ symbol = "" ,
217+ sample_value = 95.0 ,
218+ units = "mg/L as CaCO3" ,
219+ analysis_date = datetime (2024 , 3 , 2 , 9 , 0 , 0 ),
220+ )
221+ # Separate analyte with even later date to drive latest_chemistry_date
222+ chloride = NMA_MajorChemistry (
223+ chemistry_sample_info_id = csi .id ,
224+ analyte = "Cl" ,
225+ symbol = "" ,
226+ sample_value = 40.0 ,
227+ units = "mg/L" ,
228+ analysis_date = datetime (2024 , 3 , 3 , 8 , 0 , 0 ),
229+ )
230+
231+ session .add_all ([calcium_old , calcium_new , chloride ])
232+ session .commit ()
233+
234+ session .execute (
235+ text ("REFRESH MATERIALIZED VIEW ogc_normalized_chemistry_results" )
236+ )
237+ session .commit ()
238+
239+ row = session .execute (
240+ text (
241+ "SELECT calcium, calcium_units, chloride, chloride_units, latest_chemistry_date "
242+ "FROM ogc_normalized_chemistry_results WHERE id = :thing_id"
243+ ),
244+ {"thing_id" : water_well_thing .id },
245+ ).one ()
246+
247+ assert float (row .calcium ) == 95.0
248+ assert row .calcium_units == "mg/L as CaCO3"
249+ assert float (row .chloride ) == 40.0
250+ assert row .chloride_units == "mg/L"
251+ assert row .latest_chemistry_date .isoformat () == "2024-03-03"
252+
253+ session .delete (chloride )
254+ session .delete (calcium_new )
255+ session .delete (calcium_old )
256+ session .delete (csi )
257+ session .commit ()
258+ session .execute (
259+ text ("REFRESH MATERIALIZED VIEW ogc_normalized_chemistry_results" )
260+ )
261+ session .commit ()
262+
263+
193264def test_ogc_collections ():
194265 response = client .get ("/ogcapi/collections" )
195266 assert response .status_code == 200
0 commit comments