Added to track the net balance and offset of the original entries.

This commit is contained in:
2023-03-17 22:32:01 +08:00
parent 40e329d37f
commit d88b3ac770
38 changed files with 3103 additions and 183 deletions

656
tests/test_offset.py Normal file

@ -0,0 +1,656 @@
# The Mia! Accounting Flask Project.
# Author: imacat@mail.imacat.idv.tw (imacat), 2023/3/11
# 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 test for the offset.
"""
import unittest
import httpx
from click.testing import Result
from flask import Flask
from flask.testing import FlaskCliRunner
from test_site import db
from testlib import create_test_app, get_client
from testlib_offset import TestData, JournalEntryData, TransactionData, \
CurrencyData
from testlib_txn import Accounts, match_txn_detail
PREFIX: str = "/accounting/transactions"
"""The URL prefix for the transaction management."""
class OffsetTestCase(unittest.TestCase):
"""The offset test case."""
def setUp(self) -> None:
"""Sets up the test.
This is run once per test.
:return: None.
"""
self.app: Flask = create_test_app()
runner: FlaskCliRunner = self.app.test_cli_runner()
with self.app.app_context():
from accounting.models import BaseAccount, Transaction, \
JournalEntry
result: Result
result = runner.invoke(args="init-db")
self.assertEqual(result.exit_code, 0)
if BaseAccount.query.first() is None:
result = runner.invoke(args="accounting-init-base")
self.assertEqual(result.exit_code, 0)
result = runner.invoke(args=["accounting-init-currencies",
"-u", "editor"])
self.assertEqual(result.exit_code, 0)
result = runner.invoke(args=["accounting-init-accounts",
"-u", "editor"])
self.assertEqual(result.exit_code, 0)
Transaction.query.delete()
JournalEntry.query.delete()
self.client, self.csrf_token = get_client(self.app, "editor")
self.data: TestData = TestData(self.app, self.client, self.csrf_token)
def test_add_receivable_offset(self) -> None:
"""Tests to add the receivable offset.
:return: None.
"""
from accounting.models import Account, Transaction
create_uri: str = f"{PREFIX}/create/income?next=%2F_next"
store_uri: str = f"{PREFIX}/store/income"
form: dict[str, str]
response: httpx.Response
txn_data: TransactionData = TransactionData(
self.data.e_r_or3d.txn.days, [CurrencyData(
"USD",
[],
[JournalEntryData(Accounts.RECEIVABLE,
self.data.e_r_or1d.summary, "300",
original_entry=self.data.e_r_or1d),
JournalEntryData(Accounts.RECEIVABLE,
self.data.e_r_or1d.summary, "100",
original_entry=self.data.e_r_or1d),
JournalEntryData(Accounts.RECEIVABLE,
self.data.e_r_or3d.summary, "100",
original_entry=self.data.e_r_or3d)])])
# Non-existing original entry ID
form = txn_data.new_form(self.csrf_token)
form["currency-1-credit-1-original_entry_id"] = "9999"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# The same side
form = txn_data.new_form(self.csrf_token)
form["currency-1-credit-1-original_entry_id"] = self.data.e_p_or1c.id
form["currency-1-credit-1-account_code"] = self.data.e_p_or1c.account
form["currency-1-credit-1-amount"] = "100"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# The original entry does not need offset
with self.app.app_context():
account = Account.find_by_code(Accounts.RECEIVABLE)
account.is_offset_needed = False
db.session.commit()
response = self.client.post(store_uri,
data=txn_data.new_form(self.csrf_token))
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
with self.app.app_context():
account = Account.find_by_code(Accounts.RECEIVABLE)
account.is_offset_needed = True
db.session.commit()
# The original entry is also an offset
form = txn_data.new_form(self.csrf_token)
form["currency-1-credit-1-original_entry_id"] = self.data.e_p_of1d.id
form["currency-1-credit-1-account_code"] = self.data.e_p_of1d.account
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not the same currency
form = txn_data.new_form(self.csrf_token)
form["currency-1-code"] = "EUR"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not the same account
form = txn_data.new_form(self.csrf_token)
form["currency-1-credit-1-account_code"] = Accounts.NOTES_RECEIVABLE
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not exceeding net balance - partially offset
form = txn_data.new_form(self.csrf_token)
form["currency-1-credit-1-amount"] = "300.01"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not exceeding net balance - unmatched
form = txn_data.new_form(self.csrf_token)
form["currency-1-credit-3-amount"] = "100.01"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not before the original entries
txn_data.days = self.data.e_r_or3d.txn.days + 1
form = txn_data.new_form(self.csrf_token)
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
txn_data.days = 0
# Success
form = txn_data.new_form(self.csrf_token)
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
txn_id: int = match_txn_detail(response.headers["Location"])
with self.app.app_context():
txn = db.session.get(Transaction, txn_id)
for offset in txn.currencies[0].credit:
self.assertIsNotNone(offset.original_entry_id)
def test_edit_receivable_offset(self) -> None:
"""Tests to edit the receivable offset.
:return: None.
"""
from accounting.models import Account
txn_data: TransactionData = self.data.t_r_of2
edit_uri: str = f"{PREFIX}/{txn_data.id}/edit?next=%2F_next"
update_uri: str = f"{PREFIX}/{txn_data.id}/update"
form: dict[str, str]
response: httpx.Response
# Non-existing original entry ID
form = txn_data.update_form(self.csrf_token)
form["currency-1-credit-1-original_entry_id"] = "9999"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# The same side
form = txn_data.update_form(self.csrf_token)
form["currency-1-credit-1-original_entry_id"] = self.data.e_p_or1c.id
form["currency-1-credit-1-account_code"] = self.data.e_p_or1c.account
form["currency-1-debit-1-amount"] = "100"
form["currency-1-credit-1-amount"] = "100"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# The original entry does not need offset
with self.app.app_context():
account = Account.find_by_code(Accounts.RECEIVABLE)
account.is_offset_needed = False
db.session.commit()
response = self.client.post(update_uri,
data=txn_data.update_form(self.csrf_token))
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
with self.app.app_context():
account = Account.find_by_code(Accounts.RECEIVABLE)
account.is_offset_needed = True
db.session.commit()
# The original entry is also an offset
form = txn_data.update_form(self.csrf_token)
form["currency-1-credit-1-original_entry_id"] = self.data.e_p_of1d.id
form["currency-1-credit-1-account_code"] = self.data.e_p_of1d.account
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not the same currency
form = txn_data.update_form(self.csrf_token)
form["currency-1-code"] = "EUR"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not the same account
form = txn_data.update_form(self.csrf_token)
form["currency-1-credit-1-account_code"] = Accounts.NOTES_RECEIVABLE
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not exceeding net balance - partially offset
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-amount"] = "600.01"
form["currency-1-credit-1-amount"] = "600.01"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not exceeding net balance - unmatched
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-3-amount"] = "600.01"
form["currency-1-credit-3-amount"] = "600.01"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not before the original entries
txn_data.days = self.data.e_r_or3d.txn.days + 1
form = txn_data.update_form(self.csrf_token)
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
txn_data.days = 0
# Success
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-amount"] = "600"
form["currency-1-credit-1-amount"] = "600"
form["currency-1-debit-3-amount"] = "600"
form["currency-1-credit-3-amount"] = "600"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"],
f"{PREFIX}/{txn_data.id}?next=%2F_next")
def test_edit_receivable_original_entry(self) -> None:
"""Tests to edit the receivable original entry.
:return: None.
"""
from accounting.models import Transaction
txn_data: TransactionData = self.data.t_r_or1
edit_uri: str = f"{PREFIX}/{txn_data.id}/edit?next=%2F_next"
update_uri: str = f"{PREFIX}/{txn_data.id}/update"
form: dict[str, str]
response: httpx.Response
txn_data.days = self.data.t_r_of1.days
txn_data.currencies[0].debit[0].amount = "800"
txn_data.currencies[0].credit[0].amount = "800"
txn_data.currencies[0].debit[1].amount = "3.4"
txn_data.currencies[0].credit[1].amount = "3.4"
# Not the same currency
form = txn_data.update_form(self.csrf_token)
form["currency-1-code"] = "EUR"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not the same account
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-account_code"] = Accounts.NOTES_RECEIVABLE
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not less than offset total - partially offset
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-amount"] = "799.99"
form["currency-1-credit-1-amount"] = "799.99"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not less than offset total - fully offset
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-2-amount"] = "3.39"
form["currency-1-credit-2-amount"] = "3.39"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not after the offset entries
old_days: int = txn_data.days
txn_data.days = self.data.t_r_of1.days - 1
form = txn_data.update_form(self.csrf_token)
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
txn_data.days = old_days
# Not deleting matched original entries
form = txn_data.update_form(self.csrf_token)
del form["currency-1-debit-1-eid"]
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Success
form = txn_data.update_form(self.csrf_token)
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"],
f"{PREFIX}/{txn_data.id}?next=%2F_next")
# The original entry is always before the offset entry, even when they
# happen in the same day.
with self.app.app_context():
txn_or: Transaction | None = db.session.get(
Transaction, txn_data.id)
self.assertIsNotNone(txn_or)
txn_of: Transaction | None = db.session.get(
Transaction, self.data.t_r_of1.id)
self.assertIsNotNone(txn_of)
self.assertEqual(txn_or.date, txn_of.date)
self.assertLess(txn_or.no, txn_of.no)
def test_add_payable_offset(self) -> None:
"""Tests to add the payable offset.
:return: None.
"""
from accounting.models import Account, Transaction
create_uri: str = f"{PREFIX}/create/expense?next=%2F_next"
store_uri: str = f"{PREFIX}/store/expense"
form: dict[str, str]
response: httpx.Response
txn_data: TransactionData = TransactionData(
self.data.e_p_or3c.txn.days, [CurrencyData(
"USD",
[JournalEntryData(Accounts.PAYABLE,
self.data.e_p_or1c.summary, "500",
original_entry=self.data.e_p_or1c),
JournalEntryData(Accounts.PAYABLE,
self.data.e_p_or1c.summary, "300",
original_entry=self.data.e_p_or1c),
JournalEntryData(Accounts.PAYABLE,
self.data.e_p_or3c.summary, "120",
original_entry=self.data.e_p_or3c)],
[])])
# Non-existing original entry ID
form = txn_data.new_form(self.csrf_token)
form["currency-1-debit-1-original_entry_id"] = "9999"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# The same side
form = txn_data.new_form(self.csrf_token)
form["currency-1-debit-1-original_entry_id"] = self.data.e_r_or1d.id
form["currency-1-debit-1-account_code"] = self.data.e_r_or1d.account
form["currency-1-debit-1-amount"] = "100"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# The original entry does not need offset
with self.app.app_context():
account = Account.find_by_code(Accounts.PAYABLE)
account.is_offset_needed = False
db.session.commit()
response = self.client.post(store_uri,
data=txn_data.new_form(self.csrf_token))
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
with self.app.app_context():
account = Account.find_by_code(Accounts.PAYABLE)
account.is_offset_needed = True
db.session.commit()
# The original entry is also an offset
form = txn_data.new_form(self.csrf_token)
form["currency-1-debit-1-original_entry_id"] = self.data.e_r_of1c.id
form["currency-1-debit-1-account_code"] = self.data.e_r_of1c.account
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not the same currency
form = txn_data.new_form(self.csrf_token)
form["currency-1-code"] = "EUR"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not the same account
form = txn_data.new_form(self.csrf_token)
form["currency-1-debit-1-account_code"] = Accounts.NOTES_PAYABLE
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not exceeding net balance - partially offset
form = txn_data.new_form(self.csrf_token)
form["currency-1-debit-1-amount"] = "500.01"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not exceeding net balance - unmatched
form = txn_data.new_form(self.csrf_token)
form["currency-1-debit-3-amount"] = "120.01"
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Not before the original entries
txn_data.days = self.data.e_p_or3c.txn.days + 1
form = txn_data.new_form(self.csrf_token)
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
txn_data.days = 0
# Success
form = txn_data.new_form(self.csrf_token)
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
txn_id: int = match_txn_detail(response.headers["Location"])
with self.app.app_context():
txn = db.session.get(Transaction, txn_id)
for offset in txn.currencies[0].debit:
self.assertIsNotNone(offset.original_entry_id)
def test_edit_payable_offset(self) -> None:
"""Tests to edit the payable offset.
:return: None.
"""
from accounting.models import Account, Transaction
txn_data: TransactionData = self.data.t_p_of2
edit_uri: str = f"{PREFIX}/{txn_data.id}/edit?next=%2F_next"
update_uri: str = f"{PREFIX}/{txn_data.id}/update"
form: dict[str, str]
response: httpx.Response
# Non-existing original entry ID
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-original_entry_id"] = "9999"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# The same side
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-original_entry_id"] = self.data.e_r_or1d.id
form["currency-1-debit-1-account_code"] = self.data.e_r_or1d.account
form["currency-1-debit-1-amount"] = "100"
form["currency-1-credit-1-amount"] = "100"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# The original entry does not need offset
with self.app.app_context():
account = Account.find_by_code(Accounts.PAYABLE)
account.is_offset_needed = False
db.session.commit()
response = self.client.post(update_uri,
data=txn_data.update_form(self.csrf_token))
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
with self.app.app_context():
account = Account.find_by_code(Accounts.PAYABLE)
account.is_offset_needed = True
db.session.commit()
# The original entry is also an offset
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-original_entry_id"] = self.data.e_r_of1c.id
form["currency-1-debit-1-account_code"] = self.data.e_r_of1c.account
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not the same currency
form = txn_data.update_form(self.csrf_token)
form["currency-1-code"] = "EUR"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not the same account
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-account_code"] = Accounts.NOTES_PAYABLE
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not exceeding net balance - partially offset
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-amount"] = "1100.01"
form["currency-1-credit-1-amount"] = "1100.01"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not exceeding net balance - unmatched
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-3-amount"] = "900.01"
form["currency-1-credit-3-amount"] = "900.01"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not before the original entries
old_days: int = txn_data.days
txn_data.days = self.data.e_p_or3c.txn.days + 1
form = txn_data.update_form(self.csrf_token)
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
txn_data.days = old_days
# Success
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-amount"] = "1100"
form["currency-1-credit-1-amount"] = "1100"
form["currency-1-debit-3-amount"] = "900"
form["currency-1-credit-3-amount"] = "900"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
txn_id: int = match_txn_detail(response.headers["Location"])
with self.app.app_context():
txn = db.session.get(Transaction, txn_id)
for offset in txn.currencies[0].debit:
self.assertIsNotNone(offset.original_entry_id)
def test_edit_payable_original_entry(self) -> None:
"""Tests to edit the payable original entry.
:return: None.
"""
from accounting.models import Transaction
txn_data: TransactionData = self.data.t_p_or1
edit_uri: str = f"{PREFIX}/{txn_data.id}/edit?next=%2F_next"
update_uri: str = f"{PREFIX}/{txn_data.id}/update"
form: dict[str, str]
response: httpx.Response
txn_data.days = self.data.t_p_of1.days
txn_data.currencies[0].debit[0].amount = "1200"
txn_data.currencies[0].credit[0].amount = "1200"
txn_data.currencies[0].debit[1].amount = "0.9"
txn_data.currencies[0].credit[1].amount = "0.9"
# Not the same currency
form = txn_data.update_form(self.csrf_token)
form["currency-1-code"] = "EUR"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not the same account
form = txn_data.update_form(self.csrf_token)
form["currency-1-credit-1-account_code"] = Accounts.NOTES_PAYABLE
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not less than offset total - partially offset
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-1-amount"] = "1199.99"
form["currency-1-credit-1-amount"] = "1199.99"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not less than offset total - fully offset
form = txn_data.update_form(self.csrf_token)
form["currency-1-debit-2-amount"] = "0.89"
form["currency-1-credit-2-amount"] = "0.89"
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Not after the offset entries
old_days: int = txn_data.days
txn_data.days = self.data.t_p_of1.days - 1
form = txn_data.update_form(self.csrf_token)
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
txn_data.days = old_days
# Not deleting matched original entries
form = txn_data.update_form(self.csrf_token)
del form["currency-1-credit-1-eid"]
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Success
form = txn_data.update_form(self.csrf_token)
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"],
f"{PREFIX}/{txn_data.id}?next=%2F_next")
# The original entry is always before the offset entry, even when they
# happen in the same day
with self.app.app_context():
txn_or: Transaction | None = db.session.get(
Transaction, txn_data.id)
self.assertIsNotNone(txn_or)
txn_of: Transaction | None = db.session.get(
Transaction, self.data.t_p_of1.id)
self.assertIsNotNone(txn_of)
self.assertEqual(txn_or.date, txn_of.date)
self.assertLess(txn_or.no, txn_of.no)

@ -229,6 +229,15 @@ class CashIncomeTransactionTestCase(unittest.TestCase):
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# A receivable entry cannot start from the credit side
form = self.__get_add_form()
key: str = [x for x in form.keys()
if x.endswith("-account_code") and "-credit-" in x][0]
form[key] = Accounts.RECEIVABLE
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Negative amount
form = self.__get_add_form()
set_negative_amount(form)
@ -380,6 +389,15 @@ class CashIncomeTransactionTestCase(unittest.TestCase):
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# A receivable entry cannot start from the credit side
form = self.__get_add_form()
key: str = [x for x in form.keys()
if x.endswith("-account_code") and "-credit-" in x][0]
form[key] = Accounts.RECEIVABLE
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Negative amount
form: dict[str, str] = form_0.copy()
set_negative_amount(form)
@ -781,6 +799,15 @@ class CashExpenseTransactionTestCase(unittest.TestCase):
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# A payable entry cannot start from the debit side
form = self.__get_add_form()
key: str = [x for x in form.keys()
if x.endswith("-account_code") and "-debit-" in x][0]
form[key] = Accounts.PAYABLE
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Negative amount
form = self.__get_add_form()
set_negative_amount(form)
@ -935,6 +962,15 @@ class CashExpenseTransactionTestCase(unittest.TestCase):
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# A payable entry cannot start from the debit side
form = self.__get_add_form()
key: str = [x for x in form.keys()
if x.endswith("-account_code") and "-debit-" in x][0]
form[key] = Accounts.PAYABLE
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Negative amount
form: dict[str, str] = form_0.copy()
set_negative_amount(form)
@ -1356,6 +1392,24 @@ class TransferTransactionTestCase(unittest.TestCase):
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# A receivable entry cannot start from the credit side
form = self.__get_add_form()
key: str = [x for x in form.keys()
if x.endswith("-account_code") and "-credit-" in x][0]
form[key] = Accounts.RECEIVABLE
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# A payable entry cannot start from the debit side
form = self.__get_add_form()
key: str = [x for x in form.keys()
if x.endswith("-account_code") and "-debit-" in x][0]
form[key] = Accounts.PAYABLE
response = self.client.post(store_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], create_uri)
# Negative amount
form = self.__get_add_form()
set_negative_amount(form)
@ -1537,6 +1591,24 @@ class TransferTransactionTestCase(unittest.TestCase):
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# A receivable entry cannot start from the credit side
form = self.__get_add_form()
key: str = [x for x in form.keys()
if x.endswith("-account_code") and "-credit-" in x][0]
form[key] = Accounts.RECEIVABLE
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# A payable entry cannot start from the debit side
form = self.__get_add_form()
key: str = [x for x in form.keys()
if x.endswith("-account_code") and "-debit-" in x][0]
form[key] = Accounts.PAYABLE
response = self.client.post(update_uri, data=form)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.headers["Location"], edit_uri)
# Negative amount
form: dict[str, str] = form_0.copy()
set_negative_amount(form)

307
tests/testlib_offset.py Normal file

@ -0,0 +1,307 @@
# The Mia! Accounting Flask Project.
# Author: imacat@mail.imacat.idv.tw (imacat), 2023/2/27
# 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 common test libraries for the offset test cases.
"""
from __future__ import annotations
from datetime import date, timedelta
import httpx
from flask import Flask
from test_site import db
from testlib_txn import Accounts, match_txn_detail, NEXT_URI
class JournalEntryData:
"""The journal entry data."""
def __init__(self, account: str, summary: str, amount: str,
original_entry: JournalEntryData | None = None):
"""Constructs the journal entry data.
:param account: The account code.
:param summary: The summary.
:param amount: The amount.
:param original_entry: The original entry.
"""
self.txn: TransactionData | None = None
self.id: int = -1
self.no: int = -1
self.original_entry: JournalEntryData | None = original_entry
self.account: str = account
self.summary: str = summary
self.amount: str = amount
def form(self, prefix: str, entry_type: str, index: int, is_update: bool) \
-> dict[str, str]:
"""Returns the journal entry as form data.
:param prefix: The prefix of the form fields.
:param entry_type: The entry type, either "debit" or "credit".
:param index: The entry index.
:param is_update: True for an update operation, or False otherwise
:return: The form data.
"""
prefix = f"{prefix}-{entry_type}-{index}"
form: dict[str, str] = {f"{prefix}-account_code": self.account,
f"{prefix}-summary": self.summary,
f"{prefix}-amount": self.amount}
if is_update and self.id != -1:
form[f"{prefix}-eid"] = str(self.id)
form[f"{prefix}-no"] = str(index) if self.no == -1 else str(self.no)
if self.original_entry is not None:
assert self.original_entry.id != -1
form[f"{prefix}-original_entry_id"] = str(self.original_entry.id)
return form
class CurrencyData:
"""The transaction currency data."""
def __init__(self, currency: str, debit: list[JournalEntryData],
credit: list[JournalEntryData]):
"""Constructs the transaction currency data.
:param currency: The currency code.
:param debit: The debit journal entries.
:param credit: The credit journal entries.
"""
self.code: str = currency
self.debit: list[JournalEntryData] = debit
self.credit: list[JournalEntryData] = credit
def form(self, index: int, is_update: bool) -> dict[str, str]:
"""Returns the currency as form data.
:param index: The currency index.
:param is_update: True for an update operation, or False otherwise
:return: The form data.
"""
prefix: str = f"currency-{index}"
form: dict[str, str] = {f"{prefix}-code": self.code}
for i in range(len(self.debit)):
form.update(self.debit[i].form(prefix, "debit", i + 1, is_update))
for i in range(len(self.credit)):
form.update(self.credit[i].form(prefix, "credit", i + 1,
is_update))
return form
class TransactionData:
"""The transaction data."""
def __init__(self, days: int, currencies: list[CurrencyData]):
"""Constructs a transaction.
:param days: The number of days before today.
:param currencies: The transaction currency data.
"""
self.id: int = -1
self.days: int = days
self.currencies: list[CurrencyData] = currencies
self.note: str | None = None
for currency in self.currencies:
for entry in currency.debit:
entry.txn = self
for entry in currency.credit:
entry.txn = self
def new_form(self, csrf_token: str) -> dict[str, str]:
"""Returns the transaction as a form.
:param csrf_token: The CSRF token.
:return: The transaction as a form.
"""
return self.__form(csrf_token, is_update=False)
def update_form(self, csrf_token: str) -> dict[str, str]:
"""Returns the transaction as a form.
:param csrf_token: The CSRF token.
:return: The transaction as a form.
"""
return self.__form(csrf_token, is_update=True)
def __form(self, csrf_token: str, is_update: bool = False) \
-> dict[str, str]:
"""Returns the transaction as a form.
:param csrf_token: The CSRF token.
:param is_update: True for an update operation, or False otherwise
:return: The transaction as a form.
"""
txn_date: date = date.today() - timedelta(days=self.days)
form: dict[str, str] = {"csrf_token": csrf_token,
"next": NEXT_URI,
"date": txn_date.isoformat()}
for i in range(len(self.currencies)):
form.update(self.currencies[i].form(i + 1, is_update))
if self.note is not None:
form["note"] = self.note
return form
class TestData:
"""The test data."""
def __init__(self, app: Flask, client: httpx.Client, csrf_token: str):
"""Constructs the test data.
:param app: The Flask application.
:param client: The client.
:param csrf_token: The CSRF token.
"""
self.app: Flask = app
self.client: httpx.Client = client
self.csrf_token: str = csrf_token
def couple(summary: str, amount: str, debit: str, credit: str) \
-> tuple[JournalEntryData, JournalEntryData]:
"""Returns a couple of debit-credit journal entries.
:param summary: The summary.
:param amount: The amount.
:param debit: The debit account code.
:param credit: The credit account code.
:return: The debit journal entry and credit journal entry.
"""
return JournalEntryData(debit, summary, amount),\
JournalEntryData(credit, summary, amount)
# Receivable original entries
self.e_r_or1d, self.e_r_or1c = couple(
"Accountant", "1200", Accounts.RECEIVABLE, Accounts.SERVICE)
self.e_r_or2d, self.e_r_or2c = couple(
"Toy", "600", Accounts.RECEIVABLE, Accounts.SALES)
self.e_r_or3d, self.e_r_or3c = couple(
"Noodles", "100", Accounts.RECEIVABLE, Accounts.SALES)
self.e_r_or4d, self.e_r_or4c = couple(
"Interest", "3.4", Accounts.RECEIVABLE, Accounts.INTEREST)
# Payable original entries
self.e_p_or1d, self.e_p_or1c = couple(
"Airplane ticket", "2000", Accounts.TRAVEL, Accounts.PAYABLE)
self.e_p_or2d, self.e_p_or2c = couple(
"Phone", "900", Accounts.OFFICE, Accounts.PAYABLE)
self.e_p_or3d, self.e_p_or3c = couple(
"Steak", "120", Accounts.MEAL, Accounts.PAYABLE)
self.e_p_or4d, self.e_p_or4c = couple(
"Envelop", "0.9", Accounts.OFFICE, Accounts.PAYABLE)
# Original transactions
self.t_r_or1: TransactionData = TransactionData(
50, [CurrencyData("USD", [self.e_r_or1d, self.e_r_or4d],
[self.e_r_or1c, self.e_r_or4c])])
self.t_r_or2: TransactionData = TransactionData(
30, [CurrencyData("USD", [self.e_r_or2d, self.e_r_or3d],
[self.e_r_or2c, self.e_r_or3c])])
self.t_p_or1: TransactionData = TransactionData(
40, [CurrencyData("USD", [self.e_p_or1d, self.e_p_or4d],
[self.e_p_or1c, self.e_p_or4c])])
self.t_p_or2: TransactionData = TransactionData(
20, [CurrencyData("USD", [self.e_p_or2d, self.e_p_or3d],
[self.e_p_or2c, self.e_p_or3c])])
self.__add_txn(self.t_r_or1)
self.__add_txn(self.t_r_or2)
self.__add_txn(self.t_p_or1)
self.__add_txn(self.t_p_or2)
# Receivable offset entries
self.e_r_of1d, self.e_r_of1c = couple(
"Accountant", "500", Accounts.CASH, Accounts.RECEIVABLE)
self.e_r_of1c.original_entry = self.e_r_or1d
self.e_r_of2d, self.e_r_of2c = couple(
"Accountant", "200", Accounts.CASH, Accounts.RECEIVABLE)
self.e_r_of2c.original_entry = self.e_r_or1d
self.e_r_of3d, self.e_r_of3c = couple(
"Accountant", "100", Accounts.CASH, Accounts.RECEIVABLE)
self.e_r_of3c.original_entry = self.e_r_or1d
self.e_r_of4d, self.e_r_of4c = couple(
"Toy", "240", Accounts.CASH, Accounts.RECEIVABLE)
self.e_r_of4c.original_entry = self.e_r_or2d
self.e_r_of5d, self.e_r_of5c = couple(
"Interest", "3.4", Accounts.CASH, Accounts.RECEIVABLE)
self.e_r_of5c.original_entry = self.e_r_or4d
# Payable offset entries
self.e_p_of1d, self.e_p_of1c = couple(
"Airplane ticket", "800", Accounts.PAYABLE, Accounts.CASH)
self.e_p_of1d.original_entry = self.e_p_or1c
self.e_p_of2d, self.e_p_of2c = couple(
"Airplane ticket", "300", Accounts.PAYABLE, Accounts.CASH)
self.e_p_of2d.original_entry = self.e_p_or1c
self.e_p_of3d, self.e_p_of3c = couple(
"Airplane ticket", "100", Accounts.PAYABLE, Accounts.CASH)
self.e_p_of3d.original_entry = self.e_p_or1c
self.e_p_of4d, self.e_p_of4c = couple(
"Phone", "400", Accounts.PAYABLE, Accounts.CASH)
self.e_p_of4d.original_entry = self.e_p_or2c
self.e_p_of5d, self.e_p_of5c = couple(
"Envelop", "0.9", Accounts.PAYABLE, Accounts.CASH)
self.e_p_of5d.original_entry = self.e_p_or4c
# Offset transactions
self.t_r_of1: TransactionData = TransactionData(
25, [CurrencyData("USD", [self.e_r_of1d], [self.e_r_of1c])])
self.t_r_of2: TransactionData = TransactionData(
20, [CurrencyData("USD",
[self.e_r_of2d, self.e_r_of3d, self.e_r_of4d],
[self.e_r_of2c, self.e_r_of3c, self.e_r_of4c])])
self.t_r_of3: TransactionData = TransactionData(
15, [CurrencyData("USD", [self.e_r_of5d], [self.e_r_of5c])])
self.t_p_of1: TransactionData = TransactionData(
15, [CurrencyData("USD", [self.e_p_of1d], [self.e_p_of1c])])
self.t_p_of2: TransactionData = TransactionData(
10, [CurrencyData("USD",
[self.e_p_of2d, self.e_p_of3d, self.e_p_of4d],
[self.e_p_of2c, self.e_p_of3c, self.e_p_of4c])])
self.t_p_of3: TransactionData = TransactionData(
5, [CurrencyData("USD", [self.e_p_of5d], [self.e_p_of5c])])
self.__add_txn(self.t_r_of1)
self.__add_txn(self.t_r_of2)
self.__add_txn(self.t_r_of3)
self.__add_txn(self.t_p_of1)
self.__add_txn(self.t_p_of2)
self.__add_txn(self.t_p_of3)
def __add_txn(self, txn_data: TransactionData) -> None:
"""Adds a transaction.
:param txn_data: The transaction data.
:return: None.
"""
from accounting.models import Transaction
store_uri: str = "/accounting/transactions/store/transfer"
response: httpx.Response = self.client.post(
store_uri, data=txn_data.new_form(self.csrf_token))
assert response.status_code == 302
txn_id: int = match_txn_detail(response.headers["Location"])
txn_data.id = txn_id
with self.app.app_context():
txn: Transaction | None = db.session.get(Transaction, txn_id)
assert txn is not None
for i in range(len(txn.currencies)):
for j in range(len(txn.currencies[i].debit)):
txn_data.currencies[i].debit[j].id \
= txn.currencies[i].debit[j].id
for j in range(len(txn.currencies[i].credit)):
txn_data.currencies[i].credit[j].id \
= txn.currencies[i].credit[j].id

@ -40,7 +40,10 @@ class Accounts:
CASH: str = "1111-001"
PETTY_CASH: str = "1112-001"
BANK: str = "1113-001"
NOTES_RECEIVABLE: str = "1131-001"
RECEIVABLE: str = "1141-001"
PREPAID: str = "1258-001"
NOTES_PAYABLE: str = "2131-001"
PAYABLE: str = "2141-001"
SALES: str = "4111-001"
SERVICE: str = "4611-001"
@ -48,7 +51,7 @@ class Accounts:
OFFICE: str = "6153-001"
TRAVEL: str = "6154-001"
MEAL: str = "6172-001"
INTEREST: str = "4111-001"
INTEREST: str = "7111-001"
DONATION: str = "7481-001"
RENT: str = "7482-001"