From 887c35a1c8e91daf8269d41b7819a06e8e5af74a Mon Sep 17 00:00:00 2001 From: Graham McIntire Date: Tue, 29 Jul 2025 10:57:36 -0500 Subject: [PATCH] Fix DateTime.to_iso8601 error by handling NaiveDateTime - Handle both DateTime and NaiveDateTime structs from database - Convert NaiveDateTime to UTC DateTime before formatting - Add fallback for string timestamps - Fixes FunctionClauseError when processing packets --- lib/aprsme_web/live/shared/packet_utils.ex | 26 ++++++++++++++----- ...250729160000_fix_packet_notify_trigger.exs | 4 +-- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/lib/aprsme_web/live/shared/packet_utils.ex b/lib/aprsme_web/live/shared/packet_utils.ex index 2794fc2..01d8e5c 100644 --- a/lib/aprsme_web/live/shared/packet_utils.ex +++ b/lib/aprsme_web/live/shared/packet_utils.ex @@ -195,14 +195,28 @@ defmodule AprsmeWeb.Live.Shared.PacketUtils do """ @spec get_timestamp(map()) :: String.t() def get_timestamp(packet) do - cond do - Map.has_key?(packet, :received_at) && packet.received_at -> - DateTime.to_iso8601(packet.received_at) + received_at = Map.get(packet, :received_at) || Map.get(packet, "received_at") - Map.has_key?(packet, "received_at") && packet["received_at"] -> - DateTime.to_iso8601(packet["received_at"]) + case received_at do + nil -> + "" - true -> + %DateTime{} = dt -> + DateTime.to_iso8601(dt) + + %NaiveDateTime{} = ndt -> + ndt + |> DateTime.from_naive!("Etc/UTC") + |> DateTime.to_iso8601() + + timestamp when is_binary(timestamp) -> + # If it's already a string, try to parse and reformat it + case DateTime.from_iso8601(timestamp) do + {:ok, dt, _} -> DateTime.to_iso8601(dt) + _ -> timestamp + end + + _ -> "" end end diff --git a/priv/repo/migrations/20250729160000_fix_packet_notify_trigger.exs b/priv/repo/migrations/20250729160000_fix_packet_notify_trigger.exs index 50c59dc..29ca520 100644 --- a/priv/repo/migrations/20250729160000_fix_packet_notify_trigger.exs +++ b/priv/repo/migrations/20250729160000_fix_packet_notify_trigger.exs @@ -45,7 +45,7 @@ defmodule Aprsme.Repo.Migrations.FixPacketNotifyTrigger do 'rain_24h', NEW.rain_24h, 'rain_midnight', NEW.rain_midnight, 'luminosity', NEW.luminosity, - 'snow_24h', NEW.snow_24h, + 'snow', NEW.snow, 'has_weather', NEW.has_weather, 'inserted_at', NEW.inserted_at )::text; @@ -113,7 +113,7 @@ defmodule Aprsme.Repo.Migrations.FixPacketNotifyTrigger do 'rain_24h', NEW.rain_24h, 'rain_midnight', NEW.rain_midnight, 'luminosity', NEW.luminosity, - 'snow_24h', NEW.snow_24h, + 'snow', NEW.snow, 'has_weather', NEW.has_weather, 'inserted_at', NEW.inserted_at )::text;