Ejemplo n.º 1
0
class Property(models.Model):

    PROPERTY_TYPES = (('lb', 'Landbank'), ('sp', 'County Owned Surplus'))

    geometry = models.MultiPolygonField(srid=4326, blank=True)

    centroid_geometry = models.PointField(
        srid=4326, default='SRID=4326;POINT(39.7684 86.1581)', blank=True)

    #    objects = models.GeoManager()
    propertyType = models.CharField(choices=PROPERTY_TYPES,
                                    max_length=2,
                                    verbose_name='property type')

    parcel = models.CharField(
        max_length=7,
        unique=True,
        help_text="The 7 digit local parcel number for a property, ex 1052714",
        verbose_name='parcel number')
    streetAddress = models.CharField(
        max_length=255,
        help_text=
        "Supports partial matching, so you can enter either the full street address (eg 1425 E 11TH ST) to find one property or just the street name (eg 11th st) to find all the properties on that street.",
        verbose_name='Street Address',
        blank=True,
    )
    nsp = models.BooleanField(
        default=False,
        help_text=
        "If a property comes with requirements related to the Neighborhood Stabilization Program.",
        verbose_name='NSP')
    quiet_title_complete = models.BooleanField(
        default=False,
        help_text="If quiet title process has been completed.",
        verbose_name='Quiet Title Complete')
    # should restrict this with choices using valid strings as options to catch mis-spellings.
    structureType = models.CharField(max_length=255,
                                     null=True,
                                     blank=True,
                                     help_text="As classified by the Assessor",
                                     verbose_name='Structure Type')

    cdc = models.ForeignKey(
        CDC,
        blank=True,
        null=True,
        help_text=
        "The Community Development Corporation boundries the property falls within.",
        verbose_name='CDC',
        on_delete=models.CASCADE)
    zone = models.ForeignKey(Zoning,
                             blank=True,
                             null=True,
                             help_text="The zoning of the property",
                             on_delete=models.CASCADE)
    neighborhood = models.ForeignKey(
        Neighborhood,
        blank=True,
        null=True,
        help_text="The neighborhood the property is in",
        on_delete=models.CASCADE)
    zipcode = models.ForeignKey(Zipcode,
                                blank=True,
                                null=True,
                                help_text="The zipcode of the property",
                                on_delete=models.CASCADE)
    census_tract = models.ForeignKey(
        census_tract,
        blank=True,
        null=True,
        help_text="The Census Tract of the property",
        on_delete=models.CASCADE)
    urban_garden = models.BooleanField(
        default=False,
        help_text=
        "If the property is currently licensed as an urban garden through the Office of Sustainability"
    )
    status = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text="The property's status with Renew Indianapolis")
    sidelot_eligible = models.BooleanField(
        default=False,
        help_text=
        "If the property is currently elgibile for the side-lot program")
    price = models.DecimalField(max_digits=8,
                                decimal_places=2,
                                help_text="The price of the property",
                                null=True,
                                blank=True)
    area = models.FloatField(help_text="The parcel area in square feet",
                             null=True,
                             blank=True)
    # change to foreign key when ready
    applicant = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        help_text="Name of current applicant for status page")
    homestead_only = models.BooleanField(
        default=False, help_text="Only available for homestead applications")
    bep_demolition = models.BooleanField(
        default=False,
        help_text="Slated for demolition under the Blight Elimination Program",
        verbose_name="Slated for BEP demolition")
    project_agreement_released = models.BooleanField(
        default=False,
        help_text="Has the project agreement on a sold property been released?"
    )
    is_active = models.BooleanField(
        default=True, help_text="Is this property listing active?")
    price_obo = models.BooleanField(default=False,
                                    help_text="Price is Or Best Offer",
                                    verbose_name="Price is 'Or Best Offer'")
    renew_owned = models.BooleanField(
        default=False,
        help_text=
        "Property is owned directly by Renew Indianapolis or a wholly owned subsidiary.",
        verbose_name="Owned by Renew Indianapolis directly")
    hhf_demolition = models.BooleanField(
        default=False,
        help_text=
        "Property was demolished through Hardest Hit Funds/Blight Elimination Program, and may have restrictions on end use.",
        verbose_name=
        "Property was demolished through Hardest Hit Funds/Blight Elimination Program"
    )
    vacant_lot_eligible = models.BooleanField(
        default=False,
        help_text=
        "Property is eligible for sale through the vacant lot program.")
    future_development_program_eligible = models.BooleanField(
        default=False,
        help_text=
        "Property is eligible for sale through the Future Development Lot program."
    )

    short_legal_description = models.CharField(max_length=2048, blank=True)
    #slug = AutoSlugField(always_update=True, unique=True, populate_from=lambda instance: instance.streetAddress + instance.parcel)

    number_of_units = models.PositiveIntegerField(
        default=1,
        help_text="Number of units in the property, at time of sale",
        blank=True)

    acquisition_date = models.DateField(null=True,
                                        blank=True,
                                        help_text='Date property was acquired')
    renew_acquisition_date = models.DateField(
        null=True, blank=True, help_text='Date property was acquired by Renew')
    buyer_application = models.ForeignKey(
        'applications.Application',
        null=True,
        blank=True,
        help_text='The final buyer application.',
        on_delete=models.CASCADE)

    property_inspection_group = models.CharField(blank=True, max_length=10)
    update_from_server = models.BooleanField(
        default=True,
        help_text=
        "Attempt to update street address, etc from remote server on next save."
    )

    class Meta:
        verbose_name_plural = "properties"
        ordering = ['streetAddress', 'parcel']

    def natural_key(self):
        return '%s - %s' % (self.streetAddress, self.parcel)

    def __str__(self):
        return '%s - %s' % (self.streetAddress, self.parcel)

    ## added this function to calculate centroid of the geometry on saving, as it not otherwise available.
    def save(self, *args, **kwargs):
        if self.parcel is not None and self.parcel != '' and self.update_from_server == True:
            results = pull_property_info_from_arcgis(self.parcel)
            if results:
                self.streetAddress = results['street_address']
                self.geometry = results['geometry']
                self.centroid_geometry = self.geometry.centroid
                self.area = float(results['estsqft'])
                try:
                    aiv = float(results['assessed_improvement_value'])
                except ValueError:
                    aiv = 0
                if aiv > 0:
                    self.structureType = 'Residential Dwelling'
                else:
                    self.structureType = 'Vacant Lot'
                self.zipcode = Zipcode.objects.filter(
                    geometry__contains=self.centroid_geometry).first()
                self.zone = Zoning.objects.filter(
                    geometry__contains=self.centroid_geometry).first()
                self.cdc = CDC.objects.filter(
                    geometry__contains=self.centroid_geometry).first()
                self.neighborhood = Neighborhood.objects.filter(
                    geometry__contains=self.centroid_geometry).first()
                self.census_tract = census_tract.objects.filter(
                    geometry__contains=self.centroid_geometry).first()
                self.is_active = False
                self.propertyType = 'lb'
                self.update_from_server = False
        super(Property, self).save(*args, **kwargs)
Ejemplo n.º 2
0
class SensitiveArea(MapEntityMixin, StructureRelated, TimeStampedModelMixin,
                    NoDeleteMixin, AddPropertyMixin):
    geom = models.GeometryField(srid=settings.SRID)
    species = models.ForeignKey(Species,
                                verbose_name=_("Sensitive area"),
                                on_delete=models.PROTECT)
    published = models.BooleanField(verbose_name=_("Published"),
                                    default=False,
                                    help_text=_("Visible on Geotrek-rando"))
    publication_date = models.DateField(verbose_name=_("Publication date"),
                                        null=True,
                                        blank=True,
                                        editable=False)
    description = models.TextField(verbose_name=_("Description"), blank=True)
    contact = models.TextField(verbose_name=_("Contact"), blank=True)
    eid = models.CharField(verbose_name=_("External id"),
                           max_length=1024,
                           blank=True,
                           null=True)

    class Meta:
        verbose_name = _("Sensitive area")
        verbose_name_plural = _("Sensitive areas")
        permissions = (("import_sensitivearea", "Can import Sensitive area"), )

    def __str__(self):
        return self.species.name

    @property
    def radius(self):
        if self.species.radius is None:
            return settings.SENSITIVITY_DEFAULT_RADIUS
        return self.species.radius

    @classproperty
    def radius_verbose_name(cls):
        return _("Radius")

    @property
    def category_display(self):
        return self.species.get_category_display()

    @classproperty
    def category_verbose_name(cls):
        return _("Category")

    def save(self, *args, **kwargs):
        if self.publication_date is None and self.published:
            self.publication_date = datetime.date.today()
        if self.publication_date is not None and not self.published:
            self.publication_date = None
        super(SensitiveArea, self).save(*args, **kwargs)

    @property
    def any_published(self):
        return self.published

    @property
    def published_status(self):
        """Returns the publication status by language.
        """
        status = []
        for language in settings.MAPENTITY_CONFIG['TRANSLATED_LANGUAGES']:
            status.append({
                'lang': language[0],
                'language': language[1],
                'status': self.published
            })
        return status

    @property
    def published_langs(self):
        """Returns languages in which the object is published.
        """
        if self.published:
            return [
                language[0] for language in
                settings.MAPENTITY_CONFIG['TRANSLATED_LANGUAGES']
            ]
        else:
            return []

    @property
    def species_display(self):
        s = '<a data-pk="%s" href="%s" title="%s">%s</a>' % (
            self.pk, self.get_detail_url(), self.species.name,
            self.species.name)
        if self.published:
            s = '<span class="badge badge-success" title="%s">&#x2606;</span> ' % _(
                "Published") + s
        return s

    @property
    def extent(self):
        return self.geom.transform(settings.API_SRID,
                                   clone=True).extent if self.geom else None

    def kml(self):
        """Exports sensitivearea into KML format"""
        kml = simplekml.Kml()
        geom = self.geom
        if geom.geom_type == 'Point':
            geom = geom.buffer(
                self.species.radius or settings.SENSITIVITY_DEFAULT_RADIUS, 4)
        if self.species.radius:
            geometry = ()
            for coords in geom.coords[0]:
                coords += (self.species.radius, )
                geometry += (coords, )
            geom = GEOSGeometry(Polygon(geometry), srid=settings.SRID)
        geom = geom.transform(4326, clone=True)  # KML uses WGS84
        line = kml.newpolygon(
            name=self.species.name,
            description=plain_text(self.description),
            altitudemode=simplekml.AltitudeMode.relativetoground,
            outerboundaryis=simplify_coords(geom.coords[0]))
        line.style.linestyle.color = simplekml.Color.red  # Red
        line.style.linestyle.width = 4  # pixels
        return kml.kml()

    def is_public(self):
        return self.published

    @property
    def pretty_period(self):
        return self.species.pretty_period()

    pretty_period_verbose_name = _("Period")

    @property
    def pretty_practices(self):
        return self.species.pretty_practices()

    pretty_practices_verbose_name = _("Practices")
Ejemplo n.º 3
0
class VesselStatistics(models.Model):
    obj_id = models.IntegerField()
    date = models.DateField()
Ejemplo n.º 4
0
class Tree(models.Model, ManagementMixin, PendingMixin):
    def __init__(self, *args, **kwargs):
        super(Tree,
              self).__init__(*args,
                             **kwargs)  #save, in order to get ID for the tree

    #owner properties based on wiki/DatabaseQuestions
    plot = models.ForeignKey(Plot)
    tree_owner = models.CharField(max_length=256, null=True, blank=True)
    steward_name = models.CharField(max_length=256, null=True,
                                    blank=True)  #only modifyable by admin
    steward_user = models.ForeignKey(
        User, null=True, blank=True,
        related_name="steward")  #only modifyable by admin
    sponsor = models.CharField(max_length=256, null=True,
                               blank=True)  #only modifyable by us

    species = models.ForeignKey(Species,
                                verbose_name="Scientific name",
                                null=True,
                                blank=True)
    species_other1 = models.CharField(max_length=255, null=True, blank=True)
    species_other2 = models.CharField(max_length=255, null=True, blank=True)
    orig_species = models.CharField(max_length=256, null=True, blank=True)
    dbh = models.FloatField(null=True, blank=True)  #gets auto-set on save
    height = models.FloatField(
        null=True,
        blank=True,
        error_messages={'invalid': "Error: This value must be a number."})
    canopy_height = models.FloatField(
        null=True,
        blank=True,
        error_messages={'invalid': "Error: This value must be a number."})
    date_planted = models.DateField(null=True, blank=True)
    date_removed = models.DateField(null=True, blank=True)
    present = models.BooleanField(default=True)

    last_updated = models.DateTimeField(auto_now=True)
    last_updated_by = models.ForeignKey(
        User, related_name='updated_by')  # TODO set to current user

    s_order = models.IntegerField(null=True, blank=True)
    photo_count = models.IntegerField(null=True, blank=True)

    objects = models.GeoManager()
    history = audit.AuditTrail()
    projects = models.CharField(max_length=20, null=True, blank=True)

    import_event = models.ForeignKey(ImportEvent)

    condition = models.CharField(max_length=256,
                                 null=True,
                                 blank=True,
                                 choices=settings.CHOICES["conditions"])
    canopy_condition = models.CharField(
        max_length=256,
        null=True,
        blank=True,
        choices=settings.CHOICES["canopy_conditions"])

    readonly = models.BooleanField(default=False)
    url = models.URLField(max_length=255, null=True, blank=True)
    pests = models.CharField(max_length=256,
                             null=True,
                             blank=True,
                             choices=settings.CHOICES["pests"])

    def has_common_attributes(self):
        if self.get_flag_count > 0:
            return True
        if self.species:
            spp = self.species
            if spp.flower_conspicuous or spp.fall_conspicuous or spp.palatable_human or spp.native_status:
                return True
        return False

    def get_absolute_url(self):
        return "/trees/%i/" % self.id

    def get_display(self, choices, val):
        for key, value in settings.CHOICES[choices]:
            if key == val:
                return value
        return None

    def get_condition_display(self):
        return self.get_display("conditions", self.condition)

    def get_canopy_condition_display(self):
        return self.get_display("canopy_condition", self.canopy_condition)

    def get_pests_display(self):
        return self.get_display("pests", self.pests)

    def get_scientific_name(self):
        if self.species:
            sn = self.species.scientific_name
            if not sn:
                sn = self.species.genus
            if self.species.cultivar_name:
                sn += " '%s'" % self.species.cultivar_name
            return sn
        else:
            return 'unavailable'

    def get_common_name(self):
        if self.species:
            return self.species.common_name
        return 'unavailable'

    def get_eco_impact(self):
        tr = TreeResource.objects.filter(tree=self)
        if tr:
            return "%0.2f" % tr[0].total_benefit()

    def get_action_count(self):
        return len(self.treeaction_set.all())

    def get_alert_count(self):
        return len(self.treealert_set.all())

    def get_flag_count(self):
        return len(self.treeflags_set.all())

    def get_stewardship_count(self):
        return len(self.treestewardship_set.all())

    def get_active_pends(self):
        pends = self.treepending_set.filter(status='pending')
        return pends

    def is_complete(self):
        if self.species >= 0 and self.dbh:
            return True
        else:
            return False

    def set_species(self, species_id, commit=True):
        """
        sets the species, and updates the species tree count
        """
        self.old_species = self.species
        new_species = Species.objects.get(id=species_id)
        self.species = new_species
        if commit:
            self.save()

    def save(self, *args, **kwargs):
        #save new neighborhood/zip connections if needed
        self.photo_count = self.treephoto_set.count()

        self.projects = ""
        for fl in self.treeflags_set.all():
            self.projects = self.projects + " " + fl.key

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

        self.quick_save(*args, **kwargs)

    def quick_save(self, *args, **kwargs):
        super(Tree, self).save(*args, **kwargs)
        set_environmental_summaries(self)
        #set new species counts
        if hasattr(self, 'old_species') and self.old_species:
            self.old_species.save()
        if hasattr(self, 'species') and self.species:
            self.species.save()

        self.plot.last_updated = self.last_updated
        self.plot.save()

    def update_aggregate(self, ag_model, location):
        agg = ag_model.objects.filter(location=location)
        if agg:
            agg = agg[0]
        else:
            agg = ag_model(location=location)
        #print agg.__dict__
        #summaries = []
        trees = Tree.objects.filter(plot__geometry__within=location.geometry)
        plots = Plot.objects.filter(geometry__within=location.geometry)
        #print trees
        agg.total_trees = trees.count()
        agg.total_plots = plots.count()

        trees = trees.exclude(Q(dbh=None) | Q(dbh=0.0)).exclude(species=None)
        #print agg.total_trees
        #TODO figure out how to summarize diff stratum stuff
        field_names = [
            x.name for x in ResourceSummaryModel._meta.fields
            if not x.name == 'id'
        ]

        if agg.total_trees == 0:
            for f in field_names:
                setattr(agg, f, 0.0)
        else:
            #TODO speed this up
            for f in field_names:
                fn = 'treeresource__' + f
                s = trees.aggregate(Sum(fn))[fn + '__sum'] or 0.0
                setattr(agg, f, s)
        agg.save()

    def percent_complete(self):
        has = 0
        attr = settings.COMPLETE_ARRAY
        for item in attr:
            if hasattr(self, item):
                if getattr(self, item):
                    has += 1
            elif hasattr(self.plot, item):
                if getattr(self.plot, item):
                    has += 1
        return has / float(len(attr)) * 100

    def validate_all(self):
        #print watch_tests
        for test, method in watch_tests.iteritems():
            #print test
            result = getattr(self, method)()
            #print result

            # check for results and save - passed tests return None
            if not result:
                TreeWatch.objects.filter(tree=self,
                                         key=watch_choices[test]).delete()
                continue
            # if identical watch already exists skip it
            if TreeWatch.objects.filter(tree=self,
                                        key=watch_choices[test],
                                        value=result):
                continue

            TreeWatch.objects.filter(tree=self,
                                     key=watch_choices[test]).delete()
            self.treewatch_set.create(
                key=watch_choices[test],
                value=result,
            )

    def validate_proximity(self, return_trees=False, max_count=1):
        if not self.plot.geometry:
            return None
        return self.plot.validate_proximity()

    # Disallowed combinations:
    #   Dead + 0% loss, Dead + 25% loss, Dead + 50% loss, Dead + 75% loss
    #   Excellent + 100% loss, Excellent + 75% loss
    def validate_canopy_condition(self):
        if not self.canopy_condition or not self.condition:
            return None

        cond = self.condition
        c_cond = self.canopy_condition
        if cond == 'Dead':
            if not c_cond == 'Little or None (up to 100% missing)' and not c_cond == 'None':
                return cond + ", " + c_cond

        elif cond == 'Excellent':
            if c_cond == 'Little or None (up to 100% missing)' or c_cond == 'Large Gaps (up to 75% missing)':
                return cond + ", " + c_cond

        return None

    # discussions: http://www.nativetreesociety.org/measure/tdi/diameter_height_ratio.htm
    def validate_height_dbh(self):
        if not self.height or not self.dbh:
            return None
        getcontext().prec = 3
        cbh = self.dbh * math.pi
        cbh_feet = cbh * .75 / 9
        float_ratio = self.height / cbh_feet
        hd_ratio = Decimal(float_ratio.__str__())
        #print hd_ratio
        if hd_ratio < 100:
            return None
        return round(hd_ratio, 2).__str__()

    def validate_max_dbh(self):
        if not self.dbh or not self.species or not self.species.v_max_dbh:
            return None
        if self.dbh > self.species.v_max_dbh:
            return "%s (species max: %s )" % (str(
                self.dbh), str(self.species.v_max_dbh))
        return None

    def validate_max_height(self):
        if not self.height or not self.species or not self.species.v_max_height:
            return None
        if self.height > self.species.v_max_height:
            return "%s (species max: %s)" % (str(
                self.height), str(self.species.v_max_height))
        return None

    def remove(self):
        """
        Mark the tree and its associated objects as not present.
        """
        self.present = False
        self.save()
        for audit_trail_record in self.history.all():
            audit_trail_record.present = False
            audit_trail_record.save()

    def __unicode__(self):
        if self.species:
            return u'%s, %s, %s' % (self.species.common_name
                                    or '', self.species.scientific_name,
                                    self.plot.geocoded_address)
        else:
            return self.plot.geocoded_address
Ejemplo n.º 5
0
class SchoolEnrollment(models.Model):
    start_date = models.DateField(auto_now_add=True)
    school = models.ForeignKey(School, on_delete=models.CASCADE)
    student = models.ForeignKey(Person, on_delete=models.CASCADE)
Ejemplo n.º 6
0
class MetricsJobType(models.Model):
    '''Tracks all the job execution metrics grouped by job type.

    :keyword job_type: The type of job associated with these metrics.
    :type job_type: :class:`django.db.models.ForeignKey`
    :keyword occurred: The date when the job executions included in this model were ended.
    :type occurred: :class:`django.db.models.DateField`

    :keyword completed_count: The total number of completed job executions.
    :type completed_count: :class:`metrics.models.PlotIntegerField`
    :keyword failed_count: The total number of failed job executions.
    :type failed_count: :class:`metrics.models.PlotIntegerField`
    :keyword canceled_count: The total number of canceled job executions.
    :type canceled_count: :class:`metrics.models.PlotIntegerField`
    :keyword total_count: The total number of ended job executions (completed, failed, canceled).
    :type total_count: :class:`metrics.models.PlotIntegerField`

    :keyword queue_time_sum: The total time job executions were queued in seconds.
    :type queue_time_sum: :class:`metrics.models.PlotIntegerField`
    :keyword queue_time_min: The minimum time a job execution was queued in seconds.
    :type queue_time_min: :class:`metrics.models.PlotIntegerField`
    :keyword queue_time_max: The maximum time a job execution was queued in seconds.
    :type queue_time_max: :class:`metrics.models.PlotIntegerField`
    :keyword queue_time_avg: The average time job executions were queued in seconds.
    :type queue_time_avg: :class:`metrics.models.PlotIntegerField`

    :keyword pre_time_sum: The total time job executions were executing pre-task steps in seconds.
    :type pre_time_sum: :class:`metrics.models.PlotIntegerField`
    :keyword pre_time_min: The minimum time a job execution was executing pre-task steps in seconds.
    :type pre_time_min: :class:`metrics.models.PlotIntegerField`
    :keyword pre_time_max: The maximum time a job execution was executing pre-task steps in seconds.
    :type pre_time_max: :class:`metrics.models.PlotIntegerField`
    :keyword pre_time_avg: The average time job executions were executing pre-task steps in seconds.
    :type pre_time_avg: :class:`metrics.models.PlotIntegerField`

    :keyword job_time_sum: The total time job executions were executing the actual job task in seconds.
    :type job_time_sum: :class:`metrics.models.PlotIntegerField`
    :keyword job_time_min: The minimum time a job execution was executing the actual job task in seconds.
    :type job_time_min: :class:`metrics.models.PlotIntegerField`
    :keyword job_time_max: The maximum time a job execution was executing the actual job task in seconds.
    :type job_time_max: :class:`metrics.models.PlotIntegerField`
    :keyword job_time_avg: The average time job executions were executing the actual job task in seconds.
    :type job_time_avg: :class:`metrics.models.PlotIntegerField`

    :keyword post_time_sum: The total time job executions were executing post-task steps in seconds.
    :type post_time_sum: :class:`metrics.models.PlotIntegerField`
    :keyword post_time_min: The minimum time a job execution was executing post-task steps in seconds.
    :type post_time_min: :class:`metrics.models.PlotIntegerField`
    :keyword post_time_max: The maximum time a job execution was executing post-task steps in seconds.
    :type post_time_max: :class:`metrics.models.PlotIntegerField`
    :keyword post_time_avg: The average time job executions were executing post-task steps in seconds.
    :type post_time_avg: :class:`metrics.models.PlotIntegerField`

    :keyword run_time_sum: The total time job executions were running in seconds.
    :type run_time_sum: :class:`metrics.models.PlotIntegerField`
    :keyword run_time_min: The minimum time a job execution was running in seconds.
    :type run_time_min: :class:`metrics.models.PlotIntegerField`
    :keyword run_time_max: The maximum time a job execution was running in seconds.
    :type run_time_max: :class:`metrics.models.PlotIntegerField`
    :keyword run_time_avg: The average time job executions were running in seconds.
    :type run_time_avg: :class:`metrics.models.PlotIntegerField`

    :keyword stage_time_sum: The total time job executions spent in system staging between tasks in seconds.
    :type stage_time_sum: :class:`metrics.models.PlotIntegerField`
    :keyword stage_time_min: The minimum time a job execution spent in system staging between tasks in seconds.
    :type stage_time_min: :class:`metrics.models.PlotIntegerField`
    :keyword stage_time_max: The maximum time a job execution spent in system staging between tasks in seconds.
    :type stage_time_max: :class:`metrics.models.PlotIntegerField`
    :keyword stage_time_avg: The average time job executions spent in system staging between tasks in seconds.
    :type stage_time_avg: :class:`metrics.models.PlotIntegerField`

    :keyword created: When the model was first created.
    :type created: :class:`django.db.models.DateTimeField`
    '''
    GROUPS = [
        MetricsTypeGroup('overview', 'Overview',
                         'Overall counts based on job status.'),
        MetricsTypeGroup('queue_time', 'Queue Time',
                         'When jobs were in the queue.'),
        MetricsTypeGroup('pre_time', 'Pre-task Time',
                         'When jobs were being prepared.'),
        MetricsTypeGroup('job_time', 'Job Task Time',
                         'When jobs were executing their actual goal.'),
        MetricsTypeGroup('post_time', 'Post-task Time',
                         'When jobs were being cleaned up.'),
        MetricsTypeGroup('run_time', 'Run Time',
                         'When related tasks were run (pre, job, post).'),
        MetricsTypeGroup('stage_time', 'Stage Time',
                         'Times related to the overhead of the system.'),
    ]

    job_type = models.ForeignKey('job.JobType', on_delete=models.PROTECT)
    occurred = models.DateField(db_index=True)

    completed_count = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='overview',
        help_text='Number of successfully completed jobs.',
        null=True,
        units='count',
        verbose_name='Completed Count')
    failed_count = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='overview',
        help_text='Number of incomplete failed jobs.',
        null=True,
        units='count',
        verbose_name='Failed Count')
    canceled_count = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='overview',
        help_text='Number of incomplete canceled jobs.',
        null=True,
        units='count',
        verbose_name='Canceled Count')
    total_count = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='overview',
        help_text='Number of completed, failed, and canceled jobs.',
        null=True,
        units='count',
        verbose_name='Total Count')

    queue_time_sum = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='queue_time',
        help_text='Total time the job waited in the queue.',
        null=True,
        units='seconds',
        verbose_name='Queue Time (Sum)')
    queue_time_min = PlotIntegerField(
        aggregate='min',
        blank=True,
        group='queue_time',
        help_text='Minimum time the job waited in the queue.',
        null=True,
        units='seconds',
        verbose_name='Queue Time (Min)')
    queue_time_max = PlotIntegerField(
        aggregate='max',
        blank=True,
        group='queue_time',
        help_text='Maximum time the job waited in the queue.',
        null=True,
        units='seconds',
        verbose_name='Queue Time (Max)')
    queue_time_avg = PlotIntegerField(
        aggregate='avg',
        blank=True,
        group='queue_time',
        help_text='Average time the job waited in the queue.',
        null=True,
        units='seconds',
        verbose_name='Queue Time (Avg)')

    pre_time_sum = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='pre_time',
        help_text='Total time spent preparing the job task.',
        null=True,
        units='seconds',
        verbose_name='Pre-task Time (Sum)')
    pre_time_min = PlotIntegerField(
        aggregate='min',
        blank=True,
        group='pre_time',
        help_text='Minimum time spent preparing the job task.',
        null=True,
        units='seconds',
        verbose_name='Pre-task Time (Min)')
    pre_time_max = PlotIntegerField(
        aggregate='max',
        blank=True,
        group='pre_time',
        help_text='Maximum time spent preparing the job task.',
        null=True,
        units='seconds',
        verbose_name='Pre-task Time (Max)')
    pre_time_avg = PlotIntegerField(
        aggregate='avg',
        blank=True,
        group='pre_time',
        help_text='Average time spent preparing the job task.',
        null=True,
        units='seconds',
        verbose_name='Pre-task Time (Avg)')

    job_time_sum = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='job_time',
        help_text='Total time spent running the job task.',
        null=True,
        units='seconds',
        verbose_name='Job Task Time (Sum)')
    job_time_min = PlotIntegerField(
        aggregate='min',
        blank=True,
        group='job_time',
        help_text='Minimum time spent running the job task.',
        null=True,
        units='seconds',
        verbose_name='Job Task Time (Min)')
    job_time_max = PlotIntegerField(
        aggregate='max',
        blank=True,
        group='job_time',
        help_text='Maximum time spent running the job task.',
        null=True,
        units='seconds',
        verbose_name='Job Task Time (Max)')
    job_time_avg = PlotIntegerField(
        aggregate='avg',
        blank=True,
        group='job_time',
        help_text='Average time spent running the job task.',
        null=True,
        units='seconds',
        verbose_name='Job Task Time (Avg)')

    post_time_sum = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='post_time',
        help_text='Total time spent finalizing the job task.',
        null=True,
        units='seconds',
        verbose_name='Post-task Time (Sum)')
    post_time_min = PlotIntegerField(
        aggregate='min',
        blank=True,
        group='post_time',
        help_text='Minimum time spent finalizing the job task.',
        null=True,
        units='seconds',
        verbose_name='Post-task Time (Min)')
    post_time_max = PlotIntegerField(
        aggregate='max',
        blank=True,
        group='post_time',
        help_text='Maximum time spent finalizing the job task.',
        null=True,
        units='seconds',
        verbose_name='Post-task Time (Max)')
    post_time_avg = PlotIntegerField(
        aggregate='avg',
        blank=True,
        group='post_time',
        help_text='Average time spent finalizing the job task.',
        null=True,
        units='seconds',
        verbose_name='Post-task Time (Avg)')

    run_time_sum = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='run_time',
        help_text='Total time spent running the pre, job, and post tasks.',
        null=True,
        units='seconds',
        verbose_name='Run Time (Sum)')
    run_time_min = PlotIntegerField(
        aggregate='min',
        blank=True,
        group='run_time',
        help_text='Minimum time spent running the pre, job, and post tasks.',
        null=True,
        units='seconds',
        verbose_name='Run Time (Min)')
    run_time_max = PlotIntegerField(
        aggregate='max',
        blank=True,
        group='run_time',
        help_text='Maximum time spent running the pre, job, and post tasks.',
        null=True,
        units='seconds',
        verbose_name='Run Time (Max)')
    run_time_avg = PlotIntegerField(
        aggregate='avg',
        blank=True,
        group='run_time',
        help_text='Average time spent running the pre, job, and post tasks.',
        null=True,
        units='seconds',
        verbose_name='Run Time (Avg)')

    stage_time_sum = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='stage_time',
        help_text='Total overhead time spent managing tasks.',
        null=True,
        units='seconds',
        verbose_name='Stage Time (Sum)')
    stage_time_min = PlotIntegerField(
        aggregate='min',
        blank=True,
        group='stage_time',
        help_text='Minimum overhead time spent managing tasks.',
        null=True,
        units='seconds',
        verbose_name='Stage Time (Min)')
    stage_time_max = PlotIntegerField(
        aggregate='min',
        blank=True,
        group='stage_time',
        help_text='Maximum overhead time spent managing tasks.',
        null=True,
        units='seconds',
        verbose_name='Stage Time (Max)')
    stage_time_avg = PlotIntegerField(
        aggregate='avg',
        blank=True,
        group='stage_time',
        help_text='Average overhead time spent managing tasks.',
        null=True,
        units='seconds',
        verbose_name='Stage Time (Avg)')

    created = models.DateTimeField(auto_now_add=True)

    objects = MetricsJobTypeManager()

    class Meta(object):
        '''meta information for the db'''
        db_table = 'metrics_job_type'
Ejemplo n.º 7
0
class GeonamesUpdate(models.Model):
    """
    To log the geonames updates
    """
    update_date = models.DateField(auto_now_add=True)
Ejemplo n.º 8
0
class CampsiteRate(models.Model):
    RATE_TYPE_CHOICES = (
        (0, 'Standard'),
        (1, 'Discounted'),
    )

    UPDATE_LEVEL_CHOICES = (
        (0, 'Campground level'),
        (1, 'Campsite Class level'),
        (2, 'Campsite level'),
    )
    PRICE_MODEL_CHOICES = (
        (0, 'Price per Person'),
        (1, 'Fixed Price'),
    )
    campsite = models.ForeignKey('Campsite',
                                 on_delete=models.PROTECT,
                                 related_name='rates')
    rate = models.ForeignKey('Rate', on_delete=models.PROTECT)
    allow_public_holidays = models.BooleanField(default=True)
    date_start = models.DateField(default=date.today)
    date_end = models.DateField(null=True, blank=True)
    rate_type = models.SmallIntegerField(choices=RATE_TYPE_CHOICES, default=0)
    price_model = models.SmallIntegerField(choices=PRICE_MODEL_CHOICES,
                                           default=0)
    reason = models.ForeignKey('PriceReason')
    details = models.TextField(null=True, blank=True)
    update_level = models.SmallIntegerField(choices=UPDATE_LEVEL_CHOICES,
                                            default=0)

    def get_rate(self,
                 num_adult=0,
                 num_concession=0,
                 num_child=0,
                 num_infant=0):
        return self.rate.adult*num_adult + self.rate.concession*num_concession + \
                self.rate.child*num_child + self.rate.infant*num_infant

    def __str__(self):
        return '{} - ({})'.format(self.campsite, self.rate)

    class Meta:
        unique_together = (('campsite', 'rate', 'date_start', 'date_end'), )

    # Properties
    # =================================
    @property
    def deletable(self):
        today = datetime.now().date()
        if self.date_start >= today:
            return True
        return False

    @property
    def editable(self):
        today = datetime.now().date()
        if (self.date_start > today and not self.date_end) or (
                self.date_start > today <= self.date_end):
            return True
        return False

    # Methods
    # =================================
    def update(self, data):
        for attr, value in data.items():
            setattr(self, attr, value)
        self.save()
Ejemplo n.º 9
0
class Service(models.Model):
    """A bus service"""
    service_code = models.CharField(max_length=24, primary_key=True)
    line_name = models.CharField(max_length=64, blank=True)
    line_brand = models.CharField(max_length=64, blank=True)
    description = models.CharField(max_length=255, blank=True, db_index=True)
    outbound_description = models.CharField(max_length=255, blank=True)
    inbound_description = models.CharField(max_length=255, blank=True)
    slug = AutoSlugField(populate_from=str, editable=True, unique=True)
    mode = models.CharField(max_length=11)
    operator = models.ManyToManyField(Operator, blank=True)
    net = models.CharField(max_length=3, blank=True)
    line_ver = models.PositiveIntegerField(null=True, blank=True)
    region = models.ForeignKey(Region, models.CASCADE, null=True)
    stops = models.ManyToManyField(StopPoint, editable=False,
                                   through=StopUsage)
    date = models.DateField()
    current = models.BooleanField(default=True, db_index=True)
    show_timetable = models.BooleanField(default=False)
    timetable_wrong = models.BooleanField(default=False)
    geometry = models.MultiLineStringField(null=True, editable=False)

    wheelchair = models.NullBooleanField()
    low_floor = models.NullBooleanField()
    assistance_service = models.NullBooleanField()
    mobility_scooter = models.NullBooleanField()
    source = models.ForeignKey(DataSource, models.SET_NULL, null=True, blank=True)
    tracking = models.NullBooleanField()
    payment_methods = models.ManyToManyField('PaymentMethod', blank=True)

    class Meta():
        ordering = ('service_code',)

    def __str__(self):
        if self.line_name or self.line_brand or self.description:
            parts = (self.line_name, self.line_brand, self.description)
            return ' - '.join(part for part in parts if part)
        return self.service_code

    def has_long_line_name(self):
        "Is this service's line_name more than 4 characters long?"
        return len(self.line_name) > 4

    def get_a_mode(self):
        if self.mode and self.mode[0].lower() in 'aeiou':
            return 'An %s' % self.mode  # 'An underground service'
        return 'A %s' % self.mode  # 'A bus service' or 'A service'

    def get_absolute_url(self):
        return reverse('service_detail', args=(self.slug,))

    def get_order(self):
        groups = SERVICE_ORDER_REGEX.match(self.line_name).groups()
        return (groups[0], int(groups[1]) if groups[1] else 0, groups[2])

    @staticmethod
    def get_operator_number(code):
        if code in {'MEGA', 'MBGD'}:
            return '11'
        if code in {'NATX', 'NXSH', 'NXAP'}:
            return '12'
        return {
            'BHAT': '41',
            'ESYB': '53',
            'WAIR': '20',
            'TVSN': '18'
        }.get(code)

    def get_tfl_url(self):
        return 'https://tfl.gov.uk/bus/timetable/%s/' % self.line_name

    def get_trapeze_link(self, date):
        if self.region_id == 'Y':
            domain = 'yorkshiretravel.net'
            name = 'Yorkshire Travel'
        else:
            domain = 'travelinescotland.com'
            name = 'Traveline Scotland'
        if date:
            date = int(time.mktime(date.timetuple()) * 1000)
        else:
            date = ''
        query = (
            ('timetableId', self.service_code),
            ('direction', 'OUTBOUND'),
            ('queryDate', date),
            ('queryTime', date)
        )
        return 'http://www.{}/lts/#/timetables?{}'.format(domain, urlencode(query)), name

    def is_megabus(self):
        return (self.line_name in {'FALCON', 'Oxford Tube'}
                or self.pk in {'bed_1-X5-Z-y08', 'YWAX062', 'HIAG010', 'FSAM009', 'FSAG009', 'EDAO900', 'EDAAIR0',
                               'YSBX010', 'ABAX010', 'ABAO010'}
                or any(o.pk in {'MEGA', 'MBGD', 'SCMG'} for o in self.operator.all()))

    def get_megabus_url(self):
        # Using a tuple of tuples, instead of a dict, because the order of dicts is nondeterministic
        query = (
            ('mid', 2678),
            ('id', 242611),
            ('clickref', 'links'),
            ('clickref2', self.service_code),
            ('p', 'https://uk.megabus.com'),
        )
        return 'https://www.awin1.com/awclick.php?' + urlencode(query)

    def get_traveline_link(self, date=None):
        if self.region_id in ('Y', 'S'):
            return self.get_trapeze_link(date)

        if self.region_id == 'W':
            for service_code in self.servicecode_set.filter(scheme='Traveline Cymru'):
                query = (
                    ('routeNum', self.line_name),
                    ('direction_id', 0),
                    ('timetable_key', service_code.code)
                )
                url = 'https://www.traveline.cymru/timetables/?' + urlencode(query)
                return url, 'Traveline Cymru'

        query = None

        if self.net:
            if self.servicecode_set.filter(scheme='TfL').exists():
                return self.get_tfl_url(), 'Transport for London'
            elif self.net == 'tfl':
                return None, None

            parts = self.service_code.split('-')
            line = parts[0].split('_')[-1].zfill(2) + parts[1].zfill(3)
            line_ver = self.line_ver or parts[4]

            query = [('line', line),
                     ('lineVer', line_ver),
                     ('net', self.net),
                     ('project', parts[3])]
            if parts[2] != '_':
                query.append(('sup', parts[2]))

        elif self.region_id == 'GB':
            parts = self.service_code.split('_')
            operator_number = self.get_operator_number(parts[1])
            if operator_number is not None:
                query = [('line', operator_number + parts[0][:3].zfill(3)),
                         ('sup', parts[0][3:]),
                         ('net', 'nrc'),
                         ('project', 'y08')]

        if query is not None:
            query += [('command', 'direct'), ('outputFormat', 0)]
            base_url = 'http://www.travelinesoutheast.org.uk/se'
            return '%s/XSLT_TTB_REQUEST?%s' % (base_url, urlencode(query)), 'Traveline'

        return None, None

    def get_filenames(self, archive):
        if self.region_id == 'NE':
            return ['{}.xml'.format(self.pk)]
        if self.region_id in ('S', 'Y'):
            return ['SVR{}.xml'.format(self.pk)]

        namelist = archive.namelist()

        if self.region_id == 'NW':
            codes = [code.code for code in self.servicecode_set.filter(scheme='NW TNDS')] + [self.pk]
            return [name for name in namelist
                    if any(name == code + '.xml' or name.startswith(code + '_') for code in codes)]

        if self.net:
            return [name for name in namelist if name.startswith('{}-'.format(self.pk))]

        if self.region_id == 'GB':
            parts = self.pk.split('_')
            suffix = '_{}_{}.xml'.format(parts[1], parts[0])
        else:
            suffix = '_{}.xml'.format(self.pk)  # Wales
        return [name for name in namelist if name.endswith(suffix)]

    def get_files_from_zipfile(self):
        """Given a Service,
        return an iterable of open files from the relevant zipfile.
        """
        service_code = self.service_code
        if self.region_id == 'GB':
            archive_name = 'NCSD'
            parts = service_code.split('_')
            service_code = '_%s_%s' % (parts[-1], parts[-2])
        else:
            archive_name = self.region_id

        archive_path = os.path.join(settings.TNDS_DIR, archive_name + '.zip')

        try:
            with zipfile.ZipFile(archive_path) as archive:
                filenames = self.get_filenames(archive)
                return [archive.open(filename) for filename in filenames]
        except (zipfile.BadZipfile, IOError, KeyError):
            return []

    def get_timetables(self, day=None):
        """Given a Service, return a list of Timetables."""
        if day is None:
            day = date.today()

        if self.region_id == 'NI':
            path = os.path.join(settings.DATA_DIR, 'NI', self.pk + '.json')
            if os.path.exists(path):
                return northern_ireland.get_timetable(path, day)
            return []

        if self.region_id in {'UL', 'LE', 'MU', 'CO', 'HI'}:
            service_codes = self.servicecode_set.filter(scheme__endswith=' GTFS')
            timetables = [gtfs.get_timetable(service_code.get_routes(), day) for service_code in service_codes]
        else:
            cache_key = '{}:{}'.format(self.service_code, self.date)
            timetables = cache.get(cache_key)

            if timetables is None:
                timetables = []
                for xml_file in self.get_files_from_zipfile():
                    with xml_file:
                        timetable = txc.Timetable(xml_file, day, self)
                    del timetable.service
                    del timetable.journeypatterns
                    del timetable.stops
                    del timetable.operators
                    del timetable.element
                    timetables.append(timetable)
                cache.set(cache_key, timetables)

            if len(timetables) > 1 and timetables[1].operating_period.start > day:
                self.timetable_change = timetables[1].operating_period.start
            timetables = [timetable for timetable in timetables if timetable.operating_period.contains(day)]
            for timetable in timetables:
                timetable.service = self
                timetable.set_date(day)
                timetable.set_description(self.description)
                timetable.groupings = [g for g in timetable.groupings if g.rows and g.rows[0].times]
        return [t for t in timetables if t and t.groupings] or timetables[:1]
Ejemplo n.º 10
0
class BetrokkenPersonen(models.Model):
    class Meta:
        db_table = 'hr_betrokken_personen'
        managed = False

    mac_naam = models.CharField(max_length=600,
                                help_text='Maatschappelijke activiteit naam')

    kvk_nummer = models.CharField(max_length=8,
                                  blank=True,
                                  null=True,
                                  help_text="Kvk nummer")

    vestiging = models.ForeignKey(DataSelectie,
                                  models.DO_NOTHING,
                                  to_field="id",
                                  db_column="vestiging_id",
                                  blank=True,
                                  null=True,
                                  help_text="Vestiging id")

    vestigingsnummer = models.CharField(
        max_length=12,
        unique=True,
        help_text="Betreft het identificerende gegeven voor de Vestiging")

    persoons_id = models.IntegerField(null=True)

    rol = models.CharField(max_length=14,
                           blank=True,
                           null=True,
                           help_text="Rol")

    naam = models.CharField(
        max_length=600,
        blank=True,
        null=True,
        help_text="Persoonsnaam (handelsregister terminologie)")

    rechtsvorm = models.CharField(max_length=50,
                                  blank=True,
                                  null=True,
                                  help_text="Rechtsvorm")

    functietitel = models.CharField(max_length=20,
                                    blank=True,
                                    null=True,
                                    help_text="Titel van de functionaris")

    soortbevoegdheid = models.CharField(
        max_length=20,
        blank=True,
        null=True,
        help_text="Bevoegdheid van de functionaris")

    bevoegde_naam = models.CharField(
        max_length=240,
        blank=True,
        null=True,
        help_text="Bevoegdheid van de functionaris")

    datum_aanvang = models.DateField(
        max_length=8,
        blank=True,
        null=True,
        help_text="De datum van aanvang van de MaatschappelijkeActiviteit",
    )

    datum_einde = models.DateField(
        max_length=8,
        blank=True,
        null=True,
        help_text="""
            De datum van beëindiging van de MaatschappelijkeActiviteit""",
    )
Ejemplo n.º 11
0
class BookingRange(models.Model):
    BOOKING_RANGE_CHOICES = (
        (0, 'Open'),
        (1, 'Closed'),
    )
    created = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(
        auto_now_add=True,
        help_text='Used to check if the start and end dated were changed')

    status = models.SmallIntegerField(choices=BOOKING_RANGE_CHOICES, default=0)
    closure_reason = models.ForeignKey('ClosureReason', null=True, blank=True)
    open_reason = models.ForeignKey('OpenReason', null=True, blank=True)
    details = models.TextField(blank=True, null=True)
    range_start = models.DateField(blank=True, null=True)
    range_end = models.DateField(blank=True, null=True)

    class Meta:
        abstract = True

    # Properties
    # ====================================
    @property
    def editable(self):
        today = datetime.now().date()
        if self.status != 0 and (
            (self.range_start <= today and not self.range_end) or
            (self.range_start > today and not self.range_end) or
            (self.range_start > datetime.now().date() <= self.range_end)):
            return True
        elif self.status == 0 and (
            (self.range_start <= today and not self.range_end)
                or self.range_start > today):
            return True
        return False

    @property
    def reason(self):
        if self.status == 0:
            return self.open_reason.text
        return self.closure_reason.text

    # Methods
    # =====================================
    def _is_same(self, other):
        if not isinstance(other, BookingRange) and self.id != other.id:
            return False
        if self.range_start == other.range_start and self.range_end == other.range_end:
            return True
        return False

    def save(self, *args, **kwargs):
        skip_validation = bool(kwargs.pop('skip_validation', False))
        if not skip_validation:
            self.full_clean()
        if self.status == 1 and not self.closure_reason:
            self.closure_reason = ClosureReason.objects.get(pk=1)
        elif self.status == 0 and not self.open_reason:
            self.open_reason = OpenReason.objects.get(pk=1)

        super(BookingRange, self).save(*args, **kwargs)
Ejemplo n.º 12
0
class Persoon(models.Model):
    """
    Persoon (PRS)

    Een {Persoon} is een ieder die rechten en plichten kan hebben. Persoon
    wordt gebruikt als overkoepelend begrip (een verzamelnaam voor
    NatuurlijkPersoon, NietNatuurlijkPersoon en NaamPersoon) om er over
    te kunnen communiceren. Iedere in het handelsregister voorkomende Persoon
    heeft ofwel een Eigenaarschap en/ of minstens een Functievervulling
    waarmee de rol van de Persoon is vastgelegd.

    Persoon typen:

    Natuurlijk Persoon (NPS)

    Een NatuurlijkPersoon is een mens. Iedere NatuurlijkPersoon heeft ofwel
    een {Eigenaarschap} ofwel een {Functievervulling} waarbij hij optreedt in
    een relevante rol zoals bestuurder, aandeelhouder of gevolmachtigde.
    Persoonsgegevens zijn alleen authentiek indien de betreffende
    NatuurlijkPersoon:

    - een eigenaar is van een eenmanszaak;
    - deelneemt als maat, vennoot of lid van een rederij bij een
      Samenwerkingsverband.

    Niet-natuurlijk Persoon (NNP)

    Een NietNatuurlijkPersoon is een Persoon met rechten en plichten die geen
    NatuurlijkPersoon is. De definitie sluit aan bij de definitie in de
    stelselcatalogus. In het handelsregister wordt de
    EenmanszaakMetMeerdereEigenaren en RechtspersoonInOprichting niet als
    Samenwerkingsverband geregistreerd. Voor het handelsregister worden deze
    beschouwd als niet-natuurlijke personen.

    NNP subtypen:

        - Buitenlandse Vennootschap (BRV)

            Een BuitenlandseVennootschap is opgericht naar buitenlands recht.
            In het handelsregister wordt van een {BuitenlandseVennootschap}
            opgenomen: het registratienummer uit het buitenlands register,
            de naam van het register en de plaats en land waar het register
            gehouden wordt.

        - Binnenlandse Niet-natuurlijk Persoon (BNP)

            Een BinnenlandseNietNatuurlijkPersoon is een NietNatuurlijkPersoon
            die bestaat naar Nederlands recht. Dit zijn alle Nederlandse
            rechtsvormen behalve de eenmanszaak.

    """

    type_choices = [
        ('natuurlijkPersoon', 'natuurlijkPersoon'),
        ('naamPersoon', 'naamPersoon'),
        ('buitenlandseVennootschap', 'buitenlandseVennootschap'),
        ('eenmanszaak', 'eenmanszaakMetMeerdereEigenaren'),
        ('rechtspersoon', 'rechtspersoon'),
        ('rechtspersoonInOprichting', 'rechtspersoonInOprichting'),
        ('samenwerkingsverband', 'samenwerkingsverband'),
    ]

    rol_choices = [
        ('EIGENAAR', 'EIGENAAR'),
        ('AANSPRAKELIJKE', 'AANSPRAKELIJKE'),
    ]

    id = models.DecimalField(primary_key=True, max_digits=18, decimal_places=0)

    rol = models.CharField(max_length=14,
                           blank=True,
                           null=True,
                           choices=rol_choices)

    rechtsvorm = models.CharField(max_length=50, blank=True, null=True)
    uitgebreide_rechtsvorm = models.CharField(max_length=240,
                                              blank=True,
                                              null=True)

    volledige_naam = models.CharField(max_length=240, blank=True, null=True)

    typering = models.CharField(max_length=50,
                                blank=True,
                                null=True,
                                choices=type_choices)

    reden_insolvatie = models.CharField(max_length=50, blank=True, null=True)

    # BeperkinginRechtshandeling (BIR)

    natuurlijkpersoon = models.OneToOneField(
        'NatuurlijkPersoon',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        help_text="niet null bij natuurlijkpersoon",
    )

    niet_natuurlijkpersoon = models.OneToOneField(
        'NietNatuurlijkPersoon',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        help_text="niet null bij niet-natuurlijkpersoon",
    )

    datum_aanvang = models.DateField(
        max_length=8,
        blank=True,
        null=True,
        help_text="De datum van aanvang van de MaatschappelijkeActiviteit",
    )

    datum_einde = models.DateField(
        max_length=8,
        blank=True,
        null=True,
        help_text="""
            De datum van beëindiging van de MaatschappelijkeActiviteit""",
    )

    soort = models.CharField(max_length=21, blank=True, null=True)

    datumuitschrijving = models.DateField(
        max_length=8,
        blank=True,
        null=True,
        help_text="De datum van aanvang van de MaatschappelijkeActiviteit",
    )

    naam = models.CharField(max_length=600, blank=True, null=True)

    # communicatie
    nummer = models.CharField(max_length=15, blank=True, null=True)
    toegangscode = models.DecimalField(max_digits=4,
                                       decimal_places=0,
                                       blank=True,
                                       null=True)

    faillissement = models.BooleanField()

    status = models.CharField(max_length=21, blank=True, null=True)
    duur = models.CharField(max_length=240, blank=True, null=True)

    def __str__(self):
        display = "{}".format(self.id)
        if self.volledige_naam:
            display = "{} - {}".format(display, self.volledige_naam)
        if self.rechtsvorm:
            display = "{} - {}".format(display, self.rechtsvorm)
        if self.uitgebreide_rechtsvorm:
            display = "{} - {}".format(display, self.uitgebreide_rechtsvorm)

        return display
Ejemplo n.º 13
0
class Vestiging(models.Model):
    """
    Vestiging (VES)

    Een Vestiging is gebouw of een complex van gebouwen waar duurzame
    uitoefening van activiteiten van een Onderneming of Rechtspersoon
    plaatsvindt. De vestiging is een combinatie van Activiteiten en
    Locatie.
    """

    id = models.CharField(primary_key=True, max_length=20)

    maatschappelijke_activiteit = models.ForeignKey(
        'MaatschappelijkeActiviteit',
        related_name='vestigingen',
        db_index=True,
        on_delete=models.DO_NOTHING,
    )

    vestigingsnummer = models.CharField(
        max_length=12,
        unique=True,
        help_text="Betreft het identificerende gegeven voor de Vestiging")

    hoofdvestiging = models.BooleanField()

    naam = models.CharField(max_length=200, null=True, blank=True)

    datum_aanvang = models.DateField(
        null=True,
        blank=True,
        help_text="De datum van aanvang van de Vestiging")

    datum_einde = models.DateField(
        null=True,
        blank=True,
        help_text="De datum van beëindiging van de Vestiging")
    datum_voortzetting = models.DateField(
        null=True,
        blank=True,
        help_text="De datum van voortzetting van de Vestiging")
    communicatiegegevens = models.ManyToManyField(
        'Communicatiegegevens',
        help_text="Afgeleid van communicatiegegevens van inschrijving",
    )
    postadres = models.ForeignKey(
        'Locatie',
        models.DO_NOTHING,
        related_name="+",
        blank=True,
        null=True,
        help_text="postadres",
    )
    bezoekadres = models.ForeignKey(
        'Locatie',
        models.DO_NOTHING,
        related_name="+",
        blank=True,
        null=True,
        help_text="bezoekadres",
    )

    commerciele_vestiging = models.OneToOneField('CommercieleVestiging',
                                                 on_delete=models.CASCADE,
                                                 null=True,
                                                 blank=True)

    niet_commerciele_vestiging = models.OneToOneField(
        'NietCommercieleVestiging',
        on_delete=models.CASCADE,
        null=True,
        blank=True)

    activiteiten = models.ManyToManyField('Activiteit')

    handelsnamen = models.ManyToManyField('Handelsnaam')

    @property
    def _adres(self):
        adres = None

        if self.bezoekadres:
            toevoeging = ""

            if self.bezoekadres.huisletter:
                toevoeging = self.bezoekadres.huisletter

            if self.bezoekadres.huisnummertoevoeging:
                toevoeging = "{}-{}".format(
                    toevoeging, self.bezoekadres.huisnummertoevoeging)

            adres = "{} {}{}".format(
                self.bezoekadres.straatnaam,
                self.bezoekadres.huisnummer,
                toevoeging,
            )

        elif self.postadres:
            adres = "{} (post)".format(self.postadres.volledig_adres)

        return adres

    @property
    def locatie(self):
        """
        locatie
        """
        return self.bezoekadres if self.bezoekadres else self.postadres

    def __str__(self):

        kvk_adres_short = None
        handelsnaam = "{}".format(self.naam)
        # adres = self._adres

        if self.locatie:
            kvk_adres = self.locatie.volledig_adres
            kvk_adres_short = KVK_ADRES.split(kvk_adres)[0]

        if kvk_adres_short:
            return "{} - {}".format(handelsnaam, kvk_adres_short)

        return handelsnaam
Ejemplo n.º 14
0
class MaatschappelijkeActiviteit(models.Model):
    """
    Maatschappelijke Activiteit (MAC)

    Een MaatschappelijkeActiviteit is de activiteit van een
    NatuurlijkPersoon of NietNatuurlijkPersoon. De
    MaatschappelijkeActiviteit is het totaal van alle activiteiten
    uitgeoefend door een NatuurlijkPersoon of een NietNatuurlijkPersoon.
    Een MaatschappelijkeActiviteit kan ook als Onderneming voorkomen.
    """
    id = models.DecimalField(primary_key=True, max_digits=18, decimal_places=0)

    naam = models.CharField(
        max_length=600,
        blank=True,
        null=True,
        help_text="""
            De (statutaire) naam of eerste handelsnaam van de inschrijving""",
    )

    kvk_nummer = models.CharField(
        unique=True,
        max_length=8,
        blank=True,
        null=True,
        help_text="""
            Betreft het identificerende gegeven
            voor de MaatschappelijkeActiviteit, het KvK-nummer""",
    )

    datum_aanvang = models.DateField(
        max_length=8,
        blank=True,
        null=True,
        help_text="De datum van aanvang van de MaatschappelijkeActiviteit",
    )
    datum_einde = models.DateField(
        max_length=8,
        blank=True,
        null=True,
        help_text="""
            De datum van beëindiging van de MaatschappelijkeActiviteit""",
    )
    incidenteel_uitlenen_arbeidskrachten = models.NullBooleanField(
        help_text="""
            Indicatie die aangeeft of de ondernemer tijdelijk arbeidskrachten
            ter beschikking stelt en dit niet onderdeel is van zijn
            'reguliere' activiteiten.""", )
    non_mailing = models.NullBooleanField(help_text="""
            Indicator die aangeeft of de inschrijving haar adresgegevens
            beschikbaar stelt voor mailing-doeleinden.""", )

    communicatiegegevens = models.ManyToManyField(
        'Communicatiegegevens',
        help_text="Afgeleid van communicatiegegevens van inschrijving",
    )

    activiteiten = models.ManyToManyField('Activiteit',
                                          help_text="""
            De SBI-activiteiten van de MaatschappelijkeActiviteit is het totaal
            van alle SBI-activiteiten die voorkomen bij de
            MaatschappelijkeActiviteit behorende " NietCommercieleVestigingen
            en bij de Rechtspersoon""")

    postadres = models.ForeignKey(
        'Locatie',
        models.DO_NOTHING,
        related_name="+",
        blank=True,
        null=True,
        help_text="postadres",
    )
    bezoekadres = models.ForeignKey(
        'Locatie',
        models.DO_NOTHING,
        related_name="+",
        blank=True,
        null=True,
        help_text="bezoekadres",
    )

    eigenaar = models.ForeignKey(
        'Persoon',
        models.DO_NOTHING,
        related_name="maatschappelijke_activiteit",
        blank=True,
        null=True,
        help_text="",
    )

    # eigenaar zit niet ons systeem
    # iets met kvk doen?
    eigenaar_mks_id = models.DecimalField(blank=True,
                                          null=True,
                                          db_index=True,
                                          max_digits=18,
                                          decimal_places=0)

    onderneming = models.OneToOneField(
        'Onderneming',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        help_text="",
    )

    hoofdvestiging = models.ForeignKey('Vestiging',
                                       null=True,
                                       blank=True,
                                       on_delete=models.SET_NULL)

    @property
    def locatie(self):
        """
        locatie
        """
        return self.bezoekadres if self.bezoekadres else self.postadres

    def __str__(self):
        return "{}".format(self.naam)
Ejemplo n.º 15
0
class RegistriesApplication(AuditModel):
    """
    Application from a well driller or pump installer to be on the GWELLS Register.
    """
    application_guid = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        verbose_name='Register Application UUID',
        db_comment='Unique identifier for the registries_application record.')
    registration = models.ForeignKey(
        Register,
        db_column='register_guid',
        on_delete=models.PROTECT,
        verbose_name='Person Reference',
        related_name='applications',
        db_comment='Unique identifier for the registries_register record.')
    subactivity = models.ForeignKey(
        SubactivityCode,
        db_column='registries_subactivity_code',
        on_delete=models.PROTECT,
        related_name="applications")
    file_no = models.CharField(
        max_length=25, blank=True, null=True, verbose_name='ORCS File # reference.',
        db_comment=('Operational Records Classification Systems (ORCS) number. Information schedules used '
                    'to classify, file, retrieve and dispose of operational records. This number is '
                    'assigned on creation of a file.'))
    proof_of_age = models.ForeignKey(
        ProofOfAgeCode,
        db_column='registries_proof_of_age_code',
        on_delete=models.PROTECT,
        verbose_name="Proof of age.",
        null=True
    )
    registrar_notes = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        verbose_name='Registrar notes, for internal use only.',
        db_comment='Internal notes documenting communication between an applicant and the province.')
    reason_denied = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        verbose_name='Free form text explaining reason for denial.',
        db_comment=('The reason the Comptroller did not approve an individuals application for well driller '
                    'or well pump installer, for example not meeting the requirements of the application. '
                    'A brief internal note.'))

    # TODO Support multiple certificates
    primary_certificate = models.ForeignKey(
        AccreditedCertificateCode,
        blank=True,
        null=True,
        db_column='acc_cert_guid',
        on_delete=models.PROTECT,
        verbose_name="Certificate")
    primary_certificate_no = models.CharField(
        max_length=50,
        db_comment='Unique number assigned to the certificate by the certifying organization.')

    @property
    def display_status(self):
        # When an application is removed, it's status remains "Active", and only the removal date is
        # populated. We spare the front-end from having to know about this, by generating a human
        # readable property on this level.
        status = None
        if self.removal_date:
            status = 'Removed'
        elif self.current_status:
            status = self.current_status.description
        return status

    # TODO Should probably force this to have a default value of Pending!
    # This field should really be called "Approval Outcome"
    current_status = models.ForeignKey(
        ApplicationStatusCode,
        blank=True,
        null=True,
        db_column='registries_application_status_code',
        on_delete=models.PROTECT,
        verbose_name="Application Status Code Reference")
    application_recieved_date = models.DateField(
        blank=True, null=True,
        db_comment=('Date that the province received an application for registration of a well driller or '
                    'well pump installer.'))
    application_outcome_date = models.DateField(
        blank=True, null=True,
        db_comment=('Date that the comptroller decided if the application for registration of a well '
                    'driller or well pump installer was approved or denied.'))
    application_outcome_notification_date = models.DateField(
        blank=True, null=True,
        db_comment=('Date that the individual was notified of the outcome of their application for '
                    'registration for well driller or well pump installer.'))
    # The "removal_date" refers to the date on which a classification is "removed" from the register.
    # Removing a classification may result in a person being removed from the public register as a whole,
    # only if there are no other Approved classification.
    removal_date = models.DateField(
        blank=True, null=True,
        db_comment='Date that a registered individual was removed from the register.'
    )
    removal_reason = models.ForeignKey(
        RegistriesRemovalReason,
        db_column='registries_removal_reason_code',
        on_delete=models.PROTECT,
        blank=True,
        null=True,
        verbose_name='Removal Reason')

    history = GenericRelation(Version)

    class Meta:
        db_table = 'registries_application'
        verbose_name_plural = 'Applications'
        ordering = ['primary_certificate_no']

    db_table_comment = 'Placeholder table comment.'

    def __str__(self):
        return '%s : %s' % (
            self.registration,
            self.file_no)
Ejemplo n.º 16
0
class Schedule(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL,
                              verbose_name=_('owner'),
                              on_delete=models.PROTECT)

    name = models.CharField(
        _('name'),
        max_length=100,
        help_text=_('Name your test schedule, must be unique'))
    url = models.URLField(_('URL'),
                          db_index=True,
                          help_text=_('The URL you want to test'))

    trillians = models.ManyToManyField(
        Trillian,
        verbose_name=_('Trillians'),
        help_text=_(
            'The data centres from where you want this URL to be tested'))

    time = models.TimeField(
        _('time'),
        help_text=_(
            'The time of day in UTC when you want the tests to be scheduled'))
    start = models.DateField(
        _('start'),
        default=date.today,
        help_text=_('The first day that you want the tests to be run'))
    end = models.DateField(
        _('end'),
        blank=True,
        null=True,
        help_text=_('The last day that you want the tests to be run'))
    frequency = models.CharField(
        _('frequency'),
        max_length=1,
        choices=[
            ('D', _('Every day')),
            ('W', _('Every week')),
            ('M', _('Every month')),
        ],
        help_text=
        _('Frequency to schedule the tests. Can be "D" (daily), "W" (weekly) or "M" (monthly)'
          ))

    is_public = models.BooleanField(
        _('is public'),
        default=True,
        help_text=_('Whether the test results should be publicly visible'))

    class Meta:
        verbose_name = _('schedule')
        verbose_name_plural = _('schedules')
        ordering = ('start', 'end')
        unique_together = (('owner', 'name'), )

    def __str__(self):
        return self.name

    def first_testrun(self):
        return self.testruns.order_by('requested').values_list(
            'requested', flat=True).first()

    first_testrun.short_description = _('first testrun')
    first_testrun = property(first_testrun)

    def last_testrun(self):
        return self.testruns.order_by('-requested').values_list(
            'requested', flat=True).first()

    last_testrun.short_description = _('last testrun')
    last_testrun = property(last_testrun)

    def is_active(self):
        # Check if it started already
        if datetime.datetime.combine(self.start, self.time,
                                     timezone.utc) > timezone.now():
            return False

        # No end means it's still active
        if not self.end:
            return True

        return datetime.datetime.combine(self.end, self.time,
                                         timezone.utc) >= timezone.now()

    is_active.short_description = _('is active')
    is_active = property(is_active)
Ejemplo n.º 17
0
class MetricsIngest(models.Model):
    '''Tracks all the ingest metrics grouped by strike process.

    :keyword strike: The strike process associated with these metrics.
    :type strike: :class:`django.db.models.ForeignKey`
    :keyword occurred: The date when the ingests included in this model were ended.
    :type occurred: :class:`django.db.models.DateField`

    :keyword deferred_count: The total number of deferred ingests.
    :type deferred_count: :class:`metrics.models.PlotIntegerField`
    :keyword ingested_count: The total number of successfully completed ingests.
    :type ingested_count: :class:`metrics.models.PlotIntegerField`
    :keyword errored_count: The total number of failed ingests.
    :type errored_count: :class:`metrics.models.PlotIntegerField`
    :keyword duplicate_count: The total number of duplicated ingests.
    :type duplicate_count: :class:`metrics.models.PlotIntegerField`

    :keyword file_size_sum: The total size of ingested files in bytes.
    :type file_size_sum: :class:`metrics.models.PlotBigIntegerField`
    :keyword file_size_min: The minimum size of ingested files in bytes.
    :type file_size_min: :class:`metrics.models.PlotBigIntegerField`
    :keyword file_size_max: The maximum size of ingested files in bytes.
    :type file_size_max: :class:`metrics.models.PlotBigIntegerField`
    :keyword file_size_avg: The average size of ingested files in bytes.
    :type file_size_avg: :class:`metrics.models.PlotBigIntegerField`

    :keyword transfer_time_sum: The total time spent transferring ingested files in seconds.
    :type transfer_time_sum: :class:`metrics.models.PlotIntegerField`
    :keyword transfer_time_min: The minimum time spent transferring ingested files in seconds.
    :type transfer_time_min: :class:`metrics.models.PlotIntegerField`
    :keyword transfer_time_max: The maximum time spent transferring ingested files in seconds.
    :type transfer_time_max: :class:`metrics.models.PlotIntegerField`
    :keyword transfer_time_avg: The average time spent transferring ingested files in seconds.
    :type transfer_time_avg: :class:`metrics.models.PlotIntegerField`

    :keyword ingest_time_sum: The total time spent ingesting files in seconds.
    :type ingest_time_sum: :class:`metrics.models.PlotIntegerField`
    :keyword ingest_time_min: The minimum time spent ingesting files in seconds.
    :type ingest_time_min: :class:`metrics.models.PlotIntegerField`
    :keyword ingest_time_max: The maximum time spent ingesting files in seconds.
    :type ingest_time_max: :class:`metrics.models.PlotIntegerField`
    :keyword ingest_time_avg: The average time spent ingesting files in seconds.
    :type ingest_time_avg: :class:`metrics.models.PlotIntegerField`

    :keyword created: When the model was first created.
    :type created: :class:`django.db.models.DateTimeField`
    '''
    GROUPS = [
        MetricsTypeGroup('overview', 'Overview',
                         'Overall counts based on ingest status.'),
        MetricsTypeGroup('file_size', 'File Size',
                         'Size information about ingested files.'),
        MetricsTypeGroup('transfer_time', 'Transfer Time',
                         'When files were being transferred before ingest.'),
        MetricsTypeGroup('ingest_time', 'Ingest Time',
                         'When files were processed during ingest.'),
    ]

    strike = models.ForeignKey('ingest.Strike', on_delete=models.PROTECT)
    occurred = models.DateField(db_index=True)

    deferred_count = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='overview',
        help_text='Number of files deferred (ignored) by the ingest process.',
        null=True,
        units='count',
        verbose_name='Deferred Count')
    ingested_count = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='overview',
        help_text='Number of files successfully ingested.',
        null=True,
        units='count',
        verbose_name='Ingested Count')
    errored_count = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='overview',
        help_text='Number of files that failed to ingest.',
        null=True,
        units='count',
        verbose_name='Errored Count')
    duplicate_count = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='overview',
        help_text='Number of files that were duplicates of previous ingests.',
        null=True,
        units='count',
        verbose_name='Duplicate Count')
    total_count = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='overview',
        help_text=
        'Number of deferred, ingested, errored, and duplicate ingests.',
        null=True,
        units='count',
        verbose_name='Total Count')

    file_size_sum = PlotBigIntegerField(
        aggregate='sum',
        blank=True,
        group='file_size',
        help_text='Total size of ingested files.',
        null=True,
        units='bytes',
        verbose_name='File Size (Sum)')
    file_size_min = PlotBigIntegerField(
        aggregate='min',
        blank=True,
        group='file_size',
        help_text='Minimum size of ingested files.',
        null=True,
        units='bytes',
        verbose_name='File Size (Min)')
    file_size_max = PlotBigIntegerField(
        aggregate='max',
        blank=True,
        group='file_size',
        help_text='Maximum size of ingested files.',
        null=True,
        units='bytes',
        verbose_name='File Size (Max)')
    file_size_avg = PlotBigIntegerField(
        aggregate='avg',
        blank=True,
        group='file_size',
        help_text='Average size of ingested files.',
        null=True,
        units='bytes',
        verbose_name='File Size (Avg)')

    transfer_time_sum = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='transfer_time',
        help_text='Total time spent transferring files before ingest.',
        null=True,
        units='seconds',
        verbose_name='Transfer Time (Sum)')
    transfer_time_min = PlotIntegerField(
        aggregate='min',
        blank=True,
        group='transfer_time',
        help_text='Minimum time spent transferring files before ingest.',
        null=True,
        units='seconds',
        verbose_name='Transfer Time (Min)')
    transfer_time_max = PlotIntegerField(
        aggregate='max',
        blank=True,
        group='transfer_time',
        help_text='Maximum time spent transferring files before ingest.',
        null=True,
        units='seconds',
        verbose_name='Transfer Time (Max)')
    transfer_time_avg = PlotIntegerField(
        aggregate='avg',
        blank=True,
        group='transfer_time',
        help_text='Average time spent transferring files before ingest.',
        null=True,
        units='seconds',
        verbose_name='Transfer Time (Avg)')

    ingest_time_sum = PlotIntegerField(
        aggregate='sum',
        blank=True,
        group='ingest_time',
        help_text='Total time spent processing files during ingest.',
        null=True,
        units='seconds',
        verbose_name='Ingest Time (Sum)')
    ingest_time_min = PlotIntegerField(
        aggregate='min',
        blank=True,
        group='ingest_time',
        help_text='Minimum time spent processing files during ingest.',
        null=True,
        units='seconds',
        verbose_name='Ingest Time (Min)')
    ingest_time_max = PlotIntegerField(
        aggregate='max',
        blank=True,
        group='ingest_time',
        help_text='Maximum time spent processing files during ingest.',
        null=True,
        units='seconds',
        verbose_name='Ingest Time (Max)')
    ingest_time_avg = PlotIntegerField(
        aggregate='avg',
        blank=True,
        group='ingest_time',
        help_text='Average time spent processing files during ingest.',
        null=True,
        units='seconds',
        verbose_name='Ingest Time (Avg)')

    created = models.DateTimeField(auto_now_add=True)

    objects = MetricsIngestManager()

    class Meta(object):
        '''meta information for the db'''
        db_table = 'metrics_ingest'
Ejemplo n.º 18
0
class AbstractProfile(models.Model):
    registration_id = models.CharField(_('registration number'),
                                       max_length=255,
                                       blank=True)
    acquisition_date = models.DateField(_('acquisition date'), default=today)
    first_name = models.CharField(_('first name'), max_length=255)
    last_name = models.CharField(_('last name'), max_length=255)
    middle_name = models.CharField(_('middle name'),
                                   max_length=255,
                                   blank=True)
    gender = models.ForeignKey('hivs_utils.Gender',
                               related_name='clients_profiles',
                               verbose_name='gender',
                               on_delete=models.SET_NULL,
                               null=True)
    marital_status = models.ForeignKey('hivs_utils.MaritalStatus',
                                       related_name='clients_profiles',
                                       verbose_name='marital status',
                                       on_delete=models.SET_NULL,
                                       null=True,
                                       blank=True)
    birthdate = models.DateField(_('birthdate'), blank=True, null=True)
    phone = PhoneNumberField(_('phone number'), blank=True)
    other_phones = ArrayField(PhoneNumberField(),
                              blank=True,
                              default=list,
                              verbose_name=_('other phones'))
    email = models.EmailField(_('email'), blank=True)
    education_level = models.ForeignKey('hivs_utils.EducationLevel',
                                        related_name='clients_profiles',
                                        verbose_name='education level',
                                        on_delete=models.SET_NULL,
                                        null=True,
                                        blank=True)
    occupation = models.ForeignKey('hivs_utils.Occupation',
                                   related_name='clients_profiles',
                                   verbose_name='occupation',
                                   on_delete=models.SET_NULL,
                                   null=True,
                                   blank=True)
    area = models.ForeignKey('hivs_administrative.Area',
                             related_name='clients_profiles',
                             verbose_name='administrative area',
                             on_delete=models.SET_NULL,
                             blank=True,
                             null=True)
    street = models.ForeignKey('hivs_administrative.Street',
                               related_name='clients_profiles',
                               verbose_name='street',
                               on_delete=models.SET_NULL,
                               blank=True,
                               null=True)
    timestamp = models.DateTimeField('Created at', auto_now_add=True)
    last_modified = models.DateTimeField(_('Last modified'),
                                         auto_now=True,
                                         null=True,
                                         blank=True)
    extras = JSONField(_('extras'), blank=True, default=dict)

    class Meta:
        verbose_name = _('Profile')
        verbose_name_plural = _('Profiles')
        abstract = True

    def __str__(self):
        return ' '.join(
            filter(None,
                   [self.registration_id, self.first_name, self.last_name]))
Ejemplo n.º 19
0
class Locality(models.Model):
    """ Hold locality information - cities, towns, villages, etc """

    ### model options - "anything that's not a field"
    class Meta:
        ordering = ['country', 'admin1', 'admin2', 'long_name']
        verbose_name_plural = 'Localities'

    ### Python class methods
    def __unicode__(self):
        admin1_name = None
        if self.admin1: admin1_name = self.admin1.name
        admin2_name = None
        if self.admin2: admin2_name = self.admin2.name
        if settings.DEBUG:
            return u'PK{0}: {1}{2}{3} > {4}'.format(
                self.geonameid, self.country.name,
                ' > ' + admin1_name if admin1_name else '',
                ' > ' + admin2_name + ' > ' if admin2_name else '', self.name)
        return u'{0}{1}{2}, {3}'.format(
            self.name, ', ' + admin2_name if admin2_name else '',
            ', ' + admin1_name if admin1_name else '', self.country.name)

    ### Python convention class methods
    def save(self, check_duplicated_longname=True, *args, **kwargs):
        # Update long_name
        self.long_name = self.generate_long_name()

        if check_duplicated_longname is True:
            # and check if already exists other locality with the same long name
            other_localities = Locality.objects.filter(
                long_name=self.long_name)
            other_localities = other_localities.exclude(
                geonameid=self.geonameid)

            if other_localities.count() > 0:
                raise ValueError("Duplicated locality long name '{}'".format(
                    self.long_name))

        # Check consistency
        if self.admin1 is not None and self.admin1.country != self.country:
            raise ValueError(
                "The country '{}' from the Admin1 '{}' is different than the country '{}' from the locality '{}'"
                .format(self.admin1.country, self.admin1, self.country,
                        self.long_name))

        if self.admin2 is not None and self.admin2.country != self.country:
            raise ValueError(
                "The country '{}' from the Admin2 '{}' is different than the country '{}' from the locality '{}'"
                .format(self.admin2.country, self.admin2, self.country,
                        self.long_name))

        self.point = Point(float(self.longitude), float(self.latitude))

        # Call the "real" save() method.
        super(Locality, self).save(*args, **kwargs)

    ### extra model functions
    def generate_long_name(self):
        long_name = u"{}".format(self.name)
        if self.admin2 is not None:
            long_name = u"{}, {}".format(long_name, self.admin2.name)

        if self.admin1 is not None:
            long_name = u"{}, {}".format(long_name, self.admin1.name)

        return long_name

    def near_localities_rough(self, miles):
        """
        Rough calculation of the localities at 'miles' miles of this locality.
        Is rough because calculates a square instead of a circle and the earth
        is considered as an sphere, but this calculation is fast! And we don't
        need precission.
        """
        diff_lat = Decimal(degrees(miles / EARTH_RADIUS_MI))
        latitude = Decimal(self.latitude)
        longitude = Decimal(self.longitude)
        max_lat = latitude + diff_lat
        min_lat = latitude - diff_lat
        diff_long = Decimal(
            degrees(miles / EARTH_RADIUS_MI / cos(radians(latitude))))
        max_long = longitude + diff_long
        min_long = longitude - diff_long
        near_localities = Locality.objects.filter(latitude__gte=min_lat,
                                                  longitude__gte=min_long)
        near_localities = near_localities.filter(latitude__lte=max_lat,
                                                 longitude__lte=max_long)
        return near_localities

    def near_locals_nogis(self, miles):
        ids = []
        for loc in self.near_localities_rough(miles).values_list(
                "geonameid", "latitude", "longitude"):
            other_geonameid = loc[0]
            if self.geonameid == other_geonameid:
                distance = 0
                ids.append(other_geonameid)
            else:
                distance = self.calc_distance_nogis(loc[1], loc[2])
                if distance <= miles:
                    ids.append(other_geonameid)

        return ids

    def calc_distance_nogis(self, la2, lo2):
        # Convert latitude and longitude to
        # spherical coordinates in radians.
        # phi = 90 - latitude
        phi1 = (90.0 - float(self.latitude)) * DEGREES_TO_RADIANS
        phi2 = (90.0 - float(la2)) * DEGREES_TO_RADIANS

        # theta = longitude
        theta1 = float(self.longitude) * DEGREES_TO_RADIANS
        theta2 = float(lo2) * DEGREES_TO_RADIANS

        # Compute spherical distance from spherical coordinates.
        # For two localities in spherical coordinates
        # (1, theta, phi) and (1, theta, phi)
        # cosine( arc length ) =
        #    sin phi sin phi' cos(theta-theta') + cos phi cos phi'
        # distance = rho * arc length
        cosinus = sin(phi1) * sin(phi2) * cos(theta1 -
                                              theta2) + cos(phi1) * cos(phi2)
        cosinus = round(cosinus, 14)  # to avoid math domain error in acos
        arc = acos(cosinus)

        # Multiply arc by the radius of the earth
        return arc * EARTH_RADIUS_MI

    def near_localities(self, miles):
        localities = self.near_localities_rough(miles)
        localities = localities.filter(point__distance_lte=(self.point,
                                                            D(mi=miles)))
        return localities.values_list("geonameid", flat=True)

    ### custom managers
    objects = BaseManager()

    ### model DB fields
    status = models.IntegerField(
        blank=False,
        default=BaseManager.STATUS_ENABLED,
        # specify blank=False default=<value> to avoid form select '-------' rendering
        choices=BaseManager.STATUS_CHOICES)
    geonameid = models.PositiveIntegerField(primary_key=True)
    name = models.CharField(max_length=200, db_index=True)
    long_name = models.CharField(max_length=200)
    country = models.ForeignKey(Country,
                                related_name="locality_set",
                                on_delete=models.CASCADE)
    admin1 = models.ForeignKey(Admin1Code,
                               null=True,
                               blank=True,
                               related_name="locality_set",
                               on_delete=models.CASCADE)
    admin2 = models.ForeignKey(Admin2Code,
                               null=True,
                               blank=True,
                               related_name="locality_set",
                               on_delete=models.CASCADE)
    timezone = models.ForeignKey(Timezone,
                                 related_name="locality_set",
                                 null=True,
                                 on_delete=models.CASCADE)
    population = models.PositiveIntegerField()
    latitude = models.DecimalField(max_digits=7, decimal_places=2)
    longitude = models.DecimalField(max_digits=7, decimal_places=2)
    point = models.PointField(geography=False)
    modification_date = models.DateField()
Ejemplo n.º 20
0
Archivo: models.py Proyecto: mcab/hiber
class HousePhysicalFeatures(models.Model):
    """
    Describes a model that has all information regarding the physical
    characteristics of the bat house, including size, amount of chambers, etc.
    """
    house = models.ForeignKey(House,
                              on_delete=models.CASCADE,
                              related_name='physical_features')

    house_size = models.CharField(
        max_length=1,
        choices=(
            ('S', 'Small'),
            ('M', 'Medium'),
            ('L', 'Large'),
        ),
        help_text="Approximate size of the bat house")
    color = models.CharField(max_length=2,
                             choices=(
                                 ('BL', 'Black'),
                                 ('DB', 'Dark brown'),
                                 ('MB', 'Medium brown'),
                                 ('LB', 'Light brown'),
                                 ('TB', 'Tan/Beige'),
                                 ('NW', 'Natural wood'),
                                 ('WH', 'White'),
                                 ('OT', 'Other'),
                             ),
                             help_text="Color of bat house")
    other_color = models.CharField(
        blank=True,
        max_length=255,
        help_text="Color of bat house if Other is specified")
    chambers = models.PositiveIntegerField(
        validators=[MinValueValidator(1)],
        help_text="Number of chambers in bat house")
    direction = models.CharField(
        max_length=2,
        choices=(
            ('NO', 'North'),
            ('NE', 'Northeast'),
            ('EA', 'East'),
            ('SE', 'Southeast'),
            ('SO', 'South'),
            ('SW', 'Southwest'),
            ('WE', 'West'),
            ('NW', 'Northwest'),
        ),
        help_text="Direction which bat house is facing")
    mounted_on = models.CharField(
        max_length=2,
        choices=(
            ('BD', 'Building'),
            ('PI', 'On a pole by itself'),
            ('PB', 'On a pole with another bat house, back to back'),
            ('TR', 'Tree'),
            ('OT', 'Other'),
        ),
        help_text="Item which bat house is mounted to")
    other_mounted_on = models.CharField(
        blank=True,
        max_length=255,
        help_text="Mount type if Other is specified")
    ground_height = models.PositiveIntegerField(
        validators=[MinValueValidator(1)],
        help_text="Height above the ground surface (in feet)")
    installed = models.DateField(
        help_text="Date when the bat house was installed")
Ejemplo n.º 21
0
class ImportEvent(models.Model):
    file_name = models.CharField(max_length=256)
    import_date = models.DateField(auto_now=True)
Ejemplo n.º 22
0
class ICity1(CityBase):
    dt = models.DateField()

    class Meta(CityBase.Meta):
        pass
Ejemplo n.º 23
0
class TouristicEvent(AddPropertyMixin, PublishableMixin, MapEntityMixin,
                     StructureRelated, PicturesMixin, TimeStampedModelMixin,
                     NoDeleteMixin):
    """ A touristic event (conference, workshop, etc.) in the park
    """
    description_teaser = models.TextField(
        verbose_name=_(u"Description teaser"),
        blank=True,
        help_text=_(u"A brief summary"),
        db_column='chapeau')
    description = models.TextField(verbose_name=_(u"Description"),
                                   blank=True,
                                   db_column='description',
                                   help_text=_(u"Complete description"))
    themes = models.ManyToManyField(Theme,
                                    related_name="touristic_events",
                                    db_table="t_r_evenement_touristique_theme",
                                    blank=True,
                                    verbose_name=_(u"Themes"),
                                    help_text=_(u"Main theme(s)"))
    geom = models.PointField(verbose_name=_(u"Location"), srid=settings.SRID)
    begin_date = models.DateField(blank=True,
                                  null=True,
                                  verbose_name=_(u"Begin date"),
                                  db_column='date_debut')
    end_date = models.DateField(blank=True,
                                null=True,
                                verbose_name=_(u"End date"),
                                db_column='date_fin')
    duration = models.CharField(verbose_name=_(u"Duration"),
                                max_length=64,
                                blank=True,
                                db_column='duree',
                                help_text=_(u"3 days, season, ..."))
    meeting_point = models.CharField(verbose_name=_(u"Meeting point"),
                                     max_length=256,
                                     blank=True,
                                     db_column='point_rdv',
                                     help_text=_(u"Where exactly ?"))
    meeting_time = models.TimeField(verbose_name=_(u"Meeting time"),
                                    blank=True,
                                    null=True,
                                    db_column='heure_rdv',
                                    help_text=_(u"11:00, 23:30"))
    contact = models.TextField(verbose_name=_(u"Contact"),
                               blank=True,
                               db_column='contact')
    email = models.EmailField(verbose_name=_(u"Email"),
                              max_length=256,
                              db_column='email',
                              blank=True,
                              null=True)
    website = models.URLField(verbose_name=_(u"Website"),
                              max_length=256,
                              db_column='website',
                              blank=True,
                              null=True)
    organizer = models.CharField(verbose_name=_(u"Organizer"),
                                 max_length=256,
                                 blank=True,
                                 db_column='organisateur')
    speaker = models.CharField(verbose_name=_(u"Speaker"),
                               max_length=256,
                               blank=True,
                               db_column='intervenant')
    type = models.ForeignKey(TouristicEventType,
                             verbose_name=_(u"Type"),
                             blank=True,
                             null=True,
                             db_column='type')
    accessibility = models.CharField(verbose_name=_(u"Accessibility"),
                                     max_length=256,
                                     blank=True,
                                     db_column='accessibilite')
    participant_number = models.CharField(
        verbose_name=_(u"Number of participants"),
        max_length=256,
        blank=True,
        db_column='nb_places')
    booking = models.TextField(verbose_name=_(u"Booking"),
                               blank=True,
                               db_column='reservation')
    target_audience = models.CharField(verbose_name=_(u"Target audience"),
                                       max_length=128,
                                       blank=True,
                                       null=True,
                                       db_column='public_vise')
    practical_info = models.TextField(
        verbose_name=_(u"Practical info"),
        blank=True,
        db_column='infos_pratiques',
        help_text=_(u"Recommandations / To plan / Advices"))
    source = models.ManyToManyField(
        'common.RecordSource',
        blank=True,
        related_name='touristicevents',
        verbose_name=_("Source"),
        db_table='t_r_evenement_touristique_source')
    portal = models.ManyToManyField(
        'common.TargetPortal',
        blank=True,
        related_name='touristicevents',
        verbose_name=_("Portal"),
        db_table='t_r_evenement_touristique_portal')
    eid = models.CharField(verbose_name=_(u"External id"),
                           max_length=128,
                           blank=True,
                           null=True,
                           db_column='id_externe')
    approved = models.BooleanField(verbose_name=_(u"Approved"),
                                   default=False,
                                   db_column='labellise')

    objects = NoDeleteMixin.get_manager_cls(models.GeoManager)()

    category_id_prefix = 'E'

    class Meta:
        db_table = 't_t_evenement_touristique'
        verbose_name = _(u"Touristic event")
        verbose_name_plural = _(u"Touristic events")
        ordering = ['-begin_date']

    def __unicode__(self):
        return self.name

    @property
    def type1(self):
        return [self.type] if self.type else []

    @property
    def type2(self):
        return []

    @property
    def districts_display(self):
        return ', '.join([unicode(d) for d in self.districts])

    @property
    def dates_display(self):
        if not self.begin_date and not self.end_date:
            return u""
        elif not self.end_date:
            return _(u"starting from {begin}").format(
                begin=date_format(self.begin_date, 'SHORT_DATE_FORMAT'))
        elif not self.begin_date:
            return _(u"up to {end}").format(
                end=date_format(self.end_date, 'SHORT_DATE_FORMAT'))
        elif self.begin_date == self.end_date:
            return date_format(self.begin_date, 'SHORT_DATE_FORMAT')
        else:
            return _(u"from {begin} to {end}").format(
                begin=date_format(self.begin_date, 'SHORT_DATE_FORMAT'),
                end=date_format(self.end_date, 'SHORT_DATE_FORMAT'))

    @property
    def prefixed_category_id(self):
        return self.category_id_prefix

    def distance(self, to_cls):
        return settings.TOURISM_INTERSECTION_MARGIN

    @property
    def portal_display(self):
        return ', '.join([unicode(portal) for portal in self.portal.all()])

    @property
    def source_display(self):
        return ', '.join([unicode(source) for source in self.source.all()])

    @property
    def themes_display(self):
        return ','.join([unicode(source) for source in self.themes.all()])

    @property
    def rando_url(self):
        category_slug = _(u'touristic-event')
        return '{}/{}/'.format(category_slug, self.slug)

    @property
    def meta_description(self):
        return plain_text(self.description_teaser or self.description)[:500]
Ejemplo n.º 24
0
class LogbookEntry(TroggleModel):
    date = models.DateField()

    #below field is unnecessary duplicate; can figure out what expedition it is from any persontrip's personexpedition's expedition.
    expedition = models.ForeignKey(Expedition, blank=True, null=True)

    #author  = models.ForeignKey(PersonExpedition,blank=True,null=True) # the person who writes it up doesn't have to have been on the trip. <- reply to previous from Aaron: if they wrote it up and weren't on the trip, they are actually part of the trip by virtue of writing about it; they just have a time underground of 0.
    title = models.CharField(max_length=200)
    cave = models.ForeignKey('Cave', blank=True, null=True)
    place = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        help_text="Only use this if you haven't chosen a cave")
    text = models.TextField()
    slug = models.SlugField(max_length=50)

    class Meta:
        verbose_name_plural = "Logbook entries"
        ordering = ('-date', )

    def get_absolute_url(self):
        return reverse('logbookentry',
                       kwargs={
                           'date': self.date,
                           'slug': self.slug
                       })

    def __unicode__(self):
        return "%s (%s) at %s" % (self.title, self.date, self.cave
                                  or self.place)

    def get_next_by_id(self):
        LogbookEntry.objects.get(id=self.id + 1)

    def get_previous_by_id(self):
        LogbookEntry.objects.get(id=self.id - 1)

    def new_QM_number(self):
        """Returns  """
        if self.cave:
            nextQMnumber = self.cave.new_QM_number(self.date.year)
        else:
            return none
        return nextQMnumber

    def new_QM_found_link(self):
        """Produces a link to a new QM with the next number filled in and this LogbookEntry set as 'found by' """
        return r'/admin/core/qm/add/?' + r'found_by=' + str(
            self.pk) + '&number=' + str(self.new_QM_number())

    def DayIndex(self):
        return list(self.expeditionday.logbookentry_set.all()).index(self)

    def intro(self):
        if len(self.text) > 80:
            return self.text[0:80] + '...'
        else:
            return self.text

    def author(self):
        return PersonTrip.objects.get(
            logbook_entry=self,
            is_logbook_entry_author=True).personexpedition.person
Ejemplo n.º 25
0
class Person(models.Model):
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    #  Jards Macalé is an amazing brazilian musician! =]
    enjoy_jards_macale = models.BooleanField(default=True)
    like_metal_music = models.BooleanField(default=False)
    name = models.CharField(max_length=30)
    nickname = models.SlugField(max_length=36)
    age = models.IntegerField()
    bio = models.TextField()
    birthday = models.DateField()
    birth_time = models.TimeField()
    appointment = models.DateTimeField()
    blog = models.URLField()
    occupation = models.CharField(max_length=10, choices=OCCUPATION_CHOICES)
    uuid = models.UUIDField(primary_key=False)
    name_hash = models.BinaryField(max_length=16)
    days_since_last_login = models.BigIntegerField()
    duration_of_sleep = models.DurationField()
    email = models.EmailField()
    id_document = models.CharField(unique=True, max_length=10)

    try:
        from django.db.models import JSONField

        data = JSONField()
    except ImportError:
        # Skip JSONField-related fields
        pass

    try:
        from django.contrib.postgres.fields import ArrayField, HStoreField
        from django.contrib.postgres.fields import JSONField as PostgresJSONField
        from django.contrib.postgres.fields.citext import (
            CICharField,
            CIEmailField,
            CITextField,
        )
        from django.contrib.postgres.fields.ranges import (
            BigIntegerRangeField,
            DateRangeField,
            DateTimeRangeField,
            IntegerRangeField,
        )

        if settings.USING_POSTGRES:
            acquaintances = ArrayField(models.IntegerField())
            postgres_data = PostgresJSONField()
            hstore_data = HStoreField()
            ci_char = CICharField(max_length=30)
            ci_email = CIEmailField()
            ci_text = CITextField()
            int_range = IntegerRangeField()
            bigint_range = BigIntegerRangeField()
            date_range = DateRangeField()
            datetime_range = DateTimeRangeField()
    except ImportError:
        # Skip PostgreSQL-related fields
        pass

    try:
        from django.contrib.postgres.fields.ranges import FloatRangeField

        if settings.USING_POSTGRES:
            float_range = FloatRangeField()
    except ImportError:
        # Django version greater or equal than 3.1
        pass

    try:
        from django.contrib.postgres.fields.ranges import DecimalRangeField

        if settings.USING_POSTGRES:
            decimal_range = DecimalRangeField()
    except ImportError:
        # Django version lower than 2.2
        pass

    if BAKER_GIS:
        geom = models.GeometryField()
        point = models.PointField()
        line_string = models.LineStringField()
        polygon = models.PolygonField()
        multi_point = models.MultiPointField()
        multi_line_string = models.MultiLineStringField()
        multi_polygon = models.MultiPolygonField()
        geom_collection = models.GeometryCollectionField()
Ejemplo n.º 26
0
class Action(models.Model):
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE)
    action_type = models.ForeignKey(ActionType, on_delete=models.CASCADE)
    content = models.TextField()
    created_at = models.DateField(default=timezone.now)
    updated_at = AutoDateTimeField(default=timezone.now)
Ejemplo n.º 27
0
class TrainStatistics(models.Model):
    obj_id = models.IntegerField()
    date = models.DateField()
Ejemplo n.º 28
0
class Intervention(AddPropertyMixin, MapEntityMixin, AltimetryMixin,
                   TimeStampedModelMixin, StructureRelated, NoDeleteMixin):

    name = models.CharField(verbose_name=_(u"Name"),
                            max_length=128,
                            db_column='nom',
                            help_text=_(u"Brief summary"))
    date = models.DateField(default=datetime.now,
                            verbose_name=_(u"Date"),
                            db_column='date',
                            help_text=_(u"When ?"))
    subcontracting = models.BooleanField(verbose_name=_(u"Subcontracting"),
                                         default=False,
                                         db_column='sous_traitance')

    # Technical information
    width = models.FloatField(default=0.0,
                              verbose_name=_(u"Width"),
                              db_column='largeur')
    height = models.FloatField(default=0.0,
                               verbose_name=_(u"Height"),
                               db_column='hauteur')
    area = models.FloatField(editable=False,
                             default=0,
                             verbose_name=_(u"Area"),
                             db_column='surface')

    # Costs
    material_cost = models.FloatField(default=0.0,
                                      verbose_name=_(u"Material cost"),
                                      db_column='cout_materiel')
    heliport_cost = models.FloatField(default=0.0,
                                      verbose_name=_(u"Heliport cost"),
                                      db_column='cout_heliport')
    subcontract_cost = models.FloatField(default=0.0,
                                         verbose_name=_(u"Subcontract cost"),
                                         db_column='cout_soustraitant')
    """ Topology can be of type Infrastructure or of own type Intervention """
    topology = models.ForeignKey(
        Topology,
        null=True,  # TODO: why null ?
        related_name="interventions_set",
        verbose_name=_(u"Interventions"))
    # AltimetyMixin for denormalized fields from related topology, updated via trigger.

    stake = models.ForeignKey('core.Stake',
                              null=True,
                              related_name='interventions',
                              verbose_name=_("Stake"),
                              db_column='enjeu')

    status = models.ForeignKey('InterventionStatus',
                               verbose_name=_("Status"),
                               db_column='status')

    type = models.ForeignKey('InterventionType',
                             null=True,
                             blank=True,
                             verbose_name=_(u"Type"),
                             db_column='type')

    disorders = models.ManyToManyField('InterventionDisorder',
                                       related_name="interventions",
                                       db_table="m_r_intervention_desordre",
                                       verbose_name=_(u"Disorders"),
                                       blank=True)

    jobs = models.ManyToManyField('InterventionJob',
                                  through='ManDay',
                                  verbose_name=_(u"Jobs"))

    project = models.ForeignKey('Project',
                                null=True,
                                blank=True,
                                related_name="interventions",
                                verbose_name=_(u"Project"),
                                db_column='chantier')
    description = models.TextField(blank=True,
                                   verbose_name=_(u"Description"),
                                   db_column='descriptif',
                                   help_text=_(u"Remarks and notes"))

    objects = NoDeleteMixin.get_manager_cls(InterventionManager)()

    class Meta:
        db_table = 'm_t_intervention'
        verbose_name = _(u"Intervention")
        verbose_name_plural = _(u"Interventions")

    def __init__(self, *args, **kwargs):
        super(Intervention, self).__init__(*args, **kwargs)
        self._geom = None

    def set_infrastructure(self, baseinfra):
        self.topology = baseinfra
        if not self.on_infrastructure:
            raise ValueError("Expecting an infrastructure or signage")

    def default_stake(self):
        stake = None
        if self.topology:
            for path in self.topology.paths.all():
                if path.stake > stake:
                    stake = path.stake
        return stake

    def reload(self, fromdb=None):
        if self.pk:
            fromdb = self.__class__.objects.get(pk=self.pk)
            self.area = fromdb.area
            AltimetryMixin.reload(self, fromdb)
            TimeStampedModelMixin.reload(self, fromdb)
            NoDeleteMixin.reload(self, fromdb)
            if self.topology:
                self.topology.reload()
        return self

    def save(self, *args, **kwargs):
        if self.stake is None:
            self.stake = self.default_stake()

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

        # Set kind of Intervention topology
        if self.topology and not self.on_infrastructure:
            topology_kind = self._meta.object_name.upper()
            self.topology.kind = topology_kind
            self.topology.save(update_fields=['kind'])

        # Invalidate project map
        if self.project:
            try:
                os.remove(self.project.get_map_image_path())
            except OSError:
                pass

        self.reload()

    @property
    def on_infrastructure(self):
        return self.is_infrastructure or self.is_signage

    @property
    def infrastructure(self):
        """
        Equivalent of topology attribute, but casted to related type (Infrastructure or Signage)
        """
        if self.on_infrastructure:
            if self.is_signage:
                return self.signages[0]
            if self.is_infrastructure:
                return self.infrastructures[0]
        return None

    @classproperty
    def infrastructure_verbose_name(cls):
        return _("On")

    @property
    def infrastructure_display(self):
        icon = 'path'
        title = _('Path')
        if self.on_infrastructure:
            icon = self.topology.kind.lower()
            title = u'%s: %s' % (_(
                self.topology.kind.capitalize()), self.infrastructure)

        return u'<img src="%simages/%s-16.png" title="%s">' % (
            settings.STATIC_URL, icon, title)

    @property
    def infrastructure_csv_display(self):
        if self.on_infrastructure:
            return u"%s: %s (%s)" % (_(
                self.topology.kind.capitalize()), self.infrastructure,
                                     self.infrastructure.pk)
        return ''

    @property
    def is_infrastructure(self):
        if self.topology:
            return self.topology.kind == Infrastructure.KIND
        return False

    @property
    def is_signage(self):
        if self.topology:
            return self.topology.kind == Signage.KIND
        return False

    @property
    def in_project(self):
        return self.project is not None

    @property
    def paths(self):
        if self.topology:
            return self.topology.paths.all()
        return Path.objects.none()

    @property
    def signages(self):
        if self.is_signage:
            return [Signage.objects.existing().get(pk=self.topology.pk)]
        return []

    @property
    def infrastructures(self):
        if self.is_infrastructure:
            return [Infrastructure.objects.existing().get(pk=self.topology.pk)]
        return []

    @property
    def total_manday(self):
        total = 0.0
        for md in self.manday_set.all():
            total += float(md.nb_days)
        return total

    @classproperty
    def total_manday_verbose_name(cls):
        return _("Mandays")

    @property
    def total_cost_mandays(self):
        total = 0.0
        for md in self.manday_set.all():
            total += md.cost
        return total

    @classproperty
    def total_cost_mandays_verbose_name(cls):
        return _("Mandays cost")

    @property
    def total_cost(self):
        return self.total_cost_mandays + \
            self.material_cost + \
            self.heliport_cost + \
            self.subcontract_cost

    @classproperty
    def total_cost_verbose_name(cls):
        return _("Total cost")

    @classproperty
    def geomfield(cls):
        return Topology._meta.get_field('geom')

    @property
    def geom(self):
        if self._geom is None:
            if self.topology:
                self._geom = self.topology.geom
        return self._geom

    @geom.setter
    def geom(self, value):
        self._geom = value

    @property
    def name_display(self):
        return u'<a data-pk="%s" href="%s" title="%s" >%s</a>' % (
            self.pk, self.get_detail_url(), self.name, self.name)

    @property
    def name_csv_display(self):
        return unicode(self.name)

    def __unicode__(self):
        return u"%s (%s)" % (self.name, self.date)

    @classmethod
    def path_interventions(cls, path):
        return cls.objects.existing().filter(topology__aggregations__path=path)

    @classmethod
    def topology_interventions(cls, topology):
        topos = Topology.overlapping(topology).values_list('pk', flat=True)
        return cls.objects.existing().filter(topology__in=topos).distinct('pk')
Ejemplo n.º 29
0
class Nomen(projects.models.PaleoCoreBaseClass):
    """
    A class for taxonomic names (nomen).
    The Nomen class inherits the following fields form the PaleoCoreBaseClass:
    name,
    date_created, date_last_modified
    problem, problem_comment
    remarks,
    last_import
    """
    generic_name_help = 'The genus portion of the scientific name, e.g. H**o.'
    specific_epithet_help = 'The trivial (species) portion of the scientific name, e.g. sapiens.'
    authorship_help = 'The authorship of the naming publication, date included, e.g. King, 1864'
    year_help = 'The year the name was published in yyyy format.'
    type_help = 'The catalog number of the type specimen entered as a string, e.g. OH 7'
    type_object_help = 'The type specimen fossil, select from choice list'
    paratypes_help = 'A comma delimited list of catalog number for paratype specimens as given in the source text'

    # scientific_name = self.scientific_name()  self.scientific_name_html()
    # name = models.Charfield ... inherited from parent class. The scientific name without authorship, e.g. H**o sapiens
    scientific_name_id = models.CharField(max_length=255,
                                          null=True,
                                          blank=True)
    generic_name = models.CharField(max_length=255,
                                    null=True,
                                    blank=True,
                                    help_text=generic_name_help)
    specific_epithet = models.CharField(max_length=255,
                                        null=True,
                                        blank=True,
                                        help_text=specific_epithet_help)
    authorship = models.CharField(max_length=255,
                                  null=True,
                                  blank=True,
                                  help_text=authorship_help)
    year = models.IntegerField('Authorship Year',
                               null=True,
                               blank=True,
                               help_text=year_help)
    authorship_reference_obj = models.ForeignKey(
        publications.models.Publication,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='name_reference')
    taxon_rank_obj = models.ForeignKey('TaxonRank',
                                       null=True,
                                       blank=True,
                                       on_delete=models.SET_NULL)
    taxon_rank_group = models.CharField(max_length=255,
                                        null=True,
                                        blank=True,
                                        choices=TAXON_RANK_GROUP_CHOICES,
                                        default='species-group')
    nomenclatural_code = models.CharField('Nom. Code',
                                          max_length=255,
                                          null=True,
                                          blank=True,
                                          choices=NOMENCLATURAL_CODE_CHOICES,
                                          default='ICZN')
    nomenclatural_status = models.CharField(
        'Nom. Status',
        max_length=255,
        null=True,
        blank=True,
        choices=NOMENCLATURAL_STATUS_CHOICES)
    type_specimen_label = models.CharField(max_length=255,
                                           null=True,
                                           blank=True,
                                           help_text=type_help)
    type_specimen = models.ForeignKey('Fossil',
                                      null=True,
                                      blank=True,
                                      on_delete=models.SET_NULL,
                                      help_text=type_object_help)
    paratypes = models.TextField(null=True, blank=True)
    type_taxon = models.CharField(max_length=255, null=True, blank=True)

    bc_status = models.CharField('BC Status',
                                 max_length=255,
                                 null=True,
                                 blank=True,
                                 choices=BC_STATUS_CHOICES)
    is_available = models.BooleanField('Available', default=False)
    is_potentially_valid = models.BooleanField('Pot. Valid', default=False)
    is_objective_synonym = models.BooleanField('Objective Synonym',
                                               default=False)
    is_subjective_synonym = models.BooleanField('Subjective Synonym',
                                                default=False)
    is_established = models.BooleanField('Established', default=False)

    references = models.ManyToManyField(publications.models.Publication,
                                        blank=True)
    assigned_to = models.CharField('Assigned',
                                   max_length=255,
                                   null=True,
                                   blank=True,
                                   choices=VERIFIER_CHOICES)
    verified_by = models.CharField('Verified',
                                   max_length=255,
                                   null=True,
                                   blank=True,
                                   choices=VERIFIER_CHOICES)
    verified_date = models.DateField(
        null=True,
        blank=True)  # used to control visibility on nomen detail page

    def authorship_reference(self):
        """
        Get a basic reference as plain text. Handles articles, books and book chapters.
        :return:
        """
        citation_text = ""
        pub_obj = self.authorship_reference_obj  # publication object
        try:
            authors = pub_obj.authors
            year = pub_obj.year
            article_title = pub_obj.title
            journal_title = pub_obj.journal
            volume = pub_obj.volume
            pages = pub_obj.pages
            book_title = pub_obj.book_title
            publisher = pub_obj.publisher

            # Publication types are:
            # ['Journal', 'Conference', 'Technical Report',
            # 'Book', 'Book Chapter', 'Abstract', 'Thesis', 'Unpublished', 'Patent']
            # Publication bibtex types are:
            # ['article', 'inproceedings', 'techreport', 'book', 'inbook', 'abstract', 'phdthesis', 'unpublished', 'patent']
            if pub_obj.type.type in ['article', 'Journal']:
                citation_text = f'{authors}. {pub_obj.year}. {article_title}. {journal_title}. {volume}: {pages}.'
            elif pub_obj.type.type in ['book', 'Book', 'Thesis']:
                citation_text = f'{authors}. {year}. {book_title}. {publisher}.'
            elif pub_obj.type.type in [
                    'incollection', 'inproceedings', 'inbook', 'Book Chapter'
            ]:
                citation_text = f'{authors}. {year}. {article_title} In: {book_title}. {publisher}. pp. {pages}.'
        except AttributeError:
            pass
        return citation_text

    def authorship_reference_id(self):
        """
        Get the unique doi identifier for the reference publication
        :return:
        """
        doi = None
        try:
            doi = self.authorship_reference_obj.doi
        except AttributeError:
            pass
        return doi

    def from_ttaxon(self, ttaxon):
        """
        Create a nomen from a ttaxon instance
        :param ttaxon:
        :return:
        """
        self.name = ttaxon.name
        self.date_created = ttaxon.date_created
        self.date_last_modified = ttaxon.date_last_modified
        self.problem = ttaxon.problem
        self.problem_comment = ttaxon.problem_comment
        self.remarks = ttaxon.remarks
        self.authorship = ttaxon.authorship
        self.year = ttaxon.year
        self.rank = ttaxon.rank
        self.type_specimen = ttaxon.type_specimen
        self.type_status = ttaxon.type_status
        self.paratypes = ttaxon.paratypes
        self.nomenclatural_status = ttaxon.nomenclatural_status
        self.name_reference = ttaxon.name_reference
        self.save()
        self.references.add(*ttaxon.references.all())
        self.save()

    # Note that full scientific names have authorship separated from the genus and species with no punctuation
    # Date is separated from author by a comma. If three or more authors then names can be truncated with et al.
    # See ICZN Article 51.2, Also note that Campbell (1965) does not follow ICZN 4e.
    def scientific_name(self):
        """
        Get the full scientific name with authorship as plain text
        :return:
        """
        scientific_name_string = ''
        if self.name:
            scientific_name_string = self.name
            if self.authorship:
                scientific_name_string += f' {self.authorship}'
        return scientific_name_string

    def full_name_html(self):
        """
        Get the full scientific name formatted as html
        :return:
        """
        full_name_html_string = ''
        if self.name:
            full_name_html_string = f'<i>{self.name}</i>'
            if self.authorship:
                full_name_html_string += f' {self.authorship}'
        return mark_safe(full_name_html_string)

    def scientific_name_html(self):
        """
        alternate named method for full_name_html  to be consistent with scientific name
        :return:
        """
        return self.full_name_html()

    def authorship_year(self):
        return self.year

    def taxon_rank_label(self):
        label = ''
        if self.taxon_rank_obj:
            label = self.taxon_rank_obj.name
        return label

    def type_status(self):
        type_status = None
        try:
            type_status = self.type_specimen.type_status
        except AttributeError:
            pass
        return type_status

    def objective_junior_synonyms(self):
        """
        Get objective junior synonyms associated with this nomen
        :return: Returns None or a queryset of Nomina
        """
        if self.is_objective_synonym:
            result = None
        else:
            try:
                type_obj = self.type_object  # First get the type specimen fossil object assoc. with this nomen
                # from the type get the assoc. nomina that point to it, excluding this name.
                result = type_obj.nomen_set.exclude(pk=self.id)
            except AttributeError:  # if nomen has no type object, raises Attribute error.
                result = None
        return result

    def __str__(self):
        unicode_string = '[' + str(self.id) + ']'
        if self.name:
            unicode_string = unicode_string + ' ' + self.scientific_name()
        return unicode_string

    class Meta:
        ordering = ['name']
        verbose_name = 'Nomen'
        verbose_name_plural = 'Nomina'

    # Wagtail
    panels = [
        FieldPanel('title', classname="full title"),
        FieldPanel('subtitle', classname="full title"),
        FieldPanel('intro', classname="full"),
        StreamFieldPanel('body'),
        FieldPanel('template_string'),
        InlinePanel('related_links', label="Related links"),
    ]
Ejemplo n.º 30
0
class price_change(models.Model):
    Property = models.ForeignKey(Property, on_delete=models.CASCADE)
    proposed_price = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        help_text="The proposed new price for the property",
        null=False)
    notes = models.CharField(max_length=1024, blank=True)
    # meeting is the PriceChangeMeetingLink accessor
    datestamp = models.DateField(auto_now_add=True)
    approved = models.NullBooleanField()
    acquisition_date = models.DateField(null=True)
    assessed_land_value = models.IntegerField(null=True)
    assessed_improvement_value = models.IntegerField(null=True)
    cma = models.FileField(upload_to=price_change_directory_path,
                           null=True,
                           blank=True)
    make_fdl_eligible = models.BooleanField(default=False)

    @property
    def inquiries_previous_30_days(self):
        end_day = datetime.date.today()
        start_day = end_day - datetime.timedelta(30)
        return apps.get_model(
            'property_inquiry',
            'propertyInquiry').objects.filter(Property=self.Property).filter(
                timestamp__range=(start_day, end_day)).count()

    @property
    def inquiries_previous_60_days(self):
        end_day = datetime.date.today()
        start_day = end_day - datetime.timedelta(60)
        return apps.get_model(
            'property_inquiry',
            'propertyInquiry').objects.filter(Property=self.Property).filter(
                timestamp__range=(start_day, end_day)).count()

    @property
    def inquiries_previous_90_days(self):
        end_day = datetime.date.today()
        start_day = end_day - datetime.timedelta(90)
        return apps.get_model(
            'property_inquiry',
            'propertyInquiry').objects.filter(Property=self.Property).filter(
                timestamp__range=(start_day, end_day)).count()

    @property
    def inquiries_previous_180_days(self):
        end_day = datetime.date.today()
        start_day = end_day - datetime.timedelta(180)
        return apps.get_model(
            'property_inquiry',
            'propertyInquiry').objects.filter(Property=self.Property).filter(
                timestamp__range=(start_day, end_day)).count()

    def __str__(self):
        return '{0} - {1} - {2}'.format(self.Property, self.datestamp,
                                        self.proposed_price)

    class Meta:
        verbose_name = 'price change'
        verbose_name_plural = 'price changes'