Beispiel #1
0
def remove():
    """ 删除订单 """
    resjson.action_code = 16

    if not check_login():
        return resjson.print_json(resjson.NOT_LOGIN)
    uid = get_uid()

    order_id = toint(request.args.get('order_id', 0))

    if order_id <= 0:
        return resjson.print_json(resjson.PARAM_ERROR)

    order = Order.query.filter(Order.order_id == order_id).filter(
        Order.uid == uid).first()

    if not order:
        return resjson.print_json(10, _(u'订单不存在'))

    if order.order_status not in (2, 3):
        return resjson.print_json(11, _(u'当前订单状态不允许删除订单'))

    model_update(order, {'is_remove': 1}, commit=True)

    return resjson.print_json(0, u'ok')
Beispiel #2
0
def save_comment():
    """评价订单商品"""
    resjson.action_code = 17

    if not check_login():
        return resjson.print_json(resjson.NOT_LOGIN)
    uid = get_uid()
    nickname = get_nickname()
    avatar = get_avatar()

    wtf_form = CommentOrderGoodsForm()
    current_time = current_timestamp()

    if not wtf_form.validate_on_submit():
        for key, value in wtf_form.errors.items():
            msg = value[0]
        return resjson.print_json(11, msg)

    og_id = wtf_form.og_id.data
    order_goods = OrderGoods.query.get(og_id)
    if not order_goods:
        return resjson.print_json(12, _(u'订单商品不存在'))

    order = Order.query.filter(Order.order_id == order_goods.order_id).filter(
        Order.uid == uid).first()
    if not order:
        return resjson.print_json(13, _(u'订单商品不存在'))

    data = {'uid': uid, 'nickname': nickname, 'avatar': avatar, 'ttype': 1, 'tid': order_goods.goods_id,
            'rating': wtf_form.rating.data, 'content': wtf_form.content.data,
            'img_data': wtf_form.img_data.data, 'add_time': current_time}
    comment = model_create(Comment, data, commit=True)

    item = Goods.query.get(order_goods.goods_id)
    if item:
        comment_count = Comment.query.\
            filter(Comment.ttype == 1).\
            filter(Comment.tid == order_goods.goods_id).count()
        good_count = Comment.query.\
            filter(Comment.ttype == 1).\
            filter(Comment.tid == order_goods.goods_id).\
            filter(Comment.rating == 3).count()
        comment_good_rate = round(
            (Decimal(good_count)/Decimal(comment_count)) * 100)
        model_update(item, {'comment_count': comment_count,
                            'comment_good_rate': comment_good_rate})

    model_update(order_goods, {'comment_id': comment.comment_id}, commit=True)

    # 站内消息
    content = _(u'您已评价“%s”。' % order_goods.goods_name)
    mcs = MessageCreateService(
        1, uid, -1, content, ttype=2, tid=og_id, current_time=current_time)
    if not mcs.check():
        log_error('[ErrorViewApiOrderSaveComment][MessageCreateError]  og_id:%s msg:%s' % (
            og_id, mcs.msg))
    else:
        mcs.do()

    return resjson.print_json(0, u'ok')
Beispiel #3
0
def update():
    """更新个人资料"""
    resjson.action_code = 11

    if not check_login():
        return resjson.print_json(resjson.NOT_LOGIN)
    uid = get_uid()

    wtf_form = ProfileForm()
    current_time = current_timestamp()

    if not wtf_form.validate_on_submit():
        for key, value in wtf_form.errors.items():
            msg = value[0]
        return resjson.print_json(11, msg)

    data = {
        'nickname': wtf_form.nickname.data,
        'avatar': wtf_form.avatar.data,
        'gender': wtf_form.gender.data,
        'update_time': current_time
    }

    user = User.query.get(uid)
    model_update(user, data, commit=True)

    set_user_session(user)

    return resjson.print_json(0, u'ok')
Beispiel #4
0
    def deliver(self):
        """确认收货"""

        try:
            self.check()
        except OrderException as e:
            raise e

        data = {
            'order_status': 2,
            'deliver_status': 2,
            'deliver_time': self.current_time}
        model_update(self.order, data)

        # 站内消息
        content = _(u'您的订单%s已确认签收,请前往评价。' % self.order.order_sn)
        mcs = MessageCreateService(
            1,
            self.order.uid,
            -1,
            content,
            ttype=1,
            tid=self.order.order_id,
            current_time=self.current_time)
        if not mcs.check():
            log_error('order_id:%s msg:%s' % (self.order.order_id, mcs.msg))
        else:
            mcs.do()

        db.session.commit()

        # 微信消息
        WeixinMessageStaticMethodsService.deliver(self.order)
    def add_log(aftersales_id,
                content,
                al_type=0,
                current_time=0,
                commit=True):
        """添加日志
            @param al_type 类型:
                        0_默认,
                        1_申请,
                        2_审核,
                        3_收货(商家),
                        4_退款,
                        5_寄货(商家)
                        6_寄货(用户),
        """

        current_time = current_time if current_time else current_timestamp()

        aftersales = Aftersales.query.get(aftersales_id)
        if aftersales:
            data = {
                'aftersales_id': aftersales_id,
                'content': content,
                'al_type': al_type,
                'add_time': current_time
            }
            model_create(AftersalesLogs, data)

            data = {'latest_log': content, 'update_time': current_time}
            model_update(aftersales, data, commit=commit)

        return True
Beispiel #6
0
    def cancel(self):
        """取消"""

        try:
            self.check()
        except OrderException as e:
            raise e

        data = {
            'order_status': 3,
            'cancel_status': self.cancel_status,
            'cancel_desc': self.cancel_desc,
            'cancel_time': self.current_time,
            'update_time': self.current_time}
        model_update(self.order, data)

        # 站内消息
        content = _(u'您的订单%s已取消。' % self.order.order_sn)
        mcs = MessageCreateService(
            1,
            self.order.uid,
            -1,
            content,
            ttype=1,
            tid=self.order.order_id,
            current_time=self.current_time)
        if not mcs.check():
            log_error('order_id:%s msg:%s' % (self.order.order_id, mcs.msg))
        else:
            mcs.do()

        self.commit()
        return True
Beispiel #7
0
    def reset_last_time(uid, last_type):
        """重置最新时间"""

        current_time = current_timestamp()

        ult = UserLastTime.query.\
                filter(UserLastTime.uid == uid).\
                filter(UserLastTime.last_type == last_type).first()

        model_update(ult, {'last_time': current_time}, commit=True)

        return True
Beispiel #8
0
def update():
    """更新购物车"""
    resjson.action_code = 12

    uid = get_uid()
    session_id = session.sid

    args = request.args
    cart_id = toint(args.get('cart_id', 0))
    quantity = toint(args.get('quantity', 0))
    current_time = current_timestamp()

    # 检查
    if cart_id <= 0 or quantity <= 0:
        return resjson.print_json(resjson.PARAM_ERROR)

    # 获取购物车商品
    q = Cart.query.filter(Cart.cart_id == cart_id).filter(
        Cart.checkout_type == 1)
    if uid:
        q = q.filter(Cart.uid == uid)
    else:
        q = q.filter(Cart.session_id == session_id)
    cart = q.first()
    if cart is None:
        return resjson.print_json(10, _(u'购物车里找不到商品'))

    # 更新购物车商品
    data = {'quantity': quantity, 'update_time': current_time}
    model_update(cart, data, commit=True)

    cs = CartService(uid, session_id)
    cs.check()
    session['cart_total'] = cs.cart_total

    for _cart in cs.carts:
        if _cart['cart'].cart_id == cart_id:
            _items_amount = _cart['items_amount']

    # 商品状态
    item = Goods.query.get(cart.goods_id)
    is_valid, valid_status = CartStaticMethodsService.check_item_statue(
        item, cart)

    data = {
        'cart_total': cs.cart_total,
        'items_quantity': cs.items_quantity,
        'items_amount': cs.items_amount,
        '_items_amount': _items_amount,
        'is_valid': is_valid,
        'valid_status': valid_status
    }
    return resjson.print_json(0, u'ok', data)
Beispiel #9
0
    def update(self):
        """ 更新 """

        # 更新
        model_update(self.funds_obj, {'funds':self.funds, 'update_time':self.current_time})

        # 创建流水
        data = {'uid':self.uid, 'funds_prev':self.funds_prev, 'funds_change':self.funds_change, 'funds':self.funds,
                'event':self.event, 'ttype':self.ttype, 'tid':self.tid, 'remark_user':self.remark_user,
                'remark_sys':self.remark_sys, 'add_time':self.current_time}
        self.funds_detail = model_create(FundsDetail, data)

        return True
Beispiel #10
0
def checked():
    """选中"""
    resjson.action_code = 14

    uid = get_uid()
    session_id = session.sid

    carts = request.args.get('carts', '[]').strip()
    current_time = current_timestamp()

    try:
        carts = json.loads(carts)
    except Exception as e:
        return resjson.print_json(resjson.PARAM_ERROR)
    for cart in carts:
        cart_id = toint(cart.get('cart_id', 0))
        is_checked = toint(cart.get('is_checked', -1))

        # 检查
        if cart_id <= 0 or is_checked not in [0, 1]:
            return resjson.print_json(resjson.PARAM_ERROR)

        # 获取购物车商品
        q = Cart.query.filter(Cart.cart_id == cart_id).filter(
            Cart.checkout_type == 1)
        if uid:
            q = q.filter(Cart.uid == uid)
        else:
            q = q.filter(Cart.session_id == session_id)
        cart = q.first()
        if cart is None:
            return resjson.print_json(10, _(u'购物车里找不到商品'))

        # 更新购物车商品
        data = {'is_checked': is_checked, 'update_time': current_time}
        model_update(cart, data)

    db.session.commit()

    cs = CartService(uid, session_id)
    cs.check()

    data = {
        'cart_total': cs.cart_total,
        'items_quantity': cs.items_quantity,
        'items_amount': cs.items_amount
    }
    return resjson.print_json(0, u'ok', data)
Beispiel #11
0
def save():
    """保存商品"""
    g.page_title = _(u'保存商品')

    form = ItemForm(CombinedMultiDict((request.files, request.form)))
    current_time = current_timestamp()

    if not form.validate_on_submit():
        return render_template('admin/item/detail.html.j2',
                               form=form,
                               item=form.data)

    goods_img = ''
    if form.goods_img.data:
        fus = FileUploadService()
        try:
            goods_img = fus.save_storage(form.goods_img.data, 'item')
        except Exception as e:
            form.goods_img.errors = (_(u'上传失败,请检查云存储配置'))
            return render_template('admin/item/detail.html.j2',
                                   form=form,
                                   item=form.data)

    goods_id = toint(form.goods_id.data)
    if goods_id:
        item = Goods.query.get_or_404(goods_id)
    else:
        item = model_create(Goods, {'detail': '', 'add_time': current_time})

    goods_img = goods_img if goods_img else item.goods_img
    data = {
        'cat_id': form.cat_id.data,
        'goods_name': form.goods_name.data,
        'goods_img': goods_img,
        'goods_desc': form.goods_desc.data,
        'goods_price': form.goods_price.data,
        'market_price': form.market_price.data,
        'is_sale': form.is_sale.data,
        'stock_quantity': form.stock_quantity.data,
        'is_hot': form.is_hot.data,
        'is_recommend': form.is_recommend.data,
        'update_time': current_time
    }
    model_update(item, data, commit=True)

    return redirect(url_for('admin.item.index'))
Beispiel #12
0
def coupon_save():
    """优惠券派发保存"""

    admin_uid = session.get('admin_uid', None)
    if not admin_uid:
        return_url = request.args.get('return_url', '/admin/dashboard')
        return redirect(url_for('admin.auth.login', return_url=return_url))

    form = CouponForm(request.form)
    form.avatar.data = request.args.get('avatar')

    if not form.validate_on_submit():
        return render_template('admin/user/coupon.html.j2', form=form)

    coupon_batch = CouponBatch.query.filter(
        CouponBatch.cb_id == form.cb_id.data).first()

    if not coupon_batch:
        return render_template('admin/user/coupon.html.j2', form=form)

    #刷新优惠券数据
    give_num = coupon_batch.give_num + 1
    data = {'give_num': give_num}
    model_update(coupon_batch, data)

    coupon = model_create(Coupon, {'add_time': current_timestamp()})

    data = {
        'uid': form.uid.data,
        'cb_id': coupon_batch.cb_id,
        'coupon_name': coupon_batch.coupon_name,
        'begin_time': coupon_batch.begin_time,
        'end_time': coupon_batch.end_time,
        'is_valid': coupon_batch.is_valid,
        'limit_amount': coupon_batch.limit_amount,
        'coupon_amount': coupon_batch.coupon_amount,
        'limit_goods': coupon_batch.limit_goods,
        'limit_goods_name': coupon_batch.limit_goods_name,
        'coupon_from': coupon_batch.coupon_from,
        'update_timne': current_timestamp()
    }

    model_update(coupon, data, True)

    return redirect(url_for('admin.user.detail', uid=form.uid.data))
Beispiel #13
0
    def __request_token(self):
        """获取token"""

        if not self.__check():
            raise Exception(_(u'请先配置公众号'))

        params = {
            'grant_type': 'client_credential',
            'appid': self.appid.encode('utf8'),
            'secret': self.secret.encode('utf8')
        }
        url = 'https://api.weixin.qq.com/cgi-bin/token'
        url = u'%s?%s' % (url, urlencode(params))

        response = requests.get(url)
        if response.status_code != 200:
            log_error('[WeixinAccesstoken][RequestError]  request error.')
            raise Exception(_(u'网络错误'))

        data = response.json()
        errcode = data.get('errcode', 0)
        errmsg = data.get('errmsg', '')
        if errcode > 0:
            log_error('[WeixinAccesstoken][RequestError]  errcode:%s  errmsg:%s' %\
                (errcode, errmsg))
            raise Exception(errmsg)

        token = data.get('access_token', '')
        expires_in = data.get('expires_in', 0)

        if not self.st:
            self.st = model_create(SysToken, {
                'token_type': 'weixin_mp_token',
                'add_time': self.current_time
            })

        expires_in = self.current_time + expires_in - 60
        model_update(self.st, {
            'access_token': token,
            'expires_in': expires_in
        },
                     commit=True)

        return token
Beispiel #14
0
def remove():
    """删除评论"""
    resjson.action_code = 10

    comment_id = toint(request.args.get('comment_id', '0'))

    if comment_id <= 0:
        return resjson.print_json(resjson.PARAM_ERROR)

    comment = Comment.query.get(comment_id)
    if not comment:
        return resjson.print_json(10, _(u'评论不存在'))

    if comment.is_show == 0:
        return resjson.print_json(0, u'ok')

    model_update(comment, {'is_show': 0}, commit=True)

    return resjson.print_json(0, u'ok')
Beispiel #15
0
def remove():
    """删除商品"""
    resjson.action_code = 10

    goods_id = toint(request.args.get('goods_id', '0'))

    if goods_id <= 0:
        return resjson.print_json(resjson.PARAM_ERROR)

    item = Goods.query.get(goods_id)
    if not item:
        return resjson.print_json(10, _(u'商品不存在'))

    if item.is_delete == 1:
        return resjson.print_json(0, u'ok')

    model_update(item, {'is_delete': 1}, commit=True)

    return resjson.print_json(0, u'ok')
Beispiel #16
0
def category_save():
    """保存分类"""
    g.page_title = _(u'保存分类')

    form = CategoryForm(CombinedMultiDict((request.files, request.form)))

    if not form.validate_on_submit():
        return render_template('admin/post/category_detail.html.j2', form=form)

    cat_id = toint(form.cat_id.data)
    if cat_id:
        category = PostCategories.query.get_or_404(cat_id)
    else:
        category = model_create(PostCategories, {'add_time':current_timestamp()})

    data   = {'cat_name':form.cat_name.data, 'is_show':form.is_show.data, 'sorting':form.sorting.data}
    model_update(category, data, commit=True)

    return redirect(url_for('admin.post.categories'))
Beispiel #17
0
def address_save():
    """保存地址"""
    resjson.action_code = 12

    if not check_login():
        return resjson.print_json(resjson.NOT_LOGIN)
    uid = get_uid()

    wtf_form = AddressForm()
    current_time = current_timestamp()

    if not wtf_form.validate_on_submit():
        for key, value in wtf_form.errors.items():
            msg = value[0]
        return resjson.print_json(11, msg)

    is_default = toint(request.form.get('is_default', '-1'))
    if is_default not in [-1, 0, 1]:
        return resjson.print_json(resjson.PARAM_ERROR)

    ua_id = wtf_form.ua_id.data
    if ua_id:
        user_address = UserAddress.query.filter(
            UserAddress.ua_id == ua_id).filter(UserAddress.uid == uid).first()
        if not user_address:
            return resjson.print_json(12, _(u'收货地址不存在'))
    else:
        data = {'uid': uid, 'is_default': 1, 'add_time': current_time}
        user_address = model_create(UserAddress, data)

    if is_default == -1:
        is_default = user_address.is_default

    data = {
        'name': wtf_form.name.data,
        'mobile': wtf_form.mobile.data,
        'province': wtf_form.province.data,
        'city': wtf_form.city.data,
        'district': wtf_form.district.data,
        'address': wtf_form.address.data,
        'is_default': is_default,
        'update_time': current_time
    }

    if is_default == 1:
        default = UserAddress.query.filter(UserAddress.uid == uid).filter(
            UserAddress.is_default == 1).first()
        if default and default.ua_id != ua_id:
            default.is_default = 0

    user_address = model_update(user_address, data)
    db.session.commit()

    return resjson.print_json(0, u'ok', {'ua_id': user_address.ua_id})
Beispiel #18
0
def save():
    """保存广告"""
    g.page_title = _(u'保存广告')

    form = AdvForm(CombinedMultiDict((request.files, request.form)))
    current_time = current_timestamp()

    if not form.validate_on_submit():
        return render_template('admin/adv/detail.html.j2', form=form)

    img = ''
    if form.img.data:
        fus = FileUploadService()
        try:
            img = fus.save_storage(form.img.data, 'adv')
        except Exception as e:
            form.img.errors = (_(u'上传失败,请检查云存储配置'))
            return render_template('admin/adv/detail.html.j2', form=form)

    adv_id = toint(form.adv_id.data)
    if adv_id:
        adv = Adv.query.get_or_404(adv_id)
    else:
        adv = model_create(Adv, {'add_time': current_time})

    img = img if img else adv.img
    data = {
        'ac_id': form.ac_id.data,
        'img': img,
        'desc': form.desc.data,
        'ttype': form.ttype.data,
        'tid': form.tid.data,
        'url': form.url.data,
        'sorting': form.sorting.data,
        'is_show': form.is_show.data,
        'platform_type': form.platform_type.data
    }
    model_update(adv, data, commit=True)

    return redirect(url_for('admin.adv.index'))
Beispiel #19
0
def return_goods():
    """寄回商品"""
    resjson.action_code = 12

    if not check_login():
        return resjson.print_json(resjson.NOT_LOGIN)
    uid = get_uid()

    aftersales_id = toint(request.form.get('aftersales_id', '0'))
    return_shipping_sn = request.form.get('return_shipping_sn', '').strip()
    current_time = current_timestamp()

    if aftersales_id <= 0 or return_shipping_sn == '':
        return resjson.print_json(resjson.PARAM_ERROR)

    aftersales = Aftersales.query.\
                    filter(Aftersales.aftersales_id == aftersales_id).\
                    filter(Aftersales.uid == uid).first()
    if not aftersales:
        return resjson.print_json(10, _(u'售后不存在'))

    if aftersales.aftersales_type not in [2, 3]:
        return resjson.print_json(11, _(u'售后类型错误'))

    if aftersales.return_status != 1:
        return resjson.print_json(12, _(u'寄回状态错误'))

    data = {'return_shipping_sn': return_shipping_sn, 'return_status': 2}
    model_update(aftersales, data)

    content = _(u'快递单号:%s,我们收到退货/换货商品后,需要1-3个工作日处理,请耐心等待。' %
                return_shipping_sn)
    AfterSalesStaticMethodsService.add_log(aftersales_id,
                                           content,
                                           6,
                                           current_time,
                                           commit=True)

    return resjson.print_json(0, u'ok')
Beispiel #20
0
def save():
    """保存文章"""
    g.page_title = _(u'保存文章')

    form         = PostForm(CombinedMultiDict((request.files, request.form)))
    current_time = current_timestamp()

    if not form.validate_on_submit():
        return render_template('admin/post/detail.html.j2', form=form, item=form.data)
        
    post_id  = toint(form.post_id.data)
    if post_id:
        item = Post.query.get_or_404(post_id)
    else:
        item = model_create(Post, {'post_detail':'', 'add_time':current_time})

    cat_id   = form.cat_id.data
    data     = db.session.query(PostCategories.cat_name).filter(PostCategories.cat_id==cat_id).first()

    data     = {'cat_id':form.cat_id.data, 'cat_name':data[0], 'post_name':form.post_name.data,   'is_publish':form.is_publish.data, 'sorting':form.sorting.data, 'update_time':current_time}
    model_update(item, data, commit=True)

    return redirect(url_for('admin.post.h5', post_id=item.post_id))
Beispiel #21
0
    def do(self):
        """退款"""
        refunds_status = 0  # 退款状态: 0.默认; 1.成功; 2.失败;
        refunds_sn = ''

        # 资金支付
        if self.third_type == 1:
            self.fs.update()
            self.fs.commit()

            refunds_status = 1
            refunds_sn = self.fs.funds_detail.fd_id

        # 微信
        if self.third_type == 2:
            # 是否退款成功
            if self.jwrs.refunds():
                refunds_status = 1
                refunds_sn = self.jwrs.refund_id
            else:
                refunds_status = 2
                return False

        data = {'refunds_status': refunds_status}
        if refunds_status == 1:
            data = {
                'refunds_sn': refunds_sn,
                'refunds_time': self.current_time,
                'refunds_status': refunds_status
            }

        model_update(self.refunds, data, commit=True)

        # 微信消息
        WeixinMessageStaticMethodsService.refund(self.refunds)

        return True
Beispiel #22
0
def save():
    """保存优惠券"""
    g.page_title = _(u'保存优惠券')

    form = CouponBatchForm(CombinedMultiDict((request.files, request.form)))
    current_time = current_timestamp()

    if not form.validate_on_submit():
        return render_template('admin/coupon/detail.html.j2', form=form)

    cb_id = toint(form.cb_id.data)
    if cb_id:
        batch = CouponBatch.query.get_or_404(cb_id)
    else:
        batch = model_create(CouponBatch, {'add_time': current_time})

    begin_time = str2timestamp(form.begin_time.data,
                               'YYYY-MM-DD') if form.begin_time.data else 0
    end_time = str2timestamp(form.end_time.data,
                             'YYYY-MM-DD') if form.end_time.data else 0
    data = {
        'cb_name': form.cb_name.data,
        'begin_time': begin_time,
        'end_time': end_time,
        'coupon_name': form.coupon_name.data,
        'is_valid': form.is_valid.data,
        'publish_num': form.publish_num.data,
        'limit_amount': form.limit_amount.data,
        'coupon_amount': form.coupon_amount.data,
        'date_num': form.date_num.data,
        'coupon_from': form.coupon_from.data,
        'update_time': current_time
    }
    model_update(batch, data, commit=True)

    return redirect(url_for('admin.coupon.index'))
Beispiel #23
0
def update_address():
    """更新订单收货地址"""
    resjson.action_code = 20

    if not check_login():
        return resjson.print_json(resjson.NOT_LOGIN)
    uid = get_uid()

    wtf_form = OrderAddressForm()
    current_time = current_timestamp()

    if not wtf_form.validate_on_submit():
        for key, value in wtf_form.errors.items():
            msg = value[0]
        return resjson.print_json(11, msg)

    order_address = OrderAddress.query.get(wtf_form.oa_id.data)
    if not order_address:
        return resjson.print_json(12, _(u'订单地址不存在'))

    order = Order.query.\
        filter(Order.order_id == order_address.order_id).\
        filter(Order.uid == uid).first()
    if not order:
        return resjson.print_json(13, _(u'订单不存在'))

    if order.pay_status != 1:
        return resjson.print_json(14, _(u'未付款订单才可以修改地址'))

    data = {'name': wtf_form.name.data, 'mobile': wtf_form.mobile.data,
            'province': wtf_form.province.data, 'city': wtf_form.city.data,
            'district': wtf_form.district.data, 'address': wtf_form.address.data,
            'update_time': current_time}
    model_update(order_address, data, commit=True)

    return resjson.print_json(0, u'ok')
Beispiel #24
0
def category_save():
    """保存分类"""
    g.page_title = _(u'保存分类')

    form = CategoryForm(CombinedMultiDict((request.files, request.form)))

    if not form.validate_on_submit():
        return render_template('admin/item/category_detail.html.j2', form=form)

    cat_img = ''
    if form.cat_img.data:
        fus = FileUploadService()
        try:
            cat_img = fus.save_storage(form.cat_img.data, 'category')
        except Exception as e:
            form.cat_img.errors = (_(u'上传失败,请检查云存储配置'))
            return render_template('admin/item/category_detail.html.j2',
                                   form=form)

    cat_id = toint(form.cat_id.data)
    if cat_id:
        category = GoodsCategories.query.get_or_404(cat_id)
    else:
        category = model_create(GoodsCategories,
                                {'add_time': current_timestamp()})

    cat_img = cat_img if cat_img else category.cat_img
    data = {
        'cat_name': form.cat_name.data,
        'cat_img': cat_img,
        'is_show': form.is_show.data,
        'is_recommend': form.is_recommend.data
    }
    model_update(category, data, commit=True)

    return redirect(url_for('admin.item.categories'))
Beispiel #25
0
    def update(self):
        """更新订单"""

        try:
            self.check()
        except OrderException as e:
            raise e

        discount_desc = None

        # 删除已用订单地址
        model_delete(self.order_address)

        # 创建订单地址
        data = {
            'order_id': self.order_id,
            'name': self.shipping_address.name,
            'mobile': self.shipping_address.mobile,
            'province': self.shipping_address.province,
            'city': self.shipping_address.city,
            'district': self.shipping_address.district,
            'address': self.shipping_address.address,
            'zip': self.shipping_address.zip,
            'add_time': self.current_time,
            'update_time': self.current_time}
        model_create(OrderAddress, data)

        # 还原已用优惠券
        if self._coupon and self._coupon != self.coupon:
            data = {
                'is_valid': 1,
                'order_id': 0,
                'use_time': 0}
            model_update(self._coupon, data)

            discount_desc = ''

        # 使用优惠券
        if self.coupon:
            data = {
                'is_valid': 0,
                'order_id': self.order_id,
                'use_time': self.current_time}
            model_update(self.coupon, data)

            discount_desc = _(u'使用优惠券%s: %s' %
                              (self.coupon.coupon_id, self.coupon.coupon_name))

        # 更新订单金额
        self.order_amount = self.items_amount + self.shipping_amount

        # 更新应付金额
        self.pay_amount = self.order_amount - self.discount_amount

        # 更新订单
        data = {
            'goods_amount': self.items_amount,
            'order_amount': self.order_amount,
            'discount_amount': self.discount_amount,
            'pay_amount': self.pay_amount,
            'shipping_id': self.shipping_id,
            'shipping_name': self.shipping.shipping_name,
            'shipping_code': self.shipping.shipping_code,
            'shipping_amount': self.shipping_amount,
            'update_time': self.current_time}

        if discount_desc is not None:
            data['discount_desc'] = discount_desc

        model_update(self.order, data)

        db.session.commit()

        return True
Beispiel #26
0
    def paid(self):
        """已付款业务处理"""

        pay_tran_id = self.kwargs.get('pay_tran_id', '')
        pay_method = self.kwargs.get('pay_method', '')
        paid_time = self.kwargs.get('paid_time', self.current_time)
        paid_amount = Decimal(self.kwargs.get('paid_amount', '0.00'))

        log_info('[PaidService] tran_id:%s paid_amount:%.2f' % (
            self.tran_id, paid_amount))

        # 检查 - 交易
        tran = OrderTran.query.get(self.tran_id)
        if not tran:
            log_info(
                '[PaidService] not found tran: tran_id:%s' % self.tran_id)
            raise OrderException(_(u'找不到订单'))

        # 检查 - 订单
        order_id_list = json.loads(tran.order_id_list)
        order_list = Order.query.filter(
            Order.order_id.in_(order_id_list)).all()
        if not order_list:
            log_info(
              '[PaidService] not found order list: tran_id:%s' % self.tran_id)
            raise OrderException(_(u'找不到订单'))

        # 检查 - 是否已经处理过
        if tran.pay_status == 2:
            log_info('[PaidService] do already: tran_id:%s' % self.tran_id)
            return tran

        # 更新交易
        model_update(
            tran, {
                'pay_status': 2,
                'pay_method': pay_method,
                'paid_time': paid_time})

        # 更新交易 - 支付流水号
        if pay_tran_id:
            model_update(tran, {'pay_tran_id': pay_tran_id})

        # 提交交易事务
        db.session.commit()

        # 遍历更新订单及订单商品等
        for order in order_list:
            order_id = order.order_id

            # 更新订单
            data = {
                'tran_id': self.tran_id,
                'pay_method': tran.pay_method,
                'pay_status': 2,
                'pay_tran_id': tran.pay_tran_id,
                'paid_time': paid_time,
                'paid_amount': order.pay_amount,
                'update_time': paid_time}

            # 普通订单
            if order.order_type == 1:
                # 订单商品列表
                og_list = OrderGoods.query.filter(
                    OrderGoods.order_id == order_id).all()
                for og in og_list:
                    goods = Goods.query.get(og.goods_id)
                    if goods:
                        # 销量
                        sale_count = goods.sale_count + og.goods_quantity

                        # 库存
                        stock_quantity = goods.stock_quantity - og.goods_quantity

                        # 更新商品
                        model_update(
                            goods, {
                                'sale_count': sale_count,
                                'stock_quantity': stock_quantity})

                # 更新订单
                data['shipping_status'] = 1

            # 充值订单
            if order.order_type == 2:
                # 更新余额 - 充值 - 检查
                remark_user = _(u'充值成功')
                remark_sys = _(u'充值: 订单ID:%s 支付方式:%s 第三方支付流水号:%s' %
                               (order_id, tran.pay_method, tran.pay_tran_id))
                fs = FundsService(
                    order.uid,
                    order.goods_amount,
                    1,
                    1,
                    self.tran_id,
                    remark_user,
                    remark_sys,
                    paid_time)
                if not fs.check():
                    log_error(
                        '[FundsServiceError01]  remark_sys:%s' % remark_sys)
                    continue

                # 更新余额 - 充值
                fs.update()

            model_update(order, data)

            # 站内消息
            if order.order_type == 1:
                content = _(u'您的订单%s已支付,我们会尽快发货。' % order.order_sn)
                mcs = MessageCreateService(
                    1,
                    order.uid,
                    -1, content,
                    ttype=1,
                    tid=order_id,
                    current_time=self.current_time)
                if not mcs.check():
                    log_error('order_id:%s msg:%s' % (order_id, mcs.msg))
                else:
                    mcs.do()

            # 提交订单事务
            db.session.commit()

            # 微信消息
            if order.order_type == 2:
                WeixinMessageStaticMethodsService.recharge(order)
            else:
                WeixinMessageStaticMethodsService.paid(order)

        return True
Beispiel #27
0
def add():
    """加入购物车"""
    resjson.action_code = 11

    uid = get_uid()
    session_id = session.sid

    args = request.args
    order_id = toint(args.get('order_id', '0'))
    goods_id = toint(args.get('goods_id', '0'))
    quantity = toint(args.get('quantity', '1'))
    current_time = current_timestamp()
    items_data = []

    if order_id > 0:
        order = Order.query.filter(Order.order_id == order_id).filter(
            Order.uid == uid).first()
        if not order:
            return resjson.print_json(resjson.PARAM_ERROR)

        order_goods = OrderGoods.query.filter(
            OrderGoods.order_id == order_id).all()
        for _order_goods in order_goods:
            items_data.append({
                'goods_id': _order_goods.goods_id,
                'quantity': _order_goods.goods_quantity
            })
    else:
        # 检查
        if goods_id <= 0 or quantity < 1:
            return resjson.print_json(resjson.PARAM_ERROR)

        items_data.append({'goods_id': goods_id, 'quantity': quantity})

    for item_data in items_data:
        goods_id = item_data.get('goods_id')
        quantity = item_data.get('quantity')

        # 检查
        item = Goods.query.get(goods_id)
        if not item:
            return resjson.print_json(10, _(u'找不到商品'))

        # 获取购物车商品
        q = Cart.query.filter(Cart.goods_id == goods_id).filter(
            Cart.checkout_type == 1)
        if uid:
            q = q.filter(Cart.uid == uid)
        else:
            q = q.filter(Cart.session_id == session_id)
        cart = q.first()

        # 计算商品购买数量
        quantity += cart.quantity if cart else 0

        if order_id <= 0 and quantity > item.stock_quantity:
            return resjson.print_json(11, u'库存不足')

        # 是否创建购物车商品
        if not cart:
            data = {
                'uid': uid,
                'session_id': session_id,
                'goods_id': goods_id,
                'quantity': 0,
                'is_checked': 1,
                'checkout_type': 1,
                'add_time': current_time
            }
            cart = model_create(Cart, data)
        # 更新购物车商品

        data = {'quantity': quantity, 'update_time': current_time}
        cart = model_update(cart, data)

    db.session.commit()

    cs = CartService(uid, session_id)
    cs.check()
    session['cart_total'] = cs.cart_total

    return resjson.print_json(0, u'ok', {
        'cart_total': cs.cart_total,
        'cart_num': quantity
    })
    def create(self):
        """创建"""

        aftersales_sn = AfterSalesStaticMethodsService.create_aftersales_sn(
            self.current_time)

        for data in self.goods_data:
            if self.og_id > 0:
                data.pop('maximum')
        goods_data = json.dumps(self.goods_data)

        data = {
            'aftersales_sn': aftersales_sn,
            'uid': self.uid,
            'order_id': self.order.order_id,
            'aftersales_type': self.aftersales_type,
            'deliver_status': self.deliver_status,
            'content': self.content,
            'img_data': self.img_data,
            'status': 1,
            'check_status': 1,
            'refunds_amount': self.refunds_amount,
            'refunds_method': self.order.pay_method,
            'latest_log': u'',
            'goods_data': goods_data,
            'quantity': self.quantity,
            'add_time': self.current_time,
            'update_time': self.current_time
        }
        aftersales = model_create(Aftersales, data, commit=True)

        for data in self.goods_data:
            data['aftersales_id'] = aftersales.aftersales_id
            model_create(AftersalesGoods, data)

        # 售后商品数量 - 单个
        if self.order_goods:
            quantity = self.order_goods.aftersales_goods_quantity + self.quantity
            data = {
                'aftersales_goods_quantity': quantity,
                'update_time': self.current_time
            }
            model_update(self.order_goods, data)

        # 售后商品数量 - 整单
        if len(self.order_goods_list) > 0:
            for order_goods in self.order_goods_list:
                data = {
                    'aftersales_goods_quantity': order_goods.goods_quantity,
                    'update_time': self.current_time
                }
                model_update(order_goods, data)

        AfterSalesStaticMethodsService.add_log(aftersales.aftersales_id,
                                               _(u'申请售后服务,等待商家审核。'), 1,
                                               self.current_time, False)

        # 售后地址
        if self.address_data:
            self.address_data['aftersales_id'] = aftersales.aftersales_id
            model_create(AftersalesAddress, self.address_data)

        db.session.commit()

        return aftersales.aftersales_id