| 1 |
|
defmodule WalletSettlement.Commands.ResolveSettlementException do |
| 2 |
|
@moduledoc """ |
| 3 |
|
Command to resolve an open or investigating settlement exception. |
| 4 |
|
|
| 5 |
|
Marks the exception as :resolved, records the resolution note and resolver, |
| 6 |
|
persists the update, and emits an `ExceptionResolved` event + audit record. |
| 7 |
|
|
| 8 |
|
Returns `{:ok, exception_record}` or `{:error, reason}`. |
| 9 |
|
""" |
| 10 |
|
|
| 11 |
|
alias WalletSettlement.{ExceptionRecord, ExceptionStore} |
| 12 |
|
alias WalletSettlement.Events.ExceptionResolved |
| 13 |
|
alias WalletObservability.AuditEvent |
| 14 |
|
|
| 15 |
|
@spec execute( |
| 16 |
|
exception_id :: String.t(), |
| 17 |
|
resolution_note :: String.t(), |
| 18 |
|
opts :: keyword() |
| 19 |
|
) :: {:ok, ExceptionRecord.t()} | {:error, term()} |
| 20 |
12 |
def execute(exception_id, resolution_note, opts \\ []) do |
| 21 |
6 |
correlation_id = Keyword.get(opts, :correlation_id, WalletSharedKernel.Correlation.new_correlation_id()) |
| 22 |
6 |
resolved_by = Keyword.get(opts, :resolved_by, "ops") |
| 23 |
|
|
| 24 |
6 |
with {:ok, exc} <- ExceptionStore.get(exception_id), |
| 25 |
5 |
{:ok, resolved} <- ExceptionRecord.resolve(exc, resolution_note), |
| 26 |
4 |
:ok <- ExceptionStore.update(resolved) do |
| 27 |
|
|
| 28 |
4 |
emit_event(ExceptionResolved.build(exception_id, |
| 29 |
4 |
batch_id: resolved.batch_id, |
| 30 |
|
resolution_note: resolution_note, |
| 31 |
|
resolved_by: resolved_by, |
| 32 |
|
correlation_id: correlation_id)) |
| 33 |
|
|
| 34 |
4 |
emit_audit(exception_id, resolved.batch_id, resolved_by, correlation_id) |
| 35 |
|
|
| 36 |
|
{:ok, resolved} |
| 37 |
|
end |
| 38 |
|
rescue |
| 39 |
:-( |
error -> {:error, error} |
| 40 |
|
end |
| 41 |
|
|
| 42 |
4 |
defp emit_event(event) do |
| 43 |
4 |
pubsub = Application.get_env(:wallet_settlement, :pubsub, WalletWeb.PubSub) |
| 44 |
4 |
apply(Phoenix.PubSub, :broadcast, [pubsub, "wallet_settlement:events", {:domain_event, event}]) |
| 45 |
|
rescue |
| 46 |
:-( |
_ -> :ok |
| 47 |
|
end |
| 48 |
|
|
| 49 |
4 |
defp emit_audit(exception_id, batch_id, resolved_by, correlation_id) do |
| 50 |
4 |
audit = AuditEvent.build(:settlement, "exception_resolved", "settlement_exception", exception_id, |
| 51 |
|
:success, |
| 52 |
|
actor_id: resolved_by, |
| 53 |
|
correlation_id: correlation_id, |
| 54 |
|
metadata: %{batch_id: batch_id}) |
| 55 |
4 |
:telemetry.execute([:wallet_settlement, :audit], %{}, audit) |
| 56 |
|
rescue |
| 57 |
:-( |
_ -> :ok |
| 58 |
|
end |
| 59 |
|
end |