share provider connection logic between setup wizard and providers form
Extract Products.connect_provider/2 that tests the connection, fetches shop_id, creates the record, and enqueues sync. Both the setup wizard and the providers form now use this shared function instead of duplicating the flow. Also makes the products empty state context-aware (distinguishes "no provider" from "provider connected but no products"). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -64,6 +64,59 @@ defmodule Berrypod.Products do
|
||||
|> Repo.insert()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Tests an API key, creates the connection with config (shop_id etc),
|
||||
and enqueues a product sync. Used by both setup wizard and providers form.
|
||||
|
||||
Returns `{:ok, connection}` or `{:error, reason}`.
|
||||
"""
|
||||
def connect_provider(api_key, provider_type) do
|
||||
alias Berrypod.Providers
|
||||
|
||||
encrypted =
|
||||
case Berrypod.Vault.encrypt(api_key) do
|
||||
{:ok, enc} -> enc
|
||||
_ -> nil
|
||||
end
|
||||
|
||||
temp_conn = %ProviderConnection{
|
||||
provider_type: provider_type,
|
||||
api_key_encrypted: encrypted
|
||||
}
|
||||
|
||||
with {:ok, test_result} <- Providers.test_connection(temp_conn) do
|
||||
name = provider_display_name(provider_type, test_result)
|
||||
config = provider_config(provider_type, test_result)
|
||||
|
||||
params =
|
||||
%{"api_key" => api_key, "provider_type" => provider_type, "name" => name}
|
||||
|> then(fn p -> if config != %{}, do: Map.put(p, "config", config), else: p end)
|
||||
|
||||
case create_provider_connection(params) do
|
||||
{:ok, connection} ->
|
||||
enqueue_sync(connection)
|
||||
{:ok, connection}
|
||||
|
||||
{:error, _} = error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp provider_display_name("printify", %{shop_name: name}) when is_binary(name), do: name
|
||||
defp provider_display_name("printful", %{store_name: name}) when is_binary(name), do: name
|
||||
|
||||
defp provider_display_name(type, _) do
|
||||
case Berrypod.Providers.Provider.get(type) do
|
||||
nil -> type
|
||||
info -> info.name
|
||||
end
|
||||
end
|
||||
|
||||
defp provider_config("printify", %{shop_id: id}), do: %{"shop_id" => to_string(id)}
|
||||
defp provider_config("printful", %{store_id: id}), do: %{"store_id" => to_string(id)}
|
||||
defp provider_config(_, _), do: %{}
|
||||
|
||||
@doc """
|
||||
Updates a provider connection.
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user