Première version de Fiscalibre
This commit is contained in:
parent
01aa3820c8
commit
479d8a86db
24 changed files with 1153 additions and 235 deletions
9
.gitignore
vendored
Normal file
9
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
.pytest_cache/
|
||||||
|
*.pyc
|
||||||
|
*.egg-info/
|
||||||
|
*.sqlite3
|
||||||
|
.env
|
||||||
|
*.pdf
|
||||||
|
!.keep
|
||||||
37
AGENTS.md
Normal file
37
AGENTS.md
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
# Instructions aux agents Claude Code / Codex
|
||||||
|
|
||||||
|
## Mission
|
||||||
|
|
||||||
|
Construire Fiscalibre, un logiciel libre québécois qui réduit au minimum la saisie nécessaire pour préparer, contrôler et **éventuellement** transmettre des déclarations fiscales aux deux administrations (ARC et Revenu Québec), pour les particuliers, travailleurs autonomes et sociétés.
|
||||||
|
|
||||||
|
## Interdictions non négociables
|
||||||
|
|
||||||
|
1. **Ne jamais présenter un PDF de synthèse comme une déclaration officielle T1/TP-1/T2/CO-17.** Aucun export n'est transmissible avant validation de l'ensemble du schéma et homologation.
|
||||||
|
2. **Ne jamais inventer de taux, crédits, éligibilités, lignes ou exceptions.** Chaque règle contient millésime, URL source gouvernementale et tests de régression.
|
||||||
|
3. **Ne jamais utiliser un modèle d'IA pour déterminer un calcul fiscal final.** L'IA future peut classifier, documenter, expliquer, proposer; le moteur de règles approuvé décide.
|
||||||
|
4. **Ne pas ajouter de collecte du NAS ni données bancaires avant le chiffrement au repos** et le modèle d'authentification/consentement.
|
||||||
|
5. Pas de dépendances externes en exécution, CDN, télémétrie, accès réseau, Docker, Terraform ni Kubernetes sans besoin démontré et décision explicite.
|
||||||
|
6. Ne jamais transformer `pret_a_transmettre` en `True` au moyen d'un simple bouton.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
- `fiscalibre/tax.py` : algorithmes versionnés 2025, `Decimal`, provenance des règles et avertissements.
|
||||||
|
- `fiscalibre/storage.py` : persistance locale SQLite; prévoir migrations et chiffrement.
|
||||||
|
- `fiscalibre/web.py` : interface FastAPI, validation des entrées et contrôles loopback.
|
||||||
|
- `fiscalibre/pdf.py` : synthèse PDF **non transmissible**.
|
||||||
|
- `fiscalibre/templates/` et `static/` : interface progressive en français.
|
||||||
|
- `tests/` : tests unitaires et intégration.
|
||||||
|
|
||||||
|
## Définition de terminé (par tâche)
|
||||||
|
|
||||||
|
- Règle officielle citée par URL et millésime; comportement et cas limites testés.
|
||||||
|
- Vérification de la justesse de la ligne sur le vrai formulaire de l'année fiscale visée.
|
||||||
|
- Aucune perte de données existantes dans la base.
|
||||||
|
- Respect de la séparation `valeur déclarée`, `montant calculé`, `montant vérifié` et `montant officiellement transmis`.
|
||||||
|
- Tests `pytest -q` verts.
|
||||||
|
- Documentation des limites, scénarios non supportés et dépendances.
|
||||||
|
- Pour toute sortie PDF : rendre en image puis contrôler pages, lisibilité et présence de l'avertissement.
|
||||||
|
|
||||||
|
## Travail à prioriser
|
||||||
|
|
||||||
|
Lire `docs/FEUILLE-DE-ROUTE.md`, établir les cas de test officiels, puis développer la complétude fiscale avant de connecter des canaux de transmission. Les premiers jalons doivent être le chiffrement des dossiers, le modèle documentaire, les annexes de base et les tests croisés.
|
||||||
240
LICENSE
240
LICENSE
|
|
@ -1,235 +1,9 @@
|
||||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
Fiscalibre — Copyright (C) 2026 les contributeurs du projet.
|
||||||
Version 3, 19 November 2007
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
Le code source de ce prototype est distribué selon les conditions de la
|
||||||
|
GNU Affero General Public License version 3 ou toute version ultérieure.
|
||||||
|
Texte intégral officiel : https://www.gnu.org/licenses/agpl-3.0.txt
|
||||||
|
|
||||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
Aucun droit d'auteur, marque ou signe graphique de l'ARC ou de Revenu Québec
|
||||||
|
n'est revendiqué. Fiscalibre est un projet indépendant non homologué.
|
||||||
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.
|
|
||||||
|
|
||||||
fiscalibre
|
|
||||||
Copyright (C) 2026 Chezlepro
|
|
||||||
|
|
||||||
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 <http://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
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 <http://www.gnu.org/licenses/>.
|
|
||||||
|
|
|
||||||
6
Makefile
Normal file
6
Makefile
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
.PHONY: run test
|
||||||
|
run:
|
||||||
|
python -m fiscalibre
|
||||||
|
|
||||||
|
test:
|
||||||
|
pytest -q
|
||||||
89
README.md
89
README.md
|
|
@ -1,3 +1,88 @@
|
||||||
# fiscalibre
|
# Fiscalibre V0.1 — prototype local Canada / Québec
|
||||||
|
|
||||||
moteur fiscal canadien à deux juridictions, capable de traiter les particuliers, les travailleurs autonomes et les sociétés constituées.
|
**État : développement expérimental, NON HOMOLOGUÉ, NON TRANSMISSIBLE.**
|
||||||
|
|
||||||
|
Fiscalibre prépare un **dossier de révision** pour :
|
||||||
|
|
||||||
|
- particuliers québécois : T1 (ARC) et TP-1 (Revenu Québec) ;
|
||||||
|
- travailleurs autonomes : T1, TP-1 et postes préparatoires T2125/TP-80 ;
|
||||||
|
- sociétés incorporées : T2 (ARC) et CO-17 (Revenu Québec), avec estimation rudimentaire de la DPE.
|
||||||
|
|
||||||
|
Les PDF générés **ne sont pas des déclarations prescrites**, n'ont pas la structure complète des formulaires officiels et **ne peuvent pas être transmis** aux administrations fiscales. Le moteur ne calcule **pas** les cotisations RRQ/RPC/AE/RQAP, les crédits complets, toutes les annexes, les retenues, les reports ni l'ensemble des règles fiscales nécessaires. Aucun montant n'est un impôt final à payer.
|
||||||
|
|
||||||
|
## Démarrage sur Debian 13 (sans Docker)
|
||||||
|
|
||||||
|
Pré-requis : Python 3.11+ avec `venv`. Dans le dossier cloné ou extrait :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m venv .venv
|
||||||
|
. .venv/bin/activate
|
||||||
|
python -m pip install -e '.[dev]'
|
||||||
|
python -m fiscalibre
|
||||||
|
```
|
||||||
|
|
||||||
|
Ouvrir **http://127.0.0.1:8765** dans le navigateur local.
|
||||||
|
|
||||||
|
Alternative : `fiscalibre --port 8765`. L'interface n'écoute jamais sur le réseau externe.
|
||||||
|
|
||||||
|
### Tests automatisés
|
||||||
|
|
||||||
|
```bash
|
||||||
|
. .venv/bin/activate
|
||||||
|
pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
## Fonctionnalités effectives
|
||||||
|
|
||||||
|
1. Créer et reprendre des dossiers distincts pour trois profils.
|
||||||
|
2. Saisie guidée en quatre étapes, responsive et 100 % francophone.
|
||||||
|
3. Montants en dollars canadiens; interprétation décimale exacte avec `Decimal`.
|
||||||
|
4. Calculs indicatifs 2025 pour les deux administrations (barèmes vérifiés).
|
||||||
|
5. Import CSV simple `categorie;montant;description`, contrôle des montants et catégories, cumul explicite (sans déduplication).
|
||||||
|
6. Export de dossiers de calcul en PDF, avec lignes préliminaires et avertissements; export JSON pour validation et intégration future.
|
||||||
|
7. SQLite local (droits de fichier 0600), aucune télémétrie, aucun service cloud requis.
|
||||||
|
8. Tests pour les profils, les barèmes, l'import, le PDF, la validation et la sécurité locale.
|
||||||
|
|
||||||
|
### Exemple d'import CSV
|
||||||
|
|
||||||
|
```csv
|
||||||
|
categorie;montant;description
|
||||||
|
recettes_entreprise;1250,00;Facture A-001
|
||||||
|
depenses_entreprise;150,00;Frais d'hébergement
|
||||||
|
```
|
||||||
|
|
||||||
|
Utiliser le point-virgule comme séparateur, l'UTF-8 et la virgule ou le point pour les décimales. L'import additionne aux montants présents : **éviter de réimporter le même fichier.** La classification reste entièrement manuelle.
|
||||||
|
|
||||||
|
## Confidentialité et sécurité
|
||||||
|
|
||||||
|
- **Aucun chiffrement au repos** dans la V0.1; **ne pas utiliser avec des NAS, des numéros de comptes, de vraies données clients ou d'autres renseignements personnels sensibles**.
|
||||||
|
- Le stockage se trouve par défaut dans `~/.local/share/fiscalibre/dossiers.sqlite3`, avec permissions locales. Changer l'emplacement : `FISCALIBRE_DATA_DIR=/chemin/prive`.
|
||||||
|
- L'application n'expose pas d'authentification, ne doit pas être publiée sur Internet, reverse-proxyfiée ou accessible sur un LAN.
|
||||||
|
- L'interface n'appelle aucun serveur de télémétrie, aucune API fiscale, ni aucun service d'IA.
|
||||||
|
- L'export JSON contient les données en clair; conserver les fichiers dans un répertoire sûr.
|
||||||
|
- Cette V1 ne doit être utilisée qu'avec des **données synthétiques** pour l'instant.
|
||||||
|
|
||||||
|
## Exactitude et périmètre temporel
|
||||||
|
|
||||||
|
**Millésime supporté : 2025**. Aucune extrapolation automatique des barèmes 2025 à 2026. Les exercices des sociétés doivent être contrôlés : une date d'exercice qui recoupe une année ou un changement de taux nécessite une étude distincte. Une DPE cochée **n'équivaut pas à son admissibilité**; les taux 2025 9 % fédéral et 3,2 % Québec ne s'appliquent qu'aux situations admissibles. Les renseignements saisis sont interprétés comme **montants déjà qualifiés fiscalement** : le logiciel ne détermine pas encore leur admissibilité.
|
||||||
|
|
||||||
|
Pour passer à une **déclaration officiellement transmissible**, il faudra notamment :
|
||||||
|
|
||||||
|
- intégrer les gabarits officiels et **toutes** les annexes et lignes nécessaires ;
|
||||||
|
- implémenter l'IGRF (GIFI), états des résultats et bilan, DPA, ajustements fiscaux, cotisations et crédits ;
|
||||||
|
- certifier la conformité des calculs par tests croisés avec cas officiels et logiciels agréés ;
|
||||||
|
- obtenir l'homologation requise auprès de l'ARC et l'autorisation de Revenu Québec, et implémenter les protocoles de transmission ;
|
||||||
|
- chiffrer le stockage et les exports, gestion des consentements et traçabilité.
|
||||||
|
|
||||||
|
**Pour les sociétés dont l'année d'imposition commence après 2023 au fédéral et à partir du 1er janvier 2024 au Québec, la transmission électronique est généralement obligatoire** (sous réserve des exceptions prévues).
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- `AGENTS.md` : règles de collaboration avec Claude Code et Codex.
|
||||||
|
- `docs/ARCHITECTURE.md` : architecture et modules.
|
||||||
|
- `docs/FEUILLE-DE-ROUTE.md` : jalons vers la conformité.
|
||||||
|
- `docs/SOURCES.md` : liens gouvernementaux utilisés pour 2025.
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
Code prévu sous AGPL-3.0-ou-ultérieure. Voir `LICENSE` et https://www.gnu.org/licenses/agpl-3.0.html. Le projet n'est affilié ni à l'ARC ni à Revenu Québec.
|
||||||
|
|
|
||||||
55
docs/ARCHITECTURE.md
Normal file
55
docs/ARCHITECTURE.md
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
# Fiscalibre — architecture V0.1
|
||||||
|
|
||||||
|
## Frontières
|
||||||
|
|
||||||
|
```text
|
||||||
|
Navigateur local (français)
|
||||||
|
|
|
||||||
|
FastAPI / formulaires
|
||||||
|
|
|
||||||
|
+-----+------+--------------------+
|
||||||
|
| | |
|
||||||
|
SQLite Tax 2025 Import CSV contrôlé
|
||||||
|
(sans (Decimal)
|
||||||
|
chiffrement) |
|
||||||
|
+------> moteur lignes (T1, TP-1, T2, CO-17)
|
||||||
|
|
|
||||||
|
PDF de révision + JSON
|
||||||
|
(NON transmissibles)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Vocabulaire et garanties
|
||||||
|
|
||||||
|
- **Données brutes** : déclarations des utilisateurs, importations CSV; aucune preuve de nature fiscale.
|
||||||
|
- **Données calculées** : montant numériquement obtenu selon une règle limitée, avec source.
|
||||||
|
- **Données vérifiées** : aucune dans V0.1.
|
||||||
|
- **Données transmissibles** : aucune dans V0.1.
|
||||||
|
- **Profil** : particulier, autonome, société; extensible aux sociétés de personnes, fiducies.
|
||||||
|
- **Millésime** : 2025 uniquement pour cette version de moteur.
|
||||||
|
|
||||||
|
## Schéma de dossier (simplifié)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"annee": 2025,
|
||||||
|
"identite": {"nom": "", "raison_sociale": "", "debut_exercice": "2025-01-01", "fin_exercice": "2025-12-31"},
|
||||||
|
"montants": {"revenu_emploi": "0.00", "recettes_entreprise": "0.00", "depenses_entreprise": "0.00"},
|
||||||
|
"options": {"spcc": false, "dpe_federale": false, "dpe_quebec": false},
|
||||||
|
"importations": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dette technique consciente
|
||||||
|
|
||||||
|
- Présentation Jinja plutôt que SPA et code JS complexe : simplicité et accessibilité.
|
||||||
|
- SQLite non chiffré : **uniquement données synthétiques** en V0.1.
|
||||||
|
- Pas de connecteur ARC/Revenu Québec : les services sécurisés imposent une autorisation explicite.
|
||||||
|
- Pas de référentiel de feuillets T4/RL-1 etc. : actuellement chiffres manuels.
|
||||||
|
- Aucun export d'instances gouvernementales : seulement objets de calcul et dossier PDF.
|
||||||
|
- Pas de contrôles d'authentification multiutilisateur : uniquement poste local.
|
||||||
|
- Pas de transactions bancaires importées ni de classification automatique.
|
||||||
|
- Éviter le mélange des données de comptabilité commerciale et des ajustements fiscaux.
|
||||||
|
|
||||||
|
## Migrations futures
|
||||||
|
|
||||||
|
Créer des sous-paquets `tax/year_2025/personal`, `tax/year_2025/corporate` et un registre de règles `rule_id, valid_from, valid_to, source_url, test_cases`. Ajouter schémas de données explicites et migrations SQLite; ensuite format machine réconciliable par administrations et moteur de validation formelle.
|
||||||
44
docs/FEUILLE-DE-ROUTE.md
Normal file
44
docs/FEUILLE-DE-ROUTE.md
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
# De la V0.1 aux déclarations transmissibles
|
||||||
|
|
||||||
|
## Étape 0 — démonstrateur (présente livraison)
|
||||||
|
|
||||||
|
- [x] 3 profils, interface guidée locale, sauvegarde, import CSV, barèmes 2025 de base.
|
||||||
|
- [x] PDF de synthèse et JSON pour travaux et tests.
|
||||||
|
- [x] Avertissements bloquant toute allégation de conformité.
|
||||||
|
- [ ] Déclarations complètes et officiellement transmissibles — **non réalisées**.
|
||||||
|
|
||||||
|
## Étape 1 — sécurité et ingestion documentaire
|
||||||
|
|
||||||
|
- [ ] Chiffrement au repos (SQLCipher ou crypto par dossier et clés utilisateur), export chiffré.
|
||||||
|
- [ ] Identification/consentement, journal d'audit, protection CSRF, gestion de versions de schéma.
|
||||||
|
- [ ] Modèle de pièces justificatives et reconnaissance locale de feuillets (validation humaine obligatoire).
|
||||||
|
- [ ] Rapprochement des doublons CSV/feuillets, provenance de chaque chiffre.
|
||||||
|
- [ ] Périodes fiscales et statut provincial correctement modélisés.
|
||||||
|
|
||||||
|
## Étape 2 — T1 et TP-1 2025 réellement complètes (profils simples)
|
||||||
|
|
||||||
|
- [ ] Tous champs d'identification, situations familiales, résidences, dépendants.
|
||||||
|
- [ ] Cotisations RRQ/RPC/AE/RQAP, crédits non remboursables/remboursables, retenues.
|
||||||
|
- [ ] Feuillets T4/RL-1, T4A, T4A(OAS), T4A(P), T5/RL-3, REER.
|
||||||
|
- [ ] Réconciliation Québec/fédéral, année 2025, tableaux complets et annexes requises.
|
||||||
|
- [ ] Validation des références de lignes par capture des formulaires officiels.
|
||||||
|
- [ ] Export PDF officiel avec toutes les cases requises (sans caractère de certification non acquis).
|
||||||
|
|
||||||
|
## Étape 3 — T2125/TP-80 et société T2/CO-17
|
||||||
|
|
||||||
|
- [ ] Comptabilité double entrée/IGRF : bilan + état des résultats, comptes mappés, balance vérifiée.
|
||||||
|
- [ ] Stocks, DPA, ajustements fiscaux, investissements, pertes, incitatifs et crédits.
|
||||||
|
- [ ] Admissibilité réelle DPE, heures rémunérées, sociétés associées, plafond d'affaires.
|
||||||
|
- [ ] Formulaires T2 et CO-17 officiels avec leurs annexes selon année d'imposition et fin d'exercice.
|
||||||
|
- [ ] Tests contre des jeux d'exemples officiels, comparaisons avec logiciel homologué.
|
||||||
|
|
||||||
|
## Étape 4 — conformité et télétransmission
|
||||||
|
|
||||||
|
- [ ] Contacter les programmes officiels de certification de l'ARC et de Revenu Québec.
|
||||||
|
- [ ] Schémas techniques, validateurs, procédures de mise à jour annuelle.
|
||||||
|
- [ ] Homologation, environnement d'essai, procédures de signature/consentement et reçus.
|
||||||
|
- [ ] Transmission et suivi des accusés de réception via seuls canaux autorisés.
|
||||||
|
|
||||||
|
## Règles de passage des jalons
|
||||||
|
|
||||||
|
Ne jamais dire qu'un dossier est « prêt à transmettre » si une seule pièce obligatoire, une annexe, un calcul fiscal ou une autorisation réglementaire reste absent. La date d'ouverture d'un canal de production ne doit pas précéder une validation indépendante.
|
||||||
25
docs/SOURCES.md
Normal file
25
docs/SOURCES.md
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
# Sources gouvernementales — vérifiées le 21 novembre 2026
|
||||||
|
|
||||||
|
Les calculs disponibles sont limités à l'année d'imposition **2025**.
|
||||||
|
|
||||||
|
| Sujet | Source officielle |
|
||||||
|
|---|---|
|
||||||
|
| Barèmes fédéraux des particuliers 2025 (14,5 %, 20,5 %, 26 %, 29 %, 33 %) | https://www.canada.ca/en/revenue-agency/services/tax/individuals/tax-rates-brackets/last-year.html |
|
||||||
|
| Barèmes Québec particuliers 2025 (14 %, 19 %, 24 %, 25,75 %) | https://www.revenuquebec.ca/fr/citoyens/declaration-de-revenus/produire-votre-declaration-de-revenus/taux-dimposition/ |
|
||||||
|
| Montant personnel de base fédéral 2025 | https://www.canada.ca/en/revenue-agency/services/tax/individuals/topics/about-your-tax-return/tax-return/completing-a-tax-return/deductions-credits-expenses/line-30000-basic-personal-amount.html |
|
||||||
|
| Montant personnel de base Québec 2025 (18 571 $) | https://www.revenuquebec.ca/fr/citoyens/declaration-de-revenus/produire-votre-declaration-de-revenus/aide-par-ligne/350-a-398-1-credits-dimpot-non-remboursables/ligne-350/ |
|
||||||
|
| Montant canadien pour emploi 2025 (maximum 1 471 $) | https://www.canada.ca/fr/agence-revenu/services/impot/particuliers/sujets/tout-votre-declaration-revenus/declaration-revenus/remplir-declaration-revenus/deductions-credits-depenses/ligne-31260-montant-canadien-emploi.html |
|
||||||
|
| Abattement du Québec 16,5 % (sous conditions) | https://www.canada.ca/en/revenue-agency/services/tax/individuals/topics/about-your-tax-return/tax-return/completing-a-tax-return/deductions-credits-expenses/line-44000-refundable-quebec-abatement.html |
|
||||||
|
| T1 résidents du Québec | https://www.canada.ca/en/revenue-agency/services/forms-publications/forms/5005-r.html |
|
||||||
|
| TP-1, annexes, guide | https://www.revenuquebec.ca/fr/services-en-ligne/formulaires-et-publications/details-courant/tp-1/ |
|
||||||
|
| T2125 | https://www.canada.ca/fr/agence-revenu/services/formulaires-publications/formulaires/t2125.html |
|
||||||
|
| TP-80 | https://www.revenuquebec.ca/fr/services-en-ligne/formulaires-et-publications/details-courant/tp-80/ |
|
||||||
|
| T2, guide et PDF | https://www.canada.ca/en/revenue-agency/services/forms-publications/forms/t2.html |
|
||||||
|
| CO-17 et PDF | https://www.revenuquebec.ca/fr/services-en-ligne/formulaires-et-publications/details-courant/co-17/ |
|
||||||
|
| Taux des sociétés fédéral | https://www.canada.ca/en/revenue-agency/services/tax/businesses/topics/corporations/corporation-tax-rates.html |
|
||||||
|
| CO-17 guide Québec et taux | https://www.revenuquebec.ca/fr/services-en-ligne/formulaires-et-publications/co-17-g/guide-de-la-declaration-de-revenus-des-societes/ |
|
||||||
|
| Nouvelle hausse de DPE applicable après avril 2026 (hors millésime 2025) | https://www.revenuquebec.ca/en/press-room/tax-news/details/2026-05-04/increase-in-the-small-business-deduction-rate/ |
|
||||||
|
| Transmission T2 obligatoire, sous réserves | https://www.canada.ca/en/revenue-agency/services/tax/businesses/topics/corporations/corporation-income-tax-return.html |
|
||||||
|
| Transmission CO-17 obligatoire à partir d'années commençant en 2024, sous réserves | https://www.revenuquebec.ca/fr/entreprises/impots/impot-des-societes/ |
|
||||||
|
|
||||||
|
Les barèmes ci-dessus ne constituent qu'un sous-ensemble des règles fiscales. Le fait qu'un taux figure dans cette liste ne valide jamais automatiquement son applicabilité à une déclaration particulière.
|
||||||
BIN
docs/captures/accueil.png
Normal file
BIN
docs/captures/accueil.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 122 KiB |
BIN
docs/captures/parcours-societe.png
Normal file
BIN
docs/captures/parcours-societe.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 119 KiB |
2
fiscalibre/__init__.py
Normal file
2
fiscalibre/__init__.py
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
"""Fiscalibre — prototype de préparation, non logiciel de transmission fiscale."""
|
||||||
|
__version__ = "0.1.0"
|
||||||
15
fiscalibre/__main__.py
Normal file
15
fiscalibre/__main__.py
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
import argparse
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description="Démarrer Fiscalibre sur le poste local")
|
||||||
|
parser.add_argument("--port", type=int, default=8765)
|
||||||
|
parser.add_argument("--host", default="127.0.0.1")
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.host not in ("127.0.0.1", "localhost", "::1"):
|
||||||
|
parser.error("Fiscalibre V1 n'autorise que la liaison locale (loopback).")
|
||||||
|
uvicorn.run("fiscalibre.web:app", host=args.host, port=args.port)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
97
fiscalibre/pdf.py
Normal file
97
fiscalibre/pdf.py
Normal file
|
|
@ -0,0 +1,97 @@
|
||||||
|
"""Dossier de révision PDF. Ne prétend pas être un formulaire gouvernemental officiel."""
|
||||||
|
from __future__ import annotations
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
from xml.sax.saxutils import escape
|
||||||
|
|
||||||
|
from reportlab.lib import colors
|
||||||
|
from reportlab.lib.enums import TA_CENTER, TA_RIGHT
|
||||||
|
from reportlab.lib.pagesizes import A4
|
||||||
|
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
||||||
|
from reportlab.lib.units import mm
|
||||||
|
from reportlab.pdfbase import pdfmetrics
|
||||||
|
from reportlab.pdfbase.ttfonts import TTFont
|
||||||
|
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, KeepTogether
|
||||||
|
|
||||||
|
from .tax import SOURCES, monnaie
|
||||||
|
|
||||||
|
FONT_DIR = Path("/usr/share/fonts/truetype/dejavu")
|
||||||
|
if (FONT_DIR / "DejaVuSans.ttf").exists():
|
||||||
|
pdfmetrics.registerFont(TTFont("Fisc", str(FONT_DIR / "DejaVuSans.ttf")))
|
||||||
|
pdfmetrics.registerFont(TTFont("FiscBold", str(FONT_DIR / "DejaVuSans-Bold.ttf")))
|
||||||
|
REG, BOLD = "Fisc", "FiscBold"
|
||||||
|
else:
|
||||||
|
REG, BOLD = "Helvetica", "Helvetica-Bold"
|
||||||
|
|
||||||
|
|
||||||
|
def argent_fr(value) -> str:
|
||||||
|
"""Affichage français des montants, sans conversion flottante."""
|
||||||
|
entier, cents = monnaie(value).split(".")
|
||||||
|
sign = "-" if entier.startswith("-") else ""
|
||||||
|
chiffres = entier.lstrip("-")
|
||||||
|
groupes = []
|
||||||
|
while chiffres:
|
||||||
|
groupes.insert(0, chiffres[-3:])
|
||||||
|
chiffres = chiffres[:-3]
|
||||||
|
return sign + " ".join(groupes) + "," + cents + " $"
|
||||||
|
|
||||||
|
|
||||||
|
def exporter_pdf(dossier: dict, resultat: dict) -> bytes:
|
||||||
|
mem = BytesIO()
|
||||||
|
doc = SimpleDocTemplate(mem, pagesize=A4, rightMargin=18 * mm, leftMargin=18 * mm,
|
||||||
|
topMargin=19 * mm, bottomMargin=20 * mm)
|
||||||
|
styles = getSampleStyleSheet()
|
||||||
|
styles.add(ParagraphStyle(name="TitreFisc", fontName=BOLD, fontSize=21, leading=28, textColor=colors.HexColor("#123F4C"), spaceAfter=6))
|
||||||
|
styles.add(ParagraphStyle(name="SousFisc", fontName=BOLD, fontSize=11, leading=15, textColor=colors.HexColor("#123F4C"), spaceBefore=15, spaceAfter=7))
|
||||||
|
styles.add(ParagraphStyle(name="TexteFisc", fontName=REG, fontSize=8.4, leading=13, spaceAfter=6))
|
||||||
|
styles.add(ParagraphStyle(name="AlerteFisc", fontName=BOLD, fontSize=9, leading=14, textColor=colors.HexColor("#9B2F20"), spaceAfter=9))
|
||||||
|
styles.add(ParagraphStyle(name="UrlFisc", fontName=REG, fontSize=7.3, leading=11, wordWrap="CJK", spaceAfter=5))
|
||||||
|
story = [Paragraph("FISCALIBRE", styles["TitreFisc"]),
|
||||||
|
Paragraph("DOCUMENT DE TRAVAIL — NON TRANSMISSIBLE AUX AUTORITÉS FISCALES", styles["AlerteFisc"]),
|
||||||
|
Paragraph("Ce document ne remplace aucun formulaire gouvernemental officiel, n’est pas compatible IMPÔTNET et doit rester dans le dossier interne de révision.", styles["TexteFisc"]),
|
||||||
|
Paragraph(f"Millésime : 2025 · Profil : {escape(dossier['profil'])} · Référence : {escape(dossier['id'])}", styles["TexteFisc"])]
|
||||||
|
ident = dossier["data"]["identite"]
|
||||||
|
nom = ident.get("raison_sociale") or ((ident.get("prenom", "") + " " + ident.get("nom", "")).strip())
|
||||||
|
story.append(Paragraph(f"Dossier : {escape(nom or 'Non renseigné')}", styles["TexteFisc"]))
|
||||||
|
story.append(Paragraph("Résumé de calcul (incomplet)", styles["SousFisc"]))
|
||||||
|
|
||||||
|
def table(rows):
|
||||||
|
lignes = [[Paragraph(escape(str(a)), styles["TexteFisc"]), Paragraph(escape(str(b)), styles["TexteFisc"])] for a, b in rows]
|
||||||
|
t = Table(lignes, colWidths=[112 * mm, 55 * mm], hAlign="LEFT", repeatRows=0)
|
||||||
|
t.setStyle(TableStyle([
|
||||||
|
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||||||
|
("ROWBACKGROUNDS", (0, 0), (-1, -1), [colors.white, colors.HexColor("#F0F4F5")]),
|
||||||
|
("LEFTPADDING", (0, 0), (-1, -1), 8),
|
||||||
|
("RIGHTPADDING", (0, 0), (-1, -1), 8),
|
||||||
|
("BOTTOMPADDING", (0, 0), (-1, -1), 5),
|
||||||
|
("TOPPADDING", (0, 0), (-1, -1), 5),
|
||||||
|
]))
|
||||||
|
return t
|
||||||
|
|
||||||
|
story.append(table([(k, argent_fr(v)) for k, v in resultat["resume"].items()]))
|
||||||
|
for titre, lignes in resultat["lignes"].items():
|
||||||
|
story.append(Paragraph(escape(titre), styles["SousFisc"]))
|
||||||
|
story.append(table([(k, argent_fr(v)) for k, v in lignes.items()]))
|
||||||
|
story.append(Paragraph("Contrôles non réalisés et limites", styles["SousFisc"]))
|
||||||
|
for alerte in resultat["alertes"]:
|
||||||
|
story.append(Paragraph("• " + escape(alerte), styles["TexteFisc"]))
|
||||||
|
story.append(Paragraph("Références gouvernementales", styles["SousFisc"]))
|
||||||
|
for source in resultat["sources"]:
|
||||||
|
url = SOURCES[source]
|
||||||
|
domaine = urlsplit(url).hostname or "source officielle"
|
||||||
|
etiquette = source.replace("_", " ").capitalize()
|
||||||
|
story.append(Paragraph(f'<link href="{escape(url)}" color="#0b6558">{escape(etiquette)} — {escape(domaine)}</link>', styles["UrlFisc"]))
|
||||||
|
|
||||||
|
def footer(canvas, document):
|
||||||
|
canvas.saveState()
|
||||||
|
width, _ = A4
|
||||||
|
canvas.setFont(BOLD, 7)
|
||||||
|
canvas.setFillColor(colors.HexColor("#9B2F20"))
|
||||||
|
canvas.drawString(18*mm, 12*mm, "FISCALIBRE V0.1 — BROUILLON NON TRANSMISSIBLE")
|
||||||
|
canvas.setFont(REG, 7)
|
||||||
|
canvas.drawRightString(width-18*mm, 12*mm, f"Page {document.page}")
|
||||||
|
canvas.restoreState()
|
||||||
|
|
||||||
|
doc.build(story, onFirstPage=footer, onLaterPages=footer)
|
||||||
|
return mem.getvalue()
|
||||||
4
fiscalibre/static/exemple-import.csv
Normal file
4
fiscalibre/static/exemple-import.csv
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
categorie;montant;description
|
||||||
|
recettes_entreprise;1200,00;Facture 001
|
||||||
|
recettes_entreprise;300,00;Facture 002
|
||||||
|
depenses_entreprise;80,00;Hébergement serveur
|
||||||
|
1
fiscalibre/static/site.css
Normal file
1
fiscalibre/static/site.css
Normal file
File diff suppressed because one or more lines are too long
65
fiscalibre/storage.py
Normal file
65
fiscalibre/storage.py
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
"""Stockage SQLite local. Les données ne sont PAS chiffrées au repos dans cette V1."""
|
||||||
|
from __future__ import annotations
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
def data_directory() -> Path:
|
||||||
|
path = Path(os.environ.get("FISCALIBRE_DATA_DIR", Path.home() / ".local/share/fiscalibre"))
|
||||||
|
path.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
|
path.chmod(0o700)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def conn() -> sqlite3.Connection:
|
||||||
|
path = data_directory() / "dossiers.sqlite3"
|
||||||
|
connection = sqlite3.connect(path)
|
||||||
|
connection.row_factory = sqlite3.Row
|
||||||
|
connection.execute("""CREATE TABLE IF NOT EXISTS dossiers (
|
||||||
|
id TEXT PRIMARY KEY, profil TEXT NOT NULL, contenu TEXT NOT NULL,
|
||||||
|
date_modification TEXT NOT NULL
|
||||||
|
)""")
|
||||||
|
connection.commit()
|
||||||
|
if path.exists():
|
||||||
|
path.chmod(0o600)
|
||||||
|
return connection
|
||||||
|
|
||||||
|
|
||||||
|
def nouveau(profil: str) -> str:
|
||||||
|
if profil not in ("particulier", "autonome", "societe"):
|
||||||
|
raise ValueError("Profil inconnu")
|
||||||
|
reference = uuid.uuid4().hex[:12]
|
||||||
|
contenu = {
|
||||||
|
"annee": 2025,
|
||||||
|
"identite": {"nom": "", "prenom": "", "raison_sociale": "", "courriel": "", "neq": "", "numero_entreprise": "", "debut_exercice": "2025-01-01", "fin_exercice": "2025-12-31"},
|
||||||
|
"montants": {},
|
||||||
|
"options": {"spcc": False, "dpe_federale": False, "dpe_quebec": False, "activite_quebec_uniquement": True, "autres_sources": False, "depreciation": False, "actionnaires_associes": False},
|
||||||
|
"importations": [],
|
||||||
|
}
|
||||||
|
with conn() as db:
|
||||||
|
db.execute("INSERT INTO dossiers VALUES (?,?,?,?)", (reference, profil, json.dumps(contenu, ensure_ascii=False), datetime.now(timezone.utc).isoformat()))
|
||||||
|
return reference
|
||||||
|
|
||||||
|
|
||||||
|
def obtenir(reference: str) -> dict[str, Any] | None:
|
||||||
|
with conn() as db:
|
||||||
|
row = db.execute("SELECT * FROM dossiers WHERE id=?", (reference,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {"id": row["id"], "profil": row["profil"], "data": json.loads(row["contenu"]), "modifie": row["date_modification"]}
|
||||||
|
|
||||||
|
|
||||||
|
def enregistrer(dossier: dict[str, Any]) -> None:
|
||||||
|
with conn() as db:
|
||||||
|
db.execute("UPDATE dossiers SET contenu=?, date_modification=? WHERE id=?", (json.dumps(dossier["data"], ensure_ascii=False), datetime.now(timezone.utc).isoformat(), dossier["id"]))
|
||||||
|
|
||||||
|
|
||||||
|
def dossiers_recents() -> list[dict[str, Any]]:
|
||||||
|
with conn() as db:
|
||||||
|
rows = db.execute("SELECT id, profil, contenu, date_modification FROM dossiers ORDER BY date_modification DESC LIMIT 30").fetchall()
|
||||||
|
return [{"id": r["id"], "profil": r["profil"], "titre": json.loads(r["contenu"]).get("identite", {}).get("raison_sociale") or json.loads(r["contenu"]).get("identite", {}).get("nom") or "Sans nom", "modifie": r["date_modification"][:10]} for r in rows]
|
||||||
175
fiscalibre/tax.py
Normal file
175
fiscalibre/tax.py
Normal file
|
|
@ -0,0 +1,175 @@
|
||||||
|
"""Moteur 2025 déterministe de DÉMONSTRATION; aucune sortie n'est prête à produire.
|
||||||
|
|
||||||
|
Ne calcule pas l'impôt final dû, les crédits complets, les cotisations sociales,
|
||||||
|
ni les déductions et annexes requises pour une déclaration légale.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
||||||
|
from datetime import date
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
CENT = Decimal("0.01")
|
||||||
|
ZERO = Decimal("0")
|
||||||
|
|
||||||
|
SOURCES = {
|
||||||
|
"federal_tranches": "https://www.canada.ca/en/revenue-agency/services/tax/individuals/tax-rates-brackets/last-year.html",
|
||||||
|
"quebec_tranches": "https://www.revenuquebec.ca/fr/citoyens/declaration-de-revenus/produire-votre-declaration-de-revenus/taux-dimposition/",
|
||||||
|
"federal_base": "https://www.canada.ca/en/revenue-agency/services/tax/individuals/topics/about-your-tax-return/tax-return/completing-a-tax-return/deductions-credits-expenses/line-30000-basic-personal-amount.html",
|
||||||
|
"quebec_base": "https://www.revenuquebec.ca/fr/citoyens/declaration-de-revenus/produire-votre-declaration-de-revenus/aide-par-ligne/350-a-398-1-credits-dimpot-non-remboursables/ligne-350/",
|
||||||
|
"abattement": "https://www.canada.ca/en/revenue-agency/services/tax/individuals/topics/about-your-tax-return/tax-return/completing-a-tax-return/deductions-credits-expenses/line-44000-refundable-quebec-abatement.html",
|
||||||
|
"societes_federal": "https://www.canada.ca/en/revenue-agency/services/tax/businesses/topics/corporations/corporation-tax-rates.html",
|
||||||
|
"societes_quebec": "https://www.revenuquebec.ca/fr/services-en-ligne/formulaires-et-publications/co-17-g/guide-de-la-declaration-de-revenus-des-societes/",
|
||||||
|
"forms_t1": "https://www.canada.ca/en/revenue-agency/services/forms-publications/forms/5005-r.html",
|
||||||
|
"forms_tp1": "https://www.revenuquebec.ca/fr/services-en-ligne/formulaires-et-publications/details-courant/tp-1/",
|
||||||
|
"forms_t2": "https://www.canada.ca/en/revenue-agency/services/forms-publications/forms/t2.html",
|
||||||
|
"forms_co17": "https://www.revenuquebec.ca/fr/services-en-ligne/formulaires-et-publications/details-courant/co-17/",
|
||||||
|
"forms_t2125": "https://www.canada.ca/fr/agence-revenu/services/formulaires-publications/formulaires/t2125.html",
|
||||||
|
"forms_tp80": "https://www.revenuquebec.ca/fr/services-en-ligne/formulaires-et-publications/details-courant/tp-80/",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Les tranches sont en vigueur pour l'année d'imposition civile 2025 seulement.
|
||||||
|
FED = ((Decimal("57375"), Decimal("0.145")),
|
||||||
|
(Decimal("114750"), Decimal("0.205")),
|
||||||
|
(Decimal("177882"), Decimal("0.26")),
|
||||||
|
(Decimal("253414"), Decimal("0.29")),
|
||||||
|
(None, Decimal("0.33")))
|
||||||
|
QC = ((Decimal("53255"), Decimal("0.14")),
|
||||||
|
(Decimal("106495"), Decimal("0.19")),
|
||||||
|
(Decimal("129590"), Decimal("0.24")),
|
||||||
|
(None, Decimal("0.2575")))
|
||||||
|
|
||||||
|
|
||||||
|
def argent(value: Any) -> Decimal:
|
||||||
|
"""Accepte 1234,56, 1 234,56 ou 1234.56; jamais de flottant dans les calculs."""
|
||||||
|
if value is None or value == "":
|
||||||
|
return ZERO
|
||||||
|
value = str(value).replace("\u00a0", "").replace(" ", "").replace("$", "")
|
||||||
|
if "," in value and "." in value:
|
||||||
|
raise ValueError("Utilisez la virgule OU le point, pas les deux.")
|
||||||
|
try:
|
||||||
|
nombre = Decimal(value.replace(",", "."))
|
||||||
|
except InvalidOperation as exc:
|
||||||
|
raise ValueError("Montant numérique invalide") from exc
|
||||||
|
if not nombre.is_finite() or nombre < ZERO or nombre > Decimal("999999999999"):
|
||||||
|
raise ValueError("Montant hors limites (0 à 999 999 999 999)")
|
||||||
|
return nombre.quantize(CENT, rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def monnaie(value: Decimal) -> str:
|
||||||
|
return format(value.quantize(CENT, rounding=ROUND_HALF_UP), ".2f")
|
||||||
|
|
||||||
|
|
||||||
|
def progressif(revenu: Decimal, tranches: tuple) -> Decimal:
|
||||||
|
assiette = max(ZERO, revenu)
|
||||||
|
total = ZERO
|
||||||
|
bas = ZERO
|
||||||
|
for haut, taux in tranches:
|
||||||
|
portion = max(ZERO, (assiette if haut is None else min(assiette, haut)) - bas)
|
||||||
|
total += portion * taux
|
||||||
|
if haut is None or assiette <= haut:
|
||||||
|
break
|
||||||
|
bas = haut
|
||||||
|
return total.quantize(CENT, rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def champs(dossier: dict) -> dict[str, Decimal]:
|
||||||
|
return {k: argent(v) for k, v in dossier["data"]["montants"].items()}
|
||||||
|
|
||||||
|
|
||||||
|
def calculer(dossier: dict) -> dict[str, Any]:
|
||||||
|
profil, data = dossier["profil"], dossier["data"]
|
||||||
|
if data.get("annee") != 2025:
|
||||||
|
raise ValueError("Seul le millésime 2025 est couvert par ce moteur")
|
||||||
|
m, options = champs(dossier), data["options"]
|
||||||
|
get = lambda key: m.get(key, ZERO)
|
||||||
|
alertes = ["MOTEUR INCOMPLET : ne pas utiliser les résultats pour une production fiscale réelle."]
|
||||||
|
if profil in ("particulier", "autonome"):
|
||||||
|
revenus_travail = (get("revenu_emploi") + get("pension_qpp") + get("pension_autre") +
|
||||||
|
get("pension_securite_vieillesse") + get("revenu_interets") + get("autres_revenus"))
|
||||||
|
recettes = get("recettes_entreprise") if profil == "autonome" else ZERO
|
||||||
|
depenses = get("depenses_entreprise") if profil == "autonome" else ZERO
|
||||||
|
benefice = recettes - depenses
|
||||||
|
# Un déficit est possible, mais les restrictions ne sont pas modélisées.
|
||||||
|
revenu_total = revenus_travail + benefice
|
||||||
|
deductions = get("deduction_reer") + get("autres_deductions")
|
||||||
|
assiette = max(ZERO, revenu_total - deductions)
|
||||||
|
base_fed = Decimal("16129")
|
||||||
|
if assiette > Decimal("177882"):
|
||||||
|
base_fed -= min(Decimal("1591"), (assiette - Decimal("177882")) * Decimal("1591") / Decimal("75532"))
|
||||||
|
impot_fed_avant_credit = progressif(assiette, FED)
|
||||||
|
# Valeur indicative sans calcul des cotisations RRQ, AE, RQAP ni autres crédits.
|
||||||
|
credits_fed = (base_fed + min(get("revenu_emploi"), Decimal("1471"))) * Decimal("0.145")
|
||||||
|
impot_fed_base = max(ZERO, impot_fed_avant_credit - credits_fed).quantize(CENT, rounding=ROUND_HALF_UP)
|
||||||
|
abattement_qc = (impot_fed_base * Decimal("0.165")).quantize(CENT, rounding=ROUND_HALF_UP)
|
||||||
|
impot_fed_indicatif = max(ZERO, impot_fed_base - abattement_qc)
|
||||||
|
impot_qc_avant_credit = progressif(assiette, QC)
|
||||||
|
credit_qc_base = Decimal("18571") * Decimal("0.14")
|
||||||
|
impot_qc_indicatif = max(ZERO, impot_qc_avant_credit - credit_qc_base).quantize(CENT, rounding=ROUND_HALF_UP)
|
||||||
|
alertes.extend([
|
||||||
|
"Les cotisations RRQ/RPC, AE et RQAP, leurs crédits et déductions ne sont pas calculés.",
|
||||||
|
"Les prestations, remboursements, crédits remboursables, reports, retenues et taxes spéciales ne sont pas calculés.",
|
||||||
|
"Les règles de pension, dividendes, gains en capital et autres situations ne sont pas couvertes.",
|
||||||
|
"La base imposable Québec peut différer de la base fédérale : ajustements non gérés.",
|
||||||
|
])
|
||||||
|
if profil == "autonome":
|
||||||
|
alertes.append("Le bénéfice commercial ne tient pas compte des ajustements comptables, stocks, amortissement (DPA), taxe sur ventes ni cotisations de travail autonome.")
|
||||||
|
if options.get("autres_sources"):
|
||||||
|
alertes.append("D'autres sources de revenus ou situations sont signalées : examen spécialisé obligatoire.")
|
||||||
|
return {
|
||||||
|
"profil": profil,
|
||||||
|
"titre": "T1 et TP-1" + (" · T2125 et TP-80 (à compléter)" if profil == "autonome" else ""),
|
||||||
|
"lignes": {
|
||||||
|
"ARC / T1 (préparation)": {"10100": get("revenu_emploi"), "11300": get("pension_securite_vieillesse"), "11400": get("pension_qpp"), "11500": get("pension_autre"), "12100": get("revenu_interets"), "13500": benefice if profil == "autonome" else ZERO, "15000": revenu_total, "20800": get("deduction_reer"), "23600": assiette, "26000": assiette, "30000": base_fed, "42900 (indicatif)": impot_fed_base, "44000 (indicatif)": abattement_qc},
|
||||||
|
"Québec / TP-1 (préparation)": {"101": get("revenu_emploi"), "114": get("pension_securite_vieillesse"), "119": get("pension_qpp"), "122": get("pension_autre"), "130": get("revenu_interets"), "164": benefice if profil == "autonome" else ZERO, "199": revenu_total, "350": Decimal("18571")},
|
||||||
|
},
|
||||||
|
"resume": {"Revenu brut / total provisoire": revenu_total, "Revenu imposable estimatif": assiette, "Impôt fédéral indicatif après abattement": impot_fed_indicatif, "Impôt Québec indicatif": impot_qc_indicatif},
|
||||||
|
"alertes": alertes,
|
||||||
|
"sources": ["federal_tranches", "quebec_tranches", "federal_base", "quebec_base", "abattement"],
|
||||||
|
"pret_a_transmettre": False,
|
||||||
|
}
|
||||||
|
if profil != "societe":
|
||||||
|
raise ValueError("Profil inconnu")
|
||||||
|
recettes = get("recettes_entreprise")
|
||||||
|
depenses = get("depenses_entreprise")
|
||||||
|
ajustements = get("depenses_non_deductibles")
|
||||||
|
deductions = get("pertes_anterieures")
|
||||||
|
revenu_comptable = recettes - depenses
|
||||||
|
revenu_fiscal = max(ZERO, revenu_comptable + ajustements - deductions)
|
||||||
|
debut = date.fromisoformat(data["identite"]["debut_exercice"])
|
||||||
|
fin = date.fromisoformat(data["identite"]["fin_exercice"])
|
||||||
|
duree = (fin - debut).days + 1
|
||||||
|
if not 1 <= duree <= 371:
|
||||||
|
raise ValueError("Exercice fiscal invalide ou supérieur à 371 jours")
|
||||||
|
# Le plafond fédéral est proratisé pour une année de moins de 51 semaines.
|
||||||
|
plafond = min(Decimal("500000"), Decimal("500000") * Decimal(duree) / Decimal("365"))
|
||||||
|
plafond = plafond.quantize(CENT, rounding=ROUND_HALF_UP)
|
||||||
|
eligible_fed = options.get("spcc", False) and options.get("dpe_federale", False)
|
||||||
|
eligible_qc = options.get("spcc", False) and options.get("dpe_quebec", False)
|
||||||
|
tranche_fed = min(revenu_fiscal, plafond) if eligible_fed else ZERO
|
||||||
|
tranche_qc = min(revenu_fiscal, plafond) if eligible_qc else ZERO
|
||||||
|
impot_fed = (tranche_fed * Decimal("0.09") + (revenu_fiscal - tranche_fed) * Decimal("0.15")).quantize(CENT, rounding=ROUND_HALF_UP)
|
||||||
|
impot_qc = (tranche_qc * Decimal("0.032") + (revenu_fiscal - tranche_qc) * Decimal("0.115")).quantize(CENT, rounding=ROUND_HALF_UP)
|
||||||
|
alertes.extend([
|
||||||
|
"Les plafonds des affaires associés, le capital imposable, le revenu de placement passif et les règles d'attribution ne sont pas calculés.",
|
||||||
|
"La DPE québécoise dépend de critères particuliers (notamment heures rémunérées et secteurs) : les cases à cocher ne constituent PAS une vérification d'admissibilité.",
|
||||||
|
"Les ajustements d'impôt (annexe 1), pertes, impôts spéciaux, crédits, DPA, IGRF/S100-S125 et annexes obligatoires ne sont pas automatisés.",
|
||||||
|
"La répartition interprovinciale, les acomptes et soldes n'est pas couverte.",
|
||||||
|
])
|
||||||
|
if options.get("depreciation"):
|
||||||
|
alertes.append("Acquisitions d'immobilisations déclarées : traitement de la DPA indispensable, non pris en charge.")
|
||||||
|
if options.get("actionnaires_associes"):
|
||||||
|
alertes.append("Sociétés associées ou transactions entre apparentés : révision professionnelle nécessaire.")
|
||||||
|
if debut.year != 2025 or fin.year != 2025:
|
||||||
|
alertes.append("Exercice à cheval sur plusieurs années : les règles de transition et changements de taux ne sont pas calculés.")
|
||||||
|
return {
|
||||||
|
"profil": profil,
|
||||||
|
"titre": "T2 et CO-17 (ébauches de calcul)",
|
||||||
|
"lignes": {
|
||||||
|
"ARC / T2 (préparation)": {"Revenu comptable": revenu_comptable, "Ajustements réintégrés": ajustements, "Pertes indiquées (sans validation)": deductions, "Revenu imposable indicatif": revenu_fiscal, "Impôt estimé (sans annexes)": impot_fed},
|
||||||
|
"Québec / CO-17 (préparation)": {"Revenu imposable indicatif": revenu_fiscal, "Impôt estimé (sans annexes)": impot_qc},
|
||||||
|
},
|
||||||
|
"resume": {"Résultat comptable": revenu_comptable, "Revenu imposable estimatif": revenu_fiscal, "Impôt fédéral indicatif": impot_fed, "Impôt Québec indicatif": impot_qc},
|
||||||
|
"alertes": alertes,
|
||||||
|
"sources": ["societes_federal", "societes_quebec"],
|
||||||
|
"pret_a_transmettre": False,
|
||||||
|
}
|
||||||
20
fiscalibre/templates/base.html
Normal file
20
fiscalibre/templates/base.html
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="fr-CA">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<meta name="color-scheme" content="light">
|
||||||
|
<title>{% block title %}Fiscalibre{% endblock %}</title>
|
||||||
|
<link rel="stylesheet" href="/static/site.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="bar-inner">
|
||||||
|
<a class="brand" href="/"><span class="brand-emblem">F</span><span>fisca<span class="brand-strong">libre</span></span></a>
|
||||||
|
<div class="topbar-right"><span class="version">Prototype · 0.1</span><span class="local"><span class="local-dot"></span> Local · Aucune connexion</span></div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main class="page">{% block content %}{% endblock %}</main>
|
||||||
|
<footer class="footer"><div class="footer-in"><strong>Fiscalibre</strong><span>Logiciel libre · Fonctionne sur votre ordinateur</span><span>Calculs de démonstration — aucune déclaration homologuée</span></div></footer>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
66
fiscalibre/templates/dossier.html
Normal file
66
fiscalibre/templates/dossier.html
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Dossier {{ dossier.id }} · Fiscalibre{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<div class="app-layout">
|
||||||
|
<aside class="sidebar"><a class="back" href="/">← Tous les dossiers</a><div class="sidebar-heading">VOTRE DOSSIER</div><h2>{{ dossier.data.identite.raison_sociale or (dossier.data.identite.prenom ~ ' ' ~ dossier.data.identite.nom)|trim or 'Sans nom' }}</h2><div class="sidetype">{{ {'particulier':'Particulier','autonome':'Travail autonome','societe':'Société incorporée'}[dossier.profil] }} · 2025</div>
|
||||||
|
<nav class="steps" aria-label="Étapes du dossier">
|
||||||
|
{% for k, title, desc in [('identite','Votre profil','Qui déclare ?'),('revenus','Vos revenus','Ce qui est entré'),('deductions','Déductions','Ce qui est admissible'),('verification','Vérification','Ce qu’il faut confirmer')] %}
|
||||||
|
<a href="/dossier/{{ dossier.id }}?etape={{ k }}" class="step {% if etape == k %}active{% endif %}"><span class="step-num">{{ loop.index }}</span><span><strong>{{ title }}</strong><small>{{ desc }}</small></span></a>
|
||||||
|
{% endfor %}
|
||||||
|
</nav>
|
||||||
|
<div class="sidebar-disclaimer"><strong>Aucune télétransmission</strong><p>Cette version ne produit pas encore les formulaires prescrits ou fichiers électroniques acceptés par l'ARC et Revenu Québec.</p></div>
|
||||||
|
</aside>
|
||||||
|
<div class="workspace"><div class="workspace-top"><div><div class="eyebrow">Dossier {{ dossier.id }} / 2025</div><h1>{{ {'identite':'Parlons de vous','revenus':'D’où vient l’argent ?','deductions':'Réduisons ce qui est imposable','verification':'Votre dossier, en un coup d’œil'}[etape] }}</h1><p class="intro">{{ {'identite':'Seulement les renseignements nécessaires pour commencer.','revenus':'Entrez les totaux. Vous pourrez aussi importer un petit fichier CSV.','deductions':'Déclarer une déduction ne signifie pas qu’elle est fiscalement admissible.','verification':'Nous regroupons les montants pour l’ARC et Revenu Québec et signalons ce qu’il reste à vérifier.'}[etape] }}</p></div><span class="year-chip">Année fiscale 2025</span></div>
|
||||||
|
{% if erreur %}<div class="alert critical">{{ erreur }}</div>{% endif %}
|
||||||
|
{% if etape != 'verification' %}
|
||||||
|
<form method="post" action="/dossier/{{ dossier.id }}/enregistrer?etape={{ etape }}" class="data-form">
|
||||||
|
{% if etape == 'identite' %}
|
||||||
|
<section class="panel"><div class="panel-top"><span class="kicker">ÉTAPE 01</span><h2>{{ 'Identification de la société' if dossier.profil == 'societe' else 'Votre identité' }}</h2></div>
|
||||||
|
<div class="form-grid">{% for key, label, help, type in identite_champs %}<div class="field"><label for="i_{{ key }}">{{ label }}</label><input id="i_{{ key }}" name="i_{{ key }}" type="{{ type }}" maxlength="200" autocomplete="off" value="{{ dossier.data.identite.get(key,'') }}" placeholder="{{ help }}"><small>{{ help }}</small></div>{% endfor %}</div>
|
||||||
|
</section>
|
||||||
|
<div class="alert"><strong>Données sensibles :</strong> Fiscalibre n’enregistre pas encore le NAS des particuliers dans cette version. Le chiffrement de la base de données devra précéder son ajout.</div>
|
||||||
|
{% elif etape == 'revenus' %}
|
||||||
|
{% if dossier.profil != 'societe' %}
|
||||||
|
<section class="panel"><div class="panel-top"><span class="kicker">REVENU PERSONNEL</span><h2>De quoi sont composés vos revenus ?</h2><p>Utilisez le montant annuel indiqué sur vos documents.</p></div><div class="form-grid">{% for key, label, help in revenus_pers %}<div class="field"><label for="m_{{ key }}">{{ label }}</label><div class="currency-input"><input id="m_{{ key }}" name="m_{{ key }}" type="text" inputmode="decimal" value="{{ dossier.data.montants.get(key,'') }}" placeholder="0,00"><span>$ CAD</span></div><small>{{ help }}</small></div>{% endfor %}</div></section>
|
||||||
|
{% endif %}
|
||||||
|
{% if dossier.profil != 'particulier' %}<section class="panel"><div class="panel-top"><span class="kicker">ACTIVITÉ COMMERCIALE</span><h2>{{ 'Exploitation de la société' if dossier.profil == 'societe' else 'Votre travail autonome' }}</h2><p>Ces deux montants ne suffisent pas à eux seuls à établir le bénéfice fiscal légal.</p></div><div class="form-grid">{% for key, label, help in revenus_ent %}<div class="field"><label for="m_{{ key }}">{{ label }}</label><div class="currency-input"><input id="m_{{ key }}" name="m_{{ key }}" type="text" inputmode="decimal" value="{{ dossier.data.montants.get(key,'') }}" placeholder="0,00"><span>$ CAD</span></div><small>{{ help }}</small></div>{% endfor %}</div></section>{% endif %}
|
||||||
|
{% elif etape == 'deductions' %}
|
||||||
|
<section class="panel"><div class="panel-top"><span class="kicker">DÉDUCTIONS</span><h2>{{ 'Ajustements fiscaux' if dossier.profil == 'societe' else 'Déductions personnelles' }}</h2></div><div class="form-grid">{% for key, label, help in (deductions_soc if dossier.profil == 'societe' else deductions_pers) %}<div class="field"><label for="m_{{ key }}">{{ label }}</label><div class="currency-input"><input id="m_{{ key }}" name="m_{{ key }}" type="text" inputmode="decimal" value="{{ dossier.data.montants.get(key,'') }}" placeholder="0,00"><span>$ CAD</span></div><small>{{ help }}</small></div>{% endfor %}</div></section>
|
||||||
|
<section class="panel"><div class="panel-top"><span class="kicker">POINTS À VÉRIFIER</span><h2>Ces questions changent votre dossier</h2></div><div class="switches">{% for key, label, help in options %}<label class="switch"><input name="o_{{ key }}" type="checkbox" {% if dossier.data.options.get(key) %}checked{% endif %}><span><strong>{{ label }}</strong><small>{{ help }}</small></span></label>{% endfor %}</div></section>
|
||||||
|
{% endif %}
|
||||||
|
<div class="form-actions"><span>Vos réponses sont enregistrées uniquement sur cet ordinateur.</span><button class="primary-button" type="submit">Enregistrer et continuer <span>→</span></button></div>
|
||||||
|
</form>
|
||||||
|
{% if etape == 'revenus' %}
|
||||||
|
<section class="panel import-panel"><div class="panel-top"><span class="kicker">OPTION · IMPORTATION</span><h2>Vous avez déjà un tableau ?</h2><p>Importez un CSV avec trois colonnes, séparées par des points-virgules : <code>categorie;montant;description</code>. Les montants seront additionnés aux montants existants.</p></div><form method="post" action="/dossier/{{ dossier.id }}/importer" enctype="multipart/form-data" class="import-form"><input type="file" name="fichier" accept=".csv,text/csv" required><button type="submit" class="secondary-button">Importer les montants</button></form><a href="/static/exemple-import.csv" download>Voir un exemple CSV →</a></section>
|
||||||
|
{% if dossier.data.importations %}<p class="muted">{{ dossier.data.importations|length }} importation(s) enregistrée(s). Attention à ne pas importer deux fois le même fichier.</p>{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
{% else %}
|
||||||
|
{% if resultat %}
|
||||||
|
<div class="alert critical"><strong>Calculs de démonstration — NON TRANSMISSIBLES.</strong> Aucun solde fiscal réel ne peut être déduit de ces montants.</div>
|
||||||
|
<section class="summary-grid">{% for label, montant in resultat.resume.items() %}<div class="summary-card"><span>{{ label }}</span><strong>{{ montant|money }}</strong></div>{% endfor %}</section>
|
||||||
|
<section class="panel"><div class="panel-top"><span class="kicker">DOUBLE JURIDICTION</span><h2>Lignes préparatoires des formulaires</h2><p>Le logiciel fournit les données de rapprochement, pas les formulaires officiels remplis.</p></div>
|
||||||
|
{% for titre, lignes in resultat.lignes.items() %}<h3 class="jurisdiction">{{ titre }}</h3><div class="line-items">{% for code, valeur in lignes.items() %}<div class="line-item"><span>{{ code }}</span><strong>{{ valeur|money }}</strong></div>{% endfor %}</div>{% endfor %}</section>
|
||||||
|
<section class="panel"><div class="panel-top"><span class="kicker">CONTRÔLES</span><h2>À résoudre avant toute production réelle</h2></div><ul class="alerts-list">{% for alerte in resultat.alertes %}<li>{{ alerte }}</li>{% endfor %}</ul></section>
|
||||||
|
<section class="panel"><div class="panel-top"><span class="kicker">EXPORTER</span><h2>Récupérer le dossier de travail</h2><p>Le PDF est un dossier de calcul interne, pas un formulaire accepté par l'administration.</p></div><div class="download-actions"><a class="primary-button" href="/dossier/{{ dossier.id }}/export/pdf">Exporter le PDF de révision ↓</a><a class="secondary-button" href="/dossier/{{ dossier.id }}/export/json">Exporter les données JSON ↓</a></div></section>
|
||||||
|
<section class="panel"><div class="panel-top"><span class="kicker">DOCUMENTS DES ADMINISTRATIONS</span><h2>Consulter les véritables formulaires</h2><p>Pour préparer le raccordement aux modèles gouvernementaux, ces liens ouvrent les versions officielles (elles ne sont pas remplies par Fiscalibre V0.1).</p></div>
|
||||||
|
<ul class="sources-list">
|
||||||
|
{% if dossier.profil == 'societe' %}
|
||||||
|
<li><a href="{{ sources.forms_t2 }}" target="_blank" rel="noopener noreferrer">ARC — Formulaire T2 officiel ↗</a></li>
|
||||||
|
<li><a href="{{ sources.forms_co17 }}" target="_blank" rel="noopener noreferrer">Revenu Québec — Formulaire CO-17 officiel ↗</a></li>
|
||||||
|
{% else %}
|
||||||
|
<li><a href="{{ sources.forms_t1 }}" target="_blank" rel="noopener noreferrer">ARC — Formulaire T1 officiel ↗</a></li>
|
||||||
|
<li><a href="{{ sources.forms_tp1 }}" target="_blank" rel="noopener noreferrer">Revenu Québec — Formulaire TP-1 officiel ↗</a></li>
|
||||||
|
{% if dossier.profil == 'autonome' %}
|
||||||
|
<li><a href="{{ sources.forms_t2125 }}" target="_blank" rel="noopener noreferrer">ARC — Formulaire T2125 ↗</a></li>
|
||||||
|
<li><a href="{{ sources.forms_tp80 }}" target="_blank" rel="noopener noreferrer">Revenu Québec — Formulaire TP-80 ↗</a></li>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
<section class="panel"><div class="panel-top"><span class="kicker">SOURCES OFFICIELLES</span><h2>Vérifier les règles</h2></div><ul class="sources-list">{% for key in resultat.sources %}<li><a href="{{ sources[key] }}" target="_blank" rel="noopener noreferrer">{{ key|replace('_',' ')|capitalize }} ↗</a></li>{% endfor %}</ul></section>
|
||||||
|
{% else %}<div class="alert critical">Impossible de calculer ce dossier. Vérifiez les montants et les dates d'exercice.</div>{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
<p class="lastline">Fiscalibre est un prototype libre, pas un préparateur fiscal autorisé. Aucun renseignement n'est envoyé à des tiers par l'application.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
20
fiscalibre/templates/index.html
Normal file
20
fiscalibre/templates/index.html
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Accueil · Fiscalibre{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<section class="hero">
|
||||||
|
<div class="eyebrow">L'impôt sans les formulaires, un jour.</div>
|
||||||
|
<h1>Deux gouvernements.<br><em>Une seule expérience.</em></h1>
|
||||||
|
<p>Un assistant fiscal libre pour les citoyens et les entreprises du Québec. Dites-nous ce que vous avez gagné, dépensé ou épargné. Nous organisons le dossier pour les deux paliers.</p>
|
||||||
|
<div class="hero-notice"><span class="notice-icon">!</span><span><strong>Version de développement :</strong> calculs partiels pour 2025, PDF de révision seulement. Ne transmettez pas ces documents aux gouvernements.</span></div>
|
||||||
|
</section>
|
||||||
|
<section class="section">
|
||||||
|
<div class="section-head"><div class="eyebrow">Commencer</div><h2>Pour qui produisons-nous la déclaration ?</h2><p>Choisissez votre situation. Les questions s'adapteront automatiquement.</p></div>
|
||||||
|
<div class="profile-grid">
|
||||||
|
<form method="post" action="/dossier/nouveau"><input type="hidden" name="profil" value="particulier"><button type="submit" class="profile-card"><div class="profile-icon">01</div><h3>Pour moi</h3><p>Salaires, retraite, intérêts, REER et crédits courants.</p><span class="profile-bottom">Déclaration de particulier <span>↗</span></span><div class="form-ids">T1 <span>+</span> TP-1</div></button></form>
|
||||||
|
<form method="post" action="/dossier/nouveau"><input type="hidden" name="profil" value="autonome"><button type="submit" class="profile-card"><div class="profile-icon">02</div><h3>Mon activité autonome</h3><p>Revenus professionnels, factures, dépenses et déductions.</p><span class="profile-bottom">Travailleur autonome <span>↗</span></span><div class="form-ids">T2125 <span>+</span> TP-80</div></button></form>
|
||||||
|
<form method="post" action="/dossier/nouveau"><input type="hidden" name="profil" value="societe"><button type="submit" class="profile-card"><div class="profile-icon">03</div><h3>Ma société</h3><p>Comptabilité, bénéfices, déductions et impôt des sociétés.</p><span class="profile-bottom">Société incorporée <span>↗</span></span><div class="form-ids">T2 <span>+</span> CO-17</div></button></form>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% if dossiers %}<section class="section recent"><div class="section-head"><div class="eyebrow">Reprendre</div><h2>Vos dossiers locaux</h2></div><div class="recent-list">{% for dossier in dossiers %}<a href="/dossier/{{ dossier.id }}?etape=verification" class="recent-item"><div><strong>{{ dossier.titre }}</strong><span>{{ {'particulier':'Particulier','autonome':'Travail autonome','societe':'Société'}[dossier.profil] }} · {{ dossier.modifie }}</span></div><span>Continuer →</span></a>{% endfor %}</div></section>{% endif %}
|
||||||
|
<section class="facts"><div><strong>100 % local</strong><span>Sur votre poste Debian</span></div><div><strong>2025</strong><span>Premier millésime disponible</span></div><div><strong>2 administrations</strong><span>ARC + Revenu Québec</span></div></section>
|
||||||
|
{% endblock %}
|
||||||
241
fiscalibre/web.py
Normal file
241
fiscalibre/web.py
Normal file
|
|
@ -0,0 +1,241 @@
|
||||||
|
"""Interface Web volontairement locale, sans télémétrie ni dépendance CDN."""
|
||||||
|
from __future__ import annotations
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
from fastapi import FastAPI, HTTPException, Request, UploadFile, File
|
||||||
|
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from fastapi.templating import Jinja2Templates
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
|
||||||
|
from . import __version__
|
||||||
|
from . import storage
|
||||||
|
from .tax import SOURCES, argent, calculer, monnaie
|
||||||
|
from .pdf import exporter_pdf, argent_fr
|
||||||
|
|
||||||
|
BASE = Path(__file__).parent
|
||||||
|
app = FastAPI(title="Fiscalibre", version=__version__, docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
app.mount("/static", StaticFiles(directory=BASE / "static"), name="static")
|
||||||
|
templates = Jinja2Templates(directory=str(BASE / "templates"))
|
||||||
|
templates.env.filters["money"] = argent_fr
|
||||||
|
|
||||||
|
IDENTITE_PART = [
|
||||||
|
("prenom", "Prénom", "Prénom légal", "text"),
|
||||||
|
("nom", "Nom", "Nom de famille légal", "text"),
|
||||||
|
("courriel", "Courriel (facultatif)", "Pour votre suivi personnel", "email"),
|
||||||
|
]
|
||||||
|
IDENTITE_SOC = [
|
||||||
|
("raison_sociale", "Raison sociale", "Nom légal de la société", "text"),
|
||||||
|
("numero_entreprise", "Numéro d’entreprise (NE)", "9 chiffres, sans extension RP", "text"),
|
||||||
|
("neq", "Numéro d'entreprise du Québec (NEQ)", "10 chiffres", "text"),
|
||||||
|
("debut_exercice", "Début d’exercice", "Ex. 2025-01-01", "date"),
|
||||||
|
("fin_exercice", "Fin d’exercice", "Ex. 2025-12-31", "date"),
|
||||||
|
]
|
||||||
|
REVENUS_PERS = [
|
||||||
|
("revenu_emploi", "Salaires et traitements", "T4, case 14 / RL-1, case A"),
|
||||||
|
("pension_qpp", "Retraite RRQ ou RPC", "Prestations de retraite publiques"),
|
||||||
|
("pension_autre", "Autres pensions", "Régime de retraite, rente d'employeur"),
|
||||||
|
("pension_securite_vieillesse", "Sécurité de la vieillesse", "Feuillet T4A(OAS)"),
|
||||||
|
("revenu_interets", "Intérêts et placements", "Intérêts imposables simples, hors dividendes"),
|
||||||
|
("autres_revenus", "Autres revenus", "Attention : vérification particulière requise"),
|
||||||
|
]
|
||||||
|
REVENUS_ENT = [
|
||||||
|
("recettes_entreprise", "Ventes et honoraires", "Montants hors TPS/TVQ, hors remboursements"),
|
||||||
|
("depenses_entreprise", "Dépenses courantes", "Dépenses admissibles présumées, hors immobilisations"),
|
||||||
|
]
|
||||||
|
DEDUCTIONS_PERS = [
|
||||||
|
("deduction_reer", "Déduction REER", "Montant demandé, après vérification des droits"),
|
||||||
|
("autres_deductions", "Autres déductions", "Non détaillées : calcul à réviser"),
|
||||||
|
]
|
||||||
|
DEDUCTIONS_SOC = [
|
||||||
|
("depenses_non_deductibles", "Dépenses comptables non déductibles", "Réintégration provisoire au bénéfice"),
|
||||||
|
("pertes_anterieures", "Pertes fiscales reportées utilisées", "Sous réserve des règles de report et de limitation"),
|
||||||
|
]
|
||||||
|
OPTIONS_PERS = [
|
||||||
|
("autres_sources", "J'ai d'autres sources ou particularités fiscales", "Dividendes, gains en capital, revenus locatifs, revenus étrangers, etc."),
|
||||||
|
]
|
||||||
|
OPTIONS_SOC = [
|
||||||
|
("spcc", "Société privée sous contrôle canadien (SPCC)", "Déclaration du statut, non validation"),
|
||||||
|
("dpe_federale", "La DPE fédérale pourrait s'appliquer", "Plafond et règles de société associée à vérifier"),
|
||||||
|
("dpe_quebec", "La DPE québécoise pourrait s'appliquer", "Heures rémunérées/secteur et autres critères à vérifier"),
|
||||||
|
("depreciation", "J'ai acquis des immobilisations", "Ordinateurs, véhicules, bâtiments, équipements"),
|
||||||
|
("actionnaires_associes", "Société associée ou opérations entre proches", "Vérifications supplémentaires indispensables"),
|
||||||
|
]
|
||||||
|
IMPORT_CATEGORIES = {
|
||||||
|
"revenu_emploi": "Salaires", "pension_qpp": "RRQ / RPC", "pension_autre": "Pension", "pension_securite_vieillesse": "PSV", "revenu_interets": "Intérêts", "autres_revenus": "Autres revenus", "recettes_entreprise": "Ventes", "depenses_entreprise": "Dépenses", "deduction_reer": "REER", "depenses_non_deductibles": "Non-déductibles", "pertes_anterieures": "Pertes reportées",
|
||||||
|
}
|
||||||
|
|
||||||
|
class LocalOnlyMiddleware(BaseHTTPMiddleware):
|
||||||
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
host = request.headers.get("host", "").lower()
|
||||||
|
try:
|
||||||
|
parsed_host = urlsplit("http://" + host).hostname
|
||||||
|
except ValueError:
|
||||||
|
parsed_host = None
|
||||||
|
if parsed_host not in {"localhost", "127.0.0.1", "::1", "testserver"}:
|
||||||
|
return Response("Hôte non autorisé : Fiscalibre fonctionne uniquement en local.", status_code=403)
|
||||||
|
if request.method in {"POST", "PUT", "DELETE", "PATCH"}:
|
||||||
|
origin = request.headers.get("origin")
|
||||||
|
if origin:
|
||||||
|
try:
|
||||||
|
parsed_origin = urlsplit(origin)
|
||||||
|
autorise = parsed_origin.scheme == "http" and parsed_origin.hostname in {"localhost", "127.0.0.1", "::1", "testserver"}
|
||||||
|
except ValueError:
|
||||||
|
autorise = False
|
||||||
|
if not autorise:
|
||||||
|
return Response("Origine refusée", status_code=403)
|
||||||
|
response = await call_next(request)
|
||||||
|
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||||
|
response.headers["Referrer-Policy"] = "no-referrer"
|
||||||
|
response.headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; object-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'"
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
return response
|
||||||
|
|
||||||
|
app.add_middleware(LocalOnlyMiddleware)
|
||||||
|
|
||||||
|
|
||||||
|
def dossier_ou_404(reference: str) -> dict[str, Any]:
|
||||||
|
dossier = storage.obtenir(reference)
|
||||||
|
if not dossier:
|
||||||
|
raise HTTPException(404, "Dossier introuvable")
|
||||||
|
return dossier
|
||||||
|
|
||||||
|
|
||||||
|
def contexte(request: Request, **kw: Any) -> dict[str, Any]:
|
||||||
|
return {"request": request, "version": __version__, "sources": SOURCES, **kw}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/", response_class=HTMLResponse)
|
||||||
|
async def accueil(request: Request):
|
||||||
|
return templates.TemplateResponse(request, "index.html", contexte(request, dossiers=storage.dossiers_recents()))
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/dossier/nouveau")
|
||||||
|
async def creer(request: Request):
|
||||||
|
formulaire = await request.form()
|
||||||
|
profil = str(formulaire.get("profil", ""))
|
||||||
|
if profil not in {"particulier", "autonome", "societe"}:
|
||||||
|
raise HTTPException(400, "Profil invalide")
|
||||||
|
reference = storage.nouveau(profil)
|
||||||
|
return RedirectResponse(f"/dossier/{reference}?etape=identite", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/dossier/{reference}", response_class=HTMLResponse)
|
||||||
|
async def dossier(request: Request, reference: str, etape: str = "identite", erreur: str = ""):
|
||||||
|
objet = dossier_ou_404(reference)
|
||||||
|
etapes = ("identite", "revenus", "deductions", "verification")
|
||||||
|
if etape not in etapes:
|
||||||
|
etape = "identite"
|
||||||
|
resultat = None
|
||||||
|
try:
|
||||||
|
resultat = calculer(objet)
|
||||||
|
except ValueError as exc:
|
||||||
|
erreur = erreur or str(exc)
|
||||||
|
return templates.TemplateResponse(request, "dossier.html", contexte(
|
||||||
|
request, dossier=objet, etape=etape, erreur=erreur,
|
||||||
|
etapes=etapes, identite_champs=IDENTITE_SOC if objet["profil"] == "societe" else IDENTITE_PART,
|
||||||
|
revenus_pers=REVENUS_PERS, revenus_ent=REVENUS_ENT,
|
||||||
|
deductions_pers=DEDUCTIONS_PERS, deductions_soc=DEDUCTIONS_SOC,
|
||||||
|
options=OPTIONS_SOC if objet["profil"] == "societe" else OPTIONS_PERS,
|
||||||
|
resultat=resultat, categories=IMPORT_CATEGORIES,
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/dossier/{reference}/enregistrer")
|
||||||
|
async def sauver(request: Request, reference: str, etape: str = "identite"):
|
||||||
|
objet = dossier_ou_404(reference)
|
||||||
|
formulaire = await request.form()
|
||||||
|
data = objet["data"]
|
||||||
|
if etape not in ("identite", "revenus", "deductions"):
|
||||||
|
raise HTTPException(400, "Étape invalide")
|
||||||
|
if etape == "identite":
|
||||||
|
autorises = IDENTITE_SOC if objet["profil"] == "societe" else IDENTITE_PART
|
||||||
|
for key, *_ in autorises:
|
||||||
|
valeur = str(formulaire.get("i_" + key, "")).strip()[:200]
|
||||||
|
data["identite"][key] = valeur
|
||||||
|
if objet["profil"] == "societe":
|
||||||
|
for key in ("debut_exercice", "fin_exercice"):
|
||||||
|
if not data["identite"].get(key):
|
||||||
|
return RedirectResponse(f"/dossier/{reference}?etape=identite&erreur=Dates+d%27exercice+requises", 303)
|
||||||
|
else:
|
||||||
|
champs = ((REVENUS_ENT if objet["profil"] == "societe" else REVENUS_PERS + (REVENUS_ENT if objet["profil"] == "autonome" else []))
|
||||||
|
if etape == "revenus" else (DEDUCTIONS_SOC if objet["profil"] == "societe" else DEDUCTIONS_PERS))
|
||||||
|
valeurs = {}
|
||||||
|
try:
|
||||||
|
for key, *_ in champs:
|
||||||
|
valeurs[key] = monnaie(argent(formulaire.get("m_" + key, "")))
|
||||||
|
except ValueError as exc:
|
||||||
|
from urllib.parse import quote
|
||||||
|
return RedirectResponse(f"/dossier/{reference}?etape={etape}&erreur={quote(str(exc))}", 303)
|
||||||
|
data["montants"].update(valeurs)
|
||||||
|
if etape == "deductions":
|
||||||
|
options = OPTIONS_SOC if objet["profil"] == "societe" else OPTIONS_PERS
|
||||||
|
for key, *_ in options:
|
||||||
|
data["options"][key] = formulaire.get("o_" + key) == "on"
|
||||||
|
storage.enregistrer(objet)
|
||||||
|
suite = {"identite": "revenus", "revenus": "deductions", "deductions": "verification"}[etape]
|
||||||
|
return RedirectResponse(f"/dossier/{reference}?etape={suite}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/dossier/{reference}/importer")
|
||||||
|
async def importer(reference: str, fichier: UploadFile = File(...)):
|
||||||
|
objet = dossier_ou_404(reference)
|
||||||
|
if not fichier.filename or not fichier.filename.lower().endswith(".csv"):
|
||||||
|
raise HTTPException(400, "Fichier .csv obligatoire")
|
||||||
|
contenu = await fichier.read(1_000_001)
|
||||||
|
if len(contenu) > 1_000_000:
|
||||||
|
raise HTTPException(413, "CSV limité à 1 Mo")
|
||||||
|
try:
|
||||||
|
txt = contenu.decode("utf-8-sig")
|
||||||
|
tableau = csv.DictReader(io.StringIO(txt), delimiter=";")
|
||||||
|
if not {"categorie", "montant", "description"}.issubset(set(tableau.fieldnames or [])):
|
||||||
|
raise ValueError("Colonnes attendues : categorie;montant;description")
|
||||||
|
sommes: dict[str, Any] = {}
|
||||||
|
lignes = 0
|
||||||
|
for ligne in tableau:
|
||||||
|
lignes += 1
|
||||||
|
if lignes > 2000:
|
||||||
|
raise ValueError("CSV limité à 2000 opérations")
|
||||||
|
cat = (ligne.get("categorie") or "").strip()
|
||||||
|
if cat not in IMPORT_CATEGORIES:
|
||||||
|
raise ValueError(f"Catégorie inconnue à la ligne {lignes + 1} : {cat[:40]}")
|
||||||
|
somme = argent(ligne.get("montant"))
|
||||||
|
sommes[cat] = sommes.get(cat, argent("0")) + somme
|
||||||
|
if not lignes:
|
||||||
|
raise ValueError("Le CSV est vide")
|
||||||
|
except (UnicodeDecodeError, csv.Error, ValueError) as exc:
|
||||||
|
raise HTTPException(422, str(exc)) from exc
|
||||||
|
# Import contrôlé : addition au cumul existant, jamais écrasement silencieux.
|
||||||
|
for categorie, somme in sommes.items():
|
||||||
|
precedant = argent(objet["data"]["montants"].get(categorie, "0"))
|
||||||
|
objet["data"]["montants"][categorie] = monnaie(precedant + somme)
|
||||||
|
objet["data"]["importations"].append({"fichier": Path(fichier.filename).name[:100], "lignes": lignes, "sommes": {k: monnaie(v) for k, v in sommes.items()}})
|
||||||
|
storage.enregistrer(objet)
|
||||||
|
return RedirectResponse(f"/dossier/{reference}?etape=revenus", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/dossier/{reference}/export/pdf")
|
||||||
|
async def pdf(reference: str):
|
||||||
|
objet = dossier_ou_404(reference)
|
||||||
|
try:
|
||||||
|
resultat = calculer(objet)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(422, str(exc)) from exc
|
||||||
|
content = exporter_pdf(objet, resultat)
|
||||||
|
return Response(content, media_type="application/pdf", headers={"Content-Disposition": f'attachment; filename="fiscalibre-brouillon-{reference}.pdf"'})
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/dossier/{reference}/export/json")
|
||||||
|
async def export_json(reference: str):
|
||||||
|
objet = dossier_ou_404(reference)
|
||||||
|
try:
|
||||||
|
resultat = calculer(objet)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(422, str(exc)) from exc
|
||||||
|
serialisable = json.dumps({"avertissement": "PROTOTYPE, NON TRANSMISSIBLE", "dossier": objet, "calcul": resultat, "sources": {k: SOURCES[k] for k in resultat["sources"]}}, ensure_ascii=False, default=str, indent=2)
|
||||||
|
return Response(serialisable, media_type="application/json; charset=utf-8", headers={"Content-Disposition": f'attachment; filename="fiscalibre-brouillon-{reference}.json"'})
|
||||||
33
pyproject.toml
Normal file
33
pyproject.toml
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=68"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "fiscalibre"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Prototype local libre d'assistance fiscale Canada-Québec"
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
license = { text = "AGPL-3.0-or-later" }
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115,<1",
|
||||||
|
"uvicorn>=0.30,<1",
|
||||||
|
"jinja2>=3.1,<4",
|
||||||
|
"python-multipart>=0.0.9,<1",
|
||||||
|
"reportlab>=4.0,<5",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = ["pytest>=8,<10", "httpx>=0.27,<1"]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
fiscalibre = "fiscalibre.__main__:main"
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
include = ["fiscalibre*"]
|
||||||
|
|
||||||
|
[tool.setuptools.package-data]
|
||||||
|
fiscalibre = ["templates/*.html", "static/*.css"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
69
tests/test_app.py
Normal file
69
tests/test_app.py
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from fiscalibre.web import app
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setenv("FISCALIBRE_DATA_DIR", str(tmp_path / "data"))
|
||||||
|
return TestClient(app, base_url="http://localhost:8765")
|
||||||
|
|
||||||
|
|
||||||
|
def creer(client, profil):
|
||||||
|
r = client.post("/dossier/nouveau", data={"profil": profil}, follow_redirects=False)
|
||||||
|
assert r.status_code == 303
|
||||||
|
return r.headers["location"].split("/")[2].split("?")[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_accueil_et_3_profils(client):
|
||||||
|
assert client.get("/").status_code == 200
|
||||||
|
for p in ["particulier", "autonome", "societe"]:
|
||||||
|
ref = creer(client, p)
|
||||||
|
page = client.get(f"/dossier/{ref}")
|
||||||
|
assert page.status_code == 200
|
||||||
|
assert b"2025" in page.content
|
||||||
|
|
||||||
|
|
||||||
|
def test_saisie_pdf_et_json(client):
|
||||||
|
ref = creer(client, "particulier")
|
||||||
|
r = client.post(f"/dossier/{ref}/enregistrer?etape=identite", data={"i_prenom": "Zoé", "i_nom": "Dumas"}, follow_redirects=False)
|
||||||
|
assert r.status_code == 303
|
||||||
|
r = client.post(f"/dossier/{ref}/enregistrer?etape=revenus", data={"m_revenu_emploi": "60 000,25"}, follow_redirects=False)
|
||||||
|
assert r.status_code == 303
|
||||||
|
rapport = client.get(f"/dossier/{ref}/export/pdf")
|
||||||
|
assert rapport.status_code == 200 and rapport.content.startswith(b"%PDF")
|
||||||
|
assert len(rapport.content) > 4000
|
||||||
|
donnees = client.get(f"/dossier/{ref}/export/json")
|
||||||
|
document = json.loads(donnees.content)
|
||||||
|
assert document["dossier"]["data"]["identite"]["prenom"] == "Zoé"
|
||||||
|
assert document["calcul"]["pret_a_transmettre"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_validation_rejet_montant_negatif(client):
|
||||||
|
ref = creer(client, "societe")
|
||||||
|
r = client.post(f"/dossier/{ref}/enregistrer?etape=revenus", data={"m_recettes_entreprise": "-3"}, follow_redirects=False)
|
||||||
|
assert r.status_code == 303
|
||||||
|
assert "erreur=" in r.headers["location"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_csv(client):
|
||||||
|
ref = creer(client, "autonome")
|
||||||
|
donnees = "categorie;montant;description\nrecettes_entreprise;100,50;Client\ndepenses_entreprise;20,50;Outils\n"
|
||||||
|
r = client.post(f"/dossier/{ref}/importer", files={"fichier": ("ventes.csv", donnees.encode(), "text/csv")}, follow_redirects=False)
|
||||||
|
assert r.status_code == 303
|
||||||
|
bilan = json.loads(client.get(f"/dossier/{ref}/export/json").content)
|
||||||
|
assert bilan["calcul"]["lignes"]["ARC / T1 (préparation)"]["13500"] == "80.00"
|
||||||
|
|
||||||
|
|
||||||
|
def test_csv_rejet_categorie_inconnue(client):
|
||||||
|
ref = creer(client, "particulier")
|
||||||
|
donnees = b"categorie;montant;description\nweb_virus;100;test\n"
|
||||||
|
r = client.post(f"/dossier/{ref}/importer", files={"fichier": ("x.csv", donnees, "text/csv")})
|
||||||
|
assert r.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_host_non_local_interdit(client):
|
||||||
|
r = client.get("/", headers={"host": "fiscalibre.example.com"})
|
||||||
|
assert r.status_code == 403
|
||||||
75
tests/test_tax.py
Normal file
75
tests/test_tax.py
Normal file
|
|
@ -0,0 +1,75 @@
|
||||||
|
from decimal import Decimal
|
||||||
|
from copy import deepcopy
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from fiscalibre.tax import argent, calculer, progressif, FED, QC
|
||||||
|
|
||||||
|
|
||||||
|
def exemple(profil="particulier", montants=None, options=None):
|
||||||
|
return {"id": "essai", "profil": profil, "data": {
|
||||||
|
"annee": 2025,
|
||||||
|
"identite": {"debut_exercice": "2025-01-01", "fin_exercice": "2025-12-31"},
|
||||||
|
"montants": montants or {},
|
||||||
|
"options": options or {},
|
||||||
|
}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_argent_virgule_et_rejet():
|
||||||
|
assert argent("1 234,56") == Decimal("1234.56")
|
||||||
|
assert argent("0") == Decimal("0.00")
|
||||||
|
for invalide in ["NaN", "-10", "1,000.25", "inf", "hello", "9999999999999"]:
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
argent(invalide)
|
||||||
|
|
||||||
|
|
||||||
|
def test_baremes_officiels_2025():
|
||||||
|
assert progressif(Decimal("57375"), FED) == Decimal("8319.38")
|
||||||
|
assert progressif(Decimal("114750"), FED) == Decimal("20081.25")
|
||||||
|
assert progressif(Decimal("53255"), QC) == Decimal("7455.70")
|
||||||
|
assert progressif(Decimal("106495"), QC) == Decimal("17571.30")
|
||||||
|
assert progressif(Decimal("0"), FED) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_particulier_deux_administrations():
|
||||||
|
r = calculer(exemple("particulier", {"revenu_emploi": "60000", "deduction_reer": "5000"}))
|
||||||
|
assert r["resume"]["Revenu imposable estimatif"] == Decimal("55000.00")
|
||||||
|
assert "ARC / T1 (préparation)" in r["lignes"]
|
||||||
|
assert "Québec / TP-1 (préparation)" in r["lignes"]
|
||||||
|
assert r["pret_a_transmettre"] is False
|
||||||
|
assert r["resume"]["Impôt fédéral indicatif après abattement"] > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_autonome_cumule_activites():
|
||||||
|
r = calculer(exemple("autonome", {"revenu_emploi": "15000", "recettes_entreprise": "40000", "depenses_entreprise": "12000"}))
|
||||||
|
assert r["lignes"]["ARC / T1 (préparation)"]["13500"] == Decimal("28000.00")
|
||||||
|
assert r["resume"]["Revenu brut / total provisoire"] == Decimal("43000.00")
|
||||||
|
assert "TP-80" in r["titre"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_societe_pas_dpe():
|
||||||
|
r = calculer(exemple("societe", {"recettes_entreprise": "100000", "depenses_entreprise": "50000"}))
|
||||||
|
assert r["resume"]["Impôt fédéral indicatif"] == Decimal("7500.00")
|
||||||
|
assert r["resume"]["Impôt Québec indicatif"] == Decimal("5750.00")
|
||||||
|
assert r["pret_a_transmettre"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_societe_dpe_declaree_mais_pas_validee():
|
||||||
|
r = calculer(exemple("societe", {"recettes_entreprise": "100000", "depenses_entreprise": "20000"}, {"spcc": True, "dpe_federale": True, "dpe_quebec": True}))
|
||||||
|
assert r["resume"]["Impôt fédéral indicatif"] == Decimal("7200.00")
|
||||||
|
assert r["resume"]["Impôt Québec indicatif"] == Decimal("2560.00")
|
||||||
|
assert any("ne constituent PAS une vérification" in a for a in r["alertes"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_limitation_millesime():
|
||||||
|
d = exemple()
|
||||||
|
d["data"]["annee"] = 2026
|
||||||
|
with pytest.raises(ValueError, match="2025"):
|
||||||
|
calculer(d)
|
||||||
|
|
||||||
|
|
||||||
|
def test_exercice_invalide():
|
||||||
|
d = exemple("societe")
|
||||||
|
d["data"]["identite"]["debut_exercice"] = "2025-12-30"
|
||||||
|
d["data"]["identite"]["fin_exercice"] = "2025-01-01"
|
||||||
|
with pytest.raises(ValueError, match="Exercice"):
|
||||||
|
calculer(d)
|
||||||
Loading…
Reference in a new issue