Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 26ba18ac28 | |||
| 95c6bf54ed | |||
| ec9519a234 | |||
| 507eb62216 | |||
| c6805aea8f |
@@ -1,6 +1,6 @@
|
|||||||
# FiscusPublic
|
# 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.
|
(`https://gitea.marek-novak.cz/mnovak/Fiscus.git`) depends on it **by git tag**, never by path.
|
||||||
|
|
||||||
## Pure
|
## Pure
|
||||||
|
|||||||
Generated
+4
-4
@@ -139,7 +139,7 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fiscus-capture"
|
name = "fiscus-capture"
|
||||||
version = "0.8.0"
|
version = "0.9.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"fiscus-ledger",
|
"fiscus-ledger",
|
||||||
"proptest",
|
"proptest",
|
||||||
@@ -150,7 +150,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fiscus-insight"
|
name = "fiscus-insight"
|
||||||
version = "0.8.0"
|
version = "0.9.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"fiscus-ledger",
|
"fiscus-ledger",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -159,7 +159,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fiscus-ledger"
|
name = "fiscus-ledger"
|
||||||
version = "0.8.0"
|
version = "0.9.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proptest",
|
"proptest",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -169,7 +169,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fiscus-statement"
|
name = "fiscus-statement"
|
||||||
version = "0.8.0"
|
version = "0.9.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"encoding_rs",
|
"encoding_rs",
|
||||||
"fiscus-ledger",
|
"fiscus-ledger",
|
||||||
|
|||||||
+2
-2
@@ -3,9 +3,9 @@ resolver = "2"
|
|||||||
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
|
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.8.0"
|
version = "0.9.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MPL-2.0"
|
license = "CPAL-1.0"
|
||||||
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
|
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[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"
|
1.0.1 “Commercial Use” means distribution or otherwise making the Covered Code available to a third party.
|
||||||
means each individual or legal entity that creates, contributes to
|
|
||||||
the creation of, or owns Covered Software.
|
|
||||||
|
|
||||||
1.2. "Contributor Version"
|
1.1 “Contributor” means each entity that creates or contributes to the creation of Modifications.
|
||||||
means the combination of the Contributions of others (if any) used
|
|
||||||
by a Contributor and that particular Contributor's Contribution.
|
|
||||||
|
|
||||||
1.3. "Contribution"
|
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.
|
||||||
means Covered Software of a particular Contributor.
|
|
||||||
|
|
||||||
1.4. "Covered Software"
|
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.
|
||||||
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.5. "Incompatible With Secondary Licenses"
|
1.4 “Electronic Distribution Mechanism” means a mechanism generally accepted in the software development community for the electronic transfer of data.
|
||||||
means
|
|
||||||
|
|
||||||
(a) that the initial Contributor has attached the notice described
|
1.5 “Executable” means Covered Code in any form other than Source Code.
|
||||||
in Exhibit B to the Covered Software; or
|
|
||||||
|
|
||||||
(b) that the Covered Software was made available under the terms of
|
1.6 “Initial Developer” means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A.
|
||||||
version 1.1 or earlier of the License, but not also under the
|
|
||||||
terms of a Secondary License.
|
|
||||||
|
|
||||||
1.6. "Executable 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.
|
||||||
means any form of the work other than Source Code Form.
|
|
||||||
|
|
||||||
1.7. "Larger Work"
|
1.8 “License” means this document.
|
||||||
means a work that combines Covered Software with other material, in
|
|
||||||
a separate file or files, that is not Covered Software.
|
|
||||||
|
|
||||||
1.8. "License"
|
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.
|
||||||
means this document.
|
|
||||||
|
|
||||||
1.9. "Licensable"
|
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:
|
||||||
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.10. "Modifications"
|
A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications.
|
||||||
means any of the following:
|
|
||||||
|
|
||||||
(a) any file in Source Code Form that results from an addition to,
|
B. Any new file that contains any part of the Original Code or previous Modifications.
|
||||||
deletion from, or modification of the contents of Covered
|
|
||||||
Software; or
|
|
||||||
|
|
||||||
(b) any new file in Source Code Form that contains any Covered
|
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.
|
||||||
Software.
|
|
||||||
|
|
||||||
1.11. "Patent Claims" of a Contributor
|
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.
|
||||||
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.12. "Secondary License"
|
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.
|
||||||
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.13. "Source Code Form"
|
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.
|
||||||
means the form of the work preferred for making modifications.
|
|
||||||
|
|
||||||
1.14. "You" (or "Your")
|
2. Source Code License.
|
||||||
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. 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,
|
(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).
|
||||||
non-exclusive license:
|
|
||||||
|
|
||||||
(a) under intellectual property rights (other than patent or trademark)
|
(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.
|
||||||
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
|
|
||||||
|
|
||||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
(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.
|
||||||
for sale, have made, import, and otherwise transfer either its
|
|
||||||
Contributions or its Contributor Version.
|
|
||||||
|
|
||||||
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
|
(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
|
||||||
become effective for each Contribution on the date the Contributor first
|
|
||||||
distributes such Contribution.
|
|
||||||
|
|
||||||
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
|
(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.
|
||||||
this License. No additional rights or licenses will be implied from the
|
|
||||||
distribution or licensing of Covered Software under this License.
|
(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.
|
||||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
|
||||||
Contributor:
|
3. Distribution Obligations.
|
||||||
|
|
||||||
(a) for any code that a Contributor has removed from Covered Software;
|
3.1 Application of License.
|
||||||
or
|
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.
|
||||||
|
|
||||||
(b) for infringements caused by: (i) Your and any other third party's
|
3.2 Availability of Source Code.
|
||||||
modifications of Covered Software, or (ii) the combination of its
|
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.
|
||||||
Contributions with other software (except as part of its Contributor
|
|
||||||
Version); or
|
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.
|
||||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
|
||||||
its Contributions.
|
3.4 Intellectual Property Matters
|
||||||
|
|
||||||
This License does not grant any rights in the trademarks, service marks,
|
(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.
|
||||||
or logos of any Contributor (except as may be necessary to comply with
|
|
||||||
the notice requirements in Section 3.4).
|
(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.
|
||||||
|
|
||||||
2.4. Subsequent Licenses
|
(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.
|
||||||
|
|
||||||
No Contributor makes additional grants as a result of Your choice to
|
3.5 Required Notices.
|
||||||
distribute the Covered Software under a subsequent version of this
|
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.
|
||||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
|
||||||
permitted under the terms of Section 3.3).
|
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.
|
||||||
2.5. Representation
|
|
||||||
|
3.7 Larger Works.
|
||||||
Each Contributor represents that the Contributor believes its
|
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.
|
||||||
Contributions are its original creation(s) or it has sufficient rights
|
|
||||||
to grant the rights to its Contributions conveyed by this License.
|
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.
|
||||||
2.6. Fair Use
|
|
||||||
|
5. Application of this License.
|
||||||
This License is not intended to limit any rights You have under
|
This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code.
|
||||||
applicable copyright doctrines of fair use, fair dealing, or other
|
|
||||||
equivalents.
|
6. Versions of the License.
|
||||||
|
|
||||||
2.7. Conditions
|
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.
|
||||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
|
||||||
in Section 2.1.
|
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.
|
||||||
3. Responsibilities
|
|
||||||
-------------------
|
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.)
|
||||||
3.1. Distribution of Source Form
|
|
||||||
|
7. DISCLAIMER OF WARRANTY.
|
||||||
All distribution of Covered Software in Source Code Form, including any
|
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.
|
||||||
Modifications that You create or to which You contribute, must be under
|
|
||||||
the terms of this License. You must inform recipients that the Source
|
8. TERMINATION.
|
||||||
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
|
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.
|
||||||
attempt to alter or restrict the recipients' rights in the Source Code
|
|
||||||
Form.
|
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:
|
||||||
|
|
||||||
3.2. Distribution of Executable Form
|
(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.
|
||||||
|
|
||||||
If You distribute Covered Software in Executable Form then:
|
(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.
|
||||||
|
|
||||||
(a) such Covered Software must also be made available in Source Code
|
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.
|
||||||
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
|
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.
|
||||||
Form by reasonable means in a timely manner, at a charge no more
|
|
||||||
than the cost of distribution to the recipient; and
|
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.
|
||||||
(b) You may distribute such Executable Form under the terms of this
|
|
||||||
License, or sublicense it under different terms, provided that the
|
10. U.S. GOVERNMENT END USERS.
|
||||||
license for the Executable Form does not attempt to limit or alter
|
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.
|
||||||
the recipients' rights in the Source Code Form under this License.
|
|
||||||
|
11. MISCELLANEOUS.
|
||||||
3.3. Distribution of a Larger Work
|
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.
|
||||||
|
|
||||||
You may create and distribute a Larger Work under terms of Your choice,
|
12. RESPONSIBILITY FOR CLAIMS.
|
||||||
provided that You also comply with the requirements of this License for
|
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.
|
||||||
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
|
13. MULTIPLE-LICENSED CODE.
|
||||||
Covered Software is not Incompatible With Secondary Licenses, this
|
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.
|
||||||
License permits You to additionally distribute such Covered Software
|
|
||||||
under the terms of such Secondary License(s), so that the recipient of
|
14. ADDITIONAL TERM: ATTRIBUTION
|
||||||
the Larger Work may, at their option, further distribute the Covered
|
|
||||||
Software under the terms of either this License or such Secondary
|
(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.
|
||||||
License(s).
|
|
||||||
|
(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”).
|
||||||
3.4. Notices
|
|
||||||
|
(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.
|
||||||
You may not remove or alter the substance of any license notices
|
|
||||||
(including copyright notices, patent notices, disclaimers of warranty,
|
(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.
|
||||||
or limitations of liability) contained within the Source Code Form of
|
|
||||||
the Covered Software, except that You may alter any license notices to
|
15. ADDITIONAL TERM: NETWORK USE.
|
||||||
the extent required to remedy known factual inaccuracies.
|
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.
|
||||||
|
|
||||||
3.5. Application of Additional Terms
|
EXHIBIT A. Common Public Attribution License Version 1.0.
|
||||||
|
|
||||||
You may choose to offer, and to charge a fee for, warranty, support,
|
"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.
|
||||||
indemnity or liability obligations to one or more recipients of Covered
|
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.
|
||||||
Software. However, You may do so only on Your own behalf, and not on
|
The Original Code is FiscusPublic.
|
||||||
behalf of any Contributor. You must make it absolutely clear that any
|
The Original Developer is the Initial Developer.
|
||||||
such warranty, support, indemnity, or liability obligation is offered by
|
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.
|
||||||
You alone, and You hereby agree to indemnify every Contributor for any
|
Contributor: none."
|
||||||
liability incurred by such Contributor as a result of warranty, support,
|
|
||||||
indemnity or liability terms You offer. You may include additional
|
EXHIBIT B. Attribution Information
|
||||||
disclaimers of warranty and limitations of liability specific to any
|
|
||||||
jurisdiction.
|
Attribution Copyright Notice: Copyright (c) 2026 Marek Novák
|
||||||
|
Attribution Phrase (not exceeding 10 words): Built on Domi
|
||||||
4. Inability to Comply Due to Statute or Regulation
|
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.
|
||||||
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.
|
|
||||||
@@ -12,4 +12,22 @@ subscription / price-change / trial detection and a seeded month-end forecast. N
|
|||||||
|
|
||||||
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`.
|
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 amount;
|
||||||
pub mod notification;
|
pub mod notification;
|
||||||
|
pub mod receipt;
|
||||||
pub mod shortcut;
|
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.
|
/// One card payment a phone saw: an outflow, so `amount` is negative.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
@@ -15,6 +16,8 @@ pub struct Capture {
|
|||||||
pub at: Timestamp,
|
pub at: Timestamp,
|
||||||
pub merchant: String,
|
pub merchant: String,
|
||||||
pub card: Option<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.
|
/// 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)) {
|
if card.is_some_and(|c| !card_ok(c)) {
|
||||||
return None;
|
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:
|
//! 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 crate::{amount, card_ok, merchant_ok, Capture};
|
||||||
use fiscus_ledger::{Date, Timestamp};
|
use fiscus_ledger::{Date, ReceiptInfo, Timestamp};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::value::RawValue;
|
use serde_json::value::RawValue;
|
||||||
|
|
||||||
@@ -25,6 +27,10 @@ pub enum CaptureError {
|
|||||||
Card,
|
Card,
|
||||||
#[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")]
|
#[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")]
|
||||||
Time,
|
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)]
|
#[derive(Deserialize)]
|
||||||
@@ -36,6 +42,9 @@ struct Post<'a> {
|
|||||||
card: String,
|
card: String,
|
||||||
time: String,
|
time: String,
|
||||||
currency: Option<String>,
|
currency: Option<String>,
|
||||||
|
source: Option<String>,
|
||||||
|
ico: Option<String>,
|
||||||
|
dic: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One post → one capture, or the first thing wrong with it.
|
/// 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);
|
return Err(CaptureError::Card);
|
||||||
}
|
}
|
||||||
let (date, at) = parse_time(&post.time).ok_or(CaptureError::Time)?;
|
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();
|
let card = post.card.trim();
|
||||||
Ok(Capture {
|
Ok(Capture {
|
||||||
amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?,
|
amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?,
|
||||||
@@ -70,6 +89,7 @@ pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
|
|||||||
at,
|
at,
|
||||||
merchant: post.merchant.trim().to_string(),
|
merchant: post.merchant.trim().to_string(),
|
||||||
card: (!card.is_empty()).then(|| card.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());
|
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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -87,6 +87,10 @@ pub enum EventBody {
|
|||||||
PaymentAssigned { payment: PaymentId, budget: BudgetId },
|
PaymentAssigned { payment: PaymentId, budget: BudgetId },
|
||||||
#[serde(rename = "payment.trial_marked")]
|
#[serde(rename = "payment.trial_marked")]
|
||||||
PaymentTrialMarked { payment: PaymentId, ends: Date },
|
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")]
|
#[serde(rename = "budget.created")]
|
||||||
BudgetCreated { budget: BudgetId, name: String, limit: Haler },
|
BudgetCreated { budget: BudgetId, name: String, limit: Haler },
|
||||||
/// A shared budget in a personal log (created here or joined): like `budget.created`, but never the
|
/// A shared budget in a personal log (created here or joined): like `budget.created`, but never the
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ pub mod merchant;
|
|||||||
pub mod money;
|
pub mod money;
|
||||||
pub mod pay;
|
pub mod pay;
|
||||||
pub mod project;
|
pub mod project;
|
||||||
|
pub mod receipt;
|
||||||
pub mod share;
|
pub mod share;
|
||||||
pub mod split;
|
pub mod split;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
@@ -20,4 +21,5 @@ pub mod state;
|
|||||||
pub use date::{Date, Timestamp};
|
pub use date::{Date, Timestamp};
|
||||||
pub use event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, Settlement, SplitId};
|
pub use event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, Settlement, SplitId};
|
||||||
pub use money::Haler;
|
pub use money::Haler;
|
||||||
|
pub use receipt::{KnownShop, ReceiptInfo};
|
||||||
pub use state::{EffectivePayment, Glyph, Origin, ShareView, State};
|
pub use state::{EffectivePayment, Glyph, Origin, ShareView, State};
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
|
|||||||
use crate::merchant::merchant_key;
|
use crate::merchant::merchant_key;
|
||||||
use crate::money::Haler;
|
use crate::money::Haler;
|
||||||
use crate::pay::{spayd, Iban};
|
use crate::pay::{spayd, Iban};
|
||||||
|
use crate::receipt::ReceiptInfo;
|
||||||
use crate::split::Share;
|
use crate::split::Share;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
@@ -67,6 +68,9 @@ pub struct PaymentRecord {
|
|||||||
pub category: Option<Stamped<Category>>,
|
pub category: Option<Stamped<Category>>,
|
||||||
pub budget: Option<Stamped<BudgetId>>,
|
pub budget: Option<Stamped<BudgetId>>,
|
||||||
pub trial_ends: Option<Stamped<Date>>,
|
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.
|
/// The other half of a confirmed pair.
|
||||||
pub partner: Option<PaymentId>,
|
pub partner: Option<PaymentId>,
|
||||||
}
|
}
|
||||||
@@ -272,6 +276,9 @@ pub struct EffectivePayment {
|
|||||||
pub category_source: CategorySource,
|
pub category_source: CategorySource,
|
||||||
pub budget: Option<BudgetId>,
|
pub budget: Option<BudgetId>,
|
||||||
pub trial_ends: Option<Date>,
|
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.
|
/// A person's name, or one shared subscription name.
|
||||||
@@ -422,6 +429,7 @@ impl State {
|
|||||||
category: None,
|
category: None,
|
||||||
budget: None,
|
budget: None,
|
||||||
trial_ends: None,
|
trial_ends: None,
|
||||||
|
receipt: None,
|
||||||
partner: None,
|
partner: None,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -452,6 +460,7 @@ impl State {
|
|||||||
category: None,
|
category: None,
|
||||||
budget: None,
|
budget: None,
|
||||||
trial_ends: None,
|
trial_ends: None,
|
||||||
|
receipt: None,
|
||||||
partner: None,
|
partner: None,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -480,6 +489,7 @@ impl State {
|
|||||||
category: category.clone().map(|value| Stamped { seq, value }),
|
category: category.clone().map(|value| Stamped { seq, value }),
|
||||||
budget: None,
|
budget: None,
|
||||||
trial_ends: None,
|
trial_ends: None,
|
||||||
|
receipt: None,
|
||||||
partner: None,
|
partner: None,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -514,6 +524,10 @@ impl State {
|
|||||||
EventBody::PaymentTrialMarked { payment, ends } => {
|
EventBody::PaymentTrialMarked { payment, ends } => {
|
||||||
self.payment_mut(payment)?.trial_ends = Some(Stamped { seq, value: *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 } => {
|
EventBody::BudgetCreated { budget, name, limit } | EventBody::BudgetShared { budget, name, limit } => {
|
||||||
if budget.is_empty() || self.budgets.contains_key(budget) {
|
if budget.is_empty() || self.budgets.contains_key(budget) {
|
||||||
return Err("a budget with this id exists");
|
return Err("a budget with this id exists");
|
||||||
@@ -595,6 +609,7 @@ impl State {
|
|||||||
category: category.clone().map(|value| Stamped { seq, value }),
|
category: category.clone().map(|value| Stamped { seq, value }),
|
||||||
budget: Some(Stamped { seq, value: budget.clone() }),
|
budget: Some(Stamped { seq, value: budget.clone() }),
|
||||||
trial_ends: None,
|
trial_ends: None,
|
||||||
|
receipt: None,
|
||||||
partner: None,
|
partner: None,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -1346,6 +1361,8 @@ impl State {
|
|||||||
category_source,
|
category_source,
|
||||||
budget,
|
budget,
|
||||||
trial_ends: latest(&p.trial_ends, partner.map(|q| &q.trial_ends)),
|
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,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.categorised` | an explicit category for one payment |
|
||||||
| `payment.assigned` | puts a payment into a budget |
|
| `payment.assigned` | puts a payment into a budget |
|
||||||
| `payment.trial_marked` | "this is a trial", with its end date |
|
| `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 |
|
| `budget.created` / `budget.limit_set` | a monthly budget and its limit |
|
||||||
| `rule.created` | "always <merchant> → <category>" |
|
| `rule.created` | "always <merchant> → <category>" |
|
||||||
| `subscription.decided` | keep or cancel, for a merchant, at the amount seen when deciding |
|
| `subscription.decided` | keep or cancel, for a merchant, at the amount seen when deciding |
|
||||||
|
|||||||
@@ -50,6 +50,9 @@ with exactly `amount`, `merchant`, `card`, `time`, plus an optional `currency`.
|
|||||||
- `merchant`: 1–200 characters, no control characters. `card`: 0–60 characters.
|
- `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.
|
- `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.
|
- 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.
|
*(assumption)* Apple's exact `amount` text is checked against the first real post.
|
||||||
|
|
||||||
**Android bank notifications.** `recognise(app, title, text, selected)`:
|
**Android bank notifications.** `recognise(app, title, text, selected)`:
|
||||||
|
|||||||
@@ -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