Excel export functionality for yields

This commit is contained in:
2024-05-18 23:00:40 +03:00
parent 94c2da00ac
commit 34f6d44b98
7 changed files with 80 additions and 2 deletions

View File

@@ -114,4 +114,18 @@ defmodule Osuuspuutarha.Harvest.Parser do
def parse_plant(:corn) do
"Corn"
end
@spec parse_date(atom | %{:day => any, :month => any, :year => any, optional(any) => any}) ::
<<_::16, _::_*8>>
def parse_date(date) do
"#{date.day}.#{date.month}.#{date.year}"
end
def parse_unit(:kg) do
"kg"
end
def parse_unit(:kpl) do
"kpl"
end
end

View File

@@ -0,0 +1,14 @@
defmodule OsuuspuutarhaWeb.Exports.YieldController do
use OsuuspuutarhaWeb, :controller
alias Osuuspuutarha.Harvest
def index(conn, _params) do
yields = Harvest.list_yields()
conn
|> put_resp_content_type("text/xlsx")
|> put_resp_header("content-disposition", "attachment; filename=\"korjuut.xlsx\"")
|> render("korjuut.xlsx", %{yields: yields})
end
end

View File

@@ -13,7 +13,9 @@
</.modal>
<% end %>
<span><%= live_patch "New Yield", to: Routes.yield_index_path(@socket, :new) %></span>
<span class="new-yield-link"><%= live_patch "New Yield", to: Routes.yield_index_path(@socket, :new) %></span>
<%= link "Download as Excel", to: Routes.exports_yield_path(@socket, :index) %>
<table>
<thead>

View File

@@ -58,6 +58,7 @@ defmodule OsuuspuutarhaWeb.Router do
scope "/lataukset", as: :exports, alias: OsuuspuutarhaWeb.Exports do
pipe_through :admin_browser
resources "/tilaukset", OrderController, only: [:index]
resources "/korjuut", YieldController, only: [:index]
end
# Other scopes may use custom stacks.

View File

@@ -31,7 +31,7 @@ defmodule OsuuspuutarhaWeb.Exports.OrderView do
def report_generator(orders) do
rows = orders |> Enum.map(&row(&1))
%Workbook{sheets: [%Sheet{name: "Orders", rows: [@header] ++ rows}]}
%Workbook{sheets: [%Sheet{name: "Tilaukset", rows: [@header] ++ rows}]}
end
def row(order) do

View File

@@ -0,0 +1,34 @@
defmodule OsuuspuutarhaWeb.Exports.YieldView do
use OsuuspuutarhaWeb, :view
alias Elixlsx.{Workbook, Sheet}
alias Osuuspuutarha.Harvest.Parser
@header [
"Määrä",
"Päivämäärä",
"Kasvi",
"Yksikkö"
]
def render("korjuut.xlsx", %{yields: yields}) do
report_generator(yields)
|> Elixlsx.write_to_memory("korjuut.xlsx")
|> elem(1)
|> elem(1)
end
def report_generator(yields) do
rows = yields |> Enum.map(&row(&1))
%Workbook{sheets: [%Sheet{name: "Korjuut", rows: [@header] ++ rows}]}
end
def row(yield) do
[
Decimal.to_string(yield.amount),
Parser.parse_date(yield.date),
Parser.parse_plant(yield.plant),
Parser.parse_unit(yield.unit)
]
end
end