| 1 |
|
defmodule WalletNotifications.Commands.UpdatePreferences do |
| 2 |
|
@moduledoc """ |
| 3 |
|
Command to set or update per-user, per-channel notification preferences. |
| 4 |
|
|
| 5 |
|
Upserts a `Preference` record in `PreferenceStore`. |
| 6 |
|
Returns `{:ok, preference}` on success. |
| 7 |
|
""" |
| 8 |
|
|
| 9 |
|
alias WalletNotifications.{Preference, PreferenceStore} |
| 10 |
|
alias WalletObservability.AuditEvent |
| 11 |
|
|
| 12 |
|
@spec execute( |
| 13 |
|
user_id :: String.t(), |
| 14 |
|
channel :: atom(), |
| 15 |
|
opts :: keyword() |
| 16 |
|
) :: {:ok, Preference.t()} | {:error, term()} |
| 17 |
11 |
def execute(user_id, channel, opts \\ []) do |
| 18 |
11 |
correlation_id = Keyword.get(opts, :correlation_id, WalletSharedKernel.Correlation.new_correlation_id()) |
| 19 |
|
|
| 20 |
11 |
pref = Preference.new(user_id, channel, |
| 21 |
|
enabled: Keyword.get(opts, :enabled, true), |
| 22 |
|
suppression_rules: Keyword.get(opts, :suppression_rules, %{}) |
| 23 |
|
) |
| 24 |
|
|
| 25 |
11 |
with :ok <- PreferenceStore.upsert(pref) do |
| 26 |
11 |
emit_audit(user_id, channel, correlation_id, pref.enabled) |
| 27 |
|
{:ok, pref} |
| 28 |
|
end |
| 29 |
|
rescue |
| 30 |
:-( |
error -> {:error, error} |
| 31 |
|
end |
| 32 |
|
|
| 33 |
11 |
defp emit_audit(user_id, channel, correlation_id, enabled) do |
| 34 |
11 |
audit = AuditEvent.build(:notifications, "preference_updated", "notification_preference", |
| 35 |
11 |
"#{user_id}:#{channel}", :success, |
| 36 |
|
actor_id: user_id, correlation_id: correlation_id, metadata: %{channel: channel, enabled: enabled}) |
| 37 |
11 |
:telemetry.execute([:wallet_notifications, :audit], %{}, audit) |
| 38 |
|
rescue |
| 39 |
:-( |
_ -> :ok |
| 40 |
|
end |
| 41 |
|
end |