Beispiel #1
0
def get_config_variables():
    """
    Generator which yields all config variables of this app.

    There are two main groups: 'General' and 'Projector'. The group 'General'
    has subgroups. The generator has to be evaluated during app loading
    (see apps.py).
    """
    yield ConfigVariable(
        name="general_event_name",
        default_value="OpenSlides",
        label="Event name",
        weight=110,
        subgroup="Event",
        validators=(MaxLengthValidator(100), ),
    )

    yield ConfigVariable(
        name="general_event_description",
        default_value="Presentation and assembly system",
        label="Short description of event",
        weight=115,
        subgroup="Event",
        validators=(MaxLengthValidator(100), ),
    )

    yield ConfigVariable(
        name="general_event_date",
        default_value="",
        label="Event date",
        weight=120,
        subgroup="Event",
    )

    yield ConfigVariable(
        name="general_event_location",
        default_value="",
        label="Event location",
        weight=125,
        subgroup="Event",
    )

    yield ConfigVariable(
        name="general_event_legal_notice",
        default_value='<a href="http://www.openslides.org">OpenSlides</a> is a '
        "free web based presentation and assembly system for "
        "visualizing and controlling agenda, motions and "
        "elections of an assembly.",
        input_type="markupText",
        label="Legal notice",
        weight=131,
        subgroup="Event",
        hidden=True,
    )

    yield ConfigVariable(
        name="general_event_privacy_policy",
        default_value="",
        input_type="markupText",
        label="Privacy policy",
        weight=132,
        subgroup="Event",
        hidden=True,
    )

    yield ConfigVariable(
        name="general_event_welcome_title",
        default_value="Welcome to OpenSlides",
        label="Front page title",
        weight=133,
        subgroup="Event",
        hidden=True,
    )

    yield ConfigVariable(
        name="general_event_welcome_text",
        default_value="[Space for your welcome text.]",
        input_type="markupText",
        label="Front page text",
        weight=134,
        subgroup="Event",
        hidden=True,
    )

    # Live conference

    yield ConfigVariable(
        name="general_system_conference_show",
        default_value=False,
        input_type="boolean",
        label="Show live conference window",
        help_text=
        "Server settings required to activate Jitsi Meet integration.",
        weight=140,
        subgroup="Live conference",
    )

    yield ConfigVariable(
        name="general_system_conference_los_restriction",
        default_value=False,
        input_type="boolean",
        label=
        "Allow only current speakers and list of speakers managers to enter the live conference",
        help_text=
        "Server settings required to activate Jitsi Meet integration.",
        weight=141,
        subgroup="Live conference",
    )

    yield ConfigVariable(
        name="general_system_conference_auto_connect",
        default_value=False,
        input_type="boolean",
        label="Connect all users to live conference automatically",
        help_text=
        "Server settings required to activate Jitsi Meet integration.",
        weight=142,
        subgroup="Live conference",
    )

    yield ConfigVariable(
        name="general_system_conference_open_microphone",
        default_value=False,
        input_type="boolean",
        label="Automatically open the microphone for new conference speakers",
        help_text=
        "Server settings required to activate Jitsi Meet integration.",
        weight=143,
        subgroup="Live conference",
    )

    yield ConfigVariable(
        name="general_system_conference_open_video",
        default_value=False,
        input_type="boolean",
        label="Automatically open the web cam for new conference speakers",
        help_text=
        "Server settings required to activate Jitsi Meet integration.",
        weight=144,
        subgroup="Live conference",
    )

    yield ConfigVariable(
        name="general_system_conference_auto_connect_next_speakers",
        default_value=0,
        input_type="integer",
        label=
        "Number of next speakers automatically connecting to the live conference",
        help_text=
        "Live conference has to be active. Choose 0 to disable auto connect.",
        weight=145,
        subgroup="Live conference",
    )

    yield ConfigVariable(
        name="general_system_stream_url",
        default_value="",
        label="Livestream url",
        help_text=
        "Remove URL to deactivate livestream. Check extra group permission to see livestream.",
        weight=146,
        subgroup="Live conference",
    )

    yield ConfigVariable(
        name="general_system_stream_poster",
        default_value="",
        label="Livestream poster image url",
        help_text=
        "Shows if livestream is not started. Recommended image format: 500x200px, PNG or JPG",
        weight=147,
        subgroup="Live conference",
    )

    # General System

    yield ConfigVariable(
        name="general_system_enable_anonymous",
        default_value=False,
        input_type="boolean",
        label="Allow access for anonymous guest users",
        weight=150,
        subgroup="System",
    )

    yield ConfigVariable(
        name="general_login_info_text",
        default_value="",
        label="Show this text on the login page",
        weight=152,
        subgroup="System",
    )

    yield ConfigVariable(
        name="openslides_theme",
        default_value="openslides-default-light-theme",
        input_type="choice",
        label="OpenSlides Theme",
        choices=(
            {
                "value": "openslides-default-light-theme",
                "display_name": "OpenSlides Default",
            },
            {
                "value": "openslides-default-dark-theme",
                "display_name": "OpenSlides Dark",
            },
            {
                "value": "openslides-red-light-theme",
                "display_name": "OpenSlides Red"
            },
            {
                "value": "openslides-red-dark-theme",
                "display_name": "OpenSlides Red Dark",
            },
            {
                "value": "openslides-green-light-theme",
                "display_name": "OpenSlides Green",
            },
            {
                "value": "openslides-green-dark-theme",
                "display_name": "OpenSlides Green Dark",
            },
            {
                "value": "openslides-solarized-dark-theme",
                "display_name": "OpenSlides Solarized",
            },
        ),
        weight=154,
        subgroup="System",
    )

    # General export settings

    yield ConfigVariable(
        name="general_csv_separator",
        default_value=",",
        label="Separator used for all csv exports and examples",
        weight=160,
        subgroup="Export",
    )

    yield ConfigVariable(
        name="general_csv_encoding",
        default_value="utf-8",
        input_type="choice",
        label="Default encoding for all csv exports",
        choices=(
            {
                "value": "utf-8",
                "display_name": "UTF-8"
            },
            {
                "value": "iso-8859-15",
                "display_name": "ISO-8859-15"
            },
        ),
        weight=162,
        subgroup="Export",
    )

    yield ConfigVariable(
        name="general_export_pdf_pagenumber_alignment",
        default_value="center",
        input_type="choice",
        label="Page number alignment in PDF",
        choices=(
            {
                "value": "left",
                "display_name": "Left"
            },
            {
                "value": "center",
                "display_name": "Center"
            },
            {
                "value": "right",
                "display_name": "Right"
            },
        ),
        weight=164,
        subgroup="Export",
    )

    yield ConfigVariable(
        name="general_export_pdf_fontsize",
        default_value="10",
        input_type="choice",
        label="Standard font size in PDF",
        choices=(
            {
                "value": "10",
                "display_name": "10"
            },
            {
                "value": "11",
                "display_name": "11"
            },
            {
                "value": "12",
                "display_name": "12"
            },
        ),
        weight=166,
        subgroup="Export",
    )

    yield ConfigVariable(
        name="general_export_pdf_pagesize",
        default_value="A4",
        input_type="choice",
        label="Standard page size in PDF",
        choices=(
            {
                "value": "A4",
                "display_name": "DIN A4"
            },
            {
                "value": "A5",
                "display_name": "DIN A5"
            },
        ),
        weight=168,
        subgroup="Export",
    )

    # Logos
    yield ConfigVariable(
        name="logos_available",
        default_value=[
            "logo_projector_main",
            "logo_projector_header",
            "logo_web_header",
            "logo_pdf_header_L",
            "logo_pdf_header_R",
            "logo_pdf_footer_L",
            "logo_pdf_footer_R",
            "logo_pdf_ballot_paper",
        ],
        weight=300,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_projector_main",
        default_value={
            "display_name": "Projector logo",
            "path": ""
        },
        input_type="static",
        weight=301,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_projector_header",
        default_value={
            "display_name": "Projector header image",
            "path": ""
        },
        input_type="static",
        weight=302,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_web_header",
        default_value={
            "display_name": "Web interface header logo",
            "path": ""
        },
        input_type="static",
        weight=303,
        group="Logo",
        hidden=True,
    )

    # PDF logos
    yield ConfigVariable(
        name="logo_pdf_header_L",
        default_value={
            "display_name": "PDF header logo (left)",
            "path": ""
        },
        input_type="static",
        weight=310,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_pdf_header_R",
        default_value={
            "display_name": "PDF header logo (right)",
            "path": ""
        },
        input_type="static",
        weight=311,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_pdf_footer_L",
        default_value={
            "display_name": "PDF footer logo (left)",
            "path": ""
        },
        input_type="static",
        weight=312,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_pdf_footer_R",
        default_value={
            "display_name": "PDF footer logo (right)",
            "path": ""
        },
        input_type="static",
        weight=313,
        group="Logo",
        hidden=True,
    )

    yield ConfigVariable(
        name="logo_pdf_ballot_paper",
        default_value={
            "display_name": "PDF ballot paper logo",
            "path": ""
        },
        input_type="static",
        weight=314,
        group="Logo",
        hidden=True,
    )

    # Fonts
    yield ConfigVariable(
        name="fonts_available",
        default_value=[
            "font_regular",
            "font_italic",
            "font_bold",
            "font_bold_italic",
            "font_monospace",
        ],
        weight=320,
        group="Font",
        hidden=True,
    )

    yield ConfigVariable(
        name="font_regular",
        default_value={
            "display_name": "Font regular",
            "default": "assets/fonts/fira-sans-latin-400.woff",
            "path": "",
        },
        input_type="static",
        weight=321,
        group="Font",
        hidden=True,
    )

    yield ConfigVariable(
        name="font_italic",
        default_value={
            "display_name": "Font italic",
            "default": "assets/fonts/fira-sans-latin-400italic.woff",
            "path": "",
        },
        input_type="static",
        weight=321,
        group="Font",
        hidden=True,
    )

    yield ConfigVariable(
        name="font_bold",
        default_value={
            "display_name": "Font bold",
            "default": "assets/fonts/fira-sans-latin-500.woff",
            "path": "",
        },
        input_type="static",
        weight=321,
        group="Font",
        hidden=True,
    )

    yield ConfigVariable(
        name="font_bold_italic",
        default_value={
            "display_name": "Font bold italic",
            "default": "assets/fonts/fira-sans-latin-500italic.woff",
            "path": "",
        },
        input_type="static",
        weight=321,
        group="Font",
        hidden=True,
    )

    yield ConfigVariable(
        name="font_monospace",
        default_value={
            "display_name": "Font monospace",
            "default": "assets/fonts/roboto-condensed-bold.woff",
            "path": "",
        },
        input_type="static",
        weight=321,
        group="Font",
        hidden=True,
    )

    # Custom translations
    yield ConfigVariable(
        name="translations",
        label="Custom translations",
        default_value=[],
        input_type="translations",
        weight=1000,
        group="Custom translations",
    )

    # Config version and DB id
    yield ConfigVariable(
        name="config_version",
        input_type="integer",
        default_value=1,
        group="Version",
        hidden=True,
    )
    yield ConfigVariable(
        name="db_id",
        input_type="string",
        default_value=uuid.uuid4().hex,
        group="Version",
        hidden=True,
    )
Beispiel #2
0
class Event(caching.base.CachingMixin, models.Model):
    """Event Model."""
    name = models.CharField(max_length=100)
    slug = models.SlugField(blank=True, max_length=100)
    start = models.DateTimeField()
    end = models.DateTimeField()
    timezone = models.CharField(max_length=100)
    venue = models.CharField(max_length=150)
    city = models.CharField(max_length=50, blank=False, default='')
    region = models.CharField(max_length=50,
                              null=False,
                              blank=True,
                              default='')
    country = models.CharField(max_length=50)
    lat = models.FloatField()
    lon = models.FloatField()
    external_link = models.URLField(max_length=300, null=True, blank=True)
    owner = models.ForeignKey(User, related_name='events_created')
    planning_pad_url = models.URLField(blank=True, max_length=300)
    estimated_attendance = models.PositiveIntegerField()
    description = models.TextField(
        validators=[MaxLengthValidator(500),
                    MinLengthValidator(20)])
    extra_content = models.TextField(blank=True, default='')
    mozilla_event = models.BooleanField(default=False)
    hashtag = models.CharField(max_length=50, blank=True, default='')
    attendees = models.ManyToManyField(User,
                                       related_name='events_attended',
                                       through='Attendance')
    converted_visitors = models.PositiveIntegerField(editable=False, default=0)
    swag_bug = models.ForeignKey(Bug,
                                 null=True,
                                 blank=True,
                                 on_delete=models.SET_NULL,
                                 related_name='event_swag_requests')
    budget_bug = models.ForeignKey(Bug,
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   related_name='event_budget_requests')
    times_edited = models.PositiveIntegerField(default=0, editable=False)
    categories = models.ManyToManyField(FunctionalArea,
                                        related_name='events_categories')

    objects = caching.base.CachingManager()

    def __unicode__(self):
        """Event unicode representation."""
        return self.name

    def _make_local(self, obj):
        """Return a datetime obj localized in self.timezone."""
        if not obj:
            return None
        t = timezone(self.timezone)
        return obj.astimezone(t)

    def save(self, *args, **kwargs):
        """Overrides save() method to increment number of event edits."""
        self.times_edited += 1
        super(Event, self).save(*args, **kwargs)

    @property
    def local_start(self):
        """Property to start datetime localized."""
        return self._make_local(self.start)

    @property
    def local_end(self):
        """Property to end datetime localized."""
        return self._make_local(self.end)

    class Meta:
        ordering = ['start']
        permissions = (('can_subscribe_to_events', 'Can subscribe to events'),
                       ('can_edit_events', 'Can edit events'),
                       ('can_delete_events',
                        'Can delete events'), ('can_delete_event_comments',
                                               'Can delete event comments'))
Beispiel #3
0
class Favorite(models.Model):
    user = models.ForeignKey(
        User,
        help_text="The user that owns the favorite",
        related_name="favorites",
        on_delete=models.CASCADE,
    )
    cluster_id = models.ForeignKey(
        OpinionCluster,
        verbose_name="the opinion cluster that is favorited",
        on_delete=models.CASCADE,
        null=True,
        blank=True,
    )
    audio_id = models.ForeignKey(
        Audio,
        verbose_name="the audio file that is favorited",
        on_delete=models.CASCADE,
        null=True,
        blank=True,
    )
    docket_id = models.ForeignKey(
        Docket,
        verbose_name="the docket that is favorited",
        on_delete=models.CASCADE,
        null=True,
        blank=True,
    )
    recap_doc_id = models.ForeignKey(
        RECAPDocument,
        verbose_name="the RECAP document that is favorited",
        on_delete=models.CASCADE,
        null=True,
        blank=True,
    )
    date_created = models.DateTimeField(
        help_text="The original creation date for the item",
        auto_now_add=True,
        db_index=True,
    )
    date_modified = models.DateTimeField(
        auto_now=True, db_index=True, null=True
    )
    name = models.CharField("a name for the alert", max_length=100)
    notes = models.TextField(
        "notes about the favorite",
        validators=[MaxLengthValidator(500)],
        max_length=500,
        blank=True,
    )

    class Meta:
        unique_together = (
            ("cluster_id", "user"),
            ("audio_id", "user"),
            ("docket_id", "user"),
            ("recap_doc_id", "user"),
        )

    def __unicode__(self):
        return u"Favorite %s" % self.id
Beispiel #4
0
class Message(models.Model):
    contest = models.ForeignKey(Contest, null=True, blank=True)
    round = models.ForeignKey(Round, null=True, blank=True)
    problem_instance = models.ForeignKey(ProblemInstance,
                                         null=True,
                                         blank=True)
    top_reference = models.ForeignKey('self', null=True, blank=True)
    author = models.ForeignKey(User)
    kind = EnumField(message_kinds, default='QUESTION', verbose_name=_("kind"))
    topic = models.CharField(
        max_length=255,
        verbose_name=_("topic"),
        validators=[MaxLengthValidator(255), validate_whitespaces])
    content = models.TextField(verbose_name=_("content"))
    date = models.DateTimeField(default=timezone.now,
                                editable=False,
                                verbose_name=_("date"))
    pub_date = models.DateTimeField(default=None,
                                    blank=True,
                                    null=True,
                                    verbose_name=_("publication date"))

    def save(self, *args, **kwargs):
        # Assert integrity in this Message
        if not self._has_category():
            assert self.top_reference and self.top_reference._has_category()
            self.problem_instance = self.top_reference.problem_instance
            self.round = self.top_reference.round
        elif self.problem_instance:
            self.round = self.problem_instance.round
        self.contest = self.round.contest

        # Propagate to all related Messages
        if self.top_reference:
            related = Message.objects.filter(
                Q(id=self.top_reference_id)
                | Q(top_reference_id=self.top_reference_id))
        else:
            related = self.message_set.all()
        if self.id:
            related.exclude(id=self.id)
        related.update(round=self.round,
                       contest=self.contest,
                       problem_instance=self.problem_instance)

        super(Message, self).save(*args, **kwargs)

    def can_have_replies(self):
        return self.kind == 'QUESTION'

    def _has_category(self):
        return self.round is not None or self.problem_instance is not None

    def __unicode__(self):
        return u'%s - %s' % (message_kinds.get(self.kind,
                                               self.kind), self.topic)

    @property
    def to_quote(self):
        lines = self.content.strip().split('\n')
        return ''.join('> ' + l for l in lines)

    def get_absolute_url(self):
        link = reverse('message',
                       kwargs={
                           'contest_id':
                           self.contest.id,
                           'message_id':
                           self.top_reference_id
                           if self.top_reference_id is not None else self.id
                       })
        return link

    def get_user_date(self):
        """ returns date visible by a user """
        return self.pub_date if self.pub_date is not None else self.date
Beispiel #5
0
class SalesOrder(FieldGroup):
    sender_id = Field(name='SenderId', validators=[MaxLengthValidator(5)], required=True)
    reference = Field(name='Reference', validators=[MaxLengthValidator(10)])
    original_order = Field(name='OriginalOrder', validators=[MaxLengthValidator(10)])
    contract_number = Field(name='ContractNumber', validators=[MaxLengthValidator(11)])
    order_type = Field(name='OrderType', validators=[MaxLengthValidator(4)], required=True)
    sales_org = Field(name='SalesOrg', validators=[MaxLengthValidator(4)], required=True)
    distribution_channel = Field(name='DistributionChannel', validators=[MaxLengthValidator(2)],
                                 required=True)
    division = Field(name='Division', validators=[MaxLengthValidator(2)], required=True)
    sales_office = Field(name='SalesOffice', validators=[MaxLengthValidator(4)], required=True)
    sales_group = Field(name='SalesGroup', validators=[MaxLengthValidator(3)])
    po_number = Field(name='PONumber', validators=[MaxLengthValidator(35)])
    billing_block = Field(name='BillingBlock', validators=[MaxLengthValidator(4)])
    sales_district = Field(name='SalesDistrict', validators=[MaxLengthValidator(6)])
    hidden_text_l1 = Field(name='HiddenTextL1', validators=[MaxLengthValidator(70)])
    hidden_text_l2 = Field(name='HiddenTextL2', validators=[MaxLengthValidator(70)])
    hidden_text_l3 = Field(name='HiddenTextL3', validators=[MaxLengthValidator(70)])
    hidden_text_l4 = Field(name='HiddenTextL4', validators=[MaxLengthValidator(70)])
    hidden_text_l5 = Field(name='HiddenTextL5', validators=[MaxLengthValidator(70)])
    hidden_text_l6 = Field(name='HiddenTextL6', validators=[MaxLengthValidator(70)])
    bill_text_l1 = Field(name='BillTextL1', validators=[MaxLengthValidator(70)])
    bill_text_l2 = Field(name='BillTextL2', validators=[MaxLengthValidator(70)])
    bill_text_l3 = Field(name='BillTextL3', validators=[MaxLengthValidator(70)])
    bill_text_l4 = Field(name='BillTextL4', validators=[MaxLengthValidator(70)])
    bill_text_l5 = Field(name='BillTextL5', validators=[MaxLengthValidator(70)])
    bill_text_l6 = Field(name='BillTextL6', validators=[MaxLengthValidator(70)])
    reference_text = Field(name='ReferenceText', validators=[MaxLengthValidator(20)])
    pmntterm = Field(name='PMNTTERM', validators=[MaxLengthValidator(4)])
    order_reason = Field(name='OrderReason', validators=[MaxLengthValidator(3)])
    billing_date = Field(name='BillingDate', validators=[MaxLengthValidator(8)])
    pricing_date = Field(name='PricingDate', validators=[MaxLengthValidator(8)])
    value_date = Field(name='ValueDate', validators=[MaxLengthValidator(8)])
    payment_reference = Field(name='PaymentReference', validators=[MaxLengthValidator(30)])
    already_printed_flag = Field(name='AlreadyPrintedFlag', validators=[MaxLengthValidator(1)])

    # Sub elements
    order_party = Field(name='OrderParty', field_type=OrderParty)
    billing_party1 = Field(name='BillingParty1', field_type=BillingParty1)
    billing_party2 = Field(name='BillingParty2', field_type=BillingParty2)
    payer_party = Field(name='PayerParty', field_type=PayerParty)
    line_items = Field(name='LineItem', field_type=LineItem, many=True)

    class Meta:
        element_name = 'SBO_SalesOrder'

    def set_bill_texts_from_string(self, text):
        for num, line in enumerate(text.split('\n'), start=1):
            if num > 6:
                break

            setattr(self, 'bill_text_l{}'.format(num), line[:70])
Beispiel #6
0
class Question(BaseModel):

    # TODO: rename to just `slug`
    unislug = models.CharField(_('unicode slug'),
                               max_length=MAX_LENGTH_Q_SUBJECT,
                               null=True,
                               blank=True,
                               editable=False)
    author = models.ForeignKey(User,
                               related_name="questions",
                               verbose_name=_("author"))
    subject = models.CharField(_("question"), max_length=MAX_LENGTH_Q_SUBJECT)
    content = models.TextField(
        _("details"),
        validators=[MaxLengthValidator(MAX_LENGTH_Q_CONTENT)],
        help_text=_("Please enter your content in no more than %s letters") %
        MAX_LENGTH_Q_CONTENT,
        blank=True,
        default='')
    rating = models.IntegerField(_("rating"), default=1)
    flags_count = models.IntegerField(_("flags counter"), default=0)
    tags = TaggableManager(through=TaggedQuestion, blank=True)
    sites = models.ManyToManyField(Site)
    # for easy access to current site questions
    objects = models.Manager()
    on_site = CurrentSiteManager()
    entity = models.ForeignKey(Entity,
                               null=True,
                               related_name="questions",
                               verbose_name=_("entity"))

    class Meta:
        unique_together = ('unislug', 'entity')

    def __unicode__(self):
        return self.subject

    def can_answer(self, user):
        ''' Can a given user answer self? '''
        if user.is_authenticated():
            profile = user.profile
            return profile.is_candidate and profile.locality == self.entity
        else:
            return False

    def get_absolute_url(self):
        return reverse('question_detail',
                       kwargs=dict(
                           entity_id=self.entity.id,
                           slug=self.unislug,
                       ))

    def save(self, **kwargs):
        # make a unicode slug from the subject
        self.unislug = unislugify(self.subject)
        return super(Question, self).save(**kwargs)

    @transaction.commit_on_success
    def flagged(self):
        self.flags_count += 1
        self.save()
        return self.flags_count

    def can_user_delete(self, user):
        ''' returns whether a secific user can delete the question '''
        if self.author == user:
            return True
        if user.is_authenticated() and\
           user.profile.is_editor and\
           user.profile.locality == self.entity:
            return True
        return False

    def can_vote(self, user):
        ''' returns whether a secific user can upvote/downvote the question,
            or neither '''
        if self.entity.can_vote(user):
            if user.upvotes.filter(question=self).exists():
                return 'down'
            else:
                return 'up'
        return None
Beispiel #7
0
def hack_validators(validators, length=100):
    from django.core.validators import MaxLengthValidator
    for key, validator in enumerate(validators):
        if isinstance(validator, MaxLengthValidator):
            validators.pop(key)
    validators.insert(0, MaxLengthValidator(length))
class EntityClass(models.Model):
    '''
        This Class: <EntityClass> is for to identify the class that an entity belongs.
        Esta Clase: <ClaseEntidad> es para identificar la clase que pertenece una entidad.
        For example:
            Economic Activity | Actividad Econónica
                >Primary Sector | Sector Primario
                >Secondary Sector | Sector Secundario 
                >Third Sector | Sector Terciario 
            Legal Form | Forma Jurídica
                >Individual Companies | Empresa Individual
                >Corporate Companies | Empresa Societario
            Size | Tamaño
                >Micro company | Micro Empresa
                >Small company | Pequeña Empresa
                >Medium company | Mediana Empresa
                >Big company | Gran Empresa
            Scope of Operation | Ámbito de Operación
                >Local companies | Empresas Locales
                >Regional | Regionales
                >Nationals | Nacionales
                >Multinationals | Multinacionales
            Capital Composition | Composición del Capital
                >Public Company | Empresa Pública
                >Private Company | Empresa Privada
                >Mixed Company | Empresa Mixta
                >Self-management company | Empresa de Autogestión
    '''
    ENTITY_SCOPE_CHOICES = [(entity_scope.value, entity_scope.value) for entity_scope in EntityScope]
    
    entity_scope = models.CharField(
        choices = ENTITY_SCOPE_CHOICES,
        max_length=50,
        db_index=True,
        help_text= 'Entity Scope | Ámbito Entidad'
    )
    name = models.CharField(
        max_length=100,
        unique=True,
        db_index=True,
        validators=[
            MinLengthValidator(1),
            MaxLengthValidator(100),
        ],
        help_text= 'Name | Nombre'
    )
    slug = models.SlugField(
        editable=False, 
        max_length=255,
        unique=True, 
        db_index=True 
    )
    
    def __str__(self):
        return '%s - %s' %(self.get_entity_scope(), self.get_name())

    def save(self, *args, **kwargs):
        if not self.pk:
            self.slug = slugify(self.get_name())
        else:
            slug = slugify(self.get_name())
            if self.slug != slug:
                self.slug = slug
        super(EntityClass, self).save(*args, **kwargs)

    #Setter
    def set_entity_scope(self, entity_scope):
        self.entity_scope = entity_scope

    def set_name(self, name):
        self.name = name
    
    #Getter
    def get_entity_scope(self):
        return self.entity_scope

    def get_name(self):
        return self.name

    class Meta:
        db_table = 'entity_classes'
        ordering = ['entity_scope', 'name']
        verbose_name = 'Entity Class'
        verbose_name_plural = 'Entity Classes'
Beispiel #9
0
class UserUpdate(models.Model):

    recipient = models.ForeignKey(User, related_name='recipient')
    discussion = models.ForeignKey(Discussion, null=True, blank=True)
    sender = models.ForeignKey(User,
                               related_name='applicabale_sender',
                               null=True,
                               blank=True)
    header = models.CharField(max_length=200)
    content = models.TextField(blank=True,
                               null=True,
                               validators=[MaxLengthValidator(MAX_TEXT)])
    details_url = models.CharField(max_length=200, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    already_read = models.BooleanField(default=False)

    def __unicode__(self):
        return self.header

    def can_user_access(self, viewing_user=None):
        if self.discussion:
            return self.discussion.can_user_access_discussion(viewing_user)
        if not self.recipient.userprofile.is_in_the_same_segment(viewing_user):
            return False

        if not self.recipient.userprofile.is_in_the_same_segment(viewing_user):
            return False

        if self.sender:
            if not self.sender.userprofile.is_in_the_same_segment(
                    viewing_user):
                return False

        return True

    def set_as_already_read(self):
        self.already_read = True
        self.save()

    def set_as_unread(self):
        self.already_read = False
        self.save()

    def get_if_already_read(self):
        return self.already_read

    def get_if_long(self):
        if self.header.endswith('...'):
            return True
        return False

    def print_content(self):
        print 'to:', self.recipient, 'head', self.header, 'content', self.content, 'from', self.sender, 'url', self.details_url
        if self.discussion:
            self.discussion.print_content()

    def get_absolute_url(self):
        return (reverse('coplay:user_update_details',
                        kwargs={'pk': str(self.id)}))

    def get_discussion(self):
        return self.discussion
Beispiel #10
0
    def __init__(self, survey, user, *args, **kwargs):
        self.survey = survey
        self.user = user if user.is_authenticated else None
        self.field_names = []
        self.questions = self.survey.questions.all().order_by('ordering')
        super().__init__(*args, **kwargs)

        for question in self.questions:
            # to generate field name
            field_name = f'field_survey_{question.id}'

            if question.type_field == TYPE_FIELD.multi_select:
                self.fields[field_name] = forms.MultipleChoiceField(
                    choices=make_choices(question),
                    label=question.label,
                    widget=CheckboxSelectMultipleSurvey,
                )
            elif question.type_field == TYPE_FIELD.radio:
                self.fields[field_name] = forms.ChoiceField(
                    choices=make_choices(question),
                    label=question.label,
                    widget=RadioSelectSurvey)
            elif question.type_field == TYPE_FIELD.select:
                self.fields[field_name] = forms.ChoiceField(
                    choices=make_choices(question), label=question.label)
            elif question.type_field == TYPE_FIELD.number:
                self.fields[field_name] = forms.IntegerField(
                    label=question.label)
            elif question.type_field == TYPE_FIELD.url:
                self.fields[field_name] = forms.URLField(
                    label=question.label,
                    validators=[
                        MaxLengthValidator(
                            SURVEY_FIELD_VALIDATORS['max_length']['url'])
                    ])
            elif question.type_field == TYPE_FIELD.email:
                self.fields[field_name] = forms.EmailField(
                    label=question.label,
                    validators=[
                        MaxLengthValidator(
                            SURVEY_FIELD_VALIDATORS['max_length']['email'])
                    ])
            elif question.type_field == TYPE_FIELD.date:
                self.fields[field_name] = forms.DateField(
                    label=question.label,
                    widget=DateSurvey(),
                    input_formats=DATE_INPUT_FORMAT)
            elif question.type_field == TYPE_FIELD.text_area:
                self.fields[field_name] = forms.CharField(
                    label=question.label, widget=forms.Textarea)
            elif question.type_field == TYPE_FIELD.rating:
                self.fields[field_name] = forms.CharField(label=question.label,
                                                          widget=RatingSurvey)
            else:
                self.fields[field_name] = forms.CharField(
                    label=question.label,
                    validators=[
                        MaxLengthValidator(
                            SURVEY_FIELD_VALIDATORS['max_length']['text'])
                    ])

            self.fields[field_name].required = question.required
            self.fields[field_name].help_text = question.help_text
            self.field_names.append(field_name)
Beispiel #11
0
def get_config_variables():
    """
    Generator which yields all config variables of this app.

    There are two main groups: 'General' and 'Projector'. The group 'General'
    has subgroups. The generator has to be evaluated during app loading
    (see apps.py).
    """
    yield ConfigVariable(
        name='general_event_name',
        default_value='OpenSlides',
        label='Event name',
        weight=110,
        group='General',
        subgroup='Event',
        validators=(MaxLengthValidator(100),))

    yield ConfigVariable(
        name='general_event_description',
        default_value='Presentation and assembly system',
        label='Short description of event',
        weight=115,
        group='General',
        subgroup='Event',
        validators=(MaxLengthValidator(100),))

    yield ConfigVariable(
        name='general_event_date',
        default_value='',
        label='Event date',
        weight=120,
        group='General',
        subgroup='Event')

    yield ConfigVariable(
        name='general_event_location',
        default_value='',
        label='Event location',
        weight=125,
        group='General',
        subgroup='Event')

    yield ConfigVariable(
        name='general_event_legal_notice',
        default_value='<a href="http://www.openslides.org">OpenSlides</a> is a '
                      'free web based presentation and assembly system for '
                      'visualizing and controlling agenda, motions and '
                      'elections of an assembly.',
        input_type='markupText',
        label='Legal notice',
        weight=132,
        group='General',
        subgroup='Event')

    yield ConfigVariable(
        name='general_event_privacy_policy',
        default_value='',
        input_type='markupText',
        label='Privacy policy',
        weight=132,
        group='General',
        subgroup='Event')

    yield ConfigVariable(
        name='general_event_welcome_title',
        default_value='Welcome to OpenSlides',
        label='Front page title',
        weight=134,
        group='General',
        subgroup='Event')

    yield ConfigVariable(
        name='general_event_welcome_text',
        default_value='[Space for your welcome text.]',
        input_type='markupText',
        label='Front page text',
        weight=136,
        group='General',
        subgroup='Event')

    # General System

    yield ConfigVariable(
        name='general_system_enable_anonymous',
        default_value=False,
        input_type='boolean',
        label='Allow access for anonymous guest users',
        weight=138,
        group='General',
        subgroup='System')

    yield ConfigVariable(
        name='general_login_info_text',
        default_value='',
        label='Show this text on the login page',
        weight=140,
        group='General',
        subgroup='System')

    # General export settings

    yield ConfigVariable(
        name='general_csv_separator',
        default_value=',',
        label='Separator used for all csv exports and examples',
        weight=142,
        group='General',
        subgroup='Export')

    yield ConfigVariable(
        name='general_export_pdf_pagenumber_alignment',
        default_value='center',
        input_type='choice',
        label='Page number alignment in PDF',
        choices=(
            {'value': 'left', 'display_name': 'Left'},
            {'value': 'center', 'display_name': 'Center'},
            {'value': 'right', 'display_name': 'Right'}),
        weight=144,
        group='General',
        subgroup='Export')

    yield ConfigVariable(
        name='general_export_pdf_fontsize',
        default_value='10',
        input_type='choice',
        label='Standard font size in PDF',
        choices=(
            {'value': '10', 'display_name': '10'},
            {'value': '11', 'display_name': '11'},
            {'value': '12', 'display_name': '12'}),
        weight=146,
        group='General',
        subgroup='Export')

    # Projector

    yield ConfigVariable(
        name='projector_language',
        default_value='browser',
        input_type='choice',
        label='Projector language',
        choices=(
            {'value': 'browser', 'display_name': 'Current browser language'},
            {'value': 'en', 'display_name': 'English'},
            {'value': 'de', 'display_name': 'Deutsch'},
            {'value': 'fr', 'display_name': 'Français'},
            {'value': 'es', 'display_name': 'Español'},
            {'value': 'pt', 'display_name': 'Português'},
            {'value': 'cs', 'display_name': 'Čeština'},
            {'value': 'ru', 'display_name': 'русский'}),
        weight=150,
        group='Projector')

    yield ConfigVariable(
        name='projector_enable_logo',
        default_value=True,
        input_type='boolean',
        label='Show logo on projector',
        help_text='You can replace the logo by uploading an image and set it as '
                  'the "Projector logo" in "files".',
        weight=152,
        group='Projector')

    yield ConfigVariable(
        name='projector_enable_clock',
        default_value=True,
        input_type='boolean',
        label='Show the clock on projector',
        weight=154,
        group='Projector')

    yield ConfigVariable(
        name='projector_enable_title',
        default_value=True,
        input_type='boolean',
        label='Show title and description of event on projector',
        weight=155,
        group='Projector')

    yield ConfigVariable(
        name='projector_enable_header_footer',
        default_value=True,
        input_type='boolean',
        label='Display header and footer',
        weight=157,
        group='Projector')

    yield ConfigVariable(
        name='projector_header_backgroundcolor',
        default_value='#317796',
        input_type='colorpicker',
        label='Background color of projector header and footer',
        weight=160,
        group='Projector')

    yield ConfigVariable(
        name='projector_header_fontcolor',
        default_value='#F5F5F5',
        input_type='colorpicker',
        label='Font color of projector header and footer',
        weight=165,
        group='Projector')

    yield ConfigVariable(
        name='projector_h1_fontcolor',
        default_value='#317796',
        input_type='colorpicker',
        label='Font color of projector headline',
        weight=170,
        group='Projector')

    yield ConfigVariable(
        name='projector_default_countdown',
        default_value=60,
        input_type='integer',
        label='Predefined seconds of new countdowns',
        weight=185,
        group='Projector')

    yield ConfigVariable(
        name='projector_blank_color',
        default_value='#FFFFFF',
        input_type='colorpicker',
        label='Color for blanked projector',
        weight=190,
        group='Projector')

    yield ConfigVariable(
        name='projector_broadcast',
        default_value=0,
        input_type='integer',
        label='Projector which is broadcasted',
        weight=200,
        group='Projector',
        hidden=True)

    yield ConfigVariable(
        name='projector_currentListOfSpeakers_reference',
        default_value=1,
        input_type='integer',
        label='Projector reference for list of speakers',
        weight=201,
        group='Projector',
        hidden=True)

    # Logos.
    yield ConfigVariable(
        name='logos_available',
        default_value=[
            'logo_projector_main',
            'logo_projector_header',
            'logo_web_header',
            'logo_pdf_header_L',
            'logo_pdf_header_R',
            'logo_pdf_footer_L',
            'logo_pdf_footer_R',
            'logo_pdf_ballot_paper'],
        weight=300,
        group='Logo',
        hidden=True)

    yield ConfigVariable(
        name='logo_projector_main',
        default_value={
            'display_name': 'Projector logo',
            'path': ''},
        input_type='static',
        weight=301,
        group='Logo',
        hidden=True)

    yield ConfigVariable(
        name='logo_projector_header',
        default_value={
            'display_name': 'Projector header image',
            'path': ''},
        input_type='static',
        weight=302,
        group='Logo',
        hidden=True)

    yield ConfigVariable(
        name='logo_web_header',
        default_value={
            'display_name': 'Web interface header logo',
            'path': ''},
        input_type='static',
        weight=303,
        group='Logo',
        hidden=True)

    # PDF logos
    yield ConfigVariable(
        name='logo_pdf_header_L',
        default_value={
            'display_name': 'PDF header logo (left)',
            'path': ''},
        input_type='static',
        weight=310,
        group='Logo',
        hidden=True)

    yield ConfigVariable(
        name='logo_pdf_header_R',
        default_value={
            'display_name': 'PDF header logo (right)',
            'path': ''},
        input_type='static',
        weight=311,
        group='Logo',
        hidden=True)

    yield ConfigVariable(
        name='logo_pdf_footer_L',
        default_value={
            'display_name': 'PDF footer logo (left)',
            'path': ''},
        input_type='static',
        weight=312,
        group='Logo',
        hidden=True)

    yield ConfigVariable(
        name='logo_pdf_footer_R',
        default_value={
            'display_name': 'PDF footer logo (right)',
            'path': ''},
        input_type='static',
        weight=313,
        group='Logo',
        hidden=True)

    yield ConfigVariable(
        name='logo_pdf_ballot_paper',
        default_value={
            'display_name': 'PDF ballot paper logo',
            'path': ''},
        input_type='static',
        weight=314,
        group='Logo',
        hidden=True)

    # Fonts
    yield ConfigVariable(
        name='fonts_available',
        default_value=[
            'font_regular',
            'font_italic',
            'font_bold',
            'font_bold_italic'],
        weight=320,
        group='Font',
        hidden=True)

    yield ConfigVariable(
        name='font_regular',
        default_value={
            'display_name': 'Font regular',
            'default': 'static/fonts/Roboto-Regular.woff',
            'path': ''},
        input_type='static',
        weight=321,
        group='Font',
        hidden=True)

    yield ConfigVariable(
        name='font_italic',
        default_value={
            'display_name': 'Font italic',
            'default': 'static/fonts/Roboto-Medium.woff',
            'path': ''},
        input_type='static',
        weight=321,
        group='Font',
        hidden=True)

    yield ConfigVariable(
        name='font_bold',
        default_value={
            'display_name': 'Font bold',
            'default': 'static/fonts/Roboto-Condensed-Regular.woff',
            'path': ''},
        input_type='static',
        weight=321,
        group='Font',
        hidden=True)

    yield ConfigVariable(
        name='font_bold_italic',
        default_value={
            'display_name': 'Font bold italic',
            'default': 'static/fonts/Roboto-Condensed-Light.woff',
            'path': ''},
        input_type='static',
        weight=321,
        group='Font',
        hidden=True)

    # Custom translations
    yield ConfigVariable(
        name='translations',
        label='Custom translations',
        default_value=[],
        input_type='translations',
        weight=1000,
        group='Custom translations')
Beispiel #12
0
class OccupationType(models.Model):
    '''
        This Class: <OccupationType> is to identify the type of occupation.
        Esta Clase: <TipoOcupación> es para identificar el tipo de ocupación.

        For example:
            Pescador - Pesc.
            Cocinero - Coc.
    '''
    name = models.CharField(
        max_length=100,
        unique=True,
        db_index=True,
        validators=[
            MinLengthValidator(1),
            MaxLengthValidator(100),
        ], 
        help_text= 'Name | Nombre'
    )
    abbreviation = models.CharField(
        max_length=20,
        unique=True,
        db_index=True,
        validators=[
            MinLengthValidator(1),
            MaxLengthValidator(20),
        ], 
        help_text= 'Abbreviation | Abreviación'
    )
    slug = models.SlugField(
        editable=False, 
        max_length=255,
        unique=True, 
        db_index=True 
    )

    def __str__(self):
        return '%s - %s' %(self.get_name(), self.get_abbreviation())

    def save(self, *args, **kwargs):
        if not self.pk:
            self.slug = slugify(self.get_name())
        else:
            slug = slugify(self.get_name())
            if self.slug != slug:
                self.slug = slug
        super(EmployeePosition, self).save(*args, **kwargs)

    #Setter
    def set_name(self, name):
        self.name = name
    
    def set_abbreviation(self, abbreviation):
        self.abbreviation = abbreviation
    
    #Getter
    def get_name(self):
        return self.name
   
    def get_abbreviation(self):
        return self.abbreviation

    class Meta:
        db_table = 'occupation_types'
        ordering = ['name', 'abbreviation']
        verbose_name = 'Occupation Type'
        verbose_name_plural = 'Occupation Types'
Beispiel #13
0
     "validators": [MinValueValidator(5)]
 }],
 'gpio':
 ['django.forms.IntegerField', {
     "validators": [MaxValueValidator(4)]
 }],
 'parallel':
 ['django.forms.IntegerField', {
     "validators": [MaxValueValidator(3)]
 }],
 'scanning':
 ['django.forms.IntegerField', {
     "validators": [MaxValueValidator(1)]
 }],
 'rgb': ['django.forms.CharField', {
     "validators": [MaxLengthValidator(3)]
 }],
 'row_addr':
 ['django.forms.IntegerField', {
     "validators": [MaxValueValidator(1)]
 }],
 'hat_choices': [
     'django.forms.fields.ChoiceField', {
         'widget':
         'django.forms.Select',
         'choices':
         (("regular", "regular"), ("adafruit-hat", "adafruit-hat"),
          ("adafruit-hat-pwm", "adafruit-hat-pwm"))
     }
 ],
 'multiplexing': [
class stu_details(models.Model):
    branch_choices = (
        ('it', 'information_technology'),
        ('me', 'mech'),
        ('ce', 'civil'),
        ('eee', 'eee'),
        ('ece', 'ece'),
        ('ch', 'chemical'),
        ('cse', 'cse'),
    )
    gender = (('male', 'male'), ('female', 'female'), ('others', 'others'))

    username = models.CharField(max_length=9,
                                blank=False,
                                help_text="enter username ex:y16it***",
                                default="y1")
    name = models.CharField(max_length=30,
                            blank=False,
                            help_text='*required',
                            default="full name")
    phone_number = models.CharField(
        validators=[MaxLengthValidator(10),
                    MinLengthValidator(10)],
        help_text='*required',
        max_length=10)
    fathers_name = models.CharField(max_length=30,
                                    blank=False,
                                    help_text='*required')
    mothers_name = models.CharField(max_length=30,
                                    blank=False,
                                    help_text='*required')
    gender = models.CharField(blank=False, choices=gender, max_length=10)
    place = models.CharField(max_length=30, blank=False)
    branch = models.CharField(blank=False,
                              choices=branch_choices,
                              max_length=10)
    cgpa_Btech = models.FloatField(
        validators=[MinValueValidator(0),
                    MaxValueValidator(10)],
        blank=False,
        help_text='*required')
    class_10_cgpa = models.FloatField(
        validators=[MinValueValidator(0),
                    MaxValueValidator(10)],
        blank=False,
        help_text='*required')
    class_12_percentage = models.FloatField(
        validators=[MinValueValidator(0),
                    MaxValueValidator(100)],
        blank=False,
        help_text='*required')
    certifications_count = models.IntegerField(blank=False)
    internship = models.CharField(blank=False, choices=done, max_length=10)
    languages = models.CharField(max_length=100,
                                 blank=False,
                                 help_text='*required')
    sop = models.CharField(max_length=500,
                           default="statement of purpose",
                           help_text='*required')
    dob = models.DateField(
        blank=False,
        help_text='*format is YYYY-MM-DD',
    )
    email = models.EmailField(
        max_length=254,
        blank=False,
        help_text='Required. Inform a valid email address.',
        default="*****@*****.**")

    def __str__(self):
        return self.username
Beispiel #15
0
class Profile(models.Model):

    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    slug = sluggable_fields.SluggableField(
        decider=ProfileSlug, populate_from="name", slugify=slugify_user, unique=True
    )
    is_public = models.BooleanField(default=True)
    name = models.CharField(max_length=200, validators=[validate_sluggable_name])
    image = thumbnail.ImageField(
        upload_to=upload_path.auto_cleaned_path_stripped_uuid4, blank=True
    )
    city_or_town = models.CharField(max_length=100, blank=True)
    country = models.CharField(max_length=100, blank=True)
    linkedin_url = models.URLField(max_length=400, blank=True)
    facebook_url = models.URLField(max_length=400, blank=True)
    personal_website_url = models.URLField(max_length=400, blank=True)
    lat = models.FloatField(null=True, blank=True, default=None)
    lon = models.FloatField(null=True, blank=True, default=None)
    cause_areas = postgres_fields.ArrayField(
        enum.EnumField(CauseArea), blank=True, default=list
    )
    cause_areas_other = models.TextField(
        blank=True, validators=[MaxLengthValidator(2000)]
    )
    available_to_volunteer = models.BooleanField(null=True, blank=True, default=None)
    open_to_job_offers = models.BooleanField(null=True, blank=True, default=None)
    expertise_areas = postgres_fields.ArrayField(
        enum.EnumField(ExpertiseArea), blank=True, default=list
    )
    expertise_areas_other = models.TextField(
        blank=True, validators=[MaxLengthValidator(2000)]
    )
    career_interest_areas = postgres_fields.ArrayField(
        enum.EnumField(ExpertiseArea), blank=True, default=list
    )
    available_as_speaker = models.BooleanField(null=True, blank=True, default=None)
    topics_i_speak_about = models.TextField(
        blank=True, validators=[MaxLengthValidator(2000)]
    )
    organisational_affiliations = postgres_fields.ArrayField(
        enum.EnumField(OrganisationalAffiliation), blank=True, default=list
    )
    summary = models.TextField(blank=True, validators=[MaxLengthValidator(2000)])
    giving_pledges = postgres_fields.ArrayField(
        enum.EnumField(GivingPledge), blank=True, default=list
    )
    local_groups = models.ManyToManyField(LocalGroup, through="Membership", blank=True)
    legacy_record = models.PositiveIntegerField(
        null=True, default=None, editable=False, unique=True
    )

    slugs = contenttypes_fields.GenericRelation(ProfileSlug)

    objects = ProfileManager()

    class Meta:
        ordering = ["name", "slug"]

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return urls.reverse("profile", args=[self.slug])

    def geocode(self):
        self.lat = None
        self.lon = None
        if self.city_or_town and self.country:
            location = geocoders.Nominatim(timeout=10).geocode(
                f"{self.city_or_town}, {self.country}"
            )
            if location:
                self.lat = location.latitude
                self.lon = location.longitude
        return self

    def get_pretty_cause_areas(self):
        return prettify_property_list(
            CauseArea, self.cause_areas, self.cause_areas_other
        )

    def get_pretty_expertise(self):
        return prettify_property_list(
            ExpertiseArea, self.expertise_areas, self.expertise_areas_other
        )

    def get_pretty_career_interest_areas(self):
        return prettify_property_list(ExpertiseArea, self.career_interest_areas)

    def get_pretty_giving_pledges(self):
        if self.giving_pledges:
            return ", ".join(map(GivingPledge.label, self.giving_pledges))
        else:
            return "N/A"

    def get_pretty_organisational_affiliations(self):
        if self.organisational_affiliations:
            return ", ".join(
                map(OrganisationalAffiliation.label, self.organisational_affiliations)
            )
        else:
            return "N/A"

    def get_pretty_local_groups(self):
        if self.local_groups:
            return ", ".join(
                [
                    "{local_group}".format(local_group=x.name)
                    for x in self.local_groups.all()
                ]
            )
        else:
            return "N/A"

    def write_data_export_zip(self, request, response):
        with zipfile.ZipFile(response, mode="w") as zip_file:
            with zip_file.open(
                f"{self.slug}.json", mode="w"
            ) as json_binary_file, io.TextIOWrapper(json_binary_file) as json_file:
                json.dump(
                    {
                        "email": self.user.email,
                        "date_joined": self.user.date_joined.isoformat(),
                        "last_login": self.user.last_login.isoformat(),
                        "url": request.build_absolute_uri(self.get_absolute_url()),
                        "is_public": self.is_public,
                        "name": self.name,
                        "city_or_town": self.city_or_town,
                        "country": self.country,
                        "cause_areas": list(map(CauseArea.label, self.cause_areas)),
                        "cause_areas_other": self.cause_areas_other,
                        "available_to_volunteer": self.available_to_volunteer,
                        "open_to_job_offers": self.open_to_job_offers,
                        "expertise_areas": list(
                            map(ExpertiseArea.label, self.expertise_areas)
                        ),
                        "expertise_areas_other": self.expertise_areas_other,
                        "career_interest_areas": list(
                            map(ExpertiseArea.label, self.career_interest_areas)
                        ),
                        "available_as_speaker": self.available_as_speaker,
                        "topics_i_speak_about": self.topics_i_speak_about,
                        "organisational_affiliations": list(
                            map(
                                OrganisationalAffiliation.label,
                                self.organisational_affiliations,
                            )
                        ),
                        "summary": self.summary,
                        "giving_pledges": list(
                            map(GivingPledge.label, self.giving_pledges)
                        ),
                        "member_of_local_groups": [
                            request.build_absolute_uri(local_group.get_absolute_uri())
                            for local_group in self.local_groups.all()
                        ],
                        "organiser_of_local_groups": [
                            request.build_absolute_uri(local_group.get_absolute_uri())
                            for local_group in self.user.localgroup_set.all()
                        ],
                        "aliases": [
                            request.build_absolute_uri(
                                urls.reverse("profile", kwargs={"slug": slug.slug})
                            )
                            for slug in self.slugs.filter(redirect=True)
                        ],
                        "legacy_hub_url": (
                            self.legacy_record
                            and request.build_absolute_uri(
                                urls.reverse(
                                    "profile_legacy",
                                    kwargs={"legacy_record": self.legacy_record},
                                )
                            )
                        ),
                    },
                    json_file,
                    indent=2,
                )
            if self.image:
                with self.image.open() as image_src_file, zip_file.open(
                    self.slug + pathlib.PurePath(self.image.name).suffix, mode="w"
                ) as image_dst_file:
                    shutil.copyfileobj(image_src_file, image_dst_file)

    def image_placeholder(self):
        return f"Avatar{self.id % 10}.png"

    def has_cause_area_details(self):
        cause_area_details_exist = [
            len(self.cause_areas) > 0,
            len(self.cause_areas_other) > 0,
            len(self.giving_pledges) > 0,
            self.available_to_volunteer,
        ]
        return any(cause_area_details_exist)

    def has_career_details(self):
        career_details_exist = [
            len(self.expertise_areas),
            len(self.expertise_areas_other),
            self.open_to_job_offers,
        ]
        return any(career_details_exist)

    def has_community_details(self):
        community_details_exist = [
            len(self.organisational_affiliations) > 0,
            self.local_groups.exists(),
            self.user.localgroup_set.exists(),
            self.available_as_speaker,
            len(self.topics_i_speak_about) > 0,
        ]
        return any(community_details_exist)
Beispiel #16
0
class Discussion(models.Model):
    owner = models.ForeignKey(User)
    title = models.CharField(_("title"), max_length=200)
    description = models.TextField(_("Description"),
                                   blank=True,
                                   null=True,
                                   validators=[MaxLengthValidator(MAX_TEXT)])
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    locked_at = models.DateTimeField(default=None, blank=True, null=True)
    description_updated_at = models.DateTimeField(default=None,
                                                  blank=True,
                                                  null=True)
    is_restricted = models.BooleanField(default=False)
    is_viewing_require_login = models.BooleanField(default=False)
    location = models.ForeignKey(Location, null=True, blank=True)
    latitude = models.FloatField(default=None, blank=True, null=True)
    longitude = models.FloatField(default=None, blank=True, null=True)
    location_desc = models.CharField(max_length=200,
                                     default=None,
                                     blank=True,
                                     null=True)
    tags = TaggableManager(blank=True)
    parent_url = models.URLField(max_length=MAX_TEXT,
                                 default=None,
                                 blank=True,
                                 null=True)
    parent_url_text = models.CharField(max_length=MAX_TEXT,
                                       default=None,
                                       blank=True,
                                       null=True)
    picture = models.ImageField(upload_to='uploads/%Y/%m/%d/',
                                null=True,
                                blank=True,
                                default=None,
                                max_length=50000)
    anyway_progress_status = models.IntegerField(default=None,
                                                 blank=True,
                                                 null=True)
    anyway_discuss_id = models.IntegerField(default=None,
                                            blank=True,
                                            null=True)
    movie_url = models.URLField(max_length=MAX_TEXT,
                                default=None,
                                blank=True,
                                null=True)
    movie_url_url_text = models.CharField(max_length=MAX_TEXT,
                                          default=None,
                                          blank=True,
                                          null=True)

    def __unicode__(self):
        return self.id

    def get_absolute_url(self):
        return (reverse('coplay:discussion_details',
                        kwargs={'pk': str(self.id)}))

    def update_description_obs(self,
                               description,
                               location_desc=None,
                               tags_string=None):
        self.description = description
        self.location_desc = location_desc
        tags_list = tags_string.split(',')
        for tag in tags_list:
            self.tags.add(tag)

        self.description_updated_at = timezone.now()
        self.save()  #cause all previous fedbacks to be striked at

    def add_feedback_obs(self, user, feedbabk_type, content):
        feedback = Feedback(discussion=self,
                            user=user,
                            feedbabk_type=feedbabk_type,
                            content=content)
        feedback.clean()
        feedback.save()
        #         control.user_posted_a_feedback_in_another_other_user_s_discussion(user, feedback.get_absolute_url())

        return feedback

    def add_decision_obs(self, content):
        decision = Decision(parent=self, content=content)
        decision.clean()
        decision.save()
        return decision

    def add_task_obs(self,
                     responsible,
                     goal_description,
                     target_date,
                     max_inactivity_seconds=MAX_INACTIVITY_SECONDS):

        task = self.task_set.create(parent=self,
                                    responsible=responsible,
                                    goal_description=goal_description,
                                    target_date=target_date)
        task.clean()
        task.save()
        self.unlock(max_inactivity_seconds)
        return task

    def unlock(self, max_inactivity_seconds=MAX_INACTIVITY_SECONDS):
        self.locked_at = timedelta(
            seconds=max_inactivity_seconds) + timezone.now()
        self.save()

    def is_active_and_time_to_inactivation_obsolete(
            self, max_inactivity_seconds=MAX_INACTIVITY_SECONDS):
        now = timezone.now()
        list_tasks = self.task_set.all().order_by("-created_at")
        if list_tasks:
            latest_task = list_tasks.first()
            if (latest_task.created_at +
                    timedelta(seconds=max_inactivity_seconds)) >= now:
                time_left = (latest_task.created_at +
                             timedelta(seconds=max_inactivity_seconds)) - now
                discussion_is_active = True
                return discussion_is_active, time_left
            if (self.created_at +
                    timedelta(seconds=max_inactivity_seconds)) >= now:
                discussion_is_active = True
                time_left = (self.created_at +
                             timedelta(seconds=max_inactivity_seconds)) - now
                return discussion_is_active, time_left
            discussion_is_active = False
            time_left = 0
            return discussion_is_active, time_left
        if (self.created_at +
                timedelta(seconds=max_inactivity_seconds)) >= now:
            discussion_is_active = True
            time_left = (self.created_at +
                         timedelta(seconds=max_inactivity_seconds)) - now
            return discussion_is_active, time_left

        discussion_is_active = False
        time_left = 0
        return discussion_is_active, time_left

    def is_active_and_time_to_inactivation(
            self, max_inactivity_seconds=MAX_INACTIVITY_SECONDS):
        now = timezone.now()
        if self.locked_at is None:  #init self.created_at for the first time
            discussion_is_active, time_left = self.is_active_and_time_to_inactivation_obsolete(
                max_inactivity_seconds)
            if discussion_is_active:
                self.locked_at = now + time_left
                self.save()
                return discussion_is_active, time_left
            list_tasks = self.task_set.all().order_by("-created_at")
            if list_tasks:
                latest_task = list_tasks.first()
                self.locked_at = latest_task.created_at + timedelta(
                    seconds=max_inactivity_seconds)
                self.save()
                return discussion_is_active, time_left

            self.locked_at = self.created_at + timedelta(
                seconds=max_inactivity_seconds)
            self.save()
            return discussion_is_active, time_left

        if now >= self.locked_at:
            discussion_is_active = False
            time_left = 0
            return discussion_is_active, time_left

        discussion_is_active = True

        time_left = self.locked_at - now

        return discussion_is_active, time_left

    def is_active(self):
        discussion_is_active, time_left = self.is_active_and_time_to_inactivation(
        )
        return discussion_is_active

    def get_time_to_inactivation(self):
        discussion_is_active, time_left = self.is_active_and_time_to_inactivation(
        )
        return time_left

    def get_attending_list(self, include_owner=False):
        users_list = []
        for feedback in self.feedback_set.all():
            if feedback.user not in users_list:
                users_list.append(feedback.user)
        for task in self.task_set.all():
            if task.responsible not in users_list:
                users_list.append(task.responsible)
        for descision in self.decision_set.all():
            for vote in descision.vote_set.all():
                if vote.voater not in users_list:
                    users_list.append(vote.voater)

        if include_owner:
            if self.owner not in users_list:
                users_list.append(self.owner)
        else:
            if self.owner in users_list:
                users_list.remove(self.owner)

        return users_list

    def get_followers_list(self):
        followers_list = []
        for viewer in self.viewer_set.all():
            if viewer.get_is_a_follower():
                followers_list.append(viewer.user)

        return followers_list

    def record_a_view_obs(self, viewing_user):
        if viewing_user in User.objects.all():
            viewer = self.viewer_set.get_or_create(user=viewing_user)[0]
            viewer.increment_views_counter()

    def record_anonymous_view_obs(self, request):

        if 'anonymous_user_id' in request.session:
            if AnonymousVisitor.objects.filter(
                    id=int(request.session['anonymous_user_id'])).count() != 0:
                anonymous_user = AnonymousVisitor.objects.get(
                    id=int(request.session['anonymous_user_id']))
            else:
                anonymous_user = AnonymousVisitor()
                anonymous_user.save()

            anonymous_viewer = self.anonymousvisitorviewer_set.get_or_create(
                anonymous_visitor=anonymous_user)[0]

            if request.user.is_authenticated():
                anonymous_user.user = request.user
                anonymous_user.save()
            else:
                anonymous_viewer.increment_views_counter()
        else:
            if request.user.is_authenticated():
                return
            anonymous_user = AnonymousVisitor()
            anonymous_user.save()
            anonymous_viewer = self.anonymousvisitorviewer_set.get_or_create(
                anonymous_visitor=anonymous_user)[0]
            anonymous_viewer.increment_views_counter()

        request.session['anonymous_user_id'] = anonymous_user.id

    def start_follow_obs(self, viewing_user):
        if viewing_user in User.objects.all():
            viewer = self.viewer_set.get_or_create(user=viewing_user)[0]
            viewer.start_follow_obs()

    def stop_follow_obs(self, viewing_user):
        if viewing_user in User.objects.all():
            viewer = self.viewer_set.get_or_create(user=viewing_user)[0]
            viewer.stop_follow()

    def is_a_follower(self, viewing_user):
        if not viewing_user:
            return False
        if viewing_user.is_authenticated() == False:
            return False
        if self.viewer_set.all().filter(user=viewing_user).count() != 0:
            viewer = self.viewer_set.get(user=viewing_user)
            return viewer.get_is_a_follower()
        return False

    def is_user_invited(self, viewing_user):

        return self.viewer_set.all().filter(user=viewing_user,
                                            is_invited=True).count() != 0

    def can_user_participate(self, viewing_user=None):

        if self.owner == viewing_user:
            return True

        if not self.is_restricted:
            return True

        if not viewing_user:
            return False

        return self.is_user_invited(viewing_user)

    def get_is_viewing_require_login(self):
        return self.is_viewing_require_login

    def is_user_in_discussion_segment(self, viewing_user=None):

        if not self.owner.userprofile.is_in_the_same_segment(viewing_user):
            return False

        return True

    def can_user_access_discussion(self, viewing_user=None):

        if self.is_viewing_require_login and viewing_user == None:
            return False

        if not self.is_user_in_discussion_segment(viewing_user):
            return False

        if not self.can_user_participate(viewing_user):
            return False

        return True

    def invite_obs(self, invited_user):
        if invited_user in User.objects.all():
            viewer = self.viewer_set.get_or_create(user=invited_user)[0]
            viewer.invite()

    def cancel_invitation_obs(self, invited_user):
        if invited_user in User.objects.all():
            viewer = self.viewer_set.get_or_create(user=invited_user)[0]
            viewer.cancel_invitation_obs()

    def get_invited_users_list(self):

        invited_users_list = []
        for viewer in self.viewer_set.all():
            if viewer.get_is_invited():
                invited_users_list.append(viewer.user)

        return invited_users_list

    def get_discussion(self):
        return self

    def print_content(self):
        print 'Owner', self.owner.username
        print 'Title:', self.title
        print 'Description:', self.description
        discussion_is_active, time_left = self.is_active_and_time_to_inactivation(
        )
        if discussion_is_active:
            print 'active, time left', time_left
        else:
            print 'inactivated'

        if self.is_restricted:
            print 'is_restricted. only invited users can view and participate'

        if self.is_viewing_require_login:
            print 'is_viewing_require_login. only logged in users may view'

        print 'attending:'
        attending_list = self.get_followers_list()
        for user in attending_list:
            print user.username

        feedbacks = self.feedback_set.all()
        for feedback in feedbacks:
            feedback.print_content()
        decisions = self.decision_set.all()
        for decision in decisions:
            decision.print_content()
        tasks = self.task_set.all()
        for task in tasks:
            task.print_content()
        viewers = self.viewer_set.all()
        for viewer in viewers:
            viewer.print_content()

        anonymous_viewers = self.anonymousvisitorviewer_set.all()
        for anonymous_viewer in anonymous_viewers:
            anonymous_viewer.print_content()
Beispiel #17
0
def get_config_variables():
    """
    Generator which yields all config variables of this app.

    There are two main groups: 'General' and 'Projector'. The group 'General'
    has subgroups. The generator has to be evaluated during app loading
    (see apps.py).
    """
    yield ConfigVariable(
        name='general_event_name',
        default_value='OpenSlides',
        label='Event name',
        weight=110,
        group='General',
        subgroup='Event',
        validators=(MaxLengthValidator(100),))

    yield ConfigVariable(
        name='general_event_description',
        default_value='Presentation and assembly system',
        label='Short description of event',
        weight=115,
        group='General',
        subgroup='Event',
        validators=(MaxLengthValidator(100),),
        translatable=True)

    yield ConfigVariable(
        name='general_event_date',
        default_value='',
        label='Event date',
        weight=120,
        group='General',
        subgroup='Event')

    yield ConfigVariable(
        name='general_event_location',
        default_value='',
        label='Event location',
        weight=125,
        group='General',
        subgroup='Event')

    yield ConfigVariable(
        name='general_event_organizer',
        default_value='',
        label='Event organizer',
        weight=130,
        group='General',
        subgroup='Event')

    yield ConfigVariable(
        name='general_event_legal_notice',
        default_value='<a href="http://www.openslides.org">OpenSlides</a> is a '
                      'free web based presentation and assembly system for '
                      'visualizing and controlling agenda, motions and '
                      'elections of an assembly.',
        input_type='markupText',
        label='Legal notice',
        weight=132,
        group='General',
        subgroup='Event',
        translatable=True)

    yield ConfigVariable(
        name='general_event_welcome_title',
        default_value='Welcome to OpenSlides',
        label='Front page title',
        weight=134,
        group='General',
        subgroup='Event',
        translatable=True)

    yield ConfigVariable(
        name='general_event_welcome_text',
        default_value='[Space for your welcome text.]',
        input_type='markupText',
        label='Front page text',
        weight=136,
        group='General',
        subgroup='Event',
        translatable=True)

    # General System

    yield ConfigVariable(
        name='general_system_enable_anonymous',
        default_value=False,
        input_type='boolean',
        label='Allow access for anonymous guest users',
        weight=138,
        group='General',
        subgroup='System')

    yield ConfigVariable(
        name='general_login_info_text',
        default_value='',
        label='Show this text on the login page',
        weight=140,
        group='General',
        subgroup='System')

    # CSV

    yield ConfigVariable(
        name='general_csv_separator',
        default_value=',',
        label='Separator used for all csv exports and examples',
        weight=144,
        group='General',
        subgroup='CSV')

    # Projector

    yield ConfigVariable(
        name='projector_language',
        default_value='browser',
        input_type='choice',
        label='Projector language',
        choices=(
            {'value': 'browser', 'display_name': 'Current browser language'},
            {'value': 'en', 'display_name': 'English'},
            {'value': 'de', 'display_name': 'Deutsch'},
            {'value': 'fr', 'display_name': 'Français'},
            {'value': 'es', 'display_name': 'Español'},
            {'value': 'pt', 'display_name': 'Português'},
            {'value': 'cs', 'display_name': 'Čeština'},
            {'value': 'ru', 'display_name': 'русский'}),
        weight=148,
        group='Projector')

    yield ConfigVariable(
        name='projector_enable_logo',
        default_value=True,
        input_type='boolean',
        label='Show logo on projector',
        help_text='You can replace the logo. Just copy a file to '
                  '"static/img/logo-projector.png" in your OpenSlides data path.',
        weight=150,
        group='Projector')

    yield ConfigVariable(
        name='projector_enable_title',
        default_value=True,
        input_type='boolean',
        label='Show title and description of event on projector',
        weight=155,
        group='Projector')

    yield ConfigVariable(
        name='projector_header_backgroundcolor',
        default_value='#317796',
        input_type='colorpicker',
        label='Background color of projector header and footer',
        weight=160,
        group='Projector')

    yield ConfigVariable(
        name='projector_header_fontcolor',
        default_value='#F5F5F5',
        input_type='colorpicker',
        label='Font color of projector header and footer',
        weight=165,
        group='Projector')

    yield ConfigVariable(
        name='projector_h1_fontcolor',
        default_value='#317796',
        input_type='colorpicker',
        label='Font color of projector headline',
        weight=170,
        group='Projector')

    yield ConfigVariable(
        name='projector_default_countdown',
        default_value=60,
        input_type='integer',
        label='Predefined seconds of new countdowns',
        weight=185,
        group='Projector')

    yield ConfigVariable(
        name='projector_blank_color',
        default_value='#FFFFFF',
        input_type='colorpicker',
        label='Color for blanked projector',
        weight=190,
        group='Projector')

    yield ConfigVariable(
        name='projector_broadcast',
        default_value=0,
        input_type='integer',
        label='Projector which is broadcasted',
        weight=200,
        group='Projector',
        hidden=True)

    yield ConfigVariable(
        name='projector_currentListOfSpeakers_reference',
        default_value=1,
        input_type='integer',
        label='Projector reference for list of speakers',
        weight=201,
        group='Projector',
        hidden=True)

    # Logos.
    yield ConfigVariable(
        name='logos_available',
        default_value=['logo_projector_main'],
        weight=300,
        group='Logo',
        hidden=True)

    yield ConfigVariable(
        name='logo_projector_main',
        default_value={
            'display_name': 'Main projector logo',
            'path': ''},
        input_type='logo',
        weight=301,
        group='Logo',
        hidden=True)
Beispiel #18
0
class Decision(models.Model):
    parent = models.ForeignKey(Discussion)
    content = models.TextField(validators=[MaxLengthValidator(MAX_TEXT)])
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    value = models.IntegerField(default=0)

    def __unicode__(self):
        return self.content

    def get_number_of_votes(self):
        return self.vote_set.count()

    def vote_obs(self, voater, value):
        if voater == self.parent.owner:
            return False
        if (self.vote_set.filter(voater=voater).count() == 0):
            new_vote = Vote(decision=self, voater=voater, value=value)
            new_vote.save()
            self.value += value
            self.save()
            return True


#             control.user_voted_for_an_idea_in_another_user_s_discussion(voater , self.get_absolute_url())
        current_vote = self.vote_set.get(voater=voater)
        self.value -= current_vote.value
        current_vote.value = value
        self.value += current_vote.value
        current_vote.save()

        self.save()
        return False

    def get_vote_sum(self):
        return (self.value)

    def get_vote_value_or_none(self, voater):
        if self.vote_set.filter(voater=voater).count() == 1:
            vote = self.vote_set.get(voater=voater)
            return vote.value
        return None

    def get_vote_average_or_none(self):
        number_of_votes = self.get_number_of_votes()
        if number_of_votes != 0:
            average = int(round(self.get_vote_sum() / number_of_votes))
            return average
        return None

    def get_vote_level_name(self):
        number_of_votes = self.get_vote_average_or_none()
        if number_of_votes:
            if number_of_votes == LikeLevel.EXCELLENT:
                return 'מצויין'
            if number_of_votes == LikeLevel.VERY_GOOD:
                return 'טוב מאוד'
            if number_of_votes == LikeLevel.GOOD:
                return 'טוב'
            if number_of_votes == LikeLevel.MEDIUM:
                return 'אין דעה'
            if number_of_votes == LikeLevel.BAD:
                return 'רעיון לא טוב'

        return 'אין'

        return self.vote_set.count()

    def print_content(self):
        print 'Decide:', self.content, 'created_at', self.created_at, 'value', self.value
        votes = self.vote_set.all()
        for vote in votes:
            vote.print_content()

    def get_absolute_url(self):
        return self.parent.get_absolute_url() + '#Decisions'

    def get_discussion(self):
        return self.parent
Beispiel #19
0
class Person(MyModel):
    last_name = models.CharField(\
     max_length=app.MAX_LENGTH_VARCHAR_FIELDS,\
     default=None, blank=False, null=False,\
     verbose_name=pgettext("Person model", "Last name"),\
     validators=[MinLengthValidator(app.MIN_LENGTH_VARCHAR_FIELDS),\
     MaxLengthValidator(app.MAX_LENGTH_VARCHAR_FIELDS)])

    mothers_last_name=models.CharField(\
     max_length=app.MAX_LENGTH_VARCHAR_FIELDS,\
     default=None, blank=True, null=True,\
     verbose_name=pgettext("Person model", "Mothers last name"),\
     validators=[MinLengthValidator(app.MIN_LENGTH_VARCHAR_FIELDS),\
     MaxLengthValidator(app.MAX_LENGTH_VARCHAR_FIELDS)])

    first_name=models.CharField(\
     max_length=app.MAX_LENGTH_VARCHAR_FIELDS, \
     default=None, blank=False, null=False,\
     verbose_name=pgettext("Person model", "First name"),\
     validators=[MinLengthValidator(app.MIN_LENGTH_VARCHAR_FIELDS),\
     MaxLengthValidator(app.MAX_LENGTH_VARCHAR_FIELDS)])

    middle_name=models.CharField(\
     max_length=254,\
     default=None, blank=True, null=True,\
     verbose_name=pgettext("Person model", "Middle name"))

    gender=models.CharField(\
     max_length=1, choices=app.GENDERS,\
     default=None, blank=False, null=False,\
     verbose_name=pgettext("Person model", "Gender"))

    dob=models.DateField(\
     default=None, blank=False, null=False,\
     verbose_name=pgettext("Person model", "Date of birth"))

    addresses = models.ManyToManyField(PersonAddress)
    emails = models.ManyToManyField(PersonEmail)
    phones = models.ManyToManyField(PersonPhone)
    social_networks = models.ManyToManyField(SocialNetwork)

    @property
    def full_name(self):
        result = self.first_name
        if self.middle_name and self.middle_name is not None and len(
                self.middle_name.strip()) > 0:
            result += ' ' + str(self.middle_name)
        result += ' ' + str(self.last_name)
        if self.mothers_last_name and self.mothers_last_name is not None and len(
                self.mothers_last_name.strip()) > 0:
            result += ' ' + str(self.mothers_last_name)
        return result

    @property
    def gender_full_str(self):
        if self.gender == 'M':
            return _("Male")
        return _('Female')

    @property
    def email_readable(self):
        if self.email is not None:
            return self.email
        return ''

    @property
    def cell_phone_readable(self):
        if self.cell_phone is not None:
            return self.cell_phone
        return ''

    @property
    def age(self):
        dummy = pgettext("person model", "Age")
        '''
		Code taken from https://www.geeksforgeeks.org/python-program-to-calculate-age-in-year/
		Approach 3: Efficient datetime approach,
		deal with a special case i.e. when birth date is February 29 
		and the current year is not a leap year.
		'''
        today = date.today()
        try:
            birthday = self.dob.replace(year=today.year)
            # raised when birth date is February 29
            # and the current year is not a leap year
        except ValueError:
            birthday = self.dob.replace(\
             year = today.year, \
              month = self.dob.month + 1, \
               day = 1)

        if birthday > today:
            return today.year - self.dob.year - 1
        else:
            return today.year - self.dob.year

    def __str__(self):
        return self.full_name

    class Meta:
        abstract = True
        #unique_together = ('last_name', 'mothers_last_name', 'first_name', 'middle_name', 'gender', 'dob', 'city', 'address_line1')
Beispiel #20
0
class Task(models.Model):
    STARTED = 1
    CLOSED = 2
    MISSED = 3
    ABORTED = 4
    DISCUSSION_OWNER_COMPLETED = 6
    OTHER_COMPLETED = 7
    DISCUSSION_OWNER_ABORTED = 8
    OTHER_ABORTED = 9
    OTHER_CONFIRMED = 10

    STATUS_CHOICES = (
        (STARTED, 'פעילה'),
        (CLOSED, 'הושלמה בהצלחה'),
        (MISSED, 'פוספסה'),
        (ABORTED, 'בוטלה בזמן'),
    )

    parent = models.ForeignKey(Discussion, null=True, blank=True)
    responsible = models.ForeignKey(User)
    goal_description = models.TextField(
        validators=[MaxLengthValidator(MAX_TEXT)])
    target_date = models.DateTimeField()
    closed_at = models.DateTimeField(null=True, blank=True)
    closed_by = models.ForeignKey(User,
                                  related_name='closed_by',
                                  null=True,
                                  blank=True)
    status_description = models.TextField(null=True, blank=True)
    status = models.IntegerField(choices=STATUS_CHOICES, default=STARTED)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    final_state = models.BooleanField(default=False)
    result_picture = models.ImageField(_(u"תמונה של התוצאה"),
                                       upload_to='uploads/%Y/%m/%d/',
                                       null=True,
                                       blank=True,
                                       default=None,
                                       max_length=50000)

    def __unicode__(self):
        return self.goal_description

    def get_absolute_url(self):
        return (reverse('coplay:task_details', kwargs={'pk': str(self.id)}))

    def update_status_description_obs(self, status_description):
        #         self.refresh_status()
        if self.final_state:
            return False
        self.status_description = status_description
        self.save()
        return True

    def get_status_description(self):
        #         self.refresh_status()
        return self.status_description

    def set_state_obs(self, new_state, closing_user):
        #         self.refresh_status()
        if self.final_state:
            return False

        if self.responsible is closing_user:
            return False

        if (self.status != new_state):
            self.status = new_state
            self.closed_at = timezone.now()
            self.closed_by = closing_user
            self.save()
            return True
        return False

    def abort_obs(self, closing_user):

        return self.set_state(self.ABORTED, closing_user)

    def re_open_obs(self, closing_user):

        return self.set_state(self.STARTED, closing_user)

    def close_obs(self, closing_user):

        return self.set_state(self.CLOSED, closing_user)

    def get_time_until_target(self):
        #         self.refresh_status()
        if self.final_state:
            return 0

        return self.target_date - timezone.now()

    def poll_status(self):
        now = timezone.now()
        events = []
        if self.target_date < now and not self.final_state:
            self.final_state = True
            if self.status == self.STARTED or self.status == self.MISSED:
                self.status = self.MISSED
            else:
                events.append(self.OTHER_CONFIRMED)
                #                 control.user_confirmed_a_state_update_in_another_user_s_mission(self.closed_by, self.get_absolute_url())
                if self.status == self.CLOSED:
                    if self.responsible == self.parent.owner:
                        events.append(self.DISCUSSION_OWNER_COMPLETED)
#                 control.user_confirmed_a_state_u
#                         control.user_completed_a_mission_for_his_own_s_discussion( self.responsible, self.get_absolute_url())
                    else:
                        events.append(self.OTHER_COMPLETED)
#                         control.user_completed_a_mission_for_another_user_s_discussion( self.responsible, self.get_absolute_url())
                else:
                    if self.status == self.ABORTED:
                        if self.responsible == self.parent.owner:
                            events.append(self.DISCUSSION_OWNER_ABORTED)
#                             control.user_aborted_a_mission_for_his_own_s_discussion( self.responsible, self.get_absolute_url())
                        else:
                            events.append(self.OTHER_ABORTED)


#                             control.user_aborted_a_mission_for_another_user_s_discussion( self.responsible, self.get_absolute_url())

            self.save()

        return events

    def get_status_obs(self):
        return self.status

    def print_content(self):
        print 'create', self.created_at, 'update', self.updated_at, 'status:', self.get_status_display(
        ), 'now', timezone.now(
        ), 'GoalDescription:', self.goal_description, 'target_date:', self.target_date, 'remaining', self.get_time_until_target(
        ), 'closing_date:', self.closed_at, self.status_description

    def get_discussion(self):
        return self.parent
Beispiel #21
0
 def test_max_length_validator_message(self):
     v = MaxLengthValidator(16, message='"%(value)s" has more than %(limit_value)d characters.')
     with self.assertRaisesMessage(ValidationError, '"djangoproject.com" has more than 16 characters.'):
         v('djangoproject.com')
Beispiel #22
0
class UserProfile(models.Model):
    user = models.OneToOneField(User, default=None, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    segment = models.ForeignKey(Segment, null=True, blank=True)
    recieve_notifications = models.BooleanField(default=True)
    recieve_updates = models.BooleanField(default=True)
    can_limit_discussion_access = models.BooleanField(default=False)
    can_limit_discussion_to_login_users_only = models.BooleanField(
        default=False)
    a_player = models.BooleanField(default=False)
    location = models.ForeignKey(Location, null=True, blank=True)
    latitude = models.FloatField(default=None, blank=True, null=True)
    longitude = models.FloatField(default=None, blank=True, null=True)
    #    recieve_personal_messages_from_users    = models.BooleanField(default = False)
    description = models.TextField(_("Description"),
                                   blank=True,
                                   null=True,
                                   validators=[MaxLengthValidator(MAX_TEXT)])
    location_desc = models.CharField(max_length=200,
                                     default=None,
                                     blank=True,
                                     null=True)

    followed_discussions_tags = TaggableManager(blank=True)

    application = models.ForeignKey(KuterLessApp, null=True, blank=True)
    application_specific_id = models.IntegerField(
        blank=True, default=0)  #used when there is no email

    def __unicode__(self):
        return "{} ".format(self.user.username)

    def is_in_the_same_segment(self, another_user=None):
        if another_user is None:
            if self.segment is None:
                return True
            return False

        if another_user not in User.objects.all():
            return False

        return (self.segment == another_user.userprofile.segment)

    def set_segment(self, segment=None):

        self.segment = segment
        self.save()

    def get_segment(self):

        return self.segment

    def get_segment_title(self):

        if self.get_segment():
            return self.segment.title
        return u'אתר הציבורי'

    def get_all_users_in_same_segment_list(self):
        all_users_in_same_segment_list = []
        for user in User.objects.all():
            if self.is_in_the_same_segment(user):
                all_users_in_same_segment_list.append(user)

        all_users_in_same_segment_list.remove(self.user)

        return all_users_in_same_segment_list

    def print_content(self):
        print self.user.username
        if self.segment:
            print 'belong to', self.segment.title
        if self.segment:
            print 'belong to segment', self.segment.title
        else:
            print 'belong to the default public segment'

        if self.recieve_notifications:
            print 'recieve_notifications'
        if self.recieve_updates:
            print 'recieve_updates'
        if self.can_limit_discussion_access:
            print 'can_limit_discussion_access'
        if self.can_limit_discussion_to_login_users_only:
            print 'can_limit_discussion_to_login_users_only'
Beispiel #23
0
class LineItem(FieldGroup):
    grouping_factor = Field(name='GroupingFactor', validators=[MaxLengthValidator(35)])
    material = Field(name='Material', validators=[MaxLengthValidator(18)])
    material_description = Field(name='MaterialDescription', validators=[MaxLengthValidator(40)])
    quantity = Field(name='Quantity', validators=[MaxLengthValidator(13)])
    unit = Field(name='Unit', validators=[MaxLengthValidator(3)])
    net_price = Field(name='NetPrice', validators=[MaxLengthValidator(14)], required=True)
    tax_code = Field(name='TaxCode', validators=[MaxLengthValidator(1)])
    line_text_l1 = Field(name='LineTextL1', validators=[MaxLengthValidator(70)])
    line_text_l2 = Field(name='LineTextL2', validators=[MaxLengthValidator(70)])
    line_text_l3 = Field(name='LineTextL3', validators=[MaxLengthValidator(70)])
    line_text_l4 = Field(name='LineTextL4', validators=[MaxLengthValidator(70)])
    line_text_l5 = Field(name='LineTextL5', validators=[MaxLengthValidator(70)])
    line_text_l6 = Field(name='LineTextL6', validators=[MaxLengthValidator(70)])
    profit_center = Field(name='ProfitCenter', validators=[MaxLengthValidator(10)])
    order_item_number = Field(name='OrderItemNumber', validators=[MaxLengthValidator(12)])
    wbs_element = Field(name='WBS_Element', validators=[MaxLengthValidator(16)])
    functional_area = Field(name='FunctionalArea', validators=[MaxLengthValidator(6)])
    business_entity = Field(name='BusinessEntity', validators=[MaxLengthValidator(8)])
    building = Field(name='Building', validators=[MaxLengthValidator(8)])
    rental_object = Field(name='RentalObject', validators=[MaxLengthValidator(8)])

    class Meta:
        element_name = 'LineItem'
Beispiel #24
0
class OnboardingContactInfoForm(forms.Form):
    address = forms.CharField(max_length=128, required=False, widget=forms.TextInput(attrs={
        '_no_label': True, 'placeholder': 'Street Address / Office #', '_field_class': 'twelve wide field'
    }))
    line_2 = forms.CharField(max_length=32, required=False, widget=forms.TextInput(attrs={
        '_no_label': True, 'placeholder': 'Building, Apt. #, etc.', '_field_class': 'four wide field'
    }))
    city = forms.CharField(max_length=32, required=False, widget=forms.TextInput(attrs={
        '_no_label': True, 'placeholder': 'City'
    }))
    state = forms.CharField(max_length=32, required=False, widget=forms.TextInput(attrs={
        '_no_label': True, 'placeholder': 'State'
    }))
    phone = forms.CharField(required=False, widget=forms.NumberInput(attrs={'placeholder': '10-digit phone number'}),
                            validators=[MinLengthValidator(10), MaxLengthValidator(10)])
    sms = forms.ChoiceField(choices=((True, 'Yes, I consent to receiving text messages from LNL'),
                                     (False, 'No, I do not wish to receive text messages from LNL at this time')),
                            initial=True, required=False, widget=SUIRadio(attrs={'_no_label': True}))
    carrier = forms.ChoiceField(choices=(('', 'Please select your carrier...'),) + carrier_choices[1:], required=False)

    def __init__(self, has_address, *args, **kwargs):
        super(OnboardingContactInfoForm, self).__init__(*args, **kwargs)

        if has_address:
            self.fields['address'].widget.attrs['readonly'] = True
            self.fields['address'].widget.attrs['placeholder'] = 'Already Complete'
            self.fields['address'].widget.attrs['_icon'] = 'check circle outline'
            self.fields['line_2'].widget.attrs['_field_class'] = 'hidden'
            self.fields['city'].widget.attrs['_field_class'] = 'hidden'
            self.fields['state'].widget.attrs['_field_class'] = 'hidden'

    def save(self):
        pass

    def clean_carrier(self):
        sms = self.cleaned_data.get('sms')
        carrier = self.cleaned_data.get('carrier')
        if sms == 'True' and not carrier:
            raise ValidationError('Please select your cellular carrier')
        return carrier

    def clean_phone(self):
        phone = self.cleaned_data.get('phone')
        sms = self.cleaned_data.get('sms')
        if sms == 'True' and phone in [None, '']:
            raise ValidationError('To receive SMS text messages from LNL you must provide your phone number')
        return phone

    class Meta:
        layout = [
            ("Text", "<h4 class=\"ui dividing header\">Contact Information</h4>"),
            ("Text", "<div class=\"field\"><label>Address / Office Location</label>"),
            ("Two Fields",
             ("Field", "address"),
             ("Field", "line_2"),
             ),
            ("Two Fields",
             ("Field", "city"),
             ("Field", "state"),
             ),
            ("Text", "</div>"),
            ("Field", "phone"),
            ("Text", "<br>"),
            ("Text", "<div class=\"field\"><label>Consent to receive text messages from LNL</label>"),
            ("Text", "<p style=\"color: black\">LNL may periodically send you SMS text messages containing information "
                     "about your business with us. This method of communication will never be used for marketing "
                     "purposes and you may opt out at any time.</p></div>"),
            ("Field", "sms"),
            ("Field", "carrier"),
            ("Text", "<p style=\"color: darkgrey; padding-top: 2%; padding-bottom: 1%\">By clicking next you agree to "
                     "our <a href='https://lnl.wpi.edu/legal/privacy/' target='_blank'>Privacy Policy</a></p>")
        ]
Beispiel #25
0
class Party(FieldGroup):
    sap_customer_id = Field(name='SAPCustomerID', validators=[MaxLengthValidator(10)])
    customer_id = Field(name='CustomerID', validators=[MaxLengthValidator(11)])
    customer_yid = Field(name='CustomerYID', validators=[MaxLengthValidator(9)])
    customer_ovt = Field(name='CustomerOVT', validators=[MaxLengthValidator(17)])
    temporary_address1 = Field(name='TemporaryAddress1', validators=[MaxLengthValidator(35)])
    temporary_address2 = Field(name='TemporaryAddress2', validators=[MaxLengthValidator(35)])
    temporary_po_code = Field(name='TemporaryPOCode', validators=[MaxLengthValidator(35)])
    temporary_po_city = Field(name='TemporaryPOCity', validators=[MaxLengthValidator(35)])
    temporary_po_postalcode = Field(name='TemporaryPOPostalcode', validators=[MaxLengthValidator(9)])
    temporary_city = Field(name='TemporaryCity', validators=[MaxLengthValidator(35)])
    temporary_postalcode = Field(name='TemporaryPostalcode', validators=[MaxLengthValidator(9)])
    priority_name1 = Field(name='PriorityName1', validators=[MaxLengthValidator(35)])
    priority_name2 = Field(name='PriorityName2', validators=[MaxLengthValidator(35)])
    priority_name3 = Field(name='PriorityName3', validators=[MaxLengthValidator(35)])
    priority_name4 = Field(name='PriorityName4', validators=[MaxLengthValidator(35)])
    priority_address1 = Field(name='PriorityAddress1', validators=[MaxLengthValidator(35)])
    priority_address2 = Field(name='PriorityAddress2', validators=[MaxLengthValidator(35)])
    priority_po_code = Field(name='PriorityPOCode', validators=[MaxLengthValidator(35)])
    priority_po_city = Field(name='PriorityPOCity', validators=[MaxLengthValidator(35)])
    priority_po_postalcode = Field(name='PriorityPOPostalcode', validators=[MaxLengthValidator(9)])
    priority_city = Field(name='PriorityCity', validators=[MaxLengthValidator(35)])
    priority_postalcode = Field(name='PriorityPostalcode', validators=[MaxLengthValidator(9)])
    info_customer_id = Field(name='InfoCustomerID', validators=[MaxLengthValidator(11)])
    info_customer_yid = Field(name='InfoCustomerYID', validators=[MaxLengthValidator(9)])
    info_customer_ovt = Field(name='InfoCustomerOVT', validators=[MaxLengthValidator(17)])
    info_name1 = Field(name='InfoName1', validators=[MaxLengthValidator(35)])
    info_name2 = Field(name='InfoName2', validators=[MaxLengthValidator(35)])
    info_name3 = Field(name='InfoName3', validators=[MaxLengthValidator(35)])
    info_name4 = Field(name='InfoName4', validators=[MaxLengthValidator(35)])
    info_address1 = Field(name='InfoAddress1', validators=[MaxLengthValidator(35)])
    info_address2 = Field(name='InfoAddress2', validators=[MaxLengthValidator(35)])
    info_po_code = Field(name='InfoPOCode', validators=[MaxLengthValidator(35)])
    info_po_city = Field(name='InfoPOCity', validators=[MaxLengthValidator(35)])
    info_po_postalcode = Field(name='InfoPOPostalcode', validators=[MaxLengthValidator(9)])
    info_city = Field(name='InfoCity', validators=[MaxLengthValidator(35)])
    info_postalcode = Field(name='InfoPostalcode', validators=[MaxLengthValidator(9)])

    def from_contact(self, contact):
        if not contact:
            return

        self.sap_customer_id = contact.sap_customer_number
        if contact.type == ContactType.PERSON:
            self.customer_id = contact.national_identification_number
            self.info_customer_id = contact.national_identification_number
        else:
            self.customer_yid = contact.business_id
            self.info_customer_yid = contact.business_id

        name = contact.get_name()[:140]  # PriorityName1-4 max length = 4 * 35 chars

        n = 1
        if not name:
            self.priority_name1 = ''
            self.info_name1 = ''
            n += 1
        else:
            for i in range(0, len(name), 35):
                setattr(self, 'priority_name{}'.format(n), name[i:i + 35])
                setattr(self, 'info_name{}'.format(n), name[i:i + 35])
                n += 1

        # Add care of to the priority name overwriting part of the name if necessary
        if contact.care_of:
            care_of = 'c/o {}'.format(contact.care_of)

            if n == 5:
                n = 4

            for i in range(0, len(care_of), 35):
                setattr(self, 'priority_name{}'.format(n), care_of[i:i + 35])
                setattr(self, 'info_name{}'.format(n), care_of[i:i + 35])
                n += 1
                if n >= 5:
                    break

        self.priority_address1 = contact.address[:35] if contact.address else ''
        self.priority_city = contact.city
        self.priority_postalcode = contact.postal_code
        self.info_address1 = contact.address[:35] if contact.address else ''
        self.info_city = contact.city
        self.info_postalcode = contact.postal_code
class User(AbstractBaseUser, PermissionsMixin, BaseModel, DateCreatedModifiedMixin):

    username = models.CharField(
        _('username'),
        max_length=settings.USERS_USERNAME_MAX_LENGTH,
        unique=True,
        help_text=_(
            'Required. From %s to %s characters. Letters, digits and @/./+/-/_ only.'
        )
        % (settings.USERS_USERNAME_MIN_LENGTH, settings.USERS_USERNAME_MAX_LENGTH),
        validators=[
            validators.UnicodeUsernameValidator(),
            MinLengthValidator(settings.USERS_USERNAME_MIN_LENGTH),
            MaxLengthValidator(settings.USERS_USERNAME_MAX_LENGTH),
        ],
        error_messages={'unique': _("A user with that username already exists."),},
    )
    email = models.EmailField(_('email address'), blank=False, unique=True, null=True,)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )

    telegram_id = models.PositiveIntegerField(
        _('Telegram ID'), null=True, editable=False, unique=True,
    )
    vk_id = models.PositiveIntegerField(
        _('VK ID'), null=True, editable=False, unique=True,
    )

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)

    def get_lists(self) -> QuerySet:
        return self.lists.all()

    def get_public_lists(self) -> QuerySet:
        return self.lists.filter(is_public=True)

    def get_subscriptions(self) -> QuerySet:
        return self.subscriptions.enabled()

    def get_notifications(self) -> QuerySet:
        return self.notifications.enabled()

    def get_not_seen_notifications_count(self) -> int:
        return self.get_notifications().filter(seen=False).count()
Beispiel #27
0
class Customer(core_models.UuidMixin, core_models.NameMixin,
               core_models.DescendantMixin,
               quotas_models.ExtendableQuotaModelMixin, PermissionMixin,
               VATMixin, LoggableMixin, ImageModelMixin, TimeStampedModel,
               StructureModel):
    class Permissions(object):
        customer_path = 'self'
        project_path = 'projects'

    native_name = models.CharField(max_length=160, default='', blank=True)
    abbreviation = models.CharField(max_length=12, blank=True)
    contact_details = models.TextField(blank=True,
                                       validators=[MaxLengthValidator(500)])
    agreement_number = models.PositiveIntegerField(null=True,
                                                   blank=True,
                                                   unique=True)
    email = models.EmailField(_('email address'), max_length=75, blank=True)
    phone_number = models.CharField(_('phone number'),
                                    max_length=255,
                                    blank=True)
    access_subnets = models.TextField(
        validators=[validate_cidr_list],
        blank=True,
        default='',
        help_text=_(
            'Enter a comma separated list of IPv4 or IPv6 '
            'CIDR addresses from where connection to self-service is allowed.')
    )
    registration_code = models.CharField(max_length=160,
                                         default='',
                                         blank=True)

    type = models.CharField(blank=True, max_length=150)
    address = models.CharField(blank=True, max_length=300)
    postal = models.CharField(blank=True, max_length=20)
    bank_name = models.CharField(blank=True, max_length=150)
    bank_account = models.CharField(blank=True, max_length=50)
    accounting_start_date = models.DateTimeField(_('Start date of accounting'),
                                                 default=timezone.now)
    default_tax_percent = models.DecimalField(
        default=0,
        max_digits=4,
        decimal_places=2,
        validators=[MinValueValidator(0),
                    MaxValueValidator(100)])
    tracker = FieldTracker()

    class Meta(object):
        verbose_name = _('organization')

    GLOBAL_COUNT_QUOTA_NAME = 'nc_global_customer_count'

    class Quotas(quotas_models.QuotaModelMixin.Quotas):
        enable_fields_caching = False
        nc_project_count = quotas_fields.CounterQuotaField(
            target_models=lambda: [Project],
            path_to_scope='customer',
        )
        nc_service_count = quotas_fields.CounterQuotaField(
            target_models=lambda: Service.get_all_models(),
            path_to_scope='customer',
        )
        nc_service_project_link_count = quotas_fields.CounterQuotaField(
            target_models=lambda: ServiceProjectLink.get_all_models(),
            path_to_scope='project.customer',
        )
        nc_user_count = quotas_fields.QuotaField()
        nc_resource_count = quotas_fields.CounterQuotaField(
            target_models=lambda: ResourceMixin.get_all_models(),
            path_to_scope='project.customer',
        )
        nc_app_count = quotas_fields.CounterQuotaField(
            target_models=lambda: ApplicationMixin.get_all_models(),
            path_to_scope='project.customer',
        )
        nc_vm_count = quotas_fields.CounterQuotaField(
            target_models=lambda: VirtualMachine.get_all_models(),
            path_to_scope='project.customer',
        )
        nc_private_cloud_count = quotas_fields.CounterQuotaField(
            target_models=lambda: PrivateCloud.get_all_models(),
            path_to_scope='project.customer',
        )
        nc_storage_count = quotas_fields.CounterQuotaField(
            target_models=lambda: Storage.get_all_models(),
            path_to_scope='project.customer',
        )
        nc_volume_size = quotas_fields.TotalQuotaField(
            target_models=lambda: Volume.get_all_models(),
            path_to_scope='customer',
            target_field='size',
        )
        nc_snapshot_size = quotas_fields.TotalQuotaField(
            target_models=lambda: Snapshot.get_all_models(),
            path_to_scope='customer',
            target_field='size',
        )

    def get_log_fields(self):
        return ('uuid', 'name', 'abbreviation', 'contact_details')

    def get_owners(self):
        return get_user_model().objects.filter(
            customerpermission__customer=self,
            customerpermission__is_active=True,
            customerpermission__role=CustomerRole.OWNER,
        )

    def get_support_users(self):
        return get_user_model().objects.filter(
            customerpermission__customer=self,
            customerpermission__is_active=True,
            customerpermission__role=CustomerRole.SUPPORT,
        )

    def get_users(self):
        """ Return all connected to customer users """
        return get_user_model().objects.filter(
            Q(customerpermission__customer=self,
              customerpermission__is_active=True)
            | Q(projectpermission__project__customer=self,
                projectpermission__is_active=True)).distinct().order_by(
                    'username')

    def can_user_update_quotas(self, user):
        return user.is_staff

    def can_manage_role(self, user, role=None, timestamp=False):
        """
        Checks whether user can grant/update/revoke customer permissions.
        `timestamp` can have following values:
            - False - check whether user can manage permissions at the moment.
            - None - check whether user can permanently manage permissions.
            - Datetime object - check whether user will be able to manage permissions at specific timestamp.
        """
        return user.is_staff or (
            self.has_user(user, CustomerRole.OWNER, timestamp)
            and settings.WALDUR_CORE['OWNERS_CAN_MANAGE_OWNERS'])

    def get_children(self):
        return itertools.chain.from_iterable(
            m.objects.filter(customer=self)
            for m in [Project] + Service.get_all_models())

    def is_billable(self):
        return timezone.now() >= self.accounting_start_date

    @classmethod
    def get_permitted_objects_uuids(cls, user):
        if user.is_staff:
            customer_queryset = cls.objects.all()
        else:
            customer_queryset = cls.objects.filter(
                permissions__user=user,
                permissions__role=CustomerRole.OWNER,
                permissions__is_active=True)
        return {
            'customer_uuid':
            filter_queryset_for_user(customer_queryset,
                                     user).values_list('uuid', flat=True)
        }

    def __str__(self):
        return '%(name)s (%(abbreviation)s)' % {
            'name': self.name,
            'abbreviation': self.abbreviation
        }
Beispiel #28
0
class JSMinErrorForm(forms.Form):
    in_text = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'inline-txtarea'}),
        initial="(Error) Minifier failed.  Make sure your Javascript is valid.",
        label="",
        validators=[MaxLengthValidator(10000)])
Beispiel #29
0
 (int_list_validator(sep='.'), '1.2.3\n', ValidationError),
 (MaxValueValidator(10), 10, None),
 (MaxValueValidator(10), -10, None),
 (MaxValueValidator(10), 0, None),
 (MaxValueValidator(NOW), NOW, None),
 (MaxValueValidator(NOW), NOW - timedelta(days=1), None),
 (MaxValueValidator(0), 1, ValidationError),
 (MaxValueValidator(NOW), NOW + timedelta(days=1), ValidationError),
 (MinValueValidator(-10), -10, None),
 (MinValueValidator(-10), 10, None),
 (MinValueValidator(-10), 0, None),
 (MinValueValidator(NOW), NOW, None),
 (MinValueValidator(NOW), NOW + timedelta(days=1), None),
 (MinValueValidator(0), -1, ValidationError),
 (MinValueValidator(NOW), NOW - timedelta(days=1), ValidationError),
 (MaxLengthValidator(10), '', None),
 (MaxLengthValidator(10), 10 * 'x', None),
 (MaxLengthValidator(10), 15 * 'x', ValidationError),
 (MinLengthValidator(10), 15 * 'x', None),
 (MinLengthValidator(10), 10 * 'x', None),
 (MinLengthValidator(10), '', ValidationError),
 (URLValidator(EXTENDED_SCHEMES), 'file://localhost/path', None),
 (URLValidator(EXTENDED_SCHEMES), 'git://example.com/', None),
 (URLValidator(EXTENDED_SCHEMES),
  'git+ssh://[email protected]/example/hg-git.git', None),
 (URLValidator(EXTENDED_SCHEMES), 'git://-invalid.com', ValidationError),
 # Trailing newlines not accepted
 (URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
 (URLValidator(), 'http://[::ffff:192.9.5.5]\n', ValidationError),
 # Trailing junk does not take forever to reject
 (URLValidator(), 'http://www.asdasdasdasdsadfm.com.br ', ValidationError),
Beispiel #30
0
def validate_password(password):
    groups = (r'[a-z]', r'[A-Z]', r'[0-9]', r'[\W_]')
    if sum(bool(re.search(g, password)) for g in groups) < 3:
        raise ValidationError(
            _(
                'The supplied password must contain 3 of the following: '
                'a lowercase character, an uppercase character, a number, '
                'a special character.'
            )
        )


VirtualMachinePasswordValidators = [
    MinLengthValidator(6),
    MaxLengthValidator(72),
    validate_password,
    VirtualMachinePasswordValidator,
]


NetworkingNameValidator = RegexValidator(
    regex=re.compile(r'^[a-zA-Z][a-zA-Z0-9._-]+$'),
    message=_(
        'The name can contain only letters, numbers, underscore, period and hyphens.'
    ),
)


StorageAccountNameValidator = RegexValidator(
    regex=re.compile(r'^[a-z][a-z0-9]{2,23}$'),