index.ex 1.4 KB

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