Beispiel #1
0
class AuditLog(TimeStampedModel):
    ACTIONS = Choices(
        # constant, db_id, friendly string
        ("VIEWED", "VIEWED", "viewed")
    )
    user = models.ForeignKey("auth.User", blank=True, null=True)
    action = models.CharField(choices=ACTIONS, db_index=True, max_length=50)
Beispiel #2
0
class Sponsor(models.Model):
    LEVELS = Choices(
        ('platinum', 1, 'Platinum'),
        ('gold', 2, 'Gold'),
        ('silver', 3, 'Silver'),
        ('bronze', 4, 'Bronze'),
        ('diversity', 5, 'Diversity'),
        ('media', 6, 'Media'),
        ('partners', 7, 'Partners'),
        ('connectivity', 9, 'Con­nectiv­ity'),
    )

    level = models.PositiveSmallIntegerField(choices=LEVELS, default=LEVELS.silver)

    name = models.CharField(max_length=200)
    logo = models.FileField(upload_to='sponsors/pyconcz/')

    description = models.TextField()
    link_url = models.URLField()
    twitter = models.URLField(null=True, blank=True, help_text='full URL')
    facebook = models.URLField(null=True, blank=True, help_text='full URL')

    published = models.BooleanField(default=False)

    class Meta:
        ordering = ['level', 'name']

    def __str__(self):
        return self.name
Beispiel #3
0
class Charge(BaseModel, TimeStampedModel):
    STATES = Choices(
        ('created', 'created', _("Criada")),
        ('paid', 'paid', _("Paga"))
    )

    amount = models.DecimalField(max_digits=10, decimal_places=4, default=Decimal('0'), verbose_name=_("Valor"))
    user = models.ForeignKey('core.User', related_name='charges', on_delete=models.CASCADE, null=True)
    ref = models.CharField(max_length=300, verbose_name=_("Valor"))
    state = models.CharField(max_length=30, default=STATES.created)

    class Meta:
        verbose_name = _("Cobrança")
        verbose_name_plural = _("Cobranças")
Beispiel #4
0
class Registration(models.Model):
    SALUTATIONS = Choices(
        ('SALUTATION_FEMALE', 'mrs', ugettext('Ms.')),
        ('SALUTATION_MALE', 'mr', ugettext('Mr.')),
    )

    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    language_code = models.CharField(choices=settings.LANGUAGES,
                                     default=settings.LANGUAGES[0][0],
                                     max_length=32)

    event = models.ForeignKey(Event)
    salutation = models.CharField(_('Salutation'),
                                  max_length=5,
                                  choices=SALUTATIONS,
                                  default=SALUTATIONS.SALUTATION_FEMALE)
    company = models.CharField(_('Company'),
                               max_length=100,
                               blank=True,
                               default='')
    first_name = models.CharField(_('First name'), max_length=100)
    last_name = models.CharField(_('Last name'), max_length=100)

    address = models.TextField(_('Address'), blank=True, default='')
    address_zip = models.CharField(_('ZIP CODE'), max_length=20)
    address_city = models.CharField(_('City'), max_length=100)

    phone = models.CharField(_('Phone number'),
                             blank=True,
                             default='',
                             max_length=20)
    mobile = models.CharField(_('Mobile number'),
                              blank=True,
                              default='',
                              max_length=20)
    email = models.EmailField(_('E-Mail'))

    message = models.TextField(_('Message'), blank=True, default='')

    @property
    def address_street(self):
        return self.address

    class Meta:
        verbose_name = _('Registration')
        verbose_name_plural = _('Registrations')
Beispiel #5
0
class Request(TimeStampedModel):
    """
    Request model
    """
    REQUEST_STATUS = Choices(('PENDING', 1, 'Pending'),
                             ('ACCEPTED', 2, 'Accepted'),
                             ('REJECTED', 3, 'Rejected'))
    status = models.PositiveSmallIntegerField(choices=REQUEST_STATUS,
                                              verbose_name='status',
                                              default=REQUEST_STATUS.PENDING)
    offer = models.ForeignKey('offer.Offer', related_name='requests')
    creator = models.ForeignKey('account.Account', related_name='own_requests')
    was_viewed = models.BooleanField(default=False)

    def __str__(self):
        return "Request: creator - {}, {}".format(self.creator, self.offer)
Beispiel #6
0
class Report(BaseModel, TimeStampedModel):
    STATES = Choices(
        ('ok', 'ok', _("Ok")),
        ('not_ok', 'not_ok', _("Not Ok"))
    )

    analyse = models.ForeignKey(Analyze, verbose_name=_("Analyse"), on_delete=models.CASCADE)
    indicator = models.ForeignKey(Indicator, verbose_name=_("Indicator"), on_delete=models.CASCADE, null=True)
    state = models.CharField(max_length=30, choices=STATES, verbose_name=_("State"), null=True, blank=True  )
    observation = models.CharField(max_length=100, verbose_name=_("Observation"), null=True, blank=True)

    def __str__(self):
        return '{}-{}'.format(self.analyse.address, self.indicator.name)

    class Meta:
        verbose_name = _("Report")
        verbose_name_plural = _("Reports")
Beispiel #7
0
class ServiceRequest(models.Model):
    """
    Service Request Model
    represents a service request in the application
    """

    mechanic = ForeignKey(Mechanic, DB_CASCADE)
    vehicle = ForeignKey(Vehicle, DB_CASCADE)
    problem_details = models.CharField(max_length=500, blank=True)
    created_on = models.DateTimeField()
    updated_on = models.DateTimeField(null=True)

    STATUS_CHOICES = Choices(('PEN', "Pending", "Pending"),
                             ('FIN', "Finished", "Finished"))
    status = models.CharField(max_length=10,
                              choices=STATUS_CHOICES,
                              default=STATUS_CHOICES.PEN)

    class Meta:
        db_table = 'service_request'

    def __str__(self):
        return f'<ServiceRequest: {self.id}>'
Beispiel #8
0
class User(models.Model):
    """
    User Model
    represents an user for the application
    """

    id = models.AutoField(primary_key=True)
    created_on = models.DateTimeField()
    email = models.CharField(max_length=255, unique=True)
    jwt_token = models.CharField(max_length=500, unique=True, null=True)
    number = models.CharField(max_length=255, null=True)
    password = models.CharField(max_length=255)

    ROLE_CHOICES = Choices(('USER', 1, 'User'), ('MECH', 2, 'Mechanic'),
                           dict_class=OrderedDict)
    role = models.IntegerField(choices=ROLE_CHOICES, default=ROLE_CHOICES.USER)

    class Meta:
        db_table = 'user_login'
        managed = False

    def __str__(self):
        return f"<User: {self.email}>"
Beispiel #9
0
class Order(models.Model):
    """
    Order Model
    represents an order in the application
    """
    user = ForeignKey(User, DB_CASCADE)
    product = ForeignKey(Product, DB_CASCADE)
    quantity = models.IntegerField(default=1)
    created_on = models.DateTimeField()

    STATUS_CHOICES = Choices(
        ("DELIVERED", "delivered", "delivered"),
        ("RETURN_PENDING", "return pending", "return pending"),
        ("RETURNED", "returned", "returned"))
    status = models.CharField(max_length=20,
                              choices=STATUS_CHOICES,
                              default=STATUS_CHOICES.DELIVERED)

    class Meta:
        db_table = 'order'

    def __str__(self):
        return f"{self.user.email} - {self.product.name} "
Beispiel #10
0
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
from django.contrib.postgres.fields import JSONField, ArrayField

from extended_choices import Choices

from . import storage, tasks, builder, utils, client, depgraph


log = logging.getLogger(__name__)


INDEX_BACKENDS = Choices(
    ('PYPI', 'wheelsproxy.client.PyPIClient', _('PyPI')),
    ('DEVPI', 'wheelsproxy.client.DevPIClient', _('DevPI')),
)

COMPILATION_STATUSES = Choices(
    ('PENDING', 'pending', _('Pending')),
    ('DONE', 'done', _('Done')),
    ('FAILED', 'failed', _('Failed')),
)


def _get_alternate_versions(version):
    """
    Returns a set of alternate version numbers for the given version.
    E.g. for `4.0` returns `{4, 4.0, 4.0.0}`
    """
    # TODO: Add a normalized_version field to the release model instead?
Beispiel #11
0
from django.utils.translation import gettext_lazy as _
from extended_choices import Choices

PAYMENT_STATUS = Choices(('PENDING', 'pending', _('Pending')),
                         ('FAILED', 'failed', _('Failed')),
                         ('TAKEN', 'taken', _('Taken')))
Beispiel #12
0
class AbuseReport(ModelBase):
    # Note: those choices don't need to be translated for now, the
    # human-readable values are only exposed in the admin.
    ADDON_SIGNATURES = APIChoicesWithNone(
        ('CURATED_AND_PARTNER', 1, 'Curated and partner'),
        ('CURATED', 2, 'Curated'),
        ('PARTNER', 3, 'Partner'),
        ('NON_CURATED', 4, 'Non-curated'),
        ('UNSIGNED', 5, 'Unsigned'),
        ('BROKEN', 6, 'Broken'),
        ('UNKNOWN', 7, 'Unknown'),
        ('MISSING', 8, 'Missing'),
        ('PRELIMINARY', 9, 'Preliminary'),
        ('SIGNED', 10, 'Signed'),
        ('SYSTEM', 11, 'System'),
        ('PRIVILEGED', 12, 'Privileged'),
    )
    REASONS = APIChoicesWithNone(
        ('DAMAGE', 1, 'Damages computer and/or data'),
        ('SPAM', 2, 'Creates spam or advertising'),
        ('SETTINGS', 3, 'Changes search / homepage / new tab page '
         'without informing user'),
        # `4` was previously 'New tab takeover' but has been merged into the
        # previous one. We avoid re-using the value.
        ('BROKEN', 5, "Doesn’t work, breaks websites, or slows Firefox down"),
        ('POLICY', 6, 'Hateful, violent, or illegal content'),
        ('DECEPTIVE', 7, "Pretends to be something it’s not"),
        # `8` was previously "Doesn't work" but has been merged into the
        # previous one. We avoid re-using the value.
        ('UNWANTED', 9, "Wasn't wanted / impossible to get rid of"),
        # `10` was previously "Other". We avoid re-using the value.
        ('OTHER', 127, 'Other'),
    )

    ADDON_INSTALL_METHODS = APIChoicesWithNone(
        ('AMWEBAPI', 1, 'Add-on Manager Web API'),
        ('LINK', 2, 'Direct link'),
        ('INSTALLTRIGGER', 3, 'Install Trigger'),
        ('INSTALL_FROM_FILE', 4, 'From File'),
        ('MANAGEMENT_WEBEXT_API', 5, 'Webext management API'),
        ('DRAG_AND_DROP', 6, 'Drag & Drop'),
        ('SIDELOAD', 7, 'Sideload'),
        ('FILE_URI', 8, 'File URI'),
        ('ENTERPRISE_POLICY', 9, 'Enterprise Policy'),
        ('DISTRIBUTION', 10, 'Included in build'),
        ('SYSTEM_ADDON', 11, 'System Add-on'),
        ('TEMPORARY_ADDON', 12, 'Temporary Add-on'),
        ('SYNC', 13, 'Sync'),
        ('OTHER', 127, 'Other'),
    )
    REPORT_ENTRY_POINTS = APIChoicesWithNone(
        ('UNINSTALL', 1, 'Uninstall'),
        ('MENU', 2, 'Menu'),
        ('TOOLBAR_CONTEXT_MENU', 3, 'Toolbar context menu'),
    )
    STATES = Choices(
        ('UNTRIAGED', 1, 'Untriaged'),
        ('VALID', 2, 'Valid'),
        ('SUSPICIOUS', 3, 'Suspicious'),
        ('DELETED', 4, 'Deleted'),
    )

    # NULL if the reporter is anonymous.
    reporter = models.ForeignKey(UserProfile,
                                 null=True,
                                 blank=True,
                                 related_name='abuse_reported',
                                 on_delete=models.SET_NULL)
    country_code = models.CharField(max_length=2, default=None, null=True)
    # An abuse report can be for an addon or a user.
    # If user is non-null then both addon and guid should be null.
    # If user is null then addon should be non-null if guid was in our DB,
    # otherwise addon will be null also.
    # If both addon and user is null guid should be set.
    addon = models.ForeignKey(Addon,
                              null=True,
                              related_name='abuse_reports',
                              on_delete=models.CASCADE)
    guid = models.CharField(max_length=255, null=True)
    user = models.ForeignKey(UserProfile,
                             null=True,
                             related_name='abuse_reports',
                             on_delete=models.SET_NULL)
    message = models.TextField(blank=True)

    state = models.PositiveSmallIntegerField(default=STATES.UNTRIAGED,
                                             choices=STATES.choices)

    # Extra optional fields for more information, giving some context that is
    # meant to be extracted automatically by the client (i.e. Firefox) and
    # submitted via the API.
    client_id = models.CharField(default=None,
                                 max_length=64,
                                 blank=True,
                                 null=True)
    addon_name = models.CharField(default=None,
                                  max_length=255,
                                  blank=True,
                                  null=True)
    addon_summary = models.CharField(default=None,
                                     max_length=255,
                                     blank=True,
                                     null=True)
    addon_version = models.CharField(default=None,
                                     max_length=255,
                                     blank=True,
                                     null=True)
    addon_signature = models.PositiveSmallIntegerField(
        default=None, choices=ADDON_SIGNATURES.choices, blank=True, null=True)
    application = models.PositiveSmallIntegerField(default=amo.FIREFOX.id,
                                                   choices=amo.APPS_CHOICES,
                                                   blank=True,
                                                   null=True)
    application_version = models.CharField(default=None,
                                           max_length=255,
                                           blank=True,
                                           null=True)
    application_locale = models.CharField(default=None,
                                          max_length=255,
                                          blank=True,
                                          null=True)
    operating_system = models.CharField(default=None,
                                        max_length=255,
                                        blank=True,
                                        null=True)
    operating_system_version = models.CharField(default=None,
                                                max_length=255,
                                                blank=True,
                                                null=True)
    install_date = models.DateTimeField(default=None, blank=True, null=True)
    reason = models.PositiveSmallIntegerField(default=None,
                                              choices=REASONS.choices,
                                              blank=True,
                                              null=True)
    addon_install_origin = models.CharField(default=None,
                                            max_length=255,
                                            blank=True,
                                            null=True)
    addon_install_method = models.PositiveSmallIntegerField(
        default=None,
        choices=ADDON_INSTALL_METHODS.choices,
        blank=True,
        null=True)
    report_entry_point = models.PositiveSmallIntegerField(
        default=None,
        choices=REPORT_ENTRY_POINTS.choices,
        blank=True,
        null=True)

    unfiltered = AbuseReportManager(include_deleted=True)
    objects = AbuseReportManager()

    class Meta:
        db_table = 'abuse_reports'

    def send(self):
        if self.reporter:
            user_name = '%s (%s)' % (self.reporter.name, self.reporter.email)
        else:
            user_name = 'An anonymous user'

        target_url = ('%s%s' % (settings.SITE_URL, self.target.get_url_path())
                      if self.target else 'GUID not in database')
        name = self.target.name if self.target else self.guid
        msg = u'%s reported abuse for %s (%s).\n\n%s' % (
            user_name, name, target_url, self.message)
        send_mail(six.text_type(self),
                  msg,
                  recipient_list=(settings.ABUSE_EMAIL, ))

    def save(self, *args, **kwargs):
        creation = not self.pk
        super(AbuseReport, self).save(*args, **kwargs)
        if creation:
            self.send()

    def delete(self, *args, **kwargs):
        # AbuseReports are soft-deleted. Note that we keep relations, because
        # the only possible relations are to users and add-ons, which are also
        # soft-deleted.
        return self.update(state=self.STATES.DELETED)

    @classmethod
    def lookup_country_code_from_ip(cls, ip):
        try:
            # Early check to avoid initializing GeoIP2 on invalid addresses
            if not ip:
                raise forms.ValidationError('No IP')
            validate_ipv46_address(ip)
            geoip = GeoIP2()
            value = geoip.country_code(ip)
        # Annoyingly, we have to catch both django's GeoIP2Exception (setup
        # issue) and geoip2's GeoIP2Error (lookup issue)
        except (forms.ValidationError, GeoIP2Exception, GeoIP2Error):
            value = ''
        return value

    @property
    def target(self):
        return self.addon or self.user

    @property
    def type(self):
        with translation.override(settings.LANGUAGE_CODE):
            type_ = (translation.ugettext(amo.ADDON_TYPE[self.addon.type])
                     if self.addon else 'User' if self.user else 'Addon')
        return type_

    def __str__(self):
        name = self.target.name if self.target else self.guid
        return u'[%s] Abuse Report for %s' % (self.type, name)
Beispiel #13
0
from django.core.urlresolvers import reverse
from django.db import models

from djangohistory.diff import pretty_diff
from djangohistory.helpers import get_ct, get_ct_by_id, match_field, models_schemas

from collections import OrderedDict

import six

from extended_choices import Choices
ACTIONS = Choices(
    ('save', 1, 'save'),
    ('delete', 2, 'delete'),
    ('post_add', 3, 'm2m.add'),
    ('post_remove', 4, 'm2m.remove'),
    ('pre_clear', 5, 'm2m.clear'),
    ('add', 6, 'add'),
    ('rem', 7, 'remove'),
)
action_id = lambda x: ACTIONS.for_display(x).value

class HistoryMixin(object):
    def link_instance(self):
        return reverse("history-by-id", kwargs=dict(ct_id=self.model, id=self.object_id))

    def link_field(self, model, name, values):
        rel = model._meta.get_field(name).related_model
        ct_id = 0
        oid = 0
        if rel and values.get('changed'):
Beispiel #14
0
    ApiNotFoundError,
    parse_header_links,
    prepare_fetch_headers,
)
from ..managers import MODE_ALL, GithubObjectManager


class MinDateRaised(Exception):
    pass


GITHUB_STATUS_CHOICES = Choices(
    ('WAITING_CREATE', 1, u'Awaiting creation'),
    ('WAITING_UPDATE', 2, u'Awaiting update'),
    ('WAITING_DELETE', 3, u'Awaiting deletion'),
    ('FETCHED', 10, u'Fetched'),
    ('ERROR_CREATE', 21, u'Error while creating'),
    ('ERROR_UPDATE', 22, u'Error while updating'),
    ('ERROR_DELETE', 23, u'Error while deleting'),
    ('ERROR_FETCHED', 30, u'Error while fetching'),
)
GITHUB_STATUS_CHOICES.ALL_WAITING = (GITHUB_STATUS_CHOICES.WAITING_CREATE,
                                     GITHUB_STATUS_CHOICES.WAITING_UPDATE,
                                     GITHUB_STATUS_CHOICES.WAITING_DELETE)
GITHUB_STATUS_CHOICES.ALL_ERRORS = (GITHUB_STATUS_CHOICES.ERROR_CREATE,
                                    GITHUB_STATUS_CHOICES.ERROR_UPDATE,
                                    GITHUB_STATUS_CHOICES.ERROR_DELETE,
                                    GITHUB_STATUS_CHOICES.ERROR_FETCHED)

GITHUB_STATUS_CHOICES.NOT_READY = (
    GITHUB_STATUS_CHOICES.WAITING_DELETE,
    GITHUB_STATUS_CHOICES.WAITING_CREATE,
from extended_choices import Choices

YES_NO_CHOICES = (
    (True, 'Yes'),
    (False, 'No'),
)
JUDGMENT_CHOICES = (
    (True, 'Yes'),
    (False, 'No'),
)

WORKFLOW_TYPE_CHOICES = Choices(
    ['WITHOUT_EVIDENCE_URL_WORKFLOW', 'without evidence url workflow',
     'without evidence url workflow'],
    ['EVIDENCE_URL_INPUT_WORKFLOW', 'evidence url input workflow',
     'evidence url input workflow'],
    ['EVIDENCE_URLS_JUDGMENT_WORKFLOW', 'evidence urls judgment workflow',
     'evidence urls judgment workflow'],
)

TAKE_ACTION_CHOICES = (
    ('Yes', 'Yes, one or more of these actions should be taken.'),
    ('No', 'No, none of these actions should be taken.'),
    ('Not enough info', "I don't have enough information to judge")
)


JUDGMENT_REMOVE_CHOICES = (
    (True, 'Yes, platforms should remove the item.'),
    (False, 'No, platforms should not remove the item.'),
)
Beispiel #16
0
# -*- coding:utf-8 -*-
from django.db import models
from django_extensions.db import fields as exfields
from django.utils.translation import ugettext_lazy as _
from extended_choices import Choices
import datetime


EXCHANGE = Choices(
    ('OFFER',   0,  'Offre'),
    ('NEED',    1,  'Demande'),
)


class BaseExchange(models.Model):
    title = models.CharField(_('Titre'),blank=True,max_length=250)
    description = models.TextField(_(u'Description'),blank=True)
    org = models.ForeignKey('coop_local.Initiative',blank=True,null=True)
    member = models.ForeignKey('coop_local.Membre')
    etype = models.PositiveSmallIntegerField( _(u'Type d’annonce'),
                                                    choices=EXCHANGE.CHOICES, 
                                                    default=EXCHANGE.OFFER)
    uri = models.CharField(_(u'URI principale'),blank=True, max_length=250, editable=False)
    expiration = models.DateField(default=datetime.datetime.today,blank=True,null=True)
    slug = exfields.AutoSlugField(populate_from='title')
    created = exfields.CreationDateTimeField(_(u'Création'),null=True)
    modified = exfields.ModificationDateTimeField(_(u'Modification'),null=True)
    #membre_uri = models.CharField(_(u'Profil FOAF'),blank=True, max_length=250, editable=False)
    class Meta:
        abstract = True
        
Beispiel #17
0
        owner_username, repository_name = self.repository_name.split('/')
        subscription, _ = Subscription.objects.get_or_create(
            user=self.user,
            repository=self.repository
        )
        subscription.state = SUBSCRIPTION_STATES.ADMIN if rights == "admin" \
                             else SUBSCRIPTION_STATES.USER if rights == "push" \
                             else SUBSCRIPTION_STATES.READ
        subscription.save()

        self.delete()


SUBSCRIPTION_STATES = Choices(
    ('READ', 1, 'Simple user'),  # can read, create issues
    ('USER', 2, 'Collaborator'),  # can push, manage issues
    ('ADMIN', 3, 'Admin'),  # can admin, push, manage issues
    ('NORIGHTS', 4, 'No rights'),  # no access
)
SUBSCRIPTION_STATES.ALL_RIGHTS = [s[0] for s in SUBSCRIPTION_STATES]
SUBSCRIPTION_STATES.READ_RIGHTS = [SUBSCRIPTION_STATES.READ, SUBSCRIPTION_STATES.USER, SUBSCRIPTION_STATES.ADMIN]
SUBSCRIPTION_STATES.WRITE_RIGHTS = [SUBSCRIPTION_STATES.USER, SUBSCRIPTION_STATES.ADMIN]


class Subscription(models.Model):
    user = models.ForeignKey(GithubUser, related_name='subscriptions')
    repository = models.ForeignKey(Repository, related_name='subscriptions')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    state = models.PositiveSmallIntegerField(
        choices=SUBSCRIPTION_STATES.CHOICES,
        default=SUBSCRIPTION_STATES.READ)
Beispiel #18
0
from extended_choices import Choices

GRANULARITY = Choices(('DAY', 'day', 'День', {
    'pluralize': ['день', 'дня', 'дней']
}), ('WEEK', 'week', 'Неделя', {
    'pluralize': ['неделя', 'недели', 'недель']
}), ('MONTH', 'month', 'Месяц', {
    'pluralize': ['месяц', 'месяца', 'месяцев']
}), ('YEAR', 'year', 'Год', {
    'pluralize': ['год', 'года', 'лет']
}))

BALANCE_REASON = Choices(
    ('UPDATE_BALANCE', 'Пополнение баланса', 'Пополнение баланса'),
    ('BY_SUBSCRIPTION', 'Покупка абонемента', 'Покупка абонемента'),
    ('ONE_TIME', 'Разовое посещение', 'Разовое посещение'),
    ('ERROR_FIX', 'Исправление ошибки', 'Исправление ошибки'),
    ('OTHER', 'Иное', 'Иное'),
)
Beispiel #19
0
from django.utils.translation import gettext_lazy as _
from extended_choices import Choices

PAYMENT_STATUS = Choices(
    ('PENDING', 'pending', _('Pending')),  # the GOV.UK payment is ongoing
    ('FAILED', 'failed',
     _('Failed')),  # the GOV.UK payment failed or was in error
    ('TAKEN', 'taken',
     _('Taken')),  # the GOV.UK payment was successful and has a capture date
    (
        'REJECTED', 'rejected', _('Rejected')
    ),  # the GOV.UK payment didn't pass our security checks so it was cancelled
    (
        'EXPIRED', 'expired', _('Expired')
    ),  # the GOV.UK payment was capturable but timed out before being captured
)
Beispiel #20
0
from extended_choices import Choices
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
# update this to use customisable setting
# from django.contrib.auth.models import User
from django.conf import settings

#from taggit.models import TagBase, GenericTaggedItemBase
#from taggit.managers import TaggableManager
from rdf_io.models import Namespace, GenericMetaProp

import json

LABEL_TYPES = Choices(
    ('prefLabel', 0, u'preferred'),
    ('altLabel', 1, u'alternative'),
    ('hiddenLabel', 2, u'hidden'),
)

REL_TYPES = Choices(
    # ('broaderTransitive',   0,  u'Has a broader (transitive) concept'),
    # ('narrowerTransitive',  1,  u'Has a narrower (transitive) concept'),
    ('broader', 0, u'has a broader concept'),
    ('narrower', 1, u'has a narrower concept'),
    ('related', 2, u'has a related concept'),
)

reverse_map = {
    # REL_TYPES.narrowerTransitive    : REL_TYPES.broaderTransitive,
    # REL_TYPES.broaderTransitive     : REL_TYPES.narrowerTransitive,
    REL_TYPES.narrower:
Beispiel #21
0
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.db import models as gismodels
from django.conf import settings

from extended_choices import Choices
from mapentity.models import MapEntityMixin

from geotrek.common.utils import classproperty
from geotrek.core.models import Topology, Path
from geotrek.authent.models import StructureRelatedManager, StructureRelated, StructureOrNoneRelated
from geotrek.common.mixins import BasePublishableMixin, OptionalPictogramMixin

INFRASTRUCTURE_TYPES = Choices(
    ('BUILDING', 'A', _("Building")),
    ('FACILITY', 'E', _("Facility")),
    ('SIGNAGE', 'S', _("Signage")),
)


class InfrastructureTypeQuerySet(models.query.QuerySet):
    def for_infrastructures(self):
        return self.exclude(type__exact=INFRASTRUCTURE_TYPES.SIGNAGE)

    def for_signages(self):
        return self.filter(type__exact=INFRASTRUCTURE_TYPES.SIGNAGE)


class InfrastructureTypeManager(models.Manager):
    def get_queryset(self):
        return InfrastructureTypeQuerySet(self.model, using=self._db)
from django.utils.translation import gettext_lazy as _
from extended_choices import Choices

LOG_ACTIONS = Choices(
    ('CREATED', 'created', _('Created')),
    ('EDITED', 'edited', _('Edited')),
    ('REJECTED', 'rejected', _('Rejected')),
    ('CONFIRMED', 'confirmed', _('Confirmed')),
    ('SENT', 'sent', _('Sent')),
)

DISBURSEMENT_RESOLUTION = Choices(
    ('PENDING', 'pending', _('Pending')),
    ('REJECTED', 'rejected', _('Rejected')),
    ('PRECONFIRMED', 'preconfirmed', _('Pre-confirmed')),
    ('CONFIRMED', 'confirmed', _('Confirmed')),
    ('SENT', 'sent', _('Sent')),
)

DISBURSEMENT_METHOD = Choices(
    ('BANK_TRANSFER', 'bank_transfer', _('Bank transfer')),
    ('CHEQUE', 'cheque', _('Cheque')),
)
Beispiel #23
0
# Dont go to callback page for these cats
NO_CALLBACK_CATEGORIES = ("benefits",)

YES = "1"
NO = "0"

CATEGORY_ID_MAPPING = {"violence": "family"}

ORGANISATION_CATEGORY_MAPPING = {
    "Domestic abuse": "Family",
    "Public law": "Public",
    "Trouble with the police": "Action against police",
}

SAFE_TO_CONTACT = "SAFE"

CONTACT_PREFERENCE = Choices(
    ("CALL", "call", _(u"I’ll call CLA")),
    ("CALLBACK", "callback", _(u"Call me back")),
    ("THIRDPARTY", "thirdparty", _(u"Call someone else instead of me")),
)

LEGAL_ADVISER_SEARCH_PREFERENCE = (("location", _(u"Location")), ("organisation", _(u"Organisation")))

END_SERVICE_FLASH_MESSAGE = _(
    u"The information you’ve entered has not been stored on your computer or "
    u"mobile device. If you are at risk of harm, you should delete your "
    u"browser history."
)
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

from extended_choices import Choices


ITEM_TO_PUSH_STATUS = Choices(
    ('NEW', 10, 'New'),
    ('IN_PROGRESS', 20, 'In progress'),
    ('PUSHED', 50, 'Pushed'),
    # ERRORS SHOULD BE OVER 100
    ('PUSH_ERROR', 110, 'Push error'),
    ('OUTPUT_GENERATION_ERROR', 120, 'Could not generate output file'),
    ('SEND_ERROR', 130, 'Could not send file'),
    ('FILTER_BY_INSTANCE_TYPE_ERROR', 140, 'Error in select during filter by instance type'),
    ('FILTER_BY_UPDATES_ERROR', 150, 'Error in select during filter by updates'),
    ('FILTER_BY_STATE_ERROR', 160, 'Error in select during filter by state'),
    ('GET_DIRECTORY_ERROR', 170, 'Error in select during get directory'),
    ('VALIDATION_ERROR', 180, 'Failed validation'),
    ('SUPERVISOR_ERROR', 190, 'No Supervisor found'),
    ('OUTPUT_MARKER_ERROR', 200, 'No output_marker found'),
)


from carrier_pigeon import managers


class BasicDirtyFieldsMixin(object):
    """Mixin class that stores modified attributes in ``_modified_attrs``.
    ``modified_attrs`` is reset after save"""
Beispiel #25
0
# -*- coding: utf-8 -*-

from django.db import models

from extended_choices import Choices

from carrier_pigeon.models import BasicDirtyFieldsMixin

WORKFLOW_STATE = Choices(
    ('OFFLINE', 10, u'Hors ligne'),
    ('ONLINE', 20, u'En ligne'),
    ('DELETED', 99, u'Supprimé'),
)


class Photo(models.Model):
    """One content illustration."""

    title = models.CharField(blank=True, max_length=512)
    credits = models.CharField(blank=True, max_length=100)
    caption = models.CharField(blank=True, max_length=512)
    original_file = models.FileField(upload_to="photo/%Y/%m/%d",
                                     max_length=200)

    def __unicode__(self):
        return self.title


class Story(models.Model, BasicDirtyFieldsMixin):
    """One content object of a news site."""
Beispiel #26
0
from geotrek.core.models import Topology
from geotrek.common.mixins import (NoDeleteMixin, TimeStampedModelMixin,
                                   PictogramMixin, OptionalPictogramMixin,
                                   PublishableMixin, PicturesMixin,
                                   AddPropertyMixin)
from geotrek.common.models import Theme
from geotrek.common.utils import intersecting

from extended_choices import Choices
from multiselectfield import MultiSelectField

logger = logging.getLogger(__name__)

DATA_SOURCE_TYPES = Choices(
    ('GEOJSON', 'GEOJSON', _("GeoJSON")),
    ('TOURINFRANCE', 'TOURINFRANCE', _("TourInFrance")),
    ('SITRA', 'SITRA', _("Sitra")),
)


def _get_target_choices():
    """ Populate choices using installed apps names.
    """
    apps = [('public', _("Public website"))]
    for model, entity in registry.registry.items():
        if entity.menu:
            appname = model._meta.app_label.lower()
            apps.append((appname, unicode(entity.label)))
    return tuple(apps)

 def __init__(self, extended_choices=None, *args, **kwargs):
     super(ExtendedChoiceField, self).__init__(*args, **kwargs)
     if not extended_choices:
         extended_choices = Choices()
     self.extended_choices = extended_choices
     self.value_for_display = None
Beispiel #28
0
from extended_choices import Choices
from datetime import timedelta

BADGES = Choices(
    ("STAR", 1, "Star"),
    ("COLLECTOR", 2, "Collector"),
    ("PIONNEER", 3, "Pionneer"),
)

NB_VIEWS_FOR_STAR = 1000
NB_MODELS_FOR_COLLECTOR = 5
TIMEDELTA_FOR_PIONNEER = timedelta(days=365)
PIONNEER_TASK_BEAT = 3600
from extended_choices import Choices

LOG_LEVELS = Choices(
    # constant, db_id, friendly string
    ('HIGH', 29, 'HIGH'),
    ('MODERATE', 21, 'MODERATE'),
    ('MINOR', 11, 'MINOR'),
)

LOG_TYPES = Choices(
    # constant, db_id, friendly string
    ('OUTCOME', 'outcome', 'outcome'),
    ('SYSTEM', 'system', 'system'))

LOG_ROLES = Choices(
    # constant, db_id, friendly string
    ('OPERATOR', 'operator', 'operator'),
    ('SPECIALIST', 'specialist', 'special'))
Beispiel #30
0
class AbuseReport(ModelBase):
    # Note: those choices don't need to be translated for now, the
    # human-readable values are only exposed in the admin.
    ADDON_SIGNATURES = APIChoicesWithNone(
        ('CURATED_AND_PARTNER', 1, 'Curated and partner'),
        ('CURATED', 2, 'Curated'),
        ('PARTNER', 3, 'Partner'),
        ('NON_CURATED', 4, 'Non-curated'),
        ('UNSIGNED', 5, 'Unsigned'),
        ('BROKEN', 6, 'Broken'),
        ('UNKNOWN', 7, 'Unknown'),
        ('MISSING', 8, 'Missing'),
        ('PRELIMINARY', 9, 'Preliminary'),
        ('SIGNED', 10, 'Signed'),
        ('SYSTEM', 11, 'System'),
        ('PRIVILEGED', 12, 'Privileged'),
    )
    REASONS = APIChoicesWithNone(
        ('DAMAGE', 1, 'Damages computer and/or data'),
        ('SPAM', 2, 'Creates spam or advertising'),
        ('SETTINGS', 3, 'Changes search / homepage / new tab page '
         'without informing user'),
        # `4` was previously 'New tab takeover' but has been merged into the
        # previous one. We avoid re-using the value.
        ('BROKEN', 5, "Doesn’t work, breaks websites, or slows Firefox down"),
        ('POLICY', 6, 'Hateful, violent, or illegal content'),
        ('DECEPTIVE', 7, "Pretends to be something it’s not"),
        # `8` was previously "Doesn't work" but has been merged into the
        # previous one. We avoid re-using the value.
        ('UNWANTED', 9, "Wasn't wanted / impossible to get rid of"),
        # `10` was previously "Other". We avoid re-using the value.
        ('OTHER', 127, 'Other'),
    )

    # https://searchfox.org
    # /mozilla-central/source/toolkit/components/telemetry/Events.yaml#122-131
    # Firefox submits values in lowercase, with '-' and ':' changed to '_'.
    ADDON_INSTALL_METHODS = APIChoicesWithNone(
        ('AMWEBAPI', 1, 'Add-on Manager Web API'),
        ('LINK', 2, 'Direct link'),
        ('INSTALLTRIGGER', 3, 'Install Trigger'),
        ('INSTALL_FROM_FILE', 4, 'From File'),
        ('MANAGEMENT_WEBEXT_API', 5, 'Webext management API'),
        ('DRAG_AND_DROP', 6, 'Drag & Drop'),
        ('SIDELOAD', 7, 'Sideload'),
        # Values between 8 and 13 are obsolete, we use to merge
        # install source and method into addon_install_method before deciding
        # to split the two like Firefox does, so these 6 values are only kept
        # for backwards-compatibility with older reports and older versions of
        # Firefox that still only submit that.
        ('FILE_URL', 8, 'File URL'),
        ('ENTERPRISE_POLICY', 9, 'Enterprise Policy'),
        ('DISTRIBUTION', 10, 'Included in build'),
        ('SYSTEM_ADDON', 11, 'System Add-on'),
        ('TEMPORARY_ADDON', 12, 'Temporary Add-on'),
        ('SYNC', 13, 'Sync'),
        # Back to normal values.
        ('URL', 14, 'URL'),
        # Our own catch-all. The serializer expects it to be called "OTHER".
        ('OTHER', 127, 'Other'),
    )
    ADDON_INSTALL_SOURCES = APIChoicesWithNone(
        ('ABOUT_ADDONS', 1, 'Add-ons Manager'),
        ('ABOUT_DEBUGGING', 2, 'Add-ons Debugging'),
        ('ABOUT_PREFERENCES', 3, 'Preferences'),
        ('AMO', 4, 'AMO'),
        ('APP_PROFILE', 5, 'App Profile'),
        ('DISCO', 6, 'Disco Pane'),
        ('DISTRIBUTION', 7, 'Included in build'),
        ('EXTENSION', 8, 'Extension'),
        ('ENTERPRISE_POLICY', 9, 'Enterprise Policy'),
        ('FILE_URL', 10, 'File URL'),
        ('GMP_PLUGIN', 11, 'GMP Plugin'),
        ('INTERNAL', 12, 'Internal'),
        ('PLUGIN', 13, 'Plugin'),
        ('RTAMO', 14, 'Return to AMO'),
        ('SYNC', 15, 'Sync'),
        ('SYSTEM_ADDON', 16, 'System Add-on'),
        ('TEMPORARY_ADDON', 17, 'Temporary Add-on'),
        ('UNKNOWN', 18, 'Unknown'),
        # Our own catch-all. The serializer expects it to be called "OTHER".
        ('OTHER', 127, 'Other'),
    )
    REPORT_ENTRY_POINTS = APIChoicesWithNone(
        ('UNINSTALL', 1, 'Uninstall'),
        ('MENU', 2, 'Menu'),
        ('TOOLBAR_CONTEXT_MENU', 3, 'Toolbar context menu'),
        ('AMO', 4, 'AMO'),
    )
    STATES = Choices(
        ('UNTRIAGED', 1, 'Untriaged'),
        ('VALID', 2, 'Valid'),
        ('SUSPICIOUS', 3, 'Suspicious'),
        ('DELETED', 4, 'Deleted'),
    )

    # NULL if the reporter is anonymous.
    reporter = models.ForeignKey(UserProfile,
                                 null=True,
                                 blank=True,
                                 related_name='abuse_reported',
                                 on_delete=models.SET_NULL)
    country_code = models.CharField(max_length=2, default=None, null=True)
    # An abuse report can be for an addon or a user.
    # If user is non-null then both addon and guid should be null.
    # If user is null then addon should be non-null if guid was in our DB,
    # otherwise addon will be null also.
    # If both addon and user is null guid should be set.
    addon = models.ForeignKey(Addon,
                              null=True,
                              related_name='abuse_reports',
                              on_delete=models.CASCADE)
    guid = models.CharField(max_length=255, null=True)
    user = models.ForeignKey(UserProfile,
                             null=True,
                             related_name='abuse_reports',
                             on_delete=models.SET_NULL)
    message = models.TextField(blank=True)

    state = models.PositiveSmallIntegerField(default=STATES.UNTRIAGED,
                                             choices=STATES.choices)

    # Extra optional fields for more information, giving some context that is
    # meant to be extracted automatically by the client (i.e. Firefox) and
    # submitted via the API.
    client_id = models.CharField(default=None,
                                 max_length=64,
                                 blank=True,
                                 null=True)
    addon_name = models.CharField(default=None,
                                  max_length=255,
                                  blank=True,
                                  null=True)
    addon_summary = models.CharField(default=None,
                                     max_length=255,
                                     blank=True,
                                     null=True)
    addon_version = models.CharField(default=None,
                                     max_length=255,
                                     blank=True,
                                     null=True)
    addon_signature = models.PositiveSmallIntegerField(
        default=None, choices=ADDON_SIGNATURES.choices, blank=True, null=True)
    application = models.PositiveSmallIntegerField(default=amo.FIREFOX.id,
                                                   choices=amo.APPS_CHOICES,
                                                   blank=True,
                                                   null=True)
    application_version = models.CharField(default=None,
                                           max_length=255,
                                           blank=True,
                                           null=True)
    application_locale = models.CharField(default=None,
                                          max_length=255,
                                          blank=True,
                                          null=True)
    operating_system = models.CharField(default=None,
                                        max_length=255,
                                        blank=True,
                                        null=True)
    operating_system_version = models.CharField(default=None,
                                                max_length=255,
                                                blank=True,
                                                null=True)
    install_date = models.DateTimeField(default=None, blank=True, null=True)
    reason = models.PositiveSmallIntegerField(default=None,
                                              choices=REASONS.choices,
                                              blank=True,
                                              null=True)
    addon_install_origin = models.CharField(default=None,
                                            max_length=255,
                                            blank=True,
                                            null=True)
    addon_install_method = models.PositiveSmallIntegerField(
        default=None,
        choices=ADDON_INSTALL_METHODS.choices,
        blank=True,
        null=True)
    addon_install_source = models.PositiveSmallIntegerField(
        default=None,
        choices=ADDON_INSTALL_SOURCES.choices,
        blank=True,
        null=True)
    report_entry_point = models.PositiveSmallIntegerField(
        default=None,
        choices=REPORT_ENTRY_POINTS.choices,
        blank=True,
        null=True)

    unfiltered = AbuseReportManager(include_deleted=True)
    objects = AbuseReportManager()

    class Meta:
        db_table = 'abuse_reports'
        # See comment in addons/models.py about base_manager_name. It needs to
        # be unfiltered to prevent exceptions when dealing with relations or
        # saving already deleted objects.
        base_manager_name = 'unfiltered'
        indexes = [
            models.Index(fields=('created', ), name='created_idx'),
        ]

    @property
    def metadata(self):
        """
        Dict of metadata about this report. Only includes non-null values.
        """
        data = {}
        field_names = ('client_id', 'addon_name', 'addon_summary',
                       'addon_version', 'addon_signature', 'application',
                       'application_version', 'application_locale',
                       'operating_system', 'operating_system_version',
                       'install_date', 'reason', 'addon_install_origin',
                       'addon_install_method', 'report_entry_point')
        for field_name in field_names:
            value = self.__dict__[field_name]
            # Only include values that matter.
            if value is not None:
                field = self._meta.get_field(field_name)
                # If it's a choice field, display the "pretty" version.
                if field.choices:
                    value = getattr(self, 'get_%s_display' % field_name)()
                data[field_name] = value
        return data

    def delete(self, *args, **kwargs):
        # AbuseReports are soft-deleted. Note that we keep relations, because
        # the only possible relations are to users and add-ons, which are also
        # soft-deleted.
        return self.update(state=self.STATES.DELETED)

    @classmethod
    def lookup_country_code_from_ip(cls, ip):
        try:
            # Early check to avoid initializing GeoIP2 on invalid addresses
            if not ip:
                raise forms.ValidationError('No IP')
            validate_ipv46_address(ip)
            geoip = GeoIP2()
            value = geoip.country_code(ip)
        # Annoyingly, we have to catch both django's GeoIP2Exception (setup
        # issue) and geoip2's GeoIP2Error (lookup issue)
        except (forms.ValidationError, GeoIP2Exception, GeoIP2Error):
            value = ''
        return value

    @property
    def target(self):
        return self.addon or self.user

    @property
    def type(self):
        with translation.override(settings.LANGUAGE_CODE):
            if self.addon and self.addon.type in amo.ADDON_TYPE:
                type_ = (translation.ugettext(amo.ADDON_TYPE[self.addon.type]))
            elif self.user:
                type_ = 'User'
            else:
                type_ = 'Addon'
        return type_

    def __str__(self):
        name = self.target.name if self.target else self.guid
        return u'[%s] Abuse Report for %s' % (self.type, name)
Beispiel #31
0
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
from django.conf import settings

from bs4 import BeautifulSoup
from extended_choices import Choices

from mapentity.serializers import plain_text
from geotrek.common.mixins import TimeStampedModelMixin, BasePublishableMixin


FLATPAGES_TARGETS = Choices(
    ('ALL', 'all', _('All')),
    ('MOBILE', 'mobile', _('Mobile')),
    ('HIDDEN', 'hidden', _('Hidden')),
    ('WEB', 'web', _('Web')),
)


class FlatPage(BasePublishableMixin, TimeStampedModelMixin):
    """
    Manage *Geotrek-rando* static pages from Geotrek admin.

    Historically, we started static pages as static HTML files within
    *Geotrek-rando* folders.
    """
    title = models.CharField(verbose_name=_(u'Title'), max_length=200,
                             db_column='titre')
    external_url = models.URLField(verbose_name=_(u'External URL'), blank=True,
                                   db_column='url_externe', default='',
# -*- coding: utf-8 -*-
from os import environ as env
import datetime

from extended_choices import Choices


ELIGIBILITY_STATES = Choices(
    # constant, db_id, friendly string
    ("UNKNOWN", "unknown", "Unknown"),
    ("YES", "yes", "Yes"),
    ("NO", "no", "No"),
)

ELIGIBILITY_REASONS = Choices(
    # constant, db_id, friendly string
    ("DISPOSABLE_CAPITAL", "DISPOSABLE_CAPITAL", "Disposable capital too high"),
    ("GROSS_INCOME", "GROSS_INCOME", "Gross income too high"),
    ("DISPOSABLE_INCOME", "DISPOSABLE_INCOME", "Disposable income too high"),
)

TITLES = Choices(
    # constant, db_id, friendly string
    ("MR", "mr", "Mr"),
    ("MRS", "mrs", "Mrs"),
    ("MISS", "miss", "Miss"),
    ("MS", "ms", "Ms"),
    ("DR", "dr", "Dr"),
)

Beispiel #33
0
        except InvalidImageFormatError:
            logger.warning(
                _("Image %s invalid or missing from disk.") % self.photo)
            return None

    @property
    def photo_url(self):
        thumbnail = self.thumbnail
        if not thumbnail:
            return None
        return os.path.join(settings.MEDIA_URL, thumbnail.name)


GEOMETRY_TYPES = Choices(
    ('POINT', 'point', _('Point')),
    ('LINE', 'line', _('Line')),
    ('POLYGON', 'polygon', _('Polygon')),
    ('ANY', 'any', _('Any')),
)


class TouristicContentCategory(PictogramMixin):

    label = models.CharField(verbose_name=_(u"Label"),
                             max_length=128,
                             db_column='nom')
    geometry_type = models.CharField(db_column="type_geometrie",
                                     max_length=16,
                                     choices=GEOMETRY_TYPES,
                                     default=GEOMETRY_TYPES.POINT)
    type1_label = models.CharField(verbose_name=_(u"First list label"),
                                   max_length=128,