index.ex 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. defmodule VaccinsWeb.IndexLive do
  2. use VaccinsWeb, :live_view
  3. alias Vaccins.{LocationStore, Search}
  4. @impl true
  5. def mount(_params, _session, socket) do
  6. locations = LocationStore.get_locations()
  7. {:ok,
  8. socket
  9. |> assign(
  10. locations: locations,
  11. pending: %{},
  12. availabilities: locations |> Map.new(&{&1.id, []}),
  13. location_cs: LocationStore.LocationRaw.changeset(%{})
  14. )
  15. |> trigger_global_refresh}
  16. end
  17. @impl true
  18. def handle_event("add_location", %{"location_raw" => params}, socket) do
  19. case params |> LocationStore.add_location() do
  20. :ok -> {:noreply, socket}
  21. {:error, cs} -> {:noreply, socket |> assign(location_cs: cs)}
  22. end
  23. end
  24. @impl true
  25. def handle_event("trigger_all", _, socket) do
  26. {:noreply, socket |> trigger_global_refresh}
  27. end
  28. @impl true
  29. def handle_info({:query_sent, id, ref}, socket = %{assigns: %{pending: pending}}) do
  30. {:noreply, socket |> assign(pending: pending |> Map.put(ref, id))}
  31. end
  32. @impl true
  33. def handle_info(
  34. {:query_result, ref, res},
  35. socket = %{assigns: %{locations: valid, pending: pending}}
  36. ) do
  37. id = pending |> Map.get(ref)
  38. send_update(VaccinsWeb.LocationComponent, id: id, availabilities: res)
  39. {:noreply, socket |> assign(pending: pending |> Map.delete(ref))}
  40. end
  41. defp trigger_global_refresh(socket = %{assigns: %{locations: locations}}) do
  42. locations
  43. |> Enum.each(&send_update(VaccinsWeb.LocationComponent, id: &1.id, force_refresh: true))
  44. socket
  45. end
  46. end