From 6449fb2934d9ceef48665804fdb6652740ebf9fc Mon Sep 17 00:00:00 2001 From: Tom Konidas Date: Mon, 16 Sep 2024 19:09:32 -0400 Subject: [PATCH] Update App timestamp every new rating --- lib/plexus/apps.ex | 8 ++++++++ lib/plexus/ratings.ex | 12 ++++++++---- lib/plexus/schemas/app.ex | 2 +- test/plexus/ratings_test.exs | 4 ++-- 4 files changed, 19 insertions(+), 7 deletions(-) diff --git a/lib/plexus/apps.ex b/lib/plexus/apps.ex index 3963e3d8..e516fa6d 100644 --- a/lib/plexus/apps.ex +++ b/lib/plexus/apps.ex @@ -50,6 +50,14 @@ defmodule Plexus.Apps do |> Repo.one!() end + @spec fetch_app(String.t()) :: {:ok, App.t()} | {:error, :not_found} + def fetch_app(package) do + case Repo.get(App, package) do + %App{} = app -> {:ok, app} + nil -> {:error, :not_found} + end + end + @spec create_app(%{ optional(:icon_url) => String.t(), package: String.t(), diff --git a/lib/plexus/ratings.ex b/lib/plexus/ratings.ex index 5ea73c6b..738b978d 100644 --- a/lib/plexus/ratings.ex +++ b/lib/plexus/ratings.ex @@ -4,6 +4,7 @@ defmodule Plexus.Ratings do """ import Ecto.Query + alias Plexus.Apps alias Plexus.PaginationHelpers alias Plexus.QueryHelpers alias Plexus.Repo @@ -56,10 +57,13 @@ defmodule Plexus.Ratings do rating_type: atom(), score: pos_integer() }) :: {:ok, Rating.t()} | {:error, Ecto.Changeset.t()} - def create_rating(params) do - %Rating{} - |> Rating.changeset(params) - |> Repo.insert() + def create_rating(%{app_package: app_package} = params) do + Repo.transact(fn -> + with {:ok, app} <- Apps.fetch_app(app_package), + {:ok, _app} <- Apps.update_app(app, %{updated_at: DateTime.utc_now()}) do + Repo.insert(Rating.changeset(%Rating{}, params)) + end + end) |> broadcast(:app_rating_updated) end diff --git a/lib/plexus/schemas/app.ex b/lib/plexus/schemas/app.ex index ee096569..bf7c4300 100644 --- a/lib/plexus/schemas/app.ex +++ b/lib/plexus/schemas/app.ex @@ -20,7 +20,7 @@ defmodule Plexus.Schemas.App do @spec changeset(App.t(), map()) :: Ecto.Changeset.t() def changeset(%App{} = app, params) do app - |> cast(params, [:package, :name, :icon_url]) + |> cast(params, [:package, :name, :icon_url, :updated_at]) |> validate_required([:package, :name]) |> unique_constraint(:package, name: :apps_pkey) end diff --git a/test/plexus/ratings_test.exs b/test/plexus/ratings_test.exs index 54555332..74046653 100644 --- a/test/plexus/ratings_test.exs +++ b/test/plexus/ratings_test.exs @@ -8,7 +8,7 @@ defmodule Plexus.RatingsTest do alias Plexus.Schemas.Rating @invalid_attrs %{ - app_package: nil, + app_package: "", app_build_number: nil, app_version: nil, rating_type: nil, @@ -65,7 +65,7 @@ defmodule Plexus.RatingsTest do end test "invalid data returns error changeset" do - assert {:error, %Ecto.Changeset{}} = Ratings.create_rating(@invalid_attrs) + assert {:error, _reason} = Ratings.create_rating(@invalid_attrs) end end end