Current section

Files

Jump to
invoicex lib invoicex document group.ex
Raw

lib/invoicex/document/group.ex

defmodule Invoicex.Document.Group do
@moduledoc """
Group is a special type of `Invoicex.Document.Invoice` item.
It allows to collect other items, but alos discount and taxes.
It's helpful if you want to organise and style items in invoice.
For example you can create group which will describe your product and add services data as its items.
"""
use Ecto.Schema
alias Ecto.Changeset
alias Invoicex.Document
alias Invoicex.Document.Item
alias Invoicex.Extra.{Discount, Tax}
@fields [:order]
@messages %{
empty: "Expected at least one discount, item or tax",
invalid: "Invalid order of discount(s) and/or item(s) and/or tax(es)"
}
@required_fields @fields
embedded_schema do
embeds_many(:discounts, Discount)
embeds_many(:items, Item)
embeds_many(:taxes, Tax)
embeds_one(:item, Item)
field(:list, {:array, :map}, virtual: true)
field(:order, :integer)
field(:total, :map, virtual: true)
end
@doc false
def changeset(group \\ %__MODULE__{}, attrs \\ %{}) do
group
|> Changeset.cast(attrs, @fields)
|> Changeset.cast_embed(:discounts, with: &Discount.changeset(&1, &2, true))
|> Changeset.cast_embed(:item)
|> Changeset.cast_embed(:items, with: &Item.changeset(&1, &2, true))
|> Changeset.cast_embed(:taxes, with: &Tax.changeset(&1, &2, true))
|> custom_validation()
|> Changeset.validate_required(@required_fields)
end
defp custom_validation(changeset) do
list = Document.build_group_list(changeset)
Document.validate_orders(changeset, list, @messages)
end
end