What is the best way to restore a version of AshPaperTrail?

I have a complex piece of code to restore a specific version of an item from AshPaperTrail, but I think I'm going down the wrong path. Take a look at the code below.
update :restore_version do
accept []
require_atomic? false
description "Restores the discount to a previous version (tenant users)"

argument :version_id, :uuid, allow_nil?: false

validate {MishkaCmsCoreResources.Runtime.Resources.Validations.TenantContext,
require_master: false}

change fn changeset, _context ->
version_id = Ash.Changeset.get_argument(changeset, :version_id)

version =
MishkaFileSeller.Discount.Version
|> Ash.get!(version_id, action: :get_any, authorize?: false)

restored_attrs =
case version.changes do
nil -> %{}
changes when is_map(changes) -> changes
changes when is_binary(changes) -> Jason.decode!(changes)
end

accepted_fields =
@admin_fields
|> Enum.filter(&(&1 != :site_id))
|> Enum.map(&to_string/1)

Enum.reduce(restored_attrs, changeset, fn {key, value}, acc ->
if key in accepted_fields do
key_atom = String.to_atom(key)

value =
cond do
key_atom == :status and is_binary(value) -> String.to_atom(value)
key_atom == :type and is_binary(value) -> String.to_atom(value)
key_atom == :applicable_to and is_binary(value) -> String.to_atom(value)
true -> value
end

Ash.Changeset.change_attribute(acc, key_atom, value)
else
acc
end
end)
end
end
update :restore_version do
accept []
require_atomic? false
description "Restores the discount to a previous version (tenant users)"

argument :version_id, :uuid, allow_nil?: false

validate {MishkaCmsCoreResources.Runtime.Resources.Validations.TenantContext,
require_master: false}

change fn changeset, _context ->
version_id = Ash.Changeset.get_argument(changeset, :version_id)

version =
MishkaFileSeller.Discount.Version
|> Ash.get!(version_id, action: :get_any, authorize?: false)

restored_attrs =
case version.changes do
nil -> %{}
changes when is_map(changes) -> changes
changes when is_binary(changes) -> Jason.decode!(changes)
end

accepted_fields =
@admin_fields
|> Enum.filter(&(&1 != :site_id))
|> Enum.map(&to_string/1)

Enum.reduce(restored_attrs, changeset, fn {key, value}, acc ->
if key in accepted_fields do
key_atom = String.to_atom(key)

value =
cond do
key_atom == :status and is_binary(value) -> String.to_atom(value)
key_atom == :type and is_binary(value) -> String.to_atom(value)
key_atom == :applicable_to and is_binary(value) -> String.to_atom(value)
true -> value
end

Ash.Changeset.change_attribute(acc, key_atom, value)
else
acc
end
end)
end
end
Is there a shorter and better way to do this? Thank you in advance
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?