defmodule DaProductApp.Settlements.SettlementManagement do import Ecto.Query alias DaProductApp.Repo alias DaProductApp.Settlements.Settlement alias DaProductApp.Settlements.SettlementTransaction alias DaProductApp.Merchants.Merchant alias DaProductApp.Providers.Provider alias DaProductApp.Settlements.SettlementFile alias DaProductApp.Settlements.SettlementFileAudit @doc """ Returns a summary of settlements per merchant, provider, and date, with status and total amount. """ def list_settlement_summaries do from(s in Settlement, join: m in Merchant, on: s.merchant_id == m.id, join: p in Provider, on: s.provider_id == p.id, group_by: [s.merchant_id, s.provider_id, s.date, s.status, m.name, p.name], select: %{ merchant_id: s.merchant_id, merchant_name: m.name, provider_id: s.provider_id, provider_name: p.name, date: s.date, status: s.status, total_amount: sum(s.amount) } ) |> Repo.all() end @doc """ Returns all transactions for a given settlement id. """ def list_transactions_for_settlement(settlement_id) do from(t in SettlementTransaction, where: t.settlement_id == ^settlement_id) |> Repo.all() end @doc """ Returns all settlement files. """ def list_settlement_files do Repo.all(SettlementFile) end @doc """ Creates a settlement file with the given attributes. """ def create_settlement_file(attrs) do %SettlementFile{} |> SettlementFile.changeset(attrs) |> Repo.insert() end def list_file_audits(settlement_file_id) do Repo.all( from a in SettlementFileAudit, where: a.settlement_file_id == ^settlement_file_id, order_by: [desc: a.inserted_at] ) end def create_file_audit(attrs) do %SettlementFileAudit{} |> SettlementFileAudit.changeset(attrs) |> Repo.insert() end end