def get_orders(req: Request, order_status: str = None, start_time: str = None, end_time: str = None,
               limit_num: str = None):
    if order_status is not None and order_status != 'in_progress' and order_status != 'delivering' \
            and order_status != 'cancelled' and order_status != 'finished':
        raise NotFound()
    if order_status == 'in_progress':
        order_status = models.ORDER_IN_PROGRESS
    elif order_status == 'delivering':
        order_status = models.ORDER_DELIVERING
    elif order_status == 'cancelled':
        order_status = models.ORDER_CANCELLED
    elif order_status == 'finished':
        order_status = models.ORDER_FINISHED

    user = token_check(req=req)
    order_list = []
    for e in models.Order.objects.filter(buyer=user).filter(
            view_utils.general_query_time_limit(end_time=end_time, start_time=start_time, status=order_status))[
             :int(limit_num)]:
        order = view_utils.get_model_dict(e, excluded_fields=['buyer', 'delivery_address', 'delivery'])
        if e.delivery_address:
            order['delivery_address'] = json.loads(e.delivery_address)
        if e.delivery:
            order['delivery'] = json.loads(e.delivery)
        order_list.append(order)
    if len(order_list) == 0:
        raise CheckException(status=status.HTTP_404_NOT_FOUND,
                             result_code=result_code.MR_ORDER_NOT_FOUND,
                             message=_('Order not found'))
    return view_utils.get_json_response(order_list=order_list)
Beispiel #2
0
def post_feedback(req: Request):
    poster = account.token_check(req=req, optional=True)
    new_feedback = models.Feedback(poster=poster, title=req.data['title'],
                                   text=req.data['text_content'])
    new_feedback.save()
    return view_utils.get_json_response(status=status.HTTP_201_CREATED,
                                        message=_('Post feedback successfully'))
Beispiel #3
0
def get_recycle_record(req: Request, limit_num: str, start_time: str=None, end_time: str=None):
    user = account.token_check(req=req, permission_limit=models.RECYCLE_ACCOUNT_GARBAGE_COLLECTOR)
    result_list = []
    for r in models.RecycleCleaningRecord.objects.filter(view_utils.general_query_time_limit(start_time=start_time,
                                                                                             end_time=end_time,
                                                                                             user=user))[:int(limit_num)]:
        result_list.append(view_utils.get_model_dict(r, excluded_fields=['user']))
    if len(result_list) == 0:
        raise CheckException(status=status.HTTP_404_NOT_FOUND, result_code=result_code.MR_RECYCLE_RECORD_NOT_FOUND,
                             message=_('No record'))
    return view_utils.get_json_response(recycle_record_list=result_list)
def get_weekly_credit_rank(req: Request):
    global weekly_credit_rank_list
    global weekly_credit_rank_list_update_time
    user = account.token_check(req=req, optional=True)
    user_name = None
    if user is not None:
        user_name = models.RecycleAccount.objects.filter(
            user_id=user.user_id).get().user_name
    return get_credit_rank_response(
        rank_list=weekly_credit_rank_list,
        update_time=weekly_credit_rank_list_update_time,
        user_name=user_name)
Beispiel #5
0
def get_all_recycle_points(req: Request):
    user = account.token_check(req=req, optional=True)
    if user is not None:
        user = models.RecycleAccount.objects.filter(user_id=user.user_id).get()
    result_list = []
    for rp in models.RecyclePoint.objects.all():
        if user is not None and user.account_type == models.RECYCLE_ACCOUNT_GARBAGE_COLLECTOR:
            rp_dict = view_utils.get_recycle_point_dict(point=rp, is_owner=True)
        else:
            rp_dict = view_utils.get_recycle_point_dict(point=rp, is_owner=False)
        red_packet = cache.get('%s%d' % (CACHE_KEY_RED_PACKET_PREFIX, rp.point_id))
        is_red_packet_point = check_red_packet_valid(red_packet, rp.point_id) > 0
        rp_dict.update(is_red_packet_point=is_red_packet_point)
        result_list.append(rp_dict)
    return view_utils.get_json_response(recycle_point_list=result_list)
def get_credit_records(req: Request,
                       start_time: str = None,
                       end_time: str = None,
                       limit_num: str = None):
    user = account.token_check(req)
    credit_record_list = []
    for cr in models.RecycleCreditRecord.objects.filter(
            view_utils.general_query_time_limit(end_time=end_time,
                                                start_time=start_time,
                                                user=user))[:int(limit_num)]:
        credit_record_list.append(
            view_utils.get_model_dict(cr, excluded_fields=['user']))
    if len(credit_record_list) == 0:
        raise CheckException(
            status=status.HTTP_404_NOT_FOUND,
            result_code=result_code.MR_CREDIT_RECORD_NOT_FOUND,
            message=_('Credit record not found'))
    return view_utils.get_json_response(credit_record_list=credit_record_list)
Beispiel #7
0
def post_recycle_record(req: Request):
    user = account.token_check(req=req, permission_limit=models.RECYCLE_ACCOUNT_GARBAGE_COLLECTOR)
    try:
        recycle_point = models.RecyclePoint.objects.filter(point_id=req.data['recycle_point_id']).get()
    except models.RecyclePoint.DoesNotExist:
        raise CheckException(status=status.HTTP_404_NOT_FOUND, result_code=result_code.MR_RECYCLE_RECORD_RECYCLE_POINT_NOT_FOUND,
                             message=_('Recycle point not found'))
    if recycle_point.owner_id != user.user_id:
        raise CheckException(result_code=result_code.MR_RECYCLE_POINT_NOT_MANAGED,
                             message=_('The recycle point does not be managed by you'))
    if recycle_point.bottle_num is not None and recycle_point.bottle_num == 0:
        raise CheckException(result_code=result_code.MR_RECYCLE_POINT_EMPTY,
                             message=_('The recycle point is empty'))
    new_record = models.RecycleCleaningRecord(user=user, recycle_point=recycle_point,
                                              bottle_num=recycle_point.bottle_num)
    new_record.save()
    if recycle_point.bottle_num is not None:
        recycle_point.bottle_num = 0
    recycle_point.save()
    return view_utils.get_json_response(status=status.HTTP_201_CREATED,
                                        message=_('Post recycle record successfully'))
def recycle_bottle(req: Request):
    user = account.token_check(req)
    try:
        rp = models.RecyclePoint.objects.filter(
            point_id=int(req.data['recycle_point_id'])).get()
    except models.RecyclePoint.DoesNotExist:
        raise CheckException(
            status=status.HTTP_404_NOT_FOUND,
            result_code=result_code.MR_CREDIT_RECORD_RECYCLE_POINT_NOT_FOUND,
            message=_('Recycle point not found'))
    if rp.bottle_num is None:
        raise CheckException(
            result_code=result_code.MR_CREDIT_RECORD_RECYCLE_POINT_NOT_FOUND,
            message=_('This recycle point does not accept bottles'))
    user_longitude = float(req.data['longitude'])
    user_latitude = float(req.data['latitude'])
    if not check_utils.check_location(longitude=user_longitude,
                                      latitude=user_latitude):
        raise CheckException(result_code=result_code.MR_ILLEGAL_LOCATION,
                             message=_('Illegal location'))
    if not check_utils.check_distance(p1_longitude=user_longitude,
                                      p1_latitude=user_latitude,
                                      p2_longitude=rp.longitude,
                                      p2_latitude=rp.latitude,
                                      distance_limit=50.0):
        raise CheckException(
            result_code=result_code.MR_TOO_FAR_AWAY_FROM_RECYCLE_POINT,
            message=_('Too far away from specific recycle point'))
    quantity = int(req.data['quantity'])
    if quantity <= 0:
        quantity = 1
    elif quantity > settings.TN_RECYCLE_BOTTLE_MAX_QUANTITY:
        quantity = settings.TN_RECYCLE_BOTTLE_MAX_QUANTITY

    red_packet_credit = 0
    cache_red_packet = cache.get(
        '%s%d' % (recycle_point.CACHE_KEY_RED_PACKET_PREFIX, rp.point_id))
    max_red_packet_credit = recycle_point.check_red_packet_valid(
        cache_red_packet, rp.point_id)
    if max_red_packet_credit > 0:
        if max_red_packet_credit > quantity:
            max_red_packet_credit = quantity
        if random.random() < recycle_point.RED_PACKET_PROBABILITY:
            red_packet_credit = random.randint(1, max_red_packet_credit)
            cache_red_packet['total'] -= red_packet_credit
            cache.set(
                '%s%d' %
                (recycle_point.CACHE_KEY_RED_PACKET_PREFIX, rp.point_id),
                cache_red_packet, None)

    new_credit_record = models.RecycleCreditRecord(
        user=user,
        item_description='Recycled bottle x%d' % quantity,
        credit=quantity + red_packet_credit)
    new_credit_record.save()
    user = models.RecycleAccount.objects.filter(user_id=user.user_id).get()
    user.credit += new_credit_record.credit
    user.save()
    rp.bottle_num += quantity
    rp.save()
    return view_utils.get_json_response(
        status=status.HTTP_201_CREATED,
        message=_('Recycle bottle successfully'),
        credit=new_credit_record.credit,
        red_packet_credit=red_packet_credit)
def new_order(req: Request):
    global lock_dict_lock
    global commodity_lock_dict
    user = token_check(req=req)
    user = models.RecycleAccount.objects.filter(user_id=user.user_id).get()
    order = models.Order(buyer=user)
    order.quantity = int(req.data['quantity'])
    if order.quantity <= 0:
        raise CheckException(result_code=result_code.MR_ILLEGAL_QUANTITY,
                             message=_('Illegal quantity(<=0)'))

    try:
        commodity_id = int(req.data['commodity_id'])
        commodity = models.Commodity.objects.get(commodity_id=commodity_id)
    except models.Commodity.DoesNotExist:
        raise CheckException(status=status.HTTP_404_NOT_FOUND,
                             result_code=result_code.MR_COMMODITY_NOT_FOUND,
                             message=_('Commodity not found'))

    lock_dict_lock.acquire()
    if str(commodity_id) not in commodity_lock_dict:
        commodity_lock_dict.update({str(commodity_id): threading.Lock()})
    commodity_lock = commodity_lock_dict[str(commodity_id)]
    lock_dict_lock.release()

    commodity_lock.acquire()
    try:
        if commodity.commodity_type == models.COMMODITY_TYPE_PHYSICAL:
            if 'delivery_address' not in req.data:
                raise ParseError()
            addr = req.data['delivery_address']
            if not 'name' in addr or not 'phone_number' in addr or not 'address' in addr:
                raise ParseError()
            if not str(addr['phone_number']).isdigit():
                raise CheckException(result_code=result_code.MR_ILLEGAL_PHONE, message=_('Illegal phone number'))
            order.delivery_address = to_json(addr)

        if order.quantity > commodity.stock:
            raise CheckException(status=status.HTTP_422_UNPROCESSABLE_ENTITY,
                                 result_code=result_code.MR_INSUFFICIENT_STOCK,
                                 message=_('Insufficient stock'))
        if order.quantity > commodity.quantity_limit:
            raise CheckException(status=status.HTTP_422_UNPROCESSABLE_ENTITY,
                                 result_code=result_code.MR_QUANTITY_EXCEEDS_LIMIT,
                                 message=_('Quantity exceeds limit'))
        if commodity.credit * order.quantity > user.credit:
            raise CheckException(status=status.HTTP_422_UNPROCESSABLE_ENTITY,
                                 result_code=result_code.MR_INSUFFICIENT_CREDIT,
                                 message=_('Insufficient credit'))

        commodity.stock -= order.quantity
        commodity.save()

        order.order_id = timezone.datetime.now().strftime('CM%Y%m%d%H%M%S%f')
        order.credit = commodity.credit
        order.title = commodity.title
        order.commodity_id = commodity.commodity_id

        if 'remark' in req.data:
            order.remark = req.data['remark']

        order.save()
        new_credit_record = models.RecycleCreditRecord(user=user,
                                                       item_description='%s x%d' %
                                                                        (commodity.title, order.quantity),
                                                       credit=-(commodity.credit * order.quantity))
        new_credit_record.save()
        user.credit += new_credit_record.credit
        user.save()
    except Exception as e:
        raise e
    finally:
        commodity_lock.release()
    return view_utils.get_json_response(status=status.HTTP_201_CREATED, message=_('Submit order successfully'))