- import os
- from ast import literal_eval
- from datetime import datetime
- import pytz
- from django.db import models
- from django.conf import settings
- from apps.themes.models import Template
- TIMEZONES = tuple((t, t) for t in pytz.all_timezones)
- WEEKDAY_CHOICES = (
- (0, 'Monday'),
- (1, 'Tuesday'),
- (2, 'Wednesday'),
- (3, 'Thursday'),
- (4, 'Friday'),
- (5, 'Saturday'),
- (6, 'Sunday'),
- )
- class Restaurant(models.Model):
- name = models.CharField(max_length=256)
- sub_name = models.CharField(max_length=128, blank=True, null=True)
- phone = models.CharField(max_length=10)
- address_1 = models.CharField(max_length=256)
- address_2 = models.CharField(max_length=256, null=True, blank=True)
- city = models.CharField(max_length=36)
- state = models.CharField(max_length=2)
- zipcode = models.CharField(max_length=10)
- description = models.TextField()
- timezone = models.CharField(max_length=24, choices=TIMEZONES,
- default=settings.TIME_ZONE)
- subdomain = models.CharField(max_length=128, blank=True, null=True)
- template = models.ForeignKey(Template, blank=True, null=True)
- color_override = models.CharField(max_length=64, blank=True, null=True,
- help_text="To update choices for correct template, you must reload the page after saving the new template.")
- has_own_domain = models.BooleanField(default=False)
- domain_name = models.CharField(max_length=256, blank=True, null=True)
- # callback function for getting the image path
- def image_file_path(instance, filename):
- return os.path.join('uploads', str(instance.id), filename)
- logo = models.ImageField(upload_to=image_file_path,
- max_length=256, blank=True, null=True)
- image = models.ImageField(upload_to=image_file_path,
- max_length=256, blank=True, null=True)
- @property
- def address(self):
- return '%s %s %s, %s %s' % (self.address_1,
- self.address_2,
- self.city,
- self.state,
- self.zipcode)
- @property
- def is_business_time(self):
- hours = self.business_hours_list()
- if not hours:
- return False
- today = datetime.today()
- now = datetime.now()
- timezone = pytz.timezone(self.timezone)
- loc_dt = timezone.localize(now)
- try:
- for hourset in hours[today.weekday()]:
- start = datetime.strptime('%s-%s-%s %s' % (
- today.day,
- today.month,
- today.year,
- hourset[0],
- ), '%d-%m-%Y %H%M')
- end = datetime.strptime('%s-%s-%s %s' % (
- today.day,
- today.month,
- today.year,
- hourset[1],
- ), '%d-%m-%Y %H%M')
- start = timezone.localize(start)
- end = timezone.localize(end)
- if start <= loc_dt <= end:
- return True
- except:
- pass
- return False
- @property
- def render_business_hours(self):
- today = datetime.today()
- day_table = [
- 'mon',
- 'tues',
- 'wed',
- 'thurs',
- 'fri',
- 'sat',
- 'sun'
- ]
- timezone = pytz.timezone(self.timezone)
- loc_dt = timezone.localize(today)
- days = {}
- groups = {}
- prev_hours = None
- index_holder = []
- time_holder = []
- html = ''
- prev_time = None
- for node in self.timenode_set.all():
- for weekday in node.weekdays:
- if int(weekday) not in days:
- days[int(weekday)] = []
- days[int(weekday)].append('%s:%s' % (
- node.start.strftime('%H%M'), node.end.strftime('%H%M')))
- for weekday, value in days.iteritems():
- str_hours = '|'.join(value)
- if prev_hours is not None and str_hours is prev_hours:
- continue
- else:
- prev_hours = str_hours
- if str_hours not in groups:
- groups[str_hours] = []
- groups[str_hours].append(weekday)
- for iday in range(0, 7):
- for time, weekdays in groups.iteritems():
- if iday in weekdays:
- if time is prev_time:
- index_holder[len(index_holder) - 1].append(iday)
- else:
- prev_time = time
- index_holder.append([iday])
- time_holder.append(time)
- for index in range(0, len(index_holder)):
- day_set = index_holder[index]
- time = time_holder[index]
- hgroup = []
- element = '<li>'
- for hour_set in time.split('|'):
- start, end = hour_set.split(':')
- dt_start = datetime(
- today.year,
- today.month,
- today.day,
- int(start[:2]),
- int(start[2:])).strftime('%I:%M%p')
- dt_end = datetime(
- today.year,
- today.month,
- today.day,
- int(end[:2]),
- int(end[2:])).strftime('%I:%M%p')
- hgroup.append('%s - %s' % (dt_start, dt_end))
- if len(day_set) > 1:
- element = element + '<span>%s - %s</span>' % (
- day_table[day_set[0]],
- day_table[day_set[-1]],)
- else:
- element = element + '<span>%s</span>' % (
- day_table[day_set[0]],)
- element = element + ' %s %s </li>' % (' & '.join(hgroup),
- loc_dt.strftime('%Z'))
- html = html + element
- return html
- def business_hours_list(self):
- days = [ [], [], [], [], [], [], [], ]
- timenodes = self.timenode_set.all()
- for node in timenodes:
- for weekday in node.weekdays:
- days[int(weekday)].append([node.start.strftime('%H%M'), node.end.strftime('%H%M')])
- return days
- def __unicode__(self):
- return '%s in %s, %s' % (self.name, self.city, self.state)
- def save(self, *args, **kwargs):
- super(Restaurant, self).save(*args, **kwargs)
- filepath = os.path.join(settings.MEDIA_ROOT, 'uploads', str(self.id))
- # create a folder in the media/uploads with the id of the model
- if not os.path.exists(filepath):
- os.mkdir(filepath)
- class TimeNode(models.Model):
- restaurant = models.ForeignKey(Restaurant)
- start = models.TimeField()
- end = models.TimeField()
- weekdays = models.CharField(max_length=10)