├── .gitignore ├── LICENSE ├── README.md ├── bump.sh ├── docs ├── budgeting.md └── clearing.md ├── pyproject.toml ├── refried ├── __init__.py ├── extensions │ ├── accts_ext │ │ ├── __init__.py │ │ └── templates │ │ │ └── AcctsExt.html │ ├── avail_ext │ │ ├── __init__.py │ │ └── templates │ │ │ └── AvailExt.html │ └── journal_ext │ │ ├── __init__.py │ │ └── templates │ │ └── JournalExt.html ├── plugins │ ├── README.md │ ├── clearing.py │ ├── conversions.py │ ├── effective_date.py │ ├── evensplit.py │ ├── pullfrom.py │ ├── rebudget.py │ ├── tracking.py │ └── wishfarm.py └── scripts │ └── hello.py └── tests ├── __init__.py ├── test_clearing.py ├── test_evensplit.py ├── test_period.py ├── test_rebudget.py ├── test_refried.py └── test_utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | dist/ 3 | *.egg-info/ 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # refried 2 | 3 | A collection of plugins and scripts for 4 | [beancount](https://github.com/beancount/beancount) and 5 | [fava](https://github.com/beancount/fava) for monthly budgeting. 6 | Budgeting-related plugins inspired by 7 | [You Need a Budget](https://www.youneedabudget.com). 8 | 9 | ## Installation 10 | 11 | Install this plugin from PyPI: 12 | 13 | ```bash 14 | pip install beancount-refried 15 | ``` 16 | 17 | Alternatively, if you want to be able to edit the plugins locally, 18 | you can clone this repository then run the following from within 19 | the root of the repository: 20 | 21 | ```bash 22 | pip install -e . 23 | ``` 24 | 25 | The Fava extensions are currently tested against fava v1.26.1; you may have errors when using other versions. 26 | 27 | ## Quick start 28 | 29 | Enable the `rebudget` beancount plugin and the `avail_ext` fava extension 30 | by adding the following lines to your beancount file: 31 | 32 | ``` 33 | plugin "refried.plugins.rebudget" 34 | 2020-01-01 custom "fava-extension" "refried.extensions.avail_ext" 35 | ``` 36 | 37 | This will add a new report "Budget" to fava. The `rebudget` plugin is 38 | required for it to function properly. 39 | 40 | See the document on [YNAB-style budgeting](docs/budgeting.md) for details. 41 | 42 | ## Customization 43 | 44 | The fava extensions allow you to specify more user friendly names by using a 45 | `name: ` metadata on an account's `open` directive. 46 | 47 | You can also influence the ordering of displayed accounts using an `ordering: 48 | ` metadata on an account's `open` directive if you don't want the 49 | default alphabetic ordering. 50 | You can also use Decimals or strings of the form "....." 51 | to easily insert new accounts between two adjacent accounts. 52 | For example, "23.64.2" would be ordered between "23.64" and "23.65". 53 | 54 | Some of the plugins/extensions may currently make assumptions about currency (USD) and 55 | various account names. 56 | 57 | ## Attribution 58 | 59 | refried includes content based off of files from 60 | https://github.com/redstreet/beancount_reds_plugins, licensed under GPL3. 61 | -------------------------------------------------------------------------------- /bump.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -eu 3 | 4 | pytest 5 | 6 | poetry version "$@" 7 | version=$(grep '^version' pyproject.toml | sed -E 's/^version = "(.*)"/\1/') 8 | sed -i "s/__version__ =.*/__version__ = '$version'/" refried/__init__.py 9 | sed -i "s/__version__ =.*/__version__ == '$version'/" tests/test_refried.py 10 | 11 | rm -rf dist 12 | poetry build -f sdist 13 | tar xf dist/beancount-refried-*.tar.gz --strip-components=1 14 | -------------------------------------------------------------------------------- /docs/budgeting.md: -------------------------------------------------------------------------------- 1 | # YNAB-style budgeting 2 | 3 | This document describes how to do YNAB-style budgeting with the help of the `avail_ext` fava extension. 4 | 5 | ## Necessary plugins 6 | 7 | Enable the `rebudget` beancount plugin and the `avail_ext` fava extension 8 | by adding the following lines to your beancount file: 9 | 10 | ``` 11 | plugin "refried.plugins.rebudget" 12 | 2020-01-01 custom "fava-extension" "refried.extensions.avail_ext" 13 | ``` 14 | 15 | This will add a new report "Budget" to fava. The `rebudget` plugin is 16 | required for it to function properly. 17 | 18 | ## Usage 19 | 20 | The "Budget" extension will display all of your Income and Expense accounts, by month. 21 | In the style of YNAB, each account has three columns: "Budgeted", "Spent", and "Available". 22 | 23 | Normal transactions will show up under the "Spent" columns of their respective Expense accounts. 24 | No need to do anything special! 25 | 26 | To (re)budget between Expense accounts, simply create a new transaction transferring money 27 | between Income/Expense accounts. Due to the nature of double-entry bookkeeping, the signs 28 | will be the opposite of what you might expect! 29 | 30 | For example, suppose you have $3000 in unbudgeted income and you want to fill out your budget for the upcoming month: 31 | 32 | ``` 33 | 2020-02-01 "Budgeting for February" 34 | Income:To-be-budgeted 2,000 USD 35 | Expenses:Obligations:Rent -1,000 USD 36 | Expenses:Obligations:Utilities -100 USD 37 | Expenses:Necessities:Groceries -200 USD 38 | Expenses:Fun-money:Video-games -700 USD 39 | ``` 40 | 41 | Remember, the signs appear swapped! This takes $2000 _out_ of the "To be budgeted" account and moves money _into_ the expense account categories. 42 | 43 | Later, if you realize that you need more money for groceries (and don't need nearly as much for video games), you can rebudget money like so: 44 | 45 | ``` 46 | 2020-02-13 "Need more money for fancy home dinner plans" 47 | Expenses:Necessities:Groceries -300 USD 48 | Expenses:Fun-money:Video-games 300 USD 49 | ``` 50 | 51 | Understandably, this will wreak havoc with your (non-budgeting) expense reports. This is where the `rebudget` plugin comes in! 52 | For any transaction that don't involve an Assets or Liabilities account, such as the ones above, the `rebudget` plugin will 53 | automatically apply the tag `#rebudget`. So by filtering out the `#rebudget` tag you will have the correct data to use for your usual reports! 54 | (In fava you can use the search filter `-#rebudget`.) 55 | 56 | ## YNAB-style account views 57 | 58 | If you also want YNAB-style account views with "Working" vs "Cleared" totals and cleared vs uncleared postings, see the [YNAB-style account views](clearing.md) document. 59 | -------------------------------------------------------------------------------- /docs/clearing.md: -------------------------------------------------------------------------------- 1 | # YNAB-style account views 2 | 3 | This document describes how to set up YNAB-style account views with "Working" vs "Cleared" amounts 4 | with the help of the `accts_ext` and `journal_ext` fava extensions. 5 | 6 | ## Necessary plugins 7 | 8 | Enable the `clearing` beancount plugin, as well as the `accts_ext` and `journal_ext` fava extensions 9 | by adding the following lines to your beancount file: 10 | 11 | ``` 12 | plugin "refried.plugins.clearing" 13 | 2020-01-01 custom "fava-extension" "refried.extensions.accts_ext" 14 | 2020-01-01 custom "fava-extension" "refried.extensions.journal_ext" 15 | ``` 16 | 17 | This will add a new report "Accounts" to fava. It will also add a report "Journal" but you shouldn't use it directly. 18 | The `clearing` plugin is required for both of these to function properly. 19 | 20 | ## Usage 21 | 22 | The "Accounts" extension will display all of your Assets and Liabilities accounts. 23 | In the style of YNAB, each account has a "Working" and a "Cleared" column, as well as a "Total" column. 24 | The "Working" column shows the sum of all cleared transactions as well as all _negative_ uncleared transactions to the account. 25 | The "Cleared" column shows the sum of all cleared transactions and the "Total" column shows the sum of all transactions. 26 | 27 | If you click on an account, you will get sent to the account's "Journal" extension page, which will display uncleared transactions 28 | in a different color than cleared transactions. It also has other tweaks to the standard ledger display that I prefer. 29 | 30 | There are three ways for a posting to be marked as cleared. They are based on the attributes that [beancount-import](https://github.com/jbms/beancount-import) 31 | uses since that's what I personally use to import transactions. 32 | 33 | First, if an account's `open` directive has the metadata `autoclear: TRUE`, then all postings to that account will automatically be considered cleared. 34 | This is useful for cash accounts where having uncleared postings doesn't make much sense. 35 | 36 | Second, for ease of use, if an account's `open` directive has the metadata `cleared_before: `, then all postings before that date to that account 37 | will automatically be considered cleared. This is useful if you already have many transactions in your ledger before you start using these plugins. 38 | 39 | Finally, if a posting has the `date:` metadata (regardless of the value), then the posting is considered cleared. If you're using 40 | [beancount-import](https://github.com/jbms/beancount-import) then it will add the `date:` metadata to any postings it imports/matches. 41 | 42 | If the posting has the metadata `uncleared:` attached, then it is considered not cleared regardless of any of the attributes above. 43 | This is useful e.g. for overriding a posting to an autoclearing account. 44 | 45 | ## Under the hood 46 | 47 | The `clearing` plugin uses the criteria above to add a metadata key `"_cleared"` to cleared postings; the "Accounts" and "Journal" extensions 48 | check for the existence of this metadata key to determine if a posting is cleared or not. Note that according to the current beancount language 49 | spec, `"_cleared"` is not a valid metadata key due to the leading underscore. However, in my testing, beancount and fava both still handle 50 | this gracefully without problems. I can't make any guarantees about other plugins or tools you may be using. 51 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "beancount-refried" 3 | version = "0.8.0" 4 | description = "A collection of plugins and scripts for beancount and fava for monthly budgeting." 5 | license = {text="GPL-3.0-or-later"} 6 | authors = [{name="scauligi", email="scauligi@gmail.com"}] 7 | readme = "README.md" 8 | 9 | [project.urls] 10 | Repository = "https://github.com/scauligi/refried" 11 | 12 | [project.scripts] 13 | rf-hello = "refried.scripts.hello:main" 14 | -------------------------------------------------------------------------------- /refried/__init__.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | import datetime 3 | import functools 4 | import glob 5 | import re 6 | from collections import defaultdict as ddict, OrderedDict 7 | from pathlib import Path 8 | from beancount import loader 9 | from beancount.core import account as acctops 10 | from beancount.core.data import Open, Close, Custom, Transaction 11 | 12 | __version__ = '0.7.0' 13 | 14 | # re-exports 15 | from beancount.parser.options import get_account_types 16 | 17 | def halfcents(d, padded=False): 18 | s = f'{d:,.03f}' 19 | if s[-1] == '0': 20 | s = s[:-1] 21 | if padded: 22 | s += ' ' 23 | return s 24 | 25 | def is_account_account(account): 26 | return account.startswith('Assets:') or account.startswith('Liabilities:') 27 | 28 | def is_account_type(account_type, account_name): 29 | """Predicate on account type. 30 | Slightly more flexible than `beancount.core.account_type.is_account_type`. 31 | 32 | Warning: No check is made on the validity of the account type. This merely 33 | returns whether the root account name matches the given account type(s). 34 | 35 | Args: 36 | account_type: A string, the prefix type of the account. Can also be a tuple. 37 | account_name: A string, the name of the account whose type is to return. 38 | Returns: 39 | A boolean, true if the account is of the given type. 40 | """ 41 | if isinstance(account_type, str): 42 | return account_name.startswith(account_type + acctops.sep) 43 | return account_name.startswith(tuple(atype + acctops.sep for atype in account_type)) 44 | 45 | @contextlib.contextmanager 46 | def _add_files(addl_files): 47 | def _uncached_load_file(filename, *args, **kw): 48 | return loader._load([(filename, True), *[(f'include "{fname}"', False) for fname in addl_files]], *args, **kw) 49 | _orig_uncached_load_file = loader._uncached_load_file 50 | assert loader._load_file.__closure__[1].cell_contents == _orig_uncached_load_file 51 | loader._load_file.__closure__[1].cell_contents = _uncached_load_file 52 | yield 53 | loader._load_file.__closure__[1].cell_contents = _orig_uncached_load_file 54 | 55 | def load_file(filename, *args, futures=False, addl_files=(), **kwargs): 56 | for line in Path(filename).read_text().splitlines(): 57 | m = re.fullmatch(r'\d{4}-\d{2}-\d{2}\s+custom\s+"includeglob"\s+"([^"]*)"', line) 58 | if m: 59 | addl_files = (*addl_files, *glob.glob(m.group(1))) 60 | with _add_files(addl_files) if addl_files else contextlib.nullcontext(): 61 | entries, errors, options = loader.load_file(filename, *args, **kwargs) 62 | if not futures: 63 | culled_entries = [entry for entry in entries 64 | if (not isinstance(entry, Transaction)) or ('future' not in entry.tags)] 65 | entries = culled_entries 66 | return entries, errors, options 67 | 68 | def filter_postings(entries): 69 | """A generator that yields the Postings of Transaction instances in a general list of entries. 70 | 71 | Args: 72 | entries: A list of directives. 73 | Yields: 74 | A tuple (Transaction, Posting) for each posting in each transaction. 75 | """ 76 | for entry in entries: 77 | if isinstance(entry, Transaction): 78 | for posting in entry.postings: 79 | yield entry, posting 80 | 81 | # derived from beancount.core.getters.get_account_open_close() 82 | def get_account_entries(entries): 83 | """Fetch the open/close entries for each of the accounts, 84 | as well as custom entries for non-account groups. 85 | 86 | If an entry happens to be duplicated, accept the earliest 87 | entry (chronologically). 88 | 89 | Args: 90 | entries: A list of directive instances. 91 | Returns: 92 | A map of account name strings to pairs of (open/custom-directive, close-directive) 93 | tuples. 94 | """ 95 | # A dict of account name to (open/custom-entry, close-entry). 96 | open_close_map = ddict(lambda: [None, None]) 97 | for entry in entries: 98 | if not isinstance(entry, (Open, Close, Custom)): 99 | continue 100 | if isinstance(entry, Custom): 101 | if not entry.type == "group-meta": 102 | continue 103 | acct = entry.values[0].value 104 | else: 105 | acct = entry.account 106 | open_close = open_close_map[acct] 107 | index = 0 if isinstance(entry, (Open, Custom)) else 1 108 | previous_entry = open_close[index] 109 | if previous_entry is not None: 110 | if previous_entry.date <= entry.date: 111 | entry = previous_entry 112 | open_close[index] = entry 113 | 114 | return dict(open_close_map) 115 | 116 | def aname(open_close, a, prefix=''): 117 | """Retrieve a name for an account/group. 118 | If the account/group has an associated `name:` metadata 119 | then return that, else return the final component of the account string. 120 | 121 | Args: 122 | open_close: The dictionary returned from `refried.get_account_entries()`. 123 | a: The account/group string. 124 | prefix: A string to use for tree-like nesting/indentation. 125 | Returns: 126 | The associated name for the account. 127 | """ 128 | components = acctops.split(a) 129 | indent = prefix * (len(components) - 1) 130 | name = components[-1].replace('-', ' ') 131 | if a in open_close: 132 | name = open_close[a][0].meta.get('name', name) 133 | return indent + name 134 | 135 | def isopen(open_close_entry, start=None, end=None): 136 | """A predicate for whether an account is open during a given time frame. 137 | 138 | Args: 139 | open_close_entry: The value associated with an account's key in the dictionary 140 | returned from `refried.get_account_entries()`. 141 | start: A `datetime.date` or `Period` for the start of the time frame (inclusive). 142 | end: An optional `datetime.date` or `Period` for the end of the time frame (exclusive). 143 | Returns: 144 | `True` if the account is open and not closed during any date within the time frame. 145 | """ 146 | open, close = open_close_entry 147 | assert open is not None 148 | if isinstance(end, Period): 149 | end = end.asdate() 150 | if isinstance(start, Period): 151 | start = start.asdate() 152 | if end and open.date >= end: 153 | return False 154 | if start and close and close.date <= start: 155 | return False 156 | return True 157 | 158 | def _reverse_parents(a): 159 | chain = acctops.split(a) 160 | for i in range(len(chain)): 161 | yield acctops.join(*chain[:i+1]) 162 | 163 | def _generate_account_order(open_close): 164 | ordermap = ddict(lambda: (999999,)) 165 | for a, (o, _) in open_close.items(): 166 | if 'ordering' in o.meta: 167 | order = str(o.meta['ordering']).split('.') 168 | ordermap[a] = tuple(int(x) for x in order) 169 | def account_order(cat): 170 | a, _ = cat 171 | return tuple(ordermap[chain] for chain in _reverse_parents(a)) 172 | return account_order 173 | 174 | def _accounts_sorted(open_close, start=None, end=None): 175 | account_order = _generate_account_order(open_close) 176 | cats = open_close.items() 177 | if start is not None: 178 | cats = filter(lambda cat: isopen(cat[1], start, end), cats) 179 | return sorted(cats, key=account_order) 180 | 181 | def walk(open_close, root, start=None, end=None, patterns=None): 182 | """A generator that yields accounts/groups in preorder... order. 183 | Respects `ordering:` metadata, otherwise asciibetic by account name. 184 | 185 | Args: 186 | open_close: The dictionary returned from `refried.get_account_entries()`. 187 | root: The account string of the root node to start from. 188 | start: (optional) Limits accounts to those that are `refried.isopen()` during this time frame. 189 | end: (optional) Limits accounts to those that are `refried.isopen()` during this time frame. 190 | patterns: a list of regex patterns to filter accounts by. 191 | Yields: 192 | Tuples (account string, Open/Custom directive) in preorder traversal. 193 | """ 194 | accts = _accounts_sorted(open_close, start, end) 195 | accts = filter(lambda cat: cat[0].startswith(root), accts) 196 | if patterns: 197 | accts = filter( 198 | lambda cat: any(re.search(patt, cat[0], re.I) for patt in patterns), 199 | accts, 200 | ) 201 | seen = set() 202 | for a, (o, _) in accts: 203 | for parent in _reverse_parents(acctops.parent(a)): 204 | if parent not in seen: 205 | seen.add(parent) 206 | yield parent, None 207 | seen.add(a) 208 | yield a, o 209 | 210 | def tree(open_close, start=None, end=None, patterns=None): 211 | """Creates a tree (using `dict`s) of account/groups. 212 | Respects `ordering:` metadata, otherwise asciibetic by account name. 213 | 214 | Args: 215 | open_close: The dictionary returned from `refried.get_account_entries()`. 216 | start: (optional) Limits accounts to those that are `refried.isopen()` during this time frame. 217 | end: (optional) Limits accounts to those that are `refried.isopen()` during this time frame. 218 | patterns: a list of regex patterns to filter accounts by. 219 | Returns: 220 | A recursive `dict` of account string -> (Open/Custom directive, subtree of children). 221 | """ 222 | accts = _accounts_sorted(open_close, start, end) 223 | if patterns: 224 | accts = ( 225 | acct 226 | for acct in accts 227 | if any(re.search(pattern, acct[0], re.I) for pattern in patterns) 228 | ) 229 | tree = dict() 230 | for a, (o, _) in accts: 231 | subtree = tree 232 | for parent in _reverse_parents(acctops.parent(a)): 233 | subtree = subtree.setdefault(parent, (open_close[a], OrderedDict()))[1] 234 | subtree[a] = (o, OrderedDict()) 235 | return tree 236 | 237 | @functools.total_ordering 238 | class Period: 239 | """Useful class for working with month-based timeframes.""" 240 | def __init__(self, year, month): 241 | self.year = year 242 | self.month = month 243 | self._date = datetime.date(year, month, 1) 244 | 245 | @staticmethod 246 | def from_str(s): 247 | """Expects string in the form "{year}-{month}[-{day}]".""" 248 | year, month, *_ = (int(n) for n in s.split('-', maxsplit=2)) 249 | return Period(year, month) 250 | 251 | @staticmethod 252 | def from_date(date): 253 | """Takes year and month from a `datetime.date`.""" 254 | return Period(date.year, date.month) 255 | 256 | @staticmethod 257 | def from_canonical(canon): 258 | """Converts from a canonical `int` representation.""" 259 | year, month0 = divmod(canon, 12) 260 | return Period(year, month0 + 1) 261 | 262 | def __hash__(self): 263 | return hash((self.year, self.month)) 264 | 265 | def __str__(self): 266 | return f'{self.year:04}-{self.month:02}' 267 | 268 | def __repr__(self): 269 | return f'Period({self.year}, {self.month})' 270 | 271 | def __eq__(self, o): 272 | if not isinstance(o, Period): 273 | return NotImplemented 274 | return (self.year, self.month) == (o.year, o.month) 275 | 276 | def __gt__(self, o): 277 | if not isinstance(o, Period): 278 | return NotImplemented 279 | return (self.year, self.month) > (o.year, o.month) 280 | 281 | def canonical(self): 282 | """Converts to a canonical `int` representation.""" 283 | return self.year * 12 + self.month - 1 284 | 285 | def asdate(self): 286 | """Creates a `datetime.date` for the first date in this period.""" 287 | return self._date 288 | 289 | def add(self, months): 290 | """Returns a new `Period` advanced by a number of months.""" 291 | return Period.from_canonical(self.canonical() + months) 292 | 293 | def sub(self, months): 294 | """Returns a new `Period` regressed by a number of months.""" 295 | return self.add(-months) 296 | -------------------------------------------------------------------------------- /refried/extensions/accts_ext/__init__.py: -------------------------------------------------------------------------------- 1 | from beancount.core import realization 2 | from beancount.core.data import Balance 3 | from beancount.core.number import Decimal, ZERO 4 | from beancount.core.inventory import Inventory, Amount 5 | from beancount.query import query 6 | 7 | from fava.ext import FavaExtensionBase 8 | 9 | from refried import _reverse_parents 10 | 11 | import refried 12 | from beancount.core import account as acctops 13 | from refried import get_account_types, is_account_type 14 | from collections import defaultdict as ddict 15 | from fava.core.inventory import CounterInventory 16 | from dataclasses import dataclass, field 17 | 18 | import datetime 19 | 20 | 21 | @dataclass 22 | class Acct: 23 | has_balance: bool = False 24 | working: CounterInventory = field(default_factory=CounterInventory) 25 | cleared: CounterInventory = field(default_factory=CounterInventory) 26 | total: CounterInventory = field(default_factory=CounterInventory) 27 | children: "Acct" = field(default_factory=lambda: Acct(children=None)) 28 | 29 | def add_posting(self, posting): 30 | self.has_balance = True 31 | self.total.add_position(posting) 32 | if posting.meta.get('_cleared', False): 33 | self.working.add_position(posting) 34 | self.cleared.add_position(posting) 35 | elif posting.units.number < 0: 36 | self.working.add_position(posting) 37 | 38 | class AcctsExt(FavaExtensionBase): 39 | report_title = "Accounts" 40 | 41 | def __init__(self, *args, **kwargs): 42 | super().__init__(*args, **kwargs) 43 | self.open_close = refried.get_account_entries(self.ledger.all_entries) 44 | last_date = self.ledger.all_entries[-1].date 45 | self._tree = refried.tree(self.open_close, last_date) 46 | 47 | def make_table2(self): 48 | account_types = get_account_types(self.ledger.options) 49 | is_account_account = lambda a: is_account_type((account_types.assets, account_types.liabilities), a) 50 | 51 | table = ddict(Acct) 52 | 53 | for tx in self.ledger.all_entries_by_type.Transaction: 54 | if "future" in tx.tags: 55 | continue 56 | for posting in tx.postings: 57 | if is_account_account(posting.account): 58 | table[posting.account].add_posting(posting) 59 | for account in acctops.parents(posting.account): 60 | table[account].children.add_posting(posting) 61 | 62 | return table 63 | 64 | def tree(self, root): 65 | return self._tree[root] 66 | 67 | def aname(self, account_name): 68 | return refried.aname(self.open_close, account_name) 69 | 70 | def show_if_zero(self, amounts): 71 | amounts = list(amounts) 72 | if amounts: 73 | return amounts 74 | return [Amount(Decimal(), self.ledger.options['operating_currency'][0])] 75 | 76 | def make_table(self): 77 | """An account tree based on matching regex patterns.""" 78 | cash = self.ledger.accounts.get('Assets') 79 | credit = self.ledger.accounts.get('Liabilities') 80 | 81 | _, wrows = query.run_query(self.ledger.all_entries, self.ledger.options, ''' 82 | select account,sum(position) 83 | from not "future" in tags 84 | where account ~ "^(Assets|Liabilities)" 85 | and (meta('_cleared') = True or number < 0) 86 | group by 1''') 87 | _, crows = query.run_query(self.ledger.all_entries, self.ledger.options, ''' 88 | select account,sum(position) 89 | from not "future" in tags 90 | where account ~ "^(Assets|Liabilities)" 91 | and (meta('_cleared') = True) 92 | group by 1''') 93 | _, trows = query.run_query(self.ledger.all_entries, self.ledger.options, ''' 94 | select account,sum(position) 95 | from not "future" in tags 96 | where account ~ "^(Assets|Liabilities)" 97 | group by 1''') 98 | 99 | self.wrows = dict(wrows) 100 | self.crows = dict(crows) 101 | self.trows = dict(trows) 102 | 103 | return [cash, credit] 104 | 105 | def _ordering(self, a): 106 | def _ordermap(a): 107 | meta = self.ledger.accounts[a].meta 108 | return tuple(map(int, str(meta.get('ordering', 999999)).split('.'))) 109 | return tuple(map(_ordermap, _reverse_parents(a.account))) 110 | 111 | def _name(self, a): 112 | meta = self.ledger.accounts[a.account].meta 113 | name = meta.get('name') 114 | if name is None: 115 | name = a.account.rsplit(':', 1)[-1] 116 | return name 117 | 118 | def _sort_subtree(self, root): 119 | children = list(root.values()) 120 | children.sort(key=self._ordering) 121 | return children 122 | 123 | def _row(self, rows, a): 124 | inv = rows.get(a.account, Inventory()) 125 | return [pos.units for pos in inv.get_positions()] 126 | 127 | def _row_children(self, rows, a): 128 | sum = Inventory() 129 | for sub in rows: 130 | if sub.startswith(a.account) and not rows[sub].is_empty(): 131 | sum += rows[sub] 132 | return [pos.units for pos in sum.get_positions()] if not sum.is_empty() else [Amount(ZERO, "USD")] 133 | 134 | def _is_open(self, a): 135 | if not a: 136 | return True 137 | acct = self.ledger.accounts[a.account] 138 | if acct: 139 | close_date = self.ledger.accounts[a.account].close_date 140 | return close_date >= datetime.date.today() 141 | return True 142 | 143 | def account_uptodate_status(self, account_name): 144 | """Status of the last balance. 145 | 146 | Args: 147 | account_name: An account name. 148 | 149 | Returns: 150 | A status string for the last balance of the account, 151 | as well as the date of the last balance. 152 | 153 | - 'green': A balance check that passed. 154 | - 'red': A balance check that failed. 155 | """ 156 | 157 | status = None 158 | date = None 159 | for txn_posting in reversed(self.ledger.all_entries_by_type.Balance): 160 | if txn_posting.account == account_name: 161 | date = txn_posting.date 162 | if txn_posting.diff_amount: 163 | status = "red" 164 | break 165 | # XXX check date 166 | status = "green" 167 | break 168 | 169 | return status, date 170 | -------------------------------------------------------------------------------- /refried/extensions/accts_ext/templates/AcctsExt.html: -------------------------------------------------------------------------------- 1 | {% set infotext = { 2 | 'green': "The last balance check is passing.", 3 | 'red': "The last balance check is failing.", 4 | 'yellow': "The last balance check has not been updated in a while.", 5 | } %} 6 | 7 | 8 | {% macro indicator(ledger, account) %} 9 | {% set status, last_balance = extension.account_uptodate_status(account) %} 10 | {% set balance_string = ledger.accounts[account].balance_string %} 11 | {% set last_balance_activity = (today() - last_balance).days if last_balance else 0 %} 12 | {% if last_balance_activity > ledger.fava_options.uptodate_indicator_grey_lookback_days %} 13 | {% set status = "yellow" %} 14 | {% endif %} 15 | 20 | {% endmacro %} 21 | 22 | 23 | {% macro account_name(ledger, account_name, last_segment=False) -%} 24 | 27 | {%- if ledger.accounts[account_name].uptodate_status %} 28 | 29 | {{ indicator(ledger, account_name) }} 30 | {% endif %} 31 | {% endmacro %} 32 | 33 | 46 | 47 | 54 | 55 | 56 | {% set table = extension.make_table2() %} 57 | 58 | {% macro acct_tree(root) %} 59 | 60 |
    61 |
  1. 62 |

    63 | 64 | Total 65 | Cleared 66 | Working 67 |

    68 |
  2. 69 | {% set currency = ledger.options.operating_currency[0] %} 70 | {% set end_date = g.filtered.end_date %} 71 | {% for account, (_, children) in [(root, extension.tree(root))] recursive %} 72 | {% set acct = table[account] %} 73 | 74 |

    75 | 78 | {% for type in ("total", "cleared", "working") %} 79 | {% set balance = (acct[type]|cost_or_value(end_date)).amounts()|list %} 80 | {% set balance_children = (acct.children[type]|cost_or_value(end_date)).amounts() %} 81 | 82 | {% for amount in balance %} 83 | {% set num = amount.number %} 84 | 85 | {{ amount.number | format_currency(amount.currency) }} 86 | {{ amount.currency if amount.currency != currency else "" }} 87 | 88 | {% endfor %} 89 | {% for amount in extension.show_if_zero(balance_children) %} 90 | {% set num = amount.number %} 91 | 92 | {{ amount.number | format_currency(amount.currency, show_if_zero=True) }} 93 | {{ amount.currency if amount.currency != currency else "" }} 94 | 95 | {% endfor %} 96 | 97 | {% endfor %} 98 |

    99 | {% if children %} 100 |
      {{- loop(children.items()) -}}
    101 | {% endif %} 102 | 103 | {% endfor %} 104 |
105 |
106 | {% endmacro %} 107 | 108 |
109 |
110 | {{ acct_tree(ledger.options['name_assets']) }} 111 |
112 |
113 | {{ acct_tree(ledger.options['name_liabilities']) }} 114 |
115 |
116 | -------------------------------------------------------------------------------- /refried/extensions/avail_ext/__init__.py: -------------------------------------------------------------------------------- 1 | from beancount.core import convert 2 | from beancount.core.data import Open 3 | from beancount.core.number import Decimal, ZERO 4 | from beancount.core.inventory import Inventory, Position, Amount 5 | from beancount.core.realization import RealAccount 6 | from beancount.core import getters 7 | from beancount.core import convert 8 | from beancount.query import query 9 | 10 | from fava.core.tree import Tree 11 | from fava.ext import FavaExtensionBase 12 | 13 | import refried 14 | from refried import filter_postings, _reverse_parents, Period 15 | 16 | import datetime 17 | from collections import defaultdict as ddict 18 | 19 | 20 | class AvailExt(FavaExtensionBase): # pragma: no cover 21 | report_title = "Budget" 22 | 23 | def make_table(self, period): 24 | """An account tree based on matching regex patterns.""" 25 | today = datetime.date.today() 26 | 27 | if period is not None: 28 | period = Period.from_str(period) 29 | else: 30 | period = Period.from_date(today) 31 | 32 | self.account_types = refried.get_account_types(self.ledger.options) 33 | self.open_close_map = getters.get_account_open_close(self.ledger.all_entries) 34 | 35 | self.tree = {} 36 | def slurp(tree): 37 | for k, (_, v) in list(tree.items()): 38 | self.tree[k] = v 39 | slurp(v) 40 | slurp(refried.tree(self.open_close_map, start=period)) 41 | root = [ 42 | self.account_types.income, 43 | self.account_types.expenses, 44 | ] 45 | 46 | 47 | # self.period_start = self.ledger._date_first 48 | # self.period_end = self.ledger._date_last 49 | self.period_start = period.asdate() 50 | self.period_end = period.add(1).asdate() 51 | 52 | endtoday = self.period_end 53 | if Period.from_date(today) == period: 54 | endtoday = today + datetime.timedelta(days=1) 55 | 56 | self.brows = ddict(Inventory) 57 | self.midbrows = ddict(Inventory) 58 | self.srows = ddict(Inventory) 59 | self.midsrows = ddict(Inventory) 60 | self.vrows = ddict(Inventory) 61 | self.midvrows = ddict(Inventory) 62 | for entry, posting in filter_postings(self.ledger.all_entries): 63 | if entry.date >= self.period_end: 64 | continue 65 | self.vrows[posting.account].add_position(posting) 66 | if entry.date < endtoday: 67 | self.midvrows[posting.account].add_position(posting) 68 | if entry.date < self.period_start: 69 | continue 70 | if 'rebudget' in entry.tags: 71 | rows = self.brows 72 | midrows = self.midbrows 73 | else: 74 | rows = self.srows 75 | midrows = self.midsrows 76 | rows[posting.account].add_position(posting) 77 | if entry.date < endtoday: 78 | midrows[posting.account].add_position(posting) 79 | 80 | return root, str(period) 81 | 82 | def format_currency(self, value, currency = None, show_if_zero = False): 83 | if not value and not show_if_zero: 84 | return "" 85 | if value == ZERO: 86 | return self.ledger.format_decimal(ZERO, currency) 87 | return self.ledger.format_decimal(value, currency) 88 | 89 | def format_amount(self, amount, show_if_zero=False): 90 | if amount is None: 91 | return "" 92 | number, currency = amount 93 | if number is None: 94 | return "" 95 | if currency == "USD": 96 | return self.format_currency(number, currency, show_if_zero) 97 | num = self.format_currency(number, currency, show_if_zero=True).replace('\xa0', '') 98 | return "{} {}".format(num, currency) 99 | 100 | def _ordering(self, a): 101 | def _ordermap(a): 102 | meta = self.ledger.accounts[a].meta 103 | return tuple(map(int, str(meta.get('ordering', 999999)).split('.'))) 104 | return tuple(map(_ordermap, _reverse_parents(a.account))) 105 | 106 | def _name(self, a): 107 | meta = self.ledger.accounts[a].meta 108 | return meta.get('name', a) 109 | 110 | def _sort_subtree(self, root): 111 | children = list(root.values()) 112 | children.sort(key=self._ordering) 113 | return children 114 | 115 | def _only_position(self, inventory): 116 | if inventory is None: 117 | return Amount(ZERO, "USD") 118 | inventory = inventory.reduce(convert.get_weight) 119 | if inventory.is_empty(): 120 | return Amount(ZERO, "USD") 121 | return inventory.get_only_position().units 122 | 123 | def _many_positions(self, inventory): 124 | if inventory is None: 125 | return [] 126 | inventory = inventory.reduce(convert.get_weight) 127 | if inventory.is_empty(): 128 | return [] 129 | return [pos.units for pos in inventory.get_positions()] 130 | 131 | def _row(self, rows, a): 132 | d: Inventory = rows.get(a) 133 | return [-amt for amt in self._many_positions(d)] 134 | 135 | def _row_children(self, rows, a): 136 | sum = Inventory() 137 | for sub in rows: 138 | if sub.startswith(a): 139 | sum.add_inventory(rows.get(sub, Inventory())) 140 | amts = [-amt for amt in self._many_positions(sum.reduce(convert.get_weight))] 141 | return amts if amts else [Amount(ZERO, "USD")] 142 | 143 | def _has_children(self, a): 144 | # return sum(self._is_open(c) for c in a.values()) 145 | return bool(self.tree[a]) 146 | 147 | def _children(self, a): 148 | return list(self.tree[a].keys()) 149 | 150 | def _is_open(self, a): 151 | if not a: 152 | return False 153 | open, close = self.open_close_map.get(a.account, (None, None)) 154 | return (open is None or open.date < self.period_end) and (close is None or close.date > self.period_start) 155 | 156 | def _period_for(self, date): 157 | return date.strftime('%Y-%m') 158 | 159 | def _prev_month(self): 160 | return self._period_for(self.period_start - datetime.timedelta(days=1)) 161 | 162 | def _next_month(self): 163 | return self._period_for(self.period_end) 164 | 165 | def _date_range(self): 166 | end = self.period_end 167 | start = self.period_start 168 | if start.day == 1 and end.day == 1 and (end - start).days in range(28, 32): 169 | return start.strftime('%b %Y') 170 | return f'{start} - {end}' 171 | -------------------------------------------------------------------------------- /refried/extensions/avail_ext/templates/AvailExt.html: -------------------------------------------------------------------------------- 1 | {% import 'macros/_account_macros.html' as account_macros with context %} 2 | 3 | 107 | 108 | {% set root, period = extension.make_table(request.args.get('period')) %} 109 | {% set brows = extension.midbrows %} 110 | {% set srows = extension.midsrows %} 111 | {% set vrows = extension.midvrows %} 112 |

Budget: {{ extension._date_range() }}

113 |

114 | << | 115 | Current period | 116 | >> 117 |

118 |
    119 |
  1. 120 |

    121 | 122 | Budgeted 123 | Spent 124 | Available 125 |

    126 |
  2. 127 | {% set ns = namespace(rown=1) %} 128 | {% for aname in root recursive %} 129 | {% set ns.rown = 1 if extension._has_children(aname) else 1 - ns.rown %} 130 | 131 |

    132 | 140 | {% set budgeteds = extension._row(brows, aname) %} 141 | {% set spents = extension._row(srows, aname) %} 142 | {% set availables = extension._row(vrows, aname) %} 143 | 144 | {% for budgeted in budgeteds %} 145 | 146 | 147 | {{ extension.format_amount(budgeted) }} 148 | 149 | 150 | {% endfor %} 151 | {% for budgeted in extension._row_children(brows, aname) %} 152 | 153 | 154 | {{ extension.format_amount(budgeted, show_if_zero=True) }} 155 | 156 | 157 | {% endfor %} 158 | 159 | 160 | {% for spent in spents %} 161 | 162 | 163 | {{ extension.format_amount(spent) }} 164 | 165 | 166 | {% endfor %} 167 | {% for spent in extension._row_children(srows, aname) %} 168 | 169 | 170 | {{ extension.format_amount(spent, show_if_zero=True) }} 171 | 172 | 173 | {% endfor %} 174 | 175 | 176 | {% for available in availables %} 177 | 178 | 179 | {{ extension.format_amount(available) }} 180 | 181 | 182 | {% endfor %} 183 | {% for available in extension._row_children(vrows, aname) %} 184 | 185 | {{ extension.format_amount(available, show_if_zero=True) }} 186 | 187 | {% endfor %} 188 | 189 |

    190 |
      191 | {{ loop(extension._children(aname)) }} 192 |
    193 | 194 | {% endfor %} 195 |
196 |
197 | -------------------------------------------------------------------------------- /refried/extensions/journal_ext/__init__.py: -------------------------------------------------------------------------------- 1 | """Portfolio list extension for Fava. 2 | 3 | This is a simple example of Fava's extension reports system. 4 | """ 5 | import re 6 | 7 | from beancount.core.compare import hash_entry 8 | from beancount.core.data import iter_entry_dates 9 | from beancount.core.data import Open, Transaction 10 | from beancount.core.number import Decimal 11 | from beancount.core.number import ZERO 12 | from beancount.core.inventory import Inventory 13 | from beancount.query import query 14 | 15 | from fava.context import g 16 | from fava.core.tree import Tree 17 | from fava.ext import FavaExtensionBase 18 | from fava.template_filters import cost_or_value 19 | 20 | import datetime 21 | import re 22 | 23 | 24 | class JournalExt(FavaExtensionBase): # pragma: no cover 25 | """Sample Extension Report that just prints out an Portfolio List. 26 | """ 27 | 28 | report_title = "Journal" 29 | 30 | def _wct(self, account_name): 31 | if not account_name: 32 | account_name = '^(Assets:|Liabilities:)' 33 | _, wrow = query.run_query(self.ledger.all_entries, self.ledger.options, ''' 34 | select number(only("USD", sum(position))) 35 | where account = "{}" 36 | and (meta('_cleared') = True or number < 0) 37 | ''', account_name) 38 | if not wrow: 39 | wrow = [[Decimal()]] 40 | _, crow = query.run_query(self.ledger.all_entries, self.ledger.options, ''' 41 | select number(only("USD", sum(position))) 42 | where account = "{}" 43 | and (meta('_cleared') = True) 44 | ''', account_name) 45 | if not crow: 46 | crow = [[Decimal()]] 47 | _, trow = query.run_query(self.ledger.all_entries, self.ledger.options, ''' 48 | select number(only("USD", sum(position))) 49 | where account = "{}" 50 | ''', account_name) 51 | if not trow: 52 | trow = [[Decimal()]] 53 | return wrow[0][0], crow[0][0], trow[0][0] 54 | 55 | def _get_entries(self, account_name): 56 | wjc = self.ledger.fava_options.account_journal_include_children 57 | if account_name: 58 | entries = self.ledger.account_journal( 59 | g.filtered, 60 | account_name, 61 | with_journal_children=wjc) 62 | else: 63 | entries = self.ledger.account_journal( 64 | g.filtered, 65 | 'Assets', 66 | with_journal_children=wjc) 67 | entries = list(entries) 68 | entries.extend(self.ledger.account_journal( 69 | g.filtered, 70 | 'Liabilities', 71 | with_journal_children=wjc)) 72 | return entries 73 | 74 | @staticmethod 75 | def _filter_meta(meta, indicators=False): 76 | if not meta: 77 | return [] 78 | return [ 79 | (key, value) 80 | for key, value in meta.items() 81 | if not ( 82 | key 83 | in ( 84 | "filename", 85 | "lineno", 86 | "_cleared", 87 | *( 88 | ("date",) 89 | if indicators 90 | else () 91 | ), 92 | ) 93 | or key.startswith(( 94 | "__", 95 | *( 96 | ("ofx_", "n26_") 97 | if indicators 98 | else () 99 | ), 100 | )) 101 | ) 102 | ] 103 | 104 | @staticmethod 105 | def _flag_for_account(entry, account_name): 106 | flag = None 107 | flagtype = '' 108 | if isinstance(entry, Transaction): 109 | flag = entry.flag 110 | if entry.flag != '*': 111 | flagtype = 'pending' if flag == '!' else 'other' 112 | else: 113 | flagtype = 'cleared' 114 | for posting in filter(lambda p: (not account_name) or p.account == account_name, entry.postings): 115 | if not posting.meta or not posting.meta.get('_cleared', False): 116 | flagtype = 'pending' 117 | return flag, flagtype 118 | 119 | @staticmethod 120 | def _flag_for_posting(posting): 121 | flag = posting.flag 122 | flagtype = 'normal' 123 | if JournalExt._is_account_account(posting.account) \ 124 | and (not flag or flag == '*') \ 125 | and posting.meta \ 126 | and not posting.meta.get('_cleared', False): 127 | flagtype = 'pending' 128 | elif flag == '!': 129 | flagtype = 'pending' 130 | elif flag: 131 | flagtype = 'other' 132 | return flag, flagtype 133 | 134 | @staticmethod 135 | def _is_expense_account(account_name): 136 | return account_name.startswith('Expenses:') or account_name.startswith('Income:') 137 | 138 | @staticmethod 139 | def _is_account_account(account_name): 140 | return account_name.startswith('Assets:') or account_name.startswith('Liabilities:') 141 | 142 | def _get_target(self, entry, account_name): 143 | if isinstance(entry, Transaction): 144 | expenses = set() 145 | accounts = set() 146 | for posting in entry.postings: 147 | if account_name != posting.account: 148 | if self._is_expense_account(posting.account): 149 | expenses.add(posting.account) 150 | elif self._is_account_account(posting.account): 151 | accounts.add(posting.account) 152 | if len(expenses) == 1: 153 | acct ,= expenses 154 | name = self._name(acct) 155 | if accounts: 156 | name = f'({name})' 157 | return (acct, name) 158 | elif not expenses and len(accounts) == 1: 159 | acct ,= accounts 160 | name = self._name(acct) 161 | return (acct, name) 162 | return ('', '') 163 | 164 | def _name(self, a): 165 | meta = self.ledger.accounts[a].meta 166 | return meta.get('name', a) 167 | 168 | @staticmethod 169 | def _hash_entry(entry): 170 | return 'entry-' + hash_entry(entry) 171 | 172 | def _toggleDate(self, account_name, entry_hash): 173 | *_, slice_, sha256sum = self.ledger.context(entry_hash) 174 | lines = slice_.split('\n') 175 | i = 1 176 | while i < len(lines): 177 | line = lines[i] 178 | if re.match(rf'\s+{account_name}', line): 179 | i += 1 180 | addDate = True 181 | while i < len(lines): 182 | line = lines[i] 183 | if re.match(r'\s+date:\s*$', line): 184 | # found empty date: -- remove it 185 | lines.pop(i) 186 | i -= 1 # since we just removed a line 187 | addDate = False 188 | break 189 | elif re.match(r'\s+date:\s*.$', line): 190 | # found non-empty date: -- do nothing 191 | addDate = False 192 | break 193 | elif re.match(r'\s+[A-Z]', line): 194 | # found no date: meta 195 | break 196 | i += 1 197 | if addDate: 198 | lines.insert(i, ' date:') 199 | i += 1 200 | new_slice = '\n'.join(lines) 201 | self.ledger.file.save_entry_slice(entry_hash, new_slice, sha256sum) 202 | -------------------------------------------------------------------------------- /refried/extensions/journal_ext/templates/JournalExt.html: -------------------------------------------------------------------------------- 1 | {% import 'macros/_commodity_macros.html' as commodity_macros %} 2 | {% set account_name = request.args.get('account_name') %} 3 | {% if request.args.get('toggle_date_entry_hash') %} 4 | {{ extension._toggleDate(account_name, request.args.get('toggle_date_entry_hash')) }} 5 | {% else %} 6 | {% set subreport = 'journal' %} 7 | 8 | 65 | 66 | {% import 'macros/_account_macros.html' as account_macros with context %} 67 | {% import '_tree_table.html' as tree_table with context %} 68 | 69 | 70 | {% set short_type = { 71 | 'balance': 'Bal', 72 | 'close': 'Close', 73 | 'document': 'Doc', 74 | 'note': 'Note', 75 | 'open': 'Open', 76 | } %} 77 | {% set journal_show = request.args.getlist('show') %} 78 | 79 | 91 | 92 | {% macro account_link(name) %}{% endmacro %} 93 | {% macro journal_url(aname, entry) %}{{ url_for('extension_report', extension_name='JournalExt', account_name=aname) }}#{{ extension._hash_entry(entry) }}{% endmacro %} 94 | 95 | {% macro render_metadata_indicators(metadata) -%} 96 | {% for key, value in metadata %} 97 | 98 | {% endfor %} 99 | {%- endmacro %} 100 | 101 | {% macro render_metadata(metadata, entry_hash=None) -%} 102 | {% if metadata %} 103 | 115 | {% endif %} 116 | {% endmacro %} 117 | 118 | {% macro render_tags_links(entry) -%} 119 | {% for tag in entry.tags|sort %}#{{ tag }}{% endfor %} 120 | {% for link_ in entry.links|sort %}^{{ link_ }}{% endfor %} 121 | {%- endmacro %} 122 | 123 | {% macro journal_table(entries, show_change_and_balance=False) %} 124 | {% autoescape false %} 125 | 126 |
    127 |
  1. 128 |

    129 | {{ _('Date') }} 130 | {{ _('F') }} 131 | {{ _('Target') }} 132 | {{ _('Payee/Narration') }} 133 | {{ _('Position') }} 134 | 135 | 136 | {% if show_change_and_balance %} 137 | {{ _('Change') }} 138 | {{ _('Balance') }} 139 | {% endif %} 140 |

    141 |
  2. 142 | {% for entry in entries %} 143 | {% if show_change_and_balance %} 144 | {% set entry, change, balance = entry %} 145 | {% endif %} 146 | {% set type = entry.__class__.__name__.lower() %} 147 | {% set metadata_items = entry.meta|meta_items %} 148 | {% if type == 'price' %}{% continue %}{% endif %} 149 | {% set entry_hash = entry|hash_entry %} 150 | {% set flag,flagtype = extension._flag_for_account(entry, account_name) %} 151 | {% set tacct, tname = extension._get_target(entry, account_name) %} 152 |
  3. 153 |

    154 | {{ entry.date }} 155 | {% if type == 'transaction' %}{{ entry.flag }}{% else %}{{ short_type.get(type, type[:3]) }}{% endif %} 156 | 169 | 170 | {% if type == 'open' or type == 'close' %} 171 | {{ account_link(entry.account) }} 172 | {% elif type == 'note' %} 173 | {{ entry.comment }} 174 | {% elif type == 'query' %} 175 | {{ entry.name }} 176 | {% elif type == 'pad' %} 177 | {{ account_link(entry.account) }} from {{ account_link(entry.source_account) }} 178 | {% elif type == 'custom' %} 179 | {{ entry.type }} 180 | {%- for value in entry['values'] -%} 181 |  {% if value.dtype|string == "" %}{{ account_link(value.value) }} 182 | {%- elif value.dtype|string == "" %}{{ commodity_macros.render_amount(ledger, value.value) }} 183 | {%- elif value.dtype|string == "" %}"{{ value.value }}" 184 | {%- elif value.dtype|string == "" %}{{ value.value }} 185 | {%- elif value.dtype|string == "" %}{{ value.value }}{% endif -%} 186 | {%- endfor -%} 187 | {% elif type == 'document' %} 188 | {{ account_link(entry.account) }} 189 | {{ entry.filename|basename }} 190 | {{ render_tags_links(entry) }} 191 | {% elif type == 'balance' %} 192 | {{ account_link(entry.account) }} 193 | {% if entry.diff_amount %} 194 | 195 | accumulated {{ (entry.amount.number + entry.diff_amount.number)|format_currency(entry.amount.currency, show_if_zero=True) }} {{ entry.amount.currency }} 196 | {% endif %} 197 | {% elif type == 'transaction' %} 198 | {{ entry.payee or '' }}{% if entry.payee and entry.narration %}{% endif %}{{ entry.narration or '' }} 199 | {{ render_tags_links(entry) }} 200 | {% endif %} 201 | 202 | 203 | {{ render_metadata_indicators(metadata_items) }} 204 | {% for posting in entry.postings %} 205 | {% set pflag,pflagtype = extension._flag_for_posting(posting) %} 206 | 207 | {{ render_metadata_indicators(extension._filter_meta(posting.meta, indicators=True)) }} 208 | {% endfor %} 209 | 210 | {# if type == 'balance' #} 211 | {# commodity_macros.render_amount(ledger, entry.amount, 'num bal' + (' pending' if entry.diff_amount else '')) #} 212 | {# endif #} 213 | {% if show_change_and_balance %} 214 | {% if type == 'balance' %} 215 | {% if entry.diff_amount %} 216 | {{ commodity_macros.render_amount(ledger, -entry.diff_amount) }} 217 | {% endif %} 218 | {{ commodity_macros.render_amount(ledger, entry.amount, 'num bal' + (' error' if entry.diff_amount else '')) }} 219 | {% else %} 220 | 221 | {%- for pos in change|cost_or_value(entry.date) %}{{ commodity_macros.render_amount(ledger, pos.units) }}
    {% endfor -%} 222 |
    223 | 224 | {%- for pos in balance|cost_or_value(entry.date) %}{{ commodity_macros.render_amount(ledger, pos.units) }}
    {% endfor -%} 225 |
    226 | {% endif %} 227 | {% endif %} 228 |

    229 | {{ render_metadata(metadata_items, entry_hash) }} 230 | {% if entry.postings %} 231 |
      232 | {% for posting in entry.postings %} 233 | 234 |

      235 | 236 | {{ posting.flag or '' }} 237 | {{ account_link(posting.account) }} 238 | {# We want the output these amounts with the same precision as in the input file. 239 | For computed values this might give a lot of digits, so format the price using the DisplayContext for now.#} 240 | {{ posting.units or '' }} 241 | 242 | 243 | 244 | 245 | {% if show_change_and_balance %} 246 | 247 | 248 | {% endif %} 249 |

      250 | {{ render_metadata(extension._filter_meta(posting.meta)) }} 251 | 252 | {% endfor %} 253 |
    254 | {% endif %} 255 |
  4. 256 | {% endfor %} 257 |
258 |
259 | {% endautoescape %} 260 | {%- endmacro %} 261 | 262 | {% set wsum, csum, tsum = extension._wct(account_name) %} 263 | 264 | {% macro signed_num(dec) -%} 265 | {{dec|format_currency("USD", show_if_zero=True)}} 266 | {%- endmacro %} 267 | 268 |

{{ account_name or "Journal" }}

269 |

Working: {{ signed_num(wsum) }}  

(Cleared: {{ signed_num(csum) }} / Total: {{ signed_num(tsum) }})

270 |
271 | {% set entries = extension._get_entries(account_name) %} 272 | {{ journal_table(entries, show_change_and_balance=True) }} 273 |
274 | {% endif %} 275 | 276 | 285 | -------------------------------------------------------------------------------- /refried/plugins/README.md: -------------------------------------------------------------------------------- 1 | # Plugins 2 | 3 | (this document is still a WIP) 4 | 5 | ## clearing 6 | 7 | Applies metadata to postings for assets/liabilities signifying whether they 8 | have cleared in their corresponding accounts or not. 9 | See [the document on YNAB-style account views](/docs/clearing.md) for details. 10 | 11 | ## effective_date 12 | 13 | Creates linked transactions based on `effective_date:` metadata on postings. 14 | 15 | Can be specified multiple times to split the amount among the different dates, a la the `split` plugin. 16 | 17 | Useful for sending income to be budgeted in a future period. 18 | Also useful for incrementally budgeting money into a category throughout the month (e.g., adding $20 every week 19 | to a "Dining Out" category). 20 | 21 | See [the document on automatically budgeting towards goals](/docs/goals.md) for details. 22 | 23 | Based off of 24 | https://github.com/redstreet/beancount_reds_plugins, licensed under GPL3. 25 | 26 | ## evensplit 27 | 28 | Creates additional postings in a transaction according to `split:` metadata on postings. 29 | 30 | Can be specified multiple times to split the amount among several accounts. 31 | 32 | Can specify a string to create special "reimbursement" postings. 33 | 34 | ## rebudget 35 | 36 | Applies the `#rebudget` tag to (re)budgeting transactions so they can be 37 | easily filtered away for reports. 38 | See [the document on YNAB-style budgeting](/docs/budgeting.md) for details. 39 | 40 | Also checks that the amount of money in on-budget (non-tracking) accounts matches the 41 | amount of money in on-budget (non-tracking) income/expense categories. 42 | See [the document on tracking accounts](/docs/tracking.md) for details. 43 | 44 | ## tracking 45 | 46 | Creates linked transactions based on `tracking:` metadata on postings. 47 | See [the document on tracking accounts](/docs/tracking.md) for details. 48 | 49 | ## wishfarm 50 | 51 | Helper plugin for managing a [wish farm](https://www.youneedabudget.com/wish-lists/). 52 | -------------------------------------------------------------------------------- /refried/plugins/clearing.py: -------------------------------------------------------------------------------- 1 | from refried import is_account_account 2 | from beancount.core.data import Open, Transaction 3 | 4 | __plugins__ = ['clearing'] 5 | 6 | def clearing(entries, options_map): 7 | errors = [] 8 | cleardates = {} 9 | autoclears = {} 10 | for entry in entries: 11 | if isinstance(entry, Open): 12 | cleardates[entry.account] = entry.meta.get('cleared_before', None) 13 | autoclears[entry.account] = entry.meta.get('autoclear', False) 14 | elif isinstance(entry, Transaction): 15 | for i, posting in enumerate(entry.postings): 16 | if not posting.meta: 17 | posting = posting._replace(meta={}) 18 | entry.postings[i] = posting 19 | if not is_account_account(posting.account): 20 | if 'uncleared' in posting.meta: 21 | del posting.meta['uncleared'] 22 | continue 23 | cleared = False 24 | if 'date' in posting.meta: 25 | cleared = True 26 | if 'uncleared' in posting.meta: 27 | del posting.meta['uncleared'] 28 | cleared = False 29 | elif posting.account not in cleardates: 30 | # account doesn't have a corresponding Open directive! 31 | continue 32 | elif (autoclears[posting.account]) or \ 33 | (cleardates[posting.account] and \ 34 | entry.date < cleardates[posting.account]): 35 | cleared = True 36 | posting.meta['_cleared'] = cleared 37 | return entries, errors 38 | -------------------------------------------------------------------------------- /refried/plugins/conversions.py: -------------------------------------------------------------------------------- 1 | import typing 2 | 3 | from beancount.core.data import Amount, Posting, Transaction 4 | from beancount.core.inventory import Inventory 5 | from more_itertools import flatten, unzip 6 | 7 | __plugins__ = ('conversions',) 8 | 9 | 10 | class TestError(typing.NamedTuple): 11 | source: dict 12 | message: str 13 | entry: None = None 14 | 15 | 16 | # TestError = collections.namedtuple('TestError', 'source message entry') 17 | 18 | 19 | def conversions(entries, options_map): 20 | def do_conversion(entry): 21 | if not isinstance(entry, Transaction): 22 | return entry, [] 23 | errors = [] 24 | if 'convert_at' in entry.meta or any( 25 | 'convert_at' in posting.meta for posting in entry.postings 26 | ): 27 | conversion_account = None 28 | conversion_meta = {} 29 | postings = [] 30 | inv = Inventory() 31 | for posting in entry.postings: 32 | if posting.meta.get('__automatic__'): 33 | conversion_account = posting.account 34 | conversion_meta = posting.meta 35 | elif price := ( 36 | posting.meta.get('convert_at') or entry.meta.get('convert_at') 37 | ): 38 | inv.add_position(posting) 39 | num = -posting.units.number * price.number 40 | num = options_map['dcontext'].quantize(num, price.currency) 41 | units = Amount(num, price.currency) 42 | new_posting = Posting(posting.account, units, None, None, None, posting.meta) 43 | inv.add_position(new_posting) 44 | postings.extend((posting, new_posting)) 45 | else: 46 | postings.append(posting) 47 | if conversion_account: 48 | for position in inv: 49 | postings.append( 50 | Posting( 51 | conversion_account, -position.units, None, None, None, conversion_meta 52 | ) 53 | ) 54 | entry = entry._replace(postings=postings) 55 | return entry, errors 56 | 57 | entries, errors = unzip(map(do_conversion, entries)) 58 | return list(entries), list(flatten(errors)) 59 | -------------------------------------------------------------------------------- /refried/plugins/effective_date.py: -------------------------------------------------------------------------------- 1 | """Beancount plugin to implement per-posting effective dates. 2 | Modified from https://github.com/redstreet/beancount_reds_plugins, under GPL3""" 3 | 4 | import collections 5 | from beancount.core.amount import ZERO 6 | from beancount.core import data 7 | from beancount.core import account 8 | from beancount.core import getters 9 | from beancount.core import flags 10 | from beancount.ops import holdings 11 | from beancount.parser import options 12 | from beancount.parser import printer 13 | from ast import literal_eval 14 | from decimal import Decimal 15 | import copy 16 | import datetime 17 | import time 18 | import string 19 | 20 | DEBUG = False 21 | 22 | __plugins__ = ('effective_date',) 23 | 24 | LINK_FORMAT = 'edate-{date}-{index}' 25 | 26 | def has_valid_effective_date(posting): 27 | return posting.meta is not None and \ 28 | 'effective_date' in posting.meta and \ 29 | (isinstance(posting.meta['effective_date'], datetime.date) \ 30 | or (isinstance(posting.meta['effective_date'], list) \ 31 | and all(isinstance(el, datetime.date) for el in posting.meta['effective_date']))) 32 | 33 | def has_posting_with_valid_effective_date(entry): 34 | for posting in entry.postings: 35 | if has_valid_effective_date(posting): 36 | return True 37 | return False 38 | 39 | def create_new_effective_date_entry(entry, date, hold_posting, original_posting): 40 | def cleaned(p): 41 | clean_meta = copy.deepcopy(p.meta) 42 | clean_meta.pop('effective_date', None) 43 | return p._replace(meta=clean_meta) 44 | 45 | new_meta = {'original_date': entry.date} 46 | new_meta = {**entry.meta, **new_meta} 47 | new_meta['filename'] = '' 48 | new_meta['lineno'] = 0 49 | effective_date_entry = entry._replace(date=date, 50 | meta={**entry.meta, **new_meta}, 51 | postings=[cleaned(hold_posting), cleaned(original_posting)]) 52 | return effective_date_entry 53 | 54 | def build_config(config): 55 | holding_accts = {} 56 | if config: 57 | holding_accts = literal_eval(config) 58 | if not holding_accts: 59 | if DEBUG: 60 | print("Using default config") 61 | holding_accts = { 62 | 'Expenses': 'Equity:Hold:Expenses', 63 | 'Income': 'Income:To-Be-Budgeted:Future-Budgeted', 64 | 'Assets': 'Equity:Hold:Assets', 65 | } 66 | return holding_accts 67 | 68 | def effective_date(entries, options_map, config=None): 69 | """Effective dates 70 | 71 | Args: 72 | entries: a list of entry instances 73 | options_map: a dict of options parsed from the file 74 | config: A configuration string, which is intended to be a Python dict 75 | mapping match-accounts to a pair of (negative-account, position-account) 76 | account names. 77 | Returns: 78 | A tuple of entries and errors. 79 | 80 | """ 81 | start_time = time.time() 82 | errors = [] 83 | holding_accts = build_config(config) 84 | 85 | interesting_entries = [] 86 | filtered_entries = [] 87 | new_accounts = set() 88 | for entry in entries: 89 | if isinstance(entry, data.Transaction) and has_posting_with_valid_effective_date(entry): 90 | interesting_entries.append(entry) 91 | else: 92 | filtered_entries.append(entry) 93 | 94 | # add a link to each effective date entry. this gets copied over to the newly created effective date 95 | # entries, and thus links each set of effective date entries 96 | interesting_entries_linked = [] 97 | for n, entry in enumerate(interesting_entries): 98 | index_string = f'{n:04}' 99 | date = str(entry.date).replace('-', '') 100 | link = LINK_FORMAT.format(date=str(date), index=index_string) 101 | new_entry = entry._replace(links=(entry.links or set()) | set([link])) 102 | interesting_entries_linked.append(new_entry) 103 | 104 | new_entries = [] 105 | for entry in interesting_entries_linked: 106 | modified_entry_postings = [] 107 | effective_date_entry_postings = [] 108 | for posting in entry.postings: 109 | if not has_valid_effective_date(posting): 110 | modified_entry_postings += [posting] 111 | else: 112 | found_acct = '' 113 | for acct in holding_accts: 114 | if posting.account.startswith(acct): 115 | found_acct = acct 116 | 117 | new_dates = posting.meta['effective_date'] 118 | if not isinstance(new_dates, list): 119 | new_dates = [new_dates] 120 | 121 | unum = posting.units.number 122 | exp = unum.as_tuple().exponent # produces -number_of_decimal_places 123 | n_ways = len(new_dates) 124 | overflow = unum.remainder_near(Decimal(n_ways).scaleb(exp)) 125 | units_list = [round(unum / n_ways, abs(exp))] * n_ways 126 | for i in range(abs(int(overflow.scaleb(-exp)))): 127 | if overflow < 0: 128 | i = -1 - i 129 | units_list[i] += Decimal(1).scaleb(exp) 130 | for i in range(len(units_list)): 131 | units_list[i] = posting.units._replace(number=units_list[i]) 132 | 133 | for new_date, units in zip(new_dates, units_list): 134 | new_acct_name = holding_accts[found_acct] 135 | 136 | # Replace posting in original entry with holding account 137 | clean_meta = copy.deepcopy(posting.meta) 138 | clean_meta['effective_date'] = new_date 139 | new_posting = posting._replace(account=new_acct_name, units=units, meta=clean_meta) 140 | new_accounts.add(new_posting.account) 141 | modified_entry_postings.append(new_posting) 142 | 143 | # Create new entry at effective_date 144 | hold_posting = new_posting._replace(units=-units) 145 | partial_posting = posting._replace(units=units) 146 | new_entry = create_new_effective_date_entry(entry, new_date, hold_posting, partial_posting) 147 | new_entries.append(new_entry) 148 | modified_entry = entry._replace(postings=modified_entry_postings) 149 | new_entries.append(modified_entry) 150 | 151 | # if DEBUG: 152 | # print("Output results:") 153 | # for e in new_entries: 154 | # printer.print_entry(e) 155 | 156 | if DEBUG: 157 | elapsed_time = time.time() - start_time 158 | print("effective_date [{:.1f}s]: {} entries inserted.".format(elapsed_time, len(new_entries))) 159 | 160 | new_open_entries = create_open_directives(new_accounts, entries) 161 | retval = new_open_entries + new_entries + filtered_entries 162 | return(retval, errors) 163 | 164 | def create_open_directives(new_accounts, entries): 165 | if not entries: 166 | return [] 167 | # Ensure that the accounts we're going to use to book the postings exist, by 168 | # creating open entries for those that we generated that weren't already 169 | # existing accounts. 170 | earliest_date = entries[0].date 171 | open_entries = getters.get_account_open_close(entries) 172 | new_open_entries = [] 173 | for account_ in sorted(new_accounts): 174 | if account_ not in open_entries: 175 | meta = data.new_metadata('', 0) 176 | open_entry = data.Open(meta, earliest_date, account_, None, None) 177 | new_open_entries.append(open_entry) 178 | return new_open_entries 179 | -------------------------------------------------------------------------------- /refried/plugins/evensplit.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict as ddict 2 | from copy import copy, deepcopy 3 | from beancount.core.data import Transaction, Posting, Amount, Cost, filter_txns 4 | from beancount.core.account import is_valid as is_account 5 | from beancount.core.amount import div as adiv 6 | from beancount.core.number import D 7 | 8 | __plugins__ = ('evensplit',) 9 | 10 | def add_posting(posting_map, acct, amt, save_meta): 11 | old_amt, meta = posting_map[(acct, amt.currency)] 12 | new_amt = old_amt + amt.number 13 | if save_meta: 14 | for key, value in save_meta.items(): 15 | if key in meta: 16 | # XXX if no multimeta, do something else 17 | if not isinstance(meta[key], list): 18 | meta[key] = [meta[key]] 19 | if isinstance(value, list): 20 | meta[key].extend(value) 21 | else: 22 | meta[key].append(value) 23 | else: 24 | meta[key] = value 25 | posting_map[(acct, amt.currency)] = (new_amt, meta) 26 | 27 | def evensplit(entries, options_map): 28 | errors = [] 29 | for entry in filter_txns(entries): 30 | new_postings_map = ddict(lambda: (D(), {})) 31 | special_postings = [] 32 | 33 | split_others = set(posting.meta.get('split_others') 34 | for posting in entry.postings 35 | if posting.meta) 36 | split_others.discard(None) 37 | 38 | if split_others: 39 | split_others = list(split_others) 40 | try: 41 | split_others ,= split_others 42 | except ValueError: 43 | pass 44 | for i, posting in enumerate(entry.postings): 45 | if posting.meta is None: 46 | posting = posting._replace(meta={}) 47 | if 'split_others' not in posting.meta and 'split' not in posting.meta: 48 | posting.meta['split'] = copy(split_others) 49 | entry.postings[i] = posting 50 | 51 | for i, posting in enumerate(entry.postings): 52 | if posting.meta and 'split' in posting.meta: 53 | assert posting.cost is None 54 | 55 | save_meta = deepcopy(posting.meta) 56 | targets = save_meta.pop('split') 57 | 58 | if is_account(targets): 59 | # special case for single split to account (because halfcents) 60 | assert posting.account != "Assets:Receivables" 61 | amount = adiv(posting.units, D(2)) 62 | posting = posting._replace(units=amount) 63 | newacct = targets 64 | add_posting(new_postings_map, newacct, amount, save_meta) 65 | else: 66 | if not isinstance(targets, list): 67 | targets = [targets] 68 | ntargets = len(targets) 69 | if posting.account != "Assets:Receivables": 70 | ntargets += 1 71 | split_amount = posting.units.number / ntargets 72 | split_amount = round(split_amount, 2) 73 | amount = posting.units._replace(number=split_amount) 74 | 75 | if posting.account != "Assets:Receivables": 76 | remainder = posting.units.number - split_amount * len(targets) 77 | remainder = posting.units._replace(number=remainder) 78 | posting = posting._replace(units=remainder) 79 | else: 80 | posting = None 81 | 82 | for target in targets: 83 | if is_account(target): 84 | newacct = target 85 | newamount = amount 86 | newcost = None 87 | add_posting(new_postings_map, newacct, newamount, save_meta) 88 | else: 89 | newacct = "Assets:Receivables" 90 | newamount = Amount(D(1), "REIMB") 91 | newcost = Cost(amount.number, amount.currency, entry.date, target) 92 | special_postings.append(Posting(newacct, newamount, newcost, None, None, save_meta)) 93 | 94 | entry.postings[i] = posting 95 | 96 | entry.postings[:] = list(filter(lambda x: x is not None, entry.postings)) 97 | for (acct, currency), (amt, meta) in new_postings_map.items(): 98 | entry.postings.append(Posting(acct, Amount(amt, currency), None, None, None, meta)) 99 | entry.postings.extend(special_postings) 100 | return entries, errors 101 | -------------------------------------------------------------------------------- /refried/plugins/pullfrom.py: -------------------------------------------------------------------------------- 1 | from beancount.core import compare 2 | from beancount.core.account import parent 3 | from beancount.core.data import Open, Posting, Transaction, new_metadata 4 | from beancount.core.inventory import Inventory 5 | from beancount.parser.options import get_account_types 6 | 7 | __plugins__ = ('pullfrom',) 8 | 9 | AUTOKEYS = ['autopull', 'autodraw'] 10 | KEYS = ['pull_from', 'pull-from', 'draw_from', 'draw-from'] 11 | 12 | def pullfrom(entries, options_map): 13 | errors = [] 14 | autopulls = {} 15 | new_entries = [] 16 | def get_newacct(posting): 17 | for key, val in reversed(posting.meta.items()): 18 | if key in KEYS: 19 | return val 20 | key = posting.account 21 | while key in autopulls: 22 | key = autopulls[key] 23 | assert key != posting.account 24 | return key 25 | for entry in entries: 26 | add_entries = [] 27 | if isinstance(entry, Open): 28 | if any(entry.meta.get(key) for key in AUTOKEYS): 29 | autopulls[entry.account] = parent(entry.account) 30 | elif isinstance(entry, Transaction): 31 | for posting in entry.postings: 32 | if posting.meta is None: 33 | continue 34 | if any(key in posting.meta for key in KEYS) or posting.account in autopulls: 35 | new_postings = [] 36 | memo = posting.meta.get('memo', '') 37 | new_acct = get_newacct(posting) 38 | new_posting = posting._replace(units=-posting.units, meta=None) 39 | new_postings.append(new_posting) 40 | new_posting = posting._replace(account=new_acct, meta=None) 41 | new_postings.append(new_posting) 42 | 43 | link_id = set(['pull-' + compare.hash_entry(entry)]) 44 | new_links = entry.links | link_id 45 | entry = entry._replace(links=new_links) 46 | new_meta = posting.meta.copy() 47 | for key in [*KEYS, 'memo']: 48 | new_meta.pop(key, None) 49 | new_meta['filename'] = entry.meta['filename'] 50 | new_meta['lineno'] = entry.meta['lineno'] 51 | new_entry = entry._replace( 52 | payee=None, 53 | narration=memo, 54 | # tags=set(), 55 | links=link_id, 56 | meta=new_meta, 57 | postings=new_postings) 58 | add_entries.append(new_entry) 59 | new_entries.append(entry) 60 | new_entries.extend(add_entries) 61 | return new_entries, errors 62 | -------------------------------------------------------------------------------- /refried/plugins/rebudget.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from refried import is_account_account 3 | from beancount.core import convert, interpolate 4 | from beancount.core.data import Open, Transaction, filter_txns 5 | from beancount.core.inventory import Inventory 6 | 7 | __plugins__ = ('rebudget', 'balance_check') 8 | 9 | BudgetBalanceError = collections.namedtuple('BudgetBalanceError', 'source message entry') 10 | 11 | def rebudget_entry(entry): 12 | if isinstance(entry, Transaction): 13 | for posting in entry.postings: 14 | if is_account_account(posting.account): 15 | break 16 | else: 17 | if 'tx' not in entry.tags: 18 | return entry._replace(tags=(entry.tags | frozenset(('rebudget',)))) 19 | return entry 20 | 21 | def rebudget(entries, options_map): 22 | return [rebudget_entry(e) for e in entries], [] 23 | 24 | def balance_check(entries, options_map): 25 | errors = [] 26 | tracking_accounts = set() 27 | for entry in entries: 28 | if isinstance(entry, Open): 29 | if entry.meta.get('tracking', False): 30 | tracking_accounts.add(entry.account) 31 | asum = Inventory() 32 | bsum = Inventory() 33 | for entry in filter_txns(entries): 34 | for posting in entry.postings: 35 | if posting.account in tracking_accounts: 36 | continue 37 | components = posting.account.split(':') 38 | if components[0] in ('Assets', 'Liabilities'): 39 | asum.add_position(posting) 40 | elif components[0] in ('Income', 'Expenses'): 41 | bsum.add_position(posting) 42 | asum = asum.reduce(convert.get_weight) 43 | bsum = bsum.reduce(convert.get_weight) 44 | csum = asum + bsum 45 | if not csum.is_small(interpolate.infer_tolerances({}, options_map)): 46 | errors.append( 47 | BudgetBalanceError( 48 | {'filename': '', 49 | 'lineno': 0}, 50 | f"On-budget accounts and budget total do not match: {asum} vs {-bsum} -- difference of {csum}", 51 | None)) 52 | return entries, errors 53 | -------------------------------------------------------------------------------- /refried/plugins/tracking.py: -------------------------------------------------------------------------------- 1 | from beancount.core import compare 2 | from beancount.core.data import Open, Posting, Transaction 3 | from beancount.core.account_types import is_account_type 4 | from beancount.core.inventory import Inventory 5 | from beancount.parser.options import get_account_types 6 | 7 | __plugins__ = ('tracking',) 8 | 9 | def tracking(entries, options_map): 10 | account_types = get_account_types(options_map) 11 | income_tracking = set() 12 | expense_tracking = set() 13 | 14 | errors = [] 15 | new_entries = [] 16 | for entry in entries: 17 | new_entry = None 18 | if isinstance(entry, Open) and entry.meta.get('tracking', False): 19 | if is_account_type(account_types.expenses, entry.account): 20 | expense_tracking.add(entry.account) 21 | elif is_account_type(account_types.income, entry.account): 22 | income_tracking.add(entry.account) 23 | elif isinstance(entry, Transaction): 24 | new_postings = [] 25 | tracking_balance = Inventory() 26 | for posting in entry.postings: 27 | if 'tracking' in posting.meta: 28 | new_acct = posting.meta['tracking'] 29 | new_posting = posting._replace(account=new_acct, meta=None) 30 | new_postings.append(new_posting) 31 | tracking_balance.add_position(posting) 32 | if new_postings: 33 | for position in -tracking_balance: 34 | if position.units.number < 0 and len(income_tracking) == 1: 35 | posting_acct ,= income_tracking 36 | elif position.units.number > 0 and len(expense_tracking) == 1: 37 | posting_acct ,= expense_tracking 38 | else: 39 | continue 40 | new_posting = Posting(posting_acct, position.units, position.cost, None, None, None) 41 | new_postings.append(new_posting) 42 | 43 | link_id = 'tracking-' + compare.hash_entry(entry) 44 | new_links = entry.links | set([link_id]) 45 | entry = entry._replace(links=new_links) 46 | new_entry = entry._replace( 47 | postings=new_postings) 48 | new_entries.append(entry) 49 | if new_entry: 50 | new_entries.append(new_entry) 51 | return new_entries, errors 52 | -------------------------------------------------------------------------------- /refried/plugins/wishfarm.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from beancount.core.data import Open, Custom 3 | from beancount.core import account as acctops 4 | 5 | __plugins__ = ('wishfarm',) 6 | 7 | WishfarmError = collections.namedtuple('WishfarmError', 'source message entry') 8 | 9 | def wishfarm(entries, options_map): 10 | errors = [] 11 | wish_sprouts = {} 12 | for entry in entries: 13 | if isinstance(entry, Open): 14 | if 'wish_slot' in entry.meta: 15 | slot = entry.meta['wish_slot'] 16 | if 'name' in entry.meta: 17 | errors.append( 18 | WishfarmError( 19 | entry.meta, 20 | 'name should be handled by wishfarm plugin', 21 | [entry])) 22 | continue 23 | tag = entry.meta.get('tag') 24 | if tag is None: 25 | tag = acctops.split(entry.account)[-1] 26 | if slot in wish_sprouts: 27 | errors.append( 28 | WishfarmError( 29 | entry.meta, 30 | f'Duplicate wish_slot: "{slot}"', 31 | [wish_sprouts[slot], entry])) 32 | continue 33 | wish_sprouts[slot] = (entry, tag) 34 | entry.meta['name'] = f'({tag}) ...' 35 | for entry in entries: 36 | if isinstance(entry, Custom) and entry.type == "wish-list": 37 | if 'wish_slot' in entry.meta: 38 | slot = entry.meta['wish_slot'] 39 | if slot not in wish_sprouts: 40 | errors.append( 41 | WishfarmError( 42 | entry.meta, 43 | f'Unavailable wish_slot: "{slot}"', 44 | entry)) 45 | continue 46 | sprout, slot_name = wish_sprouts.pop(slot) 47 | wish_name = entry.values[0].value 48 | sprout.meta['wish_name'] = wish_name 49 | sprout.meta['wish_filename'] = entry.meta['filename'] 50 | sprout.meta['wish_lineno'] = entry.meta['lineno'] 51 | sprout.meta.update({k: v for k, v in entry.meta.items() if k not in sprout.meta}) 52 | sprout.meta['name'] = f'({slot_name}) {wish_name}' 53 | return entries, errors 54 | -------------------------------------------------------------------------------- /refried/scripts/hello.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | def main(): 4 | print("hi") 5 | 6 | if __name__ == '__main__': 7 | main() 8 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scauligi/refried/cf64dfa8d116e860a7115d5990522808eeefea91/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_clearing.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from beancount.core.data import Transaction 4 | from beancount.parser import cmptest 5 | from beancount import loader 6 | 7 | from . import test_utils 8 | 9 | def _underscore_cleared_posting(p): 10 | if 'cleared' in p.meta: 11 | p.meta['_cleared'] = p.meta['cleared'] 12 | del p.meta['cleared'] 13 | return p 14 | 15 | def _underscore_cleared_entry(e): 16 | if isinstance(e, Transaction): 17 | e = e._replace(postings=list(map(_underscore_cleared_posting, e.postings))) 18 | return e 19 | 20 | def _underscore_cleared(entries_or_str): 21 | entries = cmptest.read_string_or_entries(entries_or_str) 22 | return list(map(_underscore_cleared_entry, entries)) 23 | 24 | class TestClearing(test_utils.TestCase): 25 | 26 | @loader.load_doc(expect_errors=False) 27 | def test_leave_alone(self, entries, errors, options): 28 | """ 29 | plugin "refried.plugins.clearing" 30 | 31 | 2020-05-28 open Expenses:Dining-Out 32 | 2020-05-28 open Income:Salary 33 | 34 | 2020-05-28 * 35 | Income:Salary -20 USD 36 | Expenses:Dining-Out 20 USD 37 | """ 38 | self.assertEqualEntries(self.test_leave_alone.__input__, entries) 39 | 40 | @loader.load_doc(expect_errors=False) 41 | def test_uncleared(self, entries, errors, options): 42 | """ 43 | plugin "refried.plugins.clearing" 44 | 45 | 2020-05-28 open Assets:Cash 46 | 2020-05-28 open Liabilities:Credit 47 | 2020-05-28 open Expenses:Dining-Out 48 | 49 | 2020-05-28 * 50 | Assets:Cash -20 USD 51 | Liabilities:Credit 20 USD 52 | 53 | 2020-05-28 * 54 | Assets:Cash -20 USD 55 | Expenses:Dining-Out 20 USD 56 | 57 | 2020-05-29 * 58 | Assets:Cash -20 USD 59 | uncleared: 60 | Expenses:Dining-Out 20 USD 61 | """ 62 | expected = _underscore_cleared(""" 63 | plugin "refried.plugins.clearing" 64 | 65 | 2020-05-28 open Assets:Cash 66 | 2020-05-28 open Liabilities:Credit 67 | 2020-05-28 open Expenses:Dining-Out 68 | 69 | 2020-05-28 * 70 | Assets:Cash -20 USD 71 | cleared: FALSE 72 | Liabilities:Credit 20 USD 73 | cleared: FALSE 74 | 75 | 2020-05-28 * 76 | Assets:Cash -20 USD 77 | cleared: FALSE 78 | Expenses:Dining-Out 20 USD 79 | 80 | 2020-05-29 * 81 | Assets:Cash -20 USD 82 | cleared: FALSE 83 | Expenses:Dining-Out 20 USD 84 | """) 85 | self.assertEqualEntries(expected, entries) 86 | 87 | @loader.load_doc(expect_errors=False) 88 | def test_autoclear(self, entries, errors, options): 89 | """ 90 | plugin "refried.plugins.clearing" 91 | 92 | 2020-05-28 open Assets:Cash 93 | autoclear: TRUE 94 | 2020-05-28 open Liabilities:Credit 95 | 2020-05-28 open Expenses:Dining-Out 96 | 97 | 2020-05-28 * 98 | Assets:Cash -20 USD 99 | Liabilities:Credit 20 USD 100 | 101 | 2020-05-28 * 102 | Assets:Cash -20 USD 103 | Expenses:Dining-Out 20 USD 104 | 105 | 2020-05-29 * 106 | Assets:Cash -20 USD 107 | uncleared: 108 | Expenses:Dining-Out 20 USD 109 | """ 110 | expected = _underscore_cleared(""" 111 | plugin "refried.plugins.clearing" 112 | 113 | 2020-05-28 open Assets:Cash 114 | autoclear: TRUE 115 | 2020-05-28 open Liabilities:Credit 116 | 2020-05-28 open Expenses:Dining-Out 117 | 118 | 2020-05-28 * 119 | Assets:Cash -20 USD 120 | cleared: TRUE 121 | Liabilities:Credit 20 USD 122 | cleared: FALSE 123 | 124 | 2020-05-28 * 125 | Assets:Cash -20 USD 126 | cleared: TRUE 127 | Expenses:Dining-Out 20 USD 128 | 129 | 2020-05-29 * 130 | Assets:Cash -20 USD 131 | cleared: FALSE 132 | Expenses:Dining-Out 20 USD 133 | """) 134 | self.assertEqualEntries(expected, entries) 135 | 136 | @loader.load_doc(expect_errors=False) 137 | def test_cleared_before(self, entries, errors, options): 138 | """ 139 | plugin "refried.plugins.clearing" 140 | 141 | 2020-05-28 open Assets:Cash 142 | cleared_before: 2020-06-01 143 | 2020-05-28 open Expenses:Dining-Out 144 | 145 | 2020-05-28 * 146 | Assets:Cash -20 USD 147 | Expenses:Dining-Out 20 USD 148 | 149 | 2020-05-29 * 150 | Assets:Cash -20 USD 151 | uncleared: 152 | Expenses:Dining-Out 20 USD 153 | 154 | 2020-06-01 * 155 | Assets:Cash -20 USD 156 | Expenses:Dining-Out 20 USD 157 | 158 | 2020-06-02 * 159 | Assets:Cash -20 USD 160 | Expenses:Dining-Out 20 USD 161 | """ 162 | expected = _underscore_cleared(""" 163 | plugin "refried.plugins.clearing" 164 | 165 | 2020-05-28 open Assets:Cash 166 | cleared_before: 2020-06-01 167 | 2020-05-28 open Expenses:Dining-Out 168 | 169 | 2020-05-28 * 170 | Assets:Cash -20 USD 171 | cleared: TRUE 172 | Expenses:Dining-Out 20 USD 173 | 174 | 2020-05-29 * 175 | Assets:Cash -20 USD 176 | cleared: FALSE 177 | Expenses:Dining-Out 20 USD 178 | 179 | 2020-06-01 * 180 | Assets:Cash -20 USD 181 | cleared: FALSE 182 | Expenses:Dining-Out 20 USD 183 | 184 | 2020-06-02 * 185 | Assets:Cash -20 USD 186 | cleared: FALSE 187 | Expenses:Dining-Out 20 USD 188 | """) 189 | self.assertEqualEntries(expected, entries) 190 | 191 | @loader.load_doc(expect_errors=False) 192 | def test_date(self, entries, errors, options): 193 | """ 194 | plugin "refried.plugins.clearing" 195 | 196 | 2020-05-28 open Assets:Cash 197 | 2020-05-28 open Expenses:Dining-Out 198 | 199 | 2020-05-28 * 200 | Assets:Cash -20 USD 201 | date: 202 | Expenses:Dining-Out 20 USD 203 | 204 | 2020-05-29 * 205 | Assets:Cash -20 USD 206 | date: 207 | uncleared: 208 | Expenses:Dining-Out 20 USD 209 | """ 210 | expected = _underscore_cleared(""" 211 | plugin "refried.plugins.clearing" 212 | 213 | 2020-05-28 open Assets:Cash 214 | 2020-05-28 open Expenses:Dining-Out 215 | 216 | 2020-05-28 * 217 | Assets:Cash -20 USD 218 | cleared: TRUE 219 | date: 220 | Expenses:Dining-Out 20 USD 221 | 222 | 2020-05-29 * 223 | Assets:Cash -20 USD 224 | cleared: FALSE 225 | date: 226 | Expenses:Dining-Out 20 USD 227 | """) 228 | self.assertEqualEntries(expected, entries) 229 | 230 | if __name__ == '__main__': 231 | unittest.main() 232 | -------------------------------------------------------------------------------- /tests/test_evensplit.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from beancount.parser import cmptest 4 | from beancount import loader 5 | from beancount.utils import test_utils 6 | 7 | from . import test_utils 8 | 9 | class TestEvensplit(test_utils.TestCase): 10 | 11 | @loader.load_doc(expect_errors=False) 12 | def test_split(self, entries, errors, options): 13 | """ 14 | plugin "refried.plugins.evensplit" 15 | 16 | 2020-05-28 open Assets:Cash 17 | 2020-05-28 open Liabilities:Partner 18 | 2020-05-28 open Expenses:Dining-Out 19 | 20 | 2020-05-28 * 21 | Assets:Cash -20 USD 22 | Expenses:Dining-Out 20 USD 23 | split: Liabilities:Partner 24 | """ 25 | self.assertEqualEntries(""" 26 | 2020-05-28 open Assets:Cash 27 | 2020-05-28 open Liabilities:Partner 28 | 2020-05-28 open Expenses:Dining-Out 29 | 30 | 2020-05-28 * 31 | Assets:Cash -20 USD 32 | Expenses:Dining-Out 10 USD 33 | split: Liabilities:Partner 34 | Liabilities:Partner 10 USD 35 | """, entries) 36 | 37 | @loader.load_doc(expect_errors=False) 38 | def test_split_joining(self, entries, errors, options): 39 | """ 40 | plugin "refried.plugins.evensplit" 41 | 42 | 2020-05-28 open Assets:Cash 43 | 2020-05-28 open Liabilities:Partner 44 | 2020-05-28 open Expenses:Dining-Out 45 | 2020-05-28 open Expenses:Household 46 | 47 | 2020-05-28 * 48 | Assets:Cash -30 USD 49 | Expenses:Dining-Out 20 USD 50 | split: Liabilities:Partner 51 | Expenses:Household 10 USD 52 | split: Liabilities:Partner 53 | """ 54 | self.assertEqualEntries(""" 55 | 2020-05-28 open Assets:Cash 56 | 2020-05-28 open Liabilities:Partner 57 | 2020-05-28 open Expenses:Dining-Out 58 | 2020-05-28 open Expenses:Household 59 | 60 | 2020-05-28 * 61 | Assets:Cash -30 USD 62 | Expenses:Dining-Out 10 USD 63 | split: Liabilities:Partner 64 | Expenses:Household 5 USD 65 | split: Liabilities:Partner 66 | Liabilities:Partner 15 USD 67 | """, entries) 68 | 69 | @loader.load_doc(expect_errors=False) 70 | def test_with_interpolation(self, entries, errors, options): 71 | """ 72 | plugin "refried.plugins.evensplit" 73 | 74 | 2020-05-28 open Assets:Cash 75 | 2020-05-28 open Liabilities:Partner 76 | 2020-05-28 open Expenses:Dining-Out 77 | 78 | 2020-05-28 * 79 | Assets:Cash -20 USD 80 | Expenses:Dining-Out 81 | split: Liabilities:Partner 82 | """ 83 | self.assertEqualEntries(""" 84 | 2020-05-28 open Assets:Cash 85 | 2020-05-28 open Liabilities:Partner 86 | 2020-05-28 open Expenses:Dining-Out 87 | 88 | 2020-05-28 * 89 | Assets:Cash -20 USD 90 | Expenses:Dining-Out 10 USD 91 | split: Liabilities:Partner 92 | Liabilities:Partner 10 USD 93 | """, entries) 94 | 95 | @loader.load_doc(expect_errors=False) 96 | def test_with_meta(self, entries, errors, options): 97 | """ 98 | plugin "refried.plugins.evensplit" 99 | 100 | 2020-05-28 open Assets:Cash 101 | 2020-05-28 open Liabilities:Partner 102 | 2020-05-28 open Expenses:Dining-Out 103 | 104 | 2020-05-28 * 105 | Assets:Cash -20 USD 106 | Expenses:Dining-Out 107 | meta: "data" 108 | split: Liabilities:Partner 109 | """ 110 | self.assertEqualEntries(""" 111 | 2020-05-28 open Assets:Cash 112 | 2020-05-28 open Liabilities:Partner 113 | 2020-05-28 open Expenses:Dining-Out 114 | 115 | 2020-05-28 * 116 | Assets:Cash -20 USD 117 | Expenses:Dining-Out 10 USD 118 | meta: "data" 119 | split: Liabilities:Partner 120 | Liabilities:Partner 10 USD 121 | meta: "data" 122 | """, entries) 123 | 124 | @loader.load_doc(expect_errors=False) 125 | def test_with_meta_sanity(self, entries, errors, options): 126 | """ 127 | plugin "refried.plugins.evensplit" 128 | 129 | 2020-05-28 open Assets:Cash 130 | 2020-05-28 open Liabilities:Partner 131 | 2020-05-28 open Expenses:Dining-Out 132 | 133 | 2020-05-28 * 134 | Assets:Cash -20 USD 135 | Expenses:Dining-Out 136 | meta: "data" 137 | split: Liabilities:Partner 138 | """ 139 | with self.assertRaises(AssertionError): 140 | self.assertEqualEntries(""" 141 | 2020-05-28 open Assets:Cash 142 | 2020-05-28 open Liabilities:Partner 143 | 2020-05-28 open Expenses:Dining-Out 144 | 145 | 2020-05-28 * 146 | Assets:Cash -20 USD 147 | Expenses:Dining-Out 10 USD 148 | meta: "data" 149 | split: Liabilities:Partner 150 | Liabilities:Partner 10 USD 151 | ; meta: "data" 152 | """, entries) 153 | 154 | if __name__ == '__main__': 155 | unittest.main() 156 | -------------------------------------------------------------------------------- /tests/test_period.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import datetime 3 | from refried import Period 4 | 5 | class TestPeriod(unittest.TestCase): 6 | def test_add0(self): 7 | p = Period(2020, 1) 8 | self.assertEqual(p, p.add(0)) 9 | p = Period(2020, 2) 10 | self.assertEqual(p, p.add(0)) 11 | p = Period(2020, 11) 12 | self.assertEqual(p, p.add(0)) 13 | p = Period(2020, 12) 14 | self.assertEqual(p, p.add(0)) 15 | 16 | def test_add1(self): 17 | p1 = Period(2020, 1) 18 | p2 = Period(2020, 2) 19 | p3 = Period(2020, 3) 20 | p11 = Period(2020, 11) 21 | p12 = Period(2020, 12) 22 | p13 = Period(2021, 1) 23 | self.assertEqual(p1.add(1), p2) 24 | self.assertEqual(p2.add(1), p3) 25 | self.assertEqual(p11.add(1), p12) 26 | self.assertEqual(p12.add(1), p13) 27 | self.assertEqual(p1, p2.sub(1)) 28 | self.assertEqual(p2, p3.sub(1)) 29 | self.assertEqual(p11, p12.sub(1)) 30 | self.assertEqual(p12, p13.sub(1)) 31 | 32 | def test_add4(self): 33 | p1 = Period(2020, 1) 34 | p2 = Period(2020, 2) 35 | p5 = Period(2020, 5) 36 | p6 = Period(2020, 6) 37 | p8 = Period(2020, 8) 38 | p9 = Period(2020, 9) 39 | p10 = Period(2020, 10) 40 | p12 = Period(2020, 12) 41 | p13 = Period(2021, 1) 42 | p14 = Period(2021, 2) 43 | self.assertEqual(p1.add(4), p5) 44 | self.assertEqual(p2.add(4), p6) 45 | self.assertEqual(p8.add(4), p12) 46 | self.assertEqual(p9.add(4), p13) 47 | self.assertEqual(p10.add(4), p14) 48 | 49 | def test_asdate(self): 50 | p = Period(2020, 5) 51 | self.assertEqual(p.asdate(), datetime.date(2020, 5, 1)) 52 | 53 | if __name__ == '__main__': 54 | unittest.main() 55 | -------------------------------------------------------------------------------- /tests/test_rebudget.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from beancount.parser import cmptest 4 | from beancount import loader 5 | 6 | import refried 7 | 8 | class TestRebudget(cmptest.TestCase): 9 | 10 | @loader.load_doc(expect_errors=False) 11 | def test_leave_alone(self, entries, errors, options): 12 | """ 13 | plugin "refried.plugins.rebudget" 14 | 15 | 2020-05-28 open Assets:Cash 16 | 2020-05-28 open Liabilities:Credit 17 | 18 | 2020-05-28 * 19 | Assets:Cash -20 USD 20 | Liabilities:Credit 20 USD 21 | """ 22 | self.assertEqualEntries(self.test_leave_alone.__input__, entries) 23 | 24 | @loader.load_doc(expect_errors=False) 25 | def test_expense_expense(self, entries, errors, options): 26 | """ 27 | plugin "refried.plugins.rebudget" 28 | 29 | 2020-05-28 open Expenses:Dining-Out 30 | 2020-05-28 open Expenses:Groceries 31 | 32 | 2020-05-28 * 33 | Expenses:Dining-Out -20 USD 34 | Expenses:Groceries 20 USD 35 | """ 36 | self.assertEqualEntries(""" 37 | plugin "refried.plugins.rebudget" 38 | 39 | 2020-05-28 open Expenses:Dining-Out 40 | 2020-05-28 open Expenses:Groceries 41 | 42 | 2020-05-28 * #rebudget 43 | Expenses:Dining-Out -20 USD 44 | Expenses:Groceries 20 USD 45 | """, entries) 46 | 47 | @loader.load_doc(expect_errors=False) 48 | def test_existing_tag(self, entries, errors, options): 49 | """ 50 | plugin "refried.plugins.rebudget" 51 | 52 | 2020-05-28 open Expenses:Dining-Out 53 | 2020-05-28 open Expenses:Groceries 54 | 55 | 2020-05-28 * #tagged 56 | Expenses:Dining-Out -20 USD 57 | Expenses:Groceries 20 USD 58 | """ 59 | self.assertEqualEntries(""" 60 | plugin "refried.plugins.rebudget" 61 | 62 | 2020-05-28 open Expenses:Dining-Out 63 | 2020-05-28 open Expenses:Groceries 64 | 65 | 2020-05-28 * #tagged #rebudget 66 | Expenses:Dining-Out -20 USD 67 | Expenses:Groceries 20 USD 68 | """, entries) 69 | 70 | @loader.load_doc(expect_errors=False) 71 | def test_expense_income(self, entries, errors, options): 72 | """ 73 | plugin "refried.plugins.rebudget" 74 | 75 | 2020-05-28 open Expenses:Dining-Out 76 | 2020-05-28 open Income:Salary 77 | 78 | 2020-05-28 * 79 | Expenses:Dining-Out -20 USD 80 | Income:Salary 20 USD 81 | """ 82 | self.assertEqualEntries(""" 83 | plugin "refried.plugins.rebudget" 84 | 85 | 2020-05-28 open Expenses:Dining-Out 86 | 2020-05-28 open Income:Salary 87 | 88 | 2020-05-28 * #rebudget 89 | Expenses:Dining-Out -20 USD 90 | Income:Salary 20 USD 91 | """, entries) 92 | 93 | @loader.load_doc(expect_errors=True) 94 | def test_expense_equity(self, entries, errors, options): 95 | """ 96 | plugin "refried.plugins.rebudget" 97 | 98 | 2020-05-28 open Expenses:Dining-Out 99 | 2020-05-28 open Equity:Something 100 | 101 | 2020-05-28 * 102 | Expenses:Dining-Out -20 USD 103 | Equity:Something 20 USD 104 | """ 105 | self.assertEqualEntries(""" 106 | plugin "refried.plugins.rebudget" 107 | 108 | 2020-05-28 open Expenses:Dining-Out 109 | 2020-05-28 open Equity:Something 110 | 111 | 2020-05-28 * #rebudget 112 | Expenses:Dining-Out -20 USD 113 | Equity:Something 20 USD 114 | """, entries) 115 | 116 | @loader.load_doc(expect_errors=True) 117 | def test_tracking_mismatch(self, entries, errors, options): 118 | """ 119 | plugin "refried.plugins.rebudget" 120 | 121 | 2020-09-21 open Assets:Cash 122 | 2020-09-21 open Assets:IRA 123 | tracking: TRUE 124 | 125 | 2020-09-21 * 126 | Assets:Cash -20 USD 127 | Assets:IRA 20 USD 128 | """ 129 | self.assertEqual(len(errors), 1) 130 | self.assertIsInstance(errors[0], refried.plugins.rebudget.BudgetBalanceError) 131 | 132 | @loader.load_doc(expect_errors=False) 133 | def test_tracking_ok(self, entries, errors, options): 134 | """ 135 | plugin "refried.plugins.rebudget" 136 | 137 | 2020-09-21 open Assets:Cash 138 | 2020-09-21 open Assets:IRA 139 | tracking: TRUE 140 | 2020-09-21 open Expenses:Money-for-IRA 141 | 2020-09-21 open Income:Tracking 142 | tracking: TRUE 143 | 144 | 2020-09-21 * 145 | Assets:Cash -20 USD 146 | Assets:IRA 20 USD 147 | 148 | 2020-09-21 * 149 | Income:Tracking -20 USD 150 | Expenses:Money-for-IRA 20 USD 151 | """ 152 | pass 153 | -------------------------------------------------------------------------------- /tests/test_refried.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | import refried 4 | from refried import * 5 | 6 | from decimal import Decimal 7 | 8 | def test_version(): 9 | assert refried.__version__ == '0.7.0' 10 | 11 | class TestRefried(unittest.TestCase): 12 | def test_halfcents(self): 13 | self.assertEqual(halfcents(Decimal(0)), '0.00') 14 | self.assertEqual(halfcents(Decimal(-0)), '0.00') 15 | self.assertEqual(halfcents(Decimal(1)), '1.00') 16 | self.assertEqual(halfcents(Decimal('.23')), '0.23') 17 | self.assertEqual(halfcents(Decimal('2.3')), '2.30') 18 | self.assertEqual(halfcents(Decimal('2.345')), '2.345') 19 | self.assertEqual(halfcents(Decimal('-2.3')), '-2.30') 20 | self.assertEqual(halfcents(Decimal('-2.345')), '-2.345') 21 | self.assertEqual(halfcents(Decimal('2932.34')), '2,932.34') 22 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import io 2 | import hashlib 3 | import contextlib 4 | 5 | from beancount.parser import cmptest, printer 6 | from beancount.core import compare 7 | 8 | class TestCase(cmptest.TestCase): 9 | def assertEqualEntries(self, expected_entries, actual_entries): 10 | return assertEqualEntriesIncludingMeta(expected_entries, actual_entries, self.fail) 11 | def assertIncludesEntries(self, subset_entries, entries): 12 | raise NotImplementedError 13 | def assertExcludesEntries(self, subset_entries, entries): 14 | raise NotImplementedError 15 | 16 | @contextlib.contextmanager 17 | def meta_hashed_entries(): 18 | old_ignored_names = compare.IGNORED_FIELD_NAMES.copy() 19 | old_stable_hash_namedtuple = compare.stable_hash_namedtuple 20 | compare.IGNORED_FIELD_NAMES.remove('meta') 21 | compare.stable_hash_namedtuple = stable_hash_namedtuple 22 | try: 23 | yield 24 | finally: 25 | compare.IGNORED_FIELD_NAMES = old_ignored_names 26 | compare.stable_hash_namedtuple = old_stable_hash_namedtuple 27 | 28 | def assertEqualEntriesIncludingMeta(*args, **kwargs): 29 | with meta_hashed_entries(): 30 | return cmptest.assertEqualEntries(*args, **kwargs) 31 | 32 | IGNORE_META = ('filename', 'lineno', '__tolerances__', '__automatic__') 33 | 34 | # Taken from beancount.core.compare.stable_hash_namedtuple 35 | def stable_hash_namedtuple(objtuple, ignore=frozenset()): 36 | hashobj = hashlib.md5() 37 | for attr_name, attr_value in zip(objtuple._fields, objtuple): 38 | if attr_name in ignore: 39 | continue 40 | if isinstance(attr_value, (list, set, frozenset)): 41 | subhashes = set() 42 | for element in attr_value: 43 | if isinstance(element, tuple): 44 | subhashes.add(stable_hash_namedtuple(element, ignore)) 45 | else: 46 | md5 = hashlib.md5() 47 | md5.update(str(element).encode()) 48 | subhashes.add(md5.hexdigest()) 49 | for subhash in sorted(subhashes): 50 | hashobj.update(subhash.encode()) 51 | elif isinstance(attr_value, dict): 52 | subhashes = set() 53 | for key, value in attr_value.items(): 54 | if key in IGNORE_META: 55 | continue 56 | md5 = hashlib.md5() 57 | md5.update(str((key, value)).encode()) 58 | subhashes.add(md5.hexdigest()) 59 | for subhash in sorted(subhashes): 60 | hashobj.update(subhash.encode()) 61 | else: 62 | hashobj.update(str(attr_value).encode()) 63 | return hashobj.hexdigest() 64 | --------------------------------------------------------------------------------