Compare commits
133 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b4815dee5 | |||
| aab728392c | |||
| 5de3f337cf | |||
| 0d4da4132d | |||
| cd9f6ba536 | |||
| 29c5206638 | |||
| f44c04d678 | |||
| 2267bb29b3 | |||
| abf82176e5 | |||
| c6a13cc83a | |||
| a7b74237aa | |||
| 95eff24418 | |||
| f966868736 | |||
| 2a68ddd152 | |||
| 1cfc8dbe38 | |||
| 420a6cdfaa | |||
| ea546fc2df | |||
| d11f753aa0 | |||
| e6622d1e19 | |||
| 2cf0ba4374 | |||
| 6574165f8f | |||
| 42d84b02f4 | |||
| 729e15d4e8 | |||
| 638b833c74 | |||
| 21099909c9 | |||
| 3698654715 | |||
| 271130b107 | |||
| ec22b5e5bd | |||
| 48fae5483d | |||
| 1628f6c1ea | |||
| 60c7028f0b | |||
| 6057ec59b4 | |||
| a527fa5e1d | |||
| a355ec3642 | |||
| 0a0bc1baa0 | |||
| ffc3d477e2 | |||
| 01df97ed46 | |||
| bdd7cac4be | |||
| 13c783ca0e | |||
| da44ba5306 | |||
| 94322ae542 | |||
| 78ff6faa12 | |||
| 9f39836083 | |||
| ad62317e56 | |||
| e7abae0d17 | |||
| 9c7c06c181 | |||
| d6779b40ea | |||
| 761720b712 | |||
| 541295ef05 | |||
| 14131f50f9 | |||
| c4d2d5a378 | |||
| ef9ca1d1ea | |||
| b1de4d519a | |||
| 2c7c527ea9 | |||
| 2843c66453 | |||
| d3c36e30d5 | |||
| d6cbb10c47 | |||
| 8710722eb2 | |||
| a3d2d8215e | |||
| eb5c1781f0 | |||
| 184628dcfc | |||
| 26cf921a6f | |||
| d7bdafa62a | |||
| 88a29bdf83 | |||
| 2ad5f8171d | |||
| 84fa87958a | |||
| ddb02b33f9 | |||
| 5af05c2fa4 | |||
| 2cbf00a939 | |||
| 6b26651d22 | |||
| ed2dda63e9 | |||
| 1a774e3769 | |||
| dd724b6c28 | |||
| 6f68d971ee | |||
| f7df033d58 | |||
| 23eb2c80bd | |||
| 7453ffbd3a | |||
| da348c4ffb | |||
| 2da721d53c | |||
| f943374ade | |||
| abff76ad4e | |||
| e0fc310ef6 | |||
| 13709b7a04 | |||
| fd24ac3318 | |||
| 36e7f84bd9 | |||
| 5235fcdfc3 | |||
| ace5195164 | |||
| ae0a195069 | |||
| 8760f5a0a4 | |||
| dd0aaa01b8 | |||
| fd6793b4f4 | |||
| d4b5f1f11a | |||
| 6110858d48 | |||
| 1cce7d421e | |||
| c42a399d3d | |||
| 478bd25190 | |||
| 0d287624c4 | |||
| c37e7eb37c | |||
| 86afa99217 | |||
| 9b45ee4817 | |||
| 9500e808de | |||
| 55a5b09c45 | |||
| 071711dbdb | |||
| 7fe5b6bd32 | |||
| f20cf685ad | |||
| e57859f601 | |||
| e27f2f08cf | |||
| 058d0cc05d | |||
| 6c33a94a5f | |||
| a2b2f2c1d1 | |||
| 7986fe8e5b | |||
| 17d8d5d813 | |||
| 72a8995fe6 | |||
| d321481e29 | |||
| fed007ff89 | |||
| f721e6a910 | |||
| 471331ffc9 | |||
| 63d6a2aab7 | |||
| f09b328c66 | |||
| 6f97b883fb | |||
| 72974c90aa | |||
| d11bc6df1d | |||
| d409038072 | |||
| 9d33df78a8 | |||
| 882a77d24c | |||
| be67612f67 | |||
| 78e545589d | |||
| b8142f4f99 | |||
| e379d77995 | |||
| 91514f71b1 | |||
| 246c948d76 | |||
| 0d22b02b3f | |||
| 395576d73f |
65
.gitignore
vendored
65
.gitignore
vendored
@ -1,13 +1,5 @@
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/python,database
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=python,database
|
||||
|
||||
### Database ###
|
||||
*.accdb
|
||||
*.db
|
||||
*.dbf
|
||||
*.mdb
|
||||
*.pdb
|
||||
*.sqlite3
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/python
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=python
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
@ -32,7 +24,6 @@ parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
@ -62,7 +53,7 @@ coverage.xml
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
pytestdebug.log
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
@ -83,9 +74,9 @@ instance/
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
doc/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
@ -96,7 +87,9 @@ profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
@ -105,7 +98,22 @@ ipython_config.py
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
@ -123,7 +131,6 @@ venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
pythonenv*
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
@ -146,11 +153,27 @@ dmypy.json
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# profiling data
|
||||
.prof
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
### Python Patch ###
|
||||
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
||||
poetry.toml
|
||||
|
||||
# ruff
|
||||
.ruff_cache/
|
||||
|
||||
# LSP config files
|
||||
pyrightconfig.json
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/python
|
||||
|
||||
### Default user directories
|
||||
export/
|
||||
.pfbudget
|
||||
# Project specific ignores
|
||||
database.db
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
repos:
|
||||
- repo: https://gitlab.com/pycqa/flake8
|
||||
rev: 3.9.2
|
||||
hooks:
|
||||
- id: flake8
|
||||
additional_dependencies: [ flake8-type-checking ]
|
||||
674
COPYING
Normal file
674
COPYING
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
7
LICENSE
7
LICENSE
@ -1,7 +0,0 @@
|
||||
Copyright (c) 2021 Luís Murta
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
134
README.md
134
README.md
@ -1,37 +1,115 @@
|
||||
# Personal Finance Budget (pfbudget)
|
||||
# Personal Finance Budget (`pfbudget`)
|
||||
|
||||
parse -> categorize -> analyze (predict) -> present
|
||||
A budgeting tool for those who want full control and transparency over their finances.
|
||||
|
||||
## Parse
|
||||
Parses bank extracts, based on parsers.yaml, to a SQLite database.
|
||||
## Features
|
||||
|
||||
## Categorize
|
||||
Categorizes transactions based on categories.yaml configuration.
|
||||
- **Bank Data Ingestion:**
|
||||
- Download transactions directly from banks via a PSD2 aggregator (using the GoCardless API).
|
||||
- Or, parse CSV bank extracts using configurable YAML-based parsers (parsers.yaml).
|
||||
- **Database Storage:**
|
||||
- All transactions and categorization rules are stored in a PostgreSQL database.
|
||||
- **Rules-Based Categorization:**
|
||||
- Automatically categorize transactions using rules stored in the database.
|
||||
- Interactive mode for manual categorization of remaining transactions.
|
||||
|
||||
### Reserved categories and groups
|
||||
There is 1 special category and 2 reserved groups.
|
||||
> **Note:** Graphical reporting is currently broken. For now, you can run SQL queries directly on the database for custom reports.
|
||||
|
||||
The `Null` category represent transactions performed between banks/credit cards, that would otherwise appear in the reports and graph. This way, these transactions, while real, are shadowed from the information presented. The net effect of these transaction, if performed in the same month would be moot anyway, since they cancel each other, but could introduce visual pollution when separated for a few days, especial when spawning through different months. The `Null` category then present a placeholder category for these transactions, as well as a way to preserve them out of side.
|
||||
ToDo: As a side bonus, whenever these don't cancel eachother, a warning could be shown.
|
||||
## Quick Start
|
||||
|
||||
The 2 reserved groups are `income` and `investment`.
|
||||
The `income` is used for all income categories. These are the ones that will have a net effect on the overall balance of the individual, and are normally expected to be shown against expenses.
|
||||
The `investment` group is separated from the remaining expenses, has these might not only present in absolute terms much higher values than other categories, but will also be subject to a different treatment when market predictions are incorporated.
|
||||
### 1. Install dependencies
|
||||
|
||||
## Analyze (ToDo)
|
||||
Analyzes previous transaction and predicts future expenses.
|
||||
This project uses [Poetry](https://python-poetry.org/):
|
||||
|
||||
## Present
|
||||
Create graphs and reports
|
||||
1. Monthly spending from everyday purchases
|
||||
2. Networth with big expenses tagged in (ToDo)
|
||||
3. Future trajectory with predictable costs included (ToDo)
|
||||
```sh
|
||||
poetry install
|
||||
```
|
||||
|
||||
## ToDo
|
||||
- [ ] Support regular transactions from fixed group in categories
|
||||
- [ ] Add one table for user inputed transactions and other for fixes
|
||||
- [ ] Predicting future expenses
|
||||
- [ ] Finish writing the README.md
|
||||
- [ ] Implement undo/redo feature in sqlite3 database
|
||||
- [ ] Allow for the possibility to create a new parser during runtime by guessing from transaction list/user input
|
||||
- [ ] Allow for transaction to be passed as argument to main.py
|
||||
### 2. Configure
|
||||
|
||||
- **Database:**
|
||||
Set up a PostgreSQL database and configure your connection through a `.env` file.
|
||||
- **GoCardless credentials:**
|
||||
Create an account with GoCardless (previously Nordigen) and save them on the `.env` file.
|
||||
- **Bank Parsers:**
|
||||
For CSV parsing, edit `parsers.yaml` to match your bank’s CSV format.
|
||||
If the CSV is more complex than the basic rules can handle, you can enable `additional_parser: true` and implement a parser class in `pfbudget/extract/parsers.py`. The `Bank1` is an example implementation.
|
||||
|
||||
### 3. Run
|
||||
|
||||
You can run the app as a module:
|
||||
|
||||
```sh
|
||||
poetry run python3 -m pfbudget [options]
|
||||
```
|
||||
|
||||
#### Example workflows
|
||||
|
||||
- **Download from bank aggregator:**
|
||||
First step is to accept an End User Agreement with the bank in question to get access to your own data:
|
||||
```sh
|
||||
poetry run python3 -m pfbudget eua your_bank
|
||||
```
|
||||
```sh
|
||||
poetry run python3 -m pfbudget download --banks your_bank
|
||||
```
|
||||
- **Parse CSV:**
|
||||
```sh
|
||||
poetry run python3 -m pfbudget parse --bank your_bank export.csv
|
||||
```
|
||||
|
||||
- **Automatic categorization:**
|
||||
```sh
|
||||
poetry run python3 -m pfbudget categorize auto
|
||||
```
|
||||
|
||||
- **Interactive categorization:**
|
||||
```sh
|
||||
poetry run python3 -m pfbudget categorize manual
|
||||
```
|
||||
|
||||
## Available Commands
|
||||
|
||||
The CLI supports a variety of operations. Here are the main commands:
|
||||
|
||||
- **export**: Export transactions to a specified file and format.
|
||||
- **import**: Import transactions from a specified file and format.
|
||||
- **parse**: Parse transactions from CSV files (with optional bank and credit card arguments).
|
||||
- **categorize**
|
||||
- `auto`: Automatically categorize transactions using rules.
|
||||
- `manual`: Manually categorize uncategorized transactions.
|
||||
- **bank**
|
||||
- `add`, `del`, `mod`: Manage bank definitions.
|
||||
- `psd2`: Manage PSD2 bank connections.
|
||||
- `export`, `import`: Export/import bank definitions.
|
||||
- **token**: Manage PSD2 access tokens.
|
||||
- **eua**: Manage PSD2 requisition IDs.
|
||||
- **download**: Download transactions from banks via PSD2 API.
|
||||
- **banks**: List available banks in a country.
|
||||
- **category**
|
||||
- `add`, `remove`, `update`, `schedule`: Manage categories.
|
||||
- `rule`: Manage categorization rules (add, remove, modify, export, import).
|
||||
- `group`: Manage category groups (add, remove, export, import).
|
||||
- `export`, `import`: Export/import categories.
|
||||
- **tag**
|
||||
- `add`, `remove`: Manage tags.
|
||||
- `rule`: Manage tag rules (add, remove, modify, export, import).
|
||||
- **link**
|
||||
- `forge`, `dismantle`: Link or unlink transactions.
|
||||
|
||||
Each command may have additional options and subcommands. For details, run:
|
||||
|
||||
```sh
|
||||
poetry run python3 -m pfbudget --help
|
||||
```
|
||||
|
||||
or for a specific command:
|
||||
|
||||
```sh
|
||||
poetry run python3 -m pfbudget <command> --help
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**License:** GPL-3.0-or-later
|
||||
**Author:** Luís Murta <luis@murta.dev>
|
||||
|
||||
105
alembic.ini
Normal file
105
alembic.ini
Normal file
@ -0,0 +1,105 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = alembic
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python-dateutil library that can be
|
||||
# installed by adding `alembic[tz]` to the pip requirements
|
||||
# string value is passed to dateutil.tz.gettz()
|
||||
# leave blank for localtime
|
||||
timezone = UTC
|
||||
|
||||
# max length of characters to apply to the
|
||||
# "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to alembic/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
|
||||
|
||||
# version path separator; As mentioned above, this is the character used to split
|
||||
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||
# Valid values for version_path_separator are:
|
||||
#
|
||||
# version_path_separator = :
|
||||
# version_path_separator = ;
|
||||
# version_path_separator = space
|
||||
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
sqlalchemy.url = postgresql://pf-budget:muster-neutron-omega@database.home.arpa/pf-budget
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
hooks = black
|
||||
black.type = console_scripts
|
||||
black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
1
alembic/README
Normal file
1
alembic/README
Normal file
@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
88
alembic/env.py
Normal file
88
alembic/env.py
Normal file
@ -0,0 +1,88 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
from pfbudget.db.model import Base
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def include_name(name, type_, parent_names):
|
||||
if type_ == "schema":
|
||||
return name == "pfbudget"
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
include_name=include_name,
|
||||
include_schemas=True,
|
||||
compare_type=True,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
24
alembic/script.py.mako
Normal file
24
alembic/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
32
alembic/versions/0ce89e987770_regex_rule.py
Normal file
32
alembic/versions/0ce89e987770_regex_rule.py
Normal file
@ -0,0 +1,32 @@
|
||||
"""Regex rule
|
||||
|
||||
Revision ID: 0ce89e987770
|
||||
Revises: 7adf89ec8d14
|
||||
Create Date: 2022-12-10 14:00:49.418494+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0ce89e987770"
|
||||
down_revision = "7adf89ec8d14"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("regex", sa.String(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_column("categories_rules", "regex", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
@ -0,0 +1,40 @@
|
||||
"""Split member of base transaction
|
||||
|
||||
Revision ID: 18572111d9ff
|
||||
Revises: 28556ab17c56
|
||||
Create Date: 2023-01-23 20:09:37.892997+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "18572111d9ff"
|
||||
down_revision = "28556ab17c56"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column(
|
||||
"transactions",
|
||||
"split",
|
||||
existing_type=sa.BOOLEAN(),
|
||||
nullable=False,
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column(
|
||||
"transactions",
|
||||
"split",
|
||||
existing_type=sa.BOOLEAN(),
|
||||
nullable=True,
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
@ -0,0 +1,88 @@
|
||||
"""Selector back to transaction
|
||||
|
||||
Revision ID: 28556ab17c56
|
||||
Revises: e455c78df789
|
||||
Create Date: 2023-01-23 00:34:39.062562+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "28556ab17c56"
|
||||
down_revision = "e455c78df789"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.rename_table("tags", "tagged", schema="transactions")
|
||||
op.create_table(
|
||||
"selector",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column(
|
||||
"selector",
|
||||
sa.Enum(
|
||||
"unknown",
|
||||
"nullifier",
|
||||
"vacations",
|
||||
"rules",
|
||||
"algorithm",
|
||||
"manual",
|
||||
name="selector_t",
|
||||
schema="transactions",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.categorized.id"],
|
||||
name=op.f("fk_selector_id_categorized"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_selector")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_table("selector", schema="category")
|
||||
|
||||
op.rename_table("originals", "transactions", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.rename_table("transactions", "originals", schema="transactions")
|
||||
|
||||
op.create_table(
|
||||
"selector",
|
||||
sa.Column("id", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column(
|
||||
"selector",
|
||||
postgresql.ENUM(
|
||||
"unknown",
|
||||
"nullifier",
|
||||
"vacations",
|
||||
"rules",
|
||||
"algorithm",
|
||||
"manual",
|
||||
name="selector_t",
|
||||
schema="category",
|
||||
),
|
||||
autoincrement=False,
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.categorized.id"],
|
||||
name="fk_selector_id_categorized",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_selector"),
|
||||
schema="category",
|
||||
)
|
||||
op.drop_table("selector", schema="transactions")
|
||||
op.rename_table("tagged", "tags", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
109
alembic/versions/287fe9e6682a_add_relationships.py
Normal file
109
alembic/versions/287fe9e6682a_add_relationships.py
Normal file
@ -0,0 +1,109 @@
|
||||
"""Add relationships
|
||||
|
||||
Revision ID: 287fe9e6682a
|
||||
Revises: d3534f493239
|
||||
Create Date: 2022-12-03 16:43:39.633382+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "287fe9e6682a"
|
||||
down_revision = "d3534f493239"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint(
|
||||
"fk_categorized_id_originals",
|
||||
"categorized",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_categorized_id_originals"),
|
||||
"categorized",
|
||||
"originals",
|
||||
["id"],
|
||||
["id"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
op.drop_constraint(
|
||||
"fk_notes_id_originals", "notes", schema="transactions", type_="foreignkey"
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_notes_id_originals"),
|
||||
"notes",
|
||||
"originals",
|
||||
["id"],
|
||||
["id"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
op.drop_constraint(
|
||||
"fk_tags_id_originals", "tags", schema="transactions", type_="foreignkey"
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_tags_id_originals"),
|
||||
"tags",
|
||||
"originals",
|
||||
["id"],
|
||||
["id"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint(
|
||||
op.f("fk_tags_id_originals"), "tags", schema="transactions", type_="foreignkey"
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_tags_id_originals",
|
||||
"tags",
|
||||
"originals",
|
||||
["id"],
|
||||
["id"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
)
|
||||
op.drop_constraint(
|
||||
op.f("fk_notes_id_originals"),
|
||||
"notes",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_notes_id_originals",
|
||||
"notes",
|
||||
"originals",
|
||||
["id"],
|
||||
["id"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
)
|
||||
op.drop_constraint(
|
||||
op.f("fk_categorized_id_originals"),
|
||||
"categorized",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_categorized_id_originals",
|
||||
"categorized",
|
||||
"originals",
|
||||
["id"],
|
||||
["id"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
@ -0,0 +1,49 @@
|
||||
"""Available categories and rules
|
||||
|
||||
Revision ID: 2d0891f1be11
|
||||
Revises: 287fe9e6682a
|
||||
Create Date: 2022-12-04 11:15:22.758487+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "2d0891f1be11"
|
||||
down_revision = "287fe9e6682a"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"categories_available",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_categories_available")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"categories_rules",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column("rule", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["transactions.categories_available.name"],
|
||||
name=op.f("fk_categories_rules_name_categories_available"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", "rule", name=op.f("pk_categories_rules")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.alter_column("categorized", "category", new_column_name="name", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column("categorized", "name", new_column_name="category", schema="transactions")
|
||||
op.drop_table("categories_rules", schema="transactions")
|
||||
op.drop_table("categories_available", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
35
alembic/versions/325b901ac712_nordigen_tokens.py
Normal file
35
alembic/versions/325b901ac712_nordigen_tokens.py
Normal file
@ -0,0 +1,35 @@
|
||||
"""nordigen tokens
|
||||
|
||||
Revision ID: 325b901ac712
|
||||
Revises: 60469d5dd2b0
|
||||
Create Date: 2023-05-25 19:10:10.374008+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "325b901ac712"
|
||||
down_revision = "60469d5dd2b0"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"nordigen",
|
||||
sa.Column("type", sa.String(), nullable=False),
|
||||
sa.Column("token", sa.String(), nullable=False),
|
||||
sa.Column("expires", sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("type", name=op.f("pk_nordigen")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("nordigen", schema="pfbudget")
|
||||
# ### end Alembic commands ###
|
||||
74
alembic/versions/37d80de801a7_inheritance.py
Normal file
74
alembic/versions/37d80de801a7_inheritance.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""Inheritance
|
||||
|
||||
Revision ID: 37d80de801a7
|
||||
Revises: 8cc9870b0d74
|
||||
Create Date: 2023-01-10 22:41:03.540108+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "37d80de801a7"
|
||||
down_revision = "8cc9870b0d74"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column(
|
||||
"originals",
|
||||
sa.Column("type", sa.String(), nullable=False),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"originals",
|
||||
sa.Column("split", sa.Boolean(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"originals",
|
||||
sa.Column("original", sa.BigInteger(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.alter_column(
|
||||
"originals",
|
||||
"bank",
|
||||
existing_type=sa.TEXT(),
|
||||
nullable=True,
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_originals_original_originals"),
|
||||
"originals",
|
||||
"originals",
|
||||
["original"],
|
||||
["id"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint(
|
||||
op.f("fk_originals_original_originals"),
|
||||
"originals",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.alter_column(
|
||||
"originals",
|
||||
"bank",
|
||||
existing_type=sa.TEXT(),
|
||||
nullable=False,
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_column("originals", "original", schema="transactions")
|
||||
op.drop_column("originals", "split", schema="transactions")
|
||||
op.drop_column("originals", "type", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
111
alembic/versions/50ff1fbb8a00_init.py
Normal file
111
alembic/versions/50ff1fbb8a00_init.py
Normal file
@ -0,0 +1,111 @@
|
||||
"""Init
|
||||
|
||||
Revision ID: 50ff1fbb8a00
|
||||
Revises:
|
||||
Create Date: 2022-12-03 11:49:30.450115+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "50ff1fbb8a00"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"banks",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column("BIC", sa.String(length=8), nullable=False),
|
||||
sa.Column(
|
||||
"type",
|
||||
sa.Enum(
|
||||
"checking",
|
||||
"savings",
|
||||
"investment",
|
||||
"VISA",
|
||||
"MASTERCARD",
|
||||
name="accounttype",
|
||||
schema="transactions",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=False,
|
||||
),
|
||||
sa.PrimaryKeyConstraint("BIC", "type", name=op.f("pk_banks")),
|
||||
sa.UniqueConstraint("name", name=op.f("uq_banks_name")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"nordigen",
|
||||
sa.Column("name", sa.Text(), nullable=False),
|
||||
sa.Column("bank_id", sa.String(), nullable=True),
|
||||
sa.Column("requisition_id", sa.String(), nullable=True),
|
||||
sa.Column("invert", sa.Boolean(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"], ["transactions.banks.name"], name=op.f("fk_nordigen_name_banks")
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_nordigen")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"originals",
|
||||
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||
sa.Column("date", sa.Date(), nullable=False),
|
||||
sa.Column("description", sa.String(), nullable=True),
|
||||
sa.Column("bank", sa.Text(), nullable=False),
|
||||
sa.Column("amount", sa.Numeric(precision=16, scale=2), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["bank"], ["transactions.banks.name"], name=op.f("fk_originals_bank_banks")
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_originals")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"categorized",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("category", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.originals.id"],
|
||||
name=op.f("fk_categorized_id_originals"),
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_categorized")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"notes",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("note", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"], ["transactions.originals.id"], name=op.f("fk_notes_id_originals")
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_notes")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"tags",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("tag", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"], ["transactions.originals.id"], name=op.f("fk_tags_id_originals")
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", "tag", name=op.f("pk_tags")),
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("tags", schema="transactions")
|
||||
op.drop_table("notes", schema="transactions")
|
||||
op.drop_table("categorized", schema="transactions")
|
||||
op.drop_table("originals", schema="transactions")
|
||||
op.drop_table("nordigen", schema="transactions")
|
||||
op.drop_table("banks", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
48
alembic/versions/60469d5dd2b0_drop_sqlalchemy_enum.py
Normal file
48
alembic/versions/60469d5dd2b0_drop_sqlalchemy_enum.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""Drop SQLAlchemy enum
|
||||
|
||||
Revision ID: 60469d5dd2b0
|
||||
Revises: b599dafcf468
|
||||
Create Date: 2023-05-15 19:24:07.911352+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "60469d5dd2b0"
|
||||
down_revision = "b599dafcf468"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(
|
||||
"""
|
||||
CREATE TYPE pfbudget.scheduleperiod
|
||||
AS ENUM ('daily', 'weekly', 'monthly', 'yearly')
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""ALTER TABLE pfbudget.category_schedules
|
||||
ALTER COLUMN period TYPE pfbudget.scheduleperiod
|
||||
USING period::text::pfbudget.scheduleperiod
|
||||
"""
|
||||
)
|
||||
op.execute("DROP TYPE pfbudget.period")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(
|
||||
"""
|
||||
CREATE TYPE pfbudget.period
|
||||
AS ENUM ('daily', 'weekly', 'monthly', 'yearly')
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""ALTER TABLE pfbudget.category_schedules
|
||||
ALTER COLUMN period TYPE pfbudget.period
|
||||
USING period::text::pfbudget.period
|
||||
"""
|
||||
)
|
||||
op.execute("DROP TYPE pfbudget.scheduleperiod")
|
||||
54
alembic/versions/6863dda76ea2_category_selector.py
Normal file
54
alembic/versions/6863dda76ea2_category_selector.py
Normal file
@ -0,0 +1,54 @@
|
||||
"""Category selector
|
||||
|
||||
Revision ID: 6863dda76ea2
|
||||
Revises: 83f4c9837f6e
|
||||
Create Date: 2022-12-08 00:56:59.032641+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "6863dda76ea2"
|
||||
down_revision = "83f4c9837f6e"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"categories_selector",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column(
|
||||
"selector",
|
||||
sa.Enum(
|
||||
"unknown",
|
||||
"nullifier",
|
||||
"vacations",
|
||||
"rules",
|
||||
"algorithm",
|
||||
"manual",
|
||||
name="selector",
|
||||
schema="transactions",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.categorized.id"],
|
||||
name=op.f("fk_categories_selector_id_categorized"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_categories_selector")),
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("categories_selector", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
152
alembic/versions/6b293f78cc97_rule_inheritance.py
Normal file
152
alembic/versions/6b293f78cc97_rule_inheritance.py
Normal file
@ -0,0 +1,152 @@
|
||||
"""Rule inheritance
|
||||
|
||||
Revision ID: 6b293f78cc97
|
||||
Revises: 37d80de801a7
|
||||
Create Date: 2023-01-22 20:05:32.887092+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "6b293f78cc97"
|
||||
down_revision = "37d80de801a7"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"rules",
|
||||
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||
sa.Column("date", sa.Date(), nullable=True),
|
||||
sa.Column("description", sa.String(), nullable=True),
|
||||
sa.Column("regex", sa.String(), nullable=True),
|
||||
sa.Column("bank", sa.String(), nullable=True),
|
||||
sa.Column("min", sa.Numeric(precision=16, scale=2), nullable=True),
|
||||
sa.Column("max", sa.Numeric(precision=16, scale=2), nullable=True),
|
||||
sa.Column("type", sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_rules")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_categories_rules_id_rules"),
|
||||
"categories_rules",
|
||||
"rules",
|
||||
["id"],
|
||||
["id"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
op.drop_column("categories_rules", "bank", schema="transactions")
|
||||
op.drop_column("categories_rules", "min", schema="transactions")
|
||||
op.drop_column("categories_rules", "date", schema="transactions")
|
||||
op.drop_column("categories_rules", "regex", schema="transactions")
|
||||
op.drop_column("categories_rules", "description", schema="transactions")
|
||||
op.drop_column("categories_rules", "max", schema="transactions")
|
||||
op.create_foreign_key(
|
||||
op.f("fk_tag_rules_id_rules"),
|
||||
"tag_rules",
|
||||
"rules",
|
||||
["id"],
|
||||
["id"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
op.drop_column("tag_rules", "bank", schema="transactions")
|
||||
op.drop_column("tag_rules", "min", schema="transactions")
|
||||
op.drop_column("tag_rules", "date", schema="transactions")
|
||||
op.drop_column("tag_rules", "regex", schema="transactions")
|
||||
op.drop_column("tag_rules", "description", schema="transactions")
|
||||
op.drop_column("tag_rules", "max", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column(
|
||||
"tag_rules",
|
||||
sa.Column(
|
||||
"max", sa.NUMERIC(precision=16, scale=2), autoincrement=False, nullable=True
|
||||
),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"tag_rules",
|
||||
sa.Column("description", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"tag_rules",
|
||||
sa.Column("regex", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"tag_rules",
|
||||
sa.Column("date", sa.DATE(), autoincrement=False, nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"tag_rules",
|
||||
sa.Column(
|
||||
"min", sa.NUMERIC(precision=16, scale=2), autoincrement=False, nullable=True
|
||||
),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"tag_rules",
|
||||
sa.Column("bank", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_constraint(
|
||||
op.f("fk_tag_rules_id_rules"),
|
||||
"tag_rules",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column(
|
||||
"max", sa.NUMERIC(precision=16, scale=2), autoincrement=False, nullable=True
|
||||
),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("description", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("regex", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("date", sa.DATE(), autoincrement=False, nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column(
|
||||
"min", sa.NUMERIC(precision=16, scale=2), autoincrement=False, nullable=True
|
||||
),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("bank", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_constraint(
|
||||
op.f("fk_categories_rules_id_rules"),
|
||||
"categories_rules",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.drop_table("rules", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
49
alembic/versions/753c0bfb2062_rule_min_max.py
Normal file
49
alembic/versions/753c0bfb2062_rule_min_max.py
Normal file
@ -0,0 +1,49 @@
|
||||
"""Rule min/max
|
||||
|
||||
Revision ID: 753c0bfb2062
|
||||
Revises: e36e6321568e
|
||||
Create Date: 2022-12-18 00:24:03.861461+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "753c0bfb2062"
|
||||
down_revision = "e36e6321568e"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"min_amount",
|
||||
new_column_name="min",
|
||||
schema="transactions",
|
||||
)
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"max_amount",
|
||||
new_column_name="max",
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"min",
|
||||
new_column_name="min_amount",
|
||||
schema="transactions",
|
||||
)
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"max",
|
||||
new_column_name="max_amount",
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
43
alembic/versions/7adf89ec8d14_category_rule_date_format.py
Normal file
43
alembic/versions/7adf89ec8d14_category_rule_date_format.py
Normal file
@ -0,0 +1,43 @@
|
||||
"""Category rule date format
|
||||
|
||||
Revision ID: 7adf89ec8d14
|
||||
Revises: 83603bb7ef9c
|
||||
Create Date: 2022-12-10 00:08:47.535765+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "7adf89ec8d14"
|
||||
down_revision = "83603bb7ef9c"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"date",
|
||||
existing_type=sa.VARCHAR(),
|
||||
type_=sa.Date(),
|
||||
existing_nullable=True,
|
||||
schema="transactions",
|
||||
postgresql_using="date::date"
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"date",
|
||||
existing_type=sa.Date(),
|
||||
type_=sa.VARCHAR(),
|
||||
existing_nullable=True,
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
@ -0,0 +1,38 @@
|
||||
"""Amount of transaction per period
|
||||
|
||||
Revision ID: 83603bb7ef9c
|
||||
Revises: 8b5d5fbc8211
|
||||
Create Date: 2022-12-09 23:12:15.644758+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "83603bb7ef9c"
|
||||
down_revision = "8b5d5fbc8211"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column(
|
||||
"categories_schedules",
|
||||
sa.Column("amount", sa.Integer(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_column("categories_schedules", "recurring", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column(
|
||||
"categories_schedules",
|
||||
sa.Column("recurring", sa.BOOLEAN(), autoincrement=False, nullable=False),
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_column("categories_schedules", "amount", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
@ -0,0 +1,69 @@
|
||||
"""Category groups and relationships
|
||||
|
||||
Revision ID: 83f4c9837f6e
|
||||
Revises: 2d0891f1be11
|
||||
Create Date: 2022-12-04 15:10:51.924875+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "83f4c9837f6e"
|
||||
down_revision = "2d0891f1be11"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"categories_groups",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_categories_groups")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_available",
|
||||
sa.Column("group", sa.String(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_categories_available_group_categories_groups"),
|
||||
"categories_available",
|
||||
"categories_groups",
|
||||
["group"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_categorized_name_categories_available"),
|
||||
"categorized",
|
||||
"categories_available",
|
||||
["name"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint(
|
||||
op.f("fk_categorized_name_categories_available"),
|
||||
"categorized",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.drop_constraint(
|
||||
op.f("fk_categories_available_group_categories_groups"),
|
||||
"categories_available",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.drop_column("categories_available", "group", schema="transactions")
|
||||
op.drop_table("categories_groups", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
74
alembic/versions/8623e709e111_compact_category_selector.py
Normal file
74
alembic/versions/8623e709e111_compact_category_selector.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""Compact category selector
|
||||
|
||||
Revision ID: 8623e709e111
|
||||
Revises: ce68ee15e5d2
|
||||
Create Date: 2023-05-08 19:00:51.063240+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "8623e709e111"
|
||||
down_revision = "ce68ee15e5d2"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("category_selectors", schema="pfbudget")
|
||||
op.add_column(
|
||||
"transactions_categorized",
|
||||
sa.Column(
|
||||
"selector",
|
||||
sa.Enum(
|
||||
"unknown",
|
||||
"nullifier",
|
||||
"vacations",
|
||||
"rules",
|
||||
"algorithm",
|
||||
"manual",
|
||||
name="selector_t",
|
||||
schema="pfbudget",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=False,
|
||||
),
|
||||
schema="pfbudget",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_column("transactions_categorized", "selector", schema="pfbudget")
|
||||
op.create_table(
|
||||
"category_selectors",
|
||||
sa.Column("id", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column(
|
||||
"selector",
|
||||
postgresql.ENUM(
|
||||
"unknown",
|
||||
"nullifier",
|
||||
"vacations",
|
||||
"rules",
|
||||
"algorithm",
|
||||
"manual",
|
||||
name="selector_t",
|
||||
schema="pfbudget",
|
||||
),
|
||||
autoincrement=False,
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["pfbudget.transactions_categorized.id"],
|
||||
name="fk_category_selectors_id_transactions_categorized",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_category_selectors"),
|
||||
schema="pfbudget",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
92
alembic/versions/8b5d5fbc8211_transaction_based_rules.py
Normal file
92
alembic/versions/8b5d5fbc8211_transaction_based_rules.py
Normal file
@ -0,0 +1,92 @@
|
||||
"""Transaction based rules
|
||||
|
||||
Revision ID: 8b5d5fbc8211
|
||||
Revises: e77395969585
|
||||
Create Date: 2022-12-08 21:05:41.378466+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "8b5d5fbc8211"
|
||||
down_revision = "e77395969585"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.drop_constraint("pk_categories_rules", "categories_rules", schema="transactions")
|
||||
op.execute(sa.schema.CreateSequence(sa.schema.Sequence("categories_rules_id_seq", schema="transactions")))
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column(
|
||||
"id",
|
||||
sa.BigInteger(),
|
||||
autoincrement=True,
|
||||
nullable=False,
|
||||
server_default=sa.text(
|
||||
"nextval('transactions.categories_rules_id_seq'::regclass)"
|
||||
),
|
||||
),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("date", sa.String(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("description", sa.String(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("bank", sa.String(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("min_amount", sa.Float(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("max_amount", sa.Float(), nullable=True),
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_column("categories_rules", "rule", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
op.create_primary_key(
|
||||
"pk_categories_rules",
|
||||
"categories_rules",
|
||||
["id"],
|
||||
schema="transactions",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_constraint("pk_categories_rules", "categories_rules", schema="transactions")
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column(
|
||||
"categories_rules",
|
||||
sa.Column("rule", sa.String(), autoincrement=False, nullable=False),
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_column("categories_rules", "max_amount", schema="transactions")
|
||||
op.drop_column("categories_rules", "min_amount", schema="transactions")
|
||||
op.drop_column("categories_rules", "bank", schema="transactions")
|
||||
op.drop_column("categories_rules", "description", schema="transactions")
|
||||
op.drop_column("categories_rules", "date", schema="transactions")
|
||||
op.drop_column("categories_rules", "id", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
op.execute(sa.schema.DropSequence(sa.schema.Sequence("categories_rules_id_seq", schema="transactions")))
|
||||
op.create_primary_key(
|
||||
"pk_categories_rules",
|
||||
"categories_rules",
|
||||
["name", "rule"],
|
||||
schema="transactions",
|
||||
)
|
||||
46
alembic/versions/8cc9870b0d74_links.py
Normal file
46
alembic/versions/8cc9870b0d74_links.py
Normal file
@ -0,0 +1,46 @@
|
||||
"""Links
|
||||
|
||||
Revision ID: 8cc9870b0d74
|
||||
Revises: a910e1b2214d
|
||||
Create Date: 2022-12-19 22:10:25.136479+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "8cc9870b0d74"
|
||||
down_revision = "a910e1b2214d"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"links",
|
||||
sa.Column("original", sa.BigInteger(), nullable=False),
|
||||
sa.Column("link", sa.BigInteger(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["link"],
|
||||
["transactions.originals.id"],
|
||||
name=op.f("fk_links_link_originals"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["original"],
|
||||
["transactions.originals.id"],
|
||||
name=op.f("fk_links_original_originals"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("original", "link", name=op.f("pk_links")),
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("links", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
68
alembic/versions/9028b0f3b985_tag_rules.py
Normal file
68
alembic/versions/9028b0f3b985_tag_rules.py
Normal file
@ -0,0 +1,68 @@
|
||||
"""Tag rules
|
||||
|
||||
Revision ID: 9028b0f3b985
|
||||
Revises: 753c0bfb2062
|
||||
Create Date: 2022-12-18 22:53:13.334046+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "9028b0f3b985"
|
||||
down_revision = "753c0bfb2062"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"tags_available",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_tags_available")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"tag_rules",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("tag", sa.String(), nullable=False),
|
||||
sa.Column("date", sa.Date(), nullable=True),
|
||||
sa.Column("description", sa.String(), nullable=True),
|
||||
sa.Column("regex", sa.String(), nullable=True),
|
||||
sa.Column("bank", sa.String(), nullable=True),
|
||||
sa.Column("min", sa.Numeric(precision=16, scale=2), nullable=True),
|
||||
sa.Column("max", sa.Numeric(precision=16, scale=2), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tag"],
|
||||
["transactions.tags_available.name"],
|
||||
name=op.f("fk_tag_rules_tag_tags_available"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_tag_rules")),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_tags_tag_tags_available"),
|
||||
"tags",
|
||||
"tags_available",
|
||||
["tag"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint(
|
||||
op.f("fk_tags_tag_tags_available"),
|
||||
"tags",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.drop_table("tag_rules", schema="transactions")
|
||||
op.drop_table("tags_available", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
32
alembic/versions/952de57a3c43_start_end_date_rule.py
Normal file
32
alembic/versions/952de57a3c43_start_end_date_rule.py
Normal file
@ -0,0 +1,32 @@
|
||||
"""Start/End date rule
|
||||
|
||||
Revision ID: 952de57a3c43
|
||||
Revises: 18572111d9ff
|
||||
Create Date: 2023-02-06 21:57:57.545327+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "952de57a3c43"
|
||||
down_revision = "18572111d9ff"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column(
|
||||
"rules", sa.Column("start", sa.Date(), nullable=True), schema="transactions"
|
||||
)
|
||||
op.alter_column("rules", column_name="date", new_column_name="end", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column("rules", column_name="end", new_column_name="date", schema="transactions")
|
||||
op.drop_column("rules", "start", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
56
alembic/versions/a910e1b2214d_rule_inheritance.py
Normal file
56
alembic/versions/a910e1b2214d_rule_inheritance.py
Normal file
@ -0,0 +1,56 @@
|
||||
"""Rule inheritance
|
||||
|
||||
Revision ID: a910e1b2214d
|
||||
Revises: 9028b0f3b985
|
||||
Create Date: 2022-12-19 20:48:04.682812+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "a910e1b2214d"
|
||||
down_revision = "9028b0f3b985"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint(
|
||||
"fk_categorized_name_categories_available",
|
||||
"categorized",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_categorized_name_categories_available"),
|
||||
"categorized",
|
||||
"categories_available",
|
||||
["name"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint(
|
||||
op.f("fk_categorized_name_categories_available"),
|
||||
"categorized",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_categorized_name_categories_available",
|
||||
"categorized",
|
||||
"categories_available",
|
||||
["name"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
46
alembic/versions/b599dafcf468_selector_type_name_change.py
Normal file
46
alembic/versions/b599dafcf468_selector_type_name_change.py
Normal file
@ -0,0 +1,46 @@
|
||||
"""Selector type name change
|
||||
|
||||
Revision ID: b599dafcf468
|
||||
Revises: 8623e709e111
|
||||
Create Date: 2023-05-08 19:46:20.661214+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "b599dafcf468"
|
||||
down_revision = "8623e709e111"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(
|
||||
"""
|
||||
CREATE TYPE pfbudget.categoryselector
|
||||
AS ENUM ('unknown', 'nullifier', 'vacations', 'rules', 'algorithm', 'manual')
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""ALTER TABLE pfbudget.transactions_categorized
|
||||
ALTER COLUMN selector TYPE pfbudget.categoryselector
|
||||
USING selector::text::pfbudget.categoryselector
|
||||
"""
|
||||
)
|
||||
op.execute("DROP TYPE pfbudget.selector_t")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(
|
||||
"""
|
||||
CREATE TYPE pfbudget.selector_t
|
||||
AS ENUM ('unknown', 'nullifier', 'vacations', 'rules', 'algorithm', 'manual')
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""ALTER TABLE pfbudget.transactions_categorized
|
||||
ALTER COLUMN selector TYPE pfbudget.selector_t
|
||||
USING selector::text::pfbudget.selector_t
|
||||
"""
|
||||
)
|
||||
op.execute("DROP TYPE pfbudget.categoryselector")
|
||||
95
alembic/versions/ce68ee15e5d2_change_bank_constraints.py
Normal file
95
alembic/versions/ce68ee15e5d2_change_bank_constraints.py
Normal file
@ -0,0 +1,95 @@
|
||||
"""Change bank constraints
|
||||
|
||||
Revision ID: ce68ee15e5d2
|
||||
Revises: d7f0401c1fd3
|
||||
Create Date: 2023-04-29 15:53:24.753628+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "ce68ee15e5d2"
|
||||
down_revision = "d7f0401c1fd3"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.drop_constraint(
|
||||
"fk_transactions_bank_banks",
|
||||
"transactions",
|
||||
type_="foreignkey",
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.drop_constraint(
|
||||
"fk_banks_nordigen_name_banks",
|
||||
"banks_nordigen",
|
||||
type_="foreignkey",
|
||||
schema="pfbudget",
|
||||
)
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint("uq_banks_name", "banks", schema="pfbudget", type_="unique")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
op.execute("ALTER TABLE pfbudget.banks DROP CONSTRAINT pk_banks")
|
||||
op.create_primary_key("pk_banks", "banks", ["name"], schema="pfbudget")
|
||||
op.create_foreign_key(
|
||||
"fk_transactions_bank_banks",
|
||||
"transactions",
|
||||
"banks",
|
||||
["bank"],
|
||||
["name"],
|
||||
source_schema="pfbudget",
|
||||
referent_schema="pfbudget",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_banks_nordigen_name_banks",
|
||||
"banks_nordigen",
|
||||
"banks",
|
||||
["name"],
|
||||
["name"],
|
||||
source_schema="pfbudget",
|
||||
referent_schema="pfbudget",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_constraint(
|
||||
"fk_transactions_bank_banks",
|
||||
"transactions",
|
||||
type_="foreignkey",
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.drop_constraint(
|
||||
"fk_banks_nordigen_name_banks",
|
||||
"banks_nordigen",
|
||||
type_="foreignkey",
|
||||
schema="pfbudget",
|
||||
)
|
||||
|
||||
op.execute("ALTER TABLE pfbudget.banks DROP CONSTRAINT pk_banks")
|
||||
op.create_primary_key("pk_banks", "banks", ["BIC", "type"], schema="pfbudget")
|
||||
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_unique_constraint("uq_banks_name", "banks", ["name"], schema="pfbudget")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
op.create_foreign_key(
|
||||
"fk_transactions_bank_banks",
|
||||
"transactions",
|
||||
"banks",
|
||||
["bank"],
|
||||
["name"],
|
||||
source_schema="pfbudget",
|
||||
referent_schema="pfbudget",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_banks_nordigen_name_banks",
|
||||
"banks_nordigen",
|
||||
"banks",
|
||||
["name"],
|
||||
["name"],
|
||||
source_schema="pfbudget",
|
||||
referent_schema="pfbudget",
|
||||
)
|
||||
53
alembic/versions/d18cbd50f7c6_category_schedule.py
Normal file
53
alembic/versions/d18cbd50f7c6_category_schedule.py
Normal file
@ -0,0 +1,53 @@
|
||||
"""Category schedule
|
||||
|
||||
Revision ID: d18cbd50f7c6
|
||||
Revises: 6863dda76ea2
|
||||
Create Date: 2022-12-08 13:30:29.048811+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "d18cbd50f7c6"
|
||||
down_revision = "6863dda76ea2"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"categories_schedules",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column("recurring", sa.Boolean(), nullable=False),
|
||||
sa.Column(
|
||||
"period",
|
||||
sa.Enum(
|
||||
"daily",
|
||||
"monthly",
|
||||
"yearly",
|
||||
name="period",
|
||||
schema="transactions",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("period_multiplier", sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["transactions.categories_available.name"],
|
||||
name=op.f("fk_categories_schedules_name_categories_available"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_categories_schedules")),
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("categories_schedules", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
36
alembic/versions/d3534f493239_add_meal_card.py
Normal file
36
alembic/versions/d3534f493239_add_meal_card.py
Normal file
@ -0,0 +1,36 @@
|
||||
"""Add meal card
|
||||
|
||||
Revision ID: d3534f493239
|
||||
Revises: 50ff1fbb8a00
|
||||
Create Date: 2022-12-03 12:18:33.519666+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "d3534f493239"
|
||||
down_revision = "50ff1fbb8a00"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute("ALTER TYPE transactions.accounttype ADD VALUE 'mealcard' BEFORE 'VISA'")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(
|
||||
"""CREATE TYPE transactions.accounttype_new
|
||||
AS ENUM ('checking', 'savings', 'investment', 'VISA', 'MASTERCARD')
|
||||
"""
|
||||
)
|
||||
op.execute("UPDATE transactions.banks SET type = DEFAULT WHERE type = 'mealcard'")
|
||||
op.execute(
|
||||
"""ALTER TABLE transactions.banks
|
||||
ALTER COLUMN type TYPE transactions.accounttype_new
|
||||
USING type::text::transactions.accounttype_new
|
||||
"""
|
||||
)
|
||||
op.execute("DROP TYPE transactions.accounttype")
|
||||
op.execute("ALTER TYPE transactions.accounttype_new RENAME TO accounttype")
|
||||
594
alembic/versions/d7f0401c1fd3_unified_schemas.py
Normal file
594
alembic/versions/d7f0401c1fd3_unified_schemas.py
Normal file
@ -0,0 +1,594 @@
|
||||
"""unified schemas
|
||||
|
||||
|
||||
Revision ID: d7f0401c1fd3
|
||||
Revises: 952de57a3c43
|
||||
Create Date: 2023-04-27 16:30:08.514985+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "d7f0401c1fd3"
|
||||
down_revision = "952de57a3c43"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"banks",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column("BIC", sa.String(length=8), nullable=False),
|
||||
sa.Column(
|
||||
"type",
|
||||
sa.Enum(
|
||||
"checking",
|
||||
"savings",
|
||||
"investment",
|
||||
"mealcard",
|
||||
"VISA",
|
||||
"MASTERCARD",
|
||||
name="accounttype",
|
||||
schema="pfbudget",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=False,
|
||||
),
|
||||
sa.PrimaryKeyConstraint("BIC", "type", name=op.f("pk_banks")),
|
||||
sa.UniqueConstraint("name", name=op.f("uq_banks_name")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"category_groups",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_category_groups")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"rules",
|
||||
sa.Column(
|
||||
"id", sa.BigInteger().with_variant(sa.Integer(), "sqlite"), nullable=False
|
||||
),
|
||||
sa.Column("start", sa.Date(), nullable=True),
|
||||
sa.Column("end", sa.Date(), nullable=True),
|
||||
sa.Column("description", sa.String(), nullable=True),
|
||||
sa.Column("regex", sa.String(), nullable=True),
|
||||
sa.Column("bank", sa.String(), nullable=True),
|
||||
sa.Column("min", sa.Numeric(precision=16, scale=2), nullable=True),
|
||||
sa.Column("max", sa.Numeric(precision=16, scale=2), nullable=True),
|
||||
sa.Column("type", sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_rules")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"tags",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_tags")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"banks_nordigen",
|
||||
sa.Column("name", sa.Text(), nullable=False),
|
||||
sa.Column("bank_id", sa.String(), nullable=True),
|
||||
sa.Column("requisition_id", sa.String(), nullable=True),
|
||||
sa.Column("invert", sa.Boolean(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"], ["pfbudget.banks.name"], name=op.f("fk_banks_nordigen_name_banks")
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_banks_nordigen")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"categories",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column("group", sa.String(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["group"],
|
||||
["pfbudget.category_groups.name"],
|
||||
name=op.f("fk_categories_group_category_groups"),
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_categories")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"tag_rules",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("tag", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["pfbudget.rules.id"],
|
||||
name=op.f("fk_tag_rules_id_rules"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tag"],
|
||||
["pfbudget.tags.name"],
|
||||
name=op.f("fk_tag_rules_tag_tags"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_tag_rules")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"transactions",
|
||||
sa.Column(
|
||||
"id", sa.BigInteger().with_variant(sa.Integer(), "sqlite"), nullable=False
|
||||
),
|
||||
sa.Column("date", sa.Date(), nullable=False),
|
||||
sa.Column("description", sa.String(), nullable=True),
|
||||
sa.Column("amount", sa.Numeric(precision=16, scale=2), nullable=False),
|
||||
sa.Column("split", sa.Boolean(), nullable=False),
|
||||
sa.Column("type", sa.String(), nullable=False),
|
||||
sa.Column("bank", sa.Text(), nullable=True),
|
||||
sa.Column("original", sa.BigInteger(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["bank"], ["pfbudget.banks.name"], name=op.f("fk_transactions_bank_banks")
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["original"],
|
||||
["pfbudget.transactions.id"],
|
||||
name=op.f("fk_transactions_original_transactions"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_transactions")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"category_rules",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["pfbudget.rules.id"],
|
||||
name=op.f("fk_category_rules_id_rules"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["pfbudget.categories.name"],
|
||||
name=op.f("fk_category_rules_name_categories"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_category_rules")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"category_schedules",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column(
|
||||
"period",
|
||||
sa.Enum(
|
||||
"daily",
|
||||
"weekly",
|
||||
"monthly",
|
||||
"yearly",
|
||||
name="period",
|
||||
schema="pfbudget",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("period_multiplier", sa.Integer(), nullable=True),
|
||||
sa.Column("amount", sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["pfbudget.categories.name"],
|
||||
name=op.f("fk_category_schedules_name_categories"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_category_schedules")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"links",
|
||||
sa.Column("original", sa.BigInteger(), nullable=False),
|
||||
sa.Column("link", sa.BigInteger(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["link"],
|
||||
["pfbudget.transactions.id"],
|
||||
name=op.f("fk_links_link_transactions"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["original"],
|
||||
["pfbudget.transactions.id"],
|
||||
name=op.f("fk_links_original_transactions"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("original", "link", name=op.f("pk_links")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"notes",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("note", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["pfbudget.transactions.id"],
|
||||
name=op.f("fk_notes_id_transactions"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_notes")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"transactions_categorized",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["pfbudget.transactions.id"],
|
||||
name=op.f("fk_transactions_categorized_id_transactions"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["pfbudget.categories.name"],
|
||||
name=op.f("fk_transactions_categorized_name_categories"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_transactions_categorized")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"transactions_tagged",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("tag", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["pfbudget.transactions.id"],
|
||||
name=op.f("fk_transactions_tagged_id_transactions"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tag"],
|
||||
["pfbudget.tags.name"],
|
||||
name=op.f("fk_transactions_tagged_tag_tags"),
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", "tag", name=op.f("pk_transactions_tagged")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.create_table(
|
||||
"category_selectors",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column(
|
||||
"selector",
|
||||
sa.Enum(
|
||||
"unknown",
|
||||
"nullifier",
|
||||
"vacations",
|
||||
"rules",
|
||||
"algorithm",
|
||||
"manual",
|
||||
name="selector_t",
|
||||
schema="pfbudget",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["pfbudget.transactions_categorized.id"],
|
||||
name=op.f("fk_category_selectors_id_transactions_categorized"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_category_selectors")),
|
||||
schema="pfbudget",
|
||||
)
|
||||
op.drop_table("notes", schema="transactions")
|
||||
op.drop_table("rules", schema="tag")
|
||||
op.drop_table("tagged", schema="transactions")
|
||||
op.drop_table("available", schema="tag")
|
||||
op.drop_table("nordigen", schema="bank")
|
||||
op.drop_table("links", schema="transactions")
|
||||
op.drop_table("selector", schema="transactions")
|
||||
op.drop_table("categorized", schema="transactions")
|
||||
op.drop_table("transactions", schema="transactions")
|
||||
op.drop_table("banks", schema="bank")
|
||||
op.drop_table("rules", schema="category")
|
||||
op.drop_table("schedules", schema="category")
|
||||
op.drop_table("rules", schema="transactions")
|
||||
op.drop_table("available", schema="category")
|
||||
op.drop_table("groups", schema="category")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"transactions",
|
||||
sa.Column(
|
||||
"id",
|
||||
sa.BIGINT(),
|
||||
server_default=sa.text(
|
||||
"nextval('transactions.originals_id_seq'::regclass)"
|
||||
),
|
||||
autoincrement=True,
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("date", sa.DATE(), autoincrement=False, nullable=False),
|
||||
sa.Column("description", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.Column("bank", sa.TEXT(), autoincrement=False, nullable=True),
|
||||
sa.Column(
|
||||
"amount",
|
||||
sa.NUMERIC(precision=16, scale=2),
|
||||
autoincrement=False,
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("type", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.Column("split", sa.BOOLEAN(), autoincrement=False, nullable=False),
|
||||
sa.Column("original", sa.BIGINT(), autoincrement=False, nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["bank"], ["bank.banks.name"], name="fk_originals_bank_banks"
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["original"],
|
||||
["transactions.transactions.id"],
|
||||
name="fk_originals_original_originals",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_originals"),
|
||||
schema="transactions",
|
||||
postgresql_ignore_search_path=False,
|
||||
)
|
||||
op.create_table(
|
||||
"nordigen",
|
||||
sa.Column("name", sa.TEXT(), autoincrement=False, nullable=False),
|
||||
sa.Column("bank_id", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.Column("requisition_id", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.Column("invert", sa.BOOLEAN(), autoincrement=False, nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"], ["bank.banks.name"], name="fk_nordigen_name_banks"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_nordigen"),
|
||||
schema="bank",
|
||||
)
|
||||
op.create_table(
|
||||
"tagged",
|
||||
sa.Column("id", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column("tag", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.transactions.id"],
|
||||
name="fk_tags_id_originals",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tag"], ["tag.available.name"], name="fk_tags_tag_available"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", "tag", name="pk_tags"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"available",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.Column("group", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["group"], ["category.groups.name"], name="fk_available_group_groups"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_available"),
|
||||
schema="category",
|
||||
postgresql_ignore_search_path=False,
|
||||
)
|
||||
op.create_table(
|
||||
"rules",
|
||||
sa.Column(
|
||||
"id",
|
||||
sa.BIGINT(),
|
||||
server_default=sa.text("nextval('transactions.rules_id_seq'::regclass)"),
|
||||
autoincrement=True,
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("end", sa.DATE(), autoincrement=False, nullable=True),
|
||||
sa.Column("description", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.Column("regex", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.Column("bank", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.Column(
|
||||
"min", sa.NUMERIC(precision=16, scale=2), autoincrement=False, nullable=True
|
||||
),
|
||||
sa.Column(
|
||||
"max", sa.NUMERIC(precision=16, scale=2), autoincrement=False, nullable=True
|
||||
),
|
||||
sa.Column("type", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.Column("start", sa.DATE(), autoincrement=False, nullable=True),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_rules"),
|
||||
schema="transactions",
|
||||
postgresql_ignore_search_path=False,
|
||||
)
|
||||
op.create_table(
|
||||
"groups",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_groups"),
|
||||
schema="category",
|
||||
postgresql_ignore_search_path=False,
|
||||
)
|
||||
op.create_table(
|
||||
"rules",
|
||||
sa.Column("id", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column("tag", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.rules.id"],
|
||||
name="fk_rules_id_rules",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tag"],
|
||||
["tag.available.name"],
|
||||
name="fk_rules_tag_available",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_rules"),
|
||||
schema="tag",
|
||||
)
|
||||
op.create_table(
|
||||
"schedules",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.Column(
|
||||
"period",
|
||||
postgresql.ENUM(
|
||||
"daily", "weekly", "monthly", "yearly", name="period", schema="category"
|
||||
),
|
||||
autoincrement=False,
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column(
|
||||
"period_multiplier", sa.INTEGER(), autoincrement=False, nullable=True
|
||||
),
|
||||
sa.Column("amount", sa.INTEGER(), autoincrement=False, nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["category.available.name"],
|
||||
name="fk_schedules_name_available",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_schedules"),
|
||||
schema="category",
|
||||
)
|
||||
op.create_table(
|
||||
"rules",
|
||||
sa.Column("id", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.rules.id"],
|
||||
name="fk_rules_id_rules",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["category.available.name"],
|
||||
name="fk_rules_name_available",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_rules"),
|
||||
schema="category",
|
||||
)
|
||||
op.create_table(
|
||||
"links",
|
||||
sa.Column("original", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column("link", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["link"],
|
||||
["transactions.transactions.id"],
|
||||
name="fk_links_link_originals",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["original"],
|
||||
["transactions.transactions.id"],
|
||||
name="fk_links_original_originals",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("original", "link", name="pk_links"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"selector",
|
||||
sa.Column("id", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column(
|
||||
"selector",
|
||||
postgresql.ENUM(
|
||||
"unknown",
|
||||
"nullifier",
|
||||
"vacations",
|
||||
"rules",
|
||||
"algorithm",
|
||||
"manual",
|
||||
name="selector_t",
|
||||
schema="transactions",
|
||||
),
|
||||
autoincrement=False,
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.categorized.id"],
|
||||
name="fk_selector_id_categorized",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_selector"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"banks",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.Column("BIC", sa.VARCHAR(length=8), autoincrement=False, nullable=False),
|
||||
sa.Column(
|
||||
"type",
|
||||
postgresql.ENUM(
|
||||
"checking",
|
||||
"savings",
|
||||
"investment",
|
||||
"mealcard",
|
||||
"VISA",
|
||||
"MASTERCARD",
|
||||
name="accounttype",
|
||||
schema="bank",
|
||||
),
|
||||
autoincrement=False,
|
||||
nullable=False,
|
||||
),
|
||||
sa.PrimaryKeyConstraint("BIC", "type", name="pk_banks"),
|
||||
sa.UniqueConstraint("name", name="uq_banks_name"),
|
||||
schema="bank",
|
||||
postgresql_ignore_search_path=False,
|
||||
)
|
||||
op.create_table(
|
||||
"available",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_available"),
|
||||
schema="tag",
|
||||
)
|
||||
op.create_table(
|
||||
"notes",
|
||||
sa.Column("id", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column("note", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.transactions.id"],
|
||||
name="fk_notes_id_originals",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_notes"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"categorized",
|
||||
sa.Column("id", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.transactions.id"],
|
||||
name="fk_categorized_id_originals",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["category.available.name"],
|
||||
name="fk_categorized_name_available",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_categorized"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_table("category_selectors", schema="pfbudget")
|
||||
op.drop_table("transactions_tagged", schema="pfbudget")
|
||||
op.drop_table("transactions_categorized", schema="pfbudget")
|
||||
op.drop_table("notes", schema="pfbudget")
|
||||
op.drop_table("links", schema="pfbudget")
|
||||
op.drop_table("category_schedules", schema="pfbudget")
|
||||
op.drop_table("category_rules", schema="pfbudget")
|
||||
op.drop_table("transactions", schema="pfbudget")
|
||||
op.drop_table("tag_rules", schema="pfbudget")
|
||||
op.drop_table("categories", schema="pfbudget")
|
||||
op.drop_table("banks_nordigen", schema="pfbudget")
|
||||
op.drop_table("tags", schema="pfbudget")
|
||||
op.drop_table("rules", schema="pfbudget")
|
||||
op.drop_table("category_groups", schema="pfbudget")
|
||||
op.drop_table("banks", schema="pfbudget")
|
||||
# ### end Alembic commands ###
|
||||
58
alembic/versions/e36e6321568e_rules_min_max_money.py
Normal file
58
alembic/versions/e36e6321568e_rules_min_max_money.py
Normal file
@ -0,0 +1,58 @@
|
||||
"""Rules min/max money
|
||||
|
||||
Revision ID: e36e6321568e
|
||||
Revises: 0ce89e987770
|
||||
Create Date: 2022-12-10 18:55:07.149010+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "e36e6321568e"
|
||||
down_revision = "0ce89e987770"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"min_amount",
|
||||
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
||||
type_=sa.Numeric(precision=16, scale=2),
|
||||
existing_nullable=True,
|
||||
schema="transactions",
|
||||
)
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"max_amount",
|
||||
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
||||
type_=sa.Numeric(precision=16, scale=2),
|
||||
existing_nullable=True,
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"max_amount",
|
||||
existing_type=sa.Numeric(precision=16, scale=2),
|
||||
type_=sa.DOUBLE_PRECISION(precision=53),
|
||||
existing_nullable=True,
|
||||
schema="transactions",
|
||||
)
|
||||
op.alter_column(
|
||||
"categories_rules",
|
||||
"min_amount",
|
||||
existing_type=sa.Numeric(precision=16, scale=2),
|
||||
type_=sa.DOUBLE_PRECISION(precision=53),
|
||||
existing_nullable=True,
|
||||
schema="transactions",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
452
alembic/versions/e455c78df789_divide_by_schemas.py
Normal file
452
alembic/versions/e455c78df789_divide_by_schemas.py
Normal file
@ -0,0 +1,452 @@
|
||||
"""Divide by schemas
|
||||
|
||||
Revision ID: e455c78df789
|
||||
Revises: 6b293f78cc97
|
||||
Create Date: 2023-01-22 23:38:23.266906+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "e455c78df789"
|
||||
down_revision = "6b293f78cc97"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"banks",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column("BIC", sa.String(length=8), nullable=False),
|
||||
sa.Column(
|
||||
"type",
|
||||
sa.Enum(
|
||||
"checking",
|
||||
"savings",
|
||||
"investment",
|
||||
"mealcard",
|
||||
"VISA",
|
||||
"MASTERCARD",
|
||||
name="accounttype",
|
||||
schema="bank",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=False,
|
||||
),
|
||||
sa.PrimaryKeyConstraint("BIC", "type", name=op.f("pk_banks")),
|
||||
sa.UniqueConstraint("name", name=op.f("uq_banks_name")),
|
||||
schema="bank",
|
||||
)
|
||||
op.create_table(
|
||||
"groups",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_groups")),
|
||||
schema="category",
|
||||
)
|
||||
op.create_table(
|
||||
"available",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_available")),
|
||||
schema="tag",
|
||||
)
|
||||
op.create_table(
|
||||
"nordigen",
|
||||
sa.Column("name", sa.Text(), nullable=False),
|
||||
sa.Column("bank_id", sa.String(), nullable=True),
|
||||
sa.Column("requisition_id", sa.String(), nullable=True),
|
||||
sa.Column("invert", sa.Boolean(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"], ["bank.banks.name"], name=op.f("fk_nordigen_name_banks")
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_nordigen")),
|
||||
schema="bank",
|
||||
)
|
||||
op.create_table(
|
||||
"available",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column("group", sa.String(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["group"], ["category.groups.name"], name=op.f("fk_available_group_groups")
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_available")),
|
||||
schema="category",
|
||||
)
|
||||
op.create_table(
|
||||
"rules",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("tag", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.rules.id"],
|
||||
name=op.f("fk_rules_id_rules"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tag"],
|
||||
["tag.available.name"],
|
||||
name=op.f("fk_rules_tag_available"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_rules")),
|
||||
schema="tag",
|
||||
)
|
||||
op.create_table(
|
||||
"rules",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.rules.id"],
|
||||
name=op.f("fk_rules_id_rules"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["category.available.name"],
|
||||
name=op.f("fk_rules_name_available"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_rules")),
|
||||
schema="category",
|
||||
)
|
||||
op.create_table(
|
||||
"schedules",
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column(
|
||||
"period",
|
||||
sa.Enum(
|
||||
"daily",
|
||||
"weekly",
|
||||
"monthly",
|
||||
"yearly",
|
||||
name="period",
|
||||
schema="category",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("period_multiplier", sa.Integer(), nullable=True),
|
||||
sa.Column("amount", sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["category.available.name"],
|
||||
name=op.f("fk_schedules_name_available"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_schedules")),
|
||||
schema="category",
|
||||
)
|
||||
op.create_table(
|
||||
"selector",
|
||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
||||
sa.Column(
|
||||
"selector",
|
||||
sa.Enum(
|
||||
"unknown",
|
||||
"nullifier",
|
||||
"vacations",
|
||||
"rules",
|
||||
"algorithm",
|
||||
"manual",
|
||||
name="selector_t",
|
||||
schema="category",
|
||||
inherit_schema=True,
|
||||
),
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.categorized.id"],
|
||||
name=op.f("fk_selector_id_categorized"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_selector")),
|
||||
schema="category",
|
||||
)
|
||||
op.drop_constraint(
|
||||
"fk_categorized_name_categories_available",
|
||||
"categorized",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_categorized_name_available"),
|
||||
"categorized",
|
||||
"available",
|
||||
["name"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="category",
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
op.drop_constraint(
|
||||
"fk_originals_bank_banks",
|
||||
"originals",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_originals_bank_banks"),
|
||||
"originals",
|
||||
"banks",
|
||||
["bank"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="bank",
|
||||
)
|
||||
op.drop_constraint(
|
||||
"fk_tags_tag_tags_available", "tags", schema="transactions", type_="foreignkey"
|
||||
)
|
||||
op.create_foreign_key(
|
||||
op.f("fk_tags_tag_available"),
|
||||
"tags",
|
||||
"available",
|
||||
["tag"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="tag",
|
||||
)
|
||||
op.drop_table("categories_schedules", schema="transactions")
|
||||
op.drop_table("categories_rules", schema="transactions")
|
||||
op.drop_table("categories_available", schema="transactions")
|
||||
op.drop_table("tag_rules", schema="transactions")
|
||||
op.drop_table("nordigen", schema="transactions")
|
||||
op.drop_table("tags_available", schema="transactions")
|
||||
op.drop_table("banks", schema="transactions")
|
||||
op.drop_table("categories_selector", schema="transactions")
|
||||
op.drop_table("categories_groups", schema="transactions")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint(
|
||||
op.f("fk_tags_tag_available"), "tags", schema="transactions", type_="foreignkey"
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_tags_tag_tags_available",
|
||||
"tags",
|
||||
"tags_available",
|
||||
["tag"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
)
|
||||
op.drop_constraint(
|
||||
op.f("fk_originals_bank_banks"),
|
||||
"originals",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_originals_bank_banks",
|
||||
"originals",
|
||||
"banks",
|
||||
["bank"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
)
|
||||
op.drop_constraint(
|
||||
op.f("fk_categorized_name_available"),
|
||||
"categorized",
|
||||
schema="transactions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_categorized_name_categories_available",
|
||||
"categorized",
|
||||
"categories_available",
|
||||
["name"],
|
||||
["name"],
|
||||
source_schema="transactions",
|
||||
referent_schema="transactions",
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
op.create_table(
|
||||
"categories_groups",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_categories_groups"),
|
||||
schema="transactions",
|
||||
postgresql_ignore_search_path=False,
|
||||
)
|
||||
op.create_table(
|
||||
"categories_selector",
|
||||
sa.Column("id", sa.BIGINT(), autoincrement=False, nullable=False),
|
||||
sa.Column(
|
||||
"selector",
|
||||
postgresql.ENUM(
|
||||
"unknown",
|
||||
"nullifier",
|
||||
"vacations",
|
||||
"rules",
|
||||
"algorithm",
|
||||
"manual",
|
||||
name="selector",
|
||||
schema="transactions",
|
||||
),
|
||||
autoincrement=False,
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.categorized.id"],
|
||||
name="fk_categories_selector_id_categorized",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_categories_selector"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"banks",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.Column("BIC", sa.VARCHAR(length=8), autoincrement=False, nullable=False),
|
||||
sa.Column(
|
||||
"type",
|
||||
postgresql.ENUM(
|
||||
"checking",
|
||||
"savings",
|
||||
"investment",
|
||||
"mealcard",
|
||||
"VISA",
|
||||
"MASTERCARD",
|
||||
name="accounttype",
|
||||
schema="transactions",
|
||||
),
|
||||
autoincrement=False,
|
||||
nullable=False,
|
||||
),
|
||||
sa.PrimaryKeyConstraint("BIC", "type", name="pk_banks"),
|
||||
sa.UniqueConstraint("name", name="uq_banks_name"),
|
||||
schema="transactions",
|
||||
postgresql_ignore_search_path=False,
|
||||
)
|
||||
op.create_table(
|
||||
"tags_available",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_tags_available"),
|
||||
schema="transactions",
|
||||
postgresql_ignore_search_path=False,
|
||||
)
|
||||
op.create_table(
|
||||
"nordigen",
|
||||
sa.Column("name", sa.TEXT(), autoincrement=False, nullable=False),
|
||||
sa.Column("bank_id", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.Column("requisition_id", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.Column("invert", sa.BOOLEAN(), autoincrement=False, nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"], ["transactions.banks.name"], name="fk_nordigen_name_banks"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_nordigen"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"tag_rules",
|
||||
sa.Column(
|
||||
"id",
|
||||
sa.BIGINT(),
|
||||
server_default=sa.text(
|
||||
"nextval('transactions.tag_rules_id_seq'::regclass)"
|
||||
),
|
||||
autoincrement=True,
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("tag", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.rules.id"],
|
||||
name="fk_tag_rules_id_rules",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tag"],
|
||||
["transactions.tags_available.name"],
|
||||
name="fk_tag_rules_tag_tags_available",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_tag_rules"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"categories_rules",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.Column(
|
||||
"id",
|
||||
sa.BIGINT(),
|
||||
server_default=sa.text(
|
||||
"nextval('transactions.categories_rules_id_seq'::regclass)"
|
||||
),
|
||||
autoincrement=True,
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["id"],
|
||||
["transactions.rules.id"],
|
||||
name="fk_categories_rules_id_rules",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["transactions.categories_available.name"],
|
||||
name="fk_categories_rules_name_categories_available",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name="pk_categories_rules"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.create_table(
|
||||
"categories_available",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.Column("group", sa.VARCHAR(), autoincrement=False, nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["group"],
|
||||
["transactions.categories_groups.name"],
|
||||
name="fk_categories_available_group_categories_groups",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_categories_available"),
|
||||
schema="transactions",
|
||||
postgresql_ignore_search_path=False,
|
||||
)
|
||||
op.create_table(
|
||||
"categories_schedules",
|
||||
sa.Column("name", sa.VARCHAR(), autoincrement=False, nullable=False),
|
||||
sa.Column(
|
||||
"period",
|
||||
postgresql.ENUM(
|
||||
"daily",
|
||||
"weekly",
|
||||
"monthly",
|
||||
"yearly",
|
||||
name="period",
|
||||
schema="transactions",
|
||||
),
|
||||
autoincrement=False,
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column(
|
||||
"period_multiplier", sa.INTEGER(), autoincrement=False, nullable=True
|
||||
),
|
||||
sa.Column("amount", sa.INTEGER(), autoincrement=False, nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["name"],
|
||||
["transactions.categories_available.name"],
|
||||
name="fk_categories_schedules_name_categories_available",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("name", name="pk_categories_schedules"),
|
||||
schema="transactions",
|
||||
)
|
||||
op.drop_table("selector", schema="category")
|
||||
op.drop_table("schedules", schema="category")
|
||||
op.drop_table("rules", schema="category")
|
||||
op.drop_table("rules", schema="tag")
|
||||
op.drop_table("available", schema="category")
|
||||
op.drop_table("nordigen", schema="bank")
|
||||
op.drop_table("available", schema="tag")
|
||||
op.drop_table("groups", schema="category")
|
||||
op.drop_table("banks", schema="bank")
|
||||
# ### end Alembic commands ###
|
||||
37
alembic/versions/e77395969585_weekly_period.py
Normal file
37
alembic/versions/e77395969585_weekly_period.py
Normal file
@ -0,0 +1,37 @@
|
||||
"""Weekly period
|
||||
|
||||
Revision ID: e77395969585
|
||||
Revises: d18cbd50f7c6
|
||||
Create Date: 2022-12-08 16:35:27.506504+00:00
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "e77395969585"
|
||||
down_revision = "d18cbd50f7c6"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute("ALTER TYPE transactions.period ADD VALUE 'weekly' AFTER 'daily'")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(
|
||||
"""CREATE TYPE transactions.period_new
|
||||
AS ENUM ('daily', 'monthly', 'yearly')
|
||||
"""
|
||||
)
|
||||
op.execute("UPDATE transactions.categories_schedules SET period = DEFAULT WHERE period = 'weekly'")
|
||||
op.execute(
|
||||
"""ALTER TABLE transactions.categories_schedules
|
||||
ALTER COLUMN period TYPE transactions.period_new
|
||||
USING period::text::transactions.period_new
|
||||
"""
|
||||
)
|
||||
op.execute("DROP TYPE transactions.period")
|
||||
op.execute("ALTER TYPE transactions.period_new RENAME TO period")
|
||||
100
categories.yaml
100
categories.yaml
@ -1,100 +0,0 @@
|
||||
Groups:
|
||||
income-fixed:
|
||||
color: limegreen
|
||||
linestyle: dashed
|
||||
income-extra:
|
||||
color: limegreen
|
||||
linestyle: dashed
|
||||
income:
|
||||
color: limegreen
|
||||
linestyle: solid
|
||||
fixed:
|
||||
color: tab:blue
|
||||
required:
|
||||
color: tab:orange
|
||||
health:
|
||||
color: tab:red
|
||||
travel:
|
||||
color: tab:cyan
|
||||
discretionary:
|
||||
color: tab:brown
|
||||
|
||||
Income1:
|
||||
group: income-fixed
|
||||
regex:
|
||||
- company A
|
||||
|
||||
Income2:
|
||||
group: income-fixed
|
||||
regex:
|
||||
- transfer
|
||||
banks:
|
||||
- BankA
|
||||
|
||||
Income3:
|
||||
group: income-extra
|
||||
regex:
|
||||
- company B
|
||||
|
||||
Commute:
|
||||
group: required
|
||||
regex:
|
||||
- uber
|
||||
regular:
|
||||
- [train, 50]
|
||||
|
||||
Utilities:
|
||||
group: fixed
|
||||
regex:
|
||||
- electricity
|
||||
regular:
|
||||
- [water]
|
||||
- [internet, 30.5]
|
||||
|
||||
Groceries:
|
||||
group: required
|
||||
regex:
|
||||
- lidl
|
||||
- e.leclerc
|
||||
- aldi
|
||||
|
||||
Eating Out:
|
||||
group: discretionary
|
||||
regex:
|
||||
- restaurant 1
|
||||
- restaurant 2
|
||||
|
||||
Entertainment:
|
||||
group: discretionary
|
||||
regex:
|
||||
- cinema
|
||||
- steam
|
||||
|
||||
Investment:
|
||||
group: investment
|
||||
|
||||
Pets:
|
||||
group: required
|
||||
|
||||
Medical:
|
||||
group: health
|
||||
regex:
|
||||
- hospital
|
||||
- pharmacy
|
||||
|
||||
Miscellaneous:
|
||||
|
||||
Travel:
|
||||
group: travel
|
||||
regex:
|
||||
- ryanair
|
||||
- easyjet
|
||||
- airbnb
|
||||
not_in_groups:
|
||||
- income-fixed
|
||||
- income-extra
|
||||
- fixed
|
||||
date_fmt: "%Y-%m-%d"
|
||||
vacations:
|
||||
- ["2019-12-23", "2020-01-02"]
|
||||
- ["2020-07-01", "2020-07-30"]
|
||||
@ -1,7 +1,2 @@
|
||||
__all__ = ["run", "parse_data", "categorize_data"]
|
||||
__author__ = "Luís Murta"
|
||||
__version__ = "0.1"
|
||||
|
||||
from pfbudget.core.categories import categorize_data
|
||||
from pfbudget.cli.runnable import run
|
||||
from pfbudget.input.parsers import parse_data
|
||||
|
||||
@ -1,4 +1,278 @@
|
||||
from pfbudget.cli.runnable import run
|
||||
from pfbudget.cli.argparser import argparser
|
||||
from pfbudget.cli.interactive import Interactive
|
||||
from pfbudget.common.types import Operation
|
||||
from pfbudget.core.manager import Manager
|
||||
import pfbudget.db.model as type
|
||||
from pfbudget.utils.utils import parse_args_period
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
argparser = argparser()
|
||||
args = vars(argparser.parse_args())
|
||||
|
||||
assert "op" in args, "No Operation selected"
|
||||
op: Operation = args.pop("op")
|
||||
|
||||
assert "database" in args, "No database selected"
|
||||
db = args.pop("database")
|
||||
|
||||
assert "verbose" in args, "No verbose level specified"
|
||||
verbosity = args.pop("verbose")
|
||||
|
||||
params = []
|
||||
match (op):
|
||||
case Operation.ManualCategorization:
|
||||
Interactive(Manager(db, verbosity)).start()
|
||||
exit()
|
||||
|
||||
case Operation.Categorize:
|
||||
keys = {"no_nulls"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [args["no_nulls"]]
|
||||
|
||||
case Operation.Parse:
|
||||
keys = {"path", "bank", "creditcard"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [args["path"], args["bank"], args["creditcard"]]
|
||||
|
||||
case Operation.RequisitionId:
|
||||
keys = {"bank"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [args["bank"][0]]
|
||||
|
||||
case Operation.Download:
|
||||
keys = {"all", "banks", "interval", "start", "end", "year", "dry_run"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
start, end = parse_args_period(args)
|
||||
params = [start, end, args["dry_run"]]
|
||||
|
||||
if not args["all"]:
|
||||
params.append(args["banks"])
|
||||
else:
|
||||
params.append(None)
|
||||
|
||||
case Operation.BankAdd:
|
||||
keys = {"bank", "bic", "type"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [
|
||||
type.Bank(
|
||||
args["bank"][0],
|
||||
args["bic"][0],
|
||||
args["type"][0],
|
||||
)
|
||||
]
|
||||
|
||||
case Operation.BankMod:
|
||||
keys = {"bank", "bic", "type", "remove"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
nargs_1 = ["bic", "type"]
|
||||
|
||||
param = {"name": args["bank"][0]}
|
||||
param |= {k: v[0] for k, v in args.items() if k in nargs_1 and args[k]}
|
||||
param |= {k: None for k in args["remove"] if k in nargs_1}
|
||||
|
||||
params = [param]
|
||||
|
||||
case Operation.BankDel:
|
||||
assert len(args["bank"]) > 0, "argparser ill defined"
|
||||
params = args["bank"]
|
||||
|
||||
case Operation.PSD2Add:
|
||||
keys = {"bank", "bank_id", "requisition_id", "invert"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [
|
||||
type.Nordigen(
|
||||
args["bank"][0],
|
||||
args["bank_id"][0] if args["bank_id"] else None,
|
||||
args["requisition_id"][0] if args["requisition_id"] else None,
|
||||
args["invert"] if args["invert"] else None,
|
||||
)
|
||||
]
|
||||
|
||||
case Operation.PSD2Mod:
|
||||
keys = {"bank", "bank_id", "requisition_id", "invert", "remove"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
nargs_1 = ["bank_id", "requisition_id"]
|
||||
nargs_0 = ["invert"]
|
||||
|
||||
param = {"name": args["bank"][0]}
|
||||
param |= {k: v[0] for k, v in args.items() if k in nargs_1 and args[k]}
|
||||
param |= {k: v for k, v in args.items() if k in nargs_0}
|
||||
param |= {k: None for k in args["remove"] if k in nargs_1}
|
||||
|
||||
params = [param]
|
||||
|
||||
case Operation.PSD2Del:
|
||||
assert len(args["bank"]) > 0, "argparser ill defined"
|
||||
params = args["bank"]
|
||||
|
||||
case Operation.PSD2CountryBanks:
|
||||
keys = {"country"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [args["country"][0]]
|
||||
|
||||
case Operation.CategoryAdd:
|
||||
keys = {"category", "group"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [type.Category(cat, args["group"]) for cat in args["category"]]
|
||||
|
||||
case Operation.CategoryUpdate:
|
||||
keys = {"category", "group"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [{"name": cat, "group": args["group"]} for cat in args["category"]]
|
||||
|
||||
case Operation.CategoryRemove:
|
||||
assert "category" in args, "argparser ill defined"
|
||||
|
||||
params = args["category"]
|
||||
|
||||
case Operation.CategorySchedule:
|
||||
keys = {"category", "period", "frequency"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [
|
||||
type.CategorySchedule(
|
||||
cat, args["period"][0], args["frequency"][0], None
|
||||
)
|
||||
for cat in args["category"]
|
||||
]
|
||||
|
||||
case Operation.RuleAdd:
|
||||
keys = {
|
||||
"category",
|
||||
"start",
|
||||
"end",
|
||||
"description",
|
||||
"regex",
|
||||
"bank",
|
||||
"min",
|
||||
"max",
|
||||
}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = []
|
||||
for cat in args["category"]:
|
||||
rule = type.CategoryRule(
|
||||
start=args["start"][0] if args["start"] else None,
|
||||
end=args["end"][0] if args["end"] else None,
|
||||
description=args["description"][0] if args["description"] else None,
|
||||
regex=args["regex"][0] if args["regex"] else None,
|
||||
bank=args["bank"][0] if args["bank"] else None,
|
||||
min=args["min"][0] if args["min"] else None,
|
||||
max=args["max"][0] if args["max"] else None,
|
||||
)
|
||||
# associate the rule to the category name (mapped col has init=False)
|
||||
rule.name = cat
|
||||
params.append(rule)
|
||||
|
||||
case Operation.RuleRemove | Operation.TagRuleRemove:
|
||||
keys = {"id"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = args["id"]
|
||||
|
||||
case Operation.RuleModify:
|
||||
keys = {
|
||||
"id",
|
||||
"category",
|
||||
"date",
|
||||
"description",
|
||||
"bank",
|
||||
"min",
|
||||
"max",
|
||||
"remove",
|
||||
}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
nargs_1 = ["category", "date", "description", "regex", "bank", "min", "max"]
|
||||
params = []
|
||||
for id in args["id"]:
|
||||
param = {"id": id}
|
||||
param |= {k: v[0] for k, v in args.items() if k in nargs_1 and args[k]}
|
||||
param |= {k: None for k in args["remove"] if k in nargs_1}
|
||||
|
||||
params.append(param)
|
||||
|
||||
case Operation.TagAdd:
|
||||
keys = {"tag"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [type.Tag(tag) for tag in args["tag"]]
|
||||
|
||||
case Operation.TagRuleAdd:
|
||||
keys = {"tag", "start", "end", "description", "regex", "bank", "min", "max"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = []
|
||||
for tag in args["tag"]:
|
||||
rule = type.TagRule(
|
||||
start=args["start"][0] if args["start"] else None,
|
||||
end=args["end"][0] if args["end"] else None,
|
||||
description=args["description"][0] if args["description"] else None,
|
||||
regex=args["regex"][0] if args["regex"] else None,
|
||||
bank=args["bank"][0] if args["bank"] else None,
|
||||
min=args["min"][0] if args["min"] else None,
|
||||
max=args["max"][0] if args["max"] else None,
|
||||
)
|
||||
# associate the rule to the tag name (mapped col has init=False)
|
||||
rule.tag = tag
|
||||
params.append(rule)
|
||||
|
||||
case Operation.TagRuleModify:
|
||||
keys = {"id", "tag", "date", "description", "bank", "min", "max", "remove"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
nargs_1 = ["tag", "date", "description", "regex", "bank", "min", "max"]
|
||||
params = []
|
||||
for id in args["id"]:
|
||||
param = {"id": id}
|
||||
param |= {k: v[0] for k, v in args.items() if k in nargs_1 and args[k]}
|
||||
param |= {k: None for k in args["remove"] if k in nargs_1}
|
||||
|
||||
params.append(param)
|
||||
|
||||
case Operation.GroupAdd:
|
||||
assert "group" in args, "argparser ill defined"
|
||||
params = [type.CategoryGroup(group) for group in args["group"]]
|
||||
|
||||
case Operation.GroupRemove:
|
||||
assert "group" in args, "argparser ill defined"
|
||||
params = args["group"]
|
||||
|
||||
case Operation.Forge | Operation.Dismantle:
|
||||
keys = {"original", "links"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [args["original"][0], args["links"]]
|
||||
|
||||
case (
|
||||
Operation.Export
|
||||
| Operation.Import
|
||||
| Operation.ExportBanks
|
||||
| Operation.ImportBanks
|
||||
| Operation.ExportCategoryRules
|
||||
| Operation.ImportCategoryRules
|
||||
| Operation.ExportTagRules
|
||||
| Operation.ImportTagRules
|
||||
| Operation.ExportCategories
|
||||
| Operation.ImportCategories
|
||||
| Operation.ExportCategoryGroups
|
||||
| Operation.ImportCategoryGroups
|
||||
):
|
||||
keys = {"file", "format"}
|
||||
assert args.keys() >= keys, f"missing {args.keys() - keys}"
|
||||
|
||||
params = [args["file"][0], args["format"][0]]
|
||||
|
||||
Manager(db, verbosity).action(op, params)
|
||||
|
||||
322
pfbudget/cli/argparser.py
Normal file
322
pfbudget/cli/argparser.py
Normal file
@ -0,0 +1,322 @@
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import decimal
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
import re
|
||||
|
||||
from pfbudget.common.types import Operation
|
||||
from pfbudget.db.model import AccountType, SchedulePeriod
|
||||
|
||||
load_dotenv()
|
||||
|
||||
DEFAULT_DB = os.environ.get("DEFAULT_DB")
|
||||
|
||||
|
||||
def argparser() -> argparse.ArgumentParser:
|
||||
universal = argparse.ArgumentParser(add_help=False)
|
||||
universal.add_argument(
|
||||
"-db",
|
||||
"--database",
|
||||
nargs="?",
|
||||
help="select current database",
|
||||
default=DEFAULT_DB,
|
||||
)
|
||||
|
||||
universal.add_argument("-v", "--verbose", action="count", default=0)
|
||||
|
||||
period = argparse.ArgumentParser(add_help=False)
|
||||
period_group = period.add_mutually_exclusive_group()
|
||||
period_group.add_argument(
|
||||
"--interval", type=str, nargs=2, help="graph interval", metavar=("START", "END")
|
||||
)
|
||||
period_group.add_argument("--start", type=str, nargs=1, help="graph start date")
|
||||
period_group.add_argument("--end", type=str, nargs=1, help="graph end date")
|
||||
period_group.add_argument("--year", type=str, nargs=1, help="graph year")
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="does cool finance stuff",
|
||||
parents=[universal],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
|
||||
if version := re.search(
|
||||
r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]', open("pfbudget/__init__.py").read()
|
||||
):
|
||||
parser.add_argument(
|
||||
"--version",
|
||||
action="version",
|
||||
version=version.group(1),
|
||||
)
|
||||
|
||||
subparsers = parser.add_subparsers(required=True)
|
||||
|
||||
# Exports transactions to specified format and file
|
||||
export = subparsers.add_parser("export")
|
||||
export.set_defaults(op=Operation.Export)
|
||||
file_options(export)
|
||||
|
||||
# Imports transactions from specified format and file
|
||||
pimport = subparsers.add_parser("import")
|
||||
pimport.set_defaults(op=Operation.Import)
|
||||
file_options(pimport)
|
||||
|
||||
# Parse from .csv
|
||||
parse = subparsers.add_parser("parse")
|
||||
parse.set_defaults(op=Operation.Parse)
|
||||
parse.add_argument("path", nargs="+", type=str)
|
||||
parse.add_argument("--bank", nargs=1, type=str)
|
||||
parse.add_argument("--creditcard", nargs=1, type=str)
|
||||
|
||||
# Automatic/manual categorization
|
||||
categorize = subparsers.add_parser("categorize").add_subparsers(required=True)
|
||||
auto = categorize.add_parser("auto")
|
||||
auto.set_defaults(op=Operation.Categorize)
|
||||
auto.add_argument("--no-nulls", action="store_false")
|
||||
|
||||
categorize.add_parser("manual").set_defaults(op=Operation.ManualCategorization)
|
||||
|
||||
# Banks
|
||||
bank(subparsers.add_parser("bank"))
|
||||
|
||||
# PSD2 access token
|
||||
subparsers.add_parser("token").set_defaults(op=Operation.Token)
|
||||
|
||||
# PSD2 requisition id
|
||||
requisition = subparsers.add_parser("eua")
|
||||
requisition.set_defaults(op=Operation.RequisitionId)
|
||||
requisition.add_argument("bank", nargs=1, type=str)
|
||||
|
||||
# Download through the PSD2 API
|
||||
download = subparsers.add_parser("download", parents=[period])
|
||||
download.set_defaults(op=Operation.Download)
|
||||
download_banks = download.add_mutually_exclusive_group()
|
||||
download_banks.add_argument("--all", action="store_true")
|
||||
download_banks.add_argument("--banks", nargs="+", type=str)
|
||||
download.add_argument("--dry-run", action="store_true")
|
||||
|
||||
# List available banks in country C
|
||||
banks = subparsers.add_parser("banks")
|
||||
banks.set_defaults(op=Operation.PSD2CountryBanks)
|
||||
banks.add_argument("country", nargs=1, type=str)
|
||||
|
||||
# Categories
|
||||
category(subparsers.add_parser("category"))
|
||||
|
||||
# Tag
|
||||
tags(subparsers.add_parser("tag"))
|
||||
|
||||
# Link
|
||||
link(subparsers.add_parser("link"))
|
||||
|
||||
return parser
|
||||
|
||||
def bank(parser: argparse.ArgumentParser):
|
||||
commands = parser.add_subparsers(required=True)
|
||||
|
||||
add = commands.add_parser("add")
|
||||
add.set_defaults(op=Operation.BankAdd)
|
||||
add.add_argument("bank", nargs=1, type=str)
|
||||
add.add_argument("bic", nargs=1, type=str)
|
||||
add.add_argument("type", nargs=1, type=str, choices=[e.name for e in AccountType])
|
||||
|
||||
rem = commands.add_parser("del")
|
||||
rem.set_defaults(op=Operation.BankDel)
|
||||
rem.add_argument("bank", nargs="+", type=str)
|
||||
|
||||
mod = commands.add_parser("mod")
|
||||
mod.set_defaults(op=Operation.BankMod)
|
||||
mod.add_argument("bank", nargs=1, type=str)
|
||||
mod.add_argument("--bic", nargs=1, type=str)
|
||||
mod.add_argument("--type", nargs=1, type=str, choices=[e.name for e in AccountType])
|
||||
mod.add_argument("--remove", nargs="*", default=[], type=str)
|
||||
|
||||
psd2(commands.add_parser("psd2"))
|
||||
|
||||
export = commands.add_parser("export")
|
||||
export.set_defaults(op=Operation.ExportBanks)
|
||||
file_options(export)
|
||||
|
||||
pimport = commands.add_parser("import")
|
||||
pimport.set_defaults(op=Operation.ImportBanks)
|
||||
file_options(pimport)
|
||||
|
||||
|
||||
def psd2(parser: argparse.ArgumentParser):
|
||||
commands = parser.add_subparsers(required=True)
|
||||
|
||||
add = commands.add_parser("add")
|
||||
add.set_defaults(op=Operation.PSD2Add)
|
||||
add.add_argument("bank", nargs=1, type=str)
|
||||
add.add_argument("--bank_id", nargs=1, type=str)
|
||||
add.add_argument("--requisition_id", nargs=1, type=str)
|
||||
add.add_argument("--invert", action="store_true")
|
||||
|
||||
rem = commands.add_parser("del")
|
||||
rem.set_defaults(op=Operation.PSD2Del)
|
||||
rem.add_argument("bank", nargs="+", type=str)
|
||||
|
||||
mod = commands.add_parser("mod")
|
||||
mod.set_defaults(op=Operation.PSD2Mod)
|
||||
mod.add_argument("bank", nargs=1, type=str)
|
||||
mod.add_argument("--bank_id", nargs=1, type=str)
|
||||
mod.add_argument("--requisition_id", nargs=1, type=str)
|
||||
mod.add_argument("--invert", action="store_true")
|
||||
mod.add_argument("--remove", nargs="*", default=[], type=str)
|
||||
|
||||
|
||||
def category(parser: argparse.ArgumentParser):
|
||||
commands = parser.add_subparsers(required=True)
|
||||
|
||||
add = commands.add_parser("add")
|
||||
add.set_defaults(op=Operation.CategoryAdd)
|
||||
add.add_argument("category", nargs="+", type=str)
|
||||
add.add_argument("--group", nargs="?", type=str)
|
||||
|
||||
remove = commands.add_parser("remove")
|
||||
remove.set_defaults(op=Operation.CategoryRemove)
|
||||
remove.add_argument("category", nargs="+", type=str)
|
||||
|
||||
update = commands.add_parser("update")
|
||||
update.set_defaults(op=Operation.CategoryUpdate)
|
||||
update.add_argument("category", nargs="+", type=str)
|
||||
update.add_argument("--group", nargs="?", type=str)
|
||||
|
||||
schedule = commands.add_parser("schedule")
|
||||
schedule.set_defaults(op=Operation.CategorySchedule)
|
||||
schedule.add_argument("category", nargs="+", type=str)
|
||||
schedule.add_argument("period", nargs=1, choices=[e.value for e in SchedulePeriod])
|
||||
schedule.add_argument("--frequency", nargs=1, default=[1], type=int)
|
||||
|
||||
rule = commands.add_parser("rule")
|
||||
category_rule(rule)
|
||||
|
||||
group = commands.add_parser("group")
|
||||
category_group(group)
|
||||
|
||||
export = commands.add_parser("export")
|
||||
export.set_defaults(op=Operation.ExportCategories)
|
||||
file_options(export)
|
||||
|
||||
pimport = commands.add_parser("import")
|
||||
pimport.set_defaults(op=Operation.ImportCategories)
|
||||
file_options(pimport)
|
||||
|
||||
|
||||
def category_group(parser: argparse.ArgumentParser):
|
||||
commands = parser.add_subparsers(required=True)
|
||||
|
||||
add = commands.add_parser("add")
|
||||
add.set_defaults(op=Operation.GroupAdd)
|
||||
add.add_argument("group", nargs="+", type=str)
|
||||
|
||||
remove = commands.add_parser("remove")
|
||||
remove.set_defaults(op=Operation.GroupRemove)
|
||||
remove.add_argument("group", nargs="+", type=str)
|
||||
|
||||
export = commands.add_parser("export")
|
||||
export.set_defaults(op=Operation.ExportCategoryGroups)
|
||||
file_options(export)
|
||||
|
||||
pimport = commands.add_parser("import")
|
||||
pimport.set_defaults(op=Operation.ImportCategoryGroups)
|
||||
file_options(pimport)
|
||||
|
||||
|
||||
def category_rule(parser: argparse.ArgumentParser):
|
||||
commands = parser.add_subparsers(required=True)
|
||||
|
||||
add = commands.add_parser("add")
|
||||
add.set_defaults(op=Operation.RuleAdd)
|
||||
add.add_argument("category", nargs="+", type=str)
|
||||
rules(add)
|
||||
|
||||
remove = commands.add_parser("remove")
|
||||
remove.set_defaults(op=Operation.RuleRemove)
|
||||
remove.add_argument("id", nargs="+", type=int)
|
||||
|
||||
modify = commands.add_parser("modify")
|
||||
modify.set_defaults(op=Operation.RuleModify)
|
||||
modify.add_argument("id", nargs="+", type=int)
|
||||
modify.add_argument("--category", nargs=1, type=str)
|
||||
rules(modify)
|
||||
modify.add_argument("--remove", nargs="*", default=[], type=str)
|
||||
|
||||
export = commands.add_parser("export")
|
||||
export.set_defaults(op=Operation.ExportCategoryRules)
|
||||
file_options(export)
|
||||
|
||||
pimport = commands.add_parser("import")
|
||||
pimport.set_defaults(op=Operation.ImportCategoryRules)
|
||||
file_options(pimport)
|
||||
|
||||
|
||||
def tags(parser: argparse.ArgumentParser):
|
||||
commands = parser.add_subparsers(required=True)
|
||||
|
||||
add = commands.add_parser("add")
|
||||
add.set_defaults(op=Operation.TagAdd)
|
||||
add.add_argument("tag", nargs="+", type=str)
|
||||
|
||||
remove = commands.add_parser("remove")
|
||||
remove.set_defaults(op=Operation.TagRemove)
|
||||
remove.add_argument("tag", nargs="+", type=str)
|
||||
|
||||
rule = commands.add_parser("rule")
|
||||
tag_rule(rule)
|
||||
|
||||
|
||||
def tag_rule(parser: argparse.ArgumentParser):
|
||||
commands = parser.add_subparsers(required=True)
|
||||
|
||||
add = commands.add_parser("add")
|
||||
add.set_defaults(op=Operation.TagRuleAdd)
|
||||
add.add_argument("tag", nargs="+", type=str)
|
||||
rules(add)
|
||||
|
||||
remove = commands.add_parser("remove")
|
||||
remove.set_defaults(op=Operation.TagRuleRemove)
|
||||
remove.add_argument("id", nargs="+", type=int)
|
||||
|
||||
modify = commands.add_parser("modify")
|
||||
modify.set_defaults(op=Operation.TagRuleModify)
|
||||
modify.add_argument("id", nargs="+", type=int)
|
||||
modify.add_argument("--tag", nargs=1, type=str)
|
||||
rules(modify)
|
||||
|
||||
export = commands.add_parser("export")
|
||||
export.set_defaults(op=Operation.ExportTagRules)
|
||||
file_options(export)
|
||||
|
||||
pimport = commands.add_parser("import")
|
||||
pimport.set_defaults(op=Operation.ImportTagRules)
|
||||
file_options(pimport)
|
||||
|
||||
|
||||
def rules(parser: argparse.ArgumentParser):
|
||||
parser.add_argument("--start", nargs=1, type=dt.date.fromisoformat)
|
||||
parser.add_argument("--end", nargs=1, type=dt.date.fromisoformat)
|
||||
parser.add_argument("--description", nargs=1, type=str)
|
||||
parser.add_argument("--regex", nargs=1, type=str)
|
||||
parser.add_argument("--bank", nargs=1, type=str)
|
||||
parser.add_argument("--min", nargs=1, type=decimal.Decimal)
|
||||
parser.add_argument("--max", nargs=1, type=decimal.Decimal)
|
||||
|
||||
|
||||
def link(parser: argparse.ArgumentParser):
|
||||
commands = parser.add_subparsers(required=True)
|
||||
|
||||
forge = commands.add_parser("forge")
|
||||
forge.set_defaults(op=Operation.Forge)
|
||||
forge.add_argument("original", nargs=1, type=int)
|
||||
forge.add_argument("links", nargs="+", type=int)
|
||||
|
||||
dismantle = commands.add_parser("dismantle")
|
||||
dismantle.set_defaults(op=Operation.Dismantle)
|
||||
dismantle.add_argument("original", nargs=1, type=int)
|
||||
dismantle.add_argument("links", nargs="+", type=int)
|
||||
|
||||
|
||||
def file_options(parser: argparse.ArgumentParser):
|
||||
parser.add_argument("file", nargs=1, type=str)
|
||||
parser.add_argument("format", nargs=1, default="pickle")
|
||||
121
pfbudget/cli/interactive.py
Normal file
121
pfbudget/cli/interactive.py
Normal file
@ -0,0 +1,121 @@
|
||||
import decimal
|
||||
|
||||
from ..core.manager import Manager
|
||||
from ..db.model import (
|
||||
Category,
|
||||
Note,
|
||||
CategorySelector,
|
||||
SplitTransaction,
|
||||
Tag,
|
||||
Transaction,
|
||||
TransactionCategory,
|
||||
TransactionTag,
|
||||
)
|
||||
|
||||
|
||||
class Interactive:
|
||||
help = "category(:tag)/split/note:/skip/quit"
|
||||
selector = CategorySelector.manual
|
||||
|
||||
def __init__(self, manager: Manager) -> None:
|
||||
self.manager = manager
|
||||
|
||||
self.categories = self.manager.database.select(Category)
|
||||
self.tags = self.manager.database.select(Tag)
|
||||
|
||||
def intro(self) -> None:
|
||||
print(
|
||||
f"Welcome! Available categories are {[c.name for c in self.categories]} and"
|
||||
f" currently existing tags are {[t.name for t in self.tags]}"
|
||||
)
|
||||
|
||||
def start(self) -> None:
|
||||
self.intro()
|
||||
|
||||
with self.manager.database.session as session:
|
||||
uncategorized = session.select(
|
||||
Transaction, lambda: ~Transaction.category.has()
|
||||
)
|
||||
uncategorized.sort()
|
||||
n = len(uncategorized)
|
||||
print(f"{n} left to categorize")
|
||||
|
||||
i = 0
|
||||
new = []
|
||||
|
||||
while (command := input("$ ")) != "quit" and i < len(uncategorized):
|
||||
current = uncategorized[i] if len(new) == 0 else new.pop()
|
||||
print(current)
|
||||
|
||||
match command:
|
||||
case "help":
|
||||
print(self.help)
|
||||
|
||||
case "skip":
|
||||
if len(uncategorized) == 0:
|
||||
i += 1
|
||||
|
||||
case "quit":
|
||||
break
|
||||
|
||||
case "split":
|
||||
new = self.split(current)
|
||||
session.insert(new)
|
||||
|
||||
case other:
|
||||
if not other:
|
||||
print(self.help)
|
||||
continue
|
||||
|
||||
if other.startswith("note:"):
|
||||
# TODO adding notes to a splitted transaction won't allow
|
||||
# categorization
|
||||
current.note = Note(other[len("note:") :].strip())
|
||||
else:
|
||||
ct = other.split(":")
|
||||
if (category := ct[0]) not in [
|
||||
c.name for c in self.categories
|
||||
]:
|
||||
print(self.help, self.categories)
|
||||
continue
|
||||
|
||||
tags = []
|
||||
if len(ct) > 1:
|
||||
tags = ct[1:]
|
||||
|
||||
current.category = TransactionCategory(
|
||||
category, self.selector
|
||||
)
|
||||
for tag in tags:
|
||||
if tag not in [t.name for t in self.tags]:
|
||||
session.insert([Tag(tag)])
|
||||
self.tags = session.get(Tag)
|
||||
|
||||
current.tags.add(TransactionTag(tag))
|
||||
|
||||
if len(new) == 0:
|
||||
i += 1
|
||||
|
||||
def split(self, original: Transaction) -> list[SplitTransaction]:
|
||||
total = original.amount
|
||||
new = []
|
||||
|
||||
done = False
|
||||
while not done:
|
||||
if abs(sum(t.amount for t in new)) > abs(total):
|
||||
print("Overflow, try again")
|
||||
new.clear()
|
||||
continue
|
||||
|
||||
if sum(t.amount for t in new) == total:
|
||||
done = True
|
||||
break
|
||||
|
||||
amount = decimal.Decimal(input("amount: "))
|
||||
new.append(
|
||||
SplitTransaction(
|
||||
original.date, original.description, amount, original.id
|
||||
)
|
||||
)
|
||||
|
||||
return new
|
||||
@ -1,321 +0,0 @@
|
||||
from pathlib import Path
|
||||
import argparse
|
||||
import re
|
||||
|
||||
from pfbudget.core.categories import categorize_data
|
||||
from pfbudget.core.manager import Manager
|
||||
from pfbudget.input.json import JsonParser
|
||||
from pfbudget.input.nordigen import NordigenInput
|
||||
from pfbudget.db.client import DatabaseClient
|
||||
import pfbudget.reporting.graph
|
||||
import pfbudget.reporting.report
|
||||
import pfbudget.utils
|
||||
|
||||
|
||||
DEFAULT_DB = "data.db"
|
||||
|
||||
|
||||
class PfBudgetInitialized(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PfBudgetNotInitialized(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class DataFileMissing(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def argparser(manager: Manager) -> argparse.ArgumentParser:
|
||||
|
||||
help = argparse.ArgumentParser(add_help=False)
|
||||
help.add_argument(
|
||||
"-db",
|
||||
"--database",
|
||||
nargs="?",
|
||||
help="select current database",
|
||||
default=DEFAULT_DB,
|
||||
)
|
||||
help.add_argument(
|
||||
"-q", "--quiet", action="store_true", help="reduces the amount of verbose"
|
||||
)
|
||||
|
||||
period = argparse.ArgumentParser(add_help=False).add_mutually_exclusive_group()
|
||||
period.add_argument(
|
||||
"--interval", type=str, nargs=2, help="graph interval", metavar=("START", "END")
|
||||
)
|
||||
period.add_argument("--start", type=str, nargs=1, help="graph start date")
|
||||
period.add_argument("--end", type=str, nargs=1, help="graph end date")
|
||||
period.add_argument("--year", type=str, nargs=1, help="graph year")
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="does cool finance stuff",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
parser.add_argument(
|
||||
"--version",
|
||||
action="version",
|
||||
version=re.search(
|
||||
r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
|
||||
open("pfbudget/__init__.py").read(),
|
||||
).group(1),
|
||||
)
|
||||
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
"""
|
||||
Init
|
||||
"""
|
||||
p_init = subparsers.add_parser(
|
||||
"init",
|
||||
description="Initializes the SQLite3 database",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_init.set_defaults(func=lambda args: manager.init())
|
||||
|
||||
"""
|
||||
Exporting
|
||||
"""
|
||||
p_export = subparsers.add_parser(
|
||||
"export",
|
||||
description="Exports the selected database to a .csv file",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_export.set_defaults(func=lambda args: DatabaseClient(args.database).export())
|
||||
|
||||
"""
|
||||
Parsing
|
||||
"""
|
||||
p_parse = subparsers.add_parser(
|
||||
"parse",
|
||||
description="Parses and adds the requested transactions into the selected database",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_parse.add_argument("path", nargs="+", type=str)
|
||||
p_parse.add_argument("--bank", nargs=1, type=str)
|
||||
p_parse.add_argument("--creditcard", nargs=1, type=str)
|
||||
p_parse.add_argument("--category", nargs=1, type=int)
|
||||
p_parse.set_defaults(func=lambda args: parse(manager, args))
|
||||
|
||||
"""
|
||||
Categorizing
|
||||
"""
|
||||
p_categorize = subparsers.add_parser(
|
||||
"categorize",
|
||||
description="Categorizes the transactions in the selected database",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_categorize.set_defaults(
|
||||
func=lambda args: categorize_data(DatabaseClient(args.database))
|
||||
)
|
||||
|
||||
"""
|
||||
Graph
|
||||
"""
|
||||
p_graph = subparsers.add_parser(
|
||||
"graph",
|
||||
description="Graph of the transactions",
|
||||
parents=[help, period],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_graph.add_argument(
|
||||
"option",
|
||||
type=str,
|
||||
choices=["monthly", "discrete", "networth"],
|
||||
nargs="?",
|
||||
default="monthly",
|
||||
help="graph option help",
|
||||
)
|
||||
p_graph.add_argument("--save", action="store_true")
|
||||
p_graph.set_defaults(func=graph)
|
||||
|
||||
"""
|
||||
Report
|
||||
"""
|
||||
p_report = subparsers.add_parser(
|
||||
"report",
|
||||
description="Prints report of transaction groups",
|
||||
parents=[help, period],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_report.add_argument(
|
||||
"option",
|
||||
type=str,
|
||||
choices=["net", "detailed"],
|
||||
nargs="?",
|
||||
default="net",
|
||||
help="report option help",
|
||||
)
|
||||
p_report.set_defaults(func=report)
|
||||
|
||||
"""
|
||||
Register bank
|
||||
"""
|
||||
p_register = subparsers.add_parser(
|
||||
"register",
|
||||
description="Register a bank",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_register.add_argument("bank", type=str, nargs=1, help="bank option help")
|
||||
p_register.add_argument(
|
||||
"--requisition", type=str, nargs=1, help="requisition option help"
|
||||
)
|
||||
p_register.add_argument("--invert", action="store_true")
|
||||
p_register.set_defaults(func=lambda args: manager.register(vars(args)))
|
||||
|
||||
"""
|
||||
Unregister bank
|
||||
"""
|
||||
p_register = subparsers.add_parser(
|
||||
"unregister",
|
||||
description="Unregister a bank",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_register.add_argument("bank", type=str, nargs=1, help="bank option help")
|
||||
p_register.set_defaults(func=lambda args: manager.unregister(vars(args)))
|
||||
|
||||
"""
|
||||
Nordigen API
|
||||
"""
|
||||
p_nordigen_access = subparsers.add_parser(
|
||||
"token",
|
||||
description="Get new access token",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_nordigen_access.set_defaults(func=lambda args: NordigenInput(manager).token())
|
||||
|
||||
"""
|
||||
(Re)new bank requisition ID
|
||||
"""
|
||||
p_nordigen_access = subparsers.add_parser(
|
||||
"renew",
|
||||
description="(Re)new the Bank requisition ID",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_nordigen_access.add_argument("name", nargs=1, type=str)
|
||||
p_nordigen_access.add_argument("country", nargs=1, type=str)
|
||||
p_nordigen_access.set_defaults(
|
||||
func=lambda args: NordigenInput(manager).requisition(
|
||||
args.name[0], args.country[0]
|
||||
)
|
||||
)
|
||||
|
||||
"""
|
||||
Downloading through Nordigen API
|
||||
"""
|
||||
p_nordigen_download = subparsers.add_parser(
|
||||
"download",
|
||||
description="Downloads transactions using Nordigen API",
|
||||
parents=[help, period],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_nordigen_download.add_argument("--id", nargs="+", type=str)
|
||||
p_nordigen_download.add_argument("--name", nargs="+", type=str)
|
||||
p_nordigen_download.add_argument("--all", action="store_true")
|
||||
p_nordigen_download.set_defaults(func=lambda args: download(manager, args))
|
||||
|
||||
"""
|
||||
List available banks on Nordigen API
|
||||
"""
|
||||
p_nordigen_list = subparsers.add_parser(
|
||||
"list",
|
||||
description="Lists banks in {country}",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_nordigen_list.add_argument("country", nargs=1, type=str)
|
||||
p_nordigen_list.set_defaults(func=lambda args: nordigen_banks(manager, args))
|
||||
|
||||
"""
|
||||
Nordigen JSONs
|
||||
"""
|
||||
p_nordigen_json = subparsers.add_parser(
|
||||
"json",
|
||||
description="",
|
||||
parents=[help],
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
p_nordigen_json.add_argument("json", nargs=1, type=str)
|
||||
p_nordigen_json.add_argument("bank", nargs=1, type=str)
|
||||
p_nordigen_json.add_argument("--invert", action=argparse.BooleanOptionalAction)
|
||||
p_nordigen_json.set_defaults(
|
||||
func=lambda args: manager.parser(JsonParser(vars(args)))
|
||||
)
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def parse(manager: Manager, args):
|
||||
"""Parses the contents of the path in args to the selected database.
|
||||
|
||||
Args:
|
||||
args (dict): argparse variables
|
||||
"""
|
||||
for path in args.path:
|
||||
if (dir := Path(path)).is_dir():
|
||||
for file in dir.iterdir():
|
||||
manager.parse(file, vars(args))
|
||||
elif Path(path).is_file():
|
||||
manager.parse(path, vars(args))
|
||||
else:
|
||||
raise FileNotFoundError
|
||||
|
||||
|
||||
def graph(args):
|
||||
"""Plots the transactions over a period of time.
|
||||
|
||||
Args:
|
||||
args (dict): argparse variables
|
||||
"""
|
||||
start, end = pfbudget.utils.parse_args_period(args)
|
||||
if args.option == "monthly":
|
||||
pfbudget.reporting.graph.monthly(
|
||||
DatabaseClient(args.database), vars(args), start, end
|
||||
)
|
||||
elif args.option == "discrete":
|
||||
pfbudget.reporting.graph.discrete(
|
||||
DatabaseClient(args.database), vars(args), start, end
|
||||
)
|
||||
elif args.option == "networth":
|
||||
pfbudget.reporting.graph.networth(
|
||||
DatabaseClient(args.database), vars(args), start, end
|
||||
)
|
||||
|
||||
|
||||
def report(args):
|
||||
"""Prints a detailed report of the transactions over a period of time.
|
||||
|
||||
Args:
|
||||
args (dict): argparse variables
|
||||
"""
|
||||
start, end = pfbudget.utils.parse_args_period(args)
|
||||
if args.option == "net":
|
||||
pfbudget.reporting.report.net(DatabaseClient(args.database), start, end)
|
||||
elif args.option == "detailed":
|
||||
pfbudget.reporting.report.detailed(DatabaseClient(args.database), start, end)
|
||||
|
||||
|
||||
def nordigen_banks(manager: Manager, args):
|
||||
input = NordigenInput(manager)
|
||||
input.list(vars(args)["country"][0])
|
||||
|
||||
|
||||
def download(manager: Manager, args):
|
||||
start, end = pfbudget.utils.parse_args_period(args)
|
||||
manager.parser(NordigenInput(manager, vars(args), start, end))
|
||||
|
||||
|
||||
def run():
|
||||
manager = Manager(DEFAULT_DB)
|
||||
args = argparser(manager).parse_args()
|
||||
args.func(args)
|
||||
@ -4,6 +4,58 @@ from decimal import Decimal, InvalidOperation
|
||||
from enum import Enum, auto
|
||||
|
||||
|
||||
class Operation(Enum):
|
||||
Init = auto()
|
||||
Transactions = auto()
|
||||
Parse = auto()
|
||||
Download = auto()
|
||||
Categorize = auto()
|
||||
ManualCategorization = auto()
|
||||
Token = auto()
|
||||
RequisitionId = auto()
|
||||
CategoryAdd = auto()
|
||||
CategoryUpdate = auto()
|
||||
CategoryRemove = auto()
|
||||
CategorySchedule = auto()
|
||||
RuleAdd = auto()
|
||||
RuleRemove = auto()
|
||||
RuleModify = auto()
|
||||
GroupAdd = auto()
|
||||
GroupRemove = auto()
|
||||
TagAdd = auto()
|
||||
TagRemove = auto()
|
||||
TagRuleAdd = auto()
|
||||
TagRuleRemove = auto()
|
||||
TagRuleModify = auto()
|
||||
Forge = auto()
|
||||
Dismantle = auto()
|
||||
Split = auto()
|
||||
BankAdd = auto()
|
||||
BankMod = auto()
|
||||
BankDel = auto()
|
||||
PSD2Add = auto()
|
||||
PSD2Mod = auto()
|
||||
PSD2Del = auto()
|
||||
PSD2CountryBanks = auto()
|
||||
Export = auto()
|
||||
Import = auto()
|
||||
ExportBanks = auto()
|
||||
ImportBanks = auto()
|
||||
ExportCategoryRules = auto()
|
||||
ImportCategoryRules = auto()
|
||||
ExportTagRules = auto()
|
||||
ImportTagRules = auto()
|
||||
ExportCategories = auto()
|
||||
ImportCategories = auto()
|
||||
ExportCategoryGroups = auto()
|
||||
ImportCategoryGroups = auto()
|
||||
|
||||
|
||||
class ExportFormat(Enum):
|
||||
JSON = auto()
|
||||
pickle = auto()
|
||||
|
||||
|
||||
class TransactionError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@ -1,178 +0,0 @@
|
||||
from __future__ import annotations
|
||||
from collections import namedtuple
|
||||
from typing import TYPE_CHECKING
|
||||
import datetime as dt
|
||||
import logging
|
||||
import re
|
||||
import yaml
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pfbudget.common.types import Transaction
|
||||
from pfbudget.db.client import DatabaseClient
|
||||
|
||||
|
||||
Options = namedtuple(
|
||||
"Options",
|
||||
[
|
||||
"group",
|
||||
"regex",
|
||||
"banks",
|
||||
"regular",
|
||||
"not_in_groups",
|
||||
"date_fmt",
|
||||
"vacations",
|
||||
"timedelta",
|
||||
],
|
||||
defaults=["No group", [], [], [], [], "", [], 4],
|
||||
)
|
||||
|
||||
cfg = yaml.safe_load(open("categories.yaml"))
|
||||
try:
|
||||
categories = {
|
||||
str(k): Options(**v) if v else Options()
|
||||
for k, v in cfg.items()
|
||||
if k and k != "Groups"
|
||||
}
|
||||
except TypeError:
|
||||
logging.exception("Invalid option in categories.yaml")
|
||||
categories = {}
|
||||
|
||||
groups = {
|
||||
group: [
|
||||
category for category, options in categories.items() if options.group == group
|
||||
]
|
||||
for group in set(category.group for category in categories.values())
|
||||
}
|
||||
categories.setdefault("Null", Options())
|
||||
|
||||
order = {k: i for i, k in enumerate(cfg["Groups"])}
|
||||
groups = {
|
||||
group: groups[group]
|
||||
for group in sorted(groups, key=lambda x: order.get(x, len(groups)))
|
||||
}
|
||||
|
||||
|
||||
def categorize_data(db: DatabaseClient):
|
||||
|
||||
# 1st) Classifying null transactions, i.e. transfers between banks.
|
||||
# Will not overwrite previous categories
|
||||
nulls(db)
|
||||
|
||||
# 2nd) Classifying all vacations by vacation dates
|
||||
# Will not overwrite previous categories
|
||||
vacations(db)
|
||||
|
||||
# 3rd) Classify all else based on regex
|
||||
if transactions := db.get_uncategorized_transactions():
|
||||
for transaction in transactions:
|
||||
for name, category in categories.items():
|
||||
if matches(transaction, category):
|
||||
transaction.category = name
|
||||
break
|
||||
db.update_categories(
|
||||
[transaction for transaction in transactions if transaction.category]
|
||||
)
|
||||
|
||||
# 4th) Manually update categories from the uncategorized transactions
|
||||
if transactions := db.get_uncategorized_transactions():
|
||||
print(
|
||||
f"Still {len(transactions)} uncategorized transactions left. Type quit/exit to exit the program."
|
||||
)
|
||||
for transaction in transactions:
|
||||
while True:
|
||||
category = input(f"{repr(transaction)} category: ")
|
||||
if category == "quit" or category == "exit":
|
||||
return
|
||||
if not category:
|
||||
break
|
||||
if category not in categories:
|
||||
print(
|
||||
f"Category {category} doesn't exist. Please use one of {categories.keys()}"
|
||||
)
|
||||
else:
|
||||
transaction.category = category
|
||||
db.update_category(transaction)
|
||||
break
|
||||
|
||||
|
||||
def vacations(db: DatabaseClient) -> None:
|
||||
try:
|
||||
date_fmt = categories["Travel"].date_fmt
|
||||
for start, end in categories["Travel"].vacations:
|
||||
try:
|
||||
start = dt.datetime.strptime(start, date_fmt).date().isoformat()
|
||||
end = dt.datetime.strptime(end, date_fmt).date().isoformat()
|
||||
except ValueError as e:
|
||||
logging.warning(f"{e} continuing...")
|
||||
continue
|
||||
|
||||
not_in_groups = categories["Travel"].not_in_groups # default is []
|
||||
|
||||
update = False
|
||||
if transactions := db.get_daterange_uncategorized_transactions(start, end):
|
||||
for transaction in transactions:
|
||||
if not_in_groups:
|
||||
if not any(
|
||||
matches(
|
||||
transaction,
|
||||
categories.get(category, Options()),
|
||||
)
|
||||
for group in not_in_groups
|
||||
for category in groups[group]
|
||||
):
|
||||
transaction.category = "Travel"
|
||||
update = True
|
||||
else:
|
||||
transaction.category = "Travel"
|
||||
update = True
|
||||
|
||||
if update:
|
||||
db.update_categories(transactions)
|
||||
|
||||
except KeyError as e:
|
||||
logging.exception(e)
|
||||
|
||||
|
||||
def nulls(db: DatabaseClient) -> None:
|
||||
null = categories.get("Null", Options())
|
||||
transactions = db.get_uncategorized_transactions()
|
||||
if not transactions:
|
||||
return
|
||||
|
||||
matching_transactions = []
|
||||
for t in transactions:
|
||||
for cancel in (
|
||||
cancel
|
||||
for cancel in transactions
|
||||
if (
|
||||
t.date - dt.timedelta(days=null.timedelta)
|
||||
<= cancel.date
|
||||
<= t.date + dt.timedelta(days=null.timedelta)
|
||||
and (matches(t, null) if null.regex else True)
|
||||
and t.bank != cancel.bank
|
||||
and t not in matching_transactions
|
||||
and cancel not in matching_transactions
|
||||
and cancel != t
|
||||
and t.value == -cancel.value
|
||||
)
|
||||
):
|
||||
t.category = "Null"
|
||||
cancel.category = "Null"
|
||||
matching_transactions.extend([t, cancel])
|
||||
break # There will only be one match per null transaction pair
|
||||
|
||||
if matching_transactions:
|
||||
db.update_categories(matching_transactions)
|
||||
|
||||
|
||||
def matches(transaction: Transaction, category: Options):
|
||||
if not category.regex:
|
||||
return False
|
||||
try:
|
||||
return any(
|
||||
re.compile(pattern.lower()).search(transaction.description.lower())
|
||||
for pattern in category.regex
|
||||
)
|
||||
except re.error as e:
|
||||
print(f"{e}{transaction} {category}")
|
||||
128
pfbudget/core/command.py
Normal file
128
pfbudget/core/command.py
Normal file
@ -0,0 +1,128 @@
|
||||
from abc import ABC, abstractmethod
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pickle
|
||||
from typing import Type
|
||||
|
||||
from pfbudget.common.types import ExportFormat
|
||||
from pfbudget.db.client import Client
|
||||
from pfbudget.db.model import (
|
||||
Bank,
|
||||
Category,
|
||||
CategoryGroup,
|
||||
Serializable,
|
||||
Tag,
|
||||
Transaction,
|
||||
)
|
||||
|
||||
# required for the backup import
|
||||
import pfbudget.db.model
|
||||
|
||||
|
||||
class Command(ABC):
|
||||
@abstractmethod
|
||||
def execute(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def undo(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class ExportCommand(Command):
|
||||
def __init__(
|
||||
self, client: Client, what: Type[Serializable], fn: Path, format: ExportFormat
|
||||
):
|
||||
self.__client = client
|
||||
self.what = what
|
||||
self.fn = fn
|
||||
self.format = format
|
||||
|
||||
def execute(self) -> None:
|
||||
values = self.__client.select(self.what)
|
||||
match self.format:
|
||||
case ExportFormat.JSON:
|
||||
with open(self.fn, "w", newline="") as f:
|
||||
json.dump([e.serialize() for e in values], f, indent=4)
|
||||
case ExportFormat.pickle:
|
||||
raise AttributeError("pickle export not working at the moment!")
|
||||
with open(self.fn, "wb") as f:
|
||||
pickle.dump(values, f)
|
||||
|
||||
|
||||
class ImportCommand(Command):
|
||||
def __init__(
|
||||
self, client: Client, what: Type[Serializable], fn: Path, format: ExportFormat
|
||||
):
|
||||
self.__client = client
|
||||
self.what = what
|
||||
self.fn = fn
|
||||
self.format = format
|
||||
|
||||
def execute(self) -> None:
|
||||
match self.format:
|
||||
case ExportFormat.JSON:
|
||||
with open(self.fn, "r") as f:
|
||||
try:
|
||||
values = json.load(f)
|
||||
values = [self.what.deserialize(v) for v in values]
|
||||
except json.JSONDecodeError as e:
|
||||
raise ImportFailedError(e)
|
||||
|
||||
case ExportFormat.pickle:
|
||||
raise AttributeError("pickle import not working at the moment!")
|
||||
with open(self.fn, "rb") as f:
|
||||
values = pickle.load(f)
|
||||
|
||||
self.__client.insert(values)
|
||||
|
||||
|
||||
class ImportFailedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BackupCommand(Command):
|
||||
def __init__(self, client: Client, fn: Path, format: ExportFormat) -> None:
|
||||
self.__client = client
|
||||
self.fn = fn
|
||||
self.format = format
|
||||
|
||||
def execute(self) -> None:
|
||||
banks = self.__client.select(Bank)
|
||||
groups = self.__client.select(CategoryGroup)
|
||||
categories = self.__client.select(Category)
|
||||
tags = self.__client.select(Tag)
|
||||
transactions = self.__client.select(Transaction)
|
||||
|
||||
values = [*banks, *groups, *categories, *tags, *transactions]
|
||||
|
||||
match self.format:
|
||||
case ExportFormat.JSON:
|
||||
with open(self.fn, "w", newline="") as f:
|
||||
json.dump([e.serialize() for e in values], f, indent=4)
|
||||
case ExportFormat.pickle:
|
||||
raise AttributeError("pickle export not working at the moment!")
|
||||
|
||||
|
||||
class ImportBackupCommand(Command):
|
||||
def __init__(self, client: Client, fn: Path, format: ExportFormat) -> None:
|
||||
self.__client = client
|
||||
self.fn = fn
|
||||
self.format = format
|
||||
|
||||
def execute(self) -> None:
|
||||
match self.format:
|
||||
case ExportFormat.JSON:
|
||||
with open(self.fn, "r") as f:
|
||||
try:
|
||||
values = json.load(f)
|
||||
values = [
|
||||
getattr(pfbudget.db.model, v["class_"]).deserialize(v)
|
||||
for v in values
|
||||
]
|
||||
except json.JSONDecodeError as e:
|
||||
raise ImportFailedError(e)
|
||||
|
||||
case ExportFormat.pickle:
|
||||
raise AttributeError("pickle import not working at the moment!")
|
||||
|
||||
self.__client.insert(values)
|
||||
@ -1,47 +1,411 @@
|
||||
from pfbudget.input.input import Input
|
||||
from pfbudget.input.parsers import parse_data
|
||||
from pfbudget.common.types import Bank, Banks, Transaction, Transactions
|
||||
from pfbudget.db.client import DatabaseClient
|
||||
from pfbudget.utils import convert
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pickle
|
||||
from typing import Optional
|
||||
import webbrowser
|
||||
|
||||
from pfbudget.common.types import Operation
|
||||
from pfbudget.db.client import Client
|
||||
from pfbudget.db.model import (
|
||||
Bank,
|
||||
BankTransaction,
|
||||
Category,
|
||||
CategoryGroup,
|
||||
CategoryRule,
|
||||
CategorySchedule,
|
||||
Link,
|
||||
MoneyTransaction,
|
||||
NordigenBank,
|
||||
Rule,
|
||||
CategorySelector,
|
||||
SplitTransaction,
|
||||
Tag,
|
||||
TagRule,
|
||||
Transaction,
|
||||
TransactionCategory,
|
||||
)
|
||||
from pfbudget.extract.nordigen import NordigenClient, NordigenCredentialsManager
|
||||
from pfbudget.extract.parsers import parse_data
|
||||
from pfbudget.extract.psd2 import PSD2Extractor
|
||||
from pfbudget.load.database import DatabaseLoader
|
||||
from pfbudget.transform.categorizer import Categorizer
|
||||
from pfbudget.transform.nullifier import Nullifier
|
||||
from pfbudget.transform.tagger import Tagger
|
||||
|
||||
|
||||
class Manager:
|
||||
def __init__(self, db: str):
|
||||
self.__db = db
|
||||
def __init__(self, db: str, verbosity: int = 0):
|
||||
self._db = db
|
||||
self._database: Optional[Client] = None
|
||||
self._verbosity = verbosity
|
||||
|
||||
def init(self):
|
||||
client = DatabaseClient(self.__db)
|
||||
client.init()
|
||||
def action(self, op: Operation, params=None):
|
||||
if self._verbosity > 0:
|
||||
print(f"op={op}, params={params}")
|
||||
|
||||
def register(self, args: dict):
|
||||
bank = Bank(args["bank"][0], "", args["requisition"][0], args["invert"])
|
||||
client = DatabaseClient(self.__db)
|
||||
client.register_bank(convert(bank))
|
||||
if params is None:
|
||||
params = []
|
||||
|
||||
def unregister(self, args: dict):
|
||||
client = DatabaseClient(self.__db)
|
||||
client.unregister_bank(args["bank"][0])
|
||||
|
||||
def parser(self, parser: Input):
|
||||
transactions = parser.parse()
|
||||
self.add_transactions(transactions)
|
||||
|
||||
def parse(self, filename: str, args: dict):
|
||||
transactions = parse_data(filename, args)
|
||||
self.add_transactions(transactions)
|
||||
|
||||
def transactions() -> list[Transaction]:
|
||||
match (op):
|
||||
case Operation.Init:
|
||||
pass
|
||||
|
||||
def add_transactions(self, transactions: Transactions):
|
||||
client = DatabaseClient(self.__db)
|
||||
client.insert_transactions([convert(t) for t in transactions])
|
||||
case Operation.Transactions:
|
||||
return [t.format for t in self.database.select(Transaction)]
|
||||
|
||||
def get_bank_by(self, key: str, value: str) -> Bank:
|
||||
client = DatabaseClient(self.__db)
|
||||
bank = client.get_bank(key, value)
|
||||
return convert(bank)
|
||||
case Operation.Parse:
|
||||
# Adapter for the parse_data method. Can be refactored.
|
||||
args = {"bank": params[1], "creditcard": params[2], "category": None}
|
||||
transactions = []
|
||||
for path in [Path(p) for p in params[0]]:
|
||||
if path.is_dir():
|
||||
for file in path.iterdir():
|
||||
transactions.extend(self.parse(file, args))
|
||||
elif path.is_file():
|
||||
transactions.extend(self.parse(path, args))
|
||||
else:
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
def get_banks(self) -> Banks:
|
||||
client = DatabaseClient(self.__db)
|
||||
return [convert(bank) for bank in client.get_banks()]
|
||||
if (
|
||||
len(transactions) > 0
|
||||
and input(f"{transactions[:5]}\nCommit? (y/n)") == "y"
|
||||
):
|
||||
self.database.insert(sorted(transactions))
|
||||
|
||||
case Operation.Download:
|
||||
if params[3]:
|
||||
values = params[3]
|
||||
banks = self.database.select(Bank, lambda: Bank.name.in_(values))
|
||||
else:
|
||||
banks = self.database.select(Bank, Bank.nordigen)
|
||||
|
||||
extractor = PSD2Extractor(self.nordigen_client())
|
||||
|
||||
transactions = []
|
||||
for bank in banks:
|
||||
transactions.extend(extractor.extract(bank, params[0], params[1]))
|
||||
|
||||
# dry-run
|
||||
if params[2]:
|
||||
print(sorted(transactions))
|
||||
return
|
||||
|
||||
loader = DatabaseLoader(self.database)
|
||||
loader.load(sorted(transactions))
|
||||
|
||||
case Operation.Categorize:
|
||||
with self.database.session as session:
|
||||
uncategorized = session.select(
|
||||
BankTransaction, lambda: ~BankTransaction.category.has()
|
||||
)
|
||||
categories = session.select(Category)
|
||||
tags = session.select(Tag)
|
||||
|
||||
rules = [
|
||||
rule
|
||||
for cat in categories
|
||||
if cat.name == "null"
|
||||
for rule in cat.rules
|
||||
]
|
||||
Nullifier(rules).transform_inplace(uncategorized)
|
||||
|
||||
rules = [
|
||||
rule
|
||||
for cat in categories
|
||||
if cat.name != "null"
|
||||
for rule in cat.rules
|
||||
]
|
||||
Categorizer(rules).transform_inplace(uncategorized)
|
||||
|
||||
rules = [rule for tag in tags for rule in tag.rules]
|
||||
Tagger(rules).transform_inplace(uncategorized)
|
||||
|
||||
case Operation.BankMod:
|
||||
self.database.update(Bank, params)
|
||||
|
||||
case Operation.PSD2Mod:
|
||||
self.database.update(NordigenBank, params)
|
||||
|
||||
case Operation.BankDel:
|
||||
self.database.delete(Bank, Bank.name, params)
|
||||
|
||||
case Operation.PSD2Del:
|
||||
self.database.delete(NordigenBank, NordigenBank.name, params)
|
||||
|
||||
case Operation.RequisitionId:
|
||||
bank_name = params[0]
|
||||
bank = self.database.select(Bank, (lambda: Bank.name == bank_name))[0]
|
||||
|
||||
if not bank.nordigen or not bank.nordigen.bank_id:
|
||||
raise ValueError(f"{bank} doesn't have a Nordigen ID")
|
||||
|
||||
link, req_id = self.nordigen_client().new_requisition(
|
||||
bank.nordigen.bank_id
|
||||
)
|
||||
|
||||
self.database.update(
|
||||
NordigenBank,
|
||||
[{"name": bank.nordigen.name, "requisition_id": req_id}],
|
||||
)
|
||||
|
||||
webbrowser.open(link)
|
||||
|
||||
case Operation.PSD2CountryBanks:
|
||||
banks = self.nordigen_client().country_banks(params[0])
|
||||
print(banks)
|
||||
|
||||
case (
|
||||
Operation.BankAdd
|
||||
| Operation.CategoryAdd
|
||||
| Operation.GroupAdd
|
||||
| Operation.PSD2Add
|
||||
| Operation.RuleAdd
|
||||
| Operation.TagAdd
|
||||
| Operation.TagRuleAdd
|
||||
):
|
||||
self.database.insert(params)
|
||||
|
||||
case Operation.CategoryUpdate:
|
||||
self.database.update(Category, params)
|
||||
|
||||
case Operation.CategoryRemove:
|
||||
self.database.delete(Category, Category.name, params)
|
||||
|
||||
case Operation.CategorySchedule:
|
||||
raise NotImplementedError
|
||||
|
||||
case Operation.RuleRemove:
|
||||
self.database.delete(CategoryRule, CategoryRule.id, params)
|
||||
|
||||
case Operation.TagRemove:
|
||||
self.database.delete(Tag, Tag.name, params)
|
||||
|
||||
case Operation.TagRuleRemove:
|
||||
self.database.delete(TagRule, TagRule.id, params)
|
||||
|
||||
case Operation.RuleModify | Operation.TagRuleModify:
|
||||
self.database.update(Rule, params)
|
||||
|
||||
case Operation.GroupRemove:
|
||||
self.database.delete(CategoryGroup, CategoryGroup.name, params)
|
||||
|
||||
case Operation.Forge:
|
||||
if not (
|
||||
isinstance(params[0], int)
|
||||
and all(isinstance(p, int) for p in params[1])
|
||||
):
|
||||
raise TypeError("f{params} are not transaction ids")
|
||||
|
||||
with self.database.session as session:
|
||||
id = params[0]
|
||||
original = session.select(
|
||||
Transaction, lambda: Transaction.id == id
|
||||
)[0]
|
||||
|
||||
ids = params[1]
|
||||
links = session.select(Transaction, lambda: Transaction.id.in_(ids))
|
||||
|
||||
if not original.category:
|
||||
original.category = self.askcategory(original)
|
||||
|
||||
for link in links:
|
||||
if (
|
||||
not link.category
|
||||
or link.category.name != original.category.name
|
||||
):
|
||||
print(
|
||||
f"{link} category will change to"
|
||||
f" {original.category.name}"
|
||||
)
|
||||
link.category = original.category
|
||||
|
||||
tobelinked = [Link(original.id, link.id) for link in links]
|
||||
session.insert(tobelinked)
|
||||
|
||||
case Operation.Dismantle:
|
||||
raise NotImplementedError
|
||||
|
||||
case Operation.Split:
|
||||
if len(params) < 1 and not all(
|
||||
isinstance(p, Transaction) for p in params
|
||||
):
|
||||
raise TypeError(f"{params} are not transactions")
|
||||
|
||||
# t -> t1, t2, t3; t.value == Σti.value
|
||||
original: Transaction = params[0]
|
||||
if not original.amount == sum(t.amount for t in params[1:]):
|
||||
raise ValueError(
|
||||
f"{original.amount}€ != {sum(v for v, _ in params[1:])}€"
|
||||
)
|
||||
|
||||
with self.database.session as session:
|
||||
originals = session.select(
|
||||
Transaction, lambda: Transaction.id == original.id
|
||||
)
|
||||
assert len(originals) == 1, ">1 transactions matched {original.id}!"
|
||||
|
||||
originals[0].split = True
|
||||
transactions = []
|
||||
for t in params[1:]:
|
||||
if originals[0].date != t.date:
|
||||
t.date = originals[0].date
|
||||
print(
|
||||
f"{t.date} is different from original date"
|
||||
f" {originals[0].date}, using original"
|
||||
)
|
||||
|
||||
splitted = SplitTransaction(
|
||||
t.date, t.description, t.amount, originals[0].id
|
||||
)
|
||||
splitted.category = t.category
|
||||
transactions.append(splitted)
|
||||
|
||||
session.insert(transactions)
|
||||
|
||||
case Operation.Export:
|
||||
self.dump(params[0], params[1], self.database.select(Transaction))
|
||||
|
||||
case Operation.Import:
|
||||
transactions = []
|
||||
for row in self.load(params[0], params[1]):
|
||||
match row["type"]:
|
||||
case "bank":
|
||||
transaction = BankTransaction(
|
||||
row["date"],
|
||||
row["description"],
|
||||
row["amount"],
|
||||
row["bank"],
|
||||
)
|
||||
|
||||
case "money":
|
||||
transaction = MoneyTransaction(
|
||||
row["date"], row["description"], row["amount"]
|
||||
)
|
||||
|
||||
# TODO case "split" how to match to original transaction?? also
|
||||
# save ids?
|
||||
case _:
|
||||
continue
|
||||
|
||||
if category := row.pop("category", None):
|
||||
transaction.category = TransactionCategory(
|
||||
category["name"], category["selector"]["selector"]
|
||||
)
|
||||
|
||||
transactions.append(transaction)
|
||||
|
||||
if self.certify(transactions):
|
||||
self.database.insert(transactions)
|
||||
|
||||
case Operation.ExportBanks:
|
||||
self.dump(params[0], params[1], self.database.select(Bank))
|
||||
|
||||
case Operation.ImportBanks:
|
||||
banks = []
|
||||
for row in self.load(params[0], params[1]):
|
||||
bank = Bank(row["name"], row["BIC"], row["type"])
|
||||
if row["nordigen"]:
|
||||
bank.nordigen = NordigenBank(**row["nordigen"])
|
||||
banks.append(bank)
|
||||
|
||||
if self.certify(banks):
|
||||
self.database.insert(banks)
|
||||
|
||||
case Operation.ExportCategoryRules:
|
||||
self.dump(params[0], params[1], self.database.select(CategoryRule))
|
||||
|
||||
case Operation.ImportCategoryRules:
|
||||
rules = [CategoryRule(**row) for row in self.load(params[0], params[1])]
|
||||
|
||||
if self.certify(rules):
|
||||
self.database.insert(rules)
|
||||
|
||||
case Operation.ExportTagRules:
|
||||
self.dump(params[0], params[1], self.database.select(TagRule))
|
||||
|
||||
case Operation.ImportTagRules:
|
||||
rules = [TagRule(**row) for row in self.load(params[0], params[1])]
|
||||
|
||||
if self.certify(rules):
|
||||
self.database.insert(rules)
|
||||
|
||||
case Operation.ExportCategories:
|
||||
self.dump(params[0], params[1], self.database.select(Category))
|
||||
|
||||
case Operation.ImportCategories:
|
||||
# rules = [Category(**row) for row in self.load(params[0])]
|
||||
categories = []
|
||||
for row in self.load(params[0], params[1]):
|
||||
category = Category(row["name"], row["group"])
|
||||
if len(row["rules"]) > 0:
|
||||
# Only category rules could have been created with a rule
|
||||
rules = row["rules"]
|
||||
for rule in rules:
|
||||
del rule["type"]
|
||||
|
||||
category.rules = [CategoryRule(**rule) for rule in rules]
|
||||
if row["schedule"]:
|
||||
category.schedule = CategorySchedule(**row["schedule"])
|
||||
categories.append(category)
|
||||
|
||||
if self.certify(categories):
|
||||
self.database.insert(categories)
|
||||
|
||||
case Operation.ExportCategoryGroups:
|
||||
self.dump(params[0], params[1], self.database.select(CategoryGroup))
|
||||
|
||||
case Operation.ImportCategoryGroups:
|
||||
groups = [
|
||||
CategoryGroup(**row) for row in self.load(params[0], params[1])
|
||||
]
|
||||
|
||||
if self.certify(groups):
|
||||
self.database.insert(groups)
|
||||
|
||||
def parse(self, filename: Path, args: dict):
|
||||
return parse_data(filename, args)
|
||||
|
||||
def askcategory(self, transaction: Transaction):
|
||||
selector = CategorySelector.manual
|
||||
|
||||
categories = self.database.select(Category)
|
||||
|
||||
while True:
|
||||
category = input(f"{transaction}: ")
|
||||
if category in [c.name for c in categories]:
|
||||
return TransactionCategory(category, selector)
|
||||
|
||||
@staticmethod
|
||||
def dump(fn, format, sequence):
|
||||
if format == "pickle":
|
||||
with open(fn, "wb") as f:
|
||||
pickle.dump([e.format for e in sequence], f)
|
||||
elif format == "json":
|
||||
with open(fn, "w", newline="") as f:
|
||||
json.dump([e.format for e in sequence], f, indent=4, default=str)
|
||||
else:
|
||||
print("format not well specified")
|
||||
|
||||
@staticmethod
|
||||
def load(fn, format):
|
||||
if format == "pickle":
|
||||
with open(fn, "rb") as f:
|
||||
return pickle.load(f)
|
||||
else:
|
||||
print("format not well specified")
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def certify(imports: list) -> bool:
|
||||
if input(f"{imports[:10]}\nDoes the import seem correct? (y/n)") == "y":
|
||||
return True
|
||||
return False
|
||||
|
||||
@property
|
||||
def database(self) -> Client:
|
||||
if not self._database:
|
||||
self._database = Client(self._db, echo=self._verbosity > 2)
|
||||
return self._database
|
||||
|
||||
def nordigen_client(self) -> NordigenClient:
|
||||
return NordigenClient(NordigenCredentialsManager.default, self.database)
|
||||
|
||||
@ -1,212 +1,83 @@
|
||||
from __future__ import annotations
|
||||
from decimal import Decimal
|
||||
import csv
|
||||
import datetime
|
||||
import logging
|
||||
import logging.config
|
||||
import pathlib
|
||||
import sqlite3
|
||||
from collections.abc import Sequence
|
||||
from copy import deepcopy
|
||||
from sqlalchemy import Engine, create_engine, delete, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from typing import Any, Mapping, Optional, Type, TypeVar
|
||||
|
||||
from pfbudget.common.types import Transaction
|
||||
import pfbudget.db.schema as Q
|
||||
from pfbudget.db.exceptions import InsertError
|
||||
|
||||
|
||||
if not pathlib.Path("logs").is_dir():
|
||||
pathlib.Path("logs").mkdir()
|
||||
logging.config.fileConfig("logging.conf")
|
||||
logger = logging.getLogger("pfbudget.transactions")
|
||||
class DatabaseSession:
|
||||
def __init__(self, session: Session):
|
||||
self.__session = session
|
||||
|
||||
sqlite3.register_adapter(Decimal, lambda d: float(d))
|
||||
def __enter__(self):
|
||||
self.__session.begin()
|
||||
return self
|
||||
|
||||
__DB_NAME = "data.db"
|
||||
|
||||
|
||||
class DatabaseClient:
|
||||
"""SQLite DB connection manager"""
|
||||
|
||||
__EXPORT_DIR = "export"
|
||||
|
||||
def __init__(self, db: str):
|
||||
self.db = db
|
||||
|
||||
def __execute(self, query: str, params: tuple = None) -> list | None:
|
||||
ret = None
|
||||
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any):
|
||||
try:
|
||||
con = sqlite3.connect(self.db)
|
||||
with con:
|
||||
if params:
|
||||
ret = con.execute(query, params).fetchall()
|
||||
logger.debug(f"[{self.db}] < {query}{params}")
|
||||
if exc_type:
|
||||
self.__session.rollback()
|
||||
else:
|
||||
ret = con.execute(query).fetchall()
|
||||
logger.debug(f"[{self.db}] < {query}")
|
||||
|
||||
if ret:
|
||||
logger.debug(f"[{self.db}] > {ret}")
|
||||
except sqlite3.Error:
|
||||
logger.exception(f"Error while executing [{self.db}] < {query}")
|
||||
self.__session.commit()
|
||||
except IntegrityError as e:
|
||||
raise InsertError() from e
|
||||
finally:
|
||||
con.close()
|
||||
self.__session.close()
|
||||
|
||||
return ret
|
||||
def close(self):
|
||||
self.__session.close()
|
||||
|
||||
def __executemany(self, query: str, list_of_params: list[tuple]) -> list | None:
|
||||
ret = None
|
||||
try:
|
||||
con = sqlite3.connect(self.db)
|
||||
with con:
|
||||
ret = con.executemany(query, list_of_params).fetchall()
|
||||
logger.debug(f"[{self.db}] < {query}{list_of_params}")
|
||||
except sqlite3.Error:
|
||||
logger.exception(
|
||||
f"Error while executing [{self.db}] < {query} {list_of_params}"
|
||||
)
|
||||
finally:
|
||||
con.close()
|
||||
def insert(self, sequence: Sequence[Any]) -> None:
|
||||
self.__session.add_all(sequence)
|
||||
|
||||
return ret
|
||||
T = TypeVar("T")
|
||||
|
||||
def __create_tables(self, tables: tuple[tuple]):
|
||||
for table_name, query in tables:
|
||||
logger.info(f"Creating table {table_name} if it doesn't exist already")
|
||||
self.__execute(query)
|
||||
def select(self, what: Type[T], exists: Optional[Any] = None) -> Sequence[T]:
|
||||
if exists:
|
||||
stmt = select(what).filter(exists)
|
||||
else:
|
||||
stmt = select(what)
|
||||
|
||||
def init(self):
|
||||
logging.info(f"Initializing {self.db} database")
|
||||
self.__create_tables(
|
||||
(
|
||||
("transactions", Q.CREATE_TRANSACTIONS_TABLE),
|
||||
("backups", Q.CREATE_BACKUPS_TABLE),
|
||||
("banks", Q.CREATE_BANKS_TABLE),
|
||||
)
|
||||
)
|
||||
return self.__session.scalars(stmt).unique().all()
|
||||
|
||||
"""Transaction table methods"""
|
||||
def delete(self, obj: Any) -> None:
|
||||
self.__session.delete(obj)
|
||||
|
||||
def select_all(self) -> list[Transaction] | None:
|
||||
logger.info(f"Reading all transactions from {self.db}")
|
||||
transactions = self.__execute("SELECT * FROM transactions")
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def insert_transaction(self, transaction: Transaction):
|
||||
logger.info(f"Adding {transaction} into {self.db}")
|
||||
self.__execute(Q.ADD_TRANSACTION, (transaction.to_list(),))
|
||||
class Client:
|
||||
def __init__(self, url: str, **kwargs: Any):
|
||||
assert url, "Database URL is empty!"
|
||||
self._engine = create_engine(url, **kwargs)
|
||||
self._sessionmaker = sessionmaker(self._engine)
|
||||
|
||||
def insert_transactions(self, transactions: Q.DbTransactions):
|
||||
logger.info(f"Adding {len(transactions)} into {self.db}")
|
||||
self.__executemany(Q.ADD_TRANSACTION, [t.tuple() for t in transactions])
|
||||
def insert(self, sequence: Sequence[Any]) -> None:
|
||||
new = deepcopy(sequence)
|
||||
with self.session as session:
|
||||
session.insert(new)
|
||||
|
||||
def update_category(self, transaction: Transaction):
|
||||
logger.info(f"Update {transaction} category")
|
||||
self.__execute(Q.UPDATE_CATEGORY, transaction.update_category())
|
||||
T = TypeVar("T")
|
||||
|
||||
def update_categories(self, transactions: list[Transaction]):
|
||||
logger.info(f"Update {len(transactions)} transactions' categories")
|
||||
self.__executemany(
|
||||
Q.UPDATE_CATEGORY,
|
||||
[transaction.update_category() for transaction in transactions],
|
||||
)
|
||||
def select(self, what: Type[T], exists: Optional[Any] = None) -> Sequence[T]:
|
||||
session = self.session
|
||||
result = session.select(what, exists)
|
||||
session.close()
|
||||
return result
|
||||
|
||||
def get_duplicated_transactions(self) -> list[Transaction] | None:
|
||||
logger.info("Get duplicated transactions")
|
||||
transactions = self.__execute(Q.DUPLICATED_TRANSACTIONS)
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
def update(self, what: Type[Any], values: Sequence[Mapping[str, Any]]) -> None:
|
||||
with self._sessionmaker() as session, session.begin():
|
||||
session.execute(update(what), values)
|
||||
|
||||
def get_sorted_transactions(self) -> list[Transaction] | None:
|
||||
logger.info("Get transactions sorted by date")
|
||||
transactions = self.__execute(Q.SORTED_TRANSACTIONS)
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
def delete(self, what: Type[Any], column: Any, values: Sequence[Any]) -> None:
|
||||
with self._sessionmaker() as session, session.begin():
|
||||
session.execute(delete(what).where(column.in_(values)))
|
||||
|
||||
def get_daterange(self, start: datetime, end: datetime) -> list[Transaction] | None:
|
||||
logger.info(f"Get transactions from {start} to {end}")
|
||||
transactions = self.__execute(Q.SELECT_TRANSACTIONS_BETWEEN_DATES, (start, end))
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
@property
|
||||
def engine(self) -> Engine:
|
||||
return self._engine
|
||||
|
||||
def get_category(self, value: str) -> list[Transaction] | None:
|
||||
logger.info(f"Get transactions where category = {value}")
|
||||
transactions = self.__execute(Q.SELECT_TRANSACTIONS_BY_CATEGORY, (value,))
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def get_daterange_category(
|
||||
self, start: datetime, end: datetime, category: str
|
||||
) -> list[Transaction] | None:
|
||||
logger.info(
|
||||
f"Get transactions from {start} to {end} where category = {category}"
|
||||
)
|
||||
transactions = self.__execute(
|
||||
Q.SELECT_TRANSACTIONS_BETWEEN_DATES_WITH_CATEGORY, (start, end, category)
|
||||
)
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def get_by_period(self, period: str) -> list[Transaction] | None:
|
||||
logger.info(f"Get transactions by {period}")
|
||||
transactions = self.__execute(Q.SELECT_TRANSACTION_BY_PERIOD, period)
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def get_uncategorized_transactions(self) -> list[Transaction] | None:
|
||||
logger.debug("Get uncategorized transactions")
|
||||
return self.get_category(None)
|
||||
|
||||
def get_daterange_uncategorized_transactions(self, start: datetime, end: datetime):
|
||||
logger.debug("Get uncategorized transactions from {start} to {end}")
|
||||
return self.get_daterange_category(start, end, None)
|
||||
|
||||
def get_daterage_without(
|
||||
self, start: datetime, end: datetime, *categories: str
|
||||
) -> list[Transaction] | None:
|
||||
logger.info(f"Get transactions between {start} and {end} not in {categories}")
|
||||
query = Q.SELECT_TRANSACTIONS_BETWEEN_DATES_WITHOUT_CATEGORIES.format(
|
||||
"(" + ", ".join("?" for _ in categories) + ")"
|
||||
)
|
||||
transactions = self.__execute(query, (start, end, *categories))
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def export(self):
|
||||
filename = pathlib.Path(
|
||||
"@".join([self.db, datetime.datetime.now().isoformat()])
|
||||
).with_suffix(".csv")
|
||||
transactions = self.select_all()
|
||||
logger.info(f"Exporting {self.db} into {filename}")
|
||||
if not (dir := pathlib.Path(self.__EXPORT_DIR)).is_dir():
|
||||
dir.mkdir()
|
||||
with open(dir / filename, "w", newline="") as f:
|
||||
csv.writer(f, delimiter="\t").writerows(transactions)
|
||||
|
||||
"""Banks table methods"""
|
||||
|
||||
def register_bank(self, bank: Q.DbBank):
|
||||
logger.info(f"Registering {bank}")
|
||||
self.__execute(Q.ADD_BANK, bank.tuple())
|
||||
|
||||
def unregister_bank(self, bank: str):
|
||||
logger.info(f"Unregistering {bank}")
|
||||
self.__execute(Q.DELETE_BANK, (bank,))
|
||||
|
||||
def get_bank(self, key: str, value: str) -> Q.DbBank | None:
|
||||
logger.info(f"Get bank with {key} = {value}")
|
||||
bank = self.__execute(Q.SELECT_BANK.format(key), (value, ))
|
||||
if bank:
|
||||
return Q.DbBank(*bank[0])
|
||||
|
||||
def get_banks(self) -> Q.DbBanks:
|
||||
logger.info("Get all banks")
|
||||
banks = self.__execute(Q.SELECT_BANKS)
|
||||
if banks:
|
||||
return [Q.DbBank(*bank) for bank in banks]
|
||||
return []
|
||||
@property
|
||||
def session(self) -> DatabaseSession:
|
||||
return DatabaseSession(self._sessionmaker())
|
||||
|
||||
6
pfbudget/db/exceptions.py
Normal file
6
pfbudget/db/exceptions.py
Normal file
@ -0,0 +1,6 @@
|
||||
class InsertError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class SelectError(Exception):
|
||||
pass
|
||||
551
pfbudget/db/model.py
Normal file
551
pfbudget/db/model.py
Normal file
@ -0,0 +1,551 @@
|
||||
from __future__ import annotations
|
||||
from collections.abc import Mapping, MutableMapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
import datetime as dt
|
||||
import decimal
|
||||
import enum
|
||||
import re
|
||||
from typing import Annotated, Any, Callable, Optional, Self, cast
|
||||
|
||||
from sqlalchemy import (
|
||||
BigInteger,
|
||||
Enum,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
MetaData,
|
||||
Numeric,
|
||||
String,
|
||||
Text,
|
||||
)
|
||||
from sqlalchemy.orm import (
|
||||
DeclarativeBase,
|
||||
Mapped,
|
||||
mapped_column,
|
||||
MappedAsDataclass,
|
||||
relationship,
|
||||
)
|
||||
|
||||
|
||||
class Base(MappedAsDataclass, DeclarativeBase):
|
||||
metadata = MetaData(
|
||||
schema="pfbudget",
|
||||
naming_convention={
|
||||
"ix": "ix_%(column_0_label)s",
|
||||
"uq": "uq_%(table_name)s_%(column_0_name)s",
|
||||
"ck": "ck_%(table_name)s_`%(constraint_name)s`",
|
||||
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
||||
"pk": "pk_%(table_name)s",
|
||||
},
|
||||
)
|
||||
|
||||
type_annotation_map = {
|
||||
enum.Enum: Enum(enum.Enum, create_constraint=True, inherit_schema=True),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Serializable:
|
||||
def serialize(self) -> Mapping[str, Any]:
|
||||
return dict(class_=type(self).__name__)
|
||||
|
||||
@classmethod
|
||||
def deserialize(cls, map: Mapping[str, Any]) -> Self:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class AccountType(enum.Enum):
|
||||
checking = enum.auto()
|
||||
savings = enum.auto()
|
||||
investment = enum.auto()
|
||||
mealcard = enum.auto()
|
||||
VISA = enum.auto()
|
||||
MASTERCARD = enum.auto()
|
||||
|
||||
|
||||
class Bank(Base, Serializable):
|
||||
__tablename__ = "banks"
|
||||
|
||||
name: Mapped[str] = mapped_column(primary_key=True)
|
||||
BIC: Mapped[str] = mapped_column(String(8))
|
||||
type: Mapped[AccountType]
|
||||
|
||||
nordigen: Mapped[Optional[NordigenBank]] = relationship(default=None, lazy="joined")
|
||||
|
||||
def serialize(self) -> Mapping[str, Any]:
|
||||
nordigen = None
|
||||
if self.nordigen:
|
||||
nordigen = {
|
||||
"bank_id": self.nordigen.bank_id,
|
||||
"requisition_id": self.nordigen.requisition_id,
|
||||
"invert": self.nordigen.invert,
|
||||
}
|
||||
|
||||
return super().serialize() | dict(
|
||||
name=self.name,
|
||||
BIC=self.BIC,
|
||||
type=self.type.name,
|
||||
nordigen=nordigen,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def deserialize(cls, map: Mapping[str, Any]) -> Self:
|
||||
bank = cls(map["name"], map["BIC"], map["type"])
|
||||
if map["nordigen"]:
|
||||
bank.nordigen = NordigenBank(**map["nordigen"])
|
||||
return bank
|
||||
|
||||
|
||||
bankfk = Annotated[str, mapped_column(Text, ForeignKey(Bank.name))]
|
||||
|
||||
idpk = Annotated[
|
||||
int,
|
||||
mapped_column(
|
||||
BigInteger().with_variant(Integer, "sqlite"),
|
||||
primary_key=True,
|
||||
autoincrement=True,
|
||||
),
|
||||
]
|
||||
money = Annotated[decimal.Decimal, mapped_column(Numeric(16, 2))]
|
||||
|
||||
|
||||
class Transaction(Base, Serializable):
|
||||
__tablename__ = "transactions"
|
||||
|
||||
id: Mapped[idpk] = mapped_column(init=False)
|
||||
date: Mapped[dt.date]
|
||||
description: Mapped[Optional[str]]
|
||||
amount: Mapped[money]
|
||||
|
||||
split: Mapped[bool] = mapped_column(default=False)
|
||||
|
||||
category: Mapped[Optional[TransactionCategory]] = relationship(
|
||||
back_populates="transaction", default=None, lazy="joined"
|
||||
)
|
||||
tags: Mapped[set[TransactionTag]] = relationship(default_factory=set, lazy="joined")
|
||||
note: Mapped[Optional[Note]] = relationship(
|
||||
cascade="all, delete-orphan", passive_deletes=True, default=None, lazy="joined"
|
||||
)
|
||||
|
||||
type: Mapped[str] = mapped_column(init=False)
|
||||
__mapper_args__ = {"polymorphic_on": "type", "polymorphic_identity": "transaction"}
|
||||
|
||||
def serialize(self) -> Mapping[str, Any]:
|
||||
category = None
|
||||
if self.category:
|
||||
category = {
|
||||
"name": self.category.name,
|
||||
"selector": self.category.selector.name,
|
||||
}
|
||||
|
||||
return super().serialize() | dict(
|
||||
id=self.id,
|
||||
date=self.date.isoformat(),
|
||||
description=self.description,
|
||||
amount=str(self.amount),
|
||||
split=self.split,
|
||||
category=category if category else None,
|
||||
tags=[{"tag": tag.tag} for tag in self.tags],
|
||||
note={"note": self.note.note} if self.note else None,
|
||||
type=self.type,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def deserialize(
|
||||
cls, map: Mapping[str, Any]
|
||||
) -> Transaction | BankTransaction | MoneyTransaction | SplitTransaction:
|
||||
match map["type"]:
|
||||
case "bank":
|
||||
return BankTransaction.deserialize(map)
|
||||
case "money":
|
||||
return MoneyTransaction.deserialize(map)
|
||||
case "split":
|
||||
return SplitTransaction.deserialize(map)
|
||||
case _:
|
||||
return cls._deserialize(map)
|
||||
|
||||
@classmethod
|
||||
def _deserialize(cls, map: Mapping[str, Any]) -> Self:
|
||||
category = None
|
||||
if map["category"]:
|
||||
category = TransactionCategory(map["category"]["name"])
|
||||
if map["category"]["selector"]:
|
||||
category.selector = map["category"]["selector"]
|
||||
|
||||
tags: set[TransactionTag] = set()
|
||||
if map["tags"]:
|
||||
tags = set(TransactionTag(t["tag"]) for t in map["tags"])
|
||||
|
||||
note = None
|
||||
if map["note"]:
|
||||
note = Note(map["note"]["note"])
|
||||
|
||||
result = cls(
|
||||
dt.date.fromisoformat(map["date"]),
|
||||
map["description"],
|
||||
map["amount"],
|
||||
map["split"],
|
||||
category,
|
||||
tags,
|
||||
note,
|
||||
)
|
||||
|
||||
if map["id"]:
|
||||
result.id = map["id"]
|
||||
return result
|
||||
|
||||
def __lt__(self, other: Transaction):
|
||||
return self.date < other.date
|
||||
|
||||
|
||||
idfk = Annotated[
|
||||
int, mapped_column(BigInteger, ForeignKey(Transaction.id, ondelete="CASCADE"))
|
||||
]
|
||||
|
||||
|
||||
class BankTransaction(Transaction):
|
||||
bank: Mapped[Optional[bankfk]] = mapped_column(default=None)
|
||||
|
||||
__mapper_args__ = {"polymorphic_identity": "bank", "polymorphic_load": "inline"}
|
||||
|
||||
def serialize(self) -> Mapping[str, Any]:
|
||||
map = cast(MutableMapping[str, Any], super().serialize())
|
||||
map["bank"] = self.bank
|
||||
return map
|
||||
|
||||
@classmethod
|
||||
def deserialize(cls, map: Mapping[str, Any]) -> Self:
|
||||
transaction = cls._deserialize(map)
|
||||
transaction.bank = map["bank"]
|
||||
return transaction
|
||||
|
||||
|
||||
class MoneyTransaction(Transaction):
|
||||
__mapper_args__ = {"polymorphic_identity": "money"}
|
||||
|
||||
def serialize(self) -> Mapping[str, Any]:
|
||||
return super().serialize()
|
||||
|
||||
@classmethod
|
||||
def deserialize(cls, map: Mapping[str, Any]) -> Self:
|
||||
return cls._deserialize(map)
|
||||
|
||||
|
||||
class SplitTransaction(Transaction):
|
||||
original: Mapped[Optional[idfk]] = mapped_column(default=None)
|
||||
|
||||
__mapper_args__ = {"polymorphic_identity": "split", "polymorphic_load": "inline"}
|
||||
|
||||
def serialize(self) -> Mapping[str, Any]:
|
||||
map = cast(MutableMapping[str, Any], super().serialize())
|
||||
map["original"] = self.original
|
||||
return map
|
||||
|
||||
@classmethod
|
||||
def deserialize(cls, map: Mapping[str, Any]) -> Self:
|
||||
transaction = cls._deserialize(map)
|
||||
transaction.original = map["original"]
|
||||
return transaction
|
||||
|
||||
|
||||
class CategoryGroup(Base, Serializable):
|
||||
__tablename__ = "category_groups"
|
||||
|
||||
name: Mapped[str] = mapped_column(primary_key=True)
|
||||
|
||||
def serialize(self) -> Mapping[str, Any]:
|
||||
return super().serialize() | dict(name=self.name)
|
||||
|
||||
@classmethod
|
||||
def deserialize(cls, map: Mapping[str, Any]) -> Self:
|
||||
return cls(map["name"])
|
||||
|
||||
|
||||
class Category(Base, Serializable, repr=False):
|
||||
__tablename__ = "categories"
|
||||
|
||||
name: Mapped[str] = mapped_column(primary_key=True)
|
||||
group: Mapped[Optional[str]] = mapped_column(
|
||||
ForeignKey(CategoryGroup.name), default=None
|
||||
)
|
||||
|
||||
rules: Mapped[list[CategoryRule]] = relationship(
|
||||
cascade="all, delete-orphan",
|
||||
passive_deletes=True,
|
||||
default_factory=list,
|
||||
lazy="joined",
|
||||
)
|
||||
schedule: Mapped[Optional[CategorySchedule]] = relationship(
|
||||
cascade="all, delete-orphan", passive_deletes=True, default=None, lazy="joined"
|
||||
)
|
||||
|
||||
def serialize(self) -> Mapping[str, Any]:
|
||||
rules: Sequence[Mapping[str, Any]] = []
|
||||
for rule in self.rules:
|
||||
rules.append(
|
||||
{
|
||||
"start": rule.start.isoformat() if rule.start else None,
|
||||
"end": rule.end.isoformat() if rule.end else None,
|
||||
"description": rule.description,
|
||||
"regex": rule.regex,
|
||||
"bank": rule.bank,
|
||||
"min": str(rule.min) if rule.min is not None else None,
|
||||
"max": str(rule.max) if rule.max is not None else None,
|
||||
}
|
||||
)
|
||||
|
||||
schedule = None
|
||||
if self.schedule:
|
||||
schedule = {
|
||||
"period": self.schedule.period.name if self.schedule.period else None,
|
||||
"period_multiplier": self.schedule.period_multiplier,
|
||||
"amount": self.schedule.amount,
|
||||
}
|
||||
|
||||
return super().serialize() | dict(
|
||||
name=self.name,
|
||||
group=self.group,
|
||||
rules=rules,
|
||||
schedule=schedule,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def deserialize(cls, map: Mapping[str, Any]) -> Self:
|
||||
rules: list[CategoryRule] = []
|
||||
for rule in map["rules"]:
|
||||
rules.append(
|
||||
CategoryRule(
|
||||
dt.date.fromisoformat(rule["start"]) if rule["start"] else None,
|
||||
dt.date.fromisoformat(rule["end"]) if rule["end"] else None,
|
||||
rule["description"],
|
||||
rule["regex"],
|
||||
rule["bank"],
|
||||
rule["min"],
|
||||
rule["max"],
|
||||
)
|
||||
)
|
||||
|
||||
return cls(
|
||||
map["name"],
|
||||
map["group"],
|
||||
rules,
|
||||
CategorySchedule(**map["schedule"]) if map["schedule"] else None,
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"Category(name={self.name}, group={self.group}, #rules={len(self.rules)},"
|
||||
f" schedule={self.schedule})"
|
||||
)
|
||||
|
||||
|
||||
catfk = Annotated[
|
||||
str,
|
||||
mapped_column(ForeignKey(Category.name, ondelete="CASCADE")),
|
||||
]
|
||||
|
||||
|
||||
class CategorySelector(enum.Enum):
|
||||
unknown = enum.auto()
|
||||
nullifier = enum.auto()
|
||||
vacations = enum.auto()
|
||||
rules = enum.auto()
|
||||
algorithm = enum.auto()
|
||||
manual = enum.auto()
|
||||
|
||||
|
||||
class TransactionCategory(Base):
|
||||
__tablename__ = "transactions_categorized"
|
||||
|
||||
id: Mapped[idfk] = mapped_column(primary_key=True, init=False)
|
||||
name: Mapped[catfk]
|
||||
|
||||
selector: Mapped[CategorySelector] = mapped_column(default=CategorySelector.unknown)
|
||||
|
||||
transaction: Mapped[Transaction] = relationship(
|
||||
back_populates="category", init=False, compare=False
|
||||
)
|
||||
|
||||
|
||||
class Note(Base):
|
||||
__tablename__ = "notes"
|
||||
|
||||
id: Mapped[idfk] = mapped_column(primary_key=True, init=False)
|
||||
note: Mapped[str]
|
||||
|
||||
|
||||
class NordigenBank(Base):
|
||||
__tablename__ = "banks_nordigen"
|
||||
|
||||
name: Mapped[bankfk] = mapped_column(primary_key=True, init=False)
|
||||
bank_id: Mapped[Optional[str]]
|
||||
requisition_id: Mapped[Optional[str]]
|
||||
invert: Mapped[Optional[bool]] = mapped_column(default=None)
|
||||
|
||||
|
||||
class Tag(Base, Serializable):
|
||||
__tablename__ = "tags"
|
||||
|
||||
name: Mapped[str] = mapped_column(primary_key=True)
|
||||
|
||||
rules: Mapped[list[TagRule]] = relationship(
|
||||
cascade="all, delete-orphan",
|
||||
passive_deletes=True,
|
||||
default_factory=list,
|
||||
lazy="joined",
|
||||
)
|
||||
|
||||
def serialize(self) -> Mapping[str, Any]:
|
||||
rules: Sequence[Mapping[str, Any]] = []
|
||||
for rule in self.rules:
|
||||
rules.append(
|
||||
{
|
||||
"start": rule.start,
|
||||
"end": rule.end,
|
||||
"description": rule.description,
|
||||
"regex": rule.regex,
|
||||
"bank": rule.bank,
|
||||
"min": str(rule.min) if rule.min is not None else None,
|
||||
"max": str(rule.max) if rule.max is not None else None,
|
||||
}
|
||||
)
|
||||
|
||||
return super().serialize() | dict(name=self.name, rules=rules)
|
||||
|
||||
@classmethod
|
||||
def deserialize(cls, map: Mapping[str, Any]) -> Self:
|
||||
rules: list[TagRule] = []
|
||||
for rule in map["rules"]:
|
||||
rules.append(
|
||||
TagRule(
|
||||
dt.date.fromisoformat(rule["start"]) if rule["start"] else None,
|
||||
dt.date.fromisoformat(rule["end"]) if rule["end"] else None,
|
||||
rule["description"],
|
||||
rule["regex"],
|
||||
rule["bank"],
|
||||
rule["min"],
|
||||
rule["max"],
|
||||
)
|
||||
)
|
||||
|
||||
return cls(map["name"], rules)
|
||||
|
||||
|
||||
class TransactionTag(Base, unsafe_hash=True):
|
||||
__tablename__ = "transactions_tagged"
|
||||
|
||||
id: Mapped[idfk] = mapped_column(primary_key=True, init=False)
|
||||
tag: Mapped[str] = mapped_column(ForeignKey(Tag.name), primary_key=True)
|
||||
|
||||
|
||||
class SchedulePeriod(enum.Enum):
|
||||
daily = enum.auto()
|
||||
weekly = enum.auto()
|
||||
monthly = enum.auto()
|
||||
yearly = enum.auto()
|
||||
|
||||
|
||||
class CategorySchedule(Base):
|
||||
__tablename__ = "category_schedules"
|
||||
|
||||
name: Mapped[catfk] = mapped_column(primary_key=True, init=False)
|
||||
period: Mapped[Optional[SchedulePeriod]]
|
||||
period_multiplier: Mapped[Optional[int]]
|
||||
amount: Mapped[Optional[int]]
|
||||
|
||||
|
||||
class Link(Base):
|
||||
__tablename__ = "links"
|
||||
|
||||
original: Mapped[idfk] = mapped_column(primary_key=True)
|
||||
link: Mapped[idfk] = mapped_column(primary_key=True)
|
||||
|
||||
|
||||
class Rule(Base):
|
||||
__tablename__ = "rules"
|
||||
|
||||
id: Mapped[idpk] = mapped_column(init=False)
|
||||
start: Mapped[Optional[dt.date]] = mapped_column(default=None)
|
||||
end: Mapped[Optional[dt.date]] = mapped_column(default=None)
|
||||
description: Mapped[Optional[str]] = mapped_column(default=None)
|
||||
regex: Mapped[Optional[str]] = mapped_column(default=None)
|
||||
bank: Mapped[Optional[str]] = mapped_column(default=None)
|
||||
min: Mapped[Optional[money]] = mapped_column(default=None)
|
||||
max: Mapped[Optional[money]] = mapped_column(default=None)
|
||||
|
||||
type: Mapped[str] = mapped_column(init=False)
|
||||
|
||||
__mapper_args__ = {
|
||||
"polymorphic_identity": "rule",
|
||||
"polymorphic_on": "type",
|
||||
}
|
||||
|
||||
def matches(self, t: BankTransaction) -> bool:
|
||||
valid = None
|
||||
if self.regex:
|
||||
valid = re.compile(self.regex, re.IGNORECASE)
|
||||
|
||||
ops = (
|
||||
Rule.exists(self.start, lambda r: t.date >= r),
|
||||
Rule.exists(self.end, lambda r: t.date <= r),
|
||||
Rule.exists(self.description, lambda r: r == t.description),
|
||||
Rule.exists(
|
||||
valid,
|
||||
lambda r: r.search(t.description) if t.description else False,
|
||||
),
|
||||
Rule.exists(self.bank, lambda r: r == t.bank),
|
||||
Rule.exists(self.min, lambda r: t.amount >= r),
|
||||
Rule.exists(self.max, lambda r: t.amount <= r),
|
||||
)
|
||||
|
||||
if all(ops):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def exists(r: Optional[Any], op: Callable[[Any], bool]) -> bool:
|
||||
return op(r) if r is not None else True
|
||||
|
||||
|
||||
class CategoryRule(Rule):
|
||||
__tablename__ = "category_rules"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey(Rule.id, ondelete="CASCADE"),
|
||||
primary_key=True,
|
||||
init=False,
|
||||
)
|
||||
name: Mapped[catfk] = mapped_column(init=False)
|
||||
|
||||
__mapper_args__ = {
|
||||
"polymorphic_identity": "category_rule",
|
||||
"polymorphic_load": "selectin",
|
||||
}
|
||||
|
||||
|
||||
class TagRule(Rule):
|
||||
__tablename__ = "tag_rules"
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey(Rule.id, ondelete="CASCADE"),
|
||||
primary_key=True,
|
||||
init=False,
|
||||
)
|
||||
tag: Mapped[str] = mapped_column(
|
||||
ForeignKey(Tag.name, ondelete="CASCADE"), init=False
|
||||
)
|
||||
|
||||
__mapper_args__ = {
|
||||
"polymorphic_identity": "tag_rule",
|
||||
"polymorphic_load": "selectin",
|
||||
}
|
||||
|
||||
|
||||
class Nordigen(Base):
|
||||
__tablename__ = "nordigen"
|
||||
|
||||
type: Mapped[str] = mapped_column(primary_key=True)
|
||||
token: Mapped[str]
|
||||
expires: Mapped[dt.datetime]
|
||||
@ -141,7 +141,8 @@ ORDER BY date ASC
|
||||
"""
|
||||
|
||||
ADD_BANK = """
|
||||
INSERT INTO banks (name, bic, nordigen_id, nordigen_name, requisition_id, invert) values (?,?,?,?,?,?)
|
||||
INSERT INTO banks (name, bic, nordigen_id, nordigen_name, requisition_id, invert)
|
||||
values (?,?,?,?,?,?)
|
||||
"""
|
||||
|
||||
DELETE_BANK = """
|
||||
|
||||
212
pfbudget/db/sqlite.py
Normal file
212
pfbudget/db/sqlite.py
Normal file
@ -0,0 +1,212 @@
|
||||
from __future__ import annotations
|
||||
from decimal import Decimal
|
||||
import csv
|
||||
import datetime
|
||||
import logging
|
||||
import logging.config
|
||||
import pathlib
|
||||
import sqlite3
|
||||
|
||||
from pfbudget.common.types import Transaction
|
||||
import pfbudget.db.schema as Q
|
||||
|
||||
|
||||
if not pathlib.Path("logs").is_dir():
|
||||
pathlib.Path("logs").mkdir()
|
||||
logging.config.fileConfig("logging.conf")
|
||||
logger = logging.getLogger("pfbudget.transactions")
|
||||
|
||||
sqlite3.register_adapter(Decimal, lambda d: float(d))
|
||||
|
||||
__DB_NAME = "data.db"
|
||||
|
||||
|
||||
class DatabaseClient:
|
||||
"""SQLite DB connection manager"""
|
||||
|
||||
__EXPORT_DIR = "export"
|
||||
|
||||
def __init__(self, db: str):
|
||||
self.db = db
|
||||
|
||||
def __execute(self, query: str, params: tuple = None) -> list | None:
|
||||
ret = None
|
||||
try:
|
||||
con = sqlite3.connect(self.db)
|
||||
with con:
|
||||
if params:
|
||||
ret = con.execute(query, params).fetchall()
|
||||
logger.debug(f"[{self.db}] < {query}{params}")
|
||||
else:
|
||||
ret = con.execute(query).fetchall()
|
||||
logger.debug(f"[{self.db}] < {query}")
|
||||
|
||||
if ret:
|
||||
logger.debug(f"[{self.db}] > {ret}")
|
||||
except sqlite3.Error:
|
||||
logger.exception(f"Error while executing [{self.db}] < {query}")
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
return ret
|
||||
|
||||
def __executemany(self, query: str, list_of_params: list[tuple]) -> list | None:
|
||||
ret = None
|
||||
try:
|
||||
con = sqlite3.connect(self.db)
|
||||
with con:
|
||||
ret = con.executemany(query, list_of_params).fetchall()
|
||||
logger.debug(f"[{self.db}] < {query}{list_of_params}")
|
||||
except sqlite3.Error:
|
||||
logger.exception(
|
||||
f"Error while executing [{self.db}] < {query} {list_of_params}"
|
||||
)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
return ret
|
||||
|
||||
def __create_tables(self, tables: tuple[tuple]):
|
||||
for table_name, query in tables:
|
||||
logger.info(f"Creating table {table_name} if it doesn't exist already")
|
||||
self.__execute(query)
|
||||
|
||||
def init(self):
|
||||
logging.info(f"Initializing {self.db} database")
|
||||
self.__create_tables(
|
||||
(
|
||||
("transactions", Q.CREATE_TRANSACTIONS_TABLE),
|
||||
("backups", Q.CREATE_BACKUPS_TABLE),
|
||||
("banks", Q.CREATE_BANKS_TABLE),
|
||||
)
|
||||
)
|
||||
|
||||
"""Transaction table methods"""
|
||||
|
||||
def select_all(self) -> list[Transaction] | None:
|
||||
logger.info(f"Reading all transactions from {self.db}")
|
||||
transactions = self.__execute("SELECT * FROM transactions")
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def insert_transaction(self, transaction: Transaction):
|
||||
logger.info(f"Adding {transaction} into {self.db}")
|
||||
self.__execute(Q.ADD_TRANSACTION, (transaction.to_list(),))
|
||||
|
||||
def insert_transactions(self, transactions: Q.DbTransactions):
|
||||
logger.info(f"Adding {len(transactions)} into {self.db}")
|
||||
self.__executemany(Q.ADD_TRANSACTION, [t.tuple() for t in transactions])
|
||||
|
||||
def update_category(self, transaction: Transaction):
|
||||
logger.info(f"Update {transaction} category")
|
||||
self.__execute(Q.UPDATE_CATEGORY, transaction.update_category())
|
||||
|
||||
def update_categories(self, transactions: list[Transaction]):
|
||||
logger.info(f"Update {len(transactions)} transactions' categories")
|
||||
self.__executemany(
|
||||
Q.UPDATE_CATEGORY,
|
||||
[transaction.update_category() for transaction in transactions],
|
||||
)
|
||||
|
||||
def get_duplicated_transactions(self) -> list[Transaction] | None:
|
||||
logger.info("Get duplicated transactions")
|
||||
transactions = self.__execute(Q.DUPLICATED_TRANSACTIONS)
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def get_sorted_transactions(self) -> list[Transaction] | None:
|
||||
logger.info("Get transactions sorted by date")
|
||||
transactions = self.__execute(Q.SORTED_TRANSACTIONS)
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def get_daterange(self, start: datetime, end: datetime) -> list[Transaction] | None:
|
||||
logger.info(f"Get transactions from {start} to {end}")
|
||||
transactions = self.__execute(Q.SELECT_TRANSACTIONS_BETWEEN_DATES, (start, end))
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def get_category(self, value: str) -> list[Transaction] | None:
|
||||
logger.info(f"Get transactions where category = {value}")
|
||||
transactions = self.__execute(Q.SELECT_TRANSACTIONS_BY_CATEGORY, (value,))
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def get_daterange_category(
|
||||
self, start: datetime, end: datetime, category: str
|
||||
) -> list[Transaction] | None:
|
||||
logger.info(
|
||||
f"Get transactions from {start} to {end} where category = {category}"
|
||||
)
|
||||
transactions = self.__execute(
|
||||
Q.SELECT_TRANSACTIONS_BETWEEN_DATES_WITH_CATEGORY, (start, end, category)
|
||||
)
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def get_by_period(self, period: str) -> list[Transaction] | None:
|
||||
logger.info(f"Get transactions by {period}")
|
||||
transactions = self.__execute(Q.SELECT_TRANSACTION_BY_PERIOD, period)
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def get_uncategorized_transactions(self) -> list[Transaction] | None:
|
||||
logger.debug("Get uncategorized transactions")
|
||||
return self.get_category(None)
|
||||
|
||||
def get_daterange_uncategorized_transactions(self, start: datetime, end: datetime):
|
||||
logger.debug("Get uncategorized transactions from {start} to {end}")
|
||||
return self.get_daterange_category(start, end, None)
|
||||
|
||||
def get_daterage_without(
|
||||
self, start: datetime, end: datetime, *categories: str
|
||||
) -> list[Transaction] | None:
|
||||
logger.info(f"Get transactions between {start} and {end} not in {categories}")
|
||||
query = Q.SELECT_TRANSACTIONS_BETWEEN_DATES_WITHOUT_CATEGORIES.format(
|
||||
"(" + ", ".join("?" for _ in categories) + ")"
|
||||
)
|
||||
transactions = self.__execute(query, (start, end, *categories))
|
||||
if transactions:
|
||||
return [Transaction(t) for t in transactions]
|
||||
return None
|
||||
|
||||
def export(self):
|
||||
filename = pathlib.Path(
|
||||
"@".join([self.db, datetime.datetime.now().isoformat()])
|
||||
).with_suffix(".csv")
|
||||
transactions = self.select_all()
|
||||
logger.info(f"Exporting {self.db} into {filename}")
|
||||
if not (dir := pathlib.Path(self.__EXPORT_DIR)).is_dir():
|
||||
dir.mkdir()
|
||||
with open(dir / filename, "w", newline="") as f:
|
||||
csv.writer(f, delimiter="\t").writerows(transactions)
|
||||
|
||||
"""Banks table methods"""
|
||||
|
||||
def register_bank(self, bank: Q.DbBank):
|
||||
logger.info(f"Registering {bank}")
|
||||
self.__execute(Q.ADD_BANK, bank.tuple())
|
||||
|
||||
def unregister_bank(self, bank: str):
|
||||
logger.info(f"Unregistering {bank}")
|
||||
self.__execute(Q.DELETE_BANK, (bank,))
|
||||
|
||||
def get_bank(self, key: str, value: str) -> Q.DbBank | None:
|
||||
logger.info(f"Get bank with {key} = {value}")
|
||||
bank = self.__execute(Q.SELECT_BANK.format(key), (value, ))
|
||||
if bank:
|
||||
return Q.DbBank(*bank[0])
|
||||
|
||||
def get_banks(self) -> Q.DbBanks:
|
||||
logger.info("Get all banks")
|
||||
banks = self.__execute(Q.SELECT_BANKS)
|
||||
if banks:
|
||||
return [Q.DbBank(*bank) for bank in banks]
|
||||
return []
|
||||
18
pfbudget/extract/exceptions.py
Normal file
18
pfbudget/extract/exceptions.py
Normal file
@ -0,0 +1,18 @@
|
||||
class ExtractError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BankError(ExtractError):
|
||||
pass
|
||||
|
||||
|
||||
class PSD2ClientError(ExtractError):
|
||||
pass
|
||||
|
||||
|
||||
class CredentialsError(PSD2ClientError):
|
||||
pass
|
||||
|
||||
|
||||
class DownloadError(PSD2ClientError):
|
||||
pass
|
||||
13
pfbudget/extract/extract.py
Normal file
13
pfbudget/extract/extract.py
Normal file
@ -0,0 +1,13 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import date
|
||||
from typing import Sequence
|
||||
|
||||
from pfbudget.db.model import Bank, Transaction
|
||||
|
||||
|
||||
class Extractor(ABC):
|
||||
@abstractmethod
|
||||
def extract(
|
||||
self, bank: Bank, start: date = date.min, end: date = date.max
|
||||
) -> Sequence[Transaction]:
|
||||
raise NotImplementedError
|
||||
154
pfbudget/extract/nordigen.py
Normal file
154
pfbudget/extract/nordigen.py
Normal file
@ -0,0 +1,154 @@
|
||||
from dataclasses import dataclass
|
||||
import datetime as dt
|
||||
import dotenv
|
||||
import nordigen
|
||||
import os
|
||||
import requests
|
||||
import time
|
||||
from typing import Any, Optional, Sequence, Tuple
|
||||
import uuid
|
||||
|
||||
from pfbudget.db.client import Client
|
||||
from pfbudget.db.model import Nordigen
|
||||
|
||||
from .exceptions import CredentialsError, DownloadError
|
||||
|
||||
dotenv.load_dotenv()
|
||||
|
||||
|
||||
@dataclass
|
||||
class NordigenCredentials:
|
||||
id: str
|
||||
key: str
|
||||
|
||||
def valid(self) -> bool:
|
||||
return len(self.id) != 0 and len(self.key) != 0
|
||||
|
||||
|
||||
class NordigenClient:
|
||||
redirect_url = "https://murta.dev"
|
||||
|
||||
def __init__(self, credentials: NordigenCredentials, client: Client):
|
||||
if not credentials.valid():
|
||||
raise CredentialsError
|
||||
|
||||
self.__client = nordigen.NordigenClient(
|
||||
secret_key=credentials.key, secret_id=credentials.id, timeout=5
|
||||
)
|
||||
self.__client.token = self.__token(client)
|
||||
|
||||
def download(self, requisition_id) -> Sequence[dict[str, Any]]:
|
||||
try:
|
||||
requisition = self.__client.requisition.get_requisition_by_id(
|
||||
requisition_id
|
||||
)
|
||||
print(requisition)
|
||||
except requests.HTTPError as e:
|
||||
raise DownloadError(e)
|
||||
|
||||
transactions = []
|
||||
for acc in requisition["accounts"]:
|
||||
account = self.__client.account_api(acc)
|
||||
|
||||
retries = 0
|
||||
downloaded = None
|
||||
while retries < 3:
|
||||
try:
|
||||
downloaded = account.get_transactions()
|
||||
break
|
||||
except requests.ReadTimeout:
|
||||
retries += 1
|
||||
print(f"Request #{retries} timed-out, retrying in 1s")
|
||||
time.sleep(1)
|
||||
|
||||
if not downloaded:
|
||||
print(f"Couldn't download transactions for {account.get_metadata()}")
|
||||
continue
|
||||
|
||||
if (
|
||||
"transactions" not in downloaded
|
||||
or "booked" not in downloaded["transactions"]
|
||||
):
|
||||
print(f"{account} doesn't have transactions")
|
||||
continue
|
||||
|
||||
transactions.extend(downloaded["transactions"]["booked"])
|
||||
|
||||
return transactions
|
||||
|
||||
def dump(self, bank, downloaded):
|
||||
# @TODO log received JSON
|
||||
pass
|
||||
|
||||
def new_requisition(
|
||||
self,
|
||||
institution_id: str,
|
||||
max_historical_days: Optional[int] = None,
|
||||
access_valid_for_days: Optional[int] = None,
|
||||
) -> Tuple[str, str]:
|
||||
kwargs = {
|
||||
"max_historical_days": max_historical_days,
|
||||
"access_valid_for_days": access_valid_for_days,
|
||||
}
|
||||
kwargs = {k: v for k, v in kwargs.items() if v is not None}
|
||||
|
||||
req = self.__client.initialize_session(
|
||||
self.redirect_url, institution_id, str(uuid.uuid4()), **kwargs
|
||||
)
|
||||
return req.link, req.requisition_id
|
||||
|
||||
def country_banks(self, country: str):
|
||||
return self.__client.institution.get_institutions(country)
|
||||
|
||||
def __token(self, client: Client) -> str:
|
||||
with client.session as session:
|
||||
token = session.select(Nordigen)
|
||||
|
||||
def datetime(seconds: int) -> dt.datetime:
|
||||
return dt.datetime.now() + dt.timedelta(seconds=seconds)
|
||||
|
||||
if not len(token):
|
||||
print("First time nordigen token setup")
|
||||
new = self.__client.generate_token()
|
||||
session.insert(
|
||||
[
|
||||
Nordigen(
|
||||
"access",
|
||||
new["access"],
|
||||
datetime(new["access_expires"]),
|
||||
),
|
||||
Nordigen(
|
||||
"refresh",
|
||||
new["refresh"],
|
||||
datetime(new["refresh_expires"]),
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
return new["access"]
|
||||
|
||||
else:
|
||||
access = next(t for t in token if t.type == "access")
|
||||
refresh = next(t for t in token if t.type == "refresh")
|
||||
|
||||
if access.expires > dt.datetime.now():
|
||||
pass
|
||||
elif refresh.expires > dt.datetime.now():
|
||||
new = self.__client.exchange_token(refresh.token)
|
||||
access.token = new["access"]
|
||||
access.expires = datetime(new["access_expires"])
|
||||
else:
|
||||
new = self.__client.generate_token()
|
||||
access.token = new["access"]
|
||||
access.expires = datetime(new["access_expires"])
|
||||
refresh.token = new["refresh"]
|
||||
refresh.expires = datetime(new["refresh_expires"])
|
||||
|
||||
return access.token
|
||||
|
||||
|
||||
class NordigenCredentialsManager:
|
||||
default = NordigenCredentials(
|
||||
os.environ.get("SECRET_ID", ""),
|
||||
os.environ.get("SECRET_KEY", ""),
|
||||
)
|
||||
@ -1,56 +1,45 @@
|
||||
from collections import namedtuple
|
||||
from __future__ import annotations
|
||||
from decimal import Decimal
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
import datetime as dt
|
||||
from typing import Any, Callable, NamedTuple, Optional
|
||||
import yaml
|
||||
|
||||
from pfbudget.common.types import NoBankSelected, Transaction, Transactions
|
||||
from pfbudget.common.types import NoBankSelected
|
||||
from pfbudget.db.model import BankTransaction
|
||||
from pfbudget.utils import utils
|
||||
|
||||
Index = namedtuple(
|
||||
"Index", ["date", "text", "value", "negate"], defaults=[-1, -1, -1, False]
|
||||
)
|
||||
Options = namedtuple(
|
||||
"Options",
|
||||
[
|
||||
"encoding",
|
||||
"separator",
|
||||
"date_fmt",
|
||||
"start",
|
||||
"end",
|
||||
"debit",
|
||||
"credit",
|
||||
"additional_parser",
|
||||
"category",
|
||||
"VISA",
|
||||
"MasterCard",
|
||||
"AmericanExpress",
|
||||
],
|
||||
defaults=[
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
1,
|
||||
None,
|
||||
Index(),
|
||||
Index(),
|
||||
False,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
],
|
||||
)
|
||||
|
||||
class Index(NamedTuple):
|
||||
date: int = -1
|
||||
text: int = -1
|
||||
value: int = -1
|
||||
negate: bool = False
|
||||
|
||||
|
||||
def parse_data(filename: str, args: dict) -> Transactions:
|
||||
cfg: dict = yaml.safe_load(open("parsers.yaml"))
|
||||
class Options(NamedTuple):
|
||||
encoding: str
|
||||
separator: str
|
||||
date_fmt: str
|
||||
start: int = 1
|
||||
end: Optional[int] = None
|
||||
debit: Index = Index()
|
||||
credit: Index = Index()
|
||||
additional_parser: bool = False
|
||||
VISA: Optional[Options] = None
|
||||
MasterCard: Optional[Options] = None
|
||||
AmericanExpress: Optional[Options] = None
|
||||
|
||||
|
||||
def parse_data(filename: Path, args: dict[str, Any]) -> list[BankTransaction]:
|
||||
cfg: dict[str, Any] = yaml.safe_load(open("parsers.yaml"))
|
||||
assert (
|
||||
"Banks" in cfg
|
||||
), "parsers.yaml is missing the Banks section with the list of available banks"
|
||||
|
||||
if not args["bank"]:
|
||||
bank, creditcard = utils.find_credit_institution(
|
||||
bank, creditcard = utils.find_credit_institution( # type: ignore
|
||||
filename, cfg.get("Banks"), cfg.get("CreditCards")
|
||||
)
|
||||
else:
|
||||
@ -58,7 +47,7 @@ def parse_data(filename: str, args: dict) -> Transactions:
|
||||
creditcard = None if not args["creditcard"] else args["creditcard"][0]
|
||||
|
||||
try:
|
||||
options: dict = cfg[bank]
|
||||
options: dict[str, Any] = cfg[bank]
|
||||
except KeyError as e:
|
||||
banks = cfg["Banks"]
|
||||
raise NoBankSelected(f"{e} not a valid bank, try one of {banks}")
|
||||
@ -71,11 +60,8 @@ def parse_data(filename: str, args: dict) -> Transactions:
|
||||
raise NoBankSelected(f"{e} not a valid bank, try one of {creditcards}")
|
||||
bank += creditcard
|
||||
|
||||
if args["category"]:
|
||||
options["category"] = args["category"][0]
|
||||
|
||||
if options.get("additional_parser"):
|
||||
parser = getattr(import_module("pfbudget.input.parsers"), bank)
|
||||
parser = getattr(import_module("pfbudget.extract.parsers"), bank)
|
||||
transactions = parser(filename, bank, options).parse()
|
||||
else:
|
||||
transactions = Parser(filename, bank, options).parse()
|
||||
@ -84,7 +70,7 @@ def parse_data(filename: str, args: dict) -> Transactions:
|
||||
|
||||
|
||||
class Parser:
|
||||
def __init__(self, filename: str, bank: str, options: dict):
|
||||
def __init__(self, filename: Path, bank: str, options: dict[str, Any]):
|
||||
self.filename = filename
|
||||
self.bank = bank
|
||||
|
||||
@ -95,10 +81,10 @@ class Parser:
|
||||
|
||||
self.options = Options(**options)
|
||||
|
||||
def func(self, transaction: Transaction):
|
||||
def func(self, transaction: BankTransaction):
|
||||
pass
|
||||
|
||||
def parse(self) -> list[Transaction]:
|
||||
def parse(self) -> list[BankTransaction]:
|
||||
transactions = [
|
||||
Parser.transaction(line, self.bank, self.options, self.func)
|
||||
for line in list(open(self.filename, encoding=self.options.encoding))[
|
||||
@ -109,7 +95,8 @@ class Parser:
|
||||
return transactions
|
||||
|
||||
@staticmethod
|
||||
def index(line: list, options: Options) -> Index:
|
||||
def index(line: list[str], options: Options) -> Index:
|
||||
index = None
|
||||
if options.debit.date != -1 and options.credit.date != -1:
|
||||
if options.debit.value != options.credit.value:
|
||||
if line[options.debit.value]:
|
||||
@ -136,49 +123,57 @@ class Parser:
|
||||
else:
|
||||
raise IndexError("No debit not credit indexes available")
|
||||
|
||||
return index
|
||||
return index if index else Index()
|
||||
|
||||
@staticmethod
|
||||
def transaction(line: str, bank: str, options: Options, func) -> Transaction:
|
||||
line = line.rstrip().split(options.separator)
|
||||
def transaction(
|
||||
line_: str, bank: str, options: Options, func: Callable[[BankTransaction], None]
|
||||
) -> BankTransaction:
|
||||
line = line_.rstrip().split(options.separator)
|
||||
index = Parser.index(line, options)
|
||||
|
||||
date = (
|
||||
dt.datetime.strptime(line[index.date].strip(), options.date_fmt)
|
||||
.date()
|
||||
.isoformat()
|
||||
)
|
||||
try:
|
||||
date_str = line[index.date].strip()
|
||||
date = dt.datetime.strptime(date_str, options.date_fmt).date()
|
||||
|
||||
text = line[index.text]
|
||||
|
||||
value = utils.parse_decimal(line[index.value])
|
||||
if index.negate:
|
||||
value = -value
|
||||
|
||||
if options.category:
|
||||
category = line[options.category]
|
||||
transaction = Transaction(date, text, bank, value, category)
|
||||
else:
|
||||
transaction = Transaction(date, text, bank, value, options.category)
|
||||
transaction = BankTransaction(date, text, value, bank=bank)
|
||||
|
||||
if options.additional_parser:
|
||||
func(transaction)
|
||||
|
||||
return transaction
|
||||
|
||||
except IndexError:
|
||||
raise IndexError(line_)
|
||||
|
||||
|
||||
class Bank1(Parser):
|
||||
def __init__(self, filename: str, bank: str, options: dict):
|
||||
def __init__(self, filename: Path, bank: str, options: dict[str, Any]):
|
||||
super().__init__(filename, bank, options)
|
||||
self.transfers = []
|
||||
self.transfers: list[dt.date] = []
|
||||
self.transaction_cost = -Decimal("1")
|
||||
|
||||
def func(self, transaction: Transaction):
|
||||
if "transf" in transaction.description.lower() and transaction.value < 0:
|
||||
transaction.value -= self.transaction_cost
|
||||
def func(self, transaction: BankTransaction):
|
||||
if (
|
||||
transaction.description
|
||||
and "transf" in transaction.description.lower()
|
||||
and transaction.amount < 0
|
||||
):
|
||||
transaction.amount -= self.transaction_cost
|
||||
self.transfers.append(transaction.date)
|
||||
|
||||
def parse(self) -> list:
|
||||
def parse(self) -> list[BankTransaction]:
|
||||
transactions = super().parse()
|
||||
for date in self.transfers:
|
||||
transactions.append(
|
||||
Transaction(date, "Transaction cost", self.bank, self.transaction_cost)
|
||||
BankTransaction(
|
||||
date, "Transaction cost", self.transaction_cost, bank=self.bank
|
||||
)
|
||||
)
|
||||
return transactions
|
||||
38
pfbudget/extract/psd2.py
Normal file
38
pfbudget/extract/psd2.py
Normal file
@ -0,0 +1,38 @@
|
||||
from datetime import date
|
||||
from typing import Sequence
|
||||
|
||||
from pfbudget.db.model import Bank, BankTransaction
|
||||
from pfbudget.utils.converters import convert
|
||||
|
||||
from .exceptions import BankError, DownloadError, ExtractError
|
||||
from .extract import Extractor
|
||||
from .nordigen import NordigenClient
|
||||
|
||||
|
||||
class PSD2Extractor(Extractor):
|
||||
def __init__(self, client: NordigenClient):
|
||||
self.__client = client
|
||||
|
||||
def extract(
|
||||
self, bank: Bank, start: date = date.min, end: date = date.max
|
||||
) -> Sequence[BankTransaction]:
|
||||
if not bank.nordigen:
|
||||
raise BankError("Bank doesn't have Nordigen info")
|
||||
|
||||
try:
|
||||
print(f"Downloading from {bank}...")
|
||||
downloaded = self.__client.download(bank.nordigen.requisition_id)
|
||||
except DownloadError as e:
|
||||
print(f"There was an issue downloading from {bank.name}\n{e}")
|
||||
raise ExtractError(e)
|
||||
|
||||
self.__client.dump(bank, downloaded)
|
||||
|
||||
return [
|
||||
t
|
||||
for t in self.convert(bank, downloaded, start, end)
|
||||
if start <= t.date <= end
|
||||
]
|
||||
|
||||
def convert(self, bank, downloaded, start, end):
|
||||
return [convert(t, bank) for t in downloaded]
|
||||
@ -1,21 +0,0 @@
|
||||
from __future__ import annotations
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from pfbudget.common.types import Transactions
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pfbudget.core.manager import Manager
|
||||
|
||||
|
||||
class Input(ABC):
|
||||
def __init__(self, manager: Manager):
|
||||
self._manager = manager
|
||||
|
||||
@abstractmethod
|
||||
def parse(self) -> Transactions:
|
||||
return NotImplemented
|
||||
|
||||
@property
|
||||
def manager(self):
|
||||
return self._manager
|
||||
@ -1,30 +0,0 @@
|
||||
import json
|
||||
|
||||
from .input import Input
|
||||
from pfbudget.common.types import Transactions
|
||||
from pfbudget.utils import convert, parse_decimal
|
||||
|
||||
|
||||
class JsonParser(Input):
|
||||
def __init__(self, manager, options):
|
||||
super().__init__(manager)
|
||||
self.options = options
|
||||
|
||||
def parse(self) -> Transactions:
|
||||
try:
|
||||
with open(self.options["json"][0], "r") as f:
|
||||
return [
|
||||
convert(
|
||||
[
|
||||
t["bookingDate"],
|
||||
t["remittanceInformationUnstructured"],
|
||||
self.options["bank"][0],
|
||||
parse_decimal(t["transactionAmount"]["amount"])
|
||||
if not self.options["invert"]
|
||||
else -parse_decimal(t["transactionAmount"]["amount"]),
|
||||
],
|
||||
)
|
||||
for t in json.load(f)["transactions"]["booked"]
|
||||
]
|
||||
except KeyError:
|
||||
print("No json file defined")
|
||||
@ -1,127 +0,0 @@
|
||||
from datetime import date
|
||||
from time import sleep
|
||||
from requests import HTTPError, ReadTimeout
|
||||
from dotenv import load_dotenv
|
||||
from nordigen import NordigenClient
|
||||
from uuid import uuid4
|
||||
import json
|
||||
import os
|
||||
import webbrowser
|
||||
|
||||
from .input import Input
|
||||
from pfbudget.common.types import NoBankSelected, Transactions
|
||||
from pfbudget.utils import convert
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class NordigenInput(Input):
|
||||
def __init__(self, manager, options: dict = {}, start=date.min, end=date.max):
|
||||
super().__init__(manager)
|
||||
self._client = NordigenClient(
|
||||
secret_key=os.environ.get("SECRET_KEY"),
|
||||
secret_id=os.environ.get("SECRET_ID"),
|
||||
)
|
||||
|
||||
self.client.token = self.__token()
|
||||
|
||||
# print(options)
|
||||
|
||||
if "all" in options and options["all"]:
|
||||
self.__banks = self.manager.get_banks()
|
||||
elif "id" in options and options["id"]:
|
||||
self.__banks = [
|
||||
self.manager.get_bank_by("nordigen_id", b) for b in options["id"]
|
||||
]
|
||||
elif "name" in options and options["name"]:
|
||||
self.__banks = [
|
||||
self.manager.get_bank_by("name", b) for b in options["name"]
|
||||
]
|
||||
else:
|
||||
self.__banks = None
|
||||
|
||||
self.__from = start
|
||||
self.__to = end
|
||||
|
||||
def parse(self) -> Transactions:
|
||||
transactions = []
|
||||
if not self.__banks:
|
||||
raise NoBankSelected
|
||||
|
||||
for bank in self.__banks:
|
||||
print(f"Downloading from {bank}...")
|
||||
requisition = self.client.requisition.get_requisition_by_id(
|
||||
bank.requisition_id
|
||||
)
|
||||
|
||||
for acc in requisition["accounts"]:
|
||||
account = self._client.account_api(acc)
|
||||
|
||||
retries = 0
|
||||
downloaded = {}
|
||||
while retries < 3:
|
||||
try:
|
||||
downloaded = account.get_transactions()
|
||||
break
|
||||
except ReadTimeout:
|
||||
retries += 1
|
||||
print(f"Request #{retries} timed-out, retrying in 1s")
|
||||
sleep(1)
|
||||
except HTTPError as e:
|
||||
retries += 1
|
||||
print(f"Request #{retries} failed with {e}, retrying in 1s")
|
||||
sleep(1)
|
||||
|
||||
if not downloaded:
|
||||
print(f"Couldn't download transactions for {account}")
|
||||
continue
|
||||
|
||||
with open("json/" + bank.name + ".json", "w") as f:
|
||||
json.dump(downloaded, f)
|
||||
|
||||
converted = [
|
||||
convert(t, bank) for t in downloaded["transactions"]["booked"]
|
||||
]
|
||||
|
||||
transactions.extend(
|
||||
[t for t in converted if self.__from <= t.date <= self.__to]
|
||||
)
|
||||
|
||||
return transactions
|
||||
|
||||
def token(self):
|
||||
token = self._client.generate_token()
|
||||
print(f"New access token: {token}")
|
||||
return token
|
||||
|
||||
def requisition(self, institution: str, country: str = "PT"):
|
||||
link, _ = self.__requisition_id(institution, country)
|
||||
webbrowser.open(link)
|
||||
|
||||
def list(self, country: str):
|
||||
print(self._client.institution.get_institutions(country))
|
||||
|
||||
@property
|
||||
def client(self):
|
||||
return self._client
|
||||
|
||||
def __token(self):
|
||||
if token := os.environ.get("TOKEN"):
|
||||
return token
|
||||
else:
|
||||
token = self._client.generate_token()
|
||||
print(f"New access token: {token}")
|
||||
return token
|
||||
|
||||
def __requisition_id(self, i: str, c: str):
|
||||
id = self._client.institution.get_institution_id_by_name(
|
||||
country=c, institution=i
|
||||
)
|
||||
init = self._client.initialize_session(
|
||||
redirect_uri="https://murta.dev",
|
||||
institution_id=id,
|
||||
reference_id=str(uuid4()),
|
||||
)
|
||||
|
||||
print(f"{i}({c}) link: {init.link} and requisition ID: {init.requisition_id}")
|
||||
return (init.link, init.requisition_id)
|
||||
14
pfbudget/load/database.py
Normal file
14
pfbudget/load/database.py
Normal file
@ -0,0 +1,14 @@
|
||||
from typing import Sequence
|
||||
|
||||
from pfbudget.db.client import Client
|
||||
from pfbudget.db.model import Transaction
|
||||
|
||||
from .load import Loader
|
||||
|
||||
|
||||
class DatabaseLoader(Loader):
|
||||
def __init__(self, client: Client) -> None:
|
||||
self.client = client
|
||||
|
||||
def load(self, transactions: Sequence[Transaction]) -> None:
|
||||
self.client.insert(transactions)
|
||||
10
pfbudget/load/load.py
Normal file
10
pfbudget/load/load.py
Normal file
@ -0,0 +1,10 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Sequence
|
||||
|
||||
from pfbudget.db.model import Transaction
|
||||
|
||||
|
||||
class Loader(ABC):
|
||||
@abstractmethod
|
||||
def load(self, transactions: Sequence[Transaction]) -> None:
|
||||
raise NotImplementedError
|
||||
@ -9,7 +9,7 @@ import pfbudget.core.categories
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pfbudget.db.client import DatabaseClient
|
||||
from pfbudget.db.sqlite import DatabaseClient
|
||||
|
||||
|
||||
groups = pfbudget.core.categories.cfg["Groups"]
|
||||
|
||||
@ -6,7 +6,7 @@ import datetime as dt
|
||||
import pfbudget.core.categories
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pfbudget.db.client import DatabaseClient
|
||||
from pfbudget.db.sqlite import DatabaseClient
|
||||
|
||||
|
||||
def net(db: DatabaseClient, start: dt.date = dt.date.min, end: dt.date = dt.date.max):
|
||||
|
||||
38
pfbudget/transform/categorizer.py
Normal file
38
pfbudget/transform/categorizer.py
Normal file
@ -0,0 +1,38 @@
|
||||
from copy import deepcopy
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
from pfbudget.db.model import (
|
||||
CategoryRule,
|
||||
CategorySelector,
|
||||
Transaction,
|
||||
TransactionCategory,
|
||||
TransactionTag,
|
||||
)
|
||||
from .transform import Transformer
|
||||
|
||||
|
||||
class Categorizer(Transformer):
|
||||
def __init__(self, rules: Iterable[CategoryRule]):
|
||||
self.rules = rules
|
||||
|
||||
def transform(self, transactions: Sequence[Transaction]) -> Sequence[Transaction]:
|
||||
result = deepcopy(transactions)
|
||||
self.transform_inplace(result)
|
||||
|
||||
return result
|
||||
|
||||
def transform_inplace(self, transactions: Sequence[Transaction]) -> None:
|
||||
for rule in self.rules:
|
||||
for transaction in transactions:
|
||||
if not rule.matches(transaction):
|
||||
continue
|
||||
|
||||
if not transaction.category:
|
||||
transaction.category = TransactionCategory(
|
||||
rule.name, CategorySelector.rules
|
||||
)
|
||||
else:
|
||||
if not transaction.tags:
|
||||
transaction.tags = {TransactionTag(rule.name)}
|
||||
else:
|
||||
transaction.tags.add(TransactionTag(rule.name))
|
||||
2
pfbudget/transform/exceptions.py
Normal file
2
pfbudget/transform/exceptions.py
Normal file
@ -0,0 +1,2 @@
|
||||
class MoreThanOneMatchError(Exception):
|
||||
pass
|
||||
96
pfbudget/transform/nullifier.py
Normal file
96
pfbudget/transform/nullifier.py
Normal file
@ -0,0 +1,96 @@
|
||||
from copy import deepcopy
|
||||
import datetime as dt
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
from .exceptions import MoreThanOneMatchError
|
||||
from .transform import Transformer
|
||||
from pfbudget.db.model import (
|
||||
CategorySelector,
|
||||
Transaction,
|
||||
TransactionCategory,
|
||||
)
|
||||
|
||||
|
||||
class Nullifier(Transformer):
|
||||
NULL_DAYS = 4
|
||||
|
||||
def __init__(self, rules=None):
|
||||
self.rules = rules if rules else []
|
||||
|
||||
def transform(self, transactions: Iterable[Transaction]) -> Sequence[Transaction]:
|
||||
"""transform
|
||||
|
||||
Find transactions that nullify each others, e.g. transfers between banks or
|
||||
between bank and credit cards.
|
||||
|
||||
Args:
|
||||
transactions (Sequence[Transaction]): sequence of transactions
|
||||
|
||||
Raises:
|
||||
MoreThanOneMatchError: if there is more than a match for a single transation
|
||||
|
||||
Returns:
|
||||
Sequence[Transaction]: nullified sequence of transactions
|
||||
"""
|
||||
|
||||
result = sorted(deepcopy(transactions))
|
||||
|
||||
for i, transaction in enumerate(result[:-1]):
|
||||
if matches := [t for t in result[i + 1 :] if self._cancels(transaction, t)]:
|
||||
if len(matches) > 1:
|
||||
raise MoreThanOneMatchError(f"{transaction} -> {matches}")
|
||||
|
||||
match = matches[0]
|
||||
|
||||
transaction = self._nullify(transaction)
|
||||
match = self._nullify(match)
|
||||
|
||||
return result
|
||||
|
||||
def transform_inplace(self, transactions: Iterable[Transaction]) -> None:
|
||||
"""transform_inplace
|
||||
|
||||
Find transactions that nullify each others, e.g. transfers between banks or
|
||||
between bank and credit cards.
|
||||
|
||||
Args:
|
||||
transactions (Sequence[Transaction]): sequence of transactions that will be
|
||||
modified inplace
|
||||
|
||||
Raises:
|
||||
MoreThanOneMatchError: if there is more than a match for a single transation
|
||||
"""
|
||||
|
||||
for transaction in sorted(transactions):
|
||||
if matches := [t for t in transactions if self._cancels(transaction, t)]:
|
||||
if len(matches) > 1:
|
||||
raise MoreThanOneMatchError(f"{transaction} -> {matches}")
|
||||
|
||||
match = matches[0]
|
||||
|
||||
self._nullify(transaction)
|
||||
self._nullify(match)
|
||||
|
||||
def _cancels(self, transaction: Transaction, cancel: Transaction):
|
||||
return (
|
||||
transaction.date
|
||||
<= cancel.date
|
||||
<= transaction.date + dt.timedelta(days=self.NULL_DAYS)
|
||||
and cancel != transaction
|
||||
and cancel.bank != transaction.bank
|
||||
and cancel.amount == -transaction.amount
|
||||
# even though this class receives uncategorized transactions, they may have
|
||||
# already been nullified before reaching here
|
||||
and not transaction.category
|
||||
and (not cancel.category or cancel.category.name != "null")
|
||||
and (
|
||||
any(r.matches(transaction) for r in self.rules) if self.rules else True
|
||||
)
|
||||
and (any(r.matches(cancel) for r in self.rules) if self.rules else True)
|
||||
)
|
||||
|
||||
def _nullify(self, transaction: Transaction) -> Transaction:
|
||||
transaction.category = TransactionCategory(
|
||||
"null", selector=CategorySelector.nullifier
|
||||
)
|
||||
return transaction
|
||||
30
pfbudget/transform/tagger.py
Normal file
30
pfbudget/transform/tagger.py
Normal file
@ -0,0 +1,30 @@
|
||||
from copy import deepcopy
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
from pfbudget.db.model import TagRule, Transaction, TransactionTag
|
||||
from .transform import Transformer
|
||||
|
||||
|
||||
class Tagger(Transformer):
|
||||
def __init__(self, rules: Iterable[TagRule]):
|
||||
self.rules = rules
|
||||
|
||||
def transform(self, transactions: Sequence[Transaction]) -> Sequence[Transaction]:
|
||||
result = deepcopy(transactions)
|
||||
self.transform_inplace(result)
|
||||
|
||||
return result
|
||||
|
||||
def transform_inplace(self, transactions: Sequence[Transaction]) -> None:
|
||||
for rule in self.rules:
|
||||
for transaction in transactions:
|
||||
if rule.tag in [tag.tag for tag in transaction.tags]:
|
||||
continue
|
||||
|
||||
if not rule.matches(transaction):
|
||||
continue
|
||||
|
||||
if not transaction.tags:
|
||||
transaction.tags = {TransactionTag(rule.tag)}
|
||||
else:
|
||||
transaction.tags.add(TransactionTag(rule.tag))
|
||||
14
pfbudget/transform/transform.py
Normal file
14
pfbudget/transform/transform.py
Normal file
@ -0,0 +1,14 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Sequence
|
||||
|
||||
from pfbudget.db.model import Transaction
|
||||
|
||||
|
||||
class Transformer(ABC):
|
||||
@abstractmethod
|
||||
def transform(self, transactions: Sequence[Transaction]) -> Sequence[Transaction]:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def transform_inplace(self, transactions: Sequence[Transaction]) -> None:
|
||||
raise NotImplementedError
|
||||
@ -1,2 +0,0 @@
|
||||
from .converters import convert
|
||||
from .utils import *
|
||||
@ -1,71 +1,30 @@
|
||||
from datetime import timedelta
|
||||
from functools import singledispatch
|
||||
import datetime as dt
|
||||
import functools
|
||||
from typing import Any
|
||||
|
||||
from pfbudget.common.types import TransactionError
|
||||
import pfbudget.db.model as t
|
||||
|
||||
from pfbudget.common.types import Bank, Transaction, TransactionError
|
||||
from pfbudget.db.schema import DbBank, DbTransaction
|
||||
from .utils import parse_decimal
|
||||
|
||||
|
||||
@singledispatch
|
||||
def convert(t):
|
||||
print("No converter as been found")
|
||||
@functools.singledispatch
|
||||
def convert(t) -> Any:
|
||||
print("No converter has been found")
|
||||
pass
|
||||
|
||||
|
||||
@convert.register
|
||||
def _(t: Transaction) -> DbTransaction:
|
||||
return DbTransaction(
|
||||
t.date,
|
||||
t.description,
|
||||
t.bank,
|
||||
t.value,
|
||||
t.category,
|
||||
t.original,
|
||||
t.additional_comment,
|
||||
)
|
||||
|
||||
|
||||
@convert.register
|
||||
def _(db: DbTransaction) -> Transaction:
|
||||
def _(json: dict, bank: t.Bank) -> t.BankTransaction | None:
|
||||
i = -1 if bank.nordigen and bank.nordigen.invert else 1
|
||||
try:
|
||||
return Transaction(db)
|
||||
except TransactionError:
|
||||
print(f"{db} is in the wrong format")
|
||||
|
||||
|
||||
@convert.register
|
||||
def _(db: DbBank, key: str = "") -> Bank:
|
||||
bank = Bank(db.name, db.bic, db.requisition_id, db.invert, db.offset, key=key)
|
||||
if not bank.invert:
|
||||
bank.invert = False
|
||||
if not bank.offset:
|
||||
bank.offset = 0
|
||||
return bank
|
||||
|
||||
|
||||
@convert.register
|
||||
def _(bank: Bank) -> DbBank:
|
||||
bank = DbBank(
|
||||
bank.name, bank.bic, "", "", bank.requisition_id, bank.invert, bank.offset
|
||||
transaction = t.BankTransaction(
|
||||
date=dt.date.fromisoformat(json["bookingDate"]),
|
||||
description=json["remittanceInformationUnstructured"],
|
||||
bank=bank.name,
|
||||
amount=i * parse_decimal(json["transactionAmount"]["amount"]),
|
||||
)
|
||||
if not bank.invert:
|
||||
bank.invert = False
|
||||
if not bank.offset:
|
||||
bank.offset = 0
|
||||
return bank
|
||||
|
||||
|
||||
@convert.register
|
||||
def _(json: dict, bank: Bank) -> Transaction:
|
||||
i = -1 if bank.invert else 1
|
||||
try:
|
||||
transaction = Transaction(
|
||||
json["bookingDate"],
|
||||
json["remittanceInformationUnstructured"],
|
||||
bank.name,
|
||||
i * parse_decimal(json["transactionAmount"]["amount"]),
|
||||
)
|
||||
transaction.date += timedelta(days=bank.offset)
|
||||
# transaction.date += timedelta(days=bank.offset)
|
||||
return transaction
|
||||
|
||||
except TransactionError:
|
||||
|
||||
@ -59,21 +59,21 @@ def find_credit_institution(fn, banks, creditcards):
|
||||
return bank, cc
|
||||
|
||||
|
||||
def parse_args_period(args):
|
||||
def parse_args_period(args: dict):
|
||||
start, end = date.min, date.max
|
||||
if args.start:
|
||||
start = datetime.strptime(args.start[0], "%Y/%m/%d").date()
|
||||
if args["start"]:
|
||||
start = datetime.strptime(args["start"][0], "%Y/%m/%d").date()
|
||||
|
||||
if args.end:
|
||||
end = datetime.strptime(args.end[0], "%Y/%m/%d").date()
|
||||
if args["end"]:
|
||||
end = datetime.strptime(args["end"][0], "%Y/%m/%d").date()
|
||||
|
||||
if args.interval:
|
||||
start = datetime.strptime(args.interval[0], "%Y/%m/%d").date()
|
||||
end = datetime.strptime(args.interval[1], "%Y/%m/%d").date()
|
||||
if args["interval"]:
|
||||
start = datetime.strptime(args["interval"][0], "%Y/%m/%d").date()
|
||||
end = datetime.strptime(args["interval"][1], "%Y/%m/%d").date()
|
||||
|
||||
if args.year:
|
||||
start = datetime.strptime(args.year[0], "%Y").date()
|
||||
end = datetime.strptime(str(int(args.year[0]) + 1), "%Y").date() - timedelta(
|
||||
if args["year"]:
|
||||
start = datetime.strptime(args["year"][0], "%Y").date()
|
||||
end = datetime.strptime(str(int(args["year"][0]) + 1), "%Y").date() - timedelta(
|
||||
days=1
|
||||
)
|
||||
|
||||
|
||||
1411
poetry.lock
generated
Normal file
1411
poetry.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
43
pyproject.toml
Normal file
43
pyproject.toml
Normal file
@ -0,0 +1,43 @@
|
||||
[tool.poetry]
|
||||
name = "pf-budget"
|
||||
version = "0.2.0"
|
||||
description = "A budgeting tool for those who want full control and transparency over their finances."
|
||||
authors = ["Luís Murta <luis@murta.dev>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
readme = "README.md"
|
||||
packages = [{include = "pfbudget"}]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.11"
|
||||
codetiming = "^1.4.0"
|
||||
matplotlib = "^3.7.1"
|
||||
nordigen = "^1.3.1"
|
||||
psycopg2 = "^2.9.6"
|
||||
python-dateutil = "^2.8.2"
|
||||
python-dotenv = "^1.0.0"
|
||||
pyyaml = "^6.0"
|
||||
sqlalchemy = "^2.0.9"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
alembic = "^1.10.3"
|
||||
black = "^23.3.0"
|
||||
flake8 = "^6.0.0"
|
||||
mypy = "^1.2.0"
|
||||
pytest = "^7.3.0"
|
||||
pytest-cov = "^4.0.0"
|
||||
pytest-mock = "^3.10.0"
|
||||
sqlalchemy = {extras = ["mypy"], version = "^2.0.9"}
|
||||
ruff = "^0.0.267"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = ". tests"
|
||||
|
||||
[pytest]
|
||||
mock_use_standalone_module = true
|
||||
|
||||
[tool.mypy]
|
||||
plugins = "sqlalchemy.ext.mypy.plugin"
|
||||
@ -1,5 +0,0 @@
|
||||
matplotlib==3.6.1
|
||||
nordigen==1.3.0
|
||||
python-dateutil==2.8.2
|
||||
python-dotenv==0.21.0
|
||||
PyYAML==6.0
|
||||
@ -1,4 +0,0 @@
|
||||
[flake8]
|
||||
ignore = E203, E501, W503
|
||||
max-line-length = 88
|
||||
enable-extensions = TC, TC1
|
||||
8
tests/mocks/banks.py
Normal file
8
tests/mocks/banks.py
Normal file
@ -0,0 +1,8 @@
|
||||
from pfbudget.db.model import AccountType, Bank, NordigenBank
|
||||
|
||||
|
||||
checking = Bank(
|
||||
"bank", "BANK", AccountType.checking, NordigenBank("bank_id", "requisition_id")
|
||||
)
|
||||
|
||||
cc = Bank("cc", "CC", AccountType.MASTERCARD)
|
||||
21
tests/mocks/categories.py
Normal file
21
tests/mocks/categories.py
Normal file
@ -0,0 +1,21 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from pfbudget.db.model import Category, CategoryGroup, CategoryRule, Tag, TagRule
|
||||
|
||||
category_null = Category("null")
|
||||
|
||||
categorygroup1 = CategoryGroup("group#1")
|
||||
|
||||
category1 = Category(
|
||||
"cat#1",
|
||||
"group#1",
|
||||
rules=[CategoryRule(description="desc#1", max=Decimal(0))],
|
||||
)
|
||||
|
||||
category2 = Category(
|
||||
"cat#2",
|
||||
"group#1",
|
||||
rules=[CategoryRule(description="desc#1", max=Decimal(0))],
|
||||
)
|
||||
|
||||
tag_1 = Tag("tag#1", rules=[TagRule(description="desc#1", max=Decimal(0))])
|
||||
22
tests/mocks/client.py
Normal file
22
tests/mocks/client.py
Normal file
@ -0,0 +1,22 @@
|
||||
import datetime as dt
|
||||
|
||||
from pfbudget.db.client import Client
|
||||
from pfbudget.db.model import Base, Nordigen
|
||||
|
||||
|
||||
class MockClient(Client):
|
||||
now = dt.datetime.now()
|
||||
|
||||
def __init__(self):
|
||||
url = "sqlite://"
|
||||
super().__init__(
|
||||
url, execution_options={"schema_translate_map": {"pfbudget": None}}
|
||||
)
|
||||
Base.metadata.create_all(self.engine)
|
||||
|
||||
self.insert(
|
||||
[
|
||||
Nordigen("access", "token#1", self.now + dt.timedelta(days=1)),
|
||||
Nordigen("refresh", "token#2", self.now + dt.timedelta(days=30)),
|
||||
]
|
||||
)
|
||||
146
tests/mocks/nordigen.py
Normal file
146
tests/mocks/nordigen.py
Normal file
@ -0,0 +1,146 @@
|
||||
from typing import Any, Dict, List, Optional
|
||||
import nordigen
|
||||
from nordigen.types.http_enums import HTTPMethod
|
||||
from nordigen.types.types import RequisitionDto, TokenType
|
||||
|
||||
from pfbudget.extract.nordigen import NordigenCredentials
|
||||
|
||||
|
||||
id = "3fa85f64-5717-4562-b3fc-2c963f66afa6"
|
||||
|
||||
accounts_id = {
|
||||
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
|
||||
"created": "2023-04-13T21:45:59.957Z",
|
||||
"last_accessed": "2023-04-13T21:45:59.957Z",
|
||||
"iban": "string",
|
||||
"institution_id": "string",
|
||||
"status": "DISCOVERED",
|
||||
"owner_name": "string",
|
||||
}
|
||||
|
||||
# The downloaded transactions match the simple and simple_transformed mocks
|
||||
accounts_id_transactions = {
|
||||
"transactions": {
|
||||
"booked": [
|
||||
{
|
||||
"transactionId": "string",
|
||||
"debtorName": "string",
|
||||
"debtorAccount": {"iban": "string"},
|
||||
"transactionAmount": {"currency": "string", "amount": "328.18"},
|
||||
"bankTransactionCode": "string",
|
||||
"bookingDate": "2023-01-14",
|
||||
"valueDate": "2023-01-15",
|
||||
"remittanceInformationUnstructured": "string",
|
||||
},
|
||||
{
|
||||
"transactionId": "string",
|
||||
"transactionAmount": {"currency": "string", "amount": "947.26"},
|
||||
"bankTransactionCode": "string",
|
||||
"bookingDate": "2023-02-14",
|
||||
"valueDate": "2023-02-15",
|
||||
"remittanceInformationUnstructured": "string",
|
||||
},
|
||||
],
|
||||
"pending": [
|
||||
{
|
||||
"transactionAmount": {"currency": "string", "amount": "float"},
|
||||
"valueDate": "2023-04-14",
|
||||
"remittanceInformationUnstructured": "string",
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
requisitions = {
|
||||
"count": 123,
|
||||
"next": "https://ob.nordigen.com/api/v2/requisitions/?limit=100&offset=0",
|
||||
"previous": "https://ob.nordigen.com/api/v2/requisitions/?limit=100&offset=0",
|
||||
"results": [
|
||||
{
|
||||
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
|
||||
"created": "2023-04-13T21:43:45.027Z",
|
||||
"redirect": "string",
|
||||
"status": "CR",
|
||||
"institution_id": "string",
|
||||
"agreement": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
|
||||
"reference": "string",
|
||||
"accounts": ["3fa85f64-5717-4562-b3fc-2c963f66afa6"],
|
||||
"user_language": "strin",
|
||||
"link": "https://ob.nordigen.com/psd2/start/3fa85f64-5717-4562-b3fc-2c963f66afa6/{$INSTITUTION_ID}",
|
||||
"ssn": "string",
|
||||
"account_selection": False,
|
||||
"redirect_immediate": False,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
requisitions_id = {
|
||||
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
|
||||
"created": "2023-04-13T21:45:12.336Z",
|
||||
"redirect": "string",
|
||||
"status": "CR",
|
||||
"institution_id": "string",
|
||||
"agreement": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
|
||||
"reference": "string",
|
||||
"accounts": ["3fa85f64-5717-4562-b3fc-2c963f66afa6"],
|
||||
"user_language": "strin",
|
||||
"link": "https://ob.nordigen.com/psd2/start/3fa85f64-5717-4562-b3fc-2c963f66afa6/{$INSTITUTION_ID}",
|
||||
"ssn": "string",
|
||||
"account_selection": False,
|
||||
"redirect_immediate": False,
|
||||
}
|
||||
|
||||
credentials = NordigenCredentials("ID", "KEY")
|
||||
|
||||
|
||||
class MockNordigenClient(nordigen.NordigenClient):
|
||||
def __init__(
|
||||
self,
|
||||
secret_key: str = "ID",
|
||||
secret_id: str = "KEY",
|
||||
timeout: int = 10,
|
||||
base_url: str = "https://ob.nordigen.com/api/v2",
|
||||
) -> None:
|
||||
super().__init__(secret_key, secret_id, timeout, base_url)
|
||||
|
||||
def generate_token(self) -> TokenType:
|
||||
return {
|
||||
"access": "access_token",
|
||||
"refresh": "refresh_token",
|
||||
"access_expires": 86400,
|
||||
"refresh_expires": 2592000,
|
||||
}
|
||||
|
||||
def exchange_token(self, refresh_token: str) -> TokenType:
|
||||
assert len(refresh_token) > 0, "invalid refresh token"
|
||||
return {
|
||||
"access": "access_token",
|
||||
"refresh": "refresh_token",
|
||||
"access_expires": 86400,
|
||||
"refresh_expires": 2592000,
|
||||
}
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: HTTPMethod,
|
||||
endpoint: str,
|
||||
data: Optional[Dict[str, Any]] = None,
|
||||
headers: Optional[Dict[str, Any]] = None,
|
||||
) -> Any:
|
||||
if endpoint == "requisitions/" + "requisition_id" + "/":
|
||||
return requisitions_id
|
||||
elif endpoint == "accounts/" + id + "/transactions/":
|
||||
return accounts_id_transactions
|
||||
else:
|
||||
raise NotImplementedError(endpoint)
|
||||
|
||||
def initialize_session(
|
||||
self,
|
||||
redirect_uri: str,
|
||||
institution_id: str,
|
||||
reference_id: str,
|
||||
max_historical_days: int = 90,
|
||||
access_valid_for_days: int = 90,
|
||||
access_scope: List[str] | None = None,
|
||||
) -> RequisitionDto:
|
||||
return RequisitionDto("http://random", "requisition_id")
|
||||
73
tests/mocks/transactions.py
Normal file
73
tests/mocks/transactions.py
Normal file
@ -0,0 +1,73 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from pfbudget.db.model import (
|
||||
BankTransaction,
|
||||
CategorySelector,
|
||||
MoneyTransaction,
|
||||
Note,
|
||||
SplitTransaction,
|
||||
Transaction,
|
||||
TransactionCategory,
|
||||
TransactionTag,
|
||||
)
|
||||
|
||||
# The simple and simple_transformed match the nordigen mocks
|
||||
simple = [
|
||||
BankTransaction(date(2023, 1, 14), "string", Decimal("328.18"), bank="bank"),
|
||||
BankTransaction(date(2023, 2, 14), "string", Decimal("947.26"), bank="bank"),
|
||||
]
|
||||
|
||||
simple_transformed = [
|
||||
BankTransaction(
|
||||
date(2023, 1, 14),
|
||||
"",
|
||||
Decimal("328.18"),
|
||||
bank="bank",
|
||||
category=TransactionCategory("category#1", CategorySelector.algorithm),
|
||||
),
|
||||
BankTransaction(
|
||||
date(2023, 2, 14),
|
||||
"",
|
||||
Decimal("947.26"),
|
||||
bank="bank",
|
||||
category=TransactionCategory("category#2", CategorySelector.algorithm),
|
||||
),
|
||||
]
|
||||
|
||||
bank = [
|
||||
BankTransaction(date(2023, 1, 1), "", Decimal("-10"), bank="bank#1"),
|
||||
BankTransaction(date(2023, 1, 1), "", Decimal("-10"), bank="bank#2"),
|
||||
]
|
||||
|
||||
money = [
|
||||
MoneyTransaction(date(2023, 1, 1), "", Decimal("-10")),
|
||||
MoneyTransaction(date(2023, 1, 1), "", Decimal("-10")),
|
||||
]
|
||||
|
||||
__original = Transaction(date(2023, 1, 1), "", Decimal("-10"), split=True)
|
||||
__original.id = 9000
|
||||
|
||||
split = [
|
||||
__original,
|
||||
SplitTransaction(date(2023, 1, 1), "", Decimal("-5"), original=__original.id),
|
||||
SplitTransaction(date(2023, 1, 1), "", Decimal("-5"), original=__original.id),
|
||||
]
|
||||
|
||||
tagged = [
|
||||
Transaction(
|
||||
date(2023, 1, 1),
|
||||
"",
|
||||
Decimal("-10"),
|
||||
tags={TransactionTag("tag#1"), TransactionTag("tag#1")},
|
||||
)
|
||||
]
|
||||
|
||||
noted = [
|
||||
Transaction(
|
||||
date(2023, 1, 1),
|
||||
"",
|
||||
Decimal("-10"),
|
||||
note=Note("note#1"),
|
||||
)
|
||||
]
|
||||
144
tests/test_backup.py
Normal file
144
tests/test_backup.py
Normal file
@ -0,0 +1,144 @@
|
||||
from pathlib import Path
|
||||
from typing import Any, Sequence, Type
|
||||
import pytest
|
||||
|
||||
from mocks import banks, categories, transactions
|
||||
from mocks.client import MockClient
|
||||
|
||||
from pfbudget.common.types import ExportFormat
|
||||
from pfbudget.core.command import (
|
||||
BackupCommand,
|
||||
ExportCommand,
|
||||
ImportBackupCommand,
|
||||
ImportCommand,
|
||||
ImportFailedError,
|
||||
)
|
||||
from pfbudget.db.client import Client
|
||||
from pfbudget.db.model import (
|
||||
Bank,
|
||||
BankTransaction,
|
||||
Base,
|
||||
Category,
|
||||
CategoryGroup,
|
||||
MoneyTransaction,
|
||||
Note,
|
||||
SplitTransaction,
|
||||
Tag,
|
||||
Transaction,
|
||||
TransactionCategory,
|
||||
TransactionTag,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> Client:
|
||||
return MockClient()
|
||||
|
||||
|
||||
params = [
|
||||
(transactions.simple, Transaction),
|
||||
(transactions.simple_transformed, Transaction),
|
||||
(transactions.bank, Transaction),
|
||||
(transactions.bank, BankTransaction),
|
||||
(transactions.money, Transaction),
|
||||
(transactions.money, MoneyTransaction),
|
||||
(transactions.split, SplitTransaction),
|
||||
([banks.checking, banks.cc], Bank),
|
||||
([categories.category_null, categories.category1, categories.category2], Category),
|
||||
(
|
||||
[
|
||||
categories.categorygroup1,
|
||||
categories.category_null,
|
||||
categories.category1,
|
||||
categories.category2,
|
||||
],
|
||||
CategoryGroup,
|
||||
),
|
||||
([categories.tag_1], Tag),
|
||||
]
|
||||
|
||||
not_serializable = [
|
||||
(transactions.simple_transformed, TransactionCategory),
|
||||
(transactions.tagged, TransactionTag),
|
||||
(transactions.noted, Note),
|
||||
]
|
||||
|
||||
|
||||
class TestBackup:
|
||||
@pytest.mark.parametrize("input, what", params)
|
||||
def test_import(self, tmp_path: Path, input: Sequence[Any], what: Type[Any]):
|
||||
file = tmp_path / "test.json"
|
||||
|
||||
client = MockClient()
|
||||
client.insert(input)
|
||||
originals = client.select(what)
|
||||
|
||||
assert originals
|
||||
|
||||
command = ExportCommand(client, what, file, ExportFormat.JSON)
|
||||
command.execute()
|
||||
|
||||
other = MockClient()
|
||||
command = ImportCommand(other, what, file, ExportFormat.JSON)
|
||||
command.execute()
|
||||
|
||||
imported = other.select(what)
|
||||
|
||||
assert originals == imported
|
||||
|
||||
command = ExportCommand(client, what, file, ExportFormat.pickle)
|
||||
with pytest.raises(AttributeError):
|
||||
command.execute()
|
||||
|
||||
command = ImportCommand(other, what, file, ExportFormat.pickle)
|
||||
with pytest.raises(AttributeError):
|
||||
command.execute()
|
||||
|
||||
@pytest.mark.parametrize("input, what", not_serializable)
|
||||
def test_try_backup_not_serializable(
|
||||
self, tmp_path: Path, input: Sequence[Any], what: Type[Any]
|
||||
):
|
||||
file = tmp_path / "test.json"
|
||||
|
||||
client = MockClient()
|
||||
client.insert(input)
|
||||
originals = client.select(what)
|
||||
assert originals
|
||||
|
||||
command = ExportCommand(client, what, file, ExportFormat.JSON)
|
||||
|
||||
with pytest.raises(AttributeError):
|
||||
command.execute()
|
||||
|
||||
other = MockClient()
|
||||
command = ImportCommand(other, what, file, ExportFormat.JSON)
|
||||
|
||||
with pytest.raises(ImportFailedError):
|
||||
command.execute()
|
||||
|
||||
imported = other.select(what)
|
||||
assert not imported
|
||||
|
||||
def test_full_backup(self, tmp_path: Path):
|
||||
file = tmp_path / "test.json"
|
||||
|
||||
client = MockClient()
|
||||
client.insert([e for t in params for e in t[0]])
|
||||
|
||||
command = BackupCommand(client, file, ExportFormat.JSON)
|
||||
command.execute()
|
||||
|
||||
other = MockClient()
|
||||
command = ImportBackupCommand(other, file, ExportFormat.JSON)
|
||||
command.execute()
|
||||
|
||||
def subclasses(cls: Type[Any]) -> set[Type[Any]]:
|
||||
return set(cls.__subclasses__()) | {
|
||||
s for c in cls.__subclasses__() for s in subclasses(c)
|
||||
}
|
||||
|
||||
for t in [cls for cls in subclasses(Base)]:
|
||||
originals = client.select(t)
|
||||
imported = other.select(t)
|
||||
|
||||
assert originals == imported, f"{t}"
|
||||
54
tests/test_command.py
Normal file
54
tests/test_command.py
Normal file
@ -0,0 +1,54 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from mocks.client import MockClient
|
||||
import mocks.transactions
|
||||
|
||||
from pfbudget.common.types import ExportFormat
|
||||
from pfbudget.core.command import ExportCommand, ImportCommand
|
||||
from pfbudget.db.client import Client
|
||||
from pfbudget.db.exceptions import InsertError
|
||||
from pfbudget.db.model import Transaction
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> Client:
|
||||
return MockClient()
|
||||
|
||||
|
||||
class TestCommand:
|
||||
def test_export_json(self, tmp_path: Path, client: Client):
|
||||
file = tmp_path / "test.json"
|
||||
client.insert(mocks.transactions.simple)
|
||||
|
||||
command = ExportCommand(client, Transaction, file, ExportFormat.JSON)
|
||||
command.execute()
|
||||
|
||||
with open(file, newline="") as f:
|
||||
result = json.load(f)
|
||||
assert result == [t.serialize() for t in client.select(Transaction)]
|
||||
|
||||
def test_export_pickle(self, tmp_path: Path, client: Client):
|
||||
file = tmp_path / "test.pickle"
|
||||
command = ExportCommand(client, Transaction, file, ExportFormat.pickle)
|
||||
with pytest.raises(AttributeError):
|
||||
command.execute()
|
||||
|
||||
def test_import_json(self, tmp_path: Path, client: Client):
|
||||
file = tmp_path / "test"
|
||||
client.insert(mocks.transactions.simple)
|
||||
|
||||
command = ExportCommand(client, Transaction, file, ExportFormat.JSON)
|
||||
command.execute()
|
||||
|
||||
# Since the transactions are already in the DB, we expect an insert error
|
||||
with pytest.raises(InsertError):
|
||||
command = ImportCommand(client, Transaction, file, ExportFormat.JSON)
|
||||
command.execute()
|
||||
|
||||
def test_import_pickle(self, tmp_path: Path, client: Client):
|
||||
file = tmp_path / "test"
|
||||
command = ExportCommand(client, Transaction, file, ExportFormat.pickle)
|
||||
with pytest.raises(AttributeError):
|
||||
command.execute()
|
||||
153
tests/test_database.py
Normal file
153
tests/test_database.py
Normal file
@ -0,0 +1,153 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
import pytest
|
||||
|
||||
from mocks.client import MockClient
|
||||
|
||||
from pfbudget.db.client import Client
|
||||
from pfbudget.db.model import (
|
||||
AccountType,
|
||||
Bank,
|
||||
NordigenBank,
|
||||
CategorySelector,
|
||||
Transaction,
|
||||
TransactionCategory,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> Client:
|
||||
return MockClient()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def banks(client: Client) -> list[Bank]:
|
||||
banks = [
|
||||
Bank("bank", "BANK", AccountType.checking, NordigenBank(None, "req", None)),
|
||||
Bank("broker", "BROKER", AccountType.investment),
|
||||
Bank("creditcard", "CC", AccountType.MASTERCARD),
|
||||
]
|
||||
|
||||
# fix nordigen bank names which would be generated post DB insert
|
||||
for bank in banks:
|
||||
if bank.nordigen:
|
||||
bank.nordigen.name = bank.name
|
||||
|
||||
client.insert(banks)
|
||||
return banks
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def transactions(client: Client) -> list[Transaction]:
|
||||
transactions = [
|
||||
Transaction(
|
||||
date(2023, 1, 1),
|
||||
"",
|
||||
Decimal("-10"),
|
||||
category=TransactionCategory("category", CategorySelector.algorithm),
|
||||
),
|
||||
Transaction(date(2023, 1, 2), "", Decimal("-50")),
|
||||
]
|
||||
|
||||
client.insert(transactions)
|
||||
|
||||
# fix ids which would be generated post DB insert
|
||||
for i, transaction in enumerate(transactions):
|
||||
transaction.id = i + 1
|
||||
if transaction.category:
|
||||
transaction.category.id = 1
|
||||
|
||||
return transactions
|
||||
|
||||
|
||||
class TestDatabase:
|
||||
def test_initialization(self, client: Client):
|
||||
pass
|
||||
|
||||
def test_insert_with_session(self, client: Client):
|
||||
transactions = [
|
||||
Transaction(date(2023, 1, 1), "", Decimal("-10")),
|
||||
Transaction(date(2023, 1, 2), "", Decimal("-50")),
|
||||
]
|
||||
|
||||
with client.session as session:
|
||||
session.insert(transactions)
|
||||
assert session.select(Transaction) == transactions
|
||||
|
||||
def test_insert_transactions(self, client: Client, transactions: list[Transaction]):
|
||||
result = client.select(Transaction)
|
||||
assert result == transactions
|
||||
|
||||
def test_select_transactions_without_category(
|
||||
self, client: Client, transactions: list[Transaction]
|
||||
):
|
||||
result = client.select(Transaction, lambda: ~Transaction.category.has())
|
||||
assert result == [transactions[1]]
|
||||
|
||||
def test_select_banks(self, client: Client, banks: list[Bank]):
|
||||
result = client.select(Bank)
|
||||
assert result == banks
|
||||
|
||||
def test_select_banks_with_nordigen(self, client: Client, banks: list[Bank]):
|
||||
result = client.select(Bank, Bank.nordigen)
|
||||
assert result == [banks[0]]
|
||||
|
||||
def test_select_banks_by_name(self, client: Client, banks: list[Bank]):
|
||||
name = banks[0].name
|
||||
result = client.select(Bank, lambda: Bank.name == name)
|
||||
assert result == [banks[0]]
|
||||
|
||||
names = [banks[0].name, banks[1].name]
|
||||
result = client.select(Bank, lambda: Bank.name.in_(names))
|
||||
assert result == [banks[0], banks[1]]
|
||||
|
||||
def test_update_bank_with_session(self, client: Client, banks: list[Bank]):
|
||||
with client.session as session:
|
||||
name = banks[0].name
|
||||
bank = session.select(Bank, lambda: Bank.name == name)[0]
|
||||
bank.name = "anotherbank"
|
||||
|
||||
result = client.select(Bank, lambda: Bank.name == "anotherbank")
|
||||
assert len(result) == 1
|
||||
|
||||
def test_update_bank(self, client: Client, banks: list[Bank]):
|
||||
name = banks[0].name
|
||||
|
||||
result = client.select(Bank, lambda: Bank.name == name)
|
||||
assert result[0].type == AccountType.checking
|
||||
|
||||
update = {"name": name, "type": AccountType.savings}
|
||||
client.update(Bank, [update])
|
||||
|
||||
result = client.select(Bank, lambda: Bank.name == name)
|
||||
assert result[0].type == AccountType.savings
|
||||
|
||||
def test_update_nordigen(self, client: Client, banks: list[Bank]):
|
||||
name = banks[0].name
|
||||
|
||||
result = client.select(NordigenBank, lambda: NordigenBank.name == name)
|
||||
assert result[0].requisition_id == "req"
|
||||
|
||||
update = {"name": name, "requisition_id": "anotherreq"}
|
||||
client.update(NordigenBank, [update])
|
||||
|
||||
result = client.select(NordigenBank, lambda: NordigenBank.name == name)
|
||||
assert result[0].requisition_id == "anotherreq"
|
||||
|
||||
result = client.select(Bank, lambda: Bank.name == name)
|
||||
assert getattr(result[0].nordigen, "requisition_id", None) == "anotherreq"
|
||||
|
||||
def test_remove_bank(self, client: Client, banks: list[Bank]):
|
||||
name = banks[0].name
|
||||
|
||||
result = client.select(Bank)
|
||||
assert len(result) == 3
|
||||
|
||||
client.delete(Bank, Bank.name, [name])
|
||||
result = client.select(Bank)
|
||||
assert len(result) == 2
|
||||
|
||||
names = [banks[1].name, banks[2].name]
|
||||
client.delete(Bank, Bank.name, names)
|
||||
result = client.select(Bank)
|
||||
assert len(result) == 0
|
||||
38
tests/test_load.py
Normal file
38
tests/test_load.py
Normal file
@ -0,0 +1,38 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from typing import Sequence
|
||||
import pytest
|
||||
|
||||
from pfbudget.db.client import Client
|
||||
from pfbudget.db.model import BankTransaction, Transaction
|
||||
from pfbudget.load.database import DatabaseLoader
|
||||
from pfbudget.load.load import Loader
|
||||
|
||||
|
||||
class FakeDatabaseClient(Client):
|
||||
def __init__(self, url: str) -> None:
|
||||
super().__init__(url)
|
||||
|
||||
def insert(self, transactions: Sequence[Transaction]) -> None:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def loader() -> Loader:
|
||||
url = "postgresql://user:pass@127.0.0.1:5432/db"
|
||||
client = FakeDatabaseClient(url)
|
||||
return DatabaseLoader(client)
|
||||
|
||||
|
||||
class TestDatabaseLoad:
|
||||
def test_empty_url(self):
|
||||
with pytest.raises(AssertionError):
|
||||
_ = FakeDatabaseClient("")
|
||||
|
||||
def test_insert(self, loader: Loader):
|
||||
transactions = [
|
||||
BankTransaction(date(2023, 1, 1), "", Decimal("-500"), bank="Bank#1"),
|
||||
BankTransaction(date(2023, 1, 2), "", Decimal("500"), bank="Bank#2"),
|
||||
]
|
||||
|
||||
loader.load(transactions)
|
||||
104
tests/test_psd2.py
Normal file
104
tests/test_psd2.py
Normal file
@ -0,0 +1,104 @@
|
||||
import datetime as dt
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from mocks.client import MockClient
|
||||
import mocks.nordigen as mock
|
||||
|
||||
from pfbudget.db.model import AccountType, Bank, BankTransaction, NordigenBank
|
||||
from pfbudget.extract.exceptions import BankError, CredentialsError
|
||||
from pfbudget.extract.extract import Extractor
|
||||
from pfbudget.extract.nordigen import NordigenClient, NordigenCredentials
|
||||
from pfbudget.extract.psd2 import PSD2Extractor
|
||||
|
||||
|
||||
class MockGet:
|
||||
def __init__(self, mock_exception: Optional[Exception] = None):
|
||||
self._status_code = 200
|
||||
self._mock_exception = mock_exception
|
||||
|
||||
def __call__(self, *args: Any, **kwargs: Any):
|
||||
if self._mock_exception:
|
||||
raise self._mock_exception
|
||||
|
||||
self._headers: dict[str, str] = kwargs["headers"]
|
||||
if "Authorization" not in self._headers or not self._headers["Authorization"]:
|
||||
self._status_code = 401
|
||||
|
||||
self.url: str = kwargs["url"]
|
||||
return self
|
||||
|
||||
@property
|
||||
def ok(self):
|
||||
return True if self._status_code < 400 else False
|
||||
|
||||
@property
|
||||
def status_code(self):
|
||||
return self._status_code
|
||||
|
||||
def json(self):
|
||||
if self.url.endswith("accounts/" + mock.id + "/"):
|
||||
return mock.accounts_id
|
||||
elif self.url.endswith("accounts/" + mock.id + "/transactions/"):
|
||||
return mock.accounts_id_transactions
|
||||
elif self.url.endswith("requisitions/"):
|
||||
return mock.requisitions
|
||||
elif self.url.endswith("requisitions/" + mock.id + "/"):
|
||||
return mock.requisitions_id
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_requests(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setattr("requests.get", MockGet())
|
||||
monkeypatch.delattr("requests.post")
|
||||
monkeypatch.delattr("requests.put")
|
||||
monkeypatch.delattr("requests.delete")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def extractor() -> Extractor:
|
||||
credentials = NordigenCredentials("ID", "KEY")
|
||||
return PSD2Extractor(NordigenClient(credentials, MockClient()))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bank() -> Bank:
|
||||
bank = Bank("Bank#1", "", AccountType.checking, NordigenBank("", mock.id, False))
|
||||
return bank
|
||||
|
||||
|
||||
class TestExtractPSD2:
|
||||
def test_empty_credentials(self):
|
||||
cred = NordigenCredentials("", "")
|
||||
with pytest.raises(CredentialsError):
|
||||
NordigenClient(cred, MockClient())
|
||||
|
||||
def test_no_psd2_bank(self, extractor: Extractor):
|
||||
with pytest.raises(BankError):
|
||||
extractor.extract(Bank("", "", AccountType.checking))
|
||||
|
||||
def test_timeout(
|
||||
self, monkeypatch: pytest.MonkeyPatch, extractor: Extractor, bank: Bank
|
||||
):
|
||||
monkeypatch.setattr(
|
||||
"requests.get", MockGet(mock_exception=requests.ReadTimeout())
|
||||
)
|
||||
with pytest.raises(requests.Timeout):
|
||||
extractor.extract(bank)
|
||||
|
||||
def test_extract(
|
||||
self, monkeypatch: pytest.MonkeyPatch, extractor: Extractor, bank: Bank
|
||||
):
|
||||
monkeypatch.setattr(
|
||||
"pfbudget.extract.nordigen.NordigenClient.dump", lambda *args: None
|
||||
)
|
||||
assert extractor.extract(bank) == [
|
||||
BankTransaction(
|
||||
dt.date(2023, 1, 14), "string", Decimal("328.18"), bank="Bank#1"
|
||||
),
|
||||
BankTransaction(
|
||||
dt.date(2023, 2, 14), "string", Decimal("947.26"), bank="Bank#1"
|
||||
),
|
||||
]
|
||||
159
tests/test_transform.py
Normal file
159
tests/test_transform.py
Normal file
@ -0,0 +1,159 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
import pytest
|
||||
|
||||
import mocks.categories as mock
|
||||
|
||||
from pfbudget.db.model import (
|
||||
BankTransaction,
|
||||
Category,
|
||||
CategoryRule,
|
||||
CategorySelector,
|
||||
TransactionCategory,
|
||||
TransactionTag,
|
||||
)
|
||||
from pfbudget.transform.categorizer import Categorizer
|
||||
from pfbudget.transform.exceptions import MoreThanOneMatchError
|
||||
from pfbudget.transform.nullifier import Nullifier
|
||||
from pfbudget.transform.tagger import Tagger
|
||||
from pfbudget.transform.transform import Transformer
|
||||
|
||||
|
||||
class TestTransform:
|
||||
def test_nullifier(self):
|
||||
transactions = [
|
||||
BankTransaction(date(2023, 1, 1), "", Decimal("-500"), bank="Bank#1"),
|
||||
BankTransaction(date(2023, 1, 2), "", Decimal("500"), bank="Bank#2"),
|
||||
]
|
||||
|
||||
for t in transactions:
|
||||
assert not t.category
|
||||
|
||||
categorizer: Transformer = Nullifier()
|
||||
transactions = categorizer.transform(transactions)
|
||||
|
||||
for t in transactions:
|
||||
assert t.category == TransactionCategory("null", CategorySelector.nullifier)
|
||||
|
||||
def test_nullifier_inplace(self):
|
||||
transactions = [
|
||||
BankTransaction(date(2023, 1, 1), "", Decimal("-500"), bank="Bank#1"),
|
||||
BankTransaction(date(2023, 1, 2), "", Decimal("500"), bank="Bank#2"),
|
||||
]
|
||||
|
||||
for t in transactions:
|
||||
assert not t.category
|
||||
|
||||
categorizer: Transformer = Nullifier()
|
||||
categorizer.transform_inplace(transactions)
|
||||
|
||||
for t in transactions:
|
||||
assert t.category == TransactionCategory("null", CategorySelector.nullifier)
|
||||
|
||||
def test_nullifier_inplace_unordered(self):
|
||||
transactions = [
|
||||
BankTransaction(date(2023, 1, 2), "A2", Decimal("500"), bank="Bank#2"),
|
||||
BankTransaction(date(2023, 1, 2), "B1", Decimal("-500"), bank="Bank#1"),
|
||||
BankTransaction(date(2023, 1, 1), "A1", Decimal("-500"), bank="Bank#1"),
|
||||
BankTransaction(date(2023, 1, 2), "B2", Decimal("500"), bank="Bank#2"),
|
||||
]
|
||||
|
||||
for t in transactions:
|
||||
assert not t.category
|
||||
|
||||
categorizer: Transformer = Nullifier()
|
||||
with pytest.raises(MoreThanOneMatchError):
|
||||
categorizer.transform_inplace(transactions)
|
||||
|
||||
def test_nullifier_inplace_repeated(self):
|
||||
transactions = [
|
||||
BankTransaction(date(2023, 1, 2), "A1", Decimal("-500"), bank="Bank#1"),
|
||||
BankTransaction(date(2023, 1, 2), "A2", Decimal("500"), bank="Bank#2"),
|
||||
BankTransaction(date(2023, 1, 2), "B1", Decimal("-500"), bank="Bank#1"),
|
||||
BankTransaction(date(2023, 1, 2), "B2", Decimal("500"), bank="Bank#2"),
|
||||
]
|
||||
|
||||
for t in transactions:
|
||||
assert not t.category
|
||||
|
||||
categorizer: Transformer = Nullifier()
|
||||
with pytest.raises(MoreThanOneMatchError):
|
||||
categorizer.transform_inplace(transactions)
|
||||
|
||||
def test_nullifier_with_rules(self):
|
||||
transactions = [
|
||||
BankTransaction(date(2023, 1, 1), "", Decimal("-500"), bank="Bank#1"),
|
||||
BankTransaction(date(2023, 1, 2), "", Decimal("500"), bank="Bank#2"),
|
||||
]
|
||||
|
||||
for t in transactions:
|
||||
assert not t.category
|
||||
|
||||
rule = CategoryRule(bank="Bank#1")
|
||||
rule.name = "null"
|
||||
rules = [rule]
|
||||
|
||||
categorizer: Transformer = Nullifier(rules)
|
||||
transactions = categorizer.transform(transactions)
|
||||
|
||||
for t in transactions:
|
||||
assert not t.category
|
||||
|
||||
rule = CategoryRule(bank="Bank#2")
|
||||
rule.name = "null"
|
||||
rules.append(rule)
|
||||
categorizer = Nullifier(rules)
|
||||
transactions = categorizer.transform(transactions)
|
||||
|
||||
for t in transactions:
|
||||
assert t.category == TransactionCategory("null", CategorySelector.nullifier)
|
||||
|
||||
def test_tagger(self):
|
||||
transactions = [
|
||||
BankTransaction(date(2023, 1, 1), "desc#1", Decimal("-10"), bank="Bank#1")
|
||||
]
|
||||
|
||||
for t in transactions:
|
||||
assert not t.category
|
||||
|
||||
rules = mock.tag_1.rules
|
||||
for rule in rules:
|
||||
rule.tag = mock.tag_1.name
|
||||
|
||||
categorizer: Transformer = Tagger(rules)
|
||||
transactions = categorizer.transform(transactions)
|
||||
|
||||
for t in transactions:
|
||||
assert TransactionTag("tag#1") in t.tags
|
||||
|
||||
def test_categorize(self):
|
||||
transactions = [
|
||||
BankTransaction(date(2023, 1, 1), "desc#1", Decimal("-10"), bank="Bank#1")
|
||||
]
|
||||
|
||||
for t in transactions:
|
||||
assert not t.category
|
||||
|
||||
rules = mock.category1.rules
|
||||
for rule in rules:
|
||||
rule.name = mock.category1.name
|
||||
|
||||
categorizer: Transformer = Categorizer(rules)
|
||||
transactions = categorizer.transform(transactions)
|
||||
|
||||
for t in transactions:
|
||||
assert t.category == TransactionCategory("cat#1", CategorySelector.rules)
|
||||
|
||||
def test_rule_limits(self):
|
||||
transactions = [
|
||||
BankTransaction(date.today(), "", Decimal("-60"), bank="Bank#1"),
|
||||
BankTransaction(date.today(), "", Decimal("-120"), bank="Bank#1"),
|
||||
]
|
||||
|
||||
cat = Category("cat")
|
||||
cat.rules = [CategoryRule(min=-120, max=-60)]
|
||||
for r in cat.rules:
|
||||
r.name = cat.name
|
||||
|
||||
transactions = Categorizer(cat.rules).transform(transactions)
|
||||
assert all(t.category.name == cat.name for t in transactions)
|
||||
Loading…
x
Reference in New Issue
Block a user