Compare commits

..

1 Commits

Author SHA1 Message Date
Christian Merten b19657ff08
authentication: add oidc support aiming for authentik integration
Code Coverage #### Overview by baseline * **[Overall project (difference to reference job)](https://jenkins.merten.dev/job/gitea/job/kompass/job/authentik-integration/1//coverage#overview)** * Line Coverage: 70.65% (3158/4470) Output truncated. Details
gitea/kompass/pipeline/head This commit looks good Details
2 years ago

@ -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 }}"

18
.gitignore vendored

@ -106,6 +106,9 @@ jdav_web/my.cnf
# sass cache # sass cache
jdav_web/static/jet/css/themes/*/.sass-cache/* jdav_web/static/jet/css/themes/*/.sass-cache/*
# test config
config
# celerybeat schedule database # celerybeat schedule database
jdav_web/celerybeat-schedule.db jdav_web/celerybeat-schedule.db
@ -121,18 +124,3 @@ docker/test/db
docker/development/media docker/development/media
docker/production/media docker/production/media
docker/test/media docker/test/media
# configuration folders
docker/development/config/*
!docker/development/config/settings.toml.example
docker/production/config
*.csv
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,14 +1,8 @@
build-test: build-test:
cd docker/test; docker compose build cd docker/test; docker compose build
test-only: test:
mkdir -p docker/test/htmlcov touch docker/test/coverage.xml
chmod 777 docker/test/htmlcov chmod 666 docker/test/coverage.xml
ifeq ($(keepdb), true)
cd docker/test; DJANGO_TEST_KEEPDB=1 docker compose up --abort-on-container-exit
else
cd docker/test; docker compose up --abort-on-container-exit cd docker/test; docker compose up --abort-on-container-exit
endif sed -i 's/\/app\/jdav_web/jdav_web/g' docker/test/coverage.xml
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,45 +1,30 @@
# jdav Kompass # 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 This repository has the purpose to develop a webapplication that can be used by
tools to contact and (automatically) manage members, groups, material, excursions and statements. JDAV to send newsletters, manage user lists and keep material lists up to date.
As this repository is also meant to be a base for exchange during development, feel free
to contribute ideas in form of edits to this README, issues, landmarks, projects, wiki entries, ...
For more details on the features, see the (German) [documentation](https://jdav-hd.de/static/docs/index.html). # Docker
If you are interested in using the Kompass in your own local section, please get in touch via In the `docker` subfolder, there are `docker-compose.yaml`s for development and production use. For the development
email at `name of this project`@`merten.dev`. We are very happy to discuss how the Kompass can be used in version, no further setup is needed.
your setting.
# Contributing # Production
Any form of contribution is appreciated. If you found a bug or have a feature request, please file an In production, the docker setup needs an external database. The exact access credentials are configured in the respective
[issue](https://github.com/chrisflav/kompass/issues). If you want to help with the documentation or docker.env files.
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 # Useful stuff
also a [Gitea repository](https://git.jdav-hd.merten.dev/digitales/kompass).
The following is a short description of where to find the documentation with more information. ## Reset database for certain app
# Documentation The following can be useful in case that automatic migrations throw errors.
Documentation is handled by [sphinx](https://www.sphinx-doc.org/) and located in `docs/`. 1. delete everything in the migrations folder except for __init__.py.
2. drop into my MySQL console and do: DELETE FROM django_migrations WHERE app='my_app'
The sphinx documentation contains information about: 3. while at the MySQL console, drop all of the tables associated with my_app.
- Development Setup 4. re-run ./manage.py makemigrations my_app - this generates a 0001_initial.py file in my migrations folder.
- Architecture 5. run ./manage migrate my_app - I expect this command to re-build all my tables, but instead it says: "No migrations to apply."
- Testing
- Production Deployment
- 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).
# License
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`.
See the `NOTICE.txt` file for attributions.

@ -1,66 +0,0 @@
[section]
name = "Town"
street = "Street 12"
town = "12345 Town"
telephone = "123456789"
telefax = "987654321"
contact_mail = "contact@jdav-town.de"
board_mail = "board@jdav-town.de"
crisis_intervention_mail = "crisis@jdav-town.de"
iban = "DE42 4242 4242 4242 4242 42"
account_holder = "DAV Town"
responsible_mail = "responsible@jdav-town.de"
digital_mail = "digital@jdav-town.de"
admins = [['Admin', 'admin@jdav-town.de']]
[LJP]
v32_head_organisation = """
LJP application recipient header
"""
[misc]
allowed_email_domains_for_invite_as_user = ['alpenverein-town.de']
send_from_association_email = true
domain = 'jdav-town.de'
[finance]
allowance_per_day = 22
max_night_cost = 11
[links]
cloud = "https://nextcloud.com"
dav_360 = "https://dav360.de"
wiki = "https://wikipedia.org"
docs = "https://jdav-hd.de/static/docs"
registration_form = "download-me"
[startpage]
redirect_url = ''
root_section = 'wir'
recent_section = 'aktuelles'
reports_section = 'berichte'
[django]
deployed = true
debug = false
secret_key = 'secret key'
allowed_hosts = ['jdav-town.de']
host = 'jdav-town.de'
media_root = '/var/www/jdav_web/media'
static_root = '/var/www/jdav_web/static'
broker_url = 'redis://redis:6379/0'
memcached_url = 'cache:11211'
[mail]
host = 'host'
user = 'kompass-mailagent'
password = 'password'
default_sending_address = 'info@jdav-town.de'
default_sending_name = 'JDAV Town'
[database]
host = 'host'
port = 3306
database = 'kompass'
user = 'kompass'
password = 'kompass-db-user-password'

@ -1,86 +0,0 @@
x-kompass:
&kompass
image: kompass:production
environment:
- DJANGO_SETTINGS_MODULE=jdav_web.settings
- KOMPASS_CONFIG_DIR_PATH=/app/config/
restart: always
depends_on:
- redis
- cache
services:
master:
<<: *kompass
build:
context: https://github.com/chrisflav/kompass.git#main
dockerfile: docker/production/Dockerfile
entrypoint: /app/docker/production/entrypoint-master.sh
volumes:
- uwsgi_data:/tmp/uwsgi/
- web_static:/app/static/
- web_static:/var/www/jdav_web/static/
- ./media:/var/www/jdav_web/media/
- ./config:/app/config:ro
networks:
- main
extra_hosts:
- "host:10.26.42.1"
nginx:
build: https://github.com/chrisflav/kompass.git#main:docker/production/nginx
restart: always
volumes:
- uwsgi_data:/tmp/uwsgi/
- web_static:/var/www/jdav_web/static/:ro
- ./media:/var/www/jdav_web/media/:ro
ports:
- "3000:80"
depends_on:
- master
networks:
- main
cache:
restart: always
image: memcached:alpine
networks:
- main
redis:
restart: always
image: redis:6-alpine
networks:
- main
celery_worker:
<<: *kompass
entrypoint: /app/docker/production/entrypoint-celery-worker.sh
volumes:
- ./config:/app/config:ro
networks:
- main
extra_hosts:
- "host:10.26.42.1"
celery_beat:
<<: *kompass
entrypoint: /app/docker/production/entrypoint-celery-beat.sh
volumes:
- ./config:/app/config:ro
networks:
- main
extra_hosts:
- "host:10.26.42.1"
volumes:
uwsgi_data:
web_static:
networks:
main:
driver: bridge
ipam:
config:
- subnet: 10.26.42.0/24
gateway: 10.26.42.1

@ -1,7 +1,7 @@
FROM python:3.9-bookworm FROM python:3.9-bullseye
# install additional dependencies # install additional dependencies
RUN apt-get update && apt-get install -y gettext texlive texlive-fonts-extra pandoc RUN apt-get update && apt-get install -y gettext texlive texlive-fonts-extra
WORKDIR /app WORKDIR /app

@ -1,67 +0,0 @@
[section]
name = "Town"
street = "Street 12"
town = "12345 Town"
telephone = "123456789"
telefax = "987654321"
contact_mail = "contact@jdav-town.de"
board_mail = "board@jdav-town.de"
crisis_intervention_mail = "crisis@jdav-town.de"
iban = "DE42 4242 4242 4242 4242 42"
account_holder = "DAV Town"
responsible_mail = "responsible@jdav-town.de"
digital_mail = "digital@jdav-town.de"
admins = [['Admin', 'admin@jdav-town.de']]
[LJP]
v32_head_organisation = """
LJP application recipient header
"""
[misc]
allowed_email_domains_for_invite_as_user = ['alpenverein-town.de']
send_from_association_email = true
domain = 'jdav-town.de'
[finance]
allowance_per_day = 22
max_night_cost = 11
[links]
cloud = "https://nextcloud.com"
dav_360 = "https://dav360.de"
wiki = "https://wikipedia.org"
docs = "https://jdav-hd.de/static/docs"
registration_form = "download-me"
[startpage]
redirect_url = ''
root_section = 'root section'
recent_section = 'aktuelles'
reports_section = 'berichte'
[django]
deployed = true
debug = true
secret_key = '6_ew6l1r9_4(8=p8quv(e8b+z+k+*wm7&zxx%mcnnec99a!lpw'
allowed_hosts = ['*']
protocol = 'http'
base_url = 'localhost:8000'
host = ''
static_root = '/var/www/jdav_web/assets'
broker_url = 'redis://redis:6379/0'
memcached_url = 'cache:11211'
[mail]
host = 'jdav-town.de'
user = 'user@jdav-town.de'
password = 'password'
default_sending_address = 'info@jdav-town.de'
default_sending_name = 'JDAV Town'
[database]
host = 'db'
port = 3306
database = 'kompass'
user = 'kompass'
password = 'foobar'

@ -1,3 +1,5 @@
version: "3.9"
x-kompass: x-kompass:
&kompass &kompass
image: kompass:development image: kompass:development
@ -8,9 +10,6 @@ x-kompass:
UID: ${UID} UID: ${UID}
GID: ${UID} GID: ${UID}
USER: ${USER} USER: ${USER}
environment:
- KOMPASS_CONFIG_DIR_PATH=/app/config/
- DJANGO_SETTINGS_MODULE=jdav_web.settings
env_file: docker.env env_file: docker.env
restart: always restart: always
depends_on: depends_on:
@ -26,9 +25,7 @@ services:
tty: true tty: true
volumes: volumes:
- ./../../jdav_web:/app/jdav_web - ./../../jdav_web:/app/jdav_web
- ./../../docs:/app/docs
- ./media:/app/media - ./media:/app/media
- ./config:/app/config:ro
ports: ports:
- "8000:8000" - "8000:8000"

@ -1,4 +0,0 @@
MYSQL_ROOT_PASSWORD='secret'
MYSQL_PASSWORD='foobar'
MYSQL_USER='kompass'
MYSQL_DATABASE='kompass'

@ -33,10 +33,6 @@ cd /app
if ! [ -f /tmp/completed_initial_run ]; then if ! [ -f /tmp/completed_initial_run ]; then
echo 'Initialising kompass master container' echo 'Initialising kompass master container'
cd docs
make html
cd /app
python jdav_web/manage.py compilemessages --locale de python jdav_web/manage.py compilemessages --locale de
# python jdav_web/manage.py makemigrations # python jdav_web/manage.py makemigrations

@ -1,7 +1,7 @@
FROM python:3.9-bookworm FROM python:3.9-bullseye
# install additional dependencies # install additional dependencies
RUN apt-get update && apt-get install -y gettext texlive texlive-fonts-extra pandoc RUN apt-get update && apt-get install -y gettext texlive texlive-fonts-extra
# create user # create user
RUN groupadd -g 501 app && useradd -g 501 -u 501 -m -d /app app RUN groupadd -g 501 app && useradd -g 501 -u 501 -m -d /app app

@ -1,10 +1,9 @@
version: "3.9"
x-kompass: x-kompass:
&kompass &kompass
image: kompass:production image: kompass:production
env_file: docker.env env_file: docker.env
environment:
- DJANGO_SETTINGS_MODULE=jdav_web.settings
- KOMPASS_CONFIG_DIR_PATH=/app/config/
restart: always restart: always
depends_on: depends_on:
- redis - redis
@ -22,7 +21,6 @@ services:
- web_static:/app/static/ - web_static:/app/static/
- web_static:/var/www/jdav_web/static/ - web_static:/var/www/jdav_web/static/
- ./media:/var/www/jdav_web/media/ - ./media:/var/www/jdav_web/media/
- ./config:/app/config:ro
nginx: nginx:
build: ./nginx/ build: ./nginx/
@ -47,14 +45,10 @@ services:
celery_worker: celery_worker:
<<: *kompass <<: *kompass
entrypoint: /app/docker/production/entrypoint-celery-worker.sh entrypoint: /app/docker/production/entrypoint-celery-worker.sh
volumes:
- ./config:/app/config:ro
celery_beat: celery_beat:
<<: *kompass <<: *kompass
entrypoint: /app/docker/production/entrypoint-celery-beat.sh entrypoint: /app/docker/production/entrypoint-celery-beat.sh
volumes:
- ./config:/app/config:ro
volumes: volumes:
uwsgi_data: uwsgi_data:

@ -7,16 +7,10 @@ cd /app
if ! [ -f completed_initial_run ]; then if ! [ -f completed_initial_run ]; then
echo 'Initialising kompass master container' echo 'Initialising kompass master container'
cd docs
make html
cp -r build/html /app/jdav_web/static/docs
cd /app
python jdav_web/manage.py collectstatic --noinput python jdav_web/manage.py collectstatic --noinput
python jdav_web/manage.py compilemessages --locale de python jdav_web/manage.py compilemessages --locale de
python jdav_web/manage.py migrate python jdav_web/manage.py migrate
python jdav_web/manage.py ensuresuperuser
touch completed_initial_run touch completed_initial_run
fi fi

@ -6,21 +6,15 @@ server {
listen 80; listen 80;
server_name 127.0.0.1; server_name 127.0.0.1;
charset utf-8; charset utf-8;
error_page 502 /downtime/502.html;
location /static { location /static {
alias /var/www/jdav_web/static; alias /var/www/jdav_web/static;
} }
location /protected { location /media {
internal;
alias /var/www/jdav_web/media; alias /var/www/jdav_web/media;
} }
location /downtime {
alias /var/www/jdav_web/static/downtime;
}
location / { location / {
uwsgi_pass uwsgi; uwsgi_pass uwsgi;
include /etc/nginx/uwsgi_params; include /etc/nginx/uwsgi_params;

@ -26,9 +26,6 @@ sendfile on;
keepalive_timeout 65; keepalive_timeout 65;
# max upload size
client_max_body_size 15M;
#gzip on; #gzip on;
#include /etc/nginx/conf.d/*.conf; #include /etc/nginx/conf.d/*.conf;

@ -1,7 +1,7 @@
FROM python:3.9-bookworm FROM python:3.9-bullseye
# install additional dependencies # install additional dependencies
RUN apt-get update && apt-get install -y gettext texlive texlive-fonts-extra pandoc RUN apt-get update && apt-get install -y gettext texlive texlive-fonts-extra
# create user # create user
RUN groupadd -g 501 app && useradd -g 501 -u 501 -m -d /app app RUN groupadd -g 501 app && useradd -g 501 -u 501 -m -d /app app
@ -22,6 +22,8 @@ ENV PATH="/app/.local/bin:$PATH"
# install requirements # install requirements
COPY --chown=app:app ./requirements.txt /app/requirements.txt 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 COPY --chown=app:app . /app

@ -1,34 +0,0 @@
[testing]
mail = "test@localhost"
[django]
deployed = true
debug = true
secret_key = '6_ew6l1r9_4(8=p8quv(e8b+z+k+*wm7&zxx%mcnnec99a!lpw'
allowed_hosts = ['*']
protocol = 'http'
base_url = 'localhost:8000'
host = 'localhost'
static_root = '/var/www/jdav_web/assets'
broker_url = 'redis://redis:6379/0'
memcached_url = 'cache:11211'
[mail]
host = 'localhost'
user = 'test'
password = 'password'
default_sending_address = 'test@localhost'
[database]
host = 'db'
port = 3306
database = 'kompass'
user = 'kompass'
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"""

@ -7,20 +7,15 @@ services:
context: ./../../ context: ./../../
dockerfile: docker/test/Dockerfile dockerfile: docker/test/Dockerfile
env_file: docker.env env_file: docker.env
environment:
- KOMPASS_CONFIG_DIR_PATH=/app/config/
- DJANGO_SETTINGS_MODULE=jdav_web.settings
- DJANGO_TEST_KEEPDB=$DJANGO_TEST_KEEPDB
depends_on: depends_on:
- redis - redis
- cache - cache
- db - db
entrypoint: /app/docker/test/entrypoint-master.sh entrypoint: /app/docker/test/entrypoint-master.sh
volumes: volumes:
- ./config:/app/config:ro
- type: bind - type: bind
source: ./htmlcov/ source: ./coverage.xml
target: /app/jdav_web/htmlcov/ target: /app/jdav_web/coverage.xml
cache: cache:
restart: always restart: always

@ -1,4 +1,28 @@
DJANGO_ALLOWED_HOST='*'
DJANGO_BASE_URL='localhost:8000'
DJANGO_PROTOCOL='http'
EMAIL_HOST='localhost'
EMAIL_HOST_USER='test'
EMAIL_HOST_PASSWORD='password'
EMAIL_SENDING_ADDRESS='test@localhost'
DJANGO_DEPLOY=1
DJANGO_DEBUG=1
DJANGO_DATABASE_NAME='kompass'
DJANGO_DATABASE_USER='kompass'
DJANGO_DATABASE_PASSWORD='password'
DJANGO_DATABASE_HOST='db'
DJANGO_DATABASE_PORT=3306
MYSQL_ROOT_PASSWORD='secretpassword' MYSQL_ROOT_PASSWORD='secretpassword'
MYSQL_PASSWORD='password' MYSQL_PASSWORD='password'
MYSQL_USER='kompass' MYSQL_USER='kompass'
MYSQL_DATABASE='kompass' MYSQL_DATABASE='kompass'
DJANGO_SETTINGS_MODULE='jdav_web.settings'
DJANGO_STATIC_ROOT='/var/www/jdav_web/assets'
MEMCACHED_URL='cache:11211'
BROKER_URL='redis://redis:6379/0'

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

@ -1,20 +0,0 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

@ -1,35 +0,0 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)
if "%1" == "" goto help
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd

@ -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

@ -1,20 +0,0 @@
:orphan: true
.. meta::
:description: Miscellaneous information about the Kompass project
.. vale off
About
=====
.. rst-class:: lead
.. attention::
Die Seite befindet sich noch im Aufbau. -- The page is still under construction.
(Stand: 08.01.2025)
- About the kompass project
- About this documentation

@ -1,63 +0,0 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
from dataclasses import asdict
from sphinxawesome_theme import ThemeOptions
# -- Project information -------------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = 'Kompass'
release = '2.0'
author = 'The Kompass Team'
copyright = f'2025, {author}'
# -- General configuration -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ['_templates']
exclude_patterns = []
language = 'de'
# -- Options for HTML output ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'sphinxawesome_theme'
html_static_path = ['_static']
# -- Sphinxawsome-theme options ------------------------------------------------
# https://sphinxawesome.xyz/how-to/configure/
html_logo = "_static/favicon.svg"
html_favicon = "_static/favicon.svg"
html_sidebars = {
"about": ["sidebar_main_nav_links.html"],
# "changelog": ["sidebar_main_nav_links.html"],
}
# Code blocks color scheme
pygments_style = "emacs"
pygments_style_dark = "emacs"
# Could be directly in html_theme_options, but this way it has type hints
# from sphinxawesome_theme
theme_options = ThemeOptions(
show_prev_next=True,
show_breadcrumbs=True,
main_nav_links={
"Docs": "index",
"About": "about",
# "Changelog": "changelog"
},
show_scrolltop=True,
)
html_theme_options = asdict(theme_options)

@ -1,7 +0,0 @@
.. _development_manual/architecture:
=================
Architecture
=================
tbd

@ -1,85 +0,0 @@
.. _development_manual/contributing:
============
Contributing
============
Any form of contribution is appreciated. If you found a bug or have a feature request, please file an
`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>`_.
.. note::
Please read this page carefully before contributing.
Miscellaneous
-------------
- version control with `git <https://git-scm.com/>`_
- own gitea instance at https://git.jdav-hd.merten.dev/
- protected ``main`` branch
Organization and branches
-------------------------
The stable development happens on the ``main``-branch for which only maintainers have write access. Any pull request
should hence be targeted at ``main``. Regularly, the production instances are updated to the latest ``main`` version,
in particular these are considered to be stable.
If you have standard write access to the repository, feel free to create new branches. To make organization
easier, please follow the branch naming convention: ``<username>/<feature>``.
The ``testing``-branch is deployed on the development instances. No development should happen there, this branch
is regularly reset to the ``main``-branch.
Workflow
--------
- request a gitea account from the project maintainers
- decide on an `issue <https://git.jdav-hd.merten.dev/digitales/kompass/issues>`_ to work on or create a new one
- branch out to an own branch (naming convention: ``<username>/<feature>``) from the ``main``-branch
- work on the issue and commit your changes
- create a pull request from your branch to the ``main``-branch
.. _development_manual/contributing/documentation:
Documentation
-------------
If you want to contribute to the documentation, please follow the steps below.
Online (latest release version): https://jdav-hd.de/static/docs/
- This documentation is build `sphinx <https://www.sphinx-doc.org/>`_ and `awsome sphinx theme <https://sphinxawesome.xyz/>`_ the source code is located in ``docs/``.
- All documentation is written in `reStructuredText <https://www.sphinx-doc.org/en/master/usage/restructuredtext/index.html>`_ and uses the `sphinx directives <https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html>`_.
- The directives can vary due to the theme, see the `awesome sphinx theme documentation <https://sphinxawesome.xyz/demo/notes/>`_.
- All technical documentation is written in english, user documentation is written in german.
To read the documentation build it locally and view it in your browser:
.. code-block:: bash
cd docs/
make html
# MacOS (with firefox)
open -a firefox $(pwd)/docs/build/html/index.html
# Linux (I guess?!?)
firefox ${pwd}/docs/build/html/index.html
Code
----
If you want to contribute code, please follow the inital setup steps in the :ref:`development_manual/setup` section. And dont forget to :ref:`document <development_manual/contributing/documentation>` your code properly and write tests.
.. note::
Still open / to decide:
- linting
- (auto) formatting
- reliable tests via ci/cd pipeline

@ -1,290 +0,0 @@
.. _development_manual/deployment:
=====================
Production Deployment
=====================
The production setup is based on the docker configuration in the ``production/`` folder of the repository. In
contrast to the development setup, there is no database service configured in the ``docker-compose.yaml``. This
is to allow for a more flexible setup with a database service installed on the host, for which it is easier
to ensure data safety.
.. _user_manual/initial_installation:
Initial installation
====================
We give here step-by-step instructions how to set up an initial Kompass installation starting from a fresh
Debian Bookworm installation. Of course these steps can be easily adapted to a different Linux distribution,
the steps will mostly differ in the way the system dependencies are installed.
The instructions describe the recommended setup with a docker-independent MySQL database server on the host system.
We assume that all instructions are executed as ``root`` or with ``sudo``.
1. Install the dependencies: To install ``docker``, please follow the `official instructions`_. For the MySQL
server, run the following command:
.. code-block:: console
apt install mariadb-server
2. Setup the database: We need to create the database and create a user with a strong password. To generate
a strong password, run
.. code-block:: console
PASSWORD=$(tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 24)
Now create a MySQL user with the generated password, by executing:
.. code-block:: console
mysql <<EOF
CREATE USER 'kompass'@'10.26.42.0/255.255.255.0' IDENTIFIED BY '$PASSWORD';
GRANT ALL PRIVILEGES ON kompass.* to 'kompass'@'10.26.42.0/255.255.255.0';
FLUSH PRIVILEGES;
EOF
To make the MySQL server available from the docker container, edit ``/etc/mysql/mariadb.cnf`` and
uncomment the ``port`` line in the ``[client-server]`` code block. It could then look like this:
.. code-block:: console
[client-server]
port = 3306
socket = /run/mysqld/mysqld.sock
Finally, edit ``/etc/mysql/mariadb.conf.d/50-server.cnf`` and add ``10.26.42.1`` [#ip-address]_ to the
``bind-address`` line. It could then look like this:
.. code-block:: console
bind-address = 127.0.0.1,10.26.42.1
Now restart the MySQL database by running:
.. code-block:: console
systemctl restart mariadb.service
.. note::
If you are running a firewall service, you will need to allow connections to the ``3306`` port
from the ``10.26.42.0/24`` subnet. If you use ``ufw``, you can do:
.. code-block:: console
ufw allow from 10.26.42.0/24 to 10.26.42.1 port 3306
3. Install Kompass:
.. code-block:: console
mkdir /opt/kompass
cd /opt/kompass
Copy the contents of the ``deploy/`` directory of the Kompass repository into this folder. Afterwards,
the folder structure should look like this:
.. code-block::
.
├── config
│   └── settings.toml
└── docker-compose.yaml
.. note::
As long as the Kompass repository is private, you need to ask the maintainers to add a read-only deploy
key for your installation to the `Gitea`_. Then you can add a ``.ssh`` config file on your server with a
section
.. code-block:: console
Host git.jdav-hd.merten.dev
HostName git.jdav-hd.merten.dev
User git
IdentityFile ~/.ssh/your_deploy_key
Now set the password of the MySQL user in the ``settings.toml`` by running
.. code-block:: console
sed -i "s/kompass-db-user-password/$PASSWORD/g" config/settings.toml
Finally, we can start the docker containers for the first time by running:
.. code-block:: console
docker compose up --build
This will start building the docker images and then launch the application. If everything
works as expected, there should be no error messages. In this case open a second terminal,
navigate to ``/opt/kompass/`` and run
.. code-block:: console
docker compose exec master bash
cd jdav_web
python3 manage.py createsuperuser
This will prompt you for a username and a password for the initial admin user. Use a strong password
and don't use the same password as the one for the MySQL user above!
The webserver will be available on ``localhost`` on port ``3000``. To expose it to the
outer world, we need to setup a web server, such as ``apache2``.
4. Install a webserver: This is standard and not Kompass specific, but we still include the
steps here for completeness. First, we need to install ``apache2``:
.. code-block:: console
apt install apache2
a2enmod md ssl proxy proxy_http headers
To allow the ``md`` module to automatically request a Let's Encrypt certificate for our domain,
you need to accept the `certificate agreement`_. If you do, add the following line
.. code-block::
MDCertificateAgreement accepted
to ``/etc/apache2/apache2.conf``.
Then create a new file ``/etc/apache2/sites-available/kompass.conf`` with
.. code-block::
MDomain jdav-town.de
<VirtualHost *:443>
ServerName jdav-town.de
ServerAdmin digital@jdav-town.de
SSLEngine on
SSLOptions StrictRequire
ErrorLog /var/log/apache2/error.log
LogLevel warn
CustomLog /var/log/apache2/access.log vhost_combined
SSLProxyEngine on
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-Ssl on
RequestHeader set X-Forwarded-Port 443
</VirtualHost>
Replace the ``jdav-town.de`` domain by a domain pointing to your server. Now activate the site
and restart apache:
.. code-block:: console
a2ensite kompass.conf
systemctl restart apache2
The ``md`` module should now request an SSL certificate from Let's Encrypt, while this is still
pending you will receive a *connection not secure* error when visiting your domain. Check
``/var/log/apache2/error.log`` for any possible errors. If everything worked, you will find there a
message similar to:
.. code-block::
[Mon Feb 10 ...] ... : The Managed Domain ... has been setup and changes will be activated on next (graceful) server restart.
In this case run
.. code-block:: console
systemctl restart apache2
again. You should now see the Kompass application at your domain!
5. Update settings: Adapt ``/opt/kompass/config/settings.toml`` to your needs. If you followed the guide
as above, there should be no need to change anything in the ``[database]`` section.
.. note::
We recommend to initialize a ``git`` repository in the ``config`` folder to version control any changes
to the local configuration.
6. Run the container in background mode: If everything is working, you can cancel the
``docker compose up --build`` command from above and run
.. code-block:: console
docker compose up -d --build
Whenever you change your configuration or want to update to the latest version,
run this command again.
7. Setup mail configuration: The Kompass application needs a working mailserver for forwarding incoming
mails on personal mail accounts and on configured forward mail addresses. You can either setup
a mailserver on your own or use the docker-based `Kompass-tailored mailserver`_.
For receiving mails, no further changes to the ``settings.toml`` are needed. For sending mails,
the ``[mail]`` sections needs to be updated with authentication details for an SMTP server.
If you are using (and have already installed) the docker-based mailserver, proceed as follows:
In the Kompass administrative interface create a new user account (i.e. login data) with
a strong password and without staff access. Then update the ``[mail]`` section
in the ``settings.toml`` accordingly with the created user name and password.
The ``host = 'host'`` setting is correct in this case and points to the underlying host.
Local configuration
===================
If you followed the steps outlined in :ref:`user_manual/initial_installation`, you have a folder
``/opt/kompass/config`` currently containing only a ``settings.toml``.
While the ``settings.toml`` configures the most important options,
in practice you might want to have more control over texts on the website, used logos
or texts used in automatically generated emails. Here we will explain how to configure these.
- Mail texts: To modify the standard email texts, create a file ``texts.toml`` in your config
directory. This could then for example look like this:
.. code-block::
confirm_mail = """
Hello {name},
please confirm your email address! For this use the cool link at {link}.
..."""
new_unconfirmed_registration = """
Hi {name},
your group {group} has a new registration! ..."""
- Templates: To override ``.html`` of the Kompass application, create a directory ``templates`` inside
your config directory. This is loaded as a regular templates directory by ``django``, hence
you can override anything that lives in one of the many ``templates`` directories in the main repository.
For example, to fill the impressum page with content, you need to create a file
``templates/startpage/impressum_content.html``. In this file you can put any ``.html`` document and this
will be placed in the impressum page.
Typical templates to override here are (with their respective paths):
- ``templates/startpage/impressum_content``: impressum page
- ``templates/startpage/faq_content``: group registration FAQ
- ``templates/startpage/group_introduction``: introductory text placed above the group listing
.. rubric:: Footnotes
.. [#ip-address] The choice of the subnet ``10.26.42.0/24`` is arbitrarily chosen
from the `list of private IPv4 addresses`_. If by coincidence this specific subnet
is already used on your system, you can replace this by any other subnet from the linked
list. Note that in this case you need to replace all references to ``10.26.42.0/24``
and ``10.26.42.1`` by your choice, including in the ``networks`` section
of the ``docker-compose.yaml``.
.. _official instructions: https://docs.docker.com/engine/install/debian/
.. _Gitea: https://git.jdav-hd.merten.dev/digitales/kompass
.. _list of private IPv4 addresses: https://en.wikipedia.org/wiki/Private_network#Private_IPv4_addresses
.. _certificate agreement: https://letsencrypt.org/documents/LE-SA-v1.4-April-3-2024.pdf
.. _Kompass-tailored mailserver: https://git.jdav-hd.merten.dev/digitales/kompass-mailserver

@ -1,42 +0,0 @@
.. _development_manual/index:
#########################
Development Documentation
#########################
This part of the documentation describes the development and maintenance of the Kompass project.
.. toctree::
:titlesonly:
contributing
setup
architecture
testing
deployment
Contributing
------------
Any form of contribution is appreciated!
.. seealso::
:ref:`Contributing <development_manual/contributing>`
Documentation
-------------
Structure
- :ref:`Nutzer Dokumentation <user_manual/index>` auf deutsch
- :ref:`Development Documentation <development_manual/index>` auf englisch
.. seealso::
:ref:`Contributing #Documentation <development_manual/contributing/documentation>`

@ -1,101 +0,0 @@
.. _development_manual/setup:
=================
Development Setup
=================
The project is run with ``docker`` and all related files are in the ``docker/`` subfolder. Besides the actual Kompass
application, a database (postgresql) and a broker (redis) are setup and run in the docker container. No
external services are needed for running the development container.
Initial installation
--------------------
A working ``docker`` setup (with ``docker compose``) is required. For installation instructions see the
`docker manual <https://docs.docker.com/engine/install/>`_.
1. Clone the repository and change into the directory of the repository.
2. Fetch submodules
.. code-block:: bash
git submodule update --init
.. _step-3:
3. Prepare development environment: to allow automatic rebuilding upon changes in the source,
the owner of the ``/app/jdav_web`` directory in the Docker container must match your
user. For this, make sure that the output of ``echo UID`` and ``echo UID`` is not empty. Then run
.. code-block:: bash
export GID=${GID}
export UID=${UID}
4. Start docker
.. code-block:: bash
cd docker/development
docker compose up
This runs the docker in your current shell, which is useful to see any log output. If you want to run
the development server in the background instead, use ``docker compose up -d``.
During the initial run, the container is built and all dependencies are installed which can take a few minutes.
After successful installation, the Kompass initialization runs, which in particular sets up all tables in the
database.
If you need to rebuild the container (e.g. after changing the ``requirements.txt``), execute
.. code-block:: bash
docker compose up --build
5. Setup admin user: in a separate shell, while the docker container is running, execute
.. code-block:: bash
cd docker/development
docker compose exec master bash -c "cd jdav_web && python3 manage.py createsuperuser"
This creates an admin user for the administration interface.
Development
-----------
If the initial installation was successful, you can start developing. Changes to files cause an automatic
reload of the development server. If you need to generate and perform database migrations or generate locale files,
use
.. code-block:: bash
cd docker/development
docker compose exec master bash
cd jdav_web
This starts a shell in the container, where you can execute any django maintenance commands via
``python3 manage.py <command>``. For more information, see the https://docs.djangoproject.com/en/4.0/ref/django-admin.
Known Issues
------------
- If the ``UID`` and ``GID`` variables are not setup properly, you will encounter the following error message
after running ``docker compose up``.
.. code-block:: bash
=> ERROR [master 6/7] RUN groupadd -g fritze && useradd -g -u -m -d /app fritze 0.2s
------
> [master 6/7] RUN groupadd -g fritze && useradd -g -u -m -d /app fritze:
0.141 groupadd: invalid group ID 'fritze'
------
failed to solve: process "/bin/sh -c groupadd -g $GID $USER && useradd -g $GID -u $UID -m -d /app $USER" did not complete successfully: exit code: 3
In this case repeat :ref:`step 3 <step-3>` above.

@ -1,7 +0,0 @@
.. _development_manual/testing:
=================
Testing
=================
To run the tests, you can use the docker setup under ``docker/test``.

@ -1,42 +0,0 @@
.. Kompass documentation master file, created by
sphinx-quickstart on Sun Nov 24 18:37:20 2024.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
.. _index:
############
jdav Kompass
############
Der Kompass ist dein Kompass in der Jugendarbeit in deiner JDAV Sektion. Wenn du das
erste mal hier bist, schau doch mal :ref:`user_manual/getstarted` an.
.. attention::
Die Dokumentation befindet sich noch im Aufbau. -- The documentation is still under construction.
(Stand: 08.01.2025)
Nutzer Dokumentation
--------------------
- auf deutsch
- Hier findest Du als Nutzer alles was Du wissen musst um den Kompass bedienen zu können.
.. toctree::
:titlesonly:
user_manual/index
Development Documentation
-------------------------
- auf englisch
- Hier findest Du als Entwickler alles was Du wissen musst um den Kompass entwickeln und zu pflegen.
.. toctree::
:titlesonly:
development_manual/index

@ -1,55 +0,0 @@
.. _user_manual/excursions:
Ausfahrten
==========
Neben der :ref:`Teilnehmer\*innenverwaltung <user_manual/members>` ist das Abwickeln von Ausfahrten
die zweite wichtige Aufgabe des Kompass. Eine Ausfahrt für die eigene Jugendgruppe
anbieten ist neben der ganzen inhaltlichen Arbeit auch jede Menge bürokratischer Aufwand. Der Kompass
versucht dir von diesem Aufwand so viel wie möglich abzunehmen.
Konkret hilft dir der Kompass dabei
- Kriseninterventionslisten zu generieren
- Stadtjugendring oder Landesjugendplan Anträge zu erstellen
- Abrechnungen anzufertigen
.. warning::
Diese Seite ist noch im Aufbau.
Stammdaten
----------
Sobald du mit deinen Co-Jugendleiter\*innen eine Ausfahrt angedacht hast, kannst du diese im Kompass `anlegen`_.
Die bekannten Informationen trägst du schon ein, die noch unbekannten lässt du leer oder trägst
vorläufige Daten ein.
Wenn du weißt wer mitkommt, trägst du im Tab *Teilnehmer\*innen* alle ein, die zur Ausfahrt kommen.
.. _crisis-intervention-list:
Kriseninterventionsliste
------------------------
Bevor die Ausfahrt stattfindet, lässt du dir eine Kriseninterventionsliste mit allen Notfallkontakten der
Mitfahrer\*innen erstellen und schickst sie an die Geschäftsstelle.
Landesjugendplanantrag
----------------------
Möchtest du einen Landesjugendplan- oder SJR Antrag stellen? Dann trage alle Informationen für den
Seminarbericht direkt ein und lass dir den Papierkram vom Kompass erledigen.
SJR Antrag
----------
tbd
Abrechnung
----------
Im Nachhinein trägst du deine Ausgaben ein, lädst Belege hoch und reichst deine Abrechnung per Knopfdruck ein.
.. _anlegen: https://jdav-hd.de/kompassmembers/freizeit/add/
.. _Teilnehmer\*innen: https://jdav-hd.de/kompassmembers/member/

@ -1,11 +0,0 @@
.. _user_manual/finance:
Finanzen
========
Auf dieser Seite wird das Einreichen, Bearbeiten und Abwickeln von Abrechnungen
erklärt. Diese Seite ist für Finanzbeauftragte der Sektion gedacht und daher
für die meisten Benutzer\*innen des Kompass unwichtig.
.. warning::
Diese Seite ist noch im Aufbau.

@ -1,78 +0,0 @@
.. _user_manual/getstarted:
Erste Schritte
==============
Wenn du zum ersten Mal den Kompass deiner Sektion benutzt ist diese
Seite der richtige Einstieg. Wir verfolgen in dieser Anleitung den Jugendleiter
Fritz Walter bei seinen ersten Schritten mit seinem Kompass. Fritz Walter leitet
die Gruppe *Kletterfüchse*.
Wie finde ich die Teilnehmer\*innen meiner Jugendgruppe?
--------------------------------------------------------
Auf der `Startseite`_ siehst du eine Auflistung der von dir geleiteten Jugendgruppen.
Klickst du auf eine der Gruppen landest du in der `Teilnehmer\*innenanzeige`_.
.. image:: images/members_changelist_filters.png
Fritz hat die Gruppe *Kletterfüchse* ausgewählt, wie du oben rechts sehen kannst.
Versuche einmal dort bei dir eine andere Gruppe auszuwählen. Falls dir keine Teilnehmer\*innen
angezeigt werden liegt das daran, dass deine *Zugriffsrechte* nicht ausreichen.
Wie ändere ich Daten meiner Jugendgruppen Teilnehmer\*innen?
------------------------------------------------------------
Fritz möchte das eingetragene Geburtsdatum von *Lisa Lotte* ändern. Dazu klickt
er auf den entsprechenden Eintrag, ändert das Geburtsdatum und klickt auf *Speichern*.
.. note::
Nicht alle Einträge in der `Teilnehmer\*innenanzeige`_ sind klickbar. Das liegt daran,
dass du manche Teilnehmer\*innen zwar sehen, aber nicht ihre Details einsehen kannst.
Manche Einträge wiederum kannst du einsehen, aber nicht bearbeiten. Für mehr Details siehe :ref:`Teilnehmer\*innenverwaltung <user_manual/members>`
Probier doch einmal aus deinen eigenen Eintrag zu ändern. Sicherlich gibt es einige
Felder, die nicht ausgefüllt oder nicht mehr aktuell sind. Lade z.B. ein Bild von dir hoch,
damit unsere Website schöner wird.
Wie schicke ich eine E-Mail an meine Gruppe?
--------------------------------------------
Nachdem Fritz die Daten seiner Gruppe auf den neusten Stand gebracht hat, möchte er nun
eine E-Mail über die bevorstehende Hallenübernachtung an seine Gruppe schreiben. Dazu
geht er zurück auf die `Startseite`_ und wählt `Nachricht verfassen`_ aus.
Als Empfänger wählt er im Feld *An Gruppe* die *Kletterfüchse* aus. Damit seine
Co-Jugendleiterin Julia auch die Antworten erhält, wählt er im Feld
*Antwort an Teilnehmer* sowohl sich selbst, als auch Julia aus. Schließlich
klickt er auf *Speichern und Email senden*, um die Nachricht zu verschicken.
.. note::
Es kann sein, dass über den Kompass verschickte E-Mails nur verzögert ankommen. Das
liegt daran, dass pro Minute stets nur 10 E-Mails verschickt werden um Stau
zu verhindern.
Probier doch mal aus dir selbst eine Nachricht zu schicken. Wähle einfach im Feld
*An Teilnehmer* dich selbst aus.
Wie organisiere ich eine Ausfahrt?
----------------------------------
Nun da Fritz seine Gruppe zur Hallenübernachtung eingeladen hat, möchte er die
Ausfahrt auch im Kompass anlegen. Dazu navigiert er zurück zur `Startseite`_ und wählt
`Ausfahrten`_ aus.
Dort wählt er oben rechts *Ausfahrt hinzufügen* aus und füllt die verschiedenen Felder
aus. Im Reiter *Teilnehmer* trägt er bereits Julia und sich selbst ein, die stehen ja
schließlich schon fest. Schließlich speichert er die Ausfahrt mit *Sichern*.
Wie geht es weiter?
-------------------
Nun hat Fritz den Bürokratiekram für heute erledigt. Du willst noch mehr wissen? Dann
geh zurück zur :ref:`user_manual/index`.
.. _Startseite: https://jdav-hd.de/kompass
.. _Teilnehmer\*innenanzeige: https://jdav-hd.de/kompassmembers/member/
.. _Nachricht verfassen: https://jdav-hd.de/kompassmailer/message/add/
.. _Ausfahrten: https://jdav-hd.de/kompassmembers/freizeit/

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

@ -1,50 +0,0 @@
.. _user_manual/index:
####################
Nutzer Dokumentation
####################
Der Kompass ist dein Kompass in der Jugendarbeit in deiner JDAV Sektion. Wenn du das
erste mal hier bist, schau doch mal :ref:`user_manual/getstarted` an.
.. toctree::
:titlesonly:
getstarted
members
excursions
waitinglist
finance
Was ist der Kompass?
--------------------
Der Kompass ist eine Verwaltungsplattform für die tägliche Jugendarbeit in der JDAV.
Die wichtigsten Funktionen sind
- Verwaltung von Teilnehmer\*innen von Jugendgruppen
- Organisation von Ausfahrten
- Abwicklung von Abrechnungen
- Senden von E-Mails
Neben diesen Funktionen für die tägliche Arbeit, automatisiert der Kompass die
Aufnahme von neuen Mitgliedern und die Pflege der Daten durch
- Wartelistenverwaltung
- Registrierung neuer Mitglieder
- Rückmeldeverfahren
Feedback
--------
Wenn Du Feedback hast, schreibe uns gerne eine E-Mail an: `digitales@jdav-hd.de <mailto:digitales@jdav-hd.de?subject=Kompass Feedback>`_.
Der Kompass lebt davon, dass er genau unsere Probleme löst und nicht nur ein weiteres Tool ist.
Feedback könnte sein:
- Fehler in der Software (bug)
- Verbesserungsvorschläge
- Wünsche für neue Funktionen
- etc. pp.

@ -1,178 +0,0 @@
.. _user_manual/members:
Teilnehmer\*innenverwaltung
===========================
Das wichtigste Objekt im Kompass ist ein\*e Teilnehmer\*in. Hier meint ein\*e Teilnehmer\*in ein im
Kompass hinterlegtes Mitglied der JDAV deiner Sektion, das heißt ob 5-jähriges Jugendgruppenkind,
langgediente\*r Jugendleiter\*in oder frischgebackene\*r Jugendreferent\*in, alle haben
einen Eintrag als Teilnehmer\*in im Kompass. Insbesondere heißt das, dass auch du selbst hier einen
Eintrag hast.
In der Teilnehmer\*innenverwaltung siehst du in der Regel zwei Menüpunkte:
- Meine Jugendgruppen: eine Auflistung der von dir geleiteten Jugendgruppen.
- Teilnehmer\*innenverwaltung: Ausfahrten und *Alle Teilnehmer\*innen*.
In diesem Abschnitt geht es nur um die Teilnehmer\*innen selbst. Wenn du etwas zum Punkt Ausfahrten
lernen möchtest, kannst du zu :ref:`user_manual/excursions` springen.
.. note::
Falls du ein Amt in deiner Sektion ausübst und zum Beispiel für Jugendgruppenkoordination
oder die Verwaltung der Warteliste zuständig ist, siehst du hier noch mehr Punkte. Mehr
Informationen dazu findest du unter :ref:`user_manual/waitinglist`.
Falls du direkt zu einer von dir geleiteten Jugendgruppe gehen möchtest, findest
du unter `Teilnehmer*innenverwaltung`_ oder auf der `Startseite`_
auch direkte Links zu den Teilnehmer\*innen deiner Gruppe.
Teilnehmer\*innen Übersicht
---------------------------
Um eine Übersicht über alle Teilnehmer\*innen zu bekommen, klicke auf `Alle Teilnehmer\*innen`_. Hier siehst du
nun alle Mitglieder, für die du die einfachen Anzeigeberechtigungen hast, das heißt deren Namen du sehen darfst.
Typischerweise sind das die Gruppenkinder deiner Jugendgruppe, aber vielleicht noch zusätzlich alle Mitglieder
des Jugendausschuss.
Wie sehe ich meine Gruppenkinder?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Oberhalb der großen Auflistung mit allen Teilnehmer\*innen siehst du verschiedene Auswahlfelder.
Eines davon heißt *Nach Gruppe*. Wenn du dort drauf klickst, kannst du die Ansicht nach einer Gruppe
filtern.
.. image:: images/members_changelist_group_filter.png
In der selben Zeile siehst du noch weitere Filtermöglichkeiten.
.. note::
Du kannst auch aus der Seitenleiste oder von der `Startseite`_ direkt zu den Gruppenkindern
einer von dir geleiteten Gruppe springen.
Ich möchte nach Alter sortieren, wie geht das?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Standardmäßig ist die Teilnehmer\*innenanzeige nach Nachname sortiert, wie du im folgenden Bild an dem
kleinen Pfeil erkennen kannst:
.. image:: images/members_changelist_sorting.png
Um zum Beispiel nach Geburtsdatum zu sortieren, klicke auf die Spalte *Geburtsdatum*. Wenn du die Reihenfolge
(das heißt von jung nach alt oder von alt nach jung), klicke auf den kleinen Pfeil im *Geburtsdatum* Reiter.
Wieso sehe ich nicht alle meine Gruppenkinder?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Hast du deine Gruppe ausgewählt und siehst trotzdem nicht alle deine Gruppenkinder auf einer Seite?
Dann liegt das vermutlich daran, dass deine Gruppe mehr als 25 Teilnehmer\*innen hat. Chapeau!
In diesem Fall kannst du unten Rechts auf der Seite zwischen den verschiedenen Seiten auswählen oder
alle auf einmal anzeigen lassen:
.. image:: images/members_changelist_pages.png
Teilnehmer\*in Detailansicht
----------------------------
Möchtest du eine\*n Teilnehmer\*in im Detail ansehen, um zum Beispiel Personendaten, wie die Anschrift
nachzuschauen oder eine Änderung an den Daten machen, klicke auf den entsprechenden Eintrag in der Liste.
Die nun folgende Seite kann auf den ersten Blick ein wenig erschlagen, daher dröseln wir hier die wichtigsten
Punkte auf. Zunächst ist die Seite in mehrere Reiter unterteilt:
.. image:: images/members_change_tabs.png
Diese sind
- Allgemein: wichtigste Informationen wie Name und E-Mail Adresse
- Kontaktinformationen: Anschrift, Kontodaten (für Jugendleiter\*innen beim Abwickeln von Ausfahrten)
- Fähigkeiten: z.B. alpine Erfahrungen
- Sonstiges: z.B. medizinische Daten
- Notfallkontakte: Liste mit Namen und mindestens Telefonnummern. Mehr Informationen
unter :ref:`emergency-contacts`.
- Fortbildungen: eine Liste von besuchten Fortbildungen.
.. note::
Der Reiter *Fortbildungen* wird nur auf deiner Seite angezeigt, das heißt falls du eines deiner
Gruppenkinder ausgewählt hast, ist dieser Reiter nicht vorhanden.
Wieso kann ich nicht alle Felder ändern?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Manche Felder werden dir nur angezeigt, sind aber nicht änderbar. Das sind entweder
- geschützte Felder, für die du besondere Berechtigungen benötigst um sie zu ändern
(z.B. das *Gruppe* Feld). Um diese Felder zu ändern, wende dich an deine\*n Jugendreferent\*in
für Jugendkoordination. Oder,
- automatisch berechnete Felder wie zum Beispiel das *Rückgemeldet* Feld.
Wieso haben manche Einträge in der Teilnehmer\*innenübersicht keinen Link?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Die Teilnehmer\*innen die dir in der Übersicht angezeigt werden sind diejenigen für die du
einfache Ansichtberechtigungen hast. Um die Personendetails eines\*einer Teilnehmer\*in einzusehen,
benötigst du normale Ansichtberechtigungen. Falls du diese nicht hast, wird anstatt des Links
in der Übersicht nur der Name angezeigt.
Falls du denkst, dass du eine\*n Teilnehmer\*in einsehen können solltest, aber es nicht kannst, melde
dich gerne bei deine\*r Jugendreferent\*in für Jugendkoordination.
.. _echo:
Rückmeldung
-----------
Damit die Teilnehmer\*innendaten im Kompass aktuell bleiben, kannst du jederzeit deine Gruppenkinder
zu einer Rückmeldung auffordern. Dazu wählst du in der Teilnehmer\*innenübersicht alle
Teilnehmer\*innen aus, die du zur Rückmeldung auffordern möchtest,
.. image:: images/members_changelist_action.png
und wählst dann im Menü unten links *Rückmeldungsaufforderungen an ausgewählte Teilnehmer\*innen verschicken*
aus. Um die Aufforderungen zu verschicken, musst du dann nur noch auf *Ausführen* klicken.
Was passiert nach der Aufforderung zur Rückmeldung?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Der\*die ausgewählte Teilnehmer\*in erhält eine E-Mail mit einem Link. Dieser Link führt auf eine
Seite auf der die Person ihr Geburtsdatum eingeben muss.
.. note::
Das Geburtsdatumsformat ist ``TT.MM.JJJJ``, also wenn Peter am
1.4.1999 geboren ist, muss er *01.04.1999* eingeben.
Nach erfolgreich eingegebenem Geburtsdatum, wird die Person auf ein Formular mit ihren Daten weitergeleitet.
Dann prüfen, gegebenenfalls aktualisieren und schließlich speichern. Der Link ist
immer 30 Tage lang gültig und kann in dieser Zeit auch beliebig oft benutzt werden.
Klingt alles noch abstrakt? Dann fordere dich doch mal selbst zur Rückmeldung auf und probiere es aus.
.. _emergency-contacts:
Notfallkontakte
---------------
Im Notfall helfen uns die Anschrift oder Telefonnummer einer\*eines Teilnehmer\*in nicht weiter. Stattdessen
benötigen wir Kontaktdaten von Personen, die wir im Notfall kontaktieren können. Diese können
im Reiter *Notfallkontakte* gepflegt werden. Bei der initialen Registrierung muss jede\*r Teilnehmer\*in
mindestens einen Notfallkontakt angeben.
.. note::
Bei vielen Teilnehmer\*innen sind keine Notfallkontakte eingetragen. Das liegt dann vermutlich daran,
dass sie aus einem anderen System migriert wurden und daher nicht verfügbar sind.
Bei der regelmäßigen :ref:`echo` werden die Notfallkontakte ebenfalls abgefragt. Falls
du bei einem deiner Gruppenkinder feststellst, dass die Notfallkontakte fehlen
oder nicht mehr aktuell sind, trage das so schnell wie möglich nach oder benutze die :ref:`echo`.
Was bringen mir die Notfallkontakte im Kompass?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Passiert ein Notfall auf einer Ausfahrt, wirst du natürlich nicht immer die Möglichkeit
haben im Kompass die Notfallkontakte herauszusuchen. Daher kannst du dir zu jeder Ausfahrt
eine :ref:`crisis-intervention-list` generieren lassen, die zu allen Teilnehmer\*innen deiner Ausfahrt
auch alle Notfallkontakte auflistet.
.. _Startseite: https://jdav-hd.de/kompass
.. _Teilnehmer*innenverwaltung: https://jdav-hd.de/kompassmembers
.. _Alle Teilnehmer\*innen: https://jdav-hd.de/kompassmembers/member/

@ -1,172 +0,0 @@
.. _user_manual/waitinglist:
Warteliste und neue Mitglieder
==============================
Neben der Verwaltung von bestehenden Teilnehmer\*innen, verwaltet und automatisiert der
Kompass auch möglichst viel der Aufnahme neuer Teilnehmer\*innen.
Grundsätzlich registrieren sich neue Mitglieder als Teilnehmer\*in einer Gruppe
im Kompass selbst. Dazu gibt es ein Registrierungsformular, indem das neue Gruppenkind oder
auch der*die neue Jugendleiter*in alle Stammdaten selber eingeben kann:
.. image:: images/members_registration_form.png
Natürlich soll sich nicht jede Person einfach so registrieren können, daher gibt es zwei Wege
zur Registrierung und damit zur Aufnahme als Teilnehmer\*in im Kompass:
- `Anmeldung auf der Warteliste`_ und Einladung zu einem Gruppenplatz sobald einer verfügbar ist:
Dies betrifft Gruppen, die zur Zeit keine freien Plätze haben, wie zum Beispiel volle Klettergruppen.
- `Direkte Registrierung`_ per :ref:`group-registration-password`: Für Gruppen ohne Warteliste kannst du
als Leiter*\in deiner
Gruppe neuen Mitgliedern das persönliche Gruppenpasswort mitteilen mit dem sie sich direkt
auf der Webseite für deine Gruppe registrieren können.
Nach Ausfüllen des Registrierungsformulars landen die Daten im Kompass unter
`Unbestätigte Registrierungen`_. Du überprüfst diese dann auf Vollständigkeit und bestätigst gegebenenfalls
die Registrierung, um die Person in deine Gruppe aufzunehmen.
Im folgenden werden die verschiedenen Komponenten erläutert. Während du als Gruppenleiter\*in in der
:ref:`registration` selbst die Daten deiner neuen Gruppenmitglieder kontrollierst und bestätigst,
wird die Warteliste von unserer\*unserem Beauftragte\*n für die Warteliste geführt.
.. _registration:
Registrierung
-------------
Ob über die Warteliste oder über ein :ref:`group-registration-password`: Erreicht die Person
den Status in eine Gruppe aufgenommen zu werden, trägt die Person ihre Daten selbstständig
über die Webseite ein.
Hier werden neben den Daten aus der Wartelistenanmeldung, auch eine Telefonnummer, Adresse und ein
Scan oder Foto vom Anmeldeformular abgefragt. Ebenso ist mindestens ein Notfallkontakt zu hinterlegen.
Liegt eine neue *Unbestätigte Registrierung* für eine Gruppe vor, so werden die Jugendleiter\*innen der
Gruppe darüber benachrichtigt.
Unbestätigte Registrierungen
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Nach ausgeführter Registrierung landet der\*die Teilnehmer\*in unter `Unbestätigte Registrierungen`_.
Hier siehst du alle Teilnehmer\*innen, die sich für deine Gruppe registrieren möchten. Möchte
die Person deiner Gruppe beitreten und hast du alle
Daten auf Vollständigkeit geprüft? Dann bestätige die Registrierung um den\*die neue Teilnehmer\*in in
deine Gruppe aufzunehmen.
Hat sich die Person dagegen entschieden sich deiner Gruppe anzuschließen, kannst du
den\*die Teilnehmer\*in wieder auf die Warteliste zurücksetzen:
.. image:: images/members_unconfirmed_registration_demote.png
Neues Mitglied in euerer Gruppe
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Nach dem ihr ein neues Mitglied in eurer Gruppe habt seid ihr auch vorrangig für die Datenpflege
zuständig. Bitte ruft die Detailansicht des\*der Teilnehmer\*in auf. Öffnet das Anmeldeformular und
Übertragt die Infos in die zugehörigen Felder. Weiteres dazu findet ihr in der
:ref:`Teilnehmer\*innenverwaltung <user_manual/members>`
.. _group-registration-password:
Gruppenpasswort
---------------
Für Gruppen die keine Warteliste haben, geht die Anmeldung direkt per E-Mail. Damit auch hier
die Daten nicht manuell eingegeben werden müssen, kann für die Gruppe ein Registrierungspasswort
angelegt werden.
Möchtest du für deine Gruppe ein solches Passwort anlegen, dann `melde dich
bei uns`_. Du kannst im Anschluss das Passwort deinen neuen Teilnehmenden mitteilen, sodass
sich diese direkt `registrieren`_ können.
Warteliste
----------
Wer gute und engagierte Jugendarbeit macht, stößt meist auf ein (schönes) Problem: Die Nachfrage
ist höher als es das ehrenamtliche Angebot hergibt. Daher können wir nicht allen
Interessierten einen Gruppenplatz anbieten und dürfen daher eine Warteliste pflegen.
Auf der `Anmeldungsseite`_ können sich Interessierte in unsere Warteliste eintragen. Wann immer
es wieder Platz in einer Jugendgruppe gibt, werden die Plätze den Personen auf der Liste entsprechend
ihrer Reihenfolge angeboten.
.. note::
Die folgenden Punkte werden federführend von unserer\*m Berauftragten für die Warteliste geführt.
Lies dennoch gerne weiter um die Prozesse tiefer zu verstehen! Es kann allerdings passieren, dass
du manche der Links im Folgenden nicht aufrufen kannst.
Anmeldung
^^^^^^^^^
Interessierte können sich selbst auf der Webseite `anmelden`_. Die Daten für den Eintrag in die Warteliste
sind bewusst so gering wie möglich gehalten. Es wird nur der Name, Geburtsdatum, Gender und Mail erfasst.
Zusätzlich gibt es ein Freitextfeld für eine Nachricht.
Um sicherzustellen, dass die E-Mail Adresse stimmt, wird zusätzlich eine Bestätigung der E-Mail Adresse abgefragt.
Verwaltung im Kompass
^^^^^^^^^^^^^^^^^^^^^
Eingereichte Anmeldungen landen im Kompass im Bereich `Warteliste`_. Neben der Übersicht
über alle Einträge auf der Warteliste, siehst du in der Detailansicht weitere Felder
wie zum Beispiel der bei der Anmeldung eingegebene Text.
Hast du eine Anmerkung zu einer Anmeldung, kannst du das im *Kommentare* Feld hinterlassen.
.. note::
Im Kompass lassen sich nicht manuell Wartelisteneinträge hinzufügen. Anfragen per Mail
sind auf das Formular zu verweisen, damit wird sichergestellt, dass die
E-Mail Adresse bestätigt wird.
Einladung zu einer Gruppe
^^^^^^^^^^^^^^^^^^^^^^^^^
Ist ein Platz frei geworden wird dieser Kindern von der Warteliste angeboten. Dies kann entweder durch
Auswahl mehrer Kinder in der Liste erfolgen, oder über den Knopf *Zu Gruppe einladen*, wenn man die
Detailseite zu einem Kind geöffnet hat.
.. image:: images/members_waitinglist_change_invite_to_group_button.png
Wenn du auf *Zu Gruppe einladen* klickst, gelangst du zu einer Seite auf der du
die Gruppe auswählen kannst zu der du die Person einladen möchtest.
.. image:: images/members_waitinglist_change_invite_to_group_selection.png
Klickst du dann auf *Einladen* wird das Kind / Eltern über die hinterlegte E-Mail Adresse darüber
informiert, dass es einen freien Gruppenplatz gibt. Die Mail enthält Zeit und Wochentag der
Gruppenstunde, wenn diese im Kompass hinterlegt sind. In der Mail ist außerdem ein Downloadlink zu
unserem Anmeldeformular und ein Link zur :ref:`registration` enthalten.
Passt die Zeit nicht, so kann die eingeladene Person den Platz direkt per Link aus der Mail heraus
ablehnen.
Eine Übersicht über alle Einladungen, die an die Person bereits verschickt wurden,
siehst du in der Detailansicht im Tab *Gruppeneinladungen*. Dort siehst du auch, ob die Einladung
noch aussteht oder abgelehnt wurde.
Die Leitung der Gruppe erhält die Mail per CC. Bitte nur lesen und keine Links klicken...
Pflege der Warteliste
^^^^^^^^^^^^^^^^^^^^^
Kinder werden manchmal schon vor der Geburt auf die Warteliste gesetzt, zwischen der Anmeldung
und der ersten Einladung zu einer Schnupperstunde können also Jahre vergehen. Das bedeutet natürlich,
dass sich das Interesse über die Zeit verändern kann.
Um zu verhindern, dass über lange Zeit *Karteileichen* mitgeschleppt werden, die gar kein Interesse
mehr an einem Jugendgruppenplatz haben, bietet der Kompass die Funktion eine wartende Person
aufzufordern ihr Interesse zu bestätigen.
Das passiert in regelmäßigen Abständen automatisch: Allen Wartenden wird eine E-Mail geschickt mit
einem Link, mit dem sie mit einem Klick ihr Interesse bestätigen können. Falls die Person
drei Erinnerungen verstreichen lässt, wird sie automatisch von der Warteliste entfernt.
.. _Anmeldungsseite: https://jdav-hd.de/de/members/waitinglist
.. _`Anmeldung auf der Warteliste`: https://jdav-hd.de/de/members/waitinglist
.. _`anmelden`: https://jdav-hd.de/de/members/waitinglist
.. _`Warteliste`: https://jdav-hd.de/de/kompassmembers/memberwaitinglist/
.. _`Direkte Registrierung`: https://jdav-hd.de/de/members/register
.. _`registrieren`: https://jdav-hd.de/de/members/register
.. _`Unbestätigte Registrierungen`: https://jdav-hd.de/de/kompassmembers/memberunconfirmedproxy/
.. _`melde dich bei uns`: mailto:digitales@jdav-hd.de

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

@ -12,58 +12,18 @@ import rules.contrib.admin
from rules.permissions import perm_exists 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: class FieldPermissionsAdminMixin:
field_change_permissions = {} field_permissions = {}
field_view_permissions = {}
def may_view_field(self, field_desc, request, obj=None):
if not type(field_desc) is tuple:
field_desc = (field_desc,)
for fd in field_desc:
if fd not in self.field_view_permissions:
continue
if not request.user.has_perm(self.field_view_permissions[fd]):
return False
return True
def get_fieldsets(self, request, obj=None):
fieldsets = super(FieldPermissionsAdminMixin, self).get_fieldsets(request, obj)
d = []
for title, attrs in fieldsets:
allowed = [f for f in attrs['fields'] if self.may_view_field(f, request, obj)]
if len(allowed) == 0:
continue
d.append((title, dict(attrs, **{'fields': allowed})))
return d
def get_fields(self, request, obj=None): def get_fields(self, request, obj=None):
fields = super(FieldPermissionsAdminMixin, self).get_fields(request, obj) fields = super(FieldPermissionsAdminMixin, self).get_fields(request, obj)
return [fd for fd in fields if self.may_view_field(fd, request, obj)]
def get_readonly_fields(self, request, obj=None): def may_field(field):
readonly_fields = super(FieldPermissionsAdminMixin, self).get_readonly_fields(request, obj) if field not in self.field_permissions:
return list(readonly_fields) +\ return True
[fd for fd, perm in self.field_change_permissions.items() if not request.user.has_perm(perm)] return request.user.has_perm(self.field_permissions[field], obj)
return list(filter(may_field, fields))
class ChangeViewAdminMixin: class ChangeViewAdminMixin:

@ -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,42 +0,0 @@
import os
from django.conf import settings
from django.http import HttpResponse
from django import template
from django.template.loader import get_template
from wsgiref.util import FileWrapper
def find_template(template_name):
for engine in template.engines.all():
for loader in engine.engine.template_loaders:
for origin in loader.get_template_sources(template_name):
if os.path.exists(origin.name):
return origin.name
raise template.TemplateDoesNotExist(f"Could not find template: {template_name}")
def media_path(fp):
return os.path.join(os.path.join(settings.MEDIA_ROOT, "memberlists"), fp)
def media_dir():
return os.path.join(settings.MEDIA_ROOT, "memberlists")
def serve_media(filename, content_type):
"""
Serve the media file with the given `filename` as an HTTP response.
"""
with open(media_path(filename), 'rb') as f:
response = HttpResponse(FileWrapper(f))
response['Content-Type'] = content_type
# download other files than pdf, show pdfs in the browser
response['Content-Disposition'] = 'filename='+filename if content_type == 'application/pdf' else 'attachment; filename='+filename
return response
def ensure_media_dir():
if not os.path.exists(media_dir()):
os.makedirs(media_dir())

@ -1,9 +0,0 @@
from django import template
from django.conf import settings
register = template.Library()
# settings value
@register.simple_tag
def settings_value(name):
return getattr(settings, name, "")

@ -1,175 +1,3 @@
from datetime import datetime, timedelta from django.test import TestCase
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
User = get_user_model() # Create your tests here.
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))

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

@ -1,8 +1,5 @@
import logging
from django.contrib import admin, messages from django.contrib import admin, messages
from django.utils.safestring import mark_safe from django.forms import Textarea
from django import forms
from django.forms import Textarea, ClearableFileInput
from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponse, HttpResponseRedirect
from django.db.models import TextField, Q from django.db.models import TextField, Q
from django.urls import path, reverse from django.urls import path, reverse
@ -12,108 +9,46 @@ from django.shortcuts import render
from django.conf import settings from django.conf import settings
from contrib.admin import CommonAdminInlineMixin, CommonAdminMixin from contrib.admin import CommonAdminInlineMixin, CommonAdminMixin
from utils import get_member, RestrictedFileField
from rules.contrib.admin import ObjectPermissionsModelAdmin from rules.contrib.admin import ObjectPermissionsModelAdmin
from members.pdf import render_tex_with_attachments
from .models import Ledger, Statement, Receipt, Transaction, Bill, StatementSubmitted, StatementConfirmed,\ from .models import Ledger, Statement, Receipt, Transaction, Bill, StatementSubmitted, StatementConfirmed,\
StatementUnSubmitted, BillOnStatementProxy StatementUnSubmitted, BillOnStatementProxy
logger = logging.getLogger(__name__)
@admin.register(Ledger) @admin.register(Ledger)
class LedgerAdmin(admin.ModelAdmin): class LedgerAdmin(admin.ModelAdmin):
search_fields = ('name', ) search_fields = ('name', )
class BillOnStatementInlineForm(forms.ModelForm):
class Meta:
model = BillOnStatementProxy
fields = ['short_description', 'explanation', 'amount', 'paid_by', 'proof']
widgets = {
'proof': ClearableFileInput(attrs={'accept': 'application/pdf,image/jpeg,image/png'}),
'explanation': Textarea(attrs={'rows': 1, 'cols': 40})
}
class BillOnStatementInline(CommonAdminInlineMixin, admin.TabularInline): class BillOnStatementInline(CommonAdminInlineMixin, admin.TabularInline):
model = BillOnStatementProxy model = BillOnStatementProxy
extra = 0 extra = 0
sortable_options = [] sortable_options = []
form = BillOnStatementInlineForm fields = ['short_description', 'explanation', 'amount', 'paid_by', 'proof']
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40})}
def decorate_statement_view(model, perm=None): }
def decorator(fun):
def aux(self, request, object_id):
try: @admin.register(StatementUnSubmitted)
statement = model.objects.get(pk=object_id) class StatementUnSubmittedAdmin(CommonAdminMixin, admin.ModelAdmin):
except model.DoesNotExist: fields = ['short_description', 'explanation', 'excursion', 'submitted']
messages.error(request, _('Statement not found.')) list_display = ['__str__', 'excursion', 'created_by']
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']
inlines = [BillOnStatementInline] 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): def save_model(self, request, obj, form, change):
if not change and hasattr(request.user, 'member'): if not change and hasattr(request.user, 'member'):
obj.created_by = request.user.member obj.created_by = request.user.member
super().save_model(request, obj, form, change) 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): def get_readonly_fields(self, request, obj=None):
readonly_fields = ['status', 'excursion'] readonly_fields = ['submitted', 'excursion']
if obj is not None and obj.submitted: if obj is not None and obj.submitted:
return readonly_fields + self.fields return readonly_fields + self.fields
else: else:
return readonly_fields 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): def get_urls(self):
urls = super().get_urls() urls = super().get_urls()
@ -130,33 +65,12 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
wrap(self.submit_view), wrap(self.submit_view),
name="%s_%s_submit" % (self.opts.app_label, self.opts.model_name), 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 return custom_urls + urls
@decorate_statement_view(StatementUnSubmitted) def submit_view(self, request, object_id):
def submit_view(self, request, statement): statement = Statement.objects.get(pk=object_id)
if statement.submitted: # pragma: no cover if statement.submitted:
logger.error(f"submit_view reached with submitted statement {statement}. This should not happen.")
messages.error(request, messages.error(request,
_("%(name)s is already submitted.") % {'name': str(statement)}) _("%(name)s is already submitted.") % {'name': str(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)))
@ -166,51 +80,94 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
messages.success(request, messages.success(request,
_("Successfully submited %(name)s. The finance department will notify the requestors as soon as possible.") % {'name': str(statement)}) _("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))) return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
context = dict(self.admin_site.each_context(request),
if statement.excursion: title=_('Submit statement'),
memberlist = statement.excursion
context = dict(self.admin_site.each_context(request),
title=_('Finance overview'),
opts=self.opts, opts=self.opts,
memberlist=memberlist, statement=statement)
object=memberlist,
ljp_contributions=memberlist.payable_ljp_contributions, return render(request, 'admin/submit_statement.html', context=context)
total_relative_costs=memberlist.total_relative_costs,
**memberlist.statement.template_context())
return render(request, 'admin/freizeit_finance_overview.html', context=context) 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):
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: else:
context = dict(self.admin_site.each_context(request), return readonly_fields
title=_('Submit statement'),
opts=self.opts, def get_urls(self):
statement=statement) urls = super().get_urls()
return render(request, 'admin/submit_statement.html', context=context)
def wrap(view):
@decorate_statement_view(StatementSubmitted) def wrapper(*args, **kwargs):
def overview_view(self, request, statement): return self.admin_site.admin_view(view)(*args, **kwargs)
if not statement.submitted: # pragma: no cover
logger.error(f"overview_view reached with unsubmitted statement {statement}. This should not happen.") 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, messages.error(request,
_("%(name)s is not yet submitted.") % {'name': str(statement)}) _("%(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,))) 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)) res = statement.confirm(confirmer=get_member(request))
if not res: # pragma: no cover if not res:
# this should NOT happen! # this should NOT happen!
logger.error(f"Error occured while confirming {statement}, this should not be possible.")
messages.error(request, messages.error(request,
_("An error occured while trying to confirm %(name)s. Please try again.") % {'name': str(statement)}) _("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))) 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, messages.success(request,
_("Successfully confirmed %(name)s. I hope you executed the associated transactions, I wont remind you again.") _("Successfully confirmed %(name)s. I hope you executed the associated transactions, I wont remind you again.")
% {'name': str(statement)}) % {'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))) return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
if "confirm" in request.POST: if "confirm" in request.POST:
res = statement.validity res = statement.validity
@ -230,21 +187,10 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
_("Some transactions have no ledger configured. Please fill in the gaps.") _("Some transactions have no ledger configured. Please fill in the gaps.")
% {'name': str(statement)}) % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_overview' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,))) return HttpResponseRedirect(reverse('admin:%s_%s_overview' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
elif res == Statement.INVALID_ALLOWANCE_TO: return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
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}.")
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)))
if "reject" in request.POST: if "reject" in request.POST:
statement.status = Statement.UNSUBMITTED statement.submitted = False
statement.save() statement.save()
messages.success(request, messages.success(request,
_("Successfully rejected %(name)s. The requestor can reapply, when needed.") _("Successfully rejected %(name)s. The requestor can reapply, when needed.")
@ -256,111 +202,57 @@ class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
messages.error(request, messages.error(request,
_("%(name)s already has transactions. Please delete them first, if you want to generate new ones") % {'name': str(statement)}) _("%(name)s already has transactions. Please delete them first, if you want to generate new ones") % {'name': str(statement)})
else: else:
success = statement.generate_transactions() statement.generate_transactions()
if success: messages.success(request,
messages.success(request, _("Successfully generated transactions for %(name)s") % {'name': str(statement)})
_("Successfully generated transactions for %(name)s") % {'name': str(statement)})
else:
messages.error(request,
_("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(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,))) return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
context = dict(self.admin_site.each_context(request), context = dict(self.admin_site.each_context(request),
title=_('View submitted statement'), title=_('View submitted statement'),
opts=self.opts, opts=self.opts,
statement=statement, statement=statement,
settings=settings,
transaction_issues=statement.transaction_issues, transaction_issues=statement.transaction_issues,
**statement.template_context()) total_bills=statement.total_bills,
total=statement.total)
if statement.excursion is not None:
context = dict(context,
nights=statement.excursion.night_count,
price_per_night=statement.real_night_cost,
duration=statement.excursion.duration,
staff_count=statement.real_staff_count,
kilometers_traveled=statement.excursion.kilometers_traveled,
means_of_transport=statement.excursion.get_tour_approach(),
euro_per_km=statement.euro_per_km,
allowance_per_day=settings.ALLOWANCE_PER_DAY,
nights_per_yl=statement.nights_per_yl,
allowance_per_yl=statement.allowance_per_yl,
transportation_per_yl=statement.transportation_per_yl,
total_per_yl=statement.total_per_yl,
total_staff=statement.total_staff)
return render(request, 'admin/overview_submitted_statement.html', context=context) return render(request, 'admin/overview_submitted_statement.html', context=context)
@decorate_statement_view(StatementSubmitted) def reduce_transactions_view(self, request, object_id):
def reduce_transactions_view(self, request, statement): statement = StatementSubmitted.objects.get(pk=object_id)
statement.reduce_transactions() statement.reduce_transactions()
messages.success(request, messages.success(request,
_("Successfully reduced transactions for %(name)s.") % {'name': str(statement)}) _("Successfully reduced transactions for %(name)s.") % {'name': str(statement)})
return HttpResponseRedirect(request.GET['redirectTo']) return HttpResponseRedirect(request.GET['redirectTo'])
#return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
@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}.")
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_date = None
statement.confired_by = None
statement.save()
messages.success(request,
_("Successfully unconfirmed %(name)s. I hope you know what you are doing.")
% {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
context = dict(self.admin_site.each_context(request),
title=_('Unconfirm statement'),
opts=self.opts,
statement=statement)
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 @admin.register(StatementConfirmed)
text_length_warning.short_description = _("Length") 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',)
def has_add_permission(self, request, obj=None):
class BillOnSubmittedStatementInline(BillOnStatementInline): return False
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) @admin.register(Transaction)
class TransactionAdmin(admin.ModelAdmin): class TransactionAdmin(admin.ModelAdmin):
"""The transaction admin site. This is only used to display transactions. All editing
is disabled on this site. All transactions should be changed on the respective statement
at the correct stage of the approval chain."""
list_display = ['member', 'ledger', 'amount', 'reference', 'statement', 'confirmed', list_display = ['member', 'ledger', 'amount', 'reference', 'statement', 'confirmed',
'confirmed_date', 'confirmed_by'] 'confirmed_date', 'confirmed_by']
list_filter = ('ledger', 'member', 'statement', 'confirmed') list_filter = ('ledger', 'member', 'statement', 'confirmed')
@ -372,21 +264,16 @@ class TransactionAdmin(admin.ModelAdmin):
return self.fields return self.fields
return super(TransactionAdmin, self).get_readonly_fields(request, obj) return super(TransactionAdmin, self).get_readonly_fields(request, obj)
def has_add_permission(self, request, obj=None):
# To preserve integrity, no one is allowed to add transactions
return False
def has_change_permission(self, request, obj=None):
# To preserve integrity, no one is allowed to change transactions
return False
def has_delete_permission(self, request, obj=None):
# To preserve integrity, no one is allowed to delete transactions
return False
@admin.register(Bill) @admin.register(Bill)
class BillAdmin(admin.ModelAdmin): class BillAdmin(admin.ModelAdmin):
list_display = ['__str__', 'statement', 'explanation', 'pretty_amount', 'paid_by', 'refunded'] list_display = ['__str__', 'statement', 'short_description', 'pretty_amount', 'paid_by', 'refunded']
list_filter = ('statement', 'paid_by', 'refunded') list_filter = ('statement', 'paid_by', 'refunded')
search_fields = ('reference', 'statement') search_fields = ('reference', 'statement')
def get_member(request):
if not hasattr(request.user, 'member'):
return None
else:
return request.user.member

@ -8,7 +8,7 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: PACKAGE VERSION\n" "Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-10-16 23:09+0200\n" "POT-Creation-Date: 2023-03-20 18:48+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n" "Language-Team: LANGUAGE <LL@li.org>\n"
@ -18,20 +18,12 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n" "Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:69
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 #, python-format
msgid "%(name)s is already submitted." msgid "%(name)s is already submitted."
msgstr "%(name)s ist bereits eingereicht." msgstr "%(name)s ist bereits eingereicht."
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:75
#, python-format #, python-format
msgid "" msgid ""
"Successfully submited %(name)s. The finance department will notify the " "Successfully submited %(name)s. The finance department will notify the "
@ -40,31 +32,23 @@ msgstr ""
"Rechnung %(name)s erfolgreich eingereicht. Das Finanzreferat wird auf dich " "Rechnung %(name)s erfolgreich eingereicht. Das Finanzreferat wird auf dich "
"sobald wie möglich zukommen." "sobald wie möglich zukommen."
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:78
msgid "Finance overview"
msgstr "Kostenübersicht"
#: finance/admin.py finance/tests/admin.py
msgid "Submit statement" msgid "Submit statement"
msgstr "Rechnung einreichen" msgstr "Rechnung einreichen"
#: finance/admin.py #: finance/admin.py:152
#, python-format #, python-format
msgid "%(name)s is not yet submitted." msgid "%(name)s is not yet submitted."
msgstr "%(name)s ist noch nicht eingereicht." msgstr "%(name)s ist noch nicht eingereicht."
#: finance/admin.py #: finance/admin.py:159
#, python-format #, python-format
msgid "An error occured while trying to confirm %(name)s. Please try again." msgid "An error occured while trying to confirm %(name)s. Please try again."
msgstr "" msgstr ""
"Beim Abwickeln von %(name)s ist ein Fehler aufgetreten. Bitte versuche es " "Beim Abwickeln von %(name)s ist ein Fehler aufgetreten. Bitte versuche es "
"erneut." "erneut."
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:163
msgid "Successfully sent receipt to the office."
msgstr "Abrechnungsbeleg an die Geschäftsstelle gesendet."
#: finance/admin.py finance/tests/admin.py
#, python-format #, python-format
msgid "" msgid ""
"Successfully confirmed %(name)s. I hope you executed the associated " "Successfully confirmed %(name)s. I hope you executed the associated "
@ -73,18 +57,11 @@ msgstr ""
"Erfolgreich %(name)s abgewickelt. Ich hoffe du hast die zugehörigen " "Erfolgreich %(name)s abgewickelt. Ich hoffe du hast die zugehörigen "
"Überweisungen ausgeführt, ich werde dich nicht nochmal erinnern." "Überweisungen ausgeführt, ich werde dich nicht nochmal erinnern."
#: finance/admin.py #: finance/admin.py:170
#, 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" msgid "Statement confirmed"
msgstr "Abrechnung abgewickelt" msgstr "Abrechnung abgewickelt"
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:176
msgid "" msgid ""
"Transactions do not match the covered expenses. Please correct the mistakes " "Transactions do not match the covered expenses. Please correct the mistakes "
"listed below." "listed below."
@ -92,35 +69,19 @@ msgstr ""
"Überweisungen stimmen nicht mit den übernommenen Kosten überein. Bitte " "Überweisungen stimmen nicht mit den übernommenen Kosten überein. Bitte "
"korrigiere die unten aufgeführten Fehler." "korrigiere die unten aufgeführten Fehler."
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:181
msgid "Some transactions have no ledger configured. Please fill in the gaps." msgid "Some transactions have no ledger configured. Please fill in the gaps."
msgstr "" msgstr ""
"Manche Überweisungen haben kein Geldtopf eingestellt. Bitte trage das nach." "Manche Überweisungen haben kein Geldtopf eingestellt. Bitte trage das nach."
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:190
msgid ""
"The configured recipients for the allowance don't match the regulations. "
"Please correct this on the excursion."
msgstr ""
"Die ausgewählten Empfänger*innen der Aufwandsentschädigungen entsprechen "
"nicht den Regularien. Bitte korrigiere das in der Ausfahrt."
#: finance/admin.py
msgid ""
"The calculated total amount does not match the sum of all transactions. This "
"is most likely a bug."
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
#, python-format #, python-format
msgid "Successfully rejected %(name)s. The requestor can reapply, when needed." msgid "Successfully rejected %(name)s. The requestor can reapply, when needed."
msgstr "" msgstr ""
"Die Rechnung %(name)s wurde abgelehnt. Die Person kann die Rechnung erneut " "Die Rechnung %(name)s wurde abgelehnt. Die Person kann die Rechnung erneut "
"einstellen, wenn es benötigt wird." "einstellen, wenn es benötigt wird."
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:197
#, python-format #, python-format
msgid "" msgid ""
"%(name)s already has transactions. Please delete them first, if you want to " "%(name)s already has transactions. Please delete them first, if you want to "
@ -129,296 +90,198 @@ msgstr ""
"%(name)s hat bereits Überweisungen. Bitte lösche diese zunächst, bevor du " "%(name)s hat bereits Überweisungen. Bitte lösche diese zunächst, bevor du "
"neue generierst." "neue generierst."
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:201
#, python-format #, python-format
msgid "Successfully generated transactions for %(name)s" msgid "Successfully generated transactions for %(name)s"
msgstr "Automatisch Überweisungsträger für %(name)s generiert." msgstr "Automatisch Überweisungsträger für %(name)s generiert."
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:204
#, python-format
msgid ""
"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?"
msgstr ""
"Fehler beim Erzeugen der Überweisungsträger für %(name)s. Sind für alle "
"Quittungen eine bezahlende Person eingestellt und, falls diese Abrechnung zu "
"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
msgid "View submitted statement" msgid "View submitted statement"
msgstr "Eingereichte Abrechnung einsehen" msgstr "Eingereichte Abrechnung einsehen"
#: finance/admin.py finance/tests/admin.py #: finance/admin.py:230
#, python-format #, python-format
msgid "Successfully reduced transactions for %(name)s." msgid "Successfully reduced transactions for %(name)s."
msgstr "Überweisungsträger für %(name)s minimiert." msgstr "Überweisungsträger für %(name)s minimiert."
#: finance/admin.py #: finance/apps.py:8
#, python-format
msgid "%(name)s is not yet confirmed."
msgstr "%(name)s ist noch nicht bestätigt."
#: finance/admin.py
#, python-format
msgid "Successfully unconfirmed %(name)s. I hope you know what you are doing."
msgstr ""
"Erfolgreich die Bestätigung von %(name)s zurückgenommen. Ich hoffe du weißt "
"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" msgid "Finance"
msgstr "Finanzen" msgstr "Finanzen"
#: finance/models.py #: finance/models.py:13
msgid "Name" msgid "Name"
msgstr "Name" msgstr "Name"
#: finance/models.py finance/templates/admin/confirmed_statement.html #: finance/models.py:19 finance/models.py:372 finance/models.py:396
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/confirmed_statement.html:38
#: finance/templates/admin/overview_submitted_statement.html:100
msgid "Ledger" msgid "Ledger"
msgstr "Geldtopf" msgstr "Geldtopf"
#: finance/models.py #: finance/models.py:20
msgid "Ledgers" msgid "Ledgers"
msgstr "Geldtöpfe" msgstr "Geldtöpfe"
#: finance/models.py #: finance/models.py:42 finance/models.py:343 finance/models.py:395
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" msgid "Short description"
msgstr "Kurzbeschreibung" msgstr "Kurzbeschreibung"
#: finance/models.py finance/templates/admin/submit_statement.html #: finance/models.py:45 finance/models.py:344
msgid "Explanation" msgid "Explanation"
msgstr "Erklärung" msgstr "Erklärung"
#: finance/models.py #: finance/models.py:47
msgid "Associated excursion" msgid "Associated excursion"
msgstr "Zugehörige Ausfahrt" msgstr "Zugehörige Freizeit"
#: finance/models.py
msgid "Pay allowance to"
msgstr "Aufwandsentschädigung auszahlen an"
#: finance/models.py
msgid "The youth leaders to which an allowance should be paid."
msgstr ""
"Die Jugendleiter*innen an die eine Aufwandsentschädigung ausgezahlt werden "
"soll."
#: finance/models.py #: finance/models.py:52
msgid "Pay subsidy to"
msgstr "Übernachtungs- und Fahrtkostenzuschüsse auszahlen an"
#: finance/models.py
msgid ""
"The person that should receive the subsidy for night and travel costs. "
"Typically the person who paid for them."
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" msgid "Price per night"
msgstr "Preis pro Nacht" msgstr "Preis pro Nacht"
#: finance/models.py #: finance/models.py:54
msgid "Status" msgid "Submitted"
msgstr "Status" msgstr "Eingericht"
#: finance/models.py #: finance/models.py:55
msgid "Submitted on" msgid "Submitted on"
msgstr "Eingereicht am" msgstr "Eingereicht am"
#: finance/models.py #: finance/models.py:56
msgid "Confirmed"
msgstr "Abgewickelt"
#: finance/models.py:57 finance/models.py:379
msgid "Paid on" msgid "Paid on"
msgstr "Bezahlt am" msgstr "Bezahlt am"
#: finance/models.py #: finance/models.py:59
msgid "Created by"
msgstr "Erstellt von"
#: finance/models.py
msgid "Submitted by" msgid "Submitted by"
msgstr "Eingereicht von" msgstr "Eingereicht bei"
#: finance/models.py #: finance/models.py:64 finance/models.py:380
msgid "Authorized by" msgid "Authorized by"
msgstr "Autorisiert von" msgstr "Autorisiert von"
#: finance/models.py #: finance/models.py:71 finance/models.py:342 finance/models.py:375
msgid "Statement" msgid "Statement"
msgstr "Abrechnung" msgstr "Abrechnung"
#: finance/models.py #: finance/models.py:72
msgid "Statements" msgid "Statements"
msgstr "Abrechnungen" msgstr "Abrechnungen"
#: finance/models.py #: finance/models.py:77
#, python-format #, python-format
msgid "Excursion %(excursion)s" msgid "Statement: %(excursion)s"
msgstr "Ausfahrt %(excursion)s" msgstr "Abrechnung: %(excursion)s"
#: finance/models.py #: finance/models.py:123
msgid "Ready to confirm" msgid "Ready to confirm"
msgstr "Bereit zur Abwicklung" msgstr "Bereit zur Abwicklung"
#: finance/models.py #: finance/models.py:162
#, python-format #, python-format
msgid "Allowance for %(excu)s" msgid "Compensation for %(excu)s"
msgstr "Aufwandsentschädigung für %(excu)s" msgstr "Entschädigung für %(excu)s"
#: finance/models.py #: finance/models.py:294
#, python-format #: finance/templates/admin/overview_submitted_statement.html:78
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
msgid "Total" msgid "Total"
msgstr "Gesamtbetrag" msgstr "Gesamtbetrag"
#: finance/models.py #: finance/models.py:307
#, python-format
msgid "Statement summary for %(title)s"
msgstr "Abrechnung für %(title)s"
#: finance/models.py
msgid "Statement in preparation" msgid "Statement in preparation"
msgstr "Abrechnung in Vorbereitung" msgstr "Abrechnung in Vorbereitung"
#: finance/models.py #: finance/models.py:308
msgid "Statements in preparation" msgid "Statements in preparation"
msgstr "Abrechnungen in Vorbereitung" msgstr "Abrechnungen in Vorbereitung"
#: finance/models.py #: finance/models.py:321
msgid "Submitted statement" msgid "Submitted statement"
msgstr "Eingereichte Abrechnung" msgstr "Eingereichte Abrechnung"
#: finance/models.py #: finance/models.py:322
msgid "Submitted statements" msgid "Submitted statements"
msgstr "Eingereichte Abrechnungen" msgstr "Eingereichte Abrechnungen"
#: finance/models.py #: finance/models.py:336
msgid "Paid statement" msgid "Paid statement"
msgstr "Bezahlte Abrechnung" msgstr "Bezahlte Abrechnung"
#: finance/models.py #: finance/models.py:337
msgid "Paid statements" msgid "Paid statements"
msgstr "Bezahlte Abrechnungen" msgstr "Bezahlte Abrechnungen"
#: finance/models.py finance/templates/admin/confirmed_statement.html #: finance/models.py:347
#: finance/templates/admin/overview_submitted_statement.html
#: finance/templates/admin/submit_statement.html
msgid "Amount"
msgstr "Betrag"
#: finance/models.py finance/templates/admin/submit_statement.html
msgid "Paid by" msgid "Paid by"
msgstr "Bezahlt von" msgstr "Bezahlt von"
#: finance/models.py #: finance/models.py:349
msgid "Covered" msgid "Covered"
msgstr "Übernommen" msgstr "Übernommen"
#: finance/models.py #: finance/models.py:350
msgid "Refunded" msgid "Refunded"
msgstr "Ausgezahlt" msgstr "Ausgezahlt"
#: finance/models.py #: finance/models.py:352
msgid "Proof" msgid "Proof"
msgstr "Beleg" msgstr "Beleg"
#: finance/models.py #: finance/models.py:360 finance/models.py:369
#: finance/templates/admin/confirmed_statement.html:36
#: finance/templates/admin/overview_submitted_statement.html:31
#: finance/templates/admin/overview_submitted_statement.html:98
msgid "Amount"
msgstr "Betrag"
#: finance/models.py:363
msgid "Bill" msgid "Bill"
msgstr "Ausgabe" msgstr "Quittung"
#: finance/models.py finance/templates/admin/overview_submitted_statement.html #: finance/models.py:364
#: finance/templates/admin/overview_submitted_statement.html:26
msgid "Bills" msgid "Bills"
msgstr "Ausgaben" msgstr "Quittungen"
#: finance/models.py finance/templates/admin/confirmed_statement.html #: finance/models.py:368 finance/templates/admin/confirmed_statement.html:37
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:99
msgid "Reference" msgid "Reference"
msgstr "Verwendungszweck" msgstr "Verwendungszweck"
#: finance/models.py #: finance/models.py:370
msgid "Recipient" msgid "Recipient"
msgstr "Empfänger" msgstr "Empfänger"
#: finance/models.py #: finance/models.py:378
msgid "Paid" msgid "Paid"
msgstr "Bezahlt" msgstr "Bezahlt"
#: finance/models.py #: finance/models.py:390
msgid "Transaction" msgid "Transaction"
msgstr "Überweisung" msgstr "Überweisung"
#: finance/models.py finance/templates/admin/overview_submitted_statement.html #: finance/models.py:391
#: finance/templates/admin/overview_submitted_statement.html:84
msgid "Transactions" msgid "Transactions"
msgstr "Überweisungen" msgstr "Überweisungen"
#: finance/templates/admin/confirmed_statement.html #: finance/templates/admin/confirmed_statement.html:17
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:17
#: finance/templates/admin/submit_statement.html #: finance/templates/admin/submit_statement.html:17
#: finance/templates/admin/unconfirm_statement.html
msgid "Home" msgid "Home"
msgstr "Start" msgstr "Start"
#: finance/templates/admin/confirmed_statement.html #: finance/templates/admin/confirmed_statement.html:21
msgid "Paiment" msgid "Paiment"
msgstr "Bezahlung" msgstr "Bezahlung"
#: finance/templates/admin/confirmed_statement.html #: finance/templates/admin/confirmed_statement.html:26
msgid "Paying statement" msgid "Paying statement"
msgstr "Rechnung bezahlen" msgstr "Rechnung bezahlen"
#: finance/templates/admin/confirmed_statement.html #: finance/templates/admin/confirmed_statement.html:29
msgid "" msgid ""
"The statement is valid. Please execute the following transactions and then " "The statement is valid. Please execute the following transactions and then "
"proceed by finalizing the confirmation." "proceed by finalizing the confirmation."
@ -426,64 +289,43 @@ msgstr ""
"Die Abrechnung ist gültig. Bitte führe die folgenden Überweisungen aus und " "Die Abrechnung ist gültig. Bitte führe die folgenden Überweisungen aus und "
"fahre dann fort, indem du die Abwicklung bestätigst." "fahre dann fort, indem du die Abwicklung bestätigst."
#: finance/templates/admin/confirmed_statement.html #: finance/templates/admin/confirmed_statement.html:35
msgid "IBAN" msgid "IBAN"
msgstr "IBAN" msgstr "IBAN"
#: finance/templates/admin/confirmed_statement.html #: finance/templates/admin/confirmed_statement.html:66
msgid "QR Code"
msgstr "QR Code"
#: finance/templates/admin/confirmed_statement.html
msgid "Show"
msgstr "Anzeigen"
#: finance/templates/admin/confirmed_statement.html
msgid "No QR code can be displayed."
msgstr "Es kann kein QR-Code angezeigt werden."
#: finance/templates/admin/confirmed_statement.html
msgid "Showing"
msgstr "Sichtbar"
#: finance/templates/admin/confirmed_statement.html
msgid "I did execute the listed transactions." msgid "I did execute the listed transactions."
msgstr "Ich habe die aufgeführten Überweisungen ausgeführt." msgstr "Ich habe die aufgeführten Überweisungen ausgeführt."
#: finance/templates/admin/confirmed_statement.html #: finance/templates/admin/confirmed_statement.html:68
msgid "Confirm only" msgid "Confirm"
msgstr "Nur bestätigen" msgstr "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"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:21
msgid "Overview" msgid "Overview"
msgstr "Übersicht" msgstr "Übersicht"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:32
msgid "Covered by association" msgid "Covered by association"
msgstr "Vom Verein übernommen" msgstr "Vom Verein übernommen"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:50
#, python-format #, python-format
msgid "The total amount is %(total_bills)s €." msgid "The total amount is %(total_bills)s €."
msgstr "Der Gesamtbetrag beträgt %(total_bills)s €." msgstr "Der Gesamtbetrag beträgt %(total_bills)s €."
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:54
msgid "Excursion" msgid "Excursion"
msgstr "Ausfahrt" msgstr "Freizeit"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:57
#, python-format #, python-format
msgid "This excursion featured %(staff_count)s youth leader(s), each costing" msgid "This excursion featured %(staff_count)s youth leader(s), each costing"
msgstr "" msgstr ""
"Diese Ausfahrt hatte %(staff_count)s genehmigte Jugendleiter*innen. Für " "Diese Freizeit hatte %(staff_count)s Jugendleiter:innen. Auf jede:n "
"jede*n besteht ein Anspruch auf folgende Zuschüsse und " "entfallen die folgenden Kosten:"
"Aufwandsentschädigungen:"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:62
#, python-format #, python-format
msgid "" msgid ""
"%(nights)s nights for %(price_per_night)s€ per night making a total of " "%(nights)s nights for %(price_per_night)s€ per night making a total of "
@ -492,7 +334,7 @@ msgstr ""
"%(nights)s Nächte zum Preis von %(price_per_night)s€ pro Nacht. Das ergibt " "%(nights)s Nächte zum Preis von %(price_per_night)s€ pro Nacht. Das ergibt "
"eine Gesamtsumme von %(nights_per_yl)s€." "eine Gesamtsumme von %(nights_per_yl)s€."
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:65
#, python-format #, python-format
msgid "" msgid ""
"%(duration)s days for %(allowance_per_day)s€ per day making a total of " "%(duration)s days for %(allowance_per_day)s€ per day making a total of "
@ -501,7 +343,7 @@ msgstr ""
"%(duration)s Tage für %(allowance_per_day)s€ pro Tag. Das ergibt eine " "%(duration)s Tage für %(allowance_per_day)s€ pro Tag. Das ergibt eine "
"Gesamtsumme von %(allowance_per_yl)s€." "Gesamtsumme von %(allowance_per_yl)s€."
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:68
#, python-format #, python-format
msgid "" msgid ""
"%(kilometers_traveled)s km by %(means_of_transport)s (%(euro_per_km)s € / " "%(kilometers_traveled)s km by %(means_of_transport)s (%(euro_per_km)s € / "
@ -510,128 +352,21 @@ msgstr ""
"%(kilometers_traveled)s km mit %(means_of_transport)s (%(euro_per_km)s€ / " "%(kilometers_traveled)s km mit %(means_of_transport)s (%(euro_per_km)s€ / "
"km). Das ergibt eine Gesamtsumme von %(transportation_per_yl)s€." "km). Das ergibt eine Gesamtsumme von %(transportation_per_yl)s€."
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:73
#, python-format #, python-format
msgid "" msgid ""
"In total this is %(total_per_yl)s€ times %(staff_count)s, giving " "In total this is %(total_per_yl)s€ times %(staff_count)s, giving "
"%(theoretical_total_staff)s€." "%(total_staff)s€."
msgstr "" msgstr ""
"Insgesamt sind das Kosten von %(total_per_yl)s€ mal %(staff_count)s, " "Insgesamt sind das Kosten von %(total_per_yl)s€ mal %(staff_count)s, "
"insgesamt also maximal %(theoretical_total_staff)s€." "insgesamt also %(total_staff)s€."
#: finance/templates/admin/overview_submitted_statement.html
msgid "Payment of subsidies and allowances"
msgstr "Auszahlung von Sektionszuschüssen und Aufwandsentschädigungen"
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid "The allowance of %(allowance_per_yl)s€ per person should be paid to:"
msgstr ""
"Die Aufwandsentschädigung von %(allowance_per_yl)s€ pro Person soll "
"ausgezahlt werden an:"
#: finance/templates/admin/overview_submitted_statement.html
#: finance/templates/admin/submit_statement.html
msgid "IBAN valid"
msgstr "IBAN gültig"
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
"Only %(allowances_paid)s of the %(real_staff_count)s youth leaders have "
"requested the outpayment of their allowance."
msgstr ""
"Achtung: Nur für %(allowances_paid)s der %(real_staff_count)s "
"Jugendleiter*innen wird die Aufwandsentschädigung abgerufen."
#: finance/templates/admin/overview_submitted_statement.html
msgid ""
"No receivers of the allowance were provided. Allowance will not be used."
msgstr ""
"Keine Empfänger*innen für eine Aufwandsentschädigung angegeben. Es wird "
"daher keine Aufwandsentschädigung ausbezahlt."
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
"The subsidies for night and transportation costs of %(total_subsidies)s€ "
"should be paid to:"
msgstr ""
"Die Zuschüsse für Übernachtungs- und Fahrtkosten von %(total_subsidies)s€ "
"für alle Jugendleiter*innen sollen ausgezahlt werden an:"
#: finance/templates/admin/overview_submitted_statement.html
msgid ""
"No receivers of the subsidies were provided. Subsidies will not be used."
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 #: finance/templates/admin/overview_submitted_statement.html:81
#, 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 #, python-format
msgid "This results in a total amount of %(total)s€" msgid "This results in a total amount of %(total)s€"
msgstr "Das resultiert in einem Gesamtbetrag von %(total)s€" msgstr "Das resultiert in einem Gesamtbetrag von %(total)s€"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:87
msgid "" msgid ""
"Currently, no transactions are planned. You can auto generate them from the " "Currently, no transactions are planned. You can auto generate them from the "
"data, by clicking the following button." "data, by clicking the following button."
@ -639,19 +374,19 @@ msgstr ""
"Aktuell sind keine Überweisungen vorgesehen. Du kannst die erforderlichen " "Aktuell sind keine Überweisungen vorgesehen. Du kannst die erforderlichen "
"durch Klicken auf den folgenden Knopf generieren." "durch Klicken auf den folgenden Knopf generieren."
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:90
msgid "Generate transactions" msgid "Generate transactions"
msgstr "Erzeuge Überweisungsträger" msgstr "Erzeuge Überweisungsträger"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:94
msgid "Currently the following transactions are planned." msgid "Currently the following transactions are planned."
msgstr "Aktuell sind die folgenden Überweisungen vorgesehen." msgstr "Aktuell sind die folgenden Überweisungen vorgesehen."
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:137
msgid "These transactions match the calculated costs." msgid "These transactions match the calculated costs."
msgstr "Diese Überweisungen stimmen mit den berechneten Kosten überein." msgstr "Diese Überweisungen stimmen mit den berechneten Kosten überein."
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:140
msgid "" msgid ""
"The current transactions do not reflect all costs in this statement. Please " "The current transactions do not reflect all costs in this statement. Please "
"fix the following issues:" "fix the following issues:"
@ -659,72 +394,44 @@ msgstr ""
"Die aktuell vorgesehenen Überweisungen stimmen nicht mit den berechneten " "Die aktuell vorgesehenen Überweisungen stimmen nicht mit den berechneten "
"Kosten überein. Bitte korrigiere die folgenden Fehler:" "Kosten überein. Bitte korrigiere die folgenden Fehler:"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:145
msgid "Currently receiving" msgid "Currently receiving"
msgstr "Erhält aktuell" msgstr "Erhält aktuell"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:146
msgid "Actual costs" msgid "Actual costs"
msgstr "Tatsächliche Kosten" msgstr "Tatsächliche Kosten"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:147
msgid "Difference" msgid "Difference"
msgstr "Differenz" msgstr "Differenz"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:174
msgid "Accept" msgid "Accept"
msgstr "Annehmen" msgstr "Annehmen"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:175
msgid "Reject" msgid "Reject"
msgstr "Ablehnen" msgstr "Ablehnen"
#: finance/templates/admin/overview_submitted_statement.html #: finance/templates/admin/overview_submitted_statement.html:178
#: finance/templates/admin/submit_statement.html #: finance/templates/admin/submit_statement.html:35
#: finance/templates/admin/unconfirm_statement.html
msgid "Cancel" msgid "Cancel"
msgstr "Abbruch" msgstr "Abbruch"
#: finance/templates/admin/submit_statement.html #: finance/templates/admin/submit_statement.html:21
#: finance/templates/admin/submit_statement.html:34
msgid "Submit" msgid "Submit"
msgstr "Einreichen" msgstr "Einreichen"
#: finance/templates/admin/submit_statement.html #: finance/templates/admin/submit_statement.html:26
msgid "Submit to the finance department" msgid "Submit to the finance department"
msgstr "Beim Finanzreferat einreichen" msgstr "Beim Finanzreferat einreichen"
#: finance/templates/admin/submit_statement.html #: finance/templates/admin/submit_statement.html:28
msgid ""
"Please check if all expenses are documented correctly and if all payers have "
"a valid account code."
msgstr ""
"Bitte überprüfe, ob alle Ausgaben korrekt erfasst sind und ob alle "
"auslegenden Personen eine gültige IBAN haben."
#: finance/templates/admin/submit_statement.html
msgid "" msgid ""
"Do you want to submit the statement for further processing by the finance " "Do you want to submit the statement for further processing by the finance "
"department? If you proceed, no further changes to the statement are possible." "department? If you proceed, no further changes to the statement are possible."
msgstr "" msgstr ""
"Möchtest du die Abrechnung beim Finanzreferat einreichen? Wenn du " "Möchtest du die Abrechnung beim Finanzreferat einreichen? Wenn du "
"fortschreitest, sind keine weiteren Änderungen an der Abrechnung möglich." "fortschreitest, sind keine weiteren Änderungen an der Abrechnung möglich."
#: finance/templates/admin/unconfirm_statement.html
msgid "Unconfirm"
msgstr "Bestätigung zurücknehmen"
#: finance/templates/admin/unconfirm_statement.html
msgid ""
"You are entering risk zone! Do you really want to manually set this "
"statement back to unconfirmed?"
msgstr ""
"Du bewegst dich in einer Risiko Zone! Möchtest du wirklich manuell die "
"Bestätigung dieser Abrechnung zurücknehmen?"
#: finance/templates/admin/unconfirm_statement.html
msgid ""
"I am aware that this is not a standard procedure and this might cause data "
"integrity issues."
msgstr ""
"Mir ist bewusst, dass das keine Standardprozedur ist und das dies die "
"Integrität der Daten zerstören kann."

@ -1,18 +0,0 @@
# Generated by Django 4.0.1 on 2024-12-02 00:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('finance', '0003_alter_bill_options_and_more'),
]
operations = [
migrations.AlterField(
model_name='bill',
name='amount',
field=models.DecimalField(decimal_places=2, default=0, max_digits=6, verbose_name='Amount'),
),
]

@ -1,19 +0,0 @@
# Generated by Django 4.0.1 on 2024-12-26 09:45
from django.db import migrations
import utils
class Migration(migrations.Migration):
dependencies = [
('finance', '0004_alter_bill_amount'),
]
operations = [
migrations.AlterField(
model_name='bill',
name='proof',
field=utils.RestrictedFileField(blank=True, upload_to='bill_images', verbose_name='Proof'),
),
]

@ -1,26 +0,0 @@
# Generated by Django 4.0.1 on 2025-01-18 19:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('members', '0032_member_upload_registration_form_key'),
('members', '0033_freizeit_approved_extra_youth_leader_count'),
('finance', '0005_alter_bill_proof'),
]
operations = [
migrations.AddField(
model_name='statement',
name='allowance_to',
field=models.ManyToManyField(help_text='The youth leaders to which an allowance should be paid. The count must match the number of permitted youth leaders.', related_name='receives_allowance_for_statements', to='members.Member', verbose_name='Pay allowance to'),
),
migrations.AddField(
model_name='statement',
name='subsidy_to',
field=models.ForeignKey(help_text='The person that should receive the subsidy for night and travel costs. Typically the person who paid for them.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='receives_subsidy_for_statements', to='members.member', verbose_name='Pay subsidy to'),
),
]

@ -1,19 +0,0 @@
# Generated by Django 4.0.1 on 2025-01-18 22:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('members', '0033_freizeit_approved_extra_youth_leader_count'),
('finance', '0006_statement_add_allowance_to_subsidy_to'),
]
operations = [
migrations.AlterField(
model_name='statement',
name='allowance_to',
field=models.ManyToManyField(blank=True, help_text='The youth leaders to which an allowance should be paid. The count must match the number of permitted youth leaders.', related_name='receives_allowance_for_statements', to='members.Member', verbose_name='Pay allowance to'),
),
]

@ -1,25 +0,0 @@
# Generated by Django 4.0.1 on 2025-01-23 22:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('members', '0033_freizeit_approved_extra_youth_leader_count'),
('finance', '0007_alter_statement_allowance_to'),
]
operations = [
migrations.AlterField(
model_name='statement',
name='allowance_to',
field=models.ManyToManyField(blank=True, help_text='The youth leaders to which an allowance should be paid.', related_name='receives_allowance_for_statements', to='members.Member', verbose_name='Pay allowance to'),
),
migrations.AlterField(
model_name='statement',
name='subsidy_to',
field=models.ForeignKey(blank=True, help_text='The person that should receive the subsidy for night and travel costs. Typically the person who paid for them.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='receives_subsidy_for_statements', to='members.member', verbose_name='Pay subsidy to'),
),
]

@ -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',),
),
]

@ -5,23 +5,13 @@ from django.utils import timezone
from .rules import is_creator, not_submitted, leads_excursion from .rules import is_creator, not_submitted, leads_excursion
from members.rules import is_leader, statement_not_submitted from members.rules import is_leader, statement_not_submitted
from django.core.exceptions import ValidationError
from django.db import models from django.db import models
from django.db.models import Sum
from django.utils.translation import gettext_lazy as _ 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 members.models import Member, Freizeit, OEFFENTLICHE_ANREISE, MUSKELKRAFT_ANREISE
from django.conf import settings from django.conf import settings
import rules import rules
from contrib.models import CommonModel from contrib.models import CommonModel
from contrib.rules import has_global_perm 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
# Create your models here. # Create your models here.
@ -38,7 +28,7 @@ class Ledger(models.Model):
class TransactionIssue: class TransactionIssue:
def __init__(self, member, current, target): def __init__(self, member, current, target):
self.member, self.current, self.target = member, current, target self.member, self.current, self. target = member, current, target
@property @property
def difference(self): def difference(self):
@ -47,22 +37,15 @@ class TransactionIssue:
class StatementManager(models.Manager): class StatementManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super().get_queryset().filter(status=Statement.UNSUBMITTED) return super().get_queryset().filter(submitted=False, confirmed=False)
class Statement(CommonModel): class Statement(CommonModel):
MISSING_LEDGER, NON_MATCHING_TRANSACTIONS, INVALID_ALLOWANCE_TO, INVALID_TOTAL, VALID = 0, 1, 2, 3, 4 MISSING_LEDGER, NON_MATCHING_TRANSACTIONS, VALID = 0, 1, 2
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'), short_description = models.CharField(verbose_name=_('Short description'),
max_length=30, max_length=30,
blank=False) blank=True)
explanation = models.TextField(verbose_name=_('Explanation'), blank=True) explanation = models.TextField(verbose_name=_('Explanation'), blank=True)
excursion = models.OneToOneField(Freizeit, verbose_name=_('Associated excursion'), excursion = models.OneToOneField(Freizeit, verbose_name=_('Associated excursion'),
@ -70,30 +53,11 @@ class Statement(CommonModel):
null=True, null=True,
on_delete=models.SET_NULL) on_delete=models.SET_NULL)
allowance_to = models.ManyToManyField(Member, verbose_name=_('Pay allowance to'),
related_name='receives_allowance_for_statements',
blank=True,
help_text=_('The youth leaders to which an allowance should be paid.'))
subsidy_to = models.ForeignKey(Member, verbose_name=_('Pay subsidy to'),
null=True,
blank=True,
on_delete=models.SET_NULL,
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) night_cost = models.DecimalField(verbose_name=_('Price per night'), default=0, decimal_places=2, max_digits=5)
status = models.IntegerField(verbose_name=_('Status'), submitted = models.BooleanField(verbose_name=_('Submitted'), default=False)
choices=STATUS_CHOICES,
default=UNSUBMITTED)
submitted_date = models.DateTimeField(verbose_name=_('Submitted on'), default=None, null=True) 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) confirmed_date = models.DateTimeField(verbose_name=_('Paid on'), default=None, null=True)
created_by = models.ForeignKey(Member, verbose_name=_('Created by'), created_by = models.ForeignKey(Member, verbose_name=_('Created by'),
@ -119,74 +83,32 @@ class Statement(CommonModel):
('may_edit_submitted_statements', 'Is allowed to edit submitted statements') ('may_edit_submitted_statements', 'Is allowed to edit submitted statements')
] ]
rules_permissions = { rules_permissions = {
# All users may add draft statements. # this is suboptimal, but Statement is only ever used as an inline on Freizeit
'add_obj': rules.is_staff, # so we check for excursion permissions
# All users may view their own statements and statements of excursions they are responsible for. 'add_obj': is_leader,
'view_obj': is_creator | leads_excursion | has_global_perm('finance.view_global_statement'), 'view_obj': is_leader | has_global_perm('members.view_global_freizeit'),
# All users may change relevant (see above) draft statements. 'change_obj': is_leader & statement_not_submitted,
'change_obj': (not_submitted & (is_creator | leads_excursion)) | has_global_perm('finance.change_global_statement'), 'delete_obj': is_leader & statement_not_submitted,
# All users may delete relevant (see above) draft statements.
'delete_obj': not_submitted & (is_creator | leads_excursion | has_global_perm('finance.delete_global_statement')),
} }
@property def __str__(self):
def title(self):
if self.excursion is not None: if self.excursion is not None:
return _('Excursion %(excursion)s') % {'excursion': str(self.excursion)} return _('Statement: %(excursion)s') % {'excursion': str(self.excursion)}
else: else:
return self.short_description 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): def submit(self, submitter=None):
self.status = self.SUBMITTED self.submitted = True
self.submitted_date = timezone.now() self.submitted_date = timezone.now()
self.submitted_by = submitter self.submitted_by = submitter
self.save() self.save()
@property @property
def transaction_issues(self): def transaction_issues(self):
""" needed_paiments = [(b.paid_by, b.amount) for b in self.bill_set.all() if b.costs_covered]
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: if self.excursion is not None:
needed_paiments.extend([(yl, self.allowance_per_yl) for yl in self.allowance_to.all()]) needed_paiments.extend([(yl, self.real_per_yl) for yl in self.excursion.jugendleiter.all()])
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) 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]))) target = dict(map(lambda p: (p[0], sum([x[1] for x in p[1]])), groupby(needed_paiments, lambda p: p[0])))
@ -218,65 +140,22 @@ class Statement(CommonModel):
@property @property
def transactions_match_expenses(self): def transactions_match_expenses(self):
"""Returns true iff there are no transaction issues."""
return len(self.transaction_issues) == 0 return len(self.transaction_issues) == 0
@property def is_valid(self):
def allowance_to_valid(self): return self.ledgers_configured and self.transactions_match_expenses
"""Checks if the configured `allowance_to` field matches the regulations.""" is_valid.boolean = True
if self.allowances_paid > self.real_staff_count: is_valid.short_description = _('Ready to confirm')
# it is allowed that less allowances are utilized than youth leaders are enlisted
return False
if self.excursion is not None:
yls = self.excursion.jugendleiter.all()
for yl in self.allowance_to.all():
if yl not in yls:
return False
return True
@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`.
"""
total_transactions = 0
for transaction in self.transaction_set.all():
total_transactions += transaction.amount
return self.total == total_transactions
@property @property
def validity(self): 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: if not self.transactions_match_expenses:
return Statement.NON_MATCHING_TRANSACTIONS return Statement.NON_MATCHING_TRANSACTIONS
if not self.ledgers_configured: if not self.ledgers_configured:
return Statement.MISSING_LEDGER return Statement.MISSING_LEDGER
if not self.allowance_to_valid:
return Statement.INVALID_ALLOWANCE_TO
if not self.total_valid:
return Statement.INVALID_TOTAL
else: else:
return Statement.VALID return Statement.VALID
def is_valid(self):
return self.validity == Statement.VALID
is_valid.boolean = True
is_valid.short_description = _('Ready to confirm')
def confirm(self, confirmer=None): def confirm(self, confirmer=None):
if not self.submitted: if not self.submitted:
return False return False
@ -284,7 +163,7 @@ class Statement(CommonModel):
if not self.validity == Statement.VALID: if not self.validity == Statement.VALID:
return False return False
self.status = self.CONFIRMED self.confirmed = True
self.confirmed_date = timezone.now() self.confirmed_date = timezone.now()
self.confirmed_by = confirmer self.confirmed_by = confirmer
for trans in self.transaction_set.all(): for trans in self.transaction_set.all():
@ -300,36 +179,16 @@ class Statement(CommonModel):
for bill in self.bill_set.all(): for bill in self.bill_set.all():
if not bill.costs_covered: if not bill.costs_covered:
continue continue
if not bill.paid_by:
return False
ref = "{}: {}".format(str(self), bill.short_description) ref = "{}: {}".format(str(self), bill.short_description)
Transaction(statement=self, member=bill.paid_by, amount=bill.amount, confirmed=False, reference=ref).save() Transaction(statement=self, member=bill.paid_by, amount=bill.amount, confirmed=False, reference=ref).save()
# excursion specific # excursion specific
if self.excursion is None: if self.excursion is None:
return True return
# allowance
for yl in self.allowance_to.all():
ref = _("Allowance for %(excu)s") % {'excu': self.excursion.name}
Transaction(statement=self, member=yl, amount=self.allowance_per_yl, confirmed=False, reference=ref).save()
# subsidies (i.e. night and transportation costs)
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: for yl in self.excursion.jugendleiter.all():
ref = _("LJP-Contribution %(excu)s") % {'excu': self.excursion.name} ref = _("Compensation for %(excu)s") % {'excu': self.excursion.name}
Transaction(statement=self, member=self.ljp_to, amount=self.paid_ljp_contributions, Transaction(statement=self, member=yl, amount=self.real_per_yl, confirmed=False, reference=ref).save()
confirmed=False, reference=ref).save()
return True
def reduce_transactions(self): def reduce_transactions(self):
# to minimize the number of needed bank transactions, we bundle transactions from same ledger to # to minimize the number of needed bank transactions, we bundle transactions from same ledger to
@ -348,7 +207,7 @@ class Statement(CommonModel):
continue continue
new_amount = sum((trans.amount for trans in grp)) 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, Transaction(statement=self, member=member, amount=new_amount, confirmed=False, reference=new_ref,
ledger=ledger).save() ledger=ledger).save()
for trans in grp: for trans in grp:
@ -356,27 +215,12 @@ class Statement(CommonModel):
@property @property
def total_bills(self): def total_bills(self):
return sum([bill.amount for bill in self.bills_covered]) return sum([bill.amount for bill in self.bill_set.all() if bill.costs_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]
@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 @property
def total_bills_theoretic(self): def total_bills_theoretic(self):
return sum([bill.amount for bill in self.bill_set.all()]) 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 @property
def euro_per_km(self): def euro_per_km(self):
if self.excursion is None: if self.excursion is None:
@ -402,13 +246,9 @@ class Statement(CommonModel):
return cvt_to_decimal(self.excursion.duration * settings.ALLOWANCE_PER_DAY) return cvt_to_decimal(self.excursion.duration * settings.ALLOWANCE_PER_DAY)
@property
def allowances_paid(self):
return self.allowance_to.count()
@property @property
def total_allowance(self): def total_allowance(self):
return self.allowance_per_yl * self.allowances_paid return self.allowance_per_yl * self.real_staff_count
@property @property
def total_transportation(self): def total_transportation(self):
@ -440,61 +280,11 @@ class Statement(CommonModel):
if self.excursion is None: if self.excursion is None:
return 0 return 0
return cvt_to_decimal(self.total_staff / self.excursion.staff_count) return 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):
"""
The total amount of subsidies excluding the allowance, i.e. the transportation
and night costs per youth leader multiplied with the real number of youth leaders.
"""
if self.subsidy_to:
return (self.transportation_per_yl + self.nights_per_yl) * self.real_staff_count
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):
"""
the sum of subsidies and allowances if all eligible youth leaders would collect them.
"""
return self.total_per_yl * self.real_staff_count
@property @property
def total_staff(self): def total_staff(self):
""" return self.total_per_yl * self.real_staff_count
the sum of subsidies and allowances that youth leaders are actually collecting
"""
return self.total_allowance + self.total_subsidies
@property
def total_staff_paid(self):
return self.total_staff - self.total_org_fee
@property @property
def real_staff_count(self): def real_staff_count(self):
@ -509,135 +299,32 @@ class Statement(CommonModel):
are refinanced though.""" are refinanced though."""
if self.excursion is None: if self.excursion is None:
return 0 return 0
else:
return self.excursion.approved_staff_count #raw_staff_count = self.excursion.jugendleiter.count()
participant_count = self.excursion.participant_count
@property if participant_count < 4:
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 return 0
elif 4 <= participant_count <= 7:
return 2
else:
return 2 + math.ceil((participant_count - 7) / 7)
@property @property
def total(self): def total(self):
return self.total_bills + self.total_staff_paid + self.paid_ljp_contributions return self.total_bills + self.total_staff
@property @property
def total_theoretic(self): def total_theoretic(self):
""" return self.total_bills_theoretic + self.total_staff
The theoretic total used in SJR and LJP applications. This is the sum of all
bills (ignoring whether they are paid by the association or not) plus the
total allowance. This does not include the subsidies for night and travel costs,
since they are expected to be included in the bills.
"""
return self.total_bills_theoretic + self.total_allowance
def total_pretty(self): def total_pretty(self):
return "{}".format(self.total) return "{}".format(self.total)
total_pretty.short_description = _('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:
excursion_context = {
'nights': self.excursion.night_count,
'price_per_night': self.real_night_cost,
'duration': self.excursion.duration,
'staff_count': self.real_staff_count,
'kilometers_traveled': self.excursion.kilometers_traveled,
'means_of_transport': self.excursion.get_tour_approach(),
'euro_per_km': self.euro_per_km,
'allowance_per_day': settings.ALLOWANCE_PER_DAY,
'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:
return context
def grouped_bills(self):
return self.bill_set.values('short_description')\
.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): class StatementUnSubmittedManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super().get_queryset().filter(status=Statement.UNSUBMITTED) return super().get_queryset().filter(submitted=False, confirmed=False)
class StatementUnSubmitted(Statement): class StatementUnSubmitted(Statement):
@ -657,7 +344,7 @@ class StatementUnSubmitted(Statement):
class StatementSubmittedManager(models.Manager): class StatementSubmittedManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super().get_queryset().filter(status=Statement.SUBMITTED) return super().get_queryset().filter(submitted=True, confirmed=False)
class StatementSubmitted(Statement): class StatementSubmitted(Statement):
@ -674,7 +361,7 @@ class StatementSubmitted(Statement):
class StatementConfirmedManager(models.Manager): class StatementConfirmedManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super().get_queryset().filter(status=Statement.CONFIRMED) return super().get_queryset().filter(confirmed=True)
class StatementConfirmed(Statement): class StatementConfirmed(Statement):
@ -691,23 +378,16 @@ class StatementConfirmed(Statement):
class Bill(CommonModel): class Bill(CommonModel):
statement = models.ForeignKey(Statement, verbose_name=_('Statement'), on_delete=models.CASCADE) 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) explanation = models.TextField(verbose_name=_('Explanation'), blank=True)
amount = models.DecimalField(verbose_name=_('Amount'), max_digits=6, decimal_places=2, default=0) amount = models.DecimalField(max_digits=6, decimal_places=2, default=0)
paid_by = models.ForeignKey(Member, verbose_name=_('Paid by'), null=True, paid_by = models.ForeignKey(Member, verbose_name=_('Paid by'), null=True,
on_delete=models.SET_NULL) on_delete=models.SET_NULL)
costs_covered = models.BooleanField(verbose_name=_('Covered'), default=False) costs_covered = models.BooleanField(verbose_name=_('Covered'), default=False)
refunded = models.BooleanField(verbose_name=_('Refunded'), default=False) refunded = models.BooleanField(verbose_name=_('Refunded'), default=False)
proof = RestrictedFileField(verbose_name=_('Proof'), proof = models.ImageField(_('Proof'), upload_to='bill_images', blank=True)
upload_to='bill_images',
blank=True,
max_upload_size=5,
content_types=['application/pdf',
'image/jpeg',
'image/png',
'image/gif'])
def __str__(self): def __str__(self):
return "{} ({}€)".format(self.short_description, self.amount) return "{} ({}€)".format(self.short_description, self.amount)
@ -772,45 +452,6 @@ class Transaction(models.Model):
def __str__(self): def __str__(self):
return "T#{}".format(self.pk) return "T#{}".format(self.pk)
@staticmethod
def escape_reference(reference):
umlaut_map = {
'ä': 'ae', 'ö': 'oe', 'ü': 'ue',
'Ä': 'Ae', 'Ö': 'Oe', 'Ü': 'Ue',
'ß': 'ss'
}
pattern = re.compile('|'.join(umlaut_map.keys()))
int_reference = pattern.sub(lambda x: umlaut_map[x.group()], reference)
allowed_chars = r"[^a-z0-9 /?: .,'+-]"
clean_reference = re.sub(allowed_chars, '', int_reference, flags=re.IGNORECASE)
return clean_reference
def code(self):
if self.amount == 0:
return ""
iban = IBAN(self.member.iban, allow_invalid=True)
if not iban.is_valid:
return ""
bic = iban.bic
reference = self.escape_reference(self.reference)
# also escaping receiver as umlaute are also not allowed here
receiver = self.escape_reference(f"{self.member.prename} {self.member.lastname}")
return f"""BCD
001
1
SCT
{bic}
{receiver}
{iban}
EUR{self.amount}
{reference}"""
class Meta: class Meta:
verbose_name = _('Transaction') verbose_name = _('Transaction')
verbose_name_plural = _('Transactions') verbose_name_plural = _('Transactions')
@ -822,3 +463,7 @@ class Receipt(models.Model):
on_delete=models.CASCADE) on_delete=models.CASCADE)
amount = models.DecimalField(max_digits=6, decimal_places=2) amount = models.DecimalField(max_digits=6, decimal_places=2)
comments = models.TextField() comments = models.TextField()
def cvt_to_decimal(f):
return Decimal(f).quantize(Decimal('.01'), rounding=ROUND_HALF_DOWN)

@ -7,8 +7,6 @@
<script src="{% static 'admin/js/cancel.js' %}" async></script> <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/vendor/jquery/jquery.js" %}"></script>
<script type="text/javascript" src="{% static "admin/js/jquery.init.js" %}"></script> <script type="text/javascript" src="{% static "admin/js/jquery.init.js" %}"></script>
<script type="text/javascript" src="{% static "js/qrcode.js" %}"></script>
{% endblock %} {% endblock %}
{% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} admin-view {% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} admin-view
@ -38,7 +36,6 @@
<td>{% trans "Amount" %}</td> <td>{% trans "Amount" %}</td>
<td>{% trans "Reference" %}</td> <td>{% trans "Reference" %}</td>
<td>{% trans "Ledger" %}</td> <td>{% trans "Ledger" %}</td>
<td>{% trans "QR Code" %}</td>
</th> </th>
{% for transaction in statement.transaction_set.all %} {% for transaction in statement.transaction_set.all %}
<tr> <tr>
@ -57,60 +54,17 @@
<td> <td>
{{ transaction.ledger }} {{ transaction.ledger }}
</td> </td>
<td>
<a href="#" data-text="{{ transaction.code }}">{% trans "Show" %}</a>
</td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
</p> </p>
<div id="qr_code" style="display: none;"></div>
<script type="text/javascript">
const links = document.querySelectorAll('td a');
const imageContainer = document.getElementById('qr_code');
// Add click event listeners to all links
links.forEach(link => {
link.addEventListener('click', function (event) {
event.preventDefault(); // Prevent default link behavior
const imageText = this.getAttribute('data-text'); // Get the image path from the data attribute
imageContainer.innerHTML = '';
// Update the image element
if(imageText == "") {
imageContainer.innerHTML = '{% trans "No QR code can be displayed." %}';
} else {
var qrcode = new QRCode(imageContainer, {
text: imageText,
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.M
});
}
imageContainer.style.display = 'block'; // Show the image if hidden
links.forEach(link => {link.text = '{% trans "Show" %}'});
link.text = '{% trans "Showing" %}';
});
});
</script>
<form action="" method="post"> <form action="" method="post">
{% csrf_token %} {% csrf_token %}
<p> <p>
<input type="checkbox" required> <input type="checkbox" required>
{% blocktrans %}I did execute the listed transactions.{% endblocktrans %} {% blocktrans %}I did execute the listed transactions.{% endblocktrans %}
</p> </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" value="{% translate 'Confirm' %}">
<input class="default confirm" type="submit" name="transaction_execution_confirm_and_send" value="{% translate 'Confirm and send receipt to office' %}">
</form> </form>
{% endblock %} {% endblock %}

@ -1,6 +1,5 @@
{% extends "admin/base_site.html" %} {% extends "admin/base_site.html" %}
{% load i18n admin_urls static %} {% load i18n admin_urls static %}
{% load overview_extras %}
{% block extrahead %} {% block extrahead %}
{{ block.super }} {{ block.super }}
@ -41,7 +40,7 @@
{{ bill.amount }}€. {{ bill.amount }}€.
</td> </td>
<td> <td>
{{ bill.costs_covered|render_bool }} {{ bill.costs_covered }}
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
@ -71,124 +70,12 @@
</ul> </ul>
</p> </p>
<p> <p>
{% blocktrans %}In total this is {{ total_per_yl }}€ times {{ staff_count }}, giving {{ theoretical_total_staff }}€.{% endblocktrans %} {% blocktrans %}In total this is {{ total_per_yl }}€ times {{ staff_count }}, giving {{ total_staff }}€.{% endblocktrans %}
</p> </p>
<h2>{% trans "Payment of subsidies and allowances" %}</h2>
{% if allowances_paid > 0 %}
<p>
{% blocktrans %}The allowance of {{ allowance_per_yl }}€ per person should be paid to:{% endblocktrans %}
<table>
<th>
<td>{% trans "IBAN valid" %}</td>
</th>
{% for member in statement.allowance_to.all %}
<tr>
<td>{{ member.name }}</td>
<td>{{ member.iban_valid|render_bool }}</td>
</tr>
{% endfor %}
</table>
</p>
{% if allowances_paid < real_staff_count %}
<p>{% blocktrans %}Only {{ allowances_paid }} of the {{ real_staff_count }} youth leaders have requested the outpayment of their allowance.{% endblocktrans %}</p>
{% endif %}
{% else %}
<p>{% blocktrans %}No receivers of the allowance were provided. Allowance will not be used.{% endblocktrans %}</p>
{% endif %}
{% if statement.subsidy_to %}
<p>
{% blocktrans %}The subsidies for night and transportation costs of {{ total_subsidies }}€ should be paid to:{% endblocktrans %}
<table>
<th>
<td>{% trans "IBAN valid" %}</td>
</th>
<tr>
<td>{{ statement.subsidy_to.name }}</td>
<td>{{ statement.subsidy_to.iban_valid|render_bool }}</td>
</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 %} {% endif %}
<h2>{% trans "Total" %}</h2>
<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>
<p> <p>
{% blocktrans %}This results in a total amount of {{ total }}€{% endblocktrans %} {% blocktrans %}This results in a total amount of {{ total }}€{% endblocktrans %}

@ -1,6 +1,5 @@
{% extends "admin/base_site.html" %} {% extends "admin/base_site.html" %}
{% load i18n admin_urls static %} {% load i18n admin_urls static %}
{% load overview_extras %}
{% block extrahead %} {% block extrahead %}
{{ block.super }} {{ block.super }}
@ -25,35 +24,6 @@
{% block content %} {% block content %}
<h2>{% translate "Submit to the finance department" %}</h2> <h2>{% translate "Submit to the finance department" %}</h2>
<p>{% translate "Please check if all expenses are documented correctly and if all payers have a valid account code." %}</p>
<table>
<th>
<td>{% trans "Explanation" %}</td>
<td>{% trans "Amount" %}</td>
<td>{% trans "Paid by" %}</td>
<td>{% trans "IBAN valid" %}</td>
</th>
{% for bill in statement.bill_set.all %}
<tr>
<td>
{{bill.short_description}}
</td>
<td>
{{bill.explanation}}
</td>
<td>
{{ bill.amount }}€
</td>
<td>
{{ bill.paid_by.name }}
</td>
<td>
{{ bill.paid_by.iban_valid|render_bool }}
</td>
</tr>
{% endfor %}
</table>
<p> <p>
{% trans "Do you want to submit the statement for further processing by the finance department? If you proceed, no further changes to the statement are possible." %} {% trans "Do you want to submit the statement for further processing by the finance department? If you proceed, no further changes to the statement are possible." %}
</p> </p>

@ -1,41 +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 }} admin-view
{% 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; <a href="{% url opts|admin_urlname:'change' statement.pk|admin_urlquote %}">{{ statement|truncatewords:"18" }}</a>
&rsaquo; {% translate 'Unconfirm' %}
</div>
{% endblock %}
{% block content %}
<h2>{% translate "Unconfirm statement" %}</h2>
<p>
{% blocktrans %}You are entering risk zone! Do you really want to manually set this statement back to unconfirmed?{% endblocktrans %}
</p>
<form action="" method="post">
{% csrf_token %}
<p>
<input type="checkbox" required>
{% blocktrans %}I am aware that this is not a standard procedure and this might cause data integrity issues.{% endblocktrans %}
</p>
<input class="default danger" type="submit" name="unconfirm" value="{% translate 'Unconfirm' %}">
<a class="button cancel-link" href="{% add_preserved_filters change_url %}">{% trans 'Cancel' %}</a>
</form>
{% endblock %}

@ -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 %}

@ -0,0 +1,185 @@
from django.test import TestCase
from django.utils import timezone
from django.conf import settings
from .models import Statement, StatementUnSubmitted, StatementSubmitted, Bill, Ledger, Transaction
from members.models import Member, Group, Freizeit, GEMEINSCHAFTS_TOUR, MUSKELKRAFT_ANREISE, NewMemberOnList,\
FAHRGEMEINSCHAFT_ANREISE
# Create your tests here.
class StatementTestCase(TestCase):
night_cost = 27
kilometers_traveled = 512
participant_count = 10
staff_count = 5
def setUp(self):
self.jl = Group.objects.create(name="Jugendleiter")
self.fritz = Member.objects.create(prename="Fritz", lastname="Wulter", birth_date=timezone.now().date(),
email=settings.TEST_MAIL)
self.fritz.group.add(self.jl)
self.fritz.save()
self.personal_account = Ledger.objects.create(name='personal account')
self.st = Statement.objects.create(short_description='A statement', explanation='Important!', night_cost=0)
Bill.objects.create(statement=self.st, short_description='food', explanation='i was hungry',
amount=67.3, costs_covered=False, paid_by=self.fritz)
Transaction.objects.create(reference='gift', amount=12.3,
ledger=self.personal_account, member=self.fritz,
statement=self.st)
self.st2 = Statement.objects.create(short_description='Actual expenses', night_cost=0)
Bill.objects.create(statement=self.st2, short_description='food', explanation='i was hungry',
amount=67.3, costs_covered=True, paid_by=self.fritz)
ex = Freizeit.objects.create(name='Wild trip', kilometers_traveled=self.kilometers_traveled,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=1)
self.st3 = Statement.objects.create(night_cost=self.night_cost, excursion=ex)
for i in range(self.participant_count):
m = Member.objects.create(prename='Fritz {}'.format(i), lastname='Walter', birth_date=timezone.now().date(),
email=settings.TEST_MAIL)
mol = NewMemberOnList.objects.create(member=m, memberlist=ex)
ex.membersonlist.add(mol)
for i in range(self.staff_count):
m = Member.objects.create(prename='Fritz {}'.format(i), lastname='Walter', birth_date=timezone.now().date(),
email=settings.TEST_MAIL)
Bill.objects.create(statement=self.st3, short_description='food', explanation='i was hungry',
amount=42.69, costs_covered=True, paid_by=m)
m.group.add(self.jl)
ex.jugendleiter.add(m)
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)
for i in range(2):
m = Member.objects.create(prename='Peter {}'.format(i), lastname='Walter', birth_date=timezone.now().date(),
email=settings.TEST_MAIL)
mol = NewMemberOnList.objects.create(member=m, memberlist=ex)
ex.membersonlist.add(mol)
def test_staff_count(self):
self.assertEqual(self.st4.admissible_staff_count, 0,
'Admissible staff count is not 0, although not enough participants.')
for i in range(2):
m = Member.objects.create(prename='Peter {}'.format(i), lastname='Walter', birth_date=timezone.now().date(),
email=settings.TEST_MAIL)
mol = NewMemberOnList.objects.create(member=m, memberlist=self.st4.excursion)
self.st4.excursion.membersonlist.add(mol)
self.assertEqual(self.st4.admissible_staff_count, 2,
'Admissible staff count is not 2, although there are 4 participants.')
def test_reduce_transactions(self):
self.st3.generate_transactions()
self.assertEqual(self.st3.transaction_set.count(), self.staff_count * 2,
'Transaction count is not twice the staff count.')
self.st3.reduce_transactions()
self.assertEqual(self.st3.transaction_set.count(), self.staff_count * 2,
'Transaction count after reduction is not the same as before, although no ledgers are configured.')
for trans in self.st3.transaction_set.all():
trans.ledger = self.personal_account
trans.save()
self.st3.reduce_transactions()
self.assertEqual(self.st3.transaction_set.count(), self.staff_count,
'Transaction count after setting ledgers and reduction is not halved.')
self.st3.reduce_transactions()
self.assertEqual(self.st3.transaction_set.count(), self.staff_count,
'Transaction count did change after reducing a second time.')
def test_confirm_statement(self):
self.assertFalse(self.st3.confirm(confirmer=self.fritz), 'Statement was confirmed, although it is not submitted.')
self.st3.submit(submitter=self.fritz)
self.assertTrue(self.st3.submitted, 'Statement is not submitted, although it was.')
self.assertEqual(self.st3.submitted_by, self.fritz,
'Statement was not submitted by fritz.')
self.assertFalse(self.st3.confirm(), 'Statement was confirmed, but is not valid yet.')
self.st3.generate_transactions()
for trans in self.st3.transaction_set.all():
trans.ledger = self.personal_account
trans.save()
self.assertTrue(self.st3.confirm(confirmer=self.fritz),
'Statement was not confirmed, although it submitted and valid.')
self.assertEqual(self.st3.confirmed_by, self.fritz, 'Statement not confirmed by fritz.')
for trans in self.st3.transaction_set.all():
self.assertTrue(trans.confirmed, 'Transaction on confirmed statement is not confirmed.')
self.assertEqual(trans.confirmed_by, self.fritz, 'Transaction on confirmed statement is not confirmed by fritz.')
def test_excursion_statement(self):
self.assertEqual(self.st3.excursion.staff_count, self.staff_count,
'Calculated staff count is not constructed staff count.')
self.assertEqual(self.st3.excursion.participant_count, self.participant_count,
'Calculated participant count is not constructed participant count.')
self.assertLess(self.st3.admissible_staff_count, self.staff_count,
'All staff members are refinanced, although {} is too much for {} participants.'.format(self.staff_count, self.participant_count))
self.assertFalse(self.st3.transactions_match_expenses,
'Transactions match expenses, but currently no one is paid.')
self.assertGreater(self.st3.total_staff, 0,
'There are no costs for the staff, although there are enough participants.')
self.assertEqual(self.st3.total_nights, 0,
'There are costs for the night, although there was no night.')
self.assertEqual(self.st3.real_night_cost, settings.MAX_NIGHT_COST,
'Real night cost is not the max, although the given one is way too high.')
# changing means of transport changes euro_per_km
epkm = self.st3.euro_per_km
self.st3.excursion.tour_approach = FAHRGEMEINSCHAFT_ANREISE
self.assertNotEqual(epkm, self.st3.euro_per_km, 'Changing means of transport did not change euro per km.')
self.st3.generate_transactions()
self.assertTrue(self.st3.transactions_match_expenses,
"Transactions don't match expenses after generating them.")
self.assertGreater(self.st3.total, 0, 'Total is 0.')
def test_generate_transactions(self):
# self.st2 has an unpaid bill
self.assertFalse(self.st2.transactions_match_expenses,
'Transactions match expenses, but one bill is not paid.')
self.st2.generate_transactions()
# now transactions should match expenses
self.assertTrue(self.st2.transactions_match_expenses,
"Transactions don't match expenses after generating them.")
# self.st2 is still not valid
self.assertEqual(self.st2.validity, Statement.MISSING_LEDGER,
'Statement is valid, although transaction has no ledger setup.')
for trans in self.st2.transaction_set.all():
trans.ledger = self.personal_account
trans.save()
self.assertEqual(self.st2.validity, Statement.VALID,
'Statement is still invalid, after setting up ledger.')
# create a new transaction issue by manually changing amount
t1 = self.st2.transaction_set.all()[0]
t1.amount = 123
t1.save()
self.assertFalse(self.st2.transactions_match_expenses,
'Transactions match expenses, but one transaction was tweaked.')
def test_statement_without_excursion(self):
# should be all 0, since no excursion is associated
self.assertEqual(self.st.real_staff_count, 0)
self.assertEqual(self.st.admissible_staff_count, 0)
self.assertEqual(self.st.nights_per_yl, 0)
self.assertEqual(self.st.allowance_per_yl, 0)
self.assertEqual(self.st.real_per_yl, 0)
self.assertEqual(self.st.transportation_per_yl, 0)
self.assertEqual(self.st.euro_per_km, 0)
self.assertEqual(self.st.total_allowance, 0)
self.assertEqual(self.st.total_transportation, 0)
def test_detect_unallowed_gift(self):
# there is a bill
self.assertGreater(self.st.total_bills_theoretic, 0, 'Theoretic bill total is 0 (should be > 0).')
# but it is not covered
self.assertEqual(self.st.total_bills, 0, 'Real bill total is not 0.')
self.assertEqual(self.st.total, 0, 'Total is not 0.')
self.assertGreater(self.st.total_theoretic, 0, 'Total in theorey is 0.')
self.st.generate_transactions()
self.assertEqual(self.st.transaction_set.count(), 1, 'Generating transactions did produce new transactions.')
# but there is a transaction anyway
self.assertFalse(self.st.transactions_match_expenses,
'Transactions match expenses, although an unreasonable gift is paid.')
# so statement must be invalid
self.assertFalse(self.st.is_valid(),
'Transaction is valid, although an unreasonable gift is paid.')

@ -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,659 +0,0 @@
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,\
StatementUnSubmittedManager, StatementSubmittedManager, StatementConfirmedManager,\
StatementConfirmed, TransactionIssue, StatementManager
from members.models import Member, Group, Freizeit, LJPProposal, Intervention, 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):
night_cost = 27
kilometers_traveled = 512
participant_count = 10
staff_count = 5
allowance_to_count = 3
def setUp(self):
self.jl = Group.objects.create(name="Jugendleiter")
self.fritz = Member.objects.create(prename="Fritz", lastname="Wulter", birth_date=timezone.now().date(),
email=settings.TEST_MAIL, gender=MALE)
self.fritz.group.add(self.jl)
self.fritz.save()
self.personal_account = Ledger.objects.create(name='personal account')
self.st = Statement.objects.create(short_description='A statement', explanation='Important!', night_cost=0)
Bill.objects.create(statement=self.st, short_description='food', explanation='i was hungry',
amount=67.3, costs_covered=False, paid_by=self.fritz)
Transaction.objects.create(reference='gift', amount=12.3,
ledger=self.personal_account, member=self.fritz,
statement=self.st)
self.st2 = Statement.objects.create(short_description='Actual expenses', night_cost=0)
Bill.objects.create(statement=self.st2, short_description='food', explanation='i was hungry',
amount=67.3, costs_covered=True, paid_by=self.fritz)
ex = Freizeit.objects.create(name='Wild trip', kilometers_traveled=self.kilometers_traveled,
tour_type=GEMEINSCHAFTS_TOUR,
tour_approach=MUSKELKRAFT_ANREISE,
difficulty=1)
self.st3 = Statement.objects.create(night_cost=self.night_cost, excursion=ex, subsidy_to=self.fritz)
for i in range(self.participant_count):
m = Member.objects.create(prename='Fritz {}'.format(i), lastname='Walter', birth_date=timezone.now().date(),
email=settings.TEST_MAIL, gender=MALE)
mol = NewMemberOnList.objects.create(member=m, memberlist=ex)
ex.membersonlist.add(mol)
for i in range(self.staff_count):
m = Member.objects.create(prename='Fritz {}'.format(i), lastname='Walter', birth_date=timezone.now().date(),
email=settings.TEST_MAIL, gender=MALE)
Bill.objects.create(statement=self.st3, short_description='food', explanation='i was hungry',
amount=42.69, costs_covered=True, paid_by=m)
m.group.add(self.jl)
ex.jugendleiter.add(m)
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),
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.')
for i in range(2):
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=self.st4.excursion)
self.st4.excursion.membersonlist.add(mol)
self.assertEqual(self.st4.admissible_staff_count, 2,
'Admissible staff count is not 2, although there are 4 participants.')
def test_reduce_transactions(self):
self.st3.generate_transactions()
self.assertTrue(self.st3.allowance_to_valid, 'Configured `allowance_to` field is invalid.')
# every youth leader on `st3` paid one bill, the first three receive the allowance
# and one receives the subsidies
self.assertEqual(self.st3.transaction_set.count(), self.st3.real_staff_count + self.staff_count + 1,
'Transaction count is not twice the staff count.')
self.st3.reduce_transactions()
self.assertEqual(self.st3.transaction_set.count(), self.st3.real_staff_count + self.staff_count + 1,
'Transaction count after reduction is not the same as before, although no ledgers are configured.')
for trans in self.st3.transaction_set.all():
trans.ledger = self.personal_account
trans.save()
self.st3.reduce_transactions()
# the three yls that receive an allowance should only receive one transaction after reducing,
# the additional one is the one for the subsidies
self.assertEqual(self.st3.transaction_set.count(), self.staff_count + 1,
'Transaction count after setting ledgers and reduction is incorrect.')
self.st3.reduce_transactions()
self.assertEqual(self.st3.transaction_set.count(), self.staff_count + 1,
'Transaction count did change after reducing a second time.')
def test_confirm_statement(self):
self.assertFalse(self.st3.confirm(confirmer=self.fritz), 'Statement was confirmed, although it is not submitted.')
self.st3.submit(submitter=self.fritz)
self.assertTrue(self.st3.submitted, 'Statement is not submitted, although it was.')
self.assertEqual(self.st3.submitted_by, self.fritz,
'Statement was not submitted by fritz.')
self.assertFalse(self.st3.confirm(), 'Statement was confirmed, but is not valid yet.')
self.st3.generate_transactions()
for trans in self.st3.transaction_set.all():
trans.ledger = self.personal_account
trans.save()
self.assertEqual(self.st3.validity, Statement.VALID,
'Statement is not valid, although it was setup to be so.')
self.assertTrue(self.st3.confirm(confirmer=self.fritz),
'Statement was not confirmed, although it submitted and valid.')
self.assertEqual(self.st3.confirmed_by, self.fritz, 'Statement not confirmed by fritz.')
for trans in self.st3.transaction_set.all():
self.assertTrue(trans.confirmed, 'Transaction on confirmed statement is not confirmed.')
self.assertEqual(trans.confirmed_by, self.fritz, 'Transaction on confirmed statement is not confirmed by fritz.')
def test_excursion_statement(self):
self.assertEqual(self.st3.excursion.staff_count, self.staff_count,
'Calculated staff count is not constructed staff count.')
self.assertEqual(self.st3.excursion.participant_count, self.participant_count,
'Calculated participant count is not constructed participant count.')
self.assertLess(self.st3.admissible_staff_count, self.staff_count,
'All staff members are refinanced, although {} is too much for {} participants.'.format(self.staff_count, self.participant_count))
self.assertFalse(self.st3.transactions_match_expenses,
'Transactions match expenses, but currently no one is paid.')
self.assertGreater(self.st3.total_staff, 0,
'There are no costs for the staff, although there are enough participants.')
self.assertEqual(self.st3.total_nights, 0,
'There are costs for the night, although there was no night.')
self.assertEqual(self.st3.real_night_cost, settings.MAX_NIGHT_COST,
'Real night cost is not the max, although the given one is way too high.')
# changing means of transport changes euro_per_km
epkm = self.st3.euro_per_km
self.st3.excursion.tour_approach = FAHRGEMEINSCHAFT_ANREISE
self.assertNotEqual(epkm, self.st3.euro_per_km, 'Changing means of transport did not change euro per km.')
self.st3.generate_transactions()
self.assertTrue(self.st3.transactions_match_expenses,
"Transactions don't match expenses after generating them.")
self.assertGreater(self.st3.total, 0, 'Total is 0.')
def test_generate_transactions(self):
# self.st2 has an unpaid bill
self.assertFalse(self.st2.transactions_match_expenses,
'Transactions match expenses, but one bill is not paid.')
self.st2.generate_transactions()
# now transactions should match expenses
self.assertTrue(self.st2.transactions_match_expenses,
"Transactions don't match expenses after generating them.")
# self.st2 is still not valid
self.assertEqual(self.st2.validity, Statement.MISSING_LEDGER,
'Statement is valid, although transaction has no ledger setup.')
for trans in self.st2.transaction_set.all():
trans.ledger = self.personal_account
trans.save()
self.assertEqual(self.st2.validity, Statement.VALID,
'Statement is still invalid, after setting up ledger.')
# create a new transaction issue by manually changing amount
t1 = self.st2.transaction_set.all()[0]
t1.amount = 123
t1.save()
self.assertFalse(self.st2.transactions_match_expenses,
'Transactions match expenses, but one transaction was tweaked.')
def test_generate_transactions_not_covered(self):
bill = self.st2.bill_set.all()[0]
bill.paid_by = None
bill.save()
self.st2.generate_transactions()
self.assertTrue(self.st2.transactions_match_expenses)
bill.amount = 0
bill.paid_by = self.fritz
bill.save()
self.assertTrue(self.st2.transactions_match_expenses)
def test_statement_without_excursion(self):
# should be all 0, since no excursion is associated
self.assertEqual(self.st.real_staff_count, 0)
self.assertEqual(self.st.admissible_staff_count, 0)
self.assertEqual(self.st.nights_per_yl, 0)
self.assertEqual(self.st.allowance_per_yl, 0)
self.assertEqual(self.st.real_per_yl, 0)
self.assertEqual(self.st.transportation_per_yl, 0)
self.assertEqual(self.st.euro_per_km, 0)
self.assertEqual(self.st.total_allowance, 0)
self.assertEqual(self.st.total_transportation, 0)
def test_detect_unallowed_gift(self):
# there is a bill
self.assertGreater(self.st.total_bills_theoretic, 0, 'Theoretic bill total is 0 (should be > 0).')
# but it is not covered
self.assertEqual(self.st.total_bills, 0, 'Real bill total is not 0.')
self.assertEqual(self.st.total, 0, 'Total is not 0.')
self.assertGreater(self.st.total_theoretic, 0, 'Total in theorey is 0.')
self.st.generate_transactions()
self.assertEqual(self.st.transaction_set.count(), 1, 'Generating transactions did produce new transactions.')
# but there is a transaction anyway
self.assertFalse(self.st.transactions_match_expenses,
'Transactions match expenses, although an unreasonable gift is paid.')
# so statement must be invalid
self.assertFalse(self.st.is_valid(),
'Transaction is valid, although an unreasonable gift is paid.')
def test_allowance_to_valid(self):
self.assertEqual(self.st3.excursion.participant_count, self.participant_count)
# st3 should have 3 admissible yls and all of them should receive allowance
self.assertEqual(self.st3.admissible_staff_count, self.allowance_to_count)
self.assertEqual(self.st3.allowances_paid, self.allowance_to_count)
self.assertTrue(self.st3.allowance_to_valid)
m1 = self.st3.excursion.jugendleiter.all()[0]
m2 = self.st3.excursion.jugendleiter.all()[self.allowance_to_count]
# now remove one, so allowance_to should be reduced by one
self.st3.allowance_to.remove(m1)
self.assertEqual(self.st3.allowances_paid, self.allowance_to_count - 1)
# but still valid
self.assertTrue(self.st3.allowance_to_valid)
# and theoretical staff costs are now higher than real staff costs
self.assertLess(self.st3.total_staff, self.st3.theoretical_total_staff)
self.assertLess(self.st3.real_per_yl, self.st3.total_per_yl)
# adding a foreign yl adds the number of allowances_paid
self.st3.allowance_to.add(self.fritz)
self.assertEqual(self.st3.allowances_paid, self.allowance_to_count)
# but invalidates `allowance_to`
self.assertFalse(self.st3.allowance_to_valid)
# remove the foreign yl and add too many yls
self.st3.allowance_to.remove(self.fritz)
self.st3.allowance_to.add(m1, m2)
self.assertEqual(self.st3.allowances_paid, self.allowance_to_count + 1)
# should be invalid
self.assertFalse(self.st3.allowance_to_valid)
self.st3.generate_transactions()
for trans in self.st3.transaction_set.all():
trans.ledger = self.personal_account
trans.save()
self.assertEqual(self.st3.validity, Statement.INVALID_ALLOWANCE_TO)
def test_total_pretty(self):
self.assertEqual(self.st3.total_pretty(), "{}".format(self.st3.total))
def test_template_context(self):
# with excursion
self.assertTrue('euro_per_km' in self.st3.template_context())
# without excursion
self.assertFalse('euro_per_km' in self.st2.template_context())
def test_grouped_bills(self):
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):
self.personal_account = Ledger.objects.create(name='personal account')
def test_str(self):
self.assertTrue(str(self.personal_account), 'personal account')
class ManagerTestCase(TestCase):
def setUp(self):
self.st = Statement.objects.create(short_description='A statement',
explanation='Important!',
night_cost=0)
self.st_submitted = Statement.objects.create(short_description='A statement',
explanation='Important!',
night_cost=0,
status=Statement.SUBMITTED)
self.st_confirmed = Statement.objects.create(short_description='A statement',
explanation='Important!',
night_cost=0,
status=Statement.CONFIRMED)
def test_get_queryset(self):
# TODO: remove this manager, since it is not used
mgr = StatementManager()
mgr.model = Statement
self.assertQuerysetEqual(mgr.get_queryset(), Statement.objects.filter(pk=self.st.pk))
mgr_unsubmitted = StatementUnSubmittedManager()
mgr_unsubmitted.model = StatementUnSubmitted
self.assertQuerysetEqual(mgr_unsubmitted.get_queryset(), Statement.objects.filter(pk=self.st.pk))
mgr_submitted = StatementSubmittedManager()
mgr_submitted.model = StatementSubmitted
self.assertQuerysetEqual(mgr_submitted.get_queryset(), Statement.objects.filter(pk=self.st_submitted.pk))
mgr_confirmed = StatementConfirmedManager()
mgr_confirmed.model = StatementConfirmed
self.assertQuerysetEqual(mgr_confirmed.get_queryset(), Statement.objects.filter(pk=self.st_confirmed.pk))
class TransactionTestCase(TestCase):
def setUp(self):
self.st = Statement.objects.create(short_description='A statement',
explanation='Important!',
night_cost=0)
self.personal_account = Ledger.objects.create(name='personal account')
self.fritz = Member.objects.create(prename="Fritz", lastname="Wulter", birth_date=timezone.now().date(),
email=settings.TEST_MAIL, gender=MALE)
self.trans = Transaction.objects.create(reference='foobar',
amount=42,
member=self.fritz,
ledger=self.personal_account,
statement=self.st)
def test_str(self):
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)
def test_code(self):
self.trans.amount = 0
# amount is zero, so empty
self.assertEqual(self.trans.code(), '')
self.trans.amount = 42
# iban is invalid, so empty
self.assertEqual(self.trans.code(), '')
# a valid (random) iban
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):
self.st = Statement.objects.create(short_description='A statement',
explanation='Important!',
night_cost=0)
self.bill = Bill.objects.create(statement=self.st,
short_description='foobar')
def test_str(self):
self.assertTrue('' in str(self.bill))
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):
self.issue = TransactionIssue('foo', 42, 26)
def test_difference(self):
self.assertEqual(self.issue.difference, 26 - 42)

@ -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() app.autodiscover_tasks()
if __name__ == '__main__': if __name__ == '__main__':
app.start() # pragma: no cover app.start()

@ -0,0 +1,40 @@
from django.conf import settings
from mozilla_django_oidc.auth import OIDCAuthenticationBackend
class MyOIDCAB(OIDCAuthenticationBackend):
def filter_users_by_claims(self, claims):
username = claims.get(settings.OIDC_CLAIM_USERNAME)
if not username:
return self.UserModel.objects.none()
return self.UserModel.objects.filter(username=username)
def get_username(self, claims):
username = claims.get(settings.OIDC_CLAIM_USERNAME, '')
if not username:
return super(MyOIDCAB, self).get_username(claims)
return username
def get_userinfo(self, access_token, id_token, payload):
return super(MyOIDCAB, self).get_userinfo(access_token, id_token, payload)
def create_user(self, claims):
user = super(MyOIDCAB, self).create_user(claims)
return self.update_user(user, claims)
def update_user(self, user, claims):
user.first_name = claims.get(settings.OIDC_CLAIM_FIRST_NAME, '')
user.last_name = claims.get(settings.OIDC_CLAIM_LAST_NAME, '')
groups = claims.get('groups', [])
if settings.OIDC_GROUP_STAFF in groups:
user.is_staff = True
if settings.OIDC_GROUP_SUPERUSER in groups:
user.is_superuser = True
user.save()
return user

@ -12,54 +12,17 @@ https://docs.djangoproject.com/en/1.10/ref/settings/
from split_settings.tools import optional, include from split_settings.tools import optional, include
import os import os
import tomli
CONFIG_DIR_PATH = os.environ.get('KOMPASS_CONFIG_DIR_PATH', '')
SETTINGS_FILE = os.environ.get('KOMPASS_SETTINGS_FILE', 'settings.toml')
TEXTS_FILE = os.environ.get('KOMPASS_TEXTS_FILE', 'texts.toml')
with open(os.path.join(CONFIG_DIR_PATH, SETTINGS_FILE), 'rb') as f:
config = tomli.load(f)
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
def get_var(*keys, default='', dictionary=config):
"""
Get a variable from given config dictionary. The passed keys are used
for nested retrieval from the dictionary.
"""
cfg = dictionary
for key in keys:
if key not in cfg:
return default
else:
cfg = cfg[key]
return cfg
def get_text(*keys, default=''):
"""
Get a text from the `texts.toml`.
"""
return get_var(*keys, default=default, dictionary=texts)
base_settings = [ base_settings = [
'local.py', 'local.py',
'components/base.py', 'components/base.py',
'components/authentication.py',
'components/database.py', 'components/database.py',
'components/cache.py', 'components/cache.py',
'components/jet.py', 'components/jet.py',
'components/emails.py', 'components/emails.py',
'components/texts.py', 'components/texts.py',
'components/locale.py', 'components/locale.py',
'components/logging.py',
'components/oauth.py',
] ]
include(*base_settings) include(*base_settings)

@ -0,0 +1,51 @@
# Authentication
AUTHENTICATION_BACKENDS = (
'jdav_web.oidc.MyOIDCAB',
'django.contrib.auth.backends.ModelBackend',
'rules.permissions.ObjectPermissionBackend',
)
# Use Open ID Connect if possible
OIDC_ENABLED = '1' == os.environ.get('OIDC_ENABLED', '0')
# OIDC configuration
OIDC_RP_CLIENT_ID = os.environ.get('OIDC_RP_CLIENT_ID', '')
OIDC_RP_CLIENT_SECRET = os.environ.get('OIDC_RP_CLIENT_SECRET', '')
OIDC_OP_AUTHORIZATION_ENDPOINT = os.environ.get('OIDC_OP_AUTHORIZATION_ENDPOINT', '')
OIDC_OP_TOKEN_ENDPOINT = os.environ.get('OIDC_OP_TOKEN_ENDPOINT', '')
OIDC_OP_USER_ENDPOINT = os.environ.get('OIDC_OP_USER_ENDPOINT', '')
OIDC_OP_JWKS_ENDPOINT = os.environ.get('OIDC_OP_JWKS_ENDPOINT', '')
OIDC_RP_SIGN_ALGO = os.environ.get('OIDC_RP_SIGN_ALGO', 'RS256')
OIDC_RP_SCOPES = os.environ.get('ODIC_RP_SCOPES', 'openid email profile')
OIDC_CLAIM_USERNAME = os.environ.get('OIDC_CLAIM_USERNAME', 'username')
OIDC_CLAIM_FIRST_NAME = os.environ.get('OIDC_CLAIM_FIRST_NAME', 'given_name')
OIDC_CLAIM_LAST_NAME = os.environ.get('OIDC_CLAIM_LAST_NAME', 'last_name')
OIDC_GROUP_STAFF = os.environ.get('OIDC_GROUP_STAFF', 'staff')
OIDC_GROUP_SUPERUSER = os.environ.get('OIDC_GROUP_STAFF', 'superuser')
LOGIN_REDIRECT_URL = "/kompass"
LOGOUT_REDIRECT_URL = "/"
# default login URL, is not used if OIDC is not enabled
LOGIN_URL = "/oidc/authenticate/"
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

@ -1,25 +1,27 @@
deployed = get_var('django', 'deployed', default=False) deployed = '1' == os.environ.get('DJANGO_DEPLOY', '0')
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_var('django', 'secret_key', default='secret') SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY',
'6_ew6l1r9_4(8=p8quv(e8b+z+k+*wm7&zxx%mcnnec99a!lpw')
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = get_var('django', 'debug', default=True) DEBUG = os.environ.get('DJANGO_DEBUG', '1') == '1'
ALLOWED_HOSTS = get_var('django', 'allowed_hosts', default=["*"]) ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOST', '').split(",")
# hostname and base url # hostname and base url
HOST = get_var('django', 'host', default='localhost:8000') HOST = os.environ.get('DJANGO_ALLOWED_HOST', 'localhost:8000').split(",")[0]
PROTOCOL = get_var('django', 'protocol', default='https') PROTOCOL = os.environ.get('DJANGO_PROTOCOL', 'https')
BASE_URL = get_var('django', 'base_url', default=HOST) BASE_URL = os.environ.get('DJANGO_BASE_URL', HOST)
# Define media paths e.g. for image storage # Define media paths e.g. for image storage
MEDIA_URL = '/media/' MEDIA_URL = '/media/'
MEDIA_ROOT = get_var('django', 'media_root', MEDIA_ROOT = os.environ.get('DJANGO_MEDIA_ROOT',
default=os.path.join((os.path.join(BASE_DIR, os.pardir)), "media")) os.path.join((os.path.join(BASE_DIR, os.pardir)), "media"))
MEDIA_MEMBERLISTS = os.path.join((os.path.join(BASE_DIR, os.pardir)), "media")
# default primary key auto field type # default primary key auto field type
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
@ -36,7 +38,6 @@ USE_X_FORWARDED_HOST = True
# Application definition # Application definition
INSTALLED_APPS = [ INSTALLED_APPS = [
'logindata.apps.LoginDataConfig',
'contrib.apps.ContribConfig', 'contrib.apps.ContribConfig',
'startpage.apps.StartpageConfig', 'startpage.apps.StartpageConfig',
'material.apps.MaterialConfig', 'material.apps.MaterialConfig',
@ -52,9 +53,9 @@ INSTALLED_APPS = [
'django_celery_beat', 'django_celery_beat',
'rules', 'rules',
'jet', 'jet',
'oauth2_provider',
'django.contrib.admin', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.auth',
'mozilla_django_oidc',
'django.contrib.contenttypes', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.messages',
@ -73,17 +74,15 @@ MIDDLEWARE = [
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware',
'mozilla_django_oidc.middleware.SessionRefresh',
] ]
X_FRAME_OPTIONS = 'SAMEORIGIN'
ROOT_URLCONF = 'jdav_web.urls' ROOT_URLCONF = 'jdav_web.urls'
TEMPLATES = [ TEMPLATES = [
{ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(CONFIG_DIR_PATH, 'templates'), 'DIRS': [os.path.join(BASE_DIR, 'templates')],
os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True, 'APP_DIRS': True,
'OPTIONS': { 'OPTIONS': {
'context_processors': [ 'context_processors': [
@ -98,49 +97,26 @@ TEMPLATES = [
WSGI_APPLICATION = 'jdav_web.wsgi.application' WSGI_APPLICATION = 'jdav_web.wsgi.application'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'rules.permissions.ObjectPermissionBackend',
)
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Static files (CSS, JavaScript, Images) # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/ # https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/' STATIC_URL = '/static/'
STATICFILES_DIRS = [ STATICFILES_DIRS = [
os.path.join(CONFIG_DIR_PATH, "static"), os.path.join(BASE_DIR, "static")
os.path.join(BASE_DIR, "static"),
] ]
# static root where all the static files are collected to # static root where all the static files are collected to
# use python3 manage.py collectstatic to collect static files in the STATIC_ROOT # use python3 manage.py collectstatic to collect static files in the STATIC_ROOT
# this is needed for deployment # this is needed for deployment
STATIC_ROOT = get_var('django', 'static_root', default='/var/www/jdav_web/static') STATIC_ROOT = os.environ.get('DJANGO_STATIC_ROOT',
DEFAULT_STATIC_PATH = get_var('django', 'default_static_path', default='/app/jdav_web/static') '/var/www/jdav_web/static')
# Locale files (translations) # Locale files (translations)
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),) LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
# Celery and Redis setup # Celery and Redis setup
BROKER_URL = get_var('django', 'broker_url', default='redis://localhost:6379/0') BROKER_URL = os.environ.get('BROKER_URL', 'redis://localhost:6379/0')
# password hash algorithms used # password hash algorithms used
@ -191,11 +167,3 @@ MARKDOWNIFY = {
} }
} }
} }
# allowed characters in names appearing in urls on the website
STARTPAGE_URL_NAME_PATTERN = "[\w\-: *]"
# admins to contact on error messages
ADMINS = get_var('section', 'admins', default=[])
LOGIN_URL = '/de/kompass/login/'

@ -1,7 +1,7 @@
CACHES = { CACHES = {
'default': { 'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
'LOCATION': get_var('django', 'memcached_url', default='127.0.0.1:11211'), 'LOCATION': os.environ.get('MEMCACHED_URL', '127.0.0.1:11211'),
'OPTIONS': { 'OPTIONS': {
'no_delay': True, 'no_delay': True,
'ignore_exc': True, 'ignore_exc': True,
@ -12,6 +12,6 @@ CACHES = {
} }
CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 1 CACHE_MIDDLEWARE_SECONDS = 120
CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHE_MIDDLEWARE_KEY_PREFIX = ''

@ -4,11 +4,11 @@
DATABASES = { DATABASES = {
'default': { 'default': {
'ENGINE': 'django.db.backends.mysql', 'ENGINE': 'django.db.backends.mysql',
'NAME': get_var('database', 'database', default='jdav_db'), 'NAME': os.environ.get('DJANGO_DATABASE_NAME', 'jdav_db'),
'USER': get_var('database', 'user', default='user'), 'USER': os.environ.get('DJANGO_DATABASE_USER', 'jdav_user'),
'PASSWORD': get_var('database', 'password', default='secret'), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', 'jdav00jdav'),
'HOST': get_var('database', 'host', default='127.0.0.1'), 'HOST': os.environ.get('DJANGO_DATABASE_HOST', '127.0.0.1'),
'PORT': get_var('database', 'port', default=5432) 'PORT': os.environ.get('DJANGO_DATABASE_PORT', '5432')
} }
} }

@ -1,10 +1,10 @@
# Email setup # Email setup
EMAIL_HOST = get_var('mail', 'host', default='localhost') EMAIL_HOST = os.environ.get('EMAIL_HOST', 'localhost')
EMAIL_PORT = get_var('mail', 'port', default=587 if deployed else 25) EMAIL_PORT = 587 if deployed else 25
EMAIL_HOST_USER = get_var('mail', 'user', default='user') EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = get_var('mail', 'password', default='secret') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '')
EMAIL_USE_TLS = get_var('mail', 'tls', default=True if deployed else False) EMAIL_USE_TLS = True if deployed else False
EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'
# Celery Email Setup # Celery Email Setup
@ -13,5 +13,4 @@ CELERY_EMAIL_TASK_CONFIG = {
'rate_limit' : '10/m' # * CELERY_EMAIL_CHUNK_SIZE (default: 10) 'rate_limit' : '10/m' # * CELERY_EMAIL_CHUNK_SIZE (default: 10)
} }
DEFAULT_SENDING_MAIL = get_var('mail', 'default_sending_address', default='kompass@localhost') DEFAULT_SENDING_MAIL = os.environ.get('EMAIL_SENDING_ADDRESS', 'django@localhost')
DEFAULT_SENDING_NAME = get_var('mail', 'default_sending_name', default='Kompass')

@ -5,60 +5,48 @@ JET_DEFAULT_THEME = 'jdav-green'
JET_CHANGE_FORM_SIBLING_LINKS = False JET_CHANGE_FORM_SIBLING_LINKS = False
JET_SIDE_MENU_ITEMS = [ JET_SIDE_MENU_ITEMS = [
{'label': 'Teilnehmer*innenverwaltung', 'app_label': 'members', 'items': [ {'app_label': 'auth', 'permissions': ['auth'], 'items': [
{'name': 'member', 'label': 'Alle Teilnehmer*innen', 'permissions': ['members.view_member']}, {'name': 'group', 'permissions': ['auth.group'] },
{'name': 'freizeit', 'permissions': ['members.view_freizeit']}, {'name': 'user', 'permissions': ['auth.user']},
{'name': 'group', 'permissions': ['members.view_group']},
{'name': 'membernotelist', 'permissions': ['members.view_membernotelist']},
{'name': 'klettertreff', 'permissions': ['members.view_klettertreff']},
]}, ]},
{'label': 'Neue Mitglieder', 'app_label': 'members', 'permissions': ['members.view_memberunconfirmedproxy'], 'items': [ {'app_label': 'django_celery_beat', 'permissions': ['django_celery_beat'], 'items': [
{'name': 'memberunconfirmedproxy', 'permissions': ['members.view_memberunconfirmedproxy']}, {'name': 'crontabschedule'},
{'name': 'memberwaitinglist', 'permissions': ['members.view_memberwaitinglist']}, {'name': 'clockedschedule'},
{'name': 'intervalschedule'},
{'name': 'periodictask'},
{'name': 'solarschedule'},
]}, ]},
{'label': 'Ausbildung', 'app_label': 'members', 'permissions': ['members.view_membertraining'], 'items': [ {'app_label': 'ludwigsburgalpin', 'permissions': ['ludwigsburgalpin'], 'items': [
{'name': 'membertraining', 'permissions': ['members.view_membertraining']}, {'name': 'termin', 'permissions': ['ludwigsburgalpin.view_termin']},
{'name': 'trainingcategory', 'permissions': ['members.view_trainingcategory']},
{'name': 'activitycategory', 'permissions': ['members.view_activitycategory']},
]}, ]},
{'app_label': 'mailer', 'items': [ {'app_label': 'mailer', 'items': [
{'name': 'message', 'permissions': ['mailer.view_message']}, {'name': 'message', 'permissions': ['mailer.view_message']},
{'name': 'emailaddress', 'permissions': ['mailer.view_emailaddress']}, {'name': 'emailaddress', 'permissions': ['mailer.view_emailaddress']},
]}, ]},
{'app_label': 'finance', 'items': [ {'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': 'ledger', 'permissions': ['finance.view_ledger']},
{'name': 'bill', 'permissions': ['finance.view_bill', 'finance.view_bill_admin']}, {'name': 'bill', 'permissions': ['finance.view_bill', 'finance.view_bill_admin']},
{'name': 'transaction', 'permissions': ['finance.view_transaction']}, {'name': 'transaction', 'permissions': ['finance.view_transaction']},
]}, ]},
{'app_label': 'logindata', 'permissions': ['auth'], 'items': [ {'app_label': 'members', 'items': [
{'name': 'authgroup', 'permissions': ['auth.group'] }, {'name': 'member', 'permissions': ['members.view_member']},
{'name': 'logindatum', 'permissions': ['auth.user']}, {'name': 'group', 'permissions': ['members.view_group']},
{'name': 'registrationpassword', 'permissions': ['auth.user']}, {'name': 'membernotelist', 'permissions': ['members.view_membernotelist']},
]}, {'name': 'freizeit', 'permissions': ['members.view_freizeit']},
{'app_label': 'django_celery_beat', 'permissions': ['django_celery_beat'], 'items': [ {'name': 'klettertreff', 'permissions': ['members.view_klettertreff']},
{'name': 'crontabschedule'}, {'name': 'activitycategory', 'permissions': ['members.view_activitycategory']},
{'name': 'clockedschedule'}, {'name': 'trainingcategory', 'permissions': ['members.view_trainingcategory']},
{'name': 'intervalschedule'}, {'name': 'memberunconfirmedproxy', 'permissions': ['members.view_memberunconfirmedproxy']},
{'name': 'periodictask'}, {'name': 'memberwaitinglist', 'permissions': ['members.view_memberwaitinglist']},
{'name': 'solarschedule'},
]},
{'app_label': 'ludwigsburgalpin', 'permissions': ['ludwigsburgalpin'], 'items': [
{'name': 'termin', 'permissions': ['ludwigsburgalpin.view_termin']},
]}, ]},
{'app_label': 'material', 'permissions': ['material.view_materialpart'], 'items': [ {'app_label': 'material', 'permissions': ['material'], 'items': [
{'name': 'materialcategory', 'permissions': ['material.view_materialcategory']}, {'name': 'materialcategory', 'permissions': ['material.view_materialcategory']},
{'name': 'materialpart', 'permissions': ['material.view_materialpart']}, {'name': 'materialpart', 'permissions': ['material.view_materialpart']},
]}, ]},
{'app_label': 'startpage', 'permissions': ['startpage'], 'items': [
{'name': 'section', 'permissions': ['startpage.view_section']},
{'name': 'post', 'permissions': ['startpage.view_post']},
{'name': 'link', 'permissions': ['startpage.view_link']},
]},
{'label': 'Externe Links', 'items' : [ {'label': 'Externe Links', 'items' : [
{ 'label': 'Nextcloud', 'url': CLOUD_LINK, 'url_blank': True }, { 'label': 'Packlisten und Co.', 'url': CLOUD_LINK }
{ 'label': 'DAV 360', 'url': DAV_360_LINK, 'url_blank': True },
{ 'label': 'Julei-Wiki', 'url': WIKI_LINK, 'url_blank': True },
{ 'label': 'Kompass Dokumentation', 'url': DOCS_LINK, 'url_blank': True },
]}, ]},
] ]

@ -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",
},
}

@ -1,6 +1,6 @@
# mail texts # mail texts
CONFIRM_MAIL_TEXT = get_text('confirm_mail', default="""Hallo {name}, CONFIRM_MAIL_TEXT = """Hallo {name},
du hast bei der JDAV %(SEKTION)s eine E-Mail Adresse hinterlegt. Da bei uns alle Kommunikation 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}. Dazu klicke bitte einfach auf per Email funktioniert, brauchen wir eine Bestätigung {whattoconfirm}. Dazu klicke bitte einfach auf
@ -9,108 +9,37 @@ folgenden Link:
{link} {link}
Viele Grüße Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION }) Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION }
NEW_UNCONFIRMED_REGISTRATION = get_text('new_unconfirmed_registration', default="""Hallo {name}, NEW_UNCONFIRMED_REGISTRATION = """Hallo {name},
für deine Gruppe {group} liegt eine neue unbestätigte Reservierung vor. Die Person hat bereits ihre für deine Gruppe {group} liegt eine neue unbestätigte Reservierung vor. Die Person hat bereits ihre
E-Mailadressen bestätigt und ihr Anmeldeformular hochgeladen. Bitte prüfe die Registrierung eingehend und E-Mailadressen bestätigt. Bitte prüfe die Registrierung eingehend und bestätige falls möglich. Zu
bestätige falls möglich. Zu der Registrierung kommst du hier: der Registrierung kommst du hier:
{link} {link}
Viele Grüße Viele Grüße
Dein KOMPASS""") Dein KOMPASS"""
GROUP_INVITATION_LEFT_WAITINGLIST = get_text('group_invitation_left_waitinglist', INVITE_TEXT = """Hallo {name},
default="""Hallo {name},
der*die kürzlich zu einer Schnupperstunde für die Gruppe {group} eingeladene Wartende {waiter} wir haben gute Neuigkeiten für dich. Es ist ein Platz in der Jugendgruppe freigeworden. Wir brauchen
hat die Warteliste verlassen. jetzt noch ein paar Informationen von dir und deine Anmeldebestätigung. Das kannst du alles über folgenden
Link erledigen:
Viele Grüße {link}
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.""")
GROUP_TIME_UNAVAILABLE_TEXT = get_text('group_time_unavailable',
default="""Bitte erfrage die Gruppenzeiten bei der Gruppenleitung ({contact_email}).""")
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}).
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:
{{link}}
Du siehst dort auch die Daten, die du bei deiner Eintragung auf die Warteliste angegeben hast. Bitte Du siehst dort auch die Daten, die du bei deiner Eintragung auf die Warteliste angegeben hast. Bitte
überprüfe, ob die Daten noch stimmen und ändere sie bei Bedarf ab. überprüfe, ob die Daten noch stimmen und ändere sie bei Bedarf ab.
Falls du zu dem obigen Termin keine Zeit hast oder dich ganz von der Warteliste abmelden möchtest,
lehne bitte diese Einladung unter folgendem Link ab:
{{invitation_reject_link}}
Bei Fragen, wende dich gerne an %(RESPONSIBLE_MAIL)s. Bei Fragen, wende dich gerne an %(RESPONSIBLE_MAIL)s.
Viele Grüße Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION, 'RESPONSIBLE_MAIL': RESPONSIBLE_MAIL, Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION, 'RESPONSIBLE_MAIL': RESPONSIBLE_MAIL }
'REGISTRATION_FORM_DOWNLOAD_LINK': REGISTRATION_FORM_DOWNLOAD_LINK })
LEAVE_WAITINGLIST_TEXT = get_text('leave_waitinglist', default="""Hallo {name},
du hast dich erfolgreich von der Warteliste abgemeldet. Falls du zu einem späteren
Zeitpunkt wieder der Warteliste beitreten möchtest, kannst du das über unsere Webseite machen.
Falls du dich nicht selbst abgemeldet hast, wende dich bitte umgehend an %(RESPONSIBLE_MAIL)s.
Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION, 'RESPONSIBLE_MAIL': RESPONSIBLE_MAIL })
WAIT_CONFIRMATION_TEXT = get_text('wait_confirmation', default="""Hallo {name}, WAIT_CONFIRMATION_TEXT = """Hallo {name},
leider können wir dir zur Zeit noch keinen Platz in einer Jugendgruppe anbieten. Da wir leider können wir dir zur Zeit noch keinen Platz in einer Jugendgruppe anbieten. Da wir
sehr viele Interessenten haben und wir möglichst vielen die Möglichkeit bieten möchten, an sehr viele Interessenten haben und wir möglichst vielen die Möglichkeit bieten möchten, an
@ -121,37 +50,18 @@ Wenn du weiterhin auf der Warteliste bleiben möchtest, klicke auf den folgenden
{link} {link}
Falls du kein Interesse mehr hast, kannst du unter folgendem Link die Warteliste verlassen: Falls du nicht mehr auf der Warteliste bleiben möchtest, musst du nichts machen. Du wirst automatisch entfernt.
{leave_link}
Das ist Erinnerung Nummer {reminder} von {max_reminder_count}. Nach Erinnerung Nummer {max_reminder_count} wirst
du automatisch entfernt.
Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION })
JOIN_WAITINGLIST_CONFIRMATION_TEXT = get_text('join_waitinglist_confirmation', default="""Hallo {name},
vielen Dank für dein Interesse an einem Platz in einer Jugendgruppe der JDAV %(SEKTION)s. Du hast dich erfolgreich
für die Warteliste registriert.
Leider ist die Nachfrage nach Jugendgruppenplätzen deutlich höher als unsere Kapazitäten. Daher kann es
mehrere Jahren dauern, bis wir dir einen Platz anbieten können. Damit unsere Warteliste möglichst
aktuell bleibt, werden wir dich in regelmäßigen Abständen per E-Mail bitten, dein Interesse an der Jugendgruppe
zu bestätigen.
Viele Grüße Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION }) Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION }
UNSUBSCRIBE_CONFIRMATION_TEXT = get_text('unsubscribe_confirmation', default="""Klicke auf den Link, um dich vom Newsletter der JDAV %(SEKTION)s abzumelden UNSUBSCRIBE_CONFIRMATION_TEXT = """Klicke auf den Link, um dich vom Newsletter der JDAV %(SEKTION)s abzumelden
{link}""" % { 'SEKTION': SEKTION }) {link}""" % { 'SEKTION': SEKTION }
NOTIFY_MOST_ACTIVE_TEXT = get_text('notify_most_active', default="""Hallo {name}! NOTIFY_MOST_ACTIVE_TEXT = """Hallo {name}!
Herzlichen Glückwunsch, du hast im letzten Jahr zu den {congratulate_max} aktivsten Herzlichen Glückwunsch, du hast im letzten Jahr zu den {congratulate_max} aktivsten
Mitgliedern der JDAV %(SEKTION)s gehört! Um genau zu sein beträgt dein Aktivitäts Wert Mitgliedern der JDAV %(SEKTION)s gehört! Um genau zu sein beträgt dein Aktivitäts Wert
@ -161,32 +71,27 @@ im letzten Jahr das {position}aktivste Mitglied der JDAV %(SEKTION)s.
Auf ein weiteres aktives Jahr in der JDAV %(SEKTION)s. Auf ein weiteres aktives Jahr in der JDAV %(SEKTION)s.
Dein:e Jugendreferent:in""" % { 'SEKTION': SEKTION }) Dein:e Jugendreferent:in""" % { 'SEKTION': SEKTION }
ECHO_TEXT = get_text('echo', default="""Hallo {name}, ECHO_TEXT = """Hallo {name},
um unsere Daten auf dem aktuellen Stand zu halten und sicherzugehen, dass du um unsere Daten auf dem aktuellen Stand zu halten, brauchen wir eine
weiterhin ein Teil unserer Jugendarbeit bleiben möchtest, brauchen wir eine
kurze Bestätigung von dir. Dafür besuche einfach diesen Link: kurze Bestätigung von dir. Dafür besuche einfach diesen Link:
{link} {link}
Dort kannst du deine Daten nach Eingabe eines Passworts überprüfen und ggf. ändern. Dein Dort kannst du deine Daten überprüfen und ändern. Falls du nicht innerhalb von
Passwort ist dein Geburtsdatum. Wäre dein Geburtsdatum zum Beispiel der 4. Januar 1942, 30 Tagen deine Daten bestätigst, wirst du aus unserer Datenbank gelöscht und
so wäre dein Passwort: 04.01.1942 erhälst in Zukunft keine Mails mehr von uns.
Falls du nicht innerhalb von 30 Tagen deine Daten bestätigst, gehen wir davon aus, dass du nicht mehr Teil
unserer Jugendarbeit sein möchtest. Dein Platz wird dann weitervergeben, deine Daten aus unserer Datenbank
gelöscht und du erhälst in Zukunft keine Mails mehr von uns.
Bei Fragen, wende dich gerne an %(RESPONSIBLE_MAIL)s. Bei Fragen, wende dich gerne an %(RESPONSIBLE_MAIL)s.
Viele Grüße Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION, 'RESPONSIBLE_MAIL': RESPONSIBLE_MAIL }) Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION, 'RESPONSIBLE_MAIL': RESPONSIBLE_MAIL }
PREPEND_INCOMPLETE_REGISTRATION_TEXT = get_text('prepend_incomplete_registration', default="""WICHTIGE MITTEILUNG PREPEND_INCOMPLETE_REGISTRATION_TEXT = """WICHTIGE MITTEILUNG
Deine Anmeldung ist aktuell nicht vollständig. Bitte fülle umgehend das Deine Anmeldung ist aktuell nicht vollständig. Bitte fülle umgehend das
Anmeldeformular aus und lasse es Deine*r Jugendleiter*in zukommen! Dieses Anmeldeformular aus und lasse es Deine*r Jugendleiter*in zukommen! Dieses
@ -196,10 +101,10 @@ kannst Du unter folgendem Link herunterladen:
**************** ****************
""" % { 'REGISTRATION_FORM_DOWNLOAD_LINK': REGISTRATION_FORM_DOWNLOAD_LINK }) """ % { 'REGISTRATION_FORM_DOWNLOAD_LINK': REGISTRATION_FORM_DOWNLOAD_LINK }
MAIL_FOOTER = get_text('mail_footer', default=""" MAIL_FOOTER = """
**************** ****************
@ -208,76 +113,4 @@ Diese Email wurde über die Webseite der JDAV %(SEKTION)s
verschickt. Wenn Du in Zukunft keine Emails mehr erhalten möchtest, verschickt. Wenn Du in Zukunft keine Emails mehr erhalten möchtest,
kannst Du hier den Newsletter deabonnieren: kannst Du hier den Newsletter deabonnieren:
{link}""" % { 'SEKTION': SEKTION }) {link}""" % { 'SEKTION': SEKTION }
INVITE_AS_USER_TEXT = get_text('invite_as_user', default="""Hallo {name},
du bist Jugendleiter*in in der Sektion %(SEKTION)s. Die Verwaltung unserer Jugendgruppen,
Ausfahrten und Finanzen erfolgt in unserer Online Plattform Kompass. Deine Stammdaten sind
dort bereits hinterlegt. Damit du dich auch anmelden kannst, folge bitte dem folgenden Link
und wähle ein Passwort.
{link}
Bei Fragen, wende dich gerne an %(RESPONSIBLE_MAIL)s.
Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION, 'RESPONSIBLE_MAIL': RESPONSIBLE_MAIL })
UPLOAD_REGISTRATION_FORM_TEXT = get_text('upload_registration_form', default="""Hallo {name},
vielen Dank für deine Anmeldung in der JDAV %(SEKTION)s. Bevor es richtig losgehen kann, brauchen
wir noch die Bestätigung deiner Daten und die Zustimmung zu unseren Teilnahmebedingungen.
Dafür kannst du das für dich vorausgefüllte Anmeldeformular unter folgendem Link herunterladen,
durchlesen und, falls du zustimmst, das unterschriebene Formular wieder dort hochladen.
{link}
Bist du noch nicht volljährig? Dann muss eine erziehungsberechtigte Person das Formular unterschreiben.
Bei Fragen, wende dich gerne an %(RESPONSIBLE_MAIL)s.
Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION, 'RESPONSIBLE_MAIL': RESPONSIBLE_MAIL })
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""")

@ -1,86 +1,41 @@
# contact data # contact data
SEKTION = get_var('section', 'name', default='Heyo') SEKTION = "Heidelberg"
SEKTION_STREET = get_var('section', 'street', default='Street') SEKTION_STREET = "Harbigweg 20"
SEKTION_TOWN = get_var('section', 'town', default='12345 Town') SEKTION_TOWN = "69124 Heidelberg"
SEKTION_TELEPHONE = get_var('section', 'telephone', default='0123456789') SEKTION_TELEPHONE = "06221 284076"
SEKTION_TELEFAX = get_var('section', 'telefax', default=SEKTION_TELEPHONE) SEKTION_TELEFAX = "06221 437338"
SEKTION_CONTACT_MAIL = get_var('section', 'contact_mail', default='info@example.org') SEKTION_CONTACT_MAIL = "geschaeftsstelle@alpenverein-heidelberg.de"
SEKTION_BOARD_MAIL = get_var('section', 'board_mail', default=SEKTION_CONTACT_MAIL) SEKTION_BOARD_MAIL = "vorstand@alpenverein-heidelberg.de"
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')
RESPONSIBLE_MAIL = get_var('section', 'responsible_mail', default='foo@example.org')
DIGITAL_MAIL = get_var('section', 'digital_mail', default='bar@example.org')
# LJP
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
# used to generate the personalized echo password
ECHO_PASSWORD_BIRTHDATE_FORMAT = get_var('echo', 'password_birthdate_format', default='%d.%m.%Y')
# grace period in days after which echo keys expire
ECHO_GRACE_PERIOD = get_var('echo', 'grace_period', default=30)
# Waiting list configuration parameters, all numbers are in days RESPONSIBLE_MAIL = "jugendreferat@jdav-hd.de"
GRACE_PERIOD_WAITING_CONFIRMATION = get_var('waitinglist', 'grace_period_confirmation', default=30)
WAITING_CONFIRMATION_FREQUENCY = get_var('waitinglist', 'confirmation_frequency', default=90)
CONFIRMATION_REMINDER_FREQUENCY = get_var('waitinglist', 'confirmation_reminder_frequency', default=30)
MAX_REMINDER_COUNT = get_var('waitinglist', 'max_reminder_count', default=3)
# misc # misc
# the maximal number of members that get sent congratulations for highest activity on aprils fools day CONGRATULATE_MEMBERS_MAX = 10
CONGRATULATE_MEMBERS_MAX = get_var('misc', 'congratulate_members_max', default=10)
# expiry duration of a good conduct certificate in months
MAX_AGE_GOOD_CONDUCT_CERTIFICATE_MONTHS = get_var('misc', 'max_age_good_conduct_certificate_months', default=24)
# accepted email domains for inviting users
ALLOWED_EMAIL_DOMAINS_FOR_INVITE_AS_USER = get_var('misc', 'allowed_email_domains_for_invite_as_user',
default=['example.org'])
# send all mails from the assocation's contact mail or from personal association mails
SEND_FROM_ASSOCIATION_EMAIL = get_var('misc', 'send_from_association_email', default=False)
# 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 # finance
ALLOWANCE_PER_DAY = get_var('finance', 'allowance_per_day', default=22) ALLOWANCE_PER_DAY = 10
MAX_NIGHT_COST = get_var('finance', 'max_night_cost', default=11) MAX_NIGHT_COST = 11
EXCURSION_ORG_FEE = get_var('finance', 'org_fee', default=10) CLOUD_LINK = 'https://cloud.jdav-ludwigsburg.de/index.php/s/qxQCTR8JqYSXXCQ'
# links # Admin setup
CLOUD_LINK = get_var('links', 'cloud', default='https://startpage.com') ADMINS = (('admin', 'christian@merten-moser.de'),)
DAV_360_LINK = get_var('links', 'dav_360', default='https://dav360.de')
WIKI_LINK = get_var('links', 'wiki', default='https://wikipedia.org')
DOCS_LINK = get_var('links', 'docs', default='https://github.com/chrisflav/kompass')
REGISTRATION_FORM_DOWNLOAD_LINK = get_var('links', 'registration_form', default='https://startpage.com')
# startpage # Waiting list configuration parameters, all numbers are in days
STARTPAGE_REDIRECT_URL = get_var('startpage', 'redirect_url', default='') GRACE_PERIOD_WAITING_CONFIRMATION = 30
ROOT_SECTION = get_var('startpage', 'root_section', default='about') WAITING_CONFIRMATION_FREQUENCY = 90
RECENT_SECTION = get_var('startpage', 'recent_section', default='recent')
REPORTS_SECTION = get_var('startpage', 'reports_section', default='reports')
# testing # testing
TEST_MAIL = get_var('testing', 'mail', default='test@localhost') TEST_MAIL = "post@flavigny.de"
REGISTRATION_FORM_DOWNLOAD_LINK = 'https://cloud.jdav-ludwigsburg.de/index.php/s/NQfRqA9MTKfPBkC'
DOMAIN = 'jdav-hd.merten.dev'
STARTPAGE_REDIRECT_URL = 'https://jdav-hd.de'

@ -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,31 +13,37 @@ Including another URLconf
1. Import the include() function: from django.conf.urls import url, include 1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 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.contrib import admin
from django.contrib.admin.views.decorators import staff_member_required
from django.conf.urls.static import static from django.conf.urls.static import static
from django.conf.urls.i18n import i18n_patterns from django.conf.urls.i18n import i18n_patterns
from django.conf import settings from django.conf import settings
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.views.generic.base import RedirectView from django.views.generic.base import RedirectView
from oauth2_provider import urls as oauth2_urls
from .views import media_access urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
admin.site.index_title = _('Startpage') admin.site.index_title = _('Startpage')
admin.site.site_header = 'Kompass' admin.site.site_header = 'Kompass'
urlpatterns = i18n_patterns( if settings.OIDC_ENABLED:
re_path(r'^media/(?P<path>.*)', media_access, name='media'), admin.site.login = staff_member_required(
re_path(r'^kompass/?', admin.site.urls, name='kompass'), admin.site.login, login_url=settings.LOGIN_URL
)
urlpatterns += i18n_patterns(
re_path(r'^oidc/', include('mozilla_django_oidc.urls')),
)
urlpatterns += i18n_patterns(
re_path(r'^kompass/?', admin.site.urls),
re_path(r'^jet/', include('jet.urls', 'jet')), # Django JET URLS re_path(r'^jet/', include('jet.urls', 'jet')), # Django JET URLS
re_path(r'^admin/?', RedirectView.as_view(url='/kompass')), re_path(r'^admin/', RedirectView.as_view(url='/kompass')),
re_path(r'^newsletter/', include('mailer.urls', namespace="mailer")), re_path(r'^newsletter/', include('mailer.urls', namespace="mailer")),
re_path(r'^members/', include('members.urls', namespace="members")), re_path(r'^members/', include('members.urls', namespace="members")),
re_path(r'^login/', include('logindata.urls', namespace="logindata")),
re_path(r'^LBAlpin/Programm(/)?(20)?[0-9]{0,2}', include('ludwigsburgalpin.urls', re_path(r'^LBAlpin/Programm(/)?(20)?[0-9]{0,2}', include('ludwigsburgalpin.urls',
namespace="ludwigsburgalpin")), namespace="ludwigsburgalpin")),
re_path(r'^_nested_admin/', include('nested_admin.urls')), re_path(r'^_nested_admin/', include('nested_admin.urls')),
path('o/', include(oauth2_urls)),
re_path(r'^', include('startpage.urls', namespace="startpage")), re_path(r'^', include('startpage.urls', namespace="startpage")),
) )

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

Loading…
Cancel
Save