Current section

Files

Jump to
invoicex lib invoicex document buyer.ex
Raw

lib/invoicex/document/buyer.ex

defmodule Invoicex.Document.Buyer do
@moduledoc """
`Invoicex.Document.Invoice` buyer model.
"""
use Ecto.Schema
alias Ecto.Changeset
alias Invoicex.Document.{Address, Contact}
alias Invoicex.Extra.Email
@required_fields [:customer]
@fields @required_fields ++ [:copy_billing_address, :notes]
embedded_schema do
embeds_many(:notification_emails, Email, on_replace: :delete)
embeds_one(:billing_address, Address, on_replace: :update)
embeds_one(:contact, Contact, on_replace: :update)
embeds_one(:shipping_address, Address, on_replace: :update)
field(:copy_billing_address, :boolean, default: false, virtual: true)
field(:customer, :string)
field(:notes, :string)
end
@doc false
def changeset(address \\ %__MODULE__{}, attrs \\ %{}) do
address
|> Changeset.cast(attrs, @fields)
|> Changeset.cast_embed(:billing_address)
|> Changeset.cast_embed(:contact)
|> Changeset.cast_embed(:notification_emails)
|> prepare_shipping_address()
|> Changeset.cast_embed(:shipping_address)
|> Changeset.validate_required(@required_fields)
end
defp prepare_shipping_address(changeset) do
billing_address = Changeset.get_field(changeset, :billing_address)
copy_billing_address = Changeset.get_field(changeset, :copy_billing_address)
shipping_address = Changeset.get_change(changeset, :shipping_address)
if copy_billing_address and is_nil(shipping_address) do
Changeset.put_change(changeset, :shipping_address, billing_address)
else
changeset
end
end
end