def forwards(self, orm):
     GeoManager().contribute_to_class(orm.Shape, "objects")
     GeoManager().contribute_to_class(orm.ShapePoint, "objects")
     for shape in orm.Shape.objects.all():
         if shape.points.count() >= 2:
             points = orm.ShapePoint.objects.filter(
                 shape=shape).order_by('sequence').values_list('point',
                                                               flat=True)
             ls = 'LINESTRING (' + ', '.join(
                 ['%s %s' % pt.coords for pt in points]) + ')'
             shape.geometry = ls
             shape.save()
Exemplo n.º 2
0
 def forwards(self, orm):
     GeoManager().contribute_to_class(orm.Route, "objects")
     GeoManager().contribute_to_class(orm.Trip, "objects")
     for route in orm.Route.objects.all():
         trips = orm.Trip.objects.filter(route=route).exclude(geometry=None)
         if trips.exists():
             ls = []
             for trip in trips:
                 ls.append('(' + ', '.join(
                     ['%s %s' % pt for pt in trip.geometry.coords]) + ')')
             mls = 'MULTILINESTRING(' + ','.join(ls) + ')'
             route.geometry = mls
             route.save()
Exemplo n.º 3
0
class Incidence(models.Model):
    name = models.CharField(max_length=255)
    location = gis_models.PointField(srid=4326)
    objects = GeoManager()

    def __str__(self):
        return self.name
Exemplo n.º 4
0
class StoreStock(models.Model):

    store = models.ForeignKey(
        'stores.Store',
        verbose_name=_("Store"),
        related_name='stock'
    )
    product = models.ForeignKey(
        'catalogue.Product',
        verbose_name=_("Product"),
        related_name="store_stock"
    )
    # Stock level information
    num_in_stock = models.PositiveIntegerField(
        _("Number in stock"),
        default=0,
        blank=True,
        null=True
    )

    # The amount of stock allocated in store but not fed back to the master
    num_allocated = models.IntegerField(
        _("Number allocated"),
        default=0,
        blank=True,
        null=True
    )

    location = models.CharField(
        _("In store location"),
        max_length=50,
        blank=True,
        null=True
    )

    # Date information
    date_created = models.DateTimeField(
        _("Date Created"),
        auto_now_add=True
    )
    date_updated = models.DateTimeField(
        _("Date Updated"),
        auto_now=True,
        db_index=True
    )

    class Meta:
        verbose_name = _("Store Stock Record")
        verbose_name_plural = _("Store Stock Records")

    objects = GeoManager()  # Needed for distance queries against stores

    def __unicode__(self):
        if self.store and self.product:
            return "%s @ %s" % (self.product.title, self.store.name)
        return "Store Stock"

    @property
    def is_available_to_buy(self):
        return self.num_in_stock > self.num_allocated
Exemplo n.º 5
0
class LogEntryBase(models.Model):
    """
    Abstract base model for Geotrack log entry.
    """

    # Hard-coding this as an integer field for simplicity for the moment.
    unit_id = models.PositiveIntegerField(db_index=True)

    timestamp = models.DateTimeField(
        db_index=True, help_text='Date/time when the measurement was taken.')
    location = LocationField()
    added = models.DateTimeField(
        default=datetime.now,
        help_text='When the log entry arrived in the system')

    objects = GeoManager()

    class Meta:
        abstract = True
        ordering = 'timestamp',

    def save(self, **kwargs):
        super(LogEntryBase, self).save(**kwargs)
        self.update_last_known_position()

    def update_last_known_position(self):
        data = dict(timestamp=self.timestamp, location=self.location)

        last_pos, created = LastKnownPosition.objects.get_or_create(
            unit_id=self.unit_id, defaults=data)

        if not created and last_pos.timestamp < self.timestamp:
            for name, val in data.items():
                setattr(last_pos, name, val)
            last_pos.save()
Exemplo n.º 6
0
class Checkin(models.Model):
    seller_name = models.CharField(max_length=255, verbose_name='Your name')
    point = PointField(blank=True)
    time = models.DateTimeField(auto_now=True)
    expiry = models.DateTimeField()
    expiry_offset = models.IntegerField(verbose_name='For how long?',
                                        default=3600,
                                        choices=(
                                            (3600, u'1 Hour'),
                                            (7200, u'2 Hours'),
                                            (10800, u'3 Hours'),
                                            (14400, u'4 Hours'),
                                        ))
    items = models.ManyToManyField(Item)
    notes = models.TextField(
        help_text='Any additional information you would like to share.')

    objects = GeoManager()

    class Meta:
        ordering = ('-time', )

    def __unicode__(self):
        return self.seller_name

    def save(self, *args, **kwargs):
        self.expiry = datetime.now() + timedelta(0, self.expiry_offset)
        super(Checkin, self).save(*args, **kwargs)
Exemplo n.º 7
0
class PaintingFeature(Feature, BuiltFormFeature):
    """
        Represents a feature that can be "painted" in the API
        TODO replace this by means of a Behavior
    """
    objects = GeoManager()

    dev_pct = models.DecimalField(max_digits=8,
                                  decimal_places=4,
                                  default=1.0000)
    density_pct = models.DecimalField(max_digits=8,
                                      decimal_places=4,
                                      default=1.0000)
    gross_net_pct = models.DecimalField(max_digits=8,
                                        decimal_places=4,
                                        default=1.0000)

    clear_flag = models.BooleanField(default=False)
    dirty_flag = models.BooleanField(default=False)

    developable_proportion = models.DecimalField(max_digits=8,
                                                 decimal_places=4,
                                                 default=1)
    acres_developable = models.DecimalField(max_digits=14,
                                            decimal_places=4,
                                            default=0)

    class Meta(object):
        abstract = True
        app_label = 'main'
Exemplo n.º 8
0
class Airport(models.Model):
    name = models.CharField(_("name"), max_length=100)

    iata = models.CharField(_("IATA/FAA code"),
                            blank=True,
                            max_length=3,
                            validators=[MinLengthValidator(3)],
                            db_index=True,
                            primary_key=True
                            )

    icao = models.CharField(_("ICAO code"),
                            blank=True,
                            max_length=4,
                            validators=[MinLengthValidator(4)]
                            )

    altitude = models.FloatField(_("altitude"), default=0)
    location = models.PointField(_("location"))

    country = models.ForeignKey('cities.Country', on_delete=models.DO_NOTHING, null=True)
    city = models.ForeignKey('cities.City', on_delete=models.DO_NOTHING, null=True)

    objects = GeoManager()

    class Meta:  # pylint: disable=C1001
        ordering = ['iata']

    def __str__(self):
        return force_text(self.name)
Exemplo n.º 9
0
class Place(models.Model):
    name = models.CharField(max_length=200, db_index=True, verbose_name="ascii name")
    alt_names = models.ManyToManyField(swapper.get_model_name('cities', 'AlternativeName'))
    perimeter = models.MultiPolygonField(null=True, blank=True)

    objects = GeoManager()

    class Meta:
        abstract = True

    @property
    def hierarchy(self):
        """Get hierarchy, root first"""
        lst = self.parent.hierarchy if self.parent else []
        lst.append(self)
        return lst

    def get_absolute_url(self):
        return "/".join([place.slug for place in self.hierarchy])

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

    def save(self, *args, **kwargs):
        if hasattr(self, 'clean'):
            self.clean()
        super(Place, self).save(*args, **kwargs)
Exemplo n.º 10
0
class GeometryModel(models.Model):
    name = models.CharField(max_length=255)
    geometry = GeometryField(srid=settings.SRID)

    objects = GeoManager()

    def __str__(self):
        return self.name
Exemplo n.º 11
0
class Place(models.Model):
    name = models.CharField(max_length=200)
    listening_to = models.CharField(max_length=10, blank=True)
    public = models.CharField(max_length=3, blank=True)

    objects = GeoManager()

    def __unicode__(self):
        return self.name
Exemplo n.º 12
0
class LastKnownPosition(models.Model):
    """
    De-normalization to speed up last position lookups.
    """
    unit_id = models.PositiveIntegerField(unique=True)
    timestamp = models.DateTimeField(db_index=True)
    location = LocationField()
    modified_on = models.DateTimeField(auto_now=True)

    objects = GeoManager()
 def forwards(self, orm):
     GeoManager().contribute_to_class(orm.Trip, "objects")
     GeoManager().contribute_to_class(orm.Stop, "objects")
     GeoManager().contribute_to_class(orm.Shape, "objects")
     for trip in orm.Trip.objects.all():
         if trip.shape_id:
             shape = orm.Shape.objects.get(id=trip.shape_id)
             trip.geometry = shape.geometry
             trip.save()
         else:
             stoptimes = trip.stoptime_set.order_by('stop_sequence')
             if stoptimes.count() > 1:
                 points = []
                 for st in stoptimes.all():
                     stop = orm.Stop.objects.get(id=st.stop_id)
                     points.append(stop.point.coords)
                 ls = 'LINESTRING (' + ', '.join(['%s %s'%pt for pt in points]) + ')'
                 trip.geometry = ls
                 trip.save()
Exemplo n.º 14
0
class Location(models.Model):
    name = models.CharField(max_length=255, null=False, blank=False)
    location = PointField(null=True, blank=False, geography=True)
    date = models.DateField(blank=True, null=True)
    date_time = models.DateTimeField(blank=True, null=True)

    objects = GeoManager()

    def __unicode__(self):
        return self.name
Exemplo n.º 15
0
class Parada(models.Model):
    objects = GeoManager()

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    token = models.ForeignKey(Token, related_name='paradas')
    nome = models.CharField(max_length=100, null=True, blank=True)
    avaliacao = models.IntegerField(default=0, null=False)
    local = PointField(null=False)
    comentario = models.TextField(null=True, blank=True)
    foto = models.TextField(null=True, blank=True)
Exemplo n.º 16
0
class PermitArea(models.Model):
    '''Stores information about a single permit'''
    # The region field stores the geometric shape(s) of the permit
    region = models.MultiPolygonField(srid=4326, blank=False)
    # We need the category in order to color the map
    #category = models.CharField(max_length=1024, blank=False)
    category = models.CharField(max_length=7,
                                choices=((SITE_SUBPLAN, SITE_SUBPLAN),
                                         (REZONE, REZONE)),
                                blank=False)
    # What township contains this region?
    township = models.CharField(max_length=4,
                                choices=((CARY, CARY), (APEX, APEX)),
                                blank=False)

    # Keep track of when we've seen this field
    first_seen = models.DateField()
    last_seen = models.DateField()

    # This manager is what allows us to make GIS queries (such as
    # contains, overlap, bbcontains, etc.). It must be the main
    # manager on this model type or we cannot make these queries.
    objects = GeoManager()

    def get_timeline_data(self):
        result = dict([(field, []) for field in PermitData.VALUE_FIELDS])
        result['info_link'] = []
        for row in self.data.all().order_by('-saved_on'):
            for field in PermitData.VALUE_FIELDS:
                value = getattr(row, field)
                if value is not None:
                    result[field].append({
                        'value': value,
                        'date': row.saved_on.isoformat()
                    })
            if (row.info_link is not None):
                result['info_link'].append(row.info_link.to_dict())
        return result

    def to_dict(self):
        centroid = self.region.centroid
        return {
            'first_seen': self.first_seen.isoformat(),
            'last_seen': self.last_seen.isoformat(),
            'centroid': [centroid.y, centroid.x],
            'data': self.get_timeline_data(),
            'category': self.category,
            'township': self.township,
            'id': self.id
        }
Exemplo n.º 17
0
class VKUser(Model):
    vk_id = CharField(max_length=100, primary_key=True, unique=True)
    vk_token = CharField(max_length=400)
    phone = CharField(max_length=50, blank=True)
    is_phone_confirmed = BooleanField(default=False)
    email = TextField(blank=True)
    is_email_confirmed = BooleanField(default=False)
    auth_token = UUIDField(default=uuid4, editable=True)
    create_datetime = DateTimeField(auto_now_add=True)

    city = CharField(max_length=400, null=True, blank=True, default=None)
    point = PointField(null=True, blank=True, default=None)
    objects = GeoManager()

    def __str__(self):
        return str(self.vk_id)
Exemplo n.º 18
0
class PermitData(models.Model):
    # Attach this PermitData object to a specific PermitArea object
    owner = models.ForeignKey(PermitArea, related_name='data')

    # These are basic fields supported by all the municipalities that we
    # currently pull data from. They are all character fields.
    name = models.CharField(max_length=1024, null=True)
    proj_id = models.CharField(max_length=1024, null=True)
    #link = models.CharField(max_length=1024, null=True)
    info_link = models.ForeignKey(InfoLink, null=True)
    status = models.CharField(max_length=1024, null=True)
    comment = models.TextField(null=True)
    # We also store this here in case it changes over time.
    # Having it here also gives us full text search on category
    category = models.CharField(max_length=1024, null=True)

    # Date on which the values in this row were captured
    saved_on = models.DateField()

    # We must use a GeoManager because of our foreign key relation to the
    # PermitArea object. Otherwise we'll get errors.
    objects = GeoManager()

    VALUE_FIELDS = ('name', 'comment', 'proj_id', 'status', 'category')

    # In order to support full text search, we have a SECOND model
    # that allows for that access pattern. Attempts to use the GIS
    # mixin that is available in the pgfulltext module failed
    # miserably, so we go with this route for now. The main drawback
    # is that we must manually update the search fields on save
    # because this is not the default manager. That's not too terrible,
    # however, because we only ever save from one place inside kmlutils.py.
    search_index = VectorField()
    text = SearchManager(
        # List all the fields that you want indexed
        fields=VALUE_FIELDS,
        # This may be redundant now. Not sure.
        auto_update_search_field=False)

    @classmethod
    def create_query_dict(cls, area, data_dict):
        for field in PermitData.VALUE_FIELDS:
            if field not in data_dict:
                data_dict[field] = None
        data_dict['owner'] = area
        return data_dict
Exemplo n.º 19
0
class Flatshare(models.Model):
    token = models.CharField(max_length=20, default=generate_flatshare_token)
    admin = models.ForeignKey(User)
    name = models.CharField(max_length=50, blank=True, null=True)
    size = models.PositiveIntegerField()
    max_guests = models.PositiveIntegerField(validators=[MinValueValidator(2)])
    address = models.CharField(max_length=200)
    location = PointField()

    latest_pairing = models.ForeignKey('pairings.Pairing',
                                       blank=True,
                                       null=True,
                                       on_delete=models.SET_NULL)

    objects = GeoManager()

    def __unicode__(self):
        return unicode(self.id)
Exemplo n.º 20
0
class Facility(models.Model):
    category = models.ForeignKey(FacilityCategory)
    name = models.CharField(max_length=255, help_text='If the facility has a specific name', blank=True, null=True)
    description = models.TextField(blank=True)
    location = models.PointField(unique=True)
    
    # Important - it deals with the location stuff
    objects = GeoManager()
    
    def __unicode__(self):
        string = "Facility %d, %s" % (self.pk, self.category) 
        if self.name:
            string += ": %s" % self.name
        return string        

    class Meta:
        app_label = 'facilities'
        verbose_name_plural = 'facilities'
Exemplo n.º 21
0
class Spot(models.Model):
    DANGER_LEVEL_CHOICES = [(i,i) for i in range(1, 11)]
    SKILL_LEVEL_CHOICES = [(i,i) for i in range(1, 11)]

    user = models.ForeignKey(User, related_name="spots")
    primary_photo = models.FileField(upload_to="primary-photos/")
    title = models.CharField(max_length=250)
    description = models.CharField(max_length=1000, null=True)
    skill_level = models.SmallIntegerField(choices=SKILL_LEVEL_CHOICES, null=True)
    danger_level = models.SmallIntegerField(choices=DANGER_LEVEL_CHOICES, null=True)
    family_safe = models.NullBooleanField(null=True)
    location = LineStringField()
    feature_types = models.ManyToManyField(FeatureType, related_name="spots", null=True)
    activity_types = models.ManyToManyField(ActivityType, related_name="spots", null=True)
    created_at = models.DateTimeField(default=timezone.now)
    objects = GeoManager()

    def __unicode__(self):
        return self.title
Exemplo n.º 22
0
class Route(models.Model):
    title = models.TextField()
    external_id = models.IntegerField()
    route_type = models.CharField(max_length=100, choices=TYPES)
    route_loop = models.BooleanField()
    technical_difficulty = models.IntegerField(choices=DIFFICULTIES)
    route_length = models.FloatField()
    route_uphill = models.FloatField()
    route_downhill = models.FloatField()
    route_height = models.FloatField()
    route_low = models.FloatField()
    time = models.CharField(max_length=100, null=True, blank=True)
    coordinates = models.CharField(max_length=100, null=True, blank=True)
    upload_date = models.CharField(max_length=100, null=True, blank=True)
    recorded_date = models.CharField(max_length=100, null=True, blank=True)
    stars = models.IntegerField(null=True)
    start_point = PointField()
    line = LineStringField()
    objects = GeoManager()
Exemplo n.º 23
0
class GeoLocation(models.Model):
    """
    La localisation géographique d'une ressource
    """
    # Entry associated address
    address = models.CharField(max_length=200,
                               verbose_name=__('Adresse'),
                               help_text=__("L'adresse postale du lieu"))
    # Entry associated location
    location = PointField(editable=False,
                          verbose_name=__(u'Coordonnées'),
                          help_text=__(u"Les coordonnées GPS du lieu"))
    # manager
    objects = GeoManager()

    def save(self, *args, **kwargs):
        g = geocoders.Nominatim()  # this should be changed to openstreetmap
        try:
            place, (lat, lng) = g.geocode(self.address)
            self.location = fromstr("POINT(%s %s)" % (lng, lat))
            self.address = place
        except geopy.exc.GeocoderServiceError:
            self.location = fromstr("POINT(0 0)")
            print "WARNING: could not geocode %s !!" % self.address
        super(GeoLocation, self).save(*args, **kwargs)

    @staticmethod
    def make_from_slug(slug):
        g = geocoders.Nominatim()  # this should be changed to openstreetmap
        m = re_latitude_longitude.match(slug)
        lat = m.group(1)
        lng = m.group(2)
        location = fromstr("POINT(%s %s)" % (lng, lat))
        address = g.reverse("%s, %s" % (lat, lng), exactly_one=1)
        return GeoLocation(address=address, location=location)

    @property
    def slug(self):
        return "%s, %s" % (self.location.get_x(), self.location.get_y())

    def __unicode__(self):
        return self.address
Exemplo n.º 24
0
class CallForTenders(models.Model):

    title = models.CharField(_(u'title'), max_length=200)
    activity = models.ManyToManyField('coop_local.ActivityNomenclature',
                                      verbose_name=_(u'activity sector'))
    organization = models.ForeignKey('Organization',
                                     verbose_name=_('organization'))
    areas = models.ManyToManyField('coop_local.Area',
                                   verbose_name=_(u'execution locations'),
                                   blank=True,
                                   null=True)
    allotment = models.BooleanField(_(u'allotment'))
    lot_numbers = models.CharField(_(u'lot numbers'),
                                   max_length=200,
                                   blank=True,
                                   help_text=u'Séparés par une virgule')
    deadline = models.DateTimeField(_(u'deadline'))
    clauses = MultiSelectField(_(u'clauses (si marché public)'),
                               max_length=200,
                               choices=CLAUSE_CHOICES,
                               blank=True)
    url = models.URLField(u'URL', blank=True, null=True, max_length=250)
    en_direct = models.BooleanField(u'en direct', default=False)
    description = models.TextField(u'description synthétique', blank=True)

    objects = models.Manager()
    geo_objects = GeoManager()

    def __unicode__(self):

        return self.title

    def get_absolute_url(self):
        return '/appels-doffres/p/%u/' % self.id

    def activities(self):
        return ", ".join(self.activity.values_list('label', flat=True))

    class Meta:
        verbose_name = _(u'Call for tenders')
        verbose_name_plural = _(u'Calls for tenders')
        app_label = 'coop_local'
Exemplo n.º 25
0
class ProposedNews(Model):
    id = AutoField(primary_key=True)
    author = ForeignKey(VKUser,
                        on_delete=CASCADE,
                        null=True,
                        blank=True,
                        default=None)
    description = TextField()
    source_post = CharField(max_length=200,
                            blank=True,
                            default=None,
                            null=True)
    vk_id_reference = CharField(max_length=200,
                                blank=True,
                                default=None,
                                null=True)
    validate_status = CharField(max_length=200,
                                choices=ValidateStatus,
                                default=ValidateStatus[0][1])
    validate_message = TextField(blank=True)
    cash = FloatField(default=0, blank=True)
    create_datetime = DateTimeField(auto_now_add=True)

    city = CharField(max_length=400, null=True, blank=True, default=None)
    point = PointField(null=True, blank=True, default=None)
    objects = GeoManager()

    def vk_url(self):
        if self.vk_id_reference:
            return "https://vk.com/wall{}_{}".format(LENTACH_ID,
                                                     self.vk_id_reference)
        return None

    def photo(self):
        news_photos = NewsPhoto.objects.filter(proposed_news=self)
        return "{}{}".format(CURRENT_DOMAIN,
                             news_photos[0].photo.url) if news_photos else None

    def __str__(self):
        return str(self.id)
Exemplo n.º 26
0
class UserProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,
                                unique=True,
                                verbose_name=_('user'),
                                related_name="userprofile")
    phone = models.IntegerField(_('phone'), null=True, blank=True)
    celular = models.IntegerField(_('mobile'), null=True, blank=True)
    state = models.CharField(_('state'), max_length=30, blank=True)
    city = models.CharField(_('city'), max_length=30, blank=True)
    image = StdImageField(_('image'),
                          upload_to='statics/image_profile/',
                          blank=True,
                          variations={
                              'large': (470, 470),
                              'thumbnail': (80, 80, True),
                              'small': (180, 180, True)
                          })
    zipcode = models.IntegerField(_('zipcode'), null=True, blank=True)
    adress = models.CharField(_('address'), max_length=50, blank=True)
    terms = models.BooleanField(_('terms'), default=False)
    welcome = models.BooleanField(default=False)
    categories = models.ManyToManyField(Category)
    coords = PointField(null=True)
    objects = GeoManager()
Exemplo n.º 27
0
class MapEntity(Model):

    # entityName = CharField(max_length=60, help_text="Insert name here")
    entityType = CharField(max_length=60, help_text="Insert name here")
    # entityType = ForeignKey(EventType, help_text="What type of event is it?")

    # entityDescription = TextField(max_length=300, help_text="Very awesome party at my place")
    owner = ForeignKey(User, on_delete=CASCADE)
    publishDate = DateTimeField(null=False, auto_now_add=True)
    # lastModDate = DateTimeField(null=True, auto_now=True)

    # uuid = UUIDField(default=uuid.uuid4, editable=False)

    geoLocationField = PointField(srid=4326)
    objects = GeoManager()

    def setLocationField(self, lat, lng):
        self.geoLocationField = GEOSGeometry('POINT(' + str(lng) + ' ' +
                                             str(lat) + ')',
                                             srid=4326)

    # json encode maybe?!
    def __str__(self):
        return str(self.entityType + ":::" + str(self.geoLocationField))
Exemplo n.º 28
0
class PostalCode(Place, SlugModel):
    slug_contains_id = True

    code = models.CharField(max_length=20)
    location = PointField()

    country = models.ForeignKey(swapper.get_model_name('cities', 'Country'),
                                related_name='postal_codes',
                                on_delete=SET_NULL_OR_CASCADE)

    # Region names for each admin level, region may not exist in DB
    region_name = models.CharField(max_length=100, db_index=True)
    subregion_name = models.CharField(max_length=100, db_index=True)
    district_name = models.CharField(max_length=100, db_index=True)

    region = models.ForeignKey(Region,
                               blank=True,
                               null=True,
                               related_name='postal_codes',
                               on_delete=SET_NULL_OR_CASCADE)
    subregion = models.ForeignKey(Subregion,
                                  blank=True,
                                  null=True,
                                  related_name='postal_codes',
                                  on_delete=SET_NULL_OR_CASCADE)
    city = models.ForeignKey(swapper.get_model_name('cities', 'City'),
                             blank=True,
                             null=True,
                             related_name='postal_codes',
                             on_delete=SET_NULL_OR_CASCADE)
    district = models.ForeignKey(District,
                                 blank=True,
                                 null=True,
                                 related_name='postal_codes',
                                 on_delete=SET_NULL_OR_CASCADE)

    objects = GeoManager()

    class Meta:
        unique_together = (
            ('country', 'region', 'subregion', 'city', 'district', 'name', 'id', 'code'),
            ('country', 'region_name', 'subregion_name', 'district_name', 'name', 'id', 'code'),
        )

    @property
    def parent(self):
        return self.country

    @property
    def name_full(self):
        """Get full name including hierarchy"""
        return force_text(', '.join(reversed(self.names)))

    @property
    def names(self):
        """Get a hierarchy of non-null names, root first"""
        return [e for e in [
            force_text(self.country),
            force_text(self.region_name),
            force_text(self.subregion_name),
            force_text(self.district_name),
            force_text(self.name),
        ] if e]

    def __str__(self):
        return force_text(self.code)

    def slugify(self):
        if self.id:
            return '{}-{}'.format(self.id, unicode_func(self.code))
        return None
Exemplo n.º 29
0
class Organization(models.Model):
    name = models.CharField("Organization Name", max_length=255)
    type = models.ForeignKey(OrganizationType,
                             verbose_name='Type of Organization')
    phone = models.CharField("Contact Number",
                             max_length=255,
                             blank=True,
                             null=True)
    fax = models.CharField(max_length=255, blank=True, null=True)
    email = models.EmailField(blank=True, null=True)
    website = models.URLField(blank=True, null=True)
    country = models.CharField(max_length=3, choices=COUNTRIES, default=u'NPL')
    address = models.TextField(blank=True, null=True)
    public_desc = models.TextField("Public Description", blank=True, null=True)
    additional_desc = models.TextField("Additional Description",
                                       blank=True,
                                       null=True)
    logo = models.ImageField(upload_to="logo",
                             default="logo/default_org_image.jpg")
    is_active = models.BooleanField(default=True)
    location = PointField(
        geography=True,
        srid=4326,
        blank=True,
        null=True,
    )
    date_created = models.DateTimeField(auto_now_add=True, blank=True)
    logs = GenericRelation('eventlog.FieldSightLog')

    class Meta:
        ordering = [
            '-is_active',
            'name',
        ]

    def __unicode__(self):
        return u'{}'.format(self.name)

    objects = GeoManager()

    @property
    def latitude(self):
        if self.location:
            return self.location.y

    @property
    def longitude(self):
        if self.location:
            return self.location.x

    def getname(self):
        return self.name

    @property
    def status(self):
        if self.organization_instances.filter(form_status=1).count():
            return 1
        elif self.organization_instances.filter(form_status=2).count():
            return 2
        elif self.organization_instances.filter(form_status=0).count():
            return 0
        elif self.organization_instances.filter(form_status=3).count():
            return 3
        return 4

    def get_organization_submission(self):
        instances = self.organization_instances.all().order_by('-date')
        outstanding, flagged, approved, rejected = [], [], [], []
        for submission in instances:
            if submission.form_status == 0:
                outstanding.append(submission)
            elif submission.form_status == 1:
                rejected.append(submission)
            elif submission.form_status == 2:
                flagged.append(submission)
            elif submission.form_status == 3:
                approved.append(submission)

        return outstanding, flagged, approved, rejected

    def get_submissions_count(self):
        from onadata.apps.fsforms.models import FInstance
        outstanding = FInstance.objects.filter(project__organization=self,
                                               project__is_active=True,
                                               form_status=0).count()
        rejected = FInstance.objects.filter(project__organization=self,
                                            project__is_active=True,
                                            form_status=1).count()
        flagged = FInstance.objects.filter(project__organization=self,
                                           project__is_active=True,
                                           form_status=2).count()
        approved = FInstance.objects.filter(project__organization=self,
                                            project__is_active=True,
                                            form_status=3).count()

        return outstanding, flagged, approved, rejected

    def get_absolute_url(self):
        return reverse('fieldsight:organizations-dashboard',
                       kwargs={'pk': self.pk})

    @property
    def get_staffs(self):
        staffs = self.organization_roles.filter(
            group__name="Organization Admin").values_list(
                'id', 'user__username')
        return staffs

    @property
    def get_staffs_org(self):
        staffs = self.organization_roles.filter(
            group__name="Organization Admin")
        return staffs

    @property
    def get_staffs_id(self):
        return self.organization_roles.filter(
            group__name="Organization Admin").values_list('id', flat=True)

    def get_organization_type(self):
        return self.type.name
Exemplo n.º 30
0
class BusinessLocation(MetaDataAbstract):
    class Meta:
        unique_together = (("state_fk", "city_fk", "slug_name"),)

    CATEGORY_CHOICES = (
        ('dispensary', 'Dispensary'),
        ('delivery', 'Delivery'),
        ('grow_house', 'Cultivator'),
    )

    DEFAULT_IMAGE_URL = '{base}images/default-location-image.jpeg'.format(base=settings.STATIC_URL)

    STRAIN_INDEX_FIELDS = ['dispensary', 'delivery', 'grow_house', 'delivery_radius', 'lat', 'lng', 'removed_date']

    business = models.ForeignKey(Business, on_delete=models.CASCADE)
    location_name = models.CharField(max_length=255, blank=False, null=False)
    manager_name = models.CharField(max_length=255, blank=True, null=True)
    location_email = models.CharField(max_length=255, blank=True, null=True)

    image = models.ImageField(max_length=255, upload_to=upload_business_location_image_to, blank=True,
                              help_text='Maximum file size allowed is 5Mb',
                              validators=[validate_business_image])

    category = models.CharField(max_length=20, default='dispensary', choices=CATEGORY_CHOICES)

    slug_name = models.SlugField(max_length=611, null=True, blank=True,
                                 help_text='This will be automatically generated from a location name when created')

    primary = models.BooleanField(default=False)
    dispensary = models.BooleanField(default=False)
    delivery = models.BooleanField(default=False)
    grow_house = models.BooleanField(default=False)

    delivery_radius = models.FloatField(max_length=10, blank=True, null=True)
    grow_details = JSONField(default={'organic': False,
                                      'pesticide_free': False,
                                      'indoor': False,
                                      'outdoor': False},
                             blank=True, null=True)

    street1 = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=50)
    zip_code = models.CharField(max_length=10, db_index=True, blank=True)
    timezone = models.CharField(max_length=100, null=True, choices=zip(pytz.common_timezones, pytz.common_timezones))

    city_slug = models.SlugField(max_length=611, null=True, blank=True,
                                 help_text='This will be automatically generated from a city when updated')

    state_fk = models.ForeignKey(State, on_delete=models.DO_NOTHING, null=True, related_name='business_locations')
    city_fk = models.ForeignKey(City, on_delete=models.DO_NOTHING, null=True, related_name='business_locations')

    about = models.TextField(blank=True, null=True, default='')

    lat = models.FloatField(_('Latitude'), blank=True, null=True, max_length=50)
    lng = models.FloatField(_('Longitude'), blank=True, null=True, max_length=50)
    location_raw = JSONField(_('Location Raw JSON'), default={}, blank=True, null=True, max_length=20000)
    geo_location = PointField(geography=True, srid=4326, null=True, db_index=True)

    phone = models.CharField(max_length=15, blank=True, null=True, validators=[phone_number_validator])
    ext = models.CharField(max_length=5, blank=True, null=True)

    verified = models.BooleanField(default=False)
    removed_by = models.CharField(max_length=20, blank=True, null=True)
    removed_date = models.DateTimeField(blank=True, null=True)

    created_date = models.DateTimeField(auto_now_add=True)
    menu_updated_date = models.DateField(null=True)

    mon_open = models.TimeField(blank=True, null=True)
    mon_close = models.TimeField(blank=True, null=True)
    tue_open = models.TimeField(blank=True, null=True)
    tue_close = models.TimeField(blank=True, null=True)
    wed_open = models.TimeField(blank=True, null=True)
    wed_close = models.TimeField(blank=True, null=True)
    thu_open = models.TimeField(blank=True, null=True)
    thu_close = models.TimeField(blank=True, null=True)
    fri_open = models.TimeField(blank=True, null=True)
    fri_close = models.TimeField(blank=True, null=True)
    sat_open = models.TimeField(blank=True, null=True)
    sat_close = models.TimeField(blank=True, null=True)
    sun_open = models.TimeField(blank=True, null=True)
    sun_close = models.TimeField(blank=True, null=True)

    MetaDataAbstract._meta.get_field('meta_title').help_text = _(
        'Leave the field blank to display the default title as '
        '`{ location_name } Dispensary in { city }, { street1 }` for dispensary page and '
        '`{ location_name } Cultivator in { city }, { street1 }` for cultivator page.')
    MetaDataAbstract._meta.get_field('meta_desc').help_text = _(
        'Leave the field blank to display the default description as '
        '`StrainRx brings you the most up to date menu and the latest deals from { location_name } in { city }`')

    objects = GeoManager()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.original_location = {field: getattr(self, field) for field in self.STRAIN_INDEX_FIELDS}
        self.original_location_name = self.location_name

    @property
    def url(self):
        if self.dispensary or self.delivery:
            return reverse('businesses:dispensary_info',
                           kwargs={'state': self.state_fk.abbreviation.lower(), 'city_slug': self.city_fk.full_name_slug,
                                   'slug_name': self.slug_name})
        return reverse('businesses:grower_info',
                       kwargs={'state': self.state_fk.abbreviation.lower(), 'city_slug': self.city_fk.full_name_slug,
                               'slug_name': self.slug_name})

    @property
    def urls(self):
        urls = {}
        kwargs = {
            'state': self.state_fk.abbreviation.lower(),
            'city_slug': self.city_fk.full_name_slug,
            'slug_name': self.slug_name,
        }

        if self.dispensary or self.delivery:
            urls['dispensary'] = reverse('businesses:dispensary_info', kwargs=kwargs)

        if self.grow_house:
            urls['grow_house'] = reverse('businesses:grower_info', kwargs=kwargs)

        return urls

    @property
    def image_url(self):
        # helper to get image url or return default
        if self.image and hasattr(self.image, 'url') and self.image.url:
            return self.image.url
        else:
            return self.DEFAULT_IMAGE_URL

    @property
    def about_or_default(self):
        if self.about:
            return self.about

        types = []
        if self.dispensary:
            types.append('dispensary')
        if self.grow_house:
            types.append('cultivator')
        if self.delivery:
            types.append('delivery')

        if len(types) == 0:
            combined_type = 'business'
        elif len(types) == 1:
            combined_type = types[0]
        elif len(types) == 2:
            combined_type = ' and '.join(types)
        else:
            combined_type = ', '.join(types[:-1]) + ' and ' + types[-1]

        template = '{name} is a Marijuana {combined_type} located in {city}, {state}'
        context = {
            'name': self.location_name,
            'combined_type': combined_type,
            'city': self.city,
            'state': self.state,
        }

        return template.format(**context)

    @property
    def formatted_address(self):
        return ', '.join(filter(None, (self.street1, self.city, self.zip_code, self.state)))

    @property
    def days_since_menu_update(self):
        if not self.menu_updated_date:
            return -1

        return (self.get_current_datetime().date() - self.menu_updated_date).days

    def get_absolute_url(self):
        return self.url

    def can_user_request_menu_update(self, user):
        if not user.is_authenticated():
            return False, 'User has to be logged in'

        if 0 <= self.days_since_menu_update <= 3:
            return False, 'Menu has been updated recently'

        recent_requests = BusinessLocationMenuUpdateRequest.objects.filter(
            business_location=self,
            user=user,
            date_time__gt=datetime.now(pytz.utc) - timedelta(days=1),
        )

        if recent_requests.exists():
            return False, 'You have recently requested a menu update'

        return True, None

    def get_current_datetime(self):
        if not self.timezone:
            timezone = 'UTC'
        else:
            timezone = self.timezone

        return datetime.now(pytz.timezone(timezone))

    def is_searchable(self):
        if self.removed_by or self.removed_date:
            return False

        return self.business.is_searchable

    def save(self, *args, **kwargs):
        if (self.pk is None and not self.slug_name) or (self.pk and self.original_location_name != self.location_name):
            # determine a category
            self.category = 'dispensary' if self.dispensary else 'delivery' if self.delivery else 'dispensary'

            # create a slug name
            slugified_name = slugify(self.location_name)
            slugified_name_and_street = '{0}-{1}'.format(slugify(self.location_name), slugify(self.street1))
            if not exist_by_slug_name(slugified_name):
                self.slug_name = slugified_name
            elif not exist_by_slug_name(slugified_name_and_street):
                self.slug_name = slugified_name_and_street
            else:
                for x in range(1, 1000):
                    new_slug_name = '{0}-{1}'.format(slugified_name_and_street, x)
                    if not exist_by_slug_name(new_slug_name):
                        self.slug_name = new_slug_name
                        break
            self.original_location_name = self.location_name

        if self.city:
            self.city_slug = slugify(self.city)

        self.geo_location = Point(self.lng, self.lat)

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

    def clean(self):
        if not any((self.delivery, self.dispensary, self.grow_house)):
            raise ValidationError('Business Location needs to be one of the '
                                  'following: delivery, dispensary or cultivator.')

    def __str__(self):
        return self.location_name