示例#1
0
 def post(self, request, format=None):
     '''
     create a personal plan
     {
         "id": 18,
         "dish": [{
             "type": 0,
             "ingredient": [{
                 "id": 1,
                 "amount": 100
             }],
             "recipe": [{
                 "id": 2,
                 "amount": 200
             }]
         },{
             "type": 1,
             "ingredient": [],
             "recipe": [{
                 "id":3,
                 "amount": 300
             }]
         }],
         "joined_date": "2015-01-01"
     }
     '''
     try:
         body = json.loads(request.body)
         user = Account.find_account_by_user(request.user)
         try:
             joined_date = datetime.strptime(body['joined_date'],'%Y-%m-%d').date()
         except:
             joined_date = date.today()
         planid = body.get('id', None)
         if planid is None:
             # create
             p = Plan.objects.create(user=user)
         else :
             p = Plan.objects.get(user=user, pk=planid)
             p.delete_routines()
         r = Routine.objects.create(plan=p)
         for dish in body.get('dish', []):
             d = Dish.objects.create(type=dish['type'], routine=r)
             for si in dish.get('ingredient', []):
                 ingredient = Ingredient.objects.get(pk=si['id'])
                 SingleIngredient.objects.create(ingredient=ingredient, amount=si['amount'], dish=d)
             for sr in dish.get('recipe', []):
                 recipe = Recipe.objects.get(pk=sr['id'])
                 SingleRecipe.objects.create(recipe=recipe, amount=sr['amount'], dish=d)
         # after created it join it!
         try:
             c = Calendar.objects.get(user=user, joined_date=joined_date)
             if c.plan.id != p.id:
                 c.plan = p
                 c.save()
         except Calendar.DoesNotExist:
             Calendar.objects.create(user=user, plan=p, joined_date=joined_date)
         return self.success_response(PlanSerializer(p).data)
     except:
         return self.fail_response(400, 'fail')
示例#2
0
    def get(self, request, format=None):
        '''
        get my calendar
        '''
        user = Account.find_account_by_user(request.user)
        turn_to_date = lambda x: x and datetime.strptime(x, '%Y%m%d') or date.today()
        start_date = turn_to_date(request.GET.get('start', None))
        end_date = turn_to_date(request.GET.get('end', None))
        plans = []
        calendars = (Calendar.objects
            .select_related('plan')
            .select_related('user')
            .filter(user=user, joined_date__gte=start_date, joined_date__lte=end_date))

        try:
            last_joined = Calendar.objects.filter(user=user, joined_date__lte=start_date).order_by('-joined_date')[0]
            last = CalendarSerializer(last_joined, context={'simple': False}).data
            plans.append(last['plan'])
        except IndexError:
            last = None
        serializer = CalendarSerializer(calendars, many=True, context={'simple': False}).data
        for c in serializer:
            plans.append(c['plan'])
        punchs = Punch.objects.filter(user=user, date__lte=end_date, date__gte=start_date, state__gte=10)
        count = Punch.objects.filter(user=user, state__gte=10)
        result = {
            'lastJoined': last,
            'calendar': serializer,
            'punch': PunchSerializer(punchs, many=True).data,
            'plans': plans,
            'count': len(count)
        }
        return self.success_response(result)
示例#3
0
 def post(self, request, format=None):
     '''
     join plan
     same date & user will use the last one
     {
         "plan": 2,
         "joined_date": "2015-01-01"
     }
     '''
     body = json.loads(request.body)
     plan_id = body.get('plan', None)
     try:
         joined_date = datetime.strptime(body['authored_date'],'%Y-%m-%d').date()
     except:
         joined_date = date.today()
     user = Account.find_account_by_user(request.user)
     if plan_id is None:
         return self.fail_response(400, 'No Plan')
     try:
         p = Plan.objects.get(pk=plan_id)
         p.dish_headcount += 1
         p.save()
     except Plan.DoesNotExist:
         return self.fail_response(400, 'Plan Not Exist')
     try:
         c = Calendar.objects.create(user=user, plan=p, joined_date=joined_date)
     except IntegrityError:
         # existed today
         c = Calendar.objects.get(user=user, joined_date=joined_date)
         c.plan = p
         c.save()
     if not p.is_personal:
         # official plan should clean all plan after
         Calendar.objects.filter(user=user, joined_date__gt=joined_date).delete()
     return self.success_response('ok')
示例#4
0
 def get(self, request, format=None):
     user = Account.find_account_by_user(request.user)
     try:
         c = Calendar.objects.filter(user=user, joined_date__lte=date.today()).order_by('-joined_date')[0]
         return self.success_response(CalendarSerializer(c).data)
     except IndexError:
         # new user has no plan
         return self.success_response({})
示例#5
0
 def post(self, request, format=None):
     user = Account.find_account_by_user(request.user)
     body = json.loads(request.body)
     type = body.get('type', None)
     img = body.get('img', None)
     if None in (type, img):
         return self.fail_response(400, 'Wrong Data')
     p = Punch.objects.create(user=user, type=type, img=img)
     return self.success_response(PunchSerializer(p).data)
示例#6
0
 def post(self, request, punch_id, format=None):
     user = Account.find_account_by_user(request.user)
     try:
         p = Punch.objects.get(user=user, pk=punch_id)
         p.state = -10
         p.save()
         return self.success_response('ok')
     except Punch.DoesNotExist:
         return self.fail_response(404, 'No Punch')
示例#7
0
 def post(self, request, format=None):
     '''
     create a personal plan
     {
         "id": 18,
         "dish": [{
             "type": 0,
             "ingredient": [{
                 "id": 1,
                 "amount": 100
             }],
             "recipe": [{
                 "id": 2,
                 "amount": 200
             }]
         },{
             "type": 1,
             "ingredient": [],
             "recipe": [{
                 "id":3,
                 "amount": 300
             }]
         }],
         "joined_date": "2015-01-01"
     }
     '''
     try:
         body = json.loads(request.body)
         user = Account.find_account_by_user(request.user)
         try:
             joined_date = datetime.strptime(body['joined_date'],'%Y-%m-%d').date()
         except:
             joined_date = date.today()
         planid = body.get('id', None)
         routines = [{'video': None, 'dish': body.get('dish', [])}]
         if planid is None:
             # create
             p = Plan.objects.create(user=user, routines= json.dumps(routines))
         else :
             p = Plan.objects.get(user=user, pk=planid)
             p.routines = json.dumps(routines)
             p.save()
         # after created it join it!
         try:
             c = Calendar.objects.get(user=user, joined_date=joined_date)
             if c.plan.id != p.id:
                 c.plan = p
                 c.save()
         except Calendar.DoesNotExist:
             Calendar.objects.create(user=user, plan=p, joined_date=joined_date)
         # delete todays punch
         Punch.objects.filter(user=user, date=date.today()).update(state=-10)
         return self.success_response(PlanSerializer(p).data)
     except:
         raise#return self.fail_response(400, 'fail')
示例#8
0
 def post(self, request, format=None):
     c = Comment()
     try:
         data = json.loads(request.body)
         reply_id = data.get('reply', None)
         c.reply= reply_id and Account.objects.get(pk=reply_id)
         c.content = data['content']
         c.author = Account.find_account_by_user(request.user)
         c.recipe = Recipe.objects.get(pk=data['recipe'])
     except:
         return self.fail_response(400, 'BadArgument')
     c.save()
     return self.success_response(CommentSerializer(c).data)
示例#9
0
 def get(self, request, pk, format=None):
     '''
     reutrn a specific Theme
     '''
     theme = self.get_object(Theme, pk)
     result = ThemeSerializer(theme).data
     try:
         user = Account.find_account_by_user(request.user)
         has_collected = ThemeCollection.has_collected(theme, user)
     except Account.DoesNotExist:
         has_collected = (False, -1)
     result['has_collected'], result['collect_id'] = has_collected
     return self.success_response(result)
示例#10
0
 def get(self, request, format=None):
     '''
     List all plans in simple mode
     '''
     plans = Plan.objects.filter(is_personal=False)
     serializer = PlanSerializer(plans, many=True)
     user = Account.find_account_by_user(request.user)
     try:
         c = Calendar.objects.filter(user=user, joined_date__lte=date.today()).order_by('-joined_date')[0]
         current = CalendarSerializer(c).data
     except IndexError:
         # new user no plan
         current = {}
     result = {
         'plans': serializer.data,
         'current': current
     }
     return self.success_response(result)
示例#11
0
 def get(self, request, pk, format=None):
     '''
     return a specific recipe.
     '''
     recipe = self.get_object(Recipe, pk)
     try:
         user = Account.find_account_by_user(request.user)
         has_collected = RecipeCollection.has_collected(recipe, user)
     except Account.DoesNotExist:
         has_collected = False
     if recipe.status > 0:
         serializer = RecipeSerializer(recipe, context={'simple': False})
         result = serializer.data
         result['has_collected'] = has_collected
         result['comment_count'] = recipe.comment_set.count()
         return self.success_response(result)
     else:
         return self.fail_response(400, 'DoesNotExist')
示例#12
0
 def get(self, request, format=None):
     '''
     get my calendar
     '''
     user = Account.find_account_by_user(request.user)
     turn_to_date = lambda x: x and datetime.strptime(x, '%Y%m%d') or date.today()
     start_date = turn_to_date(request.GET.get('start', None))
     end_date = turn_to_date(request.GET.get('end', None))
     calendars = Calendar.objects.filter(user=user, joined_date__gte=start_date, joined_date__lte=end_date)
     try:
         last_joined = Calendar.objects.filter(user=user, joined_date__lte=start_date).order_by('-joined_date')[0]
         last = CalendarSerializer(last_joined).data
     except IndexError:
         last = None
     serializer = CalendarSerializer(calendars, many=True).data
     punchs = Punch.objects.filter(user=user, date__lte=end_date, date__gte=start_date)
     result = {'lastJoined': last, 'calendar': serializer, 'punch': PunchSerializer(punchs, many=True).data}
     return self.success_response(result)
示例#13
0
 def get(self, request, pk, format=None):
     '''
     return a specific recipe.
     '''
     recipe = Recipe.objects.select_related('author').get(pk=pk)
     try:
         user = Account.find_account_by_user(request.user)
         has_collected = RecipeCollection.has_collected(recipe, user)
     except Account.DoesNotExist:
         has_collected = (False, -1)
     if recipe.status > 0:
         serializer = RecipeSerializer(recipe, context={'simple': False})
         result = serializer.data
         result['has_collected'], result['collect_id'] = has_collected
         result['comment_set'] = CommentSerializer(recipe.comment_set.order_by('-created_time')[0:20], many=True).data
         result['comment_count'] = recipe.comment_set.count()
         return self.success_response(result)
     else:
         return self.fail_response(400, 'DoesNotExist')
示例#14
0
 def get(self, request, collection_type, format=None):
     lastid = request.GET.get('lastid', None)
     if collection_type == 'theme':
         model = ThemeCollection
         serializer = ThemeCollectionSerializer
     elif collection_type == 'series':
         model = SeriesCollection
         serializer = SeriesCollectionSerializer
     elif collection_type == 'recipe':
         model = RecipeCollection
         serializer = RecipeCollectionSerializer
     else:
         return self.fail_response(400, 'BadArgument')
     owner = Account.find_account_by_user(request.user)
     if lastid:
         result = model.objects.filter(owner=owner, id__lt=lastid, status__gt=0).order_by('-created_time')[0:20]
     else:
         result = model.objects.filter(owner=owner, status__gt=0).order_by('-created_time')[0:20]
     return self.success_response(serializer(result, many=True).data)
示例#15
0
    def get(self, request, format=None):
        def get_planid(punch, calendar_list):
            temp_storage = None
            for c in calendar_list:
                if punch.date > c['joined_date']:
                    day = punch.date - c['joined_date']
                    return (c['plan'], day.days)
                elif punch.date == c['joined_date']:
                    return (c['plan'], 1)
                else:
                    temp_storage = None
            return (None, 0)

        user = Account.find_account_by_user(request.user)
        turn_to_date = lambda x: x and datetime.strptime(x, '%Y%m%d') or date.today()
        start_date = turn_to_date(request.GET.get('start', None))
        end_date = turn_to_date(request.GET.get('end', None))
        punchs = Punch.objects.filter(user=user, date__lte=end_date, date__gte=start_date, state__gte=10)
        calendars = Calendar.objects.filter(user=user, joined_date__lte=end_date, joined_date__gte=start_date).order_by('joined_date') # asc
        # get all calendar
        try:
            last_calendar = Calendar.objects.filter(user=user, joined_date__lte=start_date).order_by('-joined_date')[0]
            calendar_list = [{'joined_date': last_calendar.joined_date, 'plan': last_calendar.plan.id}]
        except IndexError:
            calendar_list = []
        for c in calendars:
            calendar_list.append({'joined_date': c.joined_date, 'plan': c.plan.id})
        result = []
        calendar_list.reverse()
        for p in punchs:
            planid, day = get_planid(p, calendar_list)
            plan = Plan.objects.get(pk=planid)
            current_day_count = day % plan.total_days
            if current_day_count == 0:
                current_day_count = plan.total_days
            # 从1开始计数的
            dish = json.loads(plan.routines)[current_day_count-1]['dish']
            p_json = PunchSerializer(p).data
            p_json['dish'] = [item for item in dish if item['type'] == p.type]
            result.append(p_json)
        count = Punch.objects.filter(user=user, state__gte=10).count()
        return self.success_response({'punchs': result, 'count': count})
示例#16
0
    def get(self, request, format=None):
        def get_planid(punch, calendar_list):
            temp_storage = None
            for c in calendar_list:
                if c['joined_date'] < p.date:
                    day = p.date - c['joined_date']
                    return (temp_storage, day.days)
                elif c['joined_date'] == p.date:
                    return (c['plan'], 1)
                else:
                    # >
                    temp_storage = c['plan']
            return (None, 0)

        user = Account.find_account_by_user(request.user)
        turn_to_date = lambda x: x and datetime.strptime(x, '%Y%m%d') or date.today()
        start_date = turn_to_date(request.GET.get('start', None))
        end_date = turn_to_date(request.GET.get('end', None))
        punchs = Punch.objects.filter(user=user, date__lte=end_date, date__gte=start_date, state__gte=10)
        calendars = Calendar.objects.filter(user=user, joined_date__lte=end_date, joined_date__gte=start_date).order_by('joined_date') # asc
        # get all calendar
        try:
            last_calendar = Calendar.objects.filter(user=user, joined_date__lte=date.today()).order_by('-joined_date')[0]
            calendar_list = [{'joined_date': last_calendar.joined_date, 'plan': last_calendar.plan.id}]
        except IndexError:
            calendar_list = []
        for c in calendars:
            calendar_list.append({'joined_date': c.joined_date, 'plan': c.plan.id})
        result = []
        for p in punchs:
            planid, day = get_planid(p, calendar_list)
            plan = Plan.objects.get(pk=planid)
            current_day_count = day % plan.total_days
            if current_day_count == 0:
                current_day_count = plan.total_days
            dish = plan.routine_set.get(day=current_day_count).dish_set.get(type=p.type)
            p_json = PunchSerializer(p).data
            p_json['dish'] = DishSerializer(dish, context={'simple': False}).data
            result.append(p_json)
        return self.success_response(result)
示例#17
0
 def post(self, request, format=None):
     try:
         data = json.loads(request.body)
         collection_id = data['id']
         collection_type = data['type']
     except:
         return self.fail_response(400, 'BadArgumrent')
     try:
         if collection_type == 'theme':
             model = ThemeCollection
             obj = Theme.objects.get(pk=collection_id)
             serializer = ThemeCollectionSerializer
         elif collection_type == 'series':
             model = SeriesCollection
             obj = Series.objects.get(pk=collection_id)
             serializer = SeriesCollectionSerializer
         elif collection_type == 'recipe':
             obj = Recipe.objects.get(pk=collection_id)
             model = RecipeCollection
             serializer = RecipeCollectionSerializer
         else:
             return self.fail_response(400, 'BadArgument')
     except ObjectDoesNotExist:
         return self.fail_response(400, 'DoesNotExist')
     obj.collection_count += 1
     obj.save()
     owner = Account.find_account_by_user(request.user)
     try:
         kwargs = {collection_type: obj, 'owner': owner}
         col = model.objects.get(**kwargs)
     except model.DoesNotExist:
         col = model()
         col.owner = owner
         setattr(col, collection_type, obj)
     col.status = 10
     col.save()
     return self.success_response(serializer(col).data)
示例#18
0
 def get(self, request, format=None):
     user = Account.find_account_by_user(request.user)
     count_punch = Punch.objects.filter(user=user, state__gte=10).count()
     count_recipe = RecipeCollection.objects.filter(owner=user, status__gte=0).count()
     return self.success_response({'count': count_punch, 'recipe': count_recipe})