diff --git a/.gitignore b/.gitignore index 94433be1..f541ab85 100644 --- a/.gitignore +++ b/.gitignore @@ -47,6 +47,3 @@ backups/ env/ venv/ db.sqlite3 - -# Ignore migrations during first phase dev -migrations/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e8bd9b44..cada9068 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -2,6 +2,10 @@ stages: - test - quality-assurance +# Also fetch submodules +variables: + GIT_SUBMODULE_STRATEGY: recursive + # Debian Buster py37-django22: stage: test @@ -14,8 +18,7 @@ py37-django22: python3-django-extensions python3-django-filters python3-django-polymorphic python3-djangorestframework python3-django-cas-server python3-psycopg2 python3-pil python3-babel python3-lockfile python3-pip python3-phonenumbers - python3-bs4 python3-setuptools tox - texlive-latex-base texlive-lang-french lmodern texlive-fonts-recommended + python3-bs4 python3-setuptools tox texlive-xetex script: tox -e py37-django22 # Ubuntu 20.04 @@ -32,23 +35,14 @@ py38-django22: python3-django-extensions python3-django-filters python3-django-polymorphic python3-djangorestframework python3-django-cas-server python3-psycopg2 python3-pil python3-babel python3-lockfile python3-pip python3-phonenumbers - python3-bs4 python3-setuptools tox - texlive-latex-base texlive-lang-french lmodern texlive-fonts-recommended + python3-bs4 python3-setuptools tox texlive-xetex script: tox -e py38-django22 linters: stage: quality-assurance image: debian:buster-backports before_script: - - > - apt-get update && - apt-get install --no-install-recommends -t buster-backports -y - python3-django python3-django-crispy-forms - python3-django-extensions python3-django-filters python3-django-polymorphic - python3-djangorestframework python3-django-cas-server python3-psycopg2 python3-pil - python3-babel python3-lockfile python3-pip python3-phonenumbers - python3-bs4 python3-setuptools tox - texlive-latex-extra texlive-lang-french lmodern texlive-fonts-recommended + - apt-get update && apt-get install -y tox script: tox -e linters # Be nice to new contributors, but please use `tox` diff --git a/Dockerfile b/Dockerfile index e2eb7d4a..0dd1ce8b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,8 +12,7 @@ RUN apt-get update && \ python3-babel python3-lockfile python3-pip python3-phonenumbers ipython3 \ python3-bs4 python3-setuptools \ uwsgi uwsgi-plugin-python3 \ - texlive-latex-base texlive-lang-french lmodern texlive-fonts-recommended \ - gettext libjs-bootstrap4 fonts-font-awesome && \ + texlive-xetex gettext libjs-bootstrap4 fonts-font-awesome && \ rm -rf /var/lib/apt/lists/* # Instal PyPI requirements diff --git a/LICENSE b/LICENSE deleted file mode 100644 index f288702d..00000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is 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. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - 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. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - 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 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. Use with the GNU Affero General Public License. - - 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 Affero 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 special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU 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 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 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 General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - 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 GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/README.md b/README.md index 43c5a8a5..f2ada2a8 100644 --- a/README.md +++ b/README.md @@ -23,14 +23,13 @@ Bien que cela permette de créer une instance sur toutes les distributions, $ sudo apt update $ sudo apt install --no-install-recommends -y \ ipython3 python3-setuptools python3-venv python3-dev \ - texlive-latex-base texlive-lang-french lmodern texlive-fonts-recommended \ - gettext libjs-bootstrap4 fonts-font-awesome git + texlive-xetex gettext libjs-bootstrap4 fonts-font-awesome git ``` 2. **Clonage du dépot** là où vous voulez : ```bash - $ git clone git@gitlab.crans.org:bde/nk20.git && cd nk20 + $ git clone git@gitlab.crans.org:bde/nk20.git --recursive && cd nk20 ``` 3. **Création d'un environment de travail Python décorrélé du système.** @@ -98,8 +97,7 @@ Sinon vous pouvez suivre les étapes décrites ci-dessous. python3-babel python3-lockfile python3-pip python3-phonenumbers ipython3 \ python3-bs4 python3-setuptools \ uwsgi uwsgi-plugin-python3 \ - texlive-latex-base texlive-lang-french lmodern texlive-fonts-recommended \ - gettext libjs-bootstrap4 fonts-font-awesome \ + texlive-xetex gettext libjs-bootstrap4 fonts-font-awesome \ nginx python3-venv git acl ``` @@ -109,7 +107,7 @@ Sinon vous pouvez suivre les étapes décrites ci-dessous. $ sudo mkdir -p /var/www/note_kfet && cd /var/www/note_kfet $ sudo chown www-data:www-data . $ sudo chmod g+rwx . - $ sudo -u www-data git clone https://gitlab.crans.org/bde/nk20.git + $ sudo -u www-data git clone https://gitlab.crans.org/bde/nk20.git --recursive ``` 3. **Création d'un environment de travail Python décorrélé du système.** @@ -195,7 +193,6 @@ Sinon vous pouvez suivre les étapes décrites ci-dessous. DJANGO_SECRET_KEY=CHANGE_ME DJANGO_SETTINGS_MODULE="note_kfet.settings NOTE_URL=localhost # URL où accéder à la note - DOMAIN=localhost # note.example.com CONTACT_EMAIL=tresorerie.bde@localhost # Le reste n'est utile qu'en production, pour configurer l'envoi des mails NOTE_MAIL=notekfet@localhost @@ -211,7 +208,6 @@ Sinon vous pouvez suivre les étapes décrites ci-dessous. $ source /env/bin/activate (env)$ ./manage.py check # pas de bêtise qui traine - (env)$ ./manage.py makemigrations (env)$ ./manage.py migrate 7. *Enjoy \o/* @@ -223,7 +219,7 @@ Il est possible de travailler sur une instance Docker. Pour construire l'image Docker `nk20`, ``` -git clone https://gitlab.crans.org/bde/nk20/ && cd nk20 +git clone https://gitlab.crans.org/bde/nk20/ --recursive && cd nk20 docker build . -t nk20 ``` diff --git a/ansible/base.yml b/ansible/base.yml index 56ba83d9..950aafa5 100755 --- a/ansible/base.yml +++ b/ansible/base.yml @@ -1,10 +1,10 @@ #!/usr/bin/env ansible-playbook --- -- hosts: bde-nk20-beta.adh.crans.org +- hosts: all vars_prompt: - name: DB_PASSWORD - prompt: "Password of the database" + prompt: "Password of the database (leave it blank to skip database init)" private: yes vars: mirror: deb.debian.org @@ -12,7 +12,7 @@ - 1-apt-basic - 2-nk20 - 3-pip - - 4-nginx - - 5-certbot + - 4-certbot + - 5-nginx - 6-psql - 7-postinstall diff --git a/ansible/host_vars/bde-nk20-beta.adh.crans.org.yml b/ansible/host_vars/bde-nk20-beta.adh.crans.org.yml new file mode 100644 index 00000000..d4ef70ef --- /dev/null +++ b/ansible/host_vars/bde-nk20-beta.adh.crans.org.yml @@ -0,0 +1,5 @@ +--- +note: + server_name: note-beta.crans.org + git_branch: beta + cron_enabled: false diff --git a/ansible/host_vars/bde-note.adh.crans.org.yml b/ansible/host_vars/bde-note.adh.crans.org.yml new file mode 100644 index 00000000..ba085433 --- /dev/null +++ b/ansible/host_vars/bde-note.adh.crans.org.yml @@ -0,0 +1,5 @@ +--- +note: + server_name: note.crans.org + git_branch: master + cron_enabled: true diff --git a/ansible/host_vars/bde3-virt.adh.crans.org.yml b/ansible/host_vars/bde3-virt.adh.crans.org.yml new file mode 100644 index 00000000..477a4b7a --- /dev/null +++ b/ansible/host_vars/bde3-virt.adh.crans.org.yml @@ -0,0 +1,5 @@ +--- +note: + server_name: note-dev.crans.org + git_branch: beta + cron_enabled: false diff --git a/ansible/hosts b/ansible/hosts index beafcc55..10d86488 100644 --- a/ansible/hosts +++ b/ansible/hosts @@ -1,5 +1,9 @@ -[server] +[dev] +bde3-virt.adh.crans.org bde-nk20-beta.adh.crans.org +[prod] +bde-note.adh.crans.org + [all:vars] ansible_python_interpreter=/usr/bin/python3 diff --git a/ansible/roles/1-apt-basic/tasks/main.yml b/ansible/roles/1-apt-basic/tasks/main.yml index fa51de34..1ca1b3d6 100644 --- a/ansible/roles/1-apt-basic/tasks/main.yml +++ b/ansible/roles/1-apt-basic/tasks/main.yml @@ -38,9 +38,7 @@ - python3-venv # LaTeX (PDF generation) - - texlive-fonts-recommended - - texlive-lang-french - - texlive-latex-base + - texlive-xetex # WSGI server - uwsgi diff --git a/ansible/roles/2-nk20/tasks/main.yml b/ansible/roles/2-nk20/tasks/main.yml index 37d29819..9652359d 100644 --- a/ansible/roles/2-nk20/tasks/main.yml +++ b/ansible/roles/2-nk20/tasks/main.yml @@ -11,7 +11,7 @@ git: repo: https://gitlab.crans.org/bde/nk20.git dest: /var/www/note_kfet - version: beta + version: "{{ note.git_branch }}" force: true - name: Use default env vars (should be updated!) @@ -30,6 +30,7 @@ group: www-data - name: Setup cron jobs + when: "note.cron_enabled" template: src: note.cron.j2 dest: /etc/cron.d/note diff --git a/ansible/roles/2-nk20/templates/note.cron.j2 b/ansible/roles/2-nk20/templates/note.cron.j2 deleted file mode 100644 index 17d65279..00000000 --- a/ansible/roles/2-nk20/templates/note.cron.j2 +++ /dev/null @@ -1,22 +0,0 @@ -# {{ ansible_managed }} -# Les cronjobs dont a besoin la Note Kfet - -# m h dom mon dow user command -# Envoyer les mails en attente - * * * * * root cd /var/www/note_kfet && env/bin/python manage.py send_mail >> /var/www/note_kfet/cron_mail.log - * * * * * root cd /var/www/note_kfet && env/bin/python manage.py retry_deferred >> /var/www/note_kfet/cron_mail_deferred.log - 00 0 * * * root cd /var/www/note_kfet && env/bin/python manage.py purge_mail_log 7 >> /var/www/note_kfet/cron_mail_purge.log -# Faire une sauvegarde de la base de données - 00 2 * * * root cd /var/www/note_kfet && apps/scripts/shell/backup_db -# Vérifier la cohérence de la base et mailer en cas de problème - 00 4 * * * root cd /var/www/note_kfet && env/bin/python manage.py check_consistency --sum-all --check-all --mail -# Mettre à jour le wiki (modification sans (dé)validation, activités passées) -#30 5 * * * root cd /var/www/note_kfet && env/bin/python manage.py refresh_activities --raw --comment refresh -# Spammer les gens en négatif - 00 5 * * 2 root cd /var/www/note_kfet && env/bin/python manage.py send_mail_to_negative_balances --spam -# Envoyer le rapport mensuel aux trésoriers et respos info - 00 8 6 * * root cd /var/www/note_kfet && env/bin/python manage.py send_mail_to_negative_balances --report -# Envoyer les rapports aux gens - 55 6 * * * root cd /var/www/note_kfet && env/bin/python manage.py send_reports -# Envoyer les rapports aux gens - 00 9 * * * root cd /var/www/note_kfet && env/bin/python manage.py refresh_highlighted_buttons diff --git a/ansible/roles/2-nk20/templates/note.cron.j2 b/ansible/roles/2-nk20/templates/note.cron.j2 new file mode 120000 index 00000000..7bb39d7d --- /dev/null +++ b/ansible/roles/2-nk20/templates/note.cron.j2 @@ -0,0 +1 @@ +../../../../note.cron \ No newline at end of file diff --git a/ansible/roles/5-certbot/tasks/main.yml b/ansible/roles/4-certbot/tasks/main.yml similarity index 100% rename from ansible/roles/5-certbot/tasks/main.yml rename to ansible/roles/4-certbot/tasks/main.yml diff --git a/ansible/roles/5-certbot/templates/letsencrypt/conf.d/nk20.ini.j2 b/ansible/roles/4-certbot/templates/letsencrypt/conf.d/nk20.ini.j2 similarity index 100% rename from ansible/roles/5-certbot/templates/letsencrypt/conf.d/nk20.ini.j2 rename to ansible/roles/4-certbot/templates/letsencrypt/conf.d/nk20.ini.j2 diff --git a/ansible/roles/4-nginx/tasks/main.yml b/ansible/roles/5-nginx/tasks/main.yml similarity index 100% rename from ansible/roles/4-nginx/tasks/main.yml rename to ansible/roles/5-nginx/tasks/main.yml diff --git a/ansible/roles/4-nginx/templates/nginx_note.conf b/ansible/roles/5-nginx/templates/nginx_note.conf similarity index 71% rename from ansible/roles/4-nginx/templates/nginx_note.conf rename to ansible/roles/5-nginx/templates/nginx_note.conf index b195e739..218d6537 100644 --- a/ansible/roles/4-nginx/templates/nginx_note.conf +++ b/ansible/roles/5-nginx/templates/nginx_note.conf @@ -9,7 +9,7 @@ server { listen [::]:80 default_server; location / { - return 301 https://nk20-beta.crans.org$request_uri; + return 301 https://{{ note.server_name }}$request_uri; } } @@ -19,11 +19,11 @@ server { listen [::]:443 ssl default_server; location / { - return 301 https://nk20-beta.crans.org$request_uri; + return 301 https://{{ note.server_name }}$request_uri; } - ssl_certificate /etc/letsencrypt/live/nk20-beta.crans.org/fullchain.pem; - ssl_certificate_key /etc/letsencrypt/live/nk20-beta.crans.org/privkey.pem; + ssl_certificate /etc/letsencrypt/live/{{ note.server_name }}/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/{{ note.server_name }}/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; } @@ -35,7 +35,7 @@ server { # the port your site will be served on # the domain name it will serve for - server_name nk20-beta.crans.org; # substitute your machine's IP address or FQDN + server_name {{ note.server_name }}; # substitute your machine's IP address or FQDN charset utf-8; # max upload size @@ -56,8 +56,8 @@ server { include /etc/nginx/uwsgi_params; } - ssl_certificate /etc/letsencrypt/live/nk20-beta.crans.org/fullchain.pem; - ssl_certificate_key /etc/letsencrypt/live/nk20-beta.crans.org/privkey.pem; + ssl_certificate /etc/letsencrypt/live/{{ note.server_name }}/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/{{ note.server_name }}/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; } diff --git a/ansible/roles/6-psql/tasks/main.yml b/ansible/roles/6-psql/tasks/main.yml index 90ed8096..c4349f5e 100644 --- a/ansible/roles/6-psql/tasks/main.yml +++ b/ansible/roles/6-psql/tasks/main.yml @@ -10,17 +10,15 @@ retries: 3 until: pkg_result is succeeded -- name: Install Psycopg2 - pip: - name: psycopg2-binary - - name: Create role note + when: "DB_PASSWORD|bool" # If the password is not defined, skip the installation postgresql_user: name: note password: "{{ DB_PASSWORD }}" become_user: postgres - name: Create NK20 database + when: "DB_PASSWORD|bool" postgresql_db: name: note_db owner: note diff --git a/ansible/roles/7-postinstall/tasks/main.yml b/ansible/roles/7-postinstall/tasks/main.yml index 34a9011b..6f3017a5 100644 --- a/ansible/roles/7-postinstall/tasks/main.yml +++ b/ansible/roles/7-postinstall/tasks/main.yml @@ -1,10 +1,4 @@ --- -- name: Make Django migrations - command: /var/www/note_kfet/env/bin/python manage.py makemigrations - args: - chdir: /var/www/note_kfet - become_user: www-data - - name: Migrate Django database command: /var/www/note_kfet/env/bin/python manage.py migrate args: @@ -22,3 +16,9 @@ args: chdir: /var/www/note_kfet become_user: postgres + +- name: Collect static files + command: /var/www/note_kfet/env/bin/python manage.py collectstatic --noinput + args: + chdir: /var/www/note_kfet + become_user: www-data diff --git a/apps/activity/migrations/0001_initial.py b/apps/activity/migrations/0001_initial.py new file mode 100644 index 00000000..ba2d68da --- /dev/null +++ b/apps/activity/migrations/0001_initial.py @@ -0,0 +1,69 @@ +# Generated by Django 2.2.16 on 2020-09-04 21:41 + +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Activity', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, verbose_name='name')), + ('description', models.TextField(verbose_name='description')), + ('location', models.CharField(blank=True, default='', help_text='Place where the activity is organized, eg. Kfet.', max_length=255, verbose_name='location')), + ('date_start', models.DateTimeField(verbose_name='start date')), + ('date_end', models.DateTimeField(verbose_name='end date')), + ('valid', models.BooleanField(default=False, verbose_name='valid')), + ('open', models.BooleanField(default=False, verbose_name='open')), + ], + options={ + 'verbose_name': 'activity', + 'verbose_name_plural': 'activities', + }, + ), + migrations.CreateModel( + name='ActivityType', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, verbose_name='name')), + ('manage_entries', models.BooleanField(default=False, help_text='Enable the support of entries for this activity.', verbose_name='manage entries')), + ('can_invite', models.BooleanField(default=False, verbose_name='can invite')), + ('guest_entry_fee', models.PositiveIntegerField(default=0, verbose_name='guest entry fee')), + ], + options={ + 'verbose_name': 'activity type', + 'verbose_name_plural': 'activity types', + }, + ), + migrations.CreateModel( + name='Entry', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='entry time')), + ], + options={ + 'verbose_name': 'entry', + 'verbose_name_plural': 'entries', + }, + ), + migrations.CreateModel( + name='Guest', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('last_name', models.CharField(max_length=255, verbose_name='last name')), + ('first_name', models.CharField(max_length=255, verbose_name='first name')), + ], + options={ + 'verbose_name': 'guest', + 'verbose_name_plural': 'guests', + }, + ), + ] diff --git a/apps/activity/migrations/0002_auto_20200904_2341.py b/apps/activity/migrations/0002_auto_20200904_2341.py new file mode 100644 index 00000000..4afa74dd --- /dev/null +++ b/apps/activity/migrations/0002_auto_20200904_2341.py @@ -0,0 +1,89 @@ +# Generated by Django 2.2.16 on 2020-09-04 21:41 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('activity', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('member', '0001_initial'), + ('note', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='GuestTransaction', + fields=[ + ('transaction_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='note.Transaction')), + ('entry', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, to='activity.Entry')), + ], + options={ + 'abstract': False, + 'base_manager_name': 'objects', + }, + bases=('note.transaction',), + ), + migrations.AddField( + model_name='guest', + name='activity', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='activity.Activity'), + ), + migrations.AddField( + model_name='guest', + name='inviter', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='guests', to='note.NoteUser', verbose_name='inviter'), + ), + migrations.AddField( + model_name='entry', + name='activity', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='entries', to='activity.Activity', verbose_name='activity'), + ), + migrations.AddField( + model_name='entry', + name='guest', + field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.PROTECT, to='activity.Guest'), + ), + migrations.AddField( + model_name='entry', + name='note', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='note.NoteUser', verbose_name='note'), + ), + migrations.AddField( + model_name='activity', + name='activity_type', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='activity.ActivityType', verbose_name='type'), + ), + migrations.AddField( + model_name='activity', + name='attendees_club', + field=models.ForeignKey(help_text='Club that is authorized to join the activity. Mostly the Kfet club.', on_delete=django.db.models.deletion.PROTECT, related_name='+', to='member.Club', verbose_name='attendees club'), + ), + migrations.AddField( + model_name='activity', + name='creater', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL, verbose_name='user'), + ), + migrations.AddField( + model_name='activity', + name='organizer', + field=models.ForeignKey(help_text='Club that organizes the activity. The entry fees will go to this club.', on_delete=django.db.models.deletion.PROTECT, related_name='+', to='member.Club', verbose_name='organizer'), + ), + migrations.AlterUniqueTogether( + name='guest', + unique_together={('activity', 'last_name', 'first_name')}, + ), + migrations.AlterUniqueTogether( + name='entry', + unique_together={('activity', 'note', 'guest')}, + ), + migrations.AlterUniqueTogether( + name='activity', + unique_together={('name', 'date_start', 'date_end')}, + ), + ] diff --git a/apps/activity/models.py b/apps/activity/models.py index 131cd725..fe2cfb20 100644 --- a/apps/activity/models.py +++ b/apps/activity/models.py @@ -1,6 +1,7 @@ # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay # SPDX-License-Identifier: GPL-3.0-or-later +import os from datetime import timedelta from threading import Thread @@ -130,12 +131,16 @@ class Activity(models.Model): raise ValidationError(_("The end date must be after the start date.")) ret = super().save(*args, **kwargs) - if settings.DEBUG and self.pk and "scripts" in settings.INSTALLED_APPS: + if not settings.DEBUG and self.pk and "scripts" in settings.INSTALLED_APPS: def refresh_activities(): from scripts.management.commands.refresh_activities import Command as RefreshActivitiesCommand - RefreshActivitiesCommand.refresh_human_readable_wiki_page("Modification de l'activité " + self.name) - RefreshActivitiesCommand.refresh_raw_wiki_page("Modification de l'activité " + self.name) - Thread(daemon=True, target=refresh_activities).start() + # Consider that we can update the wiki iff the WIKI_PASSWORD env var is not empty + RefreshActivitiesCommand.refresh_human_readable_wiki_page("Modification de l'activité " + self.name, + False, os.getenv("WIKI_PASSWORD")) + RefreshActivitiesCommand.refresh_raw_wiki_page("Modification de l'activité " + self.name, + False, os.getenv("WIKI_PASSWORD")) + Thread(daemon=True, target=refresh_activities).start()\ + if settings.DATABASES["default"]["ENGINE"] == 'django.db.backends.postgresql' else refresh_activities() return ret def __str__(self): @@ -183,6 +188,12 @@ class Entry(models.Model): verbose_name = _("entry") verbose_name_plural = _("entries") + def __str__(self): + return _("Entry for {guest}, invited by {note} to the activity {activity}").format( + guest=str(self.guest), note=str(self.note), activity=str(self.activity)) if self.guest \ + else _("Entry for {note} to the activity {activity}").format( + guest=str(self.guest), note=str(self.note), activity=str(self.activity)) + def save(self, *args, **kwargs): qs = Entry.objects.filter(~Q(pk=self.pk), activity=self.activity, note=self.note, guest=self.guest) diff --git a/apps/activity/templates/activity/activity_entry.html b/apps/activity/templates/activity/activity_entry.html index d59a4c48..d778490f 100644 --- a/apps/activity/templates/activity/activity_entry.html +++ b/apps/activity/templates/activity/activity_entry.html @@ -9,7 +9,7 @@ SPDX-License-Identifier: GPL-3.0-or-later

{{ title }}

-
+
{% trans "Transfer" %} diff --git a/apps/activity/tests/test_activities.py b/apps/activity/tests/test_activities.py new file mode 100644 index 00000000..99eb2ffb --- /dev/null +++ b/apps/activity/tests/test_activities.py @@ -0,0 +1,175 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from datetime import timedelta + +from django.contrib.auth.models import User +from django.test import TestCase +from django.urls import reverse +from django.utils import timezone +from activity.models import Activity, ActivityType, Guest, Entry +from member.models import Club + + +class TestActivities(TestCase): + """ + Test activities + """ + fixtures = ('initial',) + + def setUp(self): + self.user = User.objects.create_superuser( + username="admintoto", + password="tototototo", + email="toto@example.com" + ) + self.client.force_login(self.user) + + sess = self.client.session + sess["permission_mask"] = 42 + sess.save() + + self.activity = Activity.objects.create( + name="Activity", + description="This is a test activity\non two very very long lines\nbecause this is very important.", + location="Earth", + activity_type=ActivityType.objects.get(name="Pot"), + creater=self.user, + organizer=Club.objects.get(name="Kfet"), + attendees_club=Club.objects.get(name="Kfet"), + date_start=timezone.now(), + date_end=timezone.now() + timedelta(days=2), + valid=True, + ) + + self.guest = Guest.objects.create( + activity=self.activity, + inviter=self.user.note, + last_name="GUEST", + first_name="Guest", + ) + + def test_activity_list(self): + """ + Display the list of all activities + """ + response = self.client.get(reverse("activity:activity_list")) + self.assertEqual(response.status_code, 200) + + def test_activity_create(self): + """ + Create a new activity + """ + response = self.client.get(reverse("activity:activity_create")) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("activity:activity_create"), data=dict( + name="Activity created", + description="This activity was successfully created.", + location="Earth", + activity_type=ActivityType.objects.get(name="Soirée de club").id, + creater=self.user.id, + organizer=Club.objects.get(name="Kfet").id, + attendees_club=Club.objects.get(name="Kfet").id, + date_start="{:%Y-%m-%d %H:%M}".format(timezone.now()), + date_end="{:%Y-%m-%d %H:%M}".format(timezone.now() + timedelta(days=2)), + valid=True, + )) + self.assertTrue(Activity.objects.filter(name="Activity created").exists()) + activity = Activity.objects.get(name="Activity created") + self.assertRedirects(response, reverse("activity:activity_detail", args=(activity.pk,)), 302, 200) + + def test_activity_detail(self): + """ + Display the detail of an activity + """ + response = self.client.get(reverse("activity:activity_detail", args=(self.activity.pk,))) + self.assertEqual(response.status_code, 200) + + def test_activity_update(self): + """ + Update an activity + """ + response = self.client.get(reverse("activity:activity_update", args=(self.activity.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("activity:activity_update", args=(self.activity.pk,)), data=dict( + name=str(self.activity) + " updated", + description="This activity was successfully updated.", + location="Earth", + activity_type=ActivityType.objects.get(name="Autre").id, + creater=self.user.id, + organizer=Club.objects.get(name="Kfet").id, + attendees_club=Club.objects.get(name="Kfet").id, + date_start="{:%Y-%m-%d %H:%M}".format(timezone.now()), + date_end="{:%Y-%m-%d %H:%M}".format(timezone.now() + timedelta(days=2)), + valid=True, + )) + self.assertTrue(Activity.objects.filter(name="Activity updated").exists()) + self.assertRedirects(response, reverse("activity:activity_detail", args=(self.activity.pk,)), 302, 200) + + def test_activity_entry(self): + """ + Create some entries + """ + self.activity.open = True + self.activity.save() + + response = self.client.get(reverse("activity:activity_entry", args=(self.activity.pk,))) + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("activity:activity_entry", args=(self.activity.pk,)) + "?search=guest") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("activity:activity_entry", args=(self.activity.pk,)) + "?search=admin") + self.assertEqual(response.status_code, 200) + + # User entry + response = self.client.post("/api/activity/entry/", data=dict( + activity=self.activity.id, + note=self.user.note.id, + guest="", + )) + self.assertEqual(response.status_code, 201) # 201 = Created + self.assertTrue(Entry.objects.filter(note=self.user.note, guest=None, activity=self.activity).exists()) + + # Guest entry + response = self.client.post("/api/activity/entry/", data=dict( + activity=self.activity.id, + note=self.user.note.id, + guest=self.guest.id, + )) + self.assertEqual(response.status_code, 201) # 201 = Created + self.assertTrue(Entry.objects.filter(note=self.user.note, guest=self.guest.id, activity=self.activity).exists()) + + def test_activity_invite(self): + """ + Try to invite people to an activity + """ + response = self.client.get(reverse("activity:activity_invite", args=(self.activity.pk,))) + self.assertEqual(response.status_code, 200) + + # The activity is started, can't invite + response = self.client.post(reverse("activity:activity_invite", args=(self.activity.pk,)), data=dict( + activity=self.activity.id, + inviter=self.user.note.id, + last_name="GUEST2", + first_name="Guest", + )) + self.assertEqual(response.status_code, 200) + + self.activity.date_start += timedelta(days=1) + self.activity.save() + + response = self.client.post(reverse("activity:activity_invite", args=(self.activity.pk,)), data=dict( + activity=self.activity.id, + inviter=self.user.note.id, + last_name="GUEST2", + first_name="Guest", + )) + self.assertRedirects(response, reverse("activity:activity_detail", args=(self.activity.pk,)), 302, 200) + + def test_activity_ics(self): + """ + Render the ICS calendar + """ + response = self.client.get(reverse("activity:calendar_ics")) + self.assertEqual(response.status_code, 200) diff --git a/apps/activity/urls.py b/apps/activity/urls.py index f074e8f7..155229d4 100644 --- a/apps/activity/urls.py +++ b/apps/activity/urls.py @@ -14,4 +14,5 @@ urlpatterns = [ path('/entry/', views.ActivityEntryView.as_view(), name='activity_entry'), path('/update/', views.ActivityUpdateView.as_view(), name='activity_update'), path('new/', views.ActivityCreateView.as_view(), name='activity_create'), + path('calendar.ics', views.CalendarView.as_view(), name='calendar_ics'), ] diff --git a/apps/activity/views.py b/apps/activity/views.py index fd218db5..7de31b0c 100644 --- a/apps/activity/views.py +++ b/apps/activity/views.py @@ -1,14 +1,18 @@ # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay # SPDX-License-Identifier: GPL-3.0-or-later +from hashlib import md5 + from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.contenttypes.models import ContentType from django.core.exceptions import PermissionDenied from django.db.models import F, Q +from django.http import HttpResponse from django.urls import reverse_lazy from django.utils import timezone from django.utils.translation import gettext_lazy as _ +from django.views import View from django.views.generic import DetailView, TemplateView, UpdateView from django_tables2.views import SingleTableView from note.models import Alias, NoteSpecial, NoteUser @@ -190,10 +194,10 @@ class ActivityEntryView(LoginRequiredMixin, TemplateView): if pattern[0] != "^": pattern = "^" + pattern guest_qs = guest_qs.filter( - Q(first_name__regex=pattern) - | Q(last_name__regex=pattern) - | Q(inviter__alias__name__regex=pattern) - | Q(inviter__alias__normalized_name__regex=Alias.normalize(pattern)) + Q(first_name__iregex=pattern) + | Q(last_name__iregex=pattern) + | Q(inviter__alias__name__iregex=pattern) + | Q(inviter__alias__normalized_name__iregex=Alias.normalize(pattern)) ) else: guest_qs = guest_qs.none() @@ -226,21 +230,19 @@ class ActivityEntryView(LoginRequiredMixin, TemplateView): if "search" in self.request.GET and self.request.GET["search"]: pattern = self.request.GET["search"] note_qs = note_qs.filter( - Q(note__noteuser__user__first_name__regex=pattern) - | Q(note__noteuser__user__last_name__regex=pattern) - | Q(name__regex=pattern) - | Q(normalized_name__regex=Alias.normalize(pattern)) + Q(note__noteuser__user__first_name__iregex=pattern) + | Q(note__noteuser__user__last_name__iregex=pattern) + | Q(name__iregex=pattern) + | Q(normalized_name__iregex=Alias.normalize(pattern)) ) else: note_qs = note_qs.none() - if settings.DATABASES[note_qs.db]["ENGINE"] == 'django.db.backends.postgresql': - note_qs = note_qs.distinct('note__pk')[:20] - else: - # SQLite doesn't support distinct fields. For compatibility reason (in dev mode), the note list will only - # have distinct aliases rather than distinct notes with a SQLite DB, but it can fill the result page. - # In production mode, please use PostgreSQL. - note_qs = note_qs.distinct()[:20] + # SQLite doesn't support distinct fields. For compatibility reason (in dev mode), the note list will only + # have distinct aliases rather than distinct notes with a SQLite DB, but it can fill the result page. + # In production mode, please use PostgreSQL. + note_qs = note_qs.distinct('note__pk')[:20]\ + if settings.DATABASES[note_qs.db]["ENGINE"] == 'django.db.backends.postgresql' else note_qs.distinct()[:20] return note_qs def get_context_data(self, **kwargs): @@ -281,3 +283,60 @@ class ActivityEntryView(LoginRequiredMixin, TemplateView): Entry(activity=a, note=self.request.user.note,))] return context + + +class CalendarView(View): + """ + Render an ICS calendar with all valid activities. + """ + + def multilines(self, string, maxlength, offset=0): + newstring = string[:maxlength - offset] + string = string[maxlength - offset:] + while string: + newstring += "\r\n " + newstring += string[:maxlength - 1] + string = string[maxlength - 1:] + return newstring + + def get(self, request, *args, **kwargs): + ics = """BEGIN:VCALENDAR +VERSION: 2.0 +PRODID:Note Kfet 2020 +X-WR-CALNAME:Kfet Calendar +NAME:Kfet Calendar +CALSCALE:GREGORIAN +BEGIN:VTIMEZONE +TZID:Europe/Berlin +X-LIC-LOCATION:Europe/Berlin +BEGIN:DAYLIGHT +TZOFFSETFROM:+0100 +TZOFFSETTO:+0200 +TZNAME:CEST +DTSTART:19700329T020000 +RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU +END:DAYLIGHT +BEGIN:STANDARD +TZOFFSETFROM:+0200 +TZOFFSETTO:+0100 +TZNAME:CET +DTSTART:19701025T030000 +RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU +END:STANDARD +END:VTIMEZONE +""" + for activity in Activity.objects.filter(valid=True).order_by("-date_start").all(): + ics += f"""BEGIN:VEVENT +DTSTAMP:{"{:%Y%m%dT%H%M%S}".format(activity.date_start)}Z +UID:{md5((activity.name + "$" + str(activity.id) + str(activity.date_start)).encode("UTF-8")).hexdigest()} +SUMMARY;CHARSET=UTF-8:{self.multilines(activity.name, 75, 22)} +DTSTART;TZID=Europe/Berlin:{"{:%Y%m%dT%H%M%S}".format(activity.date_start)} +DTEND;TZID=Europe/Berlin:{"{:%Y%m%dT%H%M%S}".format(activity.date_end)} +LOCATION:{self.multilines(activity.location, 75, 9) if activity.location else "Kfet"} +DESCRIPTION;CHARSET=UTF-8:""" + self.multilines(activity.description.replace("\n", "\\n"), 75, 26) + """ + -- {activity.organizer.name} +END:VEVENT +""" + ics += "END:VCALENDAR" + ics = ics.replace("\r", "").replace("\n", "\r\n") + return HttpResponse(ics, content_type="text/calendar; charset=UTF-8") diff --git a/apps/api/serializers.py b/apps/api/serializers.py index 1f658217..d59bdc43 100644 --- a/apps/api/serializers.py +++ b/apps/api/serializers.py @@ -6,6 +6,7 @@ from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User from rest_framework.serializers import ModelSerializer + class UserSerializer(ModelSerializer): """ REST API Serializer for Users. diff --git a/apps/api/urls.py b/apps/api/urls.py index 4addbdf1..7131c657 100644 --- a/apps/api/urls.py +++ b/apps/api/urls.py @@ -4,6 +4,7 @@ from django.conf import settings from django.conf.urls import url, include from rest_framework import routers + from .viewsets import ContentTypeViewSet, UserViewSet # Routers provide an easy way of automatically determining the URL conf. diff --git a/apps/api/viewsets.py b/apps/api/viewsets.py index 825082c0..fa2fc941 100644 --- a/apps/api/viewsets.py +++ b/apps/api/viewsets.py @@ -6,11 +6,8 @@ from django_filters.rest_framework import DjangoFilterBackend from django.db.models import Q from django.conf import settings from django.contrib.auth.models import User - from rest_framework.viewsets import ReadOnlyModelViewSet, ModelViewSet - from permission.backends import PermissionBackend - from note_kfet.middlewares import get_current_session from note.models import Alias @@ -29,7 +26,7 @@ class ReadProtectedModelViewSet(ModelViewSet): def get_queryset(self): user = self.request.user get_current_session().setdefault("permission_mask", 42) - return self.model.objects.filter(PermissionBackend.filter_queryset(user, self.model, "view")).distinct() + return self.queryset.filter(PermissionBackend.filter_queryset(user, self.model, "view")).distinct() class ReadOnlyProtectedModelViewSet(ReadOnlyModelViewSet): @@ -44,8 +41,7 @@ class ReadOnlyProtectedModelViewSet(ReadOnlyModelViewSet): def get_queryset(self): user = self.request.user get_current_session().setdefault("permission_mask", 42) - return self.model.objects.filter(PermissionBackend.filter_queryset(user, self.model, "view")).distinct() - + return self.queryset.filter(PermissionBackend.filter_queryset(user, self.model, "view")).distinct() class UserViewSet(ReadProtectedModelViewSet): @@ -67,29 +63,37 @@ class UserViewSet(ReadProtectedModelViewSet): if "search" in self.request.GET: pattern = self.request.GET["search"] - - # We match first a user by its username, then if an alias is matched without normalization - # And finally if the normalized pattern matches a normalized alias. + + # Filter with different rules + # We use union-all to keep each filter rule sorted in result queryset = queryset.filter( - username__iregex="^" + pattern).union( - queryset.filter( - Q(note__alias__name__iregex="^" + pattern) - & ~Q(username__iregex="^" + pattern)), all=True).union( - queryset.filter( - Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) - & ~Q(note__alias__name__iregex="^" + pattern) - & ~Q(username__iregex="^" + pattern)), all=True).union( - queryset.filter( - Q(note__alias__normalized_name__iregex="^" + pattern.lower()) - & ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) - & ~Q(note__alias__name__iregex="^" + pattern) - & ~Q(username__iregex="^" + pattern)), all=True).union( - queryset.filter( - (Q(last_name__iregex="^" + pattern) | Q(first_name__iregex="^" + pattern)) - & ~Q(note__alias__normalized_name__iregex="^" + pattern.lower()) - & ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) - & ~Q(note__alias__name__iregex="^" + pattern) - & ~Q(username__iregex="^" + pattern)), all=True) + # Match without normalization + note__alias__name__iregex="^" + pattern + ).union( + queryset.filter( + # Match with normalization + Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) + & ~Q(note__alias__name__iregex="^" + pattern) + ), + all=True, + ).union( + queryset.filter( + # Match on lower pattern + Q(note__alias__normalized_name__iregex="^" + pattern.lower()) + & ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) + & ~Q(note__alias__name__iregex="^" + pattern) + ), + all=True, + ).union( + queryset.filter( + # Match on firstname or lastname + (Q(last_name__iregex="^" + pattern) | Q(first_name__iregex="^" + pattern)) + & ~Q(note__alias__normalized_name__iregex="^" + pattern.lower()) + & ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) + & ~Q(note__alias__name__iregex="^" + pattern) + ), + all=True, + ) queryset = queryset if settings.DATABASES[queryset.db]["ENGINE"] == 'django.db.backends.postgresql' \ else queryset.order_by("username") diff --git a/apps/logs/migrations/0001_initial.py b/apps/logs/migrations/0001_initial.py new file mode 100644 index 00000000..e517edfb --- /dev/null +++ b/apps/logs/migrations/0001_initial.py @@ -0,0 +1,37 @@ +# Generated by Django 2.2.16 on 2020-09-04 21:41 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('contenttypes', '0002_remove_content_type_name'), + ] + + operations = [ + migrations.CreateModel( + name='Changelog', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('ip', models.GenericIPAddressField(blank=True, null=True, verbose_name='IP Address')), + ('instance_pk', models.CharField(max_length=255, verbose_name='identifier')), + ('previous', models.TextField(null=True, verbose_name='previous data')), + ('data', models.TextField(null=True, verbose_name='new data')), + ('action', models.CharField(choices=[('create', 'create'), ('edit', 'edit'), ('delete', 'delete')], default='edit', max_length=16, verbose_name='action')), + ('timestamp', models.DateTimeField(default=django.utils.timezone.now, verbose_name='timestamp')), + ('model', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.ContentType', verbose_name='model')), + ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL, verbose_name='user')), + ], + options={ + 'verbose_name': 'changelog', + 'verbose_name_plural': 'changelogs', + }, + ), + ] diff --git a/apps/logs/migrations/0002_replace_null_by_blank.py b/apps/logs/migrations/0002_replace_null_by_blank.py new file mode 100644 index 00000000..65fc4b14 --- /dev/null +++ b/apps/logs/migrations/0002_replace_null_by_blank.py @@ -0,0 +1,17 @@ +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('logs', '0001_initial'), + ] + + operations = [ + migrations.RunSQL( + "UPDATE logs_changelog SET previous = '' WHERE previous IS NULL;" + ), + migrations.RunSQL( + "UPDATE logs_changelog SET data = '' WHERE data IS NULL;" + ), + ] diff --git a/apps/logs/migrations/0003_remove_null_tag_on_charfields.py b/apps/logs/migrations/0003_remove_null_tag_on_charfields.py new file mode 100644 index 00000000..a6e3a581 --- /dev/null +++ b/apps/logs/migrations/0003_remove_null_tag_on_charfields.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.16 on 2020-09-06 19:17 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('logs', '0002_replace_null_by_blank'), + ] + + operations = [ + migrations.AlterField( + model_name='changelog', + name='data', + field=models.TextField(blank=True, default='', verbose_name='new data'), + ), + migrations.AlterField( + model_name='changelog', + name='previous', + field=models.TextField(blank=True, default='', verbose_name='previous data'), + ), + ] diff --git a/apps/logs/models.py b/apps/logs/models.py index e558ea82..0077af72 100644 --- a/apps/logs/models.py +++ b/apps/logs/models.py @@ -44,12 +44,14 @@ class Changelog(models.Model): ) previous = models.TextField( - null=True, + blank=True, + default="", verbose_name=_('previous data'), ) data = models.TextField( - null=True, + blank=True, + default="", verbose_name=_('new data'), ) @@ -80,3 +82,7 @@ class Changelog(models.Model): class Meta: verbose_name = _("changelog") verbose_name_plural = _("changelogs") + + def __str__(self): + return _("Changelog of type \"{action}\" for model {model} at {timestamp}").format( + action=self.get_action_display(), model=str(self.model), timestamp=str(self.timestamp)) diff --git a/apps/logs/signals.py b/apps/logs/signals.py index 2d443d13..b0b4d2c2 100644 --- a/apps/logs/signals.py +++ b/apps/logs/signals.py @@ -50,10 +50,7 @@ def save_object(sender, instance, **kwargs): in order to store each modification made """ # noinspection PyProtectedMember - if instance._meta.label_lower in EXCLUDED: - return - - if hasattr(instance, "_no_log"): + if instance._meta.label_lower in EXCLUDED or hasattr(instance, "_no_signal"): return # noinspection PyProtectedMember @@ -102,7 +99,7 @@ def save_object(sender, instance, **kwargs): model = instance.__class__ fields = changed_fields - previous_json = JSONRenderer().render(CustomSerializer(previous).data).decode("UTF-8") if previous else None + previous_json = JSONRenderer().render(CustomSerializer(previous).data).decode("UTF-8") if previous else "" instance_json = JSONRenderer().render(CustomSerializer(instance).data).decode("UTF-8") Changelog.objects.create(user=user, @@ -120,10 +117,7 @@ def delete_object(sender, instance, **kwargs): Each time a model is deleted, an entry in the table `Changelog` is added in the database """ # noinspection PyProtectedMember - if instance._meta.label_lower in EXCLUDED: - return - - if hasattr(instance, "_no_log"): + if instance._meta.label_lower in EXCLUDED or hasattr(instance, "_no_signal"): return # Si un utilisateur est connecté, on récupère l'utilisateur courant ainsi que son adresse IP @@ -155,6 +149,6 @@ def delete_object(sender, instance, **kwargs): model=ContentType.objects.get_for_model(instance), instance_pk=instance.pk, previous=instance_json, - data=None, + data="", action="delete" ).save() diff --git a/apps/member/admin.py b/apps/member/admin.py index 4cc2d0bf..7936f564 100644 --- a/apps/member/admin.py +++ b/apps/member/admin.py @@ -31,9 +31,7 @@ class CustomUserAdmin(UserAdmin): """ When creating a new user don't show profile one the first step """ - if not obj: - return list() - return super().get_inline_instances(request, obj) + return super().get_inline_instances(request, obj) if obj else [] @admin.register(Club, site=admin_site) diff --git a/apps/member/fixtures/initial.json b/apps/member/fixtures/initial.json deleted file mode 100644 index e27eb72d..00000000 --- a/apps/member/fixtures/initial.json +++ /dev/null @@ -1,31 +0,0 @@ -[ - { - "model": "member.club", - "pk": 1, - "fields": { - "name": "BDE", - "email": "tresorerie.bde@example.com", - "require_memberships": true, - "membership_fee_paid": 500, - "membership_fee_unpaid": 500, - "membership_duration": 396, - "membership_start": "2019-08-31", - "membership_end": "2020-09-30" - } - }, - { - "model": "member.club", - "pk": 2, - "fields": { - "name": "Kfet", - "email": "tresorerie.bde@example.com", - "parent_club": 1, - "require_memberships": true, - "membership_fee_paid": 3500, - "membership_fee_unpaid": 3500, - "membership_duration": 396, - "membership_start": "2019-08-31", - "membership_end": "2020-09-30" - } - } -] diff --git a/apps/member/forms.py b/apps/member/forms.py index a5d571b6..20de91b7 100644 --- a/apps/member/forms.py +++ b/apps/member/forms.py @@ -1,7 +1,11 @@ # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay # SPDX-License-Identifier: GPL-3.0-or-later +import io + +from PIL import Image, ImageSequence from django import forms +from django.conf import settings from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.forms import CheckboxSelectMultiple @@ -16,7 +20,7 @@ from .models import Profile, Club, Membership class CustomAuthenticationForm(AuthenticationForm): permission_mask = forms.ModelChoiceField( - label="Masque de permissions", + label=_("Permission mask"), queryset=PermissionMask.objects.order_by("rank"), empty_label=None, ) @@ -77,6 +81,54 @@ class ImageForm(forms.Form): width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) + def clean(self): + """ + Load image and crop + + In the future, when Pillow will support APNG we will be able to + simplify this code to save only PNG/APNG. + """ + cleaned_data = super().clean() + + # Image size is limited by Django DATA_UPLOAD_MAX_MEMORY_SIZE + image = cleaned_data.get('image') + if image: + # Let Pillow detect and load image + # If it is an animation, then there will be multiple frames + try: + im = Image.open(image) + except OSError: + # Rare case in which Django consider the upload file as an image + # but Pil is unable to load it + raise forms.ValidationError(_('This image cannot be loaded.')) + + # Crop each frame + x = cleaned_data.get('x', 0) + y = cleaned_data.get('y', 0) + w = cleaned_data.get('width', 200) + h = cleaned_data.get('height', 200) + frames = [] + for frame in ImageSequence.Iterator(im): + frame = frame.crop((x, y, x + w, y + h)) + frame = frame.resize( + (settings.PIC_WIDTH, settings.PIC_RATIO * settings.PIC_WIDTH), + Image.ANTIALIAS, + ) + frames.append(frame) + + # Save + om = frames.pop(0) # Get first frame + om.info = im.info # Copy metadata + image.file = io.BytesIO() + if len(frames) > 1: + # Save as GIF + om.save(image.file, "GIF", save_all=True, append_images=list(frames), loop=0) + else: + # Save as PNG + om.save(image.file, "PNG") + + return cleaned_data + class ClubForm(forms.ModelForm): def clean(self): diff --git a/apps/member/migrations/0001_initial.py b/apps/member/migrations/0001_initial.py new file mode 100644 index 00000000..be357568 --- /dev/null +++ b/apps/member/migrations/0001_initial.py @@ -0,0 +1,76 @@ +# Generated by Django 2.2.16 on 2020-09-04 21:41 + +import datetime +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone +import phonenumber_field.modelfields + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Club', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, unique=True, verbose_name='name')), + ('email', models.EmailField(max_length=254, verbose_name='email')), + ('require_memberships', models.BooleanField(default=True, help_text="Uncheck if this club don't require memberships.", verbose_name='require memberships')), + ('membership_fee_paid', models.PositiveIntegerField(default=0, verbose_name='membership fee (paid students)')), + ('membership_fee_unpaid', models.PositiveIntegerField(default=0, verbose_name='membership fee (unpaid students)')), + ('membership_duration', models.PositiveIntegerField(blank=True, help_text='The longest time (in days) a membership can last (NULL = infinite).', null=True, verbose_name='membership duration')), + ('membership_start', models.DateField(blank=True, help_text='Date from which the members can renew their membership.', null=True, verbose_name='membership start')), + ('membership_end', models.DateField(blank=True, help_text='Maximal date of a membership, after which members must renew it.', null=True, verbose_name='membership end')), + ], + options={ + 'verbose_name': 'club', + 'verbose_name_plural': 'clubs', + }, + ), + migrations.CreateModel( + name='Profile', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('phone_number', phonenumber_field.modelfields.PhoneNumberField(blank=True, max_length=50, null=True, region=None, verbose_name='phone number')), + ('section', models.CharField(blank=True, help_text='e.g. "1A0", "9A♥", "SAPHIRE"', max_length=255, null=True, verbose_name='section')), + ('department', models.CharField(choices=[('A0', 'Informatics (A0)'), ('A1', 'Mathematics (A1)'), ('A2', 'Physics (A2)'), ("A'2", "Applied physics (A'2)"), ('A2', "Chemistry (A''2)"), ('A3', 'Biology (A3)'), ('B1234', 'SAPHIRE (B1234)'), ('B1', 'Mechanics (B1)'), ('B2', 'Civil engineering (B2)'), ('B3', 'Mechanical engineering (B3)'), ('B4', 'EEA (B4)'), ('C', 'Design (C)'), ('D2', 'Economy-management (D2)'), ('D3', 'Social sciences (D3)'), ('E', 'English (E)'), ('EXT', 'External (EXT)')], max_length=8, verbose_name='department')), + ('promotion', models.PositiveSmallIntegerField(default=2020, help_text='Year of entry to the school (None if not ENS student)', null=True, verbose_name='promotion')), + ('address', models.CharField(blank=True, max_length=255, null=True, verbose_name='address')), + ('paid', models.BooleanField(default=False, help_text='Tells if the user receive a salary.', verbose_name='paid')), + ('ml_events_registration', models.CharField(blank=True, choices=[(None, 'No'), ('fr', 'Yes (receive them in french)'), ('en', 'Yes (receive them in english)')], default=None, max_length=2, null=True, verbose_name='Register on the mailing list to stay informed of the events of the campus (1 mail/week)')), + ('ml_sport_registration', models.BooleanField(default=False, verbose_name='Register on the mailing list to stay informed of the sport events of the campus (1 mail/week)')), + ('ml_art_registration', models.BooleanField(default=False, verbose_name='Register on the mailing list to stay informed of the art events of the campus (1 mail/week)')), + ('report_frequency', models.PositiveSmallIntegerField(default=0, verbose_name='report frequency (in days)')), + ('last_report', models.DateTimeField(default=django.utils.timezone.now, verbose_name='last report date')), + ('email_confirmed', models.BooleanField(default=False, verbose_name='email confirmed')), + ('registration_valid', models.BooleanField(default=False, verbose_name='registration valid')), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': 'user profile', + 'verbose_name_plural': 'user profile', + }, + ), + migrations.CreateModel( + name='Membership', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('date_start', models.DateField(default=datetime.date.today, verbose_name='membership starts on')), + ('date_end', models.DateField(null=True, verbose_name='membership ends on')), + ('fee', models.PositiveIntegerField(verbose_name='fee')), + ('club', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='member.Club', verbose_name='club')), + ], + options={ + 'verbose_name': 'membership', + 'verbose_name_plural': 'memberships', + }, + ), + ] diff --git a/apps/member/migrations/0002_auto_20200904_2341.py b/apps/member/migrations/0002_auto_20200904_2341.py new file mode 100644 index 00000000..3dd9d045 --- /dev/null +++ b/apps/member/migrations/0002_auto_20200904_2341.py @@ -0,0 +1,42 @@ +# Generated by Django 2.2.16 on 2020-09-04 21:41 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('permission', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('member', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='membership', + name='roles', + field=models.ManyToManyField(to='permission.Role', verbose_name='roles'), + ), + migrations.AddField( + model_name='membership', + name='user', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='memberships', to=settings.AUTH_USER_MODEL, verbose_name='user'), + ), + migrations.AddField( + model_name='club', + name='parent_club', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='member.Club', verbose_name='parent club'), + ), + migrations.AddIndex( + model_name='profile', + index=models.Index(fields=['user'], name='member_prof_user_id_30c316_idx'), + ), + migrations.AddIndex( + model_name='membership', + index=models.Index(fields=['user'], name='member_memb_user_id_945dbc_idx'), + ), + ] diff --git a/apps/member/migrations/0003_create_bde_and_kfet.py b/apps/member/migrations/0003_create_bde_and_kfet.py new file mode 100644 index 00000000..5f218040 --- /dev/null +++ b/apps/member/migrations/0003_create_bde_and_kfet.py @@ -0,0 +1,57 @@ +from django.db import migrations + + +def create_bde_and_kfet(apps, schema_editor): + """ + The clubs BDE and Kfet are pre-injected. + """ + Club = apps.get_model("member", "club") + NoteClub = apps.get_model("note", "noteclub") + ContentType = apps.get_model('contenttypes', 'ContentType') + polymorphic_ctype_id = ContentType.objects.get_for_model(NoteClub).id + + Club.objects.get_or_create( + id=1, + name="BDE", + email="tresorerie.bde@example.com", + require_memberships=True, + membership_fee_paid=500, + membership_fee_unpaid=500, + membership_duration=396, + membership_start="2020-08-01", + membership_end="2021-09-30", + ) + Club.objects.get_or_create( + id=2, + name="Kfet", + parent_club_id=1, + email="tresorerie.bde@example.com", + require_memberships=True, + membership_fee_paid=3500, + membership_fee_unpaid=3500, + membership_duration=396, + membership_start="2020-08-01", + membership_end="2021-09-30", + ) + + NoteClub.objects.get_or_create( + id=5, + club_id=1, + polymorphic_ctype_id=polymorphic_ctype_id, + ) + NoteClub.objects.get_or_create( + id=6, + club_id=2, + polymorphic_ctype_id=polymorphic_ctype_id, + ) + + +class Migration(migrations.Migration): + dependencies = [ + ('member', '0002_auto_20200904_2341'), + ('note', '0002_create_special_notes'), + ] + + operations = [ + migrations.RunPython(create_bde_and_kfet), + ] diff --git a/apps/member/migrations/0004_replace_null_by_blank.py b/apps/member/migrations/0004_replace_null_by_blank.py new file mode 100644 index 00000000..a53e3801 --- /dev/null +++ b/apps/member/migrations/0004_replace_null_by_blank.py @@ -0,0 +1,20 @@ +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('member', '0003_create_bde_and_kfet'), + ] + + operations = [ + migrations.RunSQL( + "UPDATE member_profile SET address = '' WHERE address IS NULL;", + ), + migrations.RunSQL( + "UPDATE member_profile SET ml_events_registration = '' WHERE ml_events_registration IS NULL;", + ), + migrations.RunSQL( + "UPDATE member_profile SET section = '' WHERE section IS NULL;", + ), + ] diff --git a/apps/member/migrations/0005_remove_null_tag_on_charfields.py b/apps/member/migrations/0005_remove_null_tag_on_charfields.py new file mode 100644 index 00000000..11b9f37b --- /dev/null +++ b/apps/member/migrations/0005_remove_null_tag_on_charfields.py @@ -0,0 +1,28 @@ +# Generated by Django 2.2.16 on 2020-09-06 19:17 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('member', '0004_replace_null_by_blank'), + ] + + operations = [ + migrations.AlterField( + model_name='profile', + name='address', + field=models.CharField(blank=True, default='', max_length=255, verbose_name='address'), + ), + migrations.AlterField( + model_name='profile', + name='ml_events_registration', + field=models.CharField(blank=True, choices=[('', 'No'), ('fr', 'Yes (receive them in french)'), ('en', 'Yes (receive them in english)')], default='', max_length=2, verbose_name='Register on the mailing list to stay informed of the events of the campus (1 mail/week)'), + ), + migrations.AlterField( + model_name='profile', + name='section', + field=models.CharField(blank=True, default='', help_text='e.g. "1A0", "9A♥", "SAPHIRE"', max_length=255, verbose_name='section'), + ), + ] diff --git a/apps/member/models.py b/apps/member/models.py index b17f1f09..c7467120 100644 --- a/apps/member/models.py +++ b/apps/member/models.py @@ -46,7 +46,7 @@ class Profile(models.Model): help_text=_('e.g. "1A0", "9A♥", "SAPHIRE"'), max_length=255, blank=True, - null=True, + default="", ) department = models.CharField( @@ -83,7 +83,7 @@ class Profile(models.Model): verbose_name=_('address'), max_length=255, blank=True, - null=True, + default="", ) paid = models.BooleanField( @@ -94,11 +94,10 @@ class Profile(models.Model): ml_events_registration = models.CharField( blank=True, - null=True, - default=None, + default='', max_length=2, choices=[ - (None, _("No")), + ('', _("No")), ('fr', _("Yes (receive them in french)")), ('en', _("Yes (receive them in english)")), ], @@ -172,19 +171,21 @@ class Profile(models.Model): def send_email_validation_link(self): subject = "[Note Kfet] " + str(_("Activate your Note Kfet account")) + token = email_validation_token.make_token(self.user) + uid = urlsafe_base64_encode(force_bytes(self.user_id)) message = loader.render_to_string('registration/mails/email_validation_email.txt', { 'user': self.user, 'domain': os.getenv("NOTE_URL", "note.example.com"), - 'token': email_validation_token.make_token(self.user), - 'uid': urlsafe_base64_encode(force_bytes(self.user.pk)), + 'token': token, + 'uid': uid, }) html = loader.render_to_string('registration/mails/email_validation_email.html', { 'user': self.user, 'domain': os.getenv("NOTE_URL", "note.example.com"), - 'token': email_validation_token.make_token(self.user), - 'uid': urlsafe_base64_encode(force_bytes(self.user.pk)), + 'token': token, + 'uid': uid, }) self.user.email_user(subject, message, html_message=html) @@ -339,43 +340,85 @@ class Membership(models.Model): return self.date_start.toordinal() <= datetime.datetime.now().toordinal() def renew(self): - if Membership.objects.filter( + """ + If the current membership comes to expiration, create a new membership that starts immediately after this one. + """ + if not Membership.objects.filter( user=self.user, club=self.club, date_start__gte=self.club.membership_start, ).exists(): - # Membership is already renewed - return - new_membership = Membership( + # Membership is not renewed yet + new_membership = Membership( + user=self.user, + club=self.club, + date_start=max(self.date_end + datetime.timedelta(days=1), self.club.membership_start), + ) + if hasattr(self, '_force_renew_parent') and self._force_renew_parent: + new_membership._force_renew_parent = True + if hasattr(self, '_soge') and self._soge: + new_membership._soge = True + if hasattr(self, '_force_save') and self._force_save: + new_membership._force_save = True + new_membership.save() + new_membership.roles.set(self.roles.all()) + new_membership.save() + + def renew_parent(self): + """ + Ensure that the parent membership is renewed, and renew/create it if needed. + """ + parent_membership = Membership.objects.filter( user=self.user, - club=self.club, - date_start=max(self.date_end + datetime.timedelta(days=1), self.club.membership_start), - ) - if hasattr(self, '_force_renew_parent') and self._force_renew_parent: - new_membership._force_renew_parent = True - if hasattr(self, '_soge') and self._soge: - new_membership._soge = True - if hasattr(self, '_force_save') and self._force_save: - new_membership._force_save = True - new_membership.save() - new_membership.roles.set(self.roles.all()) - new_membership.save() + club=self.club.parent_club, + ).order_by("-date_start") + if parent_membership.exists(): + # Renew the previous membership of the parent club + parent_membership = parent_membership.first() + parent_membership._force_renew_parent = True + if hasattr(self, '_soge'): + parent_membership._soge = True + if hasattr(self, '_force_save'): + parent_membership._force_save = True + parent_membership.renew() + else: + # Create a new membership in the parent club + parent_membership = Membership( + user=self.user, + club=self.club.parent_club, + date_start=self.date_start, + ) + parent_membership._force_renew_parent = True + if hasattr(self, '_soge'): + parent_membership._soge = True + if hasattr(self, '_force_save'): + parent_membership._force_save = True + parent_membership.save() + parent_membership.refresh_from_db() + + if self.club.parent_club.name == "BDE": + parent_membership.roles.set( + Role.objects.filter(Q(name="Adhérent BDE") | Q(name="Membre de club")).all()) + elif self.club.parent_club.name == "Kfet": + parent_membership.roles.set( + Role.objects.filter(Q(name="Adhérent Kfet") | Q(name="Membre de club")).all()) + else: + parent_membership.roles.set(Role.objects.filter(name="Membre de club").all()) + parent_membership.save() def save(self, *args, **kwargs): """ Calculate fee and end date before saving the membership and creating the transaction if needed. """ - - if self.pk: + created = not self.pk + if not created: for role in self.roles.all(): club = role.for_club if club is not None: if club.pk != self.club_id: raise ValidationError(_('The role {role} does not apply to the club {club}.') .format(role=role.name, club=club.name)) - - created = not self.pk - if created: + else: if Membership.objects.filter( user=self.user, club=self.club, @@ -384,7 +427,7 @@ class Membership(models.Model): ).exists(): raise ValidationError(_('User is already a member of the club')) - if self.club.parent_club is not None and not self.pk: + if self.club.parent_club is not None: # Check that the user is already a member of the parent club if the membership is created if not Membership.objects.filter( user=self.user, @@ -392,56 +435,15 @@ class Membership(models.Model): date_start__gte=self.club.parent_club.membership_start, ).exists(): if hasattr(self, '_force_renew_parent') and self._force_renew_parent: - parent_membership = Membership.objects.filter( - user=self.user, - club=self.club.parent_club, - ).order_by("-date_start") - if parent_membership.exists(): - # Renew the previous membership of the parent club - parent_membership = parent_membership.first() - parent_membership._force_renew_parent = True - if hasattr(self, '_soge'): - parent_membership._soge = True - if hasattr(self, '_force_save'): - parent_membership._force_save = True - parent_membership.renew() - else: - # Create a new membership in the parent club - parent_membership = Membership( - user=self.user, - club=self.club.parent_club, - date_start=self.date_start, - ) - parent_membership._force_renew_parent = True - if hasattr(self, '_soge'): - parent_membership._soge = True - if hasattr(self, '_force_save'): - parent_membership._force_save = True - parent_membership.save() - parent_membership.refresh_from_db() - - if self.club.parent_club.name == "BDE": - parent_membership.roles.set( - Role.objects.filter(Q(name="Adhérent BDE") | Q(name="Membre de club")).all()) - elif self.club.parent_club.name == "Kfet": - parent_membership.roles.set( - Role.objects.filter(Q(name="Adhérent Kfet") | Q(name="Membre de club")).all()) - else: - parent_membership.roles.set(Role.objects.filter(name="Membre de club").all()) - parent_membership.save() + self.renew_parent() else: raise ValidationError(_('User is not a member of the parent club') + ' ' + self.club.parent_club.name) - if self.user.profile.paid: - self.fee = self.club.membership_fee_paid - else: - self.fee = self.club.membership_fee_unpaid + self.fee = self.club.membership_fee_paid if self.user.profile.paid else self.club.membership_fee_unpaid - if self.club.membership_duration is not None: - self.date_end = self.date_start + datetime.timedelta(days=self.club.membership_duration) - else: - self.date_end = self.date_start + datetime.timedelta(days=424242) + self.date_end = self.date_start + datetime.timedelta(days=self.club.membership_duration) \ + if self.club.membership_duration is not None else self.date_start + datetime.timedelta(days=424242) if self.club.membership_end is not None and self.date_end > self.club.membership_end: self.date_end = self.club.membership_end diff --git a/apps/member/signals.py b/apps/member/signals.py index 70162b37..d590f446 100644 --- a/apps/member/signals.py +++ b/apps/member/signals.py @@ -6,11 +6,7 @@ def save_user_profile(instance, created, raw, **_kwargs): """ Hook to create and save a profile when an user is updated if it is not registered with the signup form """ - if raw: - # When provisionning data, do not try to autocreate - return - - if created and instance.is_active: + if not raw and created and instance.is_active and not hasattr(instance, "_no_signal"): from .models import Profile Profile.objects.get_or_create(user=instance) if instance.is_superuser: diff --git a/media/pic/default.png b/apps/member/static/member/img/default_picture.png similarity index 100% rename from media/pic/default.png rename to apps/member/static/member/img/default_picture.png diff --git a/apps/member/static/member/js/alias.js b/apps/member/static/member/js/alias.js index 2d652dde..444e1bcf 100644 --- a/apps/member/static/member/js/alias.js +++ b/apps/member/static/member/js/alias.js @@ -2,22 +2,22 @@ * On form submit, create a new alias */ function create_alias (e) { - // Do not submit HTML form - e.preventDefault(); + // Do not submit HTML form + e.preventDefault() - // Get data and send to API - const formData = new FormData(e.target); - $.post("/api/note/alias/", { - "csrfmiddlewaretoken": formData.get("csrfmiddlewaretoken"), - "name": formData.get("name"), - "note": formData.get("note") - }).done(function () { - // Reload table - $("#alias_table").load(location.pathname + " #alias_table"); - addMsg("Alias ajouté", "success"); - }).fail(function (xhr, _textStatus, _error) { - errMsg(xhr.responseJSON); - }); + // Get data and send to API + const formData = new FormData(e.target) + $.post('/api/note/alias/', { + csrfmiddlewaretoken: formData.get('csrfmiddlewaretoken'), + name: formData.get('name'), + note: formData.get('note') + }).done(function () { + // Reload table + $('#alias_table').load(location.pathname + ' #alias_table') + addMsg('Alias ajouté', 'success') + }).fail(function (xhr, _textStatus, _error) { + errMsg(xhr.responseJSON) + }) } /** @@ -25,19 +25,19 @@ function create_alias (e) { * @param Integer button_id Alias id to remove */ function delete_button (button_id) { - $.ajax({ - url: "/api/note/alias/" + button_id + "/", - method: "DELETE", - headers: { "X-CSRFTOKEN": CSRF_TOKEN } - }).done(function () { - addMsg('Alias supprimé', 'success'); - $("#alias_table").load(location.pathname + " #alias_table"); - }).fail(function (xhr, _textStatus, _error) { - errMsg(xhr.responseJSON); - }); + $.ajax({ + url: '/api/note/alias/' + button_id + '/', + method: 'DELETE', + headers: { 'X-CSRFTOKEN': CSRF_TOKEN } + }).done(function () { + addMsg('Alias supprimé', 'success') + $('#alias_table').load(location.pathname + ' #alias_table') + }).fail(function (xhr, _textStatus, _error) { + errMsg(xhr.responseJSON) + }) } $(document).ready(function () { - // Attach event - document.getElementById("form_alias").addEventListener("submit", create_alias); -}) \ No newline at end of file + // Attach event + document.getElementById('form_alias').addEventListener('submit', create_alias) +}) diff --git a/apps/member/templates/member/includes/club_info.html b/apps/member/templates/member/includes/club_info.html index 92c7b569..51f0ef03 100644 --- a/apps/member/templates/member/includes/club_info.html +++ b/apps/member/templates/member/includes/club_info.html @@ -48,10 +48,10 @@
- {% trans 'Manage aliases' %} ({{ user_object.note.alias_set.all|length }}) + {% trans 'Manage aliases' %} ({{ club.note.alias_set.all|length }})
{% trans 'email'|capfirst %}
{{ club.email }}
- \ No newline at end of file + diff --git a/apps/member/templates/member/manage_auth_tokens.html b/apps/member/templates/member/manage_auth_tokens.html index 473286c1..014686f1 100644 --- a/apps/member/templates/member/manage_auth_tokens.html +++ b/apps/member/templates/member/manage_auth_tokens.html @@ -1,4 +1,4 @@ -{% extends "member/base.html" %} +{% extends "base.html" %} {% comment %} SPDX-License-Identifier: GPL-3.0-or-later {% endcomment %} diff --git a/apps/member/templates/member/picture_update.html b/apps/member/templates/member/picture_update.html index 7c9128ce..51d05f91 100644 --- a/apps/member/templates/member/picture_update.html +++ b/apps/member/templates/member/picture_update.html @@ -32,8 +32,8 @@ SPDX-License-Identifier: GPL-3.0-or-later
- - + +
@@ -55,12 +55,18 @@ SPDX-License-Identifier: GPL-3.0-or-later /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#id_image").change(function (e) { if (this.files && this.files[0]) { - var reader = new FileReader(); - reader.onload = function (e) { - $("#modal-image").attr("src", e.target.result); - $("#modalCrop").modal("show"); + // Check the image size + if (this.files[0].size > 2*1024*1024) { + alert("Ce fichier est trop volumineux.") + } else { + // Read the selected image file + var reader = new FileReader(); + reader.onload = function (e) { + $("#modal-image").attr("src", e.target.result); + $("#modalCrop").modal("show"); + } + reader.readAsDataURL(this.files[0]); } - reader.readAsDataURL(this.files[0]); } }); @@ -104,4 +110,4 @@ SPDX-License-Identifier: GPL-3.0-or-later }); }); -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/apps/member/tests/test_login.py b/apps/member/tests/test_login.py index 51a4ab94..e022c4ea 100644 --- a/apps/member/tests/test_login.py +++ b/apps/member/tests/test_login.py @@ -1,9 +1,9 @@ # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay # SPDX-License-Identifier: GPL-3.0-or-later - +from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase -from note.models import TransactionTemplate, TemplateCategory +from django.urls import reverse """ Test that login page still works @@ -31,7 +31,20 @@ class TemplateLoggedInTests(TestCase): sess.save() def test_login_page(self): - response = self.client.get('/accounts/login/') + response = self.client.get(reverse("login")) + self.assertEqual(response.status_code, 200) + + self.client.logout() + + response = self.client.post('/accounts/login/', data=dict( + username="admin", + password="adminadmin", + permission_mask=3, + )) + self.assertRedirects(response, settings.LOGIN_REDIRECT_URL, 302, 200) + + def test_logout(self): + response = self.client.get(reverse("logout")) self.assertEqual(response.status_code, 200) def test_admin_index(self): @@ -41,22 +54,3 @@ class TemplateLoggedInTests(TestCase): def test_accounts_password_reset(self): response = self.client.get('/accounts/password_reset/') self.assertEqual(response.status_code, 200) - - def test_logout_page(self): - response = self.client.get('/accounts/logout/') - self.assertEqual(response.status_code, 200) - - def test_transfer_page(self): - response = self.client.get('/note/transfer/') - self.assertEqual(response.status_code, 200) - - def test_consos_page(self): - # Create one button and ensure that it is visible - cat = TemplateCategory.objects.create() - TransactionTemplate.objects.create( - destination_id=5, - category=cat, - amount=0, - ) - response = self.client.get('/note/consos/') - self.assertEqual(response.status_code, 200) diff --git a/apps/member/tests/test_memberships.py b/apps/member/tests/test_memberships.py new file mode 100644 index 00000000..90b1f382 --- /dev/null +++ b/apps/member/tests/test_memberships.py @@ -0,0 +1,405 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +import hashlib +import os +from datetime import date, timedelta + +from django.contrib.auth.models import User +from django.core.files.uploadedfile import SimpleUploadedFile +from django.db.models import Q +from django.test import TestCase +from django.urls import reverse +from django.utils import timezone +from member.models import Club, Membership, Profile +from note.models import Alias, NoteSpecial +from permission.models import Role +from treasury.models import SogeCredit + +""" +Create some users and clubs and test that all pages are rendering properly +and that memberships are working. +""" + + +class TestMemberships(TestCase): + fixtures = ('initial', ) + + def setUp(self) -> None: + """ + Create a sample superuser, a club and a membership for all tests. + """ + self.user = User.objects.create_superuser( + username="toto", + email="toto@example.com", + password="toto", + ) + self.user.profile.registration_valid = True + self.user.profile.email_confirmed = True + self.user.profile.save() + self.client.force_login(self.user) + + sess = self.client.session + sess["permission_mask"] = 42 + sess.save() + + self.club = Club.objects.create(name="totoclub", parent_club=Club.objects.get(name="BDE")) + self.bde_membership = Membership.objects.create(user=self.user, club=Club.objects.get(name="BDE")) + self.membership = Membership.objects.create(user=self.user, club=self.club) + self.membership.roles.add(Role.objects.get(name="Bureau de club")) + self.membership.save() + + def test_admin_pages(self): + """ + Check that Django Admin pages for the member app are loading successfully. + """ + response = self.client.get(reverse("admin:index") + "member/membership/") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("admin:index") + "member/club/") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("admin:index") + "auth/user/") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("admin:index") + "auth/user/" + str(self.user.pk) + "/change/") + self.assertEqual(response.status_code, 200) + + def test_render_club_list(self): + """ + Render the list of all clubs, with a search. + """ + response = self.client.get(reverse("member:club_list")) + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("member:club_list") + "?search=toto") + self.assertEqual(response.status_code, 200) + + def test_render_club_create(self): + """ + Try to create a new club. + """ + response = self.client.get(reverse("member:club_create")) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("member:club_create"), data=dict( + name="Club toto", + email="clubtoto@example.com", + parent_club=self.club.pk, + require_memberships=False, + membership_fee_paid=0, + membership_fee_unpaid=0, + )) + self.assertTrue(Club.objects.filter(name="Club toto").exists()) + club = Club.objects.get(name="Club toto") + self.assertRedirects(response, club.get_absolute_url(), 302, 200) + + def test_render_club_detail(self): + """ + Display the detail of a club. + """ + response = self.client.get(reverse("member:club_detail", args=(self.club.pk,))) + self.assertEqual(response.status_code, 200) + + def test_render_club_update(self): + """ + Try to update the information about a club. + """ + response = self.client.get(reverse("member:club_update", args=(self.club.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("member:club_update", args=(self.club.pk, )), data=dict( + name="Toto club updated", + email="clubtoto@example.com", + require_memberships=True, + membership_fee_paid=0, + membership_fee_unpaid=0, + )) + self.assertRedirects(response, self.club.get_absolute_url(), 302, 200) + self.assertTrue(Club.objects.exclude(name="Toto club updated")) + + def test_render_club_update_picture(self): + """ + Try to update the picture of the note of a club. + """ + response = self.client.get(reverse("member:club_update_pic", args=(self.club.pk,))) + self.assertEqual(response.status_code, 200) + + old_pic = self.club.note.display_image + + with open("apps/member/static/member/img/default_picture.png", "rb") as f: + image = SimpleUploadedFile("image.png", f.read(), "image/png") + response = self.client.post(reverse("member:club_update_pic", args=(self.club.pk,)), dict( + image=image, + x=0, + y=0, + width=200, + height=200, + )) + self.assertRedirects(response, self.club.get_absolute_url(), 302, 200) + + self.club.note.refresh_from_db() + self.assertTrue(os.path.exists(self.club.note.display_image.path)) + os.remove(self.club.note.display_image.path) + + self.club.note.display_image = old_pic + self.club.note.save() + + def test_render_club_aliases(self): + """ + Display the list of the aliases of a club. + """ + # Alias creation and deletion is already tested in the note app + response = self.client.get(reverse("member:club_alias", args=(self.club.pk,))) + self.assertEqual(response.status_code, 200) + + def test_render_club_members(self): + """ + Display the list of the members of a club. + """ + response = self.client.get(reverse("member:club_members", args=(self.club.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("member:club_members", args=(self.club.pk,)) + "?search=toto&roles=" + + ",".join([str(role.pk) for role in + Role.objects.filter(weirole__isnull=True).all()])) + self.assertEqual(response.status_code, 200) + + def test_render_club_add_member(self): + """ + Try to add memberships and renew them. + """ + response = self.client.get(reverse("member:club_add_member", args=(Club.objects.get(name="BDE").pk,))) + self.assertEqual(response.status_code, 200) + + user = User.objects.create(username="totototo") + user.profile.registration_valid = True + user.profile.email_confirmed = True + user.profile.save() + user.save() + + # We create a club without any parent and one club with parent BDE (that is the club Kfet) + for bde_parent in False, True: + if bde_parent: + club = Club.objects.get(name="Kfet") + else: + club = Club.objects.create( + name="Second club " + ("with BDE" if bde_parent else "without BDE"), + parent_club=None, + email="newclub@example.com", + require_memberships=True, + membership_fee_paid=1000, + membership_fee_unpaid=500, + membership_start=date.today(), + membership_end=date.today() + timedelta(days=366), + membership_duration=366, + ) + + response = self.client.get(reverse("member:club_add_member", args=(club.pk,))) + self.assertEqual(response.status_code, 200) + + # Create a new membership + response = self.client.post(reverse("member:club_add_member", args=(club.pk,)), data=dict( + user=user.pk, + date_start="{:%Y-%m-%d}".format(date.today()), + soge=False, + credit_type=NoteSpecial.objects.get(special_type="Espèces").id, + credit_amount=4200, + last_name="TOTO", + first_name="Toto", + bank="Le matelas", + )) + self.assertRedirects(response, club.get_absolute_url(), 302, 200) + + self.assertTrue(Membership.objects.filter(user=user, club=club).exists()) + + # Membership is sent to the past to check renewals + membership = Membership.objects.get(user=user, club=club) + self.assertTrue(membership.valid) + membership.date_start = date(year=2000, month=1, day=1) + membership.date_end = date(year=2000, month=12, day=31) + membership.save() + self.assertFalse(membership.valid) + + response = self.client.get(reverse("member:club_members", args=(club.pk,)) + "?only_active=0") + self.assertEqual(response.status_code, 200) + + bde_membership = self.bde_membership + if bde_parent: + bde_membership = Membership.objects.get(club__name="BDE", user=user) + bde_membership.date_start = date(year=2000, month=1, day=1) + bde_membership.date_end = date(year=2000, month=12, day=31) + bde_membership.save() + + response = self.client.get(reverse("member:club_renew_membership", args=(bde_membership.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("member:club_renew_membership", args=(membership.pk,))) + self.assertEqual(response.status_code, 200) + + # Renew membership + response = self.client.post(reverse("member:club_renew_membership", args=(membership.pk,)), data=dict( + user=user.pk, + date_start="{:%Y-%m-%d}".format(date.today()), + soge=bde_parent, + credit_type=NoteSpecial.objects.get(special_type="Chèque").id, + credit_amount=14242, + last_name="TOTO", + first_name="Toto", + bank="Bank", + )) + self.assertRedirects(response, club.get_absolute_url(), 302, 200) + + response = self.client.get(user.profile.get_absolute_url()) + self.assertEqual(response.status_code, 200) + + def test_auto_join_kfet_when_join_bde_with_soge(self): + """ + When we join the BDE club with a Soge registration, a Kfet membership is automatically created. + We check that it is the case. + """ + user = User.objects.create(username="new1A") + user.profile.registration_valid = True + user.profile.email_confirmed = True + user.profile.save() + user.save() + + bde = Club.objects.get(name="BDE") + kfet = Club.objects.get(name="Kfet") + + response = self.client.post(reverse("member:club_add_member", args=(bde.pk,)), data=dict( + user=user.pk, + date_start="{:%Y-%m-%d}".format(date.today()), + soge=True, + credit_type=NoteSpecial.objects.get(special_type="Virement bancaire").id, + credit_amount=(bde.membership_fee_paid + kfet.membership_fee_paid) / 100, + last_name="TOTO", + first_name="Toto", + bank="Société générale", + )) + self.assertRedirects(response, bde.get_absolute_url(), 302, 200) + + self.assertTrue(Membership.objects.filter(user=user, club=bde).exists()) + self.assertTrue(Membership.objects.filter(user=user, club=kfet).exists()) + self.assertTrue(SogeCredit.objects.filter(user=user).exists()) + + def test_change_roles(self): + """ + Check to change the roles of a membership. + """ + response = self.client.get(reverse("member:club_manage_roles", args=(self.membership.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("member:club_manage_roles", args=(self.membership.pk,)), data=dict( + roles=[role.id for role in Role.objects.filter( + Q(name="Membre de club") | Q(name="Trésorier·ère de club") | Q(name="Bureau de club")).all()], + )) + self.assertRedirects(response, self.user.profile.get_absolute_url(), 302, 200) + self.membership.refresh_from_db() + self.assertEqual(self.membership.roles.count(), 3) + + def test_render_user_list(self): + """ + Display the user search page. + """ + response = self.client.get(reverse("member:user_list")) + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("member:user_list") + "?search=toto") + self.assertEqual(response.status_code, 200) + + def test_render_user_detail(self): + """ + Display the user detail page. + """ + response = self.client.get(self.user.profile.get_absolute_url()) + self.assertEqual(response.status_code, 200) + + def test_render_user_update(self): + """ + Update some data about the user. + """ + response = self.client.get(reverse("member:user_update_profile", args=(self.user.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("member:user_update_profile", args=(self.user.pk,)), data=dict( + first_name="Toto", + last_name="Toto", + username="toto changed", + email="updated@example.com", + phone_number="+33600000000", + section="", + department="A0", + promotion=timezone.now().year, + address="Earth", + paid=True, + ml_events_registration="en", + ml_sports_registration=True, + ml_art_registration=True, + report_frequency=7, + )) + self.assertRedirects(response, self.user.profile.get_absolute_url(), 302, 200) + self.assertTrue(User.objects.filter(username="toto changed").exists()) + self.assertTrue(Profile.objects.filter(address="Earth").exists()) + self.assertTrue(Alias.objects.filter(normalized_name="totochanged").exists()) + + def test_render_user_update_picture(self): + """ + Update the note picture of the user. + """ + response = self.client.get(reverse("member:user_update_pic", args=(self.user.pk,))) + self.assertEqual(response.status_code, 200) + + old_pic = self.user.note.display_image + + with open("apps/member/static/member/img/default_picture.png", "rb") as f: + image = SimpleUploadedFile("image.png", f.read(), "image/png") + response = self.client.post(reverse("member:user_update_pic", args=(self.user.pk,)), dict( + image=image, + x=0, + y=0, + width=200, + height=200, + )) + self.assertRedirects(response, self.user.profile.get_absolute_url(), 302, 200) + + self.user.note.refresh_from_db() + self.assertTrue(os.path.exists(self.user.note.display_image.path)) + os.remove(self.user.note.display_image.path) + + self.user.note.display_image = old_pic + self.user.note.save() + + def test_render_user_aliases(self): + """ + Display the list of aliases of the user. + """ + # Alias creation and deletion is already tested in the note app + response = self.client.get(reverse("member:user_alias", args=(self.user.pk,))) + self.assertEqual(response.status_code, 200) + + def test_manage_auth_token(self): + """ + Display the page to see the API authentication token, see it and regenerate it. + :return: + """ + response = self.client.get(reverse("member:auth_token")) + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("member:auth_token") + "?view") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("member:auth_token") + "?regenerate") + self.assertRedirects(response, reverse("member:auth_token") + "?view", 302, 200) + + def test_random_coverage(self): + # Useless, only for coverage + self.assertEqual(str(self.user), str(self.user.profile)) + self.user.profile.promotion = None + self.assertEqual(self.user.profile.ens_year, 0) + self.membership.date_end = None + self.assertTrue(self.membership.valid) + + def test_nk15_hasher(self): + """ + Test that NK15 passwords are successfully imported. + """ + salt = "42" + password = "strongpassword42" + hashed = hashlib.sha256((salt + password).encode("utf-8")).hexdigest() + self.user.password = "custom_nk15$1$" + salt + "|" + hashed + self.user.save() + self.assertTrue(self.user.check_password(password)) diff --git a/apps/member/views.py b/apps/member/views.py index cccffc4a..033533ff 100644 --- a/apps/member/views.py +++ b/apps/member/views.py @@ -1,10 +1,8 @@ # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay # SPDX-License-Identifier: GPL-3.0-or-later -import io from datetime import timedelta, date -from PIL import Image from django.conf import settings from django.contrib.auth import logout from django.contrib.auth.mixins import LoginRequiredMixin @@ -97,8 +95,7 @@ class UserUpdateView(ProtectQuerysetMixin, LoginRequiredMixin, UpdateView): note = NoteUser.objects.filter( alias__normalized_name=Alias.normalize(new_username)) if note.exists() and note.get().user != self.object: - form.add_error('username', - _("An alias with a similar name already exists.")) + form.add_error('username', _("An alias with a similar name already exists.")) return super().form_invalid(form) # Check if the username is one of user's aliases. alias = Alias.objects.filter(name=new_username) @@ -141,10 +138,7 @@ class UserDetailView(ProtectQuerysetMixin, LoginRequiredMixin, DetailView): """ We can't display information of a not registered user. """ - qs = super().get_queryset() - if self.request.user.is_superuser and self.request.session.get("permission_mask", -1) >= 42: - return qs - return qs.filter(profile__registration_valid=True) + return super().get_queryset(**kwargs).filter(profile__registration_valid=True) def get_context_data(self, **kwargs): """ @@ -204,14 +198,16 @@ class UserListView(ProtectQuerysetMixin, LoginRequiredMixin, SingleTableView): """ Filter the user list with the given pattern. """ - qs = super().get_queryset().distinct("username").annotate(alias=F("note__alias__name"))\ + qs = super().get_queryset().annotate(alias=F("note__alias__name"))\ .annotate(normalized_alias=F("note__alias__normalized_name"))\ - .filter(profile__registration_valid=True).order_by("username") - if "search" in self.request.GET: - pattern = self.request.GET["search"] + .filter(profile__registration_valid=True) - if not pattern: - return qs.none() + # Sqlite doesn't support order by in subqueries + qs = qs.order_by("username").distinct("username")\ + if settings.DATABASES[qs.db]["ENGINE"] == 'django.db.backends.postgresql' else qs.distinct() + + if "search" in self.request.GET and self.request.GET["search"]: + pattern = self.request.GET["search"] qs = qs.filter( username__iregex="^" + pattern @@ -265,40 +261,27 @@ class PictureUpdateView(ProtectQuerysetMixin, LoginRequiredMixin, FormMixin, Det return context def get_success_url(self): + """Redirect to profile page after upload""" return reverse_lazy('member:user_detail', kwargs={'pk': self.object.id}) def post(self, request, *args, **kwargs): form = self.get_form() self.object = self.get_object() - if form.is_valid(): - return self.form_valid(form) - else: - print('is_invalid') - print(form) - return self.form_invalid(form) + return self.form_valid(form) if form.is_valid() else self.form_invalid(form) def form_valid(self, form): - image_field = form.cleaned_data['image'] - x = form.cleaned_data['x'] - y = form.cleaned_data['y'] - w = form.cleaned_data['width'] - h = form.cleaned_data['height'] - # image crop and resize - image_file = io.BytesIO(image_field.read()) - # ext = image_field.name.split('.')[-1].lower() - # TODO: support GIF format - image = Image.open(image_file) - image = image.crop((x, y, x + w, y + h)) - image_clean = image.resize((settings.PIC_WIDTH, - settings.PIC_RATIO * settings.PIC_WIDTH), - Image.ANTIALIAS) - image_file = io.BytesIO() - image_clean.save(image_file, "PNG") - image_field.file = image_file - # renaming - filename = "{}_pic.png".format(self.object.note.pk) - image_field.name = filename - self.object.note.display_image = image_field + """Save image to note""" + image = form.cleaned_data['image'] + + # Rename as a PNG or GIF + extension = image.name.split(".")[-1] + if extension == "gif": + image.name = "{}_pic.gif".format(self.object.note.pk) + else: + image.name = "{}_pic.png".format(self.object.note.pk) + + # Save + self.object.note.display_image = image self.object.note.save() return super().form_valid(form) @@ -320,8 +303,7 @@ class ManageAuthTokens(LoginRequiredMixin, TemplateView): def get(self, request, *args, **kwargs): if 'regenerate' in request.GET and Token.objects.filter(user=request.user).exists(): Token.objects.get(user=self.request.user).delete() - return redirect(reverse_lazy('member:auth_token') + "?show", - permanent=True) + return redirect(reverse_lazy('member:auth_token') + "?show") return super().get(request, *args, **kwargs) @@ -351,8 +333,9 @@ class ClubCreateView(ProtectQuerysetMixin, ProtectedCreateView): email="", ) - def form_valid(self, form): - return super().form_valid(form) + def get_success_url(self): + self.object.refresh_from_db() + return reverse_lazy("member:club_detail", kwargs={"pk": self.object.pk}) class ClubListView(ProtectQuerysetMixin, LoginRequiredMixin, SingleTableView): @@ -609,6 +592,64 @@ class ClubAddMemberView(ProtectQuerysetMixin, ProtectedCreateView): return context + def perform_verifications(self, form, user, club, fee): + """ + Make some additional verifications to check that the membership can be created. + :return: True if the form is clean, False if there is an error. + """ + error = False + + # Retrieve form data + credit_type = form.cleaned_data["credit_type"] + credit_amount = form.cleaned_data["credit_amount"] + last_name = form.cleaned_data["last_name"] + first_name = form.cleaned_data["first_name"] + bank = form.cleaned_data["bank"] + soge = form.cleaned_data["soge"] and not user.profile.soge and (club.name == "BDE" or club.name == "Kfet") + + if not soge and user.note.balance + credit_amount < fee and not Membership.objects.filter( + club__name="Kfet", + user=user, + date_start__lte=date.today(), + date_end__gte=date.today(), + ).exists(): + # Users without a valid Kfet membership can't have a negative balance. + # TODO Send a notification to the user (with a mail?) to tell her/him to credit her/his note + form.add_error('user', + _("This user don't have enough money to join this club, and can't have a negative balance.")) + error = True + + if Membership.objects.filter( + user=form.instance.user, + club=club, + date_start__lte=form.instance.date_start, + date_end__gte=form.instance.date_start, + ).exists(): + form.add_error('user', _('User is already a member of the club')) + error = True + + if club.membership_start and form.instance.date_start < club.membership_start: + form.add_error('user', _("The membership must start after {:%m-%d-%Y}.") + .format(form.instance.club.membership_start)) + error = True + + if club.membership_end and form.instance.date_start > club.membership_end: + form.add_error('user', _("The membership must begin before {:%m-%d-%Y}.") + .format(form.instance.club.membership_end)) + error = True + + if credit_amount: + if not last_name or not first_name or (not bank and credit_type.special_type == "Chèque"): + if not last_name: + form.add_error('last_name', _("This field is required.")) + if not first_name: + form.add_error('first_name', _("This field is required.")) + if not bank and credit_type.special_type == "Chèque": + form.add_error('bank', _("This field is required.")) + return self.form_invalid(form) + + return not error + def form_valid(self, form): """ Create membership, check that all is good, make transactions @@ -655,36 +696,9 @@ class ClubAddMemberView(ProtectQuerysetMixin, ProtectedCreateView): fee += c.membership_fee_paid if user.profile.paid else c.membership_fee_unpaid c = c.parent_club - if user.note.balance + credit_amount < fee and not Membership.objects.filter( - club__name="Kfet", - user=user, - date_start__lte=date.today(), - date_end__gte=date.today(), - ).exists(): - # Users without a valid Kfet membership can't have a negative balance. - # TODO Send a notification to the user (with a mail?) to tell her/him to credit her/his note - form.add_error('user', - _("This user don't have enough money to join this club, and can't have a negative balance.")) - return super().form_invalid(form) - - if Membership.objects.filter( - user=form.instance.user, - club=club, - date_start__lte=form.instance.date_start, - date_end__gte=form.instance.date_start, - ).exists(): - form.add_error('user', _('User is already a member of the club')) - return super().form_invalid(form) - - if club.membership_start and form.instance.date_start < club.membership_start: - form.add_error('user', _("The membership must start after {:%m-%d-%Y}.") - .format(form.instance.club.membership_start)) - return super().form_invalid(form) - - if club.membership_end and form.instance.date_start > club.membership_end: - form.add_error('user', _("The membership must begin before {:%m-%d-%Y}.") - .format(form.instance.club.membership_start)) - return super().form_invalid(form) + # Make some verifications about the form, and if there is an error, then assume that the form is invalid + if not self.perform_verifications(form, user, club, fee): + return self.form_invalid(form) # Now, all is fine, the membership can be created. @@ -696,15 +710,6 @@ class ClubAddMemberView(ProtectQuerysetMixin, ProtectedCreateView): # Credit note before the membership is created. if credit_amount > 0: - if not last_name or not first_name or (not bank and credit_type.special_type == "Chèque"): - if not last_name: - form.add_error('last_name', _("This field is required.")) - if not first_name: - form.add_error('first_name', _("This field is required.")) - if not bank and credit_type.special_type == "Chèque": - form.add_error('bank', _("This field is required.")) - return self.form_invalid(form) - transaction = SpecialTransaction( source=credit_type, destination=user.note, @@ -719,46 +724,38 @@ class ClubAddMemberView(ProtectQuerysetMixin, ProtectedCreateView): transaction._force_save = True transaction.save() + # Parent club memberships are automatically renewed / created. + # For example, a Kfet membership creates a BDE membership if it does not exist. form.instance._force_renew_parent = True ret = super().form_valid(form) - if club.name == "BDE": - member_role = Role.objects.filter(Q(name="Adhérent BDE") | Q(name="Membre de club")).all() - elif club.name == "Kfet": - member_role = Role.objects.filter(Q(name="Adhérent Kfet") | Q(name="Membre de club")).all() - else: - member_role = Role.objects.filter(name="Membre de club").all() + member_role = Role.objects.filter(Q(name="Adhérent BDE") | Q(name="Membre de club")).all() \ + if club.name == "BDE" else Role.objects.filter(Q(name="Adhérent Kfet") | Q(name="Membre de club")).all() \ + if club.name == "Kfet"else Role.objects.filter(name="Membre de club").all() form.instance.roles.set(member_role) form.instance._force_save = True form.instance.save() # If Société générale pays, then we assume that this is the BDE membership, and we auto-renew the # Kfet membership. - if soge: - # If not already done, create BDE and Kfet memberships - bde = Club.objects.get(name="BDE") + if soge and club.name == "BDE": kfet = Club.objects.get(name="Kfet") + fee = kfet.membership_fee_paid if user.profile.paid else kfet.membership_fee_unpaid - soge_clubs = [bde, kfet] - for club in soge_clubs: - fee = club.membership_fee_paid if user.profile.paid else club.membership_fee_unpaid - - # Get current membership, to get the end date - old_membership = Membership.objects.filter( - club=club, - user=user, - ).order_by("-date_start") - - if old_membership.filter(date_start__gte=club.membership_start).exists(): - # Membership is already renewed - continue + # Get current membership, to get the end date + old_membership = Membership.objects.filter( + club=kfet, + user=user, + ).order_by("-date_start") + if not old_membership.filter(date_start__gte=kfet.membership_start).exists(): + # If the membership is not already renewed membership = Membership( - club=club, + club=kfet, user=user, fee=fee, - date_start=max(old_membership.first().date_end + timedelta(days=1), club.membership_start) + date_start=max(old_membership.first().date_end + timedelta(days=1), kfet.membership_start) if old_membership.exists() else form.instance.date_start, ) membership._force_save = True @@ -767,10 +764,7 @@ class ClubAddMemberView(ProtectQuerysetMixin, ProtectedCreateView): membership.refresh_from_db() if old_membership.exists(): membership.roles.set(old_membership.get().roles.all()) - elif c.name == "BDE": - membership.roles.set(Role.objects.filter(Q(name="Adhérent BDE") | Q(name="Membre de club")).all()) - elif c.name == "Kfet": - membership.roles.set(Role.objects.filter(Q(name="Adhérent Kfet") | Q(name="Membre de club")).all()) + membership.roles.set(Role.objects.filter(Q(name="Adhérent Kfet") | Q(name="Membre de club")).all()) membership.save() return ret @@ -830,9 +824,7 @@ class ClubMembersListView(ProtectQuerysetMixin, LoginRequiredMixin, SingleTableV qs = qs.filter(date_start__lte=timezone.now().today(), date_end__gte=timezone.now().today()) if "roles" in self.request.GET: - if not self.request.GET["roles"]: - return qs.none() - roles_str = self.request.GET["roles"].replace(' ', '').split(',') + roles_str = self.request.GET["roles"].replace(' ', '').split(',') if self.request.GET["roles"] else ['0'] roles_int = map(int, roles_str) qs = qs.filter(roles__in=roles_int) diff --git a/apps/note/api/serializers.py b/apps/note/api/serializers.py index a9c2a107..0f2a2d72 100644 --- a/apps/note/api/serializers.py +++ b/apps/note/api/serializers.py @@ -127,7 +127,12 @@ class ConsumerSerializer(serializers.ModelSerializer): # If the user has no right to see the note, then we only display the note identifier return NotePolymorphicSerializer().to_representation(obj.note)\ if PermissionBackend.check_perm(get_current_authenticated_user(), "note.view_note", obj.note)\ - else dict(id=obj.note.id, name=str(obj.note)) + else dict( + id=obj.note.id, + name=str(obj.note), + is_active=obj.note.is_active, + display_image=obj.note.display_image.url, + ) def get_email_confirmed(self, obj): if isinstance(obj.note, NoteUser): diff --git a/apps/note/api/views.py b/apps/note/api/views.py index 1ab954c9..a478e7ff 100644 --- a/apps/note/api/views.py +++ b/apps/note/api/views.py @@ -118,7 +118,7 @@ class ConsumerViewSet(ReadOnlyProtectedModelViewSet): queryset = super().get_queryset() # Sqlite doesn't support ORDER BY in subqueries - queryset = queryset.order_by("username") \ + queryset = queryset.order_by("name") \ if settings.DATABASES[queryset.db]["ENGINE"] == 'django.db.backends.postgresql' else queryset alias = self.request.query_params.get("alias", ".*") @@ -140,6 +140,9 @@ class ConsumerViewSet(ReadOnlyProtectedModelViewSet): ), all=True) + queryset = queryset if settings.DATABASES[queryset.db]["ENGINE"] == 'django.db.backends.postgresql' \ + else queryset.order_by("name") + return queryset.distinct() diff --git a/apps/note/apps.py b/apps/note/apps.py index 4881e3b9..b3dc5a0f 100644 --- a/apps/note/apps.py +++ b/apps/note/apps.py @@ -3,7 +3,7 @@ from django.apps import AppConfig from django.conf import settings -from django.db.models.signals import post_save +from django.db.models.signals import post_save, pre_delete from django.utils.translation import gettext_lazy as _ from . import signals @@ -25,3 +25,8 @@ class NoteConfig(AppConfig): signals.save_club_note, sender='member.Club', ) + + pre_delete.connect( + signals.delete_transaction, + sender='note.transaction', + ) diff --git a/apps/note/fixtures/initial.json b/apps/note/fixtures/initial.json deleted file mode 100644 index 72853eb7..00000000 --- a/apps/note/fixtures/initial.json +++ /dev/null @@ -1,188 +0,0 @@ -[ - { - "model": "note.note", - "pk": 1, - "fields": { - "polymorphic_ctype": [ - "note", - "notespecial" - ], - "balance": 0, - "last_negative": null, - "is_active": true, - "display_image": "", - "created_at": "2020-02-20T20:02:48.778Z" - } - }, - { - "model": "note.note", - "pk": 2, - "fields": { - "polymorphic_ctype": [ - "note", - "notespecial" - ], - "balance": 0, - "last_negative": null, - "is_active": true, - "display_image": "", - "created_at": "2020-02-20T20:06:39.546Z" - } - }, - { - "model": "note.note", - "pk": 3, - "fields": { - "polymorphic_ctype": [ - "note", - "notespecial" - ], - "balance": 0, - "last_negative": null, - "is_active": true, - "display_image": "", - "created_at": "2020-02-20T20:06:43.049Z" - } - }, - { - "model": "note.note", - "pk": 4, - "fields": { - "polymorphic_ctype": [ - "note", - "notespecial" - ], - "balance": 0, - "last_negative": null, - "is_active": true, - "display_image": "", - "created_at": "2020-02-20T20:06:50.996Z" - } - }, - { - "model": "note.note", - "pk": 5, - "fields": { - "polymorphic_ctype": [ - "note", - "noteclub" - ], - "balance": 0, - "last_negative": null, - "is_active": true, - "display_image": "pic/default.png", - "created_at": "2020-02-20T20:09:38.615Z" - } - }, - { - "model": "note.note", - "pk": 6, - "fields": { - "polymorphic_ctype": [ - "note", - "noteclub" - ], - "balance": 0, - "last_negative": null, - "is_active": true, - "display_image": "pic/default.png", - "created_at": "2020-02-20T20:16:14.753Z" - } - }, - { - "model": "note.noteclub", - "pk": 5, - "fields": { - "club": 1 - } - }, - { - "model": "note.noteclub", - "pk": 6, - "fields": { - "club": 2 - } - }, - { - "model": "note.notespecial", - "pk": 1, - "fields": { - "special_type": "Esp\u00e8ces" - } - }, - { - "model": "note.notespecial", - "pk": 2, - "fields": { - "special_type": "Carte bancaire" - } - }, - { - "model": "note.notespecial", - "pk": 3, - "fields": { - "special_type": "Ch\u00e8que" - } - }, - { - "model": "note.notespecial", - "pk": 4, - "fields": { - "special_type": "Virement bancaire" - } - }, - { - "model": "note.alias", - "pk": 1, - "fields": { - "name": "Esp\u00e8ces", - "normalized_name": "especes", - "note": 1 - } - }, - { - "model": "note.alias", - "pk": 2, - "fields": { - "name": "Carte bancaire", - "normalized_name": "cartebancaire", - "note": 2 - } - }, - { - "model": "note.alias", - "pk": 3, - "fields": { - "name": "Ch\u00e8que", - "normalized_name": "cheque", - "note": 3 - } - }, - { - "model": "note.alias", - "pk": 4, - "fields": { - "name": "Virement bancaire", - "normalized_name": "virementbancaire", - "note": 4 - } - }, - { - "model": "note.alias", - "pk": 5, - "fields": { - "name": "BDE", - "normalized_name": "bde", - "note": 5 - } - }, - { - "model": "note.alias", - "pk": 6, - "fields": { - "name": "Kfet", - "normalized_name": "kfet", - "note": 6 - } - } -] \ No newline at end of file diff --git a/apps/note/migrations/0001_initial.py b/apps/note/migrations/0001_initial.py new file mode 100644 index 00000000..a0ebda31 --- /dev/null +++ b/apps/note/migrations/0001_initial.py @@ -0,0 +1,209 @@ +# Generated by Django 2.2.16 on 2020-09-04 21:41 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('member', '0001_initial'), + ('contenttypes', '0002_remove_content_type_name'), + ] + + operations = [ + migrations.CreateModel( + name='Note', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('balance', models.BigIntegerField(default=0, help_text='in centimes, money credited for this instance', verbose_name='account balance')), + ('last_negative', models.DateTimeField(blank=True, help_text='last time the balance was negative', null=True, verbose_name='last negative date')), + ('display_image', models.ImageField(default='pic/default.png', max_length=255, upload_to='pic/', verbose_name='display image')), + ('created_at', models.DateTimeField(default=django.utils.timezone.now, verbose_name='created at')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this note should be treated as active. Unselect this instead of deleting notes.', verbose_name='active')), + ('inactivity_reason', models.CharField(choices=[('manual', 'The user blocked his/her note manually, eg. when he/she left the school for holidays. It can be reactivated at any time.'), ('forced', "The note is blocked by the the BDE and can't be manually reactivated.")], default=None, max_length=255, null=True)), + ('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_note.note_set+', to='contenttypes.ContentType')), + ], + options={ + 'verbose_name': 'note', + 'verbose_name_plural': 'notes', + }, + ), + migrations.CreateModel( + name='TemplateCategory', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=31, unique=True, verbose_name='name')), + ], + options={ + 'verbose_name': 'transaction category', + 'verbose_name_plural': 'transaction categories', + }, + ), + migrations.CreateModel( + name='Transaction', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('source_alias', models.CharField(default='', max_length=255, verbose_name='used alias')), + ('destination_alias', models.CharField(default='', max_length=255, verbose_name='used alias')), + ('created_at', models.DateTimeField(default=django.utils.timezone.now, verbose_name='created at')), + ('quantity', models.PositiveIntegerField(default=1, verbose_name='quantity')), + ('amount', models.PositiveIntegerField(verbose_name='amount')), + ('reason', models.CharField(max_length=255, verbose_name='reason')), + ('valid', models.BooleanField(default=True, verbose_name='valid')), + ('invalidity_reason', models.CharField(blank=True, default=None, max_length=255, null=True, verbose_name='invalidity reason')), + ('destination', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='note.Note', verbose_name='destination')), + ('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_note.transaction_set+', to='contenttypes.ContentType')), + ('source', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='note.Note', verbose_name='source')), + ], + options={ + 'verbose_name': 'transaction', + 'verbose_name_plural': 'transactions', + }, + ), + migrations.CreateModel( + name='MembershipTransaction', + fields=[ + ('transaction_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='note.Transaction')), + ], + options={ + 'verbose_name': 'membership transaction', + 'verbose_name_plural': 'membership transactions', + }, + bases=('note.transaction',), + ), + migrations.CreateModel( + name='NoteClub', + fields=[ + ('note_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='note.Note')), + ], + options={ + 'verbose_name': 'club note', + 'verbose_name_plural': 'clubs notes', + }, + bases=('note.note',), + ), + migrations.CreateModel( + name='NoteSpecial', + fields=[ + ('note_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='note.Note')), + ('special_type', models.CharField(max_length=255, unique=True, verbose_name='type')), + ], + options={ + 'verbose_name': 'special note', + 'verbose_name_plural': 'special notes', + }, + bases=('note.note',), + ), + migrations.CreateModel( + name='NoteUser', + fields=[ + ('note_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='note.Note')), + ], + options={ + 'verbose_name': "one's note", + 'verbose_name_plural': 'users note', + }, + bases=('note.note',), + ), + migrations.CreateModel( + name='RecurrentTransaction', + fields=[ + ('transaction_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='note.Transaction')), + ], + options={ + 'verbose_name': 'recurrent transaction', + 'verbose_name_plural': 'recurrent transactions', + }, + bases=('note.transaction',), + ), + migrations.CreateModel( + name='SpecialTransaction', + fields=[ + ('transaction_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='note.Transaction')), + ('last_name', models.CharField(max_length=255, verbose_name='name')), + ('first_name', models.CharField(max_length=255, verbose_name='first_name')), + ('bank', models.CharField(blank=True, max_length=255, verbose_name='bank')), + ], + options={ + 'verbose_name': 'Special transaction', + 'verbose_name_plural': 'Special transactions', + }, + bases=('note.transaction',), + ), + migrations.CreateModel( + name='Alias', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, unique=True, verbose_name='name')), + ('normalized_name', models.CharField(editable=False, max_length=255, unique=True)), + ('note', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='note.Note')), + ], + options={ + 'verbose_name': 'alias', + 'verbose_name_plural': 'aliases', + }, + ), + migrations.CreateModel( + name='TransactionTemplate', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(error_messages={'unique': 'A template with this name already exist'}, max_length=255, unique=True, verbose_name='name')), + ('amount', models.PositiveIntegerField(verbose_name='amount')), + ('display', models.BooleanField(default=True, verbose_name='display')), + ('highlighted', models.BooleanField(default=False, verbose_name='highlighted')), + ('description', models.CharField(blank=True, max_length=255, verbose_name='description')), + ('category', models.ForeignKey(max_length=31, on_delete=django.db.models.deletion.PROTECT, related_name='templates', to='note.TemplateCategory', verbose_name='type')), + ('destination', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='note.NoteClub', verbose_name='destination')), + ], + options={ + 'verbose_name': 'transaction template', + 'verbose_name_plural': 'transaction templates', + }, + ), + migrations.AddIndex( + model_name='transaction', + index=models.Index(fields=['created_at'], name='note_transa_created_bea8b1_idx'), + ), + migrations.AddIndex( + model_name='transaction', + index=models.Index(fields=['source'], name='note_transa_source__4a1a1e_idx'), + ), + migrations.AddIndex( + model_name='transaction', + index=models.Index(fields=['destination'], name='note_transa_destina_6e1bb4_idx'), + ), + migrations.AddField( + model_name='recurrenttransaction', + name='template', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='note.TransactionTemplate'), + ), + migrations.AddField( + model_name='noteuser', + name='user', + field=models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='note', to=settings.AUTH_USER_MODEL, verbose_name='user'), + ), + migrations.AddField( + model_name='noteclub', + name='club', + field=models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='note', to='member.Club', verbose_name='club'), + ), + migrations.AddField( + model_name='membershiptransaction', + name='membership', + field=models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='transaction', to='member.Membership'), + ), + migrations.AddIndex( + model_name='alias', + index=models.Index(fields=['name'], name='note_alias_name_a89405_idx'), + ), + migrations.AddIndex( + model_name='alias', + index=models.Index(fields=['normalized_name'], name='note_alias_normali_bd52b4_idx'), + ), + ] diff --git a/apps/note/migrations/0002_create_special_notes.py b/apps/note/migrations/0002_create_special_notes.py new file mode 100644 index 00000000..12fa8583 --- /dev/null +++ b/apps/note/migrations/0002_create_special_notes.py @@ -0,0 +1,25 @@ +from django.db import migrations + + +def create_special_notes(apps, schema_editor): + """ + We create the four special note to make transfers. + """ + NoteSpecial = apps.get_model("note", "notespecial") + ContentType = apps.get_model('contenttypes', 'ContentType') + polymorphic_ctype_id = ContentType.objects.get_for_model(NoteSpecial).id + + NoteSpecial.objects.get_or_create(id=1, special_type="Espèces", polymorphic_ctype_id=polymorphic_ctype_id) + NoteSpecial.objects.get_or_create(id=2, special_type="Carte bancaire", polymorphic_ctype_id=polymorphic_ctype_id) + NoteSpecial.objects.get_or_create(id=3, special_type="Chèque", polymorphic_ctype_id=polymorphic_ctype_id) + NoteSpecial.objects.get_or_create(id=4, special_type="Virement bancaire", polymorphic_ctype_id=polymorphic_ctype_id) + + +class Migration(migrations.Migration): + dependencies = [ + ('note', '0001_initial'), + ] + + operations = [ + migrations.RunPython(create_special_notes), + ] diff --git a/apps/note/migrations/0003_replace_null_by_blank.py b/apps/note/migrations/0003_replace_null_by_blank.py new file mode 100644 index 00000000..21da860d --- /dev/null +++ b/apps/note/migrations/0003_replace_null_by_blank.py @@ -0,0 +1,17 @@ +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('note', '0002_create_special_notes'), + ] + + operations = [ + migrations.RunSQL( + "UPDATE note_note SET inactivity_reason = '' WHERE inactivity_reason IS NULL;" + ), + migrations.RunSQL( + "UPDATE note_transaction SET invalidity_reason = '' WHERE invalidity_reason IS NULL;" + ), + ] diff --git a/apps/note/migrations/0004_remove_null_tag_on_charfields.py b/apps/note/migrations/0004_remove_null_tag_on_charfields.py new file mode 100644 index 00000000..012fc359 --- /dev/null +++ b/apps/note/migrations/0004_remove_null_tag_on_charfields.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.16 on 2020-09-06 19:17 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('note', '0003_replace_null_by_blank'), + ] + + operations = [ + migrations.AlterField( + model_name='note', + name='inactivity_reason', + field=models.CharField(blank=True, choices=[('manual', 'The user blocked his/her note manually, eg. when he/she left the school for holidays. It can be reactivated at any time.'), ('forced', "The note is blocked by the the BDE and can't be manually reactivated.")], default='', max_length=255), + ), + migrations.AlterField( + model_name='transaction', + name='invalidity_reason', + field=models.CharField(blank=True, default='', max_length=255, verbose_name='invalidity reason'), + ), + ] diff --git a/apps/note/models/notes.py b/apps/note/models/notes.py index e5d9c13c..9efdd1d0 100644 --- a/apps/note/models/notes.py +++ b/apps/note/models/notes.py @@ -70,8 +70,8 @@ class Note(PolymorphicModel): "It can be reactivated at any time.")), ('forced', _("The note is blocked by the the BDE and can't be manually reactivated.")), ], - null=True, - default=None, + blank=True, + default="", ) class Meta: @@ -102,13 +102,19 @@ class Note(PolymorphicModel): super().save(*args, **kwargs) - if not Alias.objects.filter(name=str(self)).exists(): + if not Alias.objects.filter(normalized_name=Alias.normalize(str(self))).exists(): a = Alias(name=str(self)) a.clean() # Save alias a.note = self a.save(force_insert=True) + else: + # Check if the name of the note changed without changing the normalized form of the alias + alias = Alias.objects.get(normalized_name=Alias.normalize(str(self))) + if alias.name != str(self): + alias.name = str(self) + alias.save() def clean(self, *args, **kwargs): """ diff --git a/apps/note/models/transactions.py b/apps/note/models/transactions.py index d88be5a6..c28d66da 100644 --- a/apps/note/models/transactions.py +++ b/apps/note/models/transactions.py @@ -90,6 +90,9 @@ class TransactionTemplate(models.Model): def get_absolute_url(self): return reverse('note:template_update', args=(self.pk,)) + def __str__(self): + return self.name + class Transaction(PolymorphicModel): """ @@ -150,8 +153,7 @@ class Transaction(PolymorphicModel): invalidity_reason = models.CharField( verbose_name=_('invalidity reason'), max_length=255, - default=None, - null=True, + default='', blank=True, ) @@ -173,7 +175,7 @@ class Transaction(PolymorphicModel): created = self.pk is None to_transfer = self.amount * self.quantity - if not created: + if not created and not self.valid and not hasattr(self, "_force_save"): # Revert old transaction old_transaction = Transaction.objects.get(pk=self.pk) # Check that nothing important changed @@ -195,7 +197,7 @@ class Transaction(PolymorphicModel): # When a transaction is declared valid, we ensure that the invalidity reason is null, if it was # previously invalid - self.invalidity_reason = None + self.invalidity_reason = "" if source_balance > 9223372036854775807 or source_balance < -9223372036854775808\ or dest_balance > 9223372036854775807 or dest_balance < -9223372036854775808: @@ -242,14 +244,6 @@ class Transaction(PolymorphicModel): self.destination._force_save = True self.destination.save() - def delete(self, **kwargs): - """ - Whenever we want to delete a transaction (caution with this), we ensure the transaction is invalid first. - """ - self.valid = False - self.save(**kwargs) - super().delete(**kwargs) - @property def total(self): return self.amount * self.quantity @@ -356,4 +350,4 @@ class MembershipTransaction(Transaction): @property def type(self): - return _('membership transaction') + return _('membership').capitalize() diff --git a/apps/note/signals.py b/apps/note/signals.py index 06bb480b..c1545ec2 100644 --- a/apps/note/signals.py +++ b/apps/note/signals.py @@ -6,7 +6,8 @@ def save_user_note(instance, raw, **_kwargs): """ Hook to create and save a note when an user is updated """ - if not raw and (instance.is_superuser or instance.profile.registration_valid): + if not raw and (instance.is_superuser or instance.profile.registration_valid)\ + and not hasattr(instance, "_no_signal"): # Create note only when the registration is validated from note.models import NoteUser NoteUser.objects.get_or_create(user=instance) @@ -17,10 +18,17 @@ def save_club_note(instance, raw, **_kwargs): """ Hook to create and save a note when a club is updated """ - if raw: - # When provisionning data, do not try to autocreate - return + # When provisionning data, do not try to autocreate + if not raw and not hasattr(instance, "_no_signal"): + from .models import NoteClub + NoteClub.objects.get_or_create(club=instance) + instance.note.save() - from .models import NoteClub - NoteClub.objects.get_or_create(club=instance) - instance.note.save() + +def delete_transaction(instance, **_kwargs): + """ + Whenever we want to delete a transaction (caution with this), we ensure the transaction is invalid first. + """ + if not hasattr(instance, "_no_signal"): + instance.valid = False + instance.save() diff --git a/apps/note/tables.py b/apps/note/tables.py index b1d434ae..f05edc96 100644 --- a/apps/note/tables.py +++ b/apps/note/tables.py @@ -29,6 +29,7 @@ class HistoryTable(tables.Table): source = tables.Column( attrs={ "td": { + "class": "text-nowrap", "data-toggle": "tooltip", "title": lambda record: _("used alias").capitalize() + " : " + record.source_alias, } @@ -38,15 +39,47 @@ class HistoryTable(tables.Table): destination = tables.Column( attrs={ "td": { + "class": "text-nowrap", "data-toggle": "tooltip", "title": lambda record: _("used alias").capitalize() + " : " + record.destination_alias, } } ) + created_at = tables.DateTimeColumn( + format='Y-m-d H:i:s', + attrs={ + "td": { + "class": "text-nowrap", + }, + } + ) + + amount = tables.Column( + attrs={ + "td": { + "class": "text-nowrap", + }, + } + ) + + reason = tables.Column( + attrs={ + "td": { + "class": "text-break", + }, + } + ) + type = tables.Column() - total = tables.Column() # will use Transaction.total() !! + total = tables.Column( # will use Transaction.total() !! + attrs={ + "td": { + "class": "text-nowrap", + }, + } + ) valid = tables.Column( attrs={ diff --git a/apps/note/templates/note/conso_form.html b/apps/note/templates/note/conso_form.html index 07c63488..d5914055 100644 --- a/apps/note/templates/note/conso_form.html +++ b/apps/note/templates/note/conso_form.html @@ -15,7 +15,7 @@ SPDX-License-Identifier: GPL-3.0-or-later
-
diff --git a/apps/note/templates/note/mails/weekly_report.html b/apps/note/templates/note/mails/weekly_report.html index 871e09c2..6ed768a3 100644 --- a/apps/note/templates/note/mails/weekly_report.html +++ b/apps/note/templates/note/mails/weekly_report.html @@ -1,5 +1,7 @@ {% load pretty_money %} +{% load getenv %} {% load render_table from django_tables2 %} +{% load static %} {% load i18n %} @@ -8,13 +10,8 @@ [Note Kfet] Rapport de la Note Kfet - - + +

@@ -27,7 +24,7 @@ Ensuite, un rapport vous est envoyé à la fréquence demandée seulement si vous avez consommé depuis le dernier rapport.
Pour arrêter de recevoir des rapports, il vous suffit de modifier votre profil Note et de - mettre la fréquence des rapports à 0 ou -1.
+ mettre la fréquence des rapports à 0.
Pour toutes suggestions par rapport à ce service, contactez notekfet2020@lists.crans.org.

diff --git a/apps/note/templates/note/mails/weekly_report.txt b/apps/note/templates/note/mails/weekly_report.txt new file mode 100644 index 00000000..3d9bcf67 --- /dev/null +++ b/apps/note/templates/note/mails/weekly_report.txt @@ -0,0 +1,32 @@ +{% load pretty_money %} +{% load getenv %} +{% load i18n %} + +Bonjour, + +Vous recevez ce mail car vous avez défini une « Fréquence des rapports » dans la Note. +Le premier rapport récapitule toutes vos consommations depuis la création de votre compte. +Ensuite, un rapport vous est envoyé à la fréquence demandée seulement si vous avez consommé +depuis le dernier rapport. +Pour arrêter de recevoir des rapports, il vous suffit de modifier votre profil Note et de +mettre la fréquence des rapports à 0. +Pour toutes suggestions par rapport à ce service, contactez notekfet2020@lists.crans.org. + +Rapport d'activité de {{ user.first_name|safe }} {{ user.last_name|safe }} (note : {{ user|safe }}) +depuis le {{ last_report }} jusqu'au {{ now }}. + +Dépenses totales : {{ outcoming|pretty_money }} +Apports totaux : {{ incoming|pretty_money }} +Différentiel : {{ diff|pretty_money }} +Nouveau solde : {{ user.note.balance|pretty_money }} + + +Rapport détaillé : + +| Source | Destination | Créée le | Quantité | Montant | Raison | Type | Total | Valide | ++----------------------+----------------------+---------------------+----------+----------+----------------------------------+------------------+----------+---------+ +{% for tr in last_transactions %}| {{ tr.source|safe|truncatechars:20|center:"20" }} | {{ tr.destination|safe|truncatechars:20|center:"20" }} | {{ tr.created_at|date:"Y-m-d H:i:s" }} | {{ tr.quantity|center:"8" }} | {{ tr.amount|pretty_money|center:"8" }} | {{ tr.reason|safe|truncatechars:32|center:"32" }} | {{ tr.type|safe|center:"16" }} | {{ tr.total|pretty_money|center:"8" }} | {{ tr.valid|yesno|center:"7" }} | +{% endfor %} +-- +Le BDE +{% trans "Mail generated by the Note Kfet on the" %} {% now "j F Y à H:i:s" %} diff --git a/apps/note/templates/note/transaction_form.html b/apps/note/templates/note/transaction_form.html index acb09beb..f5ff0b73 100644 --- a/apps/note/templates/note/transaction_form.html +++ b/apps/note/templates/note/transaction_form.html @@ -37,8 +37,8 @@ SPDX-License-Identifier: GPL-2.0-or-later
{# Preview note profile (picture, username and balance) #}
-
- +
@@ -65,9 +65,9 @@ SPDX-License-Identifier: GPL-2.0-or-later
diff --git a/apps/permission/fixtures/initial.json b/apps/permission/fixtures/initial.json index 120bb1ee..c419f9a5 100644 --- a/apps/permission/fixtures/initial.json +++ b/apps/permission/fixtures/initial.json @@ -1103,7 +1103,7 @@ "treasury", "sogecredit" ], - "query": "{\"credit_transaction\": null}", + "query": "{}", "type": "add", "mask": 1, "field": "", @@ -2567,6 +2567,118 @@ "description": "(Dé)bloquer sa propre note et modifier la raison" } }, + { + "model": "permission.permission", + "pk": 165, + "fields": { + "model": [ + "auth", + "user" + ], + "query": "{}", + "type": "change", + "mask": 1, + "field": "password", + "permanent": true, + "description": "Changer son mot de passe" + } + }, + { + "model": "permission.permission", + "pk": 166, + "fields": { + "model": [ + "note", + "transaction" + ], + "query": "[\"OR\", {\"source__balance__gte\": {\"F\": [\"SUB\", [\"MUL\", [\"F\", \"amount\"], [\"F\", \"quantity\"]], 5000]}}, {\"valid\": false}]", + "type": "add", + "mask": 2, + "field": "", + "permanent": false, + "description": "Créer une transaction quelconque tant que la source reste au-dessus de -50 €" + } + }, + { + "model": "permission.permission", + "pk": 167, + "fields": { + "model": [ + "note", + "transaction" + ], + "query": "[\"OR\", {\"source__balance__gte\": {\"F\": [\"SUB\", [\"MUL\", [\"F\", \"amount\"], [\"F\", \"quantity\"]], 5000]}, \"valid\": true}, {\"destination__balance__gte\": {\"F\": [\"SUB\", [\"MUL\", [\"F\", \"amount\"], [\"F\", \"quantity\"]], 5000]}, \"valid\": false}]", + "type": "change", + "mask": 2, + "field": "valid", + "permanent": false, + "description": "Modifier le statut de validation d'une transaction si c'est possible" + } + }, + { + "model": "permission.permission", + "pk": 168, + "fields": { + "model": [ + "note", + "transaction" + ], + "query": "[\"OR\", {\"source__balance__gte\": {\"F\": [\"SUB\", [\"MUL\", [\"F\", \"amount\"], [\"F\", \"quantity\"]], 5000]}, \"valid\": true}, {\"destination__balance__gte\": {\"F\": [\"SUB\", [\"MUL\", [\"F\", \"amount\"], [\"F\", \"quantity\"]], 5000]}, \"valid\": false}]", + "type": "change", + "mask": 2, + "field": "invalidity_reason", + "permanent": false, + "description": "Modifier la raison d'invalidité d'une transaction si c'est possible" + } + }, + { + "model": "permission.permission", + "pk": 169, + "fields": { + "model": [ + "note", + "noteclub" + ], + "query": "{\"club\": [\"club\"]}", + "type": "change", + "mask": 1, + "field": "display_image", + "permanent": false, + "description": "Changer l'image de la note de son club" + } + }, + { + "model": "permission.permission", + "pk": 170, + "fields": { + "model": [ + "note", + "alias" + ], + "query": "{\"note__is_active\": true}", + "type": "add", + "mask": 1, + "field": "", + "permanent": false, + "description": "Ajouter n'importe quel alias à une note non bloquée" + } + }, + { + "model": "permission.permission", + "pk": 171, + "fields": { + "model": [ + "note", + "alias" + ], + "query": "{\"note__is_active\": true}", + "type": "delete", + "mask": 3, + "field": "", + "permanent": false, + "description": "Supprimer n'importe quel alias à une note non bloquée" + } + }, { "model": "permission.role", "pk": 1, @@ -2591,7 +2703,8 @@ 52, 126, 161, - 162 + 162, + 165 ] } }, @@ -2661,7 +2774,8 @@ 47, 49, 50, - 141 + 141, + 169 ] } }, @@ -2696,8 +2810,14 @@ 62, 127, 133, + 135, + 136, 141, - 142 + 142, + 150, + 166, + 167, + 168 ] } }, @@ -2711,8 +2831,7 @@ 24, 25, 26, - 27, - 33 + 27 ] } }, @@ -2763,7 +2882,9 @@ 150, 151, 163, - 164 + 164, + 170, + 171 ] } }, @@ -2932,7 +3053,14 @@ 161, 162, 163, - 164 + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171 ] } }, @@ -2944,7 +3072,6 @@ "name": "GC Kfet", "permissions": [ 32, - 33, 56, 58, 55, @@ -2959,7 +3086,13 @@ 29, 30, 31, - 143 + 70, + 143, + 166, + 167, + 168, + 170, + 171 ] } }, diff --git a/apps/permission/migrations/0001_initial.py b/apps/permission/migrations/0001_initial.py new file mode 100644 index 00000000..c82aa032 --- /dev/null +++ b/apps/permission/migrations/0001_initial.py @@ -0,0 +1,71 @@ +# Generated by Django 2.2.16 on 2020-09-04 21:41 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('member', '0001_initial'), + ('contenttypes', '0002_remove_content_type_name'), + ] + + operations = [ + migrations.CreateModel( + name='Permission', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('query', models.TextField(verbose_name='query')), + ('type', models.CharField(choices=[('add', 'add'), ('view', 'view'), ('change', 'change'), ('delete', 'delete')], max_length=15, verbose_name='type')), + ('field', models.CharField(blank=True, max_length=255, verbose_name='field')), + ('permanent', models.BooleanField(default=False, help_text='Tells if the permission should be granted even if the membership of the user is expired.', verbose_name='permanent')), + ('description', models.CharField(blank=True, max_length=255, verbose_name='description')), + ], + options={ + 'verbose_name': 'permission', + 'verbose_name_plural': 'permissions', + }, + ), + migrations.CreateModel( + name='PermissionMask', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('rank', models.PositiveSmallIntegerField(unique=True, verbose_name='rank')), + ('description', models.CharField(max_length=255, unique=True, verbose_name='description')), + ], + options={ + 'verbose_name': 'permission mask', + 'verbose_name_plural': 'permission masks', + }, + ), + migrations.CreateModel( + name='Role', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, verbose_name='name')), + ('for_club', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, to='member.Club', verbose_name='for club')), + ('permissions', models.ManyToManyField(to='permission.Permission', verbose_name='permissions')), + ], + options={ + 'verbose_name': 'role permissions', + 'verbose_name_plural': 'role permissions', + }, + ), + migrations.AddField( + model_name='permission', + name='mask', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='permissions', to='permission.PermissionMask', verbose_name='mask'), + ), + migrations.AddField( + model_name='permission', + name='model', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='contenttypes.ContentType', verbose_name='model'), + ), + migrations.AlterUniqueTogether( + name='permission', + unique_together={('model', 'query', 'type', 'field')}, + ), + ] diff --git a/apps/permission/models.py b/apps/permission/models.py index 3d395a75..ff348404 100644 --- a/apps/permission/models.py +++ b/apps/permission/models.py @@ -57,8 +57,8 @@ class InstancedPermission: # Force insertion, no data verification, no trigger obj._force_save = True - # We don't want log anything - obj._no_log = True + # We don't want to trigger any signal (log, ...) + obj._no_signal = True Model.save(obj, force_insert=True) ret = self.model.model_class().objects.filter(self.query & Q(pk=0)).exists() # Delete testing object diff --git a/apps/permission/signals.py b/apps/permission/signals.py index 112247eb..e738545a 100644 --- a/apps/permission/signals.py +++ b/apps/permission/signals.py @@ -28,7 +28,7 @@ def pre_save_object(sender, instance, **kwargs): if instance._meta.label_lower in EXCLUDED: return - if hasattr(instance, "_force_save"): + if hasattr(instance, "_force_save") or hasattr(instance, "_no_signal"): return user = get_current_authenticated_user() @@ -82,7 +82,8 @@ def pre_delete_object(instance, **kwargs): if instance._meta.label_lower in EXCLUDED: return - if hasattr(instance, "_force_delete") or hasattr(instance, "pk") and instance.pk == 0: + if hasattr(instance, "_force_delete") or hasattr(instance, "pk") and instance.pk == 0 \ + or hasattr(instance, "_no_signal"): # Don't check permissions on force-deleted objects return diff --git a/apps/permission/tests/test_permission_queries.py b/apps/permission/tests/test_permission_queries.py index e0af9cf0..fdd530a5 100644 --- a/apps/permission/tests/test_permission_queries.py +++ b/apps/permission/tests/test_permission_queries.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: GPL-3.0-or-later from datetime import date +from json.decoder import JSONDecodeError from django.contrib.auth.models import User from django.core.exceptions import FieldError @@ -56,29 +57,28 @@ class PermissionQueryTestCase(TestCase): We use a random user with a random WEIClub (to use permissions for the WEI) in a random team in a random bus. """ for perm in Permission.objects.all(): - instanced = perm.about( - user=User.objects.get(), - club=WEIClub.objects.get(), - membership=Membership.objects.get(), - User=User, - Club=Club, - Membership=Membership, - Note=Note, - NoteUser=NoteUser, - NoteClub=NoteClub, - NoteSpecial=NoteSpecial, - F=F, - Q=Q, - now=timezone.now(), - today=date.today(), - ) try: + instanced = perm.about( + user=User.objects.get(), + club=WEIClub.objects.get(), + membership=Membership.objects.get(), + User=User, + Club=Club, + Membership=Membership, + Note=Note, + NoteUser=NoteUser, + NoteClub=NoteClub, + NoteSpecial=NoteSpecial, + F=F, + Q=Q, + now=timezone.now(), + today=date.today(), + ) instanced.update_query() query = instanced.query model = perm.model.model_class() model.objects.filter(query).all() - # print("Good query for permission", perm) - except (FieldError, AttributeError, ValueError, TypeError): + except (FieldError, AttributeError, ValueError, TypeError, JSONDecodeError): print("Query error for permission", perm) print("Query:", perm.query) if instanced.query: diff --git a/apps/permission/tests/test_rights_page.py b/apps/permission/tests/test_rights_page.py new file mode 100644 index 00000000..da80bf09 --- /dev/null +++ b/apps/permission/tests/test_rights_page.py @@ -0,0 +1,44 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib.auth.models import User +from django.test import TestCase +from django.urls import reverse +from member.models import Membership, Club +from permission.models import Role + + +class TestRightsPage(TestCase): + """ + Display the rights page. + """ + fixtures = ("initial",) + + def test_anonymous_rights_page(self): + """ + Check that we can properly see the rights page even if we are not connected. + We can't nethertheless see the club managers. + """ + response = self.client.get(reverse("permission:rights")) + self.assertEqual(response.status_code, 200) + self.assertFalse("special_memberships_table" in response.context) + self.assertFalse("superusers" in response.context) + + def test_authenticated_rights_page(self): + """ + Connect to the note and check that the club mangers are also displayed. + """ + user = User.objects.create_superuser( + username="ploptoto", + password="totototo", + email="toto@example.com", + ) + self.client.force_login(user) + membership = Membership.objects.create(user=user, club=Club.objects.get(name="BDE")) + membership.roles.add(Role.objects.get(name="Respo info")) + membership.save() + + response = self.client.get(reverse("permission:rights")) + self.assertEqual(response.status_code, 200) + self.assertIsNotNone(response.context["special_memberships_table"]) + self.assertIsNotNone(response.context["superusers"]) diff --git a/apps/permission/views.py b/apps/permission/views.py index 70aa7184..343152f5 100644 --- a/apps/permission/views.py +++ b/apps/permission/views.py @@ -8,6 +8,7 @@ from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.db.models import Q from django.forms import HiddenInput +from django.http import Http404 from django.utils.translation import gettext_lazy as _ from django.views.generic import UpdateView, TemplateView, CreateView from member.models import Membership @@ -24,9 +25,20 @@ class ProtectQuerysetMixin: Display 404 error if the user can't see an object, remove the fields the user can't update on an update form (useful if the user can't change only specified fields). """ - def get_queryset(self, **kwargs): + def get_queryset(self, filter_permissions=True, **kwargs): qs = super().get_queryset(**kwargs) - return qs.filter(PermissionBackend.filter_queryset(self.request.user, qs.model, "view")).distinct() + return qs.filter(PermissionBackend.filter_queryset(self.request.user, qs.model, "view")).distinct()\ + if filter_permissions else qs + + def get_object(self, queryset=None): + try: + return super().get_object(queryset) + except Http404 as e: + try: + super().get_object(self.get_queryset(filter_permissions=False)) + raise PermissionDenied() + except Http404: + raise e def get_form(self, form_class=None): form = super().get_form(form_class) diff --git a/apps/registration/static/registration/css/login.css b/apps/registration/static/registration/css/login.css index b789b2f7..b1bac970 100644 --- a/apps/registration/static/registration/css/login.css +++ b/apps/registration/static/registration/css/login.css @@ -16,4 +16,8 @@ Font-Awesome attribution is already done inside SVG files #login-form select { -moz-appearance: none; cursor: pointer; -} \ No newline at end of file +} + +#login-form .asteriskField { + display: none; +} diff --git a/apps/registration/templates/registration/email_validation_complete.html b/apps/registration/templates/registration/email_validation_complete.html index dca26470..11a84fe9 100644 --- a/apps/registration/templates/registration/email_validation_complete.html +++ b/apps/registration/templates/registration/email_validation_complete.html @@ -5,14 +5,29 @@ SPDX-License-Identifier: GPL-3.0-or-later {% load i18n %} {% block content %} - {% if validlink %} - {% trans "Your email have successfully been validated." %} +
+

+ {{ title }} +

+
+ {% if validlink %} +

+ {% trans "Your email have successfully been validated." %} +

{% if user_object.profile.registration_valid %} +

{% blocktrans %}You can now log in.{% endblocktrans %} +

{% else %} +

{% trans "You must pay now your membership in the Kfet to complete your registration." %} +

{% endif %} - {% else %} - {% trans "The link was invalid. The token may have expired. Please send us an email to activate your account." %} - {% endif %} + {% else %} +

+ {% trans "The link was invalid. The token may have expired. Please send us an email to activate your account." %} +

+ {% endif %} +
+
{% endblock %} diff --git a/apps/registration/templates/registration/email_validation_email_sent.html b/apps/registration/templates/registration/email_validation_email_sent.html index 627c864b..f6db4cac 100644 --- a/apps/registration/templates/registration/email_validation_email_sent.html +++ b/apps/registration/templates/registration/email_validation_email_sent.html @@ -5,13 +5,17 @@ SPDX-License-Identifier: GPL-3.0-or-later {% load i18n %} {% block content %} -

{% trans "Account activation" %}

- -

- {% trans "An email has been sent. Please click on the link to activate your account." %} -

- -

- {% trans "You must also go to the Kfet to pay your membership. The WEI registration includes the BDE membership." %} -

-{% endblock %} \ No newline at end of file +
+

+ {% trans "Account activation" %} +

+
+

+ {% trans "An email has been sent. Please click on the link to activate your account." %} +

+

+ {% trans "You must also go to the Kfet to pay your membership." %} +

+
+
+{% endblock %} diff --git a/apps/registration/templates/registration/mails/email_validation_email.html b/apps/registration/templates/registration/mails/email_validation_email.html index 0d5b41f5..40d246c9 100644 --- a/apps/registration/templates/registration/mails/email_validation_email.html +++ b/apps/registration/templates/registration/mails/email_validation_email.html @@ -27,7 +27,7 @@

- {% trans "After that, you'll have to wait that someone validates your account before you can log in. You will need to pay your membership in the Kfet. Note that the WEI registration includes the Kfet membership." %} + {% trans "After that, you'll have to wait that someone validates your account before you can log in. You will need to pay your membership in the Kfet." %}

@@ -38,4 +38,4 @@

{% trans "The Note Kfet team." %}
{% trans "Mail generated by the Note Kfet on the" %} {% now "j F Y à H:i:s" %} -

\ No newline at end of file +

diff --git a/apps/registration/templates/registration/mails/email_validation_email.txt b/apps/registration/templates/registration/mails/email_validation_email.txt index 5ce48110..7b280bb2 100644 --- a/apps/registration/templates/registration/mails/email_validation_email.txt +++ b/apps/registration/templates/registration/mails/email_validation_email.txt @@ -8,9 +8,9 @@ https://{{ domain }}{% url 'registration:email_validation' uidb64=uid token=toke {% trans "This link is only valid for a couple of days, after that you will need to contact us to validate your email." %} -{% trans "After that, you'll have to wait that someone validates your account before you can log in. You will need to pay your membership in the Kfet. Note that the WEI registration includes the Kfet membership." %} +{% trans "After that, you'll have to wait that someone validates your account before you can log in. You will need to pay your membership in the Kfet." %} {% trans "Thanks" %}, {% trans "The Note Kfet team." %} -{% trans "Mail generated by the Note Kfet on the" %} {% now "j F Y à H:i:s" %} \ No newline at end of file +{% trans "Mail generated by the Note Kfet on the" %} {% now "j F Y à H:i:s" %} diff --git a/apps/registration/tests/__init__.py b/apps/registration/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/registration/tests/test_registration.py b/apps/registration/tests/test_registration.py new file mode 100644 index 00000000..adb773f9 --- /dev/null +++ b/apps/registration/tests/test_registration.py @@ -0,0 +1,386 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib.auth.models import User +from django.db.models import Q +from django.test import TestCase +from django.urls import reverse +from django.utils.encoding import force_bytes +from django.utils.http import urlsafe_base64_encode +from member.models import Club, Membership +from note.models import NoteUser, NoteSpecial, Transaction +from registration.tokens import email_validation_token +from treasury.models import SogeCredit + +""" +Check that pre-registrations and validations are working as well. +""" + + +class TestSignup(TestCase): + """ + Assume we are a new user. + Check that it can pre-register without any problem. + """ + + fixtures = ("initial", ) + + def test_signup(self): + """ + A first year member signs up and validates its email address. + """ + response = self.client.get(reverse("registration:signup")) + self.assertEqual(response.status_code, 200) + + # Signup + response = self.client.post(reverse("registration:signup"), dict( + first_name="Toto", + last_name="TOTO", + username="toto", + email="toto@example.com", + password1="toto1234", + password2="toto1234", + phone_number="+33123456789", + department="EXT", + promotion=Club.objects.get(name="BDE").membership_start.year, + address="Earth", + paid=False, + ml_events_registration="en", + ml_sport_registration=True, + ml_art_registration=True, + )) + self.assertRedirects(response, reverse("registration:email_validation_sent"), 302, 200) + self.assertTrue(User.objects.filter(username="toto").exists()) + user = User.objects.get(username="toto") + # A preregistred user has no note + self.assertFalse(NoteUser.objects.filter(user=user).exists()) + self.assertFalse(user.profile.registration_valid) + self.assertFalse(user.profile.email_confirmed) + self.assertFalse(user.is_active) + + response = self.client.get(reverse("registration:email_validation_sent")) + self.assertEqual(response.status_code, 200) + + # Check that the email validation link is valid + token = email_validation_token.make_token(user) + uid = urlsafe_base64_encode(force_bytes(user.pk)) + response = self.client.get(reverse("registration:email_validation", kwargs=dict(uidb64=uid, token=token))) + self.assertEqual(response.status_code, 200) + user.profile.refresh_from_db() + self.assertTrue(user.profile.email_confirmed) + + # Token has expired + response = self.client.get(reverse("registration:email_validation", kwargs=dict(uidb64=uid, token=token))) + self.assertEqual(response.status_code, 400) + + # Uid does not exist + response = self.client.get(reverse("registration:email_validation", kwargs=dict(uidb64=0, token="toto"))) + self.assertEqual(response.status_code, 400) + + def test_invalid_signup(self): + """ + Send wrong data and check that it is not valid + """ + User.objects.create_superuser( + first_name="Toto", + last_name="TOTO", + username="toto", + email="toto@example.com", + password="toto1234", + ) + + # The email is already used + response = self.client.post(reverse("registration:signup"), dict( + first_name="Toto", + last_name="TOTO", + username="tôtö", + email="toto@example.com", + password1="toto1234", + password2="toto1234", + phone_number="+33123456789", + department="EXT", + promotion=Club.objects.get(name="BDE").membership_start.year, + address="Earth", + paid=False, + ml_events_registration="en", + ml_sport_registration=True, + ml_art_registration=True, + )) + self.assertTrue(response.status_code, 200) + + # The username is similar to a known alias + response = self.client.post(reverse("registration:signup"), dict( + first_name="Toto", + last_name="TOTO", + username="tôtö", + email="othertoto@example.com", + password1="toto1234", + password2="toto1234", + phone_number="+33123456789", + department="EXT", + promotion=Club.objects.get(name="BDE").membership_start.year, + address="Earth", + paid=False, + ml_events_registration="en", + ml_sport_registration=True, + ml_art_registration=True, + )) + self.assertTrue(response.status_code, 200) + + # The phone number is invalid + response = self.client.post(reverse("registration:signup"), dict( + first_name="Toto", + last_name="TOTO", + username="Ihaveanotherusername", + email="othertoto@example.com", + password1="toto1234", + password2="toto1234", + phone_number="invalid phone number", + department="EXT", + promotion=Club.objects.get(name="BDE").membership_start.year, + address="Earth", + paid=False, + ml_events_registration="en", + ml_sport_registration=True, + ml_art_registration=True, + )) + self.assertTrue(response.status_code, 200) + + +class TestValidateRegistration(TestCase): + """ + Test the admin interface to validate users + """ + + fixtures = ('initial',) + + def setUp(self) -> None: + self.superuser = User.objects.create_superuser( + username="admintoto", + password="toto1234", + email="admin.toto@example.com", + ) + self.client.force_login(self.superuser) + + self.user = User.objects.create( + username="toto", + first_name="Toto", + last_name="TOTO", + email="toto@example.com", + ) + + sess = self.client.session + sess["permission_mask"] = 42 + sess.save() + + def test_future_user_list(self): + """ + Display the list of pre-registered users + """ + response = self.client.get(reverse("registration:future_user_list")) + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("registration:future_user_list") + "?search=toto") + self.assertEqual(response.status_code, 200) + + def test_invalid_registrations(self): + """ + Send wrong data and check that errors are detected + """ + + # BDE Membership is mandatory + response = self.client.post(reverse("registration:future_user_detail", args=(self.user.pk,)), data=dict( + soge=False, + credit_type=NoteSpecial.objects.get(special_type="Chèque").id, + credit_amount=4200, + last_name="TOTO", + first_name="Toto", + bank="Société générale", + join_BDE=False, + join_Kfet=False, + )) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["form"].errors) + + # Same + response = self.client.post(reverse("registration:future_user_detail", args=(self.user.pk,)), data=dict( + soge=False, + credit_type="", + credit_amount=0, + last_name="TOTO", + first_name="Toto", + bank="Société générale", + join_BDE=False, + join_Kfet=True, + )) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["form"].errors) + + # The BDE membership is not free + response = self.client.post(reverse("registration:future_user_detail", args=(self.user.pk,)), data=dict( + soge=False, + credit_type=NoteSpecial.objects.get(special_type="Espèces").id, + credit_amount=0, + last_name="TOTO", + first_name="Toto", + bank="J'ai pas d'argent", + join_BDE=True, + join_Kfet=True, + )) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["form"].errors) + + # Last and first names are required for a credit + response = self.client.post(reverse("registration:future_user_detail", args=(self.user.pk,)), data=dict( + soge=False, + credit_type=NoteSpecial.objects.get(special_type="Chèque").id, + credit_amount=4000, + last_name="", + first_name="", + bank="", + join_BDE=True, + join_Kfet=True, + )) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["form"].errors) + + # The username admïntoto is too similar with the alias admintoto. + # Since the form is valid, the user must update its username. + self.user.username = "admïntoto" + self.user.save() + response = self.client.post(reverse("registration:future_user_detail", args=(self.user.pk,)), data=dict( + soge=False, + credit_type=NoteSpecial.objects.get(special_type="Chèque").id, + credit_amount=500, + last_name="TOTO", + first_name="Toto", + bank="Société générale", + join_BDE=True, + join_Kfet=False, + )) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["form"].errors) + + def test_validate_bde_registration(self): + """ + The user wants only to join the BDE. We validate the registration. + """ + response = self.client.get(reverse("registration:future_user_detail", args=(self.user.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.get(self.user.profile.get_absolute_url()) + self.assertEqual(response.status_code, 404) + + self.user.profile.email_confirmed = True + self.user.profile.save() + + response = self.client.post(reverse("registration:future_user_detail", args=(self.user.pk,)), data=dict( + soge=False, + credit_type=NoteSpecial.objects.get(special_type="Chèque").id, + credit_amount=500, + last_name="TOTO", + first_name="Toto", + bank="Société générale", + join_BDE=True, + join_Kfet=False, + )) + self.assertRedirects(response, self.user.profile.get_absolute_url(), 302, 200) + self.user.profile.refresh_from_db() + self.assertTrue(self.user.profile.registration_valid) + self.assertTrue(NoteUser.objects.filter(user=self.user).exists()) + self.assertTrue(Membership.objects.filter(club__name="BDE", user=self.user).exists()) + self.assertFalse(Membership.objects.filter(club__name="Kfet", user=self.user).exists()) + self.assertFalse(SogeCredit.objects.filter(user=self.user).exists()) + self.assertEqual(Transaction.objects.filter( + Q(source=self.user.note) | Q(destination=self.user.note)).count(), 2) + + response = self.client.get(self.user.profile.get_absolute_url()) + self.assertEqual(response.status_code, 200) + + def test_validate_kfet_registration(self): + """ + The user joins the BDE and the Kfet. + """ + response = self.client.get(reverse("registration:future_user_detail", args=(self.user.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.get(self.user.profile.get_absolute_url()) + self.assertEqual(response.status_code, 404) + + self.user.profile.email_confirmed = True + self.user.profile.save() + + response = self.client.post(reverse("registration:future_user_detail", args=(self.user.pk,)), data=dict( + soge=False, + credit_type=NoteSpecial.objects.get(special_type="Espèces").id, + credit_amount=4000, + last_name="TOTO", + first_name="Toto", + bank="Société générale", + join_BDE=True, + join_Kfet=True, + )) + self.assertRedirects(response, self.user.profile.get_absolute_url(), 302, 200) + self.user.profile.refresh_from_db() + self.assertTrue(self.user.profile.registration_valid) + self.assertTrue(NoteUser.objects.filter(user=self.user).exists()) + self.assertTrue(Membership.objects.filter(club__name="BDE", user=self.user).exists()) + self.assertTrue(Membership.objects.filter(club__name="Kfet", user=self.user).exists()) + self.assertFalse(SogeCredit.objects.filter(user=self.user).exists()) + self.assertEqual(Transaction.objects.filter( + Q(source=self.user.note) | Q(destination=self.user.note)).count(), 3) + + response = self.client.get(self.user.profile.get_absolute_url()) + self.assertEqual(response.status_code, 200) + + def test_validate_kfet_registration_with_soge(self): + """ + The user joins the BDE and the Kfet, but the membership is paid by the Société générale. + """ + response = self.client.get(reverse("registration:future_user_detail", args=(self.user.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.get(self.user.profile.get_absolute_url()) + self.assertEqual(response.status_code, 404) + + self.user.profile.email_confirmed = True + self.user.profile.save() + + response = self.client.post(reverse("registration:future_user_detail", args=(self.user.pk,)), data=dict( + soge=True, + credit_type=NoteSpecial.objects.get(special_type="Espèces").id, + credit_amount=4000, + last_name="TOTO", + first_name="Toto", + bank="Société générale", + join_BDE=True, + join_Kfet=True, + )) + self.assertRedirects(response, self.user.profile.get_absolute_url(), 302, 200) + self.user.profile.refresh_from_db() + self.assertTrue(self.user.profile.registration_valid) + self.assertTrue(NoteUser.objects.filter(user=self.user).exists()) + self.assertTrue(Membership.objects.filter(club__name="BDE", user=self.user).exists()) + self.assertTrue(Membership.objects.filter(club__name="Kfet", user=self.user).exists()) + self.assertTrue(SogeCredit.objects.filter(user=self.user).exists()) + self.assertEqual(Transaction.objects.filter( + Q(source=self.user.note) | Q(destination=self.user.note)).count(), 3) + self.assertFalse(Transaction.objects.filter(valid=True).exists()) + + response = self.client.get(self.user.profile.get_absolute_url()) + self.assertEqual(response.status_code, 200) + + def test_invalidate_registration(self): + """ + Try to invalidate (= delete) pre-registration. + """ + response = self.client.get(reverse("registration:future_user_invalidate", args=(self.user.pk,))) + self.assertRedirects(response, reverse("registration:future_user_list"), 302, 200) + self.assertFalse(User.objects.filter(pk=self.user.pk).exists()) + + def test_resend_email_validation_link(self): + """ + Resend email validation linK. + """ + response = self.client.get(reverse("registration:email_validation_resend", args=(self.user.pk,))) + self.assertRedirects(response, reverse("registration:future_user_detail", args=(self.user.pk,)), 302, 200) diff --git a/apps/registration/views.py b/apps/registration/views.py index bf68a8ed..1f71931e 100644 --- a/apps/registration/views.py +++ b/apps/registration/views.py @@ -16,11 +16,12 @@ from django.views.generic.edit import FormMixin from django_tables2 import SingleTableView from member.forms import ProfileForm from member.models import Membership, Club -from note.models import SpecialTransaction +from note.models import SpecialTransaction, Alias from note.templatetags.pretty_money import pretty_money from permission.backends import PermissionBackend from permission.models import Role from permission.views import ProtectQuerysetMixin +from treasury.models import SogeCredit from .forms import SignUpForm, ValidationForm from .tables import FutureUserTable @@ -101,7 +102,7 @@ class UserValidateView(TemplateView): user.profile.email_confirmed = True user.save() user.profile.save() - return self.render_to_response(self.get_context_data()) + return self.render_to_response(self.get_context_data(), status=200 if self.validlink else 400) def get_user(self, uidb64): """ @@ -169,12 +170,9 @@ class FutureUserListView(ProtectQuerysetMixin, LoginRequiredMixin, SingleTableVi :return: """ qs = super().get_queryset().distinct().filter(profile__registration_valid=False) - if "search" in self.request.GET: + if "search" in self.request.GET and self.request.GET["search"]: pattern = self.request.GET["search"] - if not pattern: - return qs.none() - qs = qs.filter( Q(first_name__iregex=pattern) | Q(last_name__iregex=pattern) @@ -205,10 +203,7 @@ class FutureUserDetailView(ProtectQuerysetMixin, LoginRequiredMixin, FormMixin, def post(self, request, *args, **kwargs): form = self.get_form() self.object = self.get_object() - if form.is_valid(): - return self.form_valid(form) - else: - return self.form_invalid(form) + return self.form_valid(form) if form.is_valid() else self.form_invalid(form) def get_queryset(self, **kwargs): """ @@ -225,6 +220,9 @@ class FutureUserDetailView(ProtectQuerysetMixin, LoginRequiredMixin, FormMixin, fee += bde.membership_fee_paid if user.profile.paid else bde.membership_fee_unpaid kfet = Club.objects.get(name="Kfet") fee += kfet.membership_fee_paid if user.profile.paid else kfet.membership_fee_unpaid + # In 2020, for COVID-19 reasons, the BDE offered 80 € to each new member that opens a Sogé account, + # since there is no WEI. + fee += 8000 ctx["total_fee"] = "{:.02f}".format(fee / 100, ) return ctx @@ -239,6 +237,10 @@ class FutureUserDetailView(ProtectQuerysetMixin, LoginRequiredMixin, FormMixin, def form_valid(self, form): user = self.get_object() + if Alias.objects.filter(normalized_name=Alias.normalize(user.username)).exists(): + form.add_error(None, _("An alias with a similar name already exists.")) + return self.form_invalid(form) + # Get form data soge = form.cleaned_data["soge"] credit_type = form.cleaned_data["credit_type"] @@ -276,9 +278,6 @@ class FutureUserDetailView(ProtectQuerysetMixin, LoginRequiredMixin, FormMixin, if credit_type is None: credit_amount = 0 - if join_Kfet and not join_BDE: - form.add_error('join_Kfet', _("You must join BDE club before joining Kfet club.")) - if fee > credit_amount and not soge: # Check if the user credits enough money form.add_error('credit_type', @@ -347,6 +346,11 @@ class FutureUserDetailView(ProtectQuerysetMixin, LoginRequiredMixin, FormMixin, membership.roles.add(Role.objects.get(name="Adhérent Kfet")) membership.save() + if soge: + soge_credit = SogeCredit.objects.get(user=user) + # Update the credit transaction amount + soge_credit.save() + return ret def get_success_url(self): diff --git a/apps/scripts b/apps/scripts index 1145f75a..7e27c3b7 160000 --- a/apps/scripts +++ b/apps/scripts @@ -1 +1 @@ -Subproject commit 1145f75a968999f24f9feb3fc82946aba14fb45d +Subproject commit 7e27c3b71b04af0867d5fbe4916e2d1278637599 diff --git a/apps/treasury/admin.py b/apps/treasury/admin.py index 1db820b2..25b4f4cb 100644 --- a/apps/treasury/admin.py +++ b/apps/treasury/admin.py @@ -24,9 +24,7 @@ class RemittanceAdmin(admin.ModelAdmin): list_display = ('remittance_type', 'date', 'comment', 'count', 'amount', 'closed', ) def has_change_permission(self, request, obj=None): - if not obj: - return True - return not obj.closed and super().has_change_permission(request, obj) + return not obj or (not obj.closed and super().has_change_permission(request, obj)) @admin.register(SogeCredit, site=admin_site) diff --git a/apps/treasury/api/views.py b/apps/treasury/api/views.py index ee97e6ac..82a0ed1e 100644 --- a/apps/treasury/api/views.py +++ b/apps/treasury/api/views.py @@ -16,7 +16,7 @@ class InvoiceViewSet(ReadProtectedModelViewSet): The djangorestframework plugin will get all `Invoice` objects, serialize it to JSON with the given serializer, then render it on /api/treasury/invoice/ """ - queryset = Invoice.objects.all() + queryset = Invoice.objects.order_by("id").all() serializer_class = InvoiceSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['bde', ] @@ -28,7 +28,7 @@ class ProductViewSet(ReadProtectedModelViewSet): The djangorestframework plugin will get all `Product` objects, serialize it to JSON with the given serializer, then render it on /api/treasury/product/ """ - queryset = Product.objects.all() + queryset = Product.objects.order_by("invoice_id", "id").all() serializer_class = ProductSerializer filter_backends = [SearchFilter] search_fields = ['$designation', ] @@ -40,7 +40,7 @@ class RemittanceTypeViewSet(ReadProtectedModelViewSet): The djangorestframework plugin will get all `RemittanceType` objects, serialize it to JSON with the given serializer then render it on /api/treasury/remittance_type/ """ - queryset = RemittanceType.objects + queryset = RemittanceType.objects.order_by("id") serializer_class = RemittanceTypeSerializer @@ -50,7 +50,7 @@ class RemittanceViewSet(ReadProtectedModelViewSet): The djangorestframework plugin will get all `Remittance` objects, serialize it to JSON with the given serializer, then render it on /api/treasury/remittance/ """ - queryset = Remittance.objects + queryset = Remittance.objects.order_by("id") serializer_class = RemittanceSerializer @@ -60,5 +60,5 @@ class SogeCreditViewSet(ReadProtectedModelViewSet): The djangorestframework plugin will get all `SogeCredit` objects, serialize it to JSON with the given serializer, then render it on /api/treasury/soge_credit/ """ - queryset = SogeCredit.objects + queryset = SogeCredit.objects.order_by("id") serializer_class = SogeCreditSerializer diff --git a/apps/treasury/forms.py b/apps/treasury/forms.py index 38da324d..c2461f76 100644 --- a/apps/treasury/forms.py +++ b/apps/treasury/forms.py @@ -16,21 +16,15 @@ class InvoiceForm(forms.ModelForm): """ def clean(self): + # If the invoice is locked, it can't be updated. if self.instance and self.instance.locked: for field_name in self.fields: self.cleaned_data[field_name] = getattr(self.instance, field_name) self.errors.clear() + self.add_error(None, _('This invoice is locked and can no longer be edited.')) return self.cleaned_data return super().clean() - def save(self, commit=True): - """ - If the invoice is locked, don't save it - """ - if not self.instance.locked: - super().save(commit) - return self.instance - class Meta: model = Invoice exclude = ('bde', 'date', 'tex', ) diff --git a/apps/treasury/migrations/0001_initial.py b/apps/treasury/migrations/0001_initial.py new file mode 100644 index 00000000..0231d293 --- /dev/null +++ b/apps/treasury/migrations/0001_initial.py @@ -0,0 +1,107 @@ +# Generated by Django 2.2.16 on 2020-09-04 21:41 + +import datetime +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('note', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Invoice', + fields=[ + ('id', models.PositiveIntegerField(primary_key=True, serialize=False, verbose_name='Invoice identifier')), + ('bde', models.CharField(choices=[('Saperlistpopette.png', 'Saper[list]popette'), ('Finalist.png', 'Fina[list]'), ('Listorique.png', '[List]orique'), ('Satellist.png', 'Satel[list]'), ('Monopolist.png', 'Monopo[list]'), ('Kataclist.png', 'Katac[list]')], default='Saperlistpopette.png', max_length=32, verbose_name='BDE')), + ('object', models.CharField(max_length=255, verbose_name='Object')), + ('description', models.TextField(verbose_name='Description')), + ('name', models.CharField(max_length=255, verbose_name='Name')), + ('address', models.TextField(verbose_name='Address')), + ('date', models.DateField(default=datetime.date.today, verbose_name='Date')), + ('acquitted', models.BooleanField(default=False, verbose_name='Acquitted')), + ('locked', models.BooleanField(default=False, help_text="An invoice can't be edited when it is locked.", verbose_name='Locked')), + ('tex', models.TextField(default='', verbose_name='tex source')), + ], + options={ + 'verbose_name': 'invoice', + 'verbose_name_plural': 'invoices', + }, + ), + migrations.CreateModel( + name='Remittance', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Date')), + ('comment', models.CharField(max_length=255, verbose_name='Comment')), + ('closed', models.BooleanField(default=False, verbose_name='Closed')), + ], + options={ + 'verbose_name': 'remittance', + 'verbose_name_plural': 'remittances', + }, + ), + migrations.CreateModel( + name='SpecialTransactionProxy', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('remittance', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='treasury.Remittance', verbose_name='Remittance')), + ('transaction', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='note.SpecialTransaction')), + ], + options={ + 'verbose_name': 'special transaction proxy', + 'verbose_name_plural': 'special transaction proxies', + }, + ), + migrations.CreateModel( + name='SogeCredit', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('credit_transaction', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='note.SpecialTransaction', verbose_name='credit transaction')), + ('transactions', models.ManyToManyField(related_name='_sogecredit_transactions_+', to='note.MembershipTransaction', verbose_name='membership transactions')), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL, verbose_name='user')), + ], + options={ + 'verbose_name': 'Credit from the Société générale', + 'verbose_name_plural': 'Credits from the Société générale', + }, + ), + migrations.CreateModel( + name='RemittanceType', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('note', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='note.NoteSpecial')), + ], + options={ + 'verbose_name': 'remittance type', + 'verbose_name_plural': 'remittance types', + }, + ), + migrations.AddField( + model_name='remittance', + name='remittance_type', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='treasury.RemittanceType', verbose_name='Type'), + ), + migrations.CreateModel( + name='Product', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('designation', models.CharField(max_length=255, verbose_name='Designation')), + ('quantity', models.PositiveIntegerField(verbose_name='Quantity')), + ('amount', models.IntegerField(verbose_name='Unit price')), + ('invoice', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='products', to='treasury.Invoice', verbose_name='invoice')), + ], + options={ + 'verbose_name': 'product', + 'verbose_name_plural': 'products', + }, + ), + ] diff --git a/apps/treasury/migrations/0002_invoice_remove_png_extension.py b/apps/treasury/migrations/0002_invoice_remove_png_extension.py new file mode 100644 index 00000000..e908d699 --- /dev/null +++ b/apps/treasury/migrations/0002_invoice_remove_png_extension.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.16 on 2020-09-06 13:43 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('treasury', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='invoice', + name='bde', + field=models.CharField(choices=[('Saperlistpopette', 'Saper[list]popette'), ('Finalist', 'Fina[list]'), ('Listorique', '[List]orique'), ('Satellist', 'Satel[list]'), ('Monopolist', 'Monopo[list]'), ('Kataclist', 'Katac[list]')], default='Saperlistpopette', max_length=32, verbose_name='BDE'), + ), + ] diff --git a/apps/treasury/models.py b/apps/treasury/models.py index 6d5b4021..d611650f 100644 --- a/apps/treasury/models.py +++ b/apps/treasury/models.py @@ -25,14 +25,14 @@ class Invoice(models.Model): bde = models.CharField( max_length=32, - default='Saperlistpopette.png', + default='Saperlistpopette', choices=( - ('Saperlistpopette.png', 'Saper[list]popette'), - ('Finalist.png', 'Fina[list]'), - ('Listorique.png', '[List]orique'), - ('Satellist.png', 'Satel[list]'), - ('Monopolist.png', 'Monopo[list]'), - ('Kataclist.png', 'Katac[list]'), + ('Saperlistpopette', 'Saper[list]popette'), + ('Finalist', 'Fina[list]'), + ('Listorique', '[List]orique'), + ('Satellist', 'Satel[list]'), + ('Monopolist', 'Monopo[list]'), + ('Kataclist', 'Katac[list]'), ), verbose_name=_("BDE"), ) @@ -85,7 +85,7 @@ class Invoice(models.Model): old_invoice = Invoice.objects.filter(id=self.id) if old_invoice.exists(): - if old_invoice.get().locked: + if old_invoice.get().locked and not self._force_save: raise ValidationError(_("This invoice is locked and can no longer be edited.")) products = self.products.all() @@ -109,6 +109,9 @@ class Invoice(models.Model): verbose_name = _("invoice") verbose_name_plural = _("invoices") + def __str__(self): + return _("Invoice #{id}").format(id=self.id) + class Product(models.Model): """ @@ -151,6 +154,9 @@ class Product(models.Model): verbose_name = _("product") verbose_name_plural = _("products") + def __str__(self): + return f"{self.designation} ({self.invoice})" + class RemittanceType(models.Model): """ @@ -224,7 +230,7 @@ class Remittance(models.Model): def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # Check if all transactions have the right type. - if self.transactions.filter(~Q(source=self.remittance_type.note)).exists(): + if self.transactions.exists() and self.transactions.filter(~Q(source=self.remittance_type.note)).exists(): raise ValidationError("All transactions in a remittance must have the same type") return super().save(force_insert, force_update, using, update_fields) @@ -256,6 +262,9 @@ class SpecialTransactionProxy(models.Model): verbose_name = _("special transaction proxy") verbose_name_plural = _("special transaction proxies") + def __str__(self): + return str(self.transaction) + class SogeCredit(models.Model): """ @@ -282,11 +291,11 @@ class SogeCredit(models.Model): @property def valid(self): - return self.credit_transaction is not None + return self.credit_transaction.valid @property def amount(self): - return sum(transaction.total for transaction in self.transactions.all()) + return sum(transaction.total for transaction in self.transactions.all()) + 8000 def invalidate(self): """ @@ -295,11 +304,7 @@ class SogeCredit(models.Model): """ if self.valid: self.credit_transaction.valid = False - self.credit_transaction._force_save = True self.credit_transaction.save() - self.credit_transaction._force_delete = True - self.credit_transaction.delete() - self.credit_transaction = None for transaction in self.transactions.all(): transaction.valid = False transaction._force_save = True @@ -312,17 +317,10 @@ class SogeCredit(models.Model): # First invalidate all transaction and delete the credit if already did (and force mode) self.invalidate() - self.credit_transaction = SpecialTransaction.objects.create( - source=NoteSpecial.objects.get(special_type="Virement bancaire"), - destination=self.user.note, - quantity=1, - amount=self.amount, - reason="Crédit société générale", - last_name=self.user.last_name, - first_name=self.user.first_name, - bank="Société générale", - created_at=self.transactions.order_by("-created_at").first().created_at, - ) + # Refresh credit amount + self.save() + self.credit_transaction.valid = True + self.credit_transaction.save() self.save() for transaction in self.transactions.all(): @@ -331,6 +329,25 @@ class SogeCredit(models.Model): transaction.created_at = timezone.now() transaction.save() + def save(self, *args, **kwargs): + if not self.credit_transaction: + self.credit_transaction = SpecialTransaction.objects.create( + source=NoteSpecial.objects.get(special_type="Virement bancaire"), + destination=self.user.note, + quantity=1, + amount=0, + reason="Crédit société générale", + last_name=self.user.last_name, + first_name=self.user.first_name, + bank="Société générale", + valid=False, + ) + elif not self.valid: + self.credit_transaction.amount = self.amount + self.credit_transaction._force_save = True + self.credit_transaction.save() + super().save(*args, **kwargs) + def delete(self, **kwargs): """ Deleting a SogeCredit is equivalent to say that the Société générale didn't pay. @@ -349,8 +366,14 @@ class SogeCredit(models.Model): transaction.valid = True transaction.created_at = timezone.now() transaction.save() + self.credit_transaction.valid = False + self.credit_transaction.reason += " (invalide)" + self.credit_transaction.save() super().delete(**kwargs) class Meta: verbose_name = _("Credit from the Société générale") verbose_name_plural = _("Credits from the Société générale") + + def __str__(self): + return _("Soge credit for {user}").format(user=str(self.user)) diff --git a/apps/treasury/signals.py b/apps/treasury/signals.py index b7038ab6..f08540d1 100644 --- a/apps/treasury/signals.py +++ b/apps/treasury/signals.py @@ -9,9 +9,10 @@ def save_special_transaction(instance, created, **kwargs): When a special transaction is created, we create its linked proxy """ - if instance.is_credit(): - if created and RemittanceType.objects.filter(note=instance.source).exists(): - SpecialTransactionProxy.objects.create(transaction=instance, remittance=None).save() - else: - if created and RemittanceType.objects.filter(note=instance.destination).exists(): - SpecialTransactionProxy.objects.create(transaction=instance, remittance=None).save() + if not hasattr(instance, "_no_signal"): + if instance.is_credit(): + if created and RemittanceType.objects.filter(note=instance.source).exists(): + SpecialTransactionProxy.objects.create(transaction=instance, remittance=None).save() + else: + if created and RemittanceType.objects.filter(note=instance.destination).exists(): + SpecialTransactionProxy.objects.create(transaction=instance, remittance=None).save() diff --git a/note_kfet/static/img/Finalist.png b/apps/treasury/static/img/Finalist.png similarity index 100% rename from note_kfet/static/img/Finalist.png rename to apps/treasury/static/img/Finalist.png diff --git a/apps/treasury/static/img/Finalist_bg.jpg b/apps/treasury/static/img/Finalist_bg.jpg new file mode 100644 index 00000000..8f1fe6c7 Binary files /dev/null and b/apps/treasury/static/img/Finalist_bg.jpg differ diff --git a/note_kfet/static/img/Kataclist.png b/apps/treasury/static/img/Kataclist.png similarity index 100% rename from note_kfet/static/img/Kataclist.png rename to apps/treasury/static/img/Kataclist.png diff --git a/apps/treasury/static/img/Kataclist_bg.jpg b/apps/treasury/static/img/Kataclist_bg.jpg new file mode 100644 index 00000000..fa3888fa Binary files /dev/null and b/apps/treasury/static/img/Kataclist_bg.jpg differ diff --git a/note_kfet/static/img/Listorique.png b/apps/treasury/static/img/Listorique.png similarity index 100% rename from note_kfet/static/img/Listorique.png rename to apps/treasury/static/img/Listorique.png diff --git a/apps/treasury/static/img/Listorique_bg.jpg b/apps/treasury/static/img/Listorique_bg.jpg new file mode 100644 index 00000000..6400da23 Binary files /dev/null and b/apps/treasury/static/img/Listorique_bg.jpg differ diff --git a/note_kfet/static/img/Monopolist.png b/apps/treasury/static/img/Monopolist.png similarity index 100% rename from note_kfet/static/img/Monopolist.png rename to apps/treasury/static/img/Monopolist.png diff --git a/apps/treasury/static/img/Monopolist_bg.jpg b/apps/treasury/static/img/Monopolist_bg.jpg new file mode 100644 index 00000000..09380801 Binary files /dev/null and b/apps/treasury/static/img/Monopolist_bg.jpg differ diff --git a/note_kfet/static/img/Saperlistpopette.png b/apps/treasury/static/img/Saperlistpopette.png similarity index 100% rename from note_kfet/static/img/Saperlistpopette.png rename to apps/treasury/static/img/Saperlistpopette.png diff --git a/apps/treasury/static/img/Saperlistpopette_bg.jpg b/apps/treasury/static/img/Saperlistpopette_bg.jpg new file mode 100644 index 00000000..b88884ac Binary files /dev/null and b/apps/treasury/static/img/Saperlistpopette_bg.jpg differ diff --git a/note_kfet/static/img/Satellist.png b/apps/treasury/static/img/Satellist.png similarity index 100% rename from note_kfet/static/img/Satellist.png rename to apps/treasury/static/img/Satellist.png diff --git a/apps/treasury/static/img/Satellist_bg.jpg b/apps/treasury/static/img/Satellist_bg.jpg new file mode 100644 index 00000000..825114f7 Binary files /dev/null and b/apps/treasury/static/img/Satellist_bg.jpg differ diff --git a/apps/treasury/tables.py b/apps/treasury/tables.py index 14044f1c..9a72ecf3 100644 --- a/apps/treasury/tables.py +++ b/apps/treasury/tables.py @@ -34,7 +34,7 @@ class InvoiceTable(tables.Table): delete = tables.LinkColumn( 'treasury:invoice_delete', - args=[A('pk')], + args=[A('id')], verbose_name=_("delete"), text=_("Delete"), attrs={ diff --git a/apps/treasury/templates/treasury/invoice_list.html b/apps/treasury/templates/treasury/invoice_list.html index 32c1b1c1..d9cd8a3e 100644 --- a/apps/treasury/templates/treasury/invoice_list.html +++ b/apps/treasury/templates/treasury/invoice_list.html @@ -8,7 +8,7 @@ SPDX-License-Identifier: GPL-3.0-or-later {% block content %}
-
+
{% trans "Invoice" %}s diff --git a/apps/treasury/templates/treasury/invoice_sample.tex b/apps/treasury/templates/treasury/invoice_sample.tex index 4e6342b0..b008aac3 100644 --- a/apps/treasury/templates/treasury/invoice_sample.tex +++ b/apps/treasury/templates/treasury/invoice_sample.tex @@ -1,19 +1,13 @@ {% load escape_tex %} +\documentclass[a4paper,11pt]{article} -\nonstopmode -\documentclass[11pt]{article} - -\usepackage[french]{babel} -\usepackage[T1]{fontenc} -\usepackage[utf8]{inputenc} -\usepackage[a4paper]{geometry} -\usepackage{units} -\usepackage{bera} +\usepackage{fontspec} +\usepackage{geometry} \usepackage{graphicx} \usepackage{fancyhdr} \usepackage{fp} -\usepackage{transparent} \usepackage{eso-pic} +\usepackage{ifthen} \def\TVA{0} % Taux de la TVA @@ -58,7 +52,7 @@ \parbox[b][\paperheight]{\paperwidth}{% \vfill \centering - {\transparent{0.1}\includegraphics[width=\textwidth]{../../static/img/{{ obj.bde }}}}% + \includegraphics[width=\textwidth]{../../apps/treasury/static/img/{{ obj.bde }}_bg.jpg} \vfill } } diff --git a/apps/treasury/templates/treasury/remittance_list.html b/apps/treasury/templates/treasury/remittance_list.html index c400f18f..8ced1ad0 100644 --- a/apps/treasury/templates/treasury/remittance_list.html +++ b/apps/treasury/templates/treasury/remittance_list.html @@ -8,7 +8,7 @@ SPDX-License-Identifier: GPL-3.0-or-later {% block content %}
-
+
{% trans "Invoice" %}s diff --git a/apps/treasury/templates/treasury/sogecredit_list.html b/apps/treasury/templates/treasury/sogecredit_list.html index c3862811..c561da72 100644 --- a/apps/treasury/templates/treasury/sogecredit_list.html +++ b/apps/treasury/templates/treasury/sogecredit_list.html @@ -8,7 +8,7 @@ SPDX-License-Identifier: GPL-3.0-or-later {% block content %}
-
+
{% trans "Invoice" %}s @@ -30,7 +30,7 @@ SPDX-License-Identifier: GPL-3.0-or-later
@@ -59,9 +59,6 @@ SPDX-License-Identifier: GPL-3.0-or-later function reloadTable() { let pattern = searchbar_obj.val(); - if (pattern === old_pattern || pattern === "") - return; - $("#credits_table").load(location.pathname + "?search=" + pattern.replace(" ", "%20") + ( invalid_only_obj.is(':checked') ? "&valid=false" : "") + " #credits_table"); diff --git a/apps/treasury/tests/__init__.py b/apps/treasury/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/treasury/tests/test_treasury.py b/apps/treasury/tests/test_treasury.py new file mode 100644 index 00000000..505453b9 --- /dev/null +++ b/apps/treasury/tests/test_treasury.py @@ -0,0 +1,401 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib.auth.models import User +from django.core.exceptions import ValidationError +from django.db.models import Q +from django.test import TestCase +from django.urls import reverse +from member.models import Membership, Club +from note.models import SpecialTransaction, NoteSpecial, Transaction +from treasury.models import Invoice, Product, Remittance, RemittanceType, SogeCredit + + +class TestInvoices(TestCase): + """ + Check that invoices can be created and rendered properly. + """ + def setUp(self) -> None: + self.user = User.objects.create_superuser( + username="admintoto", + password="totototo", + email="admin@example.com", + ) + self.client.force_login(self.user) + sess = self.client.session + sess["permission_mask"] = 42 + sess.save() + + self.invoice = Invoice.objects.create( + id=1, + object="Object", + description="Description", + name="Me", + address="Earth", + acquitted=False, + ) + self.product = Product.objects.create( + invoice=self.invoice, + designation="Product", + quantity=3, + amount=3.14, + ) + + def test_admin_page(self): + """ + Display the invoice admin page. + """ + response = self.client.get(reverse("admin:index") + "treasury/invoice/") + self.assertEqual(response.status_code, 200) + + def test_invoices_list(self): + """ + Display the list of invoices. + """ + response = self.client.get(reverse("treasury:invoice_list")) + self.assertEqual(response.status_code, 200) + + def test_invoice_create(self): + """ + Try to create a new invoice. + """ + response = self.client.get(reverse("treasury:invoice_create")) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("treasury:invoice_create"), data={ + "id": 42, + "object": "Same object", + "description": "Longer description", + "name": "Me and others", + "address": "Alwways earth", + "acquitted": True, + "products-0-designation": "Designation", + "products-0-quantity": 1, + "products-0-amount": 42, + "products-TOTAL_FORMS": 1, + "products-INITIAL_FORMS": 0, + "products-MIN_NUM_FORMS": 0, + "products-MAX_NUM_FORMS": 1000, + }) + self.assertRedirects(response, reverse("treasury:invoice_list"), 302, 200) + self.assertTrue(Invoice.objects.filter(object="Same object", id=42).exists()) + self.assertTrue(Product.objects.filter(designation="Designation", invoice_id=42).exists()) + self.assertTrue(Invoice.objects.get(id=42).tex) + + def test_invoice_update(self): + """ + Try to update an invoice. + """ + response = self.client.get(reverse("treasury:invoice_update", args=(self.invoice.id,))) + self.assertEqual(response.status_code, 200) + + data = { + "object": "Same object", + "description": "Longer description", + "name": "Me and others", + "address": "Always earth", + "acquitted": True, + "locked": True, + "products-0-designation": "Designation", + "products-0-quantity": 1, + "products-0-amount": 4200, + "products-1-designation": "Second designation", + "products-1-quantity": 5, + "products-1-amount": -1800, + "products-TOTAL_FORMS": 2, + "products-INITIAL_FORMS": 0, + "products-MIN_NUM_FORMS": 0, + "products-MAX_NUM_FORMS": 1000, + } + + response = self.client.post(reverse("treasury:invoice_update", args=(self.invoice.id,)), data=data) + self.assertRedirects(response, reverse("treasury:invoice_list"), 302, 200) + self.invoice.refresh_from_db() + self.assertTrue(Invoice.objects.filter(pk=1, object="Same object", locked=True).exists()) + self.assertTrue(Product.objects.filter(designation="Second designation", invoice_id=1).exists()) + + # Resend the same data, but the invoice is locked. + response = self.client.get(reverse("treasury:invoice_update", args=(self.invoice.id,))) + self.assertTrue(response.status_code, 200) + response = self.client.post(reverse("treasury:invoice_update", args=(self.invoice.id,)), data=data) + self.assertTrue(response.status_code, 200) + + def test_delete_invoice(self): + """ + Try to delete an invoice. + """ + response = self.client.get(reverse("treasury:invoice_delete", args=(self.invoice.id,))) + self.assertEqual(response.status_code, 200) + + # Can't delete a locked invoice + self.invoice.locked = True + self.invoice.save() + response = self.client.delete(reverse("treasury:invoice_delete", args=(self.invoice.id,))) + self.assertEqual(response.status_code, 403) + self.assertTrue(Invoice.objects.filter(pk=self.invoice.id).exists()) + + # Unlock invoice and truly delete it. + self.invoice.locked = False + self.invoice._force_save = True + self.invoice.save() + response = self.client.delete(reverse("treasury:invoice_delete", args=(self.invoice.id,))) + self.assertRedirects(response, reverse("treasury:invoice_list"), 302, 200) + self.assertFalse(Invoice.objects.filter(pk=self.invoice.id).exists()) + + def test_invoice_render_pdf(self): + """ + Generate the PDF file of an invoice. + """ + response = self.client.get(reverse("treasury:invoice_render", args=(self.invoice.id,))) + self.assertEqual(response.status_code, 200) + + def test_invoice_api(self): + """ + Load some API pages + """ + response = self.client.get("/api/treasury/invoice/") + self.assertEqual(response.status_code, 200) + response = self.client.get("/api/treasury/product/") + self.assertEqual(response.status_code, 200) + + +class TestRemittances(TestCase): + """ + Create some credits and close remittances. + """ + + fixtures = ('initial',) + + def setUp(self) -> None: + self.user = User.objects.create_superuser( + username="admintoto", + password="totototo", + email="admin@example.com", + ) + self.client.force_login(self.user) + sess = self.client.session + sess["permission_mask"] = 42 + sess.save() + + self.credit = SpecialTransaction.objects.create( + source=NoteSpecial.objects.get(special_type="Chèque"), + destination=self.user.note, + amount=4200, + reason="Credit", + last_name="TOTO", + first_name="Toto", + bank="Société générale", + ) + + self.second_credit = SpecialTransaction.objects.create( + source=self.user.note, + destination=NoteSpecial.objects.get(special_type="Chèque"), + amount=424200, + reason="Second credit", + last_name="TOTO", + first_name="Toto", + bank="Société générale", + ) + + self.remittance = Remittance.objects.create( + remittance_type=RemittanceType.objects.get(), + comment="Test remittance", + closed=False, + ) + self.credit.specialtransactionproxy.remittance = self.remittance + self.credit.specialtransactionproxy.save() + + def test_admin_page(self): + """ + Load the admin page. + """ + response = self.client.get(reverse("admin:index") + "treasury/remittance/") + self.assertEqual(response.status_code, 200) + + def test_remittances_list(self): + """ + Display the remittance list. + :return: + """ + response = self.client.get(reverse("treasury:remittance_list")) + self.assertEqual(response.status_code, 200) + + def test_remittance_create(self): + """ + Create a new Remittance. + """ + response = self.client.get(reverse("treasury:remittance_create")) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("treasury:remittance_create"), data=dict( + remittance_type=RemittanceType.objects.get().pk, + comment="Created remittance", + )) + self.assertRedirects(response, reverse("treasury:remittance_list"), 302, 200) + self.assertTrue(Remittance.objects.filter(comment="Created remittance").exists()) + + def test_remittance_update(self): + """ + Update an existing remittance. + """ + response = self.client.get(reverse("treasury:remittance_update", args=(self.remittance.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("treasury:remittance_update", args=(self.remittance.pk,)), data=dict( + comment="Updated remittance", + )) + self.assertRedirects(response, reverse("treasury:remittance_list"), 302, 200) + self.assertTrue(Remittance.objects.filter(comment="Updated remittance").exists()) + + def test_remittance_close(self): + """ + Try to close an open remittance. + """ + response = self.client.get(reverse("treasury:remittance_update", args=(self.remittance.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("treasury:remittance_update", args=(self.remittance.pk,)), data=dict( + comment="Closed remittance", + close=True, + )) + self.assertRedirects(response, reverse("treasury:remittance_list"), 302, 200) + self.assertTrue(Remittance.objects.filter(comment="Closed remittance", closed=True).exists()) + + def test_remittance_link_transaction(self): + """ + Link a transaction to an open remittance. + """ + response = self.client.get(reverse("treasury:link_transaction", args=(self.credit.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("treasury:link_transaction", args=(self.credit.pk,)), data=dict( + remittance=self.remittance.pk, + last_name="Last Name", + first_name="First Name", + bank="Bank", + )) + self.assertRedirects(response, reverse("treasury:remittance_list"), 302, 200) + self.credit.refresh_from_db() + self.assertEqual(self.credit.last_name, "Last Name") + self.assertEqual(self.remittance.transactions.count(), 1) + + response = self.client.get(reverse("treasury:unlink_transaction", args=(self.credit.pk,))) + self.assertRedirects(response, reverse("treasury:remittance_list"), 302, 200) + + def test_invoice_api(self): + """ + Load some API pages + """ + response = self.client.get("/api/treasury/remittance_type/") + self.assertEqual(response.status_code, 200) + response = self.client.get("/api/treasury/remittance/") + self.assertEqual(response.status_code, 200) + + +class TestSogeCredits(TestCase): + """ + Check that credits from the Société générale are working correctly. + """ + + fixtures = ('initial',) + + def setUp(self) -> None: + self.user = User.objects.create_superuser( + username="admintoto", + password="totototo", + email="admin@example.com", + ) + self.client.force_login(self.user) + sess = self.client.session + sess["permission_mask"] = 42 + sess.save() + + self.kfet = Club.objects.get(name="Kfet") + self.bde = self.kfet.parent_club + + self.kfet_membership = Membership( + user=self.user, + club=self.kfet, + ) + self.kfet_membership._force_renew_parent = True + self.kfet_membership._soge = True + self.kfet_membership.save() + + def test_admin_page(self): + """ + Render the admin page. + """ + response = self.client.get(reverse("admin:index") + "treasury/sogecredit/") + self.assertEqual(response.status_code, 200) + + def test_sogecredit_list(self): + """ + Display the list of all credits. + """ + response = self.client.get(reverse("treasury:soge_credits")) + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("treasury:soge_credits") + "?search=toto&valid=") + self.assertEqual(response.status_code, 200) + + def test_validate_soge_credit(self): + """ + Try to validate a credit. + """ + soge_credit = SogeCredit.objects.get(user=self.user) + + response = self.client.get(reverse("treasury:manage_soge_credit", args=(soge_credit.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("treasury:manage_soge_credit", args=(soge_credit.pk,)), data=dict( + validate=True, + )) + self.assertRedirects(response, reverse("treasury:manage_soge_credit", args=(soge_credit.pk,)), 302, 200) + soge_credit.refresh_from_db() + self.assertTrue(soge_credit.valid) + self.user.note.refresh_from_db() + self.assertEqual( + Transaction.objects.filter(Q(source=self.user.note) | Q(destination=self.user.note)).count(), 3) + self.assertTrue(self.user.profile.soge) + + def test_delete_soge_credit(self): + """ + Try to invalidate a credit. + """ + soge_credit = SogeCredit.objects.get(user=self.user) + + response = self.client.get(reverse("treasury:manage_soge_credit", args=(soge_credit.pk,))) + self.assertEqual(response.status_code, 200) + + try: + self.client.post(reverse("treasury:manage_soge_credit", args=(soge_credit.pk,)), data=dict(delete=True)) + raise AssertionError("It is not possible to delete the soge credit until the note is not credited.") + except ValidationError: + pass + + SpecialTransaction.objects.create( + source=NoteSpecial.objects.get(special_type="Carte bancaire"), + destination=self.user.note, + amount=self.bde.membership_fee_paid + self.kfet.membership_fee_paid, + quantity=1, + reason="Registration is not complete, pliz pay", + last_name="TOTO", + first_name="Toto", + ) + + response = self.client.post(reverse("treasury:manage_soge_credit", args=(soge_credit.pk,)), + data=dict(delete=True)) + # 403 because no SogeCredit exists anymore, then a PermissionDenied is raised + self.assertRedirects(response, reverse("treasury:soge_credits"), 302, 403) + self.assertFalse(SogeCredit.objects.filter(pk=soge_credit.pk)) + self.user.note.refresh_from_db() + self.assertEqual(self.user.note.balance, 0) + self.assertEqual( + Transaction.objects.filter(Q(source=self.user.note) | Q(destination=self.user.note)).count(), 4) + self.assertFalse(self.user.profile.soge) + + def test_invoice_api(self): + """ + Load some API pages + """ + response = self.client.get("/api/treasury/soge_credit/") + self.assertEqual(response.status_code, 200) diff --git a/apps/treasury/views.py b/apps/treasury/views.py index c2265289..ecefc5cf 100644 --- a/apps/treasury/views.py +++ b/apps/treasury/views.py @@ -60,6 +60,11 @@ class InvoiceCreateView(ProtectQuerysetMixin, ProtectedCreateView): return context + def get_form(self, form_class=None): + form = super().get_form(form_class) + del form.fields["locked"] + return form + def form_valid(self, form): ret = super().form_valid(form) @@ -134,6 +139,11 @@ class InvoiceUpdateView(ProtectQuerysetMixin, LoginRequiredMixin, UpdateView): return context + def get_form(self, form_class=None): + form = super().get_form(form_class) + del form.fields["id"] + return form + def form_valid(self, form): ret = super().form_valid(form) @@ -165,6 +175,11 @@ class InvoiceDeleteView(ProtectQuerysetMixin, LoginRequiredMixin, DeleteView): model = Invoice extra_context = {"title": _("Delete invoice")} + def delete(self, request, *args, **kwargs): + if self.get_object().locked: + raise PermissionDenied(_("This invoice is locked and can't be deleted.")) + return super().delete(request, *args, **kwargs) + def get_success_url(self): return reverse_lazy('treasury:invoice_list') @@ -194,7 +209,7 @@ class InvoiceRenderView(LoginRequiredMixin, View): # The file has to be rendered twice for ignored in range(2): error = subprocess.Popen( - ["pdflatex", "invoice-{}.tex".format(pk)], + ["/usr/bin/xelatex", "-interaction=nonstopmode", "invoice-{}.tex".format(pk)], cwd=tmp_dir, stdin=open(os.devnull, "r"), stderr=open(os.devnull, "wb"), @@ -202,7 +217,9 @@ class InvoiceRenderView(LoginRequiredMixin, View): ).wait() if error: - raise IOError("An error attempted while generating a invoice (code=" + str(error) + ")") + with open("{}/invoice-{:d}.log".format(tmp_dir, pk), "r") as f: + log = f.read() + raise IOError("An error attempted while generating a invoice (code=" + str(error) + ")\n\n" + log) # Display the generated pdf as a HTTP Response pdf = open("{}/invoice-{}.pdf".format(tmp_dir, pk), 'rb').read() @@ -387,7 +404,7 @@ class SogeCreditListView(LoginRequiredMixin, ProtectQuerysetMixin, SingleTableVi if not request.user.is_authenticated: return self.handle_no_permission() - if not self.get_queryset().exists(): + if not super().get_queryset().exists(): raise PermissionDenied(_("You are not able to see the treasury interface.")) return super().dispatch(request, *args, **kwargs) @@ -408,11 +425,8 @@ class SogeCreditListView(LoginRequiredMixin, ProtectQuerysetMixin, SingleTableVi | Q(user__note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) ) - if "valid" in self.request.GET: - q = Q(credit_transaction=None) - if not self.request.GET["valid"]: - q = ~q - qs = qs.filter(q) + if "valid" not in self.request.GET or not self.request.GET["valid"]: + qs = qs.filter(credit_transaction__valid=False) return qs[:20] diff --git a/apps/wei/management/commands/extract_ml_registrations.py b/apps/wei/management/commands/extract_ml_registrations.py deleted file mode 100644 index 9bc82418..00000000 --- a/apps/wei/management/commands/extract_ml_registrations.py +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay -# SPDX-License-Identifier: GPL-3.0-or-later - -from datetime import date - -from django.core.management import BaseCommand -from django.db.models import Q -from member.models import Membership, Club -from wei.models import WEIClub - - -class Command(BaseCommand): - help = "Get mailing list registrations from the last wei. " \ - "Usage: manage.py extract_ml_registrations -t {events,art,sport}. " \ - "You can write this into a file with a pipe, then paste the document into your mail manager." - - def add_arguments(self, parser): - parser.add_argument('--type', '-t', choices=["members", "clubs", "events", "art", "sport"], default="members", - help='Select the type of the mailing list (default members)') - parser.add_argument('--year', '-y', type=int, default=None, - help='Select the year of the concerned WEI. Default: last year') - - def handle(self, *args, **options): - ########################################################### - # WARNING # - ########################################################### - # - # This code is obsolete. - # TODO: Improve the mailing list extraction system, and link it automatically with Mailman. - - if options["type"] == "members": - for membership in Membership.objects.filter( - club__name="BDE", - date_start__lte=date.today(), - date_end__gte=date.today(), - ).all(): - self.stdout.write(membership.user.email) - return - - if options["type"] == "clubs": - for club in Club.objects.all(): - self.stdout.write(club.email) - return - - if options["year"] is None: - wei = WEIClub.objects.order_by('-year').first() - else: - wei = WEIClub.objects.filter(year=options["year"]) - if wei.exists(): - wei = wei.get() - else: - wei = WEIClub.objects.order_by('-year').first() - self.stderr.write(self.style.WARNING("Warning: there was no WEI in year " + str(options["year"]) + ". " - + "Assuming the last WEI (year " + str(wei.year) + ")")) - q = Q(ml_events_registration=True) if options["type"] == "events" else Q(ml_art_registration=True)\ - if options["type"] == "art" else Q(ml_sport_registration=True) - registrations = wei.users.filter(q) - for registration in registrations.all(): - self.stdout.write(registration.user.email) diff --git a/apps/wei/migrations/0001_initial.py b/apps/wei/migrations/0001_initial.py new file mode 100644 index 00000000..0ad73fab --- /dev/null +++ b/apps/wei/migrations/0001_initial.py @@ -0,0 +1,120 @@ +# Generated by Django 2.2.16 on 2020-09-04 21:41 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import phonenumber_field.modelfields + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('permission', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('member', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Bus', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, verbose_name='name')), + ('description', models.TextField(blank=True, default='', verbose_name='description')), + ('information_json', models.TextField(default='{}', help_text='Information about the survey for new members, encoded in JSON', verbose_name='survey information')), + ], + options={ + 'verbose_name': 'Bus', + 'verbose_name_plural': 'Buses', + }, + ), + migrations.CreateModel( + name='BusTeam', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, verbose_name='name')), + ('color', models.PositiveIntegerField(help_text='The color of the T-Shirt, stored with its number equivalent', verbose_name='color')), + ('description', models.TextField(blank=True, default='', verbose_name='description')), + ('bus', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='teams', to='wei.Bus', verbose_name='bus')), + ], + options={ + 'verbose_name': 'Bus team', + 'verbose_name_plural': 'Bus teams', + 'unique_together': {('bus', 'name')}, + }, + ), + migrations.CreateModel( + name='WEIClub', + fields=[ + ('club_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='member.Club')), + ('year', models.PositiveIntegerField(default=2020, unique=True, verbose_name='year')), + ('date_start', models.DateField(verbose_name='date start')), + ('date_end', models.DateField(verbose_name='date end')), + ], + options={ + 'verbose_name': 'WEI', + 'verbose_name_plural': 'WEI', + }, + bases=('member.club',), + ), + migrations.CreateModel( + name='WEIRole', + fields=[ + ('role_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='permission.Role')), + ], + options={ + 'verbose_name': 'WEI Role', + 'verbose_name_plural': 'WEI Roles', + }, + bases=('permission.role',), + ), + migrations.CreateModel( + name='WEIRegistration', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('soge_credit', models.BooleanField(default=False, verbose_name='Credit from Société générale')), + ('caution_check', models.BooleanField(default=False, verbose_name='Caution check given')), + ('birth_date', models.DateField(verbose_name='birth date')), + ('gender', models.CharField(choices=[('male', 'Male'), ('female', 'Female'), ('nonbinary', 'Non binary')], max_length=16, verbose_name='gender')), + ('clothing_cut', models.CharField(choices=[('male', 'Male'), ('female', 'Female')], max_length=16, verbose_name='clothing cut')), + ('clothing_size', models.CharField(choices=[('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ('XXL', 'XXL')], max_length=4, verbose_name='clothing size')), + ('health_issues', models.TextField(blank=True, default='', verbose_name='health issues')), + ('emergency_contact_name', models.CharField(max_length=255, verbose_name='emergency contact name')), + ('emergency_contact_phone', phonenumber_field.modelfields.PhoneNumberField(max_length=32, region=None, verbose_name='emergency contact phone')), + ('first_year', models.BooleanField(default=False, help_text='Tells if the user is new in the school.', verbose_name='first year')), + ('information_json', models.TextField(default='{}', help_text='Information about the registration (buses for old members, survey fot the new members), encoded in JSON', verbose_name='registration information')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='wei', to=settings.AUTH_USER_MODEL, verbose_name='user')), + ('wei', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='users', to='wei.WEIClub', verbose_name='WEI')), + ], + options={ + 'verbose_name': 'WEI User', + 'verbose_name_plural': 'WEI Users', + 'unique_together': {('user', 'wei')}, + }, + ), + migrations.CreateModel( + name='WEIMembership', + fields=[ + ('membership_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='member.Membership')), + ('bus', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='memberships', to='wei.Bus', verbose_name='bus')), + ('registration', models.OneToOneField(blank=True, default=None, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='membership', to='wei.WEIRegistration', verbose_name='WEI registration')), + ('team', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='memberships', to='wei.BusTeam', verbose_name='team')), + ], + options={ + 'verbose_name': 'WEI membership', + 'verbose_name_plural': 'WEI memberships', + }, + bases=('member.membership',), + ), + migrations.AddField( + model_name='bus', + name='wei', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='buses', to='wei.WEIClub', verbose_name='WEI'), + ), + migrations.AlterUniqueTogether( + name='bus', + unique_together={('wei', 'name')}, + ), + ] diff --git a/apps/wei/templates/wei/weilist_sample.tex b/apps/wei/templates/wei/weilist_sample.tex index 1ab3b76d..f1b7fbd4 100644 --- a/apps/wei/templates/wei/weilist_sample.tex +++ b/apps/wei/templates/wei/weilist_sample.tex @@ -1,15 +1,11 @@ -\documentclass[landscape,10pt]{article} - -\usepackage[utf8]{inputenc} -\usepackage[T1]{fontenc} -\usepackage[french]{babel} +\documentclass[a4paper,landscape,10pt]{article} +\usepackage{fontspec} \usepackage[margin=1.5cm]{geometry} -\usepackage{lmodern} \begin{document} \begin{center} -\huge{Liste des inscrits \og {{ wei.name }} \fg{}} +\huge{Liste des inscrits « {{ wei.name }} »} {% if bus %} \LARGE{Bus {{ bus.name|safe }}} diff --git a/apps/wei/tests/test_wei_registration.py b/apps/wei/tests/test_wei_registration.py index 1e9036f0..6d294bdd 100644 --- a/apps/wei/tests/test_wei_registration.py +++ b/apps/wei/tests/test_wei_registration.py @@ -690,7 +690,7 @@ class TestWEIRegistration(TestCase): """ with open("/dev/null", "wb") as devnull: return subprocess.call( - ["which", "pdflatex"], + ["/usr/bin/which", "xelatex"], stdout=devnull, stderr=devnull, ) == 0 diff --git a/apps/wei/views.py b/apps/wei/views.py index 358cb14a..8246bebf 100644 --- a/apps/wei/views.py +++ b/apps/wei/views.py @@ -1103,14 +1103,16 @@ class MemberListRenderView(LoginRequiredMixin, View): with open(os.devnull, "wb") as devnull: error = subprocess.Popen( - ["pdflatex", "{}/wei-list.tex".format(tmp_dir)], + ["/usr/bin/xelatex", "-interaction=nonstopmode", "{}/wei-list.tex".format(tmp_dir)], cwd=tmp_dir, stderr=devnull, stdout=devnull, ).wait() if error: - raise IOError("An error attempted while generating a WEI list (code=" + str(error) + ")") + with open("{}/wei-list.log".format(tmp_dir), "r") as f: + log = f.read() + raise IOError("An error attempted while generating a WEI list (code=" + str(error) + ")\n\n" + log) # Display the generated pdf as a HTTP Response with open("{}/wei-list.pdf".format(tmp_dir), 'rb') as f: diff --git a/entrypoint.sh b/entrypoint.sh index ab33fbe8..dfd68977 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -14,7 +14,6 @@ fi # Set up Django project python3 manage.py collectstatic --noinput python3 manage.py compilemessages -python3 manage.py makemigrations python3 manage.py migrate if [ "$1" ]; then diff --git a/locale/de/LC_MESSAGES/django.po b/locale/de/LC_MESSAGES/django.po index 1f5c0403..3891a934 100644 --- a/locale/de/LC_MESSAGES/django.po +++ b/locale/de/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2020-09-02 23:17+0200\n" +"POT-Creation-Date: 2020-09-07 19:43+0200\n" "PO-Revision-Date: 2020-09-03 23:47+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -18,42 +18,42 @@ msgstr "" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Generator: Poedit 2.3\n" -#: apps/activity/apps.py:10 apps/activity/models.py:145 -#: apps/activity/models.py:161 +#: apps/activity/apps.py:10 apps/activity/models.py:150 +#: apps/activity/models.py:166 msgid "activity" msgstr "Veranstaltung" -#: apps/activity/forms.py:35 apps/activity/models.py:130 +#: apps/activity/forms.py:35 apps/activity/models.py:131 msgid "The end date must be after the start date." msgstr "Das Abschlussdatum muss nach das Anfangsdatum sein." -#: apps/activity/forms.py:76 apps/activity/models.py:257 +#: apps/activity/forms.py:76 apps/activity/models.py:268 msgid "You can't invite someone once the activity is started." msgstr "" "Sie dürfen nicht jemandem einladen wenn die Veranstaltung angefangen hat." -#: apps/activity/forms.py:79 apps/activity/models.py:260 +#: apps/activity/forms.py:79 apps/activity/models.py:271 msgid "This activity is not validated yet." msgstr "Diese Veranstaltung ist noch nicht bestätigt." -#: apps/activity/forms.py:89 apps/activity/models.py:268 +#: apps/activity/forms.py:89 apps/activity/models.py:279 msgid "This person has been already invited 5 times this year." msgstr "Diese Person wurde schon 5 mal dieses Jahr eingeladen." -#: apps/activity/forms.py:93 apps/activity/models.py:272 +#: apps/activity/forms.py:93 apps/activity/models.py:283 msgid "This person is already invited." msgstr "Diese Person wurde schon eingeladen." -#: apps/activity/forms.py:97 apps/activity/models.py:276 +#: apps/activity/forms.py:97 apps/activity/models.py:287 msgid "You can't invite more than 3 people to this activity." msgstr "Sie dürfen höchstens 3 Leute zu dieser Veranstaltung einladen." -#: apps/activity/models.py:27 apps/activity/models.py:62 -#: apps/member/models.py:198 +#: apps/activity/models.py:28 apps/activity/models.py:63 +#: apps/member/models.py:199 #: apps/member/templates/member/includes/club_info.html:4 #: apps/member/templates/member/includes/profile_info.html:4 -#: apps/note/models/notes.py:247 apps/note/models/transactions.py:26 -#: apps/note/models/transactions.py:46 apps/note/models/transactions.py:302 +#: apps/note/models/notes.py:253 apps/note/models/transactions.py:26 +#: apps/note/models/transactions.py:46 apps/note/models/transactions.py:296 #: apps/permission/models.py:329 #: apps/registration/templates/registration/future_profile_detail.html:16 #: apps/wei/models.py:66 apps/wei/models.py:118 @@ -62,161 +62,171 @@ msgstr "Sie dürfen höchstens 3 Leute zu dieser Veranstaltung einladen." msgid "name" msgstr "Name" -#: apps/activity/models.py:32 +#: apps/activity/models.py:33 msgid "manage entries" msgstr "Einträge verwalten" -#: apps/activity/models.py:33 +#: apps/activity/models.py:34 msgid "Enable the support of entries for this activity." msgstr "Aktivieren Sie die Eintrittmöglichkeit für diese Aktivität." -#: apps/activity/models.py:38 +#: apps/activity/models.py:39 #: apps/activity/templates/activity/includes/activity_info.html:42 msgid "can invite" msgstr "Darf einladen" -#: apps/activity/models.py:43 +#: apps/activity/models.py:44 #: apps/activity/templates/activity/includes/activity_info.html:46 msgid "guest entry fee" msgstr "Gasteintrittspreis" -#: apps/activity/models.py:48 +#: apps/activity/models.py:49 msgid "activity type" msgstr "Veranstaltungart" -#: apps/activity/models.py:49 +#: apps/activity/models.py:50 msgid "activity types" msgstr "Vearnstaltungarte" -#: apps/activity/models.py:67 +#: apps/activity/models.py:68 #: apps/activity/templates/activity/includes/activity_info.html:19 #: apps/note/models/transactions.py:81 apps/permission/models.py:110 #: apps/permission/models.py:189 apps/wei/models.py:72 apps/wei/models.py:129 msgid "description" msgstr "Beschreibung" -#: apps/activity/models.py:71 +#: apps/activity/models.py:72 msgid "location" msgstr "Ort" -#: apps/activity/models.py:75 +#: apps/activity/models.py:76 msgid "Place where the activity is organized, eg. Kfet." msgstr "Wo findet die Veranstaltung statt ? (z.B Kfet)" -#: apps/activity/models.py:82 +#: apps/activity/models.py:83 #: apps/activity/templates/activity/includes/activity_info.html:22 -#: apps/note/models/notes.py:223 apps/note/models/transactions.py:66 +#: apps/note/models/notes.py:229 apps/note/models/transactions.py:66 #: apps/permission/models.py:164 msgid "type" msgstr "Type" -#: apps/activity/models.py:88 apps/logs/models.py:22 apps/member/models.py:303 -#: apps/note/models/notes.py:138 apps/treasury/models.py:267 +#: apps/activity/models.py:89 apps/logs/models.py:22 apps/member/models.py:304 +#: apps/note/models/notes.py:144 apps/treasury/models.py:276 #: apps/treasury/templates/treasury/sogecredit_detail.html:14 #: apps/wei/models.py:160 apps/wei/templates/wei/survey.html:15 msgid "user" msgstr "User" -#: apps/activity/models.py:95 +#: apps/activity/models.py:96 #: apps/activity/templates/activity/includes/activity_info.html:36 msgid "organizer" msgstr "Veranstalter" -#: apps/activity/models.py:96 +#: apps/activity/models.py:97 msgid "Club that organizes the activity. The entry fees will go to this club." msgstr "" "Die Veranstaltung wurde von einem Club organisert. Die Eintrittsbeiträge " "gehen an diesen Club." -#: apps/activity/models.py:103 +#: apps/activity/models.py:104 #: apps/activity/templates/activity/includes/activity_info.html:39 msgid "attendees club" msgstr "Teilnehmer" -#: apps/activity/models.py:104 +#: apps/activity/models.py:105 msgid "Club that is authorized to join the activity. Mostly the Kfet club." msgstr "Club die an die Veranstaltung teilnehmen können." -#: apps/activity/models.py:108 +#: apps/activity/models.py:109 #: apps/activity/templates/activity/includes/activity_info.html:25 msgid "start date" msgstr "Anfangsdatum" -#: apps/activity/models.py:112 +#: apps/activity/models.py:113 #: apps/activity/templates/activity/includes/activity_info.html:28 msgid "end date" msgstr "Abschlussdatum" -#: apps/activity/models.py:117 +#: apps/activity/models.py:118 #: apps/activity/templates/activity/includes/activity_info.html:50 -#: apps/note/models/transactions.py:146 +#: apps/note/models/transactions.py:149 msgid "valid" msgstr "gültig" -#: apps/activity/models.py:122 +#: apps/activity/models.py:123 #: apps/activity/templates/activity/includes/activity_info.html:65 msgid "open" msgstr "geöffnet" -#: apps/activity/models.py:146 +#: apps/activity/models.py:151 msgid "activities" msgstr "Veranstaltungen" -#: apps/activity/models.py:166 +#: apps/activity/models.py:171 msgid "entry time" msgstr "Eintrittzeit" -#: apps/activity/models.py:172 apps/note/apps.py:14 +#: apps/activity/models.py:177 apps/note/apps.py:14 #: apps/note/models/notes.py:78 msgid "note" msgstr "Note" -#: apps/activity/models.py:183 +#: apps/activity/models.py:188 #: apps/activity/templates/activity/activity_entry.html:46 msgid "entry" msgstr "Eintritt" -#: apps/activity/models.py:184 +#: apps/activity/models.py:189 #: apps/activity/templates/activity/activity_entry.html:46 msgid "entries" msgstr "Eintritte" -#: apps/activity/models.py:190 +#: apps/activity/models.py:192 +#, python-brace-format +msgid "Entry for {guest}, invited by {note} to the activity {activity}" +msgstr "Eintritt für {guest}, von {note} zur Vanstaltung {activity} eingeladen" + +#: apps/activity/models.py:194 +#, python-brace-format +msgid "Entry for {note} to the activity {activity}" +msgstr "Eintritt von {note} zur Veranstaltung {activity}" + +#: apps/activity/models.py:201 msgid "Already entered on " msgstr "Schon eingetretten " -#: apps/activity/models.py:190 apps/activity/tables.py:54 +#: apps/activity/models.py:201 apps/activity/tables.py:54 msgid "{:%Y-%m-%d %H:%M:%S}" msgstr "{:%Y-%m-%d %H:%M:%S}" -#: apps/activity/models.py:198 +#: apps/activity/models.py:209 msgid "The balance is negative." msgstr "Kontostand ist im Rot." -#: apps/activity/models.py:228 +#: apps/activity/models.py:239 msgid "last name" msgstr "Nachname" -#: apps/activity/models.py:233 +#: apps/activity/models.py:244 #: apps/member/templates/member/includes/profile_info.html:4 #: apps/registration/templates/registration/future_profile_detail.html:16 #: apps/wei/templates/wei/weimembership_form.html:14 msgid "first name" msgstr "Vorname" -#: apps/activity/models.py:240 +#: apps/activity/models.py:251 msgid "inviter" msgstr "Einlader" -#: apps/activity/models.py:284 +#: apps/activity/models.py:295 msgid "guest" msgstr "Gast" -#: apps/activity/models.py:285 +#: apps/activity/models.py:296 msgid "guests" msgstr "Gäste" -#: apps/activity/models.py:297 +#: apps/activity/models.py:308 msgid "Invitation" msgstr "Einladung" @@ -240,19 +250,19 @@ msgstr "Eingetreten um " msgid "remove" msgstr "entfernen" -#: apps/activity/tables.py:80 apps/note/forms.py:68 apps/treasury/models.py:186 +#: apps/activity/tables.py:80 apps/note/forms.py:68 apps/treasury/models.py:192 msgid "Type" msgstr "Type" -#: apps/activity/tables.py:82 apps/member/forms.py:131 -#: apps/registration/forms.py:81 apps/treasury/forms.py:135 +#: apps/activity/tables.py:82 apps/member/forms.py:183 +#: apps/registration/forms.py:81 apps/treasury/forms.py:129 #: apps/wei/forms/registration.py:96 msgid "Last name" msgstr "Nachname" -#: apps/activity/tables.py:84 apps/member/forms.py:136 +#: apps/activity/tables.py:84 apps/member/forms.py:188 #: apps/note/templates/note/transaction_form.html:134 -#: apps/registration/forms.py:86 apps/treasury/forms.py:137 +#: apps/registration/forms.py:86 apps/treasury/forms.py:131 #: apps/wei/forms/registration.py:101 msgid "First name" msgstr "Vorname" @@ -270,21 +280,21 @@ msgid "Guests list" msgstr "Gastliste" #: apps/activity/templates/activity/activity_entry.html:14 -#: apps/note/models/transactions.py:259 +#: apps/note/models/transactions.py:253 #: apps/note/templates/note/transaction_form.html:16 #: apps/note/templates/note/transaction_form.html:148 -#: note_kfet/templates/base.html:68 +#: note_kfet/templates/base.html:70 msgid "Transfer" msgstr "Überweisen" #: apps/activity/templates/activity/activity_entry.html:18 -#: apps/note/models/transactions.py:318 +#: apps/note/models/transactions.py:312 #: apps/note/templates/note/transaction_form.html:21 msgid "Credit" msgstr "Kredit" #: apps/activity/templates/activity/activity_entry.html:21 -#: apps/note/models/transactions.py:318 +#: apps/note/models/transactions.py:312 #: apps/note/templates/note/transaction_form.html:25 msgid "Debit" msgstr "Soll" @@ -302,7 +312,7 @@ msgstr "Zurück zur Veranstaltungseite" #: apps/member/templates/member/add_members.html:32 #: apps/member/templates/member/club_form.html:16 #: apps/note/templates/note/transactiontemplate_form.html:18 -#: apps/treasury/forms.py:93 apps/treasury/forms.py:147 +#: apps/treasury/forms.py:87 apps/treasury/forms.py:141 #: apps/treasury/templates/treasury/invoice_form.html:74 #: apps/wei/templates/wei/bus_form.html:17 #: apps/wei/templates/wei/busteam_form.html:17 @@ -356,7 +366,7 @@ msgid "validate" msgstr "validate" #: apps/activity/templates/activity/includes/activity_info.html:71 -#: apps/logs/models.py:62 apps/note/tables.py:162 +#: apps/logs/models.py:64 apps/note/tables.py:195 msgid "edit" msgstr "bearbeiten" @@ -364,39 +374,39 @@ msgstr "bearbeiten" msgid "Invite" msgstr "Einladen" -#: apps/activity/views.py:29 +#: apps/activity/views.py:33 msgid "Create new activity" msgstr "Neue Veranstaltung schaffen" -#: apps/activity/views.py:59 note_kfet/templates/base.html:86 +#: apps/activity/views.py:63 note_kfet/templates/base.html:88 msgid "Activities" msgstr "Veranstaltungen" -#: apps/activity/views.py:87 +#: apps/activity/views.py:91 msgid "Activity detail" msgstr "Veranstaltunginfo" -#: apps/activity/views.py:107 +#: apps/activity/views.py:111 msgid "Update activity" msgstr "Veranstaltung bearbeiten" -#: apps/activity/views.py:134 +#: apps/activity/views.py:138 msgid "Invite guest to the activity \"{}\"" msgstr "Gast zur Veranstaltung \"{}\" einladen" -#: apps/activity/views.py:168 +#: apps/activity/views.py:172 msgid "You are not allowed to display the entry interface for this activity." msgstr "Sie haben nicht das Recht diese Seite zu benuzten." -#: apps/activity/views.py:171 +#: apps/activity/views.py:175 msgid "This activity does not support activity entries." msgstr "Diese Veranstaltung braucht nicht Eintritt." -#: apps/activity/views.py:174 +#: apps/activity/views.py:178 msgid "This activity is closed." msgstr "Diese Veranstaltung ist geschlossen." -#: apps/activity/views.py:272 +#: apps/activity/views.py:274 msgid "Entry for activity \"{}\"" msgstr "Eintritt zur Veranstaltung \"{}\"" @@ -420,59 +430,64 @@ msgstr "Model" msgid "identifier" msgstr "Kennzeichnung" -#: apps/logs/models.py:48 +#: apps/logs/models.py:49 msgid "previous data" msgstr "ehemalige Daten" -#: apps/logs/models.py:53 +#: apps/logs/models.py:55 msgid "new data" msgstr "neue Daten" -#: apps/logs/models.py:61 +#: apps/logs/models.py:63 msgid "create" msgstr "schaffen" -#: apps/logs/models.py:63 apps/note/tables.py:132 apps/note/tables.py:168 +#: apps/logs/models.py:65 apps/note/tables.py:165 apps/note/tables.py:201 #: apps/permission/models.py:127 apps/treasury/tables.py:38 #: apps/wei/tables.py:75 msgid "delete" msgstr "entfernen" -#: apps/logs/models.py:66 +#: apps/logs/models.py:68 msgid "action" msgstr "Aktion" -#: apps/logs/models.py:74 +#: apps/logs/models.py:76 msgid "timestamp" msgstr "Zeitstempel" -#: apps/logs/models.py:78 +#: apps/logs/models.py:80 msgid "Logs cannot be destroyed." msgstr "Logs können nicht entfernen sein." -#: apps/logs/models.py:81 +#: apps/logs/models.py:83 msgid "changelog" msgstr "Changelog" -#: apps/logs/models.py:82 +#: apps/logs/models.py:84 msgid "changelogs" msgstr "Changelogs" -#: apps/member/admin.py:52 apps/member/models.py:225 +#: apps/logs/models.py:87 +#, python-brace-format +msgid "Changelog of type \"{action}\" for model {model} at {timestamp}" +msgstr "Changelog \"{action}\" für Model {model} an {timestamp}" + +#: apps/member/admin.py:50 apps/member/models.py:226 #: apps/member/templates/member/includes/club_info.html:34 msgid "membership fee (paid students)" msgstr "Mitgliedschaftpreis (bezahlte Studenten)" -#: apps/member/admin.py:53 apps/member/models.py:230 +#: apps/member/admin.py:51 apps/member/models.py:231 #: apps/member/templates/member/includes/club_info.html:37 msgid "membership fee (unpaid students)" msgstr "Mitgliedschaftpreis (unbezahlte Studenten)" -#: apps/member/admin.py:67 apps/member/models.py:314 +#: apps/member/admin.py:65 apps/member/models.py:315 msgid "roles" msgstr "Rollen" -#: apps/member/admin.py:68 apps/member/models.py:328 +#: apps/member/admin.py:66 apps/member/models.py:329 msgid "fee" msgstr "Preis" @@ -480,69 +495,77 @@ msgstr "Preis" msgid "member" msgstr "Mitglied" -#: apps/member/forms.py:41 +#: apps/member/forms.py:23 +msgid "Permission mask" +msgstr "Berechtigungsmaske" + +#: apps/member/forms.py:45 msgid "Report frequency" msgstr "Bericht Frequenz" -#: apps/member/forms.py:43 +#: apps/member/forms.py:47 msgid "Last report date" msgstr "Letzen Bericht Datum" -#: apps/member/forms.py:48 +#: apps/member/forms.py:52 msgid "You can't register to the note if you come from the future." msgstr "Sie dürfen nicht einloggen wenn sie aus der Zukunft kommen." -#: apps/member/forms.py:73 +#: apps/member/forms.py:77 msgid "select an image" msgstr "Wählen sie ein Bild aus" -#: apps/member/forms.py:74 +#: apps/member/forms.py:78 msgid "Maximal size: 2MB" msgstr "Maximal Größe: 2MB" -#: apps/member/forms.py:87 apps/member/views.py:101 -#: apps/registration/forms.py:33 +#: apps/member/forms.py:103 +msgid "This image cannot be loaded." +msgstr "Dieses Bild kann nicht geladen werden." + +#: apps/member/forms.py:139 apps/member/views.py:98 +#: apps/registration/forms.py:33 apps/registration/views.py:237 msgid "An alias with a similar name already exists." msgstr "Ein ähnliches Alias ist schon benutzt." -#: apps/member/forms.py:110 apps/registration/forms.py:61 +#: apps/member/forms.py:162 apps/registration/forms.py:61 msgid "Inscription paid by Société Générale" msgstr "Mitgliedschaft von der Société Générale bezahlt" -#: apps/member/forms.py:112 apps/registration/forms.py:63 +#: apps/member/forms.py:164 apps/registration/forms.py:63 msgid "Check this case is the Société Générale paid the inscription." msgstr "Die Société Générale die Mitgliedschaft bezahlt." -#: apps/member/forms.py:117 apps/registration/forms.py:68 +#: apps/member/forms.py:169 apps/registration/forms.py:68 #: apps/wei/forms/registration.py:83 msgid "Credit type" msgstr "Kredittype" -#: apps/member/forms.py:118 apps/registration/forms.py:69 +#: apps/member/forms.py:170 apps/registration/forms.py:69 #: apps/wei/forms/registration.py:84 msgid "No credit" msgstr "Kein Kredit" -#: apps/member/forms.py:120 +#: apps/member/forms.py:172 msgid "You can credit the note of the user." msgstr "Sie dûrfen diese Note kreditieren." -#: apps/member/forms.py:124 apps/registration/forms.py:74 +#: apps/member/forms.py:176 apps/registration/forms.py:74 #: apps/wei/forms/registration.py:89 msgid "Credit amount" msgstr "Kreditanzahl" -#: apps/member/forms.py:141 apps/note/templates/note/transaction_form.html:140 -#: apps/registration/forms.py:91 apps/treasury/forms.py:139 +#: apps/member/forms.py:193 apps/note/templates/note/transaction_form.html:140 +#: apps/registration/forms.py:91 apps/treasury/forms.py:133 #: apps/wei/forms/registration.py:106 msgid "Bank" msgstr "Bank" -#: apps/member/forms.py:168 +#: apps/member/forms.py:220 msgid "User" msgstr "User" -#: apps/member/forms.py:182 +#: apps/member/forms.py:234 msgid "Roles" msgstr "Rollen" @@ -658,19 +681,19 @@ msgstr "bezahlt" msgid "Tells if the user receive a salary." msgstr "User ist bezahlt." -#: apps/member/models.py:101 apps/treasury/tables.py:146 +#: apps/member/models.py:100 apps/treasury/tables.py:146 msgid "No" msgstr "Nein" -#: apps/member/models.py:102 +#: apps/member/models.py:101 msgid "Yes (receive them in french)" msgstr "Ja (auf Fränzosich)" -#: apps/member/models.py:103 +#: apps/member/models.py:102 msgid "Yes (receive them in english)" msgstr "Ja (auf English)" -#: apps/member/models.py:105 +#: apps/member/models.py:104 msgid "" "Register on the mailing list to stay informed of the events of the campus (1 " "mail/week)" @@ -678,7 +701,7 @@ msgstr "" "Melden Sie sich auf der Mailingliste an, um über die Ereignisse des Campus " "informiert zu bleiben (1 Mail / Woche)" -#: apps/member/models.py:110 +#: apps/member/models.py:109 msgid "" "Register on the mailing list to stay informed of the sport events of the " "campus (1 mail/week)" @@ -686,7 +709,7 @@ msgstr "" "Melden Sie sich auf der Mailingliste an, um über die Sportereignisse des " "Campus informiert zu bleiben (1 Mail / Woche)" -#: apps/member/models.py:115 +#: apps/member/models.py:114 msgid "" "Register on the mailing list to stay informed of the art events of the " "campus (1 mail/week)" @@ -694,31 +717,31 @@ msgstr "" "Melden Sie sich auf der Mailingliste an, um über die Kunstereignisse des " "Campus informiert zu bleiben (1 Mail / Woche)" -#: apps/member/models.py:119 +#: apps/member/models.py:118 msgid "report frequency (in days)" msgstr "Bericht Frequenz (Tagen)" -#: apps/member/models.py:124 +#: apps/member/models.py:123 msgid "last report date" msgstr "letzen Bericht Datum" -#: apps/member/models.py:129 +#: apps/member/models.py:128 msgid "email confirmed" msgstr "email bestätigt" -#: apps/member/models.py:134 +#: apps/member/models.py:133 msgid "registration valid" msgstr "Anmeldung gültig" -#: apps/member/models.py:163 apps/member/models.py:164 +#: apps/member/models.py:162 apps/member/models.py:163 msgid "user profile" msgstr "Userprofile" -#: apps/member/models.py:174 +#: apps/member/models.py:173 msgid "Activate your Note Kfet account" msgstr "Ihre Note Kfet Konto bestätigen" -#: apps/member/models.py:203 +#: apps/member/models.py:204 #: apps/member/templates/member/includes/club_info.html:55 #: apps/member/templates/member/includes/profile_info.html:31 #: apps/registration/templates/registration/future_profile_detail.html:22 @@ -727,88 +750,88 @@ msgstr "Ihre Note Kfet Konto bestätigen" msgid "email" msgstr "Email" -#: apps/member/models.py:210 +#: apps/member/models.py:211 msgid "parent club" msgstr "Urclub" -#: apps/member/models.py:219 +#: apps/member/models.py:220 msgid "require memberships" msgstr "erfordern Mitgliedschaft" -#: apps/member/models.py:220 +#: apps/member/models.py:221 msgid "Uncheck if this club don't require memberships." msgstr "" "Deaktivieren Sie diese Option, wenn für diesen Club keine Mitgliedschaft " "erforderlich ist." -#: apps/member/models.py:236 +#: apps/member/models.py:237 #: apps/member/templates/member/includes/club_info.html:26 msgid "membership duration" msgstr "Mitgliedscahftzeit" -#: apps/member/models.py:237 +#: apps/member/models.py:238 msgid "The longest time (in days) a membership can last (NULL = infinite)." msgstr "Wie lang am höchsten eine Mitgliedschaft dauern kann." -#: apps/member/models.py:244 +#: apps/member/models.py:245 #: apps/member/templates/member/includes/club_info.html:16 msgid "membership start" msgstr "Mitgliedschaftanfangsdatum" -#: apps/member/models.py:245 +#: apps/member/models.py:246 msgid "Date from which the members can renew their membership." msgstr "Ab wann kann man sein Mitgliedschaft erneuern." -#: apps/member/models.py:251 +#: apps/member/models.py:252 #: apps/member/templates/member/includes/club_info.html:21 msgid "membership end" msgstr "Mitgliedschaftenddatum" -#: apps/member/models.py:252 +#: apps/member/models.py:253 msgid "Maximal date of a membership, after which members must renew it." msgstr "" "Maximales Datum einer Mitgliedschaft, nach dem Mitglieder es erneuern müssen." -#: apps/member/models.py:284 apps/member/models.py:309 -#: apps/note/models/notes.py:179 +#: apps/member/models.py:285 apps/member/models.py:310 +#: apps/note/models/notes.py:185 msgid "club" msgstr "Club" -#: apps/member/models.py:285 +#: apps/member/models.py:286 msgid "clubs" msgstr "Clubs" -#: apps/member/models.py:319 +#: apps/member/models.py:320 msgid "membership starts on" msgstr "Mitgliedschaft fängt an" -#: apps/member/models.py:323 +#: apps/member/models.py:324 msgid "membership ends on" msgstr "Mitgliedschaft endet am" -#: apps/member/models.py:374 +#: apps/member/models.py:419 #, python-brace-format msgid "The role {role} does not apply to the club {club}." msgstr "Die Rolle {role} ist nicht erlaubt für das Club {club}." -#: apps/member/models.py:385 apps/member/views.py:676 +#: apps/member/models.py:428 apps/member/views.py:628 msgid "User is already a member of the club" msgstr "User ist schon ein Mitglied dieser club" -#: apps/member/models.py:433 +#: apps/member/models.py:440 msgid "User is not a member of the parent club" msgstr "User ist noch nicht Mitglied des Urclubs" -#: apps/member/models.py:486 +#: apps/member/models.py:488 #, python-brace-format msgid "Membership of {user} for the club {club}" msgstr "Mitgliedschaft von {user} für das Club {club}" -#: apps/member/models.py:489 +#: apps/member/models.py:491 apps/note/models/transactions.py:353 msgid "membership" msgstr "Mitgliedschaft" -#: apps/member/models.py:490 +#: apps/member/models.py:492 msgid "memberships" msgstr "Mitgliedschaften" @@ -842,7 +865,7 @@ msgid "Account #" msgstr "Konto #" #: apps/member/templates/member/base.html:48 -#: apps/member/templates/member/base.html:62 apps/member/views.py:59 +#: apps/member/templates/member/base.html:62 apps/member/views.py:57 #: apps/registration/templates/registration/future_profile_detail.html:48 #: apps/wei/templates/wei/weimembership_form.html:117 msgid "Update Profile" @@ -886,7 +909,7 @@ msgstr "" "zu aufschliessen." #: apps/member/templates/member/base.html:110 -#: apps/member/templates/member/base.html:137 apps/treasury/forms.py:95 +#: apps/member/templates/member/base.html:137 apps/treasury/forms.py:89 msgid "Close" msgstr "Schluss" @@ -902,8 +925,8 @@ msgstr "" "erlaubt." #: apps/member/templates/member/club_alias.html:10 -#: apps/member/templates/member/profile_alias.html:10 apps/member/views.py:240 -#: apps/member/views.py:450 +#: apps/member/templates/member/profile_alias.html:10 apps/member/views.py:236 +#: apps/member/views.py:433 msgid "Note aliases" msgstr "Note Aliases" @@ -967,7 +990,7 @@ msgstr "Kontostand" #: apps/member/templates/member/includes/club_info.html:47 #: apps/member/templates/member/includes/profile_info.html:20 -#: apps/note/models/notes.py:270 apps/wei/templates/wei/base.html:66 +#: apps/note/models/notes.py:276 apps/wei/templates/wei/base.html:66 msgid "aliases" msgstr "Aliases" @@ -1006,6 +1029,14 @@ msgstr "Neue" msgid "Regenerate token" msgstr "Token erneuern" +#: apps/member/templates/member/picture_update.html:35 +msgid "Nevermind" +msgstr "Vergessen" + +#: apps/member/templates/member/picture_update.html:36 +msgid "Crop and upload" +msgstr "Beschneiden und hochladen" + #: apps/member/templates/member/profile_detail.html:11 #: apps/registration/templates/registration/future_profile_detail.html:28 #: apps/wei/templates/wei/weimembership_form.html:26 @@ -1030,47 +1061,47 @@ msgstr "Speichern" msgid "Registrations" msgstr "Anmeldung" -#: apps/member/views.py:72 apps/registration/forms.py:23 +#: apps/member/views.py:70 apps/registration/forms.py:23 msgid "This address must be valid." msgstr "Diese Adresse muss gültig sein." -#: apps/member/views.py:138 +#: apps/member/views.py:135 msgid "Profile detail" msgstr "Profile detail" -#: apps/member/views.py:201 +#: apps/member/views.py:195 msgid "Search user" msgstr "User finden" -#: apps/member/views.py:260 +#: apps/member/views.py:256 msgid "Update note picture" msgstr "Notebild ändern" -#: apps/member/views.py:318 +#: apps/member/views.py:301 msgid "Manage auth token" msgstr "Auth token bearbeiten" -#: apps/member/views.py:346 +#: apps/member/views.py:328 msgid "Create new club" msgstr "Neue Club" -#: apps/member/views.py:364 +#: apps/member/views.py:347 msgid "Search club" msgstr "Club finden" -#: apps/member/views.py:397 +#: apps/member/views.py:380 msgid "Club detail" msgstr "Club Details" -#: apps/member/views.py:473 +#: apps/member/views.py:456 msgid "Update club" msgstr "Club bearbeiten" -#: apps/member/views.py:507 +#: apps/member/views.py:490 msgid "Add new member to the club" msgstr "Neue Mitglieder" -#: apps/member/views.py:667 apps/wei/views.py:922 +#: apps/member/views.py:619 apps/wei/views.py:922 msgid "" "This user don't have enough money to join this club, and can't have a " "negative balance." @@ -1078,44 +1109,44 @@ msgstr "" "Diese User hat nicht genug Geld um Mitglied zu werden, und darf nich im Rot " "sein." -#: apps/member/views.py:680 +#: apps/member/views.py:632 msgid "The membership must start after {:%m-%d-%Y}." msgstr "Die Mitgliedschaft muss nach {:%m-%d-Y} anfängen." -#: apps/member/views.py:685 +#: apps/member/views.py:637 msgid "The membership must begin before {:%m-%d-%Y}." msgstr "Die Mitgliedschaft muss vor {:%m-%d-Y} anfängen." -#: apps/member/views.py:701 apps/member/views.py:703 apps/member/views.py:705 -#: apps/registration/views.py:292 apps/registration/views.py:294 -#: apps/registration/views.py:296 apps/wei/views.py:927 apps/wei/views.py:931 +#: apps/member/views.py:644 apps/member/views.py:646 apps/member/views.py:648 +#: apps/registration/views.py:287 apps/registration/views.py:289 +#: apps/registration/views.py:291 apps/wei/views.py:927 apps/wei/views.py:931 msgid "This field is required." msgstr "Dies ist ein Pflichtfeld." -#: apps/member/views.py:789 +#: apps/member/views.py:783 msgid "Manage roles of an user in the club" msgstr "Rollen in diesen Club bearbeiten" -#: apps/member/views.py:814 +#: apps/member/views.py:808 msgid "Members of the club" msgstr "Mitlglieder dieses Club" -#: apps/note/admin.py:129 apps/note/models/transactions.py:106 +#: apps/note/admin.py:129 apps/note/models/transactions.py:109 msgid "source" msgstr "Sender" #: apps/note/admin.py:137 apps/note/admin.py:205 -#: apps/note/models/transactions.py:56 apps/note/models/transactions.py:119 +#: apps/note/models/transactions.py:56 apps/note/models/transactions.py:122 msgid "destination" msgstr "Empfänger" #: apps/note/admin.py:210 apps/note/models/transactions.py:60 -#: apps/note/models/transactions.py:137 +#: apps/note/models/transactions.py:140 msgid "amount" msgstr "Anzahl" -#: apps/note/api/serializers.py:178 apps/note/api/serializers.py:184 -#: apps/note/models/transactions.py:224 +#: apps/note/api/serializers.py:183 apps/note/api/serializers.py:189 +#: apps/note/models/transactions.py:226 msgid "" "The transaction can't be saved since the source note or the destination note " "is not active." @@ -1175,7 +1206,7 @@ msgstr "letztes mal im Rot" msgid "display image" msgstr "Bild" -#: apps/note/models/notes.py:54 apps/note/models/transactions.py:129 +#: apps/note/models/notes.py:54 apps/note/models/transactions.py:132 msgid "created at" msgstr "erschafft am" @@ -1207,68 +1238,68 @@ msgstr "The note is blocked by the the BDE and can't be manually reactivated." msgid "notes" msgstr "Notes" -#: apps/note/models/notes.py:122 +#: apps/note/models/notes.py:128 msgid "This alias is already taken." msgstr "Dieses Alias ist schon benutzt." -#: apps/note/models/notes.py:142 +#: apps/note/models/notes.py:148 msgid "one's note" msgstr "Jemand Note" -#: apps/note/models/notes.py:143 +#: apps/note/models/notes.py:149 msgid "users note" msgstr "User Note" -#: apps/note/models/notes.py:149 +#: apps/note/models/notes.py:155 #, python-format msgid "%(user)s's note" msgstr "%(user)s's note" -#: apps/note/models/notes.py:183 +#: apps/note/models/notes.py:189 msgid "club note" msgstr "Club Note" -#: apps/note/models/notes.py:184 +#: apps/note/models/notes.py:190 msgid "clubs notes" msgstr "Club Notes" -#: apps/note/models/notes.py:190 +#: apps/note/models/notes.py:196 #, python-format msgid "Note of %(club)s club" msgstr "%(club)s Note" -#: apps/note/models/notes.py:229 +#: apps/note/models/notes.py:235 msgid "special note" msgstr "Sondernote" -#: apps/note/models/notes.py:230 +#: apps/note/models/notes.py:236 msgid "special notes" msgstr "Sondernoten" -#: apps/note/models/notes.py:253 +#: apps/note/models/notes.py:259 msgid "Invalid alias" msgstr "Unerlaublt Alias" -#: apps/note/models/notes.py:269 +#: apps/note/models/notes.py:275 msgid "alias" msgstr "Alias" -#: apps/note/models/notes.py:293 +#: apps/note/models/notes.py:299 msgid "Alias is too long." msgstr "Alias ist zu lang." -#: apps/note/models/notes.py:296 +#: apps/note/models/notes.py:302 msgid "" "This alias contains only complex character. Please use a more simple alias." msgstr "" "Dieser Alias enthält nur komplexe Zeichen. Bitte verwenden Sie einen " "einfacheren Alias." -#: apps/note/models/notes.py:300 +#: apps/note/models/notes.py:306 msgid "An alias with a similar name already exists: {} " msgstr "Ein Alias mit einem ähnlichen Namen existiert bereits: {} " -#: apps/note/models/notes.py:313 +#: apps/note/models/notes.py:319 msgid "You can't delete your main alias." msgstr "Sie können Ihren Hauptalias nicht löschen." @@ -1300,33 +1331,33 @@ msgstr "Transaktionsvorlage" msgid "transaction templates" msgstr "Transaktionsvorlagen" -#: apps/note/models/transactions.py:112 apps/note/models/transactions.py:125 -#: apps/note/tables.py:33 apps/note/tables.py:42 +#: apps/note/models/transactions.py:115 apps/note/models/transactions.py:128 +#: apps/note/tables.py:34 apps/note/tables.py:44 msgid "used alias" msgstr "benutzte Aliasen" -#: apps/note/models/transactions.py:133 +#: apps/note/models/transactions.py:136 msgid "quantity" msgstr "Anzahl" -#: apps/note/models/transactions.py:141 +#: apps/note/models/transactions.py:144 msgid "reason" msgstr "Grund" -#: apps/note/models/transactions.py:151 apps/note/tables.py:107 +#: apps/note/models/transactions.py:154 apps/note/tables.py:140 msgid "invalidity reason" msgstr "Ungültigkeit Grund" -#: apps/note/models/transactions.py:159 +#: apps/note/models/transactions.py:161 msgid "transaction" msgstr "Transaktion" -#: apps/note/models/transactions.py:160 +#: apps/note/models/transactions.py:162 #: apps/treasury/templates/treasury/sogecredit_detail.html:22 msgid "transactions" msgstr "Transaktionen" -#: apps/note/models/transactions.py:182 +#: apps/note/models/transactions.py:184 #, python-brace-format msgid "" "You can't update the {field} on a Transaction. Please invalidate it and " @@ -1335,7 +1366,7 @@ msgstr "" "Sie können das {field} einer Transaktion nicht aktualisieren. Bitte machen " "Sie es ungültig und erstellen Sie eine andere." -#: apps/note/models/transactions.py:202 +#: apps/note/models/transactions.py:204 msgid "" "The note balances must be between - 92 233 720 368 547 758.08 € and 92 233 " "720 368 547 758.07 €." @@ -1343,34 +1374,34 @@ msgstr "" "Die Notenguthaben müssen zwischen - 92 233 720 368 547 758,08 € und 92 233 " "720 368 547 758,07 € liegen." -#: apps/note/models/transactions.py:279 +#: apps/note/models/transactions.py:273 msgid "" "The destination of this transaction must equal to the destination of the " "template." msgstr "" "Der Empfänger dieser Transaktion muss dem Empfänger der Vorlage entsprechen." -#: apps/note/models/transactions.py:288 +#: apps/note/models/transactions.py:282 msgid "Template" msgstr "Vorlage" -#: apps/note/models/transactions.py:291 +#: apps/note/models/transactions.py:285 msgid "recurrent transaction" msgstr "wiederkehrende Transaktion" -#: apps/note/models/transactions.py:292 +#: apps/note/models/transactions.py:286 msgid "recurrent transactions" msgstr "wiederkehrende Transaktionen" -#: apps/note/models/transactions.py:307 +#: apps/note/models/transactions.py:301 msgid "first_name" msgstr "Vorname" -#: apps/note/models/transactions.py:312 +#: apps/note/models/transactions.py:306 msgid "bank" msgstr "Bank" -#: apps/note/models/transactions.py:329 +#: apps/note/models/transactions.py:323 msgid "" "A special transaction is only possible between a Note associated to a " "payment method and a User or a Club" @@ -1378,35 +1409,35 @@ msgstr "" "Eine Sondertransaktion ist nur zwischen einer Note, die einer " "Zahlungsmethode zugeordnet ist, und einem User oder einem Club möglich" -#: apps/note/models/transactions.py:337 +#: apps/note/models/transactions.py:331 msgid "Special transaction" msgstr "Sondertransaktion" -#: apps/note/models/transactions.py:338 +#: apps/note/models/transactions.py:332 msgid "Special transactions" msgstr "Sondertranskationen" -#: apps/note/models/transactions.py:354 apps/note/models/transactions.py:359 +#: apps/note/models/transactions.py:348 msgid "membership transaction" msgstr "Mitgliedschafttransaktion" -#: apps/note/models/transactions.py:355 apps/treasury/models.py:273 +#: apps/note/models/transactions.py:349 apps/treasury/models.py:282 msgid "membership transactions" msgstr "Mitgliedschaftttransaktionen" -#: apps/note/tables.py:61 +#: apps/note/tables.py:94 msgid "Click to invalidate" msgstr "Klicken Sie zum Ungültigmachen" -#: apps/note/tables.py:61 +#: apps/note/tables.py:94 msgid "Click to validate" msgstr "Klicken Sie zum gültigmachen" -#: apps/note/tables.py:105 +#: apps/note/tables.py:138 msgid "No reason specified" msgstr "Kein Grund gegeben" -#: apps/note/tables.py:136 apps/note/tables.py:170 apps/treasury/tables.py:39 +#: apps/note/tables.py:169 apps/note/tables.py:203 apps/treasury/tables.py:39 #: apps/treasury/templates/treasury/invoice_confirm_delete.html:30 #: apps/treasury/templates/treasury/sogecredit_detail.html:59 #: apps/wei/tables.py:76 apps/wei/tables.py:103 @@ -1414,7 +1445,7 @@ msgstr "Kein Grund gegeben" msgid "Delete" msgstr "Löschen" -#: apps/note/tables.py:164 apps/note/templates/note/conso_form.html:132 +#: apps/note/tables.py:197 apps/note/templates/note/conso_form.html:132 #: apps/wei/tables.py:47 apps/wei/tables.py:48 #: apps/wei/templates/wei/base.html:89 #: apps/wei/templates/wei/bus_detail.html:20 @@ -1462,7 +1493,8 @@ msgstr "Verlauf der letzten Transaktionen" #: apps/note/templates/note/mails/negative_balance.txt:25 #: apps/note/templates/note/mails/negative_notes_report.html:46 #: apps/note/templates/note/mails/negative_notes_report.txt:13 -#: apps/note/templates/note/mails/weekly_report.html:54 +#: apps/note/templates/note/mails/weekly_report.html:51 +#: apps/note/templates/note/mails/weekly_report.txt:32 #: apps/registration/templates/registration/mails/email_validation_email.html:40 #: apps/registration/templates/registration/mails/email_validation_email.txt:16 msgid "Mail generated by the Note Kfet on the" @@ -1487,7 +1519,7 @@ msgid "Action" msgstr "Aktion" #: apps/note/templates/note/transaction_form.html:112 -#: apps/treasury/forms.py:141 apps/treasury/tables.py:67 +#: apps/treasury/forms.py:135 apps/treasury/tables.py:67 #: apps/treasury/tables.py:135 #: apps/treasury/templates/treasury/remittance_form.html:23 msgid "Amount" @@ -1562,7 +1594,7 @@ msgstr "Tatsen finden" msgid "Update button" msgstr "Tatse bearbeiten" -#: apps/note/views.py:151 note_kfet/templates/base.html:62 +#: apps/note/views.py:151 note_kfet/templates/base.html:64 msgid "Consumptions" msgstr "Verbräuche" @@ -1671,7 +1703,7 @@ msgstr "" "Sie haben nicht die Berechtigung, eine Instanz von model {app_label}. " "{model_name} hinzufügen." -#: apps/permission/signals.py:101 +#: apps/permission/signals.py:102 #, python-brace-format msgid "" "You don't have the permission to delete this instance of model {app_label}." @@ -1740,7 +1772,7 @@ msgstr "" "diesen Parametern zu erstellen. Bitte korrigieren Sie Ihre Daten und " "versuchen Sie es erneut." -#: apps/permission/views.py:96 note_kfet/templates/base.html:104 +#: apps/permission/views.py:96 note_kfet/templates/base.html:106 msgid "Rights" msgstr "Rechten" @@ -1777,23 +1809,23 @@ msgstr "BDE Mitglieder werden" msgid "Join Kfet Club" msgstr "Kfet Mitglieder werden" -#: apps/registration/templates/registration/email_validation_complete.html:9 +#: apps/registration/templates/registration/email_validation_complete.html:15 msgid "Your email have successfully been validated." msgstr "Ihre E-Mail wurde erfolgreich validiert." -#: apps/registration/templates/registration/email_validation_complete.html:11 +#: apps/registration/templates/registration/email_validation_complete.html:19 #, python-format msgid "You can now log in." msgstr "Sie können sich jetz anmelden ." -#: apps/registration/templates/registration/email_validation_complete.html:13 +#: apps/registration/templates/registration/email_validation_complete.html:23 msgid "" "You must pay now your membership in the Kfet to complete your registration." msgstr "" "Sie müssen jetzt Ihre Mitgliedschaft im Kfet bezahlen, um Ihre Registrierung " "abzuschließen." -#: apps/registration/templates/registration/email_validation_complete.html:16 +#: apps/registration/templates/registration/email_validation_complete.html:28 msgid "" "The link was invalid. The token may have expired. Please send us an email to " "activate your account." @@ -1801,24 +1833,20 @@ msgstr "" "Der Link war ungültig. Das Token ist möglicherweise abgelaufen. Bitte senden " "Sie uns eine E-Mail, um Ihr Konto zu aktivieren." -#: apps/registration/templates/registration/email_validation_email_sent.html:8 +#: apps/registration/templates/registration/email_validation_email_sent.html:10 msgid "Account activation" msgstr "Kontoaktivierung" -#: apps/registration/templates/registration/email_validation_email_sent.html:11 +#: apps/registration/templates/registration/email_validation_email_sent.html:14 msgid "" "An email has been sent. Please click on the link to activate your account." msgstr "" "Eine E-Mail wurde gesendet. Bitte klicken Sie auf den Link, um Ihr Konto zu " "aktivieren." -#: apps/registration/templates/registration/email_validation_email_sent.html:15 -msgid "" -"You must also go to the Kfet to pay your membership. The WEI registration " -"includes the BDE membership." -msgstr "" -"Sie müssen auch zum Kfet gehen, um Ihre Mitgliedschaft zu bezahlen. Die WEI-" -"Registrierung beinhaltet die BDE-Mitgliedschaft." +#: apps/registration/templates/registration/email_validation_email_sent.html:17 +msgid "You must also go to the Kfet to pay your membership." +msgstr "Sie müssen auch zum Kfet gehen, um Ihre Mitgliedschaft zu bezahlen." #: apps/registration/templates/registration/future_profile_detail.html:49 #: apps/wei/templates/wei/weiregistration_confirm_delete.html:11 @@ -1866,12 +1894,10 @@ msgstr "" #: apps/registration/templates/registration/mails/email_validation_email.txt:11 msgid "" "After that, you'll have to wait that someone validates your account before " -"you can log in. You will need to pay your membership in the Kfet. Note that " -"the WEI registration includes the Kfet membership." +"you can log in. You will need to pay your membership in the Kfet." msgstr "" "Danach müssen Sie warten, bis jemand Ihr Konto validiert, bevor Sie sich " -"anmelden können. Sie müssen Ihre Mitgliedschaft im Kfet bezahlen. Beachten " -"Sie, dass die WEI-Registrierung die Kfet-Mitgliedschaft enthält." +"anmelden können. Sie müssen Ihre Mitgliedschaft im Kfet bezahlen." #: apps/registration/templates/registration/mails/email_validation_email.html:34 #: apps/registration/templates/registration/mails/email_validation_email.txt:13 @@ -1911,47 +1937,47 @@ msgstr "E-Mail-Validierungslink erneut senden" msgid "Pre-registered users list" msgstr "Vorregistrierte Userliste" -#: apps/registration/views.py:190 +#: apps/registration/views.py:187 msgid "Unregistered users" msgstr "Unregistrierte Users" -#: apps/registration/views.py:203 +#: apps/registration/views.py:200 msgid "Registration detail" msgstr "Registrierung Detailen" -#: apps/registration/views.py:258 +#: apps/registration/views.py:256 msgid "You must join the BDE." msgstr "Sie müssen die BDE beitreten." #: apps/registration/views.py:280 -msgid "You must join BDE club before joining Kfet club." -msgstr "" -"Sie müssen dem BDE-Club beitreten, bevor Sie dem Kfet-Club beitreten können." - -#: apps/registration/views.py:285 msgid "" "The entered amount is not enough for the memberships, should be at least {}" msgstr "" "Der eingegebene Betrag reicht für die Mitgliedschaft nicht aus, sollte " "mindestens {} betragen" -#: apps/registration/views.py:360 +#: apps/registration/views.py:355 msgid "Invalidate pre-registration" msgstr "Ungültige Vorregistrierung" -#: apps/treasury/apps.py:12 note_kfet/templates/base.html:92 +#: apps/treasury/apps.py:12 note_kfet/templates/base.html:94 msgid "Treasury" msgstr "Quaestor" -#: apps/treasury/forms.py:104 +#: apps/treasury/forms.py:24 apps/treasury/models.py:89 +#: apps/treasury/templates/treasury/invoice_form.html:22 +msgid "This invoice is locked and can no longer be edited." +msgstr "Diese Rechnung ist gesperrt und kann nicht mehr bearbeitet werden." + +#: apps/treasury/forms.py:98 msgid "Remittance is already closed." msgstr "Überweisung ist bereits geschlossen." -#: apps/treasury/forms.py:109 +#: apps/treasury/forms.py:103 msgid "You can't change the type of the remittance." msgstr "Sie können die Art der Überweisung nicht ändern." -#: apps/treasury/forms.py:129 apps/treasury/models.py:252 +#: apps/treasury/forms.py:123 apps/treasury/models.py:258 #: apps/treasury/tables.py:97 apps/treasury/tables.py:105 #: apps/treasury/templates/treasury/invoice_list.html:16 #: apps/treasury/templates/treasury/remittance_list.html:16 @@ -1959,7 +1985,7 @@ msgstr "Sie können die Art der Überweisung nicht ändern." msgid "Remittance" msgstr "Überweisung" -#: apps/treasury/forms.py:130 +#: apps/treasury/forms.py:124 msgid "No attached remittance" msgstr "Keine beigefügte Überweisung" @@ -1983,7 +2009,7 @@ msgstr "Beschreibung" msgid "Address" msgstr "Adresse" -#: apps/treasury/models.py:60 apps/treasury/models.py:180 +#: apps/treasury/models.py:60 apps/treasury/models.py:186 msgid "Date" msgstr "Datum" @@ -2003,12 +2029,7 @@ msgstr "Eine Rechnung kann nicht bearbeitet werden, wenn sie gesperrt ist." msgid "tex source" msgstr "Tex Quelle" -#: apps/treasury/models.py:89 -#: apps/treasury/templates/treasury/invoice_form.html:22 -msgid "This invoice is locked and can no longer be edited." -msgstr "Diese Rechnung ist gesperrt und kann nicht mehr bearbeitet werden." - -#: apps/treasury/models.py:109 apps/treasury/models.py:122 +#: apps/treasury/models.py:109 apps/treasury/models.py:125 msgid "invoice" msgstr "Rechnung" @@ -2016,67 +2037,72 @@ msgstr "Rechnung" msgid "invoices" msgstr "Rechnungen" -#: apps/treasury/models.py:127 +#: apps/treasury/models.py:113 +#, python-brace-format +msgid "Invoice #{id}" +msgstr "Rechnung #{id}" + +#: apps/treasury/models.py:130 msgid "Designation" msgstr "Bezeichnung" -#: apps/treasury/models.py:131 +#: apps/treasury/models.py:134 msgid "Quantity" msgstr "Qualität" -#: apps/treasury/models.py:135 +#: apps/treasury/models.py:138 msgid "Unit price" msgstr "Einzelpreis" -#: apps/treasury/models.py:151 +#: apps/treasury/models.py:154 msgid "product" msgstr "Produkt" -#: apps/treasury/models.py:152 +#: apps/treasury/models.py:155 msgid "products" msgstr "Produkten" -#: apps/treasury/models.py:169 +#: apps/treasury/models.py:175 msgid "remittance type" msgstr "Überweisungstyp" -#: apps/treasury/models.py:170 +#: apps/treasury/models.py:176 msgid "remittance types" msgstr "Überweisungstypen" -#: apps/treasury/models.py:191 +#: apps/treasury/models.py:197 msgid "Comment" msgstr "Kommentar" -#: apps/treasury/models.py:196 +#: apps/treasury/models.py:202 msgid "Closed" msgstr "Geschlossen" -#: apps/treasury/models.py:200 +#: apps/treasury/models.py:206 msgid "remittance" msgstr "Überweisung" -#: apps/treasury/models.py:201 +#: apps/treasury/models.py:207 msgid "remittances" msgstr "Überweisungen" -#: apps/treasury/models.py:233 +#: apps/treasury/models.py:239 msgid "Remittance #{:d}: {}" msgstr "Überweisung #{:d}:{}" -#: apps/treasury/models.py:256 +#: apps/treasury/models.py:262 msgid "special transaction proxy" msgstr "spezielle Transaktion Proxy" -#: apps/treasury/models.py:257 +#: apps/treasury/models.py:263 msgid "special transaction proxies" msgstr "spezielle Transaktion Proxies" -#: apps/treasury/models.py:279 +#: apps/treasury/models.py:288 msgid "credit transaction" msgstr "Kredit Transaktion" -#: apps/treasury/models.py:343 +#: apps/treasury/models.py:352 msgid "" "This user doesn't have enough money to pay the memberships with its note. " "Please ask her/him to credit the note before invalidating this credit." @@ -2084,15 +2110,20 @@ msgstr "" "Dieser Benutzer hat nicht genug Geld, um die Mitgliedschaften mit seiner " "Note zu bezahlen." -#: apps/treasury/models.py:355 +#: apps/treasury/models.py:364 #: apps/treasury/templates/treasury/sogecredit_detail.html:10 msgid "Credit from the Société générale" msgstr "Kredit von der Société générale" -#: apps/treasury/models.py:356 +#: apps/treasury/models.py:365 msgid "Credits from the Société générale" msgstr "Krediten von der Société générale" +#: apps/treasury/models.py:368 +#, python-brace-format +msgid "Soge credit for {user}" +msgstr "Kredit von der Société générale für {user}" + #: apps/treasury/tables.py:20 msgid "Invoice #{:d}" msgstr "Rechnung #{:d}" @@ -2117,11 +2148,12 @@ msgid "Yes" msgstr "Ja" #: apps/treasury/templates/treasury/invoice_confirm_delete.html:10 -#: apps/treasury/views.py:166 +#: apps/treasury/views.py:176 msgid "Delete invoice" msgstr "Rechnung löschen" #: apps/treasury/templates/treasury/invoice_confirm_delete.html:15 +#: apps/treasury/views.py:180 msgid "This invoice is locked and can't be deleted." msgstr "Eine Rechnung kann nicht gelöscht werden, wenn sie gesperrt ist." @@ -2291,46 +2323,46 @@ msgstr "" msgid "Create new invoice" msgstr "Neue Rechnung" -#: apps/treasury/views.py:89 +#: apps/treasury/views.py:94 msgid "Invoices list" msgstr "Rechnunglist" -#: apps/treasury/views.py:104 apps/treasury/views.py:265 -#: apps/treasury/views.py:391 +#: apps/treasury/views.py:109 apps/treasury/views.py:282 +#: apps/treasury/views.py:408 msgid "You are not able to see the treasury interface." msgstr "Sie können die Quaestor-App nicht sehen." -#: apps/treasury/views.py:114 +#: apps/treasury/views.py:119 msgid "Update an invoice" msgstr "Rechnung bearbeiten" -#: apps/treasury/views.py:226 +#: apps/treasury/views.py:243 msgid "Create a new remittance" msgstr "Neue Überweisung" -#: apps/treasury/views.py:253 +#: apps/treasury/views.py:270 msgid "Remittances list" msgstr "Überweisungliste" -#: apps/treasury/views.py:316 +#: apps/treasury/views.py:333 msgid "Update a remittance" msgstr "Überweisung bearbeiten" -#: apps/treasury/views.py:339 +#: apps/treasury/views.py:356 msgid "Attach a transaction to a remittance" msgstr "Fügen Sie einer Überweisung eine Transaktion hinzu" -#: apps/treasury/views.py:383 +#: apps/treasury/views.py:400 msgid "List of credits from the Société générale" msgstr "Kreditliste von Société générale" -#: apps/treasury/views.py:426 +#: apps/treasury/views.py:443 msgid "Manage credits from the Société générale" msgstr "Krediten von der Société générale handeln" #: apps/wei/apps.py:10 apps/wei/models.py:49 apps/wei/models.py:50 #: apps/wei/models.py:61 apps/wei/models.py:167 -#: note_kfet/templates/base.html:98 +#: note_kfet/templates/base.html:100 msgid "WEI" msgstr "WEI" @@ -2934,23 +2966,46 @@ msgstr "" msgid "Reset" msgstr "Reset" -#: note_kfet/templates/base.html:13 +#: note_kfet/templates/base.html:14 msgid "The ENS Paris-Saclay BDE note." msgstr "Die BDE ENS-Paris-Saclay Note." -#: note_kfet/templates/base.html:74 +#: note_kfet/templates/base.html:76 msgid "Users" msgstr "Users" -#: note_kfet/templates/base.html:80 +#: note_kfet/templates/base.html:82 msgid "Clubs" -msgstr "CLubs" +msgstr "Clubs" -#: note_kfet/templates/base.html:109 +#: note_kfet/templates/base.html:111 msgid "Admin" msgstr "Admin" -#: note_kfet/templates/base.html:153 +#: note_kfet/templates/base.html:125 +msgid "My account" +msgstr "Mein Konto" + +#: note_kfet/templates/base.html:128 +msgid "Log out" +msgstr "Abmelden" + +#: note_kfet/templates/base.html:136 +#: note_kfet/templates/registration/signup.html:6 +#: note_kfet/templates/registration/signup.html:11 +#: note_kfet/templates/registration/signup.html:27 +msgid "Sign up" +msgstr "Registrieren" + +#: note_kfet/templates/base.html:143 +#: note_kfet/templates/registration/login.html:6 +#: note_kfet/templates/registration/login.html:15 +#: note_kfet/templates/registration/login.html:38 +#: note_kfet/templates/registration/password_reset_complete.html:15 +msgid "Log in" +msgstr "Anmelden" + +#: note_kfet/templates/base.html:155 msgid "" "Your e-mail address is not validated. Please check your mail inbox and click " "on the validation link." @@ -2958,6 +3013,10 @@ msgstr "" "Ihre E-Mail-Adresse ist nicht validiert. Bitte überprüfen Sie Ihren " "Posteingang und klicken Sie auf den Validierungslink." +#: note_kfet/templates/base.html:172 +msgid "Contact us" +msgstr "Kontakt" + #: note_kfet/templates/base_search.html:15 msgid "Search by attribute such as name…" msgstr "Suche nach Attributen wie Name…" @@ -2990,13 +3049,6 @@ msgstr "" msgid "Log in again" msgstr "Nochmal anmelden" -#: note_kfet/templates/registration/login.html:6 -#: note_kfet/templates/registration/login.html:15 -#: note_kfet/templates/registration/login.html:38 -#: note_kfet/templates/registration/password_reset_complete.html:15 -msgid "Log in" -msgstr "Anmelden" - #: note_kfet/templates/registration/login.html:20 #, python-format msgid "" @@ -3088,12 +3140,6 @@ msgstr "" msgid "Reset my password" msgstr "Mein Passwort zurücksetzen" -#: note_kfet/templates/registration/signup.html:6 -#: note_kfet/templates/registration/signup.html:11 -#: note_kfet/templates/registration/signup.html:27 -msgid "Sign up" -msgstr "Registrieren" - #: note_kfet/templates/registration/signup.html:15 msgid "" "If you already signed up, your registration is taken into account. The BDE " diff --git a/locale/fr/LC_MESSAGES/django.po b/locale/fr/LC_MESSAGES/django.po index 96feaac7..5e6e2740 100644 --- a/locale/fr/LC_MESSAGES/django.po +++ b/locale/fr/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2020-09-02 23:17+0200\n" +"POT-Creation-Date: 2020-09-07 19:43+0200\n" "PO-Revision-Date: 2020-09-02 23:18+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -18,42 +18,42 @@ msgstr "" "Plural-Forms: nplurals=2; plural=(n > 1);\n" "X-Generator: Poedit 2.3\n" -#: apps/activity/apps.py:10 apps/activity/models.py:145 -#: apps/activity/models.py:161 +#: apps/activity/apps.py:10 apps/activity/models.py:150 +#: apps/activity/models.py:166 msgid "activity" msgstr "activité" -#: apps/activity/forms.py:35 apps/activity/models.py:130 +#: apps/activity/forms.py:35 apps/activity/models.py:131 msgid "The end date must be after the start date." msgstr "La date de fin doit être après celle de début." -#: apps/activity/forms.py:76 apps/activity/models.py:257 +#: apps/activity/forms.py:76 apps/activity/models.py:268 msgid "You can't invite someone once the activity is started." msgstr "" "Vous ne pouvez pas inviter quelqu'un une fois que l'activité a démarré." -#: apps/activity/forms.py:79 apps/activity/models.py:260 +#: apps/activity/forms.py:79 apps/activity/models.py:271 msgid "This activity is not validated yet." msgstr "Cette activité n'est pas encore validée." -#: apps/activity/forms.py:89 apps/activity/models.py:268 +#: apps/activity/forms.py:89 apps/activity/models.py:279 msgid "This person has been already invited 5 times this year." msgstr "Cette personne a déjà été invitée 5 fois cette année." -#: apps/activity/forms.py:93 apps/activity/models.py:272 +#: apps/activity/forms.py:93 apps/activity/models.py:283 msgid "This person is already invited." msgstr "Cette personne est déjà invitée." -#: apps/activity/forms.py:97 apps/activity/models.py:276 +#: apps/activity/forms.py:97 apps/activity/models.py:287 msgid "You can't invite more than 3 people to this activity." msgstr "Vous ne pouvez pas inviter plus de 3 personnes à cette activité." -#: apps/activity/models.py:27 apps/activity/models.py:62 -#: apps/member/models.py:198 +#: apps/activity/models.py:28 apps/activity/models.py:63 +#: apps/member/models.py:199 #: apps/member/templates/member/includes/club_info.html:4 #: apps/member/templates/member/includes/profile_info.html:4 -#: apps/note/models/notes.py:247 apps/note/models/transactions.py:26 -#: apps/note/models/transactions.py:46 apps/note/models/transactions.py:302 +#: apps/note/models/notes.py:253 apps/note/models/transactions.py:26 +#: apps/note/models/transactions.py:46 apps/note/models/transactions.py:296 #: apps/permission/models.py:329 #: apps/registration/templates/registration/future_profile_detail.html:16 #: apps/wei/models.py:66 apps/wei/models.py:118 @@ -62,161 +62,171 @@ msgstr "Vous ne pouvez pas inviter plus de 3 personnes à cette activité." msgid "name" msgstr "nom" -#: apps/activity/models.py:32 +#: apps/activity/models.py:33 msgid "manage entries" msgstr "gérer les entrées" -#: apps/activity/models.py:33 +#: apps/activity/models.py:34 msgid "Enable the support of entries for this activity." msgstr "Activer le support des entrées pour cette activité." -#: apps/activity/models.py:38 +#: apps/activity/models.py:39 #: apps/activity/templates/activity/includes/activity_info.html:42 msgid "can invite" msgstr "peut inviter" -#: apps/activity/models.py:43 +#: apps/activity/models.py:44 #: apps/activity/templates/activity/includes/activity_info.html:46 msgid "guest entry fee" msgstr "cotisation de l'entrée invité" -#: apps/activity/models.py:48 +#: apps/activity/models.py:49 msgid "activity type" msgstr "type d'activité" -#: apps/activity/models.py:49 +#: apps/activity/models.py:50 msgid "activity types" msgstr "types d'activité" -#: apps/activity/models.py:67 +#: apps/activity/models.py:68 #: apps/activity/templates/activity/includes/activity_info.html:19 #: apps/note/models/transactions.py:81 apps/permission/models.py:110 #: apps/permission/models.py:189 apps/wei/models.py:72 apps/wei/models.py:129 msgid "description" msgstr "description" -#: apps/activity/models.py:71 +#: apps/activity/models.py:72 msgid "location" msgstr "lieu" -#: apps/activity/models.py:75 +#: apps/activity/models.py:76 msgid "Place where the activity is organized, eg. Kfet." msgstr "Lieu où l'activité est organisée, par exemple la Kfet." -#: apps/activity/models.py:82 +#: apps/activity/models.py:83 #: apps/activity/templates/activity/includes/activity_info.html:22 -#: apps/note/models/notes.py:223 apps/note/models/transactions.py:66 +#: apps/note/models/notes.py:229 apps/note/models/transactions.py:66 #: apps/permission/models.py:164 msgid "type" msgstr "type" -#: apps/activity/models.py:88 apps/logs/models.py:22 apps/member/models.py:303 -#: apps/note/models/notes.py:138 apps/treasury/models.py:267 +#: apps/activity/models.py:89 apps/logs/models.py:22 apps/member/models.py:304 +#: apps/note/models/notes.py:144 apps/treasury/models.py:276 #: apps/treasury/templates/treasury/sogecredit_detail.html:14 #: apps/wei/models.py:160 apps/wei/templates/wei/survey.html:15 msgid "user" msgstr "utilisateur" -#: apps/activity/models.py:95 +#: apps/activity/models.py:96 #: apps/activity/templates/activity/includes/activity_info.html:36 msgid "organizer" msgstr "organisateur" -#: apps/activity/models.py:96 +#: apps/activity/models.py:97 msgid "Club that organizes the activity. The entry fees will go to this club." msgstr "" "Le club qui organise l'activité. Les coûts d'invitation iront pour ce club." -#: apps/activity/models.py:103 +#: apps/activity/models.py:104 #: apps/activity/templates/activity/includes/activity_info.html:39 msgid "attendees club" msgstr "club attendu" -#: apps/activity/models.py:104 +#: apps/activity/models.py:105 msgid "Club that is authorized to join the activity. Mostly the Kfet club." msgstr "" "Club qui est autorisé à rejoindre l'activité. Très souvent le club Kfet." -#: apps/activity/models.py:108 +#: apps/activity/models.py:109 #: apps/activity/templates/activity/includes/activity_info.html:25 msgid "start date" msgstr "date de début" -#: apps/activity/models.py:112 +#: apps/activity/models.py:113 #: apps/activity/templates/activity/includes/activity_info.html:28 msgid "end date" msgstr "date de fin" -#: apps/activity/models.py:117 +#: apps/activity/models.py:118 #: apps/activity/templates/activity/includes/activity_info.html:50 -#: apps/note/models/transactions.py:146 +#: apps/note/models/transactions.py:149 msgid "valid" msgstr "valide" -#: apps/activity/models.py:122 +#: apps/activity/models.py:123 #: apps/activity/templates/activity/includes/activity_info.html:65 msgid "open" msgstr "ouvrir" -#: apps/activity/models.py:146 +#: apps/activity/models.py:151 msgid "activities" msgstr "activités" -#: apps/activity/models.py:166 +#: apps/activity/models.py:171 msgid "entry time" msgstr "heure d'entrée" -#: apps/activity/models.py:172 apps/note/apps.py:14 +#: apps/activity/models.py:177 apps/note/apps.py:14 #: apps/note/models/notes.py:78 msgid "note" msgstr "note" -#: apps/activity/models.py:183 +#: apps/activity/models.py:188 #: apps/activity/templates/activity/activity_entry.html:46 msgid "entry" msgstr "entrée" -#: apps/activity/models.py:184 +#: apps/activity/models.py:189 #: apps/activity/templates/activity/activity_entry.html:46 msgid "entries" msgstr "entrées" -#: apps/activity/models.py:190 +#: apps/activity/models.py:192 +#, python-brace-format +msgid "Entry for {guest}, invited by {note} to the activity {activity}" +msgstr "Entrée pour {guest}, invité par {note} à l'activité {activity}" + +#: apps/activity/models.py:194 +#, python-brace-format +msgid "Entry for {note} to the activity {activity}" +msgstr "Entrée de la note {note} pour l'activité « {activity} »" + +#: apps/activity/models.py:201 msgid "Already entered on " msgstr "Déjà rentré le " -#: apps/activity/models.py:190 apps/activity/tables.py:54 +#: apps/activity/models.py:201 apps/activity/tables.py:54 msgid "{:%Y-%m-%d %H:%M:%S}" msgstr "{:%d/%m/%Y %H:%M:%S}" -#: apps/activity/models.py:198 +#: apps/activity/models.py:209 msgid "The balance is negative." msgstr "La note est en négatif." -#: apps/activity/models.py:228 +#: apps/activity/models.py:239 msgid "last name" msgstr "nom de famille" -#: apps/activity/models.py:233 +#: apps/activity/models.py:244 #: apps/member/templates/member/includes/profile_info.html:4 #: apps/registration/templates/registration/future_profile_detail.html:16 #: apps/wei/templates/wei/weimembership_form.html:14 msgid "first name" msgstr "prénom" -#: apps/activity/models.py:240 +#: apps/activity/models.py:251 msgid "inviter" msgstr "hôte" -#: apps/activity/models.py:284 +#: apps/activity/models.py:295 msgid "guest" msgstr "invité" -#: apps/activity/models.py:285 +#: apps/activity/models.py:296 msgid "guests" msgstr "invités" -#: apps/activity/models.py:297 +#: apps/activity/models.py:308 msgid "Invitation" msgstr "Invitation" @@ -240,19 +250,19 @@ msgstr "Entré le " msgid "remove" msgstr "supprimer" -#: apps/activity/tables.py:80 apps/note/forms.py:68 apps/treasury/models.py:186 +#: apps/activity/tables.py:80 apps/note/forms.py:68 apps/treasury/models.py:192 msgid "Type" msgstr "Type" -#: apps/activity/tables.py:82 apps/member/forms.py:131 -#: apps/registration/forms.py:81 apps/treasury/forms.py:135 +#: apps/activity/tables.py:82 apps/member/forms.py:183 +#: apps/registration/forms.py:81 apps/treasury/forms.py:129 #: apps/wei/forms/registration.py:96 msgid "Last name" msgstr "Nom de famille" -#: apps/activity/tables.py:84 apps/member/forms.py:136 +#: apps/activity/tables.py:84 apps/member/forms.py:188 #: apps/note/templates/note/transaction_form.html:134 -#: apps/registration/forms.py:86 apps/treasury/forms.py:137 +#: apps/registration/forms.py:86 apps/treasury/forms.py:131 #: apps/wei/forms/registration.py:101 msgid "First name" msgstr "Prénom" @@ -270,21 +280,21 @@ msgid "Guests list" msgstr "Liste des invités" #: apps/activity/templates/activity/activity_entry.html:14 -#: apps/note/models/transactions.py:259 +#: apps/note/models/transactions.py:253 #: apps/note/templates/note/transaction_form.html:16 #: apps/note/templates/note/transaction_form.html:148 -#: note_kfet/templates/base.html:68 +#: note_kfet/templates/base.html:70 msgid "Transfer" msgstr "Virement" #: apps/activity/templates/activity/activity_entry.html:18 -#: apps/note/models/transactions.py:318 +#: apps/note/models/transactions.py:312 #: apps/note/templates/note/transaction_form.html:21 msgid "Credit" msgstr "Crédit" #: apps/activity/templates/activity/activity_entry.html:21 -#: apps/note/models/transactions.py:318 +#: apps/note/models/transactions.py:312 #: apps/note/templates/note/transaction_form.html:25 msgid "Debit" msgstr "Débit" @@ -302,7 +312,7 @@ msgstr "Retour à la page de l'activité" #: apps/member/templates/member/add_members.html:32 #: apps/member/templates/member/club_form.html:16 #: apps/note/templates/note/transactiontemplate_form.html:18 -#: apps/treasury/forms.py:93 apps/treasury/forms.py:147 +#: apps/treasury/forms.py:87 apps/treasury/forms.py:141 #: apps/treasury/templates/treasury/invoice_form.html:74 #: apps/wei/templates/wei/bus_form.html:17 #: apps/wei/templates/wei/busteam_form.html:17 @@ -356,7 +366,7 @@ msgid "validate" msgstr "valider" #: apps/activity/templates/activity/includes/activity_info.html:71 -#: apps/logs/models.py:62 apps/note/tables.py:162 +#: apps/logs/models.py:64 apps/note/tables.py:195 msgid "edit" msgstr "modifier" @@ -364,41 +374,41 @@ msgstr "modifier" msgid "Invite" msgstr "Inviter" -#: apps/activity/views.py:29 +#: apps/activity/views.py:33 msgid "Create new activity" msgstr "Créer une nouvelle activité" -#: apps/activity/views.py:59 note_kfet/templates/base.html:86 +#: apps/activity/views.py:63 note_kfet/templates/base.html:88 msgid "Activities" msgstr "Activités" -#: apps/activity/views.py:87 +#: apps/activity/views.py:91 msgid "Activity detail" msgstr "Détails de l'activité" -#: apps/activity/views.py:107 +#: apps/activity/views.py:111 msgid "Update activity" msgstr "Modifier l'activité" -#: apps/activity/views.py:134 +#: apps/activity/views.py:138 msgid "Invite guest to the activity \"{}\"" msgstr "Invitation pour l'activité « {} »" -#: apps/activity/views.py:168 +#: apps/activity/views.py:172 msgid "You are not allowed to display the entry interface for this activity." msgstr "" "Vous n'êtes pas autorisé à afficher l'interface des entrées pour cette " "activité." -#: apps/activity/views.py:171 +#: apps/activity/views.py:175 msgid "This activity does not support activity entries." msgstr "Cette activité ne requiert pas d'entrées." -#: apps/activity/views.py:174 +#: apps/activity/views.py:178 msgid "This activity is closed." msgstr "Cette activité est fermée." -#: apps/activity/views.py:272 +#: apps/activity/views.py:274 msgid "Entry for activity \"{}\"" msgstr "Entrées pour l'activité « {} »" @@ -422,59 +432,64 @@ msgstr "modèle" msgid "identifier" msgstr "identifiant" -#: apps/logs/models.py:48 +#: apps/logs/models.py:49 msgid "previous data" msgstr "données précédentes" -#: apps/logs/models.py:53 +#: apps/logs/models.py:55 msgid "new data" msgstr "ouvelles données" -#: apps/logs/models.py:61 +#: apps/logs/models.py:63 msgid "create" msgstr "créer" -#: apps/logs/models.py:63 apps/note/tables.py:132 apps/note/tables.py:168 +#: apps/logs/models.py:65 apps/note/tables.py:165 apps/note/tables.py:201 #: apps/permission/models.py:127 apps/treasury/tables.py:38 #: apps/wei/tables.py:75 msgid "delete" msgstr "supprimer" -#: apps/logs/models.py:66 +#: apps/logs/models.py:68 msgid "action" msgstr "action" -#: apps/logs/models.py:74 +#: apps/logs/models.py:76 msgid "timestamp" msgstr "date" -#: apps/logs/models.py:78 +#: apps/logs/models.py:80 msgid "Logs cannot be destroyed." msgstr "Les logs ne peuvent pas être détruits." -#: apps/logs/models.py:81 +#: apps/logs/models.py:83 msgid "changelog" msgstr "journal de modification" -#: apps/logs/models.py:82 +#: apps/logs/models.py:84 msgid "changelogs" msgstr "journaux de modifications" -#: apps/member/admin.py:52 apps/member/models.py:225 +#: apps/logs/models.py:87 +#, python-brace-format +msgid "Changelog of type \"{action}\" for model {model} at {timestamp}" +msgstr "Changelog de type « {action} » pour le modèle {model} à {timestamp}" + +#: apps/member/admin.py:50 apps/member/models.py:226 #: apps/member/templates/member/includes/club_info.html:34 msgid "membership fee (paid students)" msgstr "cotisation pour adhérer (normalien élève)" -#: apps/member/admin.py:53 apps/member/models.py:230 +#: apps/member/admin.py:51 apps/member/models.py:231 #: apps/member/templates/member/includes/club_info.html:37 msgid "membership fee (unpaid students)" msgstr "cotisation pour adhérer (normalien étudiant)" -#: apps/member/admin.py:67 apps/member/models.py:314 +#: apps/member/admin.py:65 apps/member/models.py:315 msgid "roles" msgstr "rôles" -#: apps/member/admin.py:68 apps/member/models.py:328 +#: apps/member/admin.py:66 apps/member/models.py:329 msgid "fee" msgstr "cotisation" @@ -482,69 +497,77 @@ msgstr "cotisation" msgid "member" msgstr "adhérent" -#: apps/member/forms.py:41 +#: apps/member/forms.py:23 +msgid "Permission mask" +msgstr "Masque de permissions" + +#: apps/member/forms.py:45 msgid "Report frequency" msgstr "Fréquence des rapports (en jours)" -#: apps/member/forms.py:43 +#: apps/member/forms.py:47 msgid "Last report date" msgstr "Date de dernier rapport" -#: apps/member/forms.py:48 +#: apps/member/forms.py:52 msgid "You can't register to the note if you come from the future." msgstr "Vous ne pouvez pas vous inscrire à la note si vous venez du futur." -#: apps/member/forms.py:73 +#: apps/member/forms.py:77 msgid "select an image" msgstr "choisissez une image" -#: apps/member/forms.py:74 +#: apps/member/forms.py:78 msgid "Maximal size: 2MB" msgstr "Taille maximale : 2 Mo" -#: apps/member/forms.py:87 apps/member/views.py:101 -#: apps/registration/forms.py:33 +#: apps/member/forms.py:103 +msgid "This image cannot be loaded." +msgstr "Cette image ne peut pas être chargée." + +#: apps/member/forms.py:139 apps/member/views.py:98 +#: apps/registration/forms.py:33 apps/registration/views.py:237 msgid "An alias with a similar name already exists." msgstr "Un alias avec un nom similaire existe déjà." -#: apps/member/forms.py:110 apps/registration/forms.py:61 +#: apps/member/forms.py:162 apps/registration/forms.py:61 msgid "Inscription paid by Société Générale" msgstr "Inscription payée par la Société générale" -#: apps/member/forms.py:112 apps/registration/forms.py:63 +#: apps/member/forms.py:164 apps/registration/forms.py:63 msgid "Check this case is the Société Générale paid the inscription." msgstr "Cochez cette case si la Société Générale a payé l'inscription." -#: apps/member/forms.py:117 apps/registration/forms.py:68 +#: apps/member/forms.py:169 apps/registration/forms.py:68 #: apps/wei/forms/registration.py:83 msgid "Credit type" msgstr "Type de rechargement" -#: apps/member/forms.py:118 apps/registration/forms.py:69 +#: apps/member/forms.py:170 apps/registration/forms.py:69 #: apps/wei/forms/registration.py:84 msgid "No credit" msgstr "Pas de rechargement" -#: apps/member/forms.py:120 +#: apps/member/forms.py:172 msgid "You can credit the note of the user." msgstr "Vous pouvez créditer la note de l'utisateur avant l'adhésion." -#: apps/member/forms.py:124 apps/registration/forms.py:74 +#: apps/member/forms.py:176 apps/registration/forms.py:74 #: apps/wei/forms/registration.py:89 msgid "Credit amount" msgstr "Montant à créditer" -#: apps/member/forms.py:141 apps/note/templates/note/transaction_form.html:140 -#: apps/registration/forms.py:91 apps/treasury/forms.py:139 +#: apps/member/forms.py:193 apps/note/templates/note/transaction_form.html:140 +#: apps/registration/forms.py:91 apps/treasury/forms.py:133 #: apps/wei/forms/registration.py:106 msgid "Bank" msgstr "Banque" -#: apps/member/forms.py:168 +#: apps/member/forms.py:220 msgid "User" msgstr "Utilisateur" -#: apps/member/forms.py:182 +#: apps/member/forms.py:234 msgid "Roles" msgstr "Rôles" @@ -660,19 +683,19 @@ msgstr "payé" msgid "Tells if the user receive a salary." msgstr "Indique si l'utilisateur perçoit un salaire." -#: apps/member/models.py:101 apps/treasury/tables.py:146 +#: apps/member/models.py:100 apps/treasury/tables.py:146 msgid "No" msgstr "Non" -#: apps/member/models.py:102 +#: apps/member/models.py:101 msgid "Yes (receive them in french)" msgstr "Oui (les recevoir en français)" -#: apps/member/models.py:103 +#: apps/member/models.py:102 msgid "Yes (receive them in english)" msgstr "Oui (les recevoir en anglais)" -#: apps/member/models.py:105 +#: apps/member/models.py:104 msgid "" "Register on the mailing list to stay informed of the events of the campus (1 " "mail/week)" @@ -680,7 +703,7 @@ msgstr "" "S'inscrire sur la liste de diffusion pour rester informé des événements sur " "le campus (1 mail par semaine)" -#: apps/member/models.py:110 +#: apps/member/models.py:109 msgid "" "Register on the mailing list to stay informed of the sport events of the " "campus (1 mail/week)" @@ -688,7 +711,7 @@ msgstr "" "S'inscrire sur la liste de diffusion pour rester informé des actualités " "sportives sur le campus (1 mail par semaine)" -#: apps/member/models.py:115 +#: apps/member/models.py:114 msgid "" "Register on the mailing list to stay informed of the art events of the " "campus (1 mail/week)" @@ -696,31 +719,31 @@ msgstr "" "S'inscrire sur la liste de diffusion pour rester informé des actualités " "artistiques sur le campus (1 mail par semaine)" -#: apps/member/models.py:119 +#: apps/member/models.py:118 msgid "report frequency (in days)" msgstr "fréquence des rapports (en jours)" -#: apps/member/models.py:124 +#: apps/member/models.py:123 msgid "last report date" msgstr "date de dernier rapport" -#: apps/member/models.py:129 +#: apps/member/models.py:128 msgid "email confirmed" msgstr "adresse email confirmée" -#: apps/member/models.py:134 +#: apps/member/models.py:133 msgid "registration valid" msgstr "inscription valide" -#: apps/member/models.py:163 apps/member/models.py:164 +#: apps/member/models.py:162 apps/member/models.py:163 msgid "user profile" msgstr "profil utilisateur" -#: apps/member/models.py:174 +#: apps/member/models.py:173 msgid "Activate your Note Kfet account" msgstr "Activez votre compte Note Kfet" -#: apps/member/models.py:203 +#: apps/member/models.py:204 #: apps/member/templates/member/includes/club_info.html:55 #: apps/member/templates/member/includes/profile_info.html:31 #: apps/registration/templates/registration/future_profile_detail.html:22 @@ -729,88 +752,88 @@ msgstr "Activez votre compte Note Kfet" msgid "email" msgstr "courriel" -#: apps/member/models.py:210 +#: apps/member/models.py:211 msgid "parent club" msgstr "club parent" -#: apps/member/models.py:219 +#: apps/member/models.py:220 msgid "require memberships" msgstr "nécessite des adhésions" -#: apps/member/models.py:220 +#: apps/member/models.py:221 msgid "Uncheck if this club don't require memberships." msgstr "Décochez si ce club n'utilise pas d'adhésions." -#: apps/member/models.py:236 +#: apps/member/models.py:237 #: apps/member/templates/member/includes/club_info.html:26 msgid "membership duration" msgstr "durée de l'adhésion" -#: apps/member/models.py:237 +#: apps/member/models.py:238 msgid "The longest time (in days) a membership can last (NULL = infinite)." msgstr "La durée maximale (en jours) d'une adhésion (NULL = infinie)." -#: apps/member/models.py:244 +#: apps/member/models.py:245 #: apps/member/templates/member/includes/club_info.html:16 msgid "membership start" msgstr "début de l'adhésion" -#: apps/member/models.py:245 +#: apps/member/models.py:246 msgid "Date from which the members can renew their membership." msgstr "" "Date à partir de laquelle les adhérents peuvent renouveler leur adhésion." -#: apps/member/models.py:251 +#: apps/member/models.py:252 #: apps/member/templates/member/includes/club_info.html:21 msgid "membership end" msgstr "fin de l'adhésion" -#: apps/member/models.py:252 +#: apps/member/models.py:253 msgid "Maximal date of a membership, after which members must renew it." msgstr "" "Date maximale d'une fin d'adhésion, après laquelle les adhérents doivent la " "renouveler." -#: apps/member/models.py:284 apps/member/models.py:309 -#: apps/note/models/notes.py:179 +#: apps/member/models.py:285 apps/member/models.py:310 +#: apps/note/models/notes.py:185 msgid "club" msgstr "club" -#: apps/member/models.py:285 +#: apps/member/models.py:286 msgid "clubs" msgstr "clubs" -#: apps/member/models.py:319 +#: apps/member/models.py:320 msgid "membership starts on" msgstr "l'adhésion commence le" -#: apps/member/models.py:323 +#: apps/member/models.py:324 msgid "membership ends on" msgstr "l'adhésion finit le" -#: apps/member/models.py:374 +#: apps/member/models.py:419 #, python-brace-format msgid "The role {role} does not apply to the club {club}." msgstr "Le rôle {role} ne s'applique pas au club {club}." -#: apps/member/models.py:385 apps/member/views.py:676 +#: apps/member/models.py:428 apps/member/views.py:628 msgid "User is already a member of the club" msgstr "L'utilisateur est déjà membre du club" -#: apps/member/models.py:433 +#: apps/member/models.py:440 msgid "User is not a member of the parent club" msgstr "L'utilisateur n'est pas membre du club parent" -#: apps/member/models.py:486 +#: apps/member/models.py:488 #, python-brace-format msgid "Membership of {user} for the club {club}" msgstr "Adhésion de {user} pour le club {club}" -#: apps/member/models.py:489 +#: apps/member/models.py:491 apps/note/models/transactions.py:353 msgid "membership" msgstr "adhésion" -#: apps/member/models.py:490 +#: apps/member/models.py:492 msgid "memberships" msgstr "adhésions" @@ -844,7 +867,7 @@ msgid "Account #" msgstr "Compte n°" #: apps/member/templates/member/base.html:48 -#: apps/member/templates/member/base.html:62 apps/member/views.py:59 +#: apps/member/templates/member/base.html:62 apps/member/views.py:57 #: apps/registration/templates/registration/future_profile_detail.html:48 #: apps/wei/templates/wei/weimembership_form.html:117 msgid "Update Profile" @@ -888,7 +911,7 @@ msgstr "" "déverrouiller lui-même." #: apps/member/templates/member/base.html:110 -#: apps/member/templates/member/base.html:137 apps/treasury/forms.py:95 +#: apps/member/templates/member/base.html:137 apps/treasury/forms.py:89 msgid "Close" msgstr "Fermer" @@ -904,8 +927,8 @@ msgstr "" "à nouveau possible." #: apps/member/templates/member/club_alias.html:10 -#: apps/member/templates/member/profile_alias.html:10 apps/member/views.py:240 -#: apps/member/views.py:450 +#: apps/member/templates/member/profile_alias.html:10 apps/member/views.py:236 +#: apps/member/views.py:433 msgid "Note aliases" msgstr "Alias de la note" @@ -969,7 +992,7 @@ msgstr "solde du compte" #: apps/member/templates/member/includes/club_info.html:47 #: apps/member/templates/member/includes/profile_info.html:20 -#: apps/note/models/notes.py:270 apps/wei/templates/wei/base.html:66 +#: apps/note/models/notes.py:276 apps/wei/templates/wei/base.html:66 msgid "aliases" msgstr "alias" @@ -1008,6 +1031,14 @@ msgstr "Créé le" msgid "Regenerate token" msgstr "Regénérer le jeton" +#: apps/member/templates/member/picture_update.html:35 +msgid "Nevermind" +msgstr "Annuler" + +#: apps/member/templates/member/picture_update.html:36 +msgid "Crop and upload" +msgstr "Recadrer et envoyer" + #: apps/member/templates/member/profile_detail.html:11 #: apps/registration/templates/registration/future_profile_detail.html:28 #: apps/wei/templates/wei/weimembership_form.html:26 @@ -1032,47 +1063,47 @@ msgstr "Sauvegarder les changements" msgid "Registrations" msgstr "Inscriptions" -#: apps/member/views.py:72 apps/registration/forms.py:23 +#: apps/member/views.py:70 apps/registration/forms.py:23 msgid "This address must be valid." msgstr "Cette adresse doit être valide." -#: apps/member/views.py:138 +#: apps/member/views.py:135 msgid "Profile detail" msgstr "Détails de l'utilisateur" -#: apps/member/views.py:201 +#: apps/member/views.py:195 msgid "Search user" msgstr "Chercher un utilisateur" -#: apps/member/views.py:260 +#: apps/member/views.py:256 msgid "Update note picture" msgstr "Modifier la photo de la note" -#: apps/member/views.py:318 +#: apps/member/views.py:301 msgid "Manage auth token" msgstr "Gérer les jetons d'authentification" -#: apps/member/views.py:346 +#: apps/member/views.py:328 msgid "Create new club" msgstr "Créer un nouveau club" -#: apps/member/views.py:364 +#: apps/member/views.py:347 msgid "Search club" msgstr "Chercher un club" -#: apps/member/views.py:397 +#: apps/member/views.py:380 msgid "Club detail" msgstr "Détails du club" -#: apps/member/views.py:473 +#: apps/member/views.py:456 msgid "Update club" msgstr "Modifier le club" -#: apps/member/views.py:507 +#: apps/member/views.py:490 msgid "Add new member to the club" msgstr "Ajouter un nouveau membre au club" -#: apps/member/views.py:667 apps/wei/views.py:922 +#: apps/member/views.py:619 apps/wei/views.py:922 msgid "" "This user don't have enough money to join this club, and can't have a " "negative balance." @@ -1080,44 +1111,44 @@ msgstr "" "Cet utilisateur n'a pas assez d'argent pour rejoindre ce club et ne peut pas " "avoir un solde négatif." -#: apps/member/views.py:680 +#: apps/member/views.py:632 msgid "The membership must start after {:%m-%d-%Y}." msgstr "L'adhésion doit commencer après le {:%d/%m/%Y}." -#: apps/member/views.py:685 +#: apps/member/views.py:637 msgid "The membership must begin before {:%m-%d-%Y}." msgstr "L'adhésion doit commencer avant le {:%d/%m/%Y}." -#: apps/member/views.py:701 apps/member/views.py:703 apps/member/views.py:705 -#: apps/registration/views.py:292 apps/registration/views.py:294 -#: apps/registration/views.py:296 apps/wei/views.py:927 apps/wei/views.py:931 +#: apps/member/views.py:644 apps/member/views.py:646 apps/member/views.py:648 +#: apps/registration/views.py:287 apps/registration/views.py:289 +#: apps/registration/views.py:291 apps/wei/views.py:927 apps/wei/views.py:931 msgid "This field is required." msgstr "Ce champ est requis." -#: apps/member/views.py:789 +#: apps/member/views.py:783 msgid "Manage roles of an user in the club" msgstr "Gérer les rôles d'un utilisateur dans le club" -#: apps/member/views.py:814 +#: apps/member/views.py:808 msgid "Members of the club" msgstr "Membres du club" -#: apps/note/admin.py:129 apps/note/models/transactions.py:106 +#: apps/note/admin.py:129 apps/note/models/transactions.py:109 msgid "source" msgstr "source" #: apps/note/admin.py:137 apps/note/admin.py:205 -#: apps/note/models/transactions.py:56 apps/note/models/transactions.py:119 +#: apps/note/models/transactions.py:56 apps/note/models/transactions.py:122 msgid "destination" msgstr "destination" #: apps/note/admin.py:210 apps/note/models/transactions.py:60 -#: apps/note/models/transactions.py:137 +#: apps/note/models/transactions.py:140 msgid "amount" msgstr "montant" -#: apps/note/api/serializers.py:178 apps/note/api/serializers.py:184 -#: apps/note/models/transactions.py:224 +#: apps/note/api/serializers.py:183 apps/note/api/serializers.py:189 +#: apps/note/models/transactions.py:226 msgid "" "The transaction can't be saved since the source note or the destination note " "is not active." @@ -1177,7 +1208,7 @@ msgstr "dernier instant où la note était en négatif" msgid "display image" msgstr "image affichée" -#: apps/note/models/notes.py:54 apps/note/models/transactions.py:129 +#: apps/note/models/notes.py:54 apps/note/models/transactions.py:132 msgid "created at" msgstr "créée le" @@ -1210,68 +1241,68 @@ msgstr "" msgid "notes" msgstr "notes" -#: apps/note/models/notes.py:122 +#: apps/note/models/notes.py:128 msgid "This alias is already taken." msgstr "Cet alias est déjà pris." -#: apps/note/models/notes.py:142 +#: apps/note/models/notes.py:148 msgid "one's note" msgstr "note d'un utilisateur" -#: apps/note/models/notes.py:143 +#: apps/note/models/notes.py:149 msgid "users note" msgstr "notes des utilisateurs" -#: apps/note/models/notes.py:149 +#: apps/note/models/notes.py:155 #, python-format msgid "%(user)s's note" msgstr "Note de %(user)s" -#: apps/note/models/notes.py:183 +#: apps/note/models/notes.py:189 msgid "club note" msgstr "note d'un club" -#: apps/note/models/notes.py:184 +#: apps/note/models/notes.py:190 msgid "clubs notes" msgstr "notes des clubs" -#: apps/note/models/notes.py:190 +#: apps/note/models/notes.py:196 #, python-format msgid "Note of %(club)s club" msgstr "Note du club %(club)s" -#: apps/note/models/notes.py:229 +#: apps/note/models/notes.py:235 msgid "special note" msgstr "note spéciale" -#: apps/note/models/notes.py:230 +#: apps/note/models/notes.py:236 msgid "special notes" msgstr "notes spéciales" -#: apps/note/models/notes.py:253 +#: apps/note/models/notes.py:259 msgid "Invalid alias" msgstr "Alias invalide" -#: apps/note/models/notes.py:269 +#: apps/note/models/notes.py:275 msgid "alias" msgstr "alias" -#: apps/note/models/notes.py:293 +#: apps/note/models/notes.py:299 msgid "Alias is too long." msgstr "L'alias est trop long." -#: apps/note/models/notes.py:296 +#: apps/note/models/notes.py:302 msgid "" "This alias contains only complex character. Please use a more simple alias." msgstr "" "Cet alias ne contient que des caractères complexes. Merci d'utiliser un " "alias plus simple." -#: apps/note/models/notes.py:300 +#: apps/note/models/notes.py:306 msgid "An alias with a similar name already exists: {} " msgstr "Un alias avec un nom similaire existe déjà : {} " -#: apps/note/models/notes.py:313 +#: apps/note/models/notes.py:319 msgid "You can't delete your main alias." msgstr "Vous ne pouvez pas supprimer votre alias principal." @@ -1303,33 +1334,33 @@ msgstr "modèle de transaction" msgid "transaction templates" msgstr "modèles de transaction" -#: apps/note/models/transactions.py:112 apps/note/models/transactions.py:125 -#: apps/note/tables.py:33 apps/note/tables.py:42 +#: apps/note/models/transactions.py:115 apps/note/models/transactions.py:128 +#: apps/note/tables.py:34 apps/note/tables.py:44 msgid "used alias" msgstr "alias utilisé" -#: apps/note/models/transactions.py:133 +#: apps/note/models/transactions.py:136 msgid "quantity" msgstr "quantité" -#: apps/note/models/transactions.py:141 +#: apps/note/models/transactions.py:144 msgid "reason" msgstr "raison" -#: apps/note/models/transactions.py:151 apps/note/tables.py:107 +#: apps/note/models/transactions.py:154 apps/note/tables.py:140 msgid "invalidity reason" msgstr "motif d'invalidité" -#: apps/note/models/transactions.py:159 +#: apps/note/models/transactions.py:161 msgid "transaction" msgstr "transaction" -#: apps/note/models/transactions.py:160 +#: apps/note/models/transactions.py:162 #: apps/treasury/templates/treasury/sogecredit_detail.html:22 msgid "transactions" msgstr "transactions" -#: apps/note/models/transactions.py:182 +#: apps/note/models/transactions.py:184 #, python-brace-format msgid "" "You can't update the {field} on a Transaction. Please invalidate it and " @@ -1338,7 +1369,7 @@ msgstr "" "Vous ne pouvez pas mettre à jour le champ {field} dans une transaction. " "Merci de l'invalider et d'en créer une autre." -#: apps/note/models/transactions.py:202 +#: apps/note/models/transactions.py:204 msgid "" "The note balances must be between - 92 233 720 368 547 758.08 € and 92 233 " "720 368 547 758.07 €." @@ -1347,7 +1378,7 @@ msgstr "" "€ et 92 233 720 368 547 758.07 €. Ne cherchez pas à capitaliser l'argent du " "BDE." -#: apps/note/models/transactions.py:279 +#: apps/note/models/transactions.py:273 msgid "" "The destination of this transaction must equal to the destination of the " "template." @@ -1355,27 +1386,27 @@ msgstr "" "Le destinataire de cette transaction doit être identique à celui du bouton " "utilisé." -#: apps/note/models/transactions.py:288 +#: apps/note/models/transactions.py:282 msgid "Template" msgstr "Bouton" -#: apps/note/models/transactions.py:291 +#: apps/note/models/transactions.py:285 msgid "recurrent transaction" msgstr "transaction issue de bouton" -#: apps/note/models/transactions.py:292 +#: apps/note/models/transactions.py:286 msgid "recurrent transactions" msgstr "transactions issues de boutons" -#: apps/note/models/transactions.py:307 +#: apps/note/models/transactions.py:301 msgid "first_name" msgstr "prénom" -#: apps/note/models/transactions.py:312 +#: apps/note/models/transactions.py:306 msgid "bank" msgstr "banque" -#: apps/note/models/transactions.py:329 +#: apps/note/models/transactions.py:323 msgid "" "A special transaction is only possible between a Note associated to a " "payment method and a User or a Club" @@ -1383,35 +1414,35 @@ msgstr "" "Une transaction spéciale n'est possible que entre une note associée à un " "mode de paiement et un utilisateur ou un club" -#: apps/note/models/transactions.py:337 +#: apps/note/models/transactions.py:331 msgid "Special transaction" msgstr "Transaction de crédit/retrait" -#: apps/note/models/transactions.py:338 +#: apps/note/models/transactions.py:332 msgid "Special transactions" msgstr "Transactions de crédit/retrait" -#: apps/note/models/transactions.py:354 apps/note/models/transactions.py:359 +#: apps/note/models/transactions.py:348 msgid "membership transaction" msgstr "transaction d'adhésion" -#: apps/note/models/transactions.py:355 apps/treasury/models.py:273 +#: apps/note/models/transactions.py:349 apps/treasury/models.py:282 msgid "membership transactions" msgstr "transactions d'adhésion" -#: apps/note/tables.py:61 +#: apps/note/tables.py:94 msgid "Click to invalidate" msgstr "Cliquez pour dévalider" -#: apps/note/tables.py:61 +#: apps/note/tables.py:94 msgid "Click to validate" msgstr "Cliquez pour valider" -#: apps/note/tables.py:105 +#: apps/note/tables.py:138 msgid "No reason specified" msgstr "Pas de motif spécifié" -#: apps/note/tables.py:136 apps/note/tables.py:170 apps/treasury/tables.py:39 +#: apps/note/tables.py:169 apps/note/tables.py:203 apps/treasury/tables.py:39 #: apps/treasury/templates/treasury/invoice_confirm_delete.html:30 #: apps/treasury/templates/treasury/sogecredit_detail.html:59 #: apps/wei/tables.py:76 apps/wei/tables.py:103 @@ -1419,7 +1450,7 @@ msgstr "Pas de motif spécifié" msgid "Delete" msgstr "Supprimer" -#: apps/note/tables.py:164 apps/note/templates/note/conso_form.html:132 +#: apps/note/tables.py:197 apps/note/templates/note/conso_form.html:132 #: apps/wei/tables.py:47 apps/wei/tables.py:48 #: apps/wei/templates/wei/base.html:89 #: apps/wei/templates/wei/bus_detail.html:20 @@ -1467,7 +1498,8 @@ msgstr "Historique des transactions récentes" #: apps/note/templates/note/mails/negative_balance.txt:25 #: apps/note/templates/note/mails/negative_notes_report.html:46 #: apps/note/templates/note/mails/negative_notes_report.txt:13 -#: apps/note/templates/note/mails/weekly_report.html:54 +#: apps/note/templates/note/mails/weekly_report.html:51 +#: apps/note/templates/note/mails/weekly_report.txt:32 #: apps/registration/templates/registration/mails/email_validation_email.html:40 #: apps/registration/templates/registration/mails/email_validation_email.txt:16 msgid "Mail generated by the Note Kfet on the" @@ -1492,7 +1524,7 @@ msgid "Action" msgstr "Action" #: apps/note/templates/note/transaction_form.html:112 -#: apps/treasury/forms.py:141 apps/treasury/tables.py:67 +#: apps/treasury/forms.py:135 apps/treasury/tables.py:67 #: apps/treasury/tables.py:135 #: apps/treasury/templates/treasury/remittance_form.html:23 msgid "Amount" @@ -1567,7 +1599,7 @@ msgstr "Chercher un bouton" msgid "Update button" msgstr "Modifier le bouton" -#: apps/note/views.py:151 note_kfet/templates/base.html:62 +#: apps/note/views.py:151 note_kfet/templates/base.html:64 msgid "Consumptions" msgstr "Consommations" @@ -1678,7 +1710,7 @@ msgstr "" "Vous n'avez pas la permission d'ajouter une instance du modèle {app_label}." "{model_name}." -#: apps/permission/signals.py:101 +#: apps/permission/signals.py:102 #, python-brace-format msgid "" "You don't have the permission to delete this instance of model {app_label}." @@ -1746,7 +1778,7 @@ msgstr "" "Vous n'avez pas la permission d'ajouter une instance du modèle « {model} » " "avec ces paramètres. Merci de les corriger et de réessayer." -#: apps/permission/views.py:96 note_kfet/templates/base.html:104 +#: apps/permission/views.py:96 note_kfet/templates/base.html:106 msgid "Rights" msgstr "Droits" @@ -1783,23 +1815,23 @@ msgstr "Adhérer au club BDE" msgid "Join Kfet Club" msgstr "Adhérer au club Kfet" -#: apps/registration/templates/registration/email_validation_complete.html:9 +#: apps/registration/templates/registration/email_validation_complete.html:15 msgid "Your email have successfully been validated." msgstr "Votre adresse e-mail a bien été validée." -#: apps/registration/templates/registration/email_validation_complete.html:11 +#: apps/registration/templates/registration/email_validation_complete.html:19 #, python-format msgid "You can now log in." msgstr "Vous pouvez désormais vous connecter." -#: apps/registration/templates/registration/email_validation_complete.html:13 +#: apps/registration/templates/registration/email_validation_complete.html:23 msgid "" "You must pay now your membership in the Kfet to complete your registration." msgstr "" "Vous devez désormais payer votre adhésion à la Kfet pour compléter votre " "inscription." -#: apps/registration/templates/registration/email_validation_complete.html:16 +#: apps/registration/templates/registration/email_validation_complete.html:28 msgid "" "The link was invalid. The token may have expired. Please send us an email to " "activate your account." @@ -1807,24 +1839,20 @@ msgstr "" "Le lien est invalide. Le jeton a sans doute expiré. Merci de nous contacter " "pour activer votre compte." -#: apps/registration/templates/registration/email_validation_email_sent.html:8 +#: apps/registration/templates/registration/email_validation_email_sent.html:10 msgid "Account activation" msgstr "Activation du compte" -#: apps/registration/templates/registration/email_validation_email_sent.html:11 +#: apps/registration/templates/registration/email_validation_email_sent.html:14 msgid "" "An email has been sent. Please click on the link to activate your account." msgstr "" "Un email vient de vous être envoyé. Merci de cliquer sur le lien de " "validation pour activer votre compte." -#: apps/registration/templates/registration/email_validation_email_sent.html:15 -msgid "" -"You must also go to the Kfet to pay your membership. The WEI registration " -"includes the BDE membership." -msgstr "" -"Vous devrez également vous rendre à la Kfet pour payer votre adhésion. " -"L'inscription au WEI inclut l'adhésion au BDE." +#: apps/registration/templates/registration/email_validation_email_sent.html:17 +msgid "You must also go to the Kfet to pay your membership." +msgstr "Vous devrez également vous rendre à la Kfet pour payer votre adhésion." #: apps/registration/templates/registration/future_profile_detail.html:49 #: apps/wei/templates/wei/weiregistration_confirm_delete.html:11 @@ -1870,12 +1898,10 @@ msgstr "Ce lien n'est valide que pendant quelques jours." #: apps/registration/templates/registration/mails/email_validation_email.txt:11 msgid "" "After that, you'll have to wait that someone validates your account before " -"you can log in. You will need to pay your membership in the Kfet. Note that " -"the WEI registration includes the Kfet membership." +"you can log in. You will need to pay your membership in the Kfet." msgstr "" "Après cela, vous devrez attendre que quelqu'un valide votre compte avant de " -"pouvoir vous connecter. Vous devrez payer votre adhésion à la Kfet. Notez " -"que l'adhésion Kfet est incluse dans l'inscription au WEI." +"pouvoir vous connecter. Vous devrez payer votre adhésion à la Kfet." #: apps/registration/templates/registration/mails/email_validation_email.html:34 #: apps/registration/templates/registration/mails/email_validation_email.txt:13 @@ -1915,46 +1941,47 @@ msgstr "Renvoyer le lien de validation" msgid "Pre-registered users list" msgstr "Liste des utilisateurs en attente d'inscription" -#: apps/registration/views.py:190 +#: apps/registration/views.py:187 msgid "Unregistered users" msgstr "Utilisateurs en attente d'inscription" -#: apps/registration/views.py:203 +#: apps/registration/views.py:200 msgid "Registration detail" msgstr "Détails de l'inscription" -#: apps/registration/views.py:258 +#: apps/registration/views.py:256 msgid "You must join the BDE." msgstr "Vous devez adhérer au BDE." #: apps/registration/views.py:280 -msgid "You must join BDE club before joining Kfet club." -msgstr "Vous devez adhérer au club BDE avant d'adhérer au club Kfet." - -#: apps/registration/views.py:285 msgid "" "The entered amount is not enough for the memberships, should be at least {}" msgstr "" "Le montant crédité est trop faible pour adhérer, il doit être au minimum de " "{}" -#: apps/registration/views.py:360 +#: apps/registration/views.py:355 msgid "Invalidate pre-registration" msgstr "Invalider l'inscription" -#: apps/treasury/apps.py:12 note_kfet/templates/base.html:92 +#: apps/treasury/apps.py:12 note_kfet/templates/base.html:94 msgid "Treasury" msgstr "Trésorerie" -#: apps/treasury/forms.py:104 +#: apps/treasury/forms.py:24 apps/treasury/models.py:89 +#: apps/treasury/templates/treasury/invoice_form.html:22 +msgid "This invoice is locked and can no longer be edited." +msgstr "Cette facture est verrouillée et ne peut plus être éditée." + +#: apps/treasury/forms.py:98 msgid "Remittance is already closed." msgstr "La remise est déjà fermée." -#: apps/treasury/forms.py:109 +#: apps/treasury/forms.py:103 msgid "You can't change the type of the remittance." msgstr "Vous ne pouvez pas changer le type de la remise." -#: apps/treasury/forms.py:129 apps/treasury/models.py:252 +#: apps/treasury/forms.py:123 apps/treasury/models.py:258 #: apps/treasury/tables.py:97 apps/treasury/tables.py:105 #: apps/treasury/templates/treasury/invoice_list.html:16 #: apps/treasury/templates/treasury/remittance_list.html:16 @@ -1962,7 +1989,7 @@ msgstr "Vous ne pouvez pas changer le type de la remise." msgid "Remittance" msgstr "Remise" -#: apps/treasury/forms.py:130 +#: apps/treasury/forms.py:124 msgid "No attached remittance" msgstr "Pas de remise associée" @@ -1986,7 +2013,7 @@ msgstr "Description" msgid "Address" msgstr "Adresse" -#: apps/treasury/models.py:60 apps/treasury/models.py:180 +#: apps/treasury/models.py:60 apps/treasury/models.py:186 msgid "Date" msgstr "Date" @@ -2006,12 +2033,7 @@ msgstr "Une facture ne peut plus être modifiée si elle est verrouillée." msgid "tex source" msgstr "fichier TeX source" -#: apps/treasury/models.py:89 -#: apps/treasury/templates/treasury/invoice_form.html:22 -msgid "This invoice is locked and can no longer be edited." -msgstr "Cette facture est verrouillée et ne peut plus être éditée." - -#: apps/treasury/models.py:109 apps/treasury/models.py:122 +#: apps/treasury/models.py:109 apps/treasury/models.py:125 msgid "invoice" msgstr "facture" @@ -2019,67 +2041,72 @@ msgstr "facture" msgid "invoices" msgstr "factures" -#: apps/treasury/models.py:127 +#: apps/treasury/models.py:113 +#, python-brace-format +msgid "Invoice #{id}" +msgstr "Facture n°{id}" + +#: apps/treasury/models.py:130 msgid "Designation" msgstr "Désignation" -#: apps/treasury/models.py:131 +#: apps/treasury/models.py:134 msgid "Quantity" msgstr "Quantité" -#: apps/treasury/models.py:135 +#: apps/treasury/models.py:138 msgid "Unit price" msgstr "Prix unitaire" -#: apps/treasury/models.py:151 +#: apps/treasury/models.py:154 msgid "product" msgstr "produit" -#: apps/treasury/models.py:152 +#: apps/treasury/models.py:155 msgid "products" msgstr "produits" -#: apps/treasury/models.py:169 +#: apps/treasury/models.py:175 msgid "remittance type" msgstr "type de remise" -#: apps/treasury/models.py:170 +#: apps/treasury/models.py:176 msgid "remittance types" msgstr "types de remises" -#: apps/treasury/models.py:191 +#: apps/treasury/models.py:197 msgid "Comment" msgstr "Commentaire" -#: apps/treasury/models.py:196 +#: apps/treasury/models.py:202 msgid "Closed" msgstr "Fermée" -#: apps/treasury/models.py:200 +#: apps/treasury/models.py:206 msgid "remittance" msgstr "remise" -#: apps/treasury/models.py:201 +#: apps/treasury/models.py:207 msgid "remittances" msgstr "remises" -#: apps/treasury/models.py:233 +#: apps/treasury/models.py:239 msgid "Remittance #{:d}: {}" msgstr "Remise n°{:d} : {}" -#: apps/treasury/models.py:256 +#: apps/treasury/models.py:262 msgid "special transaction proxy" msgstr "proxy de transaction spéciale" -#: apps/treasury/models.py:257 +#: apps/treasury/models.py:263 msgid "special transaction proxies" msgstr "proxys de transactions spéciales" -#: apps/treasury/models.py:279 +#: apps/treasury/models.py:288 msgid "credit transaction" msgstr "transaction de crédit" -#: apps/treasury/models.py:343 +#: apps/treasury/models.py:352 msgid "" "This user doesn't have enough money to pay the memberships with its note. " "Please ask her/him to credit the note before invalidating this credit." @@ -2087,15 +2114,20 @@ msgstr "" "Cet utilisateur n'a pas assez d'argent pour payer les adhésions avec sa " "note. Merci de lui demander de recharger sa note avant d'invalider ce crédit." -#: apps/treasury/models.py:355 +#: apps/treasury/models.py:364 #: apps/treasury/templates/treasury/sogecredit_detail.html:10 msgid "Credit from the Société générale" msgstr "Crédit de la Société générale" -#: apps/treasury/models.py:356 +#: apps/treasury/models.py:365 msgid "Credits from the Société générale" msgstr "Crédits de la Société générale" +#: apps/treasury/models.py:368 +#, python-brace-format +msgid "Soge credit for {user}" +msgstr "Crédit de la société générale pour l'utilisateur {user}" + #: apps/treasury/tables.py:20 msgid "Invoice #{:d}" msgstr "Facture n°{:d}" @@ -2120,11 +2152,12 @@ msgid "Yes" msgstr "Oui" #: apps/treasury/templates/treasury/invoice_confirm_delete.html:10 -#: apps/treasury/views.py:166 +#: apps/treasury/views.py:176 msgid "Delete invoice" msgstr "Supprimer la facture" #: apps/treasury/templates/treasury/invoice_confirm_delete.html:15 +#: apps/treasury/views.py:180 msgid "This invoice is locked and can't be deleted." msgstr "Cette facture est verrouillée et ne peut pas être supprimée." @@ -2292,46 +2325,46 @@ msgstr "" msgid "Create new invoice" msgstr "Créer une nouvelle facture" -#: apps/treasury/views.py:89 +#: apps/treasury/views.py:94 msgid "Invoices list" msgstr "Liste des factures" -#: apps/treasury/views.py:104 apps/treasury/views.py:265 -#: apps/treasury/views.py:391 +#: apps/treasury/views.py:109 apps/treasury/views.py:282 +#: apps/treasury/views.py:408 msgid "You are not able to see the treasury interface." msgstr "Vous n'êtes pas autorisé à voir l'interface de trésorerie." -#: apps/treasury/views.py:114 +#: apps/treasury/views.py:119 msgid "Update an invoice" msgstr "Modifier la facture" -#: apps/treasury/views.py:226 +#: apps/treasury/views.py:243 msgid "Create a new remittance" msgstr "Créer une nouvelle remise" -#: apps/treasury/views.py:253 +#: apps/treasury/views.py:270 msgid "Remittances list" msgstr "Liste des remises" -#: apps/treasury/views.py:316 +#: apps/treasury/views.py:333 msgid "Update a remittance" msgstr "Modifier la remise" -#: apps/treasury/views.py:339 +#: apps/treasury/views.py:356 msgid "Attach a transaction to a remittance" msgstr "Joindre une transaction à une remise" -#: apps/treasury/views.py:383 +#: apps/treasury/views.py:400 msgid "List of credits from the Société générale" msgstr "Liste des crédits de la Société générale" -#: apps/treasury/views.py:426 +#: apps/treasury/views.py:443 msgid "Manage credits from the Société générale" msgstr "Gérer les crédits de la Société générale" #: apps/wei/apps.py:10 apps/wei/models.py:49 apps/wei/models.py:50 #: apps/wei/models.py:61 apps/wei/models.py:167 -#: note_kfet/templates/base.html:98 +#: note_kfet/templates/base.html:100 msgid "WEI" msgstr "WEI" @@ -2935,23 +2968,46 @@ msgstr "" msgid "Reset" msgstr "Réinitialiser" -#: note_kfet/templates/base.html:13 +#: note_kfet/templates/base.html:14 msgid "The ENS Paris-Saclay BDE note." msgstr "La note du BDE de l'ENS Paris-Saclay." -#: note_kfet/templates/base.html:74 +#: note_kfet/templates/base.html:76 msgid "Users" msgstr "Utilisateurs" -#: note_kfet/templates/base.html:80 +#: note_kfet/templates/base.html:82 msgid "Clubs" msgstr "Clubs" -#: note_kfet/templates/base.html:109 +#: note_kfet/templates/base.html:111 msgid "Admin" msgstr "Admin" -#: note_kfet/templates/base.html:153 +#: note_kfet/templates/base.html:125 +msgid "My account" +msgstr "Mon compte" + +#: note_kfet/templates/base.html:128 +msgid "Log out" +msgstr "Se déconnecter" + +#: note_kfet/templates/base.html:136 +#: note_kfet/templates/registration/signup.html:6 +#: note_kfet/templates/registration/signup.html:11 +#: note_kfet/templates/registration/signup.html:27 +msgid "Sign up" +msgstr "Inscription" + +#: note_kfet/templates/base.html:143 +#: note_kfet/templates/registration/login.html:6 +#: note_kfet/templates/registration/login.html:15 +#: note_kfet/templates/registration/login.html:38 +#: note_kfet/templates/registration/password_reset_complete.html:15 +msgid "Log in" +msgstr "Se connecter" + +#: note_kfet/templates/base.html:155 msgid "" "Your e-mail address is not validated. Please check your mail inbox and click " "on the validation link." @@ -2959,6 +3015,10 @@ msgstr "" "Votre adresse e-mail n'est pas validée. Merci de vérifier votre boîte mail " "et de cliquer sur le lien de validation." +#: note_kfet/templates/base.html:172 +msgid "Contact us" +msgstr "Nous contacter" + #: note_kfet/templates/base_search.html:15 msgid "Search by attribute such as name…" msgstr "Chercher par un attribut tel que le nom …" @@ -2990,13 +3050,6 @@ msgstr "Merci d'avoir utilisé la Note Kfet." msgid "Log in again" msgstr "Se connecter à nouveau" -#: note_kfet/templates/registration/login.html:6 -#: note_kfet/templates/registration/login.html:15 -#: note_kfet/templates/registration/login.html:38 -#: note_kfet/templates/registration/password_reset_complete.html:15 -msgid "Log in" -msgstr "Se connecter" - #: note_kfet/templates/registration/login.html:20 #, python-format msgid "" @@ -3088,12 +3141,6 @@ msgstr "" msgid "Reset my password" msgstr "Réinitialiser mon mot de passe" -#: note_kfet/templates/registration/signup.html:6 -#: note_kfet/templates/registration/signup.html:11 -#: note_kfet/templates/registration/signup.html:27 -msgid "Sign up" -msgstr "Inscription" - #: note_kfet/templates/registration/signup.html:15 msgid "" "If you already signed up, your registration is taken into account. The BDE " @@ -3106,914 +3153,3 @@ msgstr "" "vous connecter. Vous devez vous rendre à la Kfet et payer les frais " "d'adhésion. Vous devez également valider votre adresse email en suivant le " "lien que vous avez reçu." - -#~ msgid "Enter a valid color." -#~ msgstr "Entrer une couleur valide." - -#~ msgid "i18n text" -#~ msgstr "i18n text" - -#~ msgid "i18n legend" -#~ msgstr "i18n legend" - -#~ msgid "Enter a valid value." -#~ msgstr "Entrer une valeur correcte." - -#~ msgid "Messages" -#~ msgstr "Messages" - -#~ msgid "Site Maps" -#~ msgstr "Plan du site" - -#~ msgid "Static Files" -#~ msgstr "Fichiers statiques" - -#~ msgid "Syndication" -#~ msgstr "Invitation" - -#~ msgid "That page number is not an integer" -#~ msgstr "Ce numéro de page n'est pas entier" - -#~ msgid "That page number is less than 1" -#~ msgstr "Ce numéro de page est inférieur à 1" - -#~ msgid "That page contains no results" -#~ msgstr "Il n'y a pas de résultat" - -#~ msgid "Enter a valid URL." -#~ msgstr "Entrer une URL valide." - -#~ msgid "Enter a valid integer." -#~ msgstr "Entrer un entier valid." - -#~ msgid "Enter a valid email address." -#~ msgstr "Entrer une adresse mail valide." - -#~ msgid "" -#~ "Enter a valid 'slug' consisting of letters, numbers, underscores or " -#~ "hyphens." -#~ msgstr "" -#~ "Entrer un 'slug' valide, constitué de lettres, chiffres, tirets ou tirets " -#~ "bas." - -#~ msgid "" -#~ "Enter a valid 'slug' consisting of Unicode letters, numbers, underscores, " -#~ "or hyphens." -#~ msgstr "" -#~ "Entrer un 'slug' valide, constitué de caractère unicode, chiffres, tirets " -#~ "ou underscores." - -#~ msgid "Enter a valid IPv4 address." -#~ msgstr "Entrer une adresse IPv4 valide." - -#~ msgid "Enter a valid IPv6 address." -#~ msgstr "Entrer une adresse IPv6 valide." - -#~ msgid "Enter a valid IPv4 or IPv6 address." -#~ msgstr "Entrer une adresse IPv4 ou IPv6 valide." - -#~ msgid "Enter only digits separated by commas." -#~ msgstr "Entrer seulement des chiffres séparés par des virgules." - -#~ msgid "Ensure this value is %(limit_value)s (it is %(show_value)s)." -#~ msgstr "" -#~ "Vérifier que cette valeur est %(limit_value)s (actuellement " -#~ "%(show_value)s)." - -#~ msgid "Ensure this value is less than or equal to %(limit_value)s." -#~ msgstr "Vérifier que cette valeur est plus petite que %(limit_value)s." - -#~ msgid "Ensure this value is greater than or equal to %(limit_value)s." -#~ msgstr "Vérifier que cette valeur est plus grande que %(limit_value)s." - -#~ msgid "" -#~ "Ensure this value has at least %(limit_value)d character (it has " -#~ "%(show_value)d)." -#~ msgid_plural "" -#~ "Ensure this value has at least %(limit_value)d characters (it has " -#~ "%(show_value)d)." -#~ msgstr[0] "" -#~ "Vérifier que cette valeur a au moins %(limit_value)d caractère " -#~ "(actuellement %(show_value)d)." -#~ msgstr[1] "" -#~ "Assurer vous que cette valeur a au moins %(limit_value)d caractères " -#~ "(actuellement %(show_value)d)." - -#~ msgid "" -#~ "Ensure this value has at most %(limit_value)d character (it has " -#~ "%(show_value)d)." -#~ msgid_plural "" -#~ "Ensure this value has at most %(limit_value)d characters (it has " -#~ "%(show_value)d)." -#~ msgstr[0] "" -#~ "Vérifier que cette valeur a au plus %(limit_value)d caractère " -#~ "(actuellement %(show_value)d)." -#~ msgstr[1] "" -#~ "Assurer vous que cette valeur a au plus %(limit_value)d caractères " -#~ "(actuellement %(show_value)d)." - -#~ msgid "Enter a number." -#~ msgstr "Numéro de téléphone." - -#~ msgid "Ensure that there are no more than %(max)s digit in total." -#~ msgid_plural "Ensure that there are no more than %(max)s digits in total." -#~ msgstr[0] "Vérifier qu'il n'y a pas plus de %(max)s chiffre au total." -#~ msgstr[1] "Vérifier qu'il n'y a pas plus de %(max)s chiffres au total." - -#~ msgid "Ensure that there are no more than %(max)s decimal place." -#~ msgid_plural "Ensure that there are no more than %(max)s decimal places." -#~ msgstr[0] "Vérifier qu'il y n'as pas plus de %(max)s chiffre décimal." -#~ msgstr[1] "Vérifier qu'il y n'as pas plus de %(max)s chiffres décimaux." - -#~ msgid "" -#~ "Ensure that there are no more than %(max)s digit before the decimal point." -#~ msgid_plural "" -#~ "Ensure that there are no more than %(max)s digits before the decimal " -#~ "point." -#~ msgstr[0] "" -#~ "Vérifier qu'il y n'as pas plus d'%(max)s chiffre avant la virgule." -#~ msgstr[1] "" -#~ "Vérifier qu'il y n'as pas plus de %(max)s chiffres avant la virgule." - -#~ msgid "" -#~ "File extension '%(extension)s' is not allowed. Allowed extensions are: " -#~ "'%(allowed_extensions)s'." -#~ msgstr "" -#~ "Les fichiers d'extension '%(extension)s' ne sont pas autorisé. Les " -#~ "extension autorisées sont: \"%(allowed_extensions)s'." - -#~ msgid "Null characters are not allowed." -#~ msgstr "Les caractères nuls ne sont pas autorisés." - -#~ msgid "and" -#~ msgstr "et" - -#~ msgid "%(model_name)s with this %(field_labels)s already exists." -#~ msgstr "Un %(model_name)s avec ce %(field_labels)s existe déjà." - -#~ msgid "Value %(value)r is not a valid choice." -#~ msgstr "Le choix %(value)r n'est pas possible." - -#~ msgid "This field cannot be null." -#~ msgstr "Ce champ est requis." - -#~ msgid "This field cannot be blank." -#~ msgstr "Ce champ est requis." - -#~ msgid "%(model_name)s with this %(field_label)s already exists." -#~ msgstr "Un %(model_name)s avec ce %(field_label)s existe déjà." - -#~ msgid "" -#~ "%(field_label)s must be unique for %(date_field_label)s %(lookup_type)s." -#~ msgstr "" -#~ "%(field_label)s doit être unique pour %(date_field_label)s " -#~ "%(lookup_type)s." - -#~ msgid "Field of type: %(field_type)s" -#~ msgstr "Champ du type %(field_type)s" - -#~ msgid "Integer" -#~ msgstr "Nombre entier" - -#~ msgid "'%(value)s' value must be an integer." -#~ msgstr "'%(value)s' doit être un nombre entier." - -#~ msgid "Big (8 byte) integer" -#~ msgstr "Gros nombre entier (8 octets)" - -#~ msgid "'%(value)s' value must be either True or False." -#~ msgstr "'%(value)s' doit être Vrai ou Faux." - -#~ msgid "'%(value)s' value must be either True, False, or None." -#~ msgstr "'%(value)s' doit être Vrai, Faux, ou None." - -#~ msgid "Boolean (Either True or False)" -#~ msgstr "Booléen (Vrai ou Faux)" - -#~ msgid "String (up to %(max_length)s)" -#~ msgstr "Chaîne de caractère (maximum %(max_length)s caractères)" - -#~ msgid "Comma-separated integers" -#~ msgstr "Liste d'entier séparer par des virgules" - -#~ msgid "" -#~ "'%(value)s' value has an invalid date format. It must be in YYYY-MM-DD " -#~ "format." -#~ msgstr "'%(value)s n'est pas formaté correctement (AAAA-MM-JJ)." - -#~ msgid "" -#~ "'%(value)s' value has the correct format (YYYY-MM-DD) but it is an " -#~ "invalid date." -#~ msgstr "" -#~ "'%(value)s possède le format date requis (AAAA-MM-JJ) mais n'est pas une " -#~ "date valide." - -#~ msgid "Date (without time)" -#~ msgstr "Date (sans horaire)" - -#~ msgid "" -#~ "'%(value)s' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:" -#~ "ss[.uuuuuu]][TZ] format." -#~ msgstr "" -#~ "'%(value)s' n'est pas formatée correctement (AAAA-MM-JJ HH:MM[:ss[." -#~ "uuuuuu]][TZ])." - -#~ msgid "" -#~ "'%(value)s' value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]]" -#~ "[TZ]) but it is an invalid date/time." -#~ msgstr "" -#~ "'%(value)s' est formaté correctement, mais n'est pas une date/horaire " -#~ "valide." - -#~ msgid "Date (with time)" -#~ msgstr "Date (avec horaire)" - -#~ msgid "'%(value)s' value must be a decimal number." -#~ msgstr "'%(value)s doit être un nombre décimal." - -#~ msgid "Decimal number" -#~ msgstr "Nombre décimal" - -#~ msgid "" -#~ "'%(value)s' value has an invalid format. It must be in [DD] [HH:[MM:]]ss[." -#~ "uuuuuu] format." -#~ msgstr "" -#~ "'%(value)s' n'est pas formatée correctement (AAAA-MM-JJ HH:MM[:ss[." -#~ "uuuuuu]][TZ])." - -#~ msgid "Duration" -#~ msgstr "Durée" - -#~ msgid "Email address" -#~ msgstr "Courriel" - -#~ msgid "File path" -#~ msgstr "Chemin du fichier" - -#~ msgid "'%(value)s' value must be a float." -#~ msgstr "'%(value)s doit être un nombre décimal." - -#~ msgid "Floating point number" -#~ msgstr "Nombre décimal" - -#~ msgid "IPv4 address" -#~ msgstr "Adresse IPv4" - -#~ msgid "IP address" -#~ msgstr "Adresse IP" - -#~ msgid "'%(value)s' value must be either None, True or False." -#~ msgstr "'%(value)s' doit être Vrai, Faux, ou None." - -#~ msgid "Boolean (Either True, False or None)" -#~ msgstr "Booléen (Vrai ou Faux)" - -#~ msgid "Positive integer" -#~ msgstr "Nombre entier positif" - -#~ msgid "Positive small integer" -#~ msgstr "Nombre entier positif petit" - -#~ msgid "Slug (up to %(max_length)s)" -#~ msgstr "Slug (maximum %(max_length)s caractères)" - -#~ msgid "Small integer" -#~ msgstr "Petit entier" - -#~ msgid "Text" -#~ msgstr "Texte" - -#~ msgid "" -#~ "'%(value)s' value has an invalid format. It must be in HH:MM[:ss[." -#~ "uuuuuu]] format." -#~ msgstr "'%(value)s' n'est pas formatée correctement (HH:MM[:ss[.uuuuuu]])." - -#~ msgid "" -#~ "'%(value)s' value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is " -#~ "an invalid time." -#~ msgstr "" -#~ "'%(value)s' est formaté correctement, mais n'est pas un horaire valide." - -#~ msgid "Time" -#~ msgstr "Temps" - -#~ msgid "URL" -#~ msgstr "URL" - -#~ msgid "Raw binary data" -#~ msgstr "Donnée binaire brute" - -#~ msgid "'%(value)s' is not a valid UUID." -#~ msgstr "'%(value)s' n'est pas un UUID valide." - -#~ msgid "Universally unique identifier" -#~ msgstr "Identifiant unique universel" - -#~ msgid "File" -#~ msgstr "Fichier" - -#~ msgid "Image" -#~ msgstr "Image" - -#~ msgid "%(model)s instance with %(field)s %(value)r does not exist." -#~ msgstr "" -#~ "l'objet %(model)s avec les champs %(field)s %(value)r n'existe pas." - -#~ msgid "Foreign Key (type determined by related field)" -#~ msgstr "Relations plusieurs-à-un (type déterminé par le champ relié)" - -#~ msgid "One-to-one relationship" -#~ msgstr "Relation un-à-un" - -#~ msgid "%(from)s-%(to)s relationship" -#~ msgstr "Relation %(from)s-%(to)s" - -#~ msgid "%(from)s-%(to)s relationships" -#~ msgstr "Relations %(from)s-%(to)s" - -#~ msgid "Many-to-many relationship" -#~ msgstr "Relation plusieurs-à-plusieurs" - -#~ msgid ":?.!" -#~ msgstr ":?.!" - -#~ msgid "Enter a whole number." -#~ msgstr "Entrer un numéro complet." - -#~ msgid "Enter a valid date." -#~ msgstr "Entrer une date valide." - -#~ msgid "Enter a valid time." -#~ msgstr "Entrer un horaire valide." - -#~ msgid "Enter a valid date/time." -#~ msgstr "Entrer une date et un horaire valide." - -#~ msgid "Enter a valid duration." -#~ msgstr "Entrer une durée valide." - -#~ msgid "The number of days must be between {min_days} and {max_days}." -#~ msgstr "" -#~ "Le nombre de jours doit être compris entre {min_days} et {max_days}." - -#~ msgid "No file was submitted. Check the encoding type on the form." -#~ msgstr "Aucun fichier n'as été ajouté. Vérifier l'encodage du formulaire." - -#~ msgid "No file was submitted." -#~ msgstr "Aucun fichier n'as été ajouté." - -#~ msgid "The submitted file is empty." -#~ msgstr "Le fichier ajouté est vide." - -#~ msgid "" -#~ "Ensure this filename has at most %(max)d character (it has %(length)d)." -#~ msgid_plural "" -#~ "Ensure this filename has at most %(max)d characters (it has %(length)d)." -#~ msgstr[0] "" -#~ "Vérifier que le nom du fichier a au plus %(max)d caractère (actuellement " -#~ "%(length)d)." -#~ msgstr[1] "" -#~ "Vérifier que le nom du fichier a au plus %(max)d caractères (actuellement " -#~ "%(length)d)." - -#~ msgid "Please either submit a file or check the clear checkbox, not both." -#~ msgstr "Veuillez ajouter un fichier ou cocher la case envoi vide." - -#~ msgid "" -#~ "Upload a valid image. The file you uploaded was either not an image or a " -#~ "corrupted image." -#~ msgstr "Veuillez choisir une image valide." - -#~ msgid "" -#~ "Select a valid choice. %(value)s is not one of the available choices." -#~ msgstr "Faites un choix valide. %(value)s n'est pas autorisé." - -#~ msgid "Enter a list of values." -#~ msgstr "Entrer une liste de valeurs." - -#~ msgid "Enter a complete value." -#~ msgstr "Entrer une valeur complète." - -#~ msgid "Enter a valid UUID." -#~ msgstr "Entrer un UUID valid." - -#~ msgid ":" -#~ msgstr ":" - -#~ msgid "(Hidden field %(name)s) %(error)s" -#~ msgstr "(Champ caché %(name)s) %(error)s" - -#~ msgid "ManagementForm data is missing or has been tampered with" -#~ msgstr "Les données ManagementForm sont manquantes ou falsifiées" - -#~ msgid "Please submit %d or fewer forms." -#~ msgid_plural "Please submit %d or fewer forms." -#~ msgstr[0] "Veuillez remplir %d formulaire ou moins." -#~ msgstr[1] "Veuillez remplir %d formulaires ou moins." - -#~ msgid "Please submit %d or more forms." -#~ msgid_plural "Please submit %d or more forms." -#~ msgstr[0] "Veuillez remplir %d formulaire ou plus." -#~ msgstr[1] "Veuillez remplir %d formulaires ou plus." - -#~ msgid "Order" -#~ msgstr "Ordre" - -#~ msgid "Please correct the duplicate data for %(field)s." -#~ msgstr "Veuillez corriger les données dupliquées pour %(field)s." - -#~ msgid "" -#~ "Please correct the duplicate data for %(field)s, which must be unique." -#~ msgstr "Veuillez rendre uniques les valeurs des champs %(field)s." - -#~ msgid "" -#~ "Please correct the duplicate data for %(field_name)s which must be unique " -#~ "for the %(lookup)s in %(date_field)s." -#~ msgstr "" -#~ "Veuillez rendre unique les valeurs des champs %(field_name)s pour les " -#~ "%(lookup)s dans %(date_field)s." - -#~ msgid "Please correct the duplicate values below." -#~ msgstr "Veuillez rendre uniques les valeurs ci-dessous." - -#~ msgid "The inline value did not match the parent instance." -#~ msgstr "La valeur renseignée ne correspond pas à l'objet parent." - -#~ msgid "" -#~ "Select a valid choice. That choice is not one of the available choices." -#~ msgstr "Faites un choix possible." - -#~ msgid "\"%(pk)s\" is not a valid value." -#~ msgstr "\"%(pk)s\" n'est pas une valeur autorisée." - -#~ msgid "" -#~ "%(datetime)s couldn't be interpreted in time zone %(current_timezone)s; " -#~ "it may be ambiguous or it may not exist." -#~ msgstr "" -#~ "%(datetime)s n'a pas pu être interprété dans la zone " -#~ "%(current_timezone)s, La valeur est ambigüe ou impossible." - -#~ msgid "Clear" -#~ msgstr "Vider" - -#~ msgid "Currently" -#~ msgstr "Activité en cours" - -#~ msgid "Change" -#~ msgstr "Modifier" - -#~ msgid "Unknown" -#~ msgstr "Inconnu" - -#~ msgid "yes,no,maybe" -#~ msgstr "oui, non, peut-être" - -#~ msgid "%(size)d byte" -#~ msgid_plural "%(size)d bytes" -#~ msgstr[0] "%(size)d octet" -#~ msgstr[1] "%(size)d octets" - -#~ msgid "%s KB" -#~ msgstr "%s Ko" - -#~ msgid "%s MB" -#~ msgstr "%s Mo" - -#~ msgid "%s GB" -#~ msgstr "%s Go" - -#~ msgid "%s TB" -#~ msgstr "%s To" - -#~ msgid "%s PB" -#~ msgstr "%s Po" - -#~ msgid "p.m." -#~ msgstr "p.m." - -#~ msgid "a.m." -#~ msgstr "a.m." - -#~ msgid "PM" -#~ msgstr "PM" - -#~ msgid "AM" -#~ msgstr "AM" - -#~ msgid "midnight" -#~ msgstr "minuit" - -#~ msgid "noon" -#~ msgstr "midi" - -#~ msgid "Monday" -#~ msgstr "Lundi" - -#~ msgid "Tuesday" -#~ msgstr "Mardi" - -#~ msgid "Wednesday" -#~ msgstr "Mercredi" - -#~ msgid "Thursday" -#~ msgstr "Jeudi" - -#~ msgid "Friday" -#~ msgstr "Vendredi" - -#~ msgid "Saturday" -#~ msgstr "Samedi" - -#~ msgid "Sunday" -#~ msgstr "Dimanche" - -#~ msgid "Mon" -#~ msgstr "Lun" - -#~ msgid "Tue" -#~ msgstr "Mar" - -#~ msgid "Wed" -#~ msgstr "Mer" - -#~ msgid "Thu" -#~ msgstr "Jeu" - -#~ msgid "Fri" -#~ msgstr "Ven" - -#~ msgid "Sat" -#~ msgstr "Sam" - -#~ msgid "Sun" -#~ msgstr "Dim" - -#~ msgid "January" -#~ msgstr "Janvier" - -#~ msgid "February" -#~ msgstr "Février" - -#~ msgid "March" -#~ msgstr "Mars" - -#~ msgid "April" -#~ msgstr "Avril" - -#~ msgid "May" -#~ msgstr "Mai" - -#~ msgid "June" -#~ msgstr "Juin" - -#~ msgid "July" -#~ msgstr "Juillet" - -#~ msgid "August" -#~ msgstr "Août" - -#~ msgid "September" -#~ msgstr "Septembre" - -#~ msgid "October" -#~ msgstr "Octobre" - -#~ msgid "November" -#~ msgstr "Novembre" - -#~ msgid "December" -#~ msgstr "Décembre" - -#~ msgid "jan" -#~ msgstr "jan" - -#~ msgid "feb" -#~ msgstr "fev" - -#~ msgid "mar" -#~ msgstr "mar" - -#~ msgid "apr" -#~ msgstr "avr" - -#~ msgid "may" -#~ msgstr "mai" - -#~ msgid "jun" -#~ msgstr "jun" - -#~ msgid "jul" -#~ msgstr "jui" - -#~ msgid "aug" -#~ msgstr "aou" - -#~ msgid "sep" -#~ msgstr "sep" - -#~ msgid "oct" -#~ msgstr "oct" - -#~ msgid "nov" -#~ msgstr "nov" - -#~ msgid "dec" -#~ msgstr "dec" - -#~ msgctxt "abbrev. month" -#~ msgid "Jan." -#~ msgstr "[abbrev. month] Jan." - -#~ msgctxt "abbrev. month" -#~ msgid "Feb." -#~ msgstr "[abbrev. month] Fév." - -#~ msgctxt "abbrev. month" -#~ msgid "March" -#~ msgstr "[abbrev. month] Mars" - -#~ msgctxt "abbrev. month" -#~ msgid "April" -#~ msgstr "[abbrev. month] Avril" - -#~ msgctxt "abbrev. month" -#~ msgid "May" -#~ msgstr "[abbrev. month] Mai" - -#~ msgctxt "abbrev. month" -#~ msgid "June" -#~ msgstr "[abbrev. month] Juin" - -#~ msgctxt "abbrev. month" -#~ msgid "July" -#~ msgstr "[abbrev. month] Jui" - -#~ msgctxt "abbrev. month" -#~ msgid "Aug." -#~ msgstr "[abbrev. month] Août." - -#~ msgctxt "abbrev. month" -#~ msgid "Sept." -#~ msgstr "[abbrev. month] Sep." - -#~ msgctxt "abbrev. month" -#~ msgid "Oct." -#~ msgstr "[abbrev. month] Oct." - -#~ msgctxt "abbrev. month" -#~ msgid "Nov." -#~ msgstr "[abbrev. month] Nov." - -#~ msgctxt "abbrev. month" -#~ msgid "Dec." -#~ msgstr "[abbrev. month] Dec." - -#~ msgctxt "alt. month" -#~ msgid "January" -#~ msgstr "[alt. month] Janvier" - -#~ msgctxt "alt. month" -#~ msgid "February" -#~ msgstr "[alt. month] Février" - -#~ msgctxt "alt. month" -#~ msgid "March" -#~ msgstr "[alt. month] Mars" - -#~ msgctxt "alt. month" -#~ msgid "April" -#~ msgstr "[alt. month] Avril" - -#~ msgctxt "alt. month" -#~ msgid "May" -#~ msgstr "[alt. month] Mai" - -#~ msgctxt "alt. month" -#~ msgid "June" -#~ msgstr "[alt. month] Juin" - -#~ msgctxt "alt. month" -#~ msgid "July" -#~ msgstr "[alt. month] Juillet" - -#~ msgctxt "alt. month" -#~ msgid "August" -#~ msgstr "[alt. month] Août" - -#~ msgctxt "alt. month" -#~ msgid "September" -#~ msgstr "[alt. month] Septembre" - -#~ msgctxt "alt. month" -#~ msgid "October" -#~ msgstr "[alt. month] Octobre" - -#~ msgctxt "alt. month" -#~ msgid "November" -#~ msgstr "[alt. month] Novembre" - -#~ msgctxt "alt. month" -#~ msgid "December" -#~ msgstr "[alt. month] Décembre" - -#~ msgid "This is not a valid IPv6 address." -#~ msgstr "Adresse IPv6 non valide." - -#~ msgctxt "String to return when truncating text" -#~ msgid "%(truncated_text)s…" -#~ msgstr "[String to return when truncating text] %(truncated_text)s…" - -#~ msgid "or" -#~ msgstr "ou" - -#~ msgid ", " -#~ msgstr ", " - -#~ msgid "%d year" -#~ msgid_plural "%d years" -#~ msgstr[0] "%d année" -#~ msgstr[1] "%d années" - -#~ msgid "%d month" -#~ msgid_plural "%d months" -#~ msgstr[0] "%d mois" -#~ msgstr[1] "%d mois" - -#~ msgid "%d week" -#~ msgid_plural "%d weeks" -#~ msgstr[0] "%d semaine" -#~ msgstr[1] "%d semaines" - -#~ msgid "%d day" -#~ msgid_plural "%d days" -#~ msgstr[0] "%d jour" -#~ msgstr[1] "%d jours" - -#~ msgid "%d hour" -#~ msgid_plural "%d hours" -#~ msgstr[0] "%d heure" -#~ msgstr[1] "%d heures" - -#~ msgid "%d minute" -#~ msgid_plural "%d minutes" -#~ msgstr[0] "%d minute" -#~ msgstr[1] "%d minutes" - -#~ msgid "0 minutes" -#~ msgstr "0 minutes" - -#~ msgid "Forbidden" -#~ msgstr "Interdit" - -#~ msgid "CSRF verification failed. Request aborted." -#~ msgstr "Echec de la vérification CSRF. Requête interrompue." - -#~ msgid "" -#~ "You are seeing this message because this HTTPS site requires a 'Referer " -#~ "header' to be sent by your Web browser, but none was sent. This header is " -#~ "required for security reasons, to ensure that your browser is not being " -#~ "hijacked by third parties." -#~ msgstr "" -#~ "Vous voyez ce message car ce site HTTPS nécessite l'envoi d'un \"en-tête " -#~ "référent\" par votre navigateur. Cet en-tête est necessaire pour des " -#~ "raisons de sécurité, pour confirmer que votre navigateur n'est pas " -#~ "compromis par un tiers." - -#~ msgid "" -#~ "If you have configured your browser to disable 'Referer' headers, please " -#~ "re-enable them, at least for this site, or for HTTPS connections, or for " -#~ "'same-origin' requests." -#~ msgstr "" -#~ "Si vous avez configurer votre navigateur pour désactiver les \"en-tête " -#~ "référent\", veuillez les réactiver, au moins pour ce site, ou pour les " -#~ "requêtes HTTPS, ou les requête de même origine." - -#~ msgid "" -#~ "If you are using the tag " -#~ "or including the 'Referrer-Policy: no-referrer' header, please remove " -#~ "them. The CSRF protection requires the 'Referer' header to do strict " -#~ "referer checking. If you're concerned about privacy, use alternatives " -#~ "like for links to third-party sites." -#~ msgstr "" -#~ "Si vous utiliser le tag " -#~ "ou incluez l'en-tête 'Referrer-Policy: no-referrer', veuillez les " -#~ "retirer. La protection CSRF nécessite que l'en-tête référent fasse une " -#~ "vérification stricte. Si vous avez des préoccupations pour votre vie " -#~ "privée, vous pouvez utiliser des alternatives comme pour les liens vers des sites tiers." - -#~ msgid "" -#~ "You are seeing this message because this site requires a CSRF cookie when " -#~ "submitting forms. This cookie is required for security reasons, to ensure " -#~ "that your browser is not being hijacked by third parties." -#~ msgstr "" -#~ "Vous voyez ce message car ce site nécessite un cookie CSRF pour l'envoi " -#~ "de formulaire. Ce cookie est demandé pour des raisons de sécurité, pour " -#~ "s'assurer que votre navigateur n'est pas compromis par un tiers." - -#~ msgid "" -#~ "If you have configured your browser to disable cookies, please re-enable " -#~ "them, at least for this site, or for 'same-origin' requests." -#~ msgstr "" -#~ "Si vous avez configuré votre navigateur pour désactiver les cookies, " -#~ "veuillez les réactiver, au moins pour ce site, ou pour les requêtes de " -#~ "même origine." - -#~ msgid "More information is available with DEBUG=True." -#~ msgstr "Plus d'informations disponible avec DEBUG=True." - -#~ msgid "No year specified" -#~ msgstr "Pas d'année spécifiée" - -#~ msgid "Date out of range" -#~ msgstr "Date impossible" - -#~ msgid "No month specified" -#~ msgstr "Pas de mois spécifié" - -#~ msgid "No day specified" -#~ msgstr "Pas de jours spécifié" - -#~ msgid "No week specified" -#~ msgstr "Pas de semaine spécifiée" - -#~ msgid "No %(verbose_name_plural)s available" -#~ msgstr "%(verbose_name_plural)s non disponible" - -#~ msgid "" -#~ "Future %(verbose_name_plural)s not available because %(class_name)s." -#~ "allow_future is False." -#~ msgstr "" -#~ "Le futur %(verbose_name_plural)s n'est pas possible car %(class_name)s." -#~ "allow_future = False." - -#~ msgid "Invalid date string '%(datestr)s' given format '%(format)s'" -#~ msgstr "Date '%(datestr)s' au format non valide '%(format)s'." - -#~ msgid "No %(verbose_name)s found matching the query" -#~ msgstr "Aucun %(verbose_name)s trouvé pour cette requête" - -#~ msgid "Page is not 'last', nor can it be converted to an int." -#~ msgstr "" -#~ "La page spécifié n'est pas la dernière (last) et ne peux pas être " -#~ "convertie en nombre entier." - -#~ msgid "Invalid page (%(page_number)s): %(message)s" -#~ msgstr "Le numéro de page %(page_number)s est non valide: %(message)s" - -#~ msgid "Empty list and '%(class_name)s.allow_empty' is False." -#~ msgstr "Liste vide et '%(class_name)s.allow_empty = False." - -#~ msgid "Directory indexes are not allowed here." -#~ msgstr "L'index de Dossier n'est pas autorisé ici." - -#~ msgid "\"%(path)s\" does not exist" -#~ msgstr "\"%(path)s\" n'existe pas" - -#~ msgid "Index of %(directory)s" -#~ msgstr "Contenu de %(directory)s" - -#~ msgid "Django: the Web framework for perfectionists with deadlines." -#~ msgstr "" -#~ "Django: Le cadriciel Web pour les perfectionniste avec des dates limites." - -#~ msgid "" -#~ "View release notes for Django " -#~ "%(version)s" -#~ msgstr "" -#~ "Visiter les Notes de versions\" pour " -#~ "Django %(version)s" - -#~ msgid "The install worked successfully! Congratulations!" -#~ msgstr "L'installation a réussie! Félicitation!" - -#~ msgid "" -#~ "You are seeing this page because DEBUG=True is in your settings file and you have not configured " -#~ "any URLs." -#~ msgstr "" -#~ "Vous voyez cette page car DEBUG=True est renseigné dans vos paramètres et vous n'avez pas " -#~ "configuré d'URLs." - -#~ msgid "Django Documentation" -#~ msgstr "Documentation Django" - -#~ msgid "Topics, references, & how-to's" -#~ msgstr "Sujet, references & how-to" - -#~ msgid "Tutorial: A Polling App" -#~ msgstr "Tutoriel: Une application de sondage" - -#~ msgid "Get started with Django" -#~ msgstr "Débuter avec Django" - -#~ msgid "Django Community" -#~ msgstr "Communauté Django" - -#~ msgid "Connect, get help, or contribute" -#~ msgstr "Prendre contact, obtenir de l'aide ou contribuer" diff --git a/note.cron b/note.cron index f3e18d90..078856ea 100644 --- a/note.cron +++ b/note.cron @@ -1,22 +1,22 @@ -# Attention, il faut *copier* ce fichier dans /etc/cron.d, owner root:root et droits 644 +# {{ ansible_managed }} # Les cronjobs dont a besoin la Note Kfet # m h dom mon dow user command # Envoyer les mails en attente - * * * * * root cd /var/www/note_kfet && env/bin/python manage.py send_mail >> /var/www/note_kfet/cron_mail.log - * * * * * root cd /var/www/note_kfet && env/bin/python manage.py retry_deferred >> /var/www/note_kfet/cron_mail_deferred.log - 00 0 * * * root cd /var/www/note_kfet && env/bin/python manage.py purge_mail_log 7 >> /var/www/note_kfet/cron_mail_purge.log + * * * * * root cd /var/www/note_kfet && env/bin/python manage.py send_mail -c 1 + * * * * * root cd /var/www/note_kfet && env/bin/python manage.py retry_deferred -c 1 + 00 0 * * * root cd /var/www/note_kfet && env/bin/python manage.py purge_mail_log 7 -c 1 # Faire une sauvegarde de la base de données 00 2 * * * root cd /var/www/note_kfet && apps/scripts/shell/backup_db # Vérifier la cohérence de la base et mailer en cas de problème 00 4 * * * root cd /var/www/note_kfet && env/bin/python manage.py check_consistency --sum-all --check-all --mail # Mettre à jour le wiki (modification sans (dé)validation, activités passées) -#30 5 * * * root cd /var/www/note_kfet && env/bin/python manage.py refresh_activities --raw --comment refresh + 30 5 * * * root cd /var/www/note_kfet && env/bin/python manage.py refresh_activities --raw --human --comment refresh --wiki # Spammer les gens en négatif 00 5 * * 2 root cd /var/www/note_kfet && env/bin/python manage.py send_mail_to_negative_balances --spam # Envoyer le rapport mensuel aux trésoriers et respos info 00 8 6 * * root cd /var/www/note_kfet && env/bin/python manage.py send_mail_to_negative_balances --report # Envoyer les rapports aux gens 55 6 * * * root cd /var/www/note_kfet && env/bin/python manage.py send_reports -# Envoyer les rapports aux gens +# Mettre à jour les boutons mis en avant 00 9 * * * root cd /var/www/note_kfet && env/bin/python manage.py refresh_highlighted_buttons diff --git a/note_kfet/static/js/autocomplete_model.js b/note_kfet/static/js/autocomplete_model.js index c4f9405b..f7aafbc6 100644 --- a/note_kfet/static/js/autocomplete_model.js +++ b/note_kfet/static/js/autocomplete_model.js @@ -1,57 +1,53 @@ $(document).ready(function () { - $(".autocomplete").keyup(function(e) { - let target = $("#" + e.target.id); - let prefix = target.attr("id"); - let api_url = target.attr("api_url"); - let api_url_suffix = target.attr("api_url_suffix"); - if (!api_url_suffix) - api_url_suffix = ""; - let name_field = target.attr("name_field"); - if (!name_field) - name_field = "name"; - let input = target.val(); - target.addClass("is-invalid"); - target.removeClass("is-valid"); - $("#" + prefix + "_reset").removeClass("d-none"); + $('.autocomplete').keyup(function (e) { + const target = $('#' + e.target.id) + const prefix = target.attr('id') + const api_url = target.attr('api_url') + let api_url_suffix = target.attr('api_url_suffix') + if (!api_url_suffix) { api_url_suffix = '' } + let name_field = target.attr('name_field') + if (!name_field) { name_field = 'name' } + const input = target.val() + target.addClass('is-invalid') + target.removeClass('is-valid') + $('#' + prefix + '_reset').removeClass('d-none') - $.getJSON(api_url + (api_url.includes("?") ? "&" : "?") + "format=json&search=^" + input + api_url_suffix, function(objects) { - let html = ""; + $.getJSON(api_url + (api_url.includes('?') ? '&' : '?') + 'format=json&search=^' + input + api_url_suffix, function (objects) { + let html = '' - objects.results.forEach(function (obj) { - html += li(prefix + "_" + obj.id, obj[name_field]); - }); + objects.results.forEach(function (obj) { + html += li(prefix + '_' + obj.id, obj[name_field]) + }) - let results_list = $("#" + prefix + "_list"); - results_list.html(html); + const results_list = $('#' + prefix + '_list') + results_list.html(html) - objects.results.forEach(function (obj) { - $("#" + prefix + "_" + obj.id).click(function() { - target.val(obj[name_field]); - $("#" + prefix + "_pk").val(obj.id); + objects.results.forEach(function (obj) { + $('#' + prefix + '_' + obj.id).click(function () { + target.val(obj[name_field]) + $('#' + prefix + '_pk').val(obj.id) - results_list.html(""); - target.removeClass("is-invalid"); - target.addClass("is-valid"); + results_list.html('') + target.removeClass('is-invalid') + target.addClass('is-valid') - if (typeof autocompleted != 'undefined') - autocompleted(obj, prefix) - }); + if (typeof autocompleted !== 'undefined') { autocompleted(obj, prefix) } + }) - if (input === obj[name_field]) - $("#" + prefix + "_pk").val(obj.id); - }); + if (input === obj[name_field]) { $('#' + prefix + '_pk').val(obj.id) } + }) - if (results_list.children().length === 1 && e.originalEvent.keyCode >= 32) { - results_list.children().first().trigger("click"); - } - }); - }); + if (results_list.children().length === 1 && e.originalEvent.keyCode >= 32) { + results_list.children().first().trigger('click') + } + }) + }) - $(".autocomplete-reset").click(function() { - let name = $(this).attr("id").replace("_reset", ""); - $("#" + name + "_pk").val(""); - $("#" + name).val(""); - $("#" + name + "_list").html(""); - $(this).addClass("d-none"); - }); -}); \ No newline at end of file + $('.autocomplete-reset').click(function () { + const name = $(this).attr('id').replace('_reset', '') + $('#' + name + '_pk').val('') + $('#' + name).val('') + $('#' + name + '_list').html('') + $(this).addClass('d-none') + }) +}) diff --git a/note_kfet/static/js/base.js b/note_kfet/static/js/base.js index a20c72bc..87a99f64 100644 --- a/note_kfet/static/js/base.js +++ b/note_kfet/static/js/base.js @@ -1,18 +1,16 @@ // Copyright (C) 2018-2020 by BDE ENS Paris-Saclay // SPDX-License-Identifier: GPL-3.0-or-later - /** * Convert balance in cents to a human readable amount * @param value the balance, in cents * @returns {string} */ function pretty_money (value) { - if (value % 100 === 0) - return (value < 0 ? "- " : "") + Math.floor(Math.abs(value) / 100) + " €"; - else - return (value < 0 ? "- " : "") + Math.floor(Math.abs(value) / 100) + "." - + (Math.abs(value) % 100 < 10 ? "0" : "") + (Math.abs(value) % 100) + " €"; + if (value % 100 === 0) { return (value < 0 ? '- ' : '') + Math.floor(Math.abs(value) / 100) + ' €' } else { + return (value < 0 ? '- ' : '') + Math.floor(Math.abs(value) / 100) + '.' + + (Math.abs(value) % 100 < 10 ? '0' : '') + (Math.abs(value) % 100) + ' €' + } } /** @@ -22,19 +20,19 @@ function pretty_money (value) { * @param timeout The delay (in millis) after that the message is auto-closed. If negative, then it is ignored. */ function addMsg (msg, alert_type, timeout = -1) { - let msgDiv = $("#messages"); - let html = msgDiv.html(); - let id = Math.floor(10000 * Math.random() + 1); - html += "
" + - "" - + msg + "
\n"; - msgDiv.html(html); + const msgDiv = $('#messages') + let html = msgDiv.html() + const id = Math.floor(10000 * Math.random() + 1) + html += '
' + + '' + + msg + '
\n' + msgDiv.html(html) - if (timeout > 0) { - setTimeout(function () { - $("#close-message-" + id).click(); - }, timeout); - } + if (timeout > 0) { + setTimeout(function () { + $('#close-message-' + id).click() + }, timeout) + } } /** @@ -43,34 +41,34 @@ function addMsg (msg, alert_type, timeout = -1) { * @param timeout The delay (in millis) after that the message is auto-closed. If negative, then it is ignored. */ function errMsg (errs_obj, timeout = -1) { - for (const err_msg of Object.values(errs_obj)) { - addMsg(err_msg, 'danger', timeout); - } + for (const err_msg of Object.values(errs_obj)) { + addMsg(err_msg, 'danger', timeout) + } } var reloadWithTurbolinks = (function () { - var scrollPosition; + var scrollPosition - function reload () { - scrollPosition = [window.scrollX, window.scrollY]; - Turbolinks.visit(window.location.toString(), { action: 'replace' }) + function reload () { + scrollPosition = [window.scrollX, window.scrollY] + Turbolinks.visit(window.location.toString(), { action: 'replace' }) + } + + document.addEventListener('turbolinks:load', function () { + if (scrollPosition) { + window.scrollTo.apply(window, scrollPosition) + scrollPosition = null } + }) - document.addEventListener('turbolinks:load', function () { - if (scrollPosition) { - window.scrollTo.apply(window, scrollPosition); - scrollPosition = null - } - }); - - return reload; -})(); + return reload +})() /** * Reload the balance of the user on the right top corner */ function refreshBalance () { - $("#user_balance").load("/ #user_balance"); + $('#user_balance').load('/ #user_balance') } /** @@ -79,15 +77,15 @@ function refreshBalance () { * @param fun For each found note with the matched alias `alias`, fun(note, alias) is called. */ function getMatchedNotes (pattern, fun) { - $.getJSON("/api/note/alias/?format=json&alias=" + pattern + "&search=user|club", fun); + $.getJSON('/api/note/alias/?format=json&alias=' + pattern + '&search=user|club', fun) } /** * Generate a
  • entry with a given id and text */ function li (id, text, extra_css) { - return "
  • " + text + "
  • \n"; + return '
  • ' + text + '
  • \n' } /** @@ -95,24 +93,13 @@ function li (id, text, extra_css) { * @param note The concerned note. */ function displayStyle (note) { - if (!note) - return ""; - let balance = note.balance; - var css = ""; - if (balance < -5000) - css += " text-danger bg-dark"; - else if (balance < -1000) - css += " text-danger"; - else if (balance < 0) - css += " text-warning"; - else if (!note.email_confirmed) - css += " text-white bg-primary"; - else if (!note.is_active || (note.membership && note.membership.date_end < new Date().toISOString())) - css += "text-white bg-info"; - return css; + if (!note) { return '' } + const balance = note.balance + var css = '' + if (balance < -5000) { css += ' text-danger bg-dark' } else if (balance < -1000) { css += ' text-danger' } else if (balance < 0) { css += ' text-warning' } else if (!note.email_confirmed) { css += ' text-white bg-primary' } else if (!note.is_active || (note.membership && note.membership.date_end < new Date().toISOString())) { css += 'text-white bg-info' } + return css } - /** * Render note name and picture * @param note The note to render @@ -121,23 +108,22 @@ function displayStyle (note) { * @param profile_pic_field */ function displayNote (note, alias, user_note_field = null, profile_pic_field = null) { - if (!note.display_image) { - note.display_image = '/media/pic/default.png'; - } - let img = note.display_image; - if (alias !== note.name && note.name) - alias += " (aka. " + note.name + ")"; - if (user_note_field !== null) { - $("#" + user_note_field).removeAttr('class'); - $("#" + user_note_field).addClass(displayStyle(note)); - $("#" + user_note_field).text(alias + (note.balance == null ? "" : (" :\n" + pretty_money(note.balance)))); - if (profile_pic_field != null) { - $("#" + profile_pic_field).attr('src', img); - $("#" + profile_pic_field + "_link").attr('href', note.resourcetype === "NoteUser" ? - "/accounts/user/" + note.user : note.resourcetype === "NoteClub" ? - "/accounts/club/" + note.club : "#"); - } + if (!note.display_image) { + note.display_image = '/static/member/img/default_picture.png' + } + const img = note.display_image + if (alias !== note.name && note.name) { alias += ' (aka. ' + note.name + ')' } + if (user_note_field !== null) { + $('#' + user_note_field).removeAttr('class') + $('#' + user_note_field).addClass(displayStyle(note)) + $('#' + user_note_field).text(alias + (note.balance == null ? '' : (' :\n' + pretty_money(note.balance)))) + if (profile_pic_field != null) { + $('#' + profile_pic_field).attr('src', img) + $('#' + profile_pic_field + '_link').attr('href', note.resourcetype === 'NoteUser' + ? '/accounts/user/' + note.user : note.resourcetype === 'NoteClub' + ? '/accounts/club/' + note.club : '#') } + } } /** @@ -152,35 +138,34 @@ function displayNote (note, alias, user_note_field = null, profile_pic_field = n * (useful in consumptions, put null if not used) * @returns an anonymous function to be compatible with jQuery events */ -function removeNote (d, note_prefix = "note", notes_display, note_list_id, user_note_field = null, profile_pic_field = null) { - return (function () { - let new_notes_display = []; - let html = ""; - notes_display.forEach(function (disp) { - if (disp.quantity > 1 || disp.id !== d.id) { - disp.quantity -= disp.id === d.id ? 1 : 0; - new_notes_display.push(disp); - html += li(note_prefix + "_" + disp.id, disp.name - + "" + disp.quantity + "", - displayStyle(disp.note)); - } - }); +function removeNote (d, note_prefix = 'note', notes_display, note_list_id, user_note_field = null, profile_pic_field = null) { + return function () { + const new_notes_display = [] + let html = '' + notes_display.forEach(function (disp) { + if (disp.quantity > 1 || disp.id !== d.id) { + disp.quantity -= disp.id === d.id ? 1 : 0 + new_notes_display.push(disp) + html += li(note_prefix + '_' + disp.id, disp.name + + '' + disp.quantity + '', + displayStyle(disp.note)) + } + }) - notes_display.length = 0; - new_notes_display.forEach(function (disp) { - notes_display.push(disp); - }); + notes_display.length = 0 + new_notes_display.forEach(function (disp) { + notes_display.push(disp) + }) - $("#" + note_list_id).html(html); - notes_display.forEach(function (disp) { - let obj = $("#" + note_prefix + "_" + disp.id); - obj.click(removeNote(disp, note_prefix, notes_display, note_list_id, user_note_field, profile_pic_field)); - obj.hover(function () { - if (disp.note) - displayNote(disp.note, disp.name, user_note_field, profile_pic_field); - }); - }); - }); + $('#' + note_list_id).html(html) + notes_display.forEach(function (disp) { + const obj = $('#' + note_prefix + '_' + disp.id) + obj.click(removeNote(disp, note_prefix, notes_display, note_list_id, user_note_field, profile_pic_field)) + obj.hover(function () { + if (disp.note) { displayNote(disp.note, disp.name, user_note_field, profile_pic_field) } + }) + }) + } } /** @@ -199,203 +184,193 @@ function removeNote (d, note_prefix = "note", notes_display, note_list_id, user_ * the associated note is not displayed. * Useful for a consumption if the item is selected before. */ -function autoCompleteNote (field_id, note_list_id, notes, notes_display, alias_prefix = "alias", - note_prefix = "note", user_note_field = null, profile_pic_field = null, alias_click = null) { - let field = $("#" + field_id); +function autoCompleteNote (field_id, note_list_id, notes, notes_display, alias_prefix = 'alias', + note_prefix = 'note', user_note_field = null, profile_pic_field = null, alias_click = null) { + const field = $('#' + field_id) - // Configure tooltip - field.tooltip({ - html: true, - placement: 'bottom', - title: 'Loading...', - trigger: 'manual', - container: field.parent(), - fallbackPlacement: 'clockwise' - }); + // Configure tooltip + field.tooltip({ + html: true, + placement: 'bottom', + title: 'Loading...', + trigger: 'manual', + container: field.parent(), + fallbackPlacement: 'clockwise' + }) - // When the user clicks elsewhere, we hide the tooltip - $(document).click(function(e) { - if (!e.target.id.startsWith(alias_prefix)) { - field.tooltip("hide"); - } - }); + // When the user clicks elsewhere, we hide the tooltip + $(document).click(function (e) { + if (!e.target.id.startsWith(alias_prefix)) { + field.tooltip('hide') + } + }) - let old_pattern = null; + let old_pattern = null - // Clear search on click - field.click(function () { - field.tooltip('hide'); - field.removeClass('is-invalid'); - field.val(""); - old_pattern = ""; - }); + // Clear search on click + field.click(function () { + field.tooltip('hide') + field.removeClass('is-invalid') + field.val('') + old_pattern = '' + }) - // When the user type "Enter", the first alias is clicked - field.keypress(function (event) { - if (event.originalEvent.charCode === 13 && notes.length > 0) { - let li_obj = field.parent().find("ul li").first(); - displayNote(notes[0], li_obj.text(), user_note_field, profile_pic_field); - li_obj.trigger("click"); - } - }); + // When the user type "Enter", the first alias is clicked + field.keypress(function (event) { + if (event.originalEvent.charCode === 13 && notes.length > 0) { + const li_obj = field.parent().find('ul li').first() + displayNote(notes[0], li_obj.text(), user_note_field, profile_pic_field) + li_obj.trigger('click') + } + }) - // When the user type something, the matched aliases are refreshed - field.keyup(function (e) { - field.removeClass('is-invalid'); + // When the user type something, the matched aliases are refreshed + field.keyup(function (e) { + field.removeClass('is-invalid') - if (e.originalEvent.charCode === 13) - return; + if (e.originalEvent.charCode === 13) { return } - let pattern = field.val(); + const pattern = field.val() - // If the pattern is not modified, we don't query the API - if (pattern === old_pattern) - return; - old_pattern = pattern; - notes.length = 0; + // If the pattern is not modified, we don't query the API + if (pattern === old_pattern) { return } + old_pattern = pattern + notes.length = 0 - // get matched Alias with note associated - if (pattern === "") { - field.tooltip('hide'); - notes.length = 0; - return; - } + // get matched Alias with note associated + if (pattern === '') { + field.tooltip('hide') + notes.length = 0 + return + } - $.getJSON("/api/note/consumer/?format=json&alias=" + pattern + "&search=user|club", - function (consumers) { - // The response arrived too late, we stop the request - if (pattern !== $("#" + field_id).val()) - return; + $.getJSON('/api/note/consumer/?format=json&alias=' + pattern + '&search=user|club', + function (consumers) { + // The response arrived too late, we stop the request + if (pattern !== $('#' + field_id).val()) { return } - // Build tooltip content - let aliases_matched_html = '
      '; - consumers.results.forEach(function (consumer) { - let note = consumer.note; - note.email_confirmed = consumer.email_confirmed; - if (consumer.hasOwnProperty("membership") && consumer.membership) - note.membership = consumer.membership; - else - note.membership = undefined; - let extra_css = displayStyle(note); - aliases_matched_html += li(alias_prefix + '_' + consumer.id, - consumer.name, - extra_css); - notes.push(note); - }); - aliases_matched_html += '
    '; + // Build tooltip content + let aliases_matched_html = '
      ' + consumers.results.forEach(function (consumer) { + const note = consumer.note + note.email_confirmed = consumer.email_confirmed + if (consumer.hasOwnProperty('membership') && consumer.membership) { note.membership = consumer.membership } else { note.membership = undefined } + const extra_css = displayStyle(note) + aliases_matched_html += li(alias_prefix + '_' + consumer.id, + consumer.name, + extra_css) + notes.push(note) + }) + aliases_matched_html += '
    ' - // Show tooltip - field.attr('data-original-title', aliases_matched_html).tooltip('show'); + // Show tooltip + field.attr('data-original-title', aliases_matched_html).tooltip('show') - consumers.results.forEach(function (consumer) { - let consumer_obj = $("#" + alias_prefix + "_" + consumer.id); - consumer_obj.hover(function () { - displayNote(consumer.note, consumer.name, user_note_field, profile_pic_field) - }); - consumer_obj.click(function () { - var disp = null; - notes_display.forEach(function (d) { - // We compare the alias ids - if (d.id === consumer.id) { - d.quantity += 1; - disp = d; - } - }); - // In the other case, we add a new emitter - if (disp == null) { - disp = { - name: consumer.name, - id: consumer.id, - note: consumer.note, - quantity: 1 - }; - notes_display.push(disp); - } + consumers.results.forEach(function (consumer) { + const consumer_obj = $('#' + alias_prefix + '_' + consumer.id) + consumer_obj.hover(function () { + displayNote(consumer.note, consumer.name, user_note_field, profile_pic_field) + }) + consumer_obj.click(function () { + var disp = null + notes_display.forEach(function (d) { + // We compare the alias ids + if (d.id === consumer.id) { + d.quantity += 1 + disp = d + } + }) + // In the other case, we add a new emitter + if (disp == null) { + disp = { + name: consumer.name, + id: consumer.id, + note: consumer.note, + quantity: 1 + } + notes_display.push(disp) + } - // If the function alias_click exists, it is called. If it doesn't return true, then the notes are - // note displayed. Useful for a consumption when a button is already clicked - if (alias_click && !alias_click()) - return; + // If the function alias_click exists, it is called. If it doesn't return true, then the notes are + // note displayed. Useful for a consumption when a button is already clicked + if (alias_click && !alias_click()) { return } - let note_list = $("#" + note_list_id); - let html = ""; - notes_display.forEach(function (disp) { - html += li(note_prefix + "_" + disp.id, - disp.name - + "" - + disp.quantity + "", - displayStyle(disp.note)); - }); + const note_list = $('#' + note_list_id) + let html = '' + notes_display.forEach(function (disp) { + html += li(note_prefix + '_' + disp.id, + disp.name + + '' + + disp.quantity + '', + displayStyle(disp.note)) + }) - // Emitters are displayed - note_list.html(html); + // Emitters are displayed + note_list.html(html) - // Update tooltip position - field.tooltip('update'); + // Update tooltip position + field.tooltip('update') - notes_display.forEach(function (disp) { - let line_obj = $("#" + note_prefix + "_" + disp.id); - // Hover an emitter display also the profile picture - line_obj.hover(function () { - displayNote(disp.note, disp.name, user_note_field, profile_pic_field); - }); + notes_display.forEach(function (disp) { + const line_obj = $('#' + note_prefix + '_' + disp.id) + // Hover an emitter display also the profile picture + line_obj.hover(function () { + displayNote(disp.note, disp.name, user_note_field, profile_pic_field) + }) - // When an emitter is clicked, it is removed - line_obj.click(removeNote(disp, note_prefix, notes_display, note_list_id, user_note_field, - profile_pic_field)); - }); - }) - }); - - });// end getJSON alias - }); + // When an emitter is clicked, it is removed + line_obj.click(removeNote(disp, note_prefix, notes_display, note_list_id, user_note_field, + profile_pic_field)) + }) + }) + }) + })// end getJSON alias + }) }// end function autocomplete - // When a validate button is clicked, we switch the validation status function de_validate (id, validated, resourcetype) { - let validate_obj = $("#validate_" + id); + const validate_obj = $('#validate_' + id) - if (validate_obj.data("pending")) - // The button is already clicked - return; + if (validate_obj.data('pending')) + // The button is already clicked + { return } - let invalidity_reason = $("#invalidity_reason_" + id).val(); - validate_obj.html(""); - validate_obj.data("pending", true); + const invalidity_reason = $('#invalidity_reason_' + id).val() + validate_obj.html('') + validate_obj.data('pending', true) - // Perform a PATCH request to the API in order to update the transaction - // If the user has insufficient rights, an error message will appear - $.ajax({ - "url": "/api/note/transaction/transaction/" + id + "/", - type: "PATCH", - dataType: "json", - headers: { - "X-CSRFTOKEN": CSRF_TOKEN - }, - data: { - "resourcetype": resourcetype, - "valid": !validated, - "invalidity_reason": invalidity_reason, - }, - success: function () { - refreshBalance(); - // error if this method doesn't exist. Please define it. - refreshHistory(); - }, - error: function (err) { - let errObj = JSON.parse(err.responseText); - let error = errObj["detail"] ? errObj["detail"] : errObj["non_field_errors"]; - if (!error) - error = err.responseText; - addMsg("Une erreur est survenue lors de la validation/dévalidation " + - "de cette transaction : " + error, "danger"); + // Perform a PATCH request to the API in order to update the transaction + // If the user has insufficient rights, an error message will appear + $.ajax({ + url: '/api/note/transaction/transaction/' + id + '/', + type: 'PATCH', + dataType: 'json', + headers: { + 'X-CSRFTOKEN': CSRF_TOKEN + }, + data: { + resourcetype: resourcetype, + valid: !validated, + invalidity_reason: invalidity_reason + }, + success: function () { + refreshBalance() + // error if this method doesn't exist. Please define it. + refreshHistory() + }, + error: function (err) { + const errObj = JSON.parse(err.responseText) + let error = errObj.detail ? errObj.detail : errObj.non_field_errors + if (!error) { error = err.responseText } + addMsg('Une erreur est survenue lors de la validation/dévalidation ' + + 'de cette transaction : ' + error, 'danger') - refreshBalance(); - // error if this method doesn't exist. Please define it. - refreshHistory(); - } - }); + refreshBalance() + // error if this method doesn't exist. Please define it. + refreshHistory() + } + }) } /** @@ -404,10 +379,10 @@ function de_validate (id, validated, resourcetype) { * @param wait Debounced milliseconds */ function debounce (callback, wait) { - let timeout; - return (...args) => { - const context = this; - clearTimeout(timeout); - timeout = setTimeout(() => callback.apply(context, args), wait); - }; + let timeout + return (...args) => { + const context = this + clearTimeout(timeout) + timeout = setTimeout(() => callback.apply(context, args), wait) + } } diff --git a/note_kfet/static/js/consos.js b/note_kfet/static/js/consos.js index fc04b2b2..5a7e6144 100644 --- a/note_kfet/static/js/consos.js +++ b/note_kfet/static/js/consos.js @@ -2,95 +2,92 @@ // SPDX-License-Identifier: GPL-3.0-or-later // When a transaction is performed, lock the interface to prevent spam clicks. -var LOCK = false; +var LOCK = false /** * Refresh the history table on the consumptions page. */ -function refreshHistory() { - $("#history").load("/note/consos/ #history"); - $("#most_used").load("/note/consos/ #most_used"); +function refreshHistory () { + $('#history').load('/note/consos/ #history') + $('#most_used').load('/note/consos/ #most_used') } -$(document).ready(function() { - // If hash of a category in the URL, then select this category - // else select the first one - if (location.hash) { - $("a[href='" + location.hash + "']").tab("show"); - } else { - $("a[data-toggle='tab']").first().tab("show"); +$(document).ready(function () { + // If hash of a category in the URL, then select this category + // else select the first one + if (location.hash) { + $("a[href='" + location.hash + "']").tab('show') + } else { + $("a[data-toggle='tab']").first().tab('show') + } + + // When selecting a category, change URL + $(document.body).on('click', "a[data-toggle='tab']", function () { + location.hash = this.getAttribute('href') + }) + + // Switching in double consumptions mode should update the layout + $('#double_conso').change(function () { + $('#consos_list_div').removeClass('d-none') + $('#user_select_div').attr('class', 'col-xl-4') + $('#infos_div').attr('class', 'col-sm-5 col-xl-6') + + const note_list_obj = $('#note_list') + if (buttons.length > 0 && note_list_obj.text().length > 0) { + $('#consos_list').html(note_list_obj.html()) + note_list_obj.html('') + + buttons.forEach(function (button) { + $('#conso_button_' + button.id).click(function () { + if (LOCK) { return } + removeNote(button, 'conso_button', buttons, 'consos_list')() + }) + }) } + }) - // When selecting a category, change URL - $(document.body).on("click", "a[data-toggle='tab']", function() { - location.hash = this.getAttribute("href"); - }); + $('#single_conso').change(function () { + $('#consos_list_div').addClass('d-none') + $('#user_select_div').attr('class', 'col-xl-7') + $('#infos_div').attr('class', 'col-sm-5 col-md-4') - // Switching in double consumptions mode should update the layout - $("#double_conso").click(function() { - $("#consos_list_div").removeClass('d-none'); - $("#user_select_div").attr('class', 'col-xl-4'); - $("#infos_div").attr('class', 'col-sm-5 col-xl-6'); + const consos_list_obj = $('#consos_list') + if (buttons.length > 0) { + if (notes_display.length === 0 && consos_list_obj.text().length > 0) { + $('#note_list').html(consos_list_obj.html()) + consos_list_obj.html('') + buttons.forEach(function (button) { + $('#conso_button_' + button.id).click(function () { + if (LOCK) { return } + removeNote(button, 'conso_button', buttons, 'note_list')() + }) + }) + } else { + buttons.length = 0 + consos_list_obj.html('') + } + } + }) - let note_list_obj = $("#note_list"); - if (buttons.length > 0 && note_list_obj.text().length > 0) { - $("#consos_list").html(note_list_obj.html()); - note_list_obj.html(""); + // Ensure we begin in single consumption. Fix issue with TurboLinks and BootstrapJS + $("label[for='double_conso']").removeClass('active') - buttons.forEach(function(button) { - $("#conso_button_" + button.id).click(function() { - if (LOCK) - return; - removeNote(button, "conso_button", buttons,"consos_list")(); - }); - }); - } - }); + $('#consume_all').click(consumeAll) +}) - $("#single_conso").click(function() { - $("#consos_list_div").addClass('d-none'); - $("#user_select_div").attr('class', 'col-xl-7'); - $("#infos_div").attr('class', 'col-sm-5 col-md-4'); - - let consos_list_obj = $("#consos_list"); - if (buttons.length > 0) { - if (notes_display.length === 0 && consos_list_obj.text().length > 0) { - $("#note_list").html(consos_list_obj.html()); - consos_list_obj.html(""); - buttons.forEach(function(button) { - $("#conso_button_" + button.id).click(function() { - if (LOCK) - return; - removeNote(button, "conso_button", buttons,"note_list")(); - }); - }); - } - else { - buttons.length = 0; - consos_list_obj.html(""); - } - } - }); - - // Ensure we begin in single consumption. Fix issue with TurboLinks and BootstrapJS - $("label[for='double_conso']").removeClass('active'); - - $("#consume_all").click(consumeAll); -}); - -notes = []; -notes_display = []; -buttons = []; +notes = [] +notes_display = [] +buttons = [] // When the user searches an alias, we update the auto-completion -autoCompleteNote("note", "note_list", notes, notes_display, - "alias", "note", "user_note", "profile_pic", function() { - if (buttons.length > 0 && $("#single_conso").is(":checked")) { - consumeAll(); - return false; - } - return true; - }); +autoCompleteNote('note', 'note_list', notes, notes_display, + 'alias', 'note', 'user_note', 'profile_pic', function () { + if (buttons.length > 0 && $('#single_conso').is(':checked')) { + consumeAll() + return false + } + return true + }) /** * Add a transaction from a button. @@ -102,103 +99,98 @@ autoCompleteNote("note", "note_list", notes, notes_display, * @param template_id The identifier of the button * @param template_name The name of the button */ -function addConso(dest, amount, type, category_id, category_name, template_id, template_name) { - var button = null; - buttons.forEach(function(b) { - if (b.id === template_id) { - b.quantity += 1; - button = b; - } - }); - if (button == null) { - button = { - id: template_id, - name: template_name, - dest: dest, - quantity: 1, - amount: amount, - type: type, - category_id: category_id, - category_name: category_name - }; - buttons.push(button); +function addConso (dest, amount, type, category_id, category_name, template_id, template_name) { + var button = null + buttons.forEach(function (b) { + if (b.id === template_id) { + b.quantity += 1 + button = b } - - let dc_obj = $("#double_conso"); - if (dc_obj.is(":checked") || notes_display.length === 0) { - let list = dc_obj.is(":checked") ? "consos_list" : "note_list"; - let html = ""; - buttons.forEach(function(button) { - html += li("conso_button_" + button.id, button.name - + "" + button.quantity + ""); - }); - - $("#" + list).html(html); - - buttons.forEach(function(button) { - $("#conso_button_" + button.id).click(function() { - if (LOCK) - return; - removeNote(button, "conso_button", buttons, list)(); - }); - }); + }) + if (button == null) { + button = { + id: template_id, + name: template_name, + dest: dest, + quantity: 1, + amount: amount, + type: type, + category_id: category_id, + category_name: category_name } - else - consumeAll(); + buttons.push(button) + } + + const dc_obj = $('#double_conso') + if (dc_obj.is(':checked') || notes_display.length === 0) { + const list = dc_obj.is(':checked') ? 'consos_list' : 'note_list' + let html = '' + buttons.forEach(function (button) { + html += li('conso_button_' + button.id, button.name + + '' + button.quantity + '') + }) + + $('#' + list).html(html) + + buttons.forEach(function (button) { + $('#conso_button_' + button.id).click(function () { + if (LOCK) { return } + removeNote(button, 'conso_button', buttons, list)() + }) + }) + } else { consumeAll() } } /** * Reset the page as its initial state. */ -function reset() { - notes_display.length = 0; - notes.length = 0; - buttons.length = 0; - $("#note_list").html(""); - $("#consos_list").html(""); - $("#note").val(""); - $("#note").attr("data-original-title", "").tooltip("hide"); - $("#profile_pic").attr("src", "/media/pic/default.png"); - $("#profile_pic_link").attr("href", "#"); - refreshHistory(); - refreshBalance(); - LOCK = false; +function reset () { + notes_display.length = 0 + notes.length = 0 + buttons.length = 0 + $('#note_list').html('') + $('#consos_list').html('') + $('#note').val('') + $('#note').attr('data-original-title', '').tooltip('hide') + $('#profile_pic').attr('src', '/static/member/img/default_picture.png') + $('#profile_pic_link').attr('href', '#') + refreshHistory() + refreshBalance() + LOCK = false } - /** * Apply all transactions: all notes in `notes` buy each item in `buttons` */ -function consumeAll() { - if (LOCK) - return; +function consumeAll () { + if (LOCK) { return } - LOCK = true; + LOCK = true - let error = false; + let error = false - if (notes_display.length === 0) { - $("#note").addClass('is-invalid'); - $("#note_list").html(li("", "Ajoutez des émetteurs.", "text-danger")); - error = true; - } + if (notes_display.length === 0) { + $('#note').addClass('is-invalid') + $('#note_list').html(li('', 'Ajoutez des émetteurs.', 'text-danger')) + error = true + } - if (buttons.length === 0) { - $("#consos_list").html(li("", "Ajoutez des consommations.", "text-danger")); - error = true; - } + if (buttons.length === 0) { + $('#consos_list').html(li('', 'Ajoutez des consommations.', 'text-danger')) + error = true + } - if (error) { - LOCK = false; - return; - } + if (error) { + LOCK = false + return + } - notes_display.forEach(function(note_display) { - buttons.forEach(function(button) { - consume(note_display.note, note_display.name, button.dest, button.quantity * note_display.quantity, button.amount, - button.name + " (" + button.category_name + ")", button.type, button.category_id, button.id); - }); - }); + notes_display.forEach(function (note_display) { + buttons.forEach(function (button) { + consume(note_display.note, note_display.name, button.dest, button.quantity * note_display.quantity, button.amount, + button.name + ' (' + button.category_name + ')', button.type, button.category_id, button.id) + }) + }) } /** @@ -213,58 +205,60 @@ function consumeAll() { * @param category The category id of the button (type: int) * @param template The button id (type: int) */ -function consume(source, source_alias, dest, quantity, amount, reason, type, category, template) { - $.post("/api/note/transaction/transaction/", +function consume (source, source_alias, dest, quantity, amount, reason, type, category, template) { + $.post('/api/note/transaction/transaction/', + { + csrfmiddlewaretoken: CSRF_TOKEN, + quantity: quantity, + amount: amount, + reason: reason, + valid: true, + polymorphic_ctype: type, + resourcetype: 'RecurrentTransaction', + source: source.id, + source_alias: source_alias, + destination: dest, + template: template + }) + .done(function () { + if (!isNaN(source.balance)) { + const newBalance = source.balance - quantity * amount + if (newBalance <= -5000) { + addMsg('Attention, La transaction depuis la note ' + source_alias + ' a été réalisée avec ' + + 'succès, mais la note émettrice ' + source_alias + ' est en négatif sévère.', + 'danger', 30000) + } else if (newBalance < 0) { + addMsg('Attention, La transaction depuis la note ' + source_alias + ' a été réalisée avec ' + + 'succès, mais la note émettrice ' + source_alias + ' est en négatif.', + 'warning', 30000) + } + if (source.membership && source.membership.date_end < new Date().toISOString()) { + addMsg('Attention : la note émettrice ' + source.name + " n'est plus adhérente.", + 'danger', 30000) + } + } + reset() + }).fail(function (e) { + $.post('/api/note/transaction/transaction/', { - "csrfmiddlewaretoken": CSRF_TOKEN, - "quantity": quantity, - "amount": amount, - "reason": reason, - "valid": true, - "polymorphic_ctype": type, - "resourcetype": "RecurrentTransaction", - "source": source.id, - "source_alias": source_alias, - "destination": dest, - "template": template - }) - .done(function () { - if (!isNaN(source.balance)) { - let newBalance = source.balance - quantity * amount; - if (newBalance <= -5000) - addMsg("Attention, La transaction depuis la note " + source_alias + " a été réalisée avec " + - "succès, mais la note émettrice " + source_alias + " est en négatif sévère.", - "danger", 30000); - else if (newBalance < 0) - addMsg("Attention, La transaction depuis la note " + source_alias + " a été réalisée avec " + - "succès, mais la note émettrice " + source_alias + " est en négatif.", - "warning", 30000); - if (source.membership && source.membership.date_end < new Date().toISOString()) - addMsg("Attention : la note émettrice " + source.name + " n'est plus adhérente.", - "danger", 30000); - } - reset(); - }).fail(function (e) { - $.post("/api/note/transaction/transaction/", - { - "csrfmiddlewaretoken": CSRF_TOKEN, - "quantity": quantity, - "amount": amount, - "reason": reason, - "valid": false, - "invalidity_reason": "Solde insuffisant", - "polymorphic_ctype": type, - "resourcetype": "RecurrentTransaction", - "source": source, - "source_alias": source_alias, - "destination": dest, - "template": template - }).done(function() { - reset(); - addMsg("La transaction n'a pas pu être validée pour cause de solde insuffisant.", "danger", 10000); - }).fail(function () { - reset(); - errMsg(e.responseJSON); - }); - }); + csrfmiddlewaretoken: CSRF_TOKEN, + quantity: quantity, + amount: amount, + reason: reason, + valid: false, + invalidity_reason: 'Solde insuffisant', + polymorphic_ctype: type, + resourcetype: 'RecurrentTransaction', + source: source, + source_alias: source_alias, + destination: dest, + template: template + }).done(function () { + reset() + addMsg("La transaction n'a pas pu être validée pour cause de solde insuffisant.", 'danger', 10000) + }).fail(function () { + reset() + errMsg(e.responseJSON) + }) + }) } diff --git a/note_kfet/static/js/dynamic-formset.js b/note_kfet/static/js/dynamic-formset.js index c6ff3328..88d01eca 100644 --- a/note_kfet/static/js/dynamic-formset.js +++ b/note_kfet/static/js/dynamic-formset.js @@ -9,241 +9,240 @@ * Licensed under the New BSD License * See: http://www.opensource.org/licenses/bsd-license.php */ -;(function($) { - $.fn.formset = function(opts) - { - var options = $.extend({}, $.fn.formset.defaults, opts), - flatExtraClasses = options.extraClasses.join(' '), - totalForms = $('#id_' + options.prefix + '-TOTAL_FORMS'), - maxForms = $('#id_' + options.prefix + '-MAX_NUM_FORMS'), - minForms = $('#id_' + options.prefix + '-MIN_NUM_FORMS'), - childElementSelector = 'input,select,textarea,label,div', - $$ = $(this), +;(function ($) { + $.fn.formset = function (opts) { + var options = $.extend({}, $.fn.formset.defaults, opts) + var flatExtraClasses = options.extraClasses.join(' ') + var totalForms = $('#id_' + options.prefix + '-TOTAL_FORMS') + var maxForms = $('#id_' + options.prefix + '-MAX_NUM_FORMS') + var minForms = $('#id_' + options.prefix + '-MIN_NUM_FORMS') + var childElementSelector = 'input,select,textarea,label,div' + var $$ = $(this) - applyExtraClasses = function(row, ndx) { - if (options.extraClasses) { - row.removeClass(flatExtraClasses); - row.addClass(options.extraClasses[ndx % options.extraClasses.length]); - } - }, + var applyExtraClasses = function (row, ndx) { + if (options.extraClasses) { + row.removeClass(flatExtraClasses) + row.addClass(options.extraClasses[ndx % options.extraClasses.length]) + } + } - updateElementIndex = function(elem, prefix, ndx) { - var idRegex = new RegExp(prefix + '-(\\d+|__prefix__)-'), - replacement = prefix + '-' + ndx + '-'; - if (elem.attr("for")) elem.attr("for", elem.attr("for").replace(idRegex, replacement)); - if (elem.attr('id')) elem.attr('id', elem.attr('id').replace(idRegex, replacement)); - if (elem.attr('name')) elem.attr('name', elem.attr('name').replace(idRegex, replacement)); - }, + var updateElementIndex = function (elem, prefix, ndx) { + var idRegex = new RegExp(prefix + '-(\\d+|__prefix__)-') + var replacement = prefix + '-' + ndx + '-' + if (elem.attr('for')) elem.attr('for', elem.attr('for').replace(idRegex, replacement)) + if (elem.attr('id')) elem.attr('id', elem.attr('id').replace(idRegex, replacement)) + if (elem.attr('name')) elem.attr('name', elem.attr('name').replace(idRegex, replacement)) + } - hasChildElements = function(row) { - return row.find(childElementSelector).length > 0; - }, + var hasChildElements = function (row) { + return row.find(childElementSelector).length > 0 + } - showAddButton = function() { - return maxForms.length == 0 || // For Django versions pre 1.2 - (maxForms.val() == '' || (maxForms.val() - totalForms.val() > 0)); - }, + var showAddButton = function () { + return maxForms.length === 0 || // For Django versions pre 1.2 + (maxForms.val() === '' || (maxForms.val() - totalForms.val() > 0)) + } - /** + /** * Indicates whether delete link(s) can be displayed - when total forms > min forms */ - showDeleteLinks = function() { - return minForms.length == 0 || // For Django versions pre 1.7 - (minForms.val() == '' || (totalForms.val() - minForms.val() > 0)); - }, + var showDeleteLinks = function () { + return minForms.length === 0 || // For Django versions pre 1.7 + (minForms.val() === '' || (totalForms.val() - minForms.val() > 0)) + } - insertDeleteLink = function(row) { - var delCssSelector = $.trim(options.deleteCssClass).replace(/\s+/g, '.'), - addCssSelector = $.trim(options.addCssClass).replace(/\s+/g, '.'); + var insertDeleteLink = function (row) { + var delCssSelector = $.trim(options.deleteCssClass).replace(/\s+/g, '.') + var addCssSelector = $.trim(options.addCssClass).replace(/\s+/g, '.') - var delButtonHTML = '' + options.deleteText +''; - if (options.deleteContainerClass) { - // If we have a specific container for the remove button, - // place it as the last child of that container: - row.find('[class*="' + options.deleteContainerClass + '"]').append(delButtonHTML); - } else if (row.is('TR')) { - // If the forms are laid out in table rows, insert - // the remove button into the last table cell: - row.children('td:last').append(delButtonHTML); - } else if (row.is('UL') || row.is('OL')) { - // If they're laid out as an ordered/unordered list, - // insert an
  • after the last list item: - row.append('
  • ' + delButtonHTML + '
  • '); - } else { - // Otherwise, just insert the remove button as the - // last child element of the form's container: - row.append(delButtonHTML); - } + var delButtonHTML = '' + options.deleteText + '' + if (options.deleteContainerClass) { + // If we have a specific container for the remove button, + // place it as the last child of that container: + row.find('[class*="' + options.deleteContainerClass + '"]').append(delButtonHTML) + } else if (row.is('TR')) { + // If the forms are laid out in table rows, insert + // the remove button into the last table cell: + row.children('td:last').append(delButtonHTML) + } else if (row.is('UL') || row.is('OL')) { + // If they're laid out as an ordered/unordered list, + // insert an
  • after the last list item: + row.append('
  • ' + delButtonHTML + '
  • ') + } else { + // Otherwise, just insert the remove button as the + // last child element of the form's container: + row.append(delButtonHTML) + } - // Check if we're under the minimum number of forms - not to display delete link at rendering - if (!showDeleteLinks()){ - row.find('a.' + delCssSelector).hide(); - } + // Check if we're under the minimum number of forms - not to display delete link at rendering + if (!showDeleteLinks()) { + row.find('a.' + delCssSelector).hide() + } - row.find('a.' + delCssSelector).click(function() { - var row = $(this).parents('.' + options.formCssClass), - del = row.find('input:hidden[id $= "-DELETE"]'), - buttonRow = row.siblings("a." + addCssSelector + ', .' + options.formCssClass + '-add'), - forms; - if (del.length) { - // We're dealing with an inline formset. - // Rather than remove this form from the DOM, we'll mark it as deleted - // and hide it, then let Django handle the deleting: - del.val('on'); - row.hide(); - forms = $('.' + options.formCssClass).not(':hidden'); - } else { - row.remove(); - // Update the TOTAL_FORMS count: - forms = $('.' + options.formCssClass).not('.formset-custom-template'); - totalForms.val(forms.length); - } - for (var i=0, formCount=forms.length; i
    {% endif %} -
    - - Attention : la Note Kfet 2020 est en phase de beta. Des fonctionnalités pourront être rajoutées d'ici à la version - finale, et des bugs peuvent survenir. Pour tout problème, merci d'envoyer un mail à l'adresse - - notekfet2020@lists.crans.org, - ou bien levez une issue sur le dépôt Gitlab, - ou encore posez un commentaire sur le pad.

    - - Certaines données ont été anonymisées afin de limiter les fuites de données, et peuvent ne pas correspondre avec vos données réelles. -
    {% block content %}

    Default content...

    @@ -178,7 +169,7 @@ SPDX-License-Identifier: GPL-3.0-or-later class="form-inline"> Nous contacter — + class="text-muted">{% trans "Contact us" %} — {% csrf_token %}