stock_controller.ex 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. defmodule GiomWeb.StockController do
  2. use GiomWeb, :controller
  3. alias Giom.Accounting
  4. alias Giom.Accounting.Stock
  5. def index(conn, _params) do
  6. stocks = Accounting.list_stocks()
  7. render(conn, "index.html", stocks: stocks)
  8. end
  9. def new(conn, _params) do
  10. changeset = Accounting.change_stock(%Stock{})
  11. render(conn, "new.html", changeset: changeset)
  12. end
  13. def create(conn, %{"stock" => stock_params}) do
  14. case Accounting.create_stock(stock_params) do
  15. {:ok, stock} ->
  16. conn
  17. |> put_flash(:info, "Stock created successfully.")
  18. |> redirect(to: stock_path(conn, :show, stock))
  19. {:error, %Ecto.Changeset{} = changeset} ->
  20. render(conn, "new.html", changeset: changeset)
  21. end
  22. end
  23. def show(conn, %{"id" => id}) do
  24. stock = Accounting.get_stock!(id)
  25. render(conn, "show.html", stock: stock)
  26. end
  27. def edit(conn, %{"id" => id}) do
  28. stock = Accounting.get_stock!(id)
  29. changeset = Accounting.change_stock(stock)
  30. render(conn, "edit.html", stock: stock, changeset: changeset)
  31. end
  32. def update(conn, %{"id" => id, "stock" => stock_params}) do
  33. stock = Accounting.get_stock!(id)
  34. case Accounting.update_stock(stock, stock_params) do
  35. {:ok, stock} ->
  36. conn
  37. |> put_flash(:info, "Stock updated successfully.")
  38. |> redirect(to: stock_path(conn, :show, stock))
  39. {:error, %Ecto.Changeset{} = changeset} ->
  40. render(conn, "edit.html", stock: stock, changeset: changeset)
  41. end
  42. end
  43. def delete(conn, %{"id" => id}) do
  44. stock = Accounting.get_stock!(id)
  45. {:ok, _stock} = Accounting.delete_stock(stock)
  46. conn
  47. |> put_flash(:info, "Stock deleted successfully.")
  48. |> redirect(to: stock_path(conn, :index))
  49. end
  50. # API Section
  51. def get_stockname(conn, %{"code" => stock_code}) do
  52. json(conn, Accounting.get_stock!(stock_code).name)
  53. end
  54. end