Still not completely clear on the situation, maybe show your Ecto schema as well?
It does sound like you’d need some sort of mapping/lookup table between different line items such as a pencil or an eraser to prices/amount and how it’d affect the income statement (selling adds to revenue vs buying adds to expenses).
For example, "pencil"
mapped to {:expense, 10}
. Or even better, using a tuple like {"pencil", :expense, 10}
{:expense, 10, "purchased a pencil"}
or {:revenue, 20, "sold an eraser"}
. Then you could have a function that updates the income statement map/struct.
income_statement = %{expense: 1000, revenue: 2000}
item_1 = {:expense, 10, "purchased a pencil"}
item_2 = {:revenue, 20, "sold an eraser"}
def update_income_statement({key, amount, _description}, income_statement) do
update_in(income_statement, [key], &(&1 + amount)))
end
# results
update_income_statement(item_1, income_statement) => %{expense: 1010, revenue: 2000}
update_income_statement(item_2, income_statement) => %{expense: 1000, revenue: 2020}
While I wouldn’t suggest it but you could hardcode in those mapping if for some reason pencils are always purchased and erasers are always sold…
income_statement = %{expense: 1000, revenue: 2000}
item_1 = "pencil"
item_2 = "eraser"
# using a case statement
def some_func(item, income_statement) do
case item do
"pencil" -> %{income_statement | expense: income_statement.expense + 10}
"product sale" -> %{income_statement | revenue: income_statement.revenue + 20}
end
end
# or using pattern matching in function heads
def some_func("pencil", income_statement) do
%{income_statement | expense: income_statement.expense + 10}
end
def some_func("product sale", income_statement) do
%{income_statement | revenue: income_statement.revenue + 20}
end
# results
some_func(item_1, income_statement) => %{expense: 1010, revenue: 2000}
some_func(item_2, income_statement) => %{expense: 1000, revenue: 2020}