From e0de3b3f2e679cc615ea30fefec7098fe1438f35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o?= Date: Wed, 24 Feb 2021 01:13:02 +0000 Subject: [PATCH] Daily badge task (#213) Co-authored-by: jpcorreia99 --- lib/mix/tasks/gift.daily.badge.ex | 49 +++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 lib/mix/tasks/gift.daily.badge.ex diff --git a/lib/mix/tasks/gift.daily.badge.ex b/lib/mix/tasks/gift.daily.badge.ex new file mode 100644 index 00000000..63e15dbb --- /dev/null +++ b/lib/mix/tasks/gift.daily.badge.ex @@ -0,0 +1,49 @@ +defmodule Mix.Tasks.Gift.Daily.Badge do + use Mix.Task + + import Ecto.Query, warn: false + + alias Safira.Accounts.Attendee + alias Safira.Contest + alias Safira.Contest.Redeem + alias Safira.Contest.Badge + + alias Safira.Repo + + # Expects a date in yyyy-mm-dd format + def run(args) do + Mix.Task.run("app.start") + + cond do + length(args) != 2 -> + Mix.shell().info("Needs to receive badge_id and the date of the day.") + + true -> + args |> create() + end + end + + def create(args) do + + {badge_id, date} = {args |> Enum.at(0), args |> Enum.at(1) |> Date.from_iso8601!()} + + Repo.all( + from a in Attendee, + join: r in Redeem, on: a.id == r.attendee_id, + join: b in Badge, on: r.badge_id == b.id, + where: not(is_nil a.user_id) and fragment("?::date", r.inserted_at) == ^date, + preload: [badges: b] + ) + |> Enum.map(fn a -> Map.put(a, :badge_count, length(a.badges)) end) + |> Enum.filter(fn a -> a.badge_count > 0 end) + |> Enum.each(fn a -> + Contest.create_redeem(%{ + attendee_id: a.id, + manager_id: 1, + badge_id: badge_id + }) + end) + + end + +end