index.ex 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. display_cs: false
  15. )
  16. |> trigger_global_refresh}
  17. end
  18. @impl true
  19. def handle_event("add_location", %{"location_raw" => params}, socket) do
  20. case params |> LocationStore.add_location() do
  21. :ok -> {:noreply, socket}
  22. {:error, cs} -> {:noreply, socket |> assign(location_cs: cs)}
  23. end
  24. end
  25. def handle_event("trigger_all", _, socket) do
  26. {:noreply, socket |> trigger_global_refresh}
  27. end
  28. def handle_event("toggle_form", _, socket = %{assigns: %{display_cs: display}}),
  29. do: {:noreply, socket |> assign(display_cs: not display)}
  30. @impl true
  31. def handle_info({:query_sent, id, ref}, socket = %{assigns: %{pending: pending}}) do
  32. {:noreply, socket |> assign(pending: pending |> Map.put(ref, id))}
  33. end
  34. @impl true
  35. def handle_info(
  36. {:query_result, ref, res},
  37. socket = %{assigns: %{locations: valid, pending: pending}}
  38. ) do
  39. id = pending |> Map.get(ref)
  40. send_update(VaccinsWeb.LocationComponent, id: id, availabilities: res)
  41. {:noreply, socket |> assign(pending: pending |> Map.delete(ref))}
  42. end
  43. defp trigger_global_refresh(socket = %{assigns: %{locations: locations}}) do
  44. locations
  45. |> Enum.each(&send_update(VaccinsWeb.LocationComponent, id: &1.id, force_refresh: true))
  46. socket
  47. end
  48. end