/line_item.ex Secret
Last active
July 8, 2017 11:22
Revisions
-
shankardevy revised this gist
Jul 8, 2017 . 1 changed file with 4 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,5 +1,9 @@ defmodule Mango.Sales.LineItem do use Ecto.Schema import Ecto.Changeset alias Mango.Catalog alias Mango.Sales.LineItem embedded_schema do field :product_id, :integer -
shankardevy created this gist
Jul 8, 2017 .There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,40 @@ defmodule Mango.Sales.LineItem do use Ecto.Schema embedded_schema do field :product_id, :integer field :product_name, :string field :pack_size, :string field :quantity, :integer field :unit_price, :decimal field :total, :decimal end @doc false def changeset(%LineItem{} = line_item, attrs) do line_item |> cast(attrs, [:product_id, :product_name, :pack_size, :quantity, :unit_price, :total]) |> set_product_details |> set_total |> validate_required([:product_id, :product_name, :pack_size, :quantity, :unit_price]) end defp set_product_details(changeset) do case get_change(changeset, :product_id) do nil -> changeset product_id -> product = Catalog.get_product!(product_id) changeset |> put_change(:product_name, product.name) |> put_change(:unit_price, product.price) |> put_change(:pack_size, product.pack_size) end end defp set_total(changeset) do quantity = get_field(changeset, :quantity) |> Decimal.new unit_price = get_field(changeset, :unit_price) changeset |> put_change(:total, Decimal.mult(unit_price, quantity)) end end