Skip to content

Commit

Permalink
missed files
Browse files Browse the repository at this point in the history
  • Loading branch information
JannikStreek committed Dec 18, 2024
1 parent 4684960 commit eb2c16f
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
65 changes: 65 additions & 0 deletions lib/mindwendel/local_storage.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
defmodule Mindwendel.LocalStorage do
alias Mindwendel.Permissions

@moduledoc """
The LocalStorage context. It includes helpers to handle local storage data from clients.
"""

# This function is used to merge the brainstormings from local storage and the session.
# It returns a list of brainstormings sorted by the last_accessed_at field.
def brainstormings_from_local_storage_and_session(
brainstormings_from_local_storage,
brainstormings_from_session,
user
) do
(brainstormings_from_local_storage(brainstormings_from_local_storage) ++
brainstormings_from_session(brainstormings_from_session, user))
|> Enum.uniq_by(& &1["id"])
|> Enum.sort(&(&1["last_accessed_at"] > &2["last_accessed_at"]))
end

defp brainstormings_from_local_storage(brainstormings_stored) do
if is_list(brainstormings_stored) do
brainstormings_stored
|> Enum.map(fn e ->
Map.put(e, "last_accessed_at", format_iso8601(e["last_accessed_at"]))
end)
|> Enum.filter(&valid_stored_brainstorming?/1)
else
[]
end
end

defp brainstormings_from_session(brainstormings, user) do
Enum.map(brainstormings, fn brainstorming ->
%{
"last_accessed_at" => brainstorming.last_accessed_at,
"name" => brainstorming.name,
"id" => brainstorming.id,
"admin_url_id" =>
if(Permissions.has_moderating_permission(brainstorming, user),
do: brainstorming.admin_url_id,
else: nil
)
}
end)
end

defp valid_stored_brainstorming?(brainstorming) do
case Ecto.UUID.cast(brainstorming["id"]) do
{:ok, _} -> brainstorming["last_accessed_at"] && brainstorming["name"]
:error -> false
end
end

defp format_iso8601(iso8601) when iso8601 != nil do
case DateTime.from_iso8601(iso8601) do
{:ok, date_time, _} -> date_time
{:error, _} -> nil
end
end

defp format_iso8601(_) do
nil
end
end
8 changes: 8 additions & 0 deletions lib/mindwendel/permissions.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
defmodule Mindwendel.Permissions do
@moduledoc """
The Permissions context.
"""
def has_moderating_permission(brainstorming, current_user) do
Enum.member?(current_user.moderated_brainstormings |> Enum.map(& &1.id), brainstorming.id)
end
end

0 comments on commit eb2c16f

Please sign in to comment.