This commit is contained in:
bluepython508
2024-11-12 19:03:03 +00:00
parent f99153d6fd
commit 5ea2ef7a23
7 changed files with 130 additions and 2 deletions

View File

@@ -0,0 +1,48 @@
defmodule Monfari.Types.Amount do
use Ecto.Type
def type, do: :string
defstruct [:sign, :whole, :part, :currency]
@re ~r/^(-?)([0-9]+)\.([0-9]{2}) ([A-Z]{3})$/
def cast(str) when is_binary(str) do
case Regex.run(@re, str, capture: :all_but_first) do
[sign, whole, part, currency] ->
{:ok,
%__MODULE__{
sign: %{"" => 1, "-" => -1}[sign],
whole: String.to_integer(whole),
part: String.to_integer(part),
currency: currency
}}
nil ->
:error
end
end
def cast(%__MODULE__{} = val), do: val
def load(str) when is_binary(str), do: cast(str)
def dump(%__MODULE__{sign: sign, whole: whole, part: part, currency: currency}) do
sign = %{-1 => "-", 1 => ""}[sign]
{:ok, "#{sign}#{whole}.#{part} #{currency}"}
end
def dump(_), do: :error
def value(%__MODULE__{sign: sign, whole: whole, part: part}), do: sign * (whole * 100 + part)
def from_value(value, currency) do
sign = if value >= 0 do 1 else -1 end
whole = div(abs(value), 100)
part = rem(abs(value), 100)
%__MODULE__{sign: sign, whole: whole, part: part, currency: currency}
end
def add(%__MODULE__{currency: currency} = lhs, %__MODULE__{currency: currency} = rhs) do
from_value(value(lhs) + value(rhs), currency)
end
end

View File

@@ -0,0 +1,32 @@
defmodule Monfari.Schema.Transaction do
use Ecto.Schema
defmodule Effects do
use Ecto.Type
alias Monfari.Types.Amount
def type, do: {:map, Amount}
def cast(%{} = s), do: s |> Enum.map(fn {key, value} ->
end) |> Enum.into(%{})
end
@primary_key {:id, Needle.ULID, autogenerate: true}
@foreign_key_type Needle.ULID
@derive Jason.Encoder
schema "transactions" do
field :notes, :string
field :effects, Effects
end
defmodule Commands.Create do
end
defmodule Commands.Update do
end
defmodule Commands.Delete do
end
end