Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 26ba18ac28 | |||
| 95c6bf54ed | |||
| ec9519a234 | |||
| 507eb62216 | |||
| c6805aea8f | |||
| 59bbeaf9de | |||
| a3a50615bb | |||
| 65899bc170 | |||
| 3245341ebc | |||
| e9d7ef4239 | |||
| 03d2afd4dc | |||
| c3cb1dd060 | |||
| 2e8eee6007 | |||
| 03dc2061f9 | |||
| 4e8e80efb4 | |||
| 0f93d0ecb5 | |||
| 95a8a8965b | |||
| 0068d4b69a | |||
| deb31374ea | |||
| 235f290412 |
@@ -1,6 +1,6 @@
|
||||
# FiscusPublic
|
||||
|
||||
The public, pure core of Fiscus Domi, the household money app (MPL-2.0). The private app
|
||||
The public, pure core of Fiscus Domi, the household money app (CPAL-1.0; versions up to v0.9.0 are MPL-2.0). The private app
|
||||
(`https://gitea.marek-novak.cz/mnovak/Fiscus.git`) depends on it **by git tag**, never by path.
|
||||
|
||||
## Pure
|
||||
|
||||
Generated
+4
-4
@@ -139,7 +139,7 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-capture"
|
||||
version = "0.2.1"
|
||||
version = "0.9.1"
|
||||
dependencies = [
|
||||
"fiscus-ledger",
|
||||
"proptest",
|
||||
@@ -150,7 +150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-insight"
|
||||
version = "0.2.1"
|
||||
version = "0.9.1"
|
||||
dependencies = [
|
||||
"fiscus-ledger",
|
||||
"serde",
|
||||
@@ -159,7 +159,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-ledger"
|
||||
version = "0.2.1"
|
||||
version = "0.9.1"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -169,7 +169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-statement"
|
||||
version = "0.2.1"
|
||||
version = "0.9.1"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"fiscus-ledger",
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@ resolver = "2"
|
||||
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.2.1"
|
||||
version = "0.9.1"
|
||||
edition = "2021"
|
||||
license = "MPL-2.0"
|
||||
license = "CPAL-1.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
|
||||
|
||||
[workspace.dependencies]
|
||||
|
||||
@@ -1,373 +1,168 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
Common Public Attribution License Version 1.0 (CPAL)
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
1. “Definitions”
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
1.0.1 “Commercial Use” means distribution or otherwise making the Covered Code available to a third party.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
1.1 “Contributor” means each entity that creates or contributes to the creation of Modifications.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
1.2 “Contributor Version” means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
1.3 “Covered Code” means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
1.4 “Electronic Distribution Mechanism” means a mechanism generally accepted in the software development community for the electronic transfer of data.
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
1.5 “Executable” means Covered Code in any form other than Source Code.
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
1.6 “Initial Developer” means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
1.7 “Larger Work” means a work which combines Covered Code or portions thereof with code not governed by the terms of this License.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
1.8 “License” means this document.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
1.8.1 “Licensable” means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
1.9 “Modifications” means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is:
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications.
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
B. Any new file that contains any part of the Original Code or previous Modifications.
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
1.10 “Original Code” means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
1.10.1 “Patent Claims” means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
1.11 “Source Code” means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor’s choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
1.12 “You” (or “Your”) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, “You” includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
2. Source Code License.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
2.1 The Initial Developer Grant.
|
||||
The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims:
|
||||
|
||||
2.1. Grants
|
||||
(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, and/or as part of a Larger Work; and
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
(b) under Patents Claims infringed by the making, using or selling of Original Code, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Code (or portions thereof).
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
(c) the licenses granted in this Section 2.1(a) and (b) are effective on the date Initial Developer first distributes Original Code under the terms of this License.
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
(d) Notwithstanding Section 2.1(b) above, no patent license is granted: 1) for code that You delete from the Original Code; 2) separate from the Original Code; or 3) for infringements caused by: i) the modification of the Original Code or ii) the combination of the Original Code with other software or devices.
|
||||
|
||||
2.2. Effective Date
|
||||
2.2 Contributor Grant.
|
||||
Subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor, to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code and/or as part of a Larger Work; and
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications made by that Contributor (or portions thereof); and 2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
(c) the licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first makes Commercial Use of the Covered Code.
|
||||
|
||||
(d) Notwithstanding Section 2.2(b) above, no patent license is granted: 1) for any code that Contributor has deleted from the Contributor Version; 2) separate from the Contributor Version; 3) for infringements caused by: i) third party modifications of Contributor Version or ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or 4) under Patent Claims infringed by Covered Code in the absence of Modifications made by that Contributor.
|
||||
|
||||
3. Distribution Obligations.
|
||||
|
||||
3.1 Application of License.
|
||||
The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or restricts the applicable version of this License or the recipients’ rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5.
|
||||
|
||||
3.2 Availability of Source Code.
|
||||
Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party.
|
||||
|
||||
3.3 Description of Modifications.
|
||||
You must cause all Covered Code to which You contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code.
|
||||
|
||||
3.4 Intellectual Property Matters
|
||||
|
||||
(a) Third Party Claims. If Contributor has knowledge that a license under a third party’s intellectual property rights is required to exercise the rights granted by such Contributor under Sections 2.1 or 2.2, Contributor must include a text file with the Source Code distribution titled “LEGAL” which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If Contributor obtains such knowledge after the Modification is made available as described in Section 3.2, Contributor shall promptly modify the LEGAL file in all copies Contributor makes available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained.
|
||||
|
||||
(b) Contributor APIs. If Contributor’s Modifications include an application programming interface and Contributor has knowledge of patent licenses which are reasonably necessary to implement that API, Contributor must also include this information in the LEGAL file.
|
||||
|
||||
(c) Representations. Contributor represents that, except as disclosed pursuant to Section 3.4(a) above, Contributor believes that Contributor’s Modifications are Contributor’s original creation(s) and/or Contributor has sufficient rights to grant the rights conveyed by this License.
|
||||
|
||||
3.5 Required Notices.
|
||||
You must duplicate the notice in Exhibit A in each file of the Source Code. If it is not possible to put such notice in a particular Source Code file due to its structure, then You must include such notice in a location (such as a relevant directory) where a user would be likely to look for such a notice. If You created one or more Modification(s) You may add your name as a Contributor to the notice described in Exhibit A. You must also duplicate this License in any documentation for the Source Code where You describe recipients’ rights or ownership rights relating to Covered Code. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
|
||||
|
||||
3.6 Distribution of Executable Versions.
|
||||
You may distribute Covered Code in Executable form only if the requirements of Section 3.1-3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You describe recipients’ rights relating to the Covered Code. You may distribute the Executable version of Covered Code or ownership rights under a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient’s rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer, Original Developer or any Contributor. You hereby agree to indemnify the Initial Developer, Original Developer and every Contributor for any liability incurred by the Initial Developer, Original Developer or such Contributor as a result of any such terms You offer.
|
||||
|
||||
3.7 Larger Works.
|
||||
You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation.
|
||||
If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the LEGAL file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Application of this License.
|
||||
This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code.
|
||||
|
||||
6. Versions of the License.
|
||||
|
||||
6.1 New Versions.
|
||||
Socialtext, Inc. (“Socialtext”) may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number.
|
||||
|
||||
6.2 Effect of New Versions.
|
||||
Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by Socialtext. No one other than Socialtext has the right to modify the terms applicable to Covered Code created under this License.
|
||||
|
||||
6.3 Derivative Works.
|
||||
If You create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), You must (a) rename Your license so that the phrases “Socialtext”, “CPAL” or any confusingly similar phrase do not appear in your license (except to note that your license differs from this License) and (b) otherwise make it clear that Your version of the license contains terms which differ from the CPAL. (Filling in the name of the Initial Developer, Original Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.)
|
||||
|
||||
7. DISCLAIMER OF WARRANTY.
|
||||
COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN “AS IS” BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER, ORIGINAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
|
||||
|
||||
8. TERMINATION.
|
||||
|
||||
8.1 This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
|
||||
|
||||
8.2 If You initiate litigation by asserting a patent infringement claim (excluding declatory judgment actions) against Initial Developer, Original Developer or a Contributor (the Initial Developer, Original Developer or Contributor against whom You file such action is referred to as “Participant”) alleging that:
|
||||
|
||||
(a) such Participant’s Contributor Version directly or indirectly infringes any patent, then any and all rights granted by such Participant to You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively, unless if within 60 days after receipt of notice You either: (i) agree in writing to pay Participant a mutually agreeable reasonable royalty for Your past and future use of Modifications made by such Participant, or (ii) withdraw Your litigation claim with respect to the Contributor Version against such Participant. If within 60 days of notice, a reasonable royalty and payment arrangement are not mutually agreed upon in writing by the parties or the litigation claim is not withdrawn, the rights granted by Participant to You under Sections 2.1 and/or 2.2 automatically terminate at the expiration of the 60 day notice period specified above.
|
||||
|
||||
(b) any software, hardware, or device, other than such Participant’s Contributor Version, directly or indirectly infringes any patent, then any rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are revoked effective as of the date You first made, used, sold, distributed, or had made, Modifications made by that Participant.
|
||||
|
||||
8.3 If You assert a patent infringement claim against Participant alleging that such Participant’s Contributor Version directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license.
|
||||
|
||||
8.4 In the event of termination under Sections 8.1 or 8.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or any distributor hereunder prior to termination shall survive termination.
|
||||
|
||||
9. LIMITATION OF LIABILITY.
|
||||
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ORIGINAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY’S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
|
||||
|
||||
10. U.S. GOVERNMENT END USERS.
|
||||
The Covered Code is a “commercial item,” as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of “commercial computer software” and “commercial computer software documentation,” as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein.
|
||||
|
||||
11. MISCELLANEOUS.
|
||||
This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by California law provisions (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in the United States of America, any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California, with venue lying in Santa Clara County, California, with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys’ fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License.
|
||||
|
||||
12. RESPONSIBILITY FOR CLAIMS.
|
||||
As between Initial Developer, Original Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer, Original Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
|
||||
|
||||
13. MULTIPLE-LICENSED CODE.
|
||||
Initial Developer may designate portions of the Covered Code as Multiple-Licensed. Multiple-Licensed means that the Initial Developer permits you to utilize portions of the Covered Code under Your choice of the CPAL or the alternative licenses, if any, specified by the Initial Developer in the file described in Exhibit A.
|
||||
|
||||
14. ADDITIONAL TERM: ATTRIBUTION
|
||||
|
||||
(a) As a modest attribution to the organizer of the development of the Original Code (“Original Developer”), in the hope that its promotional value may help justify the time, money and effort invested in writing the Original Code, the Original Developer may include in Exhibit B (“Attribution Information”) a requirement that each time an Executable and Source Code or a Larger Work is launched or initially run (which includes initiating a session), a prominent display of the Original Developer’s Attribution Information (as defined below) must occur on the graphic user interface employed by the end user to access such Covered Code (which may include display on a splash screen), if any. The size of the graphic image should be consistent with the size of the other elements of the Attribution Information. If the access by the end user to the Executable and Source Code does not create a graphic user interface for access to the Covered Code, this obligation shall not apply. If the Original Code displays such Attribution Information in a particular form (such as in the form of a splash screen, notice at login, an “about” display, or dedicated attribution area on user interface screens), continued use of such form for that Attribution Information is one way of meeting this requirement for notice.
|
||||
|
||||
(b) Attribution information may only include a copyright notice, a brief phrase, graphic image and a URL (“Attribution Information”) and is subject to the Attribution Limits as defined below. For these purposes, prominent shall mean display for sufficient duration to give reasonable notice to the user of the identity of the Original Developer and that if You include Attribution Information or similar information for other parties, You must ensure that the Attribution Information for the Original Developer shall be no less prominent than such Attribution Information or similar information for the other party. For greater certainty, the Original Developer may choose to specify in Exhibit B below that the above attribution requirement only applies to an Executable and Source Code resulting from the Original Code or any Modification, but not a Larger Work. The intent is to provide for reasonably modest attribution, therefore the Original Developer cannot require that You display, at any time, more than the following information as Attribution Information: (a) a copyright notice including the name of the Original Developer; (b) a word or one phrase (not exceeding 10 words); (c) one graphic image provided by the Original Developer; and (d) a URL (collectively, the “Attribution Limits”).
|
||||
|
||||
(c) If Exhibit B does not include any Attribution Information, then there are no requirements for You to display any Attribution Information of the Original Developer.
|
||||
|
||||
(d) You acknowledge that all trademarks, service marks and/or trade names contained within the Attribution Information distributed with the Covered Code are the exclusive property of their owners and may only be used with the permission of their owners, or under circumstances otherwise permitted by law or as expressly set out in this License.
|
||||
|
||||
15. ADDITIONAL TERM: NETWORK USE.
|
||||
The term “External Deployment” means the use, distribution, or communication of the Original Code or Modifications in any way such that the Original Code or Modifications may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Code or Modifications as a distribution under section 3.1 and make Source Code available under Section 3.2.
|
||||
|
||||
EXHIBIT A. Common Public Attribution License Version 1.0.
|
||||
|
||||
"The contents of this file are subject to the Common Public Attribution License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/license/cpal_1-0. The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15 have been added to cover use of software over a computer network and provide for limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent with Exhibit B.
|
||||
Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
|
||||
The Original Code is FiscusPublic.
|
||||
The Original Developer is the Initial Developer.
|
||||
The Initial Developer of the Original Code is Marek Novák. All portions of the code written by Marek Novák are Copyright (c) 2026. All Rights Reserved.
|
||||
Contributor: none."
|
||||
|
||||
EXHIBIT B. Attribution Information
|
||||
|
||||
Attribution Copyright Notice: Copyright (c) 2026 Marek Novák
|
||||
Attribution Phrase (not exceeding 10 words): Built on Domi
|
||||
Attribution URL: https://aula.marek-novak.cz
|
||||
Graphic Image as provided in the Covered Code, if any: none.
|
||||
Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL.
|
||||
@@ -6,10 +6,28 @@ subscription / price-change / trial detection and a seeded month-end forecast. N
|
||||
|
||||
| Crate | |
|
||||
|:--|:--|
|
||||
| `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning |
|
||||
| `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning, invoices, category plans, savings goals and challenges, projects (lines, tasks, phases, time) |
|
||||
| `fiscus-statement` | strict CSV, Czech amount and date fields, decoding; bank parsers only from real samples |
|
||||
| `fiscus-insight` | subscriptions, cancel kits, the forecast |
|
||||
| `fiscus-insight` | subscriptions, cancel kits, the forecast, spending, the month against its plan, the month in numbers, goals and their ways to save, medals, projects against their budgets |
|
||||
|
||||
Design: [docs/01_core.md](docs/01_core.md). Tests: `cargo test --workspace`.
|
||||
Design: [docs/01_core.md](docs/01_core.md), [02](docs/02_capture_sharing.md), [03 invoices](docs/03_invoices.md), [04 plans and statistics](docs/04_plans_stats.md), [05 goals and rewards](docs/05_goals_rewards.md), [06 projects](docs/06_projects.md). Tests: `cargo test --workspace`.
|
||||
|
||||
Licence: MPL-2.0.
|
||||
## Licence
|
||||
|
||||
FiscusPublic is under the **Common Public Attribution License 1.0** (SPDX `CPAL-1.0`): see [LICENSE](LICENSE).
|
||||
Every file of this repository is covered by the notice in its Exhibit A.
|
||||
|
||||
Versions before this change (up to and including tag `v0.9.0`) were released under the Mozilla Public License 2.0,
|
||||
and they stay available under MPL-2.0 to those who received them. From this commit on, the code is under CPAL-1.0.
|
||||
|
||||
**The credit (Exhibit B).** Anyone who redistributes FiscusPublic, or builds it into a larger work, must show this
|
||||
credit, as CPAL §14 sets out:
|
||||
|
||||
| | |
|
||||
|:--|:--|
|
||||
| Attribution Copyright Notice | Copyright (c) 2026 Marek Novák |
|
||||
| Attribution Phrase | Built on Domi |
|
||||
| Attribution URL | https://aula.marek-novak.cz |
|
||||
| Graphic Image | none |
|
||||
|
||||
Larger works must show it as well. Use over a network counts as distribution (CPAL §15).
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
|
||||
pub mod amount;
|
||||
pub mod notification;
|
||||
pub mod receipt;
|
||||
pub mod shortcut;
|
||||
|
||||
use fiscus_ledger::{Date, Haler, Timestamp};
|
||||
use fiscus_ledger::{Date, Haler, ReceiptInfo, Timestamp};
|
||||
|
||||
/// One card payment a phone saw: an outflow, so `amount` is negative.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -15,6 +16,8 @@ pub struct Capture {
|
||||
pub at: Timestamp,
|
||||
pub merchant: String,
|
||||
pub card: Option<String>,
|
||||
/// A receipt read on the phone (`"source": "receipt"`): the shop is the merchant, with its IČO and DIČ.
|
||||
pub receipt: Option<ReceiptInfo>,
|
||||
}
|
||||
|
||||
/// 1–200 characters, no control characters.
|
||||
|
||||
@@ -175,5 +175,5 @@ fn capture(fields: &Fields, date: Date, at: Timestamp) -> Option<Capture> {
|
||||
if card.is_some_and(|c| !card_ok(c)) {
|
||||
return None;
|
||||
}
|
||||
Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string) })
|
||||
Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string), receipt: None })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
//! A receipt's text as an OCR read it (lines of words, each with its box and confidence; docs/07_receipts.md).
|
||||
//! What every Czech receipt must show is found by its label, never by a shop's layout: the total (`Celkem`,
|
||||
//! `K úhradě`…), the date and time, the IČO (with its check digit) and DIČ, and the shop's name above them.
|
||||
//!
|
||||
//! Hostile input: bounded in size, control characters dropped, and a field is either read whole or not at all.
|
||||
//! A field read from words the OCR was not sure of is marked `sure: false`, for you to check; the shop's name is
|
||||
//! always to check. Amounts are read from their text into haléře, never through a float, and confidence is in
|
||||
//! thousandths.
|
||||
|
||||
use crate::amount;
|
||||
use fiscus_ledger::invoice::{dic_ok, ico_ok};
|
||||
use fiscus_ledger::{Date, Haler};
|
||||
|
||||
/// At most this many lines, words in a line, and characters in a word.
|
||||
pub const MAX_LINES: usize = 600;
|
||||
pub const MAX_WORDS: usize = 120;
|
||||
pub const MAX_WORD: usize = 80;
|
||||
/// A word read with at least this confidence (thousandths) counts as sure.
|
||||
pub const SURE: u16 = 800;
|
||||
|
||||
/// A box in the image's pixels (as the OCR gives it, upright).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct BBox {
|
||||
pub x: u32,
|
||||
pub y: u32,
|
||||
pub w: u32,
|
||||
pub h: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Word {
|
||||
pub text: String,
|
||||
/// 0-1000.
|
||||
pub confidence: u16,
|
||||
pub bbox: BBox,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Line {
|
||||
pub words: Vec<Word>,
|
||||
}
|
||||
|
||||
/// One field read, where it was on the image, and whether every word of it was read surely.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Field<T> {
|
||||
pub value: T,
|
||||
pub sure: bool,
|
||||
pub boxes: Vec<BBox>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Receipt {
|
||||
/// What was paid, positive.
|
||||
pub total: Option<Field<Haler>>,
|
||||
pub date: Option<Field<Date>>,
|
||||
/// Hours and minutes.
|
||||
pub time: Option<Field<(u8, u8)>>,
|
||||
pub shop: Option<Field<String>>,
|
||||
pub ico: Option<Field<String>>,
|
||||
pub dic: Option<Field<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ReceiptError {
|
||||
#[error("there is more text than a receipt holds")]
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// The labels of the total, best first: what is to pay beats a sum that might be before a discount.
|
||||
const TOTAL_LABELS: [(&str, u8); 9] = [
|
||||
("K UHRADE", 0),
|
||||
("CASTKA K UHRADE", 0),
|
||||
("CELKEM K UHRADE", 0),
|
||||
("CELKEM", 1),
|
||||
("CELKOVA CASTKA", 1),
|
||||
("CELKEM KC", 1),
|
||||
("CELKEM CZK", 1),
|
||||
("SUMA", 2),
|
||||
("TOTAL", 2),
|
||||
];
|
||||
/// A line with one of these is about VAT, a subtotal or rounding, never the total.
|
||||
const NOT_TOTAL: [&str; 6] = ["DPH", "ZAKLAD", "SAZBA", "MEZISOUCET", "ZAOKROUHLENI", "VRACENO"];
|
||||
|
||||
/// A word as it reads for matching labels: upper case, Czech letters without their marks, punctuation at the
|
||||
/// ends dropped.
|
||||
fn fold(s: &str) -> String {
|
||||
let up: String = s
|
||||
.chars()
|
||||
.flat_map(char::to_uppercase)
|
||||
.map(|c| match c {
|
||||
'Á' | 'Ä' => 'A',
|
||||
'Č' => 'C',
|
||||
'Ď' => 'D',
|
||||
'É' | 'Ě' => 'E',
|
||||
'Í' => 'I',
|
||||
'Ň' => 'N',
|
||||
'Ó' | 'Ö' => 'O',
|
||||
'Ř' => 'R',
|
||||
'Š' => 'S',
|
||||
'Ť' => 'T',
|
||||
'Ú' | 'Ů' | 'Ü' => 'U',
|
||||
'Ý' => 'Y',
|
||||
'Ž' => 'Z',
|
||||
c => c,
|
||||
})
|
||||
.collect();
|
||||
up.trim_matches(|c: char| !c.is_alphanumeric()).to_string()
|
||||
}
|
||||
|
||||
struct Prepared<'a> {
|
||||
words: Vec<&'a Word>,
|
||||
texts: Vec<String>,
|
||||
folded: Vec<String>,
|
||||
}
|
||||
|
||||
impl Prepared<'_> {
|
||||
fn sure(&self, idx: &[usize]) -> bool {
|
||||
idx.iter().all(|&i| self.words[i].confidence >= SURE)
|
||||
}
|
||||
fn boxes(&self, idx: &[usize]) -> Vec<BBox> {
|
||||
idx.iter().map(|&i| self.words[i].bbox).collect()
|
||||
}
|
||||
/// Where `label` (folded words) starts in this line, if it is there as whole words.
|
||||
fn find(&self, label: &str) -> Option<usize> {
|
||||
let want: Vec<&str> = label.split(' ').collect();
|
||||
(0..self.folded.len()).find(|&i| i + want.len() <= self.folded.len() && want.iter().enumerate().all(|(k, w)| self.folded[i + k] == *w))
|
||||
}
|
||||
}
|
||||
|
||||
/// The receipt's fields, as far as they can be read. Nothing found is an empty [`Receipt`], not an error.
|
||||
pub fn read(lines: &[Line]) -> Result<Receipt, ReceiptError> {
|
||||
if lines.len() > MAX_LINES || lines.iter().any(|l| l.words.len() > MAX_WORDS || l.words.iter().any(|w| w.text.chars().count() > MAX_WORD)) {
|
||||
return Err(ReceiptError::TooLarge);
|
||||
}
|
||||
let prepared: Vec<Prepared> = lines
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let words: Vec<&Word> = l.words.iter().filter(|w| !clean(&w.text).is_empty()).collect();
|
||||
let texts: Vec<String> = words.iter().map(|w| clean(&w.text)).collect();
|
||||
let folded = texts.iter().map(|t| fold(t)).collect();
|
||||
Prepared { words, texts, folded }
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut out = Receipt { total: total(&prepared), ..Default::default() };
|
||||
let (date, time) = date_time(&prepared);
|
||||
out.date = date;
|
||||
out.time = time;
|
||||
out.dic = dic(&prepared);
|
||||
let ico_line;
|
||||
(out.ico, ico_line) = ico(&prepared);
|
||||
if out.ico.is_none() {
|
||||
// A company's DIČ is CZ and its IČO.
|
||||
out.ico = out.dic.as_ref().filter(|d| d.value.len() == 10 && ico_ok(&d.value[2..])).map(|d| Field { value: d.value[2..].to_string(), sure: d.sure, boxes: d.boxes.clone() });
|
||||
}
|
||||
out.shop = shop(&prepared, ico_line);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The word's text without control characters, trimmed.
|
||||
fn clean(s: &str) -> String {
|
||||
s.chars().filter(|c| !c.is_control()).collect::<String>().trim().to_string()
|
||||
}
|
||||
|
||||
/// An amount written over words `i..=j`: `1 284,90`, `1284.90`, `-89,00` (a sign is ignored), with `Kč` after it
|
||||
/// dropped. Groups of three digits may be split over words. `Some(None)`: well formed, but not a payment Fiscus
|
||||
/// believes (over 10 000 000 Kč, or nothing); `None`: not an amount.
|
||||
fn amount_at(p: &Prepared, i: usize, j: usize) -> Option<Option<Haler>> {
|
||||
let text = p.texts[i..=j].join(" ");
|
||||
let t = text.trim_start_matches(['-', '−']).trim_end_matches(|c: char| c.is_alphabetic() || c == '.').trim();
|
||||
let (int, frac) = t.rsplit_once([',', '.'])?;
|
||||
if frac.len() != 2 || !frac.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let groups: Vec<&str> = int.split([' ', '.', '\u{a0}']).collect();
|
||||
let ok = if groups.len() == 1 {
|
||||
(1..=7).contains(&groups[0].len()) && groups[0].bytes().all(|b| b.is_ascii_digit())
|
||||
} else {
|
||||
(1..=3).contains(&groups[0].len()) && groups.iter().all(|g| g.bytes().all(|b| b.is_ascii_digit())) && groups[1..].iter().all(|g| g.len() == 3)
|
||||
};
|
||||
if !ok {
|
||||
return None;
|
||||
}
|
||||
Some(amount::parse_positive(&format!("{},{frac}", groups.concat())))
|
||||
}
|
||||
|
||||
/// The rightmost amount in a line from word `from` on, and the words it was written in.
|
||||
fn last_amount(p: &Prepared, from: usize) -> Option<(Haler, Vec<usize>)> {
|
||||
for j in (from..p.texts.len()).rev() {
|
||||
// The longest reading that ends at j, so "1 284,90" wins over "284,90"; and one too large is refused
|
||||
// whole, never read as its tail.
|
||||
if let Some((i, a)) = (j.saturating_sub(2).max(from)..=j).find_map(|i| amount_at(p, i, j).map(|a| (i, a))) {
|
||||
return a.map(|a| (a, (i..=j).collect()));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn total(lines: &[Prepared]) -> Option<Field<Haler>> {
|
||||
let mut best: Option<(u8, Field<Haler>)> = None;
|
||||
for (n, p) in lines.iter().enumerate() {
|
||||
if NOT_TOTAL.iter().any(|w| p.folded.iter().any(|f| f == w)) {
|
||||
continue;
|
||||
}
|
||||
let Some((rank, at, len)) = TOTAL_LABELS.iter().filter_map(|(l, r)| p.find(l).map(|at| (*r, at, l.split(' ').count()))).min_by_key(|(r, _, len)| (*r, usize::MAX - len)) else { continue };
|
||||
let label: Vec<usize> = (at..at + len).collect();
|
||||
// On the label's line, or alone on the next one.
|
||||
let found = last_amount(p, at + len).map(|(a, idx)| (a, idx, p)).or_else(|| {
|
||||
let next = lines.get(n + 1)?;
|
||||
let (a, idx) = last_amount(next, 0)?;
|
||||
(idx.len() == next.texts.len()).then_some((a, idx, next))
|
||||
});
|
||||
let Some((amount, idx, q)) = found else { continue };
|
||||
let field = Field { value: amount, sure: p.sure(&label) && q.sure(&idx), boxes: [p.boxes(&label), q.boxes(&idx)].concat() };
|
||||
let better = match &best {
|
||||
None => true,
|
||||
Some((r, f)) => rank < *r || (rank == *r && amount > f.value),
|
||||
};
|
||||
if better {
|
||||
best = Some((rank, field));
|
||||
}
|
||||
}
|
||||
best.map(|(_, f)| f)
|
||||
}
|
||||
|
||||
/// Digits only, if the text is digits (a stray `.` or `:` at the ends is dropped).
|
||||
fn digits(s: &str) -> Option<&str> {
|
||||
let d = s.trim_matches(|c: char| !c.is_ascii_alphanumeric());
|
||||
(!d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())).then_some(d)
|
||||
}
|
||||
|
||||
/// A date in one word or over up to three (`16.11.2026`, `16. 11. 2026`, `16.11.26`, `2026-11-16`, `16/11/2026`).
|
||||
fn date_at(p: &Prepared, i: usize) -> Option<(Date, Vec<usize>)> {
|
||||
for len in 1..=3 {
|
||||
if i + len > p.texts.len() {
|
||||
break;
|
||||
}
|
||||
let text: String = p.texts[i..i + len].concat();
|
||||
let t = text.trim_end_matches('.');
|
||||
let parts: Vec<&str> = t.split(['.', '-', '/']).collect();
|
||||
if parts.len() != 3 || parts.iter().any(|x| x.is_empty() || !x.bytes().all(|b| b.is_ascii_digit())) {
|
||||
continue;
|
||||
}
|
||||
let n = |s: &str| s.parse::<u32>().ok();
|
||||
let (y, m, d) = if parts[0].len() == 4 {
|
||||
(n(parts[0])?, n(parts[1])?, n(parts[2])?)
|
||||
} else if parts[2].len() == 4 && parts[0].len() <= 2 && parts[1].len() <= 2 {
|
||||
(n(parts[2])?, n(parts[1])?, n(parts[0])?)
|
||||
} else if parts[2].len() == 2 && parts[0].len() <= 2 && parts[1].len() <= 2 {
|
||||
(2000 + n(parts[2])?, n(parts[1])?, n(parts[0])?)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if !(2000..=2100).contains(&y) {
|
||||
continue;
|
||||
}
|
||||
if let Some(date) = Date::from_ymd(y as i32, m, d) {
|
||||
return Some((date, (i..i + len).collect()));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `14:32` or `14:32:05` in one word.
|
||||
fn time_at(p: &Prepared, i: usize) -> Option<(u8, u8)> {
|
||||
let parts: Vec<&str> = p.texts[i].split(':').collect();
|
||||
if !(2..=3).contains(&parts.len()) || parts.iter().any(|x| x.len() != 2 || !x.bytes().all(|b| b.is_ascii_digit())) {
|
||||
return None;
|
||||
}
|
||||
let (h, m) = (parts[0].parse::<u8>().ok()?, parts[1].parse::<u8>().ok()?);
|
||||
(h <= 23 && m <= 59).then_some((h, m))
|
||||
}
|
||||
|
||||
type DateTime = (Option<Field<Date>>, Option<Field<(u8, u8)>>);
|
||||
|
||||
/// The date (one with a time on its line first), and the time on its line or anywhere.
|
||||
fn date_time(lines: &[Prepared]) -> DateTime {
|
||||
let mut first: Option<(Field<Date>, usize)> = None;
|
||||
for (n, p) in lines.iter().enumerate() {
|
||||
for i in 0..p.texts.len() {
|
||||
let Some((date, idx)) = date_at(p, i) else { continue };
|
||||
let field = Field { value: date, sure: p.sure(&idx), boxes: p.boxes(&idx) };
|
||||
if let Some(t) = (0..p.texts.len()).find_map(|k| time_at(p, k).map(|t| (t, k))) {
|
||||
let time = Field { value: t.0, sure: p.sure(&[t.1]), boxes: p.boxes(&[t.1]) };
|
||||
return (Some(field), Some(time));
|
||||
}
|
||||
if first.is_none() {
|
||||
first = Some((field, n));
|
||||
}
|
||||
}
|
||||
}
|
||||
let time = lines.iter().find_map(|p| (0..p.texts.len()).find_map(|k| time_at(p, k).map(|t| Field { value: t, sure: p.sure(&[k]), boxes: p.boxes(&[k]) })));
|
||||
(first.map(|(f, _)| f), time)
|
||||
}
|
||||
|
||||
/// The IČO after its label (`IČ`, `IČO`, `IČ:`), 8 digits with a check digit; and its line.
|
||||
fn ico(lines: &[Prepared]) -> (Option<Field<String>>, Option<usize>) {
|
||||
for (n, p) in lines.iter().enumerate() {
|
||||
for (i, f) in p.folded.iter().enumerate() {
|
||||
if f != "IC" && f != "ICO" {
|
||||
continue;
|
||||
}
|
||||
for k in i + 1..(i + 3).min(p.texts.len()) {
|
||||
if let Some(d) = digits(&p.texts[k]) {
|
||||
let value = format!("{d:0>8}");
|
||||
if d.len() <= 8 && ico_ok(&value) {
|
||||
return (Some(Field { value, sure: p.sure(&[i, k]), boxes: p.boxes(&[i, k]) }), Some(n));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
|
||||
/// The DIČ: `CZ` and 8-10 digits, in one word or two (`CZ 25672541`).
|
||||
fn dic(lines: &[Prepared]) -> Option<Field<String>> {
|
||||
for p in lines {
|
||||
for i in 0..p.texts.len() {
|
||||
for len in 1..=2 {
|
||||
if i + len > p.texts.len() {
|
||||
break;
|
||||
}
|
||||
let t: String = p.texts[i..i + len].concat().trim_matches(|c: char| !c.is_ascii_alphanumeric()).to_uppercase();
|
||||
let t = t.strip_prefix("DIC:").unwrap_or(&t).to_string();
|
||||
if t.starts_with("CZ") && dic_ok(&t) {
|
||||
let idx: Vec<usize> = (i..i + len).collect();
|
||||
return Some(Field { value: t, sure: p.sure(&idx), boxes: p.boxes(&idx) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The shop's name: the first line from the top with three letters or more and no label of its own, above the
|
||||
/// IČO's line (or among the first six lines without one). All capitals become Title Case. Always to check.
|
||||
fn shop(lines: &[Prepared], ico_line: Option<usize>) -> Option<Field<String>> {
|
||||
let end = ico_line.unwrap_or(6).min(lines.len());
|
||||
const SKIP: [&str; 10] = ["IC", "ICO", "DIC", "TEL", "WWW", "EMAIL", "PROVOZOVNA", "ADRESA", "DANOVY", "UCTENKA"];
|
||||
for p in &lines[..end] {
|
||||
let letters = p.texts.iter().flat_map(|t| t.chars()).filter(|c| c.is_alphabetic()).count();
|
||||
let digits = p.texts.iter().flat_map(|t| t.chars()).filter(|c| c.is_ascii_digit()).count();
|
||||
if letters < 3 || digits * 2 > letters || p.folded.iter().any(|f| SKIP.contains(&f.as_str()) || f.contains('@') || f.starts_with("WWW") || f.starts_with("HTTP")) {
|
||||
continue;
|
||||
}
|
||||
let name: Vec<String> = p.texts.iter().map(|t| title(t)).collect();
|
||||
let value: String = name.join(" ").chars().take(fiscus_ledger::receipt::MAX_SHOP).collect::<String>().trim().to_string();
|
||||
if value.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let idx: Vec<usize> = (0..p.texts.len()).collect();
|
||||
return Some(Field { value, sure: false, boxes: p.boxes(&idx) });
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `ALBERT` → `Albert`; a word with lower case letters, or not all letters (`s.r.o.`, `4×3,90`), stays.
|
||||
fn title(w: &str) -> String {
|
||||
if w.chars().count() > 1 && w.chars().all(|c| c.is_alphabetic() && !c.is_lowercase()) {
|
||||
let mut c = w.chars();
|
||||
let first = c.next().map(|f| f.to_string()).unwrap_or_default();
|
||||
first + &c.as_str().to_lowercase()
|
||||
} else {
|
||||
w.to_string()
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
//! The iPhone Shortcut post (`POST /inbox`). We write the Shortcut, so the shape is ours:
|
||||
//! `{"amount", "merchant", "card", "time"}` and an optional `"currency": "CZK"`, nothing else.
|
||||
//! `{"amount", "merchant", "card", "time"}` and an optional `"currency": "CZK"`, nothing else. The Android app
|
||||
//! posts a receipt it read the same way, with `"source": "receipt"` and the shop's optional `"ico"` and `"dic"`
|
||||
//! (docs/07_receipts.md).
|
||||
|
||||
use crate::{amount, card_ok, merchant_ok, Capture};
|
||||
use fiscus_ledger::{Date, Timestamp};
|
||||
use fiscus_ledger::{Date, ReceiptInfo, Timestamp};
|
||||
use serde::Deserialize;
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
@@ -25,6 +27,10 @@ pub enum CaptureError {
|
||||
Card,
|
||||
#[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")]
|
||||
Time,
|
||||
#[error("the source is not receipt")]
|
||||
Source,
|
||||
#[error("an IČO or DIČ comes only with a receipt, and must be valid (8 digits with a check digit; CZ and 8-10 digits)")]
|
||||
Receipt,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -36,6 +42,9 @@ struct Post<'a> {
|
||||
card: String,
|
||||
time: String,
|
||||
currency: Option<String>,
|
||||
source: Option<String>,
|
||||
ico: Option<String>,
|
||||
dic: Option<String>,
|
||||
}
|
||||
|
||||
/// One post → one capture, or the first thing wrong with it.
|
||||
@@ -63,6 +72,16 @@ pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
|
||||
return Err(CaptureError::Card);
|
||||
}
|
||||
let (date, at) = parse_time(&post.time).ok_or(CaptureError::Time)?;
|
||||
let receipt = match post.source.as_deref() {
|
||||
None if post.ico.is_none() && post.dic.is_none() => None,
|
||||
None => return Err(CaptureError::Receipt),
|
||||
Some("receipt") => {
|
||||
let info = ReceiptInfo { shop: post.merchant.trim().chars().take(fiscus_ledger::receipt::MAX_SHOP).collect::<String>().trim().to_string(), ico: post.ico, dic: post.dic };
|
||||
info.check().map_err(|_| CaptureError::Receipt)?;
|
||||
Some(info)
|
||||
}
|
||||
Some(_) => return Err(CaptureError::Source),
|
||||
};
|
||||
let card = post.card.trim();
|
||||
Ok(Capture {
|
||||
amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?,
|
||||
@@ -70,6 +89,7 @@ pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
|
||||
at,
|
||||
merchant: post.merchant.trim().to_string(),
|
||||
card: (!card.is_empty()).then(|| card.to_string()),
|
||||
receipt,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Receipts read from an OCR's lines (docs/07_receipts.md): the fields every Czech receipt shows, found by their
|
||||
//! labels; what to pay beats a sum before a discount; VAT lines are never the total; an IČO needs its check digit;
|
||||
//! unsure words are marked; hostile text is bounded and never panics. Synthetic text here: real receipts come as
|
||||
//! redacted OCR output in `fixtures/receipts/` (none yet).
|
||||
|
||||
use fiscus_capture::receipt::{read, BBox, Line, ReceiptError, Word, MAX_LINES};
|
||||
use fiscus_ledger::{Date, Haler};
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// A receipt as text, one line per `\n`; a word ending in `?` was read with low confidence (and loses the `?`).
|
||||
fn page(text: &str) -> Vec<Line> {
|
||||
text.lines()
|
||||
.enumerate()
|
||||
.map(|(y, l)| Line {
|
||||
words: l
|
||||
.split_whitespace()
|
||||
.enumerate()
|
||||
.map(|(x, w)| {
|
||||
let (t, c) = match w.strip_suffix('?') {
|
||||
Some(t) if !t.is_empty() => (t, 420),
|
||||
_ => (w, 960),
|
||||
};
|
||||
Word { text: t.into(), confidence: c, bbox: BBox { x: x as u32 * 50, y: y as u32 * 20, w: 40, h: 16 } }
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
const ALBERT: &str = "ALBERT HYPERMARKET
|
||||
Praha 5
|
||||
IČ: 25672541 DIČ: CZ25672541
|
||||
Rohlík tukový 4×3,90 15,60
|
||||
Mléko polotučné 1 l 24,90
|
||||
Káva zrnková 1 kg 389,00
|
||||
CELKEM Kč 1 284,90
|
||||
Platba kartou 1 284,90
|
||||
DPH 12 % 137,67
|
||||
16.11.2026 14:32 Pokl. 07
|
||||
Děkujeme za nákup";
|
||||
|
||||
#[test]
|
||||
fn a_supermarket_receipt_gives_every_field() {
|
||||
let r = read(&page(ALBERT)).unwrap();
|
||||
let total = r.total.unwrap();
|
||||
assert_eq!((total.value, total.sure), (Haler(128_490), true));
|
||||
assert_eq!(total.boxes.len(), 4, "the label and the amount, over two words each");
|
||||
assert_eq!(r.date.unwrap().value, d("2026-11-16"));
|
||||
assert_eq!(r.time.unwrap().value, (14, 32));
|
||||
assert_eq!(r.ico.unwrap().value, "25672541");
|
||||
assert_eq!(r.dic.unwrap().value, "CZ25672541");
|
||||
let shop = r.shop.unwrap();
|
||||
assert_eq!((shop.value.as_str(), shop.sure), ("Albert Hypermarket", false), "the shop's name is always to check");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_to_pay_beats_a_sum_before_a_discount_and_vat_lines_are_never_the_total() {
|
||||
let r = read(&page("OBI\nIČO 25672541\nCELKEM 1 400,00\nSleva -115,10\nZáklad DPH 21 % 1 061,90\nK ÚHRADĚ 1 284,90\n2. 11. 2026")).unwrap();
|
||||
assert_eq!(r.total.unwrap().value, Haler(128_490));
|
||||
let r = read(&page("DPH celkem 223,00\nZaokrouhlení 0,10\nSUMA 89,90")).unwrap();
|
||||
assert_eq!(r.total.unwrap().value, Haler(8_990));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_amount_alone_on_the_line_after_its_label_counts() {
|
||||
let r = read(&page("CELKEM\n389,00\n16.11.2026")).unwrap();
|
||||
assert_eq!(r.total.unwrap().value, Haler(38_900));
|
||||
let r = read(&page("CELKEM\n2 ks 389,00")).unwrap();
|
||||
assert!(r.total.is_none(), "a next line that is more than an amount is not the total");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_read_without_confidence_marks_its_field() {
|
||||
let r = read(&page("CELKEM 1 284,90?\n16.11.2026? 14:32")).unwrap();
|
||||
assert!(!r.total.unwrap().sure);
|
||||
assert!(!r.date.unwrap().sure);
|
||||
assert!(r.time.unwrap().sure);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_in_the_ways_receipts_print_them() {
|
||||
for (text, want) in [("16. 11. 2026", "2026-11-16"), ("2026-11-16", "2026-11-16"), ("16.11.26", "2026-11-16"), ("1/2/2027", "2027-02-01"), ("Datum: 05.01.2027 08:15", "2027-01-05")] {
|
||||
assert_eq!(read(&page(text)).unwrap().date.map(|f| f.value), Some(d(want)), "{text}");
|
||||
}
|
||||
for text in ["31.02.2026", "16.11.1999", "16.13.2026", "1.2.3.4"] {
|
||||
assert!(read(&page(text)).unwrap().date.is_none(), "{text}");
|
||||
}
|
||||
assert_eq!(read(&page("Čas 25:61\n09:05")).unwrap().time.map(|f| f.value), Some((9, 5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ico_needs_its_check_digit_and_a_company_dic_gives_one() {
|
||||
assert!(read(&page("IČ: 25672542")).unwrap().ico.is_none(), "the check digit does not fit");
|
||||
assert_eq!(read(&page("IČO 2567254 1")).unwrap().ico, None, "split digits are not an IČO");
|
||||
let r = read(&page("DIČ: CZ 25672541")).unwrap();
|
||||
assert_eq!((r.dic.as_ref().unwrap().value.as_str(), r.ico.unwrap().value.as_str()), ("CZ25672541", "25672541"));
|
||||
let r = read(&page("DIČ: CZ7811241234")).unwrap();
|
||||
assert!(r.ico.is_none(), "a person's DIČ is a birth number, not an IČO");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shop_is_the_first_line_with_a_name_above_the_ico() {
|
||||
let r = read(&page("www.example.cz\n123 456\nLékárna U Anděla\nIČ 25672541\nCELKEM 189,00")).unwrap();
|
||||
assert_eq!(r.shop.unwrap().value, "Lékárna U Anděla");
|
||||
let r = read(&page("IČ 25672541\nZboží 189,00")).unwrap();
|
||||
assert!(r.shop.is_none(), "nothing above the IČO");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_go_on_is_an_empty_receipt_not_an_error() {
|
||||
assert_eq!(read(&[]).unwrap(), Default::default());
|
||||
let r = read(&page("Děkujeme za nákup\nNa shledanou")).unwrap();
|
||||
assert!(r.total.is_none() && r.date.is_none() && r.ico.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_text_is_bounded_and_control_characters_are_dropped() {
|
||||
let many: Vec<Line> = (0..=MAX_LINES).map(|_| Line::default()).collect();
|
||||
assert_eq!(read(&many), Err(ReceiptError::TooLarge));
|
||||
let long = vec![Line { words: vec![Word { text: "x".repeat(81), confidence: 900, bbox: BBox::default() }] }];
|
||||
assert_eq!(read(&long), Err(ReceiptError::TooLarge));
|
||||
let r = read(&page("CELKEM\u{7} 1\u{0} 284,90\nALB\u{1b}ERT")).unwrap();
|
||||
assert_eq!(r.total.unwrap().value, Haler(128_490));
|
||||
let r = read(&page("CELKEM 99 999 999,00")).unwrap();
|
||||
assert!(r.total.is_none(), "over the largest payment Fiscus believes");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn any_text_reads_without_panicking_and_a_total_is_a_believable_payment(words in prop::collection::vec(prop::collection::vec("[ -~ÁČĎÉĚÍŇÓŘŠŤÚŮÝŽáčďéěíňóřšťúůýž×−]{0,12}", 0..12), 0..40)) {
|
||||
let lines: Vec<Line> = words.iter().map(|l| Line { words: l.iter().map(|t| Word { text: t.clone(), confidence: 900, bbox: BBox::default() }).collect() }).collect();
|
||||
if let Ok(r) = read(&lines) {
|
||||
if let Some(t) = r.total {
|
||||
prop_assert!(t.value.0 > 0 && t.value <= fiscus_capture::amount::MAX);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,3 +90,25 @@ proptest! {
|
||||
prop_assert!(parse(&full.as_bytes()[..cut]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_receipt_read_on_the_phone_carries_its_shop_ico_and_dic_and_nothing_else_does() {
|
||||
let body = |extra: &str| format!(r#"{{"amount":"1 284,90","merchant":" Albert Hypermarket ","card":"","time":"2026-11-16T14:32:00+01:00"{extra}}}"#);
|
||||
let c = parse(body(r#","source":"receipt","ico":"25672541","dic":"CZ25672541""#).as_bytes()).unwrap();
|
||||
assert_eq!(c.amount, Haler(-128_490));
|
||||
assert_eq!(c.card, None);
|
||||
let r = c.receipt.unwrap();
|
||||
assert_eq!((r.shop.as_str(), r.ico.as_deref(), r.dic.as_deref()), ("Albert Hypermarket", Some("25672541"), Some("CZ25672541")));
|
||||
let c = parse(body(r#","source":"receipt""#).as_bytes()).unwrap();
|
||||
assert_eq!(c.receipt.unwrap().ico, None, "a receipt without an IČO is fine");
|
||||
assert_eq!(parse(post("129.5").as_bytes()).unwrap().receipt, None, "a card capture has no receipt");
|
||||
for (extra, why) in [
|
||||
(r#","ico":"25672541""#, CaptureError::Receipt),
|
||||
(r#","source":"receipt","ico":"25672542""#, CaptureError::Receipt),
|
||||
(r#","source":"receipt","dic":"SK2020123456""#, CaptureError::Receipt),
|
||||
(r#","source":"card""#, CaptureError::Source),
|
||||
(r#","source":"receipt","items":[]"#, CaptureError::Malformed),
|
||||
] {
|
||||
assert_eq!(parse(body(extra).as_bytes()), Err(why), "{extra}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The cancel kit: where to cancel a known provider, and a polite email to send when there is no page.
|
||||
|
||||
use crate::subscriptions::Subscription;
|
||||
use fiscus_ledger::invoice::Language;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// `(a word in the merchant key, provider, the page where its subscription is cancelled)`.
|
||||
@@ -46,24 +47,52 @@ fn percent(s: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The kit with its email in English.
|
||||
pub fn cancel_kit(sub: &Subscription) -> CancelKit {
|
||||
cancel_kit_in(sub, Language::En)
|
||||
}
|
||||
|
||||
/// The kit with its email in Czech or English (the app's language: most Czech providers read Czech).
|
||||
pub fn cancel_kit_in(sub: &Subscription, language: Language) -> CancelKit {
|
||||
let words: Vec<&str> = sub.merchant_key.split(' ').collect();
|
||||
let known = PROVIDERS.iter().find(|(w, _, _)| words.contains(w));
|
||||
let name = known.map(|(_, p, _)| p.to_string()).unwrap_or_else(|| sub.merchant.clone());
|
||||
let cadence = match sub.cadence {
|
||||
crate::subscriptions::Cadence::Monthly => "monthly",
|
||||
crate::subscriptions::Cadence::Yearly => "yearly",
|
||||
};
|
||||
let last = sub.charges.last().map(|c| c.date.to_string()).unwrap_or_default();
|
||||
CancelKit {
|
||||
provider: known.map(|(_, p, _)| p.to_string()),
|
||||
url: known.map(|(_, _, u)| u.to_string()),
|
||||
email_subject: format!("Cancel my {name} subscription"),
|
||||
email_body: format!(
|
||||
"Hello,\n\nplease cancel my {name} subscription ({cadence}, {} CZK, last charged on {last}) \
|
||||
with effect from the end of the current period, and confirm the cancellation by email.\n\n\
|
||||
Please do not charge my card again.\n\nThank you.",
|
||||
sub.cost.to_czk()
|
||||
let monthly = sub.cadence == crate::subscriptions::Cadence::Monthly;
|
||||
let last = sub.charges.last().map(|c| c.date);
|
||||
let cost = sub.cost.to_czk();
|
||||
let (email_subject, email_body) = match language {
|
||||
Language::En => (
|
||||
format!("Cancel my {name} subscription"),
|
||||
format!(
|
||||
"Hello,
|
||||
|
||||
please cancel my {name} subscription ({}, {cost} CZK, last charged on {}) with effect from the end of the current period, and confirm the cancellation by email.
|
||||
|
||||
Please do not charge my card again.
|
||||
|
||||
Thank you.",
|
||||
if monthly { "monthly" } else { "yearly" },
|
||||
last.map(|d| d.to_string()).unwrap_or_default(),
|
||||
),
|
||||
),
|
||||
}
|
||||
Language::Cs => (
|
||||
format!("Zrušení předplatného {name}"),
|
||||
format!(
|
||||
"Dobrý den,
|
||||
|
||||
prosím o zrušení mého předplatného {name} ({}, {cost} Kč, naposledy strženo {}) ke konci aktuálního období a o potvrzení zrušení e-mailem.
|
||||
|
||||
Prosím, dále mi nestrhávejte platby z karty.
|
||||
|
||||
Děkuji.",
|
||||
if monthly { "měsíční" } else { "roční" },
|
||||
last.map(|d| {
|
||||
let (y, m, day) = d.ymd();
|
||||
format!("{day}. {m}. {y}")
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
),
|
||||
),
|
||||
};
|
||||
CancelKit { provider: known.map(|(_, p, _)| p.to_string()), url: known.map(|(_, _, u)| u.to_string()), email_subject, email_body }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Savings goals this month: how full each one is, what is still needed each month to make its date, the month
|
||||
//! you get there at your pace, this month's saving split between the goal's ways, and where the money could come
|
||||
//! from. Fiscus never moves money; these are suggestions, and a goal fills only with what you say you put aside.
|
||||
|
||||
use crate::plan::month_plan;
|
||||
use crate::spending::{between, category_of, inflow, is_spending, outflows};
|
||||
use crate::subscriptions::{Cadence, Insight, Status};
|
||||
use fiscus_ledger::categories::NOT_PLANNABLE;
|
||||
use fiscus_ledger::goal::{Colour, GoalRecord, Way, WayKind};
|
||||
use fiscus_ledger::{Category, Date, Decision, Haler, State};
|
||||
use serde::Serialize;
|
||||
|
||||
/// One way's part of this month's saving.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct WayPart {
|
||||
pub way: Way,
|
||||
/// What the way comes to this month (before what you already put aside by it).
|
||||
pub amount: Haler,
|
||||
/// Put aside by this way this month.
|
||||
pub saved: Haler,
|
||||
/// Still to put aside by it this month: `amount - saved`, never more than the goal still needs.
|
||||
pub left: Haler,
|
||||
/// Round-ups: the card payments rounded up. Leftover / income: the whole amount the share is of.
|
||||
pub basis: Haler,
|
||||
pub payments: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct GoalStatus {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub colour: Colour,
|
||||
pub target: Haler,
|
||||
pub saved: Haler,
|
||||
/// Saved of the target in thousandths, at most 1000: the tank's level.
|
||||
pub permille: u32,
|
||||
pub reached: bool,
|
||||
pub closed: Option<Date>,
|
||||
pub by: Option<Date>,
|
||||
/// Months from this one to the month of `by`, both included; 0 once it has passed.
|
||||
pub months_left: Option<u32>,
|
||||
/// What is still needed each month to make `by`, rounded up to whole crowns.
|
||||
pub needed_per_month: Option<Haler>,
|
||||
/// Put aside per month on average over the last three complete months the goal had savings in reach of.
|
||||
pub pace: Haler,
|
||||
/// The month you get there at that pace; `None` without a pace (or when reached).
|
||||
pub reach_month: Option<Date>,
|
||||
pub parts: Vec<WayPart>,
|
||||
/// All the parts still to put aside this month.
|
||||
pub left_this_month: Haler,
|
||||
pub saved_this_month: Haler,
|
||||
}
|
||||
|
||||
/// Where the money could come from: it only points, it changes nothing.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Source {
|
||||
/// A subscription still charging that you have not decided to keep: what it costs a month.
|
||||
Subscription { key: String, merchant: String, monthly: Haler },
|
||||
/// A category that cost more last month than its average of the three months before.
|
||||
Category { category: Category, last: Haler, average: Haler, extra: Haler },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct GoalsMonth {
|
||||
/// The 1st of this month.
|
||||
pub month: Date,
|
||||
/// Open goals in the order made, then the closed ones, the latest closed first.
|
||||
pub goals: Vec<GoalStatus>,
|
||||
/// What last month's plans did not use (what "leftover" shares are of).
|
||||
pub leftover: Haler,
|
||||
/// Last month's money in (what "income" shares are of).
|
||||
pub income: Haler,
|
||||
/// Leftover and income already given to goals, in thousandths.
|
||||
pub leftover_given: u32,
|
||||
pub income_given: u32,
|
||||
/// Everything in open goals.
|
||||
pub saved: Haler,
|
||||
pub sources: Vec<Source>,
|
||||
}
|
||||
|
||||
/// `a / b` rounded up, both positive.
|
||||
fn div_up(a: i64, b: i64) -> i64 {
|
||||
(a + b - 1) / b
|
||||
}
|
||||
|
||||
fn share(of: Haler, permille: u32) -> Haler {
|
||||
Haler((i128::from(of.0.max(0)) * i128::from(permille) / 1000) as i64)
|
||||
}
|
||||
|
||||
fn months_between(from: Date, to: Date) -> i64 {
|
||||
let (fy, fm, _) = from.ymd();
|
||||
let (ty, tm, _) = to.ymd();
|
||||
i64::from(ty - fy) * 12 + i64::from(tm) - i64::from(fm)
|
||||
}
|
||||
|
||||
/// Round-ups this month: each spending payment rounded up to the next `to`; a payment already a multiple adds 0.
|
||||
pub fn round_ups(state: &State, to: Haler, today: Date) -> (Haler, usize) {
|
||||
if to.0 <= 0 {
|
||||
return (Haler::ZERO, 0);
|
||||
}
|
||||
let mut sum = 0i64;
|
||||
let mut n = 0;
|
||||
for p in between(state, today.month_start(), today).iter().filter(|p| is_spending(p)) {
|
||||
let paid = p.amount.0.saturating_neg();
|
||||
let r = paid % to.0;
|
||||
if r != 0 {
|
||||
sum = sum.saturating_add(to.0 - r);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
(Haler(sum), n)
|
||||
}
|
||||
|
||||
/// What last month's plans did not use: for each planned category, the plan less what was spent, never below 0.
|
||||
pub fn leftover(state: &State, today: Date) -> Haler {
|
||||
let last = today.month_start().add_months(-1);
|
||||
let Some(p) = month_plan(state, last, today) else { return Haler::ZERO };
|
||||
Haler(p.rows.iter().filter_map(|r| r.left).fold(0i64, |s, l| s.saturating_add(l.0.max(0))))
|
||||
}
|
||||
|
||||
/// Last month's money in, not counting transfers.
|
||||
pub fn last_income(state: &State, today: Date) -> Haler {
|
||||
let last = today.month_start().add_months(-1);
|
||||
inflow(&between(state, last, last.month_end())).unwrap_or(Haler::ZERO)
|
||||
}
|
||||
|
||||
fn saved_in(g: &GoalRecord, from: Date, to: Date, way: Option<WayKind>) -> Haler {
|
||||
Haler(
|
||||
g.savings
|
||||
.iter()
|
||||
.filter(|s| s.on >= from && s.on <= to && (way.is_none() || s.way == way))
|
||||
.fold(0i64, |sum, s| sum.saturating_add(s.amount.0)),
|
||||
)
|
||||
}
|
||||
|
||||
fn status(g: &GoalRecord, today: Date, leftover: Haler, income: Haler, rounds: &mut dyn FnMut(Haler) -> (Haler, usize)) -> GoalStatus {
|
||||
let month = today.month_start();
|
||||
let saved = g.saved();
|
||||
let remaining = Haler(g.target.0.saturating_sub(saved.0).max(0));
|
||||
let reached = remaining.0 == 0;
|
||||
let permille = if g.target.0 > 0 { (i128::from(saved.0.max(0)) * 1000 / i128::from(g.target.0)).min(1000) as u32 } else { 0 };
|
||||
|
||||
let months_left = g.by.map(|by| (months_between(month, by.month_start()) + 1).max(0) as u32);
|
||||
let needed_per_month = match (months_left, reached) {
|
||||
(_, true) | (None, _) => None,
|
||||
(Some(0), false) => Some(remaining),
|
||||
(Some(n), false) => Some(Haler(div_up(div_up(remaining.0, i64::from(n)), 100) * 100)),
|
||||
};
|
||||
|
||||
// The pace: the last three complete months, from the month of the first saving on.
|
||||
let first = g.savings.iter().map(|s| s.on.month_start()).min();
|
||||
let pace = match first {
|
||||
Some(first) if first < month => {
|
||||
let from = month.add_months(-3).max(first);
|
||||
let n = months_between(from, month).max(1);
|
||||
Haler(saved_in(g, from, month.add_days(-1), None).0 / n)
|
||||
}
|
||||
_ => Haler::ZERO,
|
||||
};
|
||||
let reach_month = (!reached && pace.0 > 0 && g.is_open()).then(|| {
|
||||
let n = div_up(remaining.0, pace.0).min(1200) as i32;
|
||||
month.add_months(n)
|
||||
});
|
||||
|
||||
let mut budget = remaining.0;
|
||||
let parts: Vec<WayPart> = if g.is_open() {
|
||||
g.ways
|
||||
.iter()
|
||||
.map(|w| {
|
||||
let (amount, basis, payments) = match *w {
|
||||
Way::Fixed { amount } => (amount, amount, 0),
|
||||
Way::RoundUp { to } => {
|
||||
let (sum, n) = rounds(to);
|
||||
(sum, sum, n)
|
||||
}
|
||||
Way::Leftover { permille } => (share(leftover, u32::from(permille)), leftover, 0),
|
||||
Way::Income { permille } => (share(income, u32::from(permille)), income, 0),
|
||||
};
|
||||
let saved = saved_in(g, month, month.month_end(), Some(w.kind()));
|
||||
let left = amount.0.saturating_sub(saved.0).clamp(0, budget.max(0));
|
||||
budget -= left;
|
||||
WayPart { way: *w, amount, saved, left: Haler(left), basis, payments }
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let left_this_month = Haler(parts.iter().map(|p| p.left.0).sum());
|
||||
|
||||
GoalStatus {
|
||||
id: g.id.clone(),
|
||||
name: g.name.clone(),
|
||||
colour: g.colour,
|
||||
target: g.target,
|
||||
saved,
|
||||
permille,
|
||||
reached,
|
||||
closed: g.closed,
|
||||
by: g.by,
|
||||
months_left,
|
||||
needed_per_month,
|
||||
pace,
|
||||
reach_month,
|
||||
parts,
|
||||
left_this_month,
|
||||
saved_this_month: saved_in(g, month, month.month_end(), None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscriptions still charging and not decided "keep", the costliest a month first; then categories that cost
|
||||
/// more last month than the three months before, by at least 10 % and 200 Kč.
|
||||
pub fn sources(state: &State, insight: &Insight, today: Date) -> Vec<Source> {
|
||||
let mut subs: Vec<Source> = insight
|
||||
.subscriptions
|
||||
.iter()
|
||||
.filter(|s| s.status == Status::Active && s.decision.as_ref().map(|d| d.decision) != Some(Decision::Keep))
|
||||
.map(|s| Source::Subscription {
|
||||
key: s.key.clone(),
|
||||
merchant: s.merchant.clone(),
|
||||
monthly: match s.cadence {
|
||||
Cadence::Monthly => s.cost,
|
||||
Cadence::Yearly => Haler(div_up(s.cost.0, 12)),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
subs.sort_by_key(|s| match s {
|
||||
Source::Subscription { monthly, .. } => std::cmp::Reverse(monthly.0),
|
||||
_ => std::cmp::Reverse(0),
|
||||
});
|
||||
subs.truncate(5);
|
||||
|
||||
let last = today.month_start().add_months(-1);
|
||||
let first = state.effective_payments().iter().map(|p| p.date.month_start()).min();
|
||||
let mut cats = Vec::new();
|
||||
if let Some(first) = first {
|
||||
let earlier: Vec<Date> = (1..=3).map(|n| last.add_months(-n)).filter(|m| *m >= first).collect();
|
||||
if let (Some(oldest), Some(spent_last)) = (earlier.last().copied(), outflows(&between(state, last, last.month_end()))) {
|
||||
if let Some(spent_before) = outflows(&between(state, oldest, last.add_days(-1))) {
|
||||
for (category, amount) in spent_last {
|
||||
if NOT_PLANNABLE.contains(&category.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let average = Haler(spent_before.get(&category).map(|h| h.0).unwrap_or(0) / earlier.len() as i64);
|
||||
let extra = amount.0.saturating_sub(average.0);
|
||||
if average.0 > 0 && extra >= 20_000 && i128::from(amount.0) * 10 > i128::from(average.0) * 11 {
|
||||
cats.push(Source::Category { category, last: amount, average, extra: Haler(extra) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cats.sort_by_key(|s| match s {
|
||||
Source::Category { extra, .. } => std::cmp::Reverse(extra.0),
|
||||
_ => std::cmp::Reverse(0),
|
||||
});
|
||||
cats.truncate(3);
|
||||
subs.extend(cats);
|
||||
subs
|
||||
}
|
||||
|
||||
pub fn goals_month(state: &State, insight: &Insight, today: Date) -> GoalsMonth {
|
||||
let leftover = leftover(state, today);
|
||||
let income = last_income(state, today);
|
||||
let mut cache: Vec<(Haler, (Haler, usize))> = Vec::new();
|
||||
let mut rounds = |to: Haler| {
|
||||
if let Some((_, r)) = cache.iter().find(|(t, _)| *t == to) {
|
||||
return *r;
|
||||
}
|
||||
let r = round_ups(state, to, today);
|
||||
cache.push((to, r));
|
||||
r
|
||||
};
|
||||
let mut open: Vec<&GoalRecord> = state.goals.values().filter(|g| g.is_open()).collect();
|
||||
open.sort_by_key(|g| g.seq);
|
||||
let mut closed: Vec<&GoalRecord> = state.goals.values().filter(|g| !g.is_open()).collect();
|
||||
closed.sort_by_key(|g| std::cmp::Reverse((g.closed, g.seq)));
|
||||
let given = |kind: WayKind| open.iter().flat_map(|g| g.ways.iter()).map(|w| w.share_of(kind)).sum::<u32>();
|
||||
let (leftover_given, income_given) = (given(WayKind::Leftover), given(WayKind::Income));
|
||||
let saved = Haler(open.iter().fold(0i64, |s, g| s.saturating_add(g.saved().0)));
|
||||
let goals = open.iter().chain(closed.iter()).map(|g| status(g, today, leftover, income, &mut rounds)).collect();
|
||||
GoalsMonth { month: today.month_start(), goals, leftover, income, leftover_given, income_given, saved, sources: sources(state, insight, today) }
|
||||
}
|
||||
|
||||
/// What was spent in one category from `from` to `to`, both included (positive).
|
||||
pub fn spent_in(state: &State, category: &str, from: Date, to: Date) -> Haler {
|
||||
Haler(
|
||||
between(state, from, to)
|
||||
.iter()
|
||||
.filter(|p| is_spending(p) && category_of(p) == category)
|
||||
.fold(0i64, |s, p| s.saturating_add(p.amount.0.saturating_neg())),
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Household duplicates: two or more members paying for the same service ("You both pay Spotify"). Runs only
|
||||
//! on the subscription names members chose to share into the household budget.
|
||||
|
||||
use crate::subscriptions::{analyse, Status};
|
||||
use fiscus_ledger::merchant::merchant_key;
|
||||
use fiscus_ledger::{Date, State};
|
||||
use serde::Serialize;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -34,3 +36,16 @@ pub fn household_duplicates(shared: &[(String, Vec<String>)]) -> Vec<Duplicate>
|
||||
.map(|(key, m)| Duplicate { key, members: m.into_iter().collect() })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a member who opted in shares: the service key of every subscription they still pay (active, or charged
|
||||
/// after a cancel), sorted, at most 100. Only the key leaves, never the merchant text with its references.
|
||||
pub fn shared_names(state: &State, today: Date) -> Vec<String> {
|
||||
let keys: BTreeSet<String> = analyse(state, today)
|
||||
.subscriptions
|
||||
.iter()
|
||||
.filter(|s| matches!(s.status, Status::Active | Status::ChargedAfterCancel))
|
||||
.filter_map(|s| service_key(&s.merchant))
|
||||
.filter(|k| k.chars().count() <= 40)
|
||||
.collect();
|
||||
keys.into_iter().take(100).collect()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
//! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge,
|
||||
//! how to cancel, and whether the month will stay under its limit. Pure: "today" and seeds are parameters.
|
||||
//! how to cancel, whether the month will stay under its limit, where the money went and how it compares with
|
||||
//! your plan, how your savings goals fill, your projects against their budgets and tasks, and the medals and challenges you earn. Pure: "today" and seeds are parameters.
|
||||
|
||||
pub mod cancel;
|
||||
pub mod forecast;
|
||||
pub mod goals;
|
||||
pub mod household;
|
||||
pub mod plan;
|
||||
pub mod projects;
|
||||
pub mod rewards;
|
||||
pub mod spending;
|
||||
pub mod stats;
|
||||
pub mod subscriptions;
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
//! The month against your plan: for each category, what you meant to spend (`category.planned`), what you
|
||||
//! spent, what is left, and whether you are ahead of the pace the plan allows by today. Only your own payments
|
||||
//! count, as in the forecast; what other members of a shared budget spend is theirs.
|
||||
|
||||
use crate::spending::{between, outflows};
|
||||
use fiscus_ledger::categories::{self, NOT_PLANNABLE};
|
||||
use fiscus_ledger::date::days_in_month;
|
||||
use fiscus_ledger::{Category, Date, Haler, State};
|
||||
use serde::Serialize;
|
||||
|
||||
/// How a planned category is doing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Pace {
|
||||
/// Below 90 % of what the plan allows by today (or, for a past month, within the plan).
|
||||
Under,
|
||||
OnPace,
|
||||
/// Above 110 % of what the plan allows by today, not over the plan yet.
|
||||
Ahead,
|
||||
/// More than the whole month's plan.
|
||||
Over,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct PlanRow {
|
||||
pub category: Category,
|
||||
pub planned: Option<Haler>,
|
||||
pub spent: Haler,
|
||||
/// Planned less spent; negative when over. `None` without a plan.
|
||||
pub left: Option<Haler>,
|
||||
/// Spent of the plan in thousandths, capped at 1000 (for a bar); 0 without a plan.
|
||||
pub permille: u32,
|
||||
/// `None` without a plan, and for a month that has not begun.
|
||||
pub pace: Option<Pace>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct MonthPlan {
|
||||
/// The 1st of the month.
|
||||
pub month: Date,
|
||||
/// The categories with a plan this month, in the app's order, then those spent on without a plan, the
|
||||
/// largest first.
|
||||
pub rows: Vec<PlanRow>,
|
||||
/// All the plans of the month together.
|
||||
pub planned: Haler,
|
||||
/// Everything spent this month.
|
||||
pub spent: Haler,
|
||||
/// Of that, spent in categories without a plan.
|
||||
pub unplanned: Haler,
|
||||
}
|
||||
|
||||
fn pace(planned: Haler, spent: Haler, month: Date, today: Date) -> Option<Pace> {
|
||||
if today < month {
|
||||
return None;
|
||||
}
|
||||
if spent > planned {
|
||||
return Some(Pace::Over);
|
||||
}
|
||||
if today > month.month_end() {
|
||||
return Some(Pace::Under);
|
||||
}
|
||||
let (y, m, day) = today.ymd();
|
||||
let allowed = i128::from(planned.0) * i128::from(day) / i128::from(days_in_month(y, m));
|
||||
let spent = i128::from(spent.0) * 100;
|
||||
Some(if spent > allowed * 110 {
|
||||
Pace::Ahead
|
||||
} else if spent < allowed * 90 {
|
||||
Pace::Under
|
||||
} else {
|
||||
Pace::OnPace
|
||||
})
|
||||
}
|
||||
|
||||
/// The month of `month` against its plans. For this month, what is spent up to `today`; a later month has
|
||||
/// nothing spent yet. `None` when a sum would not fit.
|
||||
pub fn month_plan(state: &State, month: Date, today: Date) -> Option<MonthPlan> {
|
||||
let start = month.month_start();
|
||||
let end = start.month_end().min(today);
|
||||
let spent_by = if end < start { Default::default() } else { outflows(&between(state, start, end))? };
|
||||
let spent_in = |c: &str| spent_by.get(c).copied().unwrap_or(Haler::ZERO);
|
||||
|
||||
let mut rows = Vec::new();
|
||||
for (category, _) in state.categories() {
|
||||
let Some(planned) = state.plan_for(&category, start) else { continue };
|
||||
let spent = spent_in(&category);
|
||||
let permille = (i128::from(spent.0) * 1000 / i128::from(planned.0)).clamp(0, 1000) as u32;
|
||||
rows.push(PlanRow { left: Some(planned.checked_sub(spent).ok()?), planned: Some(planned), permille, pace: pace(planned, spent, start, today), spent, category });
|
||||
}
|
||||
let mut extra: Vec<(&Category, &Haler)> = spent_by.iter().filter(|(c, _)| state.plan_for(c, start).is_none()).collect();
|
||||
extra.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
|
||||
let unplanned = Haler::sum(extra.iter().map(|(_, a)| **a)).ok()?;
|
||||
rows.extend(extra.into_iter().map(|(c, a)| PlanRow { category: c.clone(), planned: None, spent: *a, left: None, permille: 0, pace: None }));
|
||||
|
||||
Some(MonthPlan {
|
||||
month: start,
|
||||
planned: Haler::sum(rows.iter().filter_map(|r| r.planned)).ok()?,
|
||||
spent: Haler::sum(spent_by.values().copied()).ok()?,
|
||||
unplanned,
|
||||
rows,
|
||||
})
|
||||
}
|
||||
|
||||
/// A plan from your history: for each category you can plan, the average of what you spent on it over the last
|
||||
/// three complete months, rounded **up** to whole hundreds of crowns. Only months since your first payment
|
||||
/// count, so a ledger a month old is not divided by three. Categories you spent nothing on are left out.
|
||||
pub fn suggest(state: &State, today: Date) -> Vec<(Category, Haler)> {
|
||||
let this_month = today.month_start();
|
||||
let Some(first) = state.effective_payments().first().map(|p| p.date.month_start()) else { return Vec::new() };
|
||||
let months: Vec<Date> = (1..=3).map(|n| this_month.add_months(-n)).filter(|m| *m >= first).collect();
|
||||
let Some(oldest) = months.last().copied() else { return Vec::new() };
|
||||
let Some(spent) = outflows(&between(state, oldest, this_month.add_days(-1))) else { return Vec::new() };
|
||||
let hundred = 10_000i128;
|
||||
let mut out = Vec::new();
|
||||
for (category, _) in state.categories() {
|
||||
if NOT_PLANNABLE.contains(&category.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(total) = spent.get(&category).filter(|t| t.0 > 0) else { continue };
|
||||
// Both are positive: rounding up is (a + b - 1) / b.
|
||||
let n = months.len() as i128;
|
||||
let avg = (i128::from(total.0) + n - 1) / n;
|
||||
let up = (avg + hundred - 1) / hundred * hundred;
|
||||
match i64::try_from(up) {
|
||||
Ok(v) if Haler(v) <= categories::MAX_PLAN => out.push((category, Haler(v))),
|
||||
_ => out.push((category, categories::MAX_PLAN)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Projects: what each one has cost against its budget lines, what it earned (a business), how far its tasks are,
|
||||
//! what it will cost in the end, whether it is late, and its time. A payment counts in a project by hand
|
||||
//! (`payment.projected`) or by a project rule of its merchant; it still counts in its budget and its month too.
|
||||
|
||||
use crate::spending::is_spending;
|
||||
use fiscus_ledger::goal::Colour;
|
||||
use fiscus_ledger::project::{week_of, EntryId, Kind, Phase, ProjectRecord, Status, TaskRecord, TaskStatus};
|
||||
use fiscus_ledger::{Date, Haler, State};
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct LineStatus {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub planned: Haler,
|
||||
pub spent: Haler,
|
||||
/// Planned less spent; negative when over.
|
||||
pub left: Haler,
|
||||
pub over: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
|
||||
pub struct TaskCounts {
|
||||
pub todo: usize,
|
||||
pub doing: usize,
|
||||
pub done: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct ProjectSummary {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub kind: Kind,
|
||||
pub status: Status,
|
||||
pub colour: Colour,
|
||||
pub starts: Option<Date>,
|
||||
pub ends: Option<Date>,
|
||||
/// All the budget lines together.
|
||||
pub planned: Haler,
|
||||
/// Money out of the payments in the project (positive).
|
||||
pub spent: Haler,
|
||||
/// A business: paid invoices of the project (without VAT) and money in put into it.
|
||||
pub income: Haler,
|
||||
pub profit: Haler,
|
||||
/// Profit of income in thousandths; `None` without income.
|
||||
pub margin_permille: Option<i64>,
|
||||
/// What the open tasks are estimated to cost.
|
||||
pub open_estimates: Haler,
|
||||
/// Spent plus the open estimates: what it will have cost.
|
||||
pub forecast: Haler,
|
||||
/// Tasks done, in thousandths: by their estimates when every task has one, else by count.
|
||||
pub progress_permille: u32,
|
||||
pub tasks: TaskCounts,
|
||||
pub late_tasks: usize,
|
||||
/// Spent, or the forecast, above the plan.
|
||||
pub over_budget: bool,
|
||||
/// An open task past its due date, or the project past its end with tasks open.
|
||||
pub late: bool,
|
||||
pub minutes: u64,
|
||||
pub unbilled_minutes: u64,
|
||||
pub unbilled: Haler,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct ProjectPayment {
|
||||
pub id: String,
|
||||
pub date: Date,
|
||||
pub merchant: String,
|
||||
pub amount: Haler,
|
||||
pub line: Option<String>,
|
||||
/// Counted by a project rule, not put in by hand.
|
||||
pub by_rule: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct TaskStatusRow {
|
||||
pub task: TaskRecord,
|
||||
pub late: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct TaskTime {
|
||||
pub task: Option<String>,
|
||||
pub minutes: u64,
|
||||
pub amount: Haler,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct ProjectDetail {
|
||||
pub summary: ProjectSummary,
|
||||
pub lines: Vec<LineStatus>,
|
||||
/// Spent outside any line.
|
||||
pub unplanned: Haler,
|
||||
/// The latest first.
|
||||
pub payments: Vec<ProjectPayment>,
|
||||
/// Open tasks by due date (none last), then the done ones, the latest done first.
|
||||
pub tasks: Vec<TaskStatusRow>,
|
||||
/// By start.
|
||||
pub phases: Vec<Phase>,
|
||||
pub time_by_task: Vec<TaskTime>,
|
||||
/// Monday of each week with time → minutes, oldest first.
|
||||
pub time_by_week: Vec<(Date, u64)>,
|
||||
/// What all the time is worth, and the entries not invoiced yet (by date).
|
||||
pub billable: Haler,
|
||||
pub unbilled_entries: Vec<EntryId>,
|
||||
pub invoices: Vec<String>,
|
||||
}
|
||||
|
||||
fn sum(it: impl Iterator<Item = Haler>) -> Haler {
|
||||
Haler(it.fold(0i64, |s, h| s.saturating_add(h.0)))
|
||||
}
|
||||
|
||||
fn permille(part: i64, whole: i64) -> u32 {
|
||||
if whole <= 0 {
|
||||
return 0;
|
||||
}
|
||||
(i128::from(part.clamp(0, whole)) * 1000 / i128::from(whole)) as u32
|
||||
}
|
||||
|
||||
fn summary_and_rows(state: &State, p: &ProjectRecord, today: Date) -> (ProjectSummary, Vec<LineStatus>, Haler, Vec<ProjectPayment>, Vec<TaskStatusRow>) {
|
||||
// The payments in the project.
|
||||
let mut payments = Vec::new();
|
||||
let mut by_line: BTreeMap<Option<String>, i64> = BTreeMap::new();
|
||||
let mut inflow = 0i64;
|
||||
let invoice_payments: Vec<&String> = state.invoice_payments.iter().filter(|(_, inv)| p.invoices.contains(*inv)).map(|(pay, _)| pay).collect();
|
||||
for e in state.effective_payments() {
|
||||
let Some((project, line)) = state.project_of(&e) else { continue };
|
||||
if project != p.id {
|
||||
continue;
|
||||
}
|
||||
let line = line.filter(|l| p.line(l).is_some());
|
||||
if is_spending(&e) {
|
||||
let slot = by_line.entry(line.clone()).or_insert(0);
|
||||
*slot = slot.saturating_add(e.amount.0.saturating_neg());
|
||||
} else if e.amount.0 > 0 && e.category.as_deref() != Some(fiscus_ledger::categories::TRANSFERS) && !invoice_payments.contains(&&e.id) {
|
||||
inflow = inflow.saturating_add(e.amount.0);
|
||||
}
|
||||
payments.push(ProjectPayment { by_rule: !state.projects.payments.contains_key(&e.id), id: e.id, date: e.date, merchant: e.merchant, amount: e.amount, line });
|
||||
}
|
||||
payments.sort_by(|a, b| b.date.cmp(&a.date).then(a.id.cmp(&b.id)));
|
||||
let spent = Haler(by_line.values().fold(0i64, |s, v| s.saturating_add(*v)));
|
||||
let unplanned = Haler(by_line.get(&None).copied().unwrap_or(0));
|
||||
let lines: Vec<LineStatus> = p
|
||||
.lines
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let s = Haler(by_line.get(&Some(l.id.clone())).copied().unwrap_or(0));
|
||||
let left = Haler(l.planned.0.saturating_sub(s.0));
|
||||
LineStatus { id: l.id.clone(), name: l.name.clone(), planned: l.planned, spent: s, left, over: left.0 < 0 }
|
||||
})
|
||||
.collect();
|
||||
let planned = sum(p.lines.iter().map(|l| l.planned));
|
||||
|
||||
// Income: the project's paid invoices without VAT, and money in put into it (not the lines that paid them).
|
||||
let invoiced = sum(p.invoices.iter().filter_map(|i| state.invoices.get(i)).filter(|r| r.paid.is_some() && !r.cancelled).map(|r| r.totals.net));
|
||||
let income = Haler(invoiced.0.saturating_add(inflow));
|
||||
let profit = Haler(income.0.saturating_sub(spent.0));
|
||||
let margin_permille = (income.0 > 0).then(|| (i128::from(profit.0) * 1000 / i128::from(income.0)) as i64);
|
||||
|
||||
// Tasks.
|
||||
let mut tasks: Vec<TaskStatusRow> = state
|
||||
.projects
|
||||
.tasks
|
||||
.values()
|
||||
.filter(|t| t.project == p.id)
|
||||
.map(|t| TaskStatusRow { late: t.status != TaskStatus::Done && t.fields.due.is_some_and(|d| d < today), task: t.clone() })
|
||||
.collect();
|
||||
tasks.sort_by(|a, b| {
|
||||
let done = |t: &TaskStatusRow| t.task.status == TaskStatus::Done;
|
||||
done(a).cmp(&done(b)).then_with(|| {
|
||||
if done(a) {
|
||||
b.task.done_on.cmp(&a.task.done_on)
|
||||
} else {
|
||||
(a.task.fields.due.is_none(), a.task.fields.due).cmp(&(b.task.fields.due.is_none(), b.task.fields.due))
|
||||
}
|
||||
})
|
||||
.then(a.task.seq.cmp(&b.task.seq))
|
||||
});
|
||||
let mut counts = TaskCounts::default();
|
||||
for t in &tasks {
|
||||
match t.task.status {
|
||||
TaskStatus::Todo => counts.todo += 1,
|
||||
TaskStatus::Doing => counts.doing += 1,
|
||||
TaskStatus::Done => counts.done += 1,
|
||||
}
|
||||
}
|
||||
let open_estimates = sum(tasks.iter().filter(|t| t.task.status != TaskStatus::Done).filter_map(|t| t.task.fields.estimate));
|
||||
let all_estimated = !tasks.is_empty() && tasks.iter().all(|t| t.task.fields.estimate.is_some_and(|e| e.0 > 0));
|
||||
let progress_permille = if all_estimated {
|
||||
let total = sum(tasks.iter().filter_map(|t| t.task.fields.estimate));
|
||||
let done = sum(tasks.iter().filter(|t| t.task.status == TaskStatus::Done).filter_map(|t| t.task.fields.estimate));
|
||||
permille(done.0, total.0)
|
||||
} else {
|
||||
permille(counts.done as i64, tasks.len() as i64)
|
||||
};
|
||||
let forecast = Haler(spent.0.saturating_add(open_estimates.0));
|
||||
let late_tasks = tasks.iter().filter(|t| t.late).count();
|
||||
let open = p.is_open();
|
||||
let late = open && (late_tasks > 0 || (p.ends.is_some_and(|e| e < today) && counts.todo + counts.doing > 0));
|
||||
let over_budget = planned.0 > 0 && (spent > planned || forecast > planned);
|
||||
|
||||
// Time.
|
||||
let entries: Vec<_> = state.projects.time.values().filter(|t| t.project == p.id).collect();
|
||||
let minutes: u64 = entries.iter().map(|t| u64::from(t.minutes)).sum();
|
||||
let unbilled_minutes: u64 = entries.iter().filter(|t| t.invoice.is_none()).map(|t| u64::from(t.minutes)).sum();
|
||||
let unbilled = sum(entries.iter().filter(|t| t.invoice.is_none()).map(|t| t.amount()));
|
||||
|
||||
let summary = ProjectSummary {
|
||||
id: p.id.clone(),
|
||||
name: p.name.clone(),
|
||||
kind: p.kind,
|
||||
status: p.status,
|
||||
colour: p.colour,
|
||||
starts: p.starts,
|
||||
ends: p.ends,
|
||||
planned,
|
||||
spent,
|
||||
income,
|
||||
profit,
|
||||
margin_permille,
|
||||
open_estimates,
|
||||
forecast,
|
||||
progress_permille,
|
||||
tasks: counts,
|
||||
late_tasks,
|
||||
over_budget,
|
||||
late,
|
||||
minutes,
|
||||
unbilled_minutes,
|
||||
unbilled,
|
||||
};
|
||||
(summary, lines, unplanned, payments, tasks)
|
||||
}
|
||||
|
||||
/// Every project: the open ones in the order made, then the done ones, the latest done first.
|
||||
pub fn projects(state: &State, today: Date) -> Vec<ProjectSummary> {
|
||||
let mut open: Vec<&ProjectRecord> = state.projects.projects.values().filter(|p| p.is_open()).collect();
|
||||
open.sort_by_key(|p| p.seq);
|
||||
let mut done: Vec<&ProjectRecord> = state.projects.projects.values().filter(|p| !p.is_open()).collect();
|
||||
done.sort_by_key(|p| std::cmp::Reverse((p.status_on, p.seq)));
|
||||
open.into_iter().chain(done).map(|p| summary_and_rows(state, p, today).0).collect()
|
||||
}
|
||||
|
||||
/// One project in full.
|
||||
pub fn project(state: &State, id: &str, today: Date) -> Option<ProjectDetail> {
|
||||
let p = state.projects.projects.get(id)?;
|
||||
let (summary, lines, unplanned, payments, tasks) = summary_and_rows(state, p, today);
|
||||
let mut phases = p.phases.clone();
|
||||
phases.sort_by(|a, b| a.starts.cmp(&b.starts).then(a.id.cmp(&b.id)));
|
||||
|
||||
let mut entries: Vec<_> = state.projects.time.values().filter(|t| t.project == p.id).collect();
|
||||
entries.sort_by(|a, b| a.on.cmp(&b.on).then(a.seq.cmp(&b.seq)));
|
||||
let mut by_task: BTreeMap<Option<String>, (u64, i64)> = BTreeMap::new();
|
||||
let mut by_week: BTreeMap<Date, u64> = BTreeMap::new();
|
||||
for t in &entries {
|
||||
let slot = by_task.entry(t.task.clone()).or_insert((0, 0));
|
||||
slot.0 += u64::from(t.minutes);
|
||||
slot.1 = slot.1.saturating_add(t.amount().0);
|
||||
*by_week.entry(week_of(t.on)).or_insert(0) += u64::from(t.minutes);
|
||||
}
|
||||
let mut time_by_task: Vec<TaskTime> = by_task.into_iter().map(|(task, (minutes, amount))| TaskTime { task, minutes, amount: Haler(amount) }).collect();
|
||||
time_by_task.sort_by(|a, b| b.minutes.cmp(&a.minutes).then(a.task.cmp(&b.task)));
|
||||
|
||||
Some(ProjectDetail {
|
||||
lines,
|
||||
unplanned,
|
||||
payments,
|
||||
tasks,
|
||||
phases,
|
||||
time_by_task,
|
||||
time_by_week: by_week.into_iter().collect(),
|
||||
billable: sum(entries.iter().map(|t| t.amount())),
|
||||
unbilled_entries: entries.iter().filter(|t| t.invoice.is_none()).map(|t| t.id.clone()).collect(),
|
||||
invoices: p.invoices.iter().cloned().collect(),
|
||||
summary,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
//! Medals and challenges, computed from the ledger and never stored. A medal is earned by a complete period
|
||||
//! (a month, a quarter, a challenge's last day); what is still running shows how far it is.
|
||||
|
||||
use crate::goals::spent_in;
|
||||
use crate::plan::month_plan;
|
||||
use crate::spending::is_spending;
|
||||
use crate::subscriptions::{Insight, Status};
|
||||
use fiscus_ledger::goal::{ChallengeGoal, ChallengeRecord};
|
||||
use fiscus_ledger::{BudgetId, Date, Decision, Haler, State};
|
||||
use serde::Serialize;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// A run of months this long earns the streak medals.
|
||||
pub const STREAK: u32 = 3;
|
||||
/// A goal's milestones, in thousandths of its target.
|
||||
pub const MILESTONES: [u32; 4] = [250, 500, 750, 1000];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Medal {
|
||||
/// A budget under its limit this many complete months running (3 or more), up to `until`'s month.
|
||||
UnderBudget { budget: BudgetId, name: String, months: u32, until: Date },
|
||||
/// Every category plan of a month kept (a month with at least one plan).
|
||||
PlansKept { month: Date },
|
||||
/// A subscription decided "cancel" and not charged since, past the day it would have charged.
|
||||
Cancelled { subscription: String, merchant: String, since: Date },
|
||||
/// A challenge won.
|
||||
ChallengeWon { challenge: String, goal: ChallengeGoal },
|
||||
/// Every invoice due in a quarter paid by its due date.
|
||||
InvoicesOnTime { year: i32, quarter: u32 },
|
||||
/// A goal reached a quarter, a half, three quarters, or all of its target.
|
||||
GoalMilestone { goal: String, name: String, permille: u32 },
|
||||
/// Money put aside in this many complete months running (3 or more), up to `until`'s month.
|
||||
SavingStreak { months: u32, until: Date },
|
||||
/// A project done within its budget (it had one).
|
||||
ProjectOnBudget { project: String, name: String },
|
||||
/// A project done by its end date (it had one).
|
||||
FinishedOnTime { project: String, name: String },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct Earned {
|
||||
pub medal: Medal,
|
||||
/// The day it was earned.
|
||||
pub on: Date,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Outcome {
|
||||
Running,
|
||||
Won,
|
||||
Lost,
|
||||
Abandoned,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct ChallengeStatus {
|
||||
pub id: String,
|
||||
pub goal: ChallengeGoal,
|
||||
pub starts: Date,
|
||||
pub ends: Date,
|
||||
pub outcome: Outcome,
|
||||
/// Spent in the category (spending challenges) or put aside (saving), so far.
|
||||
pub so_far: Haler,
|
||||
/// The tank: what is left of a spending limit, or what is saved of the amount, in thousandths (at most 1000).
|
||||
pub permille: u32,
|
||||
/// Days to the last day, 0 on it and after.
|
||||
pub days_left: i32,
|
||||
}
|
||||
|
||||
/// How far the medals still to come are.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct Progress {
|
||||
/// Complete months running with money put aside, up to last month.
|
||||
pub saving_months: u32,
|
||||
pub saved_this_month: bool,
|
||||
/// Each budget with a limit: complete months running under it, up to last month.
|
||||
pub budgets: Vec<(BudgetId, String, u32)>,
|
||||
/// Each open goal not yet full: its level and the next milestone.
|
||||
pub goals: Vec<(String, String, u32, u32)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct Rewards {
|
||||
/// The latest first.
|
||||
pub medals: Vec<Earned>,
|
||||
/// Running first (the soonest to end first), then the finished ones, the latest first.
|
||||
pub challenges: Vec<ChallengeStatus>,
|
||||
pub progress: Progress,
|
||||
}
|
||||
|
||||
fn permille(part: i64, whole: i64) -> u32 {
|
||||
if whole <= 0 {
|
||||
return 0;
|
||||
}
|
||||
(i128::from(part.clamp(0, whole)) * 1000 / i128::from(whole)) as u32
|
||||
}
|
||||
|
||||
/// Runs of `true` months: (length, last month of the run).
|
||||
fn runs(months: &[(Date, bool)]) -> Vec<(u32, Date)> {
|
||||
let mut out = Vec::new();
|
||||
let mut n = 0u32;
|
||||
for (i, (m, ok)) in months.iter().enumerate() {
|
||||
if *ok {
|
||||
n += 1;
|
||||
}
|
||||
let ends = !*ok || i + 1 == months.len();
|
||||
if ends && n > 0 {
|
||||
let last = if *ok { *m } else { months[i - 1].0 };
|
||||
out.push((n, last));
|
||||
n = 0;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The run that reaches the last month, if it does.
|
||||
fn current(months: &[(Date, bool)]) -> u32 {
|
||||
months.iter().rev().take_while(|(_, ok)| *ok).count() as u32
|
||||
}
|
||||
|
||||
/// The complete months from the first payment's month to last month.
|
||||
fn complete_months(state: &State, today: Date) -> Vec<Date> {
|
||||
let last = today.month_start().add_months(-1);
|
||||
let Some(first) = state.effective_payments().iter().map(|p| p.date.month_start()).min() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let mut m = first;
|
||||
while m <= last && out.len() < 1200 {
|
||||
out.push(m);
|
||||
m = m.add_months(1);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn challenge(state: &State, insight: &Insight, c: &ChallengeRecord, today: Date) -> ChallengeStatus {
|
||||
let to = today.min(c.ends);
|
||||
let over = today > c.ends;
|
||||
let (so_far, level, outcome) = match &c.goal {
|
||||
ChallengeGoal::SpendUnder { category, amount } => {
|
||||
let spent = if today < c.starts { Haler::ZERO } else { spent_in(state, category, c.starts, to) };
|
||||
let outcome = if spent > *amount {
|
||||
Outcome::Lost
|
||||
} else if over {
|
||||
Outcome::Won
|
||||
} else {
|
||||
Outcome::Running
|
||||
};
|
||||
(spent, permille(amount.0.saturating_sub(spent.0), amount.0), outcome)
|
||||
}
|
||||
ChallengeGoal::NoSpend { category } => {
|
||||
let spent = if today < c.starts { Haler::ZERO } else { spent_in(state, category, c.starts, to) };
|
||||
let outcome = if spent.0 > 0 {
|
||||
Outcome::Lost
|
||||
} else if over {
|
||||
Outcome::Won
|
||||
} else {
|
||||
Outcome::Running
|
||||
};
|
||||
(spent, if spent.0 > 0 { 0 } else { 1000 }, outcome)
|
||||
}
|
||||
ChallengeGoal::Cancel { subscription } => {
|
||||
let decided = state
|
||||
.decisions
|
||||
.get(subscription)
|
||||
.and_then(|ds| ds.iter().rev().find(|d| d.on >= c.starts && d.on <= c.ends))
|
||||
.filter(|d| d.decision == Decision::Cancel);
|
||||
let charged_after = decided.is_some_and(|d| {
|
||||
insight
|
||||
.subscriptions
|
||||
.iter()
|
||||
.filter(|s| &s.key == subscription)
|
||||
.flat_map(|s| s.charges.iter())
|
||||
.any(|ch| ch.date > d.on && ch.date <= to)
|
||||
});
|
||||
let outcome = match (decided.is_some(), charged_after, over) {
|
||||
(_, true, _) => Outcome::Lost,
|
||||
(true, false, true) => Outcome::Won,
|
||||
(false, _, true) => Outcome::Lost,
|
||||
_ => Outcome::Running,
|
||||
};
|
||||
(Haler::ZERO, if decided.is_some() && !charged_after { 1000 } else { 0 }, outcome)
|
||||
}
|
||||
ChallengeGoal::Save { goal, amount } => {
|
||||
let saved = state.goals.get(goal).map(|g| g.savings.iter().filter(|s| s.on >= c.starts && s.on <= to).fold(0i64, |sum, s| sum.saturating_add(s.amount.0))).unwrap_or(0);
|
||||
let outcome = if saved >= amount.0 {
|
||||
Outcome::Won
|
||||
} else if over {
|
||||
Outcome::Lost
|
||||
} else {
|
||||
Outcome::Running
|
||||
};
|
||||
(Haler(saved), permille(saved, amount.0), outcome)
|
||||
}
|
||||
};
|
||||
let outcome = match (c.abandoned, outcome) {
|
||||
(Some(_), Outcome::Running | Outcome::Lost) => Outcome::Abandoned,
|
||||
(Some(on), Outcome::Won) if on <= c.ends && !won_before(state, c, on) => Outcome::Abandoned,
|
||||
(_, o) => o,
|
||||
};
|
||||
ChallengeStatus { id: c.id.clone(), goal: c.goal.clone(), starts: c.starts, ends: c.ends, outcome, so_far, permille: level, days_left: today.days_until(c.ends).max(0) }
|
||||
}
|
||||
|
||||
/// A saving challenge reached before it was given up stays won.
|
||||
fn won_before(state: &State, c: &ChallengeRecord, on: Date) -> bool {
|
||||
match &c.goal {
|
||||
ChallengeGoal::Save { goal, amount } => {
|
||||
state.goals.get(goal).map(|g| g.savings.iter().filter(|s| s.on >= c.starts && s.on <= on).fold(0i64, |sum, s| sum.saturating_add(s.amount.0))).unwrap_or(0) >= amount.0
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// When a challenge was won: a saving challenge on the day it was reached, the others on their last day.
|
||||
fn won_on(state: &State, c: &ChallengeRecord) -> Date {
|
||||
if let ChallengeGoal::Save { goal, amount } = &c.goal {
|
||||
if let Some(g) = state.goals.get(goal) {
|
||||
let mut sum = 0i64;
|
||||
let mut savings: Vec<_> = g.savings.iter().filter(|s| s.on >= c.starts && s.on <= c.ends).collect();
|
||||
savings.sort_by_key(|s| (s.on, s.seq));
|
||||
for s in savings {
|
||||
sum = sum.saturating_add(s.amount.0);
|
||||
if sum >= amount.0 {
|
||||
return s.on;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
c.ends
|
||||
}
|
||||
|
||||
/// `shared`: the shared budgets in this log, which earn no budget medal (only your own payments are counted
|
||||
/// here, the limit is everyone's).
|
||||
pub fn rewards(state: &State, insight: &Insight, shared: &BTreeSet<BudgetId>, today: Date) -> Rewards {
|
||||
let mut medals: Vec<Earned> = Vec::new();
|
||||
let months = complete_months(state, today);
|
||||
|
||||
// Budgets under their limit (the latest limit), month by month.
|
||||
let mut budgets = Vec::new();
|
||||
let payments = state.effective_payments();
|
||||
for b in state.budgets.values().filter(|b| b.limit.0 > 0 && !shared.contains(&b.id)) {
|
||||
let flags: Vec<(Date, bool)> = months
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let spent = payments
|
||||
.iter()
|
||||
.filter(|p| p.budget.as_deref() == Some(b.id.as_str()) && p.date >= *m && p.date <= m.month_end() && is_spending(p))
|
||||
.fold(0i64, |s, p| s.saturating_add(p.amount.0.saturating_neg()));
|
||||
(*m, spent <= b.limit.0)
|
||||
})
|
||||
.collect();
|
||||
for (n, last) in runs(&flags).into_iter().filter(|(n, _)| *n >= STREAK) {
|
||||
medals.push(Earned { medal: Medal::UnderBudget { budget: b.id.clone(), name: b.name.clone(), months: n, until: last }, on: last.month_end() });
|
||||
}
|
||||
budgets.push((b.id.clone(), b.name.clone(), current(&flags)));
|
||||
}
|
||||
|
||||
// Months with every plan kept.
|
||||
for m in &months {
|
||||
if let Some(p) = month_plan(state, *m, today) {
|
||||
let planned: Vec<_> = p.rows.iter().filter(|r| r.planned.is_some_and(|x| x.0 > 0)).collect();
|
||||
if !planned.is_empty() && planned.iter().all(|r| r.left.is_some_and(|l| l.0 >= 0)) {
|
||||
medals.push(Earned { medal: Medal::PlansKept { month: *m }, on: m.month_end() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cancelled and not charged since, past the day it would have charged.
|
||||
for s in insight.subscriptions.iter().filter(|s| s.status == Status::Cancelled && s.next_charge < today) {
|
||||
if let Some(d) = s.decision.as_ref().filter(|d| d.decision == Decision::Cancel) {
|
||||
medals.push(Earned { medal: Medal::Cancelled { subscription: s.key.clone(), merchant: s.merchant.clone(), since: d.on }, on: s.next_charge });
|
||||
}
|
||||
}
|
||||
|
||||
// Challenges.
|
||||
let mut challenges: Vec<ChallengeStatus> = Vec::new();
|
||||
for c in state.challenges.values() {
|
||||
let st = challenge(state, insight, c, today);
|
||||
if st.outcome == Outcome::Won {
|
||||
medals.push(Earned { medal: Medal::ChallengeWon { challenge: c.id.clone(), goal: c.goal.clone() }, on: won_on(state, c) });
|
||||
}
|
||||
challenges.push(st);
|
||||
}
|
||||
challenges.sort_by(|a, b| {
|
||||
let running = |x: &ChallengeStatus| x.outcome == Outcome::Running;
|
||||
running(b).cmp(&running(a)).then_with(|| if running(a) { a.ends.cmp(&b.ends) } else { b.ends.cmp(&a.ends) }).then_with(|| a.id.cmp(&b.id))
|
||||
});
|
||||
|
||||
// Quarters with every invoice due in them paid by its due date.
|
||||
let mut quarters: BTreeMap<(i32, u32), bool> = BTreeMap::new();
|
||||
for r in state.invoices.values().filter(|r| !r.cancelled) {
|
||||
let (y, m, _) = r.invoice.due.ymd();
|
||||
let ok = r.paid.as_ref().is_some_and(|p| p.on <= r.invoice.due);
|
||||
let slot = quarters.entry((y, (m - 1) / 3 + 1)).or_insert(true);
|
||||
*slot &= ok;
|
||||
}
|
||||
for ((y, q), ok) in quarters {
|
||||
let end = Date::from_ymd(y, q * 3, 1).map(Date::month_end);
|
||||
if let Some(end) = end.filter(|e| ok && *e < today) {
|
||||
medals.push(Earned { medal: Medal::InvoicesOnTime { year: y, quarter: q }, on: end });
|
||||
}
|
||||
}
|
||||
|
||||
// Goals: their milestones, the first day each was reached.
|
||||
let mut goals_progress = Vec::new();
|
||||
for g in state.goals.values() {
|
||||
let mut savings: Vec<_> = g.savings.iter().collect();
|
||||
savings.sort_by_key(|s| s.seq);
|
||||
let mut sum = 0i64;
|
||||
let mut reached = 0usize;
|
||||
for s in savings {
|
||||
sum = sum.saturating_add(s.amount.0);
|
||||
let level = permille(sum, g.target.0);
|
||||
while reached < MILESTONES.len() && level >= MILESTONES[reached] {
|
||||
medals.push(Earned { medal: Medal::GoalMilestone { goal: g.id.clone(), name: g.name.clone(), permille: MILESTONES[reached] }, on: s.on });
|
||||
reached += 1;
|
||||
}
|
||||
}
|
||||
let level = permille(g.saved().0, g.target.0);
|
||||
if g.is_open() && level < 1000 {
|
||||
let next = MILESTONES.iter().copied().find(|m| *m > level).unwrap_or(1000);
|
||||
goals_progress.push((g.id.clone(), g.name.clone(), level, next));
|
||||
}
|
||||
}
|
||||
|
||||
// Months running with money put aside (more in than out across the goals).
|
||||
let saved_in = |from: Date, to: Date| {
|
||||
state.goals.values().flat_map(|g| g.savings.iter()).filter(|s| s.on >= from && s.on <= to).fold(0i64, |sum, s| sum.saturating_add(s.amount.0))
|
||||
};
|
||||
let first_saving = state.goals.values().flat_map(|g| g.savings.iter()).map(|s| s.on.month_start()).min();
|
||||
let saving_flags: Vec<(Date, bool)> = match first_saving {
|
||||
Some(first) => months.iter().filter(|m| **m >= first).map(|m| (*m, saved_in(*m, m.month_end()) > 0)).collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
for (n, last) in runs(&saving_flags).into_iter().filter(|(n, _)| *n >= STREAK) {
|
||||
medals.push(Earned { medal: Medal::SavingStreak { months: n, until: last }, on: last.month_end() });
|
||||
}
|
||||
|
||||
// Projects done: within their budget, by their end date.
|
||||
let summaries = crate::projects::projects(state, today);
|
||||
for p in state.projects.projects.values().filter(|p| !p.is_open()) {
|
||||
let Some(on) = p.status_on else { continue };
|
||||
if let Some(s) = summaries.iter().find(|s| s.id == p.id) {
|
||||
if s.planned.0 > 0 && s.spent <= s.planned {
|
||||
medals.push(Earned { medal: Medal::ProjectOnBudget { project: p.id.clone(), name: p.name.clone() }, on });
|
||||
}
|
||||
}
|
||||
if p.ends.is_some_and(|e| on <= e) {
|
||||
medals.push(Earned { medal: Medal::FinishedOnTime { project: p.id.clone(), name: p.name.clone() }, on });
|
||||
}
|
||||
}
|
||||
|
||||
medals.sort_by_key(|m| std::cmp::Reverse(m.on));
|
||||
let month = today.month_start();
|
||||
Rewards {
|
||||
medals,
|
||||
challenges,
|
||||
progress: Progress {
|
||||
saving_months: current(&saving_flags),
|
||||
saved_this_month: saved_in(month, today) > 0,
|
||||
budgets,
|
||||
goals: goals_progress,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! One definition of spending, for every screen: money out of your own payments, as positive amounts, by
|
||||
//! category. Money between your own accounts (`transfers`) is not spending; a payment nobody categorised counts
|
||||
//! as `uncategorised`. Every sum is checked: `None` when one would not fit, never a wrong number.
|
||||
|
||||
use fiscus_ledger::categories::{TRANSFERS, UNCATEGORISED};
|
||||
use fiscus_ledger::{Category, Date, EffectivePayment, Haler, State};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The payments dated in `[from, to]`, a confirmed pair as one.
|
||||
pub fn between(state: &State, from: Date, to: Date) -> Vec<EffectivePayment> {
|
||||
state.effective_payments().into_iter().filter(|p| p.date >= from && p.date <= to).collect()
|
||||
}
|
||||
|
||||
/// The category a payment counts under.
|
||||
pub fn category_of(p: &EffectivePayment) -> &str {
|
||||
p.category.as_deref().unwrap_or(UNCATEGORISED)
|
||||
}
|
||||
|
||||
/// A payment that is spending: money out, not a transfer.
|
||||
pub fn is_spending(p: &EffectivePayment) -> bool {
|
||||
p.amount.0 < 0 && category_of(p) != TRANSFERS
|
||||
}
|
||||
|
||||
/// Money out by category, positive.
|
||||
pub fn outflows(payments: &[EffectivePayment]) -> Option<BTreeMap<Category, Haler>> {
|
||||
let mut by: BTreeMap<Category, Haler> = BTreeMap::new();
|
||||
for p in payments.iter().filter(|p| is_spending(p)) {
|
||||
let slot = by.entry(category_of(p).to_string()).or_insert(Haler::ZERO);
|
||||
*slot = slot.checked_add(p.amount.checked_neg().ok()?).ok()?;
|
||||
}
|
||||
Some(by)
|
||||
}
|
||||
|
||||
/// Money in, not a transfer.
|
||||
pub fn inflow(payments: &[EffectivePayment]) -> Option<Haler> {
|
||||
Haler::sum(payments.iter().filter(|p| p.amount.0 > 0 && category_of(p) != TRANSFERS).map(|p| p.amount)).ok()
|
||||
}
|
||||
|
||||
/// Each part's share of their sum in thousandths, by the largest remainder: the shares add up to exactly 1000
|
||||
/// whenever the sum is above zero (all zeros otherwise). A tie goes to the earlier part, so callers order the
|
||||
/// parts first. A negative part counts as zero.
|
||||
pub fn permille(parts: &[Haler]) -> Vec<u32> {
|
||||
let parts: Vec<i128> = parts.iter().map(|h| i128::from(h.0.max(0))).collect();
|
||||
let total: i128 = parts.iter().sum();
|
||||
if total <= 0 {
|
||||
return vec![0; parts.len()];
|
||||
}
|
||||
let mut shares: Vec<u32> = parts.iter().map(|p| (p * 1000 / total) as u32).collect();
|
||||
let mut left = 1000 - shares.iter().sum::<u32>();
|
||||
let mut order: Vec<usize> = (0..parts.len()).collect();
|
||||
// Largest remainder first; the earlier part on a tie (the sort is stable).
|
||||
order.sort_by_key(|&i| std::cmp::Reverse(parts[i] * 1000 % total));
|
||||
for i in order {
|
||||
if left == 0 {
|
||||
break;
|
||||
}
|
||||
shares[i] += 1;
|
||||
left -= 1;
|
||||
}
|
||||
shares
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shares_always_add_up_to_a_thousand() {
|
||||
let h = |v: &[i64]| v.iter().map(|&x| Haler(x)).collect::<Vec<_>>();
|
||||
assert_eq!(permille(&h(&[1, 1, 1])), [334, 333, 333]);
|
||||
assert_eq!(permille(&h(&[2, 1])), [667, 333]);
|
||||
assert_eq!(permille(&h(&[0, 0])), [0, 0]);
|
||||
assert_eq!(permille(&h(&[])), Vec::<u32>::new());
|
||||
assert_eq!(permille(&h(&[i64::MAX, i64::MAX, 1])), [500, 500, 0]);
|
||||
assert_eq!(permille(&h(&[5, -3])), [1000, 0]);
|
||||
for n in 1..40i64 {
|
||||
let parts: Vec<Haler> = (1..=n).map(|i| Haler(i * 7919 % 1013 + 1)).collect();
|
||||
assert_eq!(permille(&parts).iter().sum::<u32>(), 1000, "{n} parts");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! A month in numbers: where the money went (the slices of a pie, in thousandths that add up to 1000), money
|
||||
//! in and out, the last six months, how far along you are compared with last month by the same day, the
|
||||
//! merchants you paid most, and what the subscriptions took. Your own payments; transfers are not spending.
|
||||
|
||||
use crate::spending::{between, inflow, is_spending, outflows, permille};
|
||||
use crate::subscriptions::Insight;
|
||||
use fiscus_ledger::{Category, Date, Haler, State};
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The pie shows this many categories; the rest are one slice.
|
||||
pub const SLICES: usize = 7;
|
||||
/// Months in the bars, this one included.
|
||||
pub const MONTHS: i32 = 6;
|
||||
pub const TOP_MERCHANTS: usize = 5;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct Slice {
|
||||
/// `None`: every other category, together.
|
||||
pub category: Option<Category>,
|
||||
pub amount: Haler,
|
||||
/// Its share of the month's spending; the slices add up to 1000.
|
||||
pub permille: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct MonthTotal {
|
||||
/// The 1st of the month.
|
||||
pub month: Date,
|
||||
pub out: Haler,
|
||||
pub inflow: Haler,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct MerchantTotal {
|
||||
pub key: String,
|
||||
/// As the latest payment to it wrote it.
|
||||
pub merchant: String,
|
||||
pub amount: Haler,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct MonthStats {
|
||||
/// The 1st of the month.
|
||||
pub month: Date,
|
||||
/// Largest first; at most [`SLICES`], then the rest.
|
||||
pub slices: Vec<Slice>,
|
||||
pub out: Haler,
|
||||
pub inflow: Haler,
|
||||
/// In less out; negative when more went out.
|
||||
pub net: Haler,
|
||||
/// The last [`MONTHS`] months, oldest first, ending with this one.
|
||||
pub months: Vec<MonthTotal>,
|
||||
/// Spent last month up to the same day of the month (all of last month for a past month).
|
||||
pub same_day_last_month: Haler,
|
||||
/// Largest first.
|
||||
pub top_merchants: Vec<MerchantTotal>,
|
||||
/// What the subscriptions charged this month.
|
||||
pub subscriptions: Haler,
|
||||
/// Their share of the month's spending, in thousandths (at most 1000).
|
||||
pub subscriptions_permille: u32,
|
||||
}
|
||||
|
||||
/// `[start, end]` of `month`, cut at `today`; `None` for a month that has not begun.
|
||||
fn span(month: Date, today: Date) -> Option<(Date, Date)> {
|
||||
let start = month.month_start();
|
||||
(start <= today).then(|| (start, start.month_end().min(today)))
|
||||
}
|
||||
|
||||
fn spent(state: &State, from: Date, to: Date) -> Option<Haler> {
|
||||
Haler::sum(outflows(&between(state, from, to))?.into_values()).ok()
|
||||
}
|
||||
|
||||
/// The month of `month`, up to `today`. `insight` is `analyse(state, today)`. `None` for a month that has not
|
||||
/// begun, or when a sum would not fit.
|
||||
pub fn month_stats(state: &State, insight: &Insight, month: Date, today: Date) -> Option<MonthStats> {
|
||||
let (start, end) = span(month, today)?;
|
||||
let payments = between(state, start, end);
|
||||
let by = outflows(&payments)?;
|
||||
let out = Haler::sum(by.values().copied()).ok()?;
|
||||
let inflow = inflow(&payments)?;
|
||||
|
||||
let mut parts: Vec<(Category, Haler)> = by.into_iter().collect();
|
||||
parts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
let mut slices: Vec<(Option<Category>, Haler)> = parts.iter().take(SLICES).map(|(c, a)| (Some(c.clone()), *a)).collect();
|
||||
if parts.len() > SLICES {
|
||||
slices.push((None, Haler::sum(parts[SLICES..].iter().map(|(_, a)| *a)).ok()?));
|
||||
}
|
||||
let shares = permille(&slices.iter().map(|(_, a)| *a).collect::<Vec<_>>());
|
||||
|
||||
let mut months = Vec::new();
|
||||
for n in (0..MONTHS).rev() {
|
||||
let m = start.add_months(-n);
|
||||
let (from, to) = span(m, today)?;
|
||||
let ps = between(state, from, to);
|
||||
months.push(MonthTotal { month: m, out: Haler::sum(outflows(&ps)?.into_values()).ok()?, inflow: crate::spending::inflow(&ps)? });
|
||||
}
|
||||
|
||||
let last = start.add_months(-1);
|
||||
let last_end = if end == start.month_end() { last.month_end() } else { last.add_days(end.ymd().2 as i32 - 1).min(last.month_end()) };
|
||||
let same_day_last_month = spent(state, last, last_end)?;
|
||||
|
||||
let mut merchants: BTreeMap<&str, MerchantTotal> = BTreeMap::new();
|
||||
for p in payments.iter().filter(|p| is_spending(p) && !p.merchant_key.is_empty()) {
|
||||
let t = merchants.entry(&p.merchant_key).or_insert(MerchantTotal { key: p.merchant_key.clone(), merchant: String::new(), amount: Haler::ZERO, count: 0 });
|
||||
t.merchant = p.merchant.clone();
|
||||
t.amount = t.amount.checked_add(p.amount.checked_neg().ok()?).ok()?;
|
||||
t.count += 1;
|
||||
}
|
||||
let mut top_merchants: Vec<MerchantTotal> = merchants.into_values().collect();
|
||||
top_merchants.sort_by(|a, b| b.amount.cmp(&a.amount).then(a.key.cmp(&b.key)));
|
||||
top_merchants.truncate(TOP_MERCHANTS);
|
||||
|
||||
// A subscription charge counts once, by the payment it was, and only when it is spending this month.
|
||||
let spending_ids: BTreeMap<&str, Haler> = payments
|
||||
.iter()
|
||||
.filter(|p| is_spending(p))
|
||||
.flat_map(|p| [Some(p.id.as_str()), p.line.as_deref(), p.captured.as_deref()].into_iter().flatten().map(move |id| (id, p.amount)))
|
||||
.collect();
|
||||
let mut charged = std::collections::BTreeSet::new();
|
||||
let mut subscriptions = Haler::ZERO;
|
||||
for c in insight.subscriptions.iter().flat_map(|s| &s.charges) {
|
||||
let Some(paid) = spending_ids.get(c.payment.as_str()) else { continue };
|
||||
if charged.insert(c.payment.as_str()) {
|
||||
subscriptions = subscriptions.checked_add(paid.checked_neg().ok()?).ok()?;
|
||||
}
|
||||
}
|
||||
let subscriptions_permille = if out.0 > 0 { (i128::from(subscriptions.0) * 1000 / i128::from(out.0)).clamp(0, 1000) as u32 } else { 0 };
|
||||
|
||||
Some(MonthStats {
|
||||
month: start,
|
||||
slices: slices.into_iter().zip(shares).map(|((category, amount), permille)| Slice { category, amount, permille }).collect(),
|
||||
net: inflow.checked_sub(out).ok()?,
|
||||
out,
|
||||
inflow,
|
||||
months,
|
||||
same_day_last_month,
|
||||
top_merchants,
|
||||
subscriptions,
|
||||
subscriptions_permille,
|
||||
})
|
||||
}
|
||||
@@ -149,7 +149,7 @@ pub fn analyse(state: &State, today: Date) -> Insight {
|
||||
let full: Vec<&EffectivePayment> = charges.iter().copied().filter(|p| cost(p) > TRIAL_MAX).collect();
|
||||
|
||||
// Trials: the last card check with no full charge after it, or a payment marked by hand.
|
||||
let last_check = charges.iter().filter(|p| cost(p) <= TRIAL_MAX).next_back();
|
||||
let last_check = charges.iter().rfind(|p| cost(p) <= TRIAL_MAX);
|
||||
for p in charges.iter().filter(|p| p.trial_ends.is_some() || Some(*p) == last_check) {
|
||||
let converted = full.iter().any(|f| f.date > p.date && f.id != p.id);
|
||||
let (ends, estimated) = match p.trial_ends {
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Savings goals this month and the rewards: round-ups to the haléř, what last month's plans left, a share of
|
||||
//! income, the split capped at what a goal still needs, the pace and the month you get there, where the money
|
||||
//! could come from; medals only for complete periods, and challenges won, lost or given up.
|
||||
|
||||
use fiscus_insight::goals::{goals_month, round_ups, Source};
|
||||
use fiscus_insight::rewards::{rewards, Medal, Outcome};
|
||||
use fiscus_insight::subscriptions::analyse;
|
||||
use fiscus_ledger::goal::{ChallengeGoal, Colour, Way, WayKind};
|
||||
use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
/// A ledger from `(date, amount in haléře, merchant, category)` added by hand, then `extra` events.
|
||||
fn ledger(payments: &[(&str, i64, &str, &str)], extra: Vec<EventBody>) -> State {
|
||||
let mut log: Vec<Event> = vec![Event::new("b", Timestamp(0), EventBody::BudgetCreated { budget: "home".into(), name: "Home".into(), limit: Haler(1_000_000) })];
|
||||
log.extend(payments.iter().enumerate().map(|(i, (date, amount, merchant, category))| {
|
||||
Event::new(
|
||||
format!("e{i}"),
|
||||
Timestamp(0),
|
||||
EventBody::PaymentAdded {
|
||||
payment: format!("p{i}"),
|
||||
amount: Haler(*amount),
|
||||
date: d(date),
|
||||
merchant: merchant.to_string(),
|
||||
category: (!category.is_empty()).then(|| category.to_string()),
|
||||
note: None,
|
||||
},
|
||||
)
|
||||
}));
|
||||
log.extend(extra.into_iter().enumerate().map(|(i, b)| Event::new(format!("x{i}"), Timestamp(0), b)));
|
||||
let s = State::replay(&log);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
s
|
||||
}
|
||||
|
||||
fn goal(id: &str, target: i64, by: Option<&str>) -> EventBody {
|
||||
EventBody::GoalCreated { goal: id.into(), name: format!("Goal {id}"), target: Haler(target), by: by.map(d), colour: Colour::Amber }
|
||||
}
|
||||
|
||||
fn saved(goal: &str, saving: &str, amount: i64, on: &str, way: Option<WayKind>) -> EventBody {
|
||||
EventBody::GoalSaved { goal: goal.into(), saving: saving.into(), amount: Haler(amount), on: d(on), way }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_ups_add_the_differences_to_the_next_10_50_or_100_kc() {
|
||||
let today = d("2026-11-07");
|
||||
let s = ledger(
|
||||
&[
|
||||
("2026-11-02", -12_900, "Albert", "groceries"),
|
||||
("2026-11-03", -25_000, "Lokál", "eating-out"),
|
||||
("2026-11-04", -8_750, "Trafika", ""),
|
||||
("2026-11-05", -100_000, "To savings", "transfers"),
|
||||
("2026-11-05", 5_000_000, "Salary", "income"),
|
||||
("2026-10-30", -12_345, "Albert", "groceries"),
|
||||
],
|
||||
vec![],
|
||||
);
|
||||
// 129 → 130, 250 stays, 87,50 → 90: 1 + 0 + 2,50. Transfers, money in and last month are not rounded.
|
||||
assert_eq!(round_ups(&s, Haler(1_000), today), (Haler(350), 2));
|
||||
assert_eq!(round_ups(&s, Haler(10_000), today), (Haler(7_100 + 5_000 + 1_250), 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_goal_month_splits_its_saving_between_its_ways() {
|
||||
let today = d("2026-11-07");
|
||||
let s = ledger(
|
||||
&[
|
||||
// October: groceries under plan by 1 500 Kč, eating out over (leftover 0, not negative); 40 000 in.
|
||||
("2026-10-05", -650_000, "Albert", "groceries"),
|
||||
("2026-10-06", -250_000, "Lokál", "eating-out"),
|
||||
("2026-10-10", 4_000_000, "Salary", "income"),
|
||||
// November so far.
|
||||
("2026-11-02", -12_900, "Albert", "groceries"),
|
||||
],
|
||||
vec![
|
||||
EventBody::CategoryPlanned { category: "groceries".into(), amount: Haler(800_000), from: d("2026-10-01") },
|
||||
EventBody::CategoryPlanned { category: "eating-out".into(), amount: Haler(200_000), from: d("2026-10-01") },
|
||||
goal("g1", 4_000_000, Some("2027-06-30")),
|
||||
EventBody::GoalWaysSet {
|
||||
goal: "g1".into(),
|
||||
ways: vec![Way::Fixed { amount: Haler(200_000) }, Way::RoundUp { to: Haler(1_000) }, Way::Leftover { permille: 500 }, Way::Income { permille: 100 }],
|
||||
},
|
||||
saved("g1", "s1", 300_000, "2026-08-10", None),
|
||||
saved("g1", "s2", 300_000, "2026-09-10", None),
|
||||
saved("g1", "s3", 300_000, "2026-10-10", None),
|
||||
saved("g1", "s4", 100_000, "2026-11-03", Some(WayKind::Fixed)),
|
||||
],
|
||||
);
|
||||
let m = goals_month(&s, &analyse(&s, today), today);
|
||||
assert_eq!((m.leftover, m.income, m.leftover_given, m.income_given), (Haler(150_000), Haler(4_000_000), 500, 100));
|
||||
let g = &m.goals[0];
|
||||
assert_eq!((g.saved, g.permille, g.reached), (Haler(1_000_000), 250, false));
|
||||
let parts: Vec<(WayKind, Haler, Haler, Haler)> = g.parts.iter().map(|p| (p.way.kind(), p.amount, p.saved, p.left)).collect();
|
||||
assert_eq!(
|
||||
parts,
|
||||
[
|
||||
(WayKind::Fixed, Haler(200_000), Haler(100_000), Haler(100_000)),
|
||||
(WayKind::RoundUp, Haler(100), Haler::ZERO, Haler(100)),
|
||||
(WayKind::Leftover, Haler(75_000), Haler::ZERO, Haler(75_000)),
|
||||
(WayKind::Income, Haler(400_000), Haler::ZERO, Haler(400_000)),
|
||||
]
|
||||
);
|
||||
assert_eq!((g.left_this_month, g.saved_this_month), (Haler(575_100), Haler(100_000)));
|
||||
// November to June is 8 months: 30 000 Kč still needed, 3 750 Kč a month.
|
||||
assert_eq!((g.months_left, g.needed_per_month), (Some(8), Some(Haler(375_000))));
|
||||
// August to October at 3 000 Kč a month: 30 000 Kč more is 10 months on, in September 2027.
|
||||
assert_eq!((g.pace, g.reach_month), (Haler(300_000), Some(d("2027-09-01"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_split_never_asks_for_more_than_the_goal_still_needs() {
|
||||
let today = d("2026-11-07");
|
||||
let s = ledger(
|
||||
&[],
|
||||
vec![
|
||||
goal("g1", 300_000, None),
|
||||
EventBody::GoalWaysSet { goal: "g1".into(), ways: vec![Way::Fixed { amount: Haler(200_000) }, Way::Fixed { amount: Haler(100) }].into_iter().take(1).collect() },
|
||||
saved("g1", "s1", 250_000, "2026-10-01", None),
|
||||
],
|
||||
);
|
||||
let g = &goals_month(&s, &analyse(&s, today), today).goals[0];
|
||||
assert_eq!((g.parts[0].amount, g.parts[0].left, g.needed_per_month, g.months_left), (Haler(200_000), Haler(50_000), None, None));
|
||||
let s = ledger(&[], vec![goal("g1", 300_000, Some("2026-09-30")), saved("g1", "s1", 300_000, "2026-10-01", None), EventBody::GoalClosed { goal: "g1".into(), on: d("2026-10-02") }]);
|
||||
let g = &goals_month(&s, &analyse(&s, today), today).goals[0];
|
||||
assert!(g.reached && g.parts.is_empty() && g.reach_month.is_none() && g.needed_per_month.is_none());
|
||||
let s = ledger(&[], vec![goal("g1", 300_000, Some("2026-09-30"))]);
|
||||
let g = &goals_month(&s, &analyse(&s, today), today).goals[0];
|
||||
assert_eq!((g.months_left, g.needed_per_month), (Some(0), Some(Haler(300_000))), "its date has passed: all of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn where_the_money_could_come_from() {
|
||||
let today = d("2026-11-07");
|
||||
let mut payments = Vec::new();
|
||||
for m in ["2026-07", "2026-08", "2026-09", "2026-10"] {
|
||||
payments.push((format!("{m}-03"), -19_900, "NETFLIX.COM", "subscriptions"));
|
||||
payments.push((format!("{m}-12"), -200_000, "Lokál", "eating-out"));
|
||||
}
|
||||
payments.push(("2026-10-20".into(), -150_000, "Lokál", "eating-out"));
|
||||
let rows: Vec<(&str, i64, &str, &str)> = payments.iter().map(|(a, b, c, e)| (a.as_str(), *b, *c, *e)).collect();
|
||||
let s = ledger(&rows, vec![]);
|
||||
let sources = goals_month(&s, &analyse(&s, today), today).sources;
|
||||
assert!(
|
||||
sources.iter().any(|x| matches!(x, Source::Subscription { merchant, monthly, .. } if merchant.contains("NETFLIX") && *monthly == Haler(19_900))),
|
||||
"{sources:?}"
|
||||
);
|
||||
assert!(
|
||||
sources.iter().any(|x| matches!(x, Source::Category { category, last, average, extra } if category == "eating-out" && *last == Haler(350_000) && *average == Haler(200_000) && *extra == Haler(150_000))),
|
||||
"{sources:?}"
|
||||
);
|
||||
// Decided "keep": not pointed at.
|
||||
let key = analyse(&s, today).subscriptions[0].key.clone();
|
||||
let s = ledger(&rows, vec![EventBody::SubscriptionDecided { subscription: key, decision: Decision::Keep, amount: Haler(19_900), on: d("2026-11-01") }]);
|
||||
assert!(!goals_month(&s, &analyse(&s, today), today).sources.iter().any(|x| matches!(x, Source::Subscription { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medals_for_goals_and_months_running_with_money_put_aside() {
|
||||
let today = d("2026-11-07");
|
||||
let s = ledger(
|
||||
&[("2026-08-01", -10_000, "Albert", "groceries")],
|
||||
vec![
|
||||
goal("g1", 100_000, None),
|
||||
saved("g1", "s1", 30_000, "2026-08-10", None),
|
||||
saved("g1", "s2", 30_000, "2026-09-10", None),
|
||||
saved("g1", "s3", 50_000, "2026-10-10", None),
|
||||
saved("g1", "s4", -20_000, "2026-10-20", None),
|
||||
],
|
||||
);
|
||||
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
||||
let milestones: Vec<(u32, Date)> = r.medals.iter().filter_map(|e| match &e.medal { Medal::GoalMilestone { permille, .. } => Some((*permille, e.on)), _ => None }).collect();
|
||||
assert_eq!(milestones, [(750, d("2026-10-10")), (1000, d("2026-10-10")), (500, d("2026-09-10")), (250, d("2026-08-10"))]);
|
||||
assert!(r.medals.iter().any(|e| e.medal == Medal::SavingStreak { months: 3, until: d("2026-10-01") }));
|
||||
assert_eq!((r.progress.saving_months, r.progress.saved_this_month), (3, false));
|
||||
assert!(r.progress.goals.iter().any(|(id, _, level, next)| id == "g1" && *level == 900 && *next == 1000), "{:?}", r.progress.goals);
|
||||
|
||||
// Two months are not a streak; this month does not count until it is over.
|
||||
let s = ledger(&[("2026-09-01", -10_000, "Albert", "groceries")], vec![goal("g1", 100_000, None), saved("g1", "s1", 1_000, "2026-09-10", None), saved("g1", "s2", 1_000, "2026-10-10", None), saved("g1", "s3", 1_000, "2026-11-02", None)]);
|
||||
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
||||
assert!(!r.medals.iter().any(|e| matches!(e.medal, Medal::SavingStreak { .. })));
|
||||
assert_eq!((r.progress.saving_months, r.progress.saved_this_month), (2, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medals_for_budgets_and_plans_kept_in_complete_months_only() {
|
||||
let today = d("2026-11-07");
|
||||
let s = ledger(
|
||||
&[
|
||||
("2026-07-05", -400_000, "Albert", "groceries"),
|
||||
("2026-08-05", -900_000, "Albert", "groceries"),
|
||||
("2026-09-05", -900_000, "Albert", "groceries"),
|
||||
("2026-10-05", -1_000_000, "Albert", "groceries"),
|
||||
("2026-11-05", -5_000_000, "Albert", "groceries"),
|
||||
],
|
||||
vec![EventBody::CategoryPlanned { category: "groceries".into(), amount: Haler(950_000), from: d("2026-09-01") }],
|
||||
);
|
||||
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
||||
assert!(r.medals.iter().any(|e| e.medal == Medal::UnderBudget { budget: "home".into(), name: "Home".into(), months: 4, until: d("2026-10-01") }), "{:?}", r.medals);
|
||||
let kept: Vec<Date> = r.medals.iter().filter_map(|e| match e.medal { Medal::PlansKept { month } => Some(month), _ => None }).collect();
|
||||
assert_eq!(kept, [d("2026-09-01")], "October went over its plan; November is not over");
|
||||
assert_eq!(r.progress.budgets, [("home".to_string(), "Home".to_string(), 4)]);
|
||||
// A shared budget earns none: only your own payments are counted, its limit is everyone's.
|
||||
let r = rewards(&s, &analyse(&s, today), &BTreeSet::from(["home".to_string()]), today);
|
||||
assert!(!r.medals.iter().any(|e| matches!(e.medal, Medal::UnderBudget { .. })) && r.progress.budgets.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn challenges_run_are_won_lost_or_given_up() {
|
||||
let start = |id: &str, goal: ChallengeGoal, starts: &str, ends: &str| EventBody::ChallengeStarted { challenge: id.into(), goal, starts: d(starts), ends: d(ends) };
|
||||
let s = ledger(
|
||||
&[("2026-10-10", -100_000, "Lokál", "eating-out"), ("2026-10-20", -50_000, "Kino", "fun"), ("2026-11-03", -100_000, "Lokál", "eating-out")],
|
||||
vec![
|
||||
goal("g1", 1_000_000, None),
|
||||
start("c-under", ChallengeGoal::SpendUnder { category: "eating-out".into(), amount: Haler(300_000) }, "2026-11-01", "2026-11-30"),
|
||||
start("c-oct", ChallengeGoal::SpendUnder { category: "eating-out".into(), amount: Haler(200_000) }, "2026-10-01", "2026-10-31"),
|
||||
start("c-none", ChallengeGoal::NoSpend { category: "fun".into() }, "2026-10-01", "2026-10-31"),
|
||||
start("c-save", ChallengeGoal::Save { goal: "g1".into(), amount: Haler(200_000) }, "2026-11-01", "2026-11-30"),
|
||||
saved("g1", "s1", 250_000, "2026-11-04", None),
|
||||
start("c-quit", ChallengeGoal::NoSpend { category: "travel".into() }, "2026-11-01", "2026-11-30"),
|
||||
EventBody::ChallengeAbandoned { challenge: "c-quit".into(), on: d("2026-11-05") },
|
||||
],
|
||||
);
|
||||
let today = d("2026-11-07");
|
||||
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
||||
let by = |id: &str| r.challenges.iter().find(|c| c.id == id).unwrap();
|
||||
assert_eq!((by("c-under").outcome, by("c-under").so_far, by("c-under").permille, by("c-under").days_left), (Outcome::Running, Haler(100_000), 666, 23));
|
||||
assert_eq!((by("c-oct").outcome, by("c-oct").permille), (Outcome::Won, 500));
|
||||
assert_eq!((by("c-none").outcome, by("c-none").permille), (Outcome::Lost, 0));
|
||||
assert_eq!((by("c-save").outcome, by("c-save").permille), (Outcome::Won, 1000), "won the day it was reached");
|
||||
assert_eq!(by("c-quit").outcome, Outcome::Abandoned);
|
||||
let won: Vec<(&str, Date)> = r.medals.iter().filter_map(|e| match &e.medal { Medal::ChallengeWon { challenge, .. } => Some((challenge.as_str(), e.on)), _ => None }).collect();
|
||||
assert_eq!(won, [("c-save", d("2026-11-04")), ("c-oct", d("2026-10-31"))]);
|
||||
assert_eq!(r.challenges[0].outcome, Outcome::Running, "running first");
|
||||
|
||||
// Over the limit before the end: lost at once.
|
||||
let s2 = ledger(&[("2026-11-03", -400_000, "Lokál", "eating-out")], vec![start("c", ChallengeGoal::SpendUnder { category: "eating-out".into(), amount: Haler(300_000) }, "2026-11-01", "2026-11-30")]);
|
||||
assert_eq!(rewards(&s2, &analyse(&s2, today), &BTreeSet::new(), today).challenges[0].outcome, Outcome::Lost);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quarter_with_every_invoice_paid_by_its_due_date() {
|
||||
use fiscus_ledger::invoice::{Invoice, InvoiceLine, Language, Party, Supplier};
|
||||
let party = |name: &str, ico: &str| Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some(ico.into()), dic: None };
|
||||
let invoice = |id: &str, number: &str, issued: &str| Invoice {
|
||||
id: id.into(),
|
||||
number: number.into(),
|
||||
issued: d(issued),
|
||||
due: d(issued).add_days(14),
|
||||
taxable: None,
|
||||
customer: party("Odběratel s.r.o.", "45244782"),
|
||||
lines: vec![InvoiceLine { text: "Work".into(), quantity: 1000, unit: "h".into(), unit_price: Haler(100_000), vat: None }],
|
||||
budget: None,
|
||||
language: Language::Cs,
|
||||
};
|
||||
let paid = |id: &str, on: &str| EventBody::InvoicePaid { invoice: id.into(), payment: None, on: d(on) };
|
||||
let s = ledger(
|
||||
&[],
|
||||
vec![
|
||||
EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } },
|
||||
// Q2: both paid in time. Q3: one paid late.
|
||||
EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-04-02") },
|
||||
EventBody::InvoiceIssued { invoice: invoice("i2", "20260002", "2026-05-10") },
|
||||
EventBody::InvoiceIssued { invoice: invoice("i3", "20260003", "2026-07-01") },
|
||||
EventBody::InvoiceIssued { invoice: invoice("i4", "20260004", "2026-10-20") },
|
||||
paid("i1", "2026-04-10"),
|
||||
paid("i2", "2026-05-24"),
|
||||
paid("i3", "2026-07-30"),
|
||||
paid("i4", "2026-10-25"),
|
||||
],
|
||||
);
|
||||
let today = d("2026-11-07");
|
||||
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
||||
let quarters: Vec<(i32, u32)> = r.medals.iter().filter_map(|e| match e.medal { Medal::InvoicesOnTime { year, quarter } => Some((year, quarter)), _ => None }).collect();
|
||||
assert_eq!(quarters, [(2026, 2)], "Q3 had one paid late; Q4 is not over");
|
||||
}
|
||||
@@ -23,6 +23,44 @@ fn two_members_paying_the_same_service_is_a_duplicate() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_shared_is_the_service_key_of_each_subscription_still_paid() {
|
||||
use fiscus_insight::household::shared_names;
|
||||
use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp};
|
||||
let d = |s: &str| s.parse::<Date>().unwrap();
|
||||
let mut log = Vec::new();
|
||||
for (i, m) in [1u32, 2, 3, 4].iter().enumerate() {
|
||||
for (j, merchant) in ["PAYPAL *SPOTIFY 4029357733", "NETFLIX.COM", "WEDOS INTERNET A.S.", "TV"].iter().enumerate() {
|
||||
log.push(Event::new(
|
||||
format!("p{i}{j}"),
|
||||
Timestamp(0),
|
||||
EventBody::PaymentAdded {
|
||||
payment: format!("p{i}{j}"),
|
||||
amount: Haler(-19_900),
|
||||
date: d(&format!("2026-{:02}-0{}", m + 6, j + 1)),
|
||||
merchant: merchant.to_string(),
|
||||
category: None,
|
||||
note: None,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
let today = d("2026-10-20");
|
||||
let state = State::replay(&log);
|
||||
// Only the first word of the merchant key, so a reference number never leaves; "TV" is too short to say anything.
|
||||
assert_eq!(shared_names(&state, today), names(&["netflix", "spotify", "wedos"]));
|
||||
|
||||
log.push(Event::new(
|
||||
"cancel",
|
||||
Timestamp(0),
|
||||
EventBody::SubscriptionDecided { subscription: "netflix com".into(), decision: Decision::Cancel, amount: Haler(19_900), on: d("2026-10-05") },
|
||||
));
|
||||
let state = State::replay(&log);
|
||||
let key = fiscus_insight::subscriptions::analyse(&state, today).subscriptions.iter().find(|s| s.merchant.starts_with("NETFLIX")).map(|s| s.key.clone());
|
||||
assert_eq!(key.as_deref(), Some("netflix com"), "the decision above names Netflix's subscription key");
|
||||
assert_eq!(shared_names(&state, today), names(&["spotify", "wedos"]), "a cancelled one is not paid any more");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_member_alone_or_nobody_sharing_is_nothing() {
|
||||
assert!(household_duplicates(&[]).is_empty());
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
//! A project's numbers: spent by line and unplanned, payments by hand and by rule within the project's dates,
|
||||
//! income without VAT and never twice, profit and margin, progress by estimates or by count, the forecast, late,
|
||||
//! time by task and week, billed and unbilled, and the two project medals.
|
||||
|
||||
use fiscus_insight::projects::{project, projects};
|
||||
use fiscus_insight::rewards::{rewards, Medal};
|
||||
use fiscus_insight::subscriptions::analyse;
|
||||
use fiscus_ledger::goal::Colour;
|
||||
use fiscus_ledger::invoice::{Invoice, InvoiceLine, Language, Party, Supplier};
|
||||
use fiscus_ledger::project::{Kind, Status, TaskFields, TaskStatus};
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn ledger(bodies: Vec<EventBody>) -> State {
|
||||
let log: Vec<Event> = bodies.into_iter().enumerate().map(|(i, b)| Event::new(format!("e{i}"), Timestamp(0), b)).collect();
|
||||
let s = State::replay(&log);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
s
|
||||
}
|
||||
|
||||
fn made(id: &str, kind: Kind, starts: &str, ends: &str) -> EventBody {
|
||||
EventBody::ProjectCreated { project: id.into(), name: format!("Project {id}"), kind, template: None, starts: Some(d(starts)), ends: Some(d(ends)), colour: Colour::Blue, rate: Some(Haler(80_000)) }
|
||||
}
|
||||
|
||||
fn line(project: &str, id: &str, planned: i64) -> EventBody {
|
||||
EventBody::ProjectLineSet { project: project.into(), line: id.into(), name: id.to_uppercase(), planned: Haler(planned) }
|
||||
}
|
||||
|
||||
fn paid(id: &str, amount: i64, date: &str, merchant: &str, category: Option<&str>) -> EventBody {
|
||||
EventBody::PaymentAdded { payment: id.into(), amount: Haler(amount), date: d(date), merchant: merchant.into(), category: category.map(str::to_string), note: None }
|
||||
}
|
||||
|
||||
fn into(payment: &str, project: &str, line: Option<&str>) -> EventBody {
|
||||
EventBody::PaymentProjected { payment: payment.into(), project: project.into(), line: line.map(str::to_string) }
|
||||
}
|
||||
|
||||
fn task(id: &str, project: &str, due: Option<&str>, estimate: Option<i64>) -> EventBody {
|
||||
EventBody::TaskCreated {
|
||||
task: id.into(),
|
||||
project: project.into(),
|
||||
fields: TaskFields { title: format!("Task {id}"), phase: None, due: due.map(d), estimate: estimate.map(Haler), line: None, assignee: None, milestone: false },
|
||||
}
|
||||
}
|
||||
|
||||
fn done(task: &str, on: &str) -> EventBody {
|
||||
EventBody::TaskStatusSet { task: task.into(), status: TaskStatus::Done, on: d(on) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renovation_spent_by_line_by_hand_and_by_rule_within_its_dates() {
|
||||
let today = d("2026-11-20");
|
||||
let s = ledger(vec![
|
||||
made("flat", Kind::Simple, "2026-11-01", "2027-02-28"),
|
||||
line("flat", "kitchen", 12_000_000),
|
||||
line("flat", "tiles", 4_500_000),
|
||||
paid("p1", -9_000_000, "2026-11-04", "IKEA Zlicin", None),
|
||||
into("p1", "flat", Some("kitchen")),
|
||||
paid("p2", -5_000_000, "2026-11-06", "Siko koupelny", None),
|
||||
into("p2", "flat", Some("tiles")),
|
||||
paid("p3", -120_000, "2026-11-08", "Hornbach Cerny Most", None),
|
||||
paid("p4", -80_000, "2026-10-20", "Hornbach Cerny Most", None),
|
||||
paid("p5", -50_000, "2026-11-09", "Albert", Some("groceries")),
|
||||
EventBody::ProjectRuleSet { merchant_key: fiscus_ledger::merchant::merchant_key("Hornbach Cerny Most"), project: Some("flat".into()) },
|
||||
task("t1", "flat", Some("2026-11-10"), None),
|
||||
task("t2", "flat", Some("2026-12-10"), None),
|
||||
task("t3", "flat", None, None),
|
||||
done("t3", "2026-11-07"),
|
||||
]);
|
||||
let p = project(&s, "flat", today).unwrap();
|
||||
let lines: Vec<(&str, Haler, Haler, bool)> = p.lines.iter().map(|l| (l.id.as_str(), l.spent, l.left, l.over)).collect();
|
||||
assert_eq!(lines, [("kitchen", Haler(9_000_000), Haler(3_000_000), false), ("tiles", Haler(5_000_000), Haler(-500_000), true)]);
|
||||
// Hornbach in November by the rule (before the project started: not), Albert never.
|
||||
assert_eq!(p.unplanned, Haler(120_000));
|
||||
assert_eq!(p.summary.spent, Haler(14_120_000));
|
||||
assert_eq!(p.payments.iter().map(|x| (x.id.as_str(), x.by_rule)).collect::<Vec<_>>(), [("p3", true), ("p2", false), ("p1", false)]);
|
||||
assert_eq!((p.summary.planned, p.summary.over_budget), (Haler(16_500_000), false), "a line over is not the project over");
|
||||
// One task of three done (no estimates: by count); t1 is past its due date.
|
||||
assert_eq!((p.summary.progress_permille, p.summary.late_tasks, p.summary.late), (333, 1, true));
|
||||
assert_eq!((p.summary.tasks.todo, p.summary.tasks.done), (2, 1));
|
||||
assert_eq!(p.tasks.iter().map(|t| (t.task.id.as_str(), t.late)).collect::<Vec<_>>(), [("t1", true), ("t2", false), ("t3", false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_forecast_and_progress_by_estimates() {
|
||||
let today = d("2026-11-20");
|
||||
let s = ledger(vec![
|
||||
made("flat", Kind::Simple, "2026-11-01", "2027-02-28"),
|
||||
line("flat", "all", 10_000_000),
|
||||
paid("p1", -6_000_000, "2026-11-04", "Firma Novak", None),
|
||||
into("p1", "flat", Some("all")),
|
||||
task("t1", "flat", None, Some(6_000_000)),
|
||||
task("t2", "flat", None, Some(5_000_000)),
|
||||
done("t1", "2026-11-05"),
|
||||
]);
|
||||
let p = &projects(&s, today)[0];
|
||||
// 6 of 11 (by estimates) done; 6 spent + 5 to come = 11 > 10 planned.
|
||||
assert_eq!((p.progress_permille, p.open_estimates, p.forecast, p.over_budget), (545, Haler(5_000_000), Haler(11_000_000), true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_business_earns_from_paid_invoices_without_vat_and_never_twice() {
|
||||
let today = d("2026-11-20");
|
||||
let party = |name: &str, ico: &str| Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some(ico.into()), dic: None };
|
||||
let invoice = |id: &str, number: &str| Invoice {
|
||||
id: id.into(),
|
||||
number: number.into(),
|
||||
issued: d("2026-11-05"),
|
||||
due: d("2026-11-19"),
|
||||
taxable: None,
|
||||
customer: party("Pekárna Novák", "45244782"),
|
||||
lines: vec![InvoiceLine { text: "Web".into(), quantity: 10_000, unit: "h".into(), unit_price: Haler(80_000), vat: None }],
|
||||
budget: None,
|
||||
language: Language::Cs,
|
||||
};
|
||||
let s = ledger(vec![
|
||||
made("web", Kind::Business, "2026-11-01", "2026-12-31"),
|
||||
EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } },
|
||||
EventBody::InvoiceIssued { invoice: invoice("i1", "20260001") },
|
||||
EventBody::InvoiceIssued { invoice: invoice("i2", "20260002") },
|
||||
EventBody::TimeLogged { entry: "l1".into(), project: "web".into(), task: None, minutes: 600, on: d("2026-11-03"), rate: Haler(80_000), note: String::new() },
|
||||
EventBody::TimeLogged { entry: "l2".into(), project: "web".into(), task: None, minutes: 90, on: d("2026-11-10"), rate: Haler(80_000), note: String::new() },
|
||||
EventBody::InvoiceProjected { invoice: "i1".into(), project: "web".into(), entries: vec!["l1".into()] },
|
||||
EventBody::InvoiceProjected { invoice: "i2".into(), project: "web".into(), entries: vec![] },
|
||||
// i1 marked paid by hand (its money in is not put into the project: the invoice is the income).
|
||||
EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-11-18") },
|
||||
// A tip from the client straight into the project; a tool bought for it.
|
||||
paid("in2", 50_000, "2026-11-19", "Pekarna Novak", Some("income")),
|
||||
into("in2", "web", None),
|
||||
paid("out1", -100_000, "2026-11-12", "Adobe", None),
|
||||
into("out1", "web", None),
|
||||
]);
|
||||
let p = project(&s, "web", today).unwrap();
|
||||
// i1 paid (8 000 Kč without VAT) and the tip (500 Kč); i2 is not paid yet.
|
||||
assert_eq!(p.summary.income, Haler(800_000 + 50_000));
|
||||
let s2 = ledger(vec![
|
||||
made("web", Kind::Business, "2026-11-01", "2026-12-31"),
|
||||
EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } },
|
||||
EventBody::InvoiceIssued { invoice: invoice("i1", "20260001") },
|
||||
EventBody::InvoiceProjected { invoice: "i1".into(), project: "web".into(), entries: vec![] },
|
||||
EventBody::PaymentImported {
|
||||
payment: "line1".into(),
|
||||
line: fiscus_ledger::import::StatementLine {
|
||||
bank: "test".into(),
|
||||
account: "1/0000".into(),
|
||||
booked: d("2026-11-18"),
|
||||
amount: Haler(800_000),
|
||||
merchant: "Pekarna Novak".into(),
|
||||
counterparty: None,
|
||||
variable_symbol: Some("20260001".into()),
|
||||
message: None,
|
||||
bank_ref: None,
|
||||
},
|
||||
line_key: "k1".into(),
|
||||
},
|
||||
EventBody::InvoicePaid { invoice: "i1".into(), payment: Some("line1".into()), on: d("2026-11-18") },
|
||||
into("line1", "web", None),
|
||||
]);
|
||||
// A statement line that paid the project's invoice, put into the project too, is the invoice: counted once.
|
||||
assert_eq!(project(&s2, "web", today).unwrap().summary.income, Haler(800_000));
|
||||
|
||||
assert_eq!((p.summary.spent, p.summary.profit), (Haler(100_000), Haler(750_000)));
|
||||
assert_eq!(p.summary.margin_permille, Some(882));
|
||||
// 11 h 30 min logged; 10 h billed by i1, 1 h 30 min (1 200 Kč) not yet.
|
||||
assert_eq!((p.summary.minutes, p.summary.unbilled_minutes, p.summary.unbilled, p.billable), (690, 90, Haler(120_000), Haler(920_000)));
|
||||
assert_eq!(p.unbilled_entries, ["l2"]);
|
||||
assert_eq!(p.time_by_week, [(d("2026-11-02"), 600), (d("2026-11-09"), 90)]);
|
||||
assert_eq!((p.time_by_task[0].task.clone(), p.time_by_task[0].minutes), (None, 690));
|
||||
assert_eq!(p.invoices, ["i1", "i2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_late_past_its_end_and_the_medals_when_done() {
|
||||
let s = ledger(vec![
|
||||
made("trip", Kind::Simple, "2026-08-01", "2026-09-30"),
|
||||
line("trip", "all", 3_000_000),
|
||||
paid("p1", -2_500_000, "2026-08-15", "Booking.com", None),
|
||||
into("p1", "trip", None),
|
||||
task("t1", "trip", None, None),
|
||||
]);
|
||||
let today = d("2026-10-05");
|
||||
assert!(projects(&s, today)[0].late, "past its end with a task open");
|
||||
|
||||
let mut log = vec![
|
||||
made("trip", Kind::Simple, "2026-08-01", "2026-09-30"),
|
||||
line("trip", "all", 3_000_000),
|
||||
paid("p1", -2_500_000, "2026-08-15", "Booking.com", None),
|
||||
into("p1", "trip", None),
|
||||
task("t1", "trip", None, None),
|
||||
done("t1", "2026-09-20"),
|
||||
EventBody::ProjectStatusSet { project: "trip".into(), status: Status::Done, on: d("2026-09-25") },
|
||||
made("late", Kind::Simple, "2026-08-01", "2026-09-01"),
|
||||
line("late", "all", 100_000),
|
||||
paid("p2", -500_000, "2026-08-15", "Bauhaus", None),
|
||||
into("p2", "late", None),
|
||||
EventBody::ProjectStatusSet { project: "late".into(), status: Status::Done, on: d("2026-09-10") },
|
||||
];
|
||||
let s = ledger(std::mem::take(&mut log));
|
||||
assert!(!projects(&s, today).iter().any(|p| p.late), "a done project is never late");
|
||||
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
|
||||
let got: Vec<(&str, Date)> = r
|
||||
.medals
|
||||
.iter()
|
||||
.filter_map(|e| match &e.medal {
|
||||
Medal::ProjectOnBudget { project, .. } => Some(("on budget", if project == "trip" { e.on } else { d("1970-01-01") })),
|
||||
Medal::FinishedOnTime { project, .. } => Some(("on time", if project == "trip" { e.on } else { d("1970-01-01") })),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(got, [("on budget", d("2026-09-25")), ("on time", d("2026-09-25"))], "the trip earns both; the late, over one neither");
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Spending, the month against its plan, and a month in numbers: one definition of spending everywhere,
|
||||
//! shares that always add up to 1000, the pace by today, and the suggested plan rounded up.
|
||||
|
||||
use fiscus_insight::plan::{month_plan, suggest, Pace};
|
||||
use fiscus_insight::stats::{month_stats, SLICES};
|
||||
use fiscus_insight::subscriptions::analyse;
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
/// A ledger from `(date, amount in haléře, merchant, category)` added by hand, then `extra` events.
|
||||
fn ledger(payments: &[(&str, i64, &str, &str)], extra: Vec<EventBody>) -> State {
|
||||
let mut log: Vec<Event> = payments
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (date, amount, merchant, category))| {
|
||||
Event::new(
|
||||
format!("e{i}"),
|
||||
Timestamp(0),
|
||||
EventBody::PaymentAdded {
|
||||
payment: format!("p{i}"),
|
||||
amount: Haler(*amount),
|
||||
date: d(date),
|
||||
merchant: merchant.to_string(),
|
||||
category: (!category.is_empty()).then(|| category.to_string()),
|
||||
note: None,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
log.extend(extra.into_iter().enumerate().map(|(i, b)| Event::new(format!("x{i}"), Timestamp(0), b)));
|
||||
let s = State::replay(&log);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
s
|
||||
}
|
||||
|
||||
fn planned(category: &str, amount: i64, from: &str) -> EventBody {
|
||||
EventBody::CategoryPlanned { category: category.into(), amount: Haler(amount), from: d(from) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_month_against_its_plan() {
|
||||
let today = d("2026-11-15");
|
||||
let s = ledger(
|
||||
&[
|
||||
("2026-11-02", -300_000, "Albert", "groceries"),
|
||||
("2026-11-10", -150_000, "Lidl", "groceries"),
|
||||
("2026-11-12", -250_000, "Lokál", "eating-out"),
|
||||
("2026-11-14", -40_000, "Trafika", ""),
|
||||
("2026-11-03", -1_000_000, "To savings", "transfers"),
|
||||
("2026-11-05", 5_000_000, "Salary", "income"),
|
||||
("2026-11-20", -90_000, "Albert", "groceries"),
|
||||
("2026-10-30", -999_999, "Albert", "groceries"),
|
||||
("2026-11-08", -60_000, "Shell", "transport"),
|
||||
],
|
||||
vec![planned("groceries", 1_000_000, "2026-10-01"), planned("eating-out", 200_000, "2026-11-01"), planned("transport", 400_000, "2026-11-01")],
|
||||
);
|
||||
let p = month_plan(&s, today, today).unwrap();
|
||||
assert_eq!(p.month, d("2026-11-01"));
|
||||
type Row<'a> = (&'a str, Option<i64>, i64, Option<i64>, u32, Option<Pace>);
|
||||
let rows: Vec<Row> =
|
||||
p.rows.iter().map(|r| (r.category.as_str(), r.planned.map(|x| x.0), r.spent.0, r.left.map(|x| x.0), r.permille, r.pace)).collect();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
// Half the month gone (15 of 30 days): 4 500 of 10 000 is 90 % of the pace, on pace.
|
||||
("groceries", Some(1_000_000), 450_000, Some(550_000), 450, Some(Pace::OnPace)),
|
||||
("eating-out", Some(200_000), 250_000, Some(-50_000), 1000, Some(Pace::Over)),
|
||||
("transport", Some(400_000), 60_000, Some(340_000), 150, Some(Pace::Under)),
|
||||
// Spent with no plan: uncategorised. Transfers, income, the future and last month do not count.
|
||||
("uncategorised", None, 40_000, None, 0, None),
|
||||
]
|
||||
);
|
||||
assert_eq!((p.planned, p.spent, p.unplanned), (Haler(1_600_000), Haler(800_000), Haler(40_000)));
|
||||
|
||||
// A past month is done: within the plan is Under, past it Over. A month to come has nothing spent.
|
||||
let oct = month_plan(&s, d("2026-10-01"), today).unwrap();
|
||||
assert_eq!(oct.rows[0].pace, Some(Pace::Under));
|
||||
assert_eq!(oct.rows[0].spent, Haler(999_999));
|
||||
let dec = month_plan(&s, d("2026-12-01"), today).unwrap();
|
||||
assert_eq!(dec.spent, Haler::ZERO);
|
||||
assert!(dec.rows.iter().all(|r| r.pace.is_none()), "not begun");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ahead_of_the_pace() {
|
||||
let s = ledger(&[("2026-11-03", -500_000, "Albert", "groceries")], vec![planned("groceries", 1_000_000, "2026-11-01")]);
|
||||
// 5 days of 30 allow 1 666,66; 5 000 is far ahead, but not over the month's 10 000.
|
||||
assert_eq!(month_plan(&s, d("2026-11-05"), d("2026-11-05")).unwrap().rows[0].pace, Some(Pace::Ahead));
|
||||
assert_eq!(month_plan(&s, d("2026-11-30"), d("2026-11-30")).unwrap().rows[0].pace, Some(Pace::Under));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_suggested_plan_is_the_average_rounded_up_to_hundreds() {
|
||||
let s = ledger(
|
||||
&[
|
||||
("2026-08-10", -100_000, "Albert", "groceries"),
|
||||
("2026-09-10", -200_000, "Albert", "groceries"),
|
||||
("2026-10-10", -300_001, "Albert", "groceries"),
|
||||
("2026-10-11", -12_345, "Lokál", "eating-out"),
|
||||
("2026-10-12", -50_000, "To savings", "transfers"),
|
||||
("2026-10-13", -7_000, "?", ""),
|
||||
("2026-11-01", -999_999, "Albert", "groceries"),
|
||||
("2026-07-01", -5_000_000, "Albert", "groceries"),
|
||||
],
|
||||
vec![],
|
||||
);
|
||||
// Aug, Sep, Oct (not this November, not July): 6 000,01 / 3 = 2 000,0034 → 2 100.
|
||||
let got = suggest(&s, d("2026-11-15"));
|
||||
assert_eq!(got, [("groceries".to_string(), Haler(210_000)), ("eating-out".to_string(), Haler(10_000))]);
|
||||
|
||||
// A ledger only a month old is not divided by three.
|
||||
let young = ledger(&[("2026-10-10", -150_000, "Albert", "groceries")], vec![]);
|
||||
assert_eq!(suggest(&young, d("2026-11-15")), [("groceries".to_string(), Haler(150_000))]);
|
||||
assert!(suggest(&State::default(), d("2026-11-15")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_month_in_numbers() {
|
||||
let today = d("2026-11-15");
|
||||
let mut payments = vec![
|
||||
("2026-11-02", -300_000, "Albert Praha", "groceries"),
|
||||
("2026-11-09", -100_000, "ALBERT PRAHA", "groceries"),
|
||||
("2026-11-03", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
|
||||
("2026-11-04", -50_000, "Lokál", "eating-out"),
|
||||
("2026-11-05", 4_000_000, "Salary", "income"),
|
||||
("2026-11-06", -1_000_000, "To savings", "transfers"),
|
||||
("2026-11-07", -33_100, "", "fun"),
|
||||
("2026-10-02", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
|
||||
("2026-09-02", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
|
||||
("2026-10-10", -200_000, "Albert Praha", "groceries"),
|
||||
("2026-10-20", -500_000, "Albert Praha", "groceries"),
|
||||
("2026-11-20", -77_700, "Albert Praha", "groceries"),
|
||||
];
|
||||
// Eight more categories, so the pie has a slice for the rest.
|
||||
let more = ["transport", "housing", "utilities", "shopping", "health", "kids", "travel", "gifts"];
|
||||
for (i, c) in more.iter().enumerate() {
|
||||
payments.push(("2026-11-10", -(1_000 + i as i64), "Shop", c));
|
||||
}
|
||||
let s = ledger(&payments, vec![]);
|
||||
let st = month_stats(&s, &analyse(&s, today), today, today).unwrap();
|
||||
|
||||
assert_eq!(st.month, d("2026-11-01"));
|
||||
let spent = 300_000 + 100_000 + 16_900 + 50_000 + 33_100 + (1_000..1_008).sum::<i64>();
|
||||
assert_eq!((st.out, st.inflow, st.net), (Haler(spent), Haler(4_000_000), Haler(4_000_000 - spent)));
|
||||
assert_eq!(st.slices.len(), SLICES + 1);
|
||||
assert_eq!(st.slices.iter().map(|s| s.permille).sum::<u32>(), 1000, "the slices add up");
|
||||
assert_eq!(st.slices[0].category.as_deref(), Some("groceries"));
|
||||
assert_eq!(st.slices[0].amount, Haler(400_000));
|
||||
assert!(st.slices.last().unwrap().category.is_none(), "the rest");
|
||||
assert!(st.slices.windows(2).take(SLICES - 1).all(|w| w[0].amount >= w[1].amount), "largest first");
|
||||
|
||||
// Six months, oldest first; October in full, November up to today.
|
||||
let months: Vec<(Date, i64)> = st.months.iter().map(|m| (m.month, m.out.0)).collect();
|
||||
assert_eq!(months.len(), 6);
|
||||
assert_eq!(months[0].0, d("2026-06-01"));
|
||||
assert_eq!(months[4], (d("2026-10-01"), 716_900));
|
||||
assert_eq!(months[5], (d("2026-11-01"), spent));
|
||||
// By 15 October: the Spotify charge and the first Albert.
|
||||
assert_eq!(st.same_day_last_month, Haler(216_900));
|
||||
|
||||
let top: Vec<(&str, i64, usize)> = st.top_merchants.iter().map(|m| (m.key.as_str(), m.amount.0, m.count)).collect();
|
||||
assert_eq!(top[0], ("albert praha", 400_000, 2), "one merchant however the bank writes it");
|
||||
assert!(top.iter().all(|(k, _, _)| !k.is_empty()), "a payment without a merchant is not a merchant");
|
||||
assert!(top.len() <= 5);
|
||||
|
||||
assert_eq!(st.subscriptions, Haler(16_900));
|
||||
assert_eq!(st.subscriptions_permille, (16_900 * 1000 / spent) as u32);
|
||||
|
||||
// A past month: whole, compared with all of the month before.
|
||||
let oct = month_stats(&s, &analyse(&s, today), d("2026-10-31"), today).unwrap();
|
||||
assert_eq!((oct.out, oct.same_day_last_month), (Haler(716_900), Haler(16_900)));
|
||||
// A month to come has no numbers yet; an empty month is zeros, not nothing.
|
||||
assert!(month_stats(&s, &analyse(&s, today), d("2026-12-01"), today).is_none());
|
||||
let empty = month_stats(&s, &analyse(&s, today), d("2026-03-01"), today).unwrap();
|
||||
assert!(empty.slices.is_empty());
|
||||
assert_eq!((empty.out, empty.subscriptions_permille), (Haler::ZERO, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sum_that_would_not_fit_gives_no_numbers() {
|
||||
let s = ledger(&[("2026-11-02", i64::MIN + 1, "A", "fun"), ("2026-11-03", i64::MIN + 1, "B", "fun")], vec![]);
|
||||
let today = d("2026-11-15");
|
||||
assert!(month_stats(&s, &analyse(&s, today), today, today).is_none());
|
||||
assert!(month_plan(&s, today, today).is_none());
|
||||
}
|
||||
@@ -178,6 +178,10 @@ fn the_cancel_kit() {
|
||||
let kit = cancel_kit(wedos);
|
||||
assert_eq!(kit.url, None, "an unknown provider gets the email only");
|
||||
assert!(kit.mailto().starts_with("mailto:?subject="));
|
||||
let kit = fiscus_insight::cancel::cancel_kit_in(netflix, fiscus_ledger::invoice::Language::Cs);
|
||||
assert_eq!(kit.email_subject, "Zrušení předplatného Netflix");
|
||||
assert!(kit.email_body.starts_with("Dobrý den,") && kit.email_body.contains("259,00 Kč") && kit.email_body.contains("měsíční"), "{}", kit.email_body);
|
||||
assert_eq!(kit.url.as_deref(), Some("https://www.netflix.com/cancelplan"), "the same page in either language");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
//! The categories the app offers. A category is an id; the label is what the app shows.
|
||||
|
||||
pub const UNCATEGORISED: &str = "uncategorised";
|
||||
/// Money between your own accounts: never spending.
|
||||
pub const TRANSFERS: &str = "transfers";
|
||||
pub const INCOME: &str = "income";
|
||||
|
||||
/// Categories a monthly plan cannot be for: money in, money moved, and money not yet sorted.
|
||||
pub const NOT_PLANNABLE: [&str; 3] = [INCOME, TRANSFERS, UNCATEGORISED];
|
||||
|
||||
/// The most a category's monthly plan can be: 100 000 000 CZK, far from any sum overflowing.
|
||||
pub const MAX_PLAN: crate::money::Haler = crate::money::Haler(10_000_000_000);
|
||||
|
||||
/// `(id, label)` in the order the app lists them.
|
||||
pub const DEFAULT: &[(&str, &str)] = &[
|
||||
@@ -16,8 +25,8 @@ pub const DEFAULT: &[(&str, &str)] = &[
|
||||
("fun", "Fun"),
|
||||
("travel", "Travel"),
|
||||
("gifts", "Gifts"),
|
||||
("income", "Income"),
|
||||
("transfers", "Transfers"),
|
||||
(INCOME, "Income"),
|
||||
(TRANSFERS, "Transfers"),
|
||||
("other", "Other"),
|
||||
(UNCATEGORISED, "Uncategorised"),
|
||||
];
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! The event log. Append only: a correction is a new event, nothing is ever edited or removed.
|
||||
|
||||
use crate::date::{Date, Timestamp};
|
||||
use crate::goal::{ChallengeGoal, ChallengeId, Colour, GoalId, Way, WayKind};
|
||||
use crate::project::{EntryId, Kind, LineId, PhaseId, ProjectId, Status, TaskFields, TaskId, TaskStatus};
|
||||
use crate::import::StatementLine;
|
||||
use crate::invoice::{Invoice, InvoiceId, Supplier};
|
||||
use crate::money::Haler;
|
||||
use crate::split::Share;
|
||||
use crate::state::Glyph;
|
||||
@@ -84,6 +87,10 @@ pub enum EventBody {
|
||||
PaymentAssigned { payment: PaymentId, budget: BudgetId },
|
||||
#[serde(rename = "payment.trial_marked")]
|
||||
PaymentTrialMarked { payment: PaymentId, ends: Date },
|
||||
/// A receipt for the payment: the shop's name you confirmed, its IČO and DIČ (docs/07_receipts.md). A later one
|
||||
/// replaces it. The payment keeps its own merchant.
|
||||
#[serde(rename = "payment.receipt_attached")]
|
||||
ReceiptAttached { payment: PaymentId, receipt: crate::receipt::ReceiptInfo },
|
||||
#[serde(rename = "budget.created")]
|
||||
BudgetCreated { budget: BudgetId, name: String, limit: Haler },
|
||||
/// A shared budget in a personal log (created here or joined): like `budget.created`, but never the
|
||||
@@ -128,4 +135,107 @@ pub enum EventBody {
|
||||
/// The account people pay back to by QR Platba.
|
||||
#[serde(rename = "account.set")]
|
||||
AccountSet { iban: String, name: String },
|
||||
/// The name this person shows to the members of their shared budgets (the personal log).
|
||||
#[serde(rename = "profile.named")]
|
||||
ProfileNamed { name: String },
|
||||
/// Share my subscription names with this shared budget's members, or stop (the personal log).
|
||||
#[serde(rename = "household.sharing_set")]
|
||||
HouseholdSharingSet { budget: BudgetId, on: bool },
|
||||
/// A shared budget's log: the name its author shows there. The latest per author counts.
|
||||
#[serde(rename = "member.named")]
|
||||
MemberNamed { budget: BudgetId, name: String },
|
||||
/// A shared budget's log: every subscription its author pays, as service keys (`spotify`). The latest per
|
||||
/// author replaces the earlier ones; an empty list withdraws them.
|
||||
#[serde(rename = "subscriptions.shared")]
|
||||
SubscriptionsShared { budget: BudgetId, names: Vec<String> },
|
||||
/// Who issues invoices from this ledger, and what share of each paid one is set aside for tax. The latest
|
||||
/// counts from then on; an invoice keeps the supplier it was issued under.
|
||||
#[serde(rename = "supplier.set")]
|
||||
SupplierSet { supplier: Supplier },
|
||||
#[serde(rename = "invoice.issued")]
|
||||
InvoiceIssued { invoice: Invoice },
|
||||
/// Paid: by `payment` (a statement line whose amount and variable symbol match), or marked paid by hand
|
||||
/// (`None`: cash, another account). The reserve is set aside then.
|
||||
#[serde(rename = "invoice.paid")]
|
||||
InvoicePaid { invoice: InvoiceId, payment: Option<PaymentId>, on: Date },
|
||||
/// Cancelled before it was paid.
|
||||
#[serde(rename = "invoice.cancelled")]
|
||||
InvoiceCancelled { invoice: InvoiceId },
|
||||
/// Money taken out of the tax reserve (the tax or insurance paid from it).
|
||||
#[serde(rename = "reserve.withdrawn")]
|
||||
ReserveWithdrawn { withdrawal: String, amount: Haler, on: Date, note: String },
|
||||
/// The most you mean to spend on one category in a month, from the month of `from` (its 1st) on, until a
|
||||
/// later plan for that category replaces it. Zero removes the plan. Personal log only.
|
||||
#[serde(rename = "category.planned")]
|
||||
CategoryPlanned { category: Category, amount: Haler, from: Date },
|
||||
/// A category of your own (an id as [`crate::categories::is_valid`]) and the name the app shows for it.
|
||||
#[serde(rename = "category.created")]
|
||||
CategoryCreated { category: Category, label: String },
|
||||
/// A savings goal (see [`crate::goal`]): a name, a target, an optional date to reach it by, the tank's colour.
|
||||
#[serde(rename = "goal.created")]
|
||||
GoalCreated { goal: GoalId, name: String, target: Haler, by: Option<Date>, colour: Colour },
|
||||
/// A goal's name, target, date or colour changed; the latest counts.
|
||||
#[serde(rename = "goal.changed")]
|
||||
GoalChanged { goal: GoalId, name: String, target: Haler, by: Option<Date>, colour: Colour },
|
||||
/// How a goal is saved for: up to one way of each kind. Replaces the goal's earlier ways.
|
||||
#[serde(rename = "goal.ways_set")]
|
||||
GoalWaysSet { goal: GoalId, ways: Vec<Way> },
|
||||
/// Money put aside for a goal (positive) or taken out (negative), by one of its ways or by hand (`None`).
|
||||
#[serde(rename = "goal.saved")]
|
||||
GoalSaved { goal: GoalId, saving: String, amount: Haler, on: Date, way: Option<WayKind> },
|
||||
/// Reached or given up: no more saving into it. Its history stays.
|
||||
#[serde(rename = "goal.closed")]
|
||||
GoalClosed { goal: GoalId, on: Date },
|
||||
/// A challenge you set yourself, from `starts` to `ends` (both included, at most 92 days).
|
||||
#[serde(rename = "challenge.started")]
|
||||
ChallengeStarted { challenge: ChallengeId, goal: ChallengeGoal, starts: Date, ends: Date },
|
||||
/// Given up; a challenge is given up once.
|
||||
#[serde(rename = "challenge.abandoned")]
|
||||
ChallengeAbandoned { challenge: ChallengeId, on: Date },
|
||||
/// A project (see [`crate::project`]): simple or business, from a template or empty.
|
||||
#[serde(rename = "project.created")]
|
||||
ProjectCreated { project: ProjectId, name: String, kind: Kind, template: Option<String>, starts: Option<Date>, ends: Option<Date>, colour: Colour, rate: Option<Haler> },
|
||||
/// Its name, kind, dates, colour or rate changed; the latest counts.
|
||||
#[serde(rename = "project.changed")]
|
||||
ProjectChanged { project: ProjectId, name: String, kind: Kind, starts: Option<Date>, ends: Option<Date>, colour: Colour, rate: Option<Haler> },
|
||||
#[serde(rename = "project.status_set")]
|
||||
ProjectStatusSet { project: ProjectId, status: Status, on: Date },
|
||||
/// A budget line: its name and planned amount. Zero planned removes it.
|
||||
#[serde(rename = "project.line_set")]
|
||||
ProjectLineSet { project: ProjectId, line: LineId, name: String, planned: Haler },
|
||||
/// A phase of a project, from `starts` to `ends`.
|
||||
#[serde(rename = "project.phase_set")]
|
||||
ProjectPhaseSet { project: ProjectId, phase: PhaseId, name: String, starts: Date, ends: Date },
|
||||
#[serde(rename = "project.phase_removed")]
|
||||
ProjectPhaseRemoved { project: ProjectId, phase: PhaseId },
|
||||
/// A payment put into a project (and one of its lines). One project per payment; it stays in its budget.
|
||||
#[serde(rename = "payment.projected")]
|
||||
PaymentProjected { payment: PaymentId, project: ProjectId, line: Option<LineId> },
|
||||
#[serde(rename = "payment.unprojected")]
|
||||
PaymentUnprojected { payment: PaymentId },
|
||||
/// "Always <merchant key> → <project>"; `None` removes the rule. It stops when the project is done.
|
||||
#[serde(rename = "project.rule_set")]
|
||||
ProjectRuleSet { merchant_key: String, project: Option<ProjectId> },
|
||||
#[serde(rename = "task.created")]
|
||||
TaskCreated { task: TaskId, project: ProjectId, fields: TaskFields },
|
||||
#[serde(rename = "task.changed")]
|
||||
TaskChanged { task: TaskId, fields: TaskFields },
|
||||
#[serde(rename = "task.status_set")]
|
||||
TaskStatusSet { task: TaskId, status: TaskStatus, on: Date },
|
||||
/// Time worked on a business project (a task of it, or the project as a whole), at an hourly rate.
|
||||
#[serde(rename = "time.logged")]
|
||||
TimeLogged { entry: EntryId, project: ProjectId, task: Option<TaskId>, minutes: u32, on: Date, rate: Haler, note: String },
|
||||
#[serde(rename = "time.removed")]
|
||||
TimeRemoved { entry: EntryId },
|
||||
/// An invoice issued for a business project, and the time entries it bills (none: not from time).
|
||||
#[serde(rename = "invoice.projected")]
|
||||
InvoiceProjected { invoice: InvoiceId, project: ProjectId, entries: Vec<EntryId> },
|
||||
/// The project is shared with the members of a shared budget: the app mirrors its name, dates, status, lines,
|
||||
/// phases and tasks through that budget's log. Time, invoices and project rules are never shared. One budget
|
||||
/// at a time.
|
||||
#[serde(rename = "project.shared")]
|
||||
ProjectShared { project: ProjectId, budget: BudgetId },
|
||||
/// Not shared any more: the members keep the copy they have.
|
||||
#[serde(rename = "project.unshared")]
|
||||
ProjectUnshared { project: ProjectId },
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Savings goals and challenges: what you mean to put aside and how, and the challenges you set yourself. Fiscus
|
||||
//! never moves money: a goal holds what you said you put aside (`goal.saved`), so it is never full unless you
|
||||
//! filled it. Personal log only, like plans: a shared budget's members never see them.
|
||||
|
||||
use crate::event::Category;
|
||||
use crate::money::Haler;
|
||||
use crate::date::Date;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub type GoalId = String;
|
||||
pub type ChallengeId = String;
|
||||
|
||||
/// At most this many goals open at once.
|
||||
pub const MAX_OPEN_GOALS: usize = 20;
|
||||
/// At most this many challenges running (not ended, not given up) at once.
|
||||
pub const MAX_OPEN_CHALLENGES: usize = 20;
|
||||
/// A goal's target, a fixed monthly amount, a challenge's amount: 1 Kč to 100 000 000 Kč.
|
||||
pub const MIN_AMOUNT: Haler = Haler(100);
|
||||
pub const MAX_AMOUNT: Haler = Haler(10_000_000_000);
|
||||
/// A challenge lasts at most 92 days, its first and last day included.
|
||||
pub const MAX_CHALLENGE_DAYS: i32 = 92;
|
||||
/// Round-ups go to the next 10, 50 or 100 Kč.
|
||||
pub const ROUND_UP_TO: [Haler; 3] = [Haler(1_000), Haler(5_000), Haler(10_000)];
|
||||
|
||||
/// The tank's colour, from the app's palette.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Colour {
|
||||
Teal,
|
||||
Amber,
|
||||
Coral,
|
||||
Blue,
|
||||
Violet,
|
||||
Green,
|
||||
}
|
||||
|
||||
/// How a goal's monthly saving is found. A goal has at most one of each kind.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Way {
|
||||
/// The same amount every month.
|
||||
Fixed { amount: Haler },
|
||||
/// Each card payment of the month rounded up to the next `to` (10, 50 or 100 Kč); the differences add up.
|
||||
RoundUp { to: Haler },
|
||||
/// This share (in thousandths) of what last month's category plans did not use.
|
||||
Leftover { permille: u16 },
|
||||
/// This share (in thousandths) of last month's money in.
|
||||
Income { permille: u16 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum WayKind {
|
||||
Fixed,
|
||||
RoundUp,
|
||||
Leftover,
|
||||
Income,
|
||||
}
|
||||
|
||||
impl Way {
|
||||
pub fn kind(&self) -> WayKind {
|
||||
match self {
|
||||
Way::Fixed { .. } => WayKind::Fixed,
|
||||
Way::RoundUp { .. } => WayKind::RoundUp,
|
||||
Way::Leftover { .. } => WayKind::Leftover,
|
||||
Way::Income { .. } => WayKind::Income,
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of the month's leftover or income this way takes, in thousandths (0 for the others).
|
||||
pub fn share_of(&self, kind: WayKind) -> u32 {
|
||||
match (self, kind) {
|
||||
(Way::Leftover { permille }, WayKind::Leftover) | (Way::Income { permille }, WayKind::Income) => u32::from(*permille),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a challenge asks.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum ChallengeGoal {
|
||||
/// Spend less than `amount` in `category` from the first day to the last.
|
||||
SpendUnder { category: Category, amount: Haler },
|
||||
/// Spend nothing in `category`.
|
||||
NoSpend { category: Category },
|
||||
/// Decide to cancel this subscription (its key) and not be charged for it again before the end.
|
||||
Cancel { subscription: String },
|
||||
/// Put `amount` aside for this goal.
|
||||
Save { goal: GoalId, amount: Haler },
|
||||
}
|
||||
|
||||
/// One amount put aside (positive) or taken out (negative).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Saving {
|
||||
pub id: String,
|
||||
pub amount: Haler,
|
||||
pub on: Date,
|
||||
pub way: Option<WayKind>,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct GoalRecord {
|
||||
pub id: GoalId,
|
||||
pub name: String,
|
||||
pub target: Haler,
|
||||
pub by: Option<Date>,
|
||||
pub colour: Colour,
|
||||
pub ways: Vec<Way>,
|
||||
/// In log order.
|
||||
pub savings: Vec<Saving>,
|
||||
pub closed: Option<Date>,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
impl GoalRecord {
|
||||
/// Everything put aside less everything taken out; never negative (the ledger refuses that).
|
||||
pub fn saved(&self) -> Haler {
|
||||
Haler(self.savings.iter().fold(0i64, |s, x| s.saturating_add(x.amount.0)))
|
||||
}
|
||||
|
||||
pub fn is_open(&self) -> bool {
|
||||
self.closed.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ChallengeRecord {
|
||||
pub id: ChallengeId,
|
||||
pub goal: ChallengeGoal,
|
||||
pub starts: Date,
|
||||
pub ends: Date,
|
||||
pub abandoned: Option<Date>,
|
||||
pub seq: u64,
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//! Invoices (faktury): the supplier, the customer, the lines and their totals, the number that is also the
|
||||
//! variable symbol, and the tax reserve set aside when one is paid. Money in haléře; quantities in thousandths.
|
||||
//!
|
||||
//! - A line's amount is `quantity × unit price`, rounded half away from zero to the haléř.
|
||||
//! - A VAT invoice (the supplier is a VAT payer): the base of each rate is the sum of its lines; the VAT of a rate
|
||||
//! is `base × rate / 100`, rounded the same way, once per rate (§ 37 ZDPH: from the base, per rate).
|
||||
//! - A non-VAT invoice has no rates, no taxable-supply date, and says the supplier is not a VAT payer.
|
||||
//! - The number is `YYYYNNNN`: the year it was issued and the invoice's place in that year. The same digits are
|
||||
//! the variable symbol, so a payment is matched by them.
|
||||
|
||||
use crate::date::{Date, Timestamp};
|
||||
use crate::event::{Event, EventBody};
|
||||
use crate::money::Haler;
|
||||
use crate::pay::MAX_AMOUNT;
|
||||
use crate::state::{CategorySource, EffectivePayment, InvoiceRecord, State};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
pub type InvoiceId = String;
|
||||
|
||||
/// The VAT rates in force in Czechia (from 2024): 21 %, 12 %, and 0 % for exempt supplies.
|
||||
pub const VAT_RATES: [u8; 3] = [21, 12, 0];
|
||||
/// At most this many lines on one invoice.
|
||||
pub const MAX_LINES: usize = 50;
|
||||
/// A quantity, in thousandths: from 0,001 to 1 000 000.
|
||||
pub const MAX_QUANTITY: i64 = 1_000_000_000;
|
||||
/// The share of a paid invoice set aside for tax, in thousandths: at most 60 %.
|
||||
pub const MAX_RESERVE_PERMILLE: u16 = 600;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum InvoiceError {
|
||||
#[error("a name must be 1-100 characters")]
|
||||
Name,
|
||||
#[error("an address has 1-4 lines of at most 100 characters")]
|
||||
Address,
|
||||
#[error("not a valid IČO (8 digits with a check digit)")]
|
||||
Ico,
|
||||
#[error("not a valid DIČ (CZ and 8-10 digits)")]
|
||||
Dic,
|
||||
#[error("an invoice has 1-50 lines")]
|
||||
Lines,
|
||||
#[error("a line's text must be 1-200 characters, its unit at most 10")]
|
||||
LineText,
|
||||
#[error("a quantity is between 0,001 and 1 000 000")]
|
||||
Quantity,
|
||||
#[error("a unit price is between 0,01 and 9 999 999,99 CZK")]
|
||||
Price,
|
||||
#[error("a VAT rate is 21, 12 or 0 %")]
|
||||
Rate,
|
||||
#[error("a VAT invoice gives every line a rate; an invoice without VAT gives none")]
|
||||
RateUse,
|
||||
#[error("the total must be between 0,01 and 9 999 999,99 CZK")]
|
||||
Total,
|
||||
#[error("an invoice number is the year and 4 digits, e.g. 20260001")]
|
||||
Number,
|
||||
#[error("the due date is before the issue date")]
|
||||
Due,
|
||||
#[error("a VAT invoice needs the date of the taxable supply; one without VAT has none")]
|
||||
Taxable,
|
||||
#[error("a VAT payer has a DIČ")]
|
||||
PayerDic,
|
||||
#[error("the reserve is 0-60 %")]
|
||||
Reserve,
|
||||
}
|
||||
|
||||
/// Someone on an invoice: the supplier or the customer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Party {
|
||||
pub name: String,
|
||||
/// Street, town and postcode, country: 1-4 lines.
|
||||
pub address: Vec<String>,
|
||||
pub ico: Option<String>,
|
||||
pub dic: Option<String>,
|
||||
}
|
||||
|
||||
/// The person issuing invoices from this ledger.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Supplier {
|
||||
pub party: Party,
|
||||
pub vat_payer: bool,
|
||||
/// Of each paid invoice's amount without VAT, this many thousandths are set aside for income tax and
|
||||
/// insurance (a VAT payer's VAT is always set aside in full, on top).
|
||||
pub reserve_permille: u16,
|
||||
/// A line printed on the invoice, such as the trade register entry. Optional.
|
||||
pub registration: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct InvoiceLine {
|
||||
pub text: String,
|
||||
/// Thousandths: 1 500 is 1,5.
|
||||
pub quantity: i64,
|
||||
/// `ks`, `h`, …; may be empty.
|
||||
pub unit: String,
|
||||
/// Per unit, without VAT on a VAT invoice.
|
||||
pub unit_price: Haler,
|
||||
/// The VAT rate in percent on a VAT invoice; `None` on an invoice without VAT.
|
||||
pub vat: Option<u8>,
|
||||
}
|
||||
|
||||
/// The language an invoice is printed in, chosen per invoice.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Language {
|
||||
#[default]
|
||||
Cs,
|
||||
En,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Invoice {
|
||||
pub id: InvoiceId,
|
||||
/// `YYYYNNNN`, also the variable symbol.
|
||||
pub number: String,
|
||||
pub issued: Date,
|
||||
pub due: Date,
|
||||
/// The date of the taxable supply (DUZP), on a VAT invoice only.
|
||||
pub taxable: Option<Date>,
|
||||
pub customer: Party,
|
||||
pub lines: Vec<InvoiceLine>,
|
||||
/// The budget the payment goes into when it arrives; `None`: the default budget.
|
||||
pub budget: Option<String>,
|
||||
/// What the printed invoice is in. Absent in an event: Czech.
|
||||
#[serde(default)]
|
||||
pub language: Language,
|
||||
}
|
||||
|
||||
/// What an invoice adds up to.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Totals {
|
||||
/// Each line's amount, in order.
|
||||
pub lines: Vec<Haler>,
|
||||
/// Rate → (base, VAT), highest rate first. Empty on an invoice without VAT.
|
||||
pub rates: Vec<(u8, Haler, Haler)>,
|
||||
/// Without VAT.
|
||||
pub net: Haler,
|
||||
pub vat: Haler,
|
||||
/// What the customer pays.
|
||||
pub total: Haler,
|
||||
}
|
||||
|
||||
/// `a × b / d`, rounded half away from zero, or `None` when it does not fit an `i64`.
|
||||
fn mul_div_round(a: i64, b: i64, d: i64) -> Option<i64> {
|
||||
let n = i128::from(a) * i128::from(b);
|
||||
let d = i128::from(d);
|
||||
let q = n / d;
|
||||
let r = n % d;
|
||||
let q = if 2 * r.abs() >= d { q + n.signum() } else { q };
|
||||
i64::try_from(q).ok()
|
||||
}
|
||||
|
||||
fn text_ok(s: &str, min: usize, max: usize) -> bool {
|
||||
let n = s.trim().chars().count();
|
||||
(min..=max).contains(&n) && s.chars().count() <= max + 20 && !s.chars().any(|c| c.is_control())
|
||||
}
|
||||
|
||||
/// An IČO: 8 digits whose last is the weighted mod-11 check of the first seven.
|
||||
pub fn ico_ok(s: &str) -> bool {
|
||||
if s.len() != 8 || !s.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return false;
|
||||
}
|
||||
let d: Vec<u32> = s.bytes().map(|b| u32::from(b - b'0')).collect();
|
||||
let sum: u32 = (0..7).map(|i| d[i] * (8 - i as u32)).sum();
|
||||
let check = (11 - sum % 11) % 10;
|
||||
d[7] == check
|
||||
}
|
||||
|
||||
/// A Czech DIČ: `CZ` and 8-10 digits.
|
||||
pub fn dic_ok(s: &str) -> bool {
|
||||
s.len() >= 10 && s.len() <= 12 && s.starts_with("CZ") && s[2..].bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
impl Party {
|
||||
pub fn check(&self) -> Result<(), InvoiceError> {
|
||||
if !text_ok(&self.name, 1, 100) {
|
||||
return Err(InvoiceError::Name);
|
||||
}
|
||||
if self.address.is_empty() || self.address.len() > 4 || !self.address.iter().all(|l| text_ok(l, 1, 100)) {
|
||||
return Err(InvoiceError::Address);
|
||||
}
|
||||
if self.ico.as_deref().is_some_and(|i| !ico_ok(i)) {
|
||||
return Err(InvoiceError::Ico);
|
||||
}
|
||||
if self.dic.as_deref().is_some_and(|d| !dic_ok(d)) {
|
||||
return Err(InvoiceError::Dic);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Supplier {
|
||||
pub fn check(&self) -> Result<(), InvoiceError> {
|
||||
self.party.check()?;
|
||||
if self.vat_payer && self.party.dic.is_none() {
|
||||
return Err(InvoiceError::PayerDic);
|
||||
}
|
||||
if self.reserve_permille > MAX_RESERVE_PERMILLE {
|
||||
return Err(InvoiceError::Reserve);
|
||||
}
|
||||
if self.registration.as_deref().is_some_and(|r| !text_ok(r, 1, 200)) {
|
||||
return Err(InvoiceError::Name);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What is set aside when an invoice with these totals is paid: all of its VAT, and the reserve share of
|
||||
/// the rest.
|
||||
pub fn reserve_for(&self, t: &Totals) -> Haler {
|
||||
let share = mul_div_round(t.net.0, i64::from(self.reserve_permille), 1000).unwrap_or(0);
|
||||
Haler(t.vat.0.saturating_add(share))
|
||||
}
|
||||
}
|
||||
|
||||
/// The amount of one line.
|
||||
pub fn line_amount(quantity: i64, unit_price: Haler) -> Result<Haler, InvoiceError> {
|
||||
if !(1..=MAX_QUANTITY).contains(&quantity) {
|
||||
return Err(InvoiceError::Quantity);
|
||||
}
|
||||
if unit_price.0 <= 0 || unit_price > MAX_AMOUNT {
|
||||
return Err(InvoiceError::Price);
|
||||
}
|
||||
mul_div_round(quantity, unit_price.0, 1000).map(Haler).ok_or(InvoiceError::Total)
|
||||
}
|
||||
|
||||
/// The totals of `lines`, for a VAT payer or not. Checks every line.
|
||||
pub fn totals(lines: &[InvoiceLine], vat_payer: bool) -> Result<Totals, InvoiceError> {
|
||||
if lines.is_empty() || lines.len() > MAX_LINES {
|
||||
return Err(InvoiceError::Lines);
|
||||
}
|
||||
let mut amounts = Vec::with_capacity(lines.len());
|
||||
let mut bases: BTreeMap<u8, i64> = BTreeMap::new();
|
||||
let mut net: i64 = 0;
|
||||
for l in lines {
|
||||
if !text_ok(&l.text, 1, 200) || !text_ok(&l.unit, 0, 10) {
|
||||
return Err(InvoiceError::LineText);
|
||||
}
|
||||
match (vat_payer, l.vat) {
|
||||
(true, Some(r)) if VAT_RATES.contains(&r) => {}
|
||||
(true, Some(_)) => return Err(InvoiceError::Rate),
|
||||
(false, None) => {}
|
||||
_ => return Err(InvoiceError::RateUse),
|
||||
}
|
||||
let a = line_amount(l.quantity, l.unit_price)?;
|
||||
amounts.push(a);
|
||||
net = net.checked_add(a.0).ok_or(InvoiceError::Total)?;
|
||||
if let Some(r) = l.vat {
|
||||
let b = bases.entry(r).or_default();
|
||||
*b = b.checked_add(a.0).ok_or(InvoiceError::Total)?;
|
||||
}
|
||||
}
|
||||
let mut rates = Vec::new();
|
||||
let mut vat: i64 = 0;
|
||||
for (r, base) in bases.into_iter().rev() {
|
||||
let v = mul_div_round(base, i64::from(r), 100).ok_or(InvoiceError::Total)?;
|
||||
vat = vat.checked_add(v).ok_or(InvoiceError::Total)?;
|
||||
rates.push((r, Haler(base), Haler(v)));
|
||||
}
|
||||
let total = net.checked_add(vat).ok_or(InvoiceError::Total)?;
|
||||
if total <= 0 || Haler(total) > MAX_AMOUNT {
|
||||
return Err(InvoiceError::Total);
|
||||
}
|
||||
Ok(Totals { lines: amounts, rates, net: Haler(net), vat: Haler(vat), total: Haler(total) })
|
||||
}
|
||||
|
||||
/// The number of the `seq`-th invoice of `year`: `20260001`.
|
||||
pub fn invoice_number(year: i32, seq: u32) -> Result<String, InvoiceError> {
|
||||
if !(2000..=9999).contains(&year) || !(1..=9999).contains(&seq) {
|
||||
return Err(InvoiceError::Number);
|
||||
}
|
||||
Ok(format!("{year}{seq:04}"))
|
||||
}
|
||||
|
||||
impl Invoice {
|
||||
/// Everything about the invoice that does not depend on the ledger; the totals when it is sound.
|
||||
pub fn check(&self, supplier: &Supplier) -> Result<Totals, InvoiceError> {
|
||||
let (year, _, _) = self.issued.ymd();
|
||||
let n = &self.number;
|
||||
if n.len() != 8 || !n.bytes().all(|b| b.is_ascii_digit()) || n[..4] != year.to_string() || &n[4..] == "0000" {
|
||||
return Err(InvoiceError::Number);
|
||||
}
|
||||
if self.due < self.issued {
|
||||
return Err(InvoiceError::Due);
|
||||
}
|
||||
if supplier.vat_payer != self.taxable.is_some() {
|
||||
return Err(InvoiceError::Taxable);
|
||||
}
|
||||
self.customer.check()?;
|
||||
totals(&self.lines, supplier.vat_payer)
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable symbol as banks write it, compared without leading zeros (`0020260001` is `20260001`).
|
||||
pub fn same_vs(a: &str, b: &str) -> bool {
|
||||
let t = |s: &str| s.trim().trim_start_matches('0').to_string();
|
||||
!t(a).is_empty() && t(a) == t(b)
|
||||
}
|
||||
|
||||
/// The events that record invoices paid by statement lines. A line pays an unpaid invoice when its amount is the
|
||||
/// invoice's total and its variable symbol is the invoice's number; the earliest such line wins, and a line pays
|
||||
/// one invoice only. The line becomes income, in the invoice's budget. Nothing is guessed: a line of another
|
||||
/// amount, or without the symbol, stays for the person to look at.
|
||||
pub fn plan_invoice_payments(state: &State, ids: &mut dyn FnMut() -> String, at: Timestamp) -> Vec<Event> {
|
||||
let mut open: Vec<&InvoiceRecord> = state.invoices.values().filter(|r| r.paid.is_none() && !r.cancelled).collect();
|
||||
open.sort_by_key(|r| r.seq);
|
||||
let lines: Vec<EffectivePayment> = state.effective_payments().into_iter().filter(|p| p.line.is_some() && p.amount.0 > 0).collect();
|
||||
let mut taken: BTreeSet<String> = state.invoice_payments.keys().cloned().collect();
|
||||
let mut out = Vec::new();
|
||||
for r in open {
|
||||
let found = lines.iter().find(|p| {
|
||||
let line = p.line.as_deref().unwrap_or_default();
|
||||
p.amount == r.totals.total
|
||||
&& p.date >= r.invoice.issued
|
||||
&& p.variable_symbol.as_deref().is_some_and(|vs| same_vs(vs, &r.invoice.number))
|
||||
&& !taken.contains(line)
|
||||
&& !taken.contains(&p.id)
|
||||
});
|
||||
let Some(p) = found else { continue };
|
||||
let line = p.line.clone().unwrap_or_default();
|
||||
taken.insert(line.clone());
|
||||
taken.insert(p.id.clone());
|
||||
out.push(Event::new(ids(), at, EventBody::InvoicePaid { invoice: r.invoice.id.clone(), payment: Some(line.clone()), on: p.date }));
|
||||
if p.category_source != CategorySource::Explicit {
|
||||
out.push(Event::new(ids(), at, EventBody::PaymentCategorised { payment: line.clone(), category: "income".into() }));
|
||||
}
|
||||
if let Some(b) = &r.invoice.budget {
|
||||
out.push(Event::new(ids(), at, EventBody::PaymentAssigned { payment: line, budget: b.clone() }));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rounding_is_half_away_from_zero() {
|
||||
assert_eq!(mul_div_round(1, 5, 10), Some(1));
|
||||
assert_eq!(mul_div_round(1, 4, 10), Some(0));
|
||||
assert_eq!(mul_div_round(-1, 5, 10), Some(-1));
|
||||
assert_eq!(mul_div_round(i64::MAX, i64::MAX, 1), None);
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,15 @@
|
||||
pub mod categories;
|
||||
pub mod date;
|
||||
pub mod event;
|
||||
pub mod goal;
|
||||
pub mod import;
|
||||
pub mod invoice;
|
||||
pub mod matching;
|
||||
pub mod merchant;
|
||||
pub mod money;
|
||||
pub mod pay;
|
||||
pub mod project;
|
||||
pub mod receipt;
|
||||
pub mod share;
|
||||
pub mod split;
|
||||
pub mod state;
|
||||
@@ -17,4 +21,5 @@ pub mod state;
|
||||
pub use date::{Date, Timestamp};
|
||||
pub use event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, Settlement, SplitId};
|
||||
pub use money::Haler;
|
||||
pub use receipt::{KnownShop, ReceiptInfo};
|
||||
pub use state::{EffectivePayment, Glyph, Origin, ShareView, State};
|
||||
|
||||
@@ -6,7 +6,7 @@ pub fn merchant_key(raw: &str) -> String {
|
||||
let folded: String = raw.chars().flat_map(fold).collect::<String>().to_lowercase();
|
||||
// A processor's prefix before `*`: "paypal *spotify", "sumup *kavarna", "sq *bistro".
|
||||
let rest = match folded.split_once('*') {
|
||||
Some((head, tail)) if !tail.trim().is_empty() && head.trim().split_whitespace().count() <= 2 => tail,
|
||||
Some((head, tail)) if !tail.trim().is_empty() && head.split_whitespace().count() <= 2 => tail,
|
||||
_ => folded.as_str(),
|
||||
};
|
||||
let cleaned: String = rest.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' }).collect();
|
||||
|
||||
@@ -49,7 +49,7 @@ impl Haler {
|
||||
let whole = (abs / 100).to_string();
|
||||
let mut grouped = String::with_capacity(whole.len() + whole.len() / 3);
|
||||
for (i, c) in whole.chars().enumerate() {
|
||||
if i > 0 && (whole.len() - i) % 3 == 0 {
|
||||
if i > 0 && (whole.len() - i).is_multiple_of(3) {
|
||||
grouped.push(' ');
|
||||
}
|
||||
grouped.push(c);
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Projects: planning and tracking a piece of work with its own budget, tasks and (for a business) phases, time
|
||||
//! and income. A project is a second label on payments: a payment in a project still counts in its budget and in
|
||||
//! the month, so nothing is counted twice. Personal log only, like plans and goals.
|
||||
|
||||
use crate::date::Date;
|
||||
use crate::event::{BudgetId, PaymentId};
|
||||
use crate::goal::Colour;
|
||||
use crate::invoice::InvoiceId;
|
||||
use crate::money::Haler;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
pub type ProjectId = String;
|
||||
pub type TaskId = String;
|
||||
pub type LineId = String;
|
||||
pub type PhaseId = String;
|
||||
pub type EntryId = String;
|
||||
|
||||
/// At most this many projects not done at once.
|
||||
pub const MAX_OPEN_PROJECTS: usize = 50;
|
||||
/// Per project: budget lines, phases, and tasks not done.
|
||||
pub const MAX_LINES: usize = 100;
|
||||
pub const MAX_PHASES: usize = 50;
|
||||
pub const MAX_OPEN_TASKS: usize = 200;
|
||||
/// A planned amount, an estimate: 0 to 100 000 000 Kč.
|
||||
pub const MAX_AMOUNT: Haler = Haler(10_000_000_000);
|
||||
/// An hourly rate: 0 to 100 000 Kč.
|
||||
pub const MAX_RATE: Haler = Haler(10_000_000);
|
||||
/// Time logged on one day across all projects: at most 24 hours.
|
||||
pub const MAX_MINUTES_A_DAY: u32 = 24 * 60;
|
||||
|
||||
/// Simple (a renovation, a trip): a budget and a checklist. Business (a side business, client work): also
|
||||
/// income, phases, a timeline and time.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Kind {
|
||||
Simple,
|
||||
Business,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Status {
|
||||
Planning,
|
||||
Active,
|
||||
OnHold,
|
||||
Done,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TaskStatus {
|
||||
Todo,
|
||||
Doing,
|
||||
Done,
|
||||
}
|
||||
|
||||
/// A task's fields as `task.created` and `task.changed` carry them.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TaskFields {
|
||||
pub title: String,
|
||||
pub phase: Option<PhaseId>,
|
||||
pub due: Option<Date>,
|
||||
pub estimate: Option<Haler>,
|
||||
pub line: Option<LineId>,
|
||||
pub assignee: Option<String>,
|
||||
pub milestone: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Line {
|
||||
pub id: LineId,
|
||||
pub name: String,
|
||||
pub planned: Haler,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Phase {
|
||||
pub id: PhaseId,
|
||||
pub name: String,
|
||||
pub starts: Date,
|
||||
pub ends: Date,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProjectRecord {
|
||||
pub id: ProjectId,
|
||||
pub name: String,
|
||||
pub kind: Kind,
|
||||
pub template: Option<String>,
|
||||
pub starts: Option<Date>,
|
||||
pub ends: Option<Date>,
|
||||
pub colour: Colour,
|
||||
/// The hourly rate time is logged at unless an entry says otherwise (business).
|
||||
pub rate: Option<Haler>,
|
||||
pub status: Status,
|
||||
/// When the status was last set (the day a project was done).
|
||||
pub status_on: Option<Date>,
|
||||
/// In the order made.
|
||||
pub lines: Vec<Line>,
|
||||
pub phases: Vec<Phase>,
|
||||
/// Invoices issued for this project.
|
||||
pub invoices: BTreeSet<InvoiceId>,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
impl ProjectRecord {
|
||||
pub fn is_open(&self) -> bool {
|
||||
self.status != Status::Done
|
||||
}
|
||||
|
||||
pub fn line(&self, id: &str) -> Option<&Line> {
|
||||
self.lines.iter().find(|l| l.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TaskRecord {
|
||||
pub id: TaskId,
|
||||
pub project: ProjectId,
|
||||
pub fields: TaskFields,
|
||||
pub status: TaskStatus,
|
||||
/// The day it was done.
|
||||
pub done_on: Option<Date>,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TimeEntry {
|
||||
pub id: EntryId,
|
||||
pub project: ProjectId,
|
||||
pub task: Option<TaskId>,
|
||||
pub minutes: u32,
|
||||
pub on: Date,
|
||||
/// Per hour.
|
||||
pub rate: Haler,
|
||||
pub note: String,
|
||||
/// The invoice that billed it.
|
||||
pub invoice: Option<InvoiceId>,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
impl TimeEntry {
|
||||
/// What the entry is worth: minutes × the hourly rate, rounded to the haléř (half up).
|
||||
pub fn amount(&self) -> Haler {
|
||||
let v = (i128::from(self.minutes) * i128::from(self.rate.0) + 30) / 60;
|
||||
Haler(i64::try_from(v).unwrap_or(i64::MAX))
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything about projects in a ledger.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Projects {
|
||||
pub projects: BTreeMap<ProjectId, ProjectRecord>,
|
||||
pub tasks: BTreeMap<TaskId, TaskRecord>,
|
||||
pub time: BTreeMap<EntryId, TimeEntry>,
|
||||
/// A payment put into a project (and a line) by hand.
|
||||
pub payments: BTreeMap<PaymentId, (ProjectId, Option<LineId>)>,
|
||||
/// "Always this merchant → this project", by merchant key.
|
||||
pub rules: BTreeMap<String, ProjectId>,
|
||||
/// A project shared with a shared budget's members → that budget (`project.shared`).
|
||||
#[serde(default)]
|
||||
pub shared: BTreeMap<ProjectId, BudgetId>,
|
||||
}
|
||||
|
||||
/// The Monday of `d`'s week.
|
||||
pub fn week_of(d: Date) -> Date {
|
||||
// 1970-01-01 was a Thursday.
|
||||
d.add_days(-(d.days() + 3).rem_euclid(7))
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! A receipt attached to a payment (`payment.receipt_attached`, docs/07_receipts.md): the shop's name as you
|
||||
//! confirmed it, and its IČO and DIČ. The payment keeps its own merchant and merchant key (so the rules that bring
|
||||
//! a category stay as they are); the receipt only adds what the shop is. Known shops and the payment a receipt
|
||||
//! fills in are read from the state here, so the PC and the node decide alike.
|
||||
|
||||
use crate::date::Date;
|
||||
use crate::event::{Category, PaymentId};
|
||||
use crate::invoice::{dic_ok, ico_ok};
|
||||
use crate::money::Haler;
|
||||
use crate::state::State;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The shop's name is 1-100 characters.
|
||||
pub const MAX_SHOP: usize = 100;
|
||||
/// A receipt fills in a payment of the same amount at most this many days before or after its date (a card
|
||||
/// payment can be booked a few days later).
|
||||
pub const MATCH_DAYS: i32 = 3;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ReceiptInfo {
|
||||
pub shop: String,
|
||||
pub ico: Option<String>,
|
||||
pub dic: Option<String>,
|
||||
}
|
||||
|
||||
impl ReceiptInfo {
|
||||
/// What the ledger accepts: a name without control characters, a valid IČO (with its check digit) and DIČ.
|
||||
pub fn check(&self) -> Result<(), &'static str> {
|
||||
let shop = self.shop.trim();
|
||||
if shop.is_empty() || shop.chars().count() > MAX_SHOP || shop.chars().any(char::is_control) || shop != self.shop {
|
||||
return Err("a shop's name must be 1-100 characters, trimmed, without control characters");
|
||||
}
|
||||
if self.ico.as_deref().is_some_and(|i| !ico_ok(i)) {
|
||||
return Err("not a valid IČO (8 digits with a check digit)");
|
||||
}
|
||||
if self.dic.as_deref().is_some_and(|d| !dic_ok(d)) {
|
||||
return Err("not a valid DIČ (CZ and 8-10 digits)");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// What a shop's IČO brings from your earlier receipts: the name you confirmed last, and the category of that
|
||||
/// payment.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct KnownShop {
|
||||
pub name: String,
|
||||
pub category: Option<Category>,
|
||||
pub payment: PaymentId,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The shop of your latest receipt with this IČO, if any.
|
||||
pub fn known_shop(&self, ico: &str) -> Option<KnownShop> {
|
||||
self.effective_payments()
|
||||
.into_iter()
|
||||
.filter_map(|p| {
|
||||
let r = p.receipt.as_ref()?;
|
||||
(r.ico.as_deref() == Some(ico)).then(|| (p.receipt_seq, KnownShop { name: r.shop.clone(), category: p.category.clone(), payment: p.id.clone() }))
|
||||
})
|
||||
.max_by_key(|(seq, _)| *seq)
|
||||
.map(|(_, k)| k)
|
||||
}
|
||||
|
||||
/// The one payment a receipt of `total` (positive) on `date` fills in: an outflow of exactly that amount,
|
||||
/// within [`MATCH_DAYS`], without a receipt yet. None when there is none, or more than one (then the receipt
|
||||
/// is a payment of its own, and nothing is guessed).
|
||||
pub fn receipt_match(&self, total: Haler, date: Date) -> Option<PaymentId> {
|
||||
let amount = total.checked_neg().ok()?;
|
||||
let mut found = self
|
||||
.effective_payments()
|
||||
.into_iter()
|
||||
.filter(|p| p.amount == amount && p.receipt.is_none() && p.date.days_until(date).abs() <= MATCH_DAYS)
|
||||
.map(|p| p.id);
|
||||
let first = found.next()?;
|
||||
found.next().is_none().then_some(first)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,14 @@
|
||||
use crate::categories;
|
||||
use crate::date::Date;
|
||||
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
|
||||
use crate::goal::{self, ChallengeGoal, ChallengeId, ChallengeRecord, GoalId, GoalRecord, Saving, Way, WayKind};
|
||||
use crate::import::StatementLine;
|
||||
use crate::project::{self, Line, Phase, ProjectRecord, Projects, TaskRecord, TaskStatus, TimeEntry};
|
||||
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
|
||||
use crate::merchant::merchant_key;
|
||||
use crate::money::Haler;
|
||||
use crate::pay::{spayd, Iban};
|
||||
use crate::receipt::ReceiptInfo;
|
||||
use crate::split::Share;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -64,6 +68,9 @@ pub struct PaymentRecord {
|
||||
pub category: Option<Stamped<Category>>,
|
||||
pub budget: Option<Stamped<BudgetId>>,
|
||||
pub trial_ends: Option<Stamped<Date>>,
|
||||
/// The receipt attached to it (docs/07_receipts.md).
|
||||
#[serde(default)]
|
||||
pub receipt: Option<Stamped<ReceiptInfo>>,
|
||||
/// The other half of a confirmed pair.
|
||||
pub partner: Option<PaymentId>,
|
||||
}
|
||||
@@ -142,6 +149,46 @@ pub struct ShareView {
|
||||
pub spayd: Option<String>,
|
||||
}
|
||||
|
||||
/// An issued invoice, its totals, and what became of it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct InvoiceRecord {
|
||||
pub invoice: Invoice,
|
||||
/// The supplier as it was when the invoice was issued.
|
||||
pub supplier: Supplier,
|
||||
pub totals: Totals,
|
||||
pub paid: Option<Paid>,
|
||||
pub cancelled: bool,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Paid {
|
||||
/// The statement line that paid it; `None` when marked paid by hand.
|
||||
pub payment: Option<PaymentId>,
|
||||
pub on: Date,
|
||||
/// Set aside for tax: the VAT, and the reserve share of the rest.
|
||||
pub reserve: Haler,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PlanRecord {
|
||||
/// The 1st of the month the plan counts from.
|
||||
pub from: Date,
|
||||
/// Positive; zero removes the plan.
|
||||
pub amount: Haler,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Withdrawal {
|
||||
pub id: String,
|
||||
pub amount: Haler,
|
||||
pub on: Date,
|
||||
pub note: String,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Rejection {
|
||||
pub event: EventId,
|
||||
@@ -171,6 +218,29 @@ pub struct State {
|
||||
/// SHA-256 (hex) of a share link's token → the link.
|
||||
pub share_links: BTreeMap<String, ShareLink>,
|
||||
pub account: Option<Account>,
|
||||
/// The name shown to the members of my shared budgets (`profile.named`).
|
||||
pub profile_name: Option<String>,
|
||||
/// The shared budgets I share my subscription names with (`household.sharing_set`).
|
||||
pub household_sharing: BTreeSet<BudgetId>,
|
||||
pub supplier: Option<Supplier>,
|
||||
pub invoices: BTreeMap<InvoiceId, InvoiceRecord>,
|
||||
/// Invoice number → invoice.
|
||||
pub invoice_numbers: BTreeMap<String, InvoiceId>,
|
||||
/// A statement line → the invoice it paid.
|
||||
pub invoice_payments: BTreeMap<PaymentId, InvoiceId>,
|
||||
pub withdrawals: Vec<Withdrawal>,
|
||||
/// Category → its monthly plans, in log order (`category.planned`).
|
||||
pub category_plans: BTreeMap<Category, Vec<PlanRecord>>,
|
||||
/// Your own categories: id → the name shown (`category.created`).
|
||||
pub custom_categories: BTreeMap<Category, String>,
|
||||
/// Savings goals by id (`goal.*`).
|
||||
pub goals: BTreeMap<GoalId, GoalRecord>,
|
||||
/// Every `goal.saved` id, so none is counted twice.
|
||||
pub saving_ids: BTreeSet<String>,
|
||||
/// Challenges by id (`challenge.*`).
|
||||
pub challenges: BTreeMap<ChallengeId, ChallengeRecord>,
|
||||
/// Projects, their tasks, time, and the payments put into them (`project.*`, `task.*`, `time.*`).
|
||||
pub projects: Projects,
|
||||
pub rejected: Vec<Rejection>,
|
||||
}
|
||||
|
||||
@@ -206,8 +276,15 @@ pub struct EffectivePayment {
|
||||
pub category_source: CategorySource,
|
||||
pub budget: Option<BudgetId>,
|
||||
pub trial_ends: Option<Date>,
|
||||
/// The receipt attached to it, and when (its event's place in the log; 0 without one).
|
||||
pub receipt: Option<ReceiptInfo>,
|
||||
pub receipt_seq: u64,
|
||||
}
|
||||
|
||||
/// A person's name, or one shared subscription name.
|
||||
const MAX_PERSON: usize = 40;
|
||||
const MAX_SHARED_NAMES: usize = 100;
|
||||
|
||||
fn text_ok(s: &str) -> bool {
|
||||
s.chars().count() <= MAX_TEXT && !s.chars().any(|c| c.is_control())
|
||||
}
|
||||
@@ -220,6 +297,53 @@ fn name_ok(s: &str, max: usize) -> bool {
|
||||
!s.trim().is_empty() && s.chars().count() <= max && text_ok(s)
|
||||
}
|
||||
|
||||
/// A project's name, dates and rate, for `project.created` and `project.changed`.
|
||||
fn project_fields(name: &str, starts: Option<Date>, ends: Option<Date>, rate: Option<Haler>) -> Result<(), &'static str> {
|
||||
if !name_ok(name, 60) || name.trim() != name {
|
||||
return Err("a project name must be 1-60 characters");
|
||||
}
|
||||
if let (Some(s), Some(e)) = (starts, ends) {
|
||||
if e < s {
|
||||
return Err("a project ends before it starts");
|
||||
}
|
||||
}
|
||||
if rate.is_some_and(|r| r.0 < 0 || r > project::MAX_RATE) {
|
||||
return Err("an hourly rate is 0-100 000 CZK");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A task's fields, checked against its project.
|
||||
fn task_fields(p: &ProjectRecord, f: &project::TaskFields) -> Result<(), &'static str> {
|
||||
if !name_ok(&f.title, 120) || f.title.trim() != f.title {
|
||||
return Err("a task title must be 1-120 characters");
|
||||
}
|
||||
if f.phase.as_ref().is_some_and(|ph| !p.phases.iter().any(|x| &x.id == ph)) {
|
||||
return Err("no such phase in the project");
|
||||
}
|
||||
if f.line.as_ref().is_some_and(|l| p.line(l).is_none()) {
|
||||
return Err("no such budget line in the project");
|
||||
}
|
||||
if f.estimate.is_some_and(|e| e.0 < 0 || e > project::MAX_AMOUNT) {
|
||||
return Err("an estimate is 0-100 000 000 CZK");
|
||||
}
|
||||
if f.assignee.as_ref().is_some_and(|a| !name_ok(a, 40) || a.trim() != a) {
|
||||
return Err("an assignee name must be 1-40 characters");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A goal's name and target, for `goal.created` and `goal.changed`.
|
||||
fn goal_fields(name: &str, target: Haler) -> Result<(), &'static str> {
|
||||
if !name_ok(name, 60) || name.trim() != name {
|
||||
return Err("a goal name must be 1-60 characters");
|
||||
}
|
||||
if target < goal::MIN_AMOUNT || target > goal::MAX_AMOUNT {
|
||||
return Err("a goal target is 1-100 000 000 CZK");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn id_ok(s: &str) -> bool {
|
||||
!s.is_empty() && s.len() <= 100 && text_ok(s)
|
||||
}
|
||||
@@ -305,6 +429,7 @@ impl State {
|
||||
category: None,
|
||||
budget: None,
|
||||
trial_ends: None,
|
||||
receipt: None,
|
||||
partner: None,
|
||||
},
|
||||
);
|
||||
@@ -335,6 +460,7 @@ impl State {
|
||||
category: None,
|
||||
budget: None,
|
||||
trial_ends: None,
|
||||
receipt: None,
|
||||
partner: None,
|
||||
},
|
||||
);
|
||||
@@ -363,6 +489,7 @@ impl State {
|
||||
category: category.clone().map(|value| Stamped { seq, value }),
|
||||
budget: None,
|
||||
trial_ends: None,
|
||||
receipt: None,
|
||||
partner: None,
|
||||
},
|
||||
);
|
||||
@@ -397,6 +524,10 @@ impl State {
|
||||
EventBody::PaymentTrialMarked { payment, ends } => {
|
||||
self.payment_mut(payment)?.trial_ends = Some(Stamped { seq, value: *ends });
|
||||
}
|
||||
EventBody::ReceiptAttached { payment, receipt } => {
|
||||
receipt.check()?;
|
||||
self.payment_mut(payment)?.receipt = Some(Stamped { seq, value: receipt.clone() });
|
||||
}
|
||||
EventBody::BudgetCreated { budget, name, limit } | EventBody::BudgetShared { budget, name, limit } => {
|
||||
if budget.is_empty() || self.budgets.contains_key(budget) {
|
||||
return Err("a budget with this id exists");
|
||||
@@ -478,6 +609,7 @@ impl State {
|
||||
category: category.clone().map(|value| Stamped { seq, value }),
|
||||
budget: Some(Stamped { seq, value: budget.clone() }),
|
||||
trial_ends: None,
|
||||
receipt: None,
|
||||
partner: None,
|
||||
},
|
||||
);
|
||||
@@ -586,10 +718,557 @@ impl State {
|
||||
}
|
||||
self.account = Some(Account { iban: iban.as_str().into(), name: name.trim().into() });
|
||||
}
|
||||
EventBody::ProfileNamed { name } => {
|
||||
if !name_ok(name, MAX_PERSON) {
|
||||
return Err("a name must be 1-40 characters");
|
||||
}
|
||||
self.profile_name = Some(name.trim().into());
|
||||
}
|
||||
EventBody::HouseholdSharingSet { budget, on } => {
|
||||
if !self.budgets.contains_key(budget) || self.default_budget.as_ref() == Some(budget) {
|
||||
return Err("subscription names are shared only with a shared budget");
|
||||
}
|
||||
if *on {
|
||||
self.household_sharing.insert(budget.clone());
|
||||
} else {
|
||||
self.household_sharing.remove(budget);
|
||||
}
|
||||
}
|
||||
EventBody::MemberNamed { budget, name } => {
|
||||
if !self.budgets.contains_key(budget) {
|
||||
return Err("no such budget");
|
||||
}
|
||||
if !name_ok(name, MAX_PERSON) {
|
||||
return Err("a name must be 1-40 characters");
|
||||
}
|
||||
}
|
||||
EventBody::SupplierSet { supplier } => {
|
||||
supplier.check().map_err(|_| "not a valid supplier")?;
|
||||
self.supplier = Some(supplier.clone());
|
||||
}
|
||||
EventBody::InvoiceIssued { invoice } => {
|
||||
let supplier = self.supplier.clone().ok_or("set the supplier before issuing an invoice")?;
|
||||
if !id_ok(&invoice.id) || self.invoices.contains_key(&invoice.id) {
|
||||
return Err("an invoice with this id exists");
|
||||
}
|
||||
if self.invoice_numbers.contains_key(&invoice.number) {
|
||||
return Err("an invoice with this number exists");
|
||||
}
|
||||
if invoice.budget.as_ref().is_some_and(|b| !self.budgets.contains_key(b)) {
|
||||
return Err("no such budget");
|
||||
}
|
||||
let totals = invoice.check(&supplier).map_err(|_| "not a valid invoice")?;
|
||||
self.invoice_numbers.insert(invoice.number.clone(), invoice.id.clone());
|
||||
self.invoices.insert(invoice.id.clone(), InvoiceRecord { invoice: invoice.clone(), supplier, totals, paid: None, cancelled: false, seq });
|
||||
}
|
||||
EventBody::InvoicePaid { invoice, payment, on } => {
|
||||
let rec = self.invoices.get(invoice).ok_or("no such invoice")?;
|
||||
if rec.cancelled || rec.paid.is_some() {
|
||||
return Err("the invoice is cancelled or paid already");
|
||||
}
|
||||
if *on < rec.invoice.issued {
|
||||
return Err("paid before it was issued");
|
||||
}
|
||||
if let Some(p) = payment {
|
||||
if self.invoice_payments.contains_key(p) {
|
||||
return Err("this payment paid another invoice");
|
||||
}
|
||||
let e = self.effective_payment(p).ok_or("no such payment")?;
|
||||
if e.line.is_none() || e.amount != rec.totals.total {
|
||||
return Err("the payment is not a statement line of the invoice's amount");
|
||||
}
|
||||
}
|
||||
let reserve = rec.supplier.reserve_for(&rec.totals);
|
||||
if let Some(p) = payment {
|
||||
self.invoice_payments.insert(p.clone(), invoice.clone());
|
||||
}
|
||||
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
|
||||
rec.paid = Some(Paid { payment: payment.clone(), on: *on, reserve, seq });
|
||||
}
|
||||
EventBody::InvoiceCancelled { invoice } => {
|
||||
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
|
||||
if rec.paid.is_some() || rec.cancelled {
|
||||
return Err("only an unpaid invoice can be cancelled");
|
||||
}
|
||||
rec.cancelled = true;
|
||||
}
|
||||
EventBody::ReserveWithdrawn { withdrawal, amount, on, note } => {
|
||||
if !id_ok(withdrawal) || self.withdrawals.iter().any(|w| &w.id == withdrawal) {
|
||||
return Err("a withdrawal with this id exists");
|
||||
}
|
||||
if amount.0 <= 0 || *amount > self.reserve_balance() {
|
||||
return Err("more than the reserve holds");
|
||||
}
|
||||
if note.chars().count() > 200 || !text_ok(note) {
|
||||
return Err("a note is at most 200 characters");
|
||||
}
|
||||
self.withdrawals.push(Withdrawal { id: withdrawal.clone(), amount: *amount, on: *on, note: note.clone(), seq });
|
||||
}
|
||||
EventBody::CategoryPlanned { category, amount, from } => {
|
||||
if !self.category_known(category) || categories::NOT_PLANNABLE.contains(&category.as_str()) {
|
||||
return Err("not a category that can have a plan");
|
||||
}
|
||||
if amount.0 < 0 || *amount > categories::MAX_PLAN {
|
||||
return Err("a plan is 0-100 000 000 CZK");
|
||||
}
|
||||
if from.ymd().2 != 1 {
|
||||
return Err("a plan starts on the 1st of a month");
|
||||
}
|
||||
self.category_plans.entry(category.clone()).or_default().push(PlanRecord { from: *from, amount: *amount, seq });
|
||||
}
|
||||
EventBody::CategoryCreated { category, label } => {
|
||||
if !categories::is_valid(category) {
|
||||
return Err("not a category id");
|
||||
}
|
||||
if self.category_known(category) {
|
||||
return Err("this category exists");
|
||||
}
|
||||
if !name_ok(label, MAX_PERSON) || label.trim() != label {
|
||||
return Err("a category's name must be 1-40 characters");
|
||||
}
|
||||
self.custom_categories.insert(category.clone(), label.clone());
|
||||
}
|
||||
EventBody::SubscriptionsShared { budget, names } => {
|
||||
if !self.budgets.contains_key(budget) {
|
||||
return Err("no such budget");
|
||||
}
|
||||
if names.len() > MAX_SHARED_NAMES {
|
||||
return Err("at most 100 subscription names");
|
||||
}
|
||||
if names.iter().any(|n| !name_ok(n, MAX_PERSON) || n.trim() != n) {
|
||||
return Err("a subscription name must be 1-40 characters");
|
||||
}
|
||||
if names.iter().collect::<BTreeSet<_>>().len() != names.len() {
|
||||
return Err("a subscription name appears twice");
|
||||
}
|
||||
}
|
||||
EventBody::GoalCreated { goal, name, target, by, colour } => {
|
||||
if !id_ok(goal) || self.goals.contains_key(goal) {
|
||||
return Err("a goal with this id exists");
|
||||
}
|
||||
goal_fields(name, *target)?;
|
||||
if self.goals.values().filter(|g| g.is_open()).count() >= goal::MAX_OPEN_GOALS {
|
||||
return Err("at most 20 goals are open at once");
|
||||
}
|
||||
self.goals.insert(
|
||||
goal.clone(),
|
||||
GoalRecord { id: goal.clone(), name: name.clone(), target: *target, by: *by, colour: *colour, ways: Vec::new(), savings: Vec::new(), closed: None, seq },
|
||||
);
|
||||
}
|
||||
EventBody::GoalChanged { goal, name, target, by, colour } => {
|
||||
goal_fields(name, *target)?;
|
||||
let g = self.goals.get_mut(goal).ok_or("no such goal")?;
|
||||
if !g.is_open() {
|
||||
return Err("the goal is closed");
|
||||
}
|
||||
(g.name, g.target, g.by, g.colour) = (name.clone(), *target, *by, *colour);
|
||||
}
|
||||
EventBody::GoalWaysSet { goal, ways } => {
|
||||
let g = self.goals.get(goal).ok_or("no such goal")?;
|
||||
if !g.is_open() {
|
||||
return Err("the goal is closed");
|
||||
}
|
||||
if ways.iter().map(Way::kind).collect::<BTreeSet<_>>().len() != ways.len() {
|
||||
return Err("a goal has at most one way of each kind");
|
||||
}
|
||||
for w in ways {
|
||||
match w {
|
||||
Way::Fixed { amount } if *amount < goal::MIN_AMOUNT || *amount > goal::MAX_AMOUNT => return Err("a fixed amount is 1-100 000 000 CZK"),
|
||||
Way::RoundUp { to } if !goal::ROUND_UP_TO.contains(to) => return Err("round-ups go to 10, 50 or 100 CZK"),
|
||||
Way::Leftover { permille } | Way::Income { permille } if *permille == 0 || *permille > 1000 => return Err("a share is 1-1000 thousandths"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for kind in [WayKind::Leftover, WayKind::Income] {
|
||||
let others: u32 = self.goals.values().filter(|o| o.is_open() && &o.id != goal).flat_map(|o| o.ways.iter()).map(|w| w.share_of(kind)).sum();
|
||||
let mine: u32 = ways.iter().map(|w| w.share_of(kind)).sum();
|
||||
if others + mine > 1000 {
|
||||
return Err("the shares of one way across the goals add up to more than all of it");
|
||||
}
|
||||
}
|
||||
self.goals.get_mut(goal).expect("checked").ways = ways.clone();
|
||||
}
|
||||
EventBody::GoalSaved { goal, saving, amount, on, way } => {
|
||||
if !id_ok(saving) || self.saving_ids.contains(saving) {
|
||||
return Err("a saving with this id exists");
|
||||
}
|
||||
let g = self.goals.get(goal).ok_or("no such goal")?;
|
||||
if !g.is_open() {
|
||||
return Err("the goal is closed");
|
||||
}
|
||||
if amount.0 == 0 || amount.0.unsigned_abs() > goal::MAX_AMOUNT.0 as u64 {
|
||||
return Err("an amount saved is 0,01-100 000 000 CZK either way");
|
||||
}
|
||||
if g.saved().checked_add(*amount).map_err(|_| "the goal would not fit")?.0 < 0 {
|
||||
return Err("more than the goal holds");
|
||||
}
|
||||
if let Some(k) = way {
|
||||
if !g.ways.iter().any(|w| w.kind() == *k) {
|
||||
return Err("the goal is not saved for that way");
|
||||
}
|
||||
}
|
||||
self.saving_ids.insert(saving.clone());
|
||||
self.goals.get_mut(goal).expect("checked").savings.push(Saving { id: saving.clone(), amount: *amount, on: *on, way: *way, seq });
|
||||
}
|
||||
EventBody::GoalClosed { goal, on } => {
|
||||
let g = self.goals.get_mut(goal).ok_or("no such goal")?;
|
||||
if !g.is_open() {
|
||||
return Err("the goal is closed");
|
||||
}
|
||||
g.closed = Some(*on);
|
||||
}
|
||||
EventBody::ChallengeStarted { challenge, goal, starts, ends } => {
|
||||
if !id_ok(challenge) || self.challenges.contains_key(challenge) {
|
||||
return Err("a challenge with this id exists");
|
||||
}
|
||||
let days = starts.days_until(*ends);
|
||||
if !(0..goal::MAX_CHALLENGE_DAYS as i64).contains(&(days as i64)) {
|
||||
return Err("a challenge lasts 1-92 days");
|
||||
}
|
||||
match goal {
|
||||
ChallengeGoal::SpendUnder { category, amount } => {
|
||||
if !self.category_known(category) || categories::NOT_PLANNABLE.contains(&category.as_str()) {
|
||||
return Err("not a category you spend in");
|
||||
}
|
||||
if *amount < goal::MIN_AMOUNT || *amount > goal::MAX_AMOUNT {
|
||||
return Err("the amount of a challenge is 1-100 000 000 CZK");
|
||||
}
|
||||
}
|
||||
ChallengeGoal::NoSpend { category } => {
|
||||
if !self.category_known(category) || categories::NOT_PLANNABLE.contains(&category.as_str()) {
|
||||
return Err("not a category you spend in");
|
||||
}
|
||||
}
|
||||
ChallengeGoal::Cancel { subscription } => {
|
||||
if subscription.is_empty() || subscription.len() > 100 || !text_ok(subscription) {
|
||||
return Err("not a subscription key");
|
||||
}
|
||||
}
|
||||
ChallengeGoal::Save { goal: g, amount } => {
|
||||
if !self.goals.get(g).is_some_and(GoalRecord::is_open) {
|
||||
return Err("no such open goal");
|
||||
}
|
||||
if *amount < goal::MIN_AMOUNT || *amount > goal::MAX_AMOUNT {
|
||||
return Err("the amount of a challenge is 1-100 000 000 CZK");
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.challenges.values().filter(|c| c.abandoned.is_none() && c.ends >= *starts).count() >= goal::MAX_OPEN_CHALLENGES {
|
||||
return Err("at most 20 challenges run at once");
|
||||
}
|
||||
self.challenges.insert(challenge.clone(), ChallengeRecord { id: challenge.clone(), goal: goal.clone(), starts: *starts, ends: *ends, abandoned: None, seq });
|
||||
}
|
||||
EventBody::ChallengeAbandoned { challenge, on } => {
|
||||
let c = self.challenges.get_mut(challenge).ok_or("no such challenge")?;
|
||||
if c.abandoned.is_some() {
|
||||
return Err("already given up");
|
||||
}
|
||||
c.abandoned = Some(*on);
|
||||
}
|
||||
EventBody::ProjectCreated { project, name, kind, template, starts, ends, colour, rate } => {
|
||||
if !id_ok(project) || self.projects.projects.contains_key(project) {
|
||||
return Err("a project with this id exists");
|
||||
}
|
||||
project_fields(name, *starts, *ends, *rate)?;
|
||||
if template.as_ref().is_some_and(|t| !id_ok(t)) {
|
||||
return Err("not a template id");
|
||||
}
|
||||
if self.projects.projects.values().filter(|p| p.is_open()).count() >= project::MAX_OPEN_PROJECTS {
|
||||
return Err("at most 50 projects are open at once");
|
||||
}
|
||||
self.projects.projects.insert(
|
||||
project.clone(),
|
||||
ProjectRecord {
|
||||
id: project.clone(),
|
||||
name: name.clone(),
|
||||
kind: *kind,
|
||||
template: template.clone(),
|
||||
starts: *starts,
|
||||
ends: *ends,
|
||||
colour: *colour,
|
||||
rate: *rate,
|
||||
status: project::Status::Active,
|
||||
status_on: None,
|
||||
lines: Vec::new(),
|
||||
phases: Vec::new(),
|
||||
invoices: BTreeSet::new(),
|
||||
seq,
|
||||
},
|
||||
);
|
||||
}
|
||||
EventBody::ProjectChanged { project, name, kind, starts, ends, colour, rate } => {
|
||||
project_fields(name, *starts, *ends, *rate)?;
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
if *kind == project::Kind::Simple && (!p.phases.is_empty() || self.projects.time.values().any(|t| &t.project == project)) {
|
||||
return Err("a project with phases or time stays a business project");
|
||||
}
|
||||
(p.name, p.kind, p.starts, p.ends, p.colour, p.rate) = (name.clone(), *kind, *starts, *ends, *colour, *rate);
|
||||
}
|
||||
EventBody::ProjectStatusSet { project, status, on } => {
|
||||
let reopening = *status != project::Status::Done;
|
||||
let open = self.projects.projects.values().filter(|p| p.is_open()).count();
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
if reopening && !p.is_open() && open >= project::MAX_OPEN_PROJECTS {
|
||||
return Err("at most 50 projects are open at once");
|
||||
}
|
||||
p.status = *status;
|
||||
p.status_on = Some(*on);
|
||||
}
|
||||
EventBody::ProjectLineSet { project, line, name, planned } => {
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
if !id_ok(line) {
|
||||
return Err("not a line id");
|
||||
}
|
||||
if planned.0 < 0 || *planned > project::MAX_AMOUNT {
|
||||
return Err("a planned amount is 0-100 000 000 CZK");
|
||||
}
|
||||
if planned.0 == 0 {
|
||||
p.lines.retain(|l| &l.id != line);
|
||||
} else {
|
||||
if !name_ok(name, 60) || name.trim() != name {
|
||||
return Err("a budget line name must be 1-60 characters");
|
||||
}
|
||||
match p.lines.iter().position(|l| &l.id == line) {
|
||||
Some(i) => (p.lines[i].name, p.lines[i].planned) = (name.clone(), *planned),
|
||||
None if p.lines.len() >= project::MAX_LINES => return Err("at most 100 budget lines a project"),
|
||||
None => p.lines.push(Line { id: line.clone(), name: name.clone(), planned: *planned, seq }),
|
||||
}
|
||||
}
|
||||
}
|
||||
EventBody::ProjectPhaseSet { project, phase, name, starts, ends } => {
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
if p.kind != project::Kind::Business {
|
||||
return Err("only a business project has phases");
|
||||
}
|
||||
if !id_ok(phase) {
|
||||
return Err("not a phase id");
|
||||
}
|
||||
if !name_ok(name, 60) || name.trim() != name {
|
||||
return Err("a phase name must be 1-60 characters");
|
||||
}
|
||||
if ends < starts {
|
||||
return Err("a phase ends before it starts");
|
||||
}
|
||||
match p.phases.iter().position(|x| &x.id == phase) {
|
||||
Some(i) => (p.phases[i].name, p.phases[i].starts, p.phases[i].ends) = (name.clone(), *starts, *ends),
|
||||
None if p.phases.len() >= project::MAX_PHASES => return Err("at most 50 phases a project"),
|
||||
None => p.phases.push(Phase { id: phase.clone(), name: name.clone(), starts: *starts, ends: *ends }),
|
||||
}
|
||||
}
|
||||
EventBody::ProjectPhaseRemoved { project, phase } => {
|
||||
if self.projects.tasks.values().any(|t| &t.project == project && t.fields.phase.as_ref() == Some(phase)) {
|
||||
return Err("tasks are still in this phase");
|
||||
}
|
||||
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
|
||||
let before = p.phases.len();
|
||||
p.phases.retain(|x| &x.id != phase);
|
||||
if p.phases.len() == before {
|
||||
return Err("no such phase in the project");
|
||||
}
|
||||
}
|
||||
EventBody::PaymentProjected { payment, project, line } => {
|
||||
if self.effective_payment(payment).is_none() {
|
||||
return Err("no such payment");
|
||||
}
|
||||
let p = self.projects.projects.get(project).ok_or("no such project")?;
|
||||
if !p.is_open() {
|
||||
return Err("the project is done");
|
||||
}
|
||||
if line.as_ref().is_some_and(|l| p.line(l).is_none()) {
|
||||
return Err("no such budget line in the project");
|
||||
}
|
||||
self.projects.payments.insert(payment.clone(), (project.clone(), line.clone()));
|
||||
}
|
||||
EventBody::PaymentUnprojected { payment } => {
|
||||
if self.projects.payments.remove(payment).is_none() {
|
||||
return Err("this payment is in no project");
|
||||
}
|
||||
}
|
||||
EventBody::ProjectRuleSet { merchant_key: key, project } => {
|
||||
if key.is_empty() || merchant_key(key) != *key {
|
||||
return Err("not a merchant key");
|
||||
}
|
||||
match project {
|
||||
Some(id) => {
|
||||
if !self.projects.projects.get(id).is_some_and(ProjectRecord::is_open) {
|
||||
return Err("no such open project");
|
||||
}
|
||||
self.projects.rules.insert(key.clone(), id.clone());
|
||||
}
|
||||
None => {
|
||||
self.projects.rules.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
EventBody::TaskCreated { task, project, fields } => {
|
||||
if !id_ok(task) || self.projects.tasks.contains_key(task) {
|
||||
return Err("a task with this id exists");
|
||||
}
|
||||
let p = self.projects.projects.get(project).ok_or("no such project")?;
|
||||
task_fields(p, fields)?;
|
||||
if self.projects.tasks.values().filter(|t| &t.project == project && t.status != TaskStatus::Done).count() >= project::MAX_OPEN_TASKS {
|
||||
return Err("at most 200 open tasks a project");
|
||||
}
|
||||
self.projects.tasks.insert(task.clone(), TaskRecord { id: task.clone(), project: project.clone(), fields: fields.clone(), status: TaskStatus::Todo, done_on: None, seq });
|
||||
}
|
||||
EventBody::TaskChanged { task, fields } => {
|
||||
let t = self.projects.tasks.get(task).ok_or("no such task")?;
|
||||
let p = self.projects.projects.get(&t.project).ok_or("no such project")?;
|
||||
task_fields(p, fields)?;
|
||||
self.projects.tasks.get_mut(task).expect("checked").fields = fields.clone();
|
||||
}
|
||||
EventBody::TaskStatusSet { task, status, on } => {
|
||||
let t = self.projects.tasks.get_mut(task).ok_or("no such task")?;
|
||||
t.status = *status;
|
||||
t.done_on = (*status == TaskStatus::Done).then_some(*on);
|
||||
}
|
||||
EventBody::TimeLogged { entry, project, task, minutes, on, rate, note } => {
|
||||
if !id_ok(entry) || self.projects.time.contains_key(entry) {
|
||||
return Err("a time entry with this id exists");
|
||||
}
|
||||
let p = self.projects.projects.get(project).ok_or("no such project")?;
|
||||
if p.kind != project::Kind::Business {
|
||||
return Err("only a business project logs time");
|
||||
}
|
||||
if task.as_ref().is_some_and(|t| !self.projects.tasks.get(t).is_some_and(|x| &x.project == project)) {
|
||||
return Err("no such task in the project");
|
||||
}
|
||||
let day: u32 = self.projects.time.values().filter(|t| t.on == *on).map(|t| t.minutes).sum();
|
||||
if *minutes == 0 || day + minutes > project::MAX_MINUTES_A_DAY {
|
||||
return Err("time logged is 1 minute to 24 hours a day");
|
||||
}
|
||||
if rate.0 < 0 || *rate > project::MAX_RATE {
|
||||
return Err("an hourly rate is 0-100 000 CZK");
|
||||
}
|
||||
if note.chars().count() > 200 || !text_ok(note) {
|
||||
return Err("a note is at most 200 characters");
|
||||
}
|
||||
self.projects.time.insert(
|
||||
entry.clone(),
|
||||
TimeEntry { id: entry.clone(), project: project.clone(), task: task.clone(), minutes: *minutes, on: *on, rate: *rate, note: note.clone(), invoice: None, seq },
|
||||
);
|
||||
}
|
||||
EventBody::TimeRemoved { entry } => {
|
||||
let t = self.projects.time.get(entry).ok_or("no such time entry")?;
|
||||
if t.invoice.is_some() {
|
||||
return Err("this time is invoiced");
|
||||
}
|
||||
self.projects.time.remove(entry);
|
||||
}
|
||||
EventBody::InvoiceProjected { invoice, project, entries } => {
|
||||
if !self.invoices.contains_key(invoice) {
|
||||
return Err("no such invoice");
|
||||
}
|
||||
let p = self.projects.projects.get(project).ok_or("no such project")?;
|
||||
if p.kind != project::Kind::Business {
|
||||
return Err("only a business project has invoices");
|
||||
}
|
||||
if self.projects.projects.values().any(|x| x.invoices.contains(invoice)) {
|
||||
return Err("this invoice is in a project already");
|
||||
}
|
||||
if entries.iter().collect::<BTreeSet<_>>().len() != entries.len() {
|
||||
return Err("a time entry appears twice");
|
||||
}
|
||||
for e in entries {
|
||||
match self.projects.time.get(e) {
|
||||
Some(t) if &t.project == project && t.invoice.is_none() => {}
|
||||
Some(t) if t.invoice.is_some() => return Err("this time is invoiced"),
|
||||
_ => return Err("no such time entry in the project"),
|
||||
}
|
||||
}
|
||||
for e in entries {
|
||||
self.projects.time.get_mut(e).expect("checked").invoice = Some(invoice.clone());
|
||||
}
|
||||
self.projects.projects.get_mut(project).expect("checked").invoices.insert(invoice.clone());
|
||||
}
|
||||
EventBody::ProjectShared { project, budget } => {
|
||||
if !self.projects.projects.contains_key(project) {
|
||||
return Err("no such project");
|
||||
}
|
||||
if !self.budgets.contains_key(budget) {
|
||||
return Err("no such budget");
|
||||
}
|
||||
if self.projects.shared.contains_key(project) {
|
||||
return Err("the project is shared already");
|
||||
}
|
||||
self.projects.shared.insert(project.clone(), budget.clone());
|
||||
}
|
||||
EventBody::ProjectUnshared { project } => {
|
||||
if self.projects.shared.remove(project).is_none() {
|
||||
return Err("the project is not shared");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The project a payment is in, and its line: put there by hand, else by a project rule of its merchant while
|
||||
/// the project is open and the payment falls in the project's dates.
|
||||
pub fn project_of(&self, p: &EffectivePayment) -> Option<(String, Option<String>)> {
|
||||
if let Some((project, line)) = self.projects.payments.get(&p.id) {
|
||||
return Some((project.clone(), line.clone()));
|
||||
}
|
||||
let id = self.projects.rules.get(&p.merchant_key)?;
|
||||
let rec = self.projects.projects.get(id)?;
|
||||
let in_dates = rec.starts.is_none_or(|s| p.date >= s) && rec.ends.is_none_or(|e| p.date <= e);
|
||||
(rec.is_open() && in_dates).then(|| (id.clone(), None))
|
||||
}
|
||||
|
||||
/// A default category or one of your own.
|
||||
pub fn category_known(&self, id: &str) -> bool {
|
||||
categories::DEFAULT.iter().any(|(d, _)| *d == id) || self.custom_categories.contains_key(id)
|
||||
}
|
||||
|
||||
/// The name the app shows for a category: yours, the default one, or the id itself.
|
||||
pub fn category_label(&self, id: &str) -> String {
|
||||
self.custom_categories.get(id).cloned().unwrap_or_else(|| categories::label(id).to_string())
|
||||
}
|
||||
|
||||
/// Every category the app offers: the default ones in their order, then yours by id.
|
||||
pub fn categories(&self) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = categories::DEFAULT.iter().map(|(id, l)| (id.to_string(), l.to_string())).collect();
|
||||
out.extend(self.custom_categories.iter().map(|(id, l)| (id.clone(), l.clone())));
|
||||
out
|
||||
}
|
||||
|
||||
/// The plan for `category` in the month of `month`: the latest plan from that month or before (by month,
|
||||
/// then log order); `None` without one, or when it was set to zero.
|
||||
pub fn plan_for(&self, category: &str, month: Date) -> Option<Haler> {
|
||||
let start = month.month_start();
|
||||
self.category_plans
|
||||
.get(category)?
|
||||
.iter()
|
||||
.filter(|p| p.from <= start)
|
||||
.max_by_key(|p| (p.from, p.seq))
|
||||
.map(|p| p.amount)
|
||||
.filter(|a| a.0 > 0)
|
||||
}
|
||||
|
||||
/// What the tax reserve holds: everything set aside for paid invoices, less what was taken out.
|
||||
pub fn reserve_balance(&self) -> Haler {
|
||||
let set: i64 = self.invoices.values().filter_map(|r| r.paid.as_ref()).map(|p| p.reserve.0).fold(0, i64::saturating_add);
|
||||
let out: i64 = self.withdrawals.iter().map(|w| w.amount.0).fold(0, i64::saturating_add);
|
||||
Haler(set.saturating_sub(out))
|
||||
}
|
||||
|
||||
/// The number the next invoice issued in `year` gets.
|
||||
pub fn next_invoice_number(&self, year: i32) -> Option<String> {
|
||||
let prefix = year.to_string();
|
||||
let last = self.invoice_numbers.keys().filter(|n| n.starts_with(&prefix)).filter_map(|n| n[4..].parse::<u32>().ok()).max().unwrap_or(0);
|
||||
crate::invoice::invoice_number(year, last + 1).ok()
|
||||
}
|
||||
|
||||
/// QR Platba for an unpaid invoice: its total, its number as the variable symbol, to the account set.
|
||||
pub fn invoice_spayd(&self, invoice: &str) -> Option<String> {
|
||||
let r = self.invoices.get(invoice)?;
|
||||
if r.paid.is_some() || r.cancelled {
|
||||
return None;
|
||||
}
|
||||
let a = self.account.as_ref()?;
|
||||
let iban = Iban::parse(&a.iban).ok()?;
|
||||
spayd(&iban, r.totals.total, Some(&a.name), &format!("Faktura {}", r.invoice.number), Some(&r.invoice.number)).ok()
|
||||
}
|
||||
|
||||
/// Whether a phone's capture token (its SHA-256 in hex) may post captures.
|
||||
pub fn capture_token_active(&self, token: &str) -> bool {
|
||||
self.capture_tokens.get(token).is_some_and(|t| !t.revoked)
|
||||
@@ -682,6 +1361,8 @@ impl State {
|
||||
category_source,
|
||||
budget,
|
||||
trial_ends: latest(&p.trial_ends, partner.map(|q| &q.trial_ends)),
|
||||
receipt_seq: [p.receipt.as_ref(), partner.and_then(|q| q.receipt.as_ref())].into_iter().flatten().map(|r| r.seq).max().unwrap_or(0),
|
||||
receipt: latest(&p.receipt, partner.map(|q| &q.receipt)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Savings goals and challenges in the ledger: what is accepted, and every refusal changing nothing. A goal never
|
||||
//! holds less than nothing, the shares of "what's left" and "income" never add up to more than all of it, and a
|
||||
//! closed goal takes no more money.
|
||||
|
||||
use fiscus_ledger::goal::{ChallengeGoal, Colour, Way, WayKind};
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn ev(id: &str, body: EventBody) -> Event {
|
||||
Event::new(id, Timestamp(0), body)
|
||||
}
|
||||
|
||||
fn goal(id: &str, name: &str, target: i64) -> EventBody {
|
||||
EventBody::GoalCreated { goal: id.into(), name: name.into(), target: Haler(target), by: Some(d("2027-06-30")), colour: Colour::Teal }
|
||||
}
|
||||
|
||||
fn saved(goal: &str, saving: &str, amount: i64, way: Option<WayKind>) -> EventBody {
|
||||
EventBody::GoalSaved { goal: goal.into(), saving: saving.into(), amount: Haler(amount), on: d("2026-11-05"), way }
|
||||
}
|
||||
|
||||
fn ways(goal: &str, ways: Vec<Way>) -> EventBody {
|
||||
EventBody::GoalWaysSet { goal: goal.into(), ways }
|
||||
}
|
||||
|
||||
/// The base ledger, then `body`: the reason it was refused, or `None` when it was accepted.
|
||||
fn refusal(base: &[EventBody], body: EventBody) -> Option<String> {
|
||||
let mut log: Vec<Event> = base.iter().enumerate().map(|(i, b)| ev(&format!("b{i}"), b.clone())).collect();
|
||||
let before = State::replay(&log);
|
||||
assert!(before.rejected.is_empty(), "{:?}", before.rejected);
|
||||
log.push(ev("x", body));
|
||||
let after = State::replay(&log);
|
||||
match after.rejected.last() {
|
||||
Some(r) => {
|
||||
assert_eq!(after.goals, before.goals, "a refusal changes no goal");
|
||||
assert_eq!(after.challenges, before.challenges, "a refusal changes no challenge");
|
||||
Some(r.reason.clone())
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_goal_fills_with_what_you_put_aside_and_empties_only_to_zero() {
|
||||
let s = State::replay(&[
|
||||
ev("e1", goal("g1", "Holiday", 4_000_000)),
|
||||
ev("e2", ways("g1", vec![Way::Fixed { amount: Haler(200_000) }, Way::RoundUp { to: Haler(5_000) }])),
|
||||
ev("e3", saved("g1", "s1", 200_000, Some(WayKind::Fixed))),
|
||||
ev("e4", saved("g1", "s2", 31_200, Some(WayKind::RoundUp))),
|
||||
ev("e5", saved("g1", "s3", -50_000, None)),
|
||||
]);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
let g = &s.goals["g1"];
|
||||
assert_eq!(g.saved(), Haler(181_200));
|
||||
assert_eq!(g.ways.len(), 2);
|
||||
assert!(g.is_open());
|
||||
|
||||
let base = [goal("g1", "Holiday", 4_000_000), saved("g1", "s1", 100_000, None)];
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", -100_001, None)).as_deref(), Some("more than the goal holds"));
|
||||
assert_eq!(refusal(&base, saved("g1", "s1", 5_000, None)).as_deref(), Some("a saving with this id exists"), "counted once");
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", 0, None)).as_deref(), Some("an amount saved is 0,01-100 000 000 CZK either way"));
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", 5_000, Some(WayKind::Income))).as_deref(), Some("the goal is not saved for that way"));
|
||||
assert_eq!(refusal(&base, saved("nope", "s2", 5_000, None)).as_deref(), Some("no such goal"));
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", -100_000, None)), None, "down to exactly zero");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_goal_is_checked_when_made_and_changed() {
|
||||
assert_eq!(refusal(&[], goal("g1", "", 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], goal("g1", " Holiday", 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], goal("g1", &"x".repeat(61), 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], goal("g1", "Bad\u{7}", 100_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], goal("g1", "Holiday", 99)).as_deref(), Some("a goal target is 1-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&[], goal("g1", "Holiday", 10_000_000_001)).as_deref(), Some("a goal target is 1-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&[goal("g1", "Holiday", 100_000)], goal("g1", "Car", 100_000)).as_deref(), Some("a goal with this id exists"));
|
||||
let twenty: Vec<EventBody> = (0..20).map(|i| goal(&format!("g{i}"), "Goal", 100_000)).collect();
|
||||
assert_eq!(refusal(&twenty, goal("g20", "One more", 100_000)).as_deref(), Some("at most 20 goals are open at once"));
|
||||
let mut closed_one = twenty.clone();
|
||||
closed_one.push(EventBody::GoalClosed { goal: "g3".into(), on: d("2026-11-05") });
|
||||
assert_eq!(refusal(&closed_one, goal("g20", "One more", 100_000)), None, "a closed goal frees its place");
|
||||
|
||||
let base = [goal("g1", "Holiday", 100_000)];
|
||||
let change = |name: &str, target: i64| EventBody::GoalChanged { goal: "g1".into(), name: name.into(), target: Haler(target), by: None, colour: Colour::Coral };
|
||||
assert_eq!(refusal(&base, change("Summer", 200_000)), None);
|
||||
assert_eq!(refusal(&base, change("", 200_000)).as_deref(), Some("a goal name must be 1-60 characters"));
|
||||
let s = State::replay(&[ev("a", base[0].clone()), ev("b", change("Summer", 200_000))]);
|
||||
assert_eq!((s.goals["g1"].name.as_str(), s.goals["g1"].target, s.goals["g1"].colour, s.goals["g1"].by), ("Summer", Haler(200_000), Colour::Coral, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ways_are_one_of_each_kind_and_shares_never_add_up_to_more_than_all() {
|
||||
let base = [goal("g1", "Holiday", 4_000_000), goal("g2", "Car", 9_000_000)];
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::Fixed { amount: Haler(100) }, Way::Fixed { amount: Haler(200) }])).as_deref(), Some("a goal has at most one way of each kind"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::Fixed { amount: Haler(99) }])).as_deref(), Some("a fixed amount is 1-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::RoundUp { to: Haler(2_000) }])).as_deref(), Some("round-ups go to 10, 50 or 100 CZK"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::Income { permille: 0 }])).as_deref(), Some("a share is 1-1000 thousandths"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![Way::Leftover { permille: 1001 }])).as_deref(), Some("a share is 1-1000 thousandths"));
|
||||
|
||||
let mut split = base.to_vec();
|
||||
split.push(ways("g1", vec![Way::Leftover { permille: 600 }, Way::Income { permille: 100 }]));
|
||||
assert_eq!(refusal(&split, ways("g2", vec![Way::Leftover { permille: 401 }])).as_deref(), Some("the shares of one way across the goals add up to more than all of it"));
|
||||
assert_eq!(refusal(&split, ways("g2", vec![Way::Leftover { permille: 400 }, Way::Income { permille: 900 }])), None, "exactly all of it");
|
||||
assert_eq!(refusal(&split, ways("g1", vec![Way::Leftover { permille: 1000 }])), None, "a goal's own earlier share is replaced, not added");
|
||||
let mut closed = split.clone();
|
||||
closed.push(EventBody::GoalClosed { goal: "g1".into(), on: d("2026-11-05") });
|
||||
assert_eq!(refusal(&closed, ways("g2", vec![Way::Leftover { permille: 1000 }])), None, "a closed goal gives its share back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_goal_takes_no_more_and_keeps_its_history() {
|
||||
let base = [goal("g1", "Holiday", 100_000), saved("g1", "s1", 100_000, None), EventBody::GoalClosed { goal: "g1".into(), on: d("2026-11-06") }];
|
||||
assert_eq!(refusal(&base, saved("g1", "s2", 5_000, None)).as_deref(), Some("the goal is closed"));
|
||||
assert_eq!(refusal(&base, ways("g1", vec![])).as_deref(), Some("the goal is closed"));
|
||||
assert_eq!(refusal(&base, EventBody::GoalClosed { goal: "g1".into(), on: d("2026-11-07") }).as_deref(), Some("the goal is closed"));
|
||||
let s = State::replay(&base.iter().enumerate().map(|(i, b)| ev(&format!("e{i}"), b.clone())).collect::<Vec<_>>());
|
||||
assert_eq!((s.goals["g1"].saved(), s.goals["g1"].closed), (Haler(100_000), Some(d("2026-11-06"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_challenge_is_checked_and_given_up_once() {
|
||||
let start = |goal: ChallengeGoal, starts: &str, ends: &str| EventBody::ChallengeStarted { challenge: "c1".into(), goal, starts: d(starts), ends: d(ends) };
|
||||
let under = |category: &str, amount: i64| ChallengeGoal::SpendUnder { category: category.into(), amount: Haler(amount) };
|
||||
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-01", "2026-11-30")), None);
|
||||
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-01", "2027-01-31")), None, "92 days");
|
||||
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-01", "2027-02-01")).as_deref(), Some("a challenge lasts 1-92 days"));
|
||||
assert_eq!(refusal(&[], start(under("eating-out", 300_000), "2026-11-02", "2026-11-01")).as_deref(), Some("a challenge lasts 1-92 days"));
|
||||
assert_eq!(refusal(&[], start(under("income", 300_000), "2026-11-01", "2026-11-30")).as_deref(), Some("not a category you spend in"));
|
||||
assert_eq!(refusal(&[], start(under("nope", 300_000), "2026-11-01", "2026-11-30")).as_deref(), Some("not a category you spend in"));
|
||||
assert_eq!(refusal(&[], start(under("fun", 0), "2026-11-01", "2026-11-30")).as_deref(), Some("the amount of a challenge is 1-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&[], start(ChallengeGoal::NoSpend { category: "transfers".into() }, "2026-11-01", "2026-11-30")).as_deref(), Some("not a category you spend in"));
|
||||
assert_eq!(refusal(&[], start(ChallengeGoal::Cancel { subscription: String::new() }, "2026-11-01", "2026-11-30")).as_deref(), Some("not a subscription key"));
|
||||
let save = ChallengeGoal::Save { goal: "g1".into(), amount: Haler(500_000) };
|
||||
assert_eq!(refusal(&[], start(save.clone(), "2026-11-01", "2026-11-30")).as_deref(), Some("no such open goal"));
|
||||
assert_eq!(refusal(&[goal("g1", "Holiday", 4_000_000)], start(save.clone(), "2026-11-01", "2026-11-30")), None);
|
||||
|
||||
let base = [start(under("fun", 100_000), "2026-11-01", "2026-11-30")];
|
||||
assert_eq!(refusal(&base, start(under("fun", 100_000), "2026-11-01", "2026-11-30")).as_deref(), Some("a challenge with this id exists"));
|
||||
let give_up = EventBody::ChallengeAbandoned { challenge: "c1".into(), on: d("2026-11-10") };
|
||||
assert_eq!(refusal(&base, give_up.clone()), None);
|
||||
let mut given_up = base.to_vec();
|
||||
given_up.push(give_up.clone());
|
||||
assert_eq!(refusal(&given_up, give_up).as_deref(), Some("already given up"));
|
||||
assert_eq!(refusal(&base, EventBody::ChallengeAbandoned { challenge: "c2".into(), on: d("2026-11-10") }).as_deref(), Some("no such challenge"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_ways_and_goals_do_not_parse() {
|
||||
for bad in [
|
||||
r#"{"id":"x","at":0,"type":"goal.ways_set","goal":"g1","ways":[{"kind":"fixed","amount":100,"extra":1}]}"#,
|
||||
r#"{"id":"x","at":0,"type":"goal.ways_set","goal":"g1","ways":[{"kind":"lottery"}]}"#,
|
||||
r#"{"id":"x","at":0,"type":"goal.ways_set","goal":"g1","ways":[{"kind":"income","permille":1.5}]}"#,
|
||||
r#"{"id":"x","at":0,"type":"goal.created","goal":"g1","name":"A","target":100.0,"by":null,"colour":"teal"}"#,
|
||||
r#"{"id":"x","at":0,"type":"goal.created","goal":"g1","name":"A","target":100,"by":null,"colour":"pink"}"#,
|
||||
r#"{"id":"x","at":0,"type":"challenge.started","challenge":"c","goal":{"kind":"no_spend","category":"fun","amount":5},"starts":"2026-11-01","ends":"2026-11-30"}"#,
|
||||
] {
|
||||
assert!(serde_json::from_str::<Event>(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! v1 close: the name a person shows to the members of their shared budgets, the opt-in to share
|
||||
//! subscription names with a shared budget, and what a shared budget's log may hold of either.
|
||||
|
||||
use fiscus_ledger::{Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn ev(id: &str, body: EventBody) -> Event {
|
||||
Event::new(id, Timestamp(0), body)
|
||||
}
|
||||
|
||||
fn budgets() -> Vec<Event> {
|
||||
vec![
|
||||
ev("e1", EventBody::BudgetCreated { budget: "b-mine".into(), name: "Mine".into(), limit: Haler(1_000_000) }),
|
||||
ev("e2", EventBody::BudgetShared { budget: "b-home".into(), name: "Home".into(), limit: Haler(2_000_000) }),
|
||||
]
|
||||
}
|
||||
|
||||
fn rejected(log: &[Event]) -> Vec<String> {
|
||||
State::replay(log).rejected.iter().map(|r| r.reason.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_profile_name_is_the_latest_trimmed_and_bounded() {
|
||||
let mut log = budgets();
|
||||
log.push(ev("n1", EventBody::ProfileNamed { name: " Mark ".into() }));
|
||||
log.push(ev("n2", EventBody::ProfileNamed { name: "Marek".into() }));
|
||||
assert_eq!(State::replay(&log).profile_name.as_deref(), Some("Marek"));
|
||||
|
||||
for bad in ["", " ", "a\u{7}b", &"x".repeat(41)] {
|
||||
let mut log = budgets();
|
||||
log.push(ev("n", EventBody::ProfileNamed { name: bad.into() }));
|
||||
assert_eq!(rejected(&log).len(), 1, "{bad:?} is not a name");
|
||||
assert_eq!(State::replay(&log).profile_name, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscription_sharing_is_an_opt_in_per_shared_budget() {
|
||||
let mut log = budgets();
|
||||
log.push(ev("h1", EventBody::HouseholdSharingSet { budget: "b-home".into(), on: true }));
|
||||
assert!(State::replay(&log).household_sharing.contains("b-home"));
|
||||
log.push(ev("h2", EventBody::HouseholdSharingSet { budget: "b-home".into(), on: false }));
|
||||
assert!(State::replay(&log).household_sharing.is_empty(), "opting out takes it back");
|
||||
|
||||
let mut log = budgets();
|
||||
log.push(ev("h1", EventBody::HouseholdSharingSet { budget: "b-mine".into(), on: true }));
|
||||
log.push(ev("h2", EventBody::HouseholdSharingSet { budget: "b-none".into(), on: true }));
|
||||
assert_eq!(rejected(&log).len(), 2, "never the default budget, never an unknown one");
|
||||
assert!(State::replay(&log).household_sharing.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_name_and_shared_subscription_names_need_the_budget_and_are_bounded() {
|
||||
let group = vec![ev("g1", EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(0) })];
|
||||
let ok = |body: EventBody| {
|
||||
let mut log = group.clone();
|
||||
log.push(ev("x", body));
|
||||
rejected(&log).is_empty()
|
||||
};
|
||||
let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
|
||||
assert!(ok(EventBody::MemberNamed { budget: "b-home".into(), name: "Jana".into() }));
|
||||
assert!(!ok(EventBody::MemberNamed { budget: "b-other".into(), name: "Jana".into() }));
|
||||
assert!(!ok(EventBody::MemberNamed { budget: "b-home".into(), name: " ".into() }));
|
||||
|
||||
assert!(ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: names(&["spotify", "netflix"]) }));
|
||||
assert!(ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: vec![] }), "an empty list withdraws them");
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-other".into(), names: names(&["spotify"]) }));
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: names(&["spotify", "spotify"]) }));
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: names(&[""]) }));
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: vec!["x".repeat(41)] }));
|
||||
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: (0..101).map(|i| format!("s{i}")).collect() }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_events_round_trip_as_json_with_their_type_tags() {
|
||||
for (body, tag) in [
|
||||
(EventBody::ProfileNamed { name: "Mark".into() }, "profile.named"),
|
||||
(EventBody::HouseholdSharingSet { budget: "b".into(), on: true }, "household.sharing_set"),
|
||||
(EventBody::MemberNamed { budget: "b".into(), name: "Mark".into() }, "member.named"),
|
||||
(EventBody::SubscriptionsShared { budget: "b".into(), names: vec!["spotify".into()] }, "subscriptions.shared"),
|
||||
] {
|
||||
let json = serde_json::to_value(&body).unwrap();
|
||||
assert_eq!(json["type"], tag);
|
||||
assert_eq!(serde_json::from_value::<EventBody>(json).unwrap(), body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Invoices (v1.1): the totals to the haléř with and without VAT, the number that is the variable symbol, a paid
|
||||
//! invoice found on a statement and landing in its budget with the reserve set aside, and everything hostile or
|
||||
//! inconsistent refused.
|
||||
|
||||
use fiscus_ledger::import::StatementLine;
|
||||
use fiscus_ledger::invoice::{dic_ok, ico_ok, invoice_number, line_amount, plan_invoice_payments, same_vs, totals, Invoice, InvoiceError, InvoiceLine, Language, Party, Supplier};
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
struct Ids(u64);
|
||||
impl Ids {
|
||||
fn next(&mut self) -> String {
|
||||
self.0 += 1;
|
||||
format!("id{:04}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn ev(ids: &mut Ids, body: EventBody) -> Event {
|
||||
Event::new(ids.next(), Timestamp(0), body)
|
||||
}
|
||||
|
||||
fn party(name: &str) -> Party {
|
||||
Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some("45244782".into()), dic: None }
|
||||
}
|
||||
|
||||
fn supplier(vat_payer: bool, reserve_permille: u16) -> Supplier {
|
||||
let mut p = party("Marek Novák");
|
||||
p.ico = Some("27074358".into());
|
||||
p.dic = vat_payer.then(|| "CZ8001011234".into());
|
||||
Supplier { party: p, vat_payer, reserve_permille, registration: Some("Fyzická osoba zapsaná v živnostenském rejstříku.".into()) }
|
||||
}
|
||||
|
||||
fn line(text: &str, quantity: i64, price: i64, vat: Option<u8>) -> InvoiceLine {
|
||||
InvoiceLine { text: text.into(), quantity, unit: "h".into(), unit_price: Haler(price), vat }
|
||||
}
|
||||
|
||||
fn invoice(id: &str, number: &str, issued: &str, lines: Vec<InvoiceLine>, vat: bool) -> Invoice {
|
||||
Invoice {
|
||||
id: id.into(),
|
||||
number: number.into(),
|
||||
issued: d(issued),
|
||||
due: d(issued).add_days(14),
|
||||
taxable: vat.then(|| d(issued)),
|
||||
customer: party("Odběratel s.r.o."),
|
||||
lines,
|
||||
budget: None,
|
||||
language: Language::Cs,
|
||||
}
|
||||
}
|
||||
|
||||
fn imported(ids: &mut Ids, amount: i64, booked: &str, vs: Option<&str>) -> (Event, String) {
|
||||
let payment = ids.next();
|
||||
let line = StatementLine {
|
||||
bank: "test".into(),
|
||||
account: "1".into(),
|
||||
booked: d(booked),
|
||||
amount: Haler(amount),
|
||||
merchant: "Odběratel s.r.o.".into(),
|
||||
counterparty: Some("123/0100".into()),
|
||||
variable_symbol: vs.map(Into::into),
|
||||
message: None,
|
||||
bank_ref: Some(payment.clone()),
|
||||
};
|
||||
(ev(ids, EventBody::PaymentImported { payment: payment.clone(), line, line_key: format!("test|1|{payment}") }), payment)
|
||||
}
|
||||
|
||||
fn apply(state: &mut State, events: &[Event]) {
|
||||
for e in events {
|
||||
state.apply(e);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ico_and_dic_are_checked() {
|
||||
assert!(ico_ok("45244782")); // Česká spořitelna
|
||||
assert!(ico_ok("27074358"));
|
||||
assert!(!ico_ok("45244783"));
|
||||
assert!(!ico_ok("4524478"));
|
||||
assert!(!ico_ok("4524478a"));
|
||||
assert!(dic_ok("CZ45244782") && dic_ok("CZ8001011234"));
|
||||
assert!(!dic_ok("SK45244782") && !dic_ok("CZ1234567") && !dic_ok("CZ1234567890123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invoice_without_vat_adds_up_to_the_haler() {
|
||||
let t = totals(&[line("Konzultace", 1_500, 120_000, None), line("Licence", 3_000, 33_333, None)], false).unwrap();
|
||||
assert_eq!(t.lines, vec![Haler(180_000), Haler(99_999)]);
|
||||
assert_eq!((t.net, t.vat, t.total), (Haler(279_999), Haler(0), Haler(279_999)));
|
||||
assert!(t.rates.is_empty());
|
||||
// 0,333 h at 1 000 Kč is 333,00; at 1 000,05 Kč 333,016… → 333,02. Rounded half away from zero.
|
||||
assert_eq!(line_amount(333, Haler(100_000)).unwrap(), Haler(33_300));
|
||||
assert_eq!(line_amount(333, Haler(100_005)).unwrap(), Haler(33_302));
|
||||
assert_eq!(line_amount(1, Haler(50)).unwrap(), Haler(0), "0,0005 Kč is nothing");
|
||||
assert_eq!(line_amount(500, Haler(1)).unwrap(), Haler(1), "0,005 Kč rounds up to 0,01");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vat_invoice_computes_vat_once_per_rate_from_its_base() {
|
||||
let t = totals(&[line("Vývoj", 10_000, 100_000, Some(21)), line("Kniha", 1_000, 100_000, Some(12)), line("Vývoj", 1_000, 3, Some(21)), line("Pojištění", 1_000, 5_000, Some(0))], true).unwrap();
|
||||
// 21 %: base 10 000,03 → VAT 2 100,0063 → 2 100,01; 12 %: 1 000 → 120; 0 %: 50 → 0.
|
||||
assert_eq!(t.rates, vec![(21, Haler(1_000_003), Haler(210_001)), (12, Haler(100_000), Haler(12_000)), (0, Haler(5_000), Haler(0))]);
|
||||
assert_eq!((t.net, t.vat, t.total), (Haler(1_105_003), Haler(222_001), Haler(1_327_004)));
|
||||
// Per rate, not per line: three lines of 0,05 at 21 % are 0,15 → 0,03 VAT (per line it would be 3 × 0,01).
|
||||
let t = totals(&[line("a", 1_000, 5, Some(21)), line("b", 1_000, 5, Some(21)), line("c", 1_000, 5, Some(21))], true).unwrap();
|
||||
assert_eq!(t.vat, Haler(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_lines_are_refused() {
|
||||
let ok = line("Práce", 1_000, 100_000, None);
|
||||
assert_eq!(totals(&[], false), Err(InvoiceError::Lines));
|
||||
assert_eq!(totals(&vec![ok.clone(); 51], false), Err(InvoiceError::Lines));
|
||||
assert_eq!(totals(&[line("Práce", 0, 100, None)], false), Err(InvoiceError::Quantity));
|
||||
assert_eq!(totals(&[line("Práce", 1_000, 0, None)], false), Err(InvoiceError::Price));
|
||||
assert_eq!(totals(&[line("Práce", 1_000, -100, None)], false), Err(InvoiceError::Price));
|
||||
assert_eq!(totals(&[line("", 1_000, 100, None)], false), Err(InvoiceError::LineText));
|
||||
assert_eq!(totals(&[line("A\u{0}B", 1_000, 100, None)], false), Err(InvoiceError::LineText));
|
||||
assert_eq!(totals(&[line("Práce", 1_000, 100, Some(21))], false), Err(InvoiceError::RateUse), "a rate without being a VAT payer");
|
||||
assert_eq!(totals(&[line("Práce", 1_000, 100, None)], true), Err(InvoiceError::RateUse), "a VAT invoice line without a rate");
|
||||
assert_eq!(totals(&[line("Práce", 1_000, 100, Some(15))], true), Err(InvoiceError::Rate));
|
||||
// Over what QR Platba and a statement can carry.
|
||||
assert_eq!(totals(&[line("Práce", 1_000_000_000, 999_999_999, None)], false), Err(InvoiceError::Total));
|
||||
assert_eq!(totals(&[line("Práce", 2_000, 999_999_999, None)], false), Err(InvoiceError::Total));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_are_the_year_and_a_sequence_and_the_variable_symbol() {
|
||||
assert_eq!(invoice_number(2026, 1).unwrap(), "20260001");
|
||||
assert_eq!(invoice_number(2026, 0), Err(InvoiceError::Number));
|
||||
assert_eq!(invoice_number(2026, 10_000), Err(InvoiceError::Number));
|
||||
assert!(same_vs("0020260001", "20260001") && same_vs(" 20260001 ", "20260001"));
|
||||
assert!(!same_vs("20260002", "20260001") && !same_vs("", "") && !same_vs("000", "0"));
|
||||
|
||||
let mut ids = Ids(0);
|
||||
let mut s = State::default();
|
||||
assert_eq!(s.next_invoice_number(2026).as_deref(), Some("20260001"));
|
||||
let events = [
|
||||
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
|
||||
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false) }),
|
||||
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i2", "20260002", "2026-04-01", vec![line("Práce", 1_000, 100_000, None)], false) }),
|
||||
];
|
||||
apply(&mut s, &events);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
assert_eq!(s.next_invoice_number(2026).as_deref(), Some("20260003"));
|
||||
assert_eq!(s.next_invoice_number(2027).as_deref(), Some("20270001"), "each year starts again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invoice_that_does_not_fit_is_rejected_and_changes_nothing() {
|
||||
let mut ids = Ids(0);
|
||||
let mut s = State::default();
|
||||
let good = || invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false);
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: good() })]);
|
||||
assert_eq!(s.rejected.len(), 1, "no supplier yet");
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) })]);
|
||||
|
||||
let mut cases: Vec<Invoice> = Vec::new();
|
||||
let mut i = good();
|
||||
i.number = "20250001".into(); // not this year's
|
||||
cases.push(i);
|
||||
let mut i = good();
|
||||
i.number = "20260000".into();
|
||||
cases.push(i);
|
||||
let mut i = good();
|
||||
i.number = "2026001".into();
|
||||
cases.push(i);
|
||||
let mut i = good();
|
||||
i.due = d("2026-02-28");
|
||||
cases.push(i);
|
||||
let mut i = good();
|
||||
i.taxable = Some(d("2026-03-01")); // a DUZP without being a VAT payer
|
||||
cases.push(i);
|
||||
let mut i = good();
|
||||
i.customer.ico = Some("12345678".into());
|
||||
cases.push(i);
|
||||
let mut i = good();
|
||||
i.customer.name = "X\u{7}".into();
|
||||
cases.push(i);
|
||||
let mut i = good();
|
||||
i.customer.address = vec![];
|
||||
cases.push(i);
|
||||
let mut i = good();
|
||||
i.budget = Some("no-such".into());
|
||||
cases.push(i);
|
||||
let before = s.rejected.len();
|
||||
for c in cases.iter().cloned() {
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: c })]);
|
||||
}
|
||||
assert_eq!(s.rejected.len() - before, cases.len());
|
||||
assert!(s.invoices.is_empty() && s.invoice_numbers.is_empty());
|
||||
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: good() })]);
|
||||
let mut again = good();
|
||||
again.id = "i2".into();
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: again })]);
|
||||
assert_eq!(s.invoices.len(), 1, "a number is used once");
|
||||
|
||||
// A VAT payer without a DIČ, a reserve over 60 %.
|
||||
let mut no_dic = supplier(true, 150);
|
||||
no_dic.party.dic = None;
|
||||
let before = s.rejected.len();
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: no_dic }), ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 601) })]);
|
||||
assert_eq!(s.rejected.len() - before, 2);
|
||||
assert_eq!(s.supplier, Some(supplier(false, 150)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paid_invoice_lands_in_its_budget_with_the_reserve_set_aside_untouched() {
|
||||
let mut ids = Ids(0);
|
||||
let mut s = State::default();
|
||||
let mut inv = invoice("i1", "20260001", "2026-03-01", vec![line("Konzultace", 10_000, 150_000, None)], false);
|
||||
inv.budget = Some("home".into());
|
||||
apply(
|
||||
&mut s,
|
||||
&[
|
||||
ev(&mut ids, EventBody::BudgetCreated { budget: "home".into(), name: "Home".into(), limit: Haler(3_000_000) }),
|
||||
ev(&mut ids, EventBody::AccountSet { iban: "CZ6508000000192000145399".into(), name: "Marek Novak".into() }),
|
||||
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
|
||||
ev(&mut ids, EventBody::InvoiceIssued { invoice: inv }),
|
||||
],
|
||||
);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
assert_eq!(s.invoices["i1"].totals.total, Haler(1_500_000));
|
||||
let qr = s.invoice_spayd("i1").unwrap();
|
||||
assert!(qr.contains("*AM:15000.00*") && qr.contains("*X-VS:20260001") && qr.contains("*MSG:Faktura 20260001"), "{qr}");
|
||||
|
||||
// The statement brings three lines: the wrong amount, no symbol, and the payment (the bank pads the symbol).
|
||||
let (wrong, _) = imported(&mut ids, 1_400_000, "2026-03-10", Some("20260001"));
|
||||
let (nosym, _) = imported(&mut ids, 1_500_000, "2026-03-11", None);
|
||||
let (right, paid_by) = imported(&mut ids, 1_500_000, "2026-03-12", Some("0020260001"));
|
||||
apply(&mut s, &[wrong, nosym, right]);
|
||||
let plan = plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0));
|
||||
let kinds: Vec<String> = plan.iter().map(|e| format!("{:?}", e.body).split_whitespace().next().unwrap().to_string()).collect();
|
||||
assert_eq!(kinds, vec!["InvoicePaid", "PaymentCategorised", "PaymentAssigned"]);
|
||||
apply(&mut s, &plan);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
|
||||
let paid = s.invoices["i1"].paid.clone().unwrap();
|
||||
assert_eq!((paid.payment.as_deref(), paid.on), (Some(paid_by.as_str()), d("2026-03-12")));
|
||||
assert_eq!(paid.reserve, Haler(225_000), "15 % of 15 000 Kč");
|
||||
assert_eq!(s.reserve_balance(), Haler(225_000));
|
||||
let p = s.effective_payment(&paid_by).unwrap();
|
||||
assert_eq!((p.category.as_deref(), p.budget.as_deref()), (Some("income"), Some("home")));
|
||||
assert_eq!(s.invoice_spayd("i1"), None, "no QR for a paid invoice");
|
||||
|
||||
// Planning again finds nothing: paid once.
|
||||
assert!(plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0)).is_empty());
|
||||
|
||||
// The reserve pays the tax: no more than it holds.
|
||||
let before = s.rejected.len();
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w1".into(), amount: Haler(225_001), on: d("2027-03-31"), note: "Daň z příjmů".into() })]);
|
||||
assert_eq!(s.rejected.len() - before, 1);
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w1".into(), amount: Haler(200_000), on: d("2027-03-31"), note: "Daň z příjmů".into() })]);
|
||||
assert_eq!(s.reserve_balance(), Haler(25_000), "{:?}", s.rejected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vat_payer_sets_aside_all_the_vat_and_the_share_of_the_rest() {
|
||||
let mut ids = Ids(0);
|
||||
let mut s = State::default();
|
||||
apply(
|
||||
&mut s,
|
||||
&[
|
||||
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 100) }),
|
||||
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Vývoj", 10_000, 100_000, Some(21))], true) }),
|
||||
],
|
||||
);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
assert_eq!(s.invoices["i1"].totals.total, Haler(1_210_000));
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-05") })]);
|
||||
// VAT 2 100 Kč, and 10 % of 10 000 Kč.
|
||||
assert_eq!(s.reserve_balance(), Haler(310_000));
|
||||
// A later change of the supplier does not change an invoice issued before it.
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 300) })]);
|
||||
assert_eq!(s.invoices["i1"].supplier.reserve_permille, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_payment_pays_one_invoice_once_and_only_its_own_amount() {
|
||||
let mut ids = Ids(0);
|
||||
let mut s = State::default();
|
||||
let one = |id: &str, n: &str| invoice(id, n, "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false);
|
||||
apply(
|
||||
&mut s,
|
||||
&[
|
||||
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
|
||||
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i1", "20260001") }),
|
||||
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i2", "20260002") }),
|
||||
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i3", "20260003") }),
|
||||
],
|
||||
);
|
||||
let (line_event, line) = imported(&mut ids, 100_000, "2026-03-02", Some("20260001"));
|
||||
let (small, small_id) = imported(&mut ids, 99_999, "2026-03-02", Some("20260002"));
|
||||
let (early, _) = imported(&mut ids, 100_000, "2026-02-27", Some("20260003"));
|
||||
apply(&mut s, &[line_event, small, early]);
|
||||
let before = s.rejected.len();
|
||||
apply(
|
||||
&mut s,
|
||||
&[
|
||||
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: Some(small_id), on: d("2026-03-02") }), // wrong amount
|
||||
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: Some("no-such".into()), on: d("2026-03-02") }),
|
||||
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: None, on: d("2026-02-01") }), // before it was issued
|
||||
ev(&mut ids, EventBody::InvoicePaid { invoice: "nope".into(), payment: None, on: d("2026-03-02") }),
|
||||
],
|
||||
);
|
||||
assert_eq!(s.rejected.len() - before, 4);
|
||||
// The early line (before the invoice was issued) pays nothing; the right one pays i1 only.
|
||||
let plan = plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0));
|
||||
let paid: Vec<String> = plan.iter().filter_map(|e| match &e.body { EventBody::InvoicePaid { invoice, .. } => Some(invoice.clone()), _ => None }).collect();
|
||||
assert_eq!(paid, vec!["i1"]);
|
||||
apply(&mut s, &plan);
|
||||
let before = s.rejected.len();
|
||||
apply(
|
||||
&mut s,
|
||||
&[
|
||||
ev(&mut ids, EventBody::InvoicePaid { invoice: "i3".into(), payment: Some(line.clone()), on: d("2026-03-02") }), // used by i1
|
||||
ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-02") }), // paid already
|
||||
ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i1".into() }), // paid: cannot be cancelled
|
||||
],
|
||||
);
|
||||
assert_eq!(s.rejected.len() - before, 3);
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i2".into() })]);
|
||||
assert!(s.invoices["i2"].cancelled);
|
||||
let before = s.rejected.len();
|
||||
apply(&mut s, &[ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: None, on: d("2026-03-03") })]);
|
||||
assert_eq!(s.rejected.len() - before, 1, "a cancelled invoice is not paid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_events_round_trip_and_keep_their_names() {
|
||||
let mut ids = Ids(0);
|
||||
let events = vec![
|
||||
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 150) }),
|
||||
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, Some(21))], true) }),
|
||||
ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-05") }),
|
||||
ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i1".into() }),
|
||||
ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w".into(), amount: Haler(1), on: d("2026-03-05"), note: String::new() }),
|
||||
];
|
||||
let json = serde_json::to_string(&events).unwrap();
|
||||
for name in ["supplier.set", "invoice.issued", "invoice.paid", "invoice.cancelled", "reserve.withdrawn"] {
|
||||
assert!(json.contains(&format!("\"type\":\"{name}\"")), "{name}");
|
||||
}
|
||||
let back: Vec<Event> = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, events);
|
||||
// Replaying the log twice gives the same state.
|
||||
assert_eq!(State::replay(&events), State::replay(&back));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invoice_is_printed_in_czech_or_english_and_czech_when_unsaid() {
|
||||
let mut i = invoice("i1", "20260001", "2026-03-01", vec![line("Work", 1_000, 100_000, None)], false);
|
||||
i.language = Language::En;
|
||||
let json = serde_json::to_string(&i).unwrap();
|
||||
assert!(json.contains("\"language\":\"en\""), "{json}");
|
||||
assert_eq!(serde_json::from_str::<Invoice>(&json).unwrap(), i);
|
||||
// An event written without the field reads as Czech.
|
||||
let older = json.replace(",\"language\":\"en\"", "");
|
||||
assert!(!older.contains("language"));
|
||||
assert_eq!(serde_json::from_str::<Invoice>(&older).unwrap().language, Language::Cs);
|
||||
// Anything else is refused.
|
||||
assert!(serde_json::from_str::<Invoice>(&json.replace("\"en\"", "\"de\"")).is_err());
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Category plans and categories of your own: a plan carries forward until a later one replaces it, zero
|
||||
//! removes it, and only a real spending category can have one. Every refusal changes nothing.
|
||||
|
||||
use fiscus_ledger::categories::MAX_PLAN;
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn plan(id: &str, category: &str, amount: i64, from: &str) -> Event {
|
||||
Event::new(id, Timestamp(0), EventBody::CategoryPlanned { category: category.into(), amount: Haler(amount), from: d(from) })
|
||||
}
|
||||
|
||||
fn created(id: &str, category: &str, label: &str) -> Event {
|
||||
Event::new(id, Timestamp(0), EventBody::CategoryCreated { category: category.into(), label: label.into() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_carries_forward_until_a_later_one_replaces_it() {
|
||||
let s = State::replay(&[plan("p1", "groceries", 800_000, "2026-09-01"), plan("p2", "groceries", 900_000, "2026-11-01"), plan("p3", "eating-out", 200_000, "2026-10-01")]);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
assert_eq!(s.plan_for("groceries", d("2026-08-31")), None, "not before its month");
|
||||
assert_eq!(s.plan_for("groceries", d("2026-09-15")), Some(Haler(800_000)));
|
||||
assert_eq!(s.plan_for("groceries", d("2026-10-31")), Some(Haler(800_000)), "carried forward");
|
||||
assert_eq!(s.plan_for("groceries", d("2026-11-01")), Some(Haler(900_000)));
|
||||
assert_eq!(s.plan_for("groceries", d("2027-06-10")), Some(Haler(900_000)));
|
||||
assert_eq!(s.plan_for("eating-out", d("2026-09-30")), None);
|
||||
assert_eq!(s.plan_for("transport", d("2026-11-01")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_latest_plan_for_a_month_wins_and_zero_removes_it() {
|
||||
// Written later for an earlier month: the plan from November still counts in November.
|
||||
let s = State::replay(&[plan("p1", "groceries", 900_000, "2026-11-01"), plan("p2", "groceries", 700_000, "2026-10-01")]);
|
||||
assert_eq!(s.plan_for("groceries", d("2026-11-20")), Some(Haler(900_000)));
|
||||
assert_eq!(s.plan_for("groceries", d("2026-10-20")), Some(Haler(700_000)));
|
||||
// Two for the same month: the later in the log.
|
||||
let s = State::replay(&[plan("p1", "groceries", 900_000, "2026-11-01"), plan("p2", "groceries", 500_000, "2026-11-01")]);
|
||||
assert_eq!(s.plan_for("groceries", d("2026-11-20")), Some(Haler(500_000)));
|
||||
// Zero from December: no plan from then on.
|
||||
let s = State::replay(&[plan("p1", "groceries", 900_000, "2026-11-01"), plan("p2", "groceries", 0, "2026-12-01")]);
|
||||
assert_eq!(s.plan_for("groceries", d("2026-11-30")), Some(Haler(900_000)));
|
||||
assert_eq!(s.plan_for("groceries", d("2026-12-01")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_spending_category_can_have_a_plan() {
|
||||
for (category, amount, from, why) in [
|
||||
("income", 100, "2026-11-01", "money in"),
|
||||
("transfers", 100, "2026-11-01", "money moved"),
|
||||
("uncategorised", 100, "2026-11-01", "not sorted"),
|
||||
("fuel", 100, "2026-11-01", "an unknown category"),
|
||||
("Groceries", 100, "2026-11-01", "not an id"),
|
||||
("groceries", -1, "2026-11-01", "negative"),
|
||||
("groceries", MAX_PLAN.0 + 1, "2026-11-01", "over 100 million"),
|
||||
("groceries", 100, "2026-11-02", "not the 1st"),
|
||||
] {
|
||||
let s = State::replay(&[plan("p", category, amount, from)]);
|
||||
assert_eq!(s.rejected.len(), 1, "{why}");
|
||||
assert!(s.category_plans.is_empty(), "{why}: nothing kept");
|
||||
}
|
||||
let s = State::replay(&[plan("p", "groceries", MAX_PLAN.0, "2026-11-01")]);
|
||||
assert!(s.rejected.is_empty(), "exactly 100 million is a plan");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn categories_of_your_own() {
|
||||
let s = State::replay(&[created("c1", "fuel", "Fuel"), plan("p1", "fuel", 300_000, "2026-11-01")]);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
assert_eq!(s.category_label("fuel"), "Fuel");
|
||||
assert_eq!(s.category_label("groceries"), "Groceries");
|
||||
assert_eq!(s.plan_for("fuel", d("2026-11-03")), Some(Haler(300_000)));
|
||||
let all = s.categories();
|
||||
assert_eq!(all.last().unwrap(), &("fuel".to_string(), "Fuel".to_string()), "yours after the default ones");
|
||||
assert_eq!(all[0].0, "groceries");
|
||||
|
||||
for (event, why) in [
|
||||
(created("c2", "fuel", "Petrol"), "the same id twice"),
|
||||
(created("c2", "groceries", "Food"), "a default category"),
|
||||
(created("c2", "Fuel-2", "Fuel"), "not an id"),
|
||||
(created("c2", "parking", ""), "an empty name"),
|
||||
(created("c2", "parking", " Parking"), "a name with spaces around"),
|
||||
(created("c2", "parking", &"x".repeat(41)), "a long name"),
|
||||
(created("c2", "parking", "Park\ning"), "a control character"),
|
||||
] {
|
||||
let mut t = s.clone();
|
||||
t.apply(&event);
|
||||
assert_eq!(t.rejected.len(), 1, "{why}");
|
||||
assert_eq!(t.custom_categories.len(), 1, "{why}: nothing kept");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_events_round_trip_and_replay_the_same() {
|
||||
let log = vec![created("c1", "fuel", "Fuel"), plan("p1", "fuel", 300_000, "2026-11-01"), plan("p2", "groceries", 900_000, "2026-10-01")];
|
||||
let json = serde_json::to_string(&log).unwrap();
|
||||
for name in ["category.planned", "category.created"] {
|
||||
assert!(json.contains(name), "{name}");
|
||||
}
|
||||
let back: Vec<Event> = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, log);
|
||||
assert_eq!(State::replay(&back), State::replay(&log));
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Projects in the ledger: what is accepted, and every refusal changing nothing. A done project takes no more
|
||||
//! payments, a simple project has no phases or time, time never passes 24 hours a day, and an entry is
|
||||
//! invoiced once.
|
||||
|
||||
use fiscus_ledger::goal::Colour;
|
||||
use fiscus_ledger::project::{week_of, Kind, Status, TaskFields, TaskStatus};
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn ev(id: &str, body: EventBody) -> Event {
|
||||
Event::new(id, Timestamp(0), body)
|
||||
}
|
||||
|
||||
fn project(id: &str, kind: Kind) -> EventBody {
|
||||
EventBody::ProjectCreated { project: id.into(), name: "Flat".into(), kind, template: Some("renovation".into()), starts: Some(d("2026-11-01")), ends: Some(d("2027-02-28")), colour: Colour::Teal, rate: Some(Haler(80_000)) }
|
||||
}
|
||||
|
||||
fn task(id: &str, project: &str, title: &str) -> EventBody {
|
||||
EventBody::TaskCreated { task: id.into(), project: project.into(), fields: fields(title) }
|
||||
}
|
||||
|
||||
fn fields(title: &str) -> TaskFields {
|
||||
TaskFields { title: title.into(), phase: None, due: None, estimate: None, line: None, assignee: None, milestone: false }
|
||||
}
|
||||
|
||||
fn payment(id: &str, amount: i64, date: &str, merchant: &str) -> EventBody {
|
||||
EventBody::PaymentAdded { payment: id.into(), amount: Haler(amount), date: d(date), merchant: merchant.into(), category: None, note: None }
|
||||
}
|
||||
|
||||
fn log(entry: &str, project: &str, minutes: u32, on: &str) -> EventBody {
|
||||
EventBody::TimeLogged { entry: entry.into(), project: project.into(), task: None, minutes, on: d(on), rate: Haler(80_000), note: String::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_is_shared_with_one_budget_at_a_time_and_unshared_once() {
|
||||
let budget = |id: &str| EventBody::BudgetShared { budget: id.into(), name: "Home".into(), limit: Haler(0) };
|
||||
let base = vec![project("p1", Kind::Simple), budget("home"), budget("chata")];
|
||||
let share = |b: &str| EventBody::ProjectShared { project: "p1".into(), budget: b.into() };
|
||||
assert_eq!(refusal(&base, share("home")), None);
|
||||
assert_eq!(refusal(&base, EventBody::ProjectShared { project: "nope".into(), budget: "home".into() }).as_deref(), Some("no such project"));
|
||||
assert_eq!(refusal(&base, share("nope")).as_deref(), Some("no such budget"));
|
||||
let mut shared = base.clone();
|
||||
shared.push(share("home"));
|
||||
assert_eq!(refusal(&shared, share("chata")).as_deref(), Some("the project is shared already"));
|
||||
assert_eq!(refusal(&shared, share("home")).as_deref(), Some("the project is shared already"));
|
||||
let state = State::replay(&shared.iter().enumerate().map(|(i, b)| ev(&format!("s{i}"), b.clone())).collect::<Vec<_>>());
|
||||
assert_eq!(state.projects.shared.get("p1").map(String::as_str), Some("home"));
|
||||
assert_eq!(refusal(&base, EventBody::ProjectUnshared { project: "p1".into() }).as_deref(), Some("the project is not shared"));
|
||||
shared.push(EventBody::ProjectUnshared { project: "p1".into() });
|
||||
assert_eq!(refusal(&shared, EventBody::ProjectUnshared { project: "p1".into() }).as_deref(), Some("the project is not shared"));
|
||||
assert_eq!(refusal(&shared, share("chata")), None, "shared again, elsewhere");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shared_events_keep_their_names_on_the_wire() {
|
||||
let json = serde_json::to_string(&EventBody::ProjectShared { project: "p1".into(), budget: "home".into() }).unwrap();
|
||||
assert!(json.contains("\"project.shared\""), "{json}");
|
||||
let json = serde_json::to_string(&EventBody::ProjectUnshared { project: "p1".into() }).unwrap();
|
||||
assert!(json.contains("\"project.unshared\""), "{json}");
|
||||
// A state saved before sharing existed still reads.
|
||||
let old = serde_json::json!({ "projects": {}, "tasks": {}, "time": {}, "payments": {}, "rules": {} });
|
||||
let p: fiscus_ledger::project::Projects = serde_json::from_value(old).unwrap();
|
||||
assert!(p.shared.is_empty());
|
||||
}
|
||||
|
||||
/// The base ledger, then `body`: the reason it was refused, or `None` when it was accepted.
|
||||
fn refusal(base: &[EventBody], body: EventBody) -> Option<String> {
|
||||
let mut log: Vec<Event> = base.iter().enumerate().map(|(i, b)| ev(&format!("b{i}"), b.clone())).collect();
|
||||
let before = State::replay(&log);
|
||||
assert!(before.rejected.is_empty(), "{:?}", before.rejected);
|
||||
log.push(ev("x", body));
|
||||
let after = State::replay(&log);
|
||||
match after.rejected.last() {
|
||||
Some(r) => {
|
||||
assert_eq!(after.projects, before.projects, "a refusal changes no project");
|
||||
Some(r.reason.clone())
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_its_lines_tasks_and_payments() {
|
||||
let s = State::replay(&[
|
||||
ev("e1", project("p1", Kind::Simple)),
|
||||
ev("e2", EventBody::ProjectLineSet { project: "p1".into(), line: "kitchen".into(), name: "Kitchen".into(), planned: Haler(12_000_000) }),
|
||||
ev("e3", EventBody::ProjectLineSet { project: "p1".into(), line: "tiles".into(), name: "Tiles".into(), planned: Haler(4_500_000) }),
|
||||
ev("e4", EventBody::ProjectLineSet { project: "p1".into(), line: "tiles".into(), name: "Tiles and grout".into(), planned: Haler(5_000_000) }),
|
||||
ev("e5", task("t1", "p1", "Order the kitchen")),
|
||||
ev("e6", EventBody::TaskStatusSet { task: "t1".into(), status: TaskStatus::Done, on: d("2026-11-05") }),
|
||||
ev("e7", payment("pay1", -1_250_000, "2026-11-04", "IKEA Zlicin")),
|
||||
ev("e8", EventBody::PaymentProjected { payment: "pay1".into(), project: "p1".into(), line: Some("kitchen".into()) }),
|
||||
ev("e9", EventBody::ProjectLineSet { project: "p1".into(), line: "kitchen".into(), name: "Kitchen".into(), planned: Haler(0) }),
|
||||
]);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
let p = &s.projects.projects["p1"];
|
||||
assert_eq!(p.lines.iter().map(|l| (l.name.as_str(), l.planned)).collect::<Vec<_>>(), [("Tiles and grout", Haler(5_000_000))], "zero removes a line");
|
||||
assert_eq!((p.status, p.kind), (Status::Active, Kind::Simple));
|
||||
let t = &s.projects.tasks["t1"];
|
||||
assert_eq!((t.status, t.done_on), (TaskStatus::Done, Some(d("2026-11-05"))));
|
||||
assert_eq!(s.projects.payments["pay1"], ("p1".to_string(), Some("kitchen".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_is_checked_when_made_and_changed() {
|
||||
let made = |name: &str, starts: &str, ends: &str, rate: i64| EventBody::ProjectCreated {
|
||||
project: "p1".into(),
|
||||
name: name.into(),
|
||||
kind: Kind::Business,
|
||||
template: None,
|
||||
starts: Some(d(starts)),
|
||||
ends: Some(d(ends)),
|
||||
colour: Colour::Amber,
|
||||
rate: Some(Haler(rate)),
|
||||
};
|
||||
assert_eq!(refusal(&[], made("", "2026-11-01", "2026-12-01", 0)).as_deref(), Some("a project name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], made(" Web", "2026-11-01", "2026-12-01", 0)).as_deref(), Some("a project name must be 1-60 characters"));
|
||||
assert_eq!(refusal(&[], made("Web", "2026-12-01", "2026-11-01", 0)).as_deref(), Some("a project ends before it starts"));
|
||||
assert_eq!(refusal(&[], made("Web", "2026-11-01", "2026-12-01", -1)).as_deref(), Some("an hourly rate is 0-100 000 CZK"));
|
||||
assert_eq!(refusal(&[], made("Web", "2026-11-01", "2026-12-01", 10_000_001)).as_deref(), Some("an hourly rate is 0-100 000 CZK"));
|
||||
assert_eq!(refusal(&[project("p1", Kind::Simple)], project("p1", Kind::Simple)).as_deref(), Some("a project with this id exists"));
|
||||
let fifty: Vec<EventBody> = (0..50).map(|i| project(&format!("p{i}"), Kind::Simple)).collect();
|
||||
assert_eq!(refusal(&fifty, project("p50", Kind::Simple)).as_deref(), Some("at most 50 projects are open at once"));
|
||||
let mut one_done = fifty.clone();
|
||||
one_done.push(EventBody::ProjectStatusSet { project: "p3".into(), status: Status::Done, on: d("2026-11-20") });
|
||||
assert_eq!(refusal(&one_done, project("p50", Kind::Simple)), None, "a done project frees its place");
|
||||
let mut full_again = one_done.clone();
|
||||
full_again.push(project("p50", Kind::Simple));
|
||||
assert_eq!(refusal(&full_again, EventBody::ProjectStatusSet { project: "p3".into(), status: Status::Active, on: d("2026-11-21") }).as_deref(), Some("at most 50 projects are open at once"), "nor can it reopen into a full list");
|
||||
|
||||
let base = [project("p1", Kind::Business), log("l1", "p1", 60, "2026-11-02")];
|
||||
let to_simple = EventBody::ProjectChanged { project: "p1".into(), name: "Flat".into(), kind: Kind::Simple, starts: None, ends: None, colour: Colour::Coral, rate: None };
|
||||
assert_eq!(refusal(&base, to_simple).as_deref(), Some("a project with phases or time stays a business project"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_phases_and_tasks_are_checked() {
|
||||
let base = [project("p1", Kind::Simple), project("b1", Kind::Business)];
|
||||
let line = |planned: i64, name: &str| EventBody::ProjectLineSet { project: "p1".into(), line: "l".into(), name: name.into(), planned: Haler(planned) };
|
||||
assert_eq!(refusal(&base, line(-1, "Tiles")).as_deref(), Some("a planned amount is 0-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&base, line(10_000_000_001, "Tiles")).as_deref(), Some("a planned amount is 0-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&base, line(100, "")).as_deref(), Some("a budget line name must be 1-60 characters"));
|
||||
let phase = |project: &str, starts: &str, ends: &str| EventBody::ProjectPhaseSet { project: project.into(), phase: "ph1".into(), name: "Design".into(), starts: d(starts), ends: d(ends) };
|
||||
assert_eq!(refusal(&base, phase("p1", "2026-11-01", "2026-11-30")).as_deref(), Some("only a business project has phases"));
|
||||
assert_eq!(refusal(&base, phase("b1", "2026-11-30", "2026-11-01")).as_deref(), Some("a phase ends before it starts"));
|
||||
assert_eq!(refusal(&base, phase("b1", "2026-11-01", "2026-11-30")), None);
|
||||
|
||||
let mut f = fields("Tile the bathroom");
|
||||
f.line = Some("nope".into());
|
||||
assert_eq!(refusal(&base, EventBody::TaskCreated { task: "t".into(), project: "p1".into(), fields: f }).as_deref(), Some("no such budget line in the project"));
|
||||
let mut f = fields("Tile the bathroom");
|
||||
f.phase = Some("nope".into());
|
||||
assert_eq!(refusal(&base, EventBody::TaskCreated { task: "t".into(), project: "b1".into(), fields: f }).as_deref(), Some("no such phase in the project"));
|
||||
let mut f = fields("Tile the bathroom");
|
||||
f.estimate = Some(Haler(-1));
|
||||
assert_eq!(refusal(&base, EventBody::TaskCreated { task: "t".into(), project: "p1".into(), fields: f }).as_deref(), Some("an estimate is 0-100 000 000 CZK"));
|
||||
assert_eq!(refusal(&base, task("t", "p1", "")).as_deref(), Some("a task title must be 1-120 characters"));
|
||||
assert_eq!(refusal(&base, task("t", "nope", "Tile")).as_deref(), Some("no such project"));
|
||||
let two_hundred: Vec<EventBody> = std::iter::once(project("p1", Kind::Simple)).chain((0..200).map(|i| task(&format!("t{i}"), "p1", "Job"))).collect();
|
||||
assert_eq!(refusal(&two_hundred, task("t200", "p1", "One more")).as_deref(), Some("at most 200 open tasks a project"));
|
||||
|
||||
let with_task = [project("b1", Kind::Business), phase("b1", "2026-11-01", "2026-11-30"), EventBody::TaskCreated { task: "t".into(), project: "b1".into(), fields: TaskFields { phase: Some("ph1".into()), ..fields("Wireframes") } }];
|
||||
assert_eq!(refusal(&with_task, EventBody::ProjectPhaseRemoved { project: "b1".into(), phase: "ph1".into() }).as_deref(), Some("tasks are still in this phase"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payments_go_into_an_open_project_once() {
|
||||
let base = [project("p1", Kind::Simple), payment("pay1", -50_000, "2026-11-03", "Hornbach")];
|
||||
assert_eq!(refusal(&base, EventBody::PaymentProjected { payment: "nope".into(), project: "p1".into(), line: None }).as_deref(), Some("no such payment"));
|
||||
assert_eq!(refusal(&base, EventBody::PaymentProjected { payment: "pay1".into(), project: "p1".into(), line: Some("nope".into()) }).as_deref(), Some("no such budget line in the project"));
|
||||
assert_eq!(refusal(&base, EventBody::PaymentUnprojected { payment: "pay1".into() }).as_deref(), Some("this payment is in no project"));
|
||||
let mut done = base.to_vec();
|
||||
done.push(EventBody::ProjectStatusSet { project: "p1".into(), status: Status::Done, on: d("2026-11-10") });
|
||||
assert_eq!(refusal(&done, EventBody::PaymentProjected { payment: "pay1".into(), project: "p1".into(), line: None }).as_deref(), Some("the project is done"));
|
||||
assert_eq!(refusal(&done, EventBody::ProjectRuleSet { merchant_key: "hornbach".into(), project: Some("p1".into()) }).as_deref(), Some("no such open project"));
|
||||
assert_eq!(refusal(&base, EventBody::ProjectRuleSet { merchant_key: "Hornbach Praha".into(), project: Some("p1".into()) }).as_deref(), Some("not a merchant key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_is_business_only_never_over_a_day_and_invoiced_once() {
|
||||
let base = [project("p1", Kind::Simple), project("b1", Kind::Business), log("l1", "b1", 600, "2026-11-02")];
|
||||
assert_eq!(refusal(&base, log("l2", "p1", 60, "2026-11-02")).as_deref(), Some("only a business project logs time"));
|
||||
assert_eq!(refusal(&base, log("l2", "b1", 0, "2026-11-02")).as_deref(), Some("time logged is 1 minute to 24 hours a day"));
|
||||
assert_eq!(refusal(&base, log("l2", "b1", 841, "2026-11-02")).as_deref(), Some("time logged is 1 minute to 24 hours a day"));
|
||||
assert_eq!(refusal(&base, log("l2", "b1", 840, "2026-11-02")), None, "exactly 24 hours");
|
||||
assert_eq!(refusal(&base, log("l1", "b1", 60, "2026-11-03")).as_deref(), Some("a time entry with this id exists"));
|
||||
assert_eq!(
|
||||
refusal(&base, EventBody::TimeLogged { entry: "l2".into(), project: "b1".into(), task: Some("nope".into()), minutes: 60, on: d("2026-11-03"), rate: Haler(0), note: String::new() }).as_deref(),
|
||||
Some("no such task in the project")
|
||||
);
|
||||
// An invoice for the project bills the entry once; billed time stays.
|
||||
use fiscus_ledger::invoice::{Invoice, InvoiceLine, Language, Party, Supplier};
|
||||
let party = |name: &str, ico: &str| Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some(ico.into()), dic: None };
|
||||
let invoice = Invoice {
|
||||
id: "i1".into(),
|
||||
number: "20260001".into(),
|
||||
issued: d("2026-11-05"),
|
||||
due: d("2026-11-19"),
|
||||
taxable: None,
|
||||
customer: party("Pekárna Novák", "45244782"),
|
||||
lines: vec![InvoiceLine { text: "Web".into(), quantity: 10_000, unit: "h".into(), unit_price: Haler(80_000), vat: None }],
|
||||
budget: None,
|
||||
language: Language::Cs,
|
||||
};
|
||||
let mut billed = base.to_vec();
|
||||
billed.push(EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } });
|
||||
billed.push(EventBody::InvoiceIssued { invoice });
|
||||
assert_eq!(refusal(&billed, EventBody::InvoiceProjected { invoice: "i1".into(), project: "p1".into(), entries: vec![] }).as_deref(), Some("only a business project has invoices"));
|
||||
assert_eq!(refusal(&billed, EventBody::InvoiceProjected { invoice: "i1".into(), project: "b1".into(), entries: vec!["l1".into(), "l1".into()] }).as_deref(), Some("a time entry appears twice"));
|
||||
billed.push(EventBody::InvoiceProjected { invoice: "i1".into(), project: "b1".into(), entries: vec!["l1".into()] });
|
||||
assert_eq!(refusal(&billed, EventBody::TimeRemoved { entry: "l1".into() }).as_deref(), Some("this time is invoiced"));
|
||||
assert_eq!(refusal(&billed, EventBody::InvoiceProjected { invoice: "i1".into(), project: "b1".into(), entries: vec![] }).as_deref(), Some("this invoice is in a project already"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weeks_start_on_monday_and_time_rounds_once() {
|
||||
assert_eq!(week_of(d("2026-11-11")), d("2026-11-09"));
|
||||
assert_eq!(week_of(d("2026-11-09")), d("2026-11-09"));
|
||||
assert_eq!(week_of(d("2026-11-15")), d("2026-11-09"));
|
||||
assert_eq!(week_of(d("1970-01-01")), d("1969-12-29"));
|
||||
let s = State::replay(&[
|
||||
ev("a", project("b1", Kind::Business)),
|
||||
ev("b", EventBody::TimeLogged { entry: "l".into(), project: "b1".into(), task: None, minutes: 25, on: d("2026-11-02"), rate: Haler(65_050), note: String::new() }),
|
||||
]);
|
||||
// 25 min at 650,50 Kč/h = 271,0416… Kč → 271,04 Kč.
|
||||
assert_eq!(s.projects.time["l"].amount(), Haler(27_104));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_projects_do_not_parse() {
|
||||
for bad in [
|
||||
r#"{"id":"x","at":0,"type":"project.created","project":"p","name":"A","kind":"empire","template":null,"starts":null,"ends":null,"colour":"teal","rate":null}"#,
|
||||
r#"{"id":"x","at":0,"type":"project.created","project":"p","name":"A","kind":"simple","template":null,"starts":null,"ends":null,"colour":"teal","rate":10.5}"#,
|
||||
r#"{"id":"x","at":0,"type":"task.created","task":"t","project":"p","fields":{"title":"A","phase":null,"due":null,"estimate":null,"line":null,"assignee":null,"milestone":false,"secret":1}}"#,
|
||||
r#"{"id":"x","at":0,"type":"time.logged","entry":"e","project":"p","task":null,"minutes":-5,"on":"2026-11-02","rate":0,"note":""}"#,
|
||||
r#"{"id":"x","at":0,"type":"task.status_set","task":"t","status":"abandoned","on":"2026-11-02"}"#,
|
||||
] {
|
||||
assert!(serde_json::from_str::<Event>(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! A receipt attached to a payment (`payment.receipt_attached`, docs/07_receipts.md): checked on the way in,
|
||||
//! visible on the payment (either half of a confirmed pair), the latest one wins; a known shop comes from your
|
||||
//! latest receipt with its IČO; a receipt fills in exactly one payment or none.
|
||||
|
||||
use fiscus_ledger::import::{plan_import, StatementLine};
|
||||
use fiscus_ledger::{Category, Date, Event, EventBody, Haler, ReceiptInfo, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn ev(id: &str, body: EventBody) -> Event {
|
||||
Event::new(id, Timestamp(0), body)
|
||||
}
|
||||
|
||||
fn added(id: &str, amount: i64, date: &str, merchant: &str) -> EventBody {
|
||||
EventBody::PaymentAdded { payment: id.into(), amount: Haler(amount), date: d(date), merchant: merchant.into(), category: None, note: None }
|
||||
}
|
||||
|
||||
fn captured(id: &str, amount: i64, date: &str) -> EventBody {
|
||||
EventBody::PaymentCaptured { payment: id.into(), amount: Haler(amount), date: d(date), merchant: "ALBERT HM 4410".into(), card: None }
|
||||
}
|
||||
|
||||
fn info(shop: &str, ico: Option<&str>) -> ReceiptInfo {
|
||||
ReceiptInfo { shop: shop.into(), ico: ico.map(Into::into), dic: ico.map(|i| format!("CZ{i}")) }
|
||||
}
|
||||
|
||||
fn attach(payment: &str, r: ReceiptInfo) -> EventBody {
|
||||
EventBody::ReceiptAttached { payment: payment.into(), receipt: r }
|
||||
}
|
||||
|
||||
fn state(bodies: Vec<EventBody>) -> State {
|
||||
let mut s = State::default();
|
||||
for (i, b) in bodies.into_iter().enumerate() {
|
||||
s.apply(&ev(&format!("e{i}"), b));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_receipt_is_checked_and_sits_on_its_payment_which_keeps_its_merchant() {
|
||||
let s = state(vec![captured("p1", -128_490, "2026-11-16"), attach("p1", info("Albert Hypermarket", Some("25672541")))]);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
let p = s.effective_payment("p1").unwrap();
|
||||
assert_eq!(p.receipt.unwrap().shop, "Albert Hypermarket");
|
||||
assert_eq!(p.merchant, "ALBERT HM 4410", "the merchant and its rules stay");
|
||||
for (bad, why) in [
|
||||
(attach("nope", info("A", None)), "no such payment"),
|
||||
(attach("p1", info("", None)), "1-100 characters"),
|
||||
(attach("p1", info(" Albert", None)), "trimmed"),
|
||||
(attach("p1", info(&"x".repeat(101), None)), "1-100"),
|
||||
(attach("p1", info("Albert", Some("25672542"))), "IČO"),
|
||||
(attach("p1", ReceiptInfo { shop: "Albert".into(), ico: None, dic: Some("SK2020123456".into()) }), "DIČ"),
|
||||
] {
|
||||
let mut s = state(vec![captured("p1", -128_490, "2026-11-16")]);
|
||||
let before = s.effective_payment("p1");
|
||||
s.apply(&ev("bad", bad));
|
||||
assert!(s.rejected.last().is_some_and(|r| r.reason.contains(why)), "{why}: {:?}", s.rejected);
|
||||
assert_eq!(s.effective_payment("p1"), before, "a refusal changes nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_a_confirmed_pair_the_receipt_shows_and_the_later_one_wins() {
|
||||
let mut s = state(vec![captured("p1", -128_490, "2026-11-16"), attach("p1", info("Albert", Some("25672541")))]);
|
||||
let line = StatementLine { bank: "test".into(), account: "1/0000".into(), booked: d("2026-11-17"), amount: Haler(-128_490), merchant: "ALBERT HM".into(), counterparty: None, variable_symbol: None, message: None, bank_ref: None };
|
||||
let mut n = 0;
|
||||
let plan = plan_import(&s, &[line], &mut || {
|
||||
n += 1;
|
||||
format!("i{n}")
|
||||
}, Timestamp(1));
|
||||
for e in plan.events.iter().chain(&plan.confirmations) {
|
||||
s.apply(e);
|
||||
}
|
||||
let p = s.effective_payment("p1").unwrap();
|
||||
assert!(p.line.is_some(), "confirmed by its line");
|
||||
assert_eq!(p.receipt.as_ref().unwrap().shop, "Albert");
|
||||
s.apply(&ev("later", attach("p1", info("Albert Hypermarket", Some("25672541")))));
|
||||
assert_eq!(s.effective_payment("p1").unwrap().receipt.unwrap().shop, "Albert Hypermarket");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_known_shop_is_your_latest_receipt_with_its_ico() {
|
||||
let s = state(vec![
|
||||
added("a", -10_000, "2026-11-01", "x"),
|
||||
EventBody::PaymentCategorised { payment: "a".into(), category: Category::from("groceries") },
|
||||
attach("a", info("Albert", Some("25672541"))),
|
||||
added("b", -20_000, "2026-11-05", "y"),
|
||||
attach("b", info("Albert Hypermarket", Some("25672541"))),
|
||||
added("c", -30_000, "2026-11-06", "z"),
|
||||
attach("c", info("Lékárna", None)),
|
||||
]);
|
||||
let k = s.known_shop("25672541").unwrap();
|
||||
assert_eq!((k.name.as_str(), k.payment.as_str()), ("Albert Hypermarket", "b"));
|
||||
assert!(s.known_shop("61774031").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_receipt_fills_in_exactly_one_payment_or_none() {
|
||||
let base = vec![captured("p1", -128_490, "2026-11-16"), added("p2", -128_490, "2026-11-30", "x"), added("p3", -9_900, "2026-11-16", "y")];
|
||||
let s = state(base.clone());
|
||||
assert_eq!(s.receipt_match(Haler(128_490), d("2026-11-18")).as_deref(), Some("p1"), "same amount, two days later");
|
||||
assert_eq!(s.receipt_match(Haler(128_490), d("2026-11-20")), None, "four days is too far");
|
||||
assert_eq!(s.receipt_match(Haler(128_400), d("2026-11-16")), None, "another amount");
|
||||
let mut two = base.clone();
|
||||
two.push(added("p4", -128_490, "2026-11-15", "z"));
|
||||
assert_eq!(state(two).receipt_match(Haler(128_490), d("2026-11-16")), None, "two candidates: nothing guessed");
|
||||
let mut done = base;
|
||||
done.push(attach("p1", info("Albert", None)));
|
||||
assert_eq!(state(done).receipt_match(Haler(128_490), d("2026-11-16")), None, "it has its receipt already");
|
||||
}
|
||||
@@ -34,6 +34,7 @@ recorded in `state.rejected` and changes nothing else. Corrections are new event
|
||||
| `payment.categorised` | an explicit category for one payment |
|
||||
| `payment.assigned` | puts a payment into a budget |
|
||||
| `payment.trial_marked` | "this is a trial", with its end date |
|
||||
| `payment.receipt_attached` | a receipt for the payment: the shop's name, its IČO and DIČ (docs/07_receipts.md); the payment keeps its merchant |
|
||||
| `budget.created` / `budget.limit_set` | a monthly budget and its limit |
|
||||
| `rule.created` | "always <merchant> → <category>" |
|
||||
| `subscription.decided` | keep or cancel, for a merchant, at the amount seen when deciding |
|
||||
|
||||
@@ -19,6 +19,10 @@ is a log of its own (one MLS group): its members see exactly what was put into i
|
||||
| `capture.token_added` / `capture.token_revoked` | personal | a phone's capture token: only its SHA-256 (`token`), a `name` and the `kind` (`iphone`, `android`). The token itself lives in Custos |
|
||||
| `share.link_created` | personal | a share link for one person of one split: only the SHA-256 of the link token, `split`, `person`, `expires` |
|
||||
| `account.set` | personal | the account for QR Platba (`iban`, `name`); the log is encrypted everywhere it is stored |
|
||||
| `profile.named` | personal | the name you show to the members of your shared budgets (1–40 characters) *(v0.3.0)* |
|
||||
| `household.sharing_set` | personal | `budget, on`: share your subscription names with this shared budget, or stop. Rejected for the default budget or an unknown one *(v0.3.0)* |
|
||||
| `member.named` | shared budget | `budget, name`: what its author is called there. The latest per author counts *(v0.3.0)* |
|
||||
| `subscriptions.shared` | shared budget | `budget, names`: the service keys of every subscription its author still pays (at most 100, each 1–40 characters, no repeats). The latest per author replaces the earlier; `[]` withdraws them *(v0.3.0)* |
|
||||
|
||||
`apply()` stays total: anything that does not fit is recorded in `state.rejected` with the reason.
|
||||
|
||||
@@ -46,6 +50,9 @@ with exactly `amount`, `merchant`, `card`, `time`, plus an optional `currency`.
|
||||
- `merchant`: 1–200 characters, no control characters. `card`: 0–60 characters.
|
||||
- `time`: ISO 8601 with an offset (`2026-11-03T14:05:00+01:00`); the payment's date is the local date in it.
|
||||
- At most 4 KiB.
|
||||
- **A receipt read on the Android phone** (docs/07_receipts.md) comes the same way, with `"source": "receipt"`, the
|
||||
shop's name as `merchant`, an empty `card`, and optionally `ico` (8 digits with its check digit) and `dic` (`CZ`
|
||||
and 8–10 digits). An `ico` or `dic` without `"source": "receipt"`, or another `source`, is an error.
|
||||
*(assumption)* Apple's exact `amount` text is checked against the first real post.
|
||||
|
||||
**Android bank notifications.** `recognise(app, title, text, selected)`:
|
||||
@@ -73,3 +80,8 @@ synthetic templates that live only in the tests.
|
||||
`household_duplicates(&[(member, names)])`: the subscription merchant keys two or more members share, each
|
||||
with its members. It runs only on names members chose to share into the household group (opt-in, asked once).
|
||||
Nobody's names are read without that.
|
||||
|
||||
`shared_names(state, today)` *(v0.3.0)* is what a member who opted in sends: the **service key** (the first word
|
||||
of the merchant key, at least three letters) of every subscription they still pay (active, or charged after a
|
||||
cancel), sorted, at most 100. Only the key leaves: `PAYPAL *SPOTIFY 4029357733` is shared as `spotify`, never
|
||||
with its merchant text, reference or amount.
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# 03 — Invoices and the tax reserve (v1.1)
|
||||
|
||||
`fiscus-ledger::invoice`: issuing invoices (faktury) from the ledger, finding them paid on a statement, and
|
||||
setting a share of each paid one aside for tax. Pure like the rest: no clock, no randomness; dates and ids are
|
||||
parameters.
|
||||
|
||||
## The supplier
|
||||
`supplier.set` names who issues invoices: name, address (1–4 lines), IČO, DIČ, whether they are a VAT payer, a
|
||||
registration line for the invoice, and the reserve: the thousandths of each paid invoice's amount without VAT
|
||||
set aside for income tax and insurance (0–600, so 0–60 %). A VAT payer must have a DIČ. The latest
|
||||
`supplier.set` counts from then on; an invoice keeps the supplier it was issued under, so changing the reserve
|
||||
never changes an invoice issued before.
|
||||
|
||||
IČO: 8 digits, the last the weighted mod-11 check of the first seven. DIČ: `CZ` and 8–10 digits.
|
||||
|
||||
## An invoice
|
||||
`invoice.issued` carries the whole invoice: id, number, issue and due dates, the taxable-supply date (DUZP, on a
|
||||
VAT invoice only), the customer, 1–50 lines, the budget its payment goes into (`None`: the default one), and
|
||||
the language it is printed in: `cs` or `en`, chosen per invoice (absent: Czech).
|
||||
|
||||
- **Number = variable symbol.** `YYYYNNNN`: the year it was issued and its place in that year
|
||||
(`State::next_invoice_number(year)`). A number is used once. The payment is matched by it.
|
||||
- **A line:** text (1–200), quantity in thousandths (0,001–1 000 000), unit (≤ 10), unit price in haléře,
|
||||
and on a VAT invoice a rate of 21, 12 or 0 %. Its amount is `quantity × price`, rounded half away from
|
||||
zero to the haléř.
|
||||
- **VAT:** per rate, from the base: the base of a rate is the sum of its lines, its VAT `base × rate / 100`
|
||||
rounded once (§ 37 ZDPH). Not per line.
|
||||
- **Total:** 0,01–9 999 999,99 CZK, what QR Platba carries. `State::invoice_spayd` gives the QR Platba of an
|
||||
unpaid invoice: its total, `X-VS` its number, to the account set by `account.set`.
|
||||
|
||||
Every rule is checked when the event is applied; an invoice that breaks one is rejected and changes nothing.
|
||||
|
||||
## Paid
|
||||
`invoice.paid { invoice, payment, on }`: `payment` is the statement line that paid it, or `None` for one marked
|
||||
paid by hand. A line pays one invoice, only of the invoice's exact total, not before the invoice was issued.
|
||||
|
||||
`plan_invoice_payments(state, ids, at)` is what the app runs after an import. For each unpaid invoice, the
|
||||
earliest statement line whose amount is its total and whose variable symbol is its number (leading zeros do
|
||||
not count) pays it: `invoice.paid`, then `payment.categorised` → `income` (unless the person chose a category),
|
||||
then `payment.assigned` → the invoice's budget. Nothing is guessed: a line of another amount, or without the
|
||||
symbol, stays for the person to look at. Run twice, the second plan is empty.
|
||||
|
||||
## The reserve
|
||||
When an invoice is paid, `reserve = VAT + round(net × reserve‰ / 1000)` is set aside: a VAT payer's VAT in full
|
||||
(it is the state's), and the reserve share of the rest. `State::reserve_balance()` is everything set aside less
|
||||
`reserve.withdrawn` (the tax or insurance paid from it), which can never take more than the reserve holds.
|
||||
|
||||
## Cancelling
|
||||
`invoice.cancelled` cancels an unpaid invoice. A paid one stays; a credit note (opravný daňový doklad) is not
|
||||
built yet.
|
||||
|
||||
| Event | Effect |
|
||||
|:--|:--|
|
||||
| `supplier.set` | the supplier from now on |
|
||||
| `invoice.issued` | a new invoice, checked, with its totals |
|
||||
| `invoice.paid` | paid by a statement line or by hand; the reserve set aside |
|
||||
| `invoice.cancelled` | an unpaid invoice withdrawn |
|
||||
| `reserve.withdrawn` | money out of the reserve, at most its balance |
|
||||
@@ -0,0 +1,68 @@
|
||||
# 04 — Spending, category plans and the month in numbers (v0.5.0)
|
||||
|
||||
Pure like the rest: `today` and the month are parameters. Money in haléře; every share is whole thousandths.
|
||||
|
||||
## One definition of spending (`fiscus-insight::spending`)
|
||||
Spending is money out of your own payments (a confirmed pair once), as positive amounts, by category. Money
|
||||
between your own accounts (`transfers`) is not spending; a payment nobody categorised counts as `uncategorised`.
|
||||
Money in is positive payments that are not transfers. Every sum is checked: when one would not fit, the answer
|
||||
is `None`, never a wrong number.
|
||||
|
||||
`permille(parts)` gives each part's share in thousandths by the largest remainder, so the shares add up to
|
||||
exactly 1000 whenever there is anything to share (a pie never has a gap or an overlap). A tie goes to the
|
||||
earlier part; callers order the parts first.
|
||||
|
||||
## Category plans (`category.planned`, `fiscus-insight::plan`)
|
||||
`category.planned { category, amount, from }`: the most you mean to spend on a category in a month, from the
|
||||
month of `from` (always the 1st) on, until a later plan for that category replaces it. You plan once; zero
|
||||
removes the plan. `State::plan_for(category, month)` is the plan from that month or before, the latest month
|
||||
first, then the latest in the log.
|
||||
|
||||
A plan is for a spending category only: not `income`, `transfers` or `uncategorised`, and a category the
|
||||
ledger knows (a default one or one of your own). 0 to 100 000 000 CZK.
|
||||
|
||||
Plans are in your personal log and count **your own payments only**, like the forecast. They are never shared:
|
||||
the sharing boundary (`share.rs`, the app's `outgoing`) builds only `payment.shared` and never copies other
|
||||
events.
|
||||
|
||||
`month_plan(state, month, today)`: per planned category, what you spent this month up to today, what is left
|
||||
(negative when over), the spent share of the plan (capped at 1000, for a bar), and the pace:
|
||||
|
||||
| Pace | When |
|
||||
|:--|:--|
|
||||
| Over | spent more than the whole month's plan |
|
||||
| Ahead | more than 110 % of what the plan allows by today (`plan × day / days in month`) |
|
||||
| On pace | 90–110 % |
|
||||
| Under | below 90 %; for a past month, within the plan |
|
||||
|
||||
Then the categories spent on without a plan (largest first), and the month's totals: planned, spent, and the
|
||||
part of it spent without a plan. A month that has not begun has nothing spent and no pace.
|
||||
|
||||
`suggest(state, today)`: a plan from your history. For each category you can plan, the average spent over the
|
||||
last three complete months, rounded **up** to whole hundreds of crowns. Only months since your first payment
|
||||
count, so a ledger one month old is not divided by three.
|
||||
|
||||
## Categories of your own (`category.created`)
|
||||
`category.created { category, label }`: an id as `categories::is_valid` that is not a default category or one
|
||||
you made before, and a name of 1–40 characters (no spaces around it, no control characters). It can be planned
|
||||
and used like a default one. `State::category_label` and `State::categories()` (the default ones in their order,
|
||||
then yours by id) are what the app lists.
|
||||
|
||||
## The month in numbers (`fiscus-insight::stats`)
|
||||
`month_stats(state, insight, month, today)` for a month that has begun (`None` for one to come):
|
||||
- **slices**: spending by category, the largest 7, then the rest as one slice; thousandths that add up to 1000;
|
||||
- **out, in, net** (in less out);
|
||||
- **months**: the last six, oldest first, ending with this one (up to today);
|
||||
- **same day last month**: spent last month up to the same day (all of it for a past month);
|
||||
- **top merchants**: the 5 you paid most, by merchant key (however the bank writes the name), with the latest
|
||||
name and how many payments; a payment without a merchant is not a merchant;
|
||||
- **subscriptions**: what the subscriptions `analyse` found charged this month, and their share of spending.
|
||||
|
||||
## Tests
|
||||
`fiscus-ledger/tests/plans.rs` (5): a plan carries forward, the latest for a month wins, zero removes it,
|
||||
every refusal (income, transfers, uncategorised, unknown, not an id, negative, over the limit, not the 1st)
|
||||
changes nothing, categories of your own and their refusals, the events round-trip and replay the same.
|
||||
`fiscus-insight/tests/stats.rs` (5) and `spending.rs` (1): the month against its plan with every pace, the
|
||||
suggested plan, the month in numbers, shares that always add up to 1000, and no numbers when a sum would not
|
||||
fit. Three deliberate mistakes (transfers as spending, a plan before its month, no largest remainder) each fail
|
||||
them.
|
||||
@@ -0,0 +1,105 @@
|
||||
# 05: Savings goals, ways to save, challenges and medals (v0.6.0)
|
||||
|
||||
This works like the rest of the core: `today` is a parameter, money is in haléře, and every level is in whole
|
||||
thousandths. **Fiscus never moves money.** A goal holds only what you said you put aside, so it is full only
|
||||
when you filled it. Goals and challenges are in your personal log. They are never shared: the sharing boundary
|
||||
(`share.rs`) builds only `payment.shared`.
|
||||
|
||||
## Goals (`fiscus-ledger::goal`)
|
||||
|
||||
| Event | What |
|
||||
|:--|:--|
|
||||
| `goal.created { goal, name, target, by?, colour }` | a goal |
|
||||
| `goal.changed { goal, name, target, by?, colour }` | its new name, target, date or colour; the latest counts |
|
||||
| `goal.ways_set { goal, ways }` | how it is saved for; replaces its earlier ways |
|
||||
| `goal.saved { goal, saving, amount, on, way? }` | put aside (positive) or taken out (negative), by one of its ways or by hand |
|
||||
| `goal.closed { goal, on }` | reached or given up; no more saving into it, the history stays |
|
||||
|
||||
**What a goal accepts:**
|
||||
- a name of 1–60 characters, with no spaces around it and no control characters;
|
||||
- a target of 1 Kč to 100 000 000 Kč;
|
||||
- at most 20 open goals;
|
||||
- a saving id used once, with an amount that is not zero, and never more taken out than the goal holds;
|
||||
- savings only into an open goal;
|
||||
- a saving made by a way only if the goal is saved for that way.
|
||||
|
||||
**Ways.** A goal has at most one way of each kind:
|
||||
|
||||
| Way | This month it comes to |
|
||||
|:--|:--|
|
||||
| `fixed { amount }` | the amount (1 Kč–100 000 000 Kč) |
|
||||
| `round_up { to }` | each spending payment of the month rounded up to the next `to` (10, 50 or 100 Kč); a payment already a multiple adds nothing |
|
||||
| `leftover { permille }` | that share of what last month's category plans did not use (per planned category, the plan less what was spent, never below 0) |
|
||||
| `income { permille }` | that share of last month's money in (not transfers) |
|
||||
|
||||
A share is 1–1000 thousandths. The open goals' shares of `leftover`, and separately of `income`, add up to at
|
||||
most 1000: together they can never take more than all of it. Closing a goal gives its shares back.
|
||||
|
||||
## A goal this month (`fiscus-insight::goals`)
|
||||
`goals_month(state, insight, today)` returns the open goals in the order they were made, then the closed ones,
|
||||
the latest closed first. Each goal has:
|
||||
- **saved**, **target**, **permille** (the tank's level, at most 1000) and **reached**;
|
||||
- **months_left** from this month to the month of `by`, both included, and **needed_per_month**: what is still
|
||||
needed, divided by those months and rounded up to whole crowns. Once the date has passed, all of what is
|
||||
still needed. Neither is set without a date, or once the goal is reached;
|
||||
- **pace**: put aside per month over the last three complete months, from the month of the first saving on;
|
||||
**reach_month**: the month it gets there at that pace;
|
||||
- **parts**, one per way. Each part has:
|
||||
- what the way comes to this month;
|
||||
- what was already put aside by it this month;
|
||||
- what is **left**. Together the parts never ask for more than the goal still needs: the parts take it in the
|
||||
goal's order of ways.
|
||||
|
||||
The month also has the leftover and the income that the shares are of, how much of each is given to goals, and
|
||||
**sources**, which point at money without changing anything:
|
||||
- **subscriptions** still charging that you have not decided to keep, with their cost a month (a yearly one
|
||||
divided by 12, rounded up). The 5 costliest;
|
||||
- **categories** that cost more last month than their average of the three months before, by at least 10 % and
|
||||
200 Kč. The 3 largest differences.
|
||||
|
||||
## Challenges
|
||||
|
||||
| Event | What |
|
||||
|:--|:--|
|
||||
| `challenge.started { challenge, goal, starts, ends }` | 1–92 days, both ends included; at most 20 running |
|
||||
| `challenge.abandoned { challenge, on }` | given up, once |
|
||||
|
||||
The `goal` of a challenge is one of these:
|
||||
- `spend_under { category, amount }`: a category you spend in (not income, transfers or uncategorised), 1 Kč or
|
||||
more;
|
||||
- `no_spend { category }`;
|
||||
- `cancel { subscription }`: decide to cancel it in the window, and not be charged for it after the decision;
|
||||
- `save { goal, amount }`: put this much aside for an open goal in the window.
|
||||
|
||||
## Rewards (`fiscus-insight::rewards`)
|
||||
`rewards(state, insight, shared_budgets, today)` computes the medals and the challenges from the ledger.
|
||||
Nothing is stored. A medal comes from a **complete** period only:
|
||||
|
||||
| Medal | Earned |
|
||||
|:--|:--|
|
||||
| `under_budget` | a budget under its (latest) limit 3+ complete months running; one medal per run. A shared budget earns none: only your own payments are counted, and its limit is everyone's |
|
||||
| `plans_kept` | a complete month with at least one plan, every plan kept |
|
||||
| `cancelled` | decided "cancel" and not charged since, past the day it would have charged |
|
||||
| `challenge_won` | `spend_under`, `no_spend` and `cancel` on their last day; `save` on the day it was reached |
|
||||
| `invoices_on_time` | a finished quarter in which every invoice due was paid by its due date |
|
||||
| `goal_milestone` | a goal at ¼, ½, ¾ and all of its target, on the day of the saving that got it there |
|
||||
| `saving_streak` | money put aside (more in than out across the goals) in 3+ complete months running |
|
||||
|
||||
The outcome of a challenge:
|
||||
- **Lost** as soon as it cannot be won: spending over the limit, any spending in a `no_spend` category, or a
|
||||
charge after the cancel decision;
|
||||
- **Abandoned** when given up, except a `save` challenge already reached, which stays won.
|
||||
|
||||
Its tank:
|
||||
- `spend_under`: what is left of the limit;
|
||||
- `no_spend`: full until anything is spent;
|
||||
- `cancel`: full once you decide to cancel and nothing has charged since;
|
||||
- `save`: what is saved of the amount.
|
||||
|
||||
**Progress** shows how far the medals not yet earned are:
|
||||
- months running with money put aside, and whether anything was put aside this month;
|
||||
- each budget's months running under its limit;
|
||||
- each open goal's level and its next milestone.
|
||||
|
||||
## The cancel kit in Czech
|
||||
`cancel_kit_in(subscription, language)` writes the email in Czech or English. `cancel_kit` stays English.
|
||||
@@ -0,0 +1,65 @@
|
||||
# 06: Projects (v0.7.0)
|
||||
|
||||
Projects plan and track a piece of work: a renovation or a trip (**simple**), or a side business or client work
|
||||
(**business**). A project is a **second label on payments**: a payment in a project still counts in its budget and
|
||||
its month, so nothing is counted twice. Projects live in the personal log, and the sharing boundary (`share.rs`)
|
||||
still builds only `payment.shared`.
|
||||
|
||||
## Events (`fiscus-ledger::project`)
|
||||
| Event | What |
|
||||
|:--|:--|
|
||||
| `project.created { project, name, kind, template?, starts?, ends?, colour, rate? }` | simple or business; a template id the app knows; an hourly rate for a business |
|
||||
| `project.changed { … }` | the latest counts. Once a project has phases or time it stays business |
|
||||
| `project.status_set { project, status, on }` | planning, active, on hold, done (`on` is the day) |
|
||||
| `project.line_set { project, line, name, planned }` | a budget line; a planned amount of 0 removes it |
|
||||
| `project.phase_set` / `project.phase_removed` | a business project's phase with dates; one still holding tasks is not removed |
|
||||
| `payment.projected { payment, project, line? }` / `payment.unprojected` | one project per payment, into an open project |
|
||||
| `project.rule_set { merchant_key, project? }` | "always this merchant → this project": payments within the project's dates, while it is open |
|
||||
| `task.created { task, project, fields }` / `task.changed` / `task.status_set` | title, phase, due, estimate, line, assignee, milestone; to do, doing, done (with the day) |
|
||||
| `time.logged { entry, project, task?, minutes, on, rate, note }` / `time.removed` | business only; invoiced time is not removed |
|
||||
| `invoice.projected { invoice, project, entries }` | an invoice for a business project, and the time entries it bills (each once) |
|
||||
| `project.shared { project, budget }` / `project.unshared { project }` | shared with a shared budget's members, one budget at a time; the app mirrors the name, dates, status, lines, phases and tasks through that budget's log, never time, invoices or project rules. Unshared, the members keep their copy |
|
||||
|
||||
**What each event accepts:**
|
||||
- names: 1–60 characters, task titles 1–120, assignees 1–40;
|
||||
- amounts: 0–100 000 000 Kč;
|
||||
- hourly rates: 0–100 000 Kč;
|
||||
- dates: a project or phase cannot end before it starts;
|
||||
- at most 50 projects open, 100 budget lines, 50 phases and 200 open tasks per project;
|
||||
- time: at most 24 hours a day across all projects.
|
||||
|
||||
Every refusal changes nothing.
|
||||
|
||||
**Time** is minutes × the rate per hour, rounded half up to the haléř once per entry. Weeks start on Monday
|
||||
(`project::week_of`).
|
||||
|
||||
## A project's numbers (`fiscus-insight::projects`)
|
||||
`projects(state, today)` returns a summary per project: the open projects in the order they were made, then the
|
||||
done ones, the latest first. `project(state, id, today)` adds the details.
|
||||
|
||||
**What a summary holds:**
|
||||
- **planned**: all budget lines together.
|
||||
- **spent**: money out of the payments in the project, positive; transfers do not count.
|
||||
- **unplanned**: spent outside any line.
|
||||
- **lines**: planned, spent, left and over for each.
|
||||
- **income** (business):
|
||||
- paid invoices of the project, without VAT;
|
||||
- money in put into the project, except a statement line that paid one of the project's invoices: that line
|
||||
*is* the invoice, so it counts once.
|
||||
|
||||
If an invoice is marked paid by hand, its money in stays out of the project.
|
||||
- **profit**: income − spent. **margin**: profit of income, in thousandths.
|
||||
- **progress**: tasks done, by their estimates when every task has one, else by count.
|
||||
- **forecast**: spent + the open tasks' estimates.
|
||||
- **over budget**: spent or the forecast above the plan. One line over is not the project over.
|
||||
- **late**: an open task past its due date, or the project past its end with tasks open. A done project is never
|
||||
late.
|
||||
- **time**:
|
||||
- minutes, billable and unbilled;
|
||||
- time by task, and by week.
|
||||
|
||||
**Medals** (`rewards`), for a project that is done:
|
||||
- *Project on budget*: it had a plan, and it spent no more;
|
||||
- *Finished on time*: it had an end date, and it was done by it.
|
||||
|
||||
Both are earned on the day it was done.
|
||||
@@ -0,0 +1,40 @@
|
||||
# 07 · Receipts
|
||||
|
||||
A receipt becomes a payment, or fills in one you have. The image is read by an OCR outside the core (Lector, on
|
||||
the PC or the phone, in the app); the core gets its words and reads the fields, and keeps the result.
|
||||
|
||||
## Reading (`fiscus_capture::receipt`)
|
||||
Input: the OCR's lines of words, each word with its box (pixels of the upright image) and its confidence in
|
||||
**thousandths** (0–1000; the app converts, so no float enters the core). Output: a `Receipt` with the fields it
|
||||
found, each with its boxes and `sure` (every word read with confidence ≥ 800).
|
||||
|
||||
What every Czech receipt must show, found **by its label, never by a shop's layout**:
|
||||
|
||||
| Field | How |
|
||||
|:--|:--|
|
||||
| total | the rightmost amount on a line labelled `K úhradě`, `Částka k úhradě`, `Celkem k úhradě` (best), `Celkem`, `Celková částka`, `Celkem Kč` (next), `Suma`, `Total`; or alone on the line after the label. A line with `DPH`, `Základ`, `Sazba`, `Mezisoučet`, `Zaokrouhlení` or `Vráceno` is never the total. Among equals, the larger. `1 284,90`, `1284.90`, groups split over words; read from text into haléře; over 10 000 000 Kč is refused whole, never read as its tail |
|
||||
| date, time | `16.11.2026`, `16. 11. 2026`, `16.11.26`, `2026-11-16`, `16/11/2026` (years 2000–2100); `14:32[:05]`. A date with a time on its line first |
|
||||
| IČO | 8 digits after `IČ`/`IČO`, with the weighted mod-11 check digit (`invoice::ico_ok`); else from a company DIČ (`CZ` + the IČO) |
|
||||
| DIČ | `CZ` and 8–10 digits, in one word or two |
|
||||
| shop | the first line from the top with three letters or more, more letters than twice its digits, and no label (`IČ`, `DIČ`, `Tel`, a web or email address…), above the IČO's line (or among the first six). All capitals become Title Case. **Always `sure: false`**: you check it |
|
||||
|
||||
Nothing found is an empty `Receipt`, not an error. Hostile input is bounded: at most 600 lines, 120 words a line,
|
||||
80 characters a word (else `TooLarge`); control characters are dropped. A proptest feeds random text.
|
||||
|
||||
**No shop templates.** As with bank statements, no rule specific to one shop's receipts is written without real
|
||||
samples of them (`fixtures/receipts/`, none yet).
|
||||
|
||||
## In the ledger
|
||||
- `payment.receipt_attached { payment, receipt: { shop, ico, dic } }` attaches it to any payment (captured, imported,
|
||||
added; on a confirmed pair it shows on the one payment). Checked: the shop 1–100 characters, trimmed, no control
|
||||
characters; a valid IČO and DIČ. A later one replaces it.
|
||||
- **The payment keeps its merchant and merchant key**, so the rules that bring a category stay as they are; the
|
||||
apps show the shop's name from the receipt.
|
||||
- `State::known_shop(ico)`: your latest receipt with that IČO, its name and that payment's category. A shop you have
|
||||
confirmed once is named and categorised from then on.
|
||||
- `State::receipt_match(total, date)`: the one outflow of exactly that amount within 3 days (`MATCH_DAYS`) that has
|
||||
no receipt yet. Two or more, or none: `None`, and the receipt is a payment of its own. Nothing is guessed.
|
||||
|
||||
## From the phone
|
||||
The Android app reads the receipt itself and posts only the fields, as the iPhone Shortcut's post with
|
||||
`"source": "receipt"` and optional `ico` and `dic` (docs/02_capture_sharing.md). The photo never leaves the phone.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Receipt samples
|
||||
|
||||
Real receipts, **redacted**, as the OCR read them: never the photo (no binaries in git). For each receipt:
|
||||
|
||||
```
|
||||
fixtures/receipts/<shop>-<n>.ocr.json # the OCR's lines of words: [[{"text","confidence","bbox":{x,y,w,h}}]]
|
||||
fixtures/receipts/<shop>-<n>.expected.json # what fiscus_capture::receipt::read must find
|
||||
```
|
||||
|
||||
Black out card numbers, loyalty numbers and anything personal on the photo **before** it is read; keep the rest
|
||||
as printed. The photos themselves stay outside git. A rule specific to one shop is written only from its samples
|
||||
here.
|
||||
|
||||
None yet.
|
||||
Reference in New Issue
Block a user