Compare commits

...

334 Commits

Author SHA1 Message Date
Christian Merten aae75ce291
perf(finance/admin): remove `is_valid` from list view (#9)
The new unified statement view is very slow in production. This is
caused by the computation of `is_valid` for every entry of the list,
which entails at least one database query per row. Instead of removing
the `is_valid` field from the list view, we could prefetch the related
fields, but I don't think the `is_valid` provides any noticeable benefit
anyway.

We also add pagination to the statement view.
1 month ago
Christian Merten efe20bc721
chore(finance/models): add documentation and test for `validity` (#11)
Currently, the `INVALID_TOTAL` case of the `Statement.validity` method
is tested indirectly via the admin tests and the behavior is hard to
trace back. We therefore add documentation and a targeted test.
1 month ago
Christian Merten 5d4f29be89
feat(finance/admin): unified statement view (#6)
This PR replaces the separate admin views for unsubmitted, submitted and
confirmed statements by one common view. To distinguish the state, we
now display a colored badge in the changelist.

The default permissions for the `Standard` group are changed so that
normal users can continue to view statements they are related to when
these are submitted or confirmed.
1 month ago
Christian Merten 3b8964fbb0
chore(deploy): update urls to github repository (#8) 1 month ago
Christian Merten 3e5f6f0d27
chore: update favicon 1 month ago
Christian Merten 461cb098f0
chore(ci): build and release docker image, build documentation (#7)
We expand the tests CI run to first build the main image, build and
deploy the documentation pages, run the test suite and publish the
docker image in the github docker registry.
2 months ago
Christian Merten 605ae3ae72
chore(tests): add executed test methods to coverage report (#5) 2 months ago
Christian Merten 69a4560ea4
refactor(finance/models): replace `submitted` and `confirmed` by a `status` field (#3)
This is in preparation for a [new statement admin
view](#179).
2 months ago
Christian Merten c6bf9fe915
chore(members/tests/tasks): fix tests for `send_notification_crisis_intervention_list` (#4) 2 months ago
marius.klein ad33d5db17 feat(members/admin): add training overview (#174)
Add a new admin view for managing all trainings of members of the association. The subsections on training and activity categories are moved to a new trainings section.

We also protect the `submitted` and `passed` fields of member trainings for the default permission set.
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
2 months ago
Christian Merten 5d3670b819
chore: update README 2 months ago
Christian Merten 9caa3195ab
chore(CI): add tests action (#1)
We run the test suite on every commit and compute the coverage. The
action succeeds only if the coverage is at 100%.
2 months ago
Christian Merten 61060d7104
chore(static): replace old favicon
The copyright of the old logo was unclear. The new one was designed by Tobias Lenk, who agreed
to its usage in this project.
2 months ago
Christian Merten 6d542456fa
feat(members/admin): enable waitinglist and memberunoconfirmed view for standard users
We change the default permissions for the standard user group to allow viewing the unconfirmed registrations
and waitinglist views (Most projects already manually added the permissions for unconfirmed registrations).
Standard users only see waiters that have a group invitation (active, expired or rejected) to a group
they are a youth leader of.
3 months ago
Christian Merten 342227624a
chore(members/tasks): adjust timeframe for crisis list sending 3 months ago
Christian Merten 9f012eed7a
fix(members/tasks): filter by date 3 months ago
Christian Merten 10cdc19011
feat(members/admin): show existence of registration form in list view 3 months ago
Christian Merten 9f7b7a9517
feat(members/admin): button to (re)request registration form 3 months ago
Christian Merten 25dd1520c2
chore: add CLAUDE.md to gitignore 3 months ago
Christian Merten c9a475797b
chore(static): replace (j)dav logos by placeholders 3 months ago
Christian Merten 691ae04142
chore(static): add attributions and replace third party images 3 months ago
Christian Merten 068dfaa6c8
chore(finance/admin): mark unreachable code as no cover 4 months ago
Christian Merten 03d4781d49
chore(settings): add logging configuration and replace print statements 4 months ago
Christian Merten 19240e47c9
chore(members/tests): mark intentionally skipped tests as no cover 4 months ago
Christian Merten adc23bc7e0
fix(*): various bugs discovered by tests 4 months ago
Christian Merten 3fd01c9001
chore(members/admin): remove RegistrationFilter
This filter was used when there was not yet a distinction between confirmed and unconfirmed members.
By design, every confirmed member should have a complete registration.
4 months ago
Christian Merten 65790d3b4d
chore(members/views): add missing tests, remove dead code 4 months ago
Christian Merten 5efdbcb63c
chore(*): add various tests 4 months ago
Christian Merten 162b9a46ea
chore(docker/test): add test texts config 4 months ago
Christian Merten f5e3769aae
chore(members/tests): cover templatetags/overview_extras 4 months ago
Christian Merten c7eb07ddd1
chore(members/tests): cover templatetags 4 months ago
Christian Merten a784957b7f
chore(mailer/tests): remove unused method 4 months ago
Christian Merten e81efe0f83
chore(contrib/tests): add missing utils tests 4 months ago
Christian Merten 205b72d8e2
chore(startpage/tests): cover missing views 4 months ago
Christian Merten b21b975252
chore(startpage/tests): test uncovered lines 4 months ago
Christian Merten 3003bbe67f
fix(finance/admin): pass participant_count only once 4 months ago
Christian Merten 1b8089dd93
fix(mailer/models): __str__ method of Attachment returns string 4 months ago
Christian Merten 69062f3e58
fix(members): various bugs 4 months ago
marius.klein a75208b41c feat(members): add group meeting checklist generation (#154)
Add an action to generate checklists for group meetings. These checklists can be used for documentation and for simplifying the check-in procedure in climbing gyms.

Co-authored-by: mariusrklein <47218379+mariusrklein@users.noreply.github.com>
Reviewed-on: #154
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
4 months ago
Christian Merten f58a7dc4b6
chore(*/tests): various tests 4 months ago
Christian Merten 52f0209912
chore(*): ignore some files from tests 4 months ago
Christian Merten 996914dc77
chore(tests): add mailer and logindata tests 4 months ago
Christian Merten 7aea91cb31
chore(*): remove stub files 4 months ago
Christian Merten afedf74f8f
chore(tests/material): add models and admin tests 4 months ago
Christian Merten b613dc70c2
chore(finance/tests): add rules tests 4 months ago
Christian Merten 25ec55d731
chore(members/tests): add remaining PDF test cases 4 months ago
Christian Merten 7ea500ebaa
chore(members/tests): various tests
Co-authored by: Claude
4 months ago
Christian Merten 44354cb681
chore(logindata/tests): add views tests
Co-authored by: Claude
4 months ago
Christian Merten 1d519d70dc
chore(mailer/tests): add admin tests
Co-authored by: Claude
4 months ago
Christian Merten 242eff1ffc
chore(members/tests): more model tests 4 months ago
Christian Merten 2b9fd2556b
chore(members/models): remove unused function 4 months ago
Christian Merten b9d112e047
chore(members/tests): more admin tests 4 months ago
Christian Merten 88521def1a
chore(mailer): remove unused subscribe views 4 months ago
Christian Merten c7c64139a4
chore(mailer/tests): unsubscribe view tests 4 months ago
Christian Merten 187e4ebf54
chore(mailer/tests): add model tests 4 months ago
Christian Merten 355aad61c2
chore(finance/tests): add more admin tests 4 months ago
Christian Merten 396ea6f796
chore(finance/tests): reorganise and add admin tests 4 months ago
Christian Merten a9b26e529b
feat(*): add more tests 4 months ago
Christian Merten 99f6dfcdfb
feat(docker/production): create superuser in initial setup
We add one step to the master entrypoint script to ensure a
superuser exists with username and password configured from the
environment variables DJANGO_SUPERUSER_USERNAME and
DJANGO_SUPERUSER_PASSWORD. The step does nothing if these variables
are not set or the user already exists.
5 months ago
Christian Merten 7f203b5139
feat(contrib/management): add command to create a superuser from env variables 5 months ago
marius.klein e02f728e8a feat(members/waitinglist): add group age range info to invite text (#168)
Pass age info to group invite text as a parameter.

Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
5 months ago
Christian Merten 2cee336397
chore: add license 5 months ago
marius.klein a8d4625719 feat(finance/tests): tests for new rules (#155)
Also makes some checks safe.

Reviewed-on: #155
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
5 months ago
Christian Merten 416af36070
chore(members): reorganize tests 8 months ago
Christian Merten 07bf5ff53f
chore(members): add more tests 8 months ago
Christian Merten 7647f93c83
chore(members): move csv import to separate file 8 months ago
Christian Merten 0eedc3ecf9
feat(finance): send statement summary to finance office 8 months ago
Christian Merten 1ada10fda4
feat(members/excursion): automatically send crisis intervention list 8 months ago
Christian Merten d4137effa4
fix(members/seminar_report_docx): make timestamps timezone aware 8 months ago
marius.klein 3250dc7089 feat(finance): org fee for old participants (#149)
Allow deducting a configurable organisational fee for participants older than 27 from subsidies. This is calculated per day and old participant.

Reviewed-on: #149
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
8 months ago
marius.klein 05f924cdef fix(members/excursion): fix seminar day calculation and add verbosity in finance overview (#153)
Reviewed-on: #153
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
8 months ago
Christian Merten fd4770d295
fix(members/tests): adapt to new texts 8 months ago
Christian Merten 6b32595a5f
chore(members/views): modify texts and button size 8 months ago
Christian Merten fb14c2f060
feat(members/views): show upload registration form after echo if missing 8 months ago
Christian Merten 2fcdf1ee25
feat(members/admin): add unconfirm member action 8 months ago
Christian Merten 62a4e37a15
feat(members/admin): re-request mail confirmation for waiters 8 months ago
Christian Merten 60942115ca
fix(members/rules): check for groups of excursion instead of groups of member 8 months ago
marius.klein f213e11772 feat(finance): creation of receipts for confirmed statements and payment of LJP contributions (#150)
Confirmed statements now come with automatically generated PDF receipts used for documenting all issued payments.

This PR also adds generation of transactions for LJP contributions and their validation.

closes #92

Co-authored-by: mariusrklein <47218379+mariusrklein@users.noreply.github.com>
Reviewed-on: #150
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
8 months ago
Christian Merten 33ab4e481d
fix(finance/admin): check existence and permission in finance admin views 8 months ago
Christian Merten d913c8049d
feat(members/waitinglist): add confirm link in invitation mail and more notifications 8 months ago
Christian Merten 0535cce70f
feat(members/waitinglist): notify responsibles in case of rejections 8 months ago
Christian Merten 5d728f1eee
fix(settings/jet): correct sidebar permissions 8 months ago
Christian Merten 865df92222
feat(mailer/models): check global permissions for messages 8 months ago
Christian Merten ffef3c93c3
fix(members/pdf): use excursion date instead of creation date 8 months ago
Christian Merten 2d69483276
chore(style): remove trailing whitespace 8 months ago
Christian Merten c8df5630b8
refactor(latex): add base template and unify designs
We add a base template for all latex documents to unify the desings and improve maintainability. Also
the table definitions are simplified fixing the various width issues.
8 months ago
Christian Merten 11b92f72b1
fix(members/tests): set date correctly 9 months ago
marius.klein 4a003ed15e fix(members/freizeit): change age calculation to first day of excursion (#148)
Reviewed-on: #148
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
9 months ago
Christian Merten 3de28c3729
feat(logindata/oauth): add email field 9 months ago
Christian Merten 7c5152c5b0
feat: oauth provider 9 months ago
Christian Merten de95c76ac7
chore: update Django to 4.2.20 9 months ago
Christian Merten 769b63d457
chore: replace jet fork by django-jet-reboot 9 months ago
marius.klein 2650eb2cb1 feat(members/pdf): added scaling for attachment images and pdf pages (#142)
PDF and image attachments are scaled to A4.

follow up for #61

Reviewed-on: #142
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
9 months ago
Christian Merten 65c58b3d44
chore: update jet 9 months ago
Christian Merten b5b62ceb92
fix(settings): permission for material section 9 months ago
Christian Merten 1fe37023de
feat(settings): allow overriding static files 9 months ago
Christian Merten fb3d37ff4f
chore(members/locale): add translation 9 months ago
Christian Merten 9694570bf0
fix(startpage/models): show deactivated url if startpage is deactivated 9 months ago
Christian Merten 443ef326cf
feat(startpage): allow disabling startpage
We add back the functionality to disable the startpage. If a non-empty redirect url is configured,
all startpage urls are disabled except for the index page which redirects to the given url.
9 months ago
Christian Merten bdbbaa41a2
chore(members/templates): replace town specific waiting list introduction by placeholder 9 months ago
Christian Merten 46e41e4cd9
feat(members/models): allow wildcard in internal domain setting 9 months ago
Christian Merten 80cf9250bb
chore(members): more tests 10 months ago
Christian Merten ae27340dcc
feat(members/waitinglist): send registration confirmation 10 months ago
Christian Merten 3591ebd08e
feat(members/waitinglist): refine wait confirmation status
Rework the wait cofirmation status shown in the admin: If there is a pending wait confirmation
request (i.e. the number of sent reminders is positive), the status is either `None` (i.e. undecided)
or `False`. Otherwise the status is `True`.
10 months ago
Christian Merten 0f19ce01e4
fix(members/pdf): escape % 10 months ago
Christian Merten edd47ac8bd
fix(members/pdf): don't escape umlaut
Partially reverts 2761efecaa. To handle invalid unicode characters, we now override
the LaTeX error message to remove invalid characters instead of crashing. We also
add various umlaut and invisible unicode characters to the test data.
10 months ago
marius.klein c4d6581e6f feat(startpage): add link model for external links on admin startpage (#138)
Add `Link` model to customize the admin startpage from the admin interface. Also add block rendering of links.

Reviewed-on: #138
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
10 months ago
marius.klein 2a0905469d feat(members/trainings): add attendance certificate field (#137)
closes #132

Reviewed-on: #137
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
10 months ago
Christian Merten 84f28b0786
fix(members/seminar_report): escape ljpproposal title 10 months ago
Christian Merten 54ed4c85e4
fix(members/excel): normalize filename of generated vbk form 10 months ago
Christian Merten 7b64f48ad7
fix: convert to str before normalizing name in esc_all 10 months ago
marius.klein 308d9f3114 feat(members/pdf): improve handling of long tables (#135)
closes #128

Reviewed-on: #135
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
10 months ago
marius.klein 7a9c6f9d85 feat: open pdfs in new tab in browser instead of download (#136)
closes #127

Reviewed-on: #136
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
10 months ago
Christian Merten bffacf7808
fix(members/models): replace `auto_now=True` by `default=timezone.now` 10 months ago
Christian Merten 2761efecaa
fix(members/templatetags): escape all non-ascii characters in esc_all 10 months ago
Christian Merten 4bd8f15e97
fix(members/crisis_intervention_list): escape emergency contact information 10 months ago
Christian Merten 4c4b450245
feat(members/waitinglist): add leave waitinglist link to reminders 10 months ago
Christian Merten 1d2f0c152f
feat(members/admin): add excursion code to filenames and generated documents 10 months ago
Christian Merten 24810a4f2b
fix(members/models): align SJR subsidizable participants with regulations 10 months ago
Christian Merten 70a576a289
docs: add detailed production deployment instructions 10 months ago
Christian Merten 40edd650dc
chore(static): remove unused images and normalize naming 10 months ago
Christian Merten c95b839191
fix(members/models): list more than 11 participants 10 months ago
Christian Merten 7cae13fc1d
feat(members/excursion): add basic approval status 10 months ago
Christian Merten 9d1351197a
fix(css/people_grid): set max-width of boxes 10 months ago
Christian Merten 362a29dca8
fix(media_access): unprotect members and website images
Since access to all media content required staff login, images intended for display on the website
were no longer accessible without login. This commit removes the protection for image files of members
and startpage posts.

We also add tests to prevent this regression from happening again.
10 months ago
Christian Merten 8b03deda5b members/admin: adapt LJP application to new format (#121)
Implements the new LJP application format as outlined in #116. In particular:

- The V-32 PDF is replaced by an `.xlsx` sheet.
- The LaTeX generated PDF for the seminar report is replaced by a `.docx` file, generated by `pandoc` from a modified `.tex` file.
- The cost and participants overview from the old PDF can still be generated separately, but is no longer required.

Also adds many fields to `LJPProposal` that are required to generate the full application.
10 months ago
Christian Merten e8f4448d62
members/admin: remove trailing whitespace 11 months ago
Christian Merten 5227efe17b
members/excursion: add LJP category field to activity category 11 months ago
Christian Merten 79c20087e3
mailer: use internal mail domains variable in error messages 11 months ago
Christian Merten 06db761021
locale: fix translations 11 months ago
Christian Merten 79b48c9079
members/admin: add action to only request mail confirmation of not yet confirmed email addresses 11 months ago
marius.klein 678559fb4d members/pdf: add numbering to participant listings (#119)
Also add a total participants and youth leaders count on the members on list inline tab.

Reviewed-on: #119
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
11 months ago
marius.klein d1a8e7f159 members/admin: group overview excel (#118)
closes #110

Reviewed-on: #118
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
11 months ago
Christian Merten 530aea3244
contrib: factor common media path manipulations out 11 months ago
Christian Merten 49c4e4c548
settings: remove MEDIA_MEMBERLISTS and use MEDIA_ROOT everywhere 11 months ago
marius.klein cfcde2da3a finance/statement: make `subsidy_to` and `allowance_to` optional (#112)
closes #108

- fields for receivers of allowance `a` and subsidies `s` are not compulsory anymore. If receivers are given, `a` and `s` are payed out for them. `s` can only be payed out in total, disregarding the number of receivers given for `a`.
- In the overview pages (activity and statement), we are now distinguishing between theoretical `a` + `s` and what has been payed out practically. If no receiver was given for either things, it is made clear that nothing is payed out. All combinations of `0`, ..., `n` payed allowances (`n` being number of approved participating YLs) and `0, `1` payed subsidies are possible.
- transaction generation logic adapted accordingly

Reviewed-on: #112
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
11 months ago
Christian Merten 7b2a47536e
templates: replace local specific templates by placeholders 11 months ago
Christian Merten 6ffa2376b8
settings: use toml configuration files
We replace the current environment variable based configuration approach by
reading all local configuration from a `settings.toml` configuration file.
The docker test, development and production setups have been updated to use
the new setup.

The configuration folder also allows overriding every template in a
`config/templates` directory. We use this in a follow-up to move
all local specific templates, e.g. the registration form, into this
config directory.
11 months ago
Christian Merten 8a9cdc22d1
startpage/templates: use section variable 11 months ago
Christian Merten 9a07ef74a6
templates/admin: use section variable 11 months ago
Christian Merten aefef315bc
members/models: use section name in signature on SJR application 11 months ago
Christian Merten aaa43b9ae1
locale: fix various grammar mistakes 11 months ago
Christian Merten 56d8adb510
members/admin: add place column and group filter to excursion list display 11 months ago
Christian Merten 3e1a5c3fbb
tests: add coveragerc to exclude jet files from coverage report 11 months ago
Christian Merten d1075f43e7
members/tests: add more admin tests 11 months ago
Christian Merten 9610503caa
finance/tests: add tests for models 11 months ago
Christian Merten 034478ba44
members/admin: show and filter by echo status 11 months ago
Christian Merten a0da26476c
members/tests: add tests for admin pages 11 months ago
Christian Merten 3622743d2c
members/pdf: normalize filenames in merge_pdf 11 months ago
Christian Merten 3e0d55c0ed
members/registration: escape special characters in user input 11 months ago
marius.klein e7dcbb47ab finance/statement: show IBAN validity in submit views (#104)
* Add new attribute `iban_valid` to `Member`.
* Submit pages of regular expenses and activity expenses now include an overview which people with expenses have a valid IBAN.
* Add a note that IBAN validity should be checked manually before submitting.

Right now, no technical barriers are in place that prevent missing/wrong IBANs when a statement is submitted. This is intentional to preserve maximal flexibility.

In a follow-up PR, one could add custom warning messages on top of page when some IBANs are invalid.

Reviewed-on: #104
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
11 months ago
Christian Merten a2cbae2c8e
media: require staff login for media access 11 months ago
Christian Merten 7d74e5d908
members/tests: add tests for views 11 months ago
Christian Merten d4a8c4a515
members/models: factor out upload_registration_form_link 11 months ago
Christian Merten 05cb501942
ludwigsburgalpin/tests: add tests for views and admin 11 months ago
Christian Merten 593cef520d
members/tests: only test age for passed dates 11 months ago
Christian Merten 39f1700131
members/tests: skip sjr application generation 11 months ago
Christian Merten 0960646d1f
finance/tests: adapt to new logic with allowance_to and subsidy_to 11 months ago
Christian Merten e02b0acefe
docker/test: improve setup
`make test` now automatically forces a rebuild. Also passing `keepdb=true` runs
the test suite with `--keepdb` which is useful when repeatedly running tests.
11 months ago
marius.klein 91ceaaf9f9 members/excursion: select invoice for sjr application form (#103)
Closes #61

Adds to the generate sjr application process a form in order to select one invoice.

Reviewed-on: #103
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
11 months ago
Christian Merten 98a03e4abd
members/ljp: fix calculation of participants
Implements the correct formula for computing the participant count according to the LJP
regulations. Also adds extensive unit tests for the formula.
11 months ago
Christian Merten afdbb56d81
finance: don't include subsidies in theoretic total
Subsidies paid for night and travel costs are expected to be listed
in the bills of the associated statement. Hence, they should not be
counted a second time in the theoretic total. This affects LJP
and SJR applications.
11 months ago
Christian Merten e2bff68471
members/admin: add check for valid allowance_to in finance overview 11 months ago
Christian Merten 2e6bfc9b75
finance/statement: make allowance_to optional
If an excursion has zero admissable youth leaders, the statement and hence the excursion
currently can't be saved, because the `allowance_to` field has to be non-empty, but
the number of entries has to be zero. This commit hence makes the field optional.
11 months ago
Christian Merten 5d0aa18dde
finance: adapt to allowance_to and subsidy_to
Use the new `allowance_to` and `subsidy_to` fields in statement validation. The
night and travel costs have to be transferred to the person listed as `subsidy_to`,
the allowance has to be paid to the persons listed in `allowance_to`.
11 months ago
Christian Merten 17bf6e8186
members/admin: fix incorrect syntax in translation string 11 months ago
Christian Merten 8b932461b7
finance/statement: add selection fields for allowance and subsidies
In the statement tab on excursions, add two new fields to select to which
youth leaders the allowance and subsidies should be paid. The fields
are checked for validity based on the number of approved youth leaders.

Also add a new field on excursions to allow for additional approved youth
leaders.

The new fields are not yet used in the statement confirmation process.
11 months ago
Christian Merten ce466671f2
members/waitinglist: fix queryset based age calculation 11 months ago
Kasimir Uihlein 35e565d0bd Update and enhance documentation (#100)
- Move documentation from README into sphinx docs
- change theme from alabaster to sphinxawsome-theme
- split into technical and user documentation
  - restructure docs/ directories
  - update sphinx refs in user documentation
- extend technical documentation with contributing page
- create seed for more technical documentation (architecture, deployment, testing)

Reviewed-on: #100
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: Kasimir Uihlein <kuihlein@mailbox.org>
Co-committed-by: Kasimir Uihlein <kuihlein@mailbox.org>
11 months ago
Christian Merten afb38c118a
members/admin: add age list filter for waitinglist 11 months ago
Christian Merten b0311dce80
members/admin: sort age in waiting list only by year
Previously, the age column was sorted according to the birth date. This typically
causes singleton grouping upon multi sort with age as the primary sorting key. A
typical use case is sorting by age and application date.

Now the age column is sorted only by the numerical year value, which causes
the groups to be bigger.
12 months ago
Christian Merten 1bd2895415
translations: remove line counts 12 months ago
Christian Merten f05c8b2fb6
members/admin: translate age label and add ordering field 12 months ago
marius.klein 3b46695b49 finance/admin: validate IBAN and show EPC-QR code for transactions (#94)
1. IBAN validation in member admin.
2. In the transaction overview, for every transaction an EPC-QR code for banking apps is generated and displayed. The (necessary) BIC field is automatically derived from the IBAN. This closes #63.

Both steps use the python library schwifty.

Reviewed-on: #94
Reviewed-by: Christian Merten <christian@merten.dev>
Co-authored-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
Co-committed-by: marius.klein <marius.klein@alpenverein-heidelberg.de>
12 months ago
Christian Merten 19eb0953d5
tests: fix, generate html coverage report 12 months ago
Christian Merten 36424f091d
chore: update README
Include information about development setup.

Co-authored by: Kasimir Uihlein <kuihlein@mailbox.org>
12 months ago
Christian Merten 7af3ec488e
members/waitinglist: remove registration form link from invite text
The link is no longer needed, since a prefilled registration form can
now be downloaded after filling out the online form.
12 months ago
Christian Merten 31b31a3eb3
members/waitinglist: allow editing of invite text 12 months ago
Christian Merten c2bfd85eb4
admin/sidebar: open external links in new tab 12 months ago
Christian Merten a749aca7a4
finance: allow pdfs in proof field 12 months ago
Christian Merten 4c7ff39432
members/registration: pre-fill registration form
Instead of directly uploading the filled-in registration form, a pre-filled
registration form is provided and the signed agreement can be uploaded
in a separate step.

Co-authored by: Marius Klein <marius.klein@alpenverein-heidelberg.de>
1 year ago
leonard.koenig 0afc2fefb5 docs: add waitinglist (#82)
documentation for managing the waitinglist

Co-authored-by: leonard.koenig <leonard.koenig@jdav-hd.merten.dev>
Co-authored-by: Christian Merten <christian@merten.dev>
Reviewed-on: #82
Co-authored-by: leonard.koenig <leonard.koenig@alpenverein-heidelberg.de>
Co-committed-by: leonard.koenig <leonard.koenig@alpenverein-heidelberg.de>
1 year ago
Christian Merten 58da7fae23
settings/texts: add space to prevent outlook glitch 1 year ago
Christian Merten f87837218e
members/waitinglist: preserve waitinglist application date 1 year ago
Christian Merten e055554125
members/admin: remove redundant sentence 1 year ago
Christian Merten 436334f23d
members/admin: show new members section also to non-waitinglist managers 1 year ago
Christian Merten c76aebdc18
members/admin: prefetch invitations to group in admin 1 year ago
Christian Merten 55c9605428
members/admin: show last group invitation and gender in list 1 year ago
Christian Merten f61941c3d0
settings: populate links from environment variables 1 year ago
Christian Merten f0ed36a0cc
docker/development: add example .env file 1 year ago
Christian Merten d4d9d97a94
mailer: force email address names to be unique 1 year ago
Christian Merten fa6f31e560
admin: allow * in group names, verify that only valid group names, section urls and post urls are saved 1 year ago
leonard.koenig 6c77d09790 docs: adapt to new naming (#75)
Co-authored-by: Christian Merten <christian@merten.dev>
Reviewed-on: #75
Co-authored-by: leonard.koenig <leonard.koenig@jdav-hd.merten.dev>
Co-committed-by: leonard.koenig <leonard.koenig@jdav-hd.merten.dev>
1 year ago
Christian Merten 948850151a
members/admin: make email and phone number links 1 year ago
Christian Merten 9a221a5c9f
members/admin: reduce filters and list fields 1 year ago
Christian Merten bf09be5d19
settings: reorder sidebar 1 year ago
Christian Merten 45a3ea40ff
jet: update version 1 year ago
Christian Merten d10a475aad
sidebar: fix permissions 1 year ago
Christian Merten adea9e0c8f
jet: update version 1 year ago
Christian Merten a27af02a27
members: personalize members landing page with list of led groups 1 year ago
leonard.koenig 307884deb8 docs: replace `:` with `*` (#74)
also fix some wording

Reviewed-on: #74
Co-authored-by: leonard.koenig <leonard.koenig@jdav-hd.merten.dev>
Co-committed-by: leonard.koenig <leonard.koenig@jdav-hd.merten.dev>
1 year ago
Christian Merten 308e4e31f5
docs: add link to sidebar 1 year ago
Christian Merten 519c3b811e
docs: add link to index page 1 year ago
Christian Merten 1779180ce1
docker: automatically build documentation and place in static root 1 year ago
Christian Merten 3bb64815ab
docs: update 1 year ago
Christian Merten ee84866da0
Merge branch 'main' into docs 1 year ago
Christian Merten 67aeb0c03a
members/echo: make gender editable, change wording 1 year ago
Christian Merten 0845c04001
members/echo: don't invalidate echo key after echoing, only expiry invalidates now 1 year ago
Christian Merten d3ceb81cc3
members/echo: check key validity before password requesting password 1 year ago
Christian Merten a24c23b13e
startpage: improve mobile adaption 1 year ago
Christian Merten 420f074620
members/echo: fix typo 1 year ago
Christian Merten b3da0b1083
mailer: fix translation 1 year ago
Christian Merten 32e361151f
mailer: set name in sender and reply to 1 year ago
Christian Merten 5cee496662
mailer: add translations 1 year ago
Christian Merten b7804884c0
Revert "mailer: remove manual message ids"
This reverts commit 8633c41b8a.
1 year ago
Christian Merten e2f9eb7db0
mailer: add option to switch between sending from one email address vs from personalized email addresses 1 year ago
Christian Merten 3d60f7e9bf
members/models: normalize usernames, use username as association name if available 1 year ago
Christian Merten 8633c41b8a
mailer: remove manual message ids 1 year ago
Christian Merten 8327b0a3b9
mailer: remove footer 1 year ago
Christian Merten ec404c7435
finance: alter field 1 year ago
Christian Merten edb113562d
members: fix field permissions 1 year ago
Christian Merten 31a7f977dd
finance/models: fix overview for independent statements 1 year ago
Christian Merten 92e77e8b3c
finance: fix permissions 1 year ago
Christian Merten 97e446f54a
members/waitinglist: fix permissions 1 year ago
Christian Merten 0a1d85e924
finance: fix permissions on submitted statement 1 year ago
Christian Merten 8c71eb744f
finance/translation: fix 1 year ago
Christian Merten 28c9da8168
members: fix has statement check 1 year ago
Christian Merten dd7af67b34
translations: replace more : with * 1 year ago
Christian Merten 5a5ffea89c
members/inviteasuser: reject if mail domain not internal 1 year ago
Christian Merten df16729bd6
mailer: add internal_only flag 1 year ago
Christian Merten 459d4b0e72
mailer: add sender whitelist field 1 year ago
Christian Merten 17cae5c009
translations: use gender star 1 year ago
Christian Merten 60c25cf845
startpage: allow markdown in group description 1 year ago
Christian Merten 3453359e1e
startpage: sort groups by name 1 year ago
Christian Merten 7bb89dd2d9
docker/production: serve maintenance page on 502 1 year ago
Christian Merten c49be3f594
startpage: fix typo 1 year ago
Christian Merten c5316fa0dc
startpage: add favicon, rename root section 1 year ago
Christian Merten 368017a20a
settings: read domain from env variable 1 year ago
Christian Merten 81eced382e
import: waitinglist default fields 1 year ago
Christian Merten 7d93a4be0a
members/excursion: add V32 and improve texts 1 year ago
Christian Merten eaccc5a5ef
members/excursion: group bills in seminar report 1 year ago
Christian Merten 302565d5f5
finance/bill: rename 1 year ago
Christian Merten 79b5389107
members/excursion: add finance overview 1 year ago
Christian Merten 5734d41a23
startpage: update impressum 1 year ago
Christian Merten d19da71fef
members: add demote to waiter button and confirmation 1 year ago
Christian Merten d1db0b833f
startpage: sort recent posts and reports 1 year ago
Christian Merten 7b5c16f6b7
mailer: remove send to note list field 1 year ago
Christian Merten fcfd1b0a9d
members: remove default from gender field 1 year ago
Christian Merten 18d5f5e989
dashboard: add mailer section 1 year ago
Christian Merten bb91d77cfc
members/views: fix prefilling of date inputs 1 year ago
Christian Merten 02db0669cd
members: don't request mail confirmation of emergency contacts 1 year ago
Christian Merten ed445a9bc6
members: update translations 1 year ago
Christian Merten b22a891157
chore: update translations 1 year ago
Christian Merten 7ef55738a5
members: provide contact info in waitinglist invitation 1 year ago
Christian Merten 5205caa6a6
chore: add read_settings templatetag 1 year ago
Christian Merten 8dafe01de0
templates: purge more ludwigsburg email addresses 1 year ago
Christian Merten 520dc1d3d2
members/admin: fix inlines 1 year ago
Christian Merten 5446dbd410
docs: add initial skeleton 1 year ago
Christian Merten 67e019073a
finance: fix allowance per day and rounding 1 year ago
Christian Merten 3087b8f8ee
members/admin: add help texts to excursion 1 year ago
Christian Merten 90f4ac88fc
members: make email field not required for emergency contacts in forms 1 year ago
Christian Merten 1f75d627e0
members: skip empty email addresses when requesting confirmation 1 year ago
Christian Merten 284f0b2420
members: make email field in emergency contact optional 1 year ago
Christian Merten 121076f9f1
docs: initial setup 1 year ago
Christian Merten 6eaa8e0414
admin: hide related objects in delete summary 1 year ago
Christian Merten 656438da90
startpage: fix portrait sizing issues 1 year ago
Christian Merten 0f69b8810c
members/admin: don't filter member selection fields 1 year ago
Christian Merten 3fc1b65d67
clubdesk import: assign youth leaders and omit groupless entries 1 year ago
Christian Merten 379c4547a6
jet: update 1 year ago
Christian Merten 8ef0bc848b
admin: add dashboard and explanations 1 year ago
Christian Merten 8c4d97b5d1
members: seminar report mode selection 1 year ago
Christian Merten 15ab8744b8
migrations: update meta information 1 year ago
Christian Merten b8b659747e
logindata: use processed username 1 year ago
Christian Merten 8a58a43bcd
finance: catch if bills have no set paid_by field 1 year ago
Christian Merten 3a9fca0a1e
members: confirmation step for invite as user 1 year ago
Christian Merten e178f56369
members: invite member as user 1 year ago
Christian Merten a49aab51b1
import: fix parsing logic for Jugendleiter 1 year ago
Christian Merten 8f709eab81
startpage: show reports on index, translations 1 year ago
Christian Merten 3eaaf1727c
startpage: flexibilize root section 1 year ago
Christian Merten 2c49c216dc
mailer: update migrations 1 year ago
Christian Merten ba8036f547
cache: set expiry time to 1s 1 year ago
Christian Merten 3c94d07bae
auth: rename User and Group, remove fields 1 year ago
Christian Merten 88e2c6ff0d
settings: allow page embedding on same host 1 year ago
Christian Merten f573eafbc0
mailer: allow more characters in email names 1 year ago
Christian Merten e8254c0761
startpage: fix footer links 1 year ago
Christian Merten d4974bfb32
members: adapt fields to latest clubdesk fields 1 year ago
Christian Merten d67caab5ae
mailer: make attachment file field mandatory 1 year ago
Christian Merten 40df91fcc7
members/waiter: add registration form download link 1 year ago
Christian Merten e2d660ed1e
members: rejection of invitations 1 year ago
Christian Merten d512d2b14c
members: Teilnehmer -> Meine Jugendgruppe 1 year ago
Christian Merten 3a0df4bc4d
members/echo: ask for dav badge number 1 year ago
Christian Merten 9cb30c98e3
members/admin: only include attachment if bill has proof 1 year ago
Christian Merten ba96bc50c6
members/excursion: add description field 1 year ago
Christian Merten 01a0f78fb4
members/excursion: fix naming place vs destination 1 year ago
Christian Merten b62464280e
members: Freizeit -> Ausfahrt 1 year ago
Christian Merten 39dbb61c86
members/echo: update texts 1 year ago
Christian Merten 2b82235e87
members/registration: client side verification of file size and format 1 year ago
Christian Merten 39c9160a12
members/views: fix wrong password default 1 year ago
Christian Merten 1faa1a1213
member: fix translation 1 year ago
Christian Merten d85d364572
members: add help texts 1 year ago
Christian Merten e88a2f2045
finance: update translations 1 year ago
Christian Merten bf5ad088cb
forms: fix file size checking 1 year ago
Christian Merten ee126335b8
members/views: hide country, add translations 1 year ago
Christian Merten 443ecc0267
local: fix cloud link 1 year ago
Christian Merten e6dbb7a03f
members/registration: fix missing group name in waiter invitation 1 year ago
Christian Merten 6ea7d3d8a1
update translations 1 year ago
Christian Merten b100999900
mailer/models: allow no reply-to 1 year ago
Christian Merten dfaa023082
mailer: set from addr to logged in users association mail 1 year ago
Christian Merten d43c7cce44
members/admin: only attach bill to sjr application if statement exists 1 year ago
Christian Merten 7ec1b3555b
members/admin: re-add birth_date field 1 year ago
Christian Merten 2aa632b19c
members/views: dont send password on invalid waiter form 1 year ago
Christian Merten e1e766d6a7
requirements: add pypdf 1 year ago
Christian Merten e6a41b26c9
members: use correct logo and show emergency contacts
gitea/kompass/pipeline/head There was a failure building this commit Details
1 year ago
Christian Merten 0220ed36fd
finance/admin: add statement unconfirm button 1 year ago
Christian Merten 7c7c67e496
finance/admin: show bills and transactions on confirmed statements 1 year ago
Christian Merten 57b4d517b1
members/waitinglist: waiting list confirmation reminders 1 year ago
Christian Merten fd29fa6199
members/waitinglist: personalize invitation mail 1 year ago
Christian Merten 52ebfcc831
mailer: ignore registration status 1 year ago
Christian Merten f2cbac30f6
members/freizeit: sjr applications 1 year ago
Christian Merten 7d9a1bf9a6
members/group: add weekly time
gitea/kompass/pipeline/head There was a failure building this commit Details
1 year ago
Christian Merten 3a862469ee
members: make some fields only changeable with extra permissions
gitea/kompass/pipeline/head There was a failure building this commit Details
1 year ago
Christian Merten a225af5905
members: automatically compute validity of good conduct certificate 1 year ago
Christian Merten 9b66301da1
members: reorganize fields on admin page
gitea/kompass/pipeline/head There was a failure building this commit Details
1 year ago
Christian Merten 6808bf9ddb
members/tests: mail confirmation 1 year ago
Christian Merten 0b3c8807e6
migration: allow nullable alternative_email field 1 year ago
Christian Merten be1f471044
members: enter and edit emergency contacts on registration and echo
gitea/kompass/pipeline/head There was a failure building this commit Details
1 year ago
Christian Merten cdab970bfc
members: emergency contacts, replace parent email with alternative email
gitea/kompass/pipeline/head There was a failure building this commit Details
1 year ago
Christian Merten 1f857e4fa3
finance/admin: allow change on submitted statements
gitea/kompass/pipeline/head There was a failure building this commit Details
1 year ago
Christian Merten 65f4787d8d
docker: remove version 1 year ago
Christian Merten efeaddba5e
mailer/admin: make sent field readonly
Code Coverage #### Overview by baseline * **[Overall project (difference to reference job)](https://jenkins.merten.dev/job/gitea/job/kompass/job/main/8//coverage#overview)** * Line Coverage: 70.82% (3131/4421) - Delta: -0.01% Output truncated. Details
gitea/kompass/pipeline/head This commit looks good Details
2 years ago
Christian Merten 20dc876216
mailer/mailutils: add List-Unsubscribe header 2 years ago
Christian Merten c97d26c5b1
members: add waitinglist import from csv
Code Coverage #### Overview by baseline * **[Overall project (difference to reference job)](https://jenkins.merten.dev/job/gitea/job/kompass/job/main/7//coverage#overview)** * Line Coverage: 70.83% (3130/4419) - Delta: -0.33% Output truncated. Details
gitea/kompass/pipeline/head This commit looks good Details
2 years ago
Christian Merten 2f3fb1fefd
contrib/admin: hide add other buttons everywhere
Code Coverage #### Overview by baseline * **[Overall project (difference to reference job)](https://jenkins.merten.dev/job/gitea/job/kompass/job/main/6//coverage#overview)** * Line Coverage: 71.16% (3121/4386) - Delta: -0.01% Output truncated. Details
gitea/kompass/pipeline/head This commit looks good Details
2 years ago
Christian Merten e1319bbd8b
readme: add build status badge
Code Coverage #### Overview by baseline * **[Overall project (difference to reference job)](https://jenkins.merten.dev/job/gitea/job/kompass/job/main/3//coverage#overview)** * Line Coverage: 71.17% (3123/4388) - Delta: +0.00% Output truncated. Details
gitea/kompass/pipeline/head This commit looks good Details
3 years ago

@ -0,0 +1,147 @@
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,9 +106,6 @@ jdav_web/my.cnf
# sass cache
jdav_web/static/jet/css/themes/*/.sass-cache/*
# test config
config
# celerybeat schedule database
jdav_web/celerybeat-schedule.db
@ -124,3 +121,18 @@ docker/test/db
docker/development/media
docker/production/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

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

@ -0,0 +1,661 @@
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,8 +1,14 @@
build-test:
cd docker/test; docker compose build
test:
touch docker/test/coverage.xml
chmod 666 docker/test/coverage.xml
test-only:
mkdir -p docker/test/htmlcov
chmod 777 docker/test/htmlcov
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
sed -i 's/\/app\/jdav_web/jdav_web/g' docker/test/coverage.xml
endif
echo "Generated coverage report. To read it, point your browser to:\n\nfile://$$(pwd)/docker/test/htmlcov/index.html"
test: build-test test-only

@ -0,0 +1,2 @@
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,28 +1,45 @@
# kompass
# jdav Kompass
This repository has the purpose to develop a webapplication that can be used by
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, ...
![Build Status](https://github.com/chrisflav/kompass/actions/workflows/build-docker.yml/badge.svg?branch=main)
# Docker
Kompass is an administration platform designed for local sections of the Young German Alpine Club. It provides
tools to contact and (automatically) manage members, groups, material, excursions and statements.
In the `docker` subfolder, there are `docker-compose.yaml`s for development and production use. For the development
version, no further setup is needed.
For more details on the features, see the (German) [documentation](https://jdav-hd.de/static/docs/index.html).
# Production
If you are interested in using the Kompass in your own local section, please get in touch via
email at `name of this project`@`merten.dev`. We are very happy to discuss how the Kompass can be used in
your setting.
In production, the docker setup needs an external database. The exact access credentials are configured in the respective
docker.env files.
# Contributing
# Useful stuff
Any form of contribution is appreciated. If you found a bug or have a feature request, please file an
[issue](https://github.com/chrisflav/kompass/issues). If you want to help with the documentation or
want to contribute code, please open a [pull request](https://github.com/chrisflav/kompass/pulls).
## Reset database for certain app
If you don't have a github account or don't want to open an issue or pull request here, there is
also a [Gitea repository](https://git.jdav-hd.merten.dev/digitales/kompass).
The following can be useful in case that automatic migrations throw errors.
The following is a short description of where to find the documentation with more information.
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'
3. while at the MySQL console, drop all of the tables associated with my_app.
4. re-run ./manage.py makemigrations my_app - this generates a 0001_initial.py file in my migrations folder.
5. run ./manage migrate my_app - I expect this command to re-build all my tables, but instead it says: "No migrations to apply."
# Documentation
Documentation is handled by [sphinx](https://www.sphinx-doc.org/) and located in `docs/`.
The sphinx documentation contains information about:
- Development Setup
- Architecture
- 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.

@ -0,0 +1,66 @@
[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'

@ -0,0 +1,86 @@
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-bullseye
FROM python:3.9-bookworm
# install additional dependencies
RUN apt-get update && apt-get install -y gettext texlive texlive-fonts-extra
RUN apt-get update && apt-get install -y gettext texlive texlive-fonts-extra pandoc
WORKDIR /app

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

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

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

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

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

@ -7,10 +7,16 @@ cd /app
if ! [ -f completed_initial_run ]; then
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 compilemessages --locale de
python jdav_web/manage.py migrate
python jdav_web/manage.py ensuresuperuser
touch completed_initial_run
fi

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

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

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

@ -0,0 +1,34 @@
[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']

@ -0,0 +1,12 @@
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,15 +7,20 @@ services:
context: ./../../
dockerfile: docker/test/Dockerfile
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:
- redis
- cache
- db
entrypoint: /app/docker/test/entrypoint-master.sh
volumes:
- ./config:/app/config:ro
- type: bind
source: ./coverage.xml
target: /app/jdav_web/coverage.xml
source: ./htmlcov/
target: /app/jdav_web/htmlcov/
cache:
restart: always

@ -1,28 +1,4 @@
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_PASSWORD='password'
MYSQL_USER='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,5 +38,11 @@ fi
cd jdav_web
coverage run manage.py test startpage finance members -v 2
coverage xml
if [[ "$DJANGO_TEST_KEEPDB" == 1 ]]; then
coverage run manage.py test startpage finance members contrib logindata mailer material ludwigsburgalpin jdav_web -v 2 --noinput --keepdb
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

@ -0,0 +1,20 @@
# 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)

@ -0,0 +1,35 @@
@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

@ -0,0 +1,40 @@
<?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>

After

Width:  |  Height:  |  Size: 1.6 KiB

@ -0,0 +1,20 @@
: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

@ -0,0 +1,63 @@
# 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)

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

@ -0,0 +1,85 @@
.. _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

@ -0,0 +1,290 @@
.. _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

@ -0,0 +1,42 @@
.. _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>`

@ -0,0 +1,101 @@
.. _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.

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

@ -0,0 +1,42 @@
.. 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

@ -0,0 +1,55 @@
.. _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/

@ -0,0 +1,11 @@
.. _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.

@ -0,0 +1,78 @@
.. _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.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

@ -0,0 +1,50 @@
.. _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.

@ -0,0 +1,178 @@
.. _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/

@ -0,0 +1,172 @@
.. _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

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

@ -12,18 +12,58 @@ import rules.contrib.admin
from rules.permissions import perm_exists
def decorate_admin_view(model, perm=None):
"""
Decorator for wrapping admin views.
"""
def decorator(fun):
def aux(self, request, object_id):
try:
obj = model.objects.get(pk=object_id)
except model.DoesNotExist:
messages.error(request, _('%(modelname)s not found.') % {'modelname': self.opts.verbose_name})
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
permitted = self.has_change_permission(request, obj) if not perm else request.user.has_perm(perm)
if not permitted:
messages.error(request, _('Insufficient permissions.'))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
return fun(self, request, obj)
return aux
return decorator
class FieldPermissionsAdminMixin:
field_permissions = {}
field_change_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):
fields = super(FieldPermissionsAdminMixin, self).get_fields(request, obj)
return [fd for fd in fields if self.may_view_field(fd, request, obj)]
def may_field(field):
if field not in self.field_permissions:
return True
return request.user.has_perm(self.field_permissions[field], obj)
return list(filter(may_field, fields))
def get_readonly_fields(self, request, obj=None):
readonly_fields = super(FieldPermissionsAdminMixin, self).get_readonly_fields(request, obj)
return list(readonly_fields) +\
[fd for fd, perm in self.field_change_permissions.items() if not request.user.has_perm(perm)]
class ChangeViewAdminMixin:
@ -136,12 +176,12 @@ class CommonAdminMixin(FieldPermissionsAdminMixin, ChangeViewAdminMixin, Filtere
# extra HTML -- the "add other" interface -- to the end of the
# rendered output. formfield can be None if it came from a
# OneToOneField with parent_link=True or a M2M intermediary.
if formfield and db_field.name not in self.raw_id_fields:
formfield.widget = widgets.RelatedFieldWidgetWrapper(
formfield.widget,
db_field.remote_field,
self.admin_site,
)
#if formfield and db_field.name not in self.raw_id_fields:
# formfield.widget = widgets.RelatedFieldWidgetWrapper(
# formfield.widget,
# db_field.remote_field,
# self.admin_site,
# )
return formfield

@ -0,0 +1,28 @@
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.')
)

@ -0,0 +1,42 @@
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())

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

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

@ -1,5 +1,8 @@
import logging
from django.contrib import admin, messages
from django.forms import Textarea
from django.utils.safestring import mark_safe
from django import forms
from django.forms import Textarea, ClearableFileInput
from django.http import HttpResponse, HttpResponseRedirect
from django.db.models import TextField, Q
from django.urls import path, reverse
@ -9,46 +12,108 @@ from django.shortcuts import render
from django.conf import settings
from contrib.admin import CommonAdminInlineMixin, CommonAdminMixin
from utils import get_member, RestrictedFileField
from rules.contrib.admin import ObjectPermissionsModelAdmin
from members.pdf import render_tex_with_attachments
from .models import Ledger, Statement, Receipt, Transaction, Bill, StatementSubmitted, StatementConfirmed,\
StatementUnSubmitted, BillOnStatementProxy
logger = logging.getLogger(__name__)
@admin.register(Ledger)
class LedgerAdmin(admin.ModelAdmin):
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):
model = BillOnStatementProxy
extra = 0
sortable_options = []
fields = ['short_description', 'explanation', 'amount', 'paid_by', 'proof']
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40})}
}
@admin.register(StatementUnSubmitted)
class StatementUnSubmittedAdmin(CommonAdminMixin, admin.ModelAdmin):
fields = ['short_description', 'explanation', 'excursion', 'submitted']
list_display = ['__str__', 'excursion', 'created_by']
form = BillOnStatementInlineForm
def decorate_statement_view(model, perm=None):
def decorator(fun):
def aux(self, request, object_id):
try:
statement = model.objects.get(pk=object_id)
except model.DoesNotExist:
messages.error(request, _('Statement not found.'))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
permitted = self.has_change_permission(request, statement) if not perm else request.user.has_perm(perm)
if not permitted:
messages.error(request, _('Insufficient permissions.'))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
return fun(self, request, statement)
return aux
return decorator
@admin.register(Statement)
class StatementAdmin(CommonAdminMixin, admin.ModelAdmin):
fields = ['short_description', 'explanation', 'excursion', 'status']
list_display = ['__str__', 'total_pretty', 'created_by', 'submitted_date', 'status_badge']
list_filter = ['status']
search_fields = ('excursion__name', 'short_description')
ordering = ['-submitted_date']
inlines = [BillOnStatementInline]
list_per_page = 25
def has_change_permission(self, request, obj=None):
if obj is None:
return super().has_change_permission(request)
if obj.confirmed:
# Confirmed statements may not be changed (they should be unconfirmed first)
return False
return super().has_change_permission(request, obj)
def has_delete_permission(self, request, obj=None):
if obj is None or obj.submitted:
# Submitted statements may not be deleted (they should be rejected first)
return False
return super().has_delete_permission(request, obj)
def save_model(self, request, obj, form, change):
if not change and hasattr(request.user, 'member'):
obj.created_by = request.user.member
super().save_model(request, obj, form, change)
def get_fields(self, request, obj=None):
if obj is not None and obj.excursion:
# if the object exists and an excursion is set, show the excursion (read only)
# instead of the short description
return ['excursion', 'explanation', 'status']
else:
# if the object is newly created or no excursion is set, require
# a short description
return ['short_description', 'explanation', 'status']
def get_readonly_fields(self, request, obj=None):
readonly_fields = ['submitted', 'excursion']
readonly_fields = ['status', 'excursion']
if obj is not None and obj.submitted:
return readonly_fields + self.fields
else:
return readonly_fields
def get_inlines(self, request, obj=None):
if obj is None or not obj.submitted:
return [BillOnStatementInline]
else:
return [BillOnSubmittedStatementInline, TransactionOnSubmittedStatementInline]
def get_urls(self):
urls = super().get_urls()
@ -65,12 +130,33 @@ class StatementUnSubmittedAdmin(CommonAdminMixin, admin.ModelAdmin):
wrap(self.submit_view),
name="%s_%s_submit" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/overview/",
wrap(self.overview_view),
name="%s_%s_overview" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/reduce_transactions/",
wrap(self.reduce_transactions_view),
name="%s_%s_reduce_transactions" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/unconfirm/",
wrap(self.unconfirm_view),
name="%s_%s_unconfirm" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/summary/",
wrap(self.statement_summary_view),
name="%s_%s_summary" % (self.opts.app_label, self.opts.model_name),
),
]
return custom_urls + urls
def submit_view(self, request, object_id):
statement = Statement.objects.get(pk=object_id)
if statement.submitted:
@decorate_statement_view(StatementUnSubmitted)
def submit_view(self, request, statement):
if statement.submitted: # pragma: no cover
logger.error(f"submit_view reached with submitted statement {statement}. This should not happen.")
messages.error(request,
_("%(name)s is already submitted.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
@ -80,94 +166,51 @@ class StatementUnSubmittedAdmin(CommonAdminMixin, admin.ModelAdmin):
messages.success(request,
_("Successfully submited %(name)s. The finance department will notify the requestors as soon as possible.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
context = dict(self.admin_site.each_context(request),
title=_('Submit statement'),
opts=self.opts,
statement=statement)
return render(request, 'admin/submit_statement.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
if statement.excursion:
memberlist = statement.excursion
context = dict(self.admin_site.each_context(request),
title=_('Finance overview'),
opts=self.opts,
memberlist=memberlist,
object=memberlist,
ljp_contributions=memberlist.payable_ljp_contributions,
total_relative_costs=memberlist.total_relative_costs,
**memberlist.statement.template_context())
return render(request, 'admin/freizeit_finance_overview.html', context=context)
else:
return readonly_fields
def get_urls(self):
urls = super().get_urls()
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
wrapper.model_admin = self
return update_wrapper(wrapper, view)
custom_urls = [
path(
"<path:object_id>/overview/",
wrap(self.overview_view),
name="%s_%s_overview" % (self.opts.app_label, self.opts.model_name),
),
path(
"<path:object_id>/reduce_transactions/",
wrap(self.reduce_transactions_view),
name="%s_%s_reduce_transactions" % (self.opts.app_label, self.opts.model_name),
),
]
return custom_urls + urls
def overview_view(self, request, object_id):
statement = StatementSubmitted.objects.get(pk=object_id)
if not statement.submitted:
context = dict(self.admin_site.each_context(request),
title=_('Submit statement'),
opts=self.opts,
statement=statement)
return render(request, 'admin/submit_statement.html', context=context)
@decorate_statement_view(StatementSubmitted)
def overview_view(self, request, statement):
if not statement.submitted: # pragma: no cover
logger.error(f"overview_view reached with unsubmitted statement {statement}. This should not happen.")
messages.error(request,
_("%(name)s is not yet submitted.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
if "transaction_execution_confirm" in request.POST:
if "transaction_execution_confirm" in request.POST or "transaction_execution_confirm_and_send" in request.POST:
res = statement.confirm(confirmer=get_member(request))
if not res:
if not res: # pragma: no cover
# this should NOT happen!
logger.error(f"Error occured while confirming {statement}, this should not be possible.")
messages.error(request,
_("An error occured while trying to confirm %(name)s. Please try again.") % {'name': str(statement)})
return HttpResponseRedirect(reverse('admin:%s_%s_overview' % (self.opts.app_label, self.opts.model_name)))
if "transaction_execution_confirm_and_send" in request.POST:
statement.send_summary(cc=[request.user.member.email] if hasattr(request.user, 'member') else [])
messages.success(request, _("Successfully sent receipt to the office."))
messages.success(request,
_("Successfully confirmed %(name)s. I hope you executed the associated transactions, I wont remind you again.")
% {'name': str(statement)})
download_link = reverse('admin:%s_%s_summary' % (self.opts.app_label, self.opts.model_name),
args=(statement.pk,))
messages.success(request,
mark_safe(_("You can download a <a href='%(link)s', target='_blank'>receipt</a>.") % {'link': download_link}))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.model_name)))
if "confirm" in request.POST:
res = statement.validity
@ -187,10 +230,21 @@ class StatementSubmittedAdmin(admin.ModelAdmin):
_("Some transactions have no ledger configured. Please fill in the gaps.")
% {'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_changelist' % (self.opts.app_label, self.opts.model_name)))
elif res == Statement.INVALID_ALLOWANCE_TO:
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:
statement.submitted = False
statement.status = Statement.UNSUBMITTED
statement.save()
messages.success(request,
_("Successfully rejected %(name)s. The requestor can reapply, when needed.")
@ -202,57 +256,111 @@ class StatementSubmittedAdmin(admin.ModelAdmin):
messages.error(request,
_("%(name)s already has transactions. Please delete them first, if you want to generate new ones") % {'name': str(statement)})
else:
statement.generate_transactions()
messages.success(request,
_("Successfully generated transactions for %(name)s") % {'name': str(statement)})
success = statement.generate_transactions()
if success:
messages.success(request,
_("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,)))
context = dict(self.admin_site.each_context(request),
title=_('View submitted statement'),
opts=self.opts,
statement=statement,
settings=settings,
transaction_issues=statement.transaction_issues,
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)
**statement.template_context())
return render(request, 'admin/overview_submitted_statement.html', context=context)
def reduce_transactions_view(self, request, object_id):
statement = StatementSubmitted.objects.get(pk=object_id)
@decorate_statement_view(StatementSubmitted)
def reduce_transactions_view(self, request, statement):
statement.reduce_transactions()
messages.success(request,
_("Successfully reduced transactions for %(name)s.") % {'name': str(statement)})
return HttpResponseRedirect(request.GET['redirectTo'])
#return HttpResponseRedirect(reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(statement.pk,)))
@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()
@admin.register(StatementConfirmed)
class StatementConfirmedAdmin(admin.ModelAdmin):
fields = ['short_description', 'explanation', 'excursion', 'confirmed']
#readonly_fields = fields
list_display = ['__str__', 'total_pretty', 'confirmed_date', 'confirmed_by']
ordering = ('-confirmed_date',)
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)))
def has_add_permission(self, request, obj=None):
return False
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
text_length_warning.short_description = _("Length")
class BillOnSubmittedStatementInline(BillOnStatementInline):
model = BillOnStatementProxy
extra = 0
sortable_options = []
fields = ['short_description', 'explanation', 'amount', 'paid_by', 'proof', 'costs_covered']
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40})}
}
def get_readonly_fields(self, request, obj=None):
return ['short_description', 'explanation', 'amount', 'paid_by', 'proof']
@admin.register(Transaction)
class TransactionAdmin(admin.ModelAdmin):
"""The transaction admin site. This is only used to display transactions. All editing
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',
'confirmed_date', 'confirmed_by']
list_filter = ('ledger', 'member', 'statement', 'confirmed')
@ -264,16 +372,21 @@ class TransactionAdmin(admin.ModelAdmin):
return self.fields
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)
class BillAdmin(admin.ModelAdmin):
list_display = ['__str__', 'statement', 'short_description', 'pretty_amount', 'paid_by', 'refunded']
list_display = ['__str__', 'statement', 'explanation', 'pretty_amount', 'paid_by', 'refunded']
list_filter = ('statement', 'paid_by', 'refunded')
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 ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-03-20 18:48+0100\n"
"POT-Creation-Date: 2025-10-16 23:09+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@ -18,12 +18,20 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: finance/admin.py:69
#: finance/admin.py finance/tests/admin.py
msgid "Statement not found."
msgstr "Abrechnung nicht gefunden."
#: finance/admin.py finance/tests/admin.py
msgid "Insufficient permissions."
msgstr "Unzureichende Berechtigungen."
#: finance/admin.py
#, python-format
msgid "%(name)s is already submitted."
msgstr "%(name)s ist bereits eingereicht."
#: finance/admin.py:75
#: finance/admin.py finance/tests/admin.py
#, python-format
msgid ""
"Successfully submited %(name)s. The finance department will notify the "
@ -32,23 +40,31 @@ msgstr ""
"Rechnung %(name)s erfolgreich eingereicht. Das Finanzreferat wird auf dich "
"sobald wie möglich zukommen."
#: finance/admin.py:78
#: finance/admin.py finance/tests/admin.py
msgid "Finance overview"
msgstr "Kostenübersicht"
#: finance/admin.py finance/tests/admin.py
msgid "Submit statement"
msgstr "Rechnung einreichen"
#: finance/admin.py:152
#: finance/admin.py
#, python-format
msgid "%(name)s is not yet submitted."
msgstr "%(name)s ist noch nicht eingereicht."
#: finance/admin.py:159
#: finance/admin.py
#, python-format
msgid "An error occured while trying to confirm %(name)s. Please try again."
msgstr ""
"Beim Abwickeln von %(name)s ist ein Fehler aufgetreten. Bitte versuche es "
"erneut."
#: finance/admin.py:163
#: finance/admin.py finance/tests/admin.py
msgid "Successfully sent receipt to the office."
msgstr "Abrechnungsbeleg an die Geschäftsstelle gesendet."
#: finance/admin.py finance/tests/admin.py
#, python-format
msgid ""
"Successfully confirmed %(name)s. I hope you executed the associated "
@ -57,11 +73,18 @@ msgstr ""
"Erfolgreich %(name)s abgewickelt. Ich hoffe du hast die zugehörigen "
"Überweisungen ausgeführt, ich werde dich nicht nochmal erinnern."
#: finance/admin.py:170
#: finance/admin.py
#, python-format
msgid "You can download a <a href='%(link)s', target='_blank'>receipt</a>."
msgstr ""
"Hier kannst du den Abrechnungsbeleg <a href='%(link)s', "
"target='_blank'>herunterladen</a>."
#: finance/admin.py finance/tests/admin.py
msgid "Statement confirmed"
msgstr "Abrechnung abgewickelt"
#: finance/admin.py:176
#: finance/admin.py finance/tests/admin.py
msgid ""
"Transactions do not match the covered expenses. Please correct the mistakes "
"listed below."
@ -69,19 +92,35 @@ msgstr ""
"Überweisungen stimmen nicht mit den übernommenen Kosten überein. Bitte "
"korrigiere die unten aufgeführten Fehler."
#: finance/admin.py:181
#: finance/admin.py finance/tests/admin.py
msgid "Some transactions have no ledger configured. Please fill in the gaps."
msgstr ""
"Manche Überweisungen haben kein Geldtopf eingestellt. Bitte trage das nach."
#: finance/admin.py:190
#: finance/admin.py finance/tests/admin.py
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
msgid "Successfully rejected %(name)s. The requestor can reapply, when needed."
msgstr ""
"Die Rechnung %(name)s wurde abgelehnt. Die Person kann die Rechnung erneut "
"einstellen, wenn es benötigt wird."
#: finance/admin.py:197
#: finance/admin.py finance/tests/admin.py
#, python-format
msgid ""
"%(name)s already has transactions. Please delete them first, if you want to "
@ -90,198 +129,296 @@ msgstr ""
"%(name)s hat bereits Überweisungen. Bitte lösche diese zunächst, bevor du "
"neue generierst."
#: finance/admin.py:201
#: finance/admin.py finance/tests/admin.py
#, python-format
msgid "Successfully generated transactions for %(name)s"
msgstr "Automatisch Überweisungsträger für %(name)s generiert."
#: finance/admin.py:204
#: finance/admin.py finance/tests/admin.py
#, 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"
msgstr "Eingereichte Abrechnung einsehen"
#: finance/admin.py:230
#: finance/admin.py finance/tests/admin.py
#, python-format
msgid "Successfully reduced transactions for %(name)s."
msgstr "Überweisungsträger für %(name)s minimiert."
#: finance/apps.py:8
#: finance/admin.py
#, 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"
msgstr "Finanzen"
#: finance/models.py:13
#: finance/models.py
msgid "Name"
msgstr "Name"
#: finance/models.py:19 finance/models.py:372 finance/models.py:396
#: finance/templates/admin/confirmed_statement.html:38
#: finance/templates/admin/overview_submitted_statement.html:100
#: finance/models.py finance/templates/admin/confirmed_statement.html
#: finance/templates/admin/overview_submitted_statement.html
msgid "Ledger"
msgstr "Geldtopf"
#: finance/models.py:20
#: finance/models.py
msgid "Ledgers"
msgstr "Geldtöpfe"
#: finance/models.py:42 finance/models.py:343 finance/models.py:395
#: finance/models.py
msgid "In preparation"
msgstr "In Vorbereitung"
#: finance/models.py
msgid "Submitted"
msgstr "Eingereicht"
#: finance/models.py
msgid "Completed"
msgstr "Abgewickelt"
#: finance/models.py
msgid "Short description"
msgstr "Kurzbeschreibung"
#: finance/models.py:45 finance/models.py:344
#: finance/models.py finance/templates/admin/submit_statement.html
msgid "Explanation"
msgstr "Erklärung"
#: finance/models.py:47
#: finance/models.py
msgid "Associated excursion"
msgstr "Zugehörige Freizeit"
msgstr "Zugehörige Ausfahrt"
#: 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:52
#: finance/models.py
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"
msgstr "Preis pro Nacht"
#: finance/models.py:54
msgid "Submitted"
msgstr "Eingericht"
#: finance/models.py
msgid "Status"
msgstr "Status"
#: finance/models.py:55
#: finance/models.py
msgid "Submitted on"
msgstr "Eingereicht am"
#: finance/models.py:56
msgid "Confirmed"
msgstr "Abgewickelt"
#: finance/models.py:57 finance/models.py:379
#: finance/models.py
msgid "Paid on"
msgstr "Bezahlt am"
#: finance/models.py:59
#: finance/models.py
msgid "Created by"
msgstr "Erstellt von"
#: finance/models.py
msgid "Submitted by"
msgstr "Eingereicht bei"
msgstr "Eingereicht von"
#: finance/models.py:64 finance/models.py:380
#: finance/models.py
msgid "Authorized by"
msgstr "Autorisiert von"
#: finance/models.py:71 finance/models.py:342 finance/models.py:375
#: finance/models.py
msgid "Statement"
msgstr "Abrechnung"
#: finance/models.py:72
#: finance/models.py
msgid "Statements"
msgstr "Abrechnungen"
#: finance/models.py:77
#: finance/models.py
#, python-format
msgid "Statement: %(excursion)s"
msgstr "Abrechnung: %(excursion)s"
msgid "Excursion %(excursion)s"
msgstr "Ausfahrt %(excursion)s"
#: finance/models.py:123
#: finance/models.py
msgid "Ready to confirm"
msgstr "Bereit zur Abwicklung"
#: finance/models.py:162
#: finance/models.py
#, python-format
msgid "Compensation for %(excu)s"
msgstr "Entschädigung für %(excu)s"
msgid "Allowance for %(excu)s"
msgstr "Aufwandsentschädigung für %(excu)s"
#: finance/models.py:294
#: finance/templates/admin/overview_submitted_statement.html:78
#: finance/models.py
#, python-format
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"
msgstr "Gesamtbetrag"
#: finance/models.py:307
#: finance/models.py
#, python-format
msgid "Statement summary for %(title)s"
msgstr "Abrechnung für %(title)s"
#: finance/models.py
msgid "Statement in preparation"
msgstr "Abrechnung in Vorbereitung"
#: finance/models.py:308
#: finance/models.py
msgid "Statements in preparation"
msgstr "Abrechnungen in Vorbereitung"
#: finance/models.py:321
#: finance/models.py
msgid "Submitted statement"
msgstr "Eingereichte Abrechnung"
#: finance/models.py:322
#: finance/models.py
msgid "Submitted statements"
msgstr "Eingereichte Abrechnungen"
#: finance/models.py:336
#: finance/models.py
msgid "Paid statement"
msgstr "Bezahlte Abrechnung"
#: finance/models.py:337
#: finance/models.py
msgid "Paid statements"
msgstr "Bezahlte Abrechnungen"
#: finance/models.py:347
#: finance/models.py finance/templates/admin/confirmed_statement.html
#: 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"
msgstr "Bezahlt von"
#: finance/models.py:349
#: finance/models.py
msgid "Covered"
msgstr "Übernommen"
#: finance/models.py:350
#: finance/models.py
msgid "Refunded"
msgstr "Ausgezahlt"
#: finance/models.py:352
#: finance/models.py
msgid "Proof"
msgstr "Beleg"
#: 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
#: finance/models.py
msgid "Bill"
msgstr "Quittung"
msgstr "Ausgabe"
#: finance/models.py:364
#: finance/templates/admin/overview_submitted_statement.html:26
#: finance/models.py finance/templates/admin/overview_submitted_statement.html
msgid "Bills"
msgstr "Quittungen"
msgstr "Ausgaben"
#: finance/models.py:368 finance/templates/admin/confirmed_statement.html:37
#: finance/templates/admin/overview_submitted_statement.html:99
#: finance/models.py finance/templates/admin/confirmed_statement.html
#: finance/templates/admin/overview_submitted_statement.html
msgid "Reference"
msgstr "Verwendungszweck"
#: finance/models.py:370
#: finance/models.py
msgid "Recipient"
msgstr "Empfänger"
#: finance/models.py:378
#: finance/models.py
msgid "Paid"
msgstr "Bezahlt"
#: finance/models.py:390
#: finance/models.py
msgid "Transaction"
msgstr "Überweisung"
#: finance/models.py:391
#: finance/templates/admin/overview_submitted_statement.html:84
#: finance/models.py finance/templates/admin/overview_submitted_statement.html
msgid "Transactions"
msgstr "Überweisungen"
#: finance/templates/admin/confirmed_statement.html:17
#: finance/templates/admin/overview_submitted_statement.html:17
#: finance/templates/admin/submit_statement.html:17
#: finance/templates/admin/confirmed_statement.html
#: finance/templates/admin/overview_submitted_statement.html
#: finance/templates/admin/submit_statement.html
#: finance/templates/admin/unconfirm_statement.html
msgid "Home"
msgstr "Start"
#: finance/templates/admin/confirmed_statement.html:21
#: finance/templates/admin/confirmed_statement.html
msgid "Paiment"
msgstr "Bezahlung"
#: finance/templates/admin/confirmed_statement.html:26
#: finance/templates/admin/confirmed_statement.html
msgid "Paying statement"
msgstr "Rechnung bezahlen"
#: finance/templates/admin/confirmed_statement.html:29
#: finance/templates/admin/confirmed_statement.html
msgid ""
"The statement is valid. Please execute the following transactions and then "
"proceed by finalizing the confirmation."
@ -289,43 +426,64 @@ msgstr ""
"Die Abrechnung ist gültig. Bitte führe die folgenden Überweisungen aus und "
"fahre dann fort, indem du die Abwicklung bestätigst."
#: finance/templates/admin/confirmed_statement.html:35
#: finance/templates/admin/confirmed_statement.html
msgid "IBAN"
msgstr "IBAN"
#: finance/templates/admin/confirmed_statement.html:66
#: finance/templates/admin/confirmed_statement.html
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."
msgstr "Ich habe die aufgeführten Überweisungen ausgeführt."
#: finance/templates/admin/confirmed_statement.html:68
msgid "Confirm"
msgstr "Bestätigen"
#: finance/templates/admin/confirmed_statement.html
msgid "Confirm only"
msgstr "Nur bestätigen"
#: finance/templates/admin/confirmed_statement.html
msgid "Confirm and send receipt to office"
msgstr "Bestätigen und Beleg an die Geschäftsstelle senden"
#: finance/templates/admin/overview_submitted_statement.html:21
#: finance/templates/admin/overview_submitted_statement.html
msgid "Overview"
msgstr "Übersicht"
#: finance/templates/admin/overview_submitted_statement.html:32
#: finance/templates/admin/overview_submitted_statement.html
msgid "Covered by association"
msgstr "Vom Verein übernommen"
#: finance/templates/admin/overview_submitted_statement.html:50
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid "The total amount is %(total_bills)s €."
msgstr "Der Gesamtbetrag beträgt %(total_bills)s €."
#: finance/templates/admin/overview_submitted_statement.html:54
#: finance/templates/admin/overview_submitted_statement.html
msgid "Excursion"
msgstr "Freizeit"
msgstr "Ausfahrt"
#: finance/templates/admin/overview_submitted_statement.html:57
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid "This excursion featured %(staff_count)s youth leader(s), each costing"
msgstr ""
"Diese Freizeit hatte %(staff_count)s Jugendleiter:innen. Auf jede:n "
"entfallen die folgenden Kosten:"
"Diese Ausfahrt hatte %(staff_count)s genehmigte Jugendleiter*innen. Für "
"jede*n besteht ein Anspruch auf folgende Zuschüsse und "
"Aufwandsentschädigungen:"
#: finance/templates/admin/overview_submitted_statement.html:62
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
"%(nights)s nights for %(price_per_night)s€ per night making a total of "
@ -334,7 +492,7 @@ msgstr ""
"%(nights)s Nächte zum Preis von %(price_per_night)s€ pro Nacht. Das ergibt "
"eine Gesamtsumme von %(nights_per_yl)s€."
#: finance/templates/admin/overview_submitted_statement.html:65
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
"%(duration)s days for %(allowance_per_day)s€ per day making a total of "
@ -343,7 +501,7 @@ msgstr ""
"%(duration)s Tage für %(allowance_per_day)s€ pro Tag. Das ergibt eine "
"Gesamtsumme von %(allowance_per_yl)s€."
#: finance/templates/admin/overview_submitted_statement.html:68
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
"%(kilometers_traveled)s km by %(means_of_transport)s (%(euro_per_km)s € / "
@ -352,21 +510,128 @@ msgstr ""
"%(kilometers_traveled)s km mit %(means_of_transport)s (%(euro_per_km)s€ / "
"km). Das ergibt eine Gesamtsumme von %(transportation_per_yl)s€."
#: finance/templates/admin/overview_submitted_statement.html:73
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
"In total this is %(total_per_yl)s€ times %(staff_count)s, giving "
"%(total_staff)s€."
"%(theoretical_total_staff)s€."
msgstr ""
"Insgesamt sind das Kosten von %(total_per_yl)s€ mal %(staff_count)s, "
"insgesamt also %(total_staff)s€."
"insgesamt also maximal %(theoretical_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:81
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
"Since overaged people where part of the excursion, an organisational fee of "
"%(org_fee)s€ per person per day has to be paid. This totals to "
"%(total_org_fee_theoretical)s€. This organisational fee will be accounted "
"against allowances and subsidies."
msgstr ""
"Da Personen über 27 an der Ausfahrt teilnehommen haben, wird ein "
"Organisationsbeitrag von %(org_fee)s€ pro Person und Tag fällig. Der "
"Gesamtbetrag von %(total_org_fee_theoretical)s€ wird mit Zuschüssen und "
"Aufwandsentschädigungen verrechnet."
#: finance/templates/admin/overview_submitted_statement.html
msgid "LJP contributions"
msgstr "LJP-Zuschüsse"
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid ""
" The youth leaders have documented interventions worth of "
"%(total_seminar_days)s seminar \n"
"days for %(participant_count)s eligible participants. Taking into account "
"the maximum contribution quota \n"
"of 90%% and possible taxes (%(ljp_tax)s%%), this results in a total of "
"%(paid_ljp_contributions)s€. \n"
"Once their proposal was approved, the ljp contributions of should be paid to:"
msgstr ""
"Jugendleiter*innen haben Lerneinheiten für insgesamt %(total_seminar_days)s "
"Seminartage und für %(participant_count)s Teilnehmende dokumentiert. Unter "
"Einbezug der maximalen Förderquote von 90%% und möglichen Steuern "
"(%(ljp_tax)s%%), ergibt sich ein auszuzahlender Betrag von "
"%(paid_ljp_contributions)s€. Sobald der LJP-Antrag geprüft ist, können LJP-"
"Zuschüsse ausbezahlt werden an:"
#: finance/templates/admin/overview_submitted_statement.html
msgid "Summary"
msgstr "Zusammenfassung"
#: finance/templates/admin/overview_submitted_statement.html
msgid "Covered bills"
msgstr "Übernommene Ausgaben"
#: finance/templates/admin/overview_submitted_statement.html
msgid "Allowance"
msgstr "Aufwandsentschädigung"
#: finance/templates/admin/overview_submitted_statement.html
msgid "Contributions by the association"
msgstr "Sektionszuschüsse"
#: finance/templates/admin/overview_submitted_statement.html
msgid "ljp contributions"
msgstr "LJP-Zuschüsse"
#: finance/templates/admin/overview_submitted_statement.html
#, python-format
msgid "This results in a total amount of %(total)s€"
msgstr "Das resultiert in einem Gesamtbetrag von %(total)s€"
#: finance/templates/admin/overview_submitted_statement.html:87
#: finance/templates/admin/overview_submitted_statement.html
msgid ""
"Currently, no transactions are planned. You can auto generate them from the "
"data, by clicking the following button."
@ -374,19 +639,19 @@ msgstr ""
"Aktuell sind keine Überweisungen vorgesehen. Du kannst die erforderlichen "
"durch Klicken auf den folgenden Knopf generieren."
#: finance/templates/admin/overview_submitted_statement.html:90
#: finance/templates/admin/overview_submitted_statement.html
msgid "Generate transactions"
msgstr "Erzeuge Überweisungsträger"
#: finance/templates/admin/overview_submitted_statement.html:94
#: finance/templates/admin/overview_submitted_statement.html
msgid "Currently the following transactions are planned."
msgstr "Aktuell sind die folgenden Überweisungen vorgesehen."
#: finance/templates/admin/overview_submitted_statement.html:137
#: finance/templates/admin/overview_submitted_statement.html
msgid "These transactions match the calculated costs."
msgstr "Diese Überweisungen stimmen mit den berechneten Kosten überein."
#: finance/templates/admin/overview_submitted_statement.html:140
#: finance/templates/admin/overview_submitted_statement.html
msgid ""
"The current transactions do not reflect all costs in this statement. Please "
"fix the following issues:"
@ -394,44 +659,72 @@ msgstr ""
"Die aktuell vorgesehenen Überweisungen stimmen nicht mit den berechneten "
"Kosten überein. Bitte korrigiere die folgenden Fehler:"
#: finance/templates/admin/overview_submitted_statement.html:145
#: finance/templates/admin/overview_submitted_statement.html
msgid "Currently receiving"
msgstr "Erhält aktuell"
#: finance/templates/admin/overview_submitted_statement.html:146
#: finance/templates/admin/overview_submitted_statement.html
msgid "Actual costs"
msgstr "Tatsächliche Kosten"
#: finance/templates/admin/overview_submitted_statement.html:147
#: finance/templates/admin/overview_submitted_statement.html
msgid "Difference"
msgstr "Differenz"
#: finance/templates/admin/overview_submitted_statement.html:174
#: finance/templates/admin/overview_submitted_statement.html
msgid "Accept"
msgstr "Annehmen"
#: finance/templates/admin/overview_submitted_statement.html:175
#: finance/templates/admin/overview_submitted_statement.html
msgid "Reject"
msgstr "Ablehnen"
#: finance/templates/admin/overview_submitted_statement.html:178
#: finance/templates/admin/submit_statement.html:35
#: finance/templates/admin/overview_submitted_statement.html
#: finance/templates/admin/submit_statement.html
#: finance/templates/admin/unconfirm_statement.html
msgid "Cancel"
msgstr "Abbruch"
#: finance/templates/admin/submit_statement.html:21
#: finance/templates/admin/submit_statement.html:34
#: finance/templates/admin/submit_statement.html
msgid "Submit"
msgstr "Einreichen"
#: finance/templates/admin/submit_statement.html:26
#: finance/templates/admin/submit_statement.html
msgid "Submit to the finance department"
msgstr "Beim Finanzreferat einreichen"
#: finance/templates/admin/submit_statement.html:28
#: finance/templates/admin/submit_statement.html
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 ""
"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."
msgstr ""
"Möchtest du die Abrechnung beim Finanzreferat einreichen? Wenn du "
"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."

@ -0,0 +1,18 @@
# 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'),
),
]

@ -0,0 +1,19 @@
# 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'),
),
]

@ -0,0 +1,26 @@
# 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'),
),
]

@ -0,0 +1,19 @@
# 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'),
),
]

@ -0,0 +1,25 @@
# 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'),
),
]

@ -0,0 +1,20 @@
# 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'),
),
]

@ -0,0 +1,39 @@
# 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),
]

@ -0,0 +1,21 @@
# 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',
),
]

@ -0,0 +1,28 @@
# 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,13 +5,23 @@ from django.utils import timezone
from .rules import is_creator, not_submitted, leads_excursion
from members.rules import is_leader, statement_not_submitted
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Sum
from django.utils.translation import gettext_lazy as _
from django.utils.html import format_html
from members.models import Member, Freizeit, OEFFENTLICHE_ANREISE, MUSKELKRAFT_ANREISE
from django.conf import settings
import rules
from contrib.models import CommonModel
from contrib.rules import has_global_perm
from utils import cvt_to_decimal, RestrictedFileField
from members.pdf import render_tex_with_attachments
from mailer.mailutils import send as send_mail
from contrib.media import media_path
from schwifty import IBAN
import re
# Create your models here.
@ -28,7 +38,7 @@ class Ledger(models.Model):
class TransactionIssue:
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
def difference(self):
@ -37,15 +47,22 @@ class TransactionIssue:
class StatementManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(submitted=False, confirmed=False)
return super().get_queryset().filter(status=Statement.UNSUBMITTED)
class Statement(CommonModel):
MISSING_LEDGER, NON_MATCHING_TRANSACTIONS, VALID = 0, 1, 2
MISSING_LEDGER, NON_MATCHING_TRANSACTIONS, INVALID_ALLOWANCE_TO, INVALID_TOTAL, VALID = 0, 1, 2, 3, 4
UNSUBMITTED, SUBMITTED, CONFIRMED = 0, 1, 2
STATUS_CHOICES = [(UNSUBMITTED, _('In preparation')),
(SUBMITTED, _('Submitted')),
(CONFIRMED, _('Completed'))]
STATUS_CSS_CLASS = { SUBMITTED: 'submitted',
CONFIRMED: 'confirmed',
UNSUBMITTED: 'unsubmitted' }
short_description = models.CharField(verbose_name=_('Short description'),
max_length=30,
blank=True)
blank=False)
explanation = models.TextField(verbose_name=_('Explanation'), blank=True)
excursion = models.OneToOneField(Freizeit, verbose_name=_('Associated excursion'),
@ -53,11 +70,30 @@ class Statement(CommonModel):
null=True,
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)
submitted = models.BooleanField(verbose_name=_('Submitted'), default=False)
status = models.IntegerField(verbose_name=_('Status'),
choices=STATUS_CHOICES,
default=UNSUBMITTED)
submitted_date = models.DateTimeField(verbose_name=_('Submitted on'), default=None, null=True)
confirmed = models.BooleanField(verbose_name=_('Confirmed'), default=False)
confirmed_date = models.DateTimeField(verbose_name=_('Paid on'), default=None, null=True)
created_by = models.ForeignKey(Member, verbose_name=_('Created by'),
@ -83,32 +119,74 @@ class Statement(CommonModel):
('may_edit_submitted_statements', 'Is allowed to edit submitted statements')
]
rules_permissions = {
# this is suboptimal, but Statement is only ever used as an inline on Freizeit
# so we check for excursion permissions
'add_obj': is_leader,
'view_obj': is_leader | has_global_perm('members.view_global_freizeit'),
'change_obj': is_leader & statement_not_submitted,
'delete_obj': is_leader & statement_not_submitted,
# All users may add draft statements.
'add_obj': rules.is_staff,
# All users may view their own statements and statements of excursions they are responsible for.
'view_obj': is_creator | leads_excursion | has_global_perm('finance.view_global_statement'),
# All users may change relevant (see above) draft statements.
'change_obj': (not_submitted & (is_creator | leads_excursion)) | has_global_perm('finance.change_global_statement'),
# All users may delete relevant (see above) draft statements.
'delete_obj': not_submitted & (is_creator | leads_excursion | has_global_perm('finance.delete_global_statement')),
}
def __str__(self):
@property
def title(self):
if self.excursion is not None:
return _('Statement: %(excursion)s') % {'excursion': str(self.excursion)}
return _('Excursion %(excursion)s') % {'excursion': str(self.excursion)}
else:
return self.short_description
def __str__(self):
return str(self.title)
@property
def submitted(self):
return self.status == Statement.SUBMITTED or self.status == Statement.CONFIRMED
@property
def confirmed(self):
return self.status == Statement.CONFIRMED
def status_badge(self):
code = Statement.STATUS_CSS_CLASS[self.status]
return format_html(f'<span class="statement-{code}">{Statement.STATUS_CHOICES[self.status][1]}</span>')
status_badge.short_description = _('Status')
status_badge.allow_tags = True
status_badge.admin_order_field = 'status'
def submit(self, submitter=None):
self.submitted = True
self.status = self.SUBMITTED
self.submitted_date = timezone.now()
self.submitted_by = submitter
self.save()
@property
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:
needed_paiments.extend([(yl, self.real_per_yl) for yl in self.excursion.jugendleiter.all()])
needed_paiments.extend([(yl, self.allowance_per_yl) for yl in self.allowance_to.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)
target = dict(map(lambda p: (p[0], sum([x[1] for x in p[1]])), groupby(needed_paiments, lambda p: p[0])))
@ -140,22 +218,65 @@ class Statement(CommonModel):
@property
def transactions_match_expenses(self):
"""Returns true iff there are no transaction issues."""
return len(self.transaction_issues) == 0
def is_valid(self):
return self.ledgers_configured and self.transactions_match_expenses
is_valid.boolean = True
is_valid.short_description = _('Ready to confirm')
@property
def allowance_to_valid(self):
"""Checks if the configured `allowance_to` field matches the regulations."""
if self.allowances_paid > self.real_staff_count:
# 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
def validity(self):
"""
Returns the validity status of the statement. This is one of:
- `Statement.VALID`:
Everything is correct.
- `Statement.NON_MATCHING_TRANSACTIONS`:
There is a transaction issue (in the sense of `transaction_issues`).
- `Statement.MISSING_LEDGER`:
At least one transaction has no ledger configured.
- `Statement.INVALID_ALLOWANCE_TO`:
The members receiving allowance don't match the regulations.
- `Statement.INVALID_TOTAL`:
The total amount of transactions differs from the calculated total payout.
"""
if not self.transactions_match_expenses:
return Statement.NON_MATCHING_TRANSACTIONS
if not self.ledgers_configured:
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:
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):
if not self.submitted:
return False
@ -163,7 +284,7 @@ class Statement(CommonModel):
if not self.validity == Statement.VALID:
return False
self.confirmed = True
self.status = self.CONFIRMED
self.confirmed_date = timezone.now()
self.confirmed_by = confirmer
for trans in self.transaction_set.all():
@ -179,16 +300,36 @@ class Statement(CommonModel):
for bill in self.bill_set.all():
if not bill.costs_covered:
continue
if not bill.paid_by:
return False
ref = "{}: {}".format(str(self), bill.short_description)
Transaction(statement=self, member=bill.paid_by, amount=bill.amount, confirmed=False, reference=ref).save()
# excursion specific
if self.excursion is None:
return
return True
# 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()
for yl in self.excursion.jugendleiter.all():
ref = _("Compensation for %(excu)s") % {'excu': self.excursion.name}
Transaction(statement=self, member=yl, amount=self.real_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:
ref = _("LJP-Contribution %(excu)s") % {'excu': self.excursion.name}
Transaction(statement=self, member=self.ljp_to, amount=self.paid_ljp_contributions,
confirmed=False, reference=ref).save()
return True
def reduce_transactions(self):
# to minimize the number of needed bank transactions, we bundle transactions from same ledger to
@ -207,7 +348,7 @@ class Statement(CommonModel):
continue
new_amount = sum((trans.amount for trans in grp))
new_ref = "\n".join((trans.reference for trans in grp))
new_ref = ", ".join((f"{trans.reference} EUR{trans.amount: .2f}" for trans in grp))
Transaction(statement=self, member=member, amount=new_amount, confirmed=False, reference=new_ref,
ledger=ledger).save()
for trans in grp:
@ -215,12 +356,27 @@ class Statement(CommonModel):
@property
def total_bills(self):
return sum([bill.amount for bill in self.bill_set.all() if bill.costs_covered])
return sum([bill.amount for bill in self.bills_covered])
@property
def bills_covered(self):
"""Returns the bills that are marked for reimbursement by the finance officer"""
return [bill for bill in self.bill_set.all() if bill.costs_covered]
@property
def bills_without_proof(self):
"""Returns the bills that lack a proof file"""
return [bill for bill in self.bill_set.all() if not bill.proof]
@property
def total_bills_theoretic(self):
return sum([bill.amount for bill in self.bill_set.all()])
@property
def total_bills_not_covered(self):
"""Returns the sum of bills that are not marked for reimbursement by the finance officer"""
return sum([bill.amount for bill in self.bill_set.all()]) - self.total_bills
@property
def euro_per_km(self):
if self.excursion is None:
@ -246,9 +402,13 @@ class Statement(CommonModel):
return cvt_to_decimal(self.excursion.duration * settings.ALLOWANCE_PER_DAY)
@property
def allowances_paid(self):
return self.allowance_to.count()
@property
def total_allowance(self):
return self.allowance_per_yl * self.real_staff_count
return self.allowance_per_yl * self.allowances_paid
@property
def total_transportation(self):
@ -280,12 +440,62 @@ class Statement(CommonModel):
if self.excursion is None:
return 0
return self.total_staff / self.excursion.staff_count
return cvt_to_decimal(self.total_staff / self.excursion.staff_count)
@property
def total_staff(self):
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
def total_staff(self):
"""
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
def real_staff_count(self):
if self.excursion is None:
@ -299,32 +509,135 @@ class Statement(CommonModel):
are refinanced though."""
if self.excursion is None:
return 0
#raw_staff_count = self.excursion.jugendleiter.count()
participant_count = self.excursion.participant_count
if participant_count < 4:
return 0
elif 4 <= participant_count <= 7:
return 2
else:
return 2 + math.ceil((participant_count - 7) / 7)
return self.excursion.approved_staff_count
@property
def paid_ljp_contributions(self):
if hasattr(self.excursion, 'ljpproposal') and self.ljp_to:
if self.excursion.theoretic_ljp_participant_count < 5:
return 0
return cvt_to_decimal(
min(
# if total costs are more than the max amount of the LJP contribution, we pay the max amount, reduced by taxes
(1-settings.LJP_TAX) * settings.LJP_CONTRIBUTION_PER_DAY * self.excursion.ljp_participant_count * self.excursion.ljp_duration,
# if the total costs are less than the max amount, we pay up to 90% of the total costs, reduced by taxes
(1-settings.LJP_TAX) * 0.9 * (float(self.total_bills_not_covered) + float(self.total_staff) ),
# we never pay more than the maximum costs of the trip
float(self.total_bills_not_covered)
)
)
else:
return 0
@property
def total(self):
return self.total_bills + self.total_staff
return self.total_bills + self.total_staff_paid + self.paid_ljp_contributions
@property
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):
return "{}".format(self.total)
total_pretty.short_description = _('Total')
total_pretty.admin_order_field = 'total'
def template_context(self):
context = {
'total_bills': self.total_bills,
'total_bills_theoretic': self.total_bills_theoretic,
'bills_covered': self.bills_covered,
'total': self.total,
}
if self.excursion:
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):
def get_queryset(self):
return super().get_queryset().filter(submitted=False, confirmed=False)
return super().get_queryset().filter(status=Statement.UNSUBMITTED)
class StatementUnSubmitted(Statement):
@ -344,7 +657,7 @@ class StatementUnSubmitted(Statement):
class StatementSubmittedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(submitted=True, confirmed=False)
return super().get_queryset().filter(status=Statement.SUBMITTED)
class StatementSubmitted(Statement):
@ -361,7 +674,7 @@ class StatementSubmitted(Statement):
class StatementConfirmedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(confirmed=True)
return super().get_queryset().filter(status=Statement.CONFIRMED)
class StatementConfirmed(Statement):
@ -378,16 +691,23 @@ class StatementConfirmed(Statement):
class Bill(CommonModel):
statement = models.ForeignKey(Statement, verbose_name=_('Statement'), on_delete=models.CASCADE)
short_description = models.CharField(verbose_name=_('Short description'), max_length=30)
short_description = models.CharField(verbose_name=_('Short description'), max_length=30, blank=False)
explanation = models.TextField(verbose_name=_('Explanation'), blank=True)
amount = models.DecimalField(max_digits=6, decimal_places=2, default=0)
amount = models.DecimalField(verbose_name=_('Amount'), max_digits=6, decimal_places=2, default=0)
paid_by = models.ForeignKey(Member, verbose_name=_('Paid by'), null=True,
on_delete=models.SET_NULL)
costs_covered = models.BooleanField(verbose_name=_('Covered'), default=False)
refunded = models.BooleanField(verbose_name=_('Refunded'), default=False)
proof = models.ImageField(_('Proof'), upload_to='bill_images', blank=True)
proof = RestrictedFileField(verbose_name=_('Proof'),
upload_to='bill_images',
blank=True,
max_upload_size=5,
content_types=['application/pdf',
'image/jpeg',
'image/png',
'image/gif'])
def __str__(self):
return "{} ({}€)".format(self.short_description, self.amount)
@ -452,6 +772,45 @@ class Transaction(models.Model):
def __str__(self):
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:
verbose_name = _('Transaction')
verbose_name_plural = _('Transactions')
@ -463,7 +822,3 @@ class Receipt(models.Model):
on_delete=models.CASCADE)
amount = models.DecimalField(max_digits=6, decimal_places=2)
comments = models.TextField()
def cvt_to_decimal(f):
return Decimal(f).quantize(Decimal('.01'), rounding=ROUND_HALF_DOWN)

@ -7,6 +7,8 @@
<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>
<script type="text/javascript" src="{% static "js/qrcode.js" %}"></script>
{% endblock %}
{% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} admin-view
@ -36,6 +38,7 @@
<td>{% trans "Amount" %}</td>
<td>{% trans "Reference" %}</td>
<td>{% trans "Ledger" %}</td>
<td>{% trans "QR Code" %}</td>
</th>
{% for transaction in statement.transaction_set.all %}
<tr>
@ -54,17 +57,60 @@
<td>
{{ transaction.ledger }}
</td>
<td>
<a href="#" data-text="{{ transaction.code }}">{% trans "Show" %}</a>
</td>
</tr>
{% endfor %}
</table>
</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">
{% csrf_token %}
<p>
<input type="checkbox" required>
{% blocktrans %}I did execute the listed transactions.{% endblocktrans %}
</p>
<input class="default confirm" type="submit" name="transaction_execution_confirm" value="{% translate 'Confirm' %}">
<input class="default confirm" type="submit" name="transaction_execution_confirm" value="{% translate 'Confirm only' %}">
<input class="default confirm" type="submit" name="transaction_execution_confirm_and_send" value="{% translate 'Confirm and send receipt to office' %}">
</form>
{% endblock %}

@ -1,5 +1,6 @@
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static %}
{% load overview_extras %}
{% block extrahead %}
{{ block.super }}
@ -40,7 +41,7 @@
{{ bill.amount }}€.
</td>
<td>
{{ bill.costs_covered }}
{{ bill.costs_covered|render_bool }}
</td>
</tr>
{% endfor %}
@ -70,12 +71,124 @@
</ul>
</p>
<p>
{% blocktrans %}In total this is {{ total_per_yl }}€ times {{ staff_count }}, giving {{ total_staff }}€.{% endblocktrans %}
{% blocktrans %}In total this is {{ total_per_yl }}€ times {{ staff_count }}, giving {{ theoretical_total_staff }}€.{% endblocktrans %}
</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 %}
<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>
{% blocktrans %}This results in a total amount of {{ total }}€{% endblocktrans %}

@ -1,5 +1,6 @@
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static %}
{% load overview_extras %}
{% block extrahead %}
{{ block.super }}
@ -24,6 +25,35 @@
{% block content %}
<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>
{% 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>

@ -0,0 +1,41 @@
{% 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 %}

@ -0,0 +1,146 @@
{% 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 %}

@ -1,185 +0,0 @@
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.')

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

@ -0,0 +1,713 @@
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, ())

@ -0,0 +1,70 @@
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')

@ -0,0 +1,659 @@
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)

@ -0,0 +1,102 @@
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)

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

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

@ -12,6 +12,42 @@ https://docs.djangoproject.com/en/1.10/ref/settings/
from split_settings.tools import optional, include
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 = [
'local.py',
@ -22,6 +58,8 @@ base_settings = [
'components/emails.py',
'components/texts.py',
'components/locale.py',
'components/logging.py',
'components/oauth.py',
]
include(*base_settings)

@ -1,27 +1,25 @@
deployed = '1' == os.environ.get('DJANGO_DEPLOY', '0')
deployed = get_var('django', 'deployed', default=False)
# 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__))))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY',
'6_ew6l1r9_4(8=p8quv(e8b+z+k+*wm7&zxx%mcnnec99a!lpw')
SECRET_KEY = get_var('django', 'secret_key', default='secret')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG', '1') == '1'
DEBUG = get_var('django', 'debug', default=True)
ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOST', '').split(",")
ALLOWED_HOSTS = get_var('django', 'allowed_hosts', default=["*"])
# hostname and base url
HOST = os.environ.get('DJANGO_ALLOWED_HOST', 'localhost:8000').split(",")[0]
PROTOCOL = os.environ.get('DJANGO_PROTOCOL', 'https')
BASE_URL = os.environ.get('DJANGO_BASE_URL', HOST)
HOST = get_var('django', 'host', default='localhost:8000')
PROTOCOL = get_var('django', 'protocol', default='https')
BASE_URL = get_var('django', 'base_url', default=HOST)
# Define media paths e.g. for image storage
MEDIA_URL = '/media/'
MEDIA_ROOT = os.environ.get('DJANGO_MEDIA_ROOT',
os.path.join((os.path.join(BASE_DIR, os.pardir)), "media"))
MEDIA_MEMBERLISTS = os.path.join((os.path.join(BASE_DIR, os.pardir)), "media")
MEDIA_ROOT = get_var('django', 'media_root',
default=os.path.join((os.path.join(BASE_DIR, os.pardir)), "media"))
# default primary key auto field type
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
@ -38,6 +36,7 @@ USE_X_FORWARDED_HOST = True
# Application definition
INSTALLED_APPS = [
'logindata.apps.LoginDataConfig',
'contrib.apps.ContribConfig',
'startpage.apps.StartpageConfig',
'material.apps.MaterialConfig',
@ -53,6 +52,7 @@ INSTALLED_APPS = [
'django_celery_beat',
'rules',
'jet',
'oauth2_provider',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
@ -75,12 +75,15 @@ MIDDLEWARE = [
'django.middleware.cache.FetchFromCacheMiddleware',
]
X_FRAME_OPTIONS = 'SAMEORIGIN'
ROOT_URLCONF = 'jdav_web.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'DIRS': [os.path.join(CONFIG_DIR_PATH, 'templates'),
os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
@ -123,21 +126,21 @@ AUTH_PASSWORD_VALIDATORS = [
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
os.path.join(CONFIG_DIR_PATH, "static"),
os.path.join(BASE_DIR, "static"),
]
# static root where all the static files are collected to
# use python3 manage.py collectstatic to collect static files in the STATIC_ROOT
# this is needed for deployment
STATIC_ROOT = os.environ.get('DJANGO_STATIC_ROOT',
'/var/www/jdav_web/static')
STATIC_ROOT = get_var('django', 'static_root', default='/var/www/jdav_web/static')
DEFAULT_STATIC_PATH = get_var('django', 'default_static_path', default='/app/jdav_web/static')
# Locale files (translations)
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
# Celery and Redis setup
BROKER_URL = os.environ.get('BROKER_URL', 'redis://localhost:6379/0')
BROKER_URL = get_var('django', 'broker_url', default='redis://localhost:6379/0')
# password hash algorithms used
@ -188,3 +191,11 @@ 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 = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
'LOCATION': os.environ.get('MEMCACHED_URL', '127.0.0.1:11211'),
'LOCATION': get_var('django', 'memcached_url', default='127.0.0.1:11211'),
'OPTIONS': {
'no_delay': True,
'ignore_exc': True,
@ -12,6 +12,6 @@ CACHES = {
}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 120
CACHE_MIDDLEWARE_SECONDS = 1
CACHE_MIDDLEWARE_KEY_PREFIX = ''

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

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

@ -5,48 +5,60 @@ JET_DEFAULT_THEME = 'jdav-green'
JET_CHANGE_FORM_SIBLING_LINKS = False
JET_SIDE_MENU_ITEMS = [
{'app_label': 'auth', 'permissions': ['auth'], 'items': [
{'name': 'group', 'permissions': ['auth.group'] },
{'name': 'user', 'permissions': ['auth.user']},
{'label': 'Teilnehmer*innenverwaltung', 'app_label': 'members', 'items': [
{'name': 'member', 'label': 'Alle Teilnehmer*innen', 'permissions': ['members.view_member']},
{'name': 'freizeit', 'permissions': ['members.view_freizeit']},
{'name': 'group', 'permissions': ['members.view_group']},
{'name': 'membernotelist', 'permissions': ['members.view_membernotelist']},
{'name': 'klettertreff', 'permissions': ['members.view_klettertreff']},
]},
{'app_label': 'django_celery_beat', 'permissions': ['django_celery_beat'], 'items': [
{'name': 'crontabschedule'},
{'name': 'clockedschedule'},
{'name': 'intervalschedule'},
{'name': 'periodictask'},
{'name': 'solarschedule'},
{'label': 'Neue Mitglieder', 'app_label': 'members', 'permissions': ['members.view_memberunconfirmedproxy'], 'items': [
{'name': 'memberunconfirmedproxy', 'permissions': ['members.view_memberunconfirmedproxy']},
{'name': 'memberwaitinglist', 'permissions': ['members.view_memberwaitinglist']},
]},
{'app_label': 'ludwigsburgalpin', 'permissions': ['ludwigsburgalpin'], 'items': [
{'name': 'termin', 'permissions': ['ludwigsburgalpin.view_termin']},
{'label': 'Ausbildung', 'app_label': 'members', 'permissions': ['members.view_membertraining'], 'items': [
{'name': 'membertraining', 'permissions': ['members.view_membertraining']},
{'name': 'trainingcategory', 'permissions': ['members.view_trainingcategory']},
{'name': 'activitycategory', 'permissions': ['members.view_activitycategory']},
]},
{'app_label': 'mailer', 'items': [
{'name': 'message', 'permissions': ['mailer.view_message']},
{'name': 'emailaddress', 'permissions': ['mailer.view_emailaddress']},
]},
{'app_label': 'finance', 'items': [
{'name': 'statementunsubmitted', 'permissions': ['finance.view_statementunsubmitted']},
{'name': 'statementsubmitted', 'permissions': ['finance.view_statementsubmitted']},
{'name': 'statementconfirmed', 'permissions': ['finance.view_statementconfirmed']},
{'name': 'statement', 'permissions': ['finance.view_statement']},
{'name': 'ledger', 'permissions': ['finance.view_ledger']},
{'name': 'bill', 'permissions': ['finance.view_bill', 'finance.view_bill_admin']},
{'name': 'transaction', 'permissions': ['finance.view_transaction']},
]},
{'app_label': 'members', 'items': [
{'name': 'member', 'permissions': ['members.view_member']},
{'name': 'group', 'permissions': ['members.view_group']},
{'name': 'membernotelist', 'permissions': ['members.view_membernotelist']},
{'name': 'freizeit', 'permissions': ['members.view_freizeit']},
{'name': 'klettertreff', 'permissions': ['members.view_klettertreff']},
{'name': 'activitycategory', 'permissions': ['members.view_activitycategory']},
{'name': 'trainingcategory', 'permissions': ['members.view_trainingcategory']},
{'name': 'memberunconfirmedproxy', 'permissions': ['members.view_memberunconfirmedproxy']},
{'name': 'memberwaitinglist', 'permissions': ['members.view_memberwaitinglist']},
{'app_label': 'logindata', 'permissions': ['auth'], 'items': [
{'name': 'authgroup', 'permissions': ['auth.group'] },
{'name': 'logindatum', 'permissions': ['auth.user']},
{'name': 'registrationpassword', 'permissions': ['auth.user']},
]},
{'app_label': 'material', 'permissions': ['material'], 'items': [
{'app_label': 'django_celery_beat', 'permissions': ['django_celery_beat'], 'items': [
{'name': 'crontabschedule'},
{'name': 'clockedschedule'},
{'name': 'intervalschedule'},
{'name': 'periodictask'},
{'name': 'solarschedule'},
]},
{'app_label': 'ludwigsburgalpin', 'permissions': ['ludwigsburgalpin'], 'items': [
{'name': 'termin', 'permissions': ['ludwigsburgalpin.view_termin']},
]},
{'app_label': 'material', 'permissions': ['material.view_materialpart'], 'items': [
{'name': 'materialcategory', 'permissions': ['material.view_materialcategory']},
{'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': 'Packlisten und Co.', 'url': CLOUD_LINK }
{ 'label': 'Nextcloud', 'url': CLOUD_LINK, 'url_blank': True },
{ '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 },
]},
]

@ -0,0 +1,59 @@
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,
},
},
}

@ -0,0 +1,11 @@
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
CONFIRM_MAIL_TEXT = """Hallo {name},
CONFIRM_MAIL_TEXT = get_text('confirm_mail', default="""Hallo {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}. Dazu klicke bitte einfach auf
@ -9,37 +9,108 @@ folgenden Link:
{link}
Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION }
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION })
NEW_UNCONFIRMED_REGISTRATION = """Hallo {name},
NEW_UNCONFIRMED_REGISTRATION = get_text('new_unconfirmed_registration', default="""Hallo {name},
für deine Gruppe {group} liegt eine neue unbestätigte Reservierung vor. Die Person hat bereits ihre
E-Mailadressen bestätigt. Bitte prüfe die Registrierung eingehend und bestätige falls möglich. Zu
der Registrierung kommst du hier:
E-Mailadressen bestätigt und ihr Anmeldeformular hochgeladen. Bitte prüfe die Registrierung eingehend und
bestätige falls möglich. Zu der Registrierung kommst du hier:
{link}
Viele Grüße
Dein KOMPASS"""
Dein KOMPASS""")
INVITE_TEXT = """Hallo {name},
GROUP_INVITATION_LEFT_WAITINGLIST = get_text('group_invitation_left_waitinglist',
default="""Hallo {name},
wir haben gute Neuigkeiten für dich. Es ist ein Platz in der Jugendgruppe freigeworden. Wir brauchen
jetzt noch ein paar Informationen von dir und deine Anmeldebestätigung. Das kannst du alles über folgenden
Link erledigen:
der*die kürzlich zu einer Schnupperstunde für die Gruppe {group} eingeladene Wartende {waiter}
hat die Warteliste verlassen.
{link}
Viele Grüße
Dein KOMPASS""")
GROUP_INVITATION_REJECTED = get_text('group_invitation_rejected',
default="""Hallo {name},
{waiter} hat die Einladung zu einer Schnupperstunde bei der Gruppe {group} abgelehnt, ist
aber weiterhin auf der Warteliste.
Viele Grüße
Dein KOMPASS""")
GROUP_INVITATION_CONFIRMED_TEXT = get_text('group_invitation_confirmed',
default="""Hallo {name},
{waiter} hat die Einladung zu einer Schnupperstunde bei der Gruppe {group} angenommen.
Viele Grüße
Dein KOMPASS""")
TRIAL_GROUP_MEETING_CONFIRMED_TEXT = get_text('trial_group_meeting_confirmed',
default="""Hallo {name},
deine Teilnahme an der Schnupperstunde der Gruppe {group} wurde erfolgreich bestätigt.
{timeinfo}
Für alle weiteren Absprachen, kontaktiere bitte die Jugendleiter*innen der Gruppe
unter {contact_email}.
Viele Grüße
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION })
GROUP_TIME_AVAILABLE_TEXT = get_text('group_time_available',
default="""Die Gruppenstunde findet jeden {weekday} von {start_time} bis {end_time} Uhr statt.""")
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
ü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.
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 = """Hallo {name},
WAIT_CONFIRMATION_TEXT = get_text('wait_confirmation', default="""Hallo {name},
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
@ -50,18 +121,37 @@ Wenn du weiterhin auf der Warteliste bleiben möchtest, klicke auf den folgenden
{link}
Falls du nicht mehr auf der Warteliste bleiben möchtest, musst du nichts machen. Du wirst automatisch entfernt.
Falls du kein Interesse mehr hast, kannst du unter folgendem Link die Warteliste verlassen:
{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
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION }
Deine JDAV %(SEKTION)s""" % { 'SEKTION': SEKTION })
UNSUBSCRIBE_CONFIRMATION_TEXT = """Klicke auf den Link, um dich vom Newsletter der JDAV %(SEKTION)s abzumelden
UNSUBSCRIBE_CONFIRMATION_TEXT = get_text('unsubscribe_confirmation', default="""Klicke auf den Link, um dich vom Newsletter der JDAV %(SEKTION)s abzumelden
{link}""" % { 'SEKTION': SEKTION }
{link}""" % { 'SEKTION': SEKTION })
NOTIFY_MOST_ACTIVE_TEXT = """Hallo {name}!
NOTIFY_MOST_ACTIVE_TEXT = get_text('notify_most_active', default="""Hallo {name}!
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
@ -71,27 +161,32 @@ im letzten Jahr das {position}aktivste Mitglied 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 = """Hallo {name},
ECHO_TEXT = get_text('echo', default="""Hallo {name},
um unsere Daten auf dem aktuellen Stand zu halten, brauchen wir eine
um unsere Daten auf dem aktuellen Stand zu halten und sicherzugehen, dass du
weiterhin ein Teil unserer Jugendarbeit bleiben möchtest, brauchen wir eine
kurze Bestätigung von dir. Dafür besuche einfach diesen Link:
{link}
Dort kannst du deine Daten überprüfen und ändern. Falls du nicht innerhalb von
30 Tagen deine Daten bestätigst, wirst du aus unserer Datenbank gelöscht und
erhälst in Zukunft keine Mails mehr von uns.
Dort kannst du deine Daten nach Eingabe eines Passworts überprüfen und ggf. ändern. Dein
Passwort ist dein Geburtsdatum. Wäre dein Geburtsdatum zum Beispiel der 4. Januar 1942,
so wäre dein Passwort: 04.01.1942
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.
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 = """WICHTIGE MITTEILUNG
PREPEND_INCOMPLETE_REGISTRATION_TEXT = get_text('prepend_incomplete_registration', default="""WICHTIGE MITTEILUNG
Deine Anmeldung ist aktuell nicht vollständig. Bitte fülle umgehend das
Anmeldeformular aus und lasse es Deine*r Jugendleiter*in zukommen! Dieses
@ -101,10 +196,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 = """
MAIL_FOOTER = get_text('mail_footer', default="""
****************
@ -113,4 +208,76 @@ Diese Email wurde über die Webseite der JDAV %(SEKTION)s
verschickt. Wenn Du in Zukunft keine Emails mehr erhalten möchtest,
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,41 +1,86 @@
# contact data
SEKTION = "Heidelberg"
SEKTION_STREET = "Harbigweg 20"
SEKTION_TOWN = "69124 Heidelberg"
SEKTION_TELEPHONE = "06221 284076"
SEKTION_TELEFAX = "06221 437338"
SEKTION_CONTACT_MAIL = "geschaeftsstelle@alpenverein-heidelberg.de"
SEKTION_BOARD_MAIL = "vorstand@alpenverein-heidelberg.de"
SEKTION = get_var('section', 'name', default='Heyo')
SEKTION_STREET = get_var('section', 'street', default='Street')
SEKTION_TOWN = get_var('section', 'town', default='12345 Town')
SEKTION_TELEPHONE = get_var('section', 'telephone', default='0123456789')
SEKTION_TELEFAX = get_var('section', 'telefax', default=SEKTION_TELEPHONE)
SEKTION_CONTACT_MAIL = get_var('section', 'contact_mail', default='info@example.org')
SEKTION_BOARD_MAIL = get_var('section', 'board_mail', default=SEKTION_CONTACT_MAIL)
SEKTION_CRISIS_INTERVENTION_MAIL = get_var('section', 'crisis_intervention_mail',
default=SEKTION_BOARD_MAIL)
SEKTION_FINANCE_MAIL = get_var('section', 'finance_mail', default=SEKTION_CONTACT_MAIL)
SEKTION_IBAN = get_var('section', 'iban', default='Foo 123')
SEKTION_ACCOUNT_HOLDER = get_var('section', 'account_holder',
default='Foo')
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)
RESPONSIBLE_MAIL = "jugendreferat@jdav-hd.de"
# Waiting list configuration parameters, all numbers are in days
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
CONGRATULATE_MEMBERS_MAX = 10
# the maximal number of members that get sent congratulations for highest activity on aprils fools day
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
ALLOWANCE_PER_DAY = 10
MAX_NIGHT_COST = 11
ALLOWANCE_PER_DAY = get_var('finance', 'allowance_per_day', default=22)
MAX_NIGHT_COST = get_var('finance', 'max_night_cost', default=11)
CLOUD_LINK = 'https://cloud.jdav-ludwigsburg.de/index.php/s/qxQCTR8JqYSXXCQ'
EXCURSION_ORG_FEE = get_var('finance', 'org_fee', default=10)
# Admin setup
# links
ADMINS = (('admin', 'christian@merten-moser.de'),)
CLOUD_LINK = get_var('links', 'cloud', default='https://startpage.com')
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')
# Waiting list configuration parameters, all numbers are in days
# startpage
GRACE_PERIOD_WAITING_CONFIRMATION = 30
WAITING_CONFIRMATION_FREQUENCY = 90
STARTPAGE_REDIRECT_URL = get_var('startpage', 'redirect_url', default='')
ROOT_SECTION = get_var('startpage', 'root_section', default='about')
RECENT_SECTION = get_var('startpage', 'recent_section', default='recent')
REPORTS_SECTION = get_var('startpage', 'reports_section', default='reports')
# testing
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'
TEST_MAIL = get_var('testing', 'mail', default='test@localhost')

@ -0,0 +1,30 @@
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,28 +13,31 @@ Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.urls import re_path, include
from django.urls import path, re_path, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf.urls.i18n import i18n_patterns
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.views.generic.base import RedirectView
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from oauth2_provider import urls as oauth2_urls
from .views import media_access
admin.site.index_title = _('Startpage')
admin.site.site_header = 'Kompass'
urlpatterns += i18n_patterns(
re_path(r'^kompass/?', admin.site.urls),
urlpatterns = i18n_patterns(
re_path(r'^media/(?P<path>.*)', media_access, name='media'),
re_path(r'^kompass/?', admin.site.urls, name='kompass'),
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'^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',
namespace="ludwigsburgalpin")),
re_path(r'^_nested_admin/', include('nested_admin.urls')),
path('o/', include(oauth2_urls)),
re_path(r'^', include('startpage.urls', namespace="startpage")),
)

@ -0,0 +1,48 @@
from django.http import HttpResponse
from django.views.static import serve
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib import admin
from django.shortcuts import render
from startpage.models import Link
import re
def media_unprotected(request, path):
if settings.DEBUG:
# if DEBUG is enabled, directly serve file
return serve(request, path, document_root=settings.MEDIA_ROOT)
# otherwise create a redirect to the internal nginx endpoint at /protected
response = HttpResponse()
# Content-type will be detected by nginx
del response['Content-Type']
response['X-Accel-Redirect'] = '/protected/' + path
return response
@staff_member_required
def media_protected(request, path):
return media_unprotected(request, path)
def media_access(request, path):
if re.match('^(people|images)/', path):
return media_unprotected(request, path)
else:
return media_protected(request, path)
def custom_admin_view(request):
"""
this methods provides access to models in order to render a custom admin page index site.
"""
app_list = admin.site.get_app_list(request)
context = {
'app_list': app_list,
'site_header': admin.site.site_header,
'site_title': admin.site.site_title,
'external_links': Link.objects.all()
}
return render(request, 'admin/index.html', context)
admin.site.index = custom_admin_view

@ -1 +0,0 @@
Subproject commit 67ab498ef24dd815a194abb0e6d714f6b02dc1de

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

Loading…
Cancel
Save