Add first version of online stores for wishlisted records (claude)

See docs/plans/online_stores.md
This commit is contained in:
Claudio Ortolina
2025-07-15 09:42:59 +01:00
parent af4587fdbf
commit 65de5fc833
13 changed files with 1189 additions and 1 deletions
@@ -0,0 +1,76 @@
defmodule MusicLibrary.OnlineStoreTemplates do
@moduledoc """
The OnlineStoreTemplates context.
"""
import Ecto.Query, warn: false
alias MusicLibrary.OnlineStoreTemplates.OnlineStoreTemplate
alias MusicLibrary.Repo
@doc """
Returns the list of enabled online store templates ordered by name.
"""
def list_enabled_templates do
OnlineStoreTemplate
|> where([t], t.enabled == true)
|> order_by([t], asc: t.name)
|> Repo.all()
end
@doc """
Returns the list of all online store templates for management.
"""
def list_templates do
OnlineStoreTemplate
|> order_by([t], asc: t.name)
|> Repo.all()
end
@doc """
Gets a single online store template.
"""
def get_template!(id), do: Repo.get!(OnlineStoreTemplate, id)
@doc """
Creates an online store template.
"""
def create_template(attrs \\ %{}) do
%OnlineStoreTemplate{}
|> OnlineStoreTemplate.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates an online store template.
"""
def update_template(%OnlineStoreTemplate{} = template, attrs) do
template
|> OnlineStoreTemplate.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes an online store template.
"""
def delete_template(%OnlineStoreTemplate{} = template) do
Repo.delete(template)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking online store template changes.
"""
def change_template(%OnlineStoreTemplate{} = template, attrs \\ %{}) do
OnlineStoreTemplate.changeset(template, attrs)
end
@doc """
Generates a URL from a template by replacing variables with record data.
"""
def generate_url(template, record) do
artists_string = Enum.map_join(record.artists, " ", & &1.name)
template.url_template
|> String.replace("{artist}", URI.encode(artists_string))
|> String.replace("{title}", URI.encode(record.title))
end
end
@@ -0,0 +1,37 @@
defmodule MusicLibrary.OnlineStoreTemplates.OnlineStoreTemplate do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "online_store_templates" do
field :name, :string
field :description, :string
field :url_template, :string
field :enabled, :boolean, default: true
timestamps(type: :utc_datetime)
end
@doc false
def changeset(template, attrs) do
template
|> cast(attrs, [:name, :description, :url_template, :enabled])
|> validate_required([:name, :url_template])
|> validate_length(:name, min: 1, max: 100)
|> validate_length(:url_template, min: 1, max: 500)
|> validate_url_template()
end
defp validate_url_template(changeset) do
if template = get_field(changeset, :url_template) do
case URI.parse(template) do
%URI{scheme: scheme} when scheme in ["http", "https"] -> changeset
_ -> add_error(changeset, :url_template, "must be a valid HTTP or HTTPS URL")
end
else
changeset
end
end
end