Esempio n. 1
0
def merge_users(user1, user2):
    """

    :param user1:
    :param user2:
    :return:
    """
    if not user1.account.is_email_verified and user2.account.is_email_verified:
        user1.account.email = user2.account.email
        user1.account.is_email_verified = True

    user1.level = max(user1.level, user2.level)
    user1.followers = list(set(user1.followers) | set(user2.followers))
    user1.following = list(set(user1.followings) | set(user2.followings))
    user1.favor_items = list(set(user1.favor_items) | set(user2.favor_items))
    user1.num_followers = len(user1.followers)
    user1.num_followings = len(user1.followings)
    user1.num_favor = len(user1.favor_items)

    merge_carts(user_id_from=str(user2.id), user_id_to=str(user1.id))
    merge_coupon_wallet(to_wallet=user1.wallet, from_wallet=user2.wallet)
    merge_coin_wallet(to_coin_wallet=user1.coin_wallet,
                      from_coin_wallet=user2.coin_wallet)
    Order.objects(customer_id=user2.id).update(set__customer_id=user1.id)
    LogisticLog.objects(user_id=str(user2.id),
                        is_guest=False).update(set__user_id=str(user1.id))

    for addr in user2.addresses:
        user1.addresses.append(addr)

    user1.save()
    user2.mark_deleted()
    return user1
Esempio n. 2
0
    def logistics(self):
        """
        物流
        :return:
        """
        items_range = request.headers.get('Range', '0-9')
        start, end = items_range.split('-')
        per_page = int(end) - int(start) + 1
        query = restruct_query(request.args)
        tracking_no = query.pop('tracking_no', '')
        include_closed = query.get('include_closed') and query.pop(
            'include_closed')
        try:
            if include_closed:
                logistic = Logistic.objects(**query)
            else:
                logistic = Logistic.objects(is_closed=False, **query)
            if tracking_no:
                logistic = logistic.filter(
                    Q(detail__us_tracking_no=tracking_no)
                    | Q(detail__cn_tracking_no=tracking_no))

            if request.args.get('status'):
                logistic = logistic.order_by('detail__%s' %
                                             LogisticDetail.attr_by_log_status[
                                                 request.args.get('status')])
        except:
            pass

        if query.get('receiver'):
            address = Address.objects(
                receiver=query.get('receiver')).distinct('id')
            orders = Order.commodities(address__in=address)
            logistic = list(
                chain.from_iterable(order.logistics for order in orders))
        if query.get('order_id'):
            orders = Order.commodities(short_id=int(query.get('order_id')))
            logistic = list(
                chain.from_iterable(order.logistics for order in orders))

        try:
            logistic_size = logistic.count()
        except:
            logistic_size = len(logistic)

        data = logistic[int(start):int(end)]
        data = [to_json(l) for l in data]
        resp = make_response(json_util.dumps(data), 200)
        resp.headers['Accept_Range'] = 'items'
        resp.headers['Content_Range'] = '%s-%s/%s' % (start, end,
                                                      logistic_size)
        resp.headers['Content_Type'] = 'application/json'
        return resp
Esempio n. 3
0
def get_orders(order_type):
    """
    获取订单信息
    :param order_type:
    :return:
    """
    if order_type == 'COMMODITIES':
        orders = Order.commidities(customer_id=current_user.id)
    elif order_type == 'TRANSFER':
        orders = Order.transfer(customer_id=current_user.id)
    else:
        return jsonify(message='Failed')
    return jsonify(
        message='OK',
        orders=[json_templ.simple_order_json(order) for order in orders])
Esempio n. 4
0
def post_payment_ops(sender, order):
    """

    :param sender:
    :param order:
    :return:
    """
    coin_wallet = order.customer.coin_wallet
    wallet = order.customer.wallet
    if order.coin:
        coin_wallet.pay(order, order.coin, coin_type=COIN_TYPE.COIN)
        coin_wallet.reload()
    if order.cash:
        coin_wallet.pay(order, order.cash, coin_type=COIN_TYPE.CASH)
        coin_wallet.reload()
    for code in order.coupon_codes:
        wallet.user_consumable_coupon(code)
        wallet.reload()

    for order in Order.objects(customer_id=str(order.customer_id),
                               status=ORDER_STATUS.PAYMENT_PENDING,
                               id__ne=order.id):
        order.update_amount()

    for entry in order.entries:
        item = entry.item
        item_bought.send('system', item_id=entry.item_snapshot.item_id)
Esempio n. 5
0
def update_transfer_order():
    """
    更新运单
    :return:
    """
    data = request.json
    order_id = data.get('order_id')
    order = Order.objects(id=order_id).first_or_404()
    # 入库订单才能修改
    if order.status != 'WAREHOUSE_IN':
        return jsonify(
            message='Failed',
            error=gettext(
                'only when order status warehouse_in can be updated'))

    address_id = data.get('address_id')
    user = current_user._get_current_object()
    if address_id:
        address = Address.objects(id=address_id).first_or_404()
    elif user.addresses:
        address = user.addresses[0]
    else:
        return jsonify(message='Failed', error=gettext('no address'))

    order.logistic_provider = data.get('logistic_provider')
    order.coupon_codes = data.get('coupon_codes', [])
    order.address = address
    order.update_amount()
    order.reload()
    result = json_templ.transfer_order_price_json(order)
    return jsonify(message='OK', order=result)
Esempio n. 6
0
def unpaid_orders(user_id):
    """
    未支付订单
    :param user_id:
    :return:
    """
    orders = Order.payment_pending(customer_id=user_id)
    return [json_templ.simple_order_json(order) for order in orders]
Esempio n. 7
0
def new_order(user, paid_at_order):
    beerPub = get_active_beer_pub()

    table = request.form['table']
    products = list(map(Product.get, request.form.getlist('products[]')))
    if any((p is None for p in products)):
        abort(400, "Some passed products are invalid!")

    amounts = request.form.getlist('amounts[]')
    if any((not is_float(a) for a in amounts)):
        abort(400, "Some passed amounts are invalid!")

    remarks = request.form['remarks']
    Order.create(beerPub, user, products, list(map(float, amounts)), table,
                 paid_at_order, remarks)
    db.session.commit()
    return ("", http.HTTPStatus.NO_CONTENT)
Esempio n. 8
0
def get_order(order_id):
    """

    :param order_id:
    :return:
    """
    order = Order.objects(id=order_id).first_or_404()
    return jsonify(message='OK', order=json_templ.order_json(order))
Esempio n. 9
0
def logistic_orders(user_id):
    """
    物流订单(在途)
    :param user_id:
    :return:
    """
    orders = Order.processing(customer_id=user_id)
    return [json_templ.simple_order_json(order) for order in orders]
Esempio n. 10
0
def delete_order(order_id):
    """

    :param order_id:
    :return:
    """
    order = Order.objects(id=order_id).first_or_404()
    if order.customer_id != current_user.id or order.is_paid:
        return jsonify(message='Failed', error=gettext('order not found'))

    order.cancel_order('user delete', 'ORDER_DELETED')
    return jsonify(message='OK')
Esempio n. 11
0
def update_user_status(user_id):
    """

    :param user_id:
    :return:
    """
    status, created = OrderStatus.objects.get_or_create(user_id=user_id)

    all_orders = Order.objects(customer_id=user_id)
    status.num_orders = all_orders.count()
    status.total = all_orders.sum('final')

    received_orders = Order.received(customer_id=user_id)
    status.received = received_orders.sum('final')

    status.num_unpaid = Order.payment_pending(customer_id=user_id).count()

    processing = Order.processing(customer_id=user_id)
    status.num_waiting = processing.count()

    status.save()
Esempio n. 12
0
def move_order_to_self(code):
    """

    :param code:
    :return:
    """
    order_code = TransferOrderCode.objects(code=code).first()
    if not order_code:
        return jsonify(message='Failed')

    order = Order.get_order_or_404(order_code.order_id)
    order.customer_id = current_user.id
    order.save()

    order_code.delete()
    return jsonify(message='OK', order=json_templ.order_json(order))
Esempio n. 13
0
def create_order():
    """

    :return:
    """
    entries = request.json.get('entries')
    entries_info = entry_info_from_ids(entries)
    user = current_user._get_current_object()
    address_id = request.json.get('address_id')
    if address_id:
        address = Address.objects(id=address_id).first_or_404()
    elif user.addresses:
        address = user.addresses[0]
    else:
        return jsonify(message='Failed', error=gettext('no address'))

    logistic_provider = request.json.get('logistic_provider')
    if not logistic_provider:
        return jsonify(message='Failed', error=gettext('no logistic provider'))

    coin = 0
    cash = 0
    coupon_codes = request.json.get('coupon_codes', [])
    order = Order.create_from_skus(user.id,
                                   entries_info,
                                   logistic_provider,
                                   coupon_codes=coupon_codes,
                                   coin=coin,
                                   cash=cash,
                                   address=address,
                                   source=ORDER_SOURCES.WECHAT)
    if not isinstance(order, Order):
        return jsonify(message='Failed',
                       error='编号为{}的商品已售光, 请重新提交'.format(order['item_id']))

    if order.final == 0:
        order.set_paid()

    remove_from_cart([entry.item_spec_snapshot.sku for entry in order.entries],
                     user_id=str(current_user.id))
    return jsonify(message='OK',
                   order_id=str(order.id),
                   order=order.to_grouped_json())
Esempio n. 14
0
def create_transfer_order():
    """

    :return:
    """
    data = request.json
    entries = data.get('entries')
    user = current_user._get_current_object()
    address_id = data.get('address_id')
    if address_id:
        address = Address.objects(id=address_id).first_or_404()
    elif user.addresses:
        address = user.addresses[0]
    else:
        return jsonify(message='Failed', error=gettext('no address'))

    coin = 0
    cash = user.coin_wallet.cash if data.get('cash') else 0
    coupon_codes = data.get('coupon_codes', [])

    entries = import_entries(entries)
    order = Order.create_transfer(
        customer_id=str(user.id),
        final=0,
        entries=entries,
        address=address,
        source=ORDER_SOURCES.WECHAT,
        status=LOG_STATUS.PENDING_REVIEW,
        order_type=ORDER_TYPE.TRANSFER,
        logistic_provider=data.get('logistic_provider'),
        coupon_codes=coupon_codes,
        coin=coin,
        cash=cash)

    logistic_provider_dispatcher(order)
    return jsonify(message='OK',
                   order_id=str(order.id),
                   order=order.to_grouped_json())
Esempio n. 15
0
def coupon_by_order():
    """
    通过订单获取优惠卷
    :return:
    """
    data = request.json
    order_id = data.get('order_id')
    if not order_id:
        return jsonify(message='Failed', error=gettext('please choose order'))

    order = Order.objects(id=order_id).first()
    price = cal_order_price(order)
    c_jsons = []
    for c in current_user.wallet.consumable_coupons:
        if c.is_expired:
            continue
        c_json = c.to_json()
        c_json['can_apply'] = c.coupon.is_effective() and c.coupon.can_apply(
            price)
        c_json['saving'] = PRICE_FN.ORDER_COUPON[c.coupon.coupon_type](
            price, c.coupon)[1]
        c_jsons.append(c_json)

    return jsonify(message='OK', consumble_coupons=c_jsons)
Esempio n. 16
0
def cal_order_price():
    """
    计算订单价格
    :return:
    """
    data = request.json
    order_id = data.get('order_id')
    address_id = data.get('address_id')
    user = current_user._get_current_object()
    if address_id:
        address = Address.objects(id=address_id).first_or_404()
    elif user.addresses:
        address = user.addresses[0]
    else:
        return jsonify(message='Failed', error=gettext('no address'))

    order = Order.objects(id=order_id).first_or_404()
    order.logistic_provider = data.get('logistic_provider')
    order.coupon_codes = data.get('coupon_codes')
    order.address = address

    price = cal_order_price(order)
    result = json_templ.transfer_order_price_json(price)
    return jsonify(message='OK', order=result)
Esempio n. 17
0
    def post(self, request, *args, **kwargs):
        total = request.data.get('total', None)

        carts = Cart.objects.filter(user=request.user.id)
        order = Order()
        order.total = total
        order.user_id = request.user.id
        order.save()

        for cart in carts:
            orderinfo = Orderinfo()
            orderinfo.order = order
            orderinfo.number = cart.number
            orderinfo.goods = cart.goods
            orderinfo.version = cart.version
            orderinfo.color = cart.color
            orderinfo.save()
            cart.delete()

        return Response('下单成功')
Esempio n. 18
0
    def download(self):
        """

        :return:
        """
        FIELDS = [
            '包裹ID', 'IMG NO', 'CTN', '下单日期', '订单ID', '订单短号', '收件人', '手机号',
            '合作物流商', 'remark', '下单备注', '估重', '渠道'
        ]

        now = datetime.datetime.now()

        status = request.args.get('status')
        query = restruct_query(request.args)
        delay_export = query.get('delay_export') and query.pop('delay_export')
        delay_type = query.get('delay_type') and query.pop('delay_type')

        try:
            logistics = Logistic.objects(is_closed=False, **query)
            if status:
                logistics = logistics.order_by(
                    'detail__%s' % LogisticDetail.attr_by_log_status[status])
        except:
            pass

        if delay_export:
            date_field = LogisticDetail.attr_by_log_status[status]
            delay_days = datetime.timedelta(days=delay_status_by_date[status])
            query = {
                'detail__%s__lt' % date_field:
                datetime.datetime.utcnow() - delay_days,
                'detail__status': status,
            }
            logistics = logistics.filter(**query).order_by('detail__%s' %
                                                           date_field)
            if delay_type:
                logistics = logistics.filter(
                    detail__delay_details__reason__contains=delay_type)

        if query.get('receiver'):
            addresses = Address.objects(
                receiver=query.get('receiver')).distince('id')
            orders = Order.commodities(address__in=addresses)
            logistics = list(
                chain.from_iterable(order.logistics for order in orders))

        if query.get('order_id'):
            orders = Order.commodities(short_id=int(query.get('order_id')))
            logistics = list(
                chain.from_iterable(order.logistics for order in orders))

        def generate():
            yield ','.join(st for st in FIELDS) + '\n'
            for logistic in logistics:
                yield ','.join([
                    str(logistic.id),
                    logistic.detail.partner_tracking_no,
                    logistic.detail.carrier_tracking_no,
                    logistic.detail.cn_tracking_no,
                    logistic.detail.cn_logistic_name,
                    format_date(logistic.detail_payment_received_date),
                    str(logistic.order.id),
                    str(logistic.order.short_id),
                    logistic.order.address.receiver,
                    logistic.order.address.mobile_number,
                    format_date(logistic.detail.processing_date),
                    format_date(logistic.detail.shipping_date),
                    format_date(logistic.detail.port_arrived_date),
                    format_date(logistic.detail.received_date),
                    format_date(logistic.detail.modified),
                    logistic.detail.partner.name
                    if logistic.detail.partner else '',
                    ';'.join([r.content for r in logistic.detail.remarks]),
                    logistic.detail.extra or '',
                    str(logistic.estimated_weight),
                    logistic.detail.channel,
                ]) + '\n'

        return Response(generate(),
                        minetype='text/csv',
                        headers={
                            'Content_Disposition':
                            'attachment;filename=%s %s.csv' %
                            (format_date(now, '%Y-%m-%d'), 'dumps_file')
                        })
Esempio n. 19
0
 def used_coupon(self, code):
     return bool(
         Order.objects(customer_id=self.id,
                       is_paid=True,
                       coupon_codes__contains=code))
Esempio n. 20
0
def delete_order():
    order = Order.get(request.form['id'])
    if order is not None:
        order.delete()
        db.session.commit()
    return ("", http.HTTPStatus.NO_CONTENT)
Esempio n. 21
0
 def orders(self):
     return Order.objects(customer_id=self.id, is_paid=True)