Exemple #1
0
class User(models.Model):
	# id bigint NOT NULL,
	id = models.BigAutoField(primary_key = True)
	# uuid uuid DEFAULT public.gen_random_uuid(),
	uuid = models.UUIDField(blank = True, null = False)
	# name_first character varying,
	name_first = models.CharField(max_length = 255, blank = True)
	# name_last character varying,
	name_last = models.CharField(max_length = 255, blank = True)
	# nickname character varying,
	nickname = models.CharField(max_length = 255, blank = True)
	# avatar_url character varying,
	avatar_url = models.CharField(max_length = 255, blank = True)
	# email character varying,
	email = models.CharField(max_length = 255, blank = True)
	# created_at timestamp without time zone DEFAULT now() NOT NULL,
	created_at = models.DateTimeField()
	# updated_at timestamp without time zone DEFAULT now() NOT NULL,
	updated_at = models.DateTimeField()
	# preferences jsonb,
	preferences = models.JSONField(blank = True)
	# avatar_image bytea,
	avatar_image = models.BinaryField(blank = True)
	# non_user_notification_state jsonb
	non_user_notification_state = models.JSONField(blank = True)

	class Meta:
		managed = False
		db_table = 'users'
		required_db_vendor = 'postgis'
Exemple #2
0
class AttributeClass(UIDMixin, TimeStampedModelMixin):

    __original_filter: dict = None
    __original_exclude: dict = None
    __original_complex: dict = None

    name = models.CharField(max_length=100, blank=False, unique=True)
    slug = LowerCaseCharField(max_length=40, blank=False, unique=True, db_index=True)
    filter = models.JSONField(
        null=True,
        blank=True,
        help_text="This field should be a dict which is passed directly to the user model for filtering users. "
        "For help see django docs on filtering models.",
    )
    exclude = models.JSONField(
        null=True,
        blank=True,
        help_text="This field should be a dict which is passed directly to the user model for excluding users. "
        "For help see django docs on excluding models.",
    )
    complex = models.JSONField(
        null=True,
        blank=True,
        unique=True,
        help_text='This is a thruple of nested thruples represented as lists. Example: \'["blue","==","color"]\'.',
    )
    users = models.ManyToManyField(User, related_name="attribute_classes")

    def __init__(self, *args, **kwargs):
        super(AttributeClass, self).__init__(*args, **kwargs)
        self.__original_filter = self.filter
        self.__original_exclude = self.exclude
        self.__original_complex = self.complex

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["filter", "exclude"], name="unique_filter_exclude"),
        ]
        verbose_name_plural = "Attribute Classes"
        verbose_name = "Attribute Class"

    def save(self, *args, **kwargs):
        # Save is here twice because if this is a NEW object it won't have an ID yet which is required.
        super(AttributeClass, self).save(*args, **kwargs)
        if any(
            [
                self.filter != self.__original_filter,
                self.exclude != self.__original_exclude,
                self.complex != self.__original_complex,
            ]
        ):
            # If this changes we need to ensure that all users correctly reflect the updates.
            update_all_users_with_attribute_class(self)
        self.__original_filter = self.filter
        self.__original_exclude = self.exclude
        self.__original_complex = self.complex

    def __str__(self):
        return self.name
Exemple #3
0
class IndicatorReportable(ReadOnlyModel):
    created = models.DateTimeField()
    modified = models.DateTimeField()
    external_id = models.CharField(max_length=32, blank=True, null=True)
    external_source = models.TextField(blank=True, null=True)
    target = models.JSONField()
    baseline = models.JSONField()
    in_need = models.JSONField(blank=True, null=True)
    assumptions = models.TextField(blank=True, null=True)
    means_of_verification = models.CharField(max_length=255,
                                             blank=True,
                                             null=True)
    comments = models.TextField(blank=True, null=True)
    measurement_specifications = models.TextField(blank=True, null=True)
    label = models.TextField(blank=True, null=True)
    numerator_label = models.CharField(max_length=256, blank=True, null=True)
    denominator_label = models.CharField(max_length=256, blank=True, null=True)
    start_date_of_reporting_period = models.DateField(blank=True, null=True)
    is_cluster_indicator = models.BooleanField()
    is_unicef_hf_indicator = models.BooleanField()
    contributes_to_partner = models.BooleanField()
    total = models.JSONField()
    context_code = models.CharField(max_length=50, blank=True, null=True)
    object_id = models.IntegerField()
    frequency = models.CharField(max_length=3)
    cs_dates = models.TextField(blank=True,
                                null=True)  # This field type is a guess.
    location_admin_refs = models.TextField(
        blank=True, null=True)  # This field type is a guess.
    active = models.BooleanField()
    blueprint = models.ForeignKey(IndicatorIndicatorblueprint,
                                  models.PROTECT,
                                  related_name='IndicatorReportable_blueprint',
                                  blank=True,
                                  null=True)
    ca_indicator_used_by_reporting_entity = models.ForeignKey(
        'self',
        models.PROTECT,
        related_name=
        'IndicatorReportable_ca_indicator_used_by_reporting_entity',
        blank=True,
        null=True)
    content_type = models.ForeignKey(
        DjangoContentType,
        models.PROTECT,
        related_name='IndicatorReportable_content_type')
    parent_indicator = models.ForeignKey(
        'self',
        models.PROTECT,
        related_name='IndicatorReportable_parent_indicator',
        blank=True,
        null=True)

    class Meta:
        managed = False
        db_table = 'indicator_reportable'
        app_label = 'source_prp'
Exemple #4
0
class PartnerPartnerproject(ReadOnlyModel):
    created = models.DateTimeField()
    modified = models.DateTimeField()
    external_id = models.CharField(max_length=32, blank=True, null=True)
    external_source = models.TextField(blank=True, null=True)
    code = models.TextField(unique=True, blank=True, null=True)
    type = models.CharField(max_length=8, blank=True, null=True)
    title = models.CharField(max_length=1024)
    description = models.TextField(blank=True, null=True)
    additional_information = models.CharField(max_length=255,
                                              blank=True,
                                              null=True)
    custom_fields = models.JSONField(blank=True, null=True)
    start_date = models.DateField()
    end_date = models.DateField()
    status = models.CharField(max_length=3)
    agency_name = models.TextField(blank=True, null=True)
    agency_type = models.TextField(blank=True, null=True)
    prioritization = models.TextField(blank=True, null=True)
    total_budget = models.DecimalField(max_digits=12,
                                       decimal_places=2,
                                       blank=True,
                                       null=True)
    funding_source = models.TextField(blank=True, null=True)
    partner = models.ForeignKey(PartnerPartner,
                                models.PROTECT,
                                related_name='PartnerPartnerproject_partner')

    class Meta:
        managed = False
        db_table = 'partner_partnerproject'
        app_label = 'source_prp'
Exemple #5
0
class Question(models.Model):
    PLAIN_TEXT = 'plain_text'
    TEXT_INPUT = 'text_input'
    MULTI_TEXT_INPUT = 'multi_text_input'
    CHECKBOX_INPUT = 'checkbox_input'
    RADIO_INPUT = 'radio_input'
    SELECT_INPUT = 'select_input'
    TEXT_AREA_INPUT = 'text_area_input'
    MAP_SELECT = 'map_select'

    FIELD_TYPE_CHOICES = (
        (PLAIN_TEXT, 'PlainText'),
        (TEXT_INPUT, 'TextInput'),
        (MULTI_TEXT_INPUT, 'MultiTextInput'),
        (CHECKBOX_INPUT, 'CheckboxInput'),
        (RADIO_INPUT, 'RadioInput'),
        (SELECT_INPUT, 'SelectInput'),
        (TEXT_AREA_INPUT, 'TextareaInput'),
        (MAP_SELECT, 'MapSelect'),
    )

    key = models.CharField(max_length=255)
    field_type = models.CharField(max_length=32,
                                  choices=FIELD_TYPE_CHOICES,
                                  default=PLAIN_TEXT)
    meta = models.JSONField(blank=True, default=dict)
    required = models.BooleanField(default=False)

    class Meta:
        verbose_name_plural = 'Questions'

    def __str__(self):
        """String representation."""
        return '{key} - {meta}'.format(key=self.key, meta=self.meta)
class ProjectSubtype(models.Model):
    project_type = models.ForeignKey(
        ProjectType,
        verbose_name=_("project type"),
        on_delete=models.CASCADE,
        related_name="subtypes",
    )

    name = models.CharField(max_length=255, verbose_name=_("name"))
    metadata = models.JSONField(
        verbose_name=_("metadata"),
        default=dict,
        blank=True,
        null=True,
        encoder=DjangoJSONEncoder,
    )
    index = models.PositiveIntegerField(verbose_name=_("index"), default=0)

    class Meta:
        verbose_name = _("project subtype")
        verbose_name_plural = _("project subtypes")
        ordering = ("index", )

    def __str__(self):
        return self.name
Exemple #7
0
class Layer(models.Model):
    SCHEMAS = (('wms', 'WMS'), ('tms', 'TMS'))

    title = models.CharField('Titre', max_length=256, blank=True, null=True)

    service = models.CharField('Service', max_length=256)

    schema_type = models.CharField("Type de couche",
                                   choices=SCHEMAS,
                                   max_length=50,
                                   default="wms")

    options = models.JSONField("Options", blank=True, null=True)

    objects = models.Manager()

    handy = LayerManager()

    class Meta:
        verbose_name = 'Couche'
        verbose_name_plural = 'Couches'

    def __str__(self):
        title = self.title or ''
        return "{0} - {1} ({2})".format(title, self.service, self.schema_type)
Exemple #8
0
class VehicleRevision(models.Model):
    datetime = models.DateTimeField()
    vehicle = models.ForeignKey(Vehicle, models.CASCADE)
    from_operator = models.ForeignKey(Operator,
                                      models.CASCADE,
                                      null=True,
                                      blank=True,
                                      related_name='revision_from')
    to_operator = models.ForeignKey(Operator,
                                    models.CASCADE,
                                    null=True,
                                    blank=True,
                                    related_name='revision_to')
    changes = models.JSONField(null=True, blank=True)
    message = models.TextField(blank=True)
    username = models.CharField(max_length=255, blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             models.SET_NULL,
                             null=True,
                             blank=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)

    def __str__(self):
        return ', '.join(f'{key}: {before} → {after}'
                         for key, before, after in self.list_changes())

    def list_changes(self):
        if self.from_operator_id or self.to_operator_id:
            yield ('operator', self.from_operator, self.to_operator)
        if self.changes:
            for key in self.changes:
                before, after = self.changes[key].split('\n+')
                before = before[1:]
                yield (key, before, after)
Exemple #9
0
class Region(UIDMixin, TimeStampedModelMixin):
    """
    Model for a HOT Export Region.
    """

    def __init__(self, *args, **kwargs):
        kwargs["the_geom"] = convert_polygon(kwargs.get("the_geom")) or ""
        kwargs["the_geom_webmercator"] = convert_polygon(kwargs.get("the_geom_webmercator")) or ""
        kwargs["the_geog"] = convert_polygon(kwargs.get("the_geog")) or ""
        super(Region, self).__init__(*args, **kwargs)

    name = models.CharField(max_length=100, db_index=True)
    description = models.CharField(max_length=1000, blank=True)

    the_geom = models.MultiPolygonField(verbose_name="Geometry", srid=4326, default="")
    the_geom_webmercator = models.MultiPolygonField(
        verbose_name="Mercator extent for export region", srid=3857, default=""
    )
    the_geog = models.MultiPolygonField(verbose_name="Geographic extent for export region", geography=True, default="")
    properties = models.JSONField(default=dict)

    class Meta:  # pragma: no cover
        managed = True
        db_table = "regions"

    def __str__(self):
        return "{0}".format(self.name)

    def save(self, *args, **kwargs):
        self.the_geom = convert_polygon(self.the_geom)
        self.the_geog = GEOSGeometry(self.the_geom)
        self.the_geom_webmercator = self.the_geom.transform(ct=3857, clone=True)
        super(Region, self).save(*args, **kwargs)
Exemple #10
0
class Address(models.Model):
    """An address indexed and searchable via PostgreSQL.
    """
    object_id = models.CharField(max_length=64, unique=True,
                                 db_index=True)  # Equivalent to cadastre PIN.
    address_text = models.TextField(help_text='Address document for search')
    address_nice = models.TextField(null=True, blank=True)
    owner = models.TextField(null=True, blank=True)
    centroid = models.PointField(srid=4326)
    envelope = models.PolygonField(srid=4326, null=True, blank=True)
    data = models.JSONField(default=dict)

    def __str__(self):
        if self.address_nice:
            return Truncator(self.address_nice).words(15)
        else:
            return Truncator(self.address_text).words(15)

    def get_address_text(self):
        # Render the address_text field value from a template.
        f = """{{ object.address_nice }}
{% if object.owner %}{{ object.owner }}{% endif %}"""
        template = Template(f)
        context = Context({'object': self})
        return template.render(context).strip()
Exemple #11
0
class CapasGeoJson(models.Model):
    autor_id = models.ForeignKey(User,null=True,on_delete=models.SET_NULL,db_column='autor_id')
    id = models.AutoField(primary_key=True)
    titulo = models.CharField(max_length=250,default=None,blank=False,verbose_name='Título')
    descripcion = models.TextField(default=None,blank=True)
    fecha_hora = models.DateTimeField(null=True,blank=True)
    capa = models.JSONField(null=False,blank=False)    
Exemple #12
0
class Location(CreatedUpdatedModel):
    """All location related information."""

    _signal = models.ForeignKey('signals.Signal',
                                related_name='locations',
                                null=False,
                                on_delete=models.CASCADE)

    geometrie = models.PointField(name='geometrie')
    stadsdeel = models.CharField(null=True, max_length=1, choices=STADSDELEN)
    area_type_code = models.CharField(null=True, max_length=256)
    area_code = models.CharField(null=True, max_length=256)
    area_name = models.CharField(null=True,
                                 max_length=256)  # used for sorting BE-166

    # we do NOT use foreign key, since we update
    # buurten as external data in a seperate process
    buurt_code = models.CharField(null=True, max_length=4)
    address = models.JSONField(null=True)
    address_text = models.CharField(null=True, max_length=256, editable=False)
    created_by = models.EmailField(null=True, blank=True)

    extra_properties = models.JSONField(null=True)
    bag_validated = models.BooleanField(default=False)

    history_log = GenericRelation('history.Log', object_id_field='object_pk')

    @property
    def short_address_text(self):
        # openbare_ruimte huisnummerhuiletter-huisnummer_toevoeging
        return AddressFormatter(
            address=self.address).format('O hlT') if self.address else ''

    def save(self, *args, **kwargs):
        # Set address_text
        self.address_text = AddressFormatter(
            address=self.address).format('O hlT p W') if self.address else ''
        super().save(*args, **kwargs)

    def get_rd_coordinates(self):
        to_transform = copy.deepcopy(self.geometrie)
        to_transform.transform(
            CoordTransform(
                SpatialReference(4326),  # WGS84
                SpatialReference(28992)  # RD
            ))
        return to_transform
Exemple #13
0
class DataSource(models.Model):
    name = models.CharField(max_length=255)
    url = models.URLField(blank=True)
    datetime = models.DateTimeField(null=True, blank=True)
    settings = models.JSONField(null=True, blank=True)

    def __str__(self):
        return self.name

    def credit(self):
        url = None
        text = None
        date = None

        if 'tnds' in self.url:
            url = 'https://www.travelinedata.org.uk/'
            text = 'the Traveline National Dataset'
        elif 'transportforireland' in self.url:
            url = 'https://www.transportforireland.ie/transitData/PT_Data.html'
            text = 'Transport for Ireland'
        elif 'open-data' in self.url or 'data.discover' in self.url:
            url = self.url
            text = self.name
            date = self.datetime
        elif self.url.startswith('https://data.bus-data.dft.gov.uk'):
            url = self.url.replace('download/', '')
            text = self.name.split('_')[0]
            date = self.datetime
        elif self.url.startswith('http://travelinedatahosting.basemap.co.uk/'):
            text = self.name
            date = self.datetime
        elif self.url.startswith('https://opendata.ticketer.com/uk/'):
            text = self.name
            date = self.datetime
        elif 'stagecoach' in self.url:
            url = 'https://www.stagecoachbus.com/open-data'
            text = self.name
            date = self.datetime
        elif self.name == 'MET' or self.name == 'ULB':
            url = self.url
            text = 'Translink open data'

        if not url and self.settings and 'url' in self.settings:
            url = self.settings['url']

        if url and 'bus-data.dft.gov.uk' in url:
            text = f'{text}/Bus Open Data Service'

        if text:
            if url:
                text = format_html('<a href="{}">{}</a>', url, text)
            else:
                text = escape(text)
            if date:
                date = date.strftime('%-d %B %Y')
                text = f'{text}, {date}'
            return mark_safe(f'<p class="credit">Timetable data from {text}</p>')

        return ''
Exemple #14
0
class RegionalPolicy(UIDMixin, TimeStampedModelMixin):
    name = models.CharField(max_length=255)
    region = models.ForeignKey(Region, on_delete=models.CASCADE, related_name="policies")
    providers = models.ManyToManyField(DataProvider, related_name="regional_policies")
    policies = models.JSONField()
    policy_title_text = models.CharField(max_length=255)
    policy_header_text = models.TextField(null=True, blank=True)
    policy_footer_text = models.TextField(null=True, blank=True)
    policy_cancel_text = models.CharField(max_length=255, null=True, blank=True)
    policy_cancel_button_text = models.CharField(max_length=255)
    justification_options = models.JSONField()

    class Meta:
        verbose_name_plural = "Regional Policies"

    def __str__(self):
        return self.name
class RegionImage(ProcessedImage):
    """A sub region of an Image."""

    task_funcs = (jobs.task_populate_region_image, )

    class SampleTypes(models.TextChoices):
        PIXEL_BOX = 'pixel box', _('Pixel bounding box')
        GEO_BOX = 'geographic box', _('Geographic bounding box')
        GEOJSON = 'geojson', _('GeoJSON feature')
        ANNOTATION = 'annotation', _('Annotation entry')

    sample_type = models.CharField(max_length=20,
                                   default=SampleTypes.PIXEL_BOX,
                                   choices=SampleTypes.choices)
    sample_parameters = models.JSONField()

    def get_extent(self):
        """Convert ``sample_parameters`` to length 4 tuple of XY extents.

        Note
        ----
        A ``KeyError`` could be raised if the sample parameters are illformed.

        Return
        ------
        extents, projection: <left, right, bottom, top>, <projection>

        """
        p = self.sample_parameters

        projection = p.pop('projection', None)
        if self.sample_type in (
                RegionImage.SampleTypes.PIXEL_BOX,
                RegionImage.SampleTypes.ANNOTATION,
        ):
            projection = 'pixels'

        if self.sample_type in (
                RegionImage.SampleTypes.GEO_BOX,
                RegionImage.SampleTypes.PIXEL_BOX,
        ):
            return p['left'], p['right'], p['bottom'], p['top'], projection
        elif self.sample_type == RegionImage.SampleTypes.GEOJSON:
            # Convert GeoJSON to extents
            geom = shape(p)
            feature = GEOSGeometry(memoryview(dumps(geom)))
            l, b, r, t = feature.extent  # (xmin, ymin, xmax, ymax)
            return l, r, b, t, projection
        elif self.sample_type == RegionImage.SampleTypes.ANNOTATION:
            from .annotation import Annotation

            ann_id = p['id']
            ann = Annotation.objects.get(id=ann_id)
            l, b, r, t = ann.segmentation.outline.extent  # (xmin, ymin, xmax, ymax)
            return l, r, b, t, projection
        else:
            raise ValueError('Sample type ({}) unknown.'.format(
                self.sample_type))
Exemple #16
0
class Collection(models.Model, CollectionSpatialExtentMixin,
                 CollectionSummariesMixin, CollectionTemporalExtentMixin):
    class Meta:
        indexes = [models.Index(fields=['name'], name='collection_name_idx')]

    # using "name" instead of "id", as "id" has a default meaning in django
    name = models.CharField('id',
                            unique=True,
                            max_length=255,
                            validators=[validate_name])
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    description = models.TextField()
    extent_geometry = models.PolygonField(default=None,
                                          srid=4326,
                                          editable=False,
                                          blank=True,
                                          null=True,
                                          validators=[validate_geometry])
    extent_start_datetime = models.DateTimeField(editable=False,
                                                 null=True,
                                                 blank=True)
    extent_end_datetime = models.DateTimeField(editable=False,
                                               null=True,
                                               blank=True)

    license = models.CharField(max_length=30)  # string

    # "summaries" values will be updated on every update of an asset inside the
    # collection
    summaries = models.JSONField(default=get_default_summaries_value,
                                 encoder=DjangoJSONEncoder,
                                 editable=False)
    title = models.CharField(blank=True, null=True, max_length=255)

    # hidden ETag field
    etag = models.CharField(blank=False,
                            null=False,
                            editable=False,
                            max_length=56)

    def __str__(self):
        return self.name

    def update_etag(self):
        '''Update the ETag with a new UUID
        '''
        logger.debug('Updating collection etag',
                     extra={'collection': self.name})
        self.etag = compute_etag()

    def save(self, *args, **kwargs):  # pylint: disable=signature-differs
        # It is important to use `*args, **kwargs` in signature because django might add dynamically
        # parameters
        logger.debug('Saving collection', extra={'collection': self.name})
        self.update_etag()
        super().save(*args, **kwargs)
Exemple #17
0
class FeatureType(models.Model):

    GEOM_CHOICES = (
        ("linestring", "Ligne"),
        ("point", "Point"),
        ("polygon", "Polygone"),
    )

    title = models.CharField("Titre", max_length=128)

    title_optional = models.BooleanField("Titre optionnel", default=False)

    slug = models.SlugField("Slug", max_length=256, editable=False, null=True)

    geom_type = models.CharField("Type de géométrie",
                                 choices=GEOM_CHOICES,
                                 max_length=50,
                                 default="point")

    color = models.CharField(verbose_name='Couleur',
                             max_length=7,
                             blank=True,
                             null=True)

    icon = models.CharField(verbose_name='Icône',
                            max_length=128,
                            blank=True,
                            null=True)

    colors_style = models.JSONField("Style Champs coloré",
                                    blank=True,
                                    null=True)

    project = models.ForeignKey("geocontrib.Project", on_delete=models.CASCADE)

    class Meta:
        verbose_name = "Type de signalement"
        verbose_name_plural = "Types de signalements"

    def clean(self):
        if self.colors_style:
            if not isinstance(self.colors_style, dict):
                raise ValidationError('Format de donnée invalide')

    def save(self, *args, **kwargs):
        if not self.pk and self.title:
            self.created_on = timezone.now()
        self.updated_on = timezone.now()
        super().save(*args, **kwargs)

    def __str__(self):
        return self.title

    @property
    def is_editable(self):
        Feature = apps.get_model(app_label='geocontrib', model_name="Feature")
        return not Feature.objects.filter(feature_type=self).exists()
Exemple #18
0
class Map(models.Model):
    url_name = models.TextField(primary_key=True)
    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    display_name = models.TextField(blank=True)
    title = models.TextField(blank=True)
    description = models.TextField(blank=True)
    fence_enter_message = models.TextField(blank=True)
    fence_leave_message = models.TextField(blank=True)
    map_center = models.JSONField(null=True)
    map_zoom_level = models.IntegerField(null=True)
    basemap = models.JSONField(null=True)
    geofencing_layer_name = models.TextField(blank=True)

    def get_absolute_url(self):
        return "/map/%s/" % self.url_name
Exemple #19
0
class ProjectPhase(models.Model):
    """Describes a phase of a certain project subtype."""

    common_project_phase = models.ForeignKey(
        CommonProjectPhase,
        verbose_name=_("common project phase"),
        on_delete=models.PROTECT,
        related_name="phases",
    )
    project_subtype = models.ForeignKey(
        ProjectSubtype,
        verbose_name=_("project subtype"),
        on_delete=models.CASCADE,
        related_name="phases",
    )
    index = models.PositiveIntegerField(verbose_name=_("index"), default=0)

    metadata = models.JSONField(
        verbose_name=_("metadata"),
        default=dict,
        blank=True,
        null=True,
        encoder=DjangoJSONEncoder,
    )

    class Meta:
        verbose_name = _("project phase")
        verbose_name_plural = _("project phases")
        ordering = ("index", )

    def __str__(self):
        return f"{self.common_project_phase} ({self.project_subtype.name})"

    @property
    def name(self):
        return self.common_project_phase.name

    @property
    def color(self):
        return self.common_project_phase.color

    @property
    def color_code(self):
        return self.common_project_phase.color_code

    @property
    def list_prefix(self):
        return self.common_project_phase.list_prefix

    @property
    def project_type(self):
        return self.project_subtype.project_type

    @property
    def prefixed_name(self):
        return self.common_project_phase.prefixed_name
Exemple #20
0
class UnicefProgrammedocument(ReadOnlyModel):
    created = models.DateTimeField()
    modified = models.DateTimeField()
    external_id = models.CharField(max_length=32, blank=True, null=True)
    agreement = models.CharField(max_length=255)
    document_type = models.CharField(max_length=4)
    reference_number = models.CharField(max_length=255)
    title = models.CharField(max_length=512)
    unicef_office = models.CharField(max_length=255)
    start_date = models.DateField()
    end_date = models.DateField()
    status = models.CharField(max_length=256)
    contributing_to_cluster = models.BooleanField()
    frequency = models.CharField(max_length=3)
    budget = models.DecimalField(max_digits=64,
                                 decimal_places=2,
                                 blank=True,
                                 null=True)
    budget_currency = models.CharField(max_length=16)
    cso_contribution = models.DecimalField(max_digits=64, decimal_places=2)
    cso_contribution_currency = models.CharField(max_length=16)
    total_unicef_cash = models.DecimalField(max_digits=64, decimal_places=2)
    total_unicef_cash_currency = models.CharField(max_length=16)
    in_kind_amount = models.DecimalField(max_digits=64, decimal_places=2)
    in_kind_amount_currency = models.CharField(max_length=16)
    funds_received_to_date = models.DecimalField(max_digits=64,
                                                 decimal_places=2,
                                                 blank=True,
                                                 null=True)
    funds_received_to_date_currency = models.CharField(max_length=16,
                                                       blank=True,
                                                       null=True)
    amendments = models.JSONField()
    partner = models.ForeignKey(PartnerPartner,
                                models.PROTECT,
                                related_name='UnicefProgrammedocument_partner')
    workspace = models.ForeignKey(
        CoreWorkspace,
        models.PROTECT,
        related_name='UnicefProgrammedocument_workspace')
    external_business_area_code = models.CharField(max_length=32,
                                                   blank=True,
                                                   null=True)
    funds_received_to_date_percent = models.DecimalField(max_digits=64,
                                                         decimal_places=2,
                                                         blank=True,
                                                         null=True)

    class Meta:
        managed = False
        db_table = 'unicef_programmedocument'
        unique_together = (('external_id', 'external_business_area_code',
                            'workspace'), )
        app_label = 'source_prp'
Exemple #21
0
class IndicatorReportablelocationgoal(ReadOnlyModel):
    created = models.DateTimeField()
    modified = models.DateTimeField()
    target = models.JSONField()
    baseline = models.JSONField()
    in_need = models.JSONField(blank=True, null=True)
    location = models.ForeignKey(
        CoreLocation,
        models.PROTECT,
        related_name='IndicatorReportablelocationgoal_location')
    reportable = models.ForeignKey(
        IndicatorReportable,
        models.PROTECT,
        related_name='IndicatorReportablelocationgoal_reportable')
    is_active = models.BooleanField()

    class Meta:
        managed = False
        db_table = 'indicator_reportablelocationgoal'
        unique_together = (('reportable', 'location'), )
        app_label = 'source_prp'
class Property(models.Model):
    class PropertyTypes(models.TextChoices):
        DETACHED = "DETACHED", "Detached house"
        SEMIDETACHED = "SEMIDETACHED", "Semi-detached house"
        TERRACED = "TERRACED", "Terraced house"
        BUNGALOW = "BUNGALOW", "Bungalow"
        DETACHEDBUNGALOW = "DETACHEDBUNGALOW", "Detached bungalow"
        SEMIDETACHEDBUNGALOW = "SEMIDETACHEDBUNGALOW", "Semi-detached bungalow"
        TERRACEDBUNGALOW = "TERRACEDBUNGALOW", "Terraced bungalow"
        COTTAGE = "COTTAGE", "Cottage"
        MOBILEPARK = "MOBILEPARK", "Mobile/park home"
        FLAT = "FLAT", "Flat"
        LAND = "LAND", "Land"
        PARKHOME = "PARKHOME", "Park home"

    url = models.URLField(null=True)
    head_image = models.URLField(null=True)
    title = models.CharField(max_length=50, null=True)
    address = models.CharField(max_length=100, null=True)
    price = models.IntegerField(null=True)
    date = models.DateField(null=True)
    agent_name = models.CharField(max_length=50, null=True)
    agent_phone = models.CharField(max_length=50, null=True)
    agent_address = models.CharField(max_length=100, null=True)
    property_type = models.CharField(max_length=25,
                                     choices=PropertyTypes.choices,
                                     null=True)
    bedrooms = models.IntegerField(null=True)
    bathrooms = models.IntegerField(null=True)
    receptionrooms = models.IntegerField(null=True)
    sqft = models.CharField(max_length=15, null=True)
    description = models.TextField(null=True)
    key_features = models.JSONField(null=True)
    stations = models.JSONField(null=True)
    listing_history = models.JSONField(null=True)
    cordinates = models.PointField(null=True)

    class Meta:
        verbose_name = "Property"
        verbose_name_plural = "Properties"
Exemple #23
0
class Answer(models.Model):
    """
    Answer to individual question in questionnaire.
    """
    created_at = models.DateTimeField(editable=False, auto_now_add=True)

    session = models.ForeignKey('Session', on_delete=models.CASCADE, null=True, related_name='answers')
    question = models.ForeignKey('Question', on_delete=models.CASCADE, null=True, related_name='+')

    payload = models.JSONField(blank=True, null=True)

    def __str__(self):
        return f'Answer (id={self.id}) to question with analysis_key={self.question.analysis_key}.'
Exemple #24
0
class Answer(models.Model):
    created_at = models.DateTimeField(editable=False, auto_now_add=True)

    session = models.ForeignKey('Session',
                                on_delete=models.CASCADE,
                                null=True,
                                related_name='answers')
    question = models.ForeignKey('Question',
                                 on_delete=models.CASCADE,
                                 null=True,
                                 related_name='+')

    payload = models.JSONField(blank=True, null=True)
Exemple #25
0
class User(AbstractBaseUser):
    id = HashidAutoField(primary_key=True, )
    username = models.CharField(
        max_length=150,
        blank=False,
        null=False,
        unique=True,
    )
    name = models.CharField(
        max_length=150,
        blank=True,
        null=False,
        default='',
    )
    phone = PhoneNumberField(
        blank=True,
        null=True,
        unique=True,
    )
    data = models.JSONField(
        null=True,
        editable=False,
    )
    is_active = models.BooleanField(default=True, )
    is_admin = models.BooleanField(default=False, )
    created = models.DateTimeField(auto_now_add=True, )
    updated = models.DateTimeField(auto_now=True, )

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    objects = UserManager()

    class Meta:
        ordering = ('phone', )

    @property
    def is_staff(self):
        return self.is_admin

    def __str__(self):
        return str(self.phone)

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True
Exemple #26
0
class HeavyTrafficAggregationBase(models.Model):
    id = models.AutoField(primary_key=True)
    passage_at_date = models.DateField()
    passage_at_year = models.SmallIntegerField()
    passage_at_month = models.SmallIntegerField()
    passage_at_day = models.SmallIntegerField()
    passage_at_week = models.SmallIntegerField()
    passage_at_day_of_week = models.CharField(max_length=20)
    passage_at_hour = models.SmallIntegerField(db_index=True)

    camera_id = models.CharField(max_length=255, null=True, blank=True)
    camera_naam = models.CharField(max_length=255, null=True, blank=True)
    camera_kijkrichting = models.FloatField(null=True, blank=True)
    camera_locatie = models.PointField(srid=4326, null=True, blank=True)

    rijrichting = models.SmallIntegerField(null=True, blank=True)
    rijrichting_correct = models.BooleanField(null=True, blank=True)
    straat = models.CharField(max_length=255, null=True, blank=True)

    cordon = models.CharField(max_length=255,
                              db_index=True,
                              null=True,
                              blank=True)
    cordon_order_kaart = models.IntegerField(null=True, blank=True)
    cordon_order_naam = models.CharField(max_length=255, null=True, blank=True)

    massa_ledig_voertuig = models.CharField(max_length=255,
                                            null=True,
                                            blank=True)
    toegestane_maximum_massa_voertuig = models.CharField(max_length=255,
                                                         null=True,
                                                         blank=True)
    voertuig_soort = models.CharField(max_length=64, null=True, blank=True)
    inrichting = models.CharField(max_length=255, null=True, blank=True)
    europese_voertuigcategorie = models.CharField(max_length=2,
                                                  null=True,
                                                  blank=True)
    europese_voertuigcategorie_toevoeging = models.CharField(max_length=1,
                                                             null=True,
                                                             blank=True)
    brandstoffen = models.JSONField(null=True, blank=True)
    lengte = models.CharField(max_length=64, null=True, blank=True)

    count = models.IntegerField(null=True, blank=True)

    class Meta:
        abstract = True
Exemple #27
0
class ExportFormat(UIDMixin, TimeStampedModelMixin):
    """
    Model for a ExportFormat.
    """

    safe_kwargs = [
        "name",
        "slug",
        "description",
        "cmd",
    ]

    name = models.CharField(max_length=100)
    slug = LowerCaseCharField(max_length=20, unique=True, default="")
    description = models.CharField(max_length=255)
    options = models.JSONField(default=dict, null=True, blank=True)
    objects = models.Manager()
    supported_projections = models.ManyToManyField(
        Projection, related_name="supported_projections")

    class Meta:  # pragma: no cover
        managed = True
        db_table = "export_formats"

    def __str__(self):
        return "{0}".format(self.name)

    @classmethod
    def get_or_create(cls, **kwargs):
        blacklisted_keys = []
        created = False
        for _key in kwargs:
            if _key not in cls.safe_kwargs:
                blacklisted_keys.append(_key)
        for _key in blacklisted_keys:
            del kwargs[_key]
        try:
            format = cls.objects.get(slug=kwargs.get("slug").lower())
        except ObjectDoesNotExist:
            format = cls.objects.create(**kwargs)
            created = True
        return format, created

    def get_supported_projection_list(self) -> List[int]:
        supported_projections = self.supported_projections.all().values_list(
            "srid", flat=True)
        return list(supported_projections)
Exemple #28
0
class Message(models.Model):
    id = HashidAutoField(primary_key=True, )
    STATE = Choices(
        (0, 'new', 'New'),
        (10, 'sent', 'Sent'),
    )
    state = FSMIntegerField(
        choices=STATE,
        default=STATE.new,
    )
    sid = models.CharField(
        max_length=100,
        blank=True,
    )
    to_phone = PhoneNumberField(
        blank=True,
        null=True,
    )
    from_phone = PhoneNumberField(
        blank=True,
        null=True,
    )
    body = models.TextField(blank=True, )
    DIRECTION = Choices(
        (10, 'inbound', 'Inbound'),
        (20, 'outbound', 'Outbound'),
    )
    direction = models.IntegerField(
        choices=DIRECTION,
        null=True,
        blank=True,
    )
    raw = models.JSONField(
        blank=True,
        null=True,
    )
    thread = models.ForeignKey(
        'app.Thread',
        on_delete=models.SET_NULL,
        related_name='messages',
        null=True,
    )
    created = models.DateTimeField(auto_now_add=True, )
    updated = models.DateTimeField(auto_now=True, )

    def __str__(self):
        return f"{self.id}"
Exemple #29
0
class DatamodelPreset(TimeStampedModelMixin):
    """
    Model provides admin interface to presets.
    These were previously provided by files like hdm_presets.xml / osm_presets.xml.
    """

    name = models.CharField(max_length=10)
    json_tags = models.JSONField(default=list)

    class Meta:
        db_table = "datamodel_preset"

    def __str__(self):
        return self.name

    def to_dict(self):
        return {"name": self.name, "json_tags": self.json_tags}
class CategoryAssignment(CreatedUpdatedModel):
    """Many-to-Many through model for `Signal` <-> `Category`."""
    _signal = models.ForeignKey('signals.Signal',
                                on_delete=models.CASCADE,
                                related_name='category_assignments')
    category = models.ForeignKey('signals.Category',
                                 on_delete=models.CASCADE,
                                 related_name='category_assignments')
    created_by = models.EmailField(null=True, blank=True)
    text = models.CharField(max_length=10000, null=True, blank=True)

    extra_properties = models.JSONField(
        null=True)  # TODO: candidate for removal

    # These deadline fields are used to track whether a Signal (complaint) is
    # handled within the allotted time. By calculating these deadlines it is
    # possible to implement filtering on punctuality. Business requirements were
    # that filtering is possible on Signals that are late or late with a factor
    # of three.
    # These are allowed to be null because the deadlines cannot be determined
    # correctly for historic data (hence no attempt is made). Furthermore, we
    # store both the deadline and the deadline delayed with a factor of three
    # because of subtleties in the way the latter is determined for workdays.
    deadline = models.DateTimeField(null=True)
    deadline_factor_3 = models.DateTimeField(null=True)

    # SIG-3555 store handling message as it was at the moment the category
    # was assigned. Before we had problems with history "changing" when the
    # handling message for a category was updated (because it was queried from
    # the category table each time the history is shown).
    stored_handling_message = models.TextField(null=True)

    def __str__(self):
        """String representation."""
        return '{sub} - {signal}'.format(sub=self.category,
                                         signal=self._signal)

    def save(self, *args, **kwargs):
        # Each time a category is changed the ServiceLevelObjective associated
        # with the new category may be different, de deadlines are recalculated
        # and saved for use in punctuality filter.
        # Note: this may be moved to the API layer of SIA/Signalen.
        self.deadline, self.deadline_factor_3 = DeadlineCalculationService.from_signal_and_category(
            self._signal, self.category)
        self.stored_handling_message = self.category.handling_message  # SIG-3555
        super().save(*args, **kwargs)