commit 2cffc3ab07934be654d2a3cd25e65176cb09c29a Author: LibrePortal Date: Thu Sep 17 01:17:16 2026 +0100 Start LibreLedger: an encrypted money ledger that stores only ciphertext LibreLedger is a single-person money ledger. The browser encrypts everything (PBKDF2-HMAC-SHA256 with 250k iterations, then AES-256-GCM), and a small standard-library Python server stores only the resulting {v, salt, iv, ct} blob. Ledger files from the earlier Money Ledger version open unchanged. - On plain http to a LAN or VPN address, where browsers hide Web Crypto, the app switches to vendored @noble/hashes and @noble/ciphers 2.2.0 and says so on the lock screen. tests/crypto-interop.test.mjs shows both paths read each other's files. - The server hands out only the app's own files, sends a self-only CSP, nosniff, frame denial and no-referrer, checks the shape of each blob, refuses cross-site writes and writes atomically. It keeps the last 10 backups plus one per day for 30 days. - The container runs that server from a digest-pinned python alpine image, as an unprivileged user, with its data in /data and a health check on /api/health. Assisted-by: Claude Opus 5 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..137241b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +* +!server.py +!index.html +!app.js +!theme.js +!crypto-fallback.js +!styles.css +!favicon.svg +!banks/*.svg +!vendor/** diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b854338 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# Encrypted ledger data: never commit it, even though it is encrypted +data/ +*.enc +*.enc.bak +*.enc.* + +# Local design-reference screenshots may contain real figures +preview.png + +# Local Claude Code settings +.claude/ + +# Test output and caches +tests/out/ +__pycache__/ +*.pyc + +# OS / editor cruft +.DS_Store +Thumbs.db +*.swp diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..852f2fb --- /dev/null +++ b/Dockerfile @@ -0,0 +1,44 @@ +# LibreLedger — the app plus its persistence server (server.py, standard +# library only). The browser encrypts; the container only stores ciphertext. +# +# Build: docker build -t libreledger . +# Run: docker run --rm -p 8080:8080 -v libreledger-data:/data libreledger +# Open: http://localhost:8080 +# +# Base image pinned by version AND index digest (multi-arch). Bump both together. +FROM python:3.14.7-alpine3.24@sha256:c6ead215bfd31f1e433d968853b7a769989117115b728874824e6c0a27cb96fc + +ARG VERSION=1.0.0 +LABEL org.opencontainers.image.title="LibreLedger" \ + org.opencontainers.image.description="Encrypted personal money ledger: your data is encrypted in your browser; the server never sees it." \ + org.opencontainers.image.version="${VERSION}" \ + org.opencontainers.image.source="https://git.libreportal.org/LibrePortal/LibreLedger" \ + org.opencontainers.image.licenses="AGPL-3.0-only" + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + LIBRELEDGER_HOST=0.0.0.0 \ + LIBRELEDGER_PORT=8080 \ + LIBRELEDGER_DATA_DIR=/data + +# Unprivileged by default. LibrePortal may override the uid so the process +# owns its bind mount (under rootless Docker that is container root, which is +# the unprivileged install user on the host). +RUN addgroup -S -g 10001 libreledger \ + && adduser -S -D -H -u 10001 -G libreledger -s /sbin/nologin libreledger \ + && mkdir -p /data \ + && chown libreledger:libreledger /data \ + && chmod 700 /data + +WORKDIR /app +COPY --chmod=0444 server.py index.html app.js theme.js crypto-fallback.js styles.css favicon.svg ./ +COPY --chmod=0444 banks/*.svg ./banks/ +COPY --chmod=0444 vendor/ ./vendor/ +RUN find /app -type d -exec chmod 0555 {} + + +USER libreledger +EXPOSE 8080 +VOLUME ["/data"] +HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ + CMD ["python3", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=4).status == 200 else 1)"] +CMD ["python3", "/app/server.py"] diff --git a/LICENSE b/LICENSE new file mode 100755 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..01d2529 --- /dev/null +++ b/README.md @@ -0,0 +1,136 @@ +# LibreLedger + +An encrypted personal money ledger: **your data is encrypted in your browser; +the server never sees it.** + +One screen, one continuous running balance: + +- **Balances** at the top: your accounts and their balances, with a grand total. That total is where the ledger *opens*. +- **Monthly ledger** below: one block per month, a table of `Date · Type · Description · In · Out · Balance`. The balance runs on from your account balances and **carries from each month into the next**. + - **Type** comes from the row: money *in* shows a green **Money** badge, money *out* an amber **Cost** badge. + - Each row has a **category** (emoji and colour) for tagging entries at a glance. + - Insert or remove rows anywhere, and add or remove whole months. +- **Recurring** bills and income (rent, phone, salary…), each with an amount, a category and a schedule: + - **Monthly** on a chosen day, **every N weeks** from an anchor date, or **yearly** on a month and day. + - **🔁 Add recurring** drops every matching occurrence into a month as real, editable rows; **+ Add month** moves to the next calendar month and pre-fills it. +- **Totals**, **Savings** and **Housing affordability** summaries, several **budgets** in one ledger, CSV and PDF export. +- **Dark / light theme**, dark by default. + +## Zero-knowledge encryption + +- Everything is encrypted **in the browser** with **AES-256-GCM**. The key is + derived from your passphrase with **PBKDF2-HMAC-SHA256, 250,000 iterations** + and a random 16-byte salt; each save uses a fresh random 12-byte IV. +- The server (`server.py`) only stores and returns the resulting blob, + `{ "v": 1, "salt": …, "iv": …, "ct": … }` (base64). It never receives the + passphrase, the key or any figure from the ledger. +- There is no account and no recovery. **Lose the passphrase and the data is + gone**; that is the point. +- The page loads nothing from anywhere else. The server sends a strict + Content-Security-Policy (`'self'` only), `nosniff`, frame denial and + `no-referrer`, and serves only the app's own files. + +### Plain http on your LAN or VPN + +Browsers only give pages their built-in encryption (Web Crypto) in a *secure +context*: HTTPS or `http://localhost`. Opened as `http://192.168.x.x:port` or +over a VPN address, LibreLedger switches to its **built-in fallback**: the same +PBKDF2-SHA256 and AES-256-GCM from the audited +[@noble/hashes](https://github.com/paulmillr/noble-hashes) and +[@noble/ciphers](https://github.com/paulmillr/noble-ciphers) libraries, +vendored and pinned in [`vendor/`](vendor/README.md). The files it writes are +identical in format, so a ledger saved one way opens the other way. + +The lock screen says when the fallback is in use. Unlocking takes a few seconds +longer, and the key sits in page memory rather than in the browser's key store, +so **prefer HTTPS** whenever you have it. Plain http also means anyone on the +network path can see (encrypted) traffic and could tamper with the page itself, +so only use it on a network you trust. + +## Self-hosting + +### Docker + +```bash +docker run -d --name libreledger -p 127.0.0.1:8080:8080 \ + -v libreledger-data:/data \ + git.libreportal.org/libreportal/libreledger:1.0.0 +# open http://localhost:8080 +``` + +Or build it yourself: `docker build -t libreledger .` + +The image runs `server.py` on port 8080 as an unprivileged user, keeps its data +in the `/data` volume and has a health check on `/api/health`. Put HTTPS in +front of it (Caddy, Traefik, nginx…) when it is reachable from anywhere but +your own machine. + +### Without Docker + +```bash +python3 server.py # http://127.0.0.1:8080, data in ./data +python3 server.py --host 0.0.0.0 --port 8080 --data-dir /srv/libreledger +``` + +Python 3.9 or newer, standard library only. + +| Option | Environment | Default | +| --- | --- | --- | +| `--host` | `LIBRELEDGER_HOST` | `127.0.0.1` | +| `--port` | `LIBRELEDGER_PORT` | `8080` | +| `--data-dir` | `LIBRELEDGER_DATA_DIR` | `./data` | +| `--backup-interval` | `LIBRELEDGER_BACKUP_INTERVAL` | `600` seconds (`0`: every save) | +| `--backup-keep-recent` | `LIBRELEDGER_BACKUP_KEEP_RECENT` | `10` | +| `--backup-keep-daily` | `LIBRELEDGER_BACKUP_KEEP_DAILY` | `30` | + +### Your data + +- `/ledger.enc` is the ledger, written atomically on every change. +- `/backups/ledger-.enc` are earlier versions: the newest + 10, plus the last one of each of the most recent 30 days. At most one is taken + per backup interval. +- All of them are encrypted with the passphrase that was current when they were + written. To restore one, stop the server and copy it over `ledger.enc`, or + use **Restore** in the app. +- To move a ledger to another server, copy `ledger.enc` into its data folder + and unlock it with your passphrase. Files from the earlier "Money Ledger" + version of this app work as they are. + +The server has no login of its own: anyone who can reach it can fetch the +encrypted file or overwrite it (the backups cover the latter). Keep it on a +private network, a VPN, or behind an authenticating proxy. + +### Install on LibrePortal + +LibreLedger is in the [LibrePortal](https://git.libreportal.org/LibrePortal/LibrePortal) +app catalog: `libreportal app install libreledger`, or **Apps → LibreLedger** +in the WebUI. It installs *private* (reachable only from your trusted places), +with its data included in LibrePortal's backups, and on +`https://ledger.` when a domain is set up. + +## In the app + +- **💾 Saved to disk**: the encrypted ledger is saving to the server. +- **🔗 Link file** *(Chrome/Edge desktop, when opened without the server)*: + auto-save to an encrypted file you choose. +- **Export CSV / PDF**: plaintext exports of the decrypted data. Handle them with care. +- **Backup / Restore**: download or load an *encrypted* copy. +- **Change passphrase**: re-encrypts with a new passphrase. Older backups keep the old one. +- **Lock**: forgets the key and the data; the passphrase is needed again. + +## Development + +```bash +python3 tests/test_server.py # server: allowlist, headers, checks, backups +node tests/crypto-interop.test.mjs # Web Crypto <-> fallback interop (Node 22.12+) +``` + +Files: `index.html` (markup and lock screen), `styles.css`, `app.js` (state, +rendering and the crypto layer), `theme.js`, `crypto-fallback.js`, `server.py`, +`banks/` (logos, see `banks/NOTICE.txt`), `vendor/`. + +## Licence + +[GNU AGPLv3](LICENSE). The vendored noble libraries are MIT-licensed (their +`LICENSE` files are next to them); bank logos are trademarks of their owners +(`banks/NOTICE.txt`). diff --git a/app.js b/app.js new file mode 100644 index 0000000..336c7dd --- /dev/null +++ b/app.js @@ -0,0 +1,2691 @@ +"use strict"; + +/* ============================================================ + LibreLedger — single-page, client-side encrypted. + Everything is encrypted in this browser with AES-256-GCM, + using a key derived from your passphrase (PBKDF2). The + server (server.py) only ever stores the ciphertext. + ============================================================ */ + +// Storage names keep the app's original "money-ledger" prefix so existing +// browsers keep their cached ledger, theme and layout after the rename. +const STORAGE_KEY = "money-ledger-v1"; +const PBKDF2_ITERATIONS = 250000; + +let book = null; // the whole decrypted document: { version, activeId, budgets: [...] } +let state = null; // the ACTIVE budget — a reference into book.budgets (keeps all rendering code unchanged) +let cryptoKey = null; // CryptoKey, only present while unlocked +let currentSalt = null; // Uint8Array(16) +let mode = "unlock"; // "unlock" | "create" +let saveTimer = null; +let serverMode = false; // true when served by server.py (persists to data/ledger.enc on disk; works in any browser) +let fileHandle = null; // FileSystemFileHandle when a save file is actively linked (write permission held) +let rememberedName = null; // name of a remembered save file (from IndexedDB) even if not active this session +// File System Access API — only Chromium desktop. Everything degrades to localStorage when absent. +const FS_SUPPORTED = !!(window.showSaveFilePicker && window.showOpenFilePicker); + +/* ---------- element refs ---------- */ +const lock = document.getElementById("lock"); +const lockForm = document.getElementById("lock-form"); +const lockMsg = document.getElementById("lock-msg"); +const lockErr = document.getElementById("lock-err"); +const lockBtn = document.getElementById("lock-btn"); +const pass1 = document.getElementById("pass1"); +const pass2 = document.getElementById("pass2"); +const app = document.getElementById("app"); +const accountsBody = document.getElementById("accounts-body"); +const recurringBody = document.getElementById("recurring-body"); +const monthsBody = document.getElementById("months-body"); +const savingsBody = document.getElementById("savings-body"); +const affordBody = document.getElementById("afford-body"); +const totalsBody = document.getElementById("totals-body"); +const budgetBar = document.getElementById("budget-bar"); +const linkBtn = document.getElementById("btn-linkfile"); +const lockFs = document.getElementById("lock-fs"); +const currencyEl = document.getElementById("currency"); + +/* ---------- small helpers ---------- */ +const enc = new TextEncoder(); +const dec = new TextDecoder(); + +// crypto.randomUUID only exists in a secure context; getRandomValues works everywhere. +function uid() { + if (crypto.randomUUID) return crypto.randomUUID(); + const b = crypto.getRandomValues(new Uint8Array(16)); + b[6] = (b[6] & 0x0f) | 0x40; // version 4 + b[8] = (b[8] & 0x3f) | 0x80; // variant 10 + const h = Array.from(b, x => x.toString(16).padStart(2, "0")).join(""); + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`; +} +function num(v) { const n = parseFloat(v); return isNaN(n) ? 0 : n; } + +function fmt(v) { + const cur = (state && state.currency) || ""; + const neg = v < 0; + const s = Math.abs(v).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); + return (neg ? "-" : "") + cur + s; +} + +function esc(s) { + return String(s == null ? "" : s) + .replace(/&/g, "&").replace(/"/g, """) + .replace(//g, ">"); +} + +function setOne(sel, text) { const el = document.querySelector(sel); if (el) el.textContent = text; } +function setAll(sel, text) { document.querySelectorAll(sel).forEach(el => (el.textContent = text)); } + +function b64encode(buf) { + const bytes = new Uint8Array(buf); + let s = ""; + for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]); + return btoa(s); +} +function b64decode(str) { return Uint8Array.from(atob(str), c => c.charCodeAt(0)); } + +/* ---------- category tags (the little colour dots) ---------- */ +const TAG_COLORS = [ + { key: "", css: "transparent" }, + { key: "blue", css: "#3b82f6" }, + { key: "cyan", css: "#06b6d4" }, + { key: "violet", css: "#8b5cf6" }, + { key: "red", css: "#ef4444" }, + { key: "green", css: "#22c55e" }, + { key: "amber", css: "#f59e0b" }, + { key: "pink", css: "#ec4899" }, +]; +function tagCss(key) { const t = TAG_COLORS.find(t => t.key === key); return t ? t.css : "transparent"; } +function nextTag(key) { + const i = TAG_COLORS.findIndex(t => t.key === key); + return TAG_COLORS[(i < 0 ? 0 : i + 1) % TAG_COLORS.length].key; +} + +/* ---------- categories (icon + name + colour) ---------- */ +// The category is keyed by its emoji. Picking one stamps the icon and a default colour. +const CATEGORIES = [ + { icon: "💰", name: "Income", tag: "green" }, + { icon: "💼", name: "Work", tag: "blue" }, + { icon: "🏠", name: "Housing", tag: "blue" }, + { icon: "💡", name: "Utilities", tag: "amber" }, + { icon: "🌐", name: "Internet", tag: "cyan" }, + { icon: "📱", name: "Phone", tag: "cyan" }, + { icon: "🛒", name: "Groceries", tag: "green" }, + { icon: "🍔", name: "Eating out", tag: "amber" }, + { icon: "☕", name: "Coffee", tag: "amber" }, + { icon: "🍺", name: "Going out", tag: "violet" }, + { icon: "🚗", name: "Transport", tag: "violet" }, + { icon: "⛽", name: "Fuel", tag: "violet" }, + { icon: "🛡️", name: "Insurance", tag: "blue" }, + { icon: "🏥", name: "Health", tag: "red" }, + { icon: "💊", name: "Pharmacy", tag: "red" }, + { icon: "🏋️", name: "Fitness", tag: "green" }, + { icon: "🎬", name: "Entertainment", tag: "pink" }, + { icon: "📺", name: "Subscriptions", tag: "violet" }, + { icon: "🛍️", name: "Shopping", tag: "pink" }, + { icon: "🎁", name: "Gifts", tag: "pink" }, + { icon: "✈️", name: "Travel", tag: "cyan" }, + { icon: "🐷", name: "Savings", tag: "green" }, + { icon: "🏦", name: "Loans", tag: "red" }, + { icon: "💳", name: "Debt / Card", tag: "red" }, + { icon: "🧾", name: "Tax", tag: "amber" }, + { icon: "🎓", name: "Education", tag: "blue" }, + { icon: "👶", name: "Childcare", tag: "pink" }, + { icon: "🐶", name: "Pets", tag: "amber" }, +]; +const CAT_BY_ICON = new Map(CATEGORIES.map(c => [c.icon, c])); +const SAVINGS_ICON = "🐷"; // rows tagged with this category feed the Savings panel +const INCOME_ICON = "💰"; // rows tagged Income feed the affordability calculator's income +const HOUSING_ICON = "🏠"; // rows tagged Housing feed the affordability calculator's cost +function catOf(icon) { return CAT_BY_ICON.get(icon) || null; } +function catLabel(icon) { const c = catOf(icon); return c ? c.name : (icon ? icon : "Other"); } +// Stamp a category (icon + its colour) onto an entry. force=false only fills a colour that's empty. +function applyCat(entry, icon, force) { + entry.icon = icon || ""; + const c = catOf(entry.icon); + if (c && (force || !entry.tag)) entry.tag = c.tag; +} + +/* ---------- banks (account logos, with badge fallback) ---------- */ +// logo:true → bundled SVG at banks/.svg (brand-coloured); otherwise a brand-colour badge with `short`. +const BANKS = [ + { key: "monzo", name: "Monzo", color: "#FF4F40", logo: true }, + { key: "starlingbank", name: "Starling Bank", color: "#6935FF", logo: true }, + { key: "revolut", name: "Revolut", color: "#0666EB", logo: true }, + { key: "barclays", name: "Barclays", color: "#00AEEF", logo: true }, + { key: "hsbc", name: "HSBC", color: "#DB0011", logo: true }, + { key: "chase", name: "Chase", color: "#117ACA", logo: true }, + { key: "wise", name: "Wise", color: "#163300", logo: true }, + { key: "tide", name: "Tide", color: "#3C3CFF", logo: true }, + { key: "santander", name: "Santander", color: "#EC0000", logo: true }, + { key: "lloyds", name: "Lloyds Bank", color: "#024731", logo: true }, + { key: "natwest", name: "NatWest", color: "#5A287D", short: "NW" }, + { key: "nationwide", name: "Nationwide", color: "#1B0088", short: "N" }, + { key: "halifax", name: "Halifax", color: "#005EB8", short: "H" }, + { key: "tsb", name: "TSB", color: "#1B3A6B", logo: true }, + { key: "cooperative", name: "Co-operative Bank", color: "#00B6F1", short: "Co" }, + { key: "metro", name: "Metro Bank", color: "#E51937", short: "M" }, + { key: "virginmoney", name: "Virgin Money", color: "#E10A0A", logo: true }, + { key: "rbs", name: "Royal Bank of Scotland", color: "#142E64", logo: true }, + { key: "bankofscotland",name: "Bank of Scotland", color: "#002B6D", logo: true }, + { key: "firstdirect", name: "first direct", color: "#1A1A1A", short: "fd" }, + { key: "monese", name: "Monese", color: "#00B0A8", short: "Mo" }, + { key: "atom", name: "Atom Bank", color: "#E4002B", short: "A" }, + { key: "chip", name: "Chip", color: "#1A1A2E", short: "C" }, + { key: "amex", name: "American Express", color: "#2E77BC", logo: true }, + { key: "visa", name: "Visa", color: "#1A1F71", logo: true }, + { key: "mastercard", name: "Mastercard", color: "#EB001B", logo: true }, + { key: "paypal", name: "PayPal", color: "#003087", logo: true }, + { key: "cash", name: "Cash / other", color: "#16A34A", short: "£" }, +]; +const BANK_BY_KEY = new Map(BANKS.map(b => [b.key, b])); +function bankOf(key) { return BANK_BY_KEY.get(key) || null; } +function bankShort(b) { return b.short || (b.name || "?").slice(0, 1).toUpperCase(); } +function bankGlyph(key) { + const b = bankOf(key); + if (!b) return `🏦`; + if (b.logo) return ``; + return `${esc(bankShort(b))}`; +} + +/* ---------- icons (emoji) ---------- */ +// Keyword → category emoji for auto-suggesting from a description. +const ICON_RULES = [ + [/rent|mortgage|landlord|housing|lease/i, "🏠"], + [/phone|mobile|cell|sim/i, "📱"], + [/internet|broadband|wifi|wi-fi|fibre|fiber/i, "🌐"], + [/electric|power|energy|\bgas\b|water|utilit/i, "💡"], + [/salary|wage|payroll|paycheck|payslip|income|dividend/i, "💰"], + [/grocer|supermarket|\bfood\b|tesco|aldi|lidl|sainsbury/i, "🛒"], + [/restaurant|dining|takeaway|takeout|cafe|coffee|costa|starbucks|mcdonald|deliveroo|uber eats/i, "🍔"], + [/\bcar\b|fuel|petrol|diesel|parking|bus|train|tube|uber|taxi|transport/i, "🚗"], + [/insurance/i, "🛡️"], + [/netflix|spotify|disney|stream|subscription|prime video/i, "🎬"], + [/gym|fitness|peloton/i, "🏋️"], + [/health|doctor|medical|pharmacy|dentist|optician|nhs/i, "🏥"], + [/saving|invest|isa|pension/i, "🐷"], + [/gift|present|birthday|christmas|xmas/i, "🎁"], + [/holiday|travel|flight|hotel|airbnb|vacation/i, "✈️"], + [/loan|debt|overdraft|repay/i, "🏦"], + [/\btax\b|hmrc|vat|council/i, "🧾"], + [/tuition|school|course|university|udemy/i, "🎓"], + [/tv licen|tv\b|cable/i, "📺"], + [/\bdog\b|\bcat\b|\bpet\b|vet/i, "🐶"], +]; +function iconFor(desc) { + const s = desc || ""; + for (const [re, emoji] of ICON_RULES) if (re.test(s)) return emoji; + return ""; +} + +/* ---------- date helpers (for the calendar month + recurring dates) ---------- */ +function pad2(n) { return String(n).padStart(2, "0"); } +function currentYm() { const d = new Date(); return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}`; } +function daysInMonth(y, m) { return new Date(y, m, 0).getDate(); } // m is 1-12 +function addMonthYm(ym) { + if (!/^\d{4}-\d{2}$/.test(ym)) return currentYm(); + let [y, m] = ym.split("-").map(Number); + m++; if (m > 12) { m = 1; y++; } + return `${y}-${pad2(m)}`; +} +function ymName(ym) { + if (!/^\d{4}-\d{2}$/.test(ym)) return ""; + const [y, m] = ym.split("-").map(Number); + return new Date(y, m - 1, 1).toLocaleString(undefined, { month: "long", year: "numeric" }); +} +// True when a month's calendar month is strictly before the current one — a settled, +// historic month. YYYY-MM strings sort lexicographically, so a plain string compare works. +function isPastYm(ym) { return /^\d{4}-\d{2}$/.test(ym || "") && ym < currentYm(); } +// Ordinal suffix for a day number: 1→st, 2→nd, 3→rd, 9→th, 11→th … +function ordSuffix(n) { + n = parseInt(n, 10); + if (!n || n < 1) return ""; + const v = n % 100; + if (v >= 11 && v <= 13) return "th"; + return { 1: "st", 2: "nd", 3: "rd" }[n % 10] || "th"; +} + +/* ---------- data shape ---------- */ +function newRow() { return { id: uid(), date: "", desc: "", inc: "", out: "", tag: "", icon: "" }; } +function newMonth(ym, rows) { + return { + id: uid(), + title: ym ? ymName(ym) : "", + ym: ym || "", + opening: "", + rows: rows && rows.length ? rows : [newRow()], + }; +} +// A recurring item: income/expense that repeats. `dir` in|out, `freq` daily|weekly|monthly|yearly. +function newRecurring() { + return { + id: uid(), desc: "", dir: "out", amount: "", tag: "", icon: "", enabled: true, + freq: "monthly", + day: "1", // monthly: day of month + every: "2", anchor: "", until: "", // daily/weekly: every N days/weeks, from anchor date, optional end (until) date + ymonth: "1", yday: "1", // yearly: month + day + }; +} +// A single budget (one "tab"). Holds everything a ledger needs, self-contained. +function newBudget(name) { + return { + id: uid(), + name: name || "Budget", + currency: "£", + accounts: [{ id: uid(), name: "", balance: "", bank: "" }], + recurring: [], + months: [newMonth(currentYm())], + }; +} +// The whole document: a book of budgets plus which one is active. +function defaultBook() { + const b = newBudget("My Budget"); + return { version: 2, activeId: b.id, budgets: [b] }; +} +// Accept either a new book or an old single-budget document and always return a book. +function migrateToBook(obj) { + if (obj && Array.isArray(obj.budgets)) return obj; // already a book + const b = { + id: uid(), + name: "My Budget", + currency: (obj && obj.currency) || "£", + accounts: (obj && obj.accounts) || [{ id: uid(), name: "", balance: "", bank: "" }], + recurring: (obj && obj.recurring) || [], + months: (obj && obj.months) || [newMonth(currentYm())], + }; + return { version: 2, activeId: b.id, budgets: [b] }; +} +function activeBudget() { return book.budgets.find(b => b.id === book.activeId) || book.budgets[0]; } +// Point `state` at the active budget and keep activeId consistent. +function syncActive() { state = activeBudget(); book.activeId = state.id; } + +// Deep copy + brand-new ids throughout, remapping rows' recId links to the cloned recurring items. +function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); } +function reassignIds(b) { + b.id = uid(); + (b.accounts || []).forEach(a => a.id = uid()); + const recMap = {}; + (b.recurring || []).forEach(it => { const old = it.id; it.id = uid(); recMap[old] = it.id; }); + (b.months || []).forEach(m => { + m.id = uid(); + (m.rows || []).forEach(r => { + r.id = uid(); + if (r.recId) { if (recMap[r.recId]) r.recId = recMap[r.recId]; else delete r.recId; } + }); + }); + return b; +} + +// Optional From/To date window shared by all frequencies (anchor = earliest, until = latest, both inclusive). +function withinBounds(item, iso) { + const t = Date.parse(iso); + const a = Date.parse(item.anchor), u = Date.parse(item.until); + if (!isNaN(a) && t < a) return false; + if (!isNaN(u) && t > u) return false; + return true; +} + +/* ---------- recurring → concrete dated rows for a given month ---------- */ +function recurOccurrences(item, ym) { + if (!/^\d{4}-\d{2}$/.test(ym)) return []; + const y = +ym.slice(0, 4), mo = +ym.slice(5, 7); + const dim = daysInMonth(y, mo); + const mk = (day) => { + const r = newRow(); + r.date = `${ym}-${pad2(day)}`; + r.desc = item.desc; + r.tag = item.tag || ""; + r.icon = item.icon || ""; + r.recId = item.id; // link back to the recurring template so edits can propagate + if (item.dir === "in") r.inc = item.amount; else r.out = item.amount; + return r; + }; + if (item.freq === "monthly") { + const day = Math.min(Math.max(parseInt(item.day, 10) || 1, 1), dim); + return withinBounds(item, `${ym}-${pad2(day)}`) ? [mk(day)] : []; + } + if (item.freq === "yearly") { + if ((parseInt(item.ymonth, 10) || 0) !== mo) return []; + const day = Math.min(Math.max(parseInt(item.yday, 10) || 1, 1), dim); + return withinBounds(item, `${ym}-${pad2(day)}`) ? [mk(day)] : []; + } + if (item.freq === "weekly" || item.freq === "daily") { + const unitDays = item.freq === "weekly" ? 7 : 1; // step in days: 7 per "week", 1 per "day" + const stepMs = Math.max(parseInt(item.every, 10) || 1, 1) * unitDays * 86400000; + let anchorMs = Date.parse(item.anchor); + if (isNaN(anchorMs)) anchorMs = Date.parse(`${ym}-01`); + const untilMs = Date.parse(item.until); // optional end date (inclusive); NaN = runs forever + const out = []; + for (let d = 1; d <= dim; d++) { + const cur = Date.parse(`${ym}-${pad2(d)}`); + if (!isNaN(untilMs) && cur > untilMs) break; // stop once past the end date + const diff = cur - anchorMs; + if (diff >= 0 && diff % stepMs === 0) out.push(mk(d)); + } + return out; + } + return []; +} +// Order rows chronologically; within a single day, money-IN rows list before money-OUT +// (and blank) rows. Array.sort is stable, so same-day/same-direction rows keep their order. +function cmpRows(a, b) { + const byDate = (a.date || "9999-99-99").localeCompare(b.date || "9999-99-99"); + if (byDate) return byDate; + return (num(a.inc) > 0 ? 0 : 1) - (num(b.inc) > 0 ? 0 : 1); +} +// Group recurring items so income (In) lists above expenses (Out). Stable, so the user's +// manual order within each group is preserved. Groups stay contiguous, which the up/down +// move buttons rely on to keep reordering inside a single direction group. +function sortRecurring(b) { + if (Array.isArray(b.recurring)) b.recurring.sort((x, y) => (x.dir === "in" ? 0 : 1) - (y.dir === "in" ? 0 : 1)); +} +// Append every recurring occurrence into a month, skipping duplicates, then sort by date. +function fillRecurring(m) { + if (!m.ym) return 0; + const seen = new Set(m.rows.map(r => r.desc + "|" + r.date)); + let added = 0; + state.recurring.forEach(item => { + if (!item.desc && !item.amount) return; // skip blank templates + if (item.enabled === false) return; // skip paused items + recurOccurrences(item, m.ym).forEach(r => { + const key = r.desc + "|" + r.date; + if (!seen.has(key)) { seen.add(key); m.rows.push(r); added++; } + }); + }); + m.rows.sort(cmpRows); + return added; +} +// Push an edit to a recurring item out to every row it has already placed in the months. +// regenDates = true when the schedule changed (dates/counts differ → rebuild that item's rows). +function syncRecurringItem(it, regenDates) { + state.months.forEach(m => { + if (!m.rows.some(r => r.recId === it.id)) return; // item isn't applied to this month — leave it + if (regenDates) { + m.rows = m.rows.filter(r => r.recId !== it.id); + recurOccurrences(it, m.ym).forEach(r => m.rows.push(r)); + m.rows.sort(cmpRows); + } else { + m.rows.forEach(r => { + if (r.recId !== it.id) return; + r.desc = it.desc; + r.tag = it.tag || ""; + r.icon = it.icon || ""; + if (it.dir === "in") { r.inc = it.amount; r.out = ""; } + else { r.out = it.amount; r.inc = ""; } + }); + } + }); +} +// Drop a single recurring item into every calendar month that doesn't already have it. +function applyItemToAllMonths(it) { + if (it.enabled === false) return; + state.months.forEach(m => { + if (!m.ym) return; + const seen = new Set(m.rows.map(r => r.desc + "|" + r.date)); + recurOccurrences(it, m.ym).forEach(r => { + const key = r.desc + "|" + r.date; + if (!seen.has(key)) { seen.add(key); m.rows.push(r); } + }); + m.rows.sort(cmpRows); + }); +} +// Pull a recurring item's rows out of every month (used when pausing it). +function removeItemFromAllMonths(it) { + state.months.forEach(m => { m.rows = m.rows.filter(r => r.recId !== it.id); }); +} +// Order a month's rows chronologically (undated rows sink to the bottom). +function sortMonthRows(m) { + m.rows.sort(cmpRows); +} +// Append one new month, calendar-advanced from the last month, pre-filled with recurring. +function addOneMonth() { + const last = state.months[state.months.length - 1]; + const m = newMonth(last && last.ym ? addMonthYm(last.ym) : currentYm()); + m.rows = []; + fillRecurring(m); + if (!m.rows.length) m.rows.push(newRow()); + state.months.push(m); + return m; +} + +// Backfill fields that older saved data may not have, for one budget. +function normalizeBudget(b) { + if (!b) return; + b.id = b.id || uid(); + b.name = b.name || "Budget"; + b.currency = b.currency || "£"; + if (!Array.isArray(b.accounts) || !b.accounts.length) b.accounts = [{ id: uid(), name: "", balance: "", bank: "" }]; + b.accounts.forEach(a => { a.bank = a.bank || ""; }); + if (!Array.isArray(b.recurring)) b.recurring = []; + if (!Array.isArray(b.months) || !b.months.length) b.months = [newMonth(currentYm())]; + b.recurring.forEach(it => { + it.dir = it.dir || "out"; it.tag = it.tag || ""; it.freq = it.freq || "monthly"; + it.day = it.day || "1"; it.every = it.every || "2"; it.anchor = it.anchor || ""; it.until = it.until || ""; + it.ymonth = it.ymonth || "1"; it.yday = it.yday || "1"; + it.amount = it.amount || ""; it.desc = it.desc || ""; it.enabled = it.enabled !== false; + if (it.icon === undefined) applyCat(it, iconFor(it.desc), false); // auto-suggest once for pre-category data + }); + sortRecurring(b); // income grouped above expenses (stable — manual order within a group survives) + b.months.forEach(m => { m.ym = m.ym || ""; (m.rows || []).forEach(r => { + r.tag = r.tag || ""; + if (r.icon === undefined) applyCat(r, iconFor(r.desc), false); + }); if (Array.isArray(m.rows)) m.rows.sort(cmpRows); }); + // Link rows generated before recId existed, so editing a recurring item propagates to them. + b.months.forEach(m => (m.rows || []).forEach(r => { + if (r.recId) return; + const match = b.recurring.find(it => it.enabled !== false && it.desc && it.desc === r.desc && ( + it.dir === "in" ? (num(it.amount) === num(r.inc) && num(r.out) === 0) + : (num(it.amount) === num(r.out) && num(r.inc) === 0))); + if (match) r.recId = match.id; + })); +} +function normalizeState() { normalizeBudget(state); } // the active budget +function normalizeBook() { if (book) book.budgets.forEach(normalizeBudget); } + +/* ---------- crypto ---------- + Web Crypto when the page is a secure context (HTTPS, localhost). On plain + http to a LAN or VPN address browsers hide crypto.subtle, so the same + PBKDF2-SHA256 + AES-256-GCM runs from crypto-fallback.js (vendored + @noble/hashes + @noble/ciphers) instead. Both write identical blobs. + A key is either a CryptoKey or { fallback: true, bytes } from the fallback. */ +const HAS_SUBTLE = !!(window.isSecureContext && window.crypto && crypto.subtle); +let fallbackCrypto = null; +function loadFallbackCrypto() { + if (!fallbackCrypto) fallbackCrypto = import("./crypto-fallback.js"); + return fallbackCrypto; +} +function wipeKey(key) { if (key && key.fallback) key.bytes.fill(0); } + +async function deriveKey(passphrase, salt) { + if (!HAS_SUBTLE) { + const fb = await loadFallbackCrypto(); + return { fallback: true, bytes: await fb.deriveKeyBytes(enc.encode(passphrase), salt, PBKDF2_ITERATIONS) }; + } + const km = await crypto.subtle.importKey("raw", enc.encode(passphrase), "PBKDF2", false, ["deriveKey"]); + return crypto.subtle.deriveKey( + { name: "PBKDF2", salt, iterations: PBKDF2_ITERATIONS, hash: "SHA-256" }, + km, + { name: "AES-GCM", length: 256 }, + false, + ["encrypt", "decrypt"] + ); +} + +// Encrypt any object into a self-contained blob { v, salt, iv, ct }. +async function encryptObj(obj, key, salt) { + const iv = crypto.getRandomValues(new Uint8Array(12)); + const pt = enc.encode(JSON.stringify(obj)); + const ct = key.fallback + ? (await loadFallbackCrypto()).encrypt(key.bytes, iv, pt) + : await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, pt); + return { v: 1, salt: b64encode(salt), iv: b64encode(iv), ct: b64encode(ct) }; +} +function encryptBook() { return encryptObj(book, cryptoKey, currentSalt); } + +async function decryptBlob(stored, key) { + const iv = b64decode(stored.iv); + const ct = b64decode(stored.ct); + const pt = key.fallback + ? (await loadFallbackCrypto()).decrypt(key.bytes, iv, ct) + : await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ct); + return JSON.parse(dec.decode(pt)); +} + +/* ---------- linked save file (File System Access API) ---------- + A tiny IndexedDB store keeps the FileSystemFileHandle between sessions so we + can offer one-click "Reconnect". localStorage stays the in-browser cache and + the unlock source; the file is the durable, portable copy. */ +const FS_DB = "money-ledger-fs", FS_STORE = "handles", FS_KEY = "saveFile"; +function fsIdb() { + return new Promise((res, rej) => { + const r = indexedDB.open(FS_DB, 1); + r.onupgradeneeded = () => r.result.createObjectStore(FS_STORE); + r.onsuccess = () => res(r.result); + r.onerror = () => rej(r.error); + }); +} +async function fsGet() { + try { + const db = await fsIdb(); + return await new Promise((res, rej) => { + const rq = db.transaction(FS_STORE, "readonly").objectStore(FS_STORE).get(FS_KEY); + rq.onsuccess = () => res(rq.result || null); rq.onerror = () => rej(rq.error); + }); + } catch (e) { return null; } +} +async function fsPut(handle) { + try { + const db = await fsIdb(); + await new Promise((res, rej) => { + const tx = db.transaction(FS_STORE, "readwrite"); + tx.objectStore(FS_STORE).put(handle, FS_KEY); + tx.oncomplete = () => res(); tx.onerror = () => rej(tx.error); + }); + } catch (e) { /* ignore — feature is best-effort */ } +} +// Confirm we hold (or can get) read/write permission. requestPermission needs a user gesture. +async function fsPermission(handle) { + const opts = { mode: "readwrite" }; + if ((await handle.queryPermission(opts)) === "granted") return true; + return (await handle.requestPermission(opts)) === "granted"; +} +async function fsWrite(text) { + if (!fileHandle) return; + const w = await fileHandle.createWritable(); + await w.write(text); + await w.close(); +} + +/* ---------- persistence ---------- */ +function loadStored() { + const raw = localStorage.getItem(STORAGE_KEY); + return raw ? JSON.parse(raw) : null; +} +async function save() { + if (!cryptoKey || !book) return; + const text = JSON.stringify(await encryptBook()); + try { localStorage.setItem(STORAGE_KEY, text); } catch (e) { /* quota — disk copies still tried below */ } + if (serverMode) { + // Persist the ciphertext to the server's on-disk file (survives clearing the browser). + try { await fetch("/api/data", { method: "PUT", headers: { "Content-Type": "application/json" }, body: text }); } + catch (e) { updateFileStatus("error"); } // server down — localStorage still holds it + } + if (fileHandle) { + try { await fsWrite(text); updateFileStatus(); } + catch (e) { fileHandle = null; updateFileStatus(); } // permission lapsed → fall back, nudge a reconnect + } +} + +// On boot: if served by server.py, pull the on-disk blob into the localStorage cache (server is the source of truth). +async function bootLoadFromServer() { + try { + const r = await fetch("/api/data", { cache: "no-store" }); + if (r.status === 200) { + const text = await r.text(); + JSON.parse(text); // sanity-check it parses + localStorage.setItem(STORAGE_KEY, text); // refresh the cache from disk + serverMode = true; + } else if (r.status === 204) { + serverMode = true; // server present, nothing stored yet + } + } catch (e) { + serverMode = false; // opened statically / via file:// → localStorage only + } +} +function scheduleSave() { clearTimeout(saveTimer); saveTimer = setTimeout(save, 400); } + +// Mirroring a recurring edit into the months is a full renderMonths() (rebuild every +// month's DOM) + recompute() (a querySelector per row). Doing that on every keystroke is +// what makes typing a recurring amount/description laggy on a big ledger. The state is +// already updated synchronously in onInput, so we just coalesce the repaint to the trailing +// edge — the months catch up a beat after typing settles, and typing itself stays smooth. +let recurPaintTimer = null; +function scheduleRecurRepaint() { + clearTimeout(recurPaintTimer); + recurPaintTimer = setTimeout(() => { recurPaintTimer = null; renderMonths(); recompute(); }, 90); +} + +/* ---------- linked-file actions + status UI ---------- */ +const FS_TYPES = [{ description: "LibreLedger (encrypted)", accept: { "application/json": [".mlg", ".json"] } }]; + +// Reflect file-link state on the toolbar button: active / needs-reconnect / not-linked. +function updateFileStatus(stateHint) { + if (!linkBtn) return; + if (serverMode) { // persistence is handled on the server; show it as a status pill + linkBtn.hidden = false; + linkBtn.classList.remove("needs"); + linkBtn.classList.toggle("linked", stateHint !== "error"); + linkBtn.classList.toggle("needs", stateHint === "error"); + linkBtn.textContent = stateHint === "error" ? "⚠️ Save server offline" : "💾 Saved to disk"; + linkBtn.title = stateHint === "error" + ? "Couldn't reach the save server — your edits are still cached in this browser. Is the LibreLedger server running?" + : "Auto-saving your encrypted ledger to the server (ledger.enc in its data folder). Survives clearing your browser."; + return; + } + if (!FS_SUPPORTED) { linkBtn.hidden = true; return; } + linkBtn.hidden = false; + linkBtn.classList.remove("linked", "needs"); + if (fileHandle) { + linkBtn.textContent = "🔗 Saving to file"; + linkBtn.title = `Auto-saving your encrypted ledger to "${fileHandle.name}". Click to switch files.`; + linkBtn.classList.add("linked"); + } else if (rememberedName) { + linkBtn.textContent = "🔗 Reconnect file"; + linkBtn.title = `File-saving is paused. Click to reconnect "${rememberedName}" and resume auto-saving.`; + linkBtn.classList.add("needs"); + } else { + linkBtn.textContent = "🔗 Link file"; + linkBtn.title = "Auto-save your encrypted ledger to a file you choose (durable & portable)."; + } +} + +// Pick a file and start auto-saving the current data to it. +async function linkSaveFile() { + if (!FS_SUPPORTED) { alert("Linking a file needs Chrome or Edge on desktop. Elsewhere, use Backup / Restore."); return; } + try { + const handle = await window.showSaveFilePicker({ suggestedName: "libreledger.mlg", types: FS_TYPES }); + if (!(await fsPermission(handle))) return; + fileHandle = handle; + rememberedName = handle.name; + await fsPut(handle); + await save(); // write current ledger into the file right away + updateFileStatus(); + alert(`Linked. Your ledger now auto-saves to "${handle.name}".`); + } catch (e) { if (e && e.name !== "AbortError") alert("Could not link that file."); } +} + +// Already unlocked, but file-saving was paused (new session) — re-grant and resume, pushing current data out. +async function resumeFileSave() { + const handle = await fsGet(); + if (!handle) { return linkSaveFile(); } + try { + if (!(await fsPermission(handle))) { alert("Permission for the file was denied."); return; } + fileHandle = handle; + rememberedName = handle.name; + await save(); + updateFileStatus(); + } catch (e) { alert("Could not reconnect the file."); } +} + +// From the LOCK screen: read a ledger file into the unlock buffer, then unlock it with its passphrase. +async function loadFileIntoUnlock(handle) { + const text = await (await handle.getFile()).text(); + const obj = JSON.parse(text); + if (!obj.salt || !obj.iv || !obj.ct) throw new Error("not a ledger file"); + localStorage.setItem(STORAGE_KEY, text); // stage it so the unlock flow decrypts the file's contents + fileHandle = handle; + rememberedName = handle.name; + await fsPut(handle); + showLock("unlock"); + lockMsg.textContent = `Unlock "${handle.name}" with its passphrase`; + pass1.focus(); +} +async function reconnectFromLock() { + const handle = await fsGet(); + if (!handle) return; + try { + if (!(await fsPermission(handle))) { alert("Permission for the file was denied."); return; } + await loadFileIntoUnlock(handle); + } catch (e) { alert("That linked file looks corrupt or unreadable."); } +} +async function openFromFile() { + if (!FS_SUPPORTED) { alert("Opening a file needs Chrome or Edge on desktop. Elsewhere, use Restore."); return; } + try { + const [handle] = await window.showOpenFilePicker({ types: FS_TYPES, multiple: false }); + if (!(await fsPermission(handle))) return; + await loadFileIntoUnlock(handle); + } catch (e) { if (e && e.name !== "AbortError") alert("That file isn't a valid ledger."); } +} + +// Lock-screen buttons: Reconnect (if a file is remembered) and Open-a-file. +async function renderLockFs() { + if (!lockFs) return; + if (!FS_SUPPORTED) { lockFs.innerHTML = ""; return; } + const remembered = await fsGet(); + rememberedName = remembered ? remembered.name : null; + const parts = []; + if (remembered) parts.push(``); + parts.push(``); + lockFs.innerHTML = parts.join(""); + const rc = document.getElementById("lock-reconnect"); if (rc) rc.onclick = reconnectFromLock; + document.getElementById("lock-open").onclick = openFromFile; +} + +if (linkBtn) linkBtn.addEventListener("click", () => { + if (serverMode) { alert("Your ledger auto-saves (encrypted) to the server, as ledger.enc in its data folder, with dated backups beside it.\n\nIt lives on disk, so clearing your browser cache does not affect it. Back that folder up to keep a copy."); return; } + return fileHandle ? linkSaveFile() : resumeFileSave(); +}); + +/* ---------- rendering ---------- */ +/* ---------- section nav: tabs (focus one) + per-section show/hide in the "All" view ---------- */ +const sectionNav = document.getElementById("section-nav"); +const SECTIONS = [ + { key: "totals", icon: "📊", label: "Totals" }, + { key: "savings", icon: "🐷", label: "Savings" }, + { key: "affordability", icon: "🏡", label: "Affordability" }, + { key: "balances", icon: "💼", label: "Balances" }, + { key: "recurring", icon: "🔁", label: "Recurring" }, + { key: "ledger", icon: "🌊", label: "Ledger" }, +]; +let activeTab = "all"; // "all" → stacked view; otherwise a single section key +let hiddenSections = new Set(); // sections hidden within the "All" view +try { activeTab = localStorage.getItem("money-ledger-tab") || "all"; } catch (e) {} +try { hiddenSections = new Set(JSON.parse(localStorage.getItem("money-ledger-hidden") || "[]")); } catch (e) {} +function saveSectionPrefs() { + try { + localStorage.setItem("money-ledger-tab", activeTab); + localStorage.setItem("money-ledger-hidden", JSON.stringify([...hiddenSections])); + } catch (e) {} +} + +function renderSectionNav() { + if (!sectionNav) return; + sectionNav.innerHTML = + `
` + + `` + + SECTIONS.map(s => ``).join("") + + `
` + + ``; + // Each section gets a ✕ in its header (shown only in the All view) to hide it. + SECTIONS.forEach(s => { + const head = document.querySelector(`.panel[data-section="${s.key}"] .panel-head`); + if (head && !head.querySelector(".panel-hide")) { + const b = document.createElement("button"); + b.className = "panel-hide"; + b.dataset.action = "sec-hide"; + b.dataset.key = s.key; + b.title = `Hide the ${s.label} section`; + b.setAttribute("aria-label", `Hide ${s.label}`); + b.textContent = "✕"; + head.appendChild(b); + } + }); + applySectionView(); +} + +function applySectionView() { + const all = activeTab === "all"; + SECTIONS.forEach(s => { + const panel = document.querySelector(`.panel[data-section="${s.key}"]`); + if (panel) panel.classList.toggle("section-hidden", all ? hiddenSections.has(s.key) : activeTab !== s.key); + }); + if (app) app.classList.toggle("view-all", all); // gates the per-panel ✕ hide buttons + if (!sectionNav) return; + sectionNav.querySelectorAll("[data-action='sec-tab']").forEach(b => b.classList.toggle("active", b.dataset.key === activeTab)); + // "Hidden" restore strip — only in the All view, and only when something is hidden. + const strip = sectionNav.querySelector("[data-sec-hidden]"); + if (strip) { + const hidden = SECTIONS.filter(s => hiddenSections.has(s.key)); + strip.hidden = !(all && hidden.length); + if (all && hidden.length) { + strip.innerHTML = `Hidden` + + hidden.map(s => ``).join(""); + } + } +} + +function render() { + normalizeState(); + renderBudgets(); + renderSectionNav(); + currencyEl.value = state.currency || ""; + renderAccounts(); + renderRecurring(); + renderMonths(); + renderSavings(); + renderAffordability(); + renderTotals(); + recompute(); +} + +// The budget "tabs" strip: one tab per budget + actions on the active one. +function renderBudgets() { + if (!book) return; + const tabs = book.budgets.map(b => { + const active = b.id === book.activeId; + const name = esc(b.name) || "Untitled"; + return ``; + }).join(""); + const multi = book.budgets.length > 1; + budgetBar.innerHTML = ` +
${tabs}
+
+ + + ${multi ? `` : ""} + +
`; +} + +// Short human summary of a recurring item's schedule — shown on the chip; full editing is in the popover. +const MON_SHORT = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function shortDate(iso) { + if (!/^\d{4}-\d{2}-\d{2}$/.test(iso || "")) return ""; + return `${parseInt(iso.slice(8, 10), 10)} ${MON_SHORT[parseInt(iso.slice(5, 7), 10)] || ""}`; +} +// Trailing "· from X", "· until Y" or "· X→Y" for an item's optional date window. +function boundText(it) { + const from = shortDate(it.anchor), to = shortDate(it.until); + if (from && to) return ` · ${from}→${to}`; + if (to) return ` · until ${to}`; + if (from) return ` · from ${from}`; + return ""; +} +function whenSummary(it) { + if (it.freq === "daily") { + return (+it.every === 1 ? "Daily" : `Every ${it.every || 1} days`) + boundText(it); + } + if (it.freq === "weekly") { + return `Every ${it.every || 1} wk${+it.every === 1 ? "" : "s"}${boundText(it)}`; + } + if (it.freq === "yearly") { + const m = parseInt(it.ymonth, 10) || 1, d = parseInt(it.yday, 10) || 1; + return `Yearly · ${d} ${MON_SHORT[m] || ""}${boundText(it)}`; + } + const d = parseInt(it.day, 10) || 1; + return `Monthly · ${d}${ordSuffix(d)}${boundText(it)}`; +} + +function renderRecurring() { + const sel = (v, opts) => opts.map(([val, label]) => + ``).join(""); + + const arr = state.recurring; + const rows = arr.map((it, idx) => { + const on = it.enabled !== false; + // Reordering is confined to an item's own direction group (In stays above Out), so the + // arrows disable at each group's edge, not just the whole list's edge. + const upOff = idx === 0 || arr[idx - 1].dir !== it.dir; + const downOff = idx === arr.length - 1 || arr[idx + 1].dir !== it.dir; + return ` + + + + + + ${withStepper(``)} + + + + + + + + `; + }).join(""); + + const empty = `No recurring items yet — add the bills & income that repeat, and they'll flow into your months. 🔁`; + + recurringBody.innerHTML = ` +
+
+ + + + + + + + + + + + ${rows || empty} +
DescriptionIn / OutAmountSchedule
+
+
+ + ${state.recurring.length ? `` : ""} +
+
`; +} + +// Wrap a number with custom rounded ▲/▼ stepper buttons. +function withStepper(inputHTML) { + return `${inputHTML}` + + `` + + `` + + ``; +} + +function renderAccounts() { + const rows = state.accounts.map(a => ` + +
+ ${withStepper(``)} + + `).join(""); + + accountsBody.innerHTML = ` +
+ + + ${rows} + +
AccountBalance
Total balance
+ +
`; +} + +// Date cell: a compact day-of-month ("9th") when the month has a calendar month set +// (the month/year already live in the block header), or the full date picker otherwise. +function dateCellHTML(m, r, locked) { + const hasYm = /^\d{4}-\d{2}$/.test(m.ym || ""); + if (!hasYm) { + return ``; + } + const day = /^\d{4}-\d{2}-\d{2}$/.test(r.date || "") ? parseInt(r.date.slice(8, 10), 10) : ""; + const ord = ordSuffix(day); + if (locked) { + return `${day || "—"}${ord}`; + } + return `` + + `${ord}`; +} + +function monthHTML(m, idx) { + const recurIds = new Set(state.recurring.map(it => it.id)); + const rows = m.rows.map(r => { + // a row generated from a (still-existing) recurring item is locked here — edit it in Recurring + const locked = !!(r.recId && recurIds.has(r.recId)); + const amtCell = (cls, field, val) => { + const input = locked + ? `` + : ``; + return `${withStepper(input)}`; + }; + return ` + + ${locked + ? `🔒` + : ``} + + ${dateCellHTML(m, r, locked)} + + ${amtCell("in", "inc", r.inc)} + ${amtCell("out", "out", r.out)} + + + `; + }).join(""); + + return ` +
+ ${monthHeadHTML(m, idx)} + + + + + + + + + + + + ${rows} + + + + + + + + + +
DateDescriptionInOutBalance
Month totals · net · 🐷 saved Money inMoney outClosing balance
+
+ + +
+
`; +} + +// Shared month header (title, calendar month, opening, delete) + the per-category summary chips strip. +function monthHeadHTML(m, idx) { + const openingLabel = idx === 0 ? "Opening · from balances" : "Opening · carried"; + const openingTitle = idx === 0 + ? "Sum of your account balances above — the ledger opens from here" + : "Carried from the previous month's ending balance"; + return ` +
+ + + ${isPastYm(m.ym) ? `🕓 Past` : ""} + + + +
+
`; +} + +// Group a month's rows by icon → [{icon,label,inSum,outSum,rows}], biggest swing first. +function groupRows(m) { + const map = new Map(); + m.rows.forEach(r => { + const icon = r.icon || ""; + let g = map.get(icon); + if (!g) { g = { icon, label: catLabel(icon), inSum: 0, outSum: 0, rows: [] }; map.set(icon, g); } + g.inSum += num(r.inc); g.outSum += num(r.out); g.rows.push(r); + }); + return [...map.values()].sort((a, b) => Math.abs(b.inSum - b.outSum) - Math.abs(a.inSum - a.outSum)); +} + +// Per-category summary chips for a month (live-rendered from recompute). +// Each chip is a toggle: click to filter the month's rows to the categories you +// pick; the leading "All" chip clears the filter (and is highlighted when no +// filter is active). Selection lives in catFilter, keyed by month id. +function monthChipsHTML(m) { + const groups = groupRows(m).filter(g => g.inSum || g.outSum); + if (!groups.length) return ""; + const sel = catFilter.get(m.id); + const noneState = !!(sel && sel.has(CAT_NONE)); + const allActive = !sel || sel.size === 0; + let totIn = 0, totOut = 0; + groups.forEach(g => { totIn += g.inSum; totOut += g.outSum; }); + const net = totIn - totOut; + const allChip = + ``; + const catChips = groups.map(g => { + const income = g.inSum >= g.outSum; + const icon = g.icon || ""; + const active = !!(sel && sel.has(icon)); + return ``; + }).join(""); + return allChip + catChips; +} + +// Per-month category filter: month id → Set of selected icons (empty/absent = show all). +const catFilter = new Map(); +const CAT_ALL = "__all__"; // sentinel data-icon for the "All" chip (toggles show-all / show-none) +const CAT_NONE = "__none__"; // sentinel held inside the filter Set to mean "hide every category" + +// Show/hide a month's rows (chronological) and groups (grouped view) per its filter. +function applyMonthFilter(m) { + const sel = catFilter.get(m.id); + const filtering = !!(sel && sel.size > 0); + const chipEl = document.querySelector(`[data-chips="${m.id}"]`); + if (chipEl) chipEl.classList.toggle("filtering", filtering); + m.rows.forEach(r => { + const tr = document.querySelector(`tr.led-row[data-row="${r.id}"]`); + if (tr) tr.classList.toggle("filtered-out", filtering && !sel.has(r.icon || "")); + }); + document.querySelectorAll(`.grp[data-grp-month="${m.id}"]`).forEach(g => { + g.classList.toggle("filtered-out", filtering && !sel.has(g.dataset.grpIcon || "")); + }); +} + +function groupedDayLabel(r) { + if (/^\d{4}-\d{2}-\d{2}$/.test(r.date || "")) { const d = parseInt(r.date.slice(8, 10), 10); return `${d}${ordSuffix(d)}`; } + return ""; +} + +// Read-only "grouped by category" view of a month (collapsible groups + subtotals; edit in the flat view). +function monthGroupedHTML(m, idx) { + const body = groupRows(m).map(g => { + const key = m.id + "|" + (g.icon || "_none"); + const open = !collapsedGroups.has(key); + const sub = g.inSum - g.outSum; + const entries = g.rows.map(r => { + const amt = num(r.inc) || num(r.out); + return `
+ ${groupedDayLabel(r)} + ${esc(r.desc) || "—"} + ${num(r.inc) ? "+" : "−"}${fmt(amt)} +
`; + }).join(""); + return `
+ + ${open ? `
${entries}
` : ""} +
`; + }).join(""); + return ` +
+ ${monthHeadHTML(m, idx)} +
${body || `
No entries yet — switch to Chronological to add some.
`}
+
+ + 🐷 Saved + In + Out + Closing +
+
Read-only overview — switch to 📋 Chronological to add or edit entries.
+
`; +} + +let grouped = false; // global view mode: chronological (edit) vs grouped (overview) +const collapsedGroups = new Set(); // "|" keys that are collapsed in grouped view + +function renderMonths() { + const render = grouped ? monthGroupedHTML : monthHTML; + monthsBody.innerHTML = + state.months.map(render).join("") + + `
+ + or generate + months ahead + + +
`; + syncHeaderHeight(); // measure the strip height + re-arm the pinned-shadow observer +} + +// Give each month header a shadow only while it's pinned to the top (cosmetic). +let stickyObserver = null; +function observeStickyHeads() { + if (!("IntersectionObserver" in window)) return; + if (stickyObserver) stickyObserver.disconnect(); + const top = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--header-h"), 10) || 60; + stickyObserver = new IntersectionObserver( + entries => entries.forEach(e => e.target.classList.toggle("stuck", e.intersectionRatio < 1)), + { rootMargin: `-${top + 1}px 0px 0px 0px`, threshold: [1] } + ); + monthsBody.querySelectorAll(".month-head").forEach(h => stickyObserver.observe(h)); +} + +function recompute() { + // accounts + let accTotal = 0; + state.accounts.forEach(a => (accTotal += num(a.balance))); + setAll("[data-acc-total]", fmt(accTotal)); + document.querySelectorAll("[data-acc-total]").forEach(el => el.classList.toggle("neg", accTotal < 0)); + + // months — the first month opens from the accounts total, then the balance + // carries continuously month to month (one running ledger). + let carry = accTotal, cumSaved = 0, totalIncome = 0; + const savings = []; // {id, label, saved, cumulative} per month, for the Savings panel + const flow = []; // {label, inc, out, net, saved} per month, for the Totals charts + state.months.forEach((m, idx) => { + const opening = carry; + const oEl = document.querySelector(`[data-opening="${m.id}"]`); + if (oEl) { oEl.textContent = fmt(opening); oEl.classList.toggle("neg", opening < 0); } + + let bal = opening, tin = 0, tout = 0, saved = 0; + m.rows.forEach(r => { + const inc = num(r.inc), out = num(r.out); + tin += inc; + tout += out; + bal += inc - out; + if (r.icon === SAVINGS_ICON) saved += out - inc; // money set aside (a withdrawal back in counts negative) + const cell = document.querySelector(`[data-balance="${r.id}"]`); + if (cell) { cell.textContent = fmt(bal); cell.classList.toggle("neg", bal < 0); } + + // row income/expense tint (Money = income, Cost = expense) + const isIn = inc > 0 && out === 0; + const isOut = out > 0 && inc === 0; + const tr = document.querySelector(`tr[data-row="${r.id}"]`); + if (tr) { tr.classList.toggle("is-in", isIn); tr.classList.toggle("is-out", isOut); } + }); + const chipEl = document.querySelector(`[data-chips="${m.id}"]`); + if (chipEl) chipEl.innerHTML = monthChipsHTML(m); + applyMonthFilter(m); // keep row/group visibility in sync with the active filter + setOne(`[data-min="${m.id}"]`, fmt(tin)); + setOne(`[data-mout="${m.id}"]`, fmt(tout)); + const net = tin - tout; + const netEl = document.querySelector(`[data-mnet="${m.id}"]`); + if (netEl) { + netEl.textContent = (net > 0 ? "📈 " : net < 0 ? "📉 " : "") + fmt(net); + netEl.classList.toggle("neg", net < 0); + } + const endEl = document.querySelector(`[data-mend="${m.id}"]`); + if (endEl) { endEl.textContent = fmt(bal); endEl.classList.toggle("neg", bal < 0); } + + totalIncome += tin; + cumSaved += saved; + const mLabel = monthLabel(m, idx); + savings.push({ id: m.id, label: mLabel, saved, cumulative: cumSaved }); + flow.push({ label: mLabel, inc: tin, out: tout, net, saved }); + document.querySelectorAll(`[data-msav="${m.id}"]`).forEach(el => { + el.textContent = fmt(saved); + el.classList.toggle("neg", saved < 0); + }); + + carry = bal; + }); + + paintSavings(savings, totalIncome); + // Affordability shares Totals' method: annualise the 💰 income and 🏠 housing straight from the + // recurring schedule (not a backward-looking average of month rows), so the two always agree. + let affIncYr = 0, affHouseYr = 0; + (state.recurring || []).forEach(it => { + if (it.enabled === false) return; + const yr = annualForItem(it); + if (!yr) return; + if (it.dir === "in" && it.icon === INCOME_ICON) affIncYr += yr; + else if (it.dir === "out" && it.icon === HOUSING_ICON) affHouseYr += yr; + }); + paintAffordability(affIncYr / 12, affHouseYr / 12); + paintTotals(flow); +} + +/* ---------- savings panel (summary stats + hand-drawn SVG chart, no deps) ---------- */ +// Compact x-axis label for a month: "Jun '26" when a calendar month is set, +// else the (truncated) title, else a positional "M1, M2 …". +function monthLabel(m, idx) { + if (/^\d{4}-\d{2}$/.test(m.ym || "")) { + const [y, mo] = m.ym.split("-").map(Number); + return `${MON_SHORT[mo]} '${String(y).slice(2)}`; + } + const t = (m.title || "").trim(); + if (t) return t.length > 9 ? t.slice(0, 8) + "…" : t; + return `M${idx + 1}`; +} + +// Skeleton: stat slots + chart container. Live values are filled by paintSavings (from recompute). +function renderSavings() { + savingsBody.innerHTML = ` +
+
+
Saved to date
+
Avg / month
+
Savings rate
+
Best month
+
+
+ Saved / month + Cumulative total +
+
+
`; +} + +function setSav(sel, text, neg) { + const el = document.querySelector(sel); + if (el) { el.textContent = text; el.classList.toggle("neg", !!neg); } +} + +function paintSavings(series, totalIncome) { + const total = series.length ? series[series.length - 1].cumulative : 0; + const withActivity = series.filter(s => s.saved !== 0); + const avg = withActivity.length ? total / withActivity.length : 0; + const best = series.reduce((b, s) => (s.saved > (b ? b.saved : 0) ? s : b), null); + const rate = totalIncome > 0 ? (total / totalIncome) * 100 : null; + + setSav("[data-sav-total]", fmt(total), total < 0); + setSav("[data-sav-avg]", withActivity.length ? fmt(avg) : "—", avg < 0); + setSav("[data-sav-rate]", rate == null ? "—" : `${Math.round(rate)}%`, rate != null && rate < 0); + setSav("[data-sav-best]", best ? `${fmt(best.saved)} · ${best.label}` : "—", false); + + const chart = document.querySelector("[data-savings-chart]"); + if (chart) chart.innerHTML = savingsChartSVG(series); +} + +// Monthly saved as green/red bars (zero baseline) with a cumulative-total line on +// top. Two independent vertical scales — bars read per-month, the line reads the +// running total — so neither swamps the other. Pure SVG; gives hover tips. +function savingsChartSVG(series) { + if (!series.length || series.every(s => s.saved === 0 && s.cumulative === 0)) { + return `<div class="sav-empty">Tag any ledger row with <b>🐷 Savings</b> to watch your savings grow here.</div>`; + } + const n = series.length; + const slot = n <= 3 ? 118 : n <= 6 ? 92 : n <= 10 ? 66 : n <= 16 ? 50 : 38; + const padL = 12, padR = 12, padT = 18, padB = 30; + const H = 210, plotH = H - padT - padB; + const W = padL + n * slot + padR; + const cx = i => padL + slot * i + slot / 2; + + // bar scale (per-month saved — may go negative on a net withdrawal) + const sv = series.map(s => s.saved); + let sMax = Math.max(0, ...sv), sMin = Math.min(0, ...sv); + if (sMax === sMin) sMax = sMin + 1; + const yBar = v => padT + (sMax - v) / (sMax - sMin) * plotH; + const zeroY = yBar(0); + + // line scale (cumulative running total) + const cv = series.map(s => s.cumulative); + let cMax = Math.max(0, ...cv), cMin = Math.min(0, ...cv); + if (cMax === cMin) cMax = cMin + 1; + const yLine = v => padT + (cMax - v) / (cMax - cMin) * plotH; + + const barW = Math.min(36, slot * 0.52); + const showLab = i => n <= 18 || i % 2 === 0; // thin labels when crowded + + const baseline = `<line class="sav-base" x1="${padL}" y1="${zeroY.toFixed(1)}" x2="${(W - padR).toFixed(1)}" y2="${zeroY.toFixed(1)}"/>`; + const bars = series.map((s, i) => { + const x = cx(i), y1 = yBar(s.saved); + const top = Math.min(zeroY, y1), h = Math.max(1.5, Math.abs(y1 - zeroY)); + return `<g class="sav-bar ${s.saved >= 0 ? "pos" : "neg"}">` + + `<rect x="${(x - barW / 2).toFixed(1)}" y="${top.toFixed(1)}" width="${barW.toFixed(1)}" height="${h.toFixed(1)}" rx="3"/>` + + `<title>${esc(s.label)} — saved ${fmt(s.saved)} · total ${fmt(s.cumulative)}`; + }).join(""); + const linePts = series.map((s, i) => `${cx(i).toFixed(1)},${yLine(s.cumulative).toFixed(1)}`).join(" "); + const dots = series.map((s, i) => + `` + + `${esc(s.label)} — running total ${fmt(s.cumulative)}`).join(""); + const labels = series.map((s, i) => showLab(i) + ? `${esc(s.label)}` : "").join(""); + + return `${baseline}${bars}` + + `${dots}${labels}`; +} + +/* ---------- housing affordability (💰 income vs 🏠 housing) ---------- + The classic "spend ~30% on housing" figure is a guideline, not a cliff — so + this reads as a green→red spectrum you sit somewhere along, rather than a + pass/fail line at 30%. Colour, words and the budget note are all guidance. */ +const AFFORD_GUIDE = 0.30; // the widely-cited ~30% comfort guideline (a marker, not a hard limit) + +// Map a housing-to-income % onto a smooth green→amber→red hue: green at/below +// ~25%, sweeping to red by ~55%. No hard threshold — the colour just slides. +function affordHue(pct) { + const t = Math.max(0, Math.min(1, (pct - 25) / (55 - 25))); // 0 at ≤25%, 1 at ≥55% + return 140 * (1 - t); // 140°=green → 0°=red +} +// Keep these light values in step with the .aff-track gradient stops in styles.css. +function affordColor(pct, light = 47) { return `hsl(${affordHue(pct).toFixed(1)} 76% ${light}%)`; } + +// A soft, graduated read on the ratio — guidance language, never a verdict. +function affordRead(pct) { + if (pct < 25) return { word: "Comfortable", note: "a relaxed share of your income" }; + if (pct < 35) return { word: "Comfortable", note: "right around the commonly-suggested ~30% comfort guide" }; + if (pct < 45) return { word: "Manageable", note: "a little above the ~30% guide, but workable for many budgets" }; + if (pct < 55) return { word: "Getting stretched", note: "a sizeable share — worth keeping an eye on" }; + return { word: "Heavy", note: "a large share of your income, which can start to feel tight" }; +} + +function renderAffordability() { + affordBody.innerHTML = ` +
+
+
Annual income 💰
+
Income / month
+
Housing / month 🏠
+
Of income on housing
+
+ + +
`; +} + +// monthlyIncome / monthlyHousing are the typical-month averages computed in recompute. +function paintAffordability(monthlyIncome, monthlyHousing) { + const setVal = (sel, text) => { const el = affordBody.querySelector(sel); if (el) el.textContent = text; }; + setVal("[data-aff-annual]", monthlyIncome > 0 ? fmt(monthlyIncome * 12) : "—"); + setVal("[data-aff-minc]", monthlyIncome > 0 ? fmt(monthlyIncome) : "—"); + setVal("[data-aff-house]", monthlyHousing > 0 ? fmt(monthlyHousing) : "—"); + + const meter = affordBody.querySelector("[data-aff-meter]"); + const empty = affordBody.querySelector("[data-aff-empty]"); + const ratioEl = affordBody.querySelector("[data-aff-ratio]"); + + if (!(monthlyIncome > 0 && monthlyHousing > 0)) { // need both to form a ratio + if (ratioEl) { ratioEl.textContent = "—"; ratioEl.style.color = ""; } + if (meter) meter.hidden = true; + if (empty) { + empty.hidden = false; + empty.innerHTML = (!monthlyIncome && !monthlyHousing) + ? `Tag income with 💰 Income and housing costs with 🏠 Housing to see your affordability here.` + : !monthlyHousing + ? `Add some 🏠 Housing costs and we'll measure them against your income.` + : `Tag your 💰 Income so we can work out your housing ratio.`; + } + return; + } + + const pct = (monthlyHousing / monthlyIncome) * 100; + const read = affordRead(pct); + const fillColor = affordColor(pct); // matches the gauge track beneath the needle + const textColor = affordColor(pct, 44); // a touch darker so it stays legible as text + + if (empty) empty.hidden = true; + if (meter) meter.hidden = false; + if (ratioEl) { ratioEl.textContent = `${Math.round(pct)}%`; ratioEl.style.color = textColor; } + + const needle = affordBody.querySelector("[data-aff-needle]"); + if (needle) { + needle.style.left = Math.max(0, Math.min(100, pct)) + "%"; + needle.style.setProperty("--aff-c", fillColor); + } + setVal("[data-aff-needleval]", `${Math.round(pct)}%`); + + const verdict = affordBody.querySelector("[data-aff-verdict]"); + if (verdict) { + verdict.style.color = textColor; + verdict.textContent = `${read.word} — about ${Math.round(pct)}% of your income goes on housing, ${read.note}.`; + } + + const guideCost = monthlyIncome * AFFORD_GUIDE, headroom = guideCost - monthlyHousing; + const budget = affordBody.querySelector("[data-aff-budget]"); + if (budget) { + budget.innerHTML = headroom >= 0 + ? `Around ${fmt(guideCost)}/mo sits on the ~30% guide · ${fmt(headroom)} to spare` + : `Around ${fmt(guideCost)}/mo sits on the ~30% guide · ${fmt(-headroom)} above it`; + } +} + +/* ---------- totals (annualised budget at a glance + click-to-chart per month) ---------- */ +// The four headline figures. `pick` pulls this metric out of a month's flow record +// (built in recompute) so a click can chart it month by month. `tone` drives bar colour. +const TT_METRICS = [ + { key: "income", icon: "💰", label: "Income", sub: "in", tone: "in", pick: f => f.inc }, + { key: "costs", icon: "💸", label: "Spending", sub: "out", tone: "out", pick: f => f.out }, + { key: "net", icon: "⚖️", label: "Net flow", sub: "in − out", tone: "net", pick: f => f.net }, + { key: "savings", icon: "🐷", label: "Savings", sub: "set aside", tone: "in", pick: f => f.saved }, +]; +const TT_BY_KEY = new Map(TT_METRICS.map(m => [m.key, m])); +let totalsFlow = []; // per-month series, set by paintTotals (for the chart modal) +let totalsAnnual = { income: 0, costs: 0, net: 0, savings: 0 }; // annualised figures, set by paintTotals + +// How many times a year a recurring item fires — a forward-looking projection of the +// schedule (date bounds are ignored: this is "at this rate, per year"). +function annualMult(item) { + if (item.freq === "yearly") return 1; + if (item.freq === "weekly") return 365.25 / 7 / Math.max(parseInt(item.every, 10) || 1, 1); + if (item.freq === "daily") return 365.25 / Math.max(parseInt(item.every, 10) || 1, 1); + return 12; // monthly +} + +// Annualised value of a recurring item over the next 12 months, honouring its date window. +// A perpetual, already-running item (no end date, not starting in the future) uses the smooth +// annualMult rate (e.g. 52.18 weeks/yr). But an item bounded by an end date (until) or a future +// start (anchor) is counted by its ACTUAL occurrences in the window — so a benefit that runs only +// until a switch-over, or starts partway through the year, is no longer over-counted as a flat 12×. +function annualForItem(item) { + const amt = num(item.amount); + if (!amt) return 0; + const winStart = Date.parse(`${currentYm()}-01`); + const anchorMs = Date.parse(item.anchor); + const bounded = !isNaN(Date.parse(item.until)) || (!isNaN(anchorMs) && anchorMs > winStart); + if (!bounded) return amt * annualMult(item); + let ym = currentYm(), count = 0; + for (let i = 0; i < 12; i++) { count += recurOccurrences(item, ym).length; ym = addMonthYm(ym); } + return amt * count; +} + +// Skeleton: four clickable stat cards. Live values are filled by paintTotals (from recompute). +function renderTotals() { + if (!totalsBody) return; + const cards = TT_METRICS.map(c => ` + `).join(""); + totalsBody.innerHTML = + `
${cards}
` + + ``; +} + +function paintTotals(flow) { + if (!totalsBody) return; + totalsFlow = flow || []; + + // Annualised budget from the recurring schedule (income vs costs; savings = 🐷-tagged outgoings). + let incYr = 0, costYr = 0, saveYr = 0; + (state.recurring || []).forEach(it => { + if (it.enabled === false) return; + const yr = annualForItem(it); + if (!yr) return; + if (it.dir === "in") incYr += yr; + else { costYr += yr; if (it.icon === SAVINGS_ICON) saveYr += yr; } + }); + const vals = { income: incYr, costs: costYr, net: incYr - costYr, savings: saveYr }; + totalsAnnual = vals; // annual rates still power the click-through chart's "planned/yr" line + const hasPlan = !!(incYr || costYr || saveYr); + + // Savings is shown as the actual whole-ledger total set aside (matching the 🐷 Savings + // panel), not a 12-month rate — so the two figures reconcile. Avg is per active month. + const savedToDate = (flow || []).reduce((s, f) => s + (f.saved || 0), 0); + const savMonths = (flow || []).filter(f => f.saved !== 0).length; + const savAvg = savMonths ? savedToDate / savMonths : 0; + const hasSaved = savMonths > 0; + + TT_METRICS.forEach(c => { + const yEl = totalsBody.querySelector(`[data-tt="${c.key}-year"]`); + const mEl = totalsBody.querySelector(`[data-tt="${c.key}-month"]`); + const capEl = totalsBody.querySelector(`[data-tt="${c.key}-cap"]`); + const mcapEl = totalsBody.querySelector(`[data-tt="${c.key}-mcap"]`); + + if (c.key === "savings") { + const show = hasSaved || hasPlan; + if (yEl) { yEl.textContent = show ? fmt(savedToDate) : "—"; yEl.classList.toggle("neg", show && savedToDate < 0); } + if (mEl) { mEl.textContent = show ? fmt(savAvg) : "—"; mEl.classList.toggle("neg", show && savAvg < 0); } + if (capEl) capEl.textContent = "saved to date"; + if (mcapEl) mcapEl.textContent = "/ mo avg"; + return; + } + + const yr = vals[c.key]; + if (yEl) { yEl.textContent = hasPlan ? fmt(yr) : "—"; yEl.classList.toggle("neg", hasPlan && yr < 0); } + if (mEl) { mEl.textContent = hasPlan ? fmt(yr / 12) : "—"; mEl.classList.toggle("neg", hasPlan && yr < 0); } + }); + + const note = totalsBody.querySelector("[data-tt-empty]"); + if (note) note.hidden = hasPlan || hasSaved; +} + +// ----- click-to-chart modal: a month-by-month bar chart of the chosen metric ----- +const ttModal = document.createElement("div"); +ttModal.className = "overlay modal-overlay tt-modal hidden"; +ttModal.innerHTML = + ``; +document.body.appendChild(ttModal); +function closeTotalsChart() { ttModal.classList.add("hidden"); } +ttModal.addEventListener("click", e => { + if (e.target === ttModal || e.target.closest("[data-ttm-close]")) closeTotalsChart(); +}); +document.addEventListener("keydown", e => { + if (e.key === "Escape" && !ttModal.classList.contains("hidden")) closeTotalsChart(); +}); + +function openTotalsChart(metric) { + const cfg = TT_BY_KEY.get(metric); + if (!cfg) return; + const series = totalsFlow.map(f => ({ label: f.label, value: cfg.pick(f) })); + const annual = totalsAnnual[metric] || 0; + const avg = series.length ? series.reduce((s, p) => s + p.value, 0) / series.length : 0; + ttModal.querySelector("[data-ttm-title]").textContent = `${cfg.icon} ${cfg.label} — month by month`; + let sub; + if (metric === "savings") { + // Reconcile with the card + Savings panel: whole-ledger total, averaged over active months. + const total = series.reduce((s, p) => s + p.value, 0); + const active = series.filter(p => p.value !== 0).length; + sub = `Saved ${fmt(total)} to date` + + (active ? `  ·  ${fmt(total / active)}/mo average` : ""); + } else { + sub = `Planned ${fmt(annual)}/yr · ${fmt(annual / 12)}/mo from recurring` + + (series.length ? `  ·  actual average ${fmt(avg)}/mo` : ""); + } + ttModal.querySelector("[data-ttm-sub]").innerHTML = sub; + ttModal.querySelector("[data-ttm-chart]").innerHTML = metricChartSVG(series, cfg, avg); + ttModal.classList.remove("hidden"); +} + +// Pure inline SVG (no deps): one bar per month off a zero baseline, with a dashed +// average line. Colour comes from the tone class on the + each bar's sign. +function metricChartSVG(series, cfg, avg) { + if (!series.length) { + return `
Add some months in your 🌊 Ledger to chart this.
`; + } + if (series.every(p => p.value === 0)) { + return `
No ${esc(cfg.label)} recorded in your ledger months yet.
`; + } + const n = series.length; + const slot = n <= 3 ? 120 : n <= 6 ? 94 : n <= 10 ? 68 : n <= 16 ? 50 : 38; + const padL = 14, padR = 14, padT = 22, padB = 30; + const H = 240, plotH = H - padT - padB; + const W = padL + n * slot + padR; + const cx = i => padL + slot * i + slot / 2; + + const vv = series.map(p => p.value); + let vMax = Math.max(0, ...vv), vMin = Math.min(0, ...vv); + if (vMax === vMin) vMax = vMin + 1; + const y = v => padT + (vMax - v) / (vMax - vMin) * plotH; + const zeroY = y(0); + const barW = Math.min(42, slot * 0.54); + const showLab = i => n <= 18 || i % 2 === 0; + + const baseline = ``; + const bars = series.map((p, i) => { + const x = cx(i), yv = y(p.value); + const top = Math.min(zeroY, yv), h = Math.max(1.5, Math.abs(yv - zeroY)); + return `` + + `` + + `${esc(p.label)} — ${fmt(p.value)}`; + }).join(""); + const avgY = y(avg); + const avgLine = avg !== 0 + ? `` + + `avg ${fmt(avg)}` + : ""; + const labels = series.map((p, i) => showLab(i) + ? `${esc(p.label)}` : "").join(""); + + return `${baseline}${bars}${avgLine}${labels}`; +} + +/* ---------- edit handlers (event delegation) ---------- */ +function onInput(e) { + if (!state) return; + const el = e.target; + const { field, scope, id, month } = el.dataset; + if (!field) return; + if (scope === "account") { + const a = state.accounts.find(a => a.id === id); + if (a) a[field] = el.value; + } else if (scope === "month") { + const m = state.months.find(m => m.id === id); + if (m) { + if (field === "ym") { + // keep the display title in sync unless it was hand-edited + const prevName = ymName(m.ym); + m.ym = el.value; + if (!m.title || m.title === prevName) m.title = ymName(el.value); + render(); scheduleSave(); return; + } + m[field] = el.value; + } + } else if (scope === "row") { + const m = state.months.find(m => m.id === month); + const r = m && m.rows.find(r => r.id === id); + if (r) { + if (field === "day") { + const raw = el.value.trim(); + if (raw === "") { + r.date = ""; + } else if (/^\d{4}-\d{2}$/.test(m.ym || "")) { + const [y, mo] = m.ym.split("-").map(Number); + const d = Math.min(Math.max(parseInt(raw, 10) || 1, 1), daysInMonth(y, mo)); + r.date = `${m.ym}-${pad2(d)}`; + } + const sup = document.querySelector(`[data-dayord="${r.id}"]`); + if (sup) sup.textContent = ordSuffix(raw); + } else { + r[field] = el.value; + if (field === "desc" && !r.icon) { applyCat(r, iconFor(el.value), false); if (r.icon) refreshDot("row", r.id, r, month); } + } + } + } else if (scope === "recurring") { + const it = state.recurring.find(x => x.id === id); + if (!it) return; + it[field] = el.value; + if (field === "desc" && !it.icon) { applyCat(it, iconFor(el.value), false); if (it.icon) refreshDot("recurring", it.id, it); } + const established = state.months.some(m => m.rows.some(r => r.recId === it.id)); + let appliedNew = false; + if (!established && num(it.amount) > 0 && it.enabled !== false) { + applyItemToAllMonths(it); // first time it has a real amount → auto-add to existing months + appliedNew = true; + } else if (established) { + syncRecurringItem(it, ["freq", "day", "every", "anchor", "until", "ymonth", "yday"].includes(field)); + } + // Reflect the change in the months, but off the typing critical path (see + // scheduleRecurRepaint). A brand-new item that isn't in any month yet has nothing to + // repaint, so skip it entirely — that keeps adding a new item instant. renderMonths() + // doesn't touch the recurring table, so the focused input stays put either way. + if (appliedNew || established) scheduleRecurRepaint(); + if (field === "dir") sortRecurring(state); // flipped In/Out → re-group (income stays on top) + if (field === "freq" || field === "dir") renderRecurring(); // swap the "when" fields / recolour amount + scheduleSave(); + return; + } + // Only repaint running balances when a money field actually changed. Typing in a + // description / name / title leaves every balance identical, so skip the whole-ledger + // recompute (a querySelector per row) and just save — keeps typing snappy on big ledgers. + const affectsBalance = + (scope === "row" && (field === "inc" || field === "out")) || + (scope === "account" && field === "balance"); + if (affectsBalance) recompute(); + scheduleSave(); +} + +// When a row's date is committed, re-sort the month so it slots into chronological order. +function onChange(e) { + if (!state) return; + const d = e.target.dataset; + if (d && d.scope === "row" && (d.field === "date" || d.field === "day")) { + const m = state.months.find(m => m.id === d.month); + if (m) { sortMonthRows(m); renderMonths(); recompute(); scheduleSave(); } + } +} + +function onClick(e) { + if (!state) return; + const btn = e.target.closest("[data-action]"); + if (!btn) return; + const { action, id, month } = btn.dataset; + switch (action) { + case "totals-chart": openTotalsChart(btn.dataset.metric); return; + case "sec-tab": activeTab = btn.dataset.key; saveSectionPrefs(); applySectionView(); return; + case "sec-hide": hiddenSections.add(btn.dataset.key); saveSectionPrefs(); applySectionView(); return; + case "sec-show": hiddenSections.delete(btn.dataset.key); saveSectionPrefs(); applySectionView(); return; + case "switch-budget": + if (id !== book.activeId) { book.activeId = id; syncActive(); render(); scheduleSave(); } + return; + case "new-budget": { + const name = prompt("Name for the new budget:", `Budget ${book.budgets.length + 1}`); + if (name == null) return; + const b = newBudget(name.trim() || `Budget ${book.budgets.length + 1}`); + book.budgets.push(b); + book.activeId = b.id; syncActive(); + render(); scheduleSave(); + return; + } + case "rename-budget": { + const b = activeBudget(); + const name = prompt("Rename budget:", b.name); + if (name == null) return; + b.name = name.trim() || b.name; + render(); scheduleSave(); + return; + } + case "dup-budget": { + const copy = reassignIds(deepClone(activeBudget())); + copy.name = activeBudget().name + " (copy)"; + book.budgets.push(copy); + book.activeId = copy.id; syncActive(); + render(); scheduleSave(); + return; + } + case "del-budget": { + if (book.budgets.length <= 1) return; // keep at least one + const b = activeBudget(); + if (!confirm(`Delete budget "${b.name}" and all its months? This cannot be undone.`)) return; + book.budgets = book.budgets.filter(x => x.id !== b.id); + book.activeId = book.budgets[0].id; syncActive(); + render(); scheduleSave(); + return; + } + case "add-account": state.accounts.push({ id: uid(), name: "", balance: "", bank: "" }); break; + case "del-account": state.accounts = state.accounts.filter(a => a.id !== id); break; + case "add-recurring": state.recurring.push(newRecurring()); break; + case "del-recurring": { + const it = state.recurring.find(x => x.id === id); + if (!it) break; + const label = it.desc ? `"${it.desc}"` : "this recurring item"; + if (!confirm(`Delete ${label} and remove its entries from all months?`)) return; + removeItemFromAllMonths(it); // pull every row it generated out of the months too + state.recurring = state.recurring.filter(x => x.id !== id); + break; + } + case "edit-sched": openSchedPop(btn); return; + case "toggle-recurring": { + const it = state.recurring.find(x => x.id === id); + if (it) { + it.enabled = it.enabled === false; // flip (undefined counts as enabled) + if (it.enabled) applyItemToAllMonths(it); // resume → add back everywhere + else removeItemFromAllMonths(it); // pause → pull from every month + } + break; + } + case "move-recurring": { + const arr = state.recurring; + const i = arr.findIndex(x => x.id === id); + const j = i + (btn.dataset.dir === "up" ? -1 : 1); + // Only swap within the same direction group — In stays grouped above Out. + if (i >= 0 && j >= 0 && j < arr.length && arr[j].dir === arr[i].dir) { + const [it] = arr.splice(i, 1); + arr.splice(j, 0, it); + } + break; + } + case "toggle-grouped": grouped = !grouped; renderMonths(); recompute(); return; + case "toggle-group": { + const key = btn.dataset.key; + if (collapsedGroups.has(key)) collapsedGroups.delete(key); else collapsedGroups.add(key); + renderMonths(); recompute(); return; + } + case "add-month": addOneMonth(); break; + case "add-months-bulk": { + const input = document.getElementById("bulk-count"); + let n = parseInt(input && input.value, 10); + n = Math.min(Math.max(n || 1, 1), 60); + for (let i = 0; i < n; i++) addOneMonth(); + break; + } + case "fill-recurring": { + const m = state.months.find(m => m.id === id); + if (!m) return; + if (!m.ym) { alert("Set this month's calendar month first (the 📅 box in the month header)."); return; } + const added = fillRecurring(m); + if (added === 0) alert("No recurring payments matched this month — add some in the Recurring section above."); + break; + } + case "fill-all-months": { + let total = 0, skipped = 0; + state.months.forEach(m => { if (!m.ym) { skipped++; return; } total += fillRecurring(m); }); + alert( + `Added ${total} recurring ${total === 1 ? "entry" : "entries"} across your months.` + + (skipped ? `\n${skipped} month${skipped === 1 ? "" : "s"} skipped — no calendar month (📅) set.` : "") + ); + break; + } + case "del-month": + if (!confirm("Delete this entire month and its rows?")) return; + state.months = state.months.filter(m => m.id !== id); + break; + case "add-row": { const m = state.months.find(m => m.id === month); if (m) m.rows.push(newRow()); break; } + case "insert-row": { + const m = state.months.find(m => m.id === month); + if (m) { const i = m.rows.findIndex(r => r.id === id); m.rows.splice(i + 1, 0, newRow()); } + break; + } + case "del-row": { const m = state.months.find(m => m.id === month); if (m) m.rows = m.rows.filter(r => r.id !== id); break; } + case "open-tags": openTagPicker(btn); return; + case "open-bank": openBankPicker(btn); return; + case "filter-cat": { + const mId = btn.dataset.month, icon = btn.dataset.icon; + let sel = catFilter.get(mId); + if (icon === CAT_ALL) { + // "All" toggles: everything already showing ⇒ hide all; otherwise ⇒ show all. + if (!sel) catFilter.set(mId, new Set([CAT_NONE])); // show-all → show-none + else catFilter.delete(mId); // filtered/none → show-all + } else { + if (!sel || sel.has(CAT_NONE)) { sel = new Set(); catFilter.set(mId, sel); } // leave none/empty + if (sel.has(icon)) sel.delete(icon); else sel.add(icon); + if (sel.size === 0) catFilter.delete(mId); // nothing selected ⇒ show all + } + const m = state.months.find(x => x.id === mId); + if (m) { + const chipEl = document.querySelector(`[data-chips="${mId}"]`); + if (chipEl) chipEl.innerHTML = monthChipsHTML(m); // refresh active states + applyMonthFilter(m); + } + return; + } + case "step": { + const input = btn.closest(".stepper") && btn.closest(".stepper").querySelector("input"); + if (!input || input.readOnly) return; + const stepAttr = parseFloat(input.getAttribute("step")) || 1; + const unit = stepAttr < 1 ? 1 : stepAttr; // money steps by 1, not 0.01 + let next = (parseFloat(input.value) || 0) + (btn.dataset.dir === "up" ? unit : -unit); + const min = input.getAttribute("min"), max = input.getAttribute("max"); + if (min !== null && next < parseFloat(min)) next = parseFloat(min); + if (max !== null && next > parseFloat(max)) next = parseFloat(max); + input.value = String(Math.round(next * 100) / 100); + input.dispatchEvent(new Event("input", { bubbles: true })); // reuse onInput → state + recompute + save + return; + } + default: return; + } + render(); + scheduleSave(); +} + +/* ---------- icon + colour picker (centered modal) ---------- */ +const tagPop = document.createElement("div"); +tagPop.className = "overlay modal-overlay tag-modal hidden"; +tagPop.innerHTML = + `