2023-03-07 22:26:51 +08:00
|
|
|
# The Mia! Accounting Flask Project.
|
|
|
|
# Author: imacat@mail.imacat.idv.tw (imacat), 2023/3/7
|
|
|
|
|
|
|
|
# Copyright (c) 2023 imacat.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
"""The income statement.
|
|
|
|
|
|
|
|
"""
|
|
|
|
from decimal import Decimal
|
|
|
|
|
|
|
|
import sqlalchemy as sa
|
2023-03-09 11:26:35 +08:00
|
|
|
from flask import render_template, Response
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
from accounting import db
|
|
|
|
from accounting.locale import gettext
|
|
|
|
from accounting.models import Currency, BaseAccount, Account, Transaction, \
|
|
|
|
JournalEntry
|
|
|
|
from accounting.report.period import Period
|
2023-03-09 11:04:12 +08:00
|
|
|
from .utils.base_page_params import BasePageParams
|
2023-03-08 00:41:34 +08:00
|
|
|
from .utils.base_report import BaseReport
|
2023-03-08 11:55:52 +08:00
|
|
|
from .utils.csv_export import BaseCSVRow, csv_download, period_spec
|
2023-03-09 11:50:02 +08:00
|
|
|
from .utils.urls import ledger_url, income_statement_url
|
2023-03-07 22:33:16 +08:00
|
|
|
from .utils.option_link import OptionLink
|
|
|
|
from .utils.period_choosers import IncomeStatementPeriodChooser
|
|
|
|
from .utils.report_chooser import ReportChooser
|
|
|
|
from .utils.report_type import ReportType
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
|
2023-03-08 17:55:34 +08:00
|
|
|
class ReportAccount:
|
|
|
|
"""An account in the report."""
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
def __init__(self, account: Account, amount: Decimal, url: str):
|
2023-03-08 17:55:34 +08:00
|
|
|
"""Constructs an account in the report.
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
:param account: The account.
|
|
|
|
:param amount: The amount.
|
|
|
|
:param url: The URL to the ledger of the account.
|
|
|
|
"""
|
|
|
|
self.account: Account = account
|
|
|
|
"""The account."""
|
|
|
|
self.amount: Decimal = amount
|
|
|
|
"""The amount of the account."""
|
|
|
|
self.url: str = url
|
|
|
|
"""The URL to the ledger of the account."""
|
|
|
|
|
|
|
|
|
2023-03-08 17:40:08 +08:00
|
|
|
class AccumulatedTotal:
|
|
|
|
"""An accumulated total."""
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
def __init__(self, title: str):
|
2023-03-08 17:40:08 +08:00
|
|
|
"""Constructs an accumulated total.
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
:param title: The title.
|
|
|
|
"""
|
|
|
|
self.title: str = title
|
|
|
|
"""The account."""
|
|
|
|
self.amount: Decimal = Decimal("0")
|
|
|
|
"""The amount of the account."""
|
|
|
|
|
|
|
|
|
2023-03-08 17:40:08 +08:00
|
|
|
class Subsection:
|
|
|
|
"""A subsection."""
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
def __init__(self, title: BaseAccount):
|
2023-03-08 17:40:08 +08:00
|
|
|
"""Constructs a subsection.
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
:param title: The title account.
|
|
|
|
"""
|
|
|
|
self.title: BaseAccount = title
|
|
|
|
"""The title account."""
|
2023-03-08 17:55:34 +08:00
|
|
|
self.accounts: list[ReportAccount] = []
|
2023-03-07 22:26:51 +08:00
|
|
|
"""The accounts in the subsection."""
|
|
|
|
|
|
|
|
@property
|
|
|
|
def total(self) -> Decimal:
|
|
|
|
"""Returns the total of the subsection.
|
|
|
|
|
|
|
|
:return: The total of the subsection.
|
|
|
|
"""
|
|
|
|
return sum([x.amount for x in self.accounts])
|
|
|
|
|
|
|
|
|
2023-03-08 17:40:08 +08:00
|
|
|
class Section:
|
|
|
|
"""A section."""
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
def __init__(self, title: BaseAccount, accumulated_title: str):
|
2023-03-08 17:40:08 +08:00
|
|
|
"""Constructs a section.
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
:param title: The title account.
|
|
|
|
:param accumulated_title: The title for the accumulated total.
|
|
|
|
"""
|
|
|
|
self.title: BaseAccount = title
|
|
|
|
"""The title account."""
|
2023-03-08 17:40:08 +08:00
|
|
|
self.subsections: list[Subsection] = []
|
2023-03-07 22:26:51 +08:00
|
|
|
"""The subsections in the section."""
|
2023-03-08 17:40:08 +08:00
|
|
|
self.accumulated: AccumulatedTotal \
|
|
|
|
= AccumulatedTotal(accumulated_title)
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def total(self) -> Decimal:
|
|
|
|
"""Returns the total of the section.
|
|
|
|
|
|
|
|
:return: The total of the section.
|
|
|
|
"""
|
|
|
|
return sum([x.total for x in self.subsections])
|
|
|
|
|
|
|
|
|
2023-03-07 22:45:29 +08:00
|
|
|
class CSVRow(BaseCSVRow):
|
2023-03-08 17:21:14 +08:00
|
|
|
"""A row in the CSV."""
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
def __init__(self, text: str | None, amount: str | Decimal | None):
|
2023-03-08 17:21:14 +08:00
|
|
|
"""Constructs a row in the CSV.
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
:param text: The text.
|
|
|
|
:param amount: The amount.
|
|
|
|
"""
|
|
|
|
self.text: str | None = text
|
|
|
|
"""The text."""
|
|
|
|
self.amount: str | Decimal | None = amount
|
|
|
|
"""The amount."""
|
|
|
|
|
|
|
|
@property
|
|
|
|
def values(self) -> list[str | Decimal | None]:
|
|
|
|
"""Returns the values of the row.
|
|
|
|
|
|
|
|
:return: The values of the row.
|
|
|
|
"""
|
|
|
|
return [self.text, self.amount]
|
|
|
|
|
|
|
|
|
2023-03-08 17:27:19 +08:00
|
|
|
class PageParams(BasePageParams):
|
|
|
|
"""The HTML page parameters."""
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
def __init__(self, currency: Currency,
|
|
|
|
period: Period,
|
|
|
|
has_data: bool,
|
2023-03-08 17:40:08 +08:00
|
|
|
sections: list[Section], ):
|
2023-03-08 17:27:19 +08:00
|
|
|
"""Constructs the HTML page parameters.
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
:param currency: The currency.
|
|
|
|
:param period: The period.
|
|
|
|
:param has_data: True if there is any data, or False otherwise.
|
|
|
|
"""
|
|
|
|
self.currency: Currency = currency
|
|
|
|
"""The currency."""
|
|
|
|
self.period: Period = period
|
|
|
|
"""The period."""
|
|
|
|
self.__has_data: bool = has_data
|
|
|
|
"""True if there is any data, or False otherwise."""
|
2023-03-08 17:40:08 +08:00
|
|
|
self.sections: list[Section] = sections
|
2023-03-07 22:26:51 +08:00
|
|
|
self.period_chooser: IncomeStatementPeriodChooser \
|
|
|
|
= IncomeStatementPeriodChooser(currency)
|
|
|
|
"""The period chooser."""
|
|
|
|
|
|
|
|
@property
|
|
|
|
def has_data(self) -> bool:
|
|
|
|
"""Returns whether there is any data on the page.
|
|
|
|
|
|
|
|
:return: True if there is any data, or False otherwise.
|
|
|
|
"""
|
|
|
|
return self.__has_data
|
|
|
|
|
|
|
|
@property
|
|
|
|
def report_chooser(self) -> ReportChooser:
|
|
|
|
"""Returns the report chooser.
|
|
|
|
|
|
|
|
:return: The report chooser.
|
|
|
|
"""
|
|
|
|
return ReportChooser(ReportType.INCOME_STATEMENT,
|
|
|
|
currency=self.currency,
|
|
|
|
period=self.period)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def currency_options(self) -> list[OptionLink]:
|
|
|
|
"""Returns the currency options.
|
|
|
|
|
|
|
|
:return: The currency options.
|
|
|
|
"""
|
2023-03-09 11:26:35 +08:00
|
|
|
return self._get_currency_options(
|
2023-03-09 11:50:02 +08:00
|
|
|
lambda x: income_statement_url(x, self.period), self.currency)
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
|
2023-03-08 00:41:34 +08:00
|
|
|
class IncomeStatement(BaseReport):
|
2023-03-07 22:26:51 +08:00
|
|
|
"""The income statement."""
|
|
|
|
|
|
|
|
def __init__(self, currency: Currency, period: Period):
|
|
|
|
"""Constructs an income statement.
|
|
|
|
|
|
|
|
:param currency: The currency.
|
|
|
|
:param period: The period.
|
|
|
|
"""
|
|
|
|
self.__currency: Currency = currency
|
|
|
|
"""The currency."""
|
|
|
|
self.__period: Period = period
|
|
|
|
"""The period."""
|
|
|
|
self.__has_data: bool
|
|
|
|
"""True if there is any data, or False otherwise."""
|
2023-03-08 17:40:08 +08:00
|
|
|
self.__sections: list[Section]
|
2023-03-07 22:26:51 +08:00
|
|
|
"""The sections."""
|
|
|
|
self.__set_data()
|
|
|
|
|
|
|
|
def __set_data(self) -> None:
|
|
|
|
"""Queries and sets data sections in the income statement.
|
|
|
|
|
|
|
|
:return: None.
|
|
|
|
"""
|
2023-03-08 17:55:34 +08:00
|
|
|
balances: list[ReportAccount] = self.__query_balances()
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
titles: list[BaseAccount] = BaseAccount.query\
|
|
|
|
.filter(BaseAccount.code.in_({"4", "5", "6", "7", "8", "9"})).all()
|
|
|
|
subtitles: list[BaseAccount] = BaseAccount.query\
|
|
|
|
.filter(BaseAccount.code.in_({x.account.base_code[:2]
|
|
|
|
for x in balances})).all()
|
|
|
|
|
|
|
|
total_titles: dict[str, str] \
|
2023-03-08 11:19:41 +08:00
|
|
|
= {"4": gettext("total operating revenue"),
|
2023-03-07 22:26:51 +08:00
|
|
|
"5": gettext("gross income"),
|
|
|
|
"6": gettext("operating income"),
|
|
|
|
"7": gettext("before tax income"),
|
|
|
|
"8": gettext("after tax income"),
|
|
|
|
"9": gettext("net income or loss for current period")}
|
|
|
|
|
2023-03-08 17:40:08 +08:00
|
|
|
sections: dict[str, Section] \
|
|
|
|
= {x.code: Section(x, total_titles[x.code]) for x in titles}
|
|
|
|
subsections: dict[str, Subsection] \
|
|
|
|
= {x.code: Subsection(x) for x in subtitles}
|
2023-03-07 22:26:51 +08:00
|
|
|
for subsection in subsections.values():
|
|
|
|
sections[subsection.title.code[0]].subsections.append(subsection)
|
|
|
|
for balance in balances:
|
|
|
|
subsections[balance.account.base_code[:2]].accounts.append(balance)
|
|
|
|
|
|
|
|
self.__has_data = len(balances) > 0
|
|
|
|
self.__sections = sorted(sections.values(), key=lambda x: x.title.code)
|
|
|
|
total: Decimal = Decimal("0")
|
|
|
|
for section in self.__sections:
|
|
|
|
total = total + section.total
|
|
|
|
section.accumulated.amount = total
|
|
|
|
|
2023-03-08 17:55:34 +08:00
|
|
|
def __query_balances(self) -> list[ReportAccount]:
|
2023-03-07 22:26:51 +08:00
|
|
|
"""Queries and returns the balances.
|
|
|
|
|
|
|
|
:return: The balances.
|
|
|
|
"""
|
|
|
|
sub_conditions: list[sa.BinaryExpression] \
|
|
|
|
= [Account.base_code.startswith(str(x)) for x in range(4, 10)]
|
|
|
|
conditions: list[sa.BinaryExpression] \
|
|
|
|
= [JournalEntry.currency_code == self.__currency.code,
|
|
|
|
sa.or_(*sub_conditions)]
|
|
|
|
if self.__period.start is not None:
|
|
|
|
conditions.append(Transaction.date >= self.__period.start)
|
|
|
|
if self.__period.end is not None:
|
|
|
|
conditions.append(Transaction.date <= self.__period.end)
|
|
|
|
balance_func: sa.Function = sa.func.sum(sa.case(
|
2023-03-07 23:15:46 +08:00
|
|
|
(JournalEntry.is_debit, -JournalEntry.amount),
|
|
|
|
else_=JournalEntry.amount)).label("balance")
|
2023-03-09 10:49:11 +08:00
|
|
|
select_balances: sa.Select = sa.select(Account.id, balance_func)\
|
2023-03-07 22:26:51 +08:00
|
|
|
.join(Transaction).join(Account)\
|
|
|
|
.filter(*conditions)\
|
2023-03-09 10:49:11 +08:00
|
|
|
.group_by(Account.id)\
|
2023-03-07 22:26:51 +08:00
|
|
|
.order_by(Account.base_code, Account.no)
|
2023-03-09 10:49:11 +08:00
|
|
|
balances: list[sa.Row] = db.session.execute(select_balances).all()
|
2023-03-07 22:26:51 +08:00
|
|
|
accounts: dict[int, Account] \
|
|
|
|
= {x.id: x for x in Account.query
|
2023-03-09 10:49:11 +08:00
|
|
|
.filter(Account.id.in_([x.id for x in balances])).all()}
|
|
|
|
return [ReportAccount(account=accounts[x.id],
|
2023-03-08 17:55:34 +08:00
|
|
|
amount=x.balance,
|
2023-03-09 11:50:02 +08:00
|
|
|
url=ledger_url(self.__currency,
|
|
|
|
accounts[x.id],
|
|
|
|
self.__period))
|
2023-03-07 22:26:51 +08:00
|
|
|
for x in balances]
|
|
|
|
|
|
|
|
def csv(self) -> Response:
|
|
|
|
"""Returns the report as CSV for download.
|
|
|
|
|
|
|
|
:return: The response of the report for download.
|
|
|
|
"""
|
|
|
|
filename: str = "income-statement-{currency}-{period}.csv"\
|
2023-03-08 11:55:52 +08:00
|
|
|
.format(currency=self.__currency.code,
|
|
|
|
period=period_spec(self.__period))
|
2023-03-07 22:45:29 +08:00
|
|
|
return csv_download(filename, self.__get_csv_rows())
|
2023-03-07 22:26:51 +08:00
|
|
|
|
|
|
|
def __get_csv_rows(self) -> list[CSVRow]:
|
|
|
|
"""Composes and returns the CSV rows.
|
|
|
|
|
|
|
|
:return: The CSV rows.
|
|
|
|
"""
|
|
|
|
total_str: str = gettext("Total")
|
|
|
|
rows: list[CSVRow] = [CSVRow(None, gettext("Amount"))]
|
|
|
|
for section in self.__sections:
|
|
|
|
rows.append(CSVRow(str(section.title).title(), None))
|
|
|
|
for subsection in section.subsections:
|
|
|
|
rows.append(CSVRow(f" {str(subsection.title).title()}", None))
|
|
|
|
for account in subsection.accounts:
|
|
|
|
rows.append(CSVRow(f" {str(account.account).title()}",
|
|
|
|
account.amount))
|
|
|
|
rows.append(CSVRow(f" {total_str}", subsection.total))
|
|
|
|
rows.append(CSVRow(section.accumulated.title.title(),
|
|
|
|
section.accumulated.amount))
|
|
|
|
rows.append(CSVRow(None, None))
|
|
|
|
rows = rows[:-1]
|
|
|
|
return rows
|
|
|
|
|
|
|
|
def html(self) -> str:
|
|
|
|
"""Composes and returns the report as HTML.
|
|
|
|
|
|
|
|
:return: The report as HTML.
|
|
|
|
"""
|
2023-03-08 17:27:19 +08:00
|
|
|
params: PageParams = PageParams(currency=self.__currency,
|
|
|
|
period=self.__period,
|
|
|
|
has_data=self.__has_data,
|
|
|
|
sections=self.__sections)
|
2023-03-07 22:26:51 +08:00
|
|
|
return render_template("accounting/report/income-statement.html",
|
|
|
|
report=params)
|