Compare commits

..

1 Commits

@ -1,147 +0,0 @@
name: Build and test
on:
push:
branches:
- main
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
REGISTRY: ghcr.io
APP_IMAGE_NAME: ${{ github.repository }}
NGINX_IMAGE_NAME: ${{ github.repository }}-nginx
jobs:
build-test-and-deploy:
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: recursive
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata for application image
id: meta-app
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.APP_IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=sha,prefix={{branch}}-
type=raw,value=latest,enable={{is_default_branch}}
- name: Extract metadata for nginx image
id: meta-nginx
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.NGINX_IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=sha,prefix={{branch}}-
type=raw,value=latest,enable={{is_default_branch}}
- name: Build application image
uses: docker/build-push-action@v5
with:
context: .
file: docker/production/Dockerfile
load: true
tags: kompass:test
cache-from: |
type=gha,scope=app-${{ github.ref_name }}
type=gha,scope=app-master
type=gha,scope=app-main
type=registry,ref=ghcr.io/${{ github.repository }}:latest
cache-to: type=gha,mode=max,scope=app-${{ github.ref_name }}
build-args: |
BUILDKIT_INLINE_CACHE=1
- name: Build documentation
run: |
# Create output directory with proper permissions
mkdir -p docs-output
chmod 777 docs-output
# Run sphinx-build inside the container
docker run --rm \
-v ${{ github.workspace }}/docs:/app/docs:ro \
-v ${{ github.workspace }}/docs-output:/app/docs-output \
kompass:test \
bash -c "cd /app/docs && sphinx-build -b html source /app/docs-output"
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v4
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docs-output
destination_dir: ${{ github.ref == 'refs/heads/main' && '.' || github.ref_name }}
keep_files: true
- name: Run tests
run: make test-only
- name: Check coverage
run: |
COVERAGE=$(python3 -c "import json; data=json.load(open('docker/test/htmlcov/coverage.json')); print(data['totals']['percent_covered'])")
echo "Coverage: ${COVERAGE}%"
if (( $(echo "$COVERAGE < 100" | bc -l) )); then
echo "Error: Coverage is ${COVERAGE}%, must be 100%"
exit 1
fi
- name: Tag and push application image
if: github.event_name != 'pull_request'
run: |
# Tag the built image with all required tags
echo "${{ steps.meta-app.outputs.tags }}" | while read -r tag; do
docker tag kompass:test "$tag"
docker push "$tag"
done
- name: Build and push nginx image
if: github.event_name != 'pull_request'
uses: docker/build-push-action@v5
with:
context: docker/production/nginx
file: docker/production/nginx/Dockerfile
push: true
tags: ${{ steps.meta-nginx.outputs.tags }}
labels: ${{ steps.meta-nginx.outputs.labels }}
cache-from: |
type=gha,scope=nginx-${{ github.ref_name }}
type=gha,scope=nginx-master
type=gha,scope=nginx-main
type=registry,ref=ghcr.io/${{ github.repository }}-nginx:latest
cache-to: type=gha,mode=max,scope=nginx-${{ github.ref_name }}
build-args: |
BUILDKIT_INLINE_CACHE=1
- name: Output image tags
if: github.event_name != 'pull_request'
run: |
echo "Application image tags:"
echo "${{ steps.meta-app.outputs.tags }}"
echo ""
echo "Nginx image tags:"
echo "${{ steps.meta-nginx.outputs.tags }}"

3
.gitignore vendored

@ -133,6 +133,3 @@ jdav_web/static/docs
# mac files
.DS_Store
# Claude configuration file
CLAUDE.md

3
.gitmodules vendored

@ -0,0 +1,3 @@
[submodule "jdav_web/jet"]
path = jdav_web/jet
url = https://git.flavigny.de/jdavlb/jet/

@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

@ -1,7 +1,7 @@
build-test:
cd docker/test; docker compose build
test-only:
test: build-test
mkdir -p docker/test/htmlcov
chmod 777 docker/test/htmlcov
ifeq ($(keepdb), true)
@ -10,5 +10,3 @@ else
cd docker/test; docker compose up --abort-on-container-exit
endif
echo "Generated coverage report. To read it, point your browser to:\n\nfile://$$(pwd)/docker/test/htmlcov/index.html"
test: build-test test-only

@ -1,2 +0,0 @@
This repository contains third-party assets. Attributions are either placed in the file itself or
in a file `NOTICE.txt` in the respective folder.

@ -1,30 +1,24 @@
# jdav Kompass
![Build Status](https://github.com/chrisflav/kompass/actions/workflows/build-docker.yml/badge.svg?branch=main)
[![Build Status](https://jenkins.merten.dev/buildStatus/icon?job=gitea%2Fkompass%2Fmain)](https://jenkins.merten.dev/job/gitea/job/kompass/job/main/)
Kompass is an administration platform designed for local sections of the Young German Alpine Club. It provides
tools to contact and (automatically) manage members, groups, material, excursions and statements.
For more details on the features, see the (German) [documentation](https://jdav-hd.de/static/docs/index.html).
If you are interested in using the Kompass in your own local section, please get in touch via
email at `name of this project`@`merten.dev`. We are very happy to discuss how the Kompass can be used in
your setting.
# Contributing
Any form of contribution is appreciated. If you found a bug or have a feature request, please file an
[issue](https://github.com/chrisflav/kompass/issues). If you want to help with the documentation or
want to contribute code, please open a [pull request](https://github.com/chrisflav/kompass/pulls).
If you don't have a github account or don't want to open an issue or pull request here, there is
also a [Gitea repository](https://git.jdav-hd.merten.dev/digitales/kompass).
[issue](https://git.jdav-hd.merten.dev/digitales/kompass/issues). If you want to help with the documentation or
want to contribute code, please open a [pull request](https://git.jdav-hd.merten.dev/digitales/kompass/pulls).
The following is a short description of where to find the documentation with more information.
# Documentation
Documentation is handled by [sphinx](https://www.sphinx-doc.org/) and located in `docs/`.
# Documentation
Documentation is handled by [sphinx](https://www.sphinx-doc.org/) and located in `docs/`.
The sphinx documentation contains information about:
- Development Setup
@ -34,12 +28,19 @@ The sphinx documentation contains information about:
- End user documentation
- and much more...
For further details on the implementation, please head to the
[developer documentation](https://jdav-hd.de/static/docs/development_manual/index.html).
> Please add all further documentation also in the sphinx documentation. And not in the readme
# License
## online
Online (latest release version): https://jdav-hd.de/static/docs/
This code is licensed under the [GNU Affero General Public License](https://www.gnu.org/licenses/agpl-3.0.en.html).
For the full license text, see `LICENCSE`.
## local
To read the documentation build it locally and view it in your browser:
```bash
cd docs/
make html
See the `NOTICE.txt` file for attributions.
# MacOS (with firefox)
open -a firefox $(pwd)/docs/build/html/index.html
# Linux (I guess?!?)
firefox ${pwd}/docs/build/html/index.html
```

@ -13,7 +13,7 @@ services:
master:
<<: *kompass
build:
context: https://github.com/chrisflav/kompass.git#main
context: git@git.jdav-hd.merten.dev:digitales/kompass#main
dockerfile: docker/production/Dockerfile
entrypoint: /app/docker/production/entrypoint-master.sh
volumes:
@ -28,7 +28,7 @@ services:
- "host:10.26.42.1"
nginx:
build: https://github.com/chrisflav/kompass.git#main:docker/production/nginx
build: git@git.jdav-hd.merten.dev:digitales/kompass#main:docker/production/nginx
restart: always
volumes:
- uwsgi_data:/tmp/uwsgi/

@ -16,7 +16,6 @@ if ! [ -f completed_initial_run ]; then
python jdav_web/manage.py compilemessages --locale de
python jdav_web/manage.py migrate
python jdav_web/manage.py ensuresuperuser
touch completed_initial_run
fi

@ -22,6 +22,8 @@ ENV PATH="/app/.local/bin:$PATH"
# install requirements
COPY --chown=app:app ./requirements.txt /app/requirements.txt
RUN pip install uwsgi -r requirements.txt
# we install uwsgi here to check if packages dependencies are resolved, but we don't actually
# need uwsgi in test
RUN pip install coverage uwsgi -r requirements.txt
COPY --chown=app:app . /app

@ -29,6 +29,3 @@ password = 'password'
[startpage]
recent_section = 'aktuelles'
reports_section = 'berichte'
[misc]
allowed_email_domains_for_invite_as_user = ['test-organization.org']

@ -1,12 +0,0 @@
confirm_mail = """
Hiho custom test test {name},
du hast bei der JDAV %(SEKTION)s eine E-Mail Adresse hinterlegt. Da bei uns alle Kommunikation
per Email funktioniert, brauchen wir eine Bestätigung {whattoconfirm}.
Custom!
{link}
Test test
Deine JDAV test test %(SEKTION)s"""

@ -39,10 +39,8 @@ fi
cd jdav_web
if [[ "$DJANGO_TEST_KEEPDB" == 1 ]]; then
coverage run manage.py test startpage finance members contrib logindata mailer material ludwigsburgalpin jdav_web -v 2 --noinput --keepdb
coverage run manage.py test startpage finance members contrib logindata mailer material ludwigsburgalpin -v 2 --noinput --keepdb
else
coverage run manage.py test startpage finance members contrib logindata mailer material ludwigsburgalpin jdav_web -v 2 --noinput
coverage run manage.py test startpage finance members contrib logindata mailer material ludwigsburgalpin -v 2 --noinput
fi
coverage html --show-contexts
coverage json -o htmlcov/coverage.json
coverage report
coverage html

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 27.3.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 48 48" style="enable-background:new 0 0 48 48;" xml:space="preserve">
<style type="text/css">
.st0{display:none;}
.st1{display:inline;fill:#254D49;}
.st2{display:inline;opacity:0.27;fill:url(#SVGID_1_);}
.st3{fill:none;stroke:#1B2E2C;stroke-width:3;stroke-miterlimit:10;}
.st4{fill:#1B2E2C;}
.st5{fill:none;stroke:#508480;stroke-width:3.2;stroke-miterlimit:10;}
.st6{fill:#BADDD9;}
.st7{fill:#508480;}
.st8{opacity:0.36;}
.st9{opacity:0.24;fill:#FFFFFF;}
</style>
<g id="Hintergrund_x5F_Uni" class="st0">
<rect class="st1" width="48" height="48"/>
</g>
<g id="Verlauf" class="st0">
<radialGradient id="SVGID_1_" cx="23.348" cy="21.0566" r="25.4002" fx="3.9002" fy="4.7179" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color:#000000;stop-opacity:0"/>
<stop offset="1" style="stop-color:#000000"/>
</radialGradient>
<circle class="st2" cx="23.6" cy="23.6" r="22.9"/>
</g>
<g id="Logo_x5F_Schatten">
<circle class="st3" cx="24.3" cy="24.3" r="21.7"/>
<polygon class="st4" points="21.4,22.9 15.8,42.4 27.5,25.7 33.2,6.2 "/>
</g>
<g id="LogooVordergrund">
<circle class="st5" cx="23.7" cy="23.7" r="21.7"/>
<g>
<polygon class="st6" points="14.9,41.8 26.6,25.1 20.5,22.2 "/>
<polygon class="st7" points="32.3,5.5 20.5,22.2 26.6,25.1 "/>
<polyline class="st8" points="14.9,41.8 26.6,25.1 32.3,5.5 "/>
<circle class="st9" cx="23.6" cy="23.6" r="1.6"/>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.6 KiB

@ -35,8 +35,8 @@ html_static_path = ['_static']
# -- Sphinxawsome-theme options ------------------------------------------------
# https://sphinxawesome.xyz/how-to/configure/
html_logo = "_static/favicon.svg"
html_favicon = "_static/favicon.svg"
html_logo = "_static/favicon.png"
html_favicon = "_static/favicon.png"
html_sidebars = {
"about": ["sidebar_main_nav_links.html"],

@ -1,10 +1,4 @@
[run]
source =
.
dynamic_context = test_function
[report]
omit =
./jet/*
manage.py
jdav_web/wsgi.py

@ -12,26 +12,6 @@ import rules.contrib.admin
from rules.permissions import perm_exists
def decorate_admin_view(model, perm=None):
"""
Decorator for wrapping admin views.
"""
def decorator(fun):
def aux(self, request, object_id):
try:
obj = model.objects.get(pk=object_id)
except model.DoesNotExist:
messages.error(request, _('%(modelname)s not found.') % {'modelname': self.opts.verbose_name})
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
permitted = self.has_change_permission(request, obj) if not perm else request.user.has_perm(perm)
if not permitted:
messages.error(request, _('Insufficient permissions.'))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
return fun(self, request, obj)
return aux
return decorator
class FieldPermissionsAdminMixin:
field_change_permissions = {}
field_view_permissions = {}

@ -1,28 +0,0 @@
import os
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Creates a super-user non-interactively if it doesn't exist."
def handle(self, *args, **options):
User = get_user_model()
username = os.environ.get('DJANGO_SUPERUSER_USERNAME', '')
password = os.environ.get('DJANGO_SUPERUSER_PASSWORD', '')
if not username or not password:
self.stdout.write(
self.style.WARNING('Superuser data was not set. Skipping.')
)
return
if not User.objects.filter(username=username).exists():
User.objects.create_superuser(username=username, password=password)
self.stdout.write(
self.style.SUCCESS('Successfully created superuser.')
)
else:
self.stdout.write(
self.style.SUCCESS('Superuser with configured username already exists. Skipping.')
)

@ -1,175 +1,3 @@
from datetime import datetime, timedelta
from decimal import Decimal
from django.test import TestCase, RequestFactory
from django.contrib.auth import get_user_model
from django.contrib import admin
from django.db import models
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils.translation import gettext_lazy as _
from unittest.mock import Mock, patch
from rules.contrib.models import RulesModelMixin, RulesModelBase
from contrib.models import CommonModel
from contrib.rules import has_global_perm
from contrib.admin import CommonAdminMixin
from utils import file_size_validator, RestrictedFileField, cvt_to_decimal, get_member, normalize_name, normalize_filename, coming_midnight, mondays_until_nth
from django.test import TestCase
User = get_user_model()
class CommonModelTestCase(TestCase):
def test_common_model_abstract_base(self):
"""Test that CommonModel provides the correct meta attributes"""
meta = CommonModel._meta
self.assertTrue(meta.abstract)
expected_permissions = (
'add_global', 'change_global', 'view_global', 'delete_global', 'list_global', 'view',
)
self.assertEqual(meta.default_permissions, expected_permissions)
def test_common_model_inheritance(self):
"""Test that CommonModel has rules mixin functionality"""
# Test that CommonModel has the expected functionality
# Since it's abstract, we can't instantiate it directly
# but we can check its metaclass and mixins
self.assertTrue(issubclass(CommonModel, RulesModelMixin))
self.assertEqual(CommonModel.__class__, RulesModelBase)
class GlobalPermissionRulesTestCase(TestCase):
def setUp(self):
self.user = User.objects.create_user(
username='testuser',
email='test@example.com',
password='testpass123'
)
def test_has_global_perm_predicate_creation(self):
"""Test that has_global_perm creates a predicate function"""
# has_global_perm is a decorator factory, not a direct predicate
predicate = has_global_perm('auth.add_user')
self.assertTrue(callable(predicate))
def test_has_global_perm_with_superuser(self):
"""Test that superusers have global permissions"""
self.user.is_superuser = True
self.user.save()
predicate = has_global_perm('auth.add_user')
result = predicate(self.user, None)
self.assertTrue(result)
def test_has_global_perm_with_regular_user(self):
"""Test that regular users don't automatically have global permissions"""
predicate = has_global_perm('auth.add_user')
result = predicate(self.user, None)
self.assertFalse(result)
class CommonAdminMixinTestCase(TestCase):
def setUp(self):
self.user = User.objects.create_user(username='testuser', password='testpass')
def test_formfield_for_dbfield_with_formfield_overrides(self):
"""Test formfield_for_dbfield when db_field class is in formfield_overrides"""
# Create a test admin instance that inherits from Django's ModelAdmin
class TestAdmin(CommonAdminMixin, admin.ModelAdmin):
formfield_overrides = {
models.ForeignKey: {'widget': Mock()}
}
# Create a mock model to use with the admin
class TestModel:
_meta = Mock()
_meta.app_label = 'test'
admin_instance = TestAdmin(TestModel, admin.site)
# Create a mock ForeignKey field to trigger the missing line 147
db_field = models.ForeignKey(User, on_delete=models.CASCADE)
# Create a test request
request = RequestFactory().get('/')
request.user = self.user
# Call the method to test formfield_overrides usage
result = admin_instance.formfield_for_dbfield(db_field, request, help_text='Test help text')
# Verify that the formfield_overrides were used
self.assertIsNotNone(result)
class UtilsTestCase(TestCase):
def setUp(self):
self.user = User.objects.create_user(
username='testuser',
email='test@example.com',
password='testpass123'
)
def test_file_size_validator_exceeds_limit(self):
"""Test file_size_validator when file exceeds size limit"""
validator = file_size_validator(1) # 1MB limit
# Create a mock file that exceeds the limit (2MB)
mock_file = Mock()
mock_file.size = 2 * 1024 * 1024 # 2MB
with self.assertRaises(ValidationError) as cm:
validator(mock_file)
# Check for the translated error message
expected_message = str(_('Please keep filesize under {} MiB. Current filesize: {:10.2f} MiB.').format(1, 2.00))
self.assertIn(expected_message, str(cm.exception))
def test_restricted_file_field_content_type_not_supported(self):
"""Test RestrictedFileField when content type is not supported"""
field = RestrictedFileField(content_types=['image/jpeg'])
# Create mock data with unsupported content type
mock_data = Mock()
mock_data.file = Mock()
mock_data.file.content_type = "text/plain"
# Mock the super().clean() to return our mock data
with patch.object(models.FileField, 'clean', return_value=mock_data):
with self.assertRaises(ValidationError) as cm:
field.clean("dummy")
# Check for the translated error message
expected_message = str(_('Filetype not supported.'))
self.assertIn(expected_message, str(cm.exception))
def test_restricted_file_field_size_exceeds_limit(self):
"""Test RestrictedFileField when file size exceeds limit"""
field = RestrictedFileField(max_upload_size=1) # 1 byte limit
# Create mock data with file that exceeds size limit
mock_data = Mock()
mock_data.file = Mock()
mock_data.file.content_type = "text/plain"
mock_data.file._size = 2 # 2 bytes, exceeds limit
# Mock the super().clean() to return our mock data
with patch.object(models.FileField, 'clean', return_value=mock_data):
with self.assertRaises(ValidationError) as cm:
field.clean("dummy")
# Check for the translated error message
expected_message = str(_('Please keep filesize under {}. Current filesize: {}').format(1, 2))
self.assertIn(expected_message, str(cm.exception))
def test_mondays_until_nth(self):
"""Test mondays_until_nth function"""
# Test with n=2 to get 3 Mondays (including the 0th)
result = mondays_until_nth(2)
# Should return a list of 3 dates
self.assertEqual(len(result), 3)
# All dates should be Mondays (weekday 0)
for date in result:
self.assertEqual(date.weekday(), 0) # Monday is 0
# Dates should be consecutive weeks
self.assertEqual(result[1] - result[0], timedelta(days=7))
self.assertEqual(result[2] - result[1], timedelta(days=7))
# Create your tests here.

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

@ -1,6 +1,4 @@
import logging
from django.contrib import admin, messages
from django.utils.safestring import mark_safe
from django import forms
from django.forms import Textarea, ClearableFileInput
from django.http import HttpResponse, HttpResponseRedirect
@ -15,13 +13,10 @@ from contrib.admin import CommonAdminInlineMixin, CommonAdminMixin
from utils import get_member, RestrictedFileField
from rules.contrib.admin import ObjectPermissionsModelAdmin
from members.pdf import render_tex_with_attachments
from .models import Ledger, Statement, Receipt, Transaction, Bill, StatementSubmitted, StatementConfirmed,\
StatementUnSubmitted, BillOnStatementProxy
logger = logging.getLogger(__name__)
@admin.register(Ledger)
class LedgerAdmin(admin.ModelAdmin):
@ -45,75 +40,24 @@ class BillOnStatementInline(CommonAdminInlineMixin, admin.TabularInline):
form = BillOnStatementInlineForm
def decorate_statement_view(model, perm=None):
def decorator(fun):
def aux(self, request, object_id):
try:
statement = model.objects.get(pk=object_id)
except model.DoesNotExist:
messages.error(request, _('Statement not found.'))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
permitted = self.has_change_permission(request, statement) if not perm else request.user.has_perm(perm)
if not permitted:
messages.error(request, _('Insufficient permissions.'))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
return fun(self, request, statement)
return aux
return decorator
@admin.register(Statement)
class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
fields = ['short_description', 'explanation', 'excursion', 'status']
list_display = ['__str__', 'total_pretty', 'created_by', 'submitted_date', 'status_badge']
list_filter = ['status']
search_fields = ('excursion__name', 'short_description')
ordering = ['-submitted_date']
@admin.register(StatementUnSubmitted)
class StatementUnSubmittedAdmin(CommonAdminMixin, admin.ModelAdmin):
fields = ['short_description', 'explanation', 'excursion', 'submitted']
list_display = ['__str__', 'excursion', 'created_by']
inlines = [BillOnStatementInline]
list_per_page = 25
def has_change_permission(self, request, obj=None):
if obj is None:
return super().has_change_permission(request)
if obj.confirmed:
# Confirmed statements may not be changed (they should be unconfirmed first)
return False
return super().has_change_permission(request, obj)
def has_delete_permission(self, request, obj=None):
if obj is None or obj.submitted:
# Submitted statements may not be deleted (they should be rejected first)
return False
return super().has_delete_permission(request, obj)
def save_model(self, request, obj, form, change):
if not change and hasattr(request.user, 'member'):
obj.created_by = request.user.member
super().save_model(request, obj, form, change)
def get_fields(self, request, obj=None):
if obj is not None and obj.excursion:
# if the object exists and an excursion is set, show the excursion (read only)
# instead of the short description
return ['excursion', 'explanation', 'status']
else:
# if the object is newly created or no excursion is set, require
# a short description
return ['short_description', 'explanation', 'status']
def get_readonly_fields(self, request, obj=None):
readonly_fields = ['status', 'excursion']
readonly_fields = ['submitted', 'excursion']
if obj is not None and obj.submitted:
return readonly_fields + self.fields
else:
return readonly_fields
def get_inlines(self, request, obj=None):
if obj is None or not obj.submitted:
return [BillOnStatementInline]
else:
return [BillOnSubmittedStatementInline, TransactionOnSubmittedStatementInline]
def get_urls(self):
urls = super().get_urls()
@ -130,33 +74,12 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
wrap(self.submit_view),
name="%s_%s_submit" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/overview/",
wrap(self.overview_view),
name="%s_%s_overview" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/reduce_transactions/",
wrap(self.reduce_transactions_view),
name="%s_%s_reduce_transactions" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/unconfirm/",
wrap(self.unconfirm_view),
name="%s_%s_unconfirm" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/summary/",
wrap(self.statement_summary_view),
name="%s_%s_summary" % (self.opts.app_label, self.opts.model_name),
),
]
return custom_urls + urls
@decorate_statement_view(StatementUnSubmitted)
def submit_view(self, request, statement):
if statement.submitted: # pragma: no cover
logger.error(f"submit_view reached with submitted statement {statement}. This should not happen.")
def submit_view(self, request, object_id):
statement = Statement.objects.get(pk=object_id)
if statement.submitted:
messages.error(request,
_("%(name)s is already submitted.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
@ -166,7 +89,7 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
messages.success(request,
_("Successfully submited %(name)s. The finance department will notify the requestors as soon as possible.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
if statement.excursion:
memberlist = statement.excursion
context = dict(self.admin_site.each_context(request),
@ -174,7 +97,8 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
opts=self.opts,
memberlist=memberlist,
object=memberlist,
ljp_contributions=memberlist.payable_ljp_contributions,
participant_count=memberlist.participant_count,
ljp_contributions=memberlist.potential_ljp_contributions,
total_relative_costs=memberlist.total_relative_costs,
**memberlist.statement.template_context())
return render(request, 'admin/freizeit_finance_overview.html', context=context)
@ -185,32 +109,97 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
statement=statement)
return render(request, 'admin/submit_statement.html', context=context)
@decorate_statement_view(StatementSubmitted)
def overview_view(self, request, statement):
if not statement.submitted: # pragma: no cover
logger.error(f"overview_view reached with unsubmitted statement {statement}. This should not happen.")
class TransactionOnSubmittedStatementInline(admin.TabularInline):
model = Transaction
fields = ['amount', 'member', 'reference', 'ledger']
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40})}
}
extra = 0
class BillOnSubmittedStatementInline(BillOnStatementInline):
model = BillOnStatementProxy
extra = 0
sortable_options = []
fields = ['short_description', 'explanation', 'amount', 'paid_by', 'proof', 'costs_covered']
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40})}
}
def get_readonly_fields(self, request, obj=None):
return ['short_description', 'explanation', 'amount', 'paid_by', 'proof']
@admin.register(StatementSubmitted)
class StatementSubmittedAdmin(admin.ModelAdmin):
fields = ['short_description', 'explanation', 'excursion', 'submitted']
list_display = ['__str__', 'is_valid', 'submitted_date', 'submitted_by']
ordering = ('-submitted_date',)
inlines = [BillOnSubmittedStatementInline, TransactionOnSubmittedStatementInline]
def has_add_permission(self, request, obj=None):
# Submitted statements should not be added directly, but instead be created
# as unsubmitted statements and then submitted.
return False
def has_change_permission(self, request, obj=None):
return request.user.has_perm('finance.process_statementsubmitted')
def has_delete_permission(self, request, obj=None):
# Submitted statements should not be deleted. Instead they can be rejected
# and then deleted as unsubmitted statements.
return False
def get_readonly_fields(self, request, obj=None):
readonly_fields = ['submitted']
if obj is not None and obj.submitted:
return readonly_fields + self.fields
else:
return readonly_fields
def get_urls(self):
urls = super().get_urls()
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
wrapper.model_admin = self
return update_wrapper(wrapper, view)
custom_urls = [
path(
"<path:object_id>/overview/",
wrap(self.overview_view),
name="%s_%s_overview" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/reduce_transactions/",
wrap(self.reduce_transactions_view),
name="%s_%s_reduce_transactions" % (self.opts.app_label, self.opts.model_name),
),
]
return custom_urls + urls
def overview_view(self, request, object_id):
statement = StatementSubmitted.objects.get(pk=object_id)
if not statement.submitted:
messages.error(request,
_("%(name)s is not yet submitted.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
if "transaction_execution_confirm" in request.POST or "transaction_execution_confirm_and_send" in request.POST:
if "transaction_execution_confirm" in request.POST:
res = statement.confirm(confirmer=get_member(request))
if not res: # pragma: no cover
if not res:
# this should NOT happen!
logger.error(f"Error occured while confirming {statement}, this should not be possible.")
messages.error(request,
_("An error occured while trying to confirm %(name)s. Please try again.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_overview' % (self.opts.app_label, self.opts.model_name)))
if "transaction_execution_confirm_and_send" in request.POST:
statement.send_summary(cc=[request.user.member.email] if hasattr(request.user, 'member') else [])
messages.success(request, _("Successfully sent receipt to the office."))
messages.success(request,
_("Successfully confirmed %(name)s. I hope you executed the associated transactions, I wont remind you again.")
% {'name': str(statement)})
download_link = reverse('admin:%s_%s_summary' % (self.opts.app_label, self.opts.model_name),
args=(statement.pk,))
messages.success(request,
mark_safe(_("You can download a <a href='%(link)s', target='_blank'>receipt</a>.") % {'link': download_link}))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
if "confirm" in request.POST:
res = statement.validity
@ -234,17 +223,14 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
messages.error(request,
_("The configured recipients for the allowance don't match the regulations. Please correct this on the excursion."))
return HttpResponseRedirect(reverse('admin:%s_%s_overview' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
elif res == Statement.INVALID_TOTAL: # pragma: no cover
logger.error(f"INVALID_TOTAL reached on {statement}.")
elif res == Statement.INVALID_TOTAL:
messages.error(request,
_("The calculated total amount does not match the sum of all transactions. This is most likely a bug."))
return HttpResponseRedirect(reverse('admin:%s_%s_overview' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
else: # pragma: no cover
logger.error(f"Statement.validity returned invalid value for {statement}.")
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
if "reject" in request.POST:
statement.status = Statement.UNSUBMITTED
statement.submitted = False
statement.save()
messages.success(request,
_("Successfully rejected %(name)s. The requestor can reapply, when needed.")
@ -268,28 +254,67 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
title=_('View submitted statement'),
opts=self.opts,
statement=statement,
settings=settings,
transaction_issues=statement.transaction_issues,
**statement.template_context())
return render(request, 'admin/overview_submitted_statement.html', context=context)
@decorate_statement_view(StatementSubmitted)
def reduce_transactions_view(self, request, statement):
def reduce_transactions_view(self, request, object_id):
statement = StatementSubmitted.objects.get(pk=object_id)
statement.reduce_transactions()
messages.success(request,
_("Successfully reduced transactions for %(name)s.") % {'name': str(statement)})
return HttpResponseRedirect(request.GET['redirectTo'])
#return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
@admin.register(StatementConfirmed)
class StatementConfirmedAdmin(admin.ModelAdmin):
fields = ['short_description', 'explanation', 'excursion', 'confirmed']
#readonly_fields = fields
list_display = ['__str__', 'total_pretty', 'confirmed_date', 'confirmed_by']
ordering = ('-confirmed_date',)
inlines = [BillOnSubmittedStatementInline, TransactionOnSubmittedStatementInline]
def has_add_permission(self, request, obj=None):
# To preserve integrity, no one is allowed to add confirmed statements
return False
def has_change_permission(self, request, obj=None):
# To preserve integrity, no one is allowed to change confirmed statements
return False
def has_delete_permission(self, request, obj=None):
# To preserve integrity, no one is allowed to delete confirmed statements
return False
def get_urls(self):
urls = super().get_urls()
@decorate_statement_view(StatementConfirmed, perm='finance.may_manage_confirmed_statements')
def unconfirm_view(self, request, statement):
if not statement.confirmed: # pragma: no cover
logger.error(f"unconfirm_view reached with unconfirmed statement {statement}.")
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
wrapper.model_admin = self
return update_wrapper(wrapper, view)
custom_urls = [
path(
"<path:object_id>/unconfirm/",
wrap(self.unconfirm_view),
name="%s_%s_unconfirm" % (self.opts.app_label, self.opts.model_name),
),
]
return custom_urls + urls
def unconfirm_view(self, request, object_id):
statement = StatementConfirmed.objects.get(pk=object_id)
if not statement.confirmed:
messages.error(request,
_("%(name)s is not yet confirmed.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
if "unconfirm" in request.POST:
statement.status = Statement.SUBMITTED
statement.confirmed = False
statement.confirmed_date = None
statement.confired_by = None
statement.save()
@ -306,56 +331,6 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
return render(request, 'admin/unconfirm_statement.html', context=context)
@decorate_statement_view(StatementConfirmed, perm='finance.may_manage_confirmed_statements')
def statement_summary_view(self, request, statement):
if not statement.confirmed: # pragma: no cover
logger.error(f"statement_summary_view reached with unconfirmed statement {statement}.")
messages.error(request,
_("%(name)s is not yet confirmed.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
excursion = statement.excursion
context = dict(statement=statement.template_context(), excursion=excursion, settings=settings)
pdf_filename = f"{excursion.code}_{excursion.name}_Zuschussbeleg" if excursion else f"Abrechnungsbeleg"
attachments = [bill.proof.path for bill in statement.bills_covered if bill.proof]
return render_tex_with_attachments(pdf_filename, 'finance/statement_summary.tex', context, attachments)
statement_summary_view.short_description = _('Download summary')
class TransactionOnSubmittedStatementInline(admin.TabularInline):
model = Transaction
fields = ['amount', 'member', 'reference', 'text_length_warning', 'ledger']
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40})}
}
readonly_fields = ['text_length_warning']
extra = 0
def text_length_warning(self, obj):
"""Display reference length, warn if exceeds 140 characters."""
len_reference = len(obj.reference)
len_string = f"{len_reference}/140"
if len_reference > 140:
return mark_safe(f'<span style="color: red;">{len_string}</span>')
return len_string
text_length_warning.short_description = _("Length")
class BillOnSubmittedStatementInline(BillOnStatementInline):
model = BillOnStatementProxy
extra = 0
sortable_options = []
fields = ['short_description', 'explanation', 'amount', 'paid_by', 'proof', 'costs_covered']
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40})}
}
def get_readonly_fields(self, request, obj=None):
return ['short_description', 'explanation', 'amount', 'paid_by', 'proof']
@admin.register(Transaction)
class TransactionAdmin(admin.ModelAdmin):
"""The transaction admin site. This is only used to display transactions. All editing

@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-10-16 23:09+0200\n"
"POT-Creation-Date: 2025-02-01 21:11+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@ -18,20 +18,12 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: finance/admin.py finance/tests/admin.py
msgid "Statement not found."
msgstr "Abrechnung nicht gefunden."
#: finance/admin.py finance/tests/admin.py
msgid "Insufficient permissions."
msgstr "Unzureichende Berechtigungen."
#: finance/admin.py
#, python-format
msgid "%(name)s is already submitted."
msgstr "%(name)s ist bereits eingereicht."
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
#, python-format
msgid ""
"Successfully submited %(name)s. The finance department will notify the "
@ -40,11 +32,11 @@ msgstr ""
"Rechnung %(name)s erfolgreich eingereicht. Das Finanzreferat wird auf dich "
"sobald wie möglich zukommen."
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
msgid "Finance overview"
msgstr "Kostenübersicht"
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
msgid "Submit statement"
msgstr "Rechnung einreichen"
@ -60,11 +52,7 @@ msgstr ""
"Beim Abwickeln von %(name)s ist ein Fehler aufgetreten. Bitte versuche es "
"erneut."
#: finance/admin.py finance/tests/admin.py
msgid "Successfully sent receipt to the office."
msgstr "Abrechnungsbeleg an die Geschäftsstelle gesendet."
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
#, python-format
msgid ""
"Successfully confirmed %(name)s. I hope you executed the associated "
@ -74,17 +62,10 @@ msgstr ""
"Überweisungen ausgeführt, ich werde dich nicht nochmal erinnern."
#: finance/admin.py
#, python-format
msgid "You can download a <a href='%(link)s', target='_blank'>receipt</a>."
msgstr ""
"Hier kannst du den Abrechnungsbeleg <a href='%(link)s', "
"target='_blank'>herunterladen</a>."
#: finance/admin.py finance/tests/admin.py
msgid "Statement confirmed"
msgstr "Abrechnung abgewickelt"
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
msgid ""
"Transactions do not match the covered expenses. Please correct the mistakes "
"listed below."
@ -92,12 +73,12 @@ msgstr ""
"Überweisungen stimmen nicht mit den übernommenen Kosten überein. Bitte "
"korrigiere die unten aufgeführten Fehler."
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
msgid "Some transactions have no ledger configured. Please fill in the gaps."
msgstr ""
"Manche Überweisungen haben kein Geldtopf eingestellt. Bitte trage das nach."
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
msgid ""
"The configured recipients for the allowance don't match the regulations. "
"Please correct this on the excursion."
@ -113,14 +94,14 @@ msgstr ""
"Der berechnete Gesamtbetrag stimmt nicht mit der Summe aller Überweisungen "
"überein. Das ist höchstwahrscheinlich ein Fehler in der Implementierung."
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
#, python-format
msgid "Successfully rejected %(name)s. The requestor can reapply, when needed."
msgstr ""
"Die Rechnung %(name)s wurde abgelehnt. Die Person kann die Rechnung erneut "
"einstellen, wenn es benötigt wird."
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
#, python-format
msgid ""
"%(name)s already has transactions. Please delete them first, if you want to "
@ -129,12 +110,12 @@ msgstr ""
"%(name)s hat bereits Überweisungen. Bitte lösche diese zunächst, bevor du "
"neue generierst."
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
#, python-format
msgid "Successfully generated transactions for %(name)s"
msgstr "Automatisch Überweisungsträger für %(name)s generiert."
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
#, python-format
msgid ""
"Error while generating transactions for %(name)s. Do all bills have a payer "
@ -146,11 +127,11 @@ msgstr ""
"einer Ausfahrt gehört, wurde eine Person als Empfänger*in der Übernachtungs- "
"und Fahrtkostenzuschüsse ausgewählt?"
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
msgid "View submitted statement"
msgstr "Eingereichte Abrechnung einsehen"
#: finance/admin.py finance/tests/admin.py
#: finance/admin.py
#, python-format
msgid "Successfully reduced transactions for %(name)s."
msgstr "Überweisungsträger für %(name)s minimiert."
@ -168,18 +149,9 @@ msgstr ""
"was du machst."
#: finance/admin.py finance/templates/admin/unconfirm_statement.html
#: finance/tests/admin.py
msgid "Unconfirm statement"
msgstr "Bestätigung zurücknehmen"
#: finance/admin.py
msgid "Download summary"
msgstr "Beleg herunterladen"
#: finance/admin.py
msgid "Length"
msgstr "Länge"
#: finance/apps.py
msgid "Finance"
msgstr "Finanzen"
@ -197,18 +169,6 @@ msgstr "Geldtopf"
msgid "Ledgers"
msgstr "Geldtöpfe"
#: finance/models.py
msgid "In preparation"
msgstr "In Vorbereitung"
#: finance/models.py
msgid "Submitted"
msgstr "Eingereicht"
#: finance/models.py
msgid "Completed"
msgstr "Abgewickelt"
#: finance/models.py
msgid "Short description"
msgstr "Kurzbeschreibung"
@ -243,30 +203,22 @@ msgstr ""
"Die Person, die die Übernachtungs- und Fahrtkostenzuschüsse erhalten soll. "
"Dies ist in der Regel die Person, die sie bezahlt hat."
#: finance/models.py
msgid "Pay ljp contributions to"
msgstr "LJP-Zuschüsse auszahlen an"
#: finance/models.py
msgid ""
"The person that should receive the ljp contributions for the participants. "
"Should be only selected if an ljp request was submitted."
msgstr ""
"Die Person, die die LJP-Zuschüsse für die Teilnehmenden erhalten soll. Nur "
"auswählen, wenn ein LJP-Antrag abgegeben wird."
#: finance/models.py
msgid "Price per night"
msgstr "Preis pro Nacht"
#: finance/models.py
msgid "Status"
msgstr "Status"
msgid "Submitted"
msgstr "Eingereicht"
#: finance/models.py
msgid "Submitted on"
msgstr "Eingereicht am"
#: finance/models.py
msgid "Confirmed"
msgstr "Abgewickelt"
#: finance/models.py
msgid "Paid on"
msgstr "Bezahlt am"
@ -293,8 +245,8 @@ msgstr "Abrechnungen"
#: finance/models.py
#, python-format
msgid "Excursion %(excursion)s"
msgstr "Ausfahrt %(excursion)s"
msgid "Statement: %(excursion)s"
msgstr "Abrechnung: %(excursion)s"
#: finance/models.py
msgid "Ready to confirm"
@ -310,24 +262,10 @@ msgstr "Aufwandsentschädigung für %(excu)s"
msgid "Night and travel costs for %(excu)s"
msgstr "Übernachtungs- und Fahrtkosten für %(excu)s"
#: finance/models.py finance/tests/models.py
msgid "reduced by org fee"
msgstr "reduziert um Org-Beitrag"
#: finance/models.py
#, python-format
msgid "LJP-Contribution %(excu)s"
msgstr "LJP-Zuschuss %(excu)s"
#: finance/models.py
#: finance/models.py finance/templates/admin/overview_submitted_statement.html
msgid "Total"
msgstr "Gesamtbetrag"
#: finance/models.py
#, python-format
msgid "Statement summary for %(title)s"
msgstr "Abrechnung für %(title)s"
#: finance/models.py
msgid "Statement in preparation"
msgstr "Abrechnung in Vorbereitung"
@ -451,12 +389,8 @@ msgid "I did execute the listed transactions."
msgstr "Ich habe die aufgeführten Überweisungen ausgeführt."
#: finance/templates/admin/confirmed_statement.html
msgid "Confirm only"
msgstr "Nur bestätigen"
#: finance/templates/admin/confirmed_statement.html
msgid "Confirm and send receipt to office"
msgstr "Bestätigen und Beleg an die Geschäftsstelle senden"
msgid "Confirm"
msgstr "Bestätigen"
#: finance/templates/admin/overview_submitted_statement.html
msgid "Overview"
@ -567,65 +501,6 @@ msgstr ""
"Keine Empfänger*innen für Sektionszuschüsse angegeben. Es werden daher keine "
"Sektionszuschüsse ausbezahlt."
#: finance/templates/admin/overview_submitted_statement.html
msgid "Org fee"
msgstr "Organisationsbeitrag"
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
"Since overaged people where part of the excursion, an organisational fee of "
"%(org_fee)s€ per person per day has to be paid. This totals to "
"%(total_org_fee_theoretical)s€. This organisational fee will be accounted "
"against allowances and subsidies."
msgstr ""
"Da Personen über 27 an der Ausfahrt teilnehommen haben, wird ein "
"Organisationsbeitrag von %(org_fee)s€ pro Person und Tag fällig. Der "
"Gesamtbetrag von %(total_org_fee_theoretical)s€ wird mit Zuschüssen und "
"Aufwandsentschädigungen verrechnet."
#: finance/templates/admin/overview_submitted_statement.html
msgid "LJP contributions"
msgstr "LJP-Zuschüsse"
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
" The youth leaders have documented interventions worth of "
"%(total_seminar_days)s seminar \n"
"days for %(participant_count)s eligible participants. Taking into account "
"the maximum contribution quota \n"
"of 90%% and possible taxes (%(ljp_tax)s%%), this results in a total of "
"%(paid_ljp_contributions)s€. \n"
"Once their proposal was approved, the ljp contributions of should be paid to:"
msgstr ""
"Jugendleiter*innen haben Lerneinheiten für insgesamt %(total_seminar_days)s "
"Seminartage und für %(participant_count)s Teilnehmende dokumentiert. Unter "
"Einbezug der maximalen Förderquote von 90%% und möglichen Steuern "
"(%(ljp_tax)s%%), ergibt sich ein auszuzahlender Betrag von "
"%(paid_ljp_contributions)s€. Sobald der LJP-Antrag geprüft ist, können LJP-"
"Zuschüsse ausbezahlt werden an:"
#: finance/templates/admin/overview_submitted_statement.html
msgid "Summary"
msgstr "Zusammenfassung"
#: finance/templates/admin/overview_submitted_statement.html
msgid "Covered bills"
msgstr "Übernommene Ausgaben"
#: finance/templates/admin/overview_submitted_statement.html
msgid "Allowance"
msgstr "Aufwandsentschädigung"
#: finance/templates/admin/overview_submitted_statement.html
msgid "Contributions by the association"
msgstr "Sektionszuschüsse"
#: finance/templates/admin/overview_submitted_statement.html
msgid "ljp contributions"
msgstr "LJP-Zuschüsse"
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid "This results in a total amount of %(total)s€"

@ -1,20 +0,0 @@
# Generated by Django 4.2.20 on 2025-04-03 21:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('members', '0039_membertraining_certificate_attendance'),
('finance', '0008_alter_statement_allowance_to_and_more'),
]
operations = [
migrations.AddField(
model_name='statement',
name='ljp_to',
field=models.ForeignKey(blank=True, help_text='The person that should receive the ljp contributions for the participants. Should be only selected if an ljp request was submitted.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='receives_ljp_for_statements', to='members.member', verbose_name='Pay ljp contributions to'),
),
]

@ -1,39 +0,0 @@
# Generated by Django 4.2.20 on 2025-10-11 15:43
from django.db import migrations, models
def set_status_from_old_fields(apps, schema_editor):
"""
Set the status field based on the existing submitted and confirmed fields.
- If confirmed is True, status = CONFIRMED (2)
- If submitted is True but confirmed is False, status = SUBMITTED (1)
- Otherwise, status = UNSUBMITTED (0)
"""
Statement = apps.get_model('finance', 'Statement')
UNSUBMITTED, SUBMITTED, CONFIRMED = 0, 1, 2
for statement in Statement.objects.all():
if statement.confirmed:
statement.status = CONFIRMED
elif statement.submitted:
statement.status = SUBMITTED
else:
statement.status = UNSUBMITTED
statement.save(update_fields=['status'])
class Migration(migrations.Migration):
dependencies = [
('finance', '0009_statement_ljp_to'),
]
operations = [
migrations.AddField(
model_name='statement',
name='status',
field=models.IntegerField(choices=[(0, 'In preparation'), (1, 'Submitted'), (2, 'Confirmed')], default=0, verbose_name='Status'),
),
migrations.RunPython(set_status_from_old_fields, reverse_code=migrations.RunPython.noop),
]

@ -1,21 +0,0 @@
# Generated by Django 4.2.20 on 2025-10-11 16:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('finance', '0010_statement_status'),
]
operations = [
migrations.RemoveField(
model_name='statement',
name='confirmed',
),
migrations.RemoveField(
model_name='statement',
name='submitted',
),
]

@ -1,28 +0,0 @@
# Generated by Django 4.2.20 on 2025-10-12 19:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('finance', '0011_remove_statement_confirmed_and_submitted'),
]
operations = [
migrations.CreateModel(
name='StatementOnExcursionProxy',
fields=[
],
options={
'verbose_name': 'Statement',
'verbose_name_plural': 'Statements',
'abstract': False,
'proxy': True,
'default_permissions': ('add_global', 'change_global', 'view_global', 'delete_global', 'list_global', 'view'),
'indexes': [],
'constraints': [],
},
bases=('finance.statement',),
),
]

@ -9,16 +9,12 @@ from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Sum
from django.utils.translation import gettext_lazy as _
from django.utils.html import format_html
from members.models import Member, Freizeit, OEFFENTLICHE_ANREISE, MUSKELKRAFT_ANREISE
from django.conf import settings
import rules
from contrib.models import CommonModel
from contrib.rules import has_global_perm
from utils import cvt_to_decimal, RestrictedFileField
from members.pdf import render_tex_with_attachments
from mailer.mailutils import send as send_mail
from contrib.media import media_path
from schwifty import IBAN
import re
@ -47,22 +43,15 @@ class TransactionIssue:
class StatementManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status=Statement.UNSUBMITTED)
return super().get_queryset().filter(submitted=False, confirmed=False)
class Statement(CommonModel):
MISSING_LEDGER, NON_MATCHING_TRANSACTIONS, INVALID_ALLOWANCE_TO, INVALID_TOTAL, VALID = 0, 1, 2, 3, 4
UNSUBMITTED, SUBMITTED, CONFIRMED = 0, 1, 2
STATUS_CHOICES = [(UNSUBMITTED, _('In preparation')),
(SUBMITTED, _('Submitted')),
(CONFIRMED, _('Completed'))]
STATUS_CSS_CLASS = { SUBMITTED: 'submitted',
CONFIRMED: 'confirmed',
UNSUBMITTED: 'unsubmitted' }
short_description = models.CharField(verbose_name=_('Short description'),
max_length=30,
blank=False)
blank=True)
explanation = models.TextField(verbose_name=_('Explanation'), blank=True)
excursion = models.OneToOneField(Freizeit, verbose_name=_('Associated excursion'),
@ -81,19 +70,11 @@ class Statement(CommonModel):
related_name='receives_subsidy_for_statements',
help_text=_('The person that should receive the subsidy for night and travel costs. Typically the person who paid for them.'))
ljp_to = models.ForeignKey(Member, verbose_name=_('Pay ljp contributions to'),
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='receives_ljp_for_statements',
help_text=_('The person that should receive the ljp contributions for the participants. Should be only selected if an ljp request was submitted.'))
night_cost = models.DecimalField(verbose_name=_('Price per night'), default=0, decimal_places=2, max_digits=5)
status = models.IntegerField(verbose_name=_('Status'),
choices=STATUS_CHOICES,
default=UNSUBMITTED)
submitted = models.BooleanField(verbose_name=_('Submitted'), default=False)
submitted_date = models.DateTimeField(verbose_name=_('Submitted on'), default=None, null=True)
confirmed = models.BooleanField(verbose_name=_('Confirmed'), default=False)
confirmed_date = models.DateTimeField(verbose_name=_('Paid on'), default=None, null=True)
created_by = models.ForeignKey(Member, verbose_name=_('Created by'),
@ -119,61 +100,28 @@ class Statement(CommonModel):
('may_edit_submitted_statements', 'Is allowed to edit submitted statements')
]
rules_permissions = {
# All users may add draft statements.
'add_obj': rules.is_staff,
# All users may view their own statements and statements of excursions they are responsible for.
'view_obj': is_creator | leads_excursion | has_global_perm('finance.view_global_statement'),
# All users may change relevant (see above) draft statements.
'change_obj': (not_submitted & (is_creator | leads_excursion)) | has_global_perm('finance.change_global_statement'),
# All users may delete relevant (see above) draft statements.
'delete_obj': not_submitted & (is_creator | leads_excursion | has_global_perm('finance.delete_global_statement')),
# this is suboptimal, but Statement is only ever used as an inline on Freizeit
# so we check for excursion permissions
'add_obj': is_leader,
'view_obj': is_leader | has_global_perm('members.view_global_freizeit'),
'change_obj': is_leader & statement_not_submitted,
'delete_obj': is_leader & statement_not_submitted,
}
@property
def title(self):
def __str__(self):
if self.excursion is not None:
return _('Excursion %(excursion)s') % {'excursion': str(self.excursion)}
return _('Statement: %(excursion)s') % {'excursion': str(self.excursion)}
else:
return self.short_description
def __str__(self):
return str(self.title)
@property
def submitted(self):
return self.status == Statement.SUBMITTED or self.status == Statement.CONFIRMED
@property
def confirmed(self):
return self.status == Statement.CONFIRMED
def status_badge(self):
code = Statement.STATUS_CSS_CLASS[self.status]
return format_html(f'<span class="statement-{code}">{Statement.STATUS_CHOICES[self.status][1]}</span>')
status_badge.short_description = _('Status')
status_badge.allow_tags = True
status_badge.admin_order_field = 'status'
def submit(self, submitter=None):
self.status = self.SUBMITTED
self.submitted = True
self.submitted_date = timezone.now()
self.submitted_by = submitter
self.save()
@property
def transaction_issues(self):
"""
Returns a list of critical problems with the currently configured transactions. This is done
by calculating a list of required paiments. From this list, we deduce the total amount
every member should receive (this amount can be negative, due to org fees).
Finally, the amounts are compared to the total amounts paid out by currently setup transactions.
The list of required paiments is generated from:
- All covered bills that have a configured payer.
(Note: This means that `transaction_issues` might return an empty list, but the calculated
total still differs from the transaction total.)
- If the statement is associated with an excursion: allowances, subsidies, LJP paiment and org fee.
"""
needed_paiments = [(b.paid_by, b.amount) for b in self.bill_set.all() if b.costs_covered and b.paid_by]
if self.excursion is not None:
@ -181,13 +129,6 @@ class Statement(CommonModel):
if self.subsidy_to:
needed_paiments.append((self.subsidy_to, self.total_subsidies))
# only include org fee if either allowance or subsidy is claimed (part of the property)
if self.total_org_fee:
needed_paiments.append((self.org_fee_payant, -self.total_org_fee))
if self.ljp_to:
needed_paiments.append((self.ljp_to, self.paid_ljp_contributions))
needed_paiments = sorted(needed_paiments, key=lambda p: p[0].pk)
target = dict(map(lambda p: (p[0], sum([x[1] for x in p[1]])), groupby(needed_paiments, lambda p: p[0])))
@ -218,7 +159,6 @@ class Statement(CommonModel):
@property
def transactions_match_expenses(self):
"""Returns true iff there are no transaction issues."""
return len(self.transaction_issues) == 0
@property
@ -236,11 +176,7 @@ class Statement(CommonModel):
@property
def total_valid(self):
"""
Checks if the calculated total agrees with the total amount of all transactions.
Note: This is not the same as `transactions_match_expenses`. For details see the
docstring of `transaction_issues`.
"""
"""Checks if the calculated total agrees with the total amount of all transactions."""
total_transactions = 0
for transaction in self.transaction_set.all():
total_transactions += transaction.amount
@ -248,19 +184,6 @@ class Statement(CommonModel):
@property
def validity(self):
"""
Returns the validity status of the statement. This is one of:
- `Statement.VALID`:
Everything is correct.
- `Statement.NON_MATCHING_TRANSACTIONS`:
There is a transaction issue (in the sense of `transaction_issues`).
- `Statement.MISSING_LEDGER`:
At least one transaction has no ledger configured.
- `Statement.INVALID_ALLOWANCE_TO`:
The members receiving allowance don't match the regulations.
- `Statement.INVALID_TOTAL`:
The total amount of transactions differs from the calculated total payout.
"""
if not self.transactions_match_expenses:
return Statement.NON_MATCHING_TRANSACTIONS
if not self.ledgers_configured:
@ -284,7 +207,7 @@ class Statement(CommonModel):
if not self.validity == Statement.VALID:
return False
self.status = self.CONFIRMED
self.confirmed = True
self.confirmed_date = timezone.now()
self.confirmed_by = confirmer
for trans in self.transaction_set.all():
@ -318,17 +241,7 @@ class Statement(CommonModel):
if self.subsidy_to:
ref = _("Night and travel costs for %(excu)s") % {'excu': self.excursion.name}
Transaction(statement=self, member=self.subsidy_to, amount=self.total_subsidies, confirmed=False, reference=ref).save()
if self.total_org_fee:
# if no subsidy receiver is given but org fees have to be paid. Just pick one of allowance receivers
ref = _("reduced by org fee")
Transaction(statement=self, member=self.org_fee_payant, amount=-self.total_org_fee, confirmed=False, reference=ref).save()
if self.ljp_to:
ref = _("LJP-Contribution %(excu)s") % {'excu': self.excursion.name}
Transaction(statement=self, member=self.ljp_to, amount=self.paid_ljp_contributions,
confirmed=False, reference=ref).save()
return True
def reduce_transactions(self):
@ -348,7 +261,7 @@ class Statement(CommonModel):
continue
new_amount = sum((trans.amount for trans in grp))
new_ref = ", ".join((f"{trans.reference} EUR{trans.amount: .2f}" for trans in grp))
new_ref = "\n".join((trans.reference for trans in grp))
Transaction(statement=self, member=member, amount=new_amount, confirmed=False, reference=new_ref,
ledger=ledger).save()
for trans in grp:
@ -356,27 +269,12 @@ class Statement(CommonModel):
@property
def total_bills(self):
return sum([bill.amount for bill in self.bills_covered])
@property
def bills_covered(self):
"""Returns the bills that are marked for reimbursement by the finance officer"""
return [bill for bill in self.bill_set.all() if bill.costs_covered]
return sum([bill.amount for bill in self.bill_set.all() if bill.costs_covered])
@property
def bills_without_proof(self):
"""Returns the bills that lack a proof file"""
return [bill for bill in self.bill_set.all() if not bill.proof]
@property
def total_bills_theoretic(self):
return sum([bill.amount for bill in self.bill_set.all()])
@property
def total_bills_not_covered(self):
"""Returns the sum of bills that are not marked for reimbursement by the finance officer"""
return sum([bill.amount for bill in self.bill_set.all()]) - self.total_bills
@property
def euro_per_km(self):
if self.excursion is None:
@ -442,26 +340,6 @@ class Statement(CommonModel):
return cvt_to_decimal(self.total_staff / self.excursion.staff_count)
@property
def total_org_fee_theoretical(self):
"""participants older than 26.99 years need to pay a specified organisation fee per person per day."""
if self.excursion is None:
return 0
return cvt_to_decimal(settings.EXCURSION_ORG_FEE * self.excursion.duration * self.excursion.old_participant_count)
@property
def total_org_fee(self):
"""only calculate org fee if subsidies or allowances are claimed."""
if self.subsidy_to or self.allowances_paid > 0:
return self.total_org_fee_theoretical
return cvt_to_decimal(0)
@property
def org_fee_payant(self):
if self.total_org_fee == 0:
return None
return self.subsidy_to if self.subsidy_to else self.allowance_to.all()[0]
@property
def total_subsidies(self):
"""
@ -473,10 +351,6 @@ class Statement(CommonModel):
else:
return cvt_to_decimal(0)
@property
def subsidies_paid(self):
return self.total_subsidies - self.total_org_fee
@property
def theoretical_total_staff(self):
"""
@ -491,11 +365,6 @@ class Statement(CommonModel):
"""
return self.total_allowance + self.total_subsidies
@property
def total_staff_paid(self):
return self.total_staff - self.total_org_fee
@property
def real_staff_count(self):
if self.excursion is None:
@ -511,30 +380,10 @@ class Statement(CommonModel):
return 0
else:
return self.excursion.approved_staff_count
@property
def paid_ljp_contributions(self):
if hasattr(self.excursion, 'ljpproposal') and self.ljp_to:
if self.excursion.theoretic_ljp_participant_count < 5:
return 0
return cvt_to_decimal(
min(
# if total costs are more than the max amount of the LJP contribution, we pay the max amount, reduced by taxes
(1-settings.LJP_TAX) * settings.LJP_CONTRIBUTION_PER_DAY * self.excursion.ljp_participant_count * self.excursion.ljp_duration,
# if the total costs are less than the max amount, we pay up to 90% of the total costs, reduced by taxes
(1-settings.LJP_TAX) * 0.9 * (float(self.total_bills_not_covered) + float(self.total_staff) ),
# we never pay more than the maximum costs of the trip
float(self.total_bills_not_covered)
)
)
else:
return 0
@property
def total(self):
return self.total_bills + self.total_staff_paid + self.paid_ljp_contributions
return self.total_bills + self.total_staff
@property
def total_theoretic(self):
@ -549,13 +398,11 @@ class Statement(CommonModel):
def total_pretty(self):
return "{}".format(self.total)
total_pretty.short_description = _('Total')
total_pretty.admin_order_field = 'total'
def template_context(self):
context = {
'total_bills': self.total_bills,
'total_bills_theoretic': self.total_bills_theoretic,
'bills_covered': self.bills_covered,
'total': self.total,
}
if self.excursion:
@ -571,28 +418,12 @@ class Statement(CommonModel):
'allowances_paid': self.allowances_paid,
'nights_per_yl': self.nights_per_yl,
'allowance_per_yl': self.allowance_per_yl,
'total_allowance': self.total_allowance,
'transportation_per_yl': self.transportation_per_yl,
'total_per_yl': self.total_per_yl,
'total_staff': self.total_staff,
'total_allowance': self.total_allowance,
'theoretical_total_staff': self.theoretical_total_staff,
'real_staff_count': self.real_staff_count,
'total_subsidies': self.total_subsidies,
'total_allowance': self.total_allowance,
'subsidy_to': self.subsidy_to,
'allowance_to': self.allowance_to,
'paid_ljp_contributions': self.paid_ljp_contributions,
'ljp_to': self.ljp_to,
'theoretic_ljp_participant_count': self.excursion.theoretic_ljp_participant_count,
'participant_count': self.excursion.participant_count,
'total_seminar_days': self.excursion.total_seminar_days,
'ljp_tax': settings.LJP_TAX * 100,
'total_org_fee_theoretical': self.total_org_fee_theoretical,
'total_org_fee': self.total_org_fee,
'old_participant_count': self.excursion.old_participant_count,
'total_staff_paid': self.total_staff_paid,
'org_fee': cvt_to_decimal(settings.EXCURSION_ORG_FEE),
}
return dict(context, **excursion_context)
else:
@ -603,41 +434,10 @@ class Statement(CommonModel):
.order_by('short_description')\
.annotate(amount=Sum('amount'))
def send_summary(self, cc=None):
"""
Sends a summary of the statement to the central office of the association.
"""
excursion = self.excursion
context = dict(statement=self.template_context(), excursion=excursion, settings=settings)
pdf_filename = f"{excursion.code}_{excursion.name}_Zuschussbeleg" if excursion else f"Abrechnungsbeleg"
attachments = [bill.proof.path for bill in self.bills_covered if bill.proof]
filename = render_tex_with_attachments(pdf_filename, 'finance/statement_summary.tex',
context, attachments, save_only=True)
send_mail(_('Statement summary for %(title)s') % { 'title': self.title },
settings.SEND_STATEMENT_SUMMARY.format(statement=self.title),
sender=settings.DEFAULT_SENDING_MAIL,
recipients=[settings.SEKTION_FINANCE_MAIL],
cc=cc,
attachments=[media_path(filename)])
class StatementOnExcursionProxy(Statement):
class Meta(CommonModel.Meta):
proxy = True
verbose_name = _('Statement')
verbose_name_plural = _('Statements')
rules_permissions = {
# This is used as an inline on excursions, so we check for excursion permissions.
'add_obj': is_leader,
'view_obj': is_leader | has_global_perm('members.view_global_freizeit'),
'change_obj': is_leader & statement_not_submitted,
'delete_obj': is_leader & statement_not_submitted,
}
class StatementUnSubmittedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status=Statement.UNSUBMITTED)
return super().get_queryset().filter(submitted=False, confirmed=False)
class StatementUnSubmitted(Statement):
@ -657,7 +457,7 @@ class StatementUnSubmitted(Statement):
class StatementSubmittedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status=Statement.SUBMITTED)
return super().get_queryset().filter(submitted=True, confirmed=False)
class StatementSubmitted(Statement):
@ -674,7 +474,7 @@ class StatementSubmitted(Statement):
class StatementConfirmedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status=Statement.CONFIRMED)
return super().get_queryset().filter(confirmed=True)
class StatementConfirmed(Statement):
@ -691,7 +491,7 @@ class StatementConfirmed(Statement):
class Bill(CommonModel):
statement = models.ForeignKey(Statement, verbose_name=_('Statement'), on_delete=models.CASCADE)
short_description = models.CharField(verbose_name=_('Short description'), max_length=30, blank=False)
short_description = models.CharField(verbose_name=_('Short description'), max_length=30)
explanation = models.TextField(verbose_name=_('Explanation'), blank=True)
amount = models.DecimalField(verbose_name=_('Amount'), max_digits=6, decimal_places=2, default=0)

@ -110,7 +110,6 @@ links.forEach(link => {
<input type="checkbox" required>
{% blocktrans %}I did execute the listed transactions.{% endblocktrans %}
</p>
<input class="default confirm" type="submit" name="transaction_execution_confirm" value="{% translate 'Confirm only' %}">
<input class="default confirm" type="submit" name="transaction_execution_confirm_and_send" value="{% translate 'Confirm and send receipt to office' %}">
<input class="default confirm" type="submit" name="transaction_execution_confirm" value="{% translate 'Confirm' %}">
</form>
{% endblock %}

@ -109,86 +109,13 @@
</tr>
</table>
</p>
{% else %}
<p>{% blocktrans %}No receivers of the subsidies were provided. Subsidies will not be used.{% endblocktrans %}</p>
{% endif %}
{% if total_org_fee %}
<h3>{% trans "Org fee" %}</h3>
{% blocktrans %}Since overaged people where part of the excursion, an organisational fee of {{ org_fee }}€ per person per day has to be paid. This totals to {{ total_org_fee_theoretical }}€. This organisational fee will be accounted against allowances and subsidies.{% endblocktrans %}
{% endif %}
{% if statement.ljp_to %}
<h3>{% trans "LJP contributions" %}</h3>
<p>
{% blocktrans %} The youth leaders have documented interventions worth of {{ total_seminar_days }} seminar
days for {{ participant_count }} eligible participants. Taking into account the maximum contribution quota
of 90% and possible taxes ({{ ljp_tax }}%), this results in a total of {{ paid_ljp_contributions }}€.
Once their proposal was approved, the ljp contributions of should be paid to:{% endblocktrans %}
<table>
<th>
<td>{% trans "IBAN valid" %}</td>
</th>
<tr>
<td>{{ statement.ljp_to.name }}</td>
<td>{{ statement.ljp_to.iban_valid|render_bool }}</td>
</tr>
</table>
</p>
{% endif %}
{% endif %}
<h2>{% trans "Summary" %}</h2>
<table>
<tr>
<td>
{% trans "Covered bills" %}
</td>
<td>
{{ total_bills }}€
</td>
</tr>
<tr>
<td>
{% trans "Allowance" %}
</td>
<td>
{{ total_allowance }}€
</td>
</tr>
<tr>
<td>
{% trans "Contributions by the association" %}
</td>
<td>
{{ total_subsidies }}€
</td>
</tr>
<tr>
<td>
{% trans "Org fee" %}
</td>
<td>
-{{ total_org_fee }}€
</td>
</tr>
<tr>
<td>
{% trans "ljp contributions" %}
</td>
<td>
{{ paid_ljp_contributions }}€
</td>
</tr>
</table>
<h2>{% trans "Total" %}</h2>
<p>
{% blocktrans %}This results in a total amount of {{ total }}€{% endblocktrans %}

@ -1,146 +0,0 @@
{% extends "members/tex_base.tex" %}
{% load static common tex_extras %}
{% block title %}Abrechnungs- und Zuschussbeleg\\[2mm]Sektionsveranstaltung{% endblock %}
{% block content %}
{% if excursion %}
\noindent\textbf{\large Ausfahrt}
% DESCRIPTION TABLE
\begin{table}[H]
\begin{tabular}{ll}
Aktivität: & {{ excursion.name|esc_all }} \\
Ordnungsnummer & {{ excursion.code|esc_all }} \\
Ort / Stützpunkt: & {{ excursion.place|esc_all }} \\
Zeitraum: & {{ excursion.duration|esc_all}} Tage ({{ excursion.time_period_str|esc_all }}) \\
Teilnehmer*innen: & {{ excursion.participant_count }} der Gruppe(n) {{ excursion.groups_str|esc_all }} \\
Betreuer*innen: & {{excursion.staff_count|esc_all }} ({{ excursion.staff_str|esc_all }}) \\
Art der Tour: & {% checked_if_true 'Gemeinschaftstour' excursion.get_tour_type %}
{% checked_if_true 'Führungstour' excursion.get_tour_type %}
{% checked_if_true 'Ausbildung' excursion.get_tour_type %} \\
Anreise: & {% checked_if_true 'ÖPNV' excursion.get_tour_approach %}
{% checked_if_true 'Muskelkraft' excursion.get_tour_approach %}
{% checked_if_true 'Fahrgemeinschaften' excursion.get_tour_approach %}
\end{tabular}
\end{table}
\noindent\textbf{\large Zuschüsse und Aufwandsentschädigung}
{% if excursion.approved_staff_count > 0 %}
\noindent Gemäß Beschluss des Jugendausschusses gelten folgende Sätze für Zuschüsse pro genehmigter Jugendleiter*in:
\begin{table}[H]
\centering
\begin{tabularx}{.97\textwidth}{Xllr}
\toprule
\textbf{Posten} & \textbf{Einzelsatz} & \textbf{Anzahl} & \textbf{Gesamtbetrag pro JL} \\
\midrule
Zuschuss Übernachtung & {{ statement.price_per_night }} € / Nacht & {{ statement.nights }} Nächte & {{ statement.nights_per_yl }}\\
Zuschuss Anreise & {{statement.euro_per_km}} € / km ({{ statement.means_of_transport }}) & {{ statement.kilometers_traveled }} km & {{ statement.transportation_per_yl }}\\
Aufwandsentschädigung & {{ statement.allowance_per_day }},00 € / Tag & {{ statement.duration }} Tage & {{ statement.allowance_per_yl }}\\
\midrule
\textbf{Summe}& & & \textbf{ {{ statement.total_per_yl }} }\\
\bottomrule
\end{tabularx}
\end{table}
\noindent Gemäß JDAV-Betreuungsschlüssel können bei {{ excursion.participant_count }} Teilnehmer*innen
bis zu {{ excursion.approved_staff_count }} Jugendleiter*innen {% if excursion.approved_extra_youth_leader_count %}
(davon {{ excursion.approved_extra_youth_leader_count }} durch das Jugendreferat zusätzlich genehmigt){% endif %} bezuschusst werden.
Zuschüsse und Aufwandsentschädigung werden wie folgt abgerufen:
\begin{itemize}
{% if statement.allowances_paid > 0 %}
\item Eine Aufwandsentschädigung von {{ statement.allowance_per_yl }} € pro Jugendleiter*in wird überwiesen an:
{% for m in statement.allowance_to.all %}{% if forloop.counter > 1 %}, {% endif %}{{ m.name }}{% endfor %}
{% else %}
\item Keiner*r der Jugendleiter*innen nimmt eine Aufwandsentschädigung in Anspruch.
{% endif %}
{% if statement.subsidy_to %}
\item Der Zuschuss zu Übernachtung und Anreise für alle Jugendleiter*innen in Höhe von {{ statement.total_subsidies }} € wird überwiesen an:
{{ statement.subsidy_to.name }}
{% else %}
\item Zuschüsse zu Übernachtung und Anreise werden nicht in Anspruch genommen.
{% endif %}
\end{itemize}
{% else %}
\noindent Für die vorliegende Ausfahrt sind keine Jugendleiter*innen anspruchsberechtigt für Zuschüsse oder Aufwandsentschädigung.
{% endif %}
{% if statement.ljp_to %}
\noindent\textbf{LJP-Zuschüsse}
\noindent Der LJP-Zuschuss für die Teilnehmenden in Höhe von {{ statement.paid_ljp_contributions|esc_all }} € wird überwiesen an:
{{ statement.ljp_to.name|esc_all }} Dieser Zuschuss wird aus Landesmitteln gewährt und ist daher
in der Ausgabenübersicht gesondert aufgeführt.
{% endif %}
{% if statement.total_org_fee %}
\noindent\textbf{Organisationsbeitrag}
\noindent An der Ausfahrt haben {{ statement.old_participant_count }} Personen teilgenommen, die 27 Jahre alt oder älter sind. Für sie wird pro Tag ein Organisationsbeitrag von {{ statement.org_fee }} € erhoben und mit den bezahlten Zuschüssen und Aufwandsentschädigungen verrechnet.
{% endif %}
{% else %}
\vspace{110pt}
{% endif %}
\vspace{12pt}
\noindent\textbf{\large Ausgabenübersicht}
\nopagebreak
\begin{table}[H]
\centering
\begin{tabularx}{.97\textwidth}{lXlr}
\toprule
\textbf{Titel} & \textbf{Beschreibung} & \textbf{Auszahlung an} & \textbf{Betrag} \\
\midrule
{% if statement.bills_covered %}
{% for bill in statement.bills_covered %}
{{ forloop.counter }}. {{ bill.short_description}} & {{ bill.explanation}} & {{ bill.paid_by.name|esc_all }} & {{ bill.amount }}\\
{% endfor %}
\midrule
\multicolumn{3}{l}{\textbf{Summe übernommene Ausgaben}} & \textbf{ {{ statement.total_bills }} }\\
{% endif %}
{% if excursion.approved_staff_count > 0 and statement.allowances_paid > 0 or excursion.approved_staff_count > 0 and statement.subsidy_to %}
\midrule
{% if statement.allowances_paid > 0 %}
{% for m in statement.allowance_to.all %}
Aufwandsentschädigung & & {{ m.name|esc_all }} & {{ statement.allowance_per_yl }}\\
{% endfor %}
{% endif %}
{% if statement.subsidy_to %}
\multicolumn{2}{l}{Zuschuss Übernachtung und Anreise für alle Jugendleiter*innen} & {{ statement.subsidy_to.name|esc_all }} & {{ statement.total_subsidies }}\\
{% endif %}
{% if statement.total_org_fee %}
\multicolumn{2}{l}{abzüglich Organisationsbeitrag für {{ statement.old_participant_count }} Teilnehmende über 27 } & & -{{ statement.total_org_fee }}\\
{% endif %}
\midrule
\multicolumn{3}{l}{\textbf{Summe Zuschüsse und Aufwandsentschädigung Jugendleitende}} & \textbf{ {{ statement.total_staff_paid }} }\\
{%endif %}
{% if statement.ljp_to %}
\midrule
LJP-Zuschuss für die Teilnehmenden && {{ statement.ljp_to.name|esc_all }} & {{ statement.paid_ljp_contributions|esc_all }}\\
{% endif %}
{% if statement.ljp_to or statement.bills_covered and excursion.approved_staff_count > 0 %}
\midrule
\textbf{Gesamtsumme}& & & \textbf{ {{ statement.total }} }\\
{% endif %}
\bottomrule
\end{tabularx}
\end{table}
\noindent Dieser Beleg wird automatisch erstellt und daher nicht unterschrieben.
{% endblock %}

@ -2,15 +2,11 @@ from unittest import skip
from django.test import TestCase
from django.utils import timezone
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from decimal import Decimal
from finance.models import Statement, StatementUnSubmitted, StatementSubmitted, Bill, Ledger, Transaction,\
from .models import Statement, StatementUnSubmitted, StatementSubmitted, Bill, Ledger, Transaction,\
StatementUnSubmittedManager, StatementSubmittedManager, StatementConfirmedManager,\
StatementConfirmed, TransactionIssue, StatementManager
from members.models import Member, Group, Freizeit, LJPProposal, Intervention, GEMEINSCHAFTS_TOUR, MUSKELKRAFT_ANREISE, NewMemberOnList,\
from members.models import Member, Group, Freizeit, GEMEINSCHAFTS_TOUR, MUSKELKRAFT_ANREISE, NewMemberOnList,\
FAHRGEMEINSCHAFT_ANREISE, MALE, FEMALE, DIVERSE
from dateutil.relativedelta import relativedelta
from utils import get_member
# Create your tests here.
class StatementTestCase(TestCase):
@ -60,152 +56,17 @@ class StatementTestCase(TestCase):
if i < self.allowance_to_count:
self.st3.allowance_to.add(m)
# Create a small excursion with < 5 theoretic LJP participants for LJP contribution test
small_ex = Freizeit.objects.create(name='Small trip', kilometers_traveled=100,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=1)
# Add only 3 participants (< 5 for theoretic_ljp_participant_count)
for i in range(3):
# Create young participants (< 6 years old) so they don't count toward LJP
birth_date = timezone.now().date() - relativedelta(years=4)
m = Member.objects.create(prename='Small {}'.format(i), lastname='Participant',
birth_date=birth_date,
email=settings.TEST_MAIL, gender=MALE)
NewMemberOnList.objects.create(member=m, memberlist=small_ex)
# Create LJP proposal for the small excursion
ljp_proposal = LJPProposal.objects.create(title='Small LJP', category=LJPProposal.LJP_STAFF_TRAINING)
small_ex.ljpproposal = ljp_proposal
small_ex.save()
self.st_small = Statement.objects.create(night_cost=10, excursion=small_ex)
ex = Freizeit.objects.create(name='Wild trip 2', kilometers_traveled=self.kilometers_traveled,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=2)
self.st4 = Statement.objects.create(night_cost=self.night_cost, excursion=ex, subsidy_to=self.fritz)
for i in range(2):
m = Member.objects.create(prename='Peter {}'.format(i), lastname='Walter',
birth_date=timezone.now().date() - relativedelta(years=30),
email=settings.TEST_MAIL, gender=DIVERSE)
mol = NewMemberOnList.objects.create(member=m, memberlist=ex)
ex.membersonlist.add(mol)
base = timezone.now()
ex = Freizeit.objects.create(name='Wild trip with old people', kilometers_traveled=self.kilometers_traveled,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=2, date=timezone.datetime(2024, 1, 2, 8, 0, 0, tzinfo=base.tzinfo), end=timezone.datetime(2024, 1, 5, 17, 0, 0, tzinfo=base.tzinfo) )
settings.EXCURSION_ORG_FEE = 20
settings.LJP_TAX = 0.2
settings.LJP_CONTRIBUTION_PER_DAY = 20
self.st5 = Statement.objects.create(night_cost=self.night_cost, excursion=ex)
for i in range(9):
m = Member.objects.create(prename='Peter {}'.format(i), lastname='Walter', birth_date=timezone.now().date() - relativedelta(years=i+21),
m = Member.objects.create(prename='Peter {}'.format(i), lastname='Walter', birth_date=timezone.now().date(),
email=settings.TEST_MAIL, gender=DIVERSE)
mol = NewMemberOnList.objects.create(member=m, memberlist=ex)
ex.membersonlist.add(mol)
ljpproposal = LJPProposal.objects.create(
title='Test proposal',
category=LJPProposal.LJP_STAFF_TRAINING,
goal=LJPProposal.LJP_ENVIRONMENT,
goal_strategy='my strategy',
not_bw_reason=LJPProposal.NOT_BW_ROOMS,
excursion=self.st5.excursion)
for i in range(3):
int = Intervention.objects.create(
date_start=timezone.datetime(2024, 1, 2+i, 12, 0, 0, tzinfo=base.tzinfo),
duration = 2+i,
activity = 'hi',
ljp_proposal=ljpproposal
)
self.b1 = Bill.objects.create(
statement=self.st5,
short_description='covered bill',
explanation='hi',
amount='300',
paid_by=self.fritz,
costs_covered=True,
refunded=False
)
self.b2 = Bill.objects.create(
statement=self.st5,
short_description='non-covered bill',
explanation='hi',
amount='900',
paid_by=self.fritz,
costs_covered=False,
refunded=False
)
self.st6 = Statement.objects.create(night_cost=self.night_cost)
Bill.objects.create(statement=self.st6, amount='42', costs_covered=True)
def test_org_fee(self):
# org fee should be collected if participants are older than 26
self.assertEqual(self.st5.excursion.old_participant_count, 3, 'Calculation of number of old people in excursion is incorrect.')
total_org = 4 * 3 * 20 # 4 days, 3 old people, 20€ per day
self.assertEqual(self.st5.total_org_fee_theoretical, total_org, 'Theoretical org_fee should equal to amount per day per person * n_persons * n_days if there are old people.')
self.assertEqual(self.st5.total_org_fee, 0, 'Paid org fee should be 0 if no allowance and subsidies are paid if there are old people.')
self.assertIsNone(self.st5.org_fee_payant)
# now collect subsidies
self.st5.subsidy_to = self.fritz
self.assertEqual(self.st5.total_org_fee, total_org, 'Paid org fee should equal to amount per day per person * n_persons * n_days if subsidies are paid.')
# now collect allowances
self.st5.allowance_to.add(self.fritz)
self.st5.subsidy_to = None
self.assertEqual(self.st5.total_org_fee, total_org, 'Paid org fee should equal to amount per day per person * n_persons * n_days if allowances are paid.')
# now collect both
self.st5.subsidy_to = self.fritz
self.assertEqual(self.st5.total_org_fee, total_org, 'Paid org fee should equal to amount per day per person * n_persons * n_days if subsidies and allowances are paid.')
self.assertEqual(self.st5.org_fee_payant, self.fritz, 'Org fee payant should be the receiver allowances and subsidies.')
# return to previous state
self.st5.subsidy_to = None
self.st5.allowance_to.remove(self.fritz)
def test_ljp_payment(self):
expected_intervention_hours = 2 + 3 + 4
expected_seminar_days = 0 + 0.5 + 0.5 # >=2.5h = 0.5days, >=5h = 1.0day
expected_ljp = (1-settings.LJP_TAX) * expected_seminar_days * settings.LJP_CONTRIBUTION_PER_DAY * 9
# (1 - 20% tax) * 1 seminar day * 20€ * 9 participants
self.assertEqual(self.st5.excursion.total_intervention_hours, expected_intervention_hours, 'Calculation of total intervention hours is incorrect.')
self.assertEqual(self.st5.excursion.total_seminar_days, expected_seminar_days, 'Calculation of total seminar days is incorrect.')
self.assertEqual(self.st5.paid_ljp_contributions, 0, 'No LJP contributions should be paid if no receiver is set.')
# now we want to pay out the LJP contributions
self.st5.ljp_to = self.fritz
self.assertEqual(self.st5.paid_ljp_contributions, expected_ljp, 'LJP contributions should be paid if a receiver is set.')
# now the total costs paid by trip organisers is lower than expected ljp contributions, should be reduced automatically
self.b2.amount=100
self.b2.save()
self.assertEqual(self.st5.total_bills_not_covered, 100, 'Changes in bills should be reflected in the total costs paid by trip organisers')
self.assertGreaterEqual(self.st5.total_bills_not_covered, self.st5.paid_ljp_contributions, 'LJP contributions should be less than or equal to the costs paid by trip organisers')
self.st5.ljp_to = None
def test_staff_count(self):
self.assertEqual(self.st4.admissible_staff_count, 0,
'Admissible staff count is not 0, although not enough participants.')
@ -399,103 +260,6 @@ class StatementTestCase(TestCase):
bills = self.st2.grouped_bills()
self.assertTrue('amount' in bills[0])
def test_euro_per_km_no_excursion(self):
"""Test euro_per_km when no excursion is associated"""
statement = Statement.objects.create(
short_description="Test Statement",
explanation="Test explanation",
night_cost=25
)
self.assertEqual(statement.euro_per_km, 0)
def test_submit_workflow(self):
"""Test statement submission workflow"""
statement = Statement.objects.create(
short_description="Test Statement",
explanation="Test explanation",
night_cost=25,
created_by=self.fritz
)
self.assertFalse(statement.submitted)
self.assertIsNone(statement.submitted_by)
self.assertIsNone(statement.submitted_date)
# Test submission - submit method doesn't return a value, just changes state
statement.submit(submitter=self.fritz)
self.assertTrue(statement.submitted)
self.assertEqual(statement.submitted_by, self.fritz)
self.assertIsNotNone(statement.submitted_date)
def test_template_context_with_excursion(self):
"""Test statement template context when excursion is present"""
# Use existing excursion from setUp
context = self.st3.template_context()
self.assertIn('euro_per_km', context)
self.assertIsInstance(context['euro_per_km'], (int, float, Decimal))
def test_title_with_excursion(self):
title = self.st3.title
self.assertIn('Wild trip', title)
def test_transaction_issues_with_org_fee(self):
issues = self.st4.transaction_issues
self.assertIsInstance(issues, list)
def test_transaction_issues_with_ljp(self):
self.st3.ljp_to = self.fritz
self.st3.save()
issues = self.st3.transaction_issues
self.assertIsInstance(issues, list)
def test_generate_transactions_org_fee(self):
# Ensure conditions for org fee are met: need subsidy_to or allowances
# and participants >= 27 years old
self.st4.subsidy_to = self.fritz
self.st4.save()
# Verify org fee is calculated
self.assertGreater(self.st4.total_org_fee, 0, "Org fee should be > 0 with subsidies and old participants")
initial_count = Transaction.objects.count()
self.st4.generate_transactions()
final_count = Transaction.objects.count()
self.assertGreater(final_count, initial_count)
org_fee_transaction = Transaction.objects.filter(statement=self.st4,
reference__icontains=_('reduced by org fee')).first()
self.assertIsNotNone(org_fee_transaction)
def test_generate_transactions_ljp(self):
self.st3.ljp_to = self.fritz
self.st3.save()
initial_count = Transaction.objects.count()
self.st3.generate_transactions()
final_count = Transaction.objects.count()
self.assertGreater(final_count, initial_count)
ljp_transaction = Transaction.objects.filter(statement=self.st3, member=self.fritz, reference__icontains='LJP').first()
self.assertIsNotNone(ljp_transaction)
def test_subsidies_paid_property(self):
subsidies_paid = self.st3.subsidies_paid
expected = self.st3.total_subsidies - self.st3.total_org_fee
self.assertEqual(subsidies_paid, expected)
def test_ljp_contributions_low_participant_count(self):
self.st_small.ljp_to = self.fritz
self.st_small.save()
# Verify that the small excursion has < 5 theoretic LJP participants
self.assertLess(self.st_small.excursion.theoretic_ljp_participant_count, 5,
"Should have < 5 theoretic LJP participants")
ljp_contrib = self.st_small.paid_ljp_contributions
self.assertEqual(ljp_contrib, 0)
def test_validity_paid_by_none(self):
# st6 has one covered bill with no payer, so no transaction issues,
# but total transaction amount (= 0) differs from actual total (> 0).
self.assertEqual(self.st6.validity, Statement.INVALID_TOTAL)
class LedgerTestCase(TestCase):
def setUp(self):
@ -513,11 +277,11 @@ class ManagerTestCase(TestCase):
self.st_submitted = Statement.objects.create(short_description='A statement',
explanation='Important!',
night_cost=0,
status=Statement.SUBMITTED)
submitted=True)
self.st_confirmed = Statement.objects.create(short_description='A statement',
explanation='Important!',
night_cost=0,
status=Statement.CONFIRMED)
confirmed=True)
def test_get_queryset(self):
# TODO: remove this manager, since it is not used
@ -556,20 +320,9 @@ class TransactionTestCase(TestCase):
self.assertTrue(str(self.trans.pk) in str(self.trans))
def test_escape_reference(self):
"""Test transaction reference escaping with various special characters"""
test_cases = [
('harmless', 'harmless'),
('äöüÄÖÜß', 'aeoeueAeOeUess'),
('ha@r!?mless+09', 'har?mless+09'),
("simple", "simple"),
("test@email.com", "testemail.com"),
("ref!with#special$chars%", "refwithspecialchars"),
("normal_text-123", "normaltext-123"), # underscores are removed
]
for input_ref, expected in test_cases:
result = Transaction.escape_reference(input_ref)
self.assertEqual(result, expected)
self.assertEqual(Transaction.escape_reference('harmless'), 'harmless')
self.assertEqual(Transaction.escape_reference('äöüÄÖÜß'), 'aeoeueAeOeUess')
self.assertEqual(Transaction.escape_reference('ha@r!?mless+09'), 'har?mless+09')
def test_code(self):
self.trans.amount = 0
@ -582,35 +335,6 @@ class TransactionTestCase(TestCase):
self.fritz.iban = 'DE89370400440532013000'
self.assertNotEqual(self.trans.code(), '')
def test_code_with_zero_amount(self):
"""Test transaction code generation with zero amount"""
transaction = Transaction.objects.create(
reference="test-ref",
amount=Decimal('0.00'),
member=self.fritz,
ledger=self.personal_account,
statement=self.st
)
# Zero amount should return empty code
self.assertEqual(transaction.code(), '')
def test_code_with_invalid_iban(self):
"""Test transaction code generation with invalid IBAN"""
self.fritz.iban = "INVALID_IBAN"
self.fritz.save()
transaction = Transaction.objects.create(
reference="test-ref",
amount=Decimal('100.00'),
member=self.fritz,
ledger=self.personal_account,
statement=self.st
)
# Invalid IBAN should return empty code
self.assertEqual(transaction.code(), '')
class BillTestCase(TestCase):
def setUp(self):
@ -626,30 +350,6 @@ class BillTestCase(TestCase):
def test_pretty_amount(self):
self.assertTrue('' in self.bill.pretty_amount())
def test_pretty_amount_formatting(self):
"""Test bill pretty_amount formatting with specific values"""
bill = Bill.objects.create(
statement=self.st,
short_description="Test Bill",
amount=Decimal('42.50')
)
pretty = bill.pretty_amount()
self.assertIn("42.50", pretty)
self.assertIn("", pretty)
def test_zero_amount(self):
"""Test bill with zero amount"""
bill = Bill.objects.create(
statement=self.st,
short_description="Zero Bill",
amount=Decimal('0.00')
)
self.assertEqual(bill.amount, Decimal('0.00'))
pretty = bill.pretty_amount()
self.assertIn("0.00", pretty)
class TransactionIssueTestCase(TestCase):
def setUp(self):

@ -1,4 +0,0 @@
from .admin import *
from .models import *
from .rules import *
from .migrations import *

@ -1,713 +0,0 @@
import unittest
from http import HTTPStatus
from django.test import TestCase, override_settings
from django.contrib.admin.sites import AdminSite
from django.test import RequestFactory, Client
from django.contrib.auth.models import User, Permission
from django.contrib.auth import models as authmodels
from django.utils import timezone
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.messages.storage.fallback import FallbackStorage
from django.contrib.messages import get_messages
from django.utils.translation import gettext_lazy as _
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect, HttpResponse
from unittest.mock import Mock, patch
from django.test.utils import override_settings
from django.urls import path, include
from django.contrib import admin as django_admin
from members.tests.utils import create_custom_user
from members.models import Member, MALE, Freizeit, GEMEINSCHAFTS_TOUR, MUSKELKRAFT_ANREISE
from ..models import (
Ledger, Statement, StatementUnSubmitted, StatementConfirmed, Transaction, Bill,
StatementSubmitted
)
from ..admin import (
LedgerAdmin, StatementAdmin, TransactionAdmin, BillAdmin
)
class AdminTestCase(TestCase):
def setUp(self, model, admin):
self.factory = RequestFactory()
self.model = model
if model is not None and admin is not None:
self.admin = admin(model, AdminSite())
superuser = User.objects.create_superuser(
username='superuser', password='secret'
)
standard = create_custom_user('standard', ['Standard'], 'Paul', 'Wulter')
trainer = create_custom_user('trainer', ['Standard', 'Trainings'], 'Lise', 'Lotte')
treasurer = create_custom_user('treasurer', ['Standard', 'Finance'], 'Lara', 'Litte')
materialwarden = create_custom_user('materialwarden', ['Standard', 'Material'], 'Loro', 'Lutte')
def _login(self, name):
c = Client()
res = c.login(username=name, password='secret')
# make sure we logged in
assert res
return c
class StatementUnSubmittedAdminTestCase(AdminTestCase):
"""Test cases for StatementAdmin in the case of unsubmitted statements"""
def setUp(self):
super().setUp(model=Statement, admin=StatementAdmin)
self.superuser = User.objects.get(username='superuser')
self.member = Member.objects.create(
prename="Test", lastname="User", birth_date=timezone.now().date(),
email="test@example.com", gender=MALE, user=self.superuser
)
self.statement = StatementUnSubmitted.objects.create(
short_description='Test Statement',
explanation='Test explanation',
night_cost=25
)
# Create excursion for testing
self.excursion = Freizeit.objects.create(
name='Test Excursion',
kilometers_traveled=100,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=1
)
# Create confirmed statement with excursion
self.statement_with_excursion = StatementUnSubmitted.objects.create(
short_description='With Excursion',
explanation='Test explanation',
night_cost=25,
excursion=self.excursion,
)
def test_save_model_with_member(self):
"""Test save_model sets created_by for new objects"""
request = self.factory.post('/')
request.user = self.superuser
# Test with change=False (new object)
new_statement = Statement(short_description='New Statement')
self.admin.save_model(request, new_statement, None, change=False)
self.assertEqual(new_statement.created_by, self.member)
def test_has_delete_permission(self):
"""Test if unsubmitted statements may be deleted"""
request = self.factory.post('/')
request.user = self.superuser
self.assertTrue(self.admin.has_delete_permission(request, self.statement))
def test_get_fields(self):
"""Test get_fields when excursion is set or not set."""
request = self.factory.post('/')
request.user = self.superuser
self.assertIn('excursion', self.admin.get_fields(request, self.statement_with_excursion))
self.assertNotIn('excursion', self.admin.get_fields(request, self.statement))
self.assertNotIn('excursion', self.admin.get_fields(request))
def test_get_inlines(self):
"""Test get_inlines"""
request = self.factory.post('/')
request.user = self.superuser
self.assertEqual(len(self.admin.get_inlines(request, self.statement)), 1)
def test_get_readonly_fields_submitted(self):
"""Test readonly fields when statement is submitted"""
# Mark statement as submitted
self.statement.status = Statement.SUBMITTED
readonly_fields = self.admin.get_readonly_fields(None, self.statement)
self.assertIn('status', readonly_fields)
self.assertIn('excursion', readonly_fields)
self.assertIn('short_description', readonly_fields)
def test_get_readonly_fields_not_submitted(self):
"""Test readonly fields when statement is not submitted"""
readonly_fields = self.admin.get_readonly_fields(None, self.statement)
self.assertEqual(readonly_fields, ['status', 'excursion'])
def test_submit_view_insufficient_permission(self):
url = reverse('admin:finance_statement_submit',
args=(self.statement.pk,))
c = self._login('standard')
response = c.get(url, follow=True)
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Insufficient permissions.'))
def test_submit_view_get(self):
url = reverse('admin:finance_statement_submit',
args=(self.statement.pk,))
c = self._login('superuser')
response = c.get(url, follow=True)
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Submit statement'))
def test_submit_view_get_with_excursion(self):
url = reverse('admin:finance_statement_submit',
args=(self.statement_with_excursion.pk,))
c = self._login('superuser')
response = c.get(url, follow=True)
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Finance overview'))
def test_submit_view_post(self):
url = reverse('admin:finance_statement_submit',
args=(self.statement.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'apply': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
text = _("Successfully submited %(name)s. The finance department will notify the requestors as soon as possible.") % {'name': str(self.statement)}
self.assertContains(response, text)
class StatementSubmittedAdminTestCase(AdminTestCase):
"""Test cases for StatementAdmin in the case of submitted statements"""
def setUp(self):
super().setUp(model=Statement, admin=StatementAdmin)
self.user = User.objects.create_user('testuser', 'test@example.com', 'pass')
self.member = Member.objects.create(
prename="Test", lastname="User", birth_date=timezone.now().date(),
email="test@example.com", gender=MALE, user=self.user
)
self.finance_user = User.objects.create_user('finance', 'finance@example.com', 'pass')
self.finance_user.groups.add(authmodels.Group.objects.get(name='Finance'),
authmodels.Group.objects.get(name='Standard'))
self.statement = Statement.objects.create(
short_description='Submitted Statement',
explanation='Test explanation',
status=Statement.SUBMITTED,
submitted_by=self.member,
submitted_date=timezone.now(),
night_cost=25
)
self.statement_unsubmitted = StatementUnSubmitted.objects.create(
short_description='Submitted Statement',
explanation='Test explanation',
night_cost=25
)
self.transaction = Transaction.objects.create(
reference='verylonglong' * 14,
amount=3,
statement=self.statement,
member=self.member,
)
# Create commonly used test objects
self.ledger = Ledger.objects.create(name='Test Ledger')
self.excursion = Freizeit.objects.create(
name='Test Excursion',
kilometers_traveled=100,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=1
)
self.other_member = Member.objects.create(
prename="Other", lastname="Member", birth_date=timezone.now().date(),
email="other@example.com", gender=MALE
)
# Create statements for generate transactions tests
self.statement_no_trans_success = Statement.objects.create(
short_description='No Transactions Success',
explanation='Test explanation',
status=Statement.SUBMITTED,
submitted_by=self.member,
submitted_date=timezone.now(),
night_cost=25
)
self.statement_no_trans_error = Statement.objects.create(
short_description='No Transactions Error',
explanation='Test explanation',
status=Statement.SUBMITTED,
submitted_by=self.member,
submitted_date=timezone.now(),
night_cost=25
)
# Create bills for generate transactions tests
self.bill_for_success = Bill.objects.create(
statement=self.statement_no_trans_success,
short_description='Test Bill Success',
amount=50,
paid_by=self.member,
costs_covered=True
)
self.bill_for_error = Bill.objects.create(
statement=self.statement_no_trans_error,
short_description='Test Bill Error',
amount=50,
paid_by=None, # No payer will cause generate_transactions to fail
costs_covered=True,
)
def _create_matching_bill(self, statement=None, amount=None):
"""Helper method to create a bill that matches transaction amount"""
return Bill.objects.create(
statement=statement or self.statement,
short_description='Test Bill',
amount=amount or self.transaction.amount,
paid_by=self.member,
costs_covered=True
)
def _create_non_matching_bill(self, statement=None, amount=100):
"""Helper method to create a bill that doesn't match transaction amount"""
return Bill.objects.create(
statement=statement or self.statement,
short_description='Non-matching Bill',
amount=amount,
paid_by=self.member
)
def test_has_change_permission_with_permission(self):
"""Test change permission with proper permission"""
request = self.factory.get('/')
request.user = self.finance_user
self.assertTrue(self.admin.has_change_permission(request))
def test_has_change_permission_without_permission(self):
"""Test change permission without proper permission"""
request = self.factory.get('/')
request.user = self.user
self.assertFalse(self.admin.has_change_permission(request))
def test_has_delete_permission(self):
"""Test that delete permission is disabled"""
request = self.factory.get('/')
request.user = self.finance_user
self.assertFalse(self.admin.has_delete_permission(request))
def test_readonly_fields(self):
self.assertNotIn('explanation',
self.admin.get_readonly_fields(None, self.statement_unsubmitted))
def test_change(self):
url = reverse('admin:finance_statement_change',
args=(self.statement.pk,))
c = self._login('superuser')
response = c.get(url)
self.assertEqual(response.status_code, HTTPStatus.OK)
def test_overview_view(self):
url = reverse('admin:finance_statement_overview',
args=(self.statement.pk,))
c = self._login('superuser')
response = c.get(url)
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('View submitted statement'))
def test_overview_view_statement_not_found(self):
"""Test overview_view with statement that can't be found in StatementSubmitted queryset"""
# When trying to access an unsubmitted statement via StatementSubmitted admin,
# the decorator will fail to find it and show "Statement not found"
self.statement.status = Statement.UNSUBMITTED
self.statement.save()
url = reverse('admin:finance_statement_overview', args=(self.statement.pk,))
c = self._login('superuser')
response = c.get(url, follow=True)
self.assertEqual(response.status_code, HTTPStatus.OK)
messages = list(get_messages(response.wsgi_request))
expected_text = str(_("Statement not found."))
self.assertTrue(any(expected_text in str(msg) for msg in messages))
def test_overview_view_transaction_execution_confirm(self):
"""Test overview_view transaction execution confirm"""
# Set up statement to be valid for confirmation
self.transaction.ledger = self.ledger
self.transaction.save()
# Create a bill that matches the transaction amount to make it valid
self._create_matching_bill()
url = reverse('admin:finance_statement_overview', args=(self.statement.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'transaction_execution_confirm': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
success_text = _("Successfully confirmed %(name)s. I hope you executed the associated transactions, I wont remind you again.") % {'name': str(self.statement)}
self.assertContains(response, success_text)
self.statement.refresh_from_db()
self.assertTrue(self.statement.confirmed)
def test_overview_view_transaction_execution_confirm_and_send(self):
"""Test overview_view transaction execution confirm and send"""
# Set up statement to be valid for confirmation
self.transaction.ledger = self.ledger
self.transaction.save()
# Create a bill that matches the transaction amount to make it valid
self._create_matching_bill()
url = reverse('admin:finance_statement_overview', args=(self.statement.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'transaction_execution_confirm_and_send': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
success_text = _("Successfully sent receipt to the office.")
self.assertContains(response, success_text)
def test_overview_view_confirm_valid(self):
"""Test overview_view confirm with valid statement"""
# Create a statement with valid configuration
# Set up transaction with ledger to make it valid
self.transaction.ledger = self.ledger
self.transaction.save()
# Create a bill that matches the transaction amount to make total valid
self._create_matching_bill()
url = reverse('admin:finance_statement_overview',
args=(self.statement.pk,))
c = self._login('superuser')
response = c.post(url, data={'confirm': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Statement confirmed'))
def test_overview_view_confirm_non_matching_transactions(self):
"""Test overview_view confirm with non-matching transactions"""
# Create a bill that doesn't match the transaction
self._create_non_matching_bill()
url = reverse('admin:finance_statement_overview',
args=(self.statement.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'confirm': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
error_text = _("Transactions do not match the covered expenses. Please correct the mistakes listed below.")
self.assertContains(response, error_text)
def test_overview_view_confirm_missing_ledger(self):
"""Test overview_view confirm with missing ledger"""
# Ensure transaction has no ledger (ledger=None)
self.transaction.ledger = None
self.transaction.save()
# Create a bill that matches the transaction amount to pass the first check
self._create_matching_bill()
url = reverse('admin:finance_statement_overview',
args=(self.statement.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'confirm': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
# Check the Django messages for the error
messages = list(get_messages(response.wsgi_request))
expected_text = str(_("Some transactions have no ledger configured. Please fill in the gaps."))
self.assertTrue(any(expected_text in str(msg) for msg in messages))
def test_overview_view_confirm_invalid_allowance_to(self):
"""Test overview_view confirm with invalid allowance"""
# Create excursion and set up invalid allowance configuration
self.statement.excursion = self.excursion
self.statement.save()
# Add allowance recipient who is not a youth leader for this excursion
self.statement_no_trans_success.allowance_to.add(self.other_member)
# Generate required transactions
self.statement_no_trans_success.generate_transactions()
for trans in self.statement_no_trans_success.transaction_set.all():
trans.ledger = self.ledger
trans.save()
# Check validity obstruction is allowances
self.assertEqual(self.statement_no_trans_success.validity, Statement.INVALID_ALLOWANCE_TO)
url = reverse('admin:finance_statement_overview',
args=(self.statement_no_trans_success.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'confirm': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
# Check the Django messages for the error
messages = list(get_messages(response.wsgi_request))
expected_text = str(_("The configured recipients for the allowance don't match the regulations. Please correct this on the excursion."))
self.assertTrue(any(expected_text in str(msg) for msg in messages))
def test_overview_view_reject(self):
"""Test overview_view reject statement"""
url = reverse('admin:finance_statement_overview', args=(self.statement.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'reject': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
success_text = _("Successfully rejected %(name)s. The requestor can reapply, when needed.") %\
{'name': str(self.statement)}
self.assertContains(response, success_text)
# Verify statement was rejected
self.statement.refresh_from_db()
self.assertFalse(self.statement.submitted)
def test_overview_view_generate_transactions_existing(self):
"""Test overview_view generate transactions with existing transactions"""
# Ensure there's already a transaction
self.assertTrue(self.statement.transaction_set.count() > 0)
url = reverse('admin:finance_statement_overview', args=(self.statement.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'generate_transactions': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
error_text = _("%(name)s already has transactions. Please delete them first, if you want to generate new ones") % {'name': str(self.statement)}
self.assertContains(response, error_text)
def test_overview_view_generate_transactions_success(self):
"""Test overview_view generate transactions successfully"""
url = reverse('admin:finance_statement_overview',
args=(self.statement_no_trans_success.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'generate_transactions': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
success_text = _("Successfully generated transactions for %(name)s") %\
{'name': str(self.statement_no_trans_success)}
self.assertContains(response, success_text)
def test_overview_view_generate_transactions_error(self):
"""Test overview_view generate transactions with error"""
url = reverse('admin:finance_statement_overview',
args=(self.statement_no_trans_error.pk,))
c = self._login('superuser')
response = c.post(url, follow=True, data={'generate_transactions': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
messages = list(get_messages(response.wsgi_request))
expected_text = str(_("Error while generating transactions for %(name)s. Do all bills have a payer and, if this statement is attached to an excursion, was a person selected that receives the subsidies?") %\
{'name': str(self.statement_no_trans_error)})
self.assertTrue(any(expected_text in str(msg) for msg in messages))
def test_reduce_transactions_view(self):
url = reverse('admin:finance_statement_reduce_transactions',
args=(self.statement.pk,))
c = self._login('superuser')
response = c.get(url, data={'redirectTo': reverse('admin:finance_statement_changelist')},
follow=True)
self.assertContains(response,
_("Successfully reduced transactions for %(name)s.") %\
{'name': str(self.statement)})
class StatementConfirmedAdminTestCase(AdminTestCase):
"""Test cases for StatementAdmin in the case of confirmed statements"""
def setUp(self):
super().setUp(model=Statement, admin=StatementAdmin)
self.user = User.objects.create_user('testuser', 'test@example.com', 'pass')
self.member = Member.objects.create(
prename="Test", lastname="User", birth_date=timezone.now().date(),
email="test@example.com", gender=MALE, user=self.user
)
self.finance_user = User.objects.create_user('finance', 'finance@example.com', 'pass')
self.finance_user.groups.add(authmodels.Group.objects.get(name='Finance'),
authmodels.Group.objects.get(name='Standard'))
# Create a base statement first
base_statement = Statement.objects.create(
short_description='Confirmed Statement',
explanation='Test explanation',
status=Statement.CONFIRMED,
confirmed_by=self.member,
confirmed_date=timezone.now(),
night_cost=25
)
# StatementConfirmed is a proxy model, so we can get it from the base statement
self.statement = StatementConfirmed.objects.get(pk=base_statement.pk)
# Create an unconfirmed statement for testing
self.unconfirmed_statement = Statement.objects.create(
short_description='Unconfirmed Statement',
explanation='Test explanation',
status=Statement.SUBMITTED,
night_cost=25
)
# Create excursion for testing
self.excursion = Freizeit.objects.create(
name='Test Excursion',
kilometers_traveled=100,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=1
)
# Create confirmed statement with excursion
confirmed_with_excursion_base = Statement.objects.create(
short_description='Confirmed with Excursion',
explanation='Test explanation',
status=Statement.CONFIRMED,
confirmed_by=self.member,
confirmed_date=timezone.now(),
excursion=self.excursion,
night_cost=25
)
self.statement_with_excursion = StatementConfirmed.objects.get(pk=confirmed_with_excursion_base.pk)
def _add_session_to_request(self, request):
"""Add session to request"""
middleware = SessionMiddleware(lambda req: None)
middleware.process_request(request)
request.session.save()
middleware = MessageMiddleware(lambda req: None)
middleware.process_request(request)
request._messages = FallbackStorage(request)
def test_has_change_permission(self):
"""Test that change permission is disabled"""
request = self.factory.get('/')
request.user = self.finance_user
self.assertFalse(self.admin.has_change_permission(request, self.statement))
def test_has_delete_permission(self):
"""Test that delete permission is disabled"""
request = self.factory.get('/')
request.user = self.finance_user
self.assertFalse(self.admin.has_delete_permission(request, self.statement))
def test_unconfirm_view_not_confirmed_statement(self):
"""Test unconfirm_view with statement that is not confirmed"""
# Create request for unconfirmed statement
request = self.factory.get('/')
request.user = self.finance_user
self._add_session_to_request(request)
# Test with unconfirmed statement (should trigger error path)
self.assertFalse(self.unconfirmed_statement.confirmed)
# Call unconfirm_view - this should go through error path
response = self.admin.unconfirm_view(request, self.unconfirmed_statement.pk)
# Should redirect due to not confirmed error
self.assertEqual(response.status_code, 302)
def test_unconfirm_view_post_unconfirm_action(self):
"""Test unconfirm_view POST request with 'unconfirm' action"""
# Create POST request with unconfirm action
request = self.factory.post('/', {'unconfirm': 'true'})
request.user = self.finance_user
self._add_session_to_request(request)
# Ensure statement is confirmed
self.assertTrue(self.statement.confirmed)
self.assertIsNotNone(self.statement.confirmed_by)
self.assertIsNotNone(self.statement.confirmed_date)
# Call unconfirm_view - this should execute the unconfirm action
response = self.admin.unconfirm_view(request, self.statement.pk)
# Should redirect after successful unconfirm
self.assertEqual(response.status_code, 302)
# Verify statement was unconfirmed (need to reload from DB)
self.statement.refresh_from_db()
self.assertFalse(self.statement.confirmed)
self.assertIsNone(self.statement.confirmed_date)
def test_unconfirm_view_get_render_template(self):
"""Test unconfirm_view GET request rendering template"""
# Create GET request (no POST data)
request = self.factory.get('/')
request.user = self.finance_user
self._add_session_to_request(request)
# Ensure statement is confirmed
self.assertTrue(self.statement.confirmed)
# Call unconfirm_view
response = self.admin.unconfirm_view(request, self.statement.pk)
# Should render template (status 200)
self.assertEqual(response.status_code, 200)
# Check response content contains expected template elements
self.assertIn(str(_('Unconfirm statement')).encode('utf-8'), response.content)
self.assertIn(self.statement.short_description.encode(), response.content)
def test_statement_summary_view_insufficient_permission(self):
url = reverse('admin:finance_statement_summary',
args=(self.statement_with_excursion.pk,))
c = self._login('standard')
response = c.get(url, follow=True)
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Insufficient permissions.'))
def test_statement_summary_view_unconfirmed(self):
url = reverse('admin:finance_statement_summary',
args=(self.unconfirmed_statement.pk,))
c = self._login('superuser')
response = c.get(url, follow=True)
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Statement not found.'))
def test_statement_summary_view_confirmed_with_excursion(self):
"""Test statement_summary_view when statement is confirmed with excursion"""
url = reverse('admin:finance_statement_summary',
args=(self.statement_with_excursion.pk,))
c = self._login('superuser')
response = c.get(url, follow=True)
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(response.headers['Content-Type'], 'application/pdf')
class TransactionAdminTestCase(TestCase):
"""Test cases for TransactionAdmin"""
def setUp(self):
self.site = AdminSite()
self.factory = RequestFactory()
self.admin = TransactionAdmin(Transaction, self.site)
self.user = User.objects.create_user('testuser', 'test@example.com', 'pass')
self.member = Member.objects.create(
prename="Test", lastname="User", birth_date=timezone.now().date(),
email="test@example.com", gender=MALE, user=self.user
)
self.ledger = Ledger.objects.create(name='Test Ledger')
self.statement = Statement.objects.create(
short_description='Test Statement',
explanation='Test explanation'
)
self.transaction = Transaction.objects.create(
member=self.member,
ledger=self.ledger,
amount=100,
reference='Test transaction',
statement=self.statement
)
def test_has_add_permission(self):
"""Test that add permission is disabled"""
request = self.factory.get('/')
request.user = self.user
self.assertFalse(self.admin.has_add_permission(request))
def test_has_change_permission(self):
"""Test that change permission is disabled"""
request = self.factory.get('/')
request.user = self.user
self.assertFalse(self.admin.has_change_permission(request))
def test_has_delete_permission(self):
"""Test that delete permission is disabled"""
request = self.factory.get('/')
request.user = self.user
self.assertFalse(self.admin.has_delete_permission(request))
def test_get_readonly_fields_confirmed(self):
"""Test readonly fields when transaction is confirmed"""
self.transaction.confirmed = True
readonly_fields = self.admin.get_readonly_fields(None, self.transaction)
self.assertEqual(readonly_fields, self.admin.fields)
def test_get_readonly_fields_not_confirmed(self):
"""Test readonly fields when transaction is not confirmed"""
readonly_fields = self.admin.get_readonly_fields(None, self.transaction)
self.assertEqual(readonly_fields, ())

@ -1,70 +0,0 @@
import django.test
from django.apps import apps
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
class StatusMigrationTestCase(django.test.TransactionTestCase):
"""Test the migration from submitted/confirmed fields to status field."""
app = 'finance'
migrate_from = [('finance', '0009_statement_ljp_to')]
migrate_to = [('finance', '0010_statement_status')]
def setUp(self):
# Get the state before migration
executor = MigrationExecutor(connection)
executor.migrate(self.migrate_from)
# Get the old models (before migration)
old_apps = executor.loader.project_state(self.migrate_from).apps
self.Statement = old_apps.get_model(self.app, 'Statement')
# Create statements with different combinations of submitted/confirmed
# created_by is nullable, so we don't need to create a Member
self.unsubmitted = self.Statement.objects.create(
short_description='Unsubmitted Statement',
submitted=False,
confirmed=False
)
self.submitted = self.Statement.objects.create(
short_description='Submitted Statement',
submitted=True,
confirmed=False
)
self.confirmed = self.Statement.objects.create(
short_description='Confirmed Statement',
submitted=True,
confirmed=True
)
def test_status_field_migration(self):
"""Test that status field is correctly set from old submitted/confirmed fields."""
# Run the migration
executor = MigrationExecutor(connection)
executor.loader.build_graph()
executor.migrate(self.migrate_to)
# Get the new models (after migration)
new_apps = executor.loader.project_state(self.migrate_to).apps
Statement = new_apps.get_model(self.app, 'Statement')
# Constants from the Statement model
UNSUBMITTED = 0
SUBMITTED = 1
CONFIRMED = 2
# Verify the migration worked correctly
unsubmitted = Statement.objects.get(pk=self.unsubmitted.pk)
self.assertEqual(unsubmitted.status, UNSUBMITTED,
'Statement with submitted=False, confirmed=False should have status=UNSUBMITTED')
submitted = Statement.objects.get(pk=self.submitted.pk)
self.assertEqual(submitted.status, SUBMITTED,
'Statement with submitted=True, confirmed=False should have status=SUBMITTED')
confirmed = Statement.objects.get(pk=self.confirmed.pk)
self.assertEqual(confirmed.status, CONFIRMED,
'Statement with submitted=True, confirmed=True should have status=CONFIRMED')

@ -1,102 +0,0 @@
from django.test import TestCase
from django.utils import timezone
from django.conf import settings
from django.contrib.auth.models import User
from unittest.mock import Mock
from finance.rules import is_creator, not_submitted, leads_excursion
from finance.models import Statement, Ledger
from members.models import Member, Group, Freizeit, GEMEINSCHAFTS_TOUR, MUSKELKRAFT_ANREISE, MALE, FEMALE
class FinanceRulesTestCase(TestCase):
def setUp(self):
self.group = Group.objects.create(name="Test Group")
self.ledger = Ledger.objects.create(name="Test Ledger")
self.user1 = User.objects.create_user(username="alice", password="test123")
self.member1 = Member.objects.create(
prename="Alice", lastname="Smith", birth_date=timezone.now().date(),
email=settings.TEST_MAIL, gender=FEMALE, user=self.user1
)
self.member1.group.add(self.group)
self.user2 = User.objects.create_user(username="bob", password="test123")
self.member2 = Member.objects.create(
prename="Bob", lastname="Jones", birth_date=timezone.now().date(),
email=settings.TEST_MAIL, gender=MALE, user=self.user2
)
self.member2.group.add(self.group)
self.freizeit = Freizeit.objects.create(
name="Test Excursion",
kilometers_traveled=100,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=2
)
self.freizeit.jugendleiter.add(self.member1)
self.statement = Statement.objects.create(
short_description="Test Statement",
explanation="Test explanation",
night_cost=27,
created_by=self.member1,
excursion=self.freizeit
)
self.statement.allowance_to.add(self.member1)
def test_is_creator_true(self):
"""Test is_creator predicate returns True when user created the statement"""
self.assertTrue(is_creator(self.user1, self.statement))
self.assertFalse(is_creator(self.user2, self.statement))
def test_not_submitted_statement(self):
"""Test not_submitted predicate returns True when statement is not submitted"""
self.statement.status = Statement.UNSUBMITTED
self.assertTrue(not_submitted(self.user1, self.statement))
self.statement.status = Statement.SUBMITTED
self.assertFalse(not_submitted(self.user1, self.statement))
def test_not_submitted_freizeit_with_statement(self):
"""Test not_submitted predicate with Freizeit having unsubmitted statement"""
self.freizeit.statement = self.statement
self.statement.status = Statement.UNSUBMITTED
self.assertTrue(not_submitted(self.user1, self.freizeit))
def test_not_submitted_freizeit_without_statement(self):
"""Test not_submitted predicate with Freizeit having no statement attribute"""
# Create a mock Freizeit that truly doesn't have the statement attribute
mock_freizeit = Mock(spec=Freizeit)
# Remove the statement attribute entirely
if hasattr(mock_freizeit, 'statement'):
delattr(mock_freizeit, 'statement')
self.assertTrue(not_submitted(self.user1, mock_freizeit))
def test_leads_excursion_freizeit_user_is_leader(self):
"""Test leads_excursion predicate returns True when user leads the Freizeit"""
self.assertTrue(leads_excursion(self.user1, self.freizeit))
self.assertFalse(leads_excursion(self.user2, self.freizeit))
def test_leads_excursion_statement_with_excursion(self):
"""Test leads_excursion predicate with statement having excursion led by user"""
result = leads_excursion(self.user1, self.statement)
self.assertTrue(result)
def test_leads_excursion_statement_no_excursion_attribute(self):
"""Test leads_excursion predicate with statement having no excursion attribute"""
mock_statement = Mock()
del mock_statement.excursion
result = leads_excursion(self.user1, mock_statement)
self.assertFalse(result)
def test_leads_excursion_statement_excursion_is_none(self):
"""Test leads_excursion predicate with statement having None excursion"""
statement_no_excursion = Statement.objects.create(
short_description="Test Statement No Excursion",
explanation="Test explanation",
night_cost=27,
created_by=self.member1,
excursion=None
)
result = leads_excursion(self.user1, statement_no_excursion)
self.assertFalse(result)

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

@ -11,4 +11,4 @@ app.config_from_object('django.conf:settings')
app.autodiscover_tasks()
if __name__ == '__main__':
app.start() # pragma: no cover
app.start()

@ -25,7 +25,7 @@ if os.path.exists(os.path.join(CONFIG_DIR_PATH, TEXTS_FILE)):
with open(os.path.join(CONFIG_DIR_PATH, TEXTS_FILE), 'rb') as f:
texts = tomli.load(f)
else:
texts = {} # pragma: no cover
texts = {}
def get_var(*keys, default='', dictionary=config):
@ -58,8 +58,6 @@ base_settings = [
'components/emails.py',
'components/texts.py',
'components/locale.py',
'components/logging.py',
'components/oauth.py',
]
include(*base_settings)

@ -52,7 +52,6 @@ INSTALLED_APPS = [
'django_celery_beat',
'rules',
'jet',
'oauth2_provider',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
@ -197,5 +196,3 @@ STARTPAGE_URL_NAME_PATTERN = "[\w\-: *]"
# admins to contact on error messages
ADMINS = get_var('section', 'admins', default=[])
LOGIN_URL = '/de/kompass/login/'

@ -11,22 +11,21 @@ JET_SIDE_MENU_ITEMS = [
{'name': 'group', 'permissions': ['members.view_group']},
{'name': 'membernotelist', 'permissions': ['members.view_membernotelist']},
{'name': 'klettertreff', 'permissions': ['members.view_klettertreff']},
{'name': 'activitycategory', 'permissions': ['members.view_group']},
{'name': 'trainingcategory', 'permissions': ['members.view_group']},
]},
{'label': 'Neue Mitglieder', 'app_label': 'members', 'permissions': ['members.view_memberunconfirmedproxy'], 'items': [
{'name': 'memberunconfirmedproxy', 'permissions': ['members.view_memberunconfirmedproxy']},
{'name': 'memberwaitinglist', 'permissions': ['members.view_memberwaitinglist']},
]},
{'label': 'Ausbildung', 'app_label': 'members', 'permissions': ['members.view_membertraining'], 'items': [
{'name': 'membertraining', 'permissions': ['members.view_membertraining']},
{'name': 'trainingcategory', 'permissions': ['members.view_trainingcategory']},
{'name': 'activitycategory', 'permissions': ['members.view_activitycategory']},
]},
{'app_label': 'mailer', 'items': [
{'name': 'message', 'permissions': ['mailer.view_message']},
{'name': 'emailaddress', 'permissions': ['mailer.view_emailaddress']},
]},
{'app_label': 'finance', 'items': [
{'name': 'statement', 'permissions': ['finance.view_statement']},
{'name': 'statementunsubmitted', 'permissions': ['finance.view_statementunsubmitted']},
{'name': 'statementsubmitted', 'permissions': ['finance.view_statementsubmitted']},
{'name': 'statementconfirmed', 'permissions': ['finance.view_statementconfirmed']},
{'name': 'ledger', 'permissions': ['finance.view_ledger']},
{'name': 'bill', 'permissions': ['finance.view_bill', 'finance.view_bill_admin']},
{'name': 'transaction', 'permissions': ['finance.view_transaction']},

@ -1,59 +0,0 @@
import os
DJANGO_LOG_LEVEL = get_var('logging', 'django_level', default='INFO')
ROOT_LOG_LEVEL = get_var('logging', 'level', default='INFO')
LOG_ERROR_TO_EMAIL = get_var('logging', 'email_admins', default=False)
LOG_EMAIL_BACKEND = EMAIL_BACKEND if LOG_ERROR_TO_EMAIL else "django.core.mail.backends.console.EmailBackend"
LOG_ERROR_INCLUDE_HTML = get_var('logging', 'error_report_include_html', default=False)
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {
"require_debug_false": {
"()": "django.utils.log.RequireDebugFalse",
},
"require_debug_true": {
"()": "django.utils.log.RequireDebugTrue",
},
},
"formatters": {
"simple": {
"format": "[{asctime}: {levelname}/{name}] {message}",
"style": "{",
},
"verbose": {
"format": "[{asctime}: {levelname}/{name}] {pathname}:{lineno} {message}",
"style": "{",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "simple",
},
"console_verbose": {
"class": "logging.StreamHandler",
"formatter": "verbose",
"level": "ERROR",
},
"mail_admins": {
"level": "ERROR",
"class": "django.utils.log.AdminEmailHandler",
"email_backend": LOG_EMAIL_BACKEND,
"include_html": LOG_ERROR_INCLUDE_HTML,
"filters": ["require_debug_false"],
},
},
"root": {
"handlers": ["console"],
"level": ROOT_LOG_LEVEL,
},
"loggers": {
"django": {
"handlers": ["console", "mail_admins"],
"level": DJANGO_LOG_LEVEL,
"propagate": False,
},
},
}

@ -1,11 +0,0 @@
OAUTH2_PROVIDER = {
"OIDC_ENABLED": True,
"PKCE_REQUIRED": False,
"OAUTH2_VALIDATOR_CLASS": "logindata.oauth.CustomOAuth2Validator",
"OIDC_RSA_PRIVATE_KEY": get_var('oauth', 'oidc_rsa_private_key', default=''),
"SCOPES": {
"openid": "OpenID Connect scope",
"profile": "profile scope",
"email": "email scope",
},
}

@ -22,46 +22,6 @@ bestätige falls möglich. Zu der Registrierung kommst du hier:
Viele Grüße
Dein KOMPASS""")
GROUP_INVITATION_LEFT_WAITINGLIST = get_text('group_invitation_left_waitinglist',
default="""Hallo {name},
der*die kürzlich zu einer Schnupperstunde für die Gruppe {group} eingeladene Wartende {waiter}
hat die Warteliste verlassen.
Viele Grüße
Dein KOMPASS""")
GROUP_INVITATION_REJECTED = get_text('group_invitation_rejected',
default="""Hallo {name},
{waiter} hat die Einladung zu einer Schnupperstunde bei der Gruppe {group} abgelehnt, ist
aber weiterhin auf der Warteliste.
Viele Grüße
Dein KOMPASS""")
GROUP_INVITATION_CONFIRMED_TEXT = get_text('group_invitation_confirmed',
default="""Hallo {name},
{waiter} hat die Einladung zu einer Schnupperstunde bei der Gruppe {group} angenommen.
Viele Grüße
Dein KOMPASS""")
TRIAL_GROUP_MEETING_CONFIRMED_TEXT = get_text('trial_group_meeting_confirmed',
default="""Hallo {name},
deine Teilnahme an der Schnupperstunde der Gruppe {group} wurde erfolgreich bestätigt.
{timeinfo}
Für alle weiteren Absprachen, kontaktiere bitte die Jugendleiter*innen der Gruppe
unter {contact_email}.
Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION })
GROUP_TIME_AVAILABLE_TEXT = get_text('group_time_available',
default="""Die Gruppenstunde findet jeden {weekday} von {start_time} bis {end_time} Uhr statt.""")
@ -73,11 +33,7 @@ INVITE_TEXT = get_text('invite', default="""Hallo {{name}},
wir haben gute Neuigkeiten für dich. Es ist ein Platz in der Jugendgruppe {group_name} {group_link}freigeworden.
{group_time}
Wenn du an der Schnupperstunde teilnehmen möchtest, bestätige deine Teilnahme bitte unter folgendem Link:
{{invitation_confirm_link}}
Für alle weiteren Absprachen, kontaktiere bitte die Gruppenleitung ({contact_email}).
Bitte kontaktiere die Gruppenleitung ({contact_email}) für alle weiteren Absprachen.
Wenn du nach der Schnupperstunde beschließt der Gruppe beizutreten, benötigen wir noch ein paar
Informationen und eine schriftliche Anmeldebestätigung von dir. Das kannst du alles über folgenden Link erledigen:
@ -247,37 +203,3 @@ Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION, 'RESPONSIBLE_MAIL': RESPONSIBL
ADDRESS = get_text('address', default="""JDAV %(SEKTION)s
%(STREET)s
%(PLACE)s""" % { 'SEKTION': SEKTION, 'STREET': SEKTION_STREET, 'PLACE': SEKTION_TOWN })
NOTIFY_EXCURSION_PARTICIPANT_LIST = get_text('notify_excursion_participant_list', default="""Hallo {name},
deine Ausfahrt {excursion} steht kurz bevor. Damit die Sektion dich im Notfall gut unterstützen kann, benötigt
die Geschäftsstelle eine aktuelle Kriseninterventionsliste, das heißt eine Teilnehmendenliste der Ausfahrt.
Das Verschicken der Liste passiert automatisch zum Zeitpunkt: {sending_time}.
Das sind die aktuell in der Ausfahrt eingetragenen Teilnehmenden:
{participants}
Falls diese Liste nicht mehr aktuell ist, gehe bitte umgehend auf {excursion_link} und trage die Daten nach.
Viele Grüße
Dein KOMPASS""")
SEND_EXCURSION_CRISIS_LIST = get_text('send_excursion_crisis_list', default="""Hallo zusammen,
vom {excursion_start} bis {excursion_end} findet die Ausfahrt {excursion} der Jugend statt. Die
Ausfahrt wird geleitet von {leaders}.
Im Anhang findet ihr die Kriseninterventionsliste.
Viele Grüße
Euer KOMPASS""")
SEND_STATEMENT_SUMMARY = get_text('send_statement_summary', default="""Hallo zusammen,
anbei findet ihr die Abrechnung inklusive Belege für {statement}. Die Überweisungen
wurden wie beschrieben ausgeführt.
Viele Grüße
Euer KOMPASS""")

@ -9,7 +9,6 @@ SEKTION_CONTACT_MAIL = get_var('section', 'contact_mail', default='info@example.
SEKTION_BOARD_MAIL = get_var('section', 'board_mail', default=SEKTION_CONTACT_MAIL)
SEKTION_CRISIS_INTERVENTION_MAIL = get_var('section', 'crisis_intervention_mail',
default=SEKTION_BOARD_MAIL)
SEKTION_FINANCE_MAIL = get_var('section', 'finance_mail', default=SEKTION_CONTACT_MAIL)
SEKTION_IBAN = get_var('section', 'iban', default='Foo 123')
SEKTION_ACCOUNT_HOLDER = get_var('section', 'account_holder',
default='Foo')
@ -21,7 +20,6 @@ DIGITAL_MAIL = get_var('section', 'digital_mail', default='bar@example.org')
V32_HEAD_ORGANISATION = get_var('LJP', 'v32_head_organisation', default='not configured')
LJP_CONTRIBUTION_PER_DAY = get_var('LJP', 'contribution_per_day', default=25)
LJP_TAX = get_var('LJP', 'tax', default=0)
# echo
@ -51,21 +49,11 @@ SEND_FROM_ASSOCIATION_EMAIL = get_var('misc', 'send_from_association_email', def
# domain for association email and generated urls
DOMAIN = get_var('misc', 'domain', default='example.org')
GROUP_CHECKLIST_N_WEEKS = get_var('misc', 'group_checklist_n_weeks', default=18)
GROUP_CHECKLIST_N_MEMBERS = get_var('misc', 'group_checklist_n_members', default=20)
GROUP_CHECKLIST_TEXT = get_var('misc', 'group_checklist_text',
default="""Anwesende Jugendleitende und Teilnehmende werden mit einem
Kreuz ($\\times$) markiert und die ausgefüllte Liste zum Anfang der Gruppenstunde an der Kasse
abgegeben. Zum Ende wird sie wieder abgeholt. Wenn die Punkte auf einer Karte fast aufgebraucht
sind, notiert die Kasse die verbliebenen Eintritte (3, 2, 1) unter dem Kreuz.""")
# finance
ALLOWANCE_PER_DAY = get_var('finance', 'allowance_per_day', default=22)
MAX_NIGHT_COST = get_var('finance', 'max_night_cost', default=11)
EXCURSION_ORG_FEE = get_var('finance', 'org_fee', default=10)
# links
CLOUD_LINK = get_var('links', 'cloud', default='https://startpage.com')

@ -1,30 +0,0 @@
from django.test import TestCase, RequestFactory, override_settings
from django.contrib.auth.models import User
from django.contrib import admin
from unittest.mock import Mock, patch
from jdav_web.views import media_unprotected, custom_admin_view
from startpage.models import Link
class ViewsTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = User.objects.create_user('testuser', 'test@example.com', 'password')
Link.objects.create(title='Test Link', url='https://example.com')
@override_settings(DEBUG=True)
def test_media_unprotected_debug_true(self):
request = self.factory.get('/media/test.jpg')
with patch('jdav_web.views.serve') as mock_serve:
mock_serve.return_value = Mock()
result = media_unprotected(request, 'test.jpg')
mock_serve.assert_called_once()
def test_custom_admin_view(self):
request = self.factory.get('/admin/')
request.user = self.user
with patch.object(admin.site, 'get_app_list') as mock_get_app_list:
mock_get_app_list.return_value = []
response = custom_admin_view(request)
self.assertEqual(response.status_code, 200)
mock_get_app_list.assert_called_once_with(request)

@ -13,14 +13,13 @@ Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.urls import path, re_path, include
from django.urls import re_path, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf.urls.i18n import i18n_patterns
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.views.generic.base import RedirectView
from oauth2_provider import urls as oauth2_urls
from .views import media_access
admin.site.index_title = _('Startpage')
@ -37,7 +36,6 @@ urlpatterns = i18n_patterns(
re_path(r'^LBAlpin/Programm(/)?(20)?[0-9]{0,2}', include('ludwigsburgalpin.urls',
namespace="ludwigsburgalpin")),
re_path(r'^_nested_admin/', include('nested_admin.urls')),
path('o/', include(oauth2_urls)),
re_path(r'^', include('startpage.urls', namespace="startpage")),
)

@ -0,0 +1 @@
Subproject commit 0126d5596fcba43730ecc7e6cbc0987b12f0640d

@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-04-15 23:05+0200\n"
"POT-Creation-Date: 2025-02-01 14:54+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@ -236,10 +236,6 @@ msgstr "Löschen?"
msgid "Unconfirm"
msgstr "Bestätigung zurücknehmen"
#: templates/admin/finance/statementconfirmed/change_form_object_tools.html
msgid "Download summary"
msgstr "Beleg herunterladen"
#: templates/admin/finance/statementsubmitted/change_form_object_tools.html
msgid "Reduce transactions"
msgstr "Überweisungen minimieren"
@ -276,10 +272,6 @@ msgstr "Kostenübersicht"
msgid "Generate group overview"
msgstr "Gruppenübersicht erstellen"
#: templates/admin/members/group/change_list.html
msgid "Generate group checklist"
msgstr "Gruppencheckliste erstellen"
#: templates/admin/members/member/change_form_object_tools.html
msgid "Invite as user"
msgstr "Als Kompassbenutzer*in einladen"

@ -1,13 +0,0 @@
from oauth2_provider.oauth2_validators import OAuth2Validator
class CustomOAuth2Validator(OAuth2Validator):
# Set `oidc_claim_scope = None` to ignore scopes that limit which claims to return,
# otherwise the OIDC standard scopes are used.
def get_additional_claims(self, request):
if request.user.member:
context = {'email': request.user.member.email}
else:
context = {}
return dict(context, preferred_username=request.user.username)

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -1,2 +0,0 @@
from .views import *
from .oauth import *

@ -1,47 +0,0 @@
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from unittest.mock import Mock
from logindata.oauth import CustomOAuth2Validator
from members.models import Member, MALE
class CustomOAuth2ValidatorTestCase(TestCase):
def setUp(self):
self.validator = CustomOAuth2Validator()
# Create user with member
self.user_with_member = User.objects.create_user(username="alice", password="test123")
self.member = Member.objects.create(
prename="Alice", lastname="Smith", birth_date="1990-01-01",
email=settings.TEST_MAIL, gender=MALE, user=self.user_with_member
)
# Create user without member
self.user_without_member = User.objects.create_user(username="bob", password="test123")
def test_get_additional_claims_with_member(self):
"""Test get_additional_claims when user has a member"""
request = Mock()
request.user = self.user_with_member
result = self.validator.get_additional_claims(request)
self.assertEqual(result['email'], settings.TEST_MAIL)
self.assertEqual(result['preferred_username'], 'alice')
def test_get_additional_claims_without_member(self):
"""Test get_additional_claims when user has no member"""
# ensure branch coverage, not possible under standard scenarios
request = Mock()
request.user = Mock()
request.user.member = None
self.assertEqual(len(self.validator.get_additional_claims(request)), 1)
request = Mock()
request.user = self.user_without_member
# The method will raise RelatedObjectDoesNotExist, which means the code
# should use hasattr or try/except. For now, test that it raises.
with self.assertRaises(User.member.RelatedObjectDoesNotExist):
self.validator.get_additional_claims(request)

@ -1,154 +0,0 @@
from http import HTTPStatus
from django.test import TestCase, Client
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext as _
from django.contrib.auth.models import User, Group
from members.models import Member, DIVERSE
from ..models import RegistrationPassword, initial_user_setup
class RegistrationPasswordTestCase(TestCase):
def test_str_method(self):
"""Test RegistrationPassword __str__ method returns password"""
reg_password = RegistrationPassword.objects.create(password="test123")
self.assertEqual(str(reg_password), "test123")
class RegisterViewTestCase(TestCase):
def setUp(self):
self.client = Client()
# Create a test member with invite key
self.member = Member.objects.create(
prename='Test',
lastname='User',
birth_date=timezone.now().date(),
email='test@example.com',
gender=DIVERSE,
invite_as_user_key='test_key_123'
)
# Create a registration password
self.registration_password = RegistrationPassword.objects.create(
password='test_password'
)
# Get or create Standard group for user setup
self.standard_group, created = Group.objects.get_or_create(name='Standard')
def test_register_get_without_key_redirects(self):
"""Test GET request without key redirects to startpage."""
url = reverse('logindata:register')
response = self.client.get(url)
self.assertEqual(response.status_code, HTTPStatus.FOUND)
def test_register_post_without_key_redirects(self):
"""Test POST request without key redirects to startpage."""
url = reverse('logindata:register')
response = self.client.post(url)
self.assertEqual(response.status_code, HTTPStatus.FOUND)
def test_register_get_with_empty_key_shows_failed(self):
"""Test GET request with empty key shows registration failed page."""
url = reverse('logindata:register')
response = self.client.get(url, {'key': ''})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Something went wrong. The registration key is invalid or has expired.'))
def test_register_get_with_invalid_key_shows_failed(self):
"""Test GET request with invalid key shows registration failed page."""
url = reverse('logindata:register')
response = self.client.get(url, {'key': 'invalid_key'})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Something went wrong. The registration key is invalid or has expired.'))
def test_register_get_with_valid_key_shows_password_form(self):
"""Test GET request with valid key shows password entry form."""
url = reverse('logindata:register')
response = self.client.get(url, {'key': self.member.invite_as_user_key})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Set login data'))
self.assertContains(response, _('Welcome, '))
self.assertContains(response, self.member.prename)
def test_register_post_without_password_shows_failed(self):
"""Test POST request without password shows registration failed page."""
url = reverse('logindata:register')
response = self.client.post(url, {'key': self.member.invite_as_user_key})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Something went wrong. The registration key is invalid or has expired.'))
def test_register_post_with_wrong_password_shows_error(self):
"""Test POST request with wrong password shows error message."""
url = reverse('logindata:register')
response = self.client.post(url, {
'key': self.member.invite_as_user_key,
'password': 'wrong_password'
})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('You entered a wrong password.'))
def test_register_post_with_correct_password_shows_form(self):
"""Test POST request with correct password shows user creation form."""
url = reverse('logindata:register')
response = self.client.post(url, {
'key': self.member.invite_as_user_key,
'password': self.registration_password.password
})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Set login data'))
self.assertContains(response, self.member.suggested_username())
def test_register_post_with_save_and_invalid_form_shows_errors(self):
"""Test POST request with save but invalid form shows form errors."""
url = reverse('logindata:register')
response = self.client.post(url, {
'key': self.member.invite_as_user_key,
'password': self.registration_password.password,
'save': 'true',
'username': '', # Invalid - empty username
'password1': 'testpass123',
'password2': 'different_pass' # Invalid - passwords don't match
})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Set login data'))
def test_register_post_with_save_and_valid_form_shows_success(self):
"""Test POST request with save and valid form shows success page."""
url = reverse('logindata:register')
response = self.client.post(url, {
'key': self.member.invite_as_user_key,
'password': self.registration_password.password,
'save': 'true',
'username': 'testuser',
'password1': 'testpass123',
'password2': 'testpass123'
})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('You successfully set your login data. You can now proceed to'))
# Verify user was created and associated with member
user = User.objects.get(username='testuser')
self.assertEqual(user.is_staff, True)
self.member.refresh_from_db()
self.assertEqual(self.member.user, user)
self.assertEqual(self.member.invite_as_user_key, '')
def test_register_post_with_save_and_no_standard_group_shows_failed(self):
"""Test POST request with save but no Standard group shows failed page."""
# Delete the Standard group
self.standard_group.delete()
url = reverse('logindata:register')
response = self.client.post(url, {
'key': self.member.invite_as_user_key,
'password': self.registration_password.password,
'save': 'true',
'username': 'testuser',
'password1': 'testpass123',
'password2': 'testpass123'
})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _('Something went wrong. The registration key is invalid or has expired.'))

@ -1,13 +1,9 @@
from django.core import mail
from django.core.mail import EmailMessage
from django.conf import settings
import logging
import os
logger = logging.getLogger(__name__)
NOT_SENT, SENT, PARTLY_SENT = 0, 1, 2
def send(subject, content, sender, recipients, message_id=None, reply_to=None,
@ -45,7 +41,7 @@ def send(subject, content, sender, recipients, message_id=None, reply_to=None,
# send all mails with one connection
connection.send_messages(mails)
except Exception as e:
logger.error(f"Caught exception while sending email: {e}")
print("Error when sending mail:", e)
failed = True
else:
succeeded = True
@ -80,10 +76,6 @@ def get_invitation_reject_link(key):
return prepend_base_url("/members/waitinglist/invitation/reject?key={}".format(key))
def get_invitation_confirm_link(key):
return prepend_base_url("/members/waitinglist/invitation/confirm?key={}".format(key))
def get_wait_confirmation_link(waiter):
key = waiter.generate_wait_confirmation_key()
return prepend_base_url("/members/waitinglist/confirm?key={}".format(key))

@ -1,4 +1,3 @@
import logging
from django.db import models
from django.core.exceptions import ValidationError
from django import forms
@ -11,16 +10,12 @@ from jdav_web.celery import app
from django.core.validators import RegexValidator
from django.conf import settings
from contrib.rules import has_global_perm
from contrib.models import CommonModel
from .rules import is_creator
import os
logger = logging.getLogger(__name__)
alphanumeric = RegexValidator(r'^[0-9a-zA-Z._-]*$',
_('Only alphanumeric characters, ., - and _ are allowed'))
@ -149,7 +144,7 @@ class Message(CommonModel):
members.update([mol.member for mol in
self.to_notelist.membersonlist.all()])
filtered = [m for m in members if m.gets_newsletter]
logger.info(f"sending mail to {filtered}")
print("sending mail to", filtered)
attach = [a.f.path for a in Attachment.objects.filter(msg__id=self.pk)
if a.f.name]
@ -193,7 +188,7 @@ class Message(CommonModel):
a.delete()
success = SENT
except Exception as e:
logger.error(f"Caught exception while sending email: {e}")
print("Exception caught", e)
success = NOT_SENT
finally:
self.save()
@ -206,9 +201,9 @@ class Message(CommonModel):
("submit_mails", _("Can submit mails")),
)
rules_permissions = {
"view_obj": is_creator | has_global_perm('mailer.view_global_message'),
"change_obj": is_creator | has_global_perm('mailer.change_global_message'),
"delete_obj": is_creator | has_global_perm('mailer.delete_global_message'),
"view_obj": is_creator,
"change_obj": is_creator,
"delete_obj": is_creator,
}
@ -236,15 +231,15 @@ class Attachment(CommonModel):
max_upload_size=10)
def __str__(self):
return os.path.basename(self.f.name) if self.f.name else str(_("Empty"))
return os.path.basename(self.f.name) if self.f.name else _("Empty")
class Meta:
verbose_name = _('attachment')
verbose_name_plural = _('attachments')
rules_permissions = {
"add_obj": is_creator | has_global_perm('mailer.view_global_message'),
"view_obj": is_creator | has_global_perm('mailer.view_global_message'),
"change_obj": is_creator | has_global_perm('mailer.change_global_message'),
"delete_obj": is_creator | has_global_perm('mailer.delete_global_message'),
"add_obj": is_creator,
"view_obj": is_creator,
"change_obj": is_creator,
"delete_obj": is_creator,
}

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -1,5 +0,0 @@
from .models import *
from .admin import *
from .views import *
from .rules import *
from .mailutils import *

@ -1,330 +0,0 @@
import json
import unittest
from http import HTTPStatus
from django.test import TestCase, override_settings
from django.contrib.admin.sites import AdminSite
from django.test import RequestFactory, Client
from django.contrib.auth.models import User, Permission
from django.utils import timezone
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.messages.storage.fallback import FallbackStorage
from django.contrib.messages import get_messages
from django.utils.translation import gettext_lazy as _
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect, HttpResponse
from unittest.mock import Mock, patch
from django.test.utils import override_settings
from django.urls import path, include
from django.contrib import admin as django_admin
from django.conf import settings
from members.tests.utils import create_custom_user
from members.models import Member, MALE, DIVERSE, Group
from ..models import Message, Attachment, EmailAddress
from ..admin import MessageAdmin, submit_message
from ..mailutils import SENT, NOT_SENT, PARTLY_SENT
class AdminTestCase(TestCase):
def setUp(self, model, admin):
self.factory = RequestFactory()
self.model = model
if model is not None and admin is not None:
self.admin = admin(model, AdminSite())
superuser = User.objects.create_superuser(
username='superuser', password='secret'
)
standard = create_custom_user('standard', ['Standard'], 'Paul', 'Wulter')
trainer = create_custom_user('trainer', ['Standard', 'Trainings'], 'Lise', 'Lotte')
def _add_middleware(self, request):
"""Add required middleware to request."""
# Session middleware
middleware = SessionMiddleware(lambda x: None)
middleware.process_request(request)
request.session.save()
# Messages middleware
messages_middleware = MessageMiddleware(lambda x: None)
messages_middleware.process_request(request)
request._messages = FallbackStorage(request)
class MessageAdminTestCase(AdminTestCase):
def setUp(self):
super().setUp(Message, MessageAdmin)
# Create test data
self.group = Group.objects.create(name='Test Group')
self.email_address = EmailAddress.objects.create(name='testmail')
# Create test member with internal email
self.internal_member = Member.objects.create(
prename='Internal',
lastname='User',
birth_date=timezone.now().date(),
email=f'internal@{settings.ALLOWED_EMAIL_DOMAINS_FOR_INVITE_AS_USER[0]}',
gender=DIVERSE
)
# Create test member with external email
self.external_member = Member.objects.create(
prename='External',
lastname='User',
birth_date=timezone.now().date(),
email='external@example.com',
gender=DIVERSE
)
# Create users for testing
self.user_with_internal_member = User.objects.create_user(username='testuser', password='secret')
self.user_with_internal_member.member = self.internal_member
self.user_with_internal_member.save()
self.user_with_external_member = User.objects.create_user(username='external_user', password='secret')
self.user_with_external_member.member = self.external_member
self.user_with_external_member.save()
self.user_without_member = User.objects.create_user(username='no_member_user', password='secret')
# Create test message
self.message = Message.objects.create(
subject='Test Message',
content='Test content'
)
self.message.to_groups.add(self.group)
self.message.to_members.add(self.internal_member)
def test_save_model_sets_created_by(self):
"""Test that save_model sets created_by when creating new message."""
request = self.factory.post('/admin/mailer/message/add/')
request.user = self.user_with_internal_member
# Create new message
new_message = Message(subject='New Message', content='New content')
# Test save_model for new object (change=False)
self.admin.save_model(request, new_message, None, change=False)
self.assertEqual(new_message.created_by, self.internal_member)
def test_save_model_does_not_change_created_by_on_update(self):
"""Test that save_model doesn't change created_by when updating."""
request = self.factory.post('/admin/mailer/message/1/change/')
request.user = self.user_with_internal_member
# Message already has created_by set
self.message.created_by = self.external_member
# Test save_model for existing object (change=True)
self.admin.save_model(request, self.message, None, change=True)
self.assertEqual(self.message.created_by, self.external_member)
@patch('mailer.models.Message.submit')
def test_submit_message_success(self, mock_submit):
"""Test submit_message with successful send."""
mock_submit.return_value = SENT
request = self.factory.post('/admin/mailer/message/')
request.user = self.user_with_internal_member
self._add_middleware(request)
# Test submit_message
submit_message(self.message, request)
# Verify submit was called with correct sender
mock_submit.assert_called_once_with(self.internal_member)
# Check success message
messages_list = list(get_messages(request))
self.assertEqual(len(messages_list), 1)
self.assertIn(str(_('Successfully sent message')), str(messages_list[0]))
@patch('mailer.models.Message.submit')
def test_submit_message_not_sent(self, mock_submit):
"""Test submit_message when sending fails."""
mock_submit.return_value = NOT_SENT
request = self.factory.post('/admin/mailer/message/')
request.user = self.user_with_internal_member
self._add_middleware(request)
# Test submit_message
submit_message(self.message, request)
# Check error message
messages_list = list(get_messages(request))
self.assertEqual(len(messages_list), 1)
self.assertIn(str(_('Failed to send message')), str(messages_list[0]))
@patch('mailer.models.Message.submit')
def test_submit_message_partly_sent(self, mock_submit):
"""Test submit_message when partially sent."""
mock_submit.return_value = PARTLY_SENT
request = self.factory.post('/admin/mailer/message/')
request.user = self.user_with_internal_member
self._add_middleware(request)
# Test submit_message
submit_message(self.message, request)
# Check warning message
messages_list = list(get_messages(request))
self.assertEqual(len(messages_list), 1)
self.assertIn(str(_('Failed to send some messages')), str(messages_list[0]))
def test_submit_message_user_has_no_member(self):
"""Test submit_message when user has no associated member."""
request = self.factory.post('/admin/mailer/message/')
request.user = self.user_without_member
self._add_middleware(request)
# Test submit_message
submit_message(self.message, request)
# Check error message
messages_list = list(get_messages(request))
self.assertEqual(len(messages_list), 1)
self.assertIn(str(_('Your account is not connected to a member. Please contact your system administrator.')), str(messages_list[0]))
def test_submit_message_user_has_external_email(self):
"""Test submit_message when user has external email."""
request = self.factory.post('/admin/mailer/message/')
request.user = self.user_with_external_member
self._add_middleware(request)
# Test submit_message
submit_message(self.message, request)
# Check error message
messages_list = list(get_messages(request))
self.assertEqual(len(messages_list), 1)
self.assertIn(str(_('Your email address is not an internal email address. Please use an email address with one of the following domains: %(domains)s.') % {'domains': ", ".join(settings.ALLOWED_EMAIL_DOMAINS_FOR_INVITE_AS_USER)}), str(messages_list[0]))
@patch('mailer.admin.submit_message')
def test_send_message_action_confirmed(self, mock_submit_message):
"""Test send_message action when confirmed."""
request = self.factory.post('/admin/mailer/message/', {'confirmed': 'true'})
request.user = self.user_with_internal_member
self._add_middleware(request)
queryset = Message.objects.filter(pk=self.message.pk)
# Test send_message action
result = self.admin.send_message(request, queryset)
# Verify submit_message was called for each message
mock_submit_message.assert_called_once_with(self.message, request)
# Should return None when confirmed (no template response)
self.assertIsNone(result)
def test_send_message_action_not_confirmed(self):
"""Test send_message action when not confirmed (shows confirmation page)."""
request = self.factory.post('/admin/mailer/message/')
request.user = self.user_with_internal_member
self._add_middleware(request)
queryset = Message.objects.filter(pk=self.message.pk)
# Test send_message action
result = self.admin.send_message(request, queryset)
# Should return HttpResponse with confirmation template
self.assertIsNotNone(result)
self.assertEqual(result.status_code, HTTPStatus.OK)
@patch('mailer.admin.submit_message')
def test_response_change_with_send(self, mock_submit_message):
"""Test response_change when _send is in POST."""
request = self.factory.post('/admin/mailer/message/1/change/', {'_send': 'Send'})
request.user = self.user_with_internal_member
self._add_middleware(request)
# Test response_change
with patch.object(self.admin.__class__.__bases__[2], 'response_change') as mock_super:
mock_super.return_value = HttpResponseRedirect('/admin/')
result = self.admin.response_change(request, self.message)
# Verify submit_message was called
mock_submit_message.assert_called_once_with(self.message, request)
# Verify super method was called
mock_super.assert_called_once()
@patch('mailer.admin.submit_message')
def test_response_change_without_send(self, mock_submit_message):
"""Test response_change when _send is not in POST."""
request = self.factory.post('/admin/mailer/message/1/change/', {'_save': 'Save'})
request.user = self.user_with_internal_member
self._add_middleware(request)
# Test response_change
with patch.object(self.admin.__class__.__bases__[2], 'response_change') as mock_super:
mock_super.return_value = HttpResponseRedirect('/admin/')
result = self.admin.response_change(request, self.message)
# Verify submit_message was NOT called
mock_submit_message.assert_not_called()
# Verify super method was called
mock_super.assert_called_once()
@patch('mailer.admin.submit_message')
def test_response_add_with_send(self, mock_submit_message):
"""Test response_add when _send is in POST."""
request = self.factory.post('/admin/mailer/message/add/', {'_send': 'Send'})
request.user = self.user_with_internal_member
self._add_middleware(request)
# Test response_add
with patch.object(self.admin.__class__.__bases__[2], 'response_add') as mock_super:
mock_super.return_value = HttpResponseRedirect('/admin/')
result = self.admin.response_add(request, self.message)
# Verify submit_message was called
mock_submit_message.assert_called_once_with(self.message, request)
# Verify super method was called
mock_super.assert_called_once()
def test_get_form_with_members_param(self):
"""Test get_form when members parameter is provided."""
# Create request with members parameter
members_ids = [self.internal_member.pk, self.external_member.pk]
request = self.factory.get(f'/admin/mailer/message/add/?members={json.dumps(members_ids)}')
request.user = self.user_with_internal_member
# Test get_form
form_class = self.admin.get_form(request)
form = form_class()
# Verify initial members are set
self.assertEqual(list(form.fields['to_members'].initial), [self.internal_member, self.external_member])
def test_get_form_with_invalid_members_param(self):
"""Test get_form when members parameter is not a list."""
# Create request with invalid members parameter
request = self.factory.get('/admin/mailer/message/add/?members="not_a_list"')
request.user = self.user_with_internal_member
# Test get_form
form_class = self.admin.get_form(request)
# Should return form without modification
self.assertIsNotNone(form_class)
def test_get_form_without_members_param(self):
"""Test get_form when no members parameter is provided."""
# Create request without members parameter
request = self.factory.get('/admin/mailer/message/add/')
request.user = self.user_with_internal_member
# Test get_form
form_class = self.admin.get_form(request)
# Should return form without modification
self.assertIsNotNone(form_class)

@ -1,34 +0,0 @@
from django.test import TestCase, override_settings
from unittest.mock import patch, Mock
from mailer.mailutils import send, SENT, NOT_SENT
class MailUtilsTest(TestCase):
def setUp(self):
self.subject = "Test Subject"
self.content = "Test Content"
self.sender = "sender@example.com"
self.recipient = "recipient@example.com"
def test_send_with_reply_to(self):
with patch('mailer.mailutils.mail.get_connection') as mock_connection:
mock_conn = Mock()
mock_connection.return_value = mock_conn
result = send(self.subject, self.content, self.sender, self.recipient, reply_to=["reply@example.com"])
self.assertEqual(result, SENT)
def test_send_with_message_id(self):
with patch('mailer.mailutils.mail.get_connection') as mock_connection:
mock_conn = Mock()
mock_connection.return_value = mock_conn
result = send(self.subject, self.content, self.sender, self.recipient, message_id="<test@example.com>")
self.assertEqual(result, SENT)
def test_send_exception_handling(self):
with patch('mailer.mailutils.mail.get_connection') as mock_connection:
mock_conn = Mock()
mock_conn.send_messages.side_effect = Exception("Test exception")
mock_connection.return_value = mock_conn
with patch('builtins.print'):
result = send(self.subject, self.content, self.sender, self.recipient)
self.assertEqual(result, NOT_SENT)

@ -1,271 +0,0 @@
from unittest import skip, mock
from django.test import TestCase
from django.conf import settings
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
from django.core.files.uploadedfile import SimpleUploadedFile
from members.models import Member, Group, DIVERSE, Freizeit, MemberNoteList, GEMEINSCHAFTS_TOUR, MUSKELKRAFT_ANREISE
from mailer.models import EmailAddress, EmailAddressForm, Message, MessageForm, Attachment
from mailer.mailutils import SENT, NOT_SENT, PARTLY_SENT
from .utils import BasicMailerTestCase
class EmailAddressTestCase(BasicMailerTestCase):
def test_email(self):
self.assertEqual(self.em.email, f"foobar@{settings.DOMAIN}")
def test_str(self):
self.assertEqual(self.em.email, str(self.em))
def test_forwards(self):
self.assertEqual(self.em.forwards, {'fritz@foo.com', 'paul@foo.com'})
class EmailAddressFormTestCase(BasicMailerTestCase):
def test_clean(self):
# instantiate form with only name field set
form = EmailAddressForm(data={'name': 'bar'})
# validate the form - this should fail due to missing required recipients
self.assertFalse(form.is_valid())
class MessageFormTestCase(BasicMailerTestCase):
def test_clean(self):
# instantiate form with only subject and content fields set
form = MessageForm(data={'subject': 'Test Subject', 'content': 'Test content'})
# validate the form - this should fail due to missing required recipients
self.assertFalse(form.is_valid())
class MessageTestCase(BasicMailerTestCase):
def setUp(self):
super().setUp()
self.message = Message.objects.create(
subject='Test Message',
content='This is a test message'
)
self.freizeit = Freizeit.objects.create(
name='Test Freizeit',
kilometers_traveled=120,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=1
)
self.notelist = MemberNoteList.objects.create(
title='Test Note List'
)
# Set up message with multiple recipient types
self.message.to_groups.add(self.mygroup)
self.message.to_freizeit = self.freizeit
self.message.to_notelist = self.notelist
self.message.to_members.add(self.fritz)
self.message.save()
# Create a sender member for submit tests
self.sender = Member.objects.create(
prename='Sender',
lastname='Test',
birth_date=timezone.now().date(),
email='sender@test.com',
gender=DIVERSE
)
def test_str(self):
self.assertEqual(str(self.message), 'Test Message')
def test_get_recipients(self):
recipients = self.message.get_recipients()
self.assertIn('My Group', recipients)
self.assertIn('Test Freizeit', recipients)
self.assertIn('Test Note List', recipients)
self.assertIn('Fritz Wulter', recipients)
def test_get_recipients_with_many_members(self):
# Add additional members to test the "Some other members" case
for i in range(3):
member = Member.objects.create(
prename=f'Member{i}',
lastname='Test',
birth_date=timezone.now().date(),
email=f'member{i}@test.com',
gender=DIVERSE
)
self.message.to_members.add(member)
recipients = self.message.get_recipients()
self.assertIn(_('Some other members'), recipients)
@mock.patch('mailer.models.send')
def test_submit_successful(self, mock_send):
# Mock successful email sending
mock_send.return_value = SENT
# Test submit method
result = self.message.submit(sender=self.sender)
# Verify the message was marked as sent
self.message.refresh_from_db()
self.assertTrue(self.message.sent)
self.assertEqual(result, SENT)
# Verify send was called
self.assertTrue(mock_send.called)
@mock.patch('mailer.models.send')
def test_submit_failed(self, mock_send):
# Mock failed email sending
mock_send.return_value = NOT_SENT
# Test submit method
result = self.message.submit(sender=self.sender)
# Verify the message was not marked as sent
self.message.refresh_from_db()
self.assertFalse(self.message.sent)
# Note: The submit method always returns SENT when an exception occurs
self.assertEqual(result, SENT)
@mock.patch('mailer.models.send')
def test_submit_without_sender(self, mock_send):
# Mock successful email sending
mock_send.return_value = SENT
# Test submit method without sender
result = self.message.submit()
# Verify the message was marked as sent
self.message.refresh_from_db()
self.assertTrue(self.message.sent)
self.assertEqual(result, SENT)
@mock.patch('mailer.models.send')
def test_submit_subject_cleaning(self, mock_send):
# Mock successful email sending
mock_send.return_value = SENT
# Create message with underscores in subject
message_with_underscores = Message.objects.create(
subject='Test_Message_With_Underscores',
content='Test content'
)
message_with_underscores.to_members.add(self.fritz)
# Test submit method
result = message_with_underscores.submit()
# Verify underscores were removed from subject
message_with_underscores.refresh_from_db()
self.assertEqual(message_with_underscores.subject, 'Test Message With Underscores')
@mock.patch('mailer.models.send')
def test_submit_exception_handling(self, mock_send):
# Mock an exception during email sending
mock_send.side_effect = Exception("Email sending failed")
# Test submit method
result = self.message.submit(sender=self.sender)
# Verify the message was not marked as sent
self.message.refresh_from_db()
self.assertFalse(self.message.sent)
# When exception occurs, it should return NOT_SENT
self.assertEqual(result, NOT_SENT)
@mock.patch('mailer.models.send')
@mock.patch('django.conf.settings.SEND_FROM_ASSOCIATION_EMAIL', False)
def test_submit_with_sender_no_association_email(self, mock_send):
# Mock successful email sending
mock_send.return_value = PARTLY_SENT
# Test submit method with sender but SEND_FROM_ASSOCIATION_EMAIL disabled
result = self.message.submit(sender=self.sender)
# Verify the message was marked as sent
self.message.refresh_from_db()
self.assertTrue(self.message.sent)
self.assertEqual(result, SENT)
@mock.patch('mailer.models.send')
@mock.patch('django.conf.settings.SEND_FROM_ASSOCIATION_EMAIL', False)
def test_submit_with_reply_to_logic(self, mock_send):
# Mock successful email sending
mock_send.return_value = SENT
# Create a sender with internal email capability
sender_with_internal = Member.objects.create(
prename='Internal',
lastname='Sender',
birth_date=timezone.now().date(),
email='internal@test.com',
gender=DIVERSE
)
# Mock has_internal_email to return True
with mock.patch.object(sender_with_internal, 'has_internal_email', return_value=True):
# Test submit method
result = self.message.submit(sender=sender_with_internal)
# Verify the message was marked as sent
self.message.refresh_from_db()
self.assertTrue(self.message.sent)
self.assertEqual(result, SENT)
@mock.patch('mailer.models.send')
@mock.patch('os.remove')
def test_submit_with_attachments(self, mock_os_remove, mock_send):
# Mock successful email sending
mock_send.return_value = SENT
# Create an attachment with a file
test_file = SimpleUploadedFile("test_file.pdf", b"file_content", content_type="application/pdf")
attachment = Attachment.objects.create(msg=self.message, f=test_file)
# Test submit method
result = self.message.submit()
# Verify the message was marked as sent
self.message.refresh_from_db()
self.assertTrue(self.message.sent)
self.assertEqual(result, SENT)
# Verify file removal was attempted (the path will be the actual file path)
mock_os_remove.assert_called()
# Attachment should be deleted
with self.assertRaises(Attachment.DoesNotExist):
attachment.refresh_from_db()
@mock.patch('mailer.models.send')
def test_submit_with_association_email_enabled(self, mock_send):
"""Test submit method when SEND_FROM_ASSOCIATION_EMAIL is True and sender has association_email"""
mock_send.return_value = SENT
# Mock settings to enable association email sending
with mock.patch.object(settings, 'SEND_FROM_ASSOCIATION_EMAIL', True):
result = self.message.submit(sender=self.sender)
# Check that send was called with sender's association email
self.assertTrue(mock_send.called)
call_args = mock_send.call_args
from_addr = call_args[0][2] # from_addr is the 3rd positional argument
expected_from = f"{self.sender.name} <{self.sender.association_email}>"
self.assertEqual(from_addr, expected_from)
class AttachmentTestCase(BasicMailerTestCase):
def setUp(self):
super().setUp()
self.message = Message.objects.create(
subject='Test Message',
content='Test content'
)
self.attachment = Attachment.objects.create(msg=self.message)
def test_str_with_file(self):
# Simulate a file name
self.attachment.f.name = 'attachments/test_document.pdf'
self.assertEqual(str(self.attachment), 'test_document.pdf')
def test_str_without_file(self):
self.assertEqual(str(self.attachment), _('Empty'))

@ -1,31 +0,0 @@
from django.test import TestCase
from django.conf import settings
from django.contrib.auth.models import User
from mailer.rules import is_creator
from mailer.models import Message
from members.models import Member, MALE
class MailerRulesTestCase(TestCase):
def setUp(self):
self.user1 = User.objects.create_user(username="alice", password="test123")
self.member1 = Member.objects.create(
prename="Alice", lastname="Smith", birth_date="1990-01-01",
email=settings.TEST_MAIL, gender=MALE, user=self.user1
)
self.message = Message.objects.create(
subject="Test Message",
content="Test content",
created_by=self.member1
)
def test_is_creator_returns_true_when_user_created_message(self):
"""Test is_creator predicate returns True when user created the message"""
result = is_creator(self.user1, self.message)
self.assertTrue(result)
def test_is_creator_returns_false_when_message_is_none(self):
"""Test is_creator predicate returns False when message is None"""
result = is_creator(self.user1, None)
self.assertFalse(result)

@ -1,27 +0,0 @@
from unittest import skip, mock
from django.test import TestCase
from django.conf import settings
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
from django.core.files.uploadedfile import SimpleUploadedFile
from members.models import Member, Group, DIVERSE, Freizeit, MemberNoteList, GEMEINSCHAFTS_TOUR, MUSKELKRAFT_ANREISE
from mailer.models import EmailAddress, EmailAddressForm, Message, MessageForm, Attachment
from mailer.mailutils import SENT, NOT_SENT, PARTLY_SENT
class BasicMailerTestCase(TestCase):
def setUp(self):
self.mygroup = Group.objects.create(name="My Group")
self.fritz = Member.objects.create(prename="Fritz", lastname="Wulter", birth_date=timezone.now().date(),
email='fritz@foo.com', gender=DIVERSE)
self.fritz.group.add(self.mygroup)
self.fritz.save()
self.fritz.generate_key()
self.paul = Member.objects.create(prename="Paul", lastname="Wulter", birth_date=timezone.now().date(),
email='paul@foo.com', gender=DIVERSE)
self.em = EmailAddress.objects.create(name='foobar')
self.em.to_groups.add(self.mygroup)
self.em.to_members.add(self.paul)

@ -1,65 +0,0 @@
from unittest import skip, mock
from http import HTTPStatus
from django.urls import reverse
from django.test import TestCase
from django.conf import settings
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
from django.core.files.uploadedfile import SimpleUploadedFile
from members.models import Member, Group, DIVERSE, Freizeit, MemberNoteList, GEMEINSCHAFTS_TOUR, MUSKELKRAFT_ANREISE
from mailer.models import EmailAddress, EmailAddressForm, Message, MessageForm, Attachment
from mailer.mailutils import SENT, NOT_SENT, PARTLY_SENT
from .utils import BasicMailerTestCase
class IndexTestCase(BasicMailerTestCase):
def test_index(self):
url = reverse('mailer:index')
response = self.client.get(url)
self.assertEqual(response.status_code, HTTPStatus.FOUND)
class UnsubscribeTestCase(BasicMailerTestCase):
def test_unsubscribe(self):
url = reverse('mailer:unsubscribe')
response = self.client.get(url)
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _("Here you can unsubscribe from the newsletter"))
def test_unsubscribe_key_invalid(self):
url = reverse('mailer:unsubscribe')
# invalid key
response = self.client.get(url, data={'key': 'invalid'})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _("Can't verify this link. Try again!"))
# expired key
self.fritz.unsubscribe_expire = timezone.now()
self.fritz.save()
response = self.client.get(url, data={'key': self.fritz.unsubscribe_key})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _("Can't verify this link. Try again!"))
def test_unsubscribe_key(self):
url = reverse('mailer:unsubscribe')
response = self.client.get(url, data={'key': self.fritz.unsubscribe_key})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _("Successfully unsubscribed from the newsletter for "))
def test_unsubscribe_post_incomplete(self):
url = reverse('mailer:unsubscribe')
response = self.client.post(url, data={'post': True})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _("Please fill in every field"))
response = self.client.post(url, data={'post': True, 'email': 'foobar@notexisting.com'})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _("Please fill in every field"))
def test_unsubscribe_post(self):
url = reverse('mailer:unsubscribe')
response = self.client.post(url, data={'post': True, 'email': self.fritz.email})
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertContains(response, _("Sent confirmation mail to"))

@ -5,5 +5,6 @@ from . import views
app_name = "mailer"
urlpatterns = [
re_path(r'^$', views.index, name='index'),
# url(r'^subscribe', views.subscribe, name='subscribe'),
re_path(r'^unsubscribe', views.unsubscribe, name='unsubscribe'),
]

@ -53,5 +53,52 @@ def unsubscribe(request):
return render_confirmation_sent(request, email)
def render_subscribe(request, error_message=""):
date_input = forms.DateInput(attrs={'required': True,
'class': 'datepicker',
'name': 'birthdate'})
date_field = date_input.render(_("Birthdate"), "")
context = {'date_field': date_field}
if error_message:
context['error_message'] = error_message
return render(request, 'mailer/subscribe.html', context)
def render_confirmation_sent(request, email):
return render(request, 'mailer/confirmation_sent.html', {'email': email})
def subscribe(request):
try:
request.POST['post']
try:
print("trying to subscribe")
prename = request.POST['prename']
lastname = request.POST['lastname']
email = request.POST['email']
print("email", email)
birth_date = request.POST['birthdate']
print("birthdate", birth_date)
except KeyError:
return subscribe(request, _("Please fill in every field!"))
else:
# TODO: check whether member exists
exists = Member.objects.filter(prename=prename,
lastname=lastname)
if len(exists) > 0:
return render_subscribe(request,
error_message=_("Member "
"already exists"))
member = Member(prename=prename,
lastname=lastname,
email=email,
birth_date=birth_date,
gets_newsletter=True)
member.save()
return subscribed(request)
except KeyError:
return render_subscribe(request)
def subscribed(request):
return render(request, 'mailer/subscribed.html')

@ -1,238 +1,3 @@
from django.test import TestCase, RequestFactory
from django.utils import timezone
from datetime import date, datetime
from decimal import Decimal
from unittest.mock import Mock
from material.models import MaterialCategory, MaterialPart, Ownership, yearsago
from material.admin import NotTooOldFilter, MaterialAdmin
from members.models import Member, MALE, FEMALE, DIVERSE
from django.test import TestCase
class MaterialCategoryTestCase(TestCase):
def setUp(self):
self.category = MaterialCategory.objects.create(name="Climbing Gear")
def test_str(self):
"""Test string representation of MaterialCategory"""
self.assertEqual(str(self.category), "Climbing Gear")
def test_verbose_names(self):
"""Test verbose names are set correctly"""
meta = MaterialCategory._meta
self.assertTrue(hasattr(meta, 'verbose_name'))
self.assertTrue(hasattr(meta, 'verbose_name_plural'))
class MaterialPartTestCase(TestCase):
def setUp(self):
self.category = MaterialCategory.objects.create(name="Ropes")
self.material_part = MaterialPart.objects.create(
name="Dynamic Rope 10mm",
description="60m dynamic climbing rope",
quantity=5,
buy_date=date(2020, 1, 15),
lifetime=Decimal('8')
)
self.material_part.material_cat.add(self.category)
self.member = Member.objects.create(
prename="John",
lastname="Doe",
birth_date=date(1990, 1, 1),
email="john@example.com",
gender=MALE
)
def test_str(self):
"""Test string representation of MaterialPart"""
self.assertEqual(str(self.material_part), "Dynamic Rope 10mm")
def test_quantity_real_no_ownership(self):
"""Test quantity_real when no ownership exists"""
result = self.material_part.quantity_real()
self.assertEqual(result, "0/5")
def test_quantity_real_with_ownership(self):
"""Test quantity_real with ownership records"""
Ownership.objects.create(
material=self.material_part,
owner=self.member,
count=3
)
Ownership.objects.create(
material=self.material_part,
owner=self.member,
count=1
)
result = self.material_part.quantity_real()
self.assertEqual(result, "4/5")
def test_verbose_names(self):
"""Test field verbose names"""
# Just test that verbose names exist, since they might be translated
field_names = ['name', 'description', 'quantity', 'buy_date', 'lifetime', 'photo', 'material_cat']
for field_name in field_names:
field = self.material_part._meta.get_field(field_name)
self.assertTrue(hasattr(field, 'verbose_name'))
self.assertIsNotNone(field.verbose_name)
def test_admin_thumbnail_with_photo(self):
"""Test admin_thumbnail when photo exists"""
mock_photo = Mock()
mock_photo.url = "/media/test.jpg"
self.material_part.photo = mock_photo
result = self.material_part.admin_thumbnail()
self.assertIn("/media/test.jpg", result)
self.assertIn("<img", result)
def test_admin_thumbnail_without_photo(self):
"""Test admin_thumbnail when no photo exists"""
self.material_part.photo = None
result = self.material_part.admin_thumbnail()
self.assertIn("kein Bild", result)
def test_ownership_overview(self):
"""Test ownership_overview method"""
Ownership.objects.create(material=self.material_part, owner=self.member, count=2)
result = self.material_part.ownership_overview()
self.assertIn(str(self.member), result)
self.assertIn("2", result)
def test_not_too_old(self):
"""Test not_too_old method"""
# Set a buy_date that makes the material old
old_date = date(2000, 1, 1)
self.material_part.buy_date = old_date
self.material_part.lifetime = Decimal('5')
result = self.material_part.not_too_old()
self.assertFalse(result)
class OwnershipTestCase(TestCase):
def setUp(self):
self.category = MaterialCategory.objects.create(name="Hardware")
self.material_part = MaterialPart.objects.create(
name="Carabiner Set",
description="Lightweight aluminum carabiners",
quantity=10,
buy_date=date(2021, 6, 1),
lifetime=Decimal('10')
)
self.member = Member.objects.create(
prename="Alice",
lastname="Smith",
birth_date=date(1985, 3, 15),
email="alice@example.com",
gender=FEMALE
)
self.ownership = Ownership.objects.create(
material=self.material_part,
owner=self.member,
count=6
)
def test_ownership_creation(self):
"""Test ownership record creation"""
self.assertEqual(self.ownership.material, self.material_part)
self.assertEqual(self.ownership.owner, self.member)
self.assertEqual(self.ownership.count, 6)
def test_material_part_relationship(self):
"""Test relationship between MaterialPart and Ownership"""
ownerships = Ownership.objects.filter(material=self.material_part)
self.assertEqual(ownerships.count(), 1)
self.assertEqual(ownerships.first(), self.ownership)
def test_str(self):
"""Test string representation of Ownership"""
result = str(self.ownership)
self.assertEqual(result, str(self.member))
class UtilityFunctionTestCase(TestCase):
def test_yearsago_with_from_date(self):
"""Test yearsago function with explicit from_date"""
test_date = timezone.make_aware(datetime(2020, 5, 15, 12, 0, 0))
result = yearsago(5, from_date=test_date)
expected = timezone.make_aware(datetime(2015, 5, 15, 12, 0, 0))
self.assertEqual(result, expected)
def test_yearsago_default_from_date(self):
"""Test yearsago function with default from_date (None)"""
# This will use timezone.now() internally
result = yearsago(1)
self.assertIsNotNone(result)
self.assertLess(result, timezone.now())
def test_yearsago_leap_year_edge_case(self):
"""Test yearsago function with leap year edge case (Feb 29)"""
# Feb 29, 2020 (leap year) minus 1 year should become Feb 28, 2019
leap_date = timezone.make_aware(datetime(2020, 2, 29, 12, 0, 0))
result = yearsago(1, from_date=leap_date)
expected = timezone.make_aware(datetime(2019, 2, 28, 12, 0, 0))
self.assertEqual(result, expected)
class NotTooOldFilterTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.filter = NotTooOldFilter(None, {}, MaterialPart, MaterialAdmin)
# Create test data
self.member = Member.objects.create(
prename="Test", lastname="User", birth_date=date(1990, 1, 1),
email="test@example.com", gender=MALE
)
# Create old material (should be too old)
self.old_material = MaterialPart.objects.create(
name="Old Material",
description="Old material",
quantity=1,
buy_date=date(2000, 1, 1), # Very old
lifetime=Decimal('5')
)
# Create new material (should not be too old)
self.new_material = MaterialPart.objects.create(
name="New Material",
description="New material",
quantity=1,
buy_date=date.today(), # Today
lifetime=Decimal('10')
)
def test_not_too_old_filter_lookups(self):
"""Test NotTooOldFilter lookups method"""
request = self.factory.get('/')
lookups = self.filter.lookups(request, None)
self.assertEqual(len(lookups), 2)
self.assertEqual(lookups[0][0], 'too_old')
self.assertEqual(lookups[1][0], 'not_too_old')
def test_not_too_old_filter_queryset_too_old(self):
"""Test NotTooOldFilter queryset method with 'too_old' value"""
request = self.factory.get('/?age=too_old')
self.filter.used_parameters = {'age': 'too_old'}
queryset = MaterialPart.objects.all()
filtered = self.filter.queryset(request, queryset)
# Should return materials that are not too old (i.e., new materials)
self.assertIn(self.new_material, filtered)
self.assertNotIn(self.old_material, filtered)
def test_not_too_old_filter_queryset_not_too_old(self):
"""Test NotTooOldFilter queryset method with 'not_too_old' value"""
request = self.factory.get('/?age=not_too_old')
self.filter.used_parameters = {'age': 'not_too_old'}
queryset = MaterialPart.objects.all()
filtered = self.filter.queryset(request, queryset)
# Should return materials that are too old
self.assertIn(self.old_material, filtered)
self.assertNotIn(self.new_material, filtered)
# Create your tests here.

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

@ -30,9 +30,8 @@ from django.shortcuts import render
from django.core.exceptions import PermissionDenied, ValidationError
from .pdf import render_tex, fill_pdf_form, merge_pdfs, serve_pdf, render_docx
from .excel import generate_group_overview, generate_ljp_vbk
from .models import WEEKDAYS
from contrib.admin import CommonAdminInlineMixin, CommonAdminMixin, decorate_admin_view
from contrib.admin import CommonAdminInlineMixin, CommonAdminMixin
import nested_admin
@ -42,10 +41,10 @@ from .models import (Member, Group, Freizeit, MemberNoteList, NewMemberOnList, K
KlettertreffAttendee, ActivityCategory, EmergencyContact,
annotate_activity_score, RegistrationPassword, MemberUnconfirmedProxy,
InvitationToGroup)
from finance.models import BillOnExcursionProxy, StatementOnExcursionProxy
from finance.models import Statement, BillOnExcursionProxy
from mailer.mailutils import send as send_mail, get_echo_link
from django.conf import settings
from utils import get_member, RestrictedFileField, mondays_until_nth
from utils import get_member, RestrictedFileField
from schwifty import IBAN
from .pdf import media_path, media_dir
@ -108,22 +107,15 @@ class PermissionOnMemberInline(admin.StackedInline):
class TrainingOnMemberInline(CommonAdminInlineMixin, admin.TabularInline):
model = MemberTraining
description = _("Please enter all training courses and further education courses that you have already attended or will be attending soon. Please also upload your confirmation of participation so that the responsible person can fill in the 'Attended' and 'Passed' fields. If the activity selection does not match your training, please describe it in the comment field.")
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 25})}
}
ordering = ("date",)
extra = 1
field_change_permissions = {
'participated': 'members.manage_success_trainings',
'passed': 'members.manage_success_trainings',
}
class EmergencyContactInline(CommonAdminInlineMixin, admin.TabularInline):
model = EmergencyContact
description = _('Please enter at least one emergency contact with contact details here. These are necessary for crisis intervention during trips.')
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40})}
}
@ -136,6 +128,44 @@ class TrainingCategoryAdmin(admin.ModelAdmin):
ordering = ('name', )
class RegistrationFilter(admin.SimpleListFilter):
title = _('Registration complete')
parameter_name = 'registration_complete'
default_value = ('All', None)
def lookups(self, request, model_admin):
return (
('True', _('True')),
('False', _('False')),
('All', _('All'))
)
def queryset(self, request, queryset):
if self.value() == 'True':
return queryset.filter(registration_complete=True)
elif self.value() == 'False':
return queryset.filter(registration_complete=False)
elif self.value() is None:
if self.default_value[1] is None:
return queryset
else:
return queryset.filter(registration_complete=self.default_value[1])
elif self.value() == 'All':
return queryset
def choices(self, cl):
for lookup, title in self.lookup_choices:
yield {
'selected':
self.value() == lookup or
(self.value() is None and lookup == self.default_value[0]),
'query_string': cl.get_query_string({
self.parameter_name:
lookup,
}, []),
'display': title
}
class MemberAdminForm(forms.ModelForm):
class Meta:
@ -165,6 +195,7 @@ class MemberAdmin(CommonAdminMixin, admin.ModelAdmin):
('join_date', 'leave_date'),
'comments',
'legal_guardians',
'dav_badge_no',
'active', 'echoed',
'user',
]
@ -182,8 +213,8 @@ class MemberAdmin(CommonAdminMixin, admin.ModelAdmin):
),
(_("Others"),
{
'fields': ['dav_badge_no', 'ticket_no', 'allergies', 'tetanus_vaccination',
'medication', 'photos_may_be_taken','may_cancel_appointment_independently']
'fields': ['allergies', 'tetanus_vaccination', 'medication', 'photos_may_be_taken',
'may_cancel_appointment_independently']
}
),
(_("Organizational"),
@ -209,7 +240,7 @@ class MemberAdmin(CommonAdminMixin, admin.ModelAdmin):
}
change_form_template = "members/change_member.html"
ordering = ('lastname',)
actions = ['request_echo', 'invite_as_user_action', 'unconfirm']
actions = ['request_echo', 'invite_as_user_action']
list_per_page = 25
form = MemberAdminForm
@ -300,8 +331,7 @@ class MemberAdmin(CommonAdminMixin, admin.ModelAdmin):
return request.user.has_perm('%s.%s' % (self.opts.app_label, 'may_invite_as_user'))
def invite_as_user_action(self, request, queryset):
if not request.user.has_perm('members.may_invite_as_user'): # pragma: no cover
# this should be unreachable, because of allowed_permissions attribute
if not request.user.has_perm('members.may_invite_as_user'):
messages.error(request, _('Permission denied.'))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
if "apply" in request.POST:
@ -379,12 +409,6 @@ class MemberAdmin(CommonAdminMixin, admin.ModelAdmin):
name_text_or_link.short_description = _('Name')
name_text_or_link.admin_order_field = 'lastname'
def unconfirm(self, request, queryset):
for member in queryset:
member.unconfirm()
messages.success(request, _("Successfully unconfirmed selected members."))
unconfirm.short_description = _('Unconfirm selected members.')
class DemoteToWaiterForm(forms.Form):
_selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
@ -433,8 +457,7 @@ class MemberUnconfirmedAdmin(CommonAdminMixin, admin.ModelAdmin):
}
),
]
list_display = ('name', 'birth_date', 'age', 'get_group', 'confirmed_mail', 'confirmed_alternative_mail',
'registration_form_uploaded')
list_display = ('name', 'birth_date', 'age', 'get_group', 'confirmed_mail', 'confirmed_alternative_mail')
search_fields = ('prename', 'lastname', 'email')
list_filter = ('group', 'confirmed_mail', 'confirmed_alternative_mail')
readonly_fields = ['confirmed_mail', 'confirmed_alternative_mail',
@ -488,15 +511,13 @@ class MemberUnconfirmedAdmin(CommonAdminMixin, admin.ModelAdmin):
notify_individual = len(queryset.all()) < 10
success = True
for member in queryset:
confirmed = member.confirm()
if not confirmed:
success = False
if notify_individual:
if confirmed:
messages.success(request, _("Successfully confirmed %(name)s.") % {'name': member.name})
else:
if member.confirm() and notify_individual:
messages.success(request, _("Successfully confirmed %(name)s.") % {'name': member.name})
else:
if notify_individual:
messages.error(request,
_("Can't confirm. %(name)s has unconfirmed email addresses.") % {'name': member.name})
success = False
if notify_individual:
return
if success:
@ -521,11 +542,6 @@ class MemberUnconfirmedAdmin(CommonAdminMixin, admin.ModelAdmin):
wrap(self.demote_to_waiter_view),
name="%s_%s_demote" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/request_registration_form/",
wrap(self.request_registration_form_view),
name="%s_%s_request_registration_form" % (self.opts.app_label, self.opts.model_name),
),
]
return custom_urls + urls
@ -558,18 +574,6 @@ class MemberUnconfirmedAdmin(CommonAdminMixin, admin.ModelAdmin):
member.demote_to_waiter()
messages.success(request, _("Successfully demoted %(name)s to waiter.") % {'name': member.name})
@decorate_admin_view(MemberUnconfirmedProxy)
def request_registration_form_view(self, request, member):
if "apply" in request.POST:
member.request_registration_form()
messages.success(request, _("Requested registration form for %(name)s.") % {'name': member.name})
return HttpResponseRedirect(reverse('admin:members_memberunconfirmedproxy_change', args=(member.pk,)))
context = dict(self.admin_site.each_context(request),
title=_('Request upload registration form'),
opts=self.opts,
member=member)
return render(request, 'admin/request_registration_form.html', context=context)
def response_change(self, request, member):
if "_confirm" in request.POST:
if member.confirm():
@ -592,7 +596,7 @@ class WaiterInviteTextForm(forms.Form):
widget=forms.Textarea(attrs={'rows': 30, 'cols': 100}))
class InvitationToGroupAdmin(CommonAdminInlineMixin, admin.TabularInline):
class InvitationToGroupAdmin(admin.TabularInline):
model = InvitationToGroup
fields = ['group', 'date', 'status']
readonly_fields = ['group', 'date', 'status']
@ -639,17 +643,13 @@ class MemberWaitingListAdmin(CommonAdminMixin, admin.ModelAdmin):
'confirmed_mail', 'waiting_confirmed', 'sent_reminders')
search_fields = ('prename', 'lastname', 'email')
list_filter = ['confirmed_mail', InvitedToGroupFilter, AgeFilter, 'gender']
actions = ['ask_for_registration_action', 'ask_for_wait_confirmation',
'request_mail_confirmation', 'request_required_mail_confirmation']
actions = ['ask_for_registration_action', 'ask_for_wait_confirmation']
inlines = [InvitationToGroupAdmin]
readonly_fields= ['application_date', 'sent_reminders']
def has_add_permission(self, request, obj=None):
return False
def has_action_permission(self, request):
return request.user.has_perm('members.change_global_memberwaitinglist')
def age(self, obj):
return obj.birth_date_delta
age.short_description=_('age')
@ -662,7 +662,6 @@ class MemberWaitingListAdmin(CommonAdminMixin, admin.ModelAdmin):
messages.success(request,
_("Successfully asked %(name)s to confirm their waiting status.") % {'name': waiter.name})
ask_for_wait_confirmation.short_description = _('Ask selected waiters to confirm their waiting status')
ask_for_wait_confirmation.allowed_permissions = ('action',)
def response_change(self, request, waiter):
ret = super(MemberWaitingListAdmin, self).response_change(request, waiter)
@ -672,20 +671,6 @@ class MemberWaitingListAdmin(CommonAdminMixin, admin.ModelAdmin):
args=(waiter.pk,)))
return ret
def request_mail_confirmation(self, request, queryset):
for member in queryset:
member.request_mail_confirmation()
messages.success(request, _("Successfully requested mail confirmation from selected waiters."))
request_mail_confirmation.short_description = _('Request mail confirmation from selected waiters.')
request_mail_confirmation.allowed_permissions = ('action',)
def request_required_mail_confirmation(self, request, queryset):
for member in queryset:
member.request_mail_confirmation(rerequest=False)
messages.success(request, _("Successfully re-requested missing mail confirmations from selected waiters."))
request_required_mail_confirmation.short_description = _('Re-request missing mail confirmations from selected waiters.')
request_required_mail_confirmation.allowed_permissions = ('action',)
def get_urls(self):
urls = super().get_urls()
@ -724,16 +709,10 @@ class MemberWaitingListAdmin(CommonAdminMixin, admin.ModelAdmin):
def ask_for_registration_action(self, request, queryset):
return self.invite_view(request, queryset)
ask_for_registration_action.short_description = _('Offer waiter a place in a group.')
ask_for_registration_action.allowed_permissions = ('action',)
def invite_view(self, request, object_id):
if type(object_id) == str:
try:
waiter = MemberWaitingList.objects.get(pk=object_id)
except MemberWaitingList.DoesNotExist:
messages.error(request,
_("A waiter with this ID does not exist."))
return HttpResponseRedirect(reverse('admin:members_memberwaitinglist_changelist'))
waiter = MemberWaitingList.objects.get(pk=object_id)
queryset = [waiter]
id_list = [waiter.pk]
else:
@ -777,8 +756,7 @@ class MemberWaitingListAdmin(CommonAdminMixin, admin.ModelAdmin):
_("An error occurred while trying to invite said members. Please try again."))
return HttpResponseRedirect(request.get_full_path())
for w in queryset:
w.invite_to_group(group, text_template=text_template,
creator=request.user.member if hasattr(request.user, 'member') else None)
w.invite_to_group(group, text_template=text_template)
messages.success(request,
_("Successfully invited %(name)s to %(group)s.") % {'name': w.name, 'group': w.invited_for_group.name})
@ -843,15 +821,13 @@ class GroupAdmin(CommonAdminMixin, admin.ModelAdmin):
return update_wrapper(wrapper, view)
custom_urls = [
path('action/', wrap(self.action_view), name='members_group_action'),
path('action/', self.action_view, name='members_group_action'),
]
return custom_urls + urls
def action_view(self, request):
if "group_overview" in request.POST:
return self.group_overview(request)
elif "group_checklist" in request.POST:
return self.group_checklist(request)
def group_overview(self, request):
@ -865,28 +841,6 @@ class GroupAdmin(CommonAdminMixin, admin.ModelAdmin):
response = serve_media(filename=filename, content_type='application/xlsx')
return response
def group_checklist(self, request):
if not request.user.has_perm('members.view_group'):
messages.error(request,
_("You are not allowed to create a group checklist."))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
ensure_media_dir()
n_weeks = settings.GROUP_CHECKLIST_N_WEEKS
n_members = settings.GROUP_CHECKLIST_N_MEMBERS
context = {
'groups': self.model.objects.filter(show_website=True),
'settings': settings,
'week_range': range(n_weeks),
'member_range': range(n_members),
'dates': mondays_until_nth(n_weeks),
'weekdays': [long for i, long in WEEKDAYS],
'header_text': settings.GROUP_CHECKLIST_TEXT,
}
return render_tex(f"Gruppen-Checkliste", 'members/group_checklist.tex', context)
class ActivityCategoryAdmin(admin.ModelAdmin):
@ -938,11 +892,10 @@ class StatementOnListForm(forms.ModelForm):
# of subsidies and allowance
self.fields['allowance_to'].queryset = excursion.jugendleiter.all()
self.fields['subsidy_to'].queryset = excursion.jugendleiter.all()
self.fields['ljp_to'].queryset = excursion.jugendleiter.all()
class Meta:
model = StatementOnExcursionProxy
fields = ['night_cost', 'allowance_to', 'subsidy_to', 'ljp_to']
model = Statement
fields = ['night_cost', 'allowance_to', 'subsidy_to']
def clean(self):
"""Check if the `allowance_to` and `subsidy_to` fields are compatible with
@ -959,11 +912,11 @@ class StatementOnListForm(forms.ModelForm):
class StatementOnListInline(CommonAdminInlineMixin, nested_admin.NestedStackedInline):
model = StatementOnExcursionProxy
model = Statement
extra = 1
description = _('Please list here all expenses in relation with this excursion and upload relevant bills. These have to be permanently stored for the application of LJP contributions. The short descriptions are used in the seminar report cost overview (possible descriptions are e.g. food, material, etc.).')
sortable_options = []
fields = ['night_cost', 'allowance_to', 'subsidy_to', 'ljp_to']
fields = ['night_cost', 'allowance_to', 'subsidy_to']
inlines = [BillOnExcursionInline]
form = StatementOnListForm
@ -1006,7 +959,7 @@ class MemberOnListInline(CommonAdminInlineMixin, GenericTabularInline):
}
sortable_options = []
template = "admin/members/freizeit/memberonlistinline.html"
def people_count(self, obj):
if isinstance(obj, Freizeit):
# Number of organizers who are also in the Memberlist
@ -1014,7 +967,7 @@ class MemberOnListInline(CommonAdminInlineMixin, GenericTabularInline):
# Total number of people in the Memberlist
total_people = obj.head_count
else: # fallback if no activity was found
total_people = 0
organizer_count = 0
@ -1029,6 +982,7 @@ class MemberOnListInline(CommonAdminInlineMixin, GenericTabularInline):
formset.organizer_count = self.people_count(obj)['organizer_count']
return formset
class MemberNoteListAdmin(admin.ModelAdmin):
@ -1079,8 +1033,7 @@ class MemberNoteListAdmin(admin.ModelAdmin):
if not self.may_view_notelist(request, memberlist):
return self.not_allowed_view(request, memberlist)
context = dict(memberlist=memberlist, settings=settings)
return render_tex(f"{memberlist.title}_Zusammenfassung", 'members/notelist_summary.tex', context,
date=memberlist.date)
return render_tex(f"{memberlist.title}_Zusammenfassung", 'members/notelist_summary.tex', context)
summary.short_description = _('Generate PDF summary')
@ -1173,9 +1126,7 @@ class FreizeitAdmin(CommonAdminMixin, nested_admin.NestedModelAdmin):
if not self.may_view_excursion(request, memberlist):
return self.not_allowed_view(request, memberlist)
context = dict(memberlist=memberlist, settings=settings)
return render_tex(f"{memberlist.code}_{memberlist.name}_Krisenliste",
'members/crisis_intervention_list.tex', context,
date=memberlist.date)
return render_tex(f"{memberlist.code}_{memberlist.name}_Krisenliste", 'members/crisis_intervention_list.tex', context)
crisis_intervention_list.short_description = _('Generate crisis intervention list')
def notes_list(self, request, memberlist):
@ -1183,9 +1134,7 @@ class FreizeitAdmin(CommonAdminMixin, nested_admin.NestedModelAdmin):
return self.not_allowed_view(request, memberlist)
people, skills = memberlist.skill_summary
context = dict(memberlist=memberlist, people=people, skills=skills, settings=settings)
return render_tex(f"{memberlist.code}_{memberlist.name}_Notizen",
'members/notes_list.tex', context,
date=memberlist.date)
return render_tex(f"{memberlist.code}_{memberlist.name}_Notizen", 'members/notes_list.tex', context)
notes_list.short_description = _('Generate overview')
@decorate_download
@ -1197,17 +1146,13 @@ class FreizeitAdmin(CommonAdminMixin, nested_admin.NestedModelAdmin):
def download_seminar_report_docx(self, request, memberlist):
title = memberlist.ljpproposal.title
context = dict(memberlist=memberlist, settings=settings)
return render_docx(f"{memberlist.code}_{title}_Seminarbericht",
'members/seminar_report_docx.tex', context,
date=memberlist.date)
return render_docx(f"{memberlist.code}_{title}_Seminarbericht", 'members/seminar_report_docx.tex', context)
@decorate_download
def download_seminar_report_costs_and_participants(self, request, memberlist):
title = memberlist.ljpproposal.title
context = dict(memberlist=memberlist, settings=settings)
return render_tex(f"{memberlist.code}_{title}_TN_Kosten",
'members/seminar_report.tex', context,
date=memberlist.date)
return render_tex(f"{memberlist.code}_{title}_TN_Kosten", 'members/seminar_report.tex', context)
def seminar_report(self, request, memberlist):
if not self.may_view_excursion(request, memberlist):
@ -1254,29 +1199,20 @@ class FreizeitAdmin(CommonAdminMixin, nested_admin.NestedModelAdmin):
context = memberlist.sjr_application_fields()
title = memberlist.ljpproposal.title if hasattr(memberlist, 'ljpproposal') else memberlist.name
return fill_pdf_form(f"{memberlist.code}_{title}_SJR_Antrag", 'members/sjr_template.pdf', context,
selected_attachments,
date=memberlist.date)
return fill_pdf_form(f"{memberlist.code}_{title}_SJR_Antrag", 'members/sjr_template.pdf', context, selected_attachments)
return self.render_sjr_options(request, memberlist, GenerateSjrForm(attachments=attachments))
sjr_application.short_description = _('Generate SJR application')
def finance_overview(self, request, memberlist):
if not hasattr(memberlist, 'statement'):
if not memberlist.statement:
messages.error(request, _("No statement found. Please add a statement and then retry."))
return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(memberlist.pk,)))
if "apply" in request.POST:
if not memberlist.statement.allowance_to_valid:
messages.error(request,
_("The configured recipients of the allowance don't match the regulations. Please correct this and try again."))
return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(memberlist.pk,)))
if memberlist.statement.ljp_to and len(memberlist.statement.bills_without_proof) > 0:
messages.error(request,
_("The excursion is configured to claim LJP contributions. In that case, for all bills, a proof must be uploaded. Please correct this and try again."))
return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(memberlist.pk,)))
memberlist.statement.submit(get_member(request))
messages.success(request,
_("Successfully submited statement. The finance department will notify you as soon as possible."))
@ -1286,7 +1222,8 @@ class FreizeitAdmin(CommonAdminMixin, nested_admin.NestedModelAdmin):
opts=self.opts,
memberlist=memberlist,
object=memberlist,
ljp_contributions=memberlist.payable_ljp_contributions,
participant_count=memberlist.participant_count,
ljp_contributions=memberlist.potential_ljp_contributions,
total_relative_costs=memberlist.total_relative_costs,
**memberlist.statement.template_context())
return render(request, 'admin/freizeit_finance_overview.html', context=context)
@ -1326,6 +1263,8 @@ class FreizeitAdmin(CommonAdminMixin, nested_admin.NestedModelAdmin):
def action_view(self, request, object_id):
if "sjr_application" in request.POST:
return self.sjr_application(request, Freizeit.objects.get(pk=object_id))
if "seminar_vbk" in request.POST:
return self.seminar_vbk(request, Freizeit.objects.get(pk=object_id))
if "seminar_report" in request.POST:
return self.seminar_report(request, Freizeit.objects.get(pk=object_id))
if "notes_list" in request.POST:
@ -1374,13 +1313,13 @@ class KlettertreffAdmin(admin.ModelAdmin):
inlines = [KlettertreffAttendeeInline]
list_display = ['__str__', 'date', 'get_jugendleiter']
search_fields = ('date', 'location', 'topic')
list_filter = [('date', DateFieldListFilter), 'group']
list_filter = [('date', DateFieldListFilter), 'group__name']
actions = ['overview']
def overview(self, request, queryset):
group = request.GET.get('group__id__exact')
group = request.GET.get('group__name')
if group != None:
members = Member.objects.filter(group=group)
members = Member.objects.filter(group__name__contains=group)
else:
members = Member.objects.all()
context = {
@ -1399,20 +1338,6 @@ class KlettertreffAdmin(admin.ModelAdmin):
# ForeignKey: {'widget': apply_select2(forms.Select)}
#}
class MemberTrainingAdminForm(forms.ModelForm):
class Meta:
model = MemberTraining
exclude = []
class MemberTrainingAdmin(CommonAdminMixin, nested_admin.NestedModelAdmin):
form = MemberTrainingAdminForm
list_display = ['title', 'member', 'date', 'category', 'get_activities', 'participated', 'passed', 'certificate']
search_fields = ['title']
list_filter = (('date', DateFieldListFilter), 'category', 'passed', 'activity', 'member')
ordering = ('-date',)
admin.site.register(Member, MemberAdmin)
admin.site.register(MemberUnconfirmedProxy, MemberUnconfirmedAdmin)
@ -1423,4 +1348,3 @@ admin.site.register(MemberNoteList, MemberNoteListAdmin)
admin.site.register(Klettertreff, KlettertreffAdmin)
admin.site.register(ActivityCategory, ActivityCategoryAdmin)
admin.site.register(TrainingCategory, TrainingCategoryAdmin)
admin.site.register(MemberTraining, MemberTrainingAdmin)

@ -1,227 +0,0 @@
from .models import * # pragma: no cover
import re # pragma: no cover
import csv # pragma: no cover
def import_from_csv(path, omit_groupless=True): # pragma: no cover
with open(path, encoding='ISO-8859-1') as csvfile:
reader = csv.DictReader(csvfile, delimiter=';')
rows = list(reader)
def transform_field(key, value):
new_key = CLUBDESK_TO_KOMPASS[key]
if isinstance(new_key, str):
return (new_key, value)
else:
return (new_key[0], new_key[1](value))
def transform_row(row):
kwargs = dict([ transform_field(k, v) for k, v in row.items() if k in CLUBDESK_TO_KOMPASS ])
kwargs_filtered = { k : v for k, v in kwargs.items() if k not in ['group', 'last_training', 'has_fundamental_training', 'special_training', 'phone_number_private', 'phone_number_parents'] }
if not kwargs['group'] and omit_groupless:
# if member does not have a group, skip them
return
mem = Member(**kwargs_filtered)
mem.save()
mem.group.set([group for group, is_jl in kwargs['group']])
for group, is_jl in kwargs['group']:
if is_jl:
group.leiters.add(mem)
if kwargs['has_fundamental_training']:
try:
ga_cat = TrainingCategory.objects.get(name='Grundausbildung')
except TrainingCategory.DoesNotExist:
ga_cat = TrainingCategory(name='Grundausbildung', permission_needed=True)
ga_cat.save()
ga_training = MemberTraining(member=mem, title='Grundausbildung', date=None, category=ga_cat,
participated=True, passed=True)
ga_training.save()
if kwargs['last_training'] is not None:
try:
cat = TrainingCategory.objects.get(name='Fortbildung')
except TrainingCategory.DoesNotExist:
cat = TrainingCategory(name='Fortbildung', permission_needed=False)
cat.save()
training = MemberTraining(member=mem, title='Unbekannt', date=kwargs['last_training'], category=cat,
participated=True, passed=True)
training.save()
if kwargs['special_training'] != '':
try:
cat = TrainingCategory.objects.get(name='Sonstiges')
except TrainingCategory.DoesNotExist:
cat = TrainingCategory(name='Sonstiges', permission_needed=False)
cat.save()
training = MemberTraining(member=mem, title=kwargs['special_training'], date=None, category=cat,
participated=True, passed=True)
training.save()
if kwargs['phone_number_private'] != '':
prefix = '\n' if mem.comments else ''
mem.comments += prefix + 'Telefon (Privat): ' + kwargs['phone_number_private']
mem.save()
if kwargs['phone_number_parents'] != '':
prefix = '\n' if mem.comments else ''
mem.comments += prefix + 'Telefon (Eltern): ' + kwargs['phone_number_parents']
mem.save()
for row in rows:
transform_row(row)
def parse_group(value): # pragma: no cover
groups_raw = re.split(',', value)
# need to determine if member is youth leader
roles = set()
def extract_group_name_and_role(raw):
obj = re.search('^(.*?)(?: \((.*)\))?$', raw)
is_jl = False
if obj.group(2) is not None:
roles.add(obj.group(2).strip())
if obj.group(2) == 'Jugendleiter*in':
is_jl = True
return (obj.group(1).strip(), is_jl)
group_names = [extract_group_name_and_role(raw) for raw in groups_raw if raw != '']
if "Jugendleiter*in" in roles:
group_names.append(('Jugendleiter', False))
groups = []
for group_name, is_jl in group_names:
try:
group = Group.objects.get(name=group_name)
except Group.DoesNotExist:
group = Group(name=group_name)
group.save()
groups.append((group, is_jl))
return groups
def parse_date(value): # pragma: no cover
if value == '':
return None
return datetime.strptime(value, '%d.%m.%Y').date()
def parse_datetime(value): # pragma: no cover
tz = pytz.timezone('Europe/Berlin')
if value == '':
return timezone.now()
return tz.localize(datetime.strptime(value, '%d.%m.%Y %H:%M:%S'))
def parse_status(value): # pragma: no cover
return value != "Passivmitglied"
def parse_boolean(value): # pragma: no cover
return value.lower() == "ja"
def parse_nullable_boolean(value): # pragma: no cover
if value == '':
return None
else:
return value.lower() == "ja"
def parse_gender(value): # pragma: no cover
if value == 'männlich':
return MALE
elif value == 'weiblich':
return FEMALE
else:
return DIVERSE
def parse_can_swim(value): # pragma: no cover
return True if len(value) > 0 else False
CLUBDESK_TO_KOMPASS = { # pragma: no cover
'Nachname': 'lastname',
'Vorname': 'prename',
'Adresse': 'street',
'PLZ': 'plz',
'Ort': 'town',
'Telefon Privat': 'phone_number_private',
'Telefon Mobil': 'phone_number',
'Adress-Zusatz': 'address_extra',
'Land': 'country',
'E-Mail': 'email',
'E-Mail Alternativ': 'alternative_email',
'Status': ('active', parse_status),
'Eintritt': ('join_date', parse_date),
'Austritt': ('leave_date', parse_date),
'Geburtsdatum': ('birth_date', parse_date),
'Geburtstag': ('birth_date', parse_date),
'Geschlecht': ('gender', parse_gender),
'Bemerkungen': 'comments',
'IBAN': 'iban',
'Vorlage Führungszeugnis': ('good_conduct_certificate_presented_date', parse_date),
'Letzte Fortbildung': ('last_training', parse_date),
'Grundausbildung': ('has_fundamental_training', parse_boolean),
'Besondere Ausbildung': 'special_training',
'[Gruppen]' : ('group', parse_group),
'Schlüssel': ('has_key', parse_boolean),
'Freikarte': ('has_free_ticket_gym', parse_boolean),
'DAV Ausweis Nr.': 'dav_badge_no',
'Schwimmabzeichen': ('swimming_badge', parse_can_swim),
'Kletterschein': 'climbing_badge',
'Felserfahrung': 'alpine_experience',
'Allergien': 'allergies',
'Medikamente': 'medication',
'Tetanusimpfung': 'tetanus_vaccination',
'Fotoerlaubnis': ('photos_may_be_taken', parse_boolean),
'Erziehungsberechtigte': 'legal_guardians',
'Darf sich allein von der Gruppenstunde abmelden':
('may_cancel_appointment_independently', parse_nullable_boolean),
'Mobil Eltern': 'phone_number_parents',
'Sonstiges': 'application_text',
'Erhalten am': ('application_date', parse_datetime),
'Angeschrieben von': 'contacted_by',
'Angeschrieben von ': 'contacted_by',
}
def import_from_csv_waitinglist(path): # pragma: no cover
with open(path, encoding='ISO-8859-1') as csvfile:
reader = csv.DictReader(csvfile, delimiter=';')
rows = list(reader)
def transform_field(key, value):
new_key = CLUBDESK_TO_KOMPASS[key]
if isinstance(new_key, str):
return (new_key, value)
else:
return (new_key[0], new_key[1](value))
def transform_field(key, value):
new_key = CLUBDESK_TO_KOMPASS[key]
if isinstance(new_key, str):
return (new_key, value)
else:
return (new_key[0], new_key[1](value))
def transform_row(row):
kwargs = dict([ transform_field(k, v) for k, v in row.items() if k in CLUBDESK_TO_KOMPASS ])
kwargs_filtered = { k : v for k, v in kwargs.items() if k in ['prename', 'lastname', 'email', 'birth_date', 'application_text', 'application_date'] }
mem = MemberWaitingList(gender=DIVERSE, **kwargs_filtered)
mem.save()
if kwargs['contacted_by']:
group_name = kwargs['contacted_by']
try:
group = Group.objects.get(name=group_name)
invitation = InvitationToGroup(group=group, waiter=mem)
invitation.save()
except Group.DoesNotExist:
pass
for row in rows:
transform_row(row)

@ -117,7 +117,7 @@ def generate_ljp_vbk(excursion):
sheet['D19'] = settings.SEKTION
sheet['G19'] = title
sheet['I19'] = f"von {excursion.date:%d.%m.%y} bis {excursion.end:%d.%m.%y}"
sheet['J19'] = excursion.ljp_duration
sheet['J19'] = excursion.duration
sheet['L19'] = f"{excursion.ljp_participant_count}"
sheet['H19'] = excursion.get_ljp_activity_category()
sheet['M19'] = f"{excursion.postcode}, {excursion.place}"
@ -127,8 +127,7 @@ def generate_ljp_vbk(excursion):
if hasattr(excursion, 'statement'):
sheet['Q19'] = f"{excursion.statement.total_theoretic}"
name = normalize_filename(f"{excursion.code}_{title}_LJP_V-BK_3.{excursion.ljpproposal.category}",
date=excursion.date)
name = normalize_filename(f"{excursion.code}_{title}_LJP_V-BK_3.{excursion.ljpproposal.category}")
filename = name + ".xlsx"
workbook.save(media_path(filename))
return filename

@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-10-10 18:31+0200\n"
"POT-Creation-Date: 2025-03-08 16:16+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@ -18,28 +18,21 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: members/admin.py members/models.py
msgid "Registration complete"
msgstr "Anmeldung vollständig"
#: members/admin.py
msgid ""
"Please enter all training courses and further education courses that you "
"have already attended or will be attending soon. Please also upload your "
"confirmation of participation so that the responsible person can fill in the "
"'Attended' and 'Passed' fields. If the activity selection does not match "
"your training, please describe it in the comment field."
msgstr ""
"Bitte trage alle Ausbildungen und Fortbildungen ein, die du bereits besucht "
"hast oder bald besuchst. Lade auch deine Teilnahmebestätigung hoch, damit "
"von der verantwortlichen Person die Felder 'Teilgenommen' und 'Bestanden' "
"gepflegt werden können. Wenn die Aktivitätsauswahl nicht zu deiner "
"Ausbildung passt, dann beschreibe sie im Kommentarfeld."
msgid "True"
msgstr "Ja"
#: members/admin.py
msgid ""
"Please enter at least one emergency contact with contact details here. These "
"are necessary for crisis intervention during trips."
msgstr ""
"Trage hier bitte mindestens einen Notfallkontakt mit Kontaktdaten ein. Diese "
"sind notwendig für die Krisenintervention auf Ausfahrten und bei "
"Veranstaltungen."
msgid "False"
msgstr "Nein"
#: members/admin.py members/tests.py
msgid "All"
msgstr "Alle"
#: members/admin.py
msgid "The entered IBAN is not valid."
@ -89,18 +82,18 @@ msgstr "%(name)s hat keine DAV360 E-Mail Adresse oder ist bereits registriert."
msgid "Successfully invited %(name)s as user."
msgstr "Erfolgreich %(name)s aufgefordert Zugangsdaten zu wählen."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "Successfully invited selected members to join as users."
msgstr ""
"Erfolgreich ausgewählte Teilnehmer*innen aufgefordert Zugangsdaten zu wählen."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "Some members have been invited, others could not be invited."
msgstr ""
"Manche Teilnehmer*innen wurden eingeladen, andere konnten nicht eingeladen "
"werden."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "Permission denied."
msgstr "Fehlende Berechtigungen."
@ -112,21 +105,21 @@ msgstr "Kompass Zugangsdaten wählen lassen"
msgid "Invite selected members to join Kompass as users."
msgstr "Ausgewählte Teilnehmer*innen Kompass Zugangsdaten wählen lassen."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "Member not found."
msgstr "Teilnehmer*in nicht gefunden."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
#, python-format
msgid "%(name)s already has login data."
msgstr "%(name)s hat schon Zugangsdaten."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
#, python-format
msgid "The configured email address for %(name)s is not an internal one."
msgstr "Die für %(name)s eingestellte E-Mail Adresse ist keine DAV360 Adresse."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
#, python-format
msgid "%(name)s already has a pending invitation as user."
msgstr ""
@ -140,17 +133,7 @@ msgstr "Aktivität"
msgid "Name"
msgstr "Name"
#: members/admin.py
msgid "Successfully unconfirmed selected members."
msgstr ""
"Ausgewählte Teilnehmer*innen zu unbestätigten Registrierungen zurückgesetzt."
#: members/admin.py
msgid "Unconfirm selected members."
msgstr ""
"Ausgewählte Teilnehmer*innen zu unbestätigten Registrierungen zurücksetzen."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "Successfully requested mail confirmation from selected registrations."
msgstr "Aufforderung zur Bestätigung der Email Adresse versendet."
@ -158,7 +141,7 @@ msgstr "Aufforderung zur Bestätigung der Email Adresse versendet."
msgid "Request mail confirmation from selected registrations"
msgstr "Aufforderung zur Bestätigung der Email Adresse versenden"
#: members/admin.py members/tests/basic.py
#: members/admin.py
msgid ""
"Successfully re-requested missing mail confirmations from selected "
"registrations."
@ -182,11 +165,11 @@ msgstr "Registrierung von %(name)s erfolgreich bestätigt."
msgid "Can't confirm. %(name)s has unconfirmed email addresses."
msgstr "Bestätigung nicht möglich. %(name)s hat unbestätigte Emailadressen."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "Successfully confirmed multiple registrations."
msgstr "Erfolgreich mehrere Registrierungen bestätigt."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid ""
"Failed to confirm some registrations because of unconfirmed email addresses."
msgstr ""
@ -201,7 +184,7 @@ msgstr "Ausgewählte Registrierungen bestätigen"
msgid "Demote selected registrations to waiters."
msgstr "Ausgewählte Registrierungen zurück auf die Warteliste setzen."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "Demote member to waiter"
msgstr "Ausgewählte Registrierung zurück auf die Warteliste setzen."
@ -210,15 +193,6 @@ msgstr "Ausgewählte Registrierung zurück auf die Warteliste setzen."
msgid "Successfully demoted %(name)s to waiter."
msgstr "%(name)s zurück auf die Warteliste gesetzt."
#: members/admin.py
#, python-format
msgid "Requested registration form for %(name)s."
msgstr "Anmeldeformular für %(name)s angefragt."
#: members/admin.py
msgid "Request upload registration form"
msgstr "Anmeldeformular anfragen"
#: members/admin.py members/models.py
msgid "Group"
msgstr "Gruppe"
@ -248,35 +222,10 @@ msgstr "Erfolgreich %(name)s aufgefordert den Wartelistenplatz zu bestätigen."
msgid "Ask selected waiters to confirm their waiting status"
msgstr "Wartende auffordern den Wartelistenplatz zu bestätigen"
#: members/admin.py
msgid "Successfully requested mail confirmation from selected waiters."
msgstr "Aufforderung zur Bestätigung der Email Adresse versendet."
#: members/admin.py
msgid "Request mail confirmation from selected waiters."
msgstr "Aufforderung zur Bestätigung der Email Adresse versenden"
#: members/admin.py
msgid ""
"Successfully re-requested missing mail confirmations from selected waiters."
msgstr ""
"Erinnerung zur Bestätigung von noch nicht bestätigten Email Adressen "
"versendet."
#: members/admin.py
msgid "Re-request missing mail confirmations from selected waiters."
msgstr ""
"Erinnerung zur Bestätigung von noch nicht bestätigten Email Adressen "
"versenden."
#: members/admin.py
msgid "Offer waiter a place in a group."
msgstr "Personen auf der Warteliste einen Gruppenplatz anbieten."
#: members/admin.py members/tests/basic.py
msgid "A waiter with this ID does not exist."
msgstr "Es existiert keine wartende Person mit dieser ID."
#: members/admin.py
msgid ""
"An error occurred while trying to invite said members. Please try again."
@ -317,11 +266,6 @@ msgid "You are not allowed to create a group overview."
msgstr ""
"Du hast nicht die notwendigen Rechte um eine Gruppenübersicht zu erstellen."
#: members/admin.py
msgid "You are not allowed to create a group checklist."
msgstr ""
"Du hast nicht die notwendigen Rechte um eine Gruppencheckliste zu erstellen."
#: members/admin.py
msgid "Difficulty"
msgstr "Schwierigkeit"
@ -395,11 +339,11 @@ msgstr "Übersicht erstellen"
msgid "Invoice"
msgstr "Beleg"
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "Excursion not found."
msgstr "Ausfahrt nicht gefunden."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid ""
"This excursion does not have a LJP proposal. Please add one and try again."
msgstr ""
@ -428,7 +372,7 @@ msgstr ""
"nicht sichtbar für Standardbenutzer*innen, nur der Genehmigungszustand wird "
"in der Übersicht alle Ausfahrten angezeigt."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
#, python-format
msgid "You are not allowed to view all members on excursion %(name)s."
msgstr ""
@ -451,17 +395,17 @@ msgstr "Landesjugendplan Antrag erstellen"
msgid "Generate SJR application"
msgstr "SJR Antrag erstellen"
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "Please select an invoice."
msgstr "Bitte wähle einen Beleg aus."
#: members/admin.py members/tests/basic.py
#: members/admin.py members/tests.py
msgid "No statement found. Please add a statement and then retry."
msgstr ""
"Keine Abrechnung angelegt. Bitte lege eine Abrechnung and und versuche es "
"erneut."
#: members/admin.py members/tests/basic.py
#: members/admin.py
msgid ""
"The configured recipients of the allowance don't match the regulations. "
"Please correct this and try again."
@ -469,15 +413,6 @@ msgstr ""
"Die ausgewählten Empfänger*innen der Aufwandsentschädigung stimmen nicht mit "
"den Richtlinien überein. Bitte korrigiere das und versuche es erneut. "
#: members/admin.py members/tests/basic.py
msgid ""
"The excursion is configured to claim LJP contributions. In that case, for "
"all bills, a proof must be uploaded. Please correct this and try again."
msgstr ""
"Für die Ausfahrt werden LJP-Zuschüsse beantragt. Dafür müssen für alle "
"Ausgaben Belege hochgeladen werden. Bitte lade für alle Ausgaben einen Beleg "
"hoch und versuche es erneut. "
#: members/admin.py
msgid ""
"Successfully submited statement. The finance department will notify you as "
@ -611,15 +546,6 @@ msgstr "Gruppe"
msgid "groups"
msgstr "Gruppen"
#: members/models.py
#, python-format
msgid "years %(from)s to %(to)s"
msgstr "Jahrgang %(from)s bis %(to)s"
#: members/models.py
msgid "no information available"
msgstr "keine Angabe"
#: members/models.py
msgid "prename"
msgstr "Vorname"
@ -700,10 +626,6 @@ msgstr "Hat Freikarte für Kletterhalle"
msgid "DAV badge number"
msgstr "DAV Mitgliedsnummer"
#: members/models.py
msgid "entrance ticket number"
msgstr "Eintrittskarten Nummer"
#: members/models.py
msgid "Knows how to swim"
msgstr "Kann schwimmen"
@ -788,10 +710,6 @@ msgstr ""
msgid "Good conduct certificate valid"
msgstr "Führungszeugnis gültig"
#: members/models.py
msgid "Registration complete"
msgstr "Anmeldung vollständig"
#: members/models.py
msgid "member"
msgstr "Teilnehmer*in"
@ -800,10 +718,6 @@ msgstr "Teilnehmer*in"
msgid "members"
msgstr "Teilnehmer*innen"
#: members/models.py
msgid "Registration form"
msgstr "Anmeldeformular"
#: members/models.py
msgid "Upload registration form"
msgstr "Anmeldeformular hochladen"
@ -849,10 +763,6 @@ msgstr "Einladungsdatum"
msgid "Invitation rejected"
msgstr "Einladung abgelehnt"
#: members/models.py
msgid "Created by"
msgstr "Erstellt von"
#: members/models.py
msgid "Invitation to group"
msgstr "Gruppeneinladung"
@ -861,15 +771,15 @@ msgstr "Gruppeneinladung"
msgid "Invitations to groups"
msgstr "Gruppeneinladungen"
#: members/models.py members/tests/basic.py
#: members/models.py
msgid "Rejected"
msgstr "Abgelehnt"
#: members/models.py members/tests/basic.py
#: members/models.py
msgid "Expired"
msgstr "Abgelaufen"
#: members/models.py members/tests/basic.py
#: members/models.py
msgid "Undecided"
msgstr "Ausstehend"
@ -877,25 +787,6 @@ msgstr "Ausstehend"
msgid "Status"
msgstr "Status"
#: members/models.py
#, python-format
msgid "%(waiter)s left the waiting list"
msgstr "%(waiter)s hat die Warteliste verlassen"
#: members/models.py
#, python-format
msgid "Group invitation rejected by %(waiter)s"
msgstr "Einladung zur Schnupperstunde von %(waiter)s abgelehnt"
#: members/models.py
#, python-format
msgid "Group invitation confirmed by %(waiter)s"
msgstr "Teilnahme an Schnupperstunde von %(waiter)s bestätigt"
#: members/models.py
msgid "Trial group meeting confirmed"
msgstr "Teilnahme an Schnupperstunde bestätigt"
#: members/models.py
msgid "Do you want to tell us something else?"
msgstr "Möchtest du uns noch etwas mitteilen?"
@ -1035,16 +926,6 @@ msgstr "Ausfahrt"
msgid "Excursions"
msgstr "Ausfahrten"
#: members/models.py
#, python-format
msgid "Crisis intervention list for %(excursion)s from %(start)s to %(end)s"
msgstr "Kriseninterventionsliste für %(excursion)s vom %(start)s bis %(end)s"
#: members/models.py
#, python-format
msgid "Participant list for %(excursion)s from %(start)s to %(end)s"
msgstr "Teilnehmendenliste für %(excursion)s vom %(start)s bis %(end)s"
#: members/models.py
msgid "Title"
msgstr "Titel"
@ -1229,11 +1110,11 @@ msgstr "Darf Teilnehmer*innen folgender Gruppen ändern"
msgid "May delete members of groups"
msgstr "Darf Teilnehmer*innen folgender Gruppen löschen"
#: members/models.py members/tests/basic.py
#: members/models.py
msgid "Permissions"
msgstr "Berechtigungen"
#: members/models.py members/tests/basic.py
#: members/models.py
msgid "Group permissions"
msgstr "Gruppenberechtigungen"
@ -1265,10 +1146,6 @@ msgstr "Bestanden"
msgid "certificate of attendance"
msgstr "Teilnahmebestätigung"
#: members/models.py
msgid "(no date)"
msgstr "(ohne Datum)"
#: members/models.py
msgid "Training"
msgstr "Fortbildung"
@ -1286,25 +1163,19 @@ msgstr "Fortbildungen"
#: members/templates/admin/invite_for_group_text.html
#: members/templates/admin/invite_selected_as_user.html
#: members/templates/admin/invite_selected_for_group.html
#: members/templates/admin/request_registration_form.html
#: members/templates/admin/request_registratoin_form.html
msgid "Home"
msgstr "Start"
#: members/templates/admin/demote_to_waiter.html
#: members/templates/admin/request_registration_form.html
#: members/templates/admin/request_registratoin_form.html
msgid "Demote to waiter"
msgstr "Zurück auf die Warteliste setzen"
#: members/templates/admin/demote_to_waiter.html
#: members/templates/admin/request_registratoin_form.html
msgid ""
"Do you want to demote the following unconfirmed registrations to waiters?"
msgstr "Möchtest du die folgenden Personen zurück auf die Warteliste setzen?"
#: members/templates/admin/demote_to_waiter.html
#: members/templates/admin/request_registratoin_form.html
msgid "Demote"
msgstr "Zurück auf die Warteliste setzen"
@ -1315,8 +1186,6 @@ msgstr "Zurück auf die Warteliste setzen"
#: members/templates/admin/invite_for_group.html
#: members/templates/admin/invite_selected_as_user.html
#: members/templates/admin/invite_selected_for_group.html
#: members/templates/admin/request_registration_form.html
#: members/templates/admin/request_registratoin_form.html
msgid "Cancel"
msgstr "Abbrechen"
@ -1443,24 +1312,6 @@ msgstr ""
"Keine Empfänger*innen für Sektionszuschüsse angegeben. Es werden daher keine "
"Sektionszuschüsse ausbezahlt."
#: members/templates/admin/freizeit_finance_overview.html
msgid "Org fee"
msgstr "Organisationsbeitrag"
#: members/templates/admin/freizeit_finance_overview.html
#, python-format
msgid ""
"Warning: %(old_participant_count)s participant(s) of the excursion are 27 or "
"older. For each of them, an organisation fee of %(org_fee)s € per day has to "
"be paid to the account. With a duration of %(duration)s days, a total of "
"%(total_org_fee_theoretical)s € is charged against the other transactions."
msgstr ""
"Achtung: %(old_participant_count)s Teilnehmende der Ausfahrt sind 27 oder "
"älter. Für diese Teilnehmende(n) ist ein Org-Beitrag von %(org_fee)s € pro "
"Tag fällig. Durch die Länge der Ausfahrt von %(duration)s Tagen werden "
"insgesamt %(total_org_fee_theoretical)s € mit den Zuschüssen und "
"Aufwandsentschädigungen verrechnet, sofern diese in Anspruch genommen werden."
#: members/templates/admin/freizeit_finance_overview.html
msgid ""
"Warning: The configured recipients of the allowance don't match the "
@ -1476,82 +1327,29 @@ msgstr ""
msgid "LJP contributions"
msgstr "LJP Zuschüsse"
#: members/templates/admin/freizeit_finance_overview.html
#, python-format
msgid ""
"By submitting the given seminar report, you will receive LJP contributions.\n"
"You have documented interventions worth of %(total_seminar_days)s seminar "
"days for %(participant_count)s participants.\n"
"This results in a total contribution of %(ljp_contributions)s€.\n"
"To receive them, you need to submit the LJP-Proposal within 3 weeks after "
"your excursion and have it approved by the finance office."
msgstr ""
"Wenn du den erstellten LJP-Antrag einreichst, erhältst du LJP-Zuschüsse. Du "
"hast Lehreinheiten für insgesamt %(total_seminar_days)s Seminartage und für "
"%(participant_count)s Teilnehmende dokumentiert.\n"
"Daraus ergibt sich ein auszahlbarer LJP-Zuschuss von %(ljp_contributions)s€. "
"Um den zu erhalten, musst du den LJP-Antrag innerhalb von 3 Wochen nach der "
"Ausfahrt beim Jugendreferat einreichen und formal genehmigt bekommen."
#: members/templates/admin/freizeit_finance_overview.html
msgid "Seminar hours"
msgstr "Seminar-Stunden"
#: members/templates/admin/freizeit_finance_overview.html
msgid "Seminar days"
msgstr "Seminar-Tage"
#: members/templates/admin/freizeit_finance_overview.html
msgid "Sum"
msgstr "Summe"
#: members/templates/admin/freizeit_finance_overview.html
msgid "The LJP contributions are configured to be paid to:"
msgstr "Die LJP-Zuschüsse werden ausgezahlt an:"
#: members/templates/admin/freizeit_finance_overview.html
#, python-format
msgid ""
"By submitting a seminar report, you may apply for LJP contributions. In this "
"case,\n"
"you may obtain up to 25€ times %(duration)s days for "
"%(theoretic_ljp_participant_count)s participants but only up to\n"
"90%% of the total costs. This results in a total of %(ljp_contributions)s€. "
"If you have created a seminar report, you need to specify who should receive "
"the contributions in order to make use of them."
"you may obtain up to 25€ times %(duration)s days for %(participant_count)s "
"participants but only up to\n"
"90%% of the total costs. This results in a total of %(ljp_contributions)s€."
msgstr ""
"Indem du einen Seminarbericht anfertigst, kannst du Landesjugendplan (LJP) "
"Zuschüsse beantragen. In diesem Fall kannst du bis zu 25€ mal %(duration)s "
"Tage für %(theoretic_ljp_participant_count)s Teilnehmende, aber nicht mehr "
"als 90%% der Gesamtausgaben erhalten. Das resultiert in einem Gesamtzuschuss "
"von %(ljp_contributions)s€. Wenn du schon einen Seminarbericht erstellt "
"hast, musst du im Tab 'Abrechnungen' noch angeben, an wen die LJP-Zuschüsse "
"ausgezahlt werden sollen."
#: members/templates/admin/freizeit_finance_overview.html
#, python-format
msgid ""
" Warning: LJP contributions can only be claimed for activities with at least "
"5 participants and one leader. This activity currently has only "
"%(theoretic_ljp_participant_count)s participants."
msgstr ""
"Achtung: Nur für Aktivitäten mit mindestens 5 Teilnehmenden und einer "
"Leitungsperson kann ein LJP-Antrag gestellt werden. Diese Ausfahrt hat "
"aktuell nur %(theoretic_ljp_participant_count)s Teilnehmende."
"Tage für %(participant_count)s Teilnehmende, aber nicht mehr als 90%% der "
"Gesamtausgaben erhalten. Das resultiert in einem Gesamtzuschuss von "
"%(ljp_contributions)s€."
#: members/templates/admin/freizeit_finance_overview.html
msgid "Summary"
msgstr "Zusammenfassung"
#: members/templates/admin/freizeit_finance_overview.html
#: members/tests/basic.py
#: members/templates/admin/freizeit_finance_overview.html members/tests.py
msgid "This is the estimated cost and contribution summary:"
msgstr "Das ist die geschätzte Kosten- und Zuschussübersicht."
#: members/templates/admin/freizeit_finance_overview.html
msgid "Organisation fees"
msgstr "Org-Beitrag"
#: members/templates/admin/freizeit_finance_overview.html
msgid "Potential LJP contributions"
msgstr "Mögliche LJP Zuschüsse"
@ -1640,7 +1438,7 @@ msgstr ""
"notwendig. Aus den Informationen, die du in der Ausfahrt angegeben hast, "
"kann automatisch ein solcher Antrag erstellt werden."
#: members/templates/admin/generate_seminar_report.html members/tests/basic.py
#: members/templates/admin/generate_seminar_report.html members/tests.py
msgid "A seminar report consists of multiple components:"
msgstr "Ein LJP Antrag besteht aus verschiedenen Komponenten:"
@ -1675,7 +1473,7 @@ msgstr ""
"Eine Kosten- und Teilnehmendenübersicht. Dies ist nicht notwendig für den "
"eigentlichen Bericht, muss aber langfristig aufbewahrt werden."
#: members/templates/admin/generate_sjr_application.html members/tests/basic.py
#: members/templates/admin/generate_sjr_application.html members/tests.py
msgid "Here you can generate an allowance application for the SJR."
msgstr "Hier kannst du einen SJR-Zuschussantrag erstellen."
@ -1712,8 +1510,7 @@ msgstr ""
#: members/templates/admin/invite_as_user.html
#: members/templates/admin/invite_for_group.html
#: members/templates/admin/invite_selected_as_user.html
#: members/templates/admin/invite_selected_for_group.html
#: members/tests/basic.py
#: members/templates/admin/invite_selected_for_group.html members/tests.py
msgid "Invite"
msgstr "Einladen"
@ -1824,21 +1621,6 @@ msgstr "Anzahl Personen:"
msgid "thereof leaders:"
msgstr "davon Leitung:"
#: members/templates/admin/request_registration_form.html
#: members/tests/basic.py
msgid "Request registration form"
msgstr "Anmeldeformular anfragen"
#: members/templates/admin/request_registration_form.html
#, python-format
msgid "Do you want to ask %(member)s to upload their registration form?"
msgstr "Möchtest du %(member)s auffordern das Anmeldeformular hochzuladen?"
#: members/templates/admin/request_registration_form.html
#, python-format
msgid "Warning: %(member)s has already uploaded a registration form."
msgstr "Warnung: %(member)s hat bereits ein Anmeldeformular hochgeladen."
#: members/templates/members/change_member.html
msgid "Participations:"
msgstr "Ausfahrtteilnahmen:"
@ -1855,80 +1637,21 @@ msgstr "Fähigkeitsniveau"
msgid "Save and confirm registration"
msgstr "Speichern und Registrierung bestätigen"
#: members/templates/members/confirm_invalid.html
msgid "Confirm invitation"
msgstr "Teilnahme bestätigen"
#: members/templates/members/confirm_invalid.html
#: members/templates/members/reject_invalid.html members/tests/basic.py
#: members/tests/views.py
msgid "This invitation is invalid or expired."
msgstr "Diese Einladung ist ungültig oder abgelaufen."
#: members/templates/members/confirm_invitation.html members/tests/views.py
msgid "Confirm trial group meeting invitation"
msgstr "Teilnahme bestätigen"
#: members/templates/members/confirm_invitation.html
#, python-format
msgid "You were invited to a trial group meeting of the group %(groupname)s."
msgstr ""
"Du wurdest zu einer Schnupperstunde in der Gruppe %(groupname)s eingeladen."
#: members/templates/members/confirm_invitation.html
msgid ""
"Do you want to take part in the trial group meeting? If yes, please confirm "
"your attendance by clicking on the following button."
msgstr ""
"Möchtest du an der Schnupperstunde teilnehmen? Falls ja, bitte bestätige "
"deine Teilnahme durch das Betätigen des folgenden Knopfes."
#: members/templates/members/confirm_invitation.html
msgid "Confirm trial group meeting"
msgstr "Teilnahme bestätigen"
#: members/templates/members/confirm_success.html members/tests/views.py
msgid "Invitation confirmed"
msgstr "Teilnahme bestätigt"
#: members/templates/members/confirm_success.html
#, python-format
msgid ""
"You successfully confirmed the invitation to the trial group meeting of the "
"group %(groupname)s."
msgstr ""
"Deine Teilnahme an der Schnupperstunde der Gruppe %(groupname)s wurde "
"erfolgreich bestätigt."
#: members/templates/members/confirm_success.html
msgid ""
"We have informed the group leaders about your confirmation. If for some "
"reason you can not make it,\n"
"please contact the group leaders at"
msgstr ""
"Wir haben die Jugendleiter*innen der Jugendgruppe über deine Bestätigung "
"informiert. Falls du doch nicht zur Schnupperstunde kommen kannst, "
"informiere bitte die Jugendleiter*innen unter"
#: members/templates/members/echo.html
#: members/templates/members/echo_failed.html
#: members/templates/members/echo_password.html
#: members/templates/members/echo_success.html
#: members/templates/members/echo_wrong_password.html
#: members/templates/members/upload_registration_form.html
#: members/templates/members/upload_registration_form_success.html
msgid "Echo"
msgstr "Rückmeldung"
#: members/templates/members/echo.html members/tests/basic.py
msgid ""
"Here is your current data. Please check if it is up to date and change "
"accordingly."
#: members/templates/members/echo.html members/tests.py
msgid "Thanks for echoing back. Here is your current data:"
msgstr ""
"Hier siehst du deine aktuellen Daten. Bitte überprüfe alles und passe es bei "
"Bedarf an."
"Vielen Dank, dass du dich rückmeldest. Hier siehst du deine aktuellen Daten. "
"Falls sich etwas geändert hat, trage das bitte hier ein."
#: members/templates/members/echo_failed.html members/tests/basic.py
#: members/templates/members/echo_failed.html members/tests.py
msgid "Echo failed"
msgstr "Rückmeldung fehlgeschlagen"
@ -1949,7 +1672,7 @@ msgstr "Wenn du denkst, dass das ein Fehler ist, "
msgid "contact us."
msgstr "kontaktiere uns."
#: members/templates/members/echo_password.html members/tests/basic.py
#: members/templates/members/echo_password.html members/tests.py
msgid ""
"Thanks for echoing back. Please enter the password, which you can find in "
"the email we sent you.\n"
@ -1971,7 +1694,7 @@ msgstr "Rückmeldung erfolgreich"
msgid "Thank you"
msgstr "Danke"
#: members/templates/members/echo_success.html members/tests/basic.py
#: members/templates/members/echo_success.html members/tests.py
msgid "Your data was successfully updated."
msgstr "Deine Daten wurden erfolgreich aktualisiert."
@ -1982,7 +1705,7 @@ msgstr ""
"Jugendleiter nach einem korrekten Passwort."
#: members/templates/members/invited_registration_failed.html
#: members/templates/members/register_failed.html members/tests/basic.py
#: members/templates/members/register_failed.html
msgid "Registration failed"
msgstr "Registrierung fehlgeschlagen"
@ -1998,7 +1721,7 @@ msgstr "Registrierung fehlgeschlagen"
msgid "Registration"
msgstr "Registrierung"
#: members/templates/members/leave_waitinglist.html members/tests/basic.py
#: members/templates/members/leave_waitinglist.html members/tests.py
msgid "Leave waitinglist"
msgstr "Warteliste verlassen"
@ -2015,8 +1738,7 @@ msgstr ""
msgid "Yes, leave the waitinglist"
msgstr "Ja, Warteliste verlassen"
#: members/templates/members/leave_waitinglist_success.html
#: members/tests/basic.py
#: members/templates/members/leave_waitinglist_success.html members/tests.py
msgid "Left waitinglist"
msgstr "Warteliste verlassen"
@ -2031,19 +1753,16 @@ msgstr ""
"einem späteren Zeitpunkt wieder auf die Warteliste setzen lassen möchtest "
"kannst du das auf unserer Webseite machen.\n"
#: members/templates/members/mail_confirmation_invalid.html
#: members/tests/basic.py
#: members/templates/members/mail_confirmation_invalid.html members/tests.py
msgid "Mail confirmation failed"
msgstr "Emailbestätigung fehlgeschlagen"
#: members/templates/members/mail_confirmation_invalid.html
#: members/templates/members/waiting_confirmation_invalid.html
#: members/tests/basic.py
#: members/templates/members/waiting_confirmation_invalid.html members/tests.py
msgid "The supplied link is invalid."
msgstr "Der verwendete Link ist ungültig."
#: members/templates/members/mail_confirmation_success.html
#: members/tests/basic.py
#: members/templates/members/mail_confirmation_success.html members/tests.py
msgid "Mail confirmed"
msgstr "Emailadresse bestätigt"
@ -2116,7 +1835,7 @@ msgstr "Registrieren"
msgid "Here you can register for group"
msgstr "Hier kannst du dich registrieren für die Gruppe"
#: members/templates/members/register_failed.html members/tests/basic.py
#: members/templates/members/register_failed.html members/tests.py
msgid "Something went wrong while processing your registration."
msgstr "Etwas ist schief gelaufen, bei der Verarbeitung deiner Registrierung."
@ -2179,7 +1898,7 @@ msgid "Registration for waiting list."
msgstr "Registrierung für die Warteliste."
#: members/templates/members/register_waiting_list_success.html
#: members/tests/basic.py
#: members/tests.py
msgid "Your registration for the waiting list was successful."
msgstr "Du wurdest auf die Warteliste gesetzt."
@ -2205,6 +1924,10 @@ msgstr ""
msgid "Reject invitation"
msgstr "Einladung ablehnen"
#: members/templates/members/reject_invalid.html members/tests.py
msgid "This invitation is invalid or expired."
msgstr "Diese Einladung ist ungültig oder abgelaufen."
#: members/templates/members/reject_invitation.html
#, python-format
msgid ""
@ -2245,24 +1968,6 @@ msgstr ""
"abgelehnt. Wenn ein Platz in einer anderen Gruppe frei wird, erhältst du "
"eine neue Einladung.\n"
#: members/templates/members/upload_registration_form.html
#, python-format
msgid ""
"Thank you for echoing back, your data was updated. For legal\n"
"reasons, we also need a signed participation form. In your case, a recent\n"
"participation form is missing. Please <a href=\"%(download_url)s?"
"key=%(key)s\">download</a>\n"
"the pre-filled form, fill in the remaining fields and read the general "
"conditions. If you agree,\n"
"please sign the document and upload a scan or image here."
msgstr ""
"Danke für das Aktualisieren deiner Daten. Aus rechtlichen Gründen, benötigen "
"wir zusätzlich ein schriftliches Anmeldeformular. Für dich liegt uns kein "
"aktuelles Formular vor. Bitte <a href=\"%(download_url)s?key=%(key)s\">lade "
"das Formular herunter</a>, fülle die verbleibenden Felder aus und lese "
"unsere Teilnahmebedingungen. Falls du zustimmst, unterschreibe bitte das "
"Formular und lade hier einen Scan oder ein Bild hoch."
#: members/templates/members/upload_registration_form.html
#, python-format
msgid ""
@ -2277,8 +1982,7 @@ msgstr ""
"zustimmst, unterschreibe bitte das Formular und lade hier einen Scan oder "
"ein Bild hoch."
#: members/templates/members/upload_registration_form.html
#: members/tests/basic.py
#: members/templates/members/upload_registration_form.html members/tests.py
msgid ""
"If you are not an adult yet, please let someone responsible for you sign the "
"agreement."
@ -2291,20 +1995,18 @@ msgid "Upload"
msgstr "Hochladen"
#: members/templates/members/upload_registration_form_invalid.html
#: members/tests/basic.py
#: members/tests.py
msgid "The supplied key for uploading a registration form is invalid."
msgstr "Der verwendete Link zum Hochladen eines Anmeldeformulars ist ungültig."
#: members/templates/members/upload_registration_form_success.html
msgid "Thank you for uploading the registration form."
msgstr "Danke für das Hochladen des Anmeldeformulars."
#: members/templates/members/upload_registration_form_success.html
#: members/tests/basic.py
msgid "Our team will process your registration shortly."
#: members/tests.py
msgid ""
"Thank you for uploading the registration form. Our team will process your "
"registration shortly."
msgstr ""
"Unser Jugendleiter*innenteam wird deine Registrierung so schnell wie möglich "
"bearbeiten."
"Danke für das Hochladen des Anmeldeformulars. Unser Jugendleiterteam wird "
"deine Registrierung so schnell wie möglich bearbeiten."
#: members/templates/members/waiting_confirmation_invalid.html
msgid "Waiting confirmation failed"
@ -2318,13 +2020,11 @@ msgstr ""
"Leider hast du deinen Wartelistenplatz nicht rechtzeitig bestätigt und hast "
"somit deinen Platz verloren. Du kannst"
#: members/templates/members/waiting_confirmation_invalid.html
#: members/tests/basic.py
#: members/templates/members/waiting_confirmation_invalid.html members/tests.py
msgid "rejoin the waiting list"
msgstr "der Warteliste erneut beitreten"
#: members/templates/members/waiting_confirmation_success.html
#: members/tests/basic.py
#: members/templates/members/waiting_confirmation_success.html members/tests.py
msgid "Waiting confirmed"
msgstr "Wartelistenplatz bestätigt"
@ -2346,23 +2046,19 @@ msgstr ""
"Danke %(prename)s für dein Interesse auf der Warteliste zu bleiben.\n"
"Dein Platz wurde bestätigt."
#: members/tests/basic.py
msgid "Insufficient permissions."
msgstr "Unzureichende Berechtigungen."
#: members/tests/basic.py
#: members/tests.py
msgid "This field is required."
msgstr ""
#: members/tests/basic.py members/views.py
#: members/tests.py members/views.py
msgid "The entered password is wrong."
msgstr "Das eingegebene Passwort ist falsch."
#: members/tests/basic.py members/views.py
#: members/tests.py members/views.py
msgid "invalid"
msgstr "ungültig"
#: members/tests/basic.py members/views.py
#: members/tests.py members/views.py
msgid "expired"
msgstr "abgelaufen"
@ -2392,22 +2088,6 @@ msgstr "Optionale zusätzliche E-Mailadresse"
msgid "Invalid emergency contacts"
msgstr "Ungültige Notfallkontakte"
#~ msgid "True"
#~ msgstr "Ja"
#~ msgid "False"
#~ msgstr "Nein"
#~ msgid "All"
#~ msgstr "Alle"
#~ msgid "Inform youth leaders about sending of crisis intervention list."
#~ msgstr ""
#~ "Informiere Jugendleiter:innen über Versand der Kriseninterventionsliste."
#~ msgid "Send crisis intervention list."
#~ msgstr "Kriseninterventionsliste verschicken"
#~ msgid "You may also choose to include the V32 attachment."
#~ msgstr ""
#~ "Ein LJP Antrag benötigt immer ein Formblatt (in unserem Fall V32-1 "
@ -2542,6 +2222,14 @@ msgstr "Ungültige Notfallkontakte"
#~ msgid "Good conduct certificate presentation needed"
#~ msgstr "Vorlage Führungszeugnis notwendig"
#, python-format
#~ msgid ""
#~ "Do you want to reject the invitation to a trial group meeting of the\n"
#~ "group %(invitation.group.name)s?"
#~ msgstr ""
#~ "Möchtest du die Einladung zur Schnupperstunde bei der Gruppe "
#~ "%(invitation.group.name)s wirklich ablehnen?"
#~ msgid "Yes, reject invitation"
#~ msgstr "Ja, Einladung ablehnen."

@ -83,7 +83,7 @@ def create_group_with_perms(apps, schema_editor, name, perm_names):
Group = apps.get_model("auth", "Group")
Permission = apps.get_model("auth", "Permission")
if Group.objects.filter(name=name).exists():
raise ValueError("A group with name %s already exists." % name) # pragma: no cover
raise ValueError("A group with name %s already exists." % name)
perms = [ Permission.objects.get(codename=codename, content_type__app_label=app_label) for app_label, codename in perm_names ]
g = Group.objects.using(db_alias).create(name=name)
g.permissions.set(perms)

@ -1,19 +0,0 @@
# Generated by Django 4.2.20 on 2025-04-06 11:30
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('members', '0039_membertraining_certificate_attendance'),
]
operations = [
migrations.AddField(
model_name='invitationtogroup',
name='created_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='created_group_invitations', to='members.member', verbose_name='Created by'),
),
]

@ -1,23 +0,0 @@
# Generated by Django 4.2.20 on 2025-05-03 15:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('members', '0040_invitationtogroup_created_by'),
]
operations = [
migrations.AddField(
model_name='freizeit',
name='crisis_intervention_list_sent',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='freizeit',
name='notification_crisis_intervention_list_sent',
field=models.BooleanField(default=False),
),
]

@ -1,18 +0,0 @@
# Generated by Django 4.2.20 on 2025-06-22 11:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('members', '0041_freizeit_crisis_intervention_list_sent_and_more'),
]
operations = [
migrations.AddField(
model_name='member',
name='ticket_no',
field=models.CharField(blank=True, default='', max_length=20, verbose_name='entrance ticket number'),
),
]

@ -1,121 +0,0 @@
from django.utils.translation import gettext_lazy as _
from django.db import migrations
from django.contrib.auth.management import create_permissions
STANDARD_PERMS = [
('members', 'view_member'),
('members', 'view_freizeit'),
('members', 'add_global_freizeit'),
('members', 'view_memberwaitinglist'),
('members', 'view_memberunconfirmedproxy'),
('mailer', 'view_message'),
('mailer', 'add_global_message'),
('finance', 'view_statementunsubmitted'),
('finance', 'add_global_statementunsubmitted'),
]
FINANCE_PERMS = [
('finance', 'view_bill'),
('finance', 'view_ledger'),
('finance', 'add_ledger'),
('finance', 'change_ledger'),
('finance', 'delete_ledger'),
('finance', 'view_statementsubmitted'),
('finance', 'view_global_statementsubmitted'),
('finance', 'change_global_statementsubmitted'),
('finance', 'view_transaction'),
('finance', 'change_transaction'),
('finance', 'add_transaction'),
('finance', 'delete_transaction'),
('finance', 'process_statementsubmitted'),
('members', 'list_global_freizeit'),
('members', 'view_global_freizeit'),
]
WAITINGLIST_PERMS = [
('members', 'view_global_memberwaitinglist'),
('members', 'list_global_memberwaitinglist'),
('members', 'change_global_memberwaitinglist'),
('members', 'delete_global_memberwaitinglist'),
]
TRAINING_PERMS = [
('members', 'change_global_member'),
('members', 'list_global_member'),
('members', 'view_global_member'),
('members', 'add_global_membertraining'),
('members', 'change_global_membertraining'),
('members', 'list_global_membertraining'),
('members', 'view_global_membertraining'),
('members', 'view_trainingcategory'),
('members', 'add_trainingcategory'),
('members', 'change_trainingcategory'),
('members', 'delete_trainingcategory'),
]
REGISTRATION_PERMS = [
('members', 'may_manage_all_registrations'),
('members', 'change_memberunconfirmedproxy'),
('members', 'delete_memberunconfirmedproxy'),
]
MATERIAL_PERMS = [
('members', 'list_global_member'),
('material', 'view_materialpart'),
('material', 'change_materialpart'),
('material', 'add_materialpart'),
('material', 'delete_materialpart'),
('material', 'view_materialcategory'),
('material', 'change_materialcategory'),
('material', 'add_materialcategory'),
('material', 'delete_materialcategory'),
('material', 'view_ownership'),
('material', 'change_ownership'),
('material', 'add_ownership'),
('material', 'delete_ownership'),
]
def ensure_group_perms(apps, schema_editor, name, perm_names):
"""
Ensure the group `name` has the permissions `perm_names`. If the group does not
exist, create it with the given permissions, otherwise add the missing ones.
This only adds permissions, already existing ones that are not listed here are not
removed.
"""
db_alias = schema_editor.connection.alias
Group = apps.get_model("auth", "Group")
Permission = apps.get_model("auth", "Permission")
perms = [ Permission.objects.get(codename=codename, content_type__app_label=app_label) for app_label, codename in perm_names ]
try:
g = Group.objects.using(db_alias).get(name=name)
for perm in perms:
g.permissions.add(perm)
g.save()
# This case is only executed if users have manually removed one of the standard groups.
except Group.DoesNotExist: # pragma: no cover
g = Group.objects.using(db_alias).create(name=name)
g.permissions.set(perms)
g.save()
def update_default_permission_groups(apps, schema_editor):
ensure_group_perms(apps, schema_editor, "Standard", STANDARD_PERMS)
ensure_group_perms(apps, schema_editor, "Finance", FINANCE_PERMS)
ensure_group_perms(apps, schema_editor, "Waitinglist", WAITINGLIST_PERMS)
ensure_group_perms(apps, schema_editor, "Trainings", TRAINING_PERMS)
ensure_group_perms(apps, schema_editor, "Registrations", REGISTRATION_PERMS)
ensure_group_perms(apps, schema_editor, "Material", MATERIAL_PERMS)
class Migration(migrations.Migration):
dependencies = [
('members', '0010_create_default_permission_groups'),
('members', '0042_member_ticket_no'),
]
operations = [
migrations.RunPython(update_default_permission_groups, migrations.RunPython.noop),
]

@ -1,42 +0,0 @@
# Generated by Django 4.2.20 on 2025-10-10 15:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('members', '0043_waitinglist_permissions'),
]
operations = [
migrations.AddField(
model_name='membertraining',
name='activity',
field=models.ManyToManyField(to='members.activitycategory', verbose_name='Activity'),
),
migrations.AlterModelOptions(
name='membertraining',
options={'default_permissions': ('add_global', 'change_global', 'view_global', 'delete_global', 'list_global', 'view'), 'permissions': (('manage_success_trainings', 'Can edit the success status of trainings.'),), 'verbose_name': 'Training', 'verbose_name_plural': 'Trainings'},
),
migrations.AlterField(
model_name='membertraining',
name='title',
field=models.CharField(max_length=150, verbose_name='Title'),
),
migrations.AlterField(
model_name='membertraining',
name='member',
field=models.ForeignKey(on_delete=models.deletion.CASCADE, related_name='traininigs', to='members.member', verbose_name='Member'),
),
migrations.AlterField(
model_name='membertraining',
name='participated',
field=models.BooleanField(null=True, verbose_name='Participated'),
),
migrations.AlterField(
model_name='membertraining',
name='passed',
field=models.BooleanField(null=True, verbose_name='Passed'),
),
]

@ -1,121 +0,0 @@
from django.utils.translation import gettext_lazy as _
from django.db import migrations
from django.contrib.auth.management import create_permissions
STANDARD_PERMS = [
('members', 'view_member'),
('members', 'view_freizeit'),
('members', 'add_global_freizeit'),
('members', 'view_memberwaitinglist'),
('members', 'view_memberunconfirmedproxy'),
('mailer', 'view_message'),
('mailer', 'add_global_message'),
('finance', 'view_statement'),
('finance', 'add_global_statement'),
]
FINANCE_PERMS = [
('finance', 'view_bill'),
('finance', 'view_ledger'),
('finance', 'add_ledger'),
('finance', 'change_ledger'),
('finance', 'delete_ledger'),
('finance', 'view_global_statement'),
('finance', 'change_global_statement'),
('finance', 'process_statementsubmitted'),
('finance', 'may_manage_confirmed_statements'),
('finance', 'view_transaction'),
('finance', 'change_transaction'),
('finance', 'add_transaction'),
('finance', 'delete_transaction'),
('members', 'list_global_freizeit'),
('members', 'view_global_freizeit'),
]
WAITINGLIST_PERMS = [
('members', 'view_global_memberwaitinglist'),
('members', 'list_global_memberwaitinglist'),
('members', 'change_global_memberwaitinglist'),
('members', 'delete_global_memberwaitinglist'),
]
TRAINING_PERMS = [
('members', 'change_global_member'),
('members', 'list_global_member'),
('members', 'view_global_member'),
('members', 'add_global_membertraining'),
('members', 'change_global_membertraining'),
('members', 'list_global_membertraining'),
('members', 'view_global_membertraining'),
('members', 'view_trainingcategory'),
('members', 'add_trainingcategory'),
('members', 'change_trainingcategory'),
('members', 'delete_trainingcategory'),
]
REGISTRATION_PERMS = [
('members', 'may_manage_all_registrations'),
('members', 'change_memberunconfirmedproxy'),
('members', 'delete_memberunconfirmedproxy'),
]
MATERIAL_PERMS = [
('members', 'list_global_member'),
('material', 'view_materialpart'),
('material', 'change_materialpart'),
('material', 'add_materialpart'),
('material', 'delete_materialpart'),
('material', 'view_materialcategory'),
('material', 'change_materialcategory'),
('material', 'add_materialcategory'),
('material', 'delete_materialcategory'),
('material', 'view_ownership'),
('material', 'change_ownership'),
('material', 'add_ownership'),
('material', 'delete_ownership'),
]
def ensure_group_perms(apps, schema_editor, name, perm_names):
"""
Ensure the group `name` has the permissions `perm_names`. If the group does not
exist, create it with the given permissions, otherwise add the missing ones.
This only adds permissions, already existing ones that are not listed here are not
removed.
"""
db_alias = schema_editor.connection.alias
Group = apps.get_model("auth", "Group")
Permission = apps.get_model("auth", "Permission")
perms = [ Permission.objects.get(codename=codename, content_type__app_label=app_label) for app_label, codename in perm_names ]
try:
g = Group.objects.using(db_alias).get(name=name)
for perm in perms:
g.permissions.add(perm)
g.save()
# This case is only executed if users have manually removed one of the standard groups.
except Group.DoesNotExist: # pragma: no cover
g = Group.objects.using(db_alias).create(name=name)
g.permissions.set(perms)
g.save()
def update_default_permission_groups(apps, schema_editor):
ensure_group_perms(apps, schema_editor, "Standard", STANDARD_PERMS)
ensure_group_perms(apps, schema_editor, "Finance", FINANCE_PERMS)
ensure_group_perms(apps, schema_editor, "Waitinglist", WAITINGLIST_PERMS)
ensure_group_perms(apps, schema_editor, "Trainings", TRAINING_PERMS)
ensure_group_perms(apps, schema_editor, "Registrations", REGISTRATION_PERMS)
ensure_group_perms(apps, schema_editor, "Material", MATERIAL_PERMS)
class Migration(migrations.Migration):
dependencies = [
('finance', '0012_statementonexcursionproxy'),
('members', '0044_membertraining_activity_and_more'),
]
operations = [
migrations.RunPython(update_default_permission_groups, migrations.RunPython.noop),
]

@ -1,13 +1,13 @@
from datetime import datetime, timedelta, date
from datetime import datetime, timedelta
import uuid
import math
import pytz
import unicodedata
import re
import csv
from django.db import models
from django.db.models import TextField, ManyToManyField, ForeignKey, Count,\
Sum, Case, Q, F, When, Value, IntegerField, Subquery, OuterRef
from django.db.models.functions import Cast
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from django.utils.html import format_html
@ -18,24 +18,23 @@ from utils import RestrictedFileField, normalize_name
import os
from mailer.mailutils import send as send_mail, get_mail_confirmation_link,\
prepend_base_url, get_registration_link, get_wait_confirmation_link,\
get_invitation_reject_link, get_invite_as_user_key, get_leave_waitinglist_link,\
get_invitation_confirm_link
get_invitation_reject_link, get_invite_as_user_key, get_leave_waitinglist_link
from django.contrib.auth.models import User
from django.conf import settings
from django.core.validators import MinValueValidator
from .rules import may_view, may_change, may_delete, is_own_training, is_oneself, is_leader, is_leader_of_excursion,\
is_leader_of_relevant_invitation
from .pdf import render_tex
from .rules import may_view, may_change, may_delete, is_own_training, is_oneself, is_leader, is_leader_of_excursion
import rules
from contrib.models import CommonModel
from contrib.media import media_path
from contrib.rules import memberize_user, has_global_perm
from utils import cvt_to_decimal, coming_midnight
from utils import cvt_to_decimal
from dateutil.relativedelta import relativedelta
from schwifty import IBAN
def generate_random_key():
return uuid.uuid4().hex
GEMEINSCHAFTS_TOUR = MUSKELKRAFT_ANREISE = MALE = 0
FUEHRUNGS_TOUR = OEFFENTLICHE_ANREISE = FEMALE = 1
@ -105,33 +104,11 @@ class Group(models.Model):
class Meta:
verbose_name = _('group')
verbose_name_plural = _('groups')
@property
def sorted_members(self):
"""Returns the members of this group sorted by their last name."""
return self.member_set.all().order_by('lastname')
def has_time_info(self):
# return if the group has all relevant time slot information filled
return self.weekday and self.start_time and self.end_time
def get_time_info(self):
if self.has_time_info():
return settings.GROUP_TIME_AVAILABLE_TEXT.format(weekday=WEEKDAYS[self.weekday][1],
start_time=self.start_time.strftime('%H:%M'),
end_time=self.end_time.strftime('%H:%M'))
else:
return ""
def has_age_info(self):
return self.year_from and self.year_to
def get_age_info(self):
if self.has_age_info():
return _("years %(from)s to %(to)s") % {'from':self.year_from, 'to':self.year_to}
else:
return ""
def get_invitation_text_template(self):
"""The text template used to invite waiters to this group. This contains
placeholders for the name of the waiter and personalized links."""
@ -140,17 +117,13 @@ class Group(models.Model):
else:
group_link = ''
if self.has_time_info():
group_time = self.get_time_info()
group_time = settings.GROUP_TIME_AVAILABLE_TEXT.format(weekday=WEEKDAYS[self.weekday][1],
start_time=self.start_time.strftime('%H:%M'),
end_time=self.end_time.strftime('%H:%M'))
else:
group_time = settings.GROUP_TIME_UNAVAILABLE_TEXT.format(contact_email=self.contact_email)
if self.has_age_info():
group_age = self.get_age_info()
else:
group_age = _("no information available")
return settings.INVITE_TEXT.format(group_time=group_time,
group_name=self.name,
group_age=group_age,
group_link=group_link,
contact_email=self.contact_email)
@ -211,8 +184,7 @@ class Contact(CommonModel):
for email_fd, confirmed_email_fd, confirm_mail_key_fd in self.email_fields:
if getattr(self, confirmed_email_fd) and not rerequest:
continue
if not getattr(self, email_fd): # pragma: no cover
# Only reachable with misconfigured `email_fields`
if not getattr(self, email_fd):
continue
requested_confirmation = True
setattr(self, confirmed_email_fd, False)
@ -285,10 +257,6 @@ class Person(Contact):
age.admin_order_field = 'birth_date'
age.short_description = _('age')
def age_at(self, date: date):
"""Age of member at a given date"""
return relativedelta(date.replace(tzinfo=None), self.birth_date).years
@property
def birth_date_str(self):
if self.birth_date is None:
@ -324,9 +292,6 @@ class Member(Person):
has_key = models.BooleanField(_('Has key'), default=False)
has_free_ticket_gym = models.BooleanField(_('Has a free ticket for the climbing gym'), default=False)
dav_badge_no = models.CharField(max_length=20, verbose_name=_('DAV badge number'), default='', blank=True)
# use this to store a climbing gym customer or membership id, used to print on meeting checklists
ticket_no = models.CharField(max_length=20, verbose_name=_('entrance ticket number'), default='', blank=True)
swimming_badge = models.BooleanField(verbose_name=_('Knows how to swim'), default=False)
climbing_badge = models.CharField(max_length=100, verbose_name=_('Climbing badge'), default='', blank=True)
alpine_experience = models.TextField(verbose_name=_('Alpine experience'), default='', blank=True)
@ -377,7 +342,6 @@ class Member(Person):
help_text=_('If the person registered from the waitinglist, this is their application date.'))
objects = MemberManager()
all_objects = models.Manager()
@property
def email_fields(self):
@ -388,11 +352,6 @@ class Member(Person):
def place(self):
"""Returning the whole place (plz + town)"""
return "{0} {1}".format(self.plz, self.town)
@property
def ticket_tag(self):
"""Returning the ticket number stripped of strings and spaces"""
return "{" + ''.join(re.findall(r'\d', self.ticket_no)) + "}"
@property
def iban_valid(self):
@ -443,10 +402,6 @@ class Member(Person):
self.save()
return True
def unconfirm(self):
self.confirmed = False
self.save()
def unsubscribe(self, key):
if self.unsubscribe_key == key and timezone.now() <\
self.unsubscribe_expire:
@ -538,10 +493,6 @@ class Member(Person):
# get activity overview
return Freizeit.objects.filter(membersonlist__member=self)
def generate_upload_registration_form_key(self):
self.upload_registration_form_key = uuid.uuid4().hex
self.save()
def create_from_registration(self, waiter, group):
"""Given a member, a corresponding waiting-list object and a group, this completes
the registration and requests email confirmations if necessary.
@ -566,12 +517,6 @@ class Member(Person):
waiter.delete()
return self.request_mail_confirmation(rerequest=False)
def registration_form_uploaded(self):
print(self.registration_form.name)
return not self.registration_form.name is None and self.registration_form.name != ""
registration_form_uploaded.boolean = True
registration_form_uploaded.short_description = _('Registration form')
def registration_ready(self):
"""Returns if the member is currently unconfirmed and all email addresses
are confirmed."""
@ -597,16 +542,12 @@ class Member(Person):
def send_upload_registration_form_link(self):
if not self.upload_registration_form_key:
return
print(self.name, self.upload_registration_form_key)
link = self.get_upload_registration_form_link()
self.send_mail(_('Upload registration form'),
settings.UPLOAD_REGISTRATION_FORM_TEXT.format(name=self.prename,
link=link))
def request_registration_form(self):
"""Ask the member to upload a registration form via email."""
self.generate_upload_registration_form_key()
self.send_upload_registration_form_link()
def notify_jugendleiters_about_confirmed_mail(self):
group = ", ".join([g.name for g in self.group.all()])
# notify jugendleiters of group of registration
@ -621,16 +562,7 @@ class Member(Person):
settings.DEFAULT_SENDING_MAIL,
jl.email)
def filter_queryset_by_permissions(self, queryset=None, annotate=False, model=None): # pragma: no cover
"""
Filter the given queryset of objects of type `model` by the permissions of `self`.
For example, only returns `Message`s created by `self`.
This method is used by the `FilteredMemberFieldMixin` to filter the selection
in `ForeignKey` and `ManyToMany` fields.
"""
# This method is not used by all models listed below, so covering all cases in tests
# is hard and not useful. It is therefore exempt from testing.
def filter_queryset_by_permissions(self, queryset=None, annotate=False, model=None):
name = model._meta.object_name
if queryset is None:
queryset = Member.objects.all()
@ -643,8 +575,6 @@ class Member(Person):
return self.filter_statements_by_permissions(queryset, annotate)
elif name == "Freizeit":
return self.filter_excursions_by_permissions(queryset, annotate)
elif name == "MemberWaitingList":
return self.filter_waiters_by_permissions(queryset, annotate)
elif name == "LJPProposal":
return queryset
elif name == "MemberTraining":
@ -652,9 +582,7 @@ class Member(Person):
elif name == "NewMemberOnList":
return queryset
elif name == "Statement":
return self.filter_statements_by_permissions(queryset, annotate)
elif name == "StatementOnExcursionProxy":
return self.filter_statements_by_permissions(queryset, annotate)
return queryset
elif name == "BillOnExcursionProxy":
return queryset
elif name == "Intervention":
@ -669,8 +597,6 @@ class Member(Person):
return queryset
elif name == "MemberUnconfirmedProxy":
return queryset
elif name == "InvitationToGroup":
return queryset
else:
raise ValueError(name)
@ -749,12 +675,6 @@ class Member(Person):
queryset = queryset.filter(Q(groups__in=groups) | Q(jugendleiter=self)).distinct()
return queryset
def filter_waiters_by_permissions(self, queryset, annotate=False):
# ignores annotate
# return waiters that have a pending, expired or rejected group invitation for a group
# led by the member
return queryset.filter(invitationtogroup__group__leiters=self)
def may_list(self, other):
if self.pk == other.pk:
return True
@ -943,28 +863,17 @@ def gen_key():
return uuid.uuid4().hex
class InvitationToGroup(CommonModel):
class InvitationToGroup(models.Model):
"""An invitation of a waiter to a group."""
waiter = models.ForeignKey('MemberWaitingList', verbose_name=_('Waiter'), on_delete=models.CASCADE)
group = models.ForeignKey(Group, verbose_name=_('Group'), on_delete=models.CASCADE)
date = models.DateField(default=timezone.now, verbose_name=_('Invitation date'))
rejected = models.BooleanField(verbose_name=_('Invitation rejected'), default=False)
key = models.CharField(max_length=32, default=gen_key)
created_by = models.ForeignKey(Member, verbose_name=_('Created by'),
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name='created_group_invitations')
class Meta(CommonModel.Meta):
class Meta:
verbose_name = _('Invitation to group')
verbose_name_plural = _('Invitations to groups')
rules_permissions = {
'add_obj': has_global_perm('members.add_global_memberwaitinglist'),
'view_obj': is_leader_of_relevant_invitation | has_global_perm('members.view_global_memberwaitinglist'),
'change_obj': has_global_perm('members.change_global_memberwaitinglist'),
'delete_obj': has_global_perm('members.delete_global_memberwaitinglist'),
}
def is_expired(self):
return self.date < (timezone.now() - timezone.timedelta(days=30)).date()
@ -978,69 +887,6 @@ class InvitationToGroup(CommonModel):
return _('Undecided')
status.short_description = _('Status')
def send_left_waitinglist_notification_to(self, recipient):
send_mail(_('%(waiter)s left the waiting list') % {'waiter': self.waiter},
settings.GROUP_INVITATION_LEFT_WAITINGLIST.format(name=recipient.prename,
waiter=self.waiter,
group=self.group),
settings.DEFAULT_SENDING_MAIL,
recipient.email)
def send_reject_notification_to(self, recipient):
send_mail(_('Group invitation rejected by %(waiter)s') % {'waiter': self.waiter},
settings.GROUP_INVITATION_REJECTED.format(name=recipient.prename,
waiter=self.waiter,
group=self.group),
settings.DEFAULT_SENDING_MAIL,
recipient.email)
def send_confirm_notification_to(self, recipient):
send_mail(_('Group invitation confirmed by %(waiter)s') % {'waiter': self.waiter},
settings.GROUP_INVITATION_CONFIRMED_TEXT.format(name=recipient.prename,
waiter=self.waiter,
group=self.group),
settings.DEFAULT_SENDING_MAIL,
recipient.email)
def send_confirm_confirmation(self):
self.waiter.send_mail(_('Trial group meeting confirmed'),
settings.TRIAL_GROUP_MEETING_CONFIRMED_TEXT.format(name=self.waiter.prename,
group=self.group,
contact_email=self.group.contact_email,
timeinfo=self.group.get_time_info()))
def notify_left_waitinglist(self):
"""
Inform youth leaders of the group and the inviter that the waiter left the waitinglist,
prompted by this group invitation.
"""
if self.created_by:
self.send_left_waitinglist_notification_to(self.created_by)
for jl in self.group.leiters.all():
self.send_left_waitinglist_notification_to(jl)
def reject(self):
"""Reject this invitation. Informs the youth leaders of the group of the rejection."""
self.rejected = True
self.save()
# send notifications
if self.created_by:
self.send_reject_notification_to(self.created_by)
for jl in self.group.leiters.all():
self.send_reject_notification_to(jl)
def confirm(self):
"""Confirm this invitation. Informs the youth leaders of the group of the invitation."""
self.rejected = False
self.save()
# confirm the confirmation
self.send_confirm_confirmation()
# send notifications
if self.created_by:
self.send_confirm_notification_to(self.created_by)
for jl in self.group.leiters.all():
self.send_confirm_notification_to(jl)
class MemberWaitingList(Person):
"""A participant on the waiting list"""
@ -1071,7 +917,7 @@ class MemberWaitingList(Person):
permissions = (('may_manage_waiting_list', 'Can view and manage the waiting list.'),)
rules_permissions = {
'add_obj': has_global_perm('members.add_global_memberwaitinglist'),
'view_obj': is_leader_of_relevant_invitation | has_global_perm('members.view_global_memberwaitinglist'),
'view_obj': has_global_perm('members.view_global_memberwaitinglist'),
'change_obj': has_global_perm('members.change_global_memberwaitinglist'),
'delete_obj': has_global_perm('members.delete_global_memberwaitinglist'),
}
@ -1087,8 +933,8 @@ class MemberWaitingList(Person):
@property
def waiting_confirmation_needed(self):
"""Returns if person should be asked to confirm waiting status."""
return not self.wait_confirmation_key \
and self.last_wait_confirmation < timezone.now() -\
return wait_confirmation_key is None \
and last_wait_confirmation < timezone.now() -\
timezone.timedelta(days=settings.WAITING_CONFIRMATION_FREQUENCY)
def waiting_confirmed(self):
@ -1151,13 +997,14 @@ class MemberWaitingList(Person):
return self.wait_confirmation_key
def may_register(self, key):
print("may_register", key)
try:
invitation = InvitationToGroup.objects.get(key=key)
return self.pk == invitation.waiter.pk and timezone.now().date() < invitation.date + timezone.timedelta(days=30)
return self.pk == invitation.waiter.pk and timezone.now() < invitation.date + timezone.timedelta(days=30)
except InvitationToGroup.DoesNotExist:
return False
def invite_to_group(self, group, text_template=None, creator=None):
def invite_to_group(self, group, text_template=None):
"""
Invite waiter to given group. Stores a new group invitation
and sends a personalized e-mail based on the passed template.
@ -1166,13 +1013,12 @@ class MemberWaitingList(Person):
self.save()
if not text_template:
text_template = group.get_invitation_text_template()
invitation = InvitationToGroup(group=group, waiter=self, created_by=creator)
invitation = InvitationToGroup(group=group, waiter=self)
invitation.save()
self.send_mail(_("Invitation to trial group meeting"),
text_template.format(name=self.prename,
link=get_registration_link(invitation.key),
invitation_reject_link=get_invitation_reject_link(invitation.key),
invitation_confirm_link=get_invitation_confirm_link(invitation.key)),
invitation_reject_link=get_invitation_reject_link(invitation.key)),
cc=group.contact_email.email)
def unregister(self):
@ -1223,13 +1069,13 @@ class NewMemberOnList(CommonModel):
@property
def skills(self):
activities = [a.name for a in self.memberlist.activity.all()]
activities = [a.name for a in memberlist.activity.all()]
return {k: v for k, v in self.member.get_skills().items() if k in activities}
@property
def qualities_tex(self):
qualities = []
for activity, value in self.skills.items():
for activity, value in self.skills:
qualities.append("\\textit{%s:} %s" % (activity, value))
return ", ".join(qualities)
@ -1281,10 +1127,6 @@ class Freizeit(CommonModel):
approval_comments = models.TextField(verbose_name=_('Approval comments'),
blank=True, default='')
# automatic sending of crisis intervention list
crisis_intervention_list_sent = models.BooleanField(default=False)
notification_crisis_intervention_list_sent = models.BooleanField(default=False)
def __str__(self):
"""String represenation"""
return self.name
@ -1307,23 +1149,6 @@ class Freizeit(CommonModel):
def code(self):
return f"B{self.date:%y}-{self.pk}"
@staticmethod
def filter_queryset_date_next_n_hours(hours, queryset=None):
if queryset is None:
queryset = Freizeit.objects.all()
return queryset.filter(date__lte=timezone.now() + timezone.timedelta(hours=hours),
date__gte=timezone.now())
@staticmethod
def to_notify_crisis_intervention_list():
qs = Freizeit.objects.filter(notification_crisis_intervention_list_sent=False)
return Freizeit.filter_queryset_date_next_n_hours(48, queryset=qs)
@staticmethod
def to_send_crisis_intervention_list():
qs = Freizeit.objects.filter(crisis_intervention_list_sent=False)
return Freizeit.filter_queryset_date_next_n_hours(24, queryset=qs)
def get_tour_type(self):
if self.tour_type == FUEHRUNGS_TOUR:
return "Führungstour"
@ -1351,28 +1176,18 @@ class Freizeit(CommonModel):
@property
def duration(self):
# number of nights is number of full days + 1
full_days = max(self.night_count - 1, 0)
full_days = self.night_count - 1
extra_days = 0
if self.date.date() == self.end.date():
# excursion starts and ends on the same day
hours = max(self.end.hour - self.date.hour, 0)
# at least 6 hours counts as full day
if hours >= 6:
extra_days = 1.0
# otherwise half day
else:
extra_days = 0.5
if self.date.hour <= 12:
extra_days += 1.0
else:
if self.date.hour <= 12:
extra_days += 1.0
else:
extra_days += 0.5
extra_days += 0.5
if self.end.hour >= 12:
extra_days += 1.0
else:
extra_days += 0.5
if self.end.hour >= 12:
extra_days += 1.0
else:
extra_days += 0.5
return full_days + extra_days
@ -1383,75 +1198,26 @@ class Freizeit(CommonModel):
else:
return 0
@property
def total_seminar_days(self):
"""calculate seminar days based on intervention hours in every day"""
# TODO: add tests for this
if hasattr(self, 'ljpproposal'):
hours_per_day = self.seminar_time_per_day
# Calculate the total number of seminar days
# Each day is counted as 1 if total_duration is >= 5 hours, as 0.5 if total_duration is >= 2.5
# otherwise 0
sum_days = sum([h['sum_days'] for h in hours_per_day])
return sum_days
else:
return 0
@property
def seminar_time_per_day(self):
if hasattr(self, 'ljpproposal'):
return (
self.ljpproposal.intervention_set
.annotate(day=Cast('date_start', output_field=models.DateField())) # Force it to date
.values('day') # Group by day
.annotate(total_duration=Sum('duration'))# Sum durations for each day
.annotate(
sum_days=Case(
When(total_duration__gte=5.0, then=Value(1.0)),
When(total_duration__gte=2.5, then=Value(0.5)),
default=Value(0.0),)
)
.order_by('day') # Sort results by date
)
else:
return []
@property
def ljp_duration(self):
"""calculate the duration in days for the LJP"""
return min(self.duration, self.total_seminar_days)
@property
def staff_count(self):
return self.jugendleiter.count()
@property
def staff_on_memberlist(self):
ps = set(map(lambda x: x.member, self.membersonlist.distinct()))
jls = set(self.jugendleiter.distinct())
return ps.intersection(jls)
@property
def staff_on_memberlist_count(self):
return len(self.staff_on_memberlist)
@property
def participant_count(self):
return len(self.participants)
@property
def participants(self):
ps = set(map(lambda x: x.member, self.membersonlist.distinct()))
jls = set(self.jugendleiter.distinct())
return list(ps - jls)
@property
def old_participant_count(self):
old_ps = [m for m in self.participants if m.age() >= 27]
return len(old_ps)
return len(ps - jls)
@property
def head_count(self):
return self.staff_on_memberlist_count + self.participant_count
@ -1486,7 +1252,7 @@ class Freizeit(CommonModel):
# non-youth leader participants
ps_only = ps - jls
# participants of the correct age
ps_correct_age = {m for m in ps_only if m.age_at(self.date) >= 6 and m.age_at(self.date) < 27}
ps_correct_age = {m for m in ps_only if m.age() >= 6 and m.age() < 27}
# m = the official non-youth-leader participant count
# and, assuming there exist enough participants, unrounded m satisfies the equation
# len(ps_correct_age) + 1/5 * m = m
@ -1513,33 +1279,19 @@ class Freizeit(CommonModel):
@property
def maximal_ljp_contributions(self):
"""This is the maximal amount of LJP contributions that can be requested given participants and length
This calculation if intended for the LJP application, not for the payout."""
return cvt_to_decimal(settings.LJP_CONTRIBUTION_PER_DAY * self.ljp_participant_count * self.duration)
@property
def potential_ljp_contributions(self):
"""The maximal amount can be reduced if the actual costs are lower than the maximal amount
This calculation if intended for the LJP application, not for the payout."""
if not hasattr(self, 'statement'):
return cvt_to_decimal(0)
return cvt_to_decimal(min(self.maximal_ljp_contributions,
0.9 * float(self.statement.total_bills_theoretic) + float(self.statement.total_staff)))
@property
def payable_ljp_contributions(self):
"""the payable contributions can differ from potential contributions if a tax is deducted for risk reduction.
the actual payout depends on more factors, e.g. the actual costs that had to be paid by the trip organisers."""
if hasattr(self, 'statement') and self.statement.ljp_to:
return self.statement.paid_ljp_contributions
return cvt_to_decimal(self.potential_ljp_contributions * cvt_to_decimal(1 - settings.LJP_TAX))
@property
def total_relative_costs(self):
if not hasattr(self, 'statement'):
if not self.statement:
return 0
total_costs = self.statement.total_bills_theoretic
total_contributions = self.statement.total_subsidies + self.payable_ljp_contributions
total_contributions = self.statement.total_subsidies + self.potential_ljp_contributions
return total_costs - total_contributions
@property
@ -1588,9 +1340,9 @@ class Freizeit(CommonModel):
jls = set(self.jugendleiter.distinct())
participants = members - jls
b27_local = len([m for m in participants
if m.age_at(self.date) <= 27 and settings.SEKTION in m.town])
if m.age() <= 27 and settings.SEKTION in m.town])
b27_non_local = len([m for m in participants
if m.age_at(self.date) <= 27 and not settings.SEKTION in m.town])
if m.age() <= 27 and not settings.SEKTION in m.town])
staff = len(jls)
total = b27_local + b27_non_local + len(jls)
relevant_b27 = min(b27_local + b27_non_local, math.floor(3/2 * b27_local))
@ -1625,6 +1377,7 @@ class Freizeit(CommonModel):
'Betreuer/in': str(numbers['staff']),
'Auswahl Veranstaltung': 'Auswahl2',
'Ort, Datum': '{p}, {d}'.format(p=settings.SEKTION, d=datetime.now().strftime('%d.%m.%Y'))}
print(members)
for i, m in enumerate(members):
suffix = str(' {}'.format(i + 1))
# indexing starts at zero, but the listing in the pdf starts at 1
@ -1634,7 +1387,7 @@ class Freizeit(CommonModel):
suffix = str(i + 1)
base['Vor- und Nachname' + suffix] = m.name
base['Anschrift' + suffix] = m.address
base['Alter' + suffix] = str(m.age_at(self.date))
base['Alter' + suffix] = str(m.age())
base['Status' + str(i+1)] = '2' if m in jls else 'Auswahl1' if settings.SEKTION in m.address else 'Auswahl2'
return base
@ -1710,61 +1463,6 @@ class Freizeit(CommonModel):
queryset = queryset.filter(Q(groups__in=groups) | Q(jugendleiter__pk=member.pk)).distinct()
return queryset
def send_crisis_intervention_list(self, sending_time=None):
"""
Send the crisis intervention list to the crisis invervention email, the
responsible and the youth leaders of this excursion.
"""
context = dict(memberlist=self, settings=settings)
start_date= timezone.localtime(self.date).strftime('%d.%m.%Y')
filename = render_tex(f"{self.code}_{self.name}_Krisenliste",
'members/crisis_intervention_list.tex', context,
date=self.date, save_only=True)
leaders = ", ".join([yl.name for yl in self.jugendleiter.all()])
start_date = timezone.localtime(self.date).strftime('%d.%m.%Y')
end_date = timezone.localtime(self.end).strftime('%d.%m.%Y')
# create email with attachment
send_mail(_('Crisis intervention list for %(excursion)s from %(start)s to %(end)s') %\
{ 'excursion': self.name,
'start': start_date,
'end': end_date },
settings.SEND_EXCURSION_CRISIS_LIST.format(excursion=self.name, leaders=leaders,
excursion_start=start_date,
excursion_end=end_date),
sender=settings.DEFAULT_SENDING_MAIL,
recipients=[settings.SEKTION_CRISIS_INTERVENTION_MAIL],
cc=[settings.RESPONSIBLE_MAIL] + [yl.email for yl in self.jugendleiter.all()],
attachments=[media_path(filename)])
self.crisis_intervention_list_sent = True
self.save()
def notify_leaders_crisis_intervention_list(self, sending_time=None):
"""
Send an email to the youth leaders of this excursion with a list of currently
registered participants and a heads-up that the crisis intervention list
will be automatically sent on the night of this day.
"""
participants = "\n".join([f"- {p.member.name}" for p in self.membersonlist.all()])
if not sending_time:
sending_time = coming_midnight().strftime("%d.%m.%y %H:%M")
elif not isinstance(sending_time, str):
sending_time = sending_time.strftime("%d.%m.%y %H:%M")
start_date = timezone.localtime(self.date).strftime('%d.%m.%Y')
end_date = timezone.localtime(self.end).strftime('%d.%m.%Y')
excursion_link = prepend_base_url(self.get_absolute_url())
for yl in self.jugendleiter.all():
yl.send_mail(_('Participant list for %(excursion)s from %(start)s to %(end)s') %\
{ 'excursion': self.name,
'start': start_date,
'end': end_date },
settings.NOTIFY_EXCURSION_PARTICIPANT_LIST.format(name=yl.prename,
excursion=self.name,
participants=participants,
sending_time=sending_time,
excursion_link=excursion_link))
self.notification_crisis_intervention_list_sent = True
self.save()
class MemberNoteList(models.Model):
"""
@ -2095,14 +1793,13 @@ class TrainingCategory(models.Model):
class MemberTraining(CommonModel):
"""Represents a training planned or attended by a member."""
member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='traininigs', verbose_name=_('Member'))
title = models.CharField(verbose_name=_('Title'), max_length=150)
member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='traininigs')
title = models.CharField(verbose_name=_('Title'), max_length=30)
date = models.DateField(verbose_name=_('Date'), null=True, blank=True)
category = models.ForeignKey(TrainingCategory, on_delete=models.PROTECT, verbose_name=_('Category'))
activity = models.ManyToManyField(ActivityCategory, verbose_name=_('Activity'))
comments = models.TextField(verbose_name=_('Comments'), blank=True)
participated = models.BooleanField(verbose_name=_('Participated'), null=True)
passed = models.BooleanField(verbose_name=_('Passed'), null=True)
participated = models.BooleanField(verbose_name=_('Participated'))
passed = models.BooleanField(verbose_name=_('Passed'))
certificate = RestrictedFileField(verbose_name=_('certificate of attendance'),
upload_to='training_forms',
blank=True,
@ -2111,26 +1808,10 @@ class MemberTraining(CommonModel):
'image/jpeg',
'image/png',
'image/gif'])
def __str__(self):
if self.date:
return self.title + ' ' + self.date.strftime('%d.%m.%Y')
return self.title + ' ' + str(_('(no date)'))
def get_activities(self):
activity_string = ', '.join(a.name for a in self.activity.all())
return activity_string
get_activities.short_description = _('Activities')
class Meta(CommonModel.Meta):
verbose_name = _('Training')
verbose_name_plural = _('Trainings')
permissions = (
('manage_success_trainings', 'Can edit the success status of trainings.'),
)
rules_permissions = {
# sine this is used in an inline, the member and not the training is passed
'add_obj': is_oneself | has_global_perm('members.add_global_membertraining'),
@ -2138,3 +1819,227 @@ class MemberTraining(CommonModel):
'change_obj': is_oneself | has_global_perm('members.change_global_membertraining'),
'delete_obj': is_oneself | has_global_perm('members.delete_global_membertraining'),
}
def import_from_csv(path, omit_groupless=True):
with open(path, encoding='ISO-8859-1') as csvfile:
reader = csv.DictReader(csvfile, delimiter=';')
rows = list(reader)
def transform_field(key, value):
new_key = CLUBDESK_TO_KOMPASS[key]
if isinstance(new_key, str):
return (new_key, value)
else:
return (new_key[0], new_key[1](value))
def transform_row(row):
kwargs = dict([ transform_field(k, v) for k, v in row.items() if k in CLUBDESK_TO_KOMPASS ])
kwargs_filtered = { k : v for k, v in kwargs.items() if k not in ['group', 'last_training', 'has_fundamental_training', 'special_training', 'phone_number_private', 'phone_number_parents'] }
if not kwargs['group'] and omit_groupless:
# if member does not have a group, skip them
return
mem = Member(**kwargs_filtered)
mem.save()
mem.group.set([group for group, is_jl in kwargs['group']])
for group, is_jl in kwargs['group']:
if is_jl:
group.leiters.add(mem)
if kwargs['has_fundamental_training']:
try:
ga_cat = TrainingCategory.objects.get(name='Grundausbildung')
except TrainingCategory.DoesNotExist:
ga_cat = TrainingCategory(name='Grundausbildung', permission_needed=True)
ga_cat.save()
ga_training = MemberTraining(member=mem, title='Grundausbildung', date=None, category=ga_cat,
participated=True, passed=True)
ga_training.save()
if kwargs['last_training'] is not None:
try:
cat = TrainingCategory.objects.get(name='Fortbildung')
except TrainingCategory.DoesNotExist:
cat = TrainingCategory(name='Fortbildung', permission_needed=False)
cat.save()
training = MemberTraining(member=mem, title='Unbekannt', date=kwargs['last_training'], category=cat,
participated=True, passed=True)
training.save()
if kwargs['special_training'] != '':
try:
cat = TrainingCategory.objects.get(name='Sonstiges')
except TrainingCategory.DoesNotExist:
cat = TrainingCategory(name='Sonstiges', permission_needed=False)
cat.save()
training = MemberTraining(member=mem, title=kwargs['special_training'], date=None, category=cat,
participated=True, passed=True)
training.save()
if kwargs['phone_number_private'] != '':
prefix = '\n' if mem.comments else ''
mem.comments += prefix + 'Telefon (Privat): ' + kwargs['phone_number_private']
mem.save()
if kwargs['phone_number_parents'] != '':
prefix = '\n' if mem.comments else ''
mem.comments += prefix + 'Telefon (Eltern): ' + kwargs['phone_number_parents']
mem.save()
for row in rows:
transform_row(row)
def parse_group(value):
groups_raw = re.split(',', value)
# need to determine if member is youth leader
roles = set()
def extract_group_name_and_role(raw):
obj = re.search('^(.*?)(?: \((.*)\))?$', raw)
is_jl = False
if obj.group(2) is not None:
roles.add(obj.group(2).strip())
if obj.group(2) == 'Jugendleiter*in':
is_jl = True
return (obj.group(1).strip(), is_jl)
group_names = [extract_group_name_and_role(raw) for raw in groups_raw if raw != '']
if "Jugendleiter*in" in roles:
group_names.append(('Jugendleiter', False))
groups = []
for group_name, is_jl in group_names:
try:
group = Group.objects.get(name=group_name)
except Group.DoesNotExist:
group = Group(name=group_name)
group.save()
groups.append((group, is_jl))
return groups
def parse_date(value):
if value == '':
return None
return datetime.strptime(value, '%d.%m.%Y').date()
def parse_datetime(value):
tz = pytz.timezone('Europe/Berlin')
if value == '':
return timezone.now()
return tz.localize(datetime.strptime(value, '%d.%m.%Y %H:%M:%S'))
def parse_status(value):
return value != "Passivmitglied"
def parse_boolean(value):
return value.lower() == "ja"
def parse_nullable_boolean(value):
if value == '':
return None
else:
return value.lower() == "ja"
def parse_gender(value):
if value == 'männlich':
return MALE
elif value == 'weiblich':
return FEMALE
else:
return DIVERSE
def parse_can_swim(value):
return True if len(value) > 0 else False
CLUBDESK_TO_KOMPASS = {
'Nachname': 'lastname',
'Vorname': 'prename',
'Adresse': 'street',
'PLZ': 'plz',
'Ort': 'town',
'Telefon Privat': 'phone_number_private',
'Telefon Mobil': 'phone_number',
'Adress-Zusatz': 'address_extra',
'Land': 'country',
'E-Mail': 'email',
'E-Mail Alternativ': 'alternative_email',
'Status': ('active', parse_status),
'Eintritt': ('join_date', parse_date),
'Austritt': ('leave_date', parse_date),
'Geburtsdatum': ('birth_date', parse_date),
'Geburtstag': ('birth_date', parse_date),
'Geschlecht': ('gender', parse_gender),
'Bemerkungen': 'comments',
'IBAN': 'iban',
'Vorlage Führungszeugnis': ('good_conduct_certificate_presented_date', parse_date),
'Letzte Fortbildung': ('last_training', parse_date),
'Grundausbildung': ('has_fundamental_training', parse_boolean),
'Besondere Ausbildung': 'special_training',
'[Gruppen]' : ('group', parse_group),
'Schlüssel': ('has_key', parse_boolean),
'Freikarte': ('has_free_ticket_gym', parse_boolean),
'DAV Ausweis Nr.': 'dav_badge_no',
'Schwimmabzeichen': ('swimming_badge', parse_can_swim),
'Kletterschein': 'climbing_badge',
'Felserfahrung': 'alpine_experience',
'Allergien': 'allergies',
'Medikamente': 'medication',
'Tetanusimpfung': 'tetanus_vaccination',
'Fotoerlaubnis': ('photos_may_be_taken', parse_boolean),
'Erziehungsberechtigte': 'legal_guardians',
'Darf sich allein von der Gruppenstunde abmelden':
('may_cancel_appointment_independently', parse_nullable_boolean),
'Mobil Eltern': 'phone_number_parents',
'Sonstiges': 'application_text',
'Erhalten am': ('application_date', parse_datetime),
'Angeschrieben von': 'contacted_by',
'Angeschrieben von ': 'contacted_by',
}
def import_from_csv_waitinglist(path):
with open(path, encoding='ISO-8859-1') as csvfile:
reader = csv.DictReader(csvfile, delimiter=';')
rows = list(reader)
def transform_field(key, value):
new_key = CLUBDESK_TO_KOMPASS[key]
if isinstance(new_key, str):
return (new_key, value)
else:
return (new_key[0], new_key[1](value))
def transform_field(key, value):
new_key = CLUBDESK_TO_KOMPASS[key]
if isinstance(new_key, str):
return (new_key, value)
else:
return (new_key[0], new_key[1](value))
def transform_row(row):
kwargs = dict([ transform_field(k, v) for k, v in row.items() if k in CLUBDESK_TO_KOMPASS ])
kwargs_filtered = { k : v for k, v in kwargs.items() if k in ['prename', 'lastname', 'email', 'birth_date', 'application_text', 'application_date'] }
mem = MemberWaitingList(gender=DIVERSE, **kwargs_filtered)
mem.save()
if kwargs['contacted_by']:
group_name = kwargs['contacted_by']
try:
group = Group.objects.get(name=group_name)
invitation = InvitationToGroup(group=group, waiter=mem)
invitation.save()
except Group.DoesNotExist:
pass
for row in rows:
transform_row(row)

@ -4,7 +4,6 @@ import os
import subprocess
import time
import glob
import logging
from io import BytesIO
from pypdf import PdfReader, PdfWriter, PageObject
from django import template
@ -16,15 +15,13 @@ from contrib.media import media_path, media_dir, serve_media, ensure_media_dir,
from utils import normalize_filename
from PIL import Image
logger = logging.getLogger(__name__)
def serve_pdf(filename_pdf):
return serve_media(filename_pdf, 'application/pdf')
def generate_tex(name, template_path, context, date=None):
filename = normalize_filename(name, date=date)
def generate_tex(name, template_path, context):
filename = normalize_filename(name)
filename_tex = filename + '.tex'
tmpl = get_template(template_path)
@ -37,8 +34,8 @@ def generate_tex(name, template_path, context, date=None):
return filename
def render_docx(name, template_path, context, date=None, save_only=False):
filename = generate_tex(name, template_path, context, date=date)
def render_docx(name, template_path, context, save_only=False):
filename = generate_tex(name, template_path, context)
filename_tex = filename + '.tex'
filename_docx = filename + '.docx'
oldwd = os.getcwd()
@ -50,26 +47,9 @@ def render_docx(name, template_path, context, date=None, save_only=False):
return filename_docx
return serve_media(filename_docx, 'application/docx')
def render_tex_with_attachments(name, template_path, context, attachments, save_only=False):
rendered_pdf = render_tex(name, template_path, context, save_only=True)
reader = PdfReader(media_path(rendered_pdf))
writer = PdfWriter()
writer.append(reader)
pdf_add_attachments(writer, attachments)
with open(media_path(rendered_pdf), 'wb') as output_stream:
writer.write(output_stream)
if save_only:
return rendered_pdf
return serve_pdf(rendered_pdf)
def render_tex(name, template_path, context, date=None, save_only=False):
filename = generate_tex(name, template_path, context, date=date)
def render_tex(name, template_path, context, save_only=False):
filename = generate_tex(name, template_path, context)
filename_tex = filename + '.tex'
filename_pdf = filename + '.pdf'
# compile using pdflatex
@ -93,54 +73,32 @@ def render_tex(name, template_path, context, date=None, save_only=False):
return serve_pdf(filename_pdf)
def pdf_add_attachments(pdf_writer, attachments):
for fp in attachments:
try:
if fp.endswith(".pdf"):
# append pdf directly
img_pdf = PdfReader(fp)
else:
# convert ensures that png files with an alpha channel can be appended
img = Image.open(fp).convert("RGB")
img_io = BytesIO()
img.save(img_io, "pdf")
img_io.seek(0)
img_pdf = PdfReader(img_io)
img_pdf_scaled = scale_pdf_to_a4(img_pdf)
pdf_writer.append(img_pdf_scaled)
except Exception as e:
logger.warning(f"Could not add image under filepath {fp}: {e}.")
def scale_pdf_page_to_a4(page):
A4_WIDTH, A4_HEIGHT = 595, 842
page_width = page.mediabox.width
page_height = page.mediabox.height
scale_x = A4_WIDTH / page_width
scale_y = A4_HEIGHT / page_height
scale_factor = min(scale_x, scale_y)
new_page = PageObject.create_blank_page(width=A4_WIDTH, height=A4_HEIGHT)
page.scale_by(scale_factor)
x_offset = (A4_WIDTH - page.mediabox.width) / 2
y_offset = (A4_HEIGHT - page.mediabox.height) / 2
new_page.merge_translated_page(page, x_offset, y_offset)
return new_page
def scale_pdf_to_a4(pdf):
scaled_pdf = PdfWriter()
for page in pdf.pages:
scaled_pdf.add_page(scale_pdf_page_to_a4(page))
return scaled_pdf
def fill_pdf_form(name, template_path, fields, attachments=[], date=None, save_only=False):
filename = normalize_filename(name, date=date)
def fill_pdf_form(name, template_path, fields, attachments=[], save_only=False):
filename = normalize_filename(name)
filename_pdf = filename + '.pdf'
path = find_template(template_path)
@ -154,7 +112,23 @@ def fill_pdf_form(name, template_path, fields, attachments=[], date=None, save_o
writer.update_page_form_field_values(None, fields, auto_regenerate=False)
pdf_add_attachments(writer, attachments)
for fp in attachments:
try:
if fp.endswith(".pdf"):
# append pdf directly
img_pdf = PdfReader(fp)
else:
# convert ensures that png files with an alpha channel can be appended
img = Image.open(fp).convert("RGB")
img_io = BytesIO()
img.save(img_io, "pdf")
img_io.seek(0)
img_pdf = PdfReader(img_io)
img_pdf_scaled = scale_pdf_to_a4(img_pdf)
writer.append(img_pdf_scaled)
except Exception as e:
print("Could not add image", fp)
print(e)
with open(media_path(filename_pdf), 'wb') as output_stream:
writer.write(output_stream)
@ -164,13 +138,13 @@ def fill_pdf_form(name, template_path, fields, attachments=[], date=None, save_o
return serve_pdf(filename_pdf)
def merge_pdfs(name, filenames, date=None, save_only=False):
def merge_pdfs(name, filenames, save_only=False):
merger = PdfWriter()
for pdf in filenames:
merger.append(media_path(pdf))
filename = normalize_filename(name, date=date)
filename = normalize_filename(name)
filename_pdf = filename + ".pdf"
merger.write(media_path(filename_pdf))
merger.close()

@ -1,5 +1,4 @@
from contrib.rules import memberize_user
from django.utils import timezone
from rules import predicate
@ -61,7 +60,7 @@ def _is_leader(member, excursion):
return False
if member in excursion.jugendleiter.all():
return True
yl = [ yl for group in excursion.groups.all() for yl in group.leiters.all() ]
yl = [ yl for group in member.group.all() for yl in group.leiters.all() ]
return member in yl
@ -74,10 +73,3 @@ def statement_not_submitted(self, excursion):
if excursion.statement is None:
return False
return not excursion.statement.submitted
@predicate
@memberize_user
def is_leader_of_relevant_invitation(member, waiter):
assert waiter is not None
return waiter.invitationtogroup_set.filter(group__leiters=member).exists()

@ -1,7 +1,7 @@
from celery import shared_task
from django.utils import timezone
from django.conf import settings
from .models import MemberWaitingList, Freizeit
from .models import MemberWaitingList
@shared_task
def ask_for_waiting_confirmation():
@ -18,29 +18,3 @@ def ask_for_waiting_confirmation():
waiter.ask_for_wait_confirmation()
no += 1
return no
@shared_task
def send_crisis_intervention_list():
"""
Send crisis intervention lists for all excursions that start on the current day and
that have not been sent yet.
"""
no = 0
for excursion in Freizeit.to_send_crisis_intervention_list():
excursion.send_crisis_intervention_list()
no += 1
return no
@shared_task
def send_notification_crisis_intervention_list():
"""
Send crisis intervention list notifiactions for all excursions that start on the next
day and that have not been sent yet.
"""
no = 0
for excursion in Freizeit.to_notify_crisis_intervention_list():
excursion.notify_leaders_crisis_intervention_list()
no += 1
return no

@ -122,15 +122,8 @@ cost plan!
</p>
{% else %}
<p>{% blocktrans %}No receivers of the subsidies were provided. Subsidies will not be used.{% endblocktrans %}</p>
{% endif %}
{% if total_org_fee %}
<h3>{% trans "Org fee" %}</h3>
<p>
{% blocktrans %}Warning: {{ old_participant_count }} participant(s) of the excursion are 27 or older. For each of them, an organisation fee of {{ org_fee }} € per day has to be paid to the account. With a duration of {{ duration }} days, a total of {{ total_org_fee_theoretical }} € is charged against the other transactions.{% endblocktrans %}
</p>
{% endif %}
{% if not memberlist.statement.allowance_to_valid %}
<p>
{% blocktrans %}Warning: The configured recipients of the allowance don't match the regulations. This might be because the number of recipients is bigger then the number of admissable youth leaders for this excursion.{% endblocktrans %}
@ -138,63 +131,12 @@ cost plan!
{% endif %}
<h3>{% trans "LJP contributions" %}</h3>
{% if memberlist.statement.ljp_to %}
<p>
{% blocktrans %}By submitting the given seminar report, you will receive LJP contributions.
You have documented interventions worth of {{ total_seminar_days }} seminar days for {{ participant_count }} participants.
This results in a total contribution of {{ ljp_contributions }}€.
To receive them, you need to submit the LJP-Proposal within 3 weeks after your excursion and have it approved by the finance office.{% endblocktrans %}
</p>
<table>
<tr>
<td></td>
<td>{% trans "Seminar hours" %}</td>
<td>{% trans "Seminar days" %}</td>
</tr>
{% for day in memberlist.seminar_time_per_day %}
<tr>
<td>{{ day.day }}</td>
<td>{{ day.total_duration }}</td>
<td>{{ day.sum_days }}</td>
</tr>
{% endfor %}
<tr>
<td><b>{% trans "Sum" %}</b></td>
<td></td>
<td>{{ total_seminar_days }}</td>
</tr>
</table>
<p>
{% blocktrans %}The LJP contributions are configured to be paid to:{% endblocktrans %}
<table>
<th>
<td>{% trans "IBAN valid" %}</td>
</th>
<tr>
<td>{{ memberlist.statement.ljp_to.name }}</td>
<td>{{ memberlist.statement.ljp_to.iban_valid|render_bool }}</td>
</tr>
</table>
</p>
{% else %}
<p>
{% blocktrans %}By submitting a seminar report, you may apply for LJP contributions. In this case,
you may obtain up to 25€ times {{ duration }} days for {{ theoretic_ljp_participant_count }} participants but only up to
90% of the total costs. This results in a total of {{ ljp_contributions }}€. If you have created a seminar report, you need to specify who should receive the contributions in order to make use of them.{% endblocktrans %}
</p>
{% endif %}
{% if memberlist.theoretic_ljp_participant_count < 5 %}
<p>
{% blocktrans %} Warning: LJP contributions can only be claimed for activities with at least 5 participants and one leader. This activity currently has only {{ theoretic_ljp_participant_count }} participants.{% endblocktrans %}
you may obtain up to 25€ times {{ duration }} days for {{ participant_count }} participants but only up to
90% of the total costs. This results in a total of {{ ljp_contributions }}€.{% endblocktrans %}
</p>
{% endif %}
<h3>{% trans "Summary" %}</h3>
@ -211,14 +153,6 @@ you may obtain up to 25€ times {{ duration }} days for {{ theoretic_ljp_partic
{{ total_bills_theoretic }}€
</td>
</tr>
<tr>
<td>
{% trans "Organisation fees" %}
</td>
<td>
{{ total_org_fee }}€
</td>
</tr>
<tr>
<td>
{% trans "Contributions by the association" %}
@ -229,7 +163,7 @@ you may obtain up to 25€ times {{ duration }} days for {{ theoretic_ljp_partic
</tr>
<tr>
<td>
{% if memberlist.statement.ljp_to %}{% trans "LJP contributions" %}{% else %}{% trans "Potential LJP contributions" %}{% endif %}
{% trans "Potential LJP contributions" %}
</td>
<td>
-{{ ljp_contributions }}€

@ -1,40 +0,0 @@
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static %}
{% block extrahead %}
{{ block.super }}
{{ media }}
<script src="{% static 'admin/js/cancel.js' %}" async></script>
<script type="text/javascript" src="{% static "admin/js/vendor/jquery/jquery.js" %}"></script>
<script type="text/javascript" src="{% static "admin/js/jquery.init.js" %}"></script>
{% endblock %}
{% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} invite-waiter
{% endblock %}
{% block breadcrumbs %}
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}">{% translate 'Home' %}</a>
&rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a>
&rsaquo; <a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a>
&rsaquo; {% translate 'Demote to waiter' %}
</div>
{% endblock %}
{% block content %}
<h2>{% translate "Request registration form" %}</h2>
<p>
{% blocktrans %}Do you want to ask {{ member }} to upload their registration form?{% endblocktrans %}
</p>
<p>
{% if member.registration_form %}
{% blocktrans %}Warning: {{ member }} has already uploaded a registration form.{% endblocktrans %}
{% endif %}
</p>
<form action="" method="post">
{% csrf_token %}
<input class="default" style="color: $default-link-color" type="submit" name="apply" value="{% translate 'Request registration form' %}">
<a href="#" class="button cancel-link">{% translate "Cancel" %}</a>
</form>
{% endblock %}

@ -1,48 +0,0 @@
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static %}
{% block extrahead %}
{{ block.super }}
{{ media }}
<script src="{% static 'admin/js/cancel.js' %}" async></script>
<script type="text/javascript" src="{% static "admin/js/vendor/jquery/jquery.js" %}"></script>
<script type="text/javascript" src="{% static "admin/js/jquery.init.js" %}"></script>
{% endblock %}
{% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} invite-waiter
{% endblock %}
{% block breadcrumbs %}
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}">{% translate 'Home' %}</a>
&rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a>
&rsaquo; <a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a>
&rsaquo; {% translate 'Demote to waiter' %}
</div>
{% endblock %}
{% block content %}
<h2>{% translate "Demote to waiter" %}</h2>
<p>
{% trans "Do you want to demote the following unconfirmed registrations to waiters?" %}
</p>
<p>
<ul>
{% for member in queryset %}
<li>
<a href="{% url 'admin:members_memberunconfirmedproxy_change' 3 %}">{{ member }}</a>
</li>
{% endfor %}
</ul>
</p>
<form action="" method="post">
{% csrf_token %}
{% if form %}
{{form}}
{% endif %}
<input type="hidden" name="action" value="demote_to_waiter_action">
<input class="default" style="color: $default-link-color" type="submit" name="apply" value="{% translate 'Demote' %}">
<a href="#" class="button cancel-link">{% translate "Cancel" %}</a>
</form>
{% endblock %}

@ -1,15 +0,0 @@
{% extends "members/base.html" %}
{% load i18n %}
{% load static %}
{% block title %}
{% trans "Confirm invitation" %}
{% endblock %}
{% block content %}
<h1>{% trans "Confirm invitation" %}</h1>
<p>{% trans "This invitation is invalid or expired." %}</p>
{% endblock %}

@ -1,29 +0,0 @@
{% extends "members/base.html" %}
{% load i18n %}
{% load static %}
{% block title %}
{% trans "Confirm trial group meeting invitation" %}
{% endblock %}
{% block content %}
<h1>{% trans "Confirm trial group meeting invitation" %}</h1>
<p>
{% blocktrans %}You were invited to a trial group meeting of the group {{ groupname }}.{% endblocktrans %}
{{ timeinfo }}
</p>
<p>
{% blocktrans %}Do you want to take part in the trial group meeting? If yes, please confirm your attendance by clicking on the following button.{% endblocktrans %}
</p>
<form action="" method="post">
{% csrf_token %}
<input type="hidden" name="key" value="{{invitation.key}}">
<input type="submit" name="confirm_invitation"
value="{% trans "Confirm trial group meeting" %}"/>
</form>
{% endblock %}

@ -1,23 +0,0 @@
{% extends "members/base.html" %}
{% load i18n %}
{% load static %}
{% block title %}
{% trans "Invitation confirmed" %}
{% endblock %}
{% block content %}
<h1>{% trans "Invitation confirmed" %}</h1>
<p>
{% blocktrans %}You successfully confirmed the invitation to the trial group meeting of the group {{ groupname }}.{% endblocktrans %}
{{ timeinfo }}
</p>
<p>
{% blocktrans %}We have informed the group leaders about your confirmation. If for some reason you can not make it,
please contact the group leaders at{% endblocktrans %}
<a href="mailto:{{ contact_email }}">{{ contact_email }}</a>.
</p>
{% endblock %}

@ -1,9 +1,74 @@
{% extends "members/tex_base.tex" %}
{% load static common tex_extras %}
{% block title %}Teilnehmer*innenliste Sektionsveranstaltung{% endblock %}
\documentclass[a4paper]{article}
{% block content %}
\usepackage[utf8]{inputenc}
% remove all undefined unicode characters instead of throwing an error
\makeatletter
\def\UTFviii@undefined@err#1{}
\makeatother
\usepackage{booktabs}
\usepackage{amssymb}
\usepackage{cmbright}
\usepackage{graphicx}
\usepackage{textpos}
\usepackage[colorlinks, breaklinks]{hyperref}
\usepackage{float}
\usepackage[margin=2cm]{geometry}
\usepackage{array}
\usepackage{tabularx}
\usepackage{ltablex}
\newcommand{\picpos}[4]{
\begin{textblock*}{#1}(#2, #3)
\includegraphics[width=\textwidth]{#4}
\end{textblock*}
}
% custom url command for properly formatting emails
\DeclareUrlCommand\Email{\urlstyle{same}}
% allow linebreak after every character
\expandafter\def\expandafter\UrlBreaks\expandafter{\UrlBreaks
\do\/\do\a\do\b\do\c\do\d\do\e\do\f\do\g\do\h\do\i\do\j\do\k
\do\l\do\m\do\n\do\o\do\p\do\q\do\r\do\s\do\t\do\u\do\v
\do\w\do\x\do\y\do\z
\do\A\do\B\do\C\do\D\do\E\do\F\do\G\do\H\do\I\do\J\do\K
\do\L\do\M\do\N\do\O\do\P\do\Q\do\R\do\S\do\T\do\U\do\V
\do\W\do\X\do\Y\do\Z}
\renewcommand{\arraystretch}{1.5}
\newcolumntype{L}{>{\hspace{0pt}\raggedright\arraybackslash}X}
\newcolumntype{S}{>{\raggedright\arraybackslash\hsize=0.7\hsize}X}
\newcommand{\tickedbox}{
\makebox[0pt][l]{$\square$}\raisebox{.15ex}{\hspace{0.1em}$\checkmark$}
}
\newcommand{\checkbox}{
\makebox[0pt][l]{$\square$}
}
\begin{document}
% HEADER RIGHT
{% settings_value 'DEFAULT_STATIC_PATH' as static_root %}
\picpos{4.5cm}{11.5cm}{0cm}{%
{{ static_root }}/general/img/dav_logo_sektion.png%
}
\begin{textblock*}{5cm}(12cm, 2.3cm)
\begin{flushright}
\small
\noindent Deutscher Alpenverein e. V. \\
Sektion {{ settings.SEKTION }} \\
{{ settings.SEKTION_STREET }} \\
{{ settings.SEKTION_TOWN }} \\
Tel.: {{ settings.SEKTION_TELEPHONE }} \\
Fax: {{ settings.SEKTION_TELEFAX }} \\
{{ settings.SEKTION_CONTACT_MAIL }} \\
\end{flushright}
\end{textblock*}
% HEADLINE
{\noindent\LARGE{Teilnehmer*innenliste\\[2mm]Sektionsveranstaltung}}\\[1mm]
\textit{Erstellt: {{ creation_date }} }\\
% DESCRIPTION TABLE
\begin{table}[H]
@ -24,7 +89,7 @@
\end{tabular}
\end{table}
\begin{tabularx}{.97\linewidth}{lXXXX}
\begin{tabularx}{1\linewidth}{lSLSL}
\toprule
\# & \textbf{Name} & \textbf{Anschrift} & \textbf{Telefon} & \textbf{Notfallkontakte} \\
\midrule
@ -33,7 +98,7 @@
\endfoot
{% for m in memberlist.membersonlist.all %}
{{ forloop.counter }} &
{{ forloop.counter }} &
{{ m.member.name|esc_all }} &
{{ m.member.address_multiline|esc_all }} &
{{ m.member.contact_phone_number|esc_all }} &
@ -50,4 +115,4 @@
\noindent Bitte die ausgefüllte Teilnehmerliste vor Antritt der Aktivität per E-Mail an
\href{mailto:{{ settings.SEKTION_CRISIS_INTERVENTION_MAIL }}}{ {{ settings.SEKTION_CRISIS_INTERVENTION_MAIL }} } senden.
{% endblock content %}
\end{document}

@ -12,7 +12,7 @@
<h1>{% trans "Echo" %}</h1>
<p>{% trans "Here is your current data. Please check if it is up to date and change accordingly." %}</p>
<p>{% trans "Thanks for echoing back. Here is your current data:" %}</p>
{% if error_message %}
<p><b>{{ error_message }}</b></p>

@ -1,65 +0,0 @@
{% extends "members/tex_base.tex" %}
{% load static common tex_extras %}
{% block headline %}{% endblock %}
{% block contact %}{% endblock %}
{% block extra-preamble %}
\usepackage{rotating}
\usepackage[code=Code39,X=.48mm,ratio=3.5,H=0.5cm]{makebarcode}
\geometry{reset,margin=1cm, bottom=1.5cm}
\renewcommand{\arraystretch}{1}
{% endblock %}
{% block content %}
{% settings_value 'DEFAULT_STATIC_PATH' as static_root %}
{% for group in groups %}
\picpos{2.5cm}{16cm}{-0.4cm}{%
{{ static_root }}/general/img/dav_logo_sektion.png%
}
% HEADLINE
{\noindent\Large{Gruppenliste {{ group.name }} }}\\[1mm]
{% if group.has_time_info %} \noindent {{ weekdays|index:group.weekday|esc_all }}, {{ group.start_time }} - {{ group.end_time }} Uhr\\ {% endif %}
\noindent {{ header_text }}
\begin{table}[H]
\centering
%\begin{tabularx}{\textwidth}{lYY|l|l|l|l|l|l|l|l|l|l|l|l|l|l|l|l|l}
\begin{tabularx}{\textwidth}{X{% for i in week_range %}|l{% endfor%}}
\toprule
\textbf{Name} {% for i in week_range %}
& \begin{sideways} {{ dates|index:i|add:group.weekday|date_vs }} \end{sideways}
{% endfor %} \\
{% for j in member_range %}
{% with m=group.sorted_members|index:j %}
{% with codelength=m.ticket_tag|length %}
\midrule
\begin{tabular}{@{}l}
{% if codelength > 2 %}
\barcode[
X=\dimexpr 3.5mm / \numexpr {{ codelength }} \relax \relax
]{{ m.ticket_tag }}
{% else %}
\rule{0pt}{5mm}
{% endif %}
\vspace{-0.8ex} \\
{\small {{ j|plus:1 }} {% if m in group.leiters.all %}\textbf{JL}{% endif %}
{{ m.name|esc_all }} {% if codelength > 2 %} - {{ m.ticket_tag }}{% endif %}
\vspace{-3ex} }
\end{tabular}
{% for i in week_range %} & {% endfor %}\\
{% endwith %}
{% endwith %}
{% endfor %}
\bottomrule
\end{tabularx}
\end{table}
\clearpage
{% endfor %}
{% endblock content %}

@ -34,7 +34,7 @@
<input type="hidden" name="waiter_key" value="{{ waiter_key }}">
<input type="hidden" name="save">
<input type="hidden" name="key" value="{{ key }}">
<p><input style="font-size: 14pt" type="submit" value="{% trans "Save" %}"/></p>
<p><input type="submit" value="{% trans "Save" %}"/></p>
</form>
<div id="empty_form" class="form-row" style="display:none">

@ -1,12 +1,34 @@
{% extends "members/tex_base.tex" %}
{% load static common tex_extras %}
{% load tex_extras %}
{% block title %}{{ memberlist.title|esc_all }}{% endblock %}
{% block contact %}{% endblock %}
\documentclass{article}
{% block content %}
\usepackage[utf8]{inputenc}
% remove all undefined unicode characters instead of throwing an error
\makeatletter
\def\UTFviii@undefined@err#1{}
\makeatother
\usepackage{booktabs}
\usepackage{tabularx}
\usepackage{ragged2e}
\usepackage{amssymb}
\usepackage{cmbright}
\usepackage{graphicx}
\usepackage{textpos}
\usepackage[colorlinks]{hyperref}
\usepackage{float}
\usepackage[margin=1cm]{geometry}
\begin{tabularx}{\textwidth}{l X}
\renewcommand{\arraystretch}{1.5}
\newcolumntype{Y}{>{\RaggedRight\arraybackslash}X}
\begin{document}
% HEADLINE
{\noindent\LARGE\textsc{ {{ memberlist.title|esc_all }} }}\\
\textit{Erstellt: {{ creation_date }} }\\
\begin{table}[H]
\begin{tabularx}{\textwidth}{@{} l l Y @{}}
\toprule
\textbf{Name} & \textbf{Kommentare} \\
\midrule
@ -14,6 +36,7 @@
{{ m.member.name|esc_all }} & {{ m.comments_tex|esc_all }} \\
{% endfor %}
\bottomrule
\end{tabularx}
\end{tabularx}
\end{table}
{% endblock %}
\end{document}

@ -1,9 +1,32 @@
{% extends "members/tex_base.tex" %}
{% load static common tex_extras %}
{% load tex_extras %}
{% block title %}Teilnehmer*innenübersicht{% endblock %}
\documentclass[a4paper]{article}
{% block content %}
\usepackage[utf8]{inputenc}
% remove all undefined unicode characters instead of throwing an error
\makeatletter
\def\UTFviii@undefined@err#1{}
\makeatother
\usepackage{booktabs}
\usepackage{tabularx}
\usepackage{ragged2e}
\usepackage{amssymb}
\usepackage{cmbright}
\usepackage{graphicx}
\usepackage{textpos}
\usepackage[colorlinks]{hyperref}
\usepackage{float}
\usepackage[margin=1cm]{geometry}
\usepackage{ltablex}
\renewcommand{\arraystretch}{1.5}
\newcolumntype{Y}{>{\RaggedRight\arraybackslash}p{0.4\linewidth}}
\begin{document}
% HEADLINE
{\noindent\LARGE{Teilnehmer*innenübersicht}}\\[1mm]
\textit{Erstellt: {{ creation_date }} }\\
% DESCRIPTION
\begin{table}[H]
@ -17,21 +40,20 @@
\end{tabular}
\end{table}
\begin{tabularx}{.97\linewidth}{lXXX}
\begin{tabularx}{1\linewidth}{ l l l Y}
\toprule
\# & \textbf{Name} & \textbf{Fähigkeiten (max. 100)} & \textbf{Kommentare} \\
\midrule
\endhead
\bottomrule
\endfoot
{% for p in people %}
{{ forloop.counter }} & {{ p.name|esc_all }} & {{ p.qualities|esc_all }} & {{ p.comments|esc_all }} \\
{% endfor %}
\bottomrule
\end{tabularx}
\noindent{\large Fähigkeiten der Gruppe}\\
\begin{tabularx}{.97\linewidth}{Xlll}
\noindent\large Fähigkeiten der Gruppe\\
\begin{table}[H]
\begin{tabular*}{1\linewidth}{@{\extracolsep{\fill}}llll}
\toprule
\textbf{Name} & \textbf{Durchschnitt} & \textbf{Minimum} & \textbf{Maximum} \\
\midrule
@ -39,6 +61,9 @@
{{ skill.name|esc_all }} & {{ skill.skill_avg|esc_all }} & {{ skill.skill_min|esc_all }} & {{ skill.skill_max|esc_all }} \\
{% endfor %}
\bottomrule
\end{tabularx}
\end{tabular*}
\end{table}
\vspace{1cm}
{% endblock %}
\end{document}

@ -1,9 +1,80 @@
{% extends "members/tex_base.tex" %}
{% load static common tex_extras %}
{% block title %}Seminarbericht{% endblock %}
\documentclass[a4paper]{article}
{% block content %}
\usepackage[utf8]{inputenc}
% remove all undefined unicode characters instead of throwing an error
\makeatletter
\def\UTFviii@undefined@err#1{}
\makeatother
\usepackage{booktabs}
\usepackage{amssymb}
\usepackage{cmbright}
\usepackage{graphicx}
\usepackage{textpos}
\usepackage[colorlinks, breaklinks]{hyperref}
\usepackage{float}
\usepackage[margin=1in]{geometry}
\usepackage{array}
\usepackage{ragged2e}
\usepackage{tabularx}
\usepackage{titlesec}
\usepackage{ltablex}
\titleformat{\section}
{\Large\slshape}{\thesection\;}
{0em}{}
\newcommand{\picpos}[4]{
\begin{textblock*}{#1}(#2, #3)
\includegraphics[width=\textwidth]{#4}
\end{textblock*}
}
% custom url command for properly formatting emails
\DeclareUrlCommand\Email{\urlstyle{same}}
% allow linebreak after every character
\expandafter\def\expandafter\UrlBreaks\expandafter{\UrlBreaks
\do\/\do\a\do\b\do\c\do\d\do\e\do\f\do\g\do\h\do\i\do\j\do\k
\do\l\do\m\do\n\do\o\do\p\do\q\do\r\do\s\do\t\do\u\do\v
\do\w\do\x\do\y\do\z
\do\A\do\B\do\C\do\D\do\E\do\F\do\G\do\H\do\I\do\J\do\K
\do\L\do\M\do\N\do\O\do\P\do\Q\do\R\do\S\do\T\do\U\do\V
\do\W\do\X\do\Y\do\Z}
\renewcommand{\arraystretch}{1.5}
\newcolumntype{L}{>{\hspace{0pt}}X}
\newcolumntype{Y}{>{\RaggedRight\arraybackslash}X}
\newcommand{\tickedbox}{
\makebox[0pt][l]{$\square$}\raisebox{.15ex}{\hspace{0.1em}$\checkmark$}
}
\newcommand{\checkbox}{
\makebox[0pt][l]{$\square$}
}
\begin{document}
% HEADER RIGHT
{% settings_value 'DEFAULT_STATIC_PATH' as static_root %}
\picpos{4.5cm}{11.5cm}{0cm}{%
{{ static_root }}/general/img/dav_logo_sektion.png%
}
\begin{textblock*}{5cm}(11.5cm, 2.3cm)
\begin{flushright}
\small
\noindent Deutscher Alpenverein e. V. \\
Sektion {{ settings.SEKTION }} \\
{{ settings.SEKTION_STREET }} \\
{{ settings.SEKTION_TOWN }} \\
Tel.: {{ settings.SEKTION_TELEPHONE }} \\
Fax: {{ settings.SEKTION_TELEFAX }} \\
{{ settings.RESPONSIBLE_MAIL }} \\
\end{flushright}
\end{textblock*}
% HEADLINE
{\noindent\LARGE{Seminarbericht}}\\[1mm]
\textit{Erstellt: {{ creation_date }} }\\
% DESCRIPTION TABLE
\begin{table}[H]
@ -18,14 +89,54 @@
\end{tabular}
\end{table}
\section{Teilnehmer*innenliste}
{% if mode == 'full' %}
{% if memberlist.ljpproposal %}
\section{Alpintechnische Ziele}
{{ memberlist.ljpproposal.goals_alpinistic|esc_all }}
\section{Pädagogische Ziele}
{{ memberlist.ljpproposal.goals_pedagogic|esc_all }}
\section{Inhalte und Methoden}
{{ memberlist.ljpproposal.methods|esc_all }}
\section{Wertung}
{{ memberlist.ljpproposal.evaluation|esc_all }}
\section{Erfahrungen und Verbesserungsvorschläge}
\begin{tabularx}{.97\linewidth}{lp{0.2\textwidth}Xlccc}
{{ memberlist.ljpproposal.experiences|esc_all }}
\section{Zeitlicher und methodischer Ablauf}
\begin{table}[H]
\begin{tabularx}{1\linewidth}{@{}l l Y @{}}
\toprule
\# & \textbf{Name} & \textbf{Anschrift} & \textbf{Geburtsdatum} & \textbf{m} & \textbf{w} & \textbf{d} \\
\textbf{Zeitpunkt} & \textbf{Dauer} & \textbf{Art der Aktion inkl. Methode} \\
\midrule
\endhead
{% for intervention in memberlist.ljpproposal.intervention_set.all %}
{{ intervention.date_start|datetime_short }} & {{ intervention.duration }} h & {{ intervention.activity|esc_all }} \\
{% endfor %}
\bottomrule
\end{tabularx}
\end{table}
{% endif %}
{% endif %}
\section{Teilnehmer*innenliste}
\begin{tabularx}{1\linewidth}{p{0.01\linewidth}>{\RaggedRight\arraybackslash}p{0.22\linewidth}>{\RaggedRight\arraybackslash}p{0.38\linewidth}p{0.14\linewidth}|c|c|c}
\hline
\# & \textbf{Name} & \textbf{Anschrift} & \textbf{Geburtsdatum} & \textbf{m} & \textbf{w} & \textbf{d} \\
\hline
\endhead
\hline
\endfoot
{% for m in memberlist.membersonlist.all %}
{{ forloop.counter }} & {{ m.member.name|esc_all }} & {{ m.member.address|esc_all }} & {{ m.member.birth_date_str|esc_all }}
@ -39,7 +150,7 @@
\section{Kosten}
\begin{tabularx}{.97\textwidth}{Xr}
\begin{tabularx}{1\linewidth}{@{\extracolsep{\fill}}Lr}
\toprule
\textbf{Beschreibung} & \textbf{Betrag} \\
\midrule
@ -49,11 +160,10 @@
{% for bill in memberlist.statement.grouped_bills %}
{{ bill.short_description|esc_all }} & {{ bill.amount }}\\
{% endfor %}
\midrule
Gesamt & {{ memberlist.statement.total_theoretic }}\\
\bottomrule
Gesamt & {{ memberlist.statement.total_theoretic }}\\
\end{tabularx}
{% endif %}
{% endblock %}
\end{document}

@ -1,4 +1,4 @@
{% load tex_extras tz %}
{% load tex_extras %}
\documentclass[a4paper]{article}
@ -36,7 +36,7 @@
\textbf{Sektion:} & {{ settings.SEKTION }} \\
\textbf{Titel der Maßnahme:} & {% if not memberlist.ljpproposal %}{{ memberlist.name|esc_all }}{% else %}{{ memberlist.ljpproposal.title }} {% endif %} \\
\textbf{Interne Ordnungsnummer:} & {{ memberlist.code|esc_all }} \\
\textbf{Anzahl der durchgeführten Lehrgangstage:} & {{ memberlist.ljp_duration }} \\
\textbf{Anzahl der durchgeführten Lehrgangstage:} & {{ memberlist.duration }} \\
\end{tabular}
\end{table}
@ -63,8 +63,8 @@
\textbf{Datum} & \textbf{Uhrzeit} & \multicolumn{4}{l}{\textbf{Art der Aktion}} & \textbf{Dauer} \\
\midrule
{% for intervention in memberlist.ljpproposal.intervention_set.all %}
{{ intervention.date_start|localtime|date_short }}
& {{ intervention.date_start|localtime|time_short }}
{{ intervention.date_start|date_short }}
& {{ intervention.date_start|time_short }}
& \multicolumn{4}{l}{ {{ intervention.activity|esc_all }} }
& {{ intervention.duration }} h \\
{% endfor %}

@ -1,98 +0,0 @@
{% load static common tex_extras %}
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
% remove all undefined unicode characters instead of throwing an error
\makeatletter
\def\UTFviii@undefined@err#1{}
\makeatother
\usepackage{booktabs}
\usepackage{amssymb}
\usepackage{cmbright}
\usepackage{graphicx}
\usepackage{textpos}
\usepackage[colorlinks, breaklinks]{hyperref}
\usepackage{float}
\usepackage[margin=2cm]{geometry}
\usepackage{array}
\usepackage{tabularx}
\usepackage{ltablex}
\usepackage{ragged2e}
\usepackage{titlesec}
\keepXColumns
\titleformat{\section}
{\Large\slshape}{\thesection\;}
{0em}{}
\newcommand{\picpos}[4]{
\begin{textblock*}{#1}(#2, #3)
\includegraphics[width=\textwidth]{#4}
\end{textblock*}
}
% custom url command for properly formatting emails
\DeclareUrlCommand\Email{\urlstyle{same}}
% allow linebreak after every character
\expandafter\def\expandafter\UrlBreaks\expandafter{\UrlBreaks
\do\/\do\a\do\b\do\c\do\d\do\e\do\f\do\g\do\h\do\i\do\j\do\k
\do\l\do\m\do\n\do\o\do\p\do\q\do\r\do\s\do\t\do\u\do\v
\do\w\do\x\do\y\do\z
\do\A\do\B\do\C\do\D\do\E\do\F\do\G\do\H\do\I\do\J\do\K
\do\L\do\M\do\N\do\O\do\P\do\Q\do\R\do\S\do\T\do\U\do\V
\do\W\do\X\do\Y\do\Z}
\renewcommand{\arraystretch}{1.5}
\newcolumntype{L}{>{\hspace{0pt}\raggedright\arraybackslash}X}
\newcolumntype{S}{>{\raggedright\arraybackslash\hsize=0.7\hsize}X}
\newcolumntype{Y}{>{\RaggedRight\arraybackslash}p{0.4\linewidth}}
\newcommand{\tickedbox}{
\makebox[0pt][l]{$\square$}\raisebox{.15ex}{\hspace{0.1em}$\checkmark$}
}
\newcommand{\checkbox}{
\makebox[0pt][l]{$\square$}
}
{% block extra-preamble %}
{% endblock extra-preamble %}
\begin{document}
{% block contact %}
% HEADER RIGHT
{% settings_value 'DEFAULT_STATIC_PATH' as static_root %}
\picpos{4.5cm}{11.7cm}{0cm}{%
{{ static_root }}/general/img/dav_logo_sektion.png%
}
\begin{textblock*}{5cm}(11.7cm, 2.3cm)
\begin{flushright}
\small
\noindent Deutscher Alpenverein e. V. \\
Sektion {{ settings.SEKTION }} \\
{{ settings.SEKTION_STREET }} \\
{{ settings.SEKTION_TOWN }} \\
Tel.: {{ settings.SEKTION_TELEPHONE }} \\
Fax: {{ settings.SEKTION_TELEFAX }} \\
{{ settings.RESPONSIBLE_MAIL }} \\
\end{flushright}
\end{textblock*}
{% endblock contact %}
{% block headline %}
% HEADLINE
{\LARGE{\noindent {% block title %}{% endblock title %} }}\\[1mm]
\textit{Erstellt: {{ creation_date }} }\\
{% endblock headline %}
{% block content %}
{% endblock content %}
\end{document}

@ -3,36 +3,19 @@
{% load static %}
{% block title %}
{% if member.confirmed %}
{% trans "Echo" %}
{% else %}
{% trans "Registration" %}
{% endif %}
{% endblock %}
{% block content %}
{% if member.confirmed %}
<h1>{% trans "Echo" %}</h1>
{% else %}
<h1>{% trans "Register" %}</h1>
{% endif %}
{% url 'members:download_registration_form' as download_url %}
{% if member.confirmed %}
<p>{% blocktrans %}Thank you for echoing back, your data was updated. For legal
reasons, we also need a signed participation form. In your case, a recent
participation form is missing. Please <a href="{{ download_url }}?key={{ key }}">download</a>
the pre-filled form, fill in the remaining fields and read the general conditions. If you agree,
please sign the document and upload a scan or image here.{% endblocktrans %}
</p>
{% else %}
<p>{% blocktrans %}We summarized your registration in our registration
form. Please <a href="{{ download_url }}?key={{ key }}">download</a> it,
fill in the remaining fields and read the general conditions. If you agree,
please sign the document and upload a scan or image here.{% endblocktrans %}
</p>
{% endif %}
<p>{% blocktrans %}If you are not an adult yet, please let someone responsible for you sign the agreement.{% endblocktrans %}
</p>

@ -3,26 +3,14 @@
{% load static %}
{% block title %}
{% if member.confirmed %}
{% trans "Echo" %}
{% else %}
{% trans "Registration" %}
{% endif %}
{% endblock %}
{% block content %}
{% if member.confirmed %}
<h1>{% trans "Echo" %}</h1>
{% else %}
<h1>{% trans "Register" %}</h1>
{% endif %}
<p>
{% blocktrans %}Thank you for uploading the registration form.{% endblocktrans %}
{% if not member.confirmed %}
{% blocktrans %}Our team will process your registration shortly.{% endblocktrans %}
{% endif %}
<p>{% blocktrans %}Thank you for uploading the registration form. Our team will process your registration shortly.{% endblocktrans %}
</p>
{% endblock %}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save