Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 20th, 2012  |  syntax: None  |  size: 6.77 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import os
  2. from ast import literal_eval
  3. from datetime import datetime
  4. import pytz
  5.  
  6. from django.db import models
  7. from django.conf import settings
  8.  
  9. from apps.themes.models import Template
  10.  
  11. TIMEZONES = tuple((t, t) for t in pytz.all_timezones)
  12. WEEKDAY_CHOICES = (
  13.     (0, 'Monday'),
  14.     (1, 'Tuesday'),
  15.     (2, 'Wednesday'),
  16.     (3, 'Thursday'),
  17.     (4, 'Friday'),
  18.     (5, 'Saturday'),
  19.     (6, 'Sunday'),
  20. )
  21.  
  22. class Restaurant(models.Model):
  23.     name = models.CharField(max_length=256)
  24.     sub_name = models.CharField(max_length=128, blank=True, null=True)
  25.  
  26.     phone = models.CharField(max_length=10)
  27.     address_1 = models.CharField(max_length=256)
  28.     address_2 = models.CharField(max_length=256, null=True, blank=True)
  29.     city = models.CharField(max_length=36)
  30.     state = models.CharField(max_length=2)
  31.     zipcode = models.CharField(max_length=10)
  32.     description = models.TextField()
  33.  
  34.     timezone = models.CharField(max_length=24, choices=TIMEZONES,
  35.         default=settings.TIME_ZONE)
  36.  
  37.     subdomain = models.CharField(max_length=128, blank=True, null=True)
  38.     template = models.ForeignKey(Template, blank=True, null=True)
  39.     color_override = models.CharField(max_length=64, blank=True, null=True,
  40.         help_text="To update choices for correct template, you must reload the page after saving the new template.")
  41.  
  42.     has_own_domain = models.BooleanField(default=False)
  43.     domain_name = models.CharField(max_length=256, blank=True, null=True)
  44.  
  45.     # callback function for getting the image path
  46.  
  47.     def image_file_path(instance, filename):
  48.         return os.path.join('uploads', str(instance.id), filename)
  49.  
  50.     logo = models.ImageField(upload_to=image_file_path,
  51.         max_length=256, blank=True, null=True)
  52.     image = models.ImageField(upload_to=image_file_path,
  53.         max_length=256, blank=True, null=True)
  54.  
  55.     @property
  56.     def address(self):
  57.         return '%s %s %s, %s %s' % (self.address_1,
  58.                                     self.address_2,
  59.                                     self.city,
  60.                                     self.state,
  61.                                     self.zipcode)
  62.  
  63.     @property
  64.     def is_business_time(self):
  65.         hours = self.business_hours_list()
  66.  
  67.         if not hours:
  68.             return False
  69.         today = datetime.today()
  70.         now = datetime.now()
  71.         timezone = pytz.timezone(self.timezone)
  72.         loc_dt = timezone.localize(now)
  73.         try:
  74.             for hourset in hours[today.weekday()]:
  75.                 start = datetime.strptime('%s-%s-%s %s' % (
  76.                     today.day,
  77.                     today.month,
  78.                     today.year,
  79.                     hourset[0],
  80.                     ), '%d-%m-%Y %H%M')
  81.                 end = datetime.strptime('%s-%s-%s %s' % (
  82.                     today.day,
  83.                     today.month,
  84.                     today.year,
  85.                     hourset[1],
  86.                     ), '%d-%m-%Y %H%M')
  87.                
  88.                 start = timezone.localize(start)
  89.                 end = timezone.localize(end)
  90.                 if start <= loc_dt <= end:
  91.                     return True
  92.         except:
  93.             pass
  94.         return False
  95.  
  96.     @property
  97.     def render_business_hours(self):
  98.         today = datetime.today()
  99.         day_table = [
  100.             'mon',
  101.             'tues',
  102.             'wed',
  103.             'thurs',
  104.             'fri',
  105.             'sat',
  106.             'sun'
  107.         ]
  108.         timezone = pytz.timezone(self.timezone)
  109.         loc_dt = timezone.localize(today)
  110.  
  111.         days = {}
  112.         groups = {}
  113.         prev_hours = None
  114.         index_holder = []
  115.         time_holder = []
  116.         html = ''
  117.         prev_time = None
  118.  
  119.         for node in self.timenode_set.all():
  120.             for weekday in node.weekdays:
  121.                 if int(weekday) not in days:
  122.                     days[int(weekday)] = []
  123.                 days[int(weekday)].append('%s:%s' % (
  124.                     node.start.strftime('%H%M'), node.end.strftime('%H%M')))
  125.  
  126.         for weekday, value in days.iteritems():
  127.             str_hours = '|'.join(value)
  128.             if prev_hours is not None and str_hours is prev_hours:
  129.                 continue
  130.             else:
  131.                 prev_hours = str_hours
  132.                 if str_hours not in groups:
  133.                     groups[str_hours] = []
  134.                 groups[str_hours].append(weekday)
  135.  
  136.         for iday in range(0, 7):
  137.              for time, weekdays in groups.iteritems():
  138.                 if iday in weekdays:
  139.                     if time is prev_time:
  140.                         index_holder[len(index_holder) - 1].append(iday)
  141.                     else:
  142.                         prev_time = time
  143.                         index_holder.append([iday])
  144.                         time_holder.append(time)
  145.        
  146.         for index in range(0, len(index_holder)):
  147.             day_set = index_holder[index]
  148.             time = time_holder[index]
  149.             hgroup = []
  150.             element = '<li>'
  151.             for hour_set in time.split('|'):
  152.                 start, end = hour_set.split(':')
  153.                 dt_start = datetime(
  154.                     today.year,
  155.                     today.month,
  156.                     today.day,
  157.                     int(start[:2]),
  158.                     int(start[2:])).strftime('%I:%M%p')
  159.                 dt_end = datetime(
  160.                     today.year,
  161.                     today.month,
  162.                     today.day,
  163.                     int(end[:2]),
  164.                     int(end[2:])).strftime('%I:%M%p')
  165.                 hgroup.append('%s - %s' % (dt_start, dt_end))
  166.             if len(day_set) > 1:
  167.                 element = element + '<span>%s - %s</span>' % (
  168.                     day_table[day_set[0]],
  169.                     day_table[day_set[-1]],)
  170.             else:
  171.                 element = element + '<span>%s</span>' % (
  172.                     day_table[day_set[0]],)
  173.             element = element + ' %s %s </li>' % (' & '.join(hgroup),
  174.                 loc_dt.strftime('%Z'))
  175.             html = html + element
  176.         return html
  177.  
  178.     def business_hours_list(self):
  179.         days = [ [], [], [], [], [], [], [], ]
  180.         timenodes = self.timenode_set.all()
  181.         for node in timenodes:
  182.             for weekday in node.weekdays:
  183.                 days[int(weekday)].append([node.start.strftime('%H%M'), node.end.strftime('%H%M')])
  184.         return days
  185.    
  186.  
  187.     def __unicode__(self):
  188.         return '%s in %s, %s' % (self.name, self.city, self.state)
  189.  
  190.     def save(self, *args, **kwargs):
  191.         super(Restaurant, self).save(*args, **kwargs)
  192.  
  193.         filepath = os.path.join(settings.MEDIA_ROOT, 'uploads', str(self.id))
  194.         # create a folder in the media/uploads with the id of the model
  195.         if not os.path.exists(filepath):
  196.             os.mkdir(filepath)
  197.  
  198.  
  199. class TimeNode(models.Model):
  200.     restaurant = models.ForeignKey(Restaurant)
  201.     start = models.TimeField()
  202.     end = models.TimeField()
  203.     weekdays = models.CharField(max_length=10)