OpenSlides/server/openslides/motions/models.py

1155 lines
36 KiB
Python
Raw Normal View History

from django.conf import settings
2018-06-12 14:17:02 +02:00
from django.contrib.auth.models import AnonymousUser
from django.db import IntegrityError, models, transaction
from django.db.models import Max
from jsonfield import JSONField
2011-07-31 10:46:29 +02:00
from openslides.agenda.mixins import AgendaItemWithListOfSpeakersMixin
2015-06-29 12:08:15 +02:00
from openslides.core.config import config
2018-12-23 11:05:38 +01:00
from openslides.core.models import Tag
from openslides.mediafiles.models import Mediafile
2019-10-18 14:18:49 +02:00
from openslides.poll.models import BaseOption, BasePoll, BaseVote
from openslides.utils.autoupdate import inform_changed_data
2018-06-12 14:17:02 +02:00
from openslides.utils.exceptions import OpenSlidesError
from openslides.utils.manager import BaseManager
2015-06-29 12:08:15 +02:00
from openslides.utils.models import RESTModelMixin
from openslides.utils.rest_api import ValidationError
from ..utils.models import CASCADE_AND_AUTOUPDATE, SET_NULL_AND_AUTOUPDATE
from .access_permissions import (
CategoryAccessPermissions,
MotionAccessPermissions,
MotionBlockAccessPermissions,
2016-09-10 18:49:38 +02:00
MotionChangeRecommendationAccessPermissions,
MotionCommentSectionAccessPermissions,
MotionOptionAccessPermissions,
2019-10-18 14:18:49 +02:00
MotionPollAccessPermissions,
MotionVoteAccessPermissions,
2019-07-17 16:13:49 +02:00
StateAccessPermissions,
StatuteParagraphAccessPermissions,
WorkflowAccessPermissions,
)
from .exceptions import WorkflowError
2013-02-17 17:07:44 +01:00
class StatuteParagraph(RESTModelMixin, models.Model):
"""
Model for parts of the statute
"""
2019-01-06 16:22:33 +01:00
access_permissions = StatuteParagraphAccessPermissions()
title = models.CharField(max_length=255)
"""Title of the statute paragraph."""
text = models.TextField()
"""Content of the statute paragraph."""
weight = models.IntegerField(default=10000)
"""
A weight field to sort statute paragraphs.
"""
class Meta:
default_permissions = ()
2019-01-06 16:22:33 +01:00
ordering = ["weight", "title"]
def __str__(self):
return self.title
class MotionManager(BaseManager):
2016-09-30 20:42:58 +02:00
"""
Customized model manager to support our get_prefetched_queryset method.
2016-09-30 20:42:58 +02:00
"""
2019-01-06 16:22:33 +01:00
def get_prefetched_queryset(self, *args, **kwargs):
2016-09-30 20:42:58 +02:00
"""
Returns the normal queryset with all motions. In the background we
join and prefetch all related models.
"""
2019-01-06 16:22:33 +01:00
return (
super()
.get_prefetched_queryset(*args, **kwargs)
2019-01-06 16:22:33 +01:00
.select_related("state")
.prefetch_related(
"state__workflow",
"comments",
"comments__section",
"comments__section__read_groups",
"agenda_items",
"lists_of_speakers",
2019-01-06 16:22:33 +01:00
"attachments",
"tags",
"submitters",
"supporters",
"change_recommendations",
"amendments",
2019-01-06 16:22:33 +01:00
)
)
class Motion(RESTModelMixin, AgendaItemWithListOfSpeakersMixin, models.Model):
2013-04-19 14:12:49 +02:00
"""
2016-09-30 20:42:58 +02:00
Model for motions.
2013-01-26 12:28:51 +01:00
2013-02-05 18:46:46 +01:00
This class is the main entry point to all other classes related to a motion.
"""
2019-01-06 16:22:33 +01:00
access_permissions = MotionAccessPermissions()
2019-01-06 16:22:33 +01:00
can_see_permission = "motions.can_see"
2013-01-26 12:28:51 +01:00
objects = MotionManager()
title = models.CharField(max_length=255)
"""The title of a motion."""
text = models.TextField()
"""The text of a motion."""
2013-01-26 15:25:54 +01:00
amendment_paragraphs = JSONField(null=True)
"""
If paragraph-based, diff-enabled amendment style is used, this field stores an array of strings or null values.
Each entry corresponds to a paragraph of the text of the original motion.
If the entry is null, then the paragraph remains unchanged.
If the entry is a string, this is the new text of the paragraph.
amendment_paragraphs and text are mutually exclusive.
2013-02-05 18:46:46 +01:00
"""
2013-01-06 12:07:37 +01:00
modified_final_version = models.TextField(null=True, blank=True)
"""A field to copy in the final version of the motion and edit it there."""
reason = models.TextField(null=True, blank=True)
"""The reason for a motion."""
state = models.ForeignKey(
2019-01-06 16:22:33 +01:00
"State",
related_name="+",
on_delete=models.PROTECT, # Do not let the user delete states, that are used for motions
2019-01-06 16:22:33 +01:00
null=True,
) # TODO: Check whether null=True is necessary.
2013-04-19 14:12:49 +02:00
"""
The related state object.
2013-01-06 12:07:37 +01:00
This attribute is to get the current state of the motion.
2013-01-26 12:28:51 +01:00
"""
2013-01-06 12:07:37 +01:00
state_extension = models.TextField(blank=True, null=True)
"""
A text field fo additional information about the state.
"""
recommendation = models.ForeignKey(
"State", related_name="+", on_delete=SET_NULL_AND_AUTOUPDATE, null=True
2019-01-06 16:22:33 +01:00
)
"""
The recommendation of a person or committee for this motion.
"""
recommendation_extension = models.TextField(blank=True, null=True)
"""
A text field fo additional information about the recommendation.
"""
2019-01-06 16:22:33 +01:00
identifier = models.CharField(max_length=255, null=True, blank=True, unique=True)
2013-04-19 14:12:49 +02:00
"""
A string as human readable identifier for the motion.
"""
2013-02-05 18:46:46 +01:00
2013-03-12 22:03:56 +01:00
identifier_number = models.IntegerField(null=True)
2013-04-19 14:12:49 +02:00
"""
Counts the number of the motion in one category.
2013-03-12 22:03:56 +01:00
Needed to find the next free motion identifier.
2013-03-12 22:03:56 +01:00
"""
weight = models.IntegerField(default=10000)
"""
A weight field to sort motions.
"""
sort_parent = models.ForeignKey(
2019-01-06 16:22:33 +01:00
"self",
on_delete=SET_NULL_AND_AUTOUPDATE,
null=True,
blank=True,
2019-01-06 16:22:33 +01:00
related_name="children",
)
"""
A parent field for multi-depth sorting of motions.
"""
category = models.ForeignKey(
"Category", on_delete=SET_NULL_AND_AUTOUPDATE, null=True, blank=True
2019-01-06 16:22:33 +01:00
)
2013-04-19 14:12:49 +02:00
"""
ForeignKey to one category of motions.
"""
2013-03-11 20:17:19 +01:00
2019-04-30 13:48:21 +02:00
category_weight = models.IntegerField(default=10000)
"""
Sorts the motions inside a category. Default is 10000 so new motions
in a category will be added on the end of the list.
"""
motion_block = models.ForeignKey(
"MotionBlock", on_delete=SET_NULL_AND_AUTOUPDATE, null=True, blank=True,
2019-01-06 16:22:33 +01:00
)
"""
ForeignKey to one block of motions.
"""
2016-07-13 14:45:40 +02:00
origin = models.CharField(max_length=255, blank=True)
"""
A string to describe the origin of this motion e. g. that it was
discussed at another assembly/conference.
"""
attachments = models.ManyToManyField(Mediafile, blank=True)
"""
Many to many relation to mediafile objects.
"""
parent = models.ForeignKey(
2019-01-06 16:22:33 +01:00
"self",
on_delete=SET_NULL_AND_AUTOUPDATE,
null=True,
blank=True,
2019-01-06 16:22:33 +01:00
related_name="amendments",
)
2014-12-25 10:58:52 +01:00
"""
Field for amendments to reference to the motion that should be altered.
Null if the motion is not an amendment.
"""
2011-07-31 10:46:29 +02:00
statute_paragraph = models.ForeignKey(
StatuteParagraph,
on_delete=SET_NULL_AND_AUTOUPDATE,
null=True,
blank=True,
2019-01-06 16:22:33 +01:00
related_name="motions",
)
"""
Field to reference to a statute paragraph if this motion is a
statute-amendment.
Null if the motion is not a statute-amendment.
"""
tags = models.ManyToManyField(Tag, blank=True)
"""
Tags to categorise motions.
"""
2011-07-31 10:46:29 +02:00
2019-01-06 16:22:33 +01:00
supporters = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="motion_supporters", blank=True
)
"""
Users who support this motion.
"""
2019-01-19 10:27:50 +01:00
created = models.DateTimeField(auto_now_add=True)
"""
Timestamp when motion is created.
"""
last_modified = models.DateTimeField(auto_now=True)
"""
Timestamp when motion is modified.
"""
2013-01-06 12:07:37 +01:00
class Meta:
2015-12-10 00:20:59 +01:00
default_permissions = ()
2013-01-06 12:07:37 +01:00
permissions = (
2019-01-06 16:22:33 +01:00
("can_see", "Can see motions"),
("can_see_internal", "Can see motions in internal state"),
2019-01-06 16:22:33 +01:00
("can_create", "Can create motions"),
("can_create_amendments", "Can create amendments"),
2019-01-06 16:22:33 +01:00
("can_support", "Can support motions"),
("can_manage_metadata", "Can manage motion metadata"),
("can_manage", "Can manage motions"),
2019-10-18 14:18:49 +02:00
("can_manage_polls", "Can manage motion polls"),
2013-01-06 12:07:37 +01:00
)
2019-01-06 16:22:33 +01:00
ordering = ("identifier",)
2019-01-12 23:01:42 +01:00
verbose_name = "Motion"
def __str__(self):
2013-04-19 14:12:49 +02:00
"""
Return the title of this motion.
2013-04-19 14:12:49 +02:00
"""
return self.title
2013-01-06 12:07:37 +01:00
# TODO: Use transaction
def save(self, skip_autoupdate=False, *args, **kwargs):
2013-04-19 14:12:49 +02:00
"""
Save the motion.
2013-02-05 18:46:46 +01:00
1. Set the state of a new motion to the default state.
2. Ensure that the identifier is not an empty string.
3. Save the motion object.
2013-01-26 12:28:51 +01:00
"""
if not self.state:
self.reset_state()
# Solves the problem, that there can only be one motion with an empty
# string as identifier.
if not self.identifier and isinstance(self.identifier, str):
2013-04-19 14:12:49 +02:00
self.identifier = None
# Try to save the motion until it succeeds with a correct identifier.
while True:
try:
# Always skip autoupdate. Maybe we run it later in this method.
with transaction.atomic():
2019-01-06 16:22:33 +01:00
super(Motion, self).save( # type: ignore
skip_autoupdate=True, *args, **kwargs
)
except IntegrityError:
# Identifier is already used.
2019-01-06 16:22:33 +01:00
if hasattr(self, "_identifier_prefix"):
# Calculate a new one and try again.
2019-10-29 15:05:52 +01:00
(
self.identifier_number,
self.identifier,
) = self.increment_identifier_number(
2019-01-06 16:22:33 +01:00
self.identifier_number, self._identifier_prefix
)
else:
# Do not calculate a new one but reraise the IntegrityError.
# The error is caught in the category sort view.
raise
else:
# Save was successful. End loop.
break
2013-02-05 18:46:46 +01:00
if not skip_autoupdate:
inform_changed_data(self)
2013-02-03 13:24:29 +01:00
2013-03-12 22:03:56 +01:00
def set_identifier(self):
"""
2014-12-25 10:58:52 +01:00
Sets the motion identifier automaticly according to the config value if
it is not set yet.
"""
# The identifier is already set or should be set manually.
2019-01-06 16:22:33 +01:00
if config["motions_identifier"] == "manually" or self.identifier:
2013-03-12 23:35:08 +01:00
# Do not set an identifier.
return
2014-12-25 10:58:52 +01:00
# If config 'motions_identifier_with_blank' is set, use blanks when building identifier.
with_blank = config["motions_identifier_with_blank"]
# Build prefix.
2014-12-25 10:58:52 +01:00
if self.is_amendment():
2019-01-06 16:22:33 +01:00
parent_identifier = self.parent.identifier or ""
if with_blank:
prefix = f"{parent_identifier} {config['motions_amendments_prefix']}"
else:
prefix = f"{parent_identifier}{config['motions_amendments_prefix']}"
2014-12-25 10:58:52 +01:00
elif self.category is None or not self.category.prefix:
2019-01-06 16:22:33 +01:00
prefix = ""
2013-03-12 23:35:08 +01:00
else:
if with_blank:
2019-01-12 23:01:42 +01:00
prefix = f"{self.category.prefix} "
else:
prefix = self.category.prefix
self._identifier_prefix = prefix
2013-03-12 22:03:56 +01:00
2017-10-13 10:55:11 +02:00
# Use the already assigned identifier_number, if the motion has one.
# Else get the biggest number.
if self.identifier_number is not None:
number = self.identifier_number
initial_increment = False
else:
# Find all motions that should be included in the calculations.
if self.is_amendment():
motions = self.parent.amendments.all()
# The motions should be counted per category.
2019-01-06 16:22:33 +01:00
elif config["motions_identifier"] == "per_category":
2017-10-13 10:55:11 +02:00
motions = Motion.objects.filter(category=self.category)
# The motions should be counted over all.
else:
motions = Motion.objects.all()
2019-01-06 16:22:33 +01:00
number = (
motions.aggregate(Max("identifier_number"))["identifier_number__max"]
or 0
)
2017-10-13 10:55:11 +02:00
initial_increment = True
# Calculate new identifier.
2017-10-13 10:55:11 +02:00
number, identifier = self.increment_identifier_number(
2019-01-06 16:22:33 +01:00
number, prefix, initial_increment=initial_increment
)
# Set identifier and identifier_number.
self.identifier = identifier
self.identifier_number = number
2017-10-13 10:55:11 +02:00
def increment_identifier_number(self, number, prefix, initial_increment=True):
"""
Helper method. It increments the number until a free identifier
number is found. Returns new number and identifier.
"""
2017-10-13 10:55:11 +02:00
if initial_increment:
number += 1
2019-06-03 14:17:42 +02:00
identifier = f"{prefix}{Motion.extend_identifier_number(number)}"
while Motion.objects.filter(identifier=identifier).exists():
2013-03-12 22:03:56 +01:00
number += 1
2019-06-03 14:17:42 +02:00
identifier = f"{prefix}{Motion.extend_identifier_number(number)}"
return number, identifier
2013-03-12 22:03:56 +01:00
2019-06-03 14:17:42 +02:00
@classmethod
def extend_identifier_number(cls, number):
"""
Returns the number used in the set_identifier method with leading
zero charaters according to the config value.
"""
return "0" * (config["motions_identifier_min_digits"] - len(str(number))) + str(
number
)
def is_submitter(self, user):
2013-04-19 14:12:49 +02:00
"""
Returns True if user is a submitter of this motion, else False.
Anonymous users cannot be submitters.
2013-04-19 14:12:49 +02:00
"""
if isinstance(user, AnonymousUser):
return False
2018-06-12 14:17:02 +02:00
return self.submitters.filter(user=user).exists()
def is_supporter(self, user):
2013-04-19 14:12:49 +02:00
"""
Returns True if user is a supporter of this motion, else False.
2013-04-19 14:12:49 +02:00
"""
return user in self.supporters.all()
@property
def workflow_id(self):
"""
Returns the id of the workflow of the motion.
"""
return self.state.workflow.pk
2013-03-12 22:03:56 +01:00
def set_state(self, state):
2013-04-19 14:12:49 +02:00
"""
Set the state of the motion.
2013-03-12 22:03:56 +01:00
'state' can be the id of a state object or a state object.
2013-03-12 22:03:56 +01:00
"""
2019-01-12 23:01:42 +01:00
if isinstance(state, int):
2013-03-12 22:03:56 +01:00
state = State.objects.get(pk=state)
if not state.dont_set_identifier:
2013-03-12 22:03:56 +01:00
self.set_identifier()
self.state = state
def reset_state(self, workflow=None):
2013-04-19 14:12:49 +02:00
"""
Set the state to the default state. If an identifier was set
automatically, reset the identifier and identifier_number.
2013-04-19 14:12:49 +02:00
'workflow' can be a workflow, an id of a workflow or None.
If the motion is new and workflow is None, it chooses the default
workflow from config.
2013-04-19 14:12:49 +02:00
"""
2019-01-12 23:01:42 +01:00
if isinstance(workflow, int):
workflow = Workflow.objects.get(pk=workflow)
if workflow is not None:
new_state = workflow.first_state
elif self.state:
new_state = self.state.workflow.first_state
else:
2019-01-06 16:22:33 +01:00
new_state = (
Workflow.objects.get(pk=config["motions_workflow"]).first_state
or Workflow.objects.get(pk=config["motions_workflow"]).states.all()[0]
)
self.set_state(new_state)
def set_recommendation(self, recommendation):
"""
Set the recommendation of the motion.
'recommendation' can be the id of a state object or a state object.
"""
2019-01-12 23:01:42 +01:00
if isinstance(recommendation, int):
recommendation = State.objects.get(pk=recommendation)
self.recommendation = recommendation
def follow_recommendation(self):
"""
Set the state of this motion to its recommendation.
"""
if self.recommendation is not None:
self.set_state(self.recommendation)
2019-01-19 21:36:30 +01:00
if (
self.recommendation_extension is not None
and self.state.show_state_extension_field
and self.recommendation.show_recommendation_extension_field
):
self.state_extension = self.recommendation_extension
def get_title_information(self):
2019-02-15 12:17:08 +01:00
return {"title": self.title, "identifier": self.identifier}
2014-12-25 10:58:52 +01:00
def is_amendment(self):
"""
Returns True if the motion is an amendment.
A motion is a amendment if amendments are activated in the config and
the motion has a parent.
"""
2019-01-06 16:22:33 +01:00
return config["motions_amendments_enabled"] and self.parent is not None
2014-12-25 10:58:52 +01:00
def is_paragraph_based_amendment(self):
"""
Returns True if the motion is an amendment that stores the changes on a per-paragraph-basis
and is therefore eligible to be shown in diff-view.
"""
return self.is_amendment() and self.amendment_paragraphs
def get_paragraph_based_amendments(self):
"""
Returns a list of all paragraph-based amendments to this motion
"""
2019-01-06 16:22:33 +01:00
return list(
filter(
lambda amend: amend.is_paragraph_based_amendment(),
self.amendments.all(),
)
)
2019-06-03 14:17:42 +02:00
@property
def amendment_level(self):
"""
Returns the amount of parent motions.
"""
if self.parent is None:
return 0
else:
return self.parent.amendment_level + 1
class MotionCommentSection(RESTModelMixin, models.Model):
"""
The model for comment sections for motions. Each comment is related to one section, so
each motions has the ability to have comments from the same section.
"""
2019-01-06 16:22:33 +01:00
access_permissions = MotionCommentSectionAccessPermissions()
name = models.CharField(max_length=255)
"""
The name of the section.
"""
read_groups = models.ManyToManyField(
2019-01-06 16:22:33 +01:00
settings.AUTH_GROUP_MODEL, blank=True, related_name="read_comments"
)
"""
These groups have read-access to the section.
"""
write_groups = models.ManyToManyField(
2019-01-06 16:22:33 +01:00
settings.AUTH_GROUP_MODEL, blank=True, related_name="write_comments"
)
"""
These groups have write-access to the section.
"""
2019-07-19 13:43:33 +02:00
weight = models.IntegerField(default=10000)
"""
To sort comment sections.
"""
class Meta:
default_permissions = ()
class MotionComment(RESTModelMixin, models.Model):
"""
Represents a motion comment. A comment is always related to a motion and a comment
section. The section determinates the title of the category.
"""
comment = models.TextField()
"""
The comment.
"""
motion = models.ForeignKey(
2019-01-06 16:22:33 +01:00
Motion, on_delete=models.CASCADE, related_name="comments"
)
"""
The motion where this comment belongs to.
"""
section = models.ForeignKey(
2019-01-06 16:22:33 +01:00
MotionCommentSection, on_delete=models.PROTECT, related_name="comments"
)
"""
The section of the comment.
"""
class Meta:
default_permissions = ()
2019-01-06 16:22:33 +01:00
unique_together = ("motion", "section")
def get_root_rest_element(self):
"""
Returns the motion to this instance which is the root REST element.
"""
return self.motion
2018-06-12 14:17:02 +02:00
class SubmitterManager(models.Manager):
"""
Manager for Submitter model. Provides a customized add method.
"""
2019-01-06 16:22:33 +01:00
2018-06-12 14:17:02 +02:00
def add(self, user, motion, skip_autoupdate=False):
"""
Customized manager method to prevent anonymous users to be a
submitter and that someone is not twice a submitter. Cares also
for the initial sorting of the submitters.
"""
if self.filter(user=user, motion=motion).exists():
2019-01-12 23:01:42 +01:00
raise OpenSlidesError(f"{user} is already a submitter.")
2018-06-12 14:17:02 +02:00
if isinstance(user, AnonymousUser):
2019-01-12 23:01:42 +01:00
raise OpenSlidesError("An anonymous user can not be a submitter.")
2019-01-06 16:22:33 +01:00
weight = (
self.filter(motion=motion).aggregate(models.Max("weight"))["weight__max"]
or 0
)
2018-06-12 14:17:02 +02:00
submitter = self.model(user=user, motion=motion, weight=weight + 1)
submitter.save(force_insert=True, skip_autoupdate=skip_autoupdate)
return submitter
class Submitter(RESTModelMixin, models.Model):
"""
M2M Model for submitters.
"""
objects = SubmitterManager()
"""
Use custom Manager.
"""
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE_AND_AUTOUPDATE)
2018-06-12 14:17:02 +02:00
"""
ForeignKey to the user who is the submitter.
"""
motion = models.ForeignKey(
2019-01-06 16:22:33 +01:00
Motion, on_delete=models.CASCADE, related_name="submitters"
)
2018-06-12 14:17:02 +02:00
"""
ForeignKey to the motion.
"""
weight = models.IntegerField(null=True)
class Meta:
default_permissions = ()
def __str__(self):
return str(self.user)
def get_root_rest_element(self):
"""
Returns the motion to this instance which is the root REST element.
"""
return self.motion
2016-09-10 18:49:38 +02:00
class MotionChangeRecommendation(RESTModelMixin, models.Model):
"""
A MotionChangeRecommendation object saves change recommendations for a specific Motion
2016-09-10 18:49:38 +02:00
"""
access_permissions = MotionChangeRecommendationAccessPermissions()
motion = models.ForeignKey(
Motion, on_delete=CASCADE_AND_AUTOUPDATE, related_name="change_recommendations"
2019-01-06 16:22:33 +01:00
)
"""The motion to which the change recommendation belongs."""
2016-09-10 18:49:38 +02:00
rejected = models.BooleanField(default=False)
"""If true, this change recommendation has been rejected"""
2016-09-10 18:49:38 +02:00
internal = models.BooleanField(default=False)
"""If true, this change recommendation can not be seen by regular users"""
type = models.PositiveIntegerField(default=0)
2017-11-17 12:10:46 +01:00
"""Replacement (0), Insertion (1), Deletion (2), Other (3)"""
other_description = models.TextField(blank=True)
"""The description text for type 'other'"""
2016-09-10 18:49:38 +02:00
line_from = models.PositiveIntegerField()
"""The number or the first affected line"""
line_to = models.PositiveIntegerField()
"""The number or the last affected line (inclusive)"""
text = models.TextField(blank=True)
"""The replacement for the section of the original text specified by motion, line_from and line_to"""
2016-09-10 18:49:38 +02:00
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=SET_NULL_AND_AUTOUPDATE, null=True
2019-01-06 16:22:33 +01:00
)
2016-09-10 18:49:38 +02:00
"""A user object, who created this change recommendation. Optional."""
creation_time = models.DateTimeField(auto_now=True)
"""Time when the change recommendation was saved."""
class Meta:
default_permissions = ()
def __str__(self):
"""Return a string, representing this object."""
return f"Recommendation for Motion {self.motion_id}, line {self.line_from} - {self.line_to}"
def collides_with_other_recommendation(self, recommendations):
for recommendation in recommendations:
2019-01-06 16:22:33 +01:00
if not (
self.line_from < recommendation.line_from
and self.line_to <= recommendation.line_from
) and not (
self.line_from >= recommendation.line_to
and self.line_to > recommendation.line_to
):
return True
return False
def save(self, *args, **kwargs):
2019-01-06 16:22:33 +01:00
recommendations = MotionChangeRecommendation.objects.filter(
motion=self.motion
).exclude(pk=self.pk)
if self.collides_with_other_recommendation(recommendations):
2019-01-06 16:22:33 +01:00
raise ValidationError(
{
"detail": "The recommendation collides with an existing one (line {0} - {1}).",
"args": [self.line_from, self.line_to],
}
2019-01-06 16:22:33 +01:00
)
result = super().save(*args, **kwargs)
# Hotfix for #4491: Trigger extra autoupdate for motion so that the serializer
# field vor motion change recommendations gets updated too.
inform_changed_data(self.motion)
2016-09-10 18:49:38 +02:00
return result
def delete(self, *args, **kwargs):
# Hotfix for #4491: Trigger extra autoupdate for motion so that the serializer
# field vor motion change recommendations gets updated too.
motion = self.motion
result = super().delete(*args, **kwargs)
inform_changed_data(motion)
return result
2016-09-10 18:49:38 +02:00
class Category(RESTModelMixin, models.Model):
"""
Model for categories of motions.
"""
2019-01-06 16:22:33 +01:00
access_permissions = CategoryAccessPermissions()
name = models.CharField(max_length=255)
"""Name of the category."""
prefix = models.CharField(blank=True, max_length=32)
2019-08-05 13:11:32 +02:00
"""
Prefix of the category.
Used to build the identifier of a motion.
"""
2013-03-11 20:17:19 +01:00
2019-06-03 14:17:42 +02:00
parent = models.ForeignKey(
"self",
2019-08-05 13:11:32 +02:00
on_delete=CASCADE_AND_AUTOUPDATE,
2019-06-03 14:17:42 +02:00
null=True,
blank=True,
related_name="children",
)
weight = models.IntegerField(default=10000)
2013-03-11 21:29:56 +01:00
class Meta:
2015-12-10 00:20:59 +01:00
default_permissions = ()
2019-06-03 14:17:42 +02:00
ordering = ["weight"]
2013-02-05 18:46:46 +01:00
2015-12-10 00:20:59 +01:00
def __str__(self):
2019-06-03 14:17:42 +02:00
if self.prefix:
return f"{self.prefix} - {self.name}"
else:
return self.name
@property
def level(self):
"""
Returns the level in the tree of categories. Level 0 means this
item is a root item in the tree. Level 1 indicates that the parent is
a root item, level 2 that the parent's parent is a root item and so on.
Attention! This executes one query for each ancestor of the category.
"""
if self.parent is None:
return 0
else:
return self.parent.level + 1
2015-12-10 00:20:59 +01:00
2013-02-01 12:51:54 +01:00
class MotionBlockManager(BaseManager):
"""
Customized model manager to support our get_prefetched_queryset method.
"""
2019-01-06 16:22:33 +01:00
def get_prefetched_queryset(self, *args, **kwargs):
"""
Returns the normal queryset with all motion blocks. In the
background the related agenda item is prefetched from the database.
"""
return (
super()
.get_prefetched_queryset(*args, **kwargs)
.prefetch_related("agenda_items", "lists_of_speakers", "motion_set")
)
class MotionBlock(RESTModelMixin, AgendaItemWithListOfSpeakersMixin, models.Model):
"""
Model for blocks of motions.
"""
2019-01-06 16:22:33 +01:00
access_permissions = MotionBlockAccessPermissions()
objects = MotionBlockManager()
title = models.CharField(max_length=255)
internal = models.BooleanField(default=False)
"""
If a motion block is internal, only users with `motions.can_manage` can see and
manage these blocks.
"""
class Meta:
2019-01-12 23:01:42 +01:00
verbose_name = "Motion block"
default_permissions = ()
def __str__(self):
return self.title
def get_title_information(self):
2019-02-15 12:17:08 +01:00
return {"title": self.title}
class MotionVoteManager(BaseManager):
"""
Customized model manager to support our get_prefetched_queryset method.
"""
def get_prefetched_queryset(self, *args, **kwargs):
"""
Returns the normal queryset with all motion votes. In the background we
join and prefetch all related models.
"""
return (
super()
.get_prefetched_queryset(*args, **kwargs)
.select_related("user", "option", "option__poll")
)
class MotionVote(RESTModelMixin, BaseVote):
2019-10-18 14:18:49 +02:00
access_permissions = MotionVoteAccessPermissions()
option = models.ForeignKey(
2020-02-12 17:18:01 +01:00
"MotionOption", on_delete=CASCADE_AND_AUTOUPDATE, related_name="votes"
2019-10-18 14:18:49 +02:00
)
2013-02-01 12:51:54 +01:00
objects = MotionVoteManager()
2015-12-10 00:20:59 +01:00
class Meta:
default_permissions = ()
unique_together = ("user", "option")
2015-12-10 00:20:59 +01:00
2013-02-01 12:51:54 +01:00
2020-02-13 18:24:51 +01:00
class MotionOptionManager(BaseManager):
"""
Customized model manager to support our get_prefetched_queryset method.
"""
def get_prefetched_queryset(self, *args, **kwargs):
"""
Returns the normal queryset. In the background we
2020-02-13 18:24:51 +01:00
join and prefetch all related models.
"""
return (
super()
.get_prefetched_queryset(*args, **kwargs)
.select_related("poll")
.prefetch_related("votes")
2020-02-13 18:24:51 +01:00
)
class MotionOption(RESTModelMixin, BaseOption):
access_permissions = MotionOptionAccessPermissions()
can_see_permission = "motions.can_see"
2020-02-13 18:24:51 +01:00
objects = MotionOptionManager()
2013-02-01 12:51:54 +01:00
vote_class = MotionVote
2019-10-18 14:18:49 +02:00
poll = models.ForeignKey(
2020-02-12 17:18:01 +01:00
"MotionPoll", related_name="options", on_delete=CASCADE_AND_AUTOUPDATE
)
2013-02-01 12:51:54 +01:00
2015-12-10 00:20:59 +01:00
class Meta:
default_permissions = ()
2013-02-01 12:51:54 +01:00
class MotionPollManager(BaseManager):
"""
Customized model manager to support our get_prefetched_queryset method.
"""
def get_prefetched_queryset(self, *args, **kwargs):
"""
Returns the normal queryset with all motion polls. In the background we
join and prefetch all related models.
"""
return (
super()
.get_prefetched_queryset(*args, **kwargs)
.select_related("motion")
.prefetch_related("options", "options__votes", "voted", "groups")
)
2019-10-18 14:18:49 +02:00
class MotionPoll(RESTModelMixin, BasePoll):
access_permissions = MotionPollAccessPermissions()
can_see_permission = "motions.can_see"
2019-10-18 14:18:49 +02:00
option_class = MotionOption
2013-02-05 18:46:46 +01:00
objects = MotionPollManager()
2020-02-12 17:18:01 +01:00
motion = models.ForeignKey(
Motion, on_delete=CASCADE_AND_AUTOUPDATE, related_name="polls"
)
2013-02-05 18:46:46 +01:00
2019-10-18 14:18:49 +02:00
POLLMETHOD_YN = "YN"
POLLMETHOD_YNA = "YNA"
POLLMETHODS = (("YN", "YN"), ("YNA", "YNA"))
pollmethod = models.CharField(max_length=3, choices=POLLMETHODS)
2013-02-01 12:51:54 +01:00
2015-12-10 00:20:59 +01:00
class Meta:
default_permissions = ()
2019-10-18 14:18:49 +02:00
def create_options(self):
MotionOption.objects.create(poll=self)
class State(RESTModelMixin, models.Model):
"""
Defines a state for a motion.
Every state belongs to a workflow. All states of a workflow are linked
together via 'next_states'. One of these states is the first state, but
this is saved in the workflow table (one-to-one relation). In every
state you can configure some handling of a motion. See the following
fields for more information.
Additionally every motion can refer to one state as recommendation of
an person or committee (see config 'motions_recommendations_by'). This
means that the person or committee recommends to set the motion to this
state.
"""
2019-07-17 16:13:49 +02:00
access_permissions = StateAccessPermissions()
name = models.CharField(max_length=255)
"""A string representing the state."""
recommendation_label = models.CharField(max_length=255, null=True)
"""A string for a recommendation to set the motion to this state."""
workflow = models.ForeignKey(
2019-01-06 16:22:33 +01:00
"Workflow", on_delete=models.CASCADE, related_name="states"
)
"""A many-to-one relation to a workflow."""
2019-01-06 16:22:33 +01:00
next_states = models.ManyToManyField("self", symmetrical=False, blank=True)
"""A many-to-many relation to all states, that can be choosen from this state."""
css_class = models.CharField(max_length=255, default="lightblue")
"""
A css class string for showing the state name in a coloured label. Currently supported
values are grey, red, green, lightblue and yellow. The default is lightblue.
"""
restriction = JSONField(default=list)
"""
Defines which users may see motions in this state:
Contains a list of one or more of the following strings:
* motions.can_see_internal
* motions.can_manage_metadata
* motions.can_manage
* is_submitter
If the list is empty, everybody with the general permission to see motions
can see this motion. If the list contains at least one item, the user needs
the permission (or have the attribute) for at least one of the restrictions.
Default: Empty list so everybody can see the motion.
"""
allow_support = models.BooleanField(default=False)
"""If true, persons can support the motion in this state."""
allow_create_poll = models.BooleanField(default=False)
"""If true, polls can be created in this state."""
allow_submitter_edit = models.BooleanField(default=False)
"""If true, the submitter can edit the motion in this state."""
dont_set_identifier = models.BooleanField(default=False)
2014-12-25 10:58:52 +01:00
"""
Decides if the motion gets an identifier.
If true, the motion does not get an identifier if the state change to
2014-12-25 10:58:52 +01:00
this one, else it does.
"""
2013-03-12 22:03:56 +01:00
show_state_extension_field = models.BooleanField(default=False)
"""
If true, an additional input field (from motion comment) is visible
to extend the state name. The full state name is composed of the given
state name and the entered value of this input field.
"""
2018-11-04 11:11:48 +01:00
merge_amendment_into_final = models.SmallIntegerField(default=0)
"""
Relevant for amendments:
1: Amendments of this status or recommendation will be merged into the
2018-11-04 11:11:48 +01:00
final version of the motion.
0: Undefined.
-1: Amendments of this status or recommendation will not be merged into the
final version of the motion.
(Hint: The status field takes precedence. That means, if status is 1 or -1,
this is the final decision. The recommendation only is considered if the
status is 0)
"""
show_recommendation_extension_field = models.BooleanField(default=False)
"""
If true, an additional input field (from motion comment) is visible
to extend the recommendation label. The full recommendation string is
composed of the given recommendation label and the entered value of this input field.
"""
2015-12-10 00:20:59 +01:00
class Meta:
default_permissions = ()
def __str__(self):
"""Returns the name of the state."""
return self.name
def save(self, **kwargs):
"""Saves a state in the database.
Used to check the integrity before saving. Also used to check that
recommendation_label is not an empty string.
"""
self.check_next_states()
2019-01-06 16:22:33 +01:00
if self.recommendation_label == "":
raise WorkflowError(
2019-01-12 23:01:42 +01:00
f"The field recommendation_label of {self} must not "
"be an empty string."
2019-01-06 16:22:33 +01:00
)
super(State, self).save(**kwargs)
def check_next_states(self):
"""Checks whether all next states of a state belong to the correct workflow."""
# No check if it is a new state which has not been saved yet.
if not self.id:
return
for state in self.next_states.all():
if not state.workflow == self.workflow:
2019-01-06 16:22:33 +01:00
raise WorkflowError(
2019-01-12 23:01:42 +01:00
f"{state} can not be next state of {self} because it does not belong to the same workflow."
2019-01-06 16:22:33 +01:00
)
2019-02-08 09:48:58 +01:00
def is_next_or_previous_state_id(self, state_id):
""" Returns true, if the given state id is a valid next or previous state """
next_state_ids = [item.id for item in self.next_states.all()]
previous_state_ids = [
item.id for item in State.objects.filter(next_states__in=[self.id])
]
return state_id in next_state_ids or state_id in previous_state_ids
class WorkflowManager(BaseManager):
2016-09-30 20:42:58 +02:00
"""
Customized model manager to support our get_prefetched_queryset method.
2016-09-30 20:42:58 +02:00
"""
2019-01-06 16:22:33 +01:00
def get_prefetched_queryset(self, *args, **kwargs):
2016-09-30 20:42:58 +02:00
"""
Returns the normal queryset with all workflows. In the background
all states are prefetched from the database.
2016-09-30 20:42:58 +02:00
"""
2019-01-06 16:22:33 +01:00
return (
super().get_prefetched_queryset(*args, **kwargs).prefetch_related("states")
2019-01-06 16:22:33 +01:00
)
class Workflow(RESTModelMixin, models.Model):
"""
Defines a workflow for a motion.
"""
2019-01-06 16:22:33 +01:00
access_permissions = WorkflowAccessPermissions()
objects = WorkflowManager()
name = models.CharField(max_length=255)
"""A string representing the workflow."""
first_state = models.OneToOneField(
State, on_delete=models.CASCADE, related_name="+", null=True
2019-01-06 16:22:33 +01:00
)
"""A one-to-one relation to a state, the starting point for the workflow."""
2015-12-10 00:20:59 +01:00
class Meta:
default_permissions = ()
def __str__(self):
"""Returns the name of the workflow."""
return self.name
def save(self, **kwargs):
"""Saves a workflow in the database.
Used to check the integrity before saving.
"""
self.check_first_state()
super(Workflow, self).save(**kwargs)
def check_first_state(self):
"""Checks whether the first_state itself belongs to the workflow."""
if self.first_state and not self.first_state.workflow == self:
raise WorkflowError(
2019-01-12 23:01:42 +01:00
f"{self.first_state} can not be first state of {self} because it "
"does not belong to it."
2019-01-06 16:22:33 +01:00
)