Exemplo n.º 1
0
    def post(self):
        form = Form(self.request.arguments, add_schema)
        goods_info, shops, properties, img = get_goods_info(self.db, form.id.value)

        if goods_info.supplier_id != self.current_user.supplier_id:
            raise HTTPError(403)

        if goods_info.status not in ['PREPARE', 'REJECT']:
            raise HTTPError(403)

        # 为了下面的 validate 成功 这里必须填入数据
        form.arguments.update({'generate_type': EmptyDict({'value': goods_info.generate_type})})
        img_paths = dict()
        for key in self.request.arguments:
            if key.startswith('var_img_path_'):
                v = self.request.arguments[key][0]
                if v:
                    img_paths[key[key.rindex('_')+1:]] = v
        form.img_paths['value'] = json_dumps(img_paths)
        if not form.validate():
            form.properties.value = properties
            form.shops['value'] = shops
            form.img_paths['value'] = img_paths

            supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0',
                                           self.current_user.supplier_id)
            logging.error(json_dumps(form.errors))
            self.render('goods/add.html', form=form, error='', action='edit', supplier_shops=supplier_shops,
                        img_url=img_url)

        fields = ('type', 'generate_type', 'expire_at', 'category_id', 'name', 'short_name', 'sms_name', 'face_value',
                  'sales_price', 'purchase_price', 'stock', 'virtual_sales_count', 'img_path', 'detail', 'tips',
                  'supplier_intro', 'all_shop', 'on_sale_at', 'off_sale_at', 'img_paths', 'postage')

        update_sql = 'update goods set %s where id=%%s' % ','.join([field + '=%s' for field in fields])

        form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None
        form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None
        params = [form.arguments[field]['value'] for field in fields]
        params.append(form.id.value)

        self.db.execute(update_sql, *params)

        self.db.execute('insert into journal(created_at, type, created_by, message, iid) '
                        'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '商户修改了商品', form.id.value)

        # 批量更新商品属性
        self.db.execute('delete from goods_property where goods_id=%s and name in ("gift_card", "hidden", "ktv")',
                        form.id.value)
        if form.properties.value:
            insert_properties(self.db, form.properties.value, form.id.value)

        # 批量更新关联门店
        self.db.execute('delete from goods_supplier_shop where goods_id=%s', form.id.value)
        if not form.all_shop.value:
            if form.shops.value:
                insert_shops(self.db, form.shops.value, form.id.value)

        self.redirect(self.reverse_url('goods.list'))
Exemplo n.º 2
0
    def post(self):
        form = Form(self.request.arguments, add_schema)
        img_paths = dict()
        for key in self.request.arguments:
            if key.startswith('var_img_path_'):
                v = self.request.arguments[key][0]
                if v:
                    img_paths[key[key.rindex('_')+1:]] = v

        if not form.validate():
            supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0',
                                           self.current_user.supplier_id)
            form.img_paths['value'] = img_paths
            logging.error(json_dumps(form.errors))
            return self.render('wx/mall/goods_add.html', form=form, error='error', action='add', supplier_shops=supplier_shops,
                               img_url=img_url)
        # 获取微信商品手续费
        commission = self.db.get('select value from supplier_property where sp_id=%s and name="wx_commission"',
                                 self.current_user.supplier_id)
        if not commission:
            rate = Decimal((100 - options.wx_min_commission)/100.0)
        else:
            rate = Decimal((100 - int(commission.value))/100.0)
        # 更新结算价
        form.arguments['purchase_price']['value'] = form.arguments['sales_price']['value'] * rate

        fields = ('type', 'generate_type', 'expire_at', 'category_id', 'short_name', 'sms_name',
                  'max_buy', 'on_sale_at', 'off_sale_at', 'face_value', 'sales_price', 'purchase_price',
                  'stock', 'img_path', 'all_shop', 'detail',  'postage')

        goods_sql = """
            insert into goods(%s, supplier_id, created_by, img_paths, created_at, status, name)
            values (%s, %%s, %%s, %%s, NOW(), "PREPARE", "")""" % (','.join(fields), ','.join(['%s']*len(fields)))

        form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None
        form.on_sale_at['value'] = form.on_sale_at.value if form.off_sale_at.value else None
        form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None
        params = [form.arguments[field]['value'] for field in fields]

        params.extend([self.current_user.supplier_id, self.current_user.name, json_dumps(img_paths)])

        goods_id = self.db.execute_lastrowid(goods_sql, * params)

        self.db.execute('insert into journal(created_at, type, created_by, message, iid) '
                        'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '商户新增了微商城商品', goods_id)

        # 批量插入关联的门店
        if not form.all_shop.value:
            if form.shops.value:
                insert_shops(self.db, form.shops.value, goods_id)

        # 插入微信商品特有属性
        self.db.execute('insert into goods_property (goods_id, name, value) values '
                        '(%s, "is_wx_goods", %s)', goods_id, "1")
        self.db.execute('insert into goods_property (goods_id, name, value) values '
                        '(%s, "is_wx_on_sale", %s)', goods_id, "0")

        self.redirect(self.reverse_url('wx.goods.list'))
Exemplo n.º 3
0
    def post(self):
        form = Form(self.request.arguments, add_schema)

        img_paths = dict()
        for key in self.request.arguments:
            if key.startswith('var_img_path_'):
                v = self.request.arguments[key][0]
                if v:
                    img_paths[key[key.rindex('_')+1:]] = v
        form.img_paths['value'] = json_dumps(img_paths)

        if not form.validate():
            supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0',
                                           form.supplier_id.value)
            distributors = self.db.query('select * from distributor_shop where deleted = 0')
            all_sku = self.db.query('select * from sku where deleted=0 and supplier_id=%s', form.supplier_id.value)
            form.img_paths['value'] = img_paths
            logging.error(json_dumps(form.errors))

            return self.render('goods/add.html', form=form, error='error', action='add', img_url=img_url,
                               supplier_shops=supplier_shops, all_sku=all_sku, distributors=distributors)

        fields = ('type', 'generate_type', 'expire_at', 'category_id', 'name', 'short_name', 'sms_name', 'img_paths',
                  'face_value', 'sales_price', 'purchase_price', 'stock', 'virtual_sales_count', 'img_path', 'all_shop',
                  'detail', 'tips', 'supplier_intro', 'created_by', 'supplier_id', 'on_sale_at', 'off_sale_at')

        goods_sql = 'insert into goods(%s, created_at, status) values (%s ,NOW(), "ON_SALE")' % (
            ','.join(fields), ','.join(['%s']*len(fields)))

        form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None
        form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None
        form.arguments['created_by'] = EmptyDict({'value': self.current_user.name})

        params = [form.arguments[field]['value'] for field in fields]

        goods_id = self.db.execute_lastrowid(goods_sql, * params)
        self.db.execute('insert into journal(created_at, type, created_by, message, iid) '
                        'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '新增了商品', goods_id)

        # 批量插入商品属性
        if form.properties.value:
            insert_properties(self.db, form.properties.value, goods_id)

        # 批量插入关联的门店
        if not form.all_shop.value:
            if form.shops.value:
                insert_shops(self.db, form.shops.value, goods_id)

        # 批量插入SKU信息
        if form.skus.value:
            insert_skus(self.db, form.skus.value, goods_id)
        # 批量插入分销店铺佣金
        if form.ratios.value:
            insert_ratios(self.db, form.ratios.value, goods_id)
        self.redirect(self.reverse_url('goods.show_list'))
Exemplo n.º 4
0
    def post(self):
        params = dict([(name, self.get_argument(name).encode('utf-8'))
                       for name in self.request.arguments])
        params.pop('_xsrf')

        shop_id = params.pop('shop_id')
        shop = self.db.get(
            'select taobao_seller_id, taobao_api_info from distributor_shop where id=%s',
            shop_id)
        api_info = json.loads(shop.taobao_api_info, object_hook=json_hook)

        jingdong = Jingdong(self.get_argument('method'),
                            str(shop.taobao_seller_id), api_info.vender_key,
                            api_info.secret_key)
        response = yield jingdong.fetch(**params)
        jingdong.parse_response(response.body)
        if jingdong.is_ok():
            if params['method'] == 'teamExtension':
                params['sale_end_date'] = ceiling(datetime.strptime(
                    params['sale_end_date'], '%Y-%m-%d %H:%M:%S'),
                                                  today=True)
                self.db.execute(
                    'update goods_distributor_shop set offsale_at = %s where id = %s',
                    params['sale_end_date'], params['product_id'])
            message = '修改成功'
        else:
            message = '修改失败, 失败原因: ' + jd_error.get(
                self.get_argument('method'), {}).get(int(jingdong.result_code),
                                                     '')

        self.render('goods/distributor/jd/result.html', message=message)
Exemplo n.º 5
0
    def post(self):
        form = Form(self.request.arguments, add_schema)
        if not form.validate():
            logging.error(form.errors)
            self.render('wx/activity/edit.html', form=form, error='参数不正确', action='add')
            return

        # 添加新的微活动
        fields = ('type', 'name', 'start_at', 'expire_at', 'detail', 'win_desc', 'lose_desc', 'due_desc', 'max_try',
                  'daily_try', 'rewards_possibility')
        sql = """insert into wx_activity (%s,  sp_id, created_at, deleted) values  (%s, %%s, NOW(), 0)"""\
              % (','.join(fields), ','.join(['%s']*len(fields)))

        form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None
        params = [form.arguments[field]['value'] for field in fields]
        params.extend([self.current_user.supplier_id])
        activity_id = self.db.execute(sql, *params)

        # 添加相关的奖品信息
        r_types = self.get_arguments('rewards_type')
        r_names = self.get_arguments('rewards_name')
        r_nums = [int(i) for i in self.get_arguments('rewards_num')]
        for i in range(len(r_types)):
            rewards_id = self.db.execute('insert into wx_activity_rewards (act_id, type, name, num) values '
                                         '(%s, %s, %s, %s)', activity_id, r_types[i], r_names[i], r_nums[i])
            # 产生兑奖SN码
            generate_sn(self.db, rewards_id, r_nums[i])

        self.redirect(self.reverse_url('wx.activity.list'))
Exemplo n.º 6
0
    def post(self):
        form = Form(self.request.arguments, add_schema)
        # flag为2时表示广告费
        if self.get_argument('flag') == '2':
            fee_sql = """insert into external_money(amount, uid, source, expire_at, created_at, created_by, type,
                         remark, flag, deleted) values(%s, %s, %s, %s, NOW(), %s, 1, %s, %s, 0)"""
            flag = {'ONLINE_FEE': 0, 'ADS_FEE': 1, 'OPERATE_FEE': 2}.get(form.received_type.value, 'ONLINE_FEE')
            params = [form.fee.value, form.supplier.value, 2, form.received_at.value, self.current_user.name,
                      form.fee_remark.value, flag]
            trade_id = self.db.execute(fee_sql, *params)

            # #将该广告费加入对应销售的帐下
            self.db.execute('insert into supplier_ads_fee(supplier_id, created_at, fee, received_at, type, remark) '
                            'values(%s, NOW(), %s, %s, %s, %s)', form.supplier.value, form.fee.value,
                            form.received_at.value, flag, form.fee_remark.value)
             # 记录日志
            self.db.execute('insert into journal (created_at, type, created_by, message, iid)'
                            'values (NOW(), 5, %s, %s, %s)',
                            self.current_user.name, "广告费添加 fee_id:%s" % trade_id,
                            trade_id)
        # flag为3时表示微信收费, 后期可扩展, 目前只记一笔到外部资金, 插一条日志,type=6
        elif self.get_argument('flag') == '3':
            sql = """insert into external_money (amount, uid, source, expire_at, created_at, created_by, remark,
            flag, deleted, type) values (%s,%s,%s,%s,now(),%s,%s,%s,0,1)"""
            flag = 0  # 暂时记为微信服务费
            source = 3  # 来源记为3
            trade_id = self.db.execute(sql, form.amount.value.strip(), form.supplier.value, source,
                                       form.expire_at.value, self.current_user.name, form.remark.value, flag)
            # 记录日志
            self.db.execute('insert into journal (created_at, type, created_by, message, iid)'
                            'values (NOW(), 6, %s, %s, %s)',
                            self.current_user.name, "微信收费.trade_id:%s" % trade_id,
                            trade_id)

        else:
            form.expire_at.value = ceiling(datetime.strptime(form.expire_at.value, '%Y-%m-%d'), today=True)
            #我们给商户时,给flag设值
            if form.source.value == '0':
                form.flag.value = form.type.value
            sql = """ insert into external_money (amount,uid,source,expire_at,created_at,created_by,remark,flag,
            deleted,type) values (%s,%s,%s,%s,now(),%s,%s,%s,0,1) """
            trade_id = self.db.execute(sql, form.amount.value.strip(), form.supplier.value, form.source.value,
                                       form.expire_at.value, self.current_user.name, form.remark.value, form.flag.value)

            # 查找商户及门店的账户
            supplier_shop_account_id = self.db.get('select ss.account_id from supplier s,supplier_shop ss '
                                                   'where s.id=ss.supplier_id and s.deleted =0 and s.id=%s limit 1',
                                                   form.supplier.value).account_id
            #我们给商户场合,预付款(前期销售额不能提现)或者商户给我的保证金从销售额中扣除的场合,都要记一笔资金
            if (form.source.value == '0' and form.type.value == '0') or \
                    (form.source.value == '1' and form.type.value == '0'):
                #seq 中加一条 负资金
                self.db.execute('insert into account_sequence(type, trade_id, account_id,created_at, amount,remark) '
                                'values(%s, %s, %s, NOW(), %s, %s)', const.seq.PRE_PAYMENT, trade_id,
                                supplier_shop_account_id, -Decimal(form.amount.value), "付给商户的预付款(前期销售额不能提现)")

        self.redirect('/external-money')
Exemplo n.º 7
0
    def post(self):
        sql = """update contract set start_at=%s, expire_at=%s, remark=%s where id=%s"""
        form = Form(self.request.arguments, supplier_schema)
        expire_at = datetime.strptime(str(form.expire_at.value), '%Y-%m-%d')

        #插入数据
        self.db.execute(sql, form.start_at.value, ceiling(expire_at, today=True), form.remark.value, form.id.value)
        contract_id = form.id.value

        self.redirect(self.reverse_url('supplier.contract_upload', contract_id))
Exemplo n.º 8
0
    def post(self):
        """推送商品"""
        arg = lambda k: self.get_argument(k).encode('utf-8')
        goods_id = self.get_argument('goods_id')

        dg = alloc_distributor_goods(self.db, goods_id, options.shop_id_wuba)
        params = dict([(name, self.get_argument(name).encode('utf-8')) for name in self.request.arguments])

        params.pop("goods_id")
        params.pop("_xsrf")
        params['groupbuyId'] = dg.goods_link_id
        prod_model_json = dict(prodmodcatename=arg('prodName'), prodprice=arg('prodPrice'),
                               groupprice=arg('groupPrice'), prodcode='', count=arg('saleMaxNum'))

        cityIds = self.request.arguments['cityIds']
        ids = []
        for cityId in cityIds:
            ids.append(int(cityId))

        params['cityIds'] = str(ids)

        if options.app_mode == 'dev':
            params['prodImg'] = 'http://www.itlearner.com/google_commonweal_ad/images/sun/300px.jpg'
        params['prodModelJson'] = '{%s}' % json_dumps(prod_model_json)
        #商家信息参数
        shop_ids = list(arg('shop_ids').split(","))
        # 将团购信息参数中的特定key值转移出来,构建商家信息参数
        partner_keys = {"partnerId", "title", "shortTitle", "telephone", "webUrl", "busline", "mapImg",
                        "mapServiceId", "mapUrl", "latitude", "longitude", "address", "circleId"}
        partners = []
        for shop_id in shop_ids:
            partner = {}
            for key in partner_keys:
                partner[key] = params.pop(key + "_" + shop_id)
            partners.append(partner)

        request_params = {'groupbuyInfo': params, 'partners': partners}
        wb = Wuba('addgroupbuy')
        response = yield wb.fetch(**request_params)
        wb.parse_response(response.body)

        if wb.is_ok():
            off_sale_at = datetime.strptime(params['endTime'], '%Y-%m-%d %H:%M:%S')
            expire_at = ceiling(datetime.strptime(params['deadline'], '%Y-%m-%d %H:%M:%S'), today=True)
            self.db.execute('update goods_distributor_shop set status="PENDING", created_by=%s, created_at=NOW(), '
                            'offsale_at = %s, expire_at = %s, distributor_goods_id = %s '
                            'where goods_id=%s and distributor_shop_id=%s and goods_link_id=%s',
                            self.current_user.name, off_sale_at, expire_at,
                            wb.message.data.groupbuyId58, goods_id, options.shop_id_wuba, dg.goods_link_id)

            self.render('goods/distributor/wuba/result.html', ok=True, title='上传成功',
                        explain='<a href="http://t.58.com/sh/%s" target="_blank">去58查看商品</a><br/><a href="/goods/distributor?shop=wb">'
                                '继续上传58商品</a>' % wb.message.data.groupbuyId58)
        else:
            self.render('goods/distributor/wuba/result.html', ok=False, title='上传出错', explain=wb.message.msg)
Exemplo n.º 9
0
    def post(self):
        sql = """insert into contract (uid, start_at, expire_at, created_at, deleted, remark, type)
        values (%s, %s, %s, now(), 0, %s, 1)"""
        form = Form(self.request.arguments, supplier_schema)
        expire_at = datetime.strptime(str(form.expire_at.value), '%Y-%m-%d')

        #插入数据
        contract_id = self.db.execute(sql, form.supplier_id.value, form.start_at.value,
                                      ceiling(expire_at, today=True), form.remark.value)

        self.redirect(self.reverse_url('supplier.contract_upload', contract_id))
Exemplo n.º 10
0
    def post(self):
        sql = """update contract set start_at=%s, expire_at=%s, remark=%s where id=%s"""
        form = Form(self.request.arguments, supplier_schema)
        expire_at = datetime.strptime(str(form.expire_at.value), '%Y-%m-%d')

        #插入数据
        self.db.execute(sql, form.start_at.value, ceiling(expire_at,
                                                          today=True),
                        form.remark.value, form.id.value)
        contract_id = form.id.value

        self.redirect(self.reverse_url('supplier.contract_upload',
                                       contract_id))
Exemplo n.º 11
0
    def post(self):
        sql = """insert into contract (uid, start_at, expire_at, created_at, deleted, remark, type)
        values (%s, %s, %s, now(), 0, %s, 1)"""
        form = Form(self.request.arguments, supplier_schema)
        expire_at = datetime.strptime(str(form.expire_at.value), '%Y-%m-%d')

        #插入数据
        contract_id = self.db.execute(sql, form.supplier_id.value,
                                      form.start_at.value,
                                      ceiling(expire_at,
                                              today=True), form.remark.value)

        self.redirect(self.reverse_url('supplier.contract_upload',
                                       contract_id))
Exemplo n.º 12
0
    def post(self):
        id = self.get_argument('id')
        form = Form(self.request.arguments, add_schema)
        form.expire_at.value = ceiling(datetime.strptime(form.expire_at.value, '%Y-%m-%d'), today=True)
        #我们给商户时,给flag设值
        if form.source.value == '0':
            form.flag.value = form.type.value

        sql = """ update external_money set amount =%s, remark=%s, expire_at=%s,updated_at=now(),updated_by=%s
        where id=%s"""
        self.db.execute(sql, form.amount.value.strip(), form.remark.value, form.expire_at.value,
                        self.current_user.name, id)
        #我们给商户场合,预付款(前期销售额不能提现)或者商户给我的保证金从销售额中扣除的场合,都要记一笔资金
        if (form.source.value == '0' and form.type.value == '0') or \
                (form.source.value == '1' and form.type.value == '0'):
            #更新seq 负资金
            self.db.execute('update account_sequence set amount = %s '
                            'where trade_id = %s and type = %s and amount > 0',
                            Decimal(form.amount.value).copy_negate(), const.seq.PRE_PAYMENT, id)
        self.redirect('/external-money')
Exemplo n.º 13
0
    def post(self):
        id = self.get_argument('id')
        form = Form(self.request.arguments, add_schema)
        form.expire_at.value = ceiling(datetime.strptime(
            form.expire_at.value, '%Y-%m-%d'),
                                       today=True)
        #我们给商户时,给flag设值
        if form.source.value == '0':
            form.flag.value = form.type.value

        sql = """ update external_money set amount =%s, remark=%s, expire_at=%s,updated_at=now(),updated_by=%s
        where id=%s"""
        self.db.execute(sql, form.amount.value.strip(), form.remark.value,
                        form.expire_at.value, self.current_user.name, id)
        #我们给商户场合,预付款(前期销售额不能提现)或者商户给我的保证金从销售额中扣除的场合,都要记一笔资金
        if (form.source.value == '0' and form.type.value == '0') or \
                (form.source.value == '1' and form.type.value == '0'):
            #更新seq 负资金
            self.db.execute(
                'update account_sequence set amount = %s '
                'where trade_id = %s and type = %s and amount > 0',
                Decimal(form.amount.value).copy_negate(),
                const.seq.PRE_PAYMENT, id)
        self.redirect('/external-money')
Exemplo n.º 14
0
    def post(self):
        form = Form(self.request.arguments, add_schema)
        if not form.validate():
            logging.error(form.errors)
            self.render('wx/activity/edit.html',
                        form=form,
                        error='参数不正确',
                        action='add')
            return

        # 添加新的微活动
        fields = ('type', 'name', 'start_at', 'expire_at', 'detail',
                  'win_desc', 'lose_desc', 'due_desc', 'max_try', 'daily_try',
                  'rewards_possibility')
        sql = """insert into wx_activity (%s,  sp_id, created_at, deleted) values  (%s, %%s, NOW(), 0)"""\
              % (','.join(fields), ','.join(['%s']*len(fields)))

        form.expire_at['value'] = ceiling(
            form.expire_at.value, today=True) if form.expire_at.value else None
        params = [form.arguments[field]['value'] for field in fields]
        params.extend([self.current_user.supplier_id])
        activity_id = self.db.execute(sql, *params)

        # 添加相关的奖品信息
        r_types = self.get_arguments('rewards_type')
        r_names = self.get_arguments('rewards_name')
        r_nums = [int(i) for i in self.get_arguments('rewards_num')]
        for i in range(len(r_types)):
            rewards_id = self.db.execute(
                'insert into wx_activity_rewards (act_id, type, name, num) values '
                '(%s, %s, %s, %s)', activity_id, r_types[i], r_names[i],
                r_nums[i])
            # 产生兑奖SN码
            generate_sn(self.db, rewards_id, r_nums[i])

        self.redirect(self.reverse_url('wx.activity.list'))
Exemplo n.º 15
0
    def post(self):
        form = Form(self.request.arguments, add_schema)
        goods_info, shops, properties = get_goods_info(self.db, form.id.value)
        # 为了下面的 validate 成功 这里必须填入数据
        form.arguments.update({'type': EmptyDict({'value': goods_info.type}),
                               'generate_type': EmptyDict({'value': goods_info.generate_type})})
        img_paths = dict()
        for key in self.request.arguments:
            if key.startswith('var_img_path_'):
                v = self.request.arguments[key][0]
                if v:
                    img_paths[key[key.rindex('_')+1:]] = v
        form.img_paths['value'] = json_dumps(img_paths)
        if not form.validate():
            form.properties.value = ['%s-%s' % (item.name, item.value) for item in properties]
            form.shops['value'] = shops

            supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0',
                                           form.supplier_id.value)
            all_sku = self.db.query('select * from sku where deleted=0 and supplier_id=%s', form.supplier_id.value)
            distributors = self.db.query('select * from distributor_shop where deleted = 0')
            form.img_paths['value'] = img_paths
            logging.error(json_dumps(form.errors))
            self.render('goods/add.html', form=form, error='', action='edit', img_url=img_url,
                        supplier_shops=supplier_shops, all_sku=all_sku, distributors=distributors)
            return

        fields = ('expire_at', 'category_id', 'name', 'short_name', 'sms_name', 'face_value', 'sales_price',
                  'stock', 'virtual_sales_count', 'img_path', 'detail', 'tips', 'supplier_intro', 'all_shop',
                  'on_sale_at', 'off_sale_at', 'purchase_price', 'img_paths')

        update_sql = 'update goods set %s, created_at = NOW(), created_by = %%s where id=%%s' % \
                     ','.join([field + '=%s' for field in fields])

        form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None
        form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None
        params = [form.arguments[field]['value'] for field in fields]
        params.append(self.current_user.name)
        params.append(form.id.value)

        #将更新前的旧数据插入goods_copy商品
        insert_fields = ('supplier_id', 'face_value', 'purchase_price', 'sales_price', 'sales_count', 'stock',
                         'virtual_sales_count', 'code', 'all_shop', 'name', 'short_name', 'sms_name', 'category_id',
                         'img_path', 'created_at', 'expire_at', 'detail', 'tips', 'supplier_intro', 'status',
                         'created_by', 'deleted', 'type', 'generate_type', 'supplier_goods_id', 'on_sale_at',
                         'off_sale_at', 'img_paths')
        change_fields = ','.join([field for field in insert_fields])
        insert_id = self.db.execute('insert into goods_copy({0}) select {0} from goods '
                                    'where id = %s'.format(change_fields), form.id.value)
        self.db.execute('update goods_copy set goods_id = %s where id = %s', form.id.value, insert_id)

        #更新goods表
        self.db.execute(update_sql, *params)

        self.db.execute('insert into journal(created_at, type, created_by, message, iid) '
                        'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '修改了商品', form.id.value)

        # 批量更新商品属性
        self.db.execute('delete from goods_property where goods_id=%s and name in '
                        '("gift_card", "hidden", "ktv", "jd_team_id")', form.id.value)
        if form.properties.value:
            insert_properties(self.db, form.properties.value, form.id.value)

        # 批量更新关联门店
        self.db.execute('delete from goods_supplier_shop where goods_id=%s', form.id.value)
        if not form.all_shop.value:
            if form.shops.value:
                insert_shops(self.db, form.shops.value, form.id.value)
        # 批量更新SKU
        self.db.execute('delete from sku_goods where goods_id=%s', form.id.value)
        if form.skus.value:
            insert_skus(self.db, form.skus.value, form.id.value)
        # 批量更新分销店铺佣金
        self.db.execute('delete from goods_distributor_commission where goods_id=%s', form.id.value)
        if form.ratios.value:
            insert_ratios(self.db, form.ratios.value, form.id.value)

        self.redirect(self.reverse_url('goods.show_list'))
Exemplo n.º 16
0
    def get(self):
        form = Form(self.request.arguments, list_schema)
        if not form.summary_type.value:
            form.summary_type['value'] = 'goods_type'

        distr_shops = self.db.query('select id, name from distributor_shop where deleted = 0 ')

        common_fields = """
            i.goods_name, i.goods_id,
            sum(case when i.created_at <=%s and i.created_at >=%s then 1 else 0 end) as sales_count,
            sum(case when i.created_at <=%s and i.created_at >=%s then i.payment else 0 end) as sales_amount,
            sum(case when i.created_at <=%s and i.created_at >=%s then i.purchase_price else 0 end) as cost,
            sum(case when i.created_at <=%s and i.created_at >=%s then i.payment-i.purchase_price else 0 end) as profit,
            sum(case when i.used_at <=%s and i.used_at >=%s then 1 else 0 end) as used,
            sum(case when i.used_at <=%s and i.used_at >=%s then i.payment else 0 end) as used_amount,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is not NULL then 1 else 0 end) as vrefund,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is not NULL then i.refund_value else 0 end) as vrefund_amount,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is NULL then 1 else 0 end) as refund,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is NULL then i.refund_value else 0 end) as refund_amount,
            sum(case when i.cheat_at <=%s and i.cheat_at >=%s then 1 else 0 end) as cheat,
            sum(case when i.cheat_at <=%s and i.cheat_at >=%s then i.payment else 0 end) as cheat_amount,
            sum(case when i.cheat_at <=%s and i.cheat_at >=%s then i.cheat_value-i.purchase_price else 0 end) as cheat_profit
        """

        sql = ''
        sql_foot = ''
        if form.summary_type.value == 'goods_type':
            sql += 'select gc.name category_name, NULL as dsid, ' + common_fields
            sql += """ from item i, goods g, goods_category gct, goods_category gc
                    where i.goods_id = g.id and g.category_id=gct.id and gct.parent_id=gc.id
                  """
            sql_foot = 'group by i.goods_id order by gc.id '
        elif form.summary_type.value == 'distr_shop':
            sql += 'select ds.name distr_shop_name, ds.id dsid, ' + common_fields
            sql += """ from item i, distributor_shop ds where i.distr_shop_id=ds.id """
            sql_foot = 'group by ds.id, i.goods_id order by ds.id '

        sql += ' and (i.created_at <=%s and i.created_at >=%s or ' \
               ' i.used_at <=%s and i.used_at >=%s or ' \
               ' i.refund_at <=%s and i.refund_at >=%s or ' \
               ' i.cheat_at <=%s and i.cheat_at >=%s ) '

        params = []
        # 未指定截止日期,默认为今天
        if not form.end_date.value:
            end = ceiling(datetime.today(), today=True)
            form.end_date.value = end
        else:
            end = form.end_date.value
        # 未指定开始日期,默认为最近7天
        if not form.start_date.value:
            start = truncate(datetime.today() - timedelta(days=6))
            form.start_date.value = start
        else:
            start = form.start_date.value

        for i in range(17):
            params.append(end)
            params.append(start)

        # 指定商户
        if form.supplier.value:
            sql += ' and i.sp_id=%s '
            params.append(form.supplier.value)

        sql += sql_foot

        if form.action.value == 'download':
            distr_shops = self.db.query('select id, name from distributor_shop')
            distr_shops = PropDict([(i.id, i.name) for i in distr_shops])
            page = self.db.query(sql, *params)
            title = [u'商品名称', u'销售数量', u'销售金额', u'成本', u'利润', u'已消费或发货',
                     u'消费金额', u'未消费退款数量', u'未消费退款金额', u'已消费退款数量', u'已消费退款金额',
                     u'刷单数量', u'刷单金额', u'刷单利润']
            range_list = ['goods_name', 'sales_count', 'sales_amount', 'cost', 'profit', 'used', 'used_amount',
                          'refund', 'refund_amount', 'vrefund', 'vrefund_amount', 'cheat', 'cheat_amount', 'cheat_profit']
            if form.summary_type.value == 'goods_type':
                title.append(u'大类')
                range_list.append('category_name')
            else:
                title.append(u'渠道')
                range_list.append('distr_shop_name')
            self.set_header('Content-type', 'application/excel')
            self.set_header('Content-Disposition', u'attachment; filename='+u'商品销售报表'+start+u'至'+end+u'.xls')
            order_excel = Workbook(encoding='utf-8')
            write_order_excel = order_excel.add_sheet('sheet0')

            for index, content in enumerate(title):
                write_order_excel.write(0, index, content)

            for i, item in enumerate(page):
                for j, content in enumerate(range_list):
                    v = item.get(content, '')
                    v = v if v else 0
                    write_order_excel.write(i + 1, j, v)

            stream = StringIO.StringIO()
            order_excel.save(stream)
            self.write(stream.getvalue())
            pass
        else:
            # 查询
            page = Paginator(self, sql, params)
            self.render('finance/channel_goods_report.html', form=form, page=page, distr_shops=distr_shops)
Exemplo n.º 17
0
    def post(self, goods_id):
        params = dict([(name, self.get_argument(name).encode('utf-8'))
                       for name in self.request.arguments])
        shops = self.db.query(
            'select ss.* from supplier_shop ss,goods g where ss.supplier_id=g.supplier_id and g.id=%s and ss.deleted=0 '
            'and (g.all_shop=1 or ss.id in (select supplier_shop_id from goods_supplier_shop where goods_id=%s))',
            goods_id, goods_id)
        params.pop('_xsrf')
        shop_id = params.pop('shop_id')
        params['shops'] = shops
        params['market_price'] = Decimal(params['market_price'])
        params['team_price'] = Decimal(params['team_price'])
        #params['groupon_bimg'] = 'http://www.itlearner.com/google_commonweal_ad/images/sun/300px.jpg'
        params['min_number'] = 1
        if params['max_number'] == '0':
            params['max_number'] = '9999'
        #分割区域和商圈信息
        district_info = params.pop('district_info')
        sp = (',', '-')
        for s in sp:
            district_info = district_info.replace(s, ' ')
        dd = string.split(district_info, ' ')
        districts = {}
        for i in range(len(dd) / 2):
            if dd[2 * i] not in districts:
                districts[dd[2 * i]] = []
            districts[dd[2 * i]].append(dd[2 * i + 1])
        params['districts'] = districts
        params['group2'] = string.split(params['group2'], ',')
        vender_team = alloc_distributor_goods(self.db, goods_id, shop_id)
        params['vender_team_id'] = vender_team.goods_link_id

        shop = self.db.get(
            'select taobao_seller_id, taobao_api_info from distributor_shop where id=%s',
            shop_id)
        api_info = json.loads(shop.taobao_api_info, object_hook=json_hook)

        jd_push = Jingdong('uploadTeam', str(shop.taobao_seller_id),
                           api_info.vender_key, api_info.secret_key)
        response = yield jd_push.fetch(**params)
        jd_push.parse_response(response.body)

        if jd_push.is_ok():
            message = '发布成功'
            offsale_at = datetime.strptime(params['end_time'],
                                           '%Y-%m-%d %H:%M:%S')
            expire_at = ceiling(datetime.strptime(params['expire_time'],
                                                  '%Y-%m-%d %H:%M:%S'),
                                today=True)
            self.db.execute(
                'update goods_distributor_shop set status="PENDING", created_by=%s, created_at=NOW(), '
                'offsale_at = %s, expire_at = %s, distributor_goods_id = %s '
                'where goods_id=%s and distributor_shop_id=%s and goods_link_id=%s',
                self.current_user.name, offsale_at, expire_at,
                jd_push.message.findtext('JdTeamId'), goods_id, shop_id,
                vender_team.goods_link_id)

            logging.info(
                'jingdong push success. goods_id = %s, distributor_goods_id = %s',
                goods_id, jd_push.message.findtext('JdTeamId'))

        else:
            message = '上传失败:' + str(jd_error['error_message'].get(
                int(jd_push.result_code)))

        self.render('goods/distributor/jd/result.html', message=message)
Exemplo n.º 18
0
    def post(self):
        form = Form(self.request.arguments, add_schema)
        # flag为2时表示广告费
        if self.get_argument('flag') == '2':
            fee_sql = """insert into external_money(amount, uid, source, expire_at, created_at, created_by, type,
                         remark, flag, deleted) values(%s, %s, %s, %s, NOW(), %s, 1, %s, %s, 0)"""
            flag = {
                'ONLINE_FEE': 0,
                'ADS_FEE': 1,
                'OPERATE_FEE': 2
            }.get(form.received_type.value, 'ONLINE_FEE')
            params = [
                form.fee.value, form.supplier.value, 2, form.received_at.value,
                self.current_user.name, form.fee_remark.value, flag
            ]
            trade_id = self.db.execute(fee_sql, *params)

            # #将该广告费加入对应销售的帐下
            self.db.execute(
                'insert into supplier_ads_fee(supplier_id, created_at, fee, received_at, type, remark) '
                'values(%s, NOW(), %s, %s, %s, %s)', form.supplier.value,
                form.fee.value, form.received_at.value, flag,
                form.fee_remark.value)
            # 记录日志
            self.db.execute(
                'insert into journal (created_at, type, created_by, message, iid)'
                'values (NOW(), 5, %s, %s, %s)', self.current_user.name,
                "广告费添加 fee_id:%s" % trade_id, trade_id)
        # flag为3时表示微信收费, 后期可扩展, 目前只记一笔到外部资金, 插一条日志,type=6
        elif self.get_argument('flag') == '3':
            sql = """insert into external_money (amount, uid, source, expire_at, created_at, created_by, remark,
            flag, deleted, type) values (%s,%s,%s,%s,now(),%s,%s,%s,0,1)"""
            flag = 0  # 暂时记为微信服务费
            source = 3  # 来源记为3
            trade_id = self.db.execute(sql, form.amount.value.strip(),
                                       form.supplier.value, source,
                                       form.expire_at.value,
                                       self.current_user.name,
                                       form.remark.value, flag)
            # 记录日志
            self.db.execute(
                'insert into journal (created_at, type, created_by, message, iid)'
                'values (NOW(), 6, %s, %s, %s)', self.current_user.name,
                "微信收费.trade_id:%s" % trade_id, trade_id)

        else:
            form.expire_at.value = ceiling(datetime.strptime(
                form.expire_at.value, '%Y-%m-%d'),
                                           today=True)
            #我们给商户时,给flag设值
            if form.source.value == '0':
                form.flag.value = form.type.value
            sql = """ insert into external_money (amount,uid,source,expire_at,created_at,created_by,remark,flag,
            deleted,type) values (%s,%s,%s,%s,now(),%s,%s,%s,0,1) """
            trade_id = self.db.execute(sql, form.amount.value.strip(),
                                       form.supplier.value, form.source.value,
                                       form.expire_at.value,
                                       self.current_user.name,
                                       form.remark.value, form.flag.value)

            # 查找商户及门店的账户
            supplier_shop_account_id = self.db.get(
                'select ss.account_id from supplier s,supplier_shop ss '
                'where s.id=ss.supplier_id and s.deleted =0 and s.id=%s limit 1',
                form.supplier.value).account_id
            #我们给商户场合,预付款(前期销售额不能提现)或者商户给我的保证金从销售额中扣除的场合,都要记一笔资金
            if (form.source.value == '0' and form.type.value == '0') or \
                    (form.source.value == '1' and form.type.value == '0'):
                #seq 中加一条 负资金
                self.db.execute(
                    'insert into account_sequence(type, trade_id, account_id,created_at, amount,remark) '
                    'values(%s, %s, %s, NOW(), %s, %s)', const.seq.PRE_PAYMENT,
                    trade_id, supplier_shop_account_id,
                    -Decimal(form.amount.value), "付给商户的预付款(前期销售额不能提现)")

        self.redirect('/external-money')
Exemplo n.º 19
0
    def get(self):
        form = Form(self.request.arguments, list_schema)
        if not form.summary_type.value:
            form.summary_type['value'] = 'goods_type'

        distr_shops = self.db.query(
            'select id, name from distributor_shop where deleted = 0 ')

        common_fields = """
            i.goods_name, i.goods_id,
            sum(case when i.created_at <=%s and i.created_at >=%s then 1 else 0 end) as sales_count,
            sum(case when i.created_at <=%s and i.created_at >=%s then i.payment else 0 end) as sales_amount,
            sum(case when i.created_at <=%s and i.created_at >=%s then i.purchase_price else 0 end) as cost,
            sum(case when i.created_at <=%s and i.created_at >=%s then i.payment-i.purchase_price else 0 end) as profit,
            sum(case when i.used_at <=%s and i.used_at >=%s then 1 else 0 end) as used,
            sum(case when i.used_at <=%s and i.used_at >=%s then i.payment else 0 end) as used_amount,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is not NULL then 1 else 0 end) as vrefund,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is not NULL then i.refund_value else 0 end) as vrefund_amount,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is NULL then 1 else 0 end) as refund,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is NULL then i.refund_value else 0 end) as refund_amount,
            sum(case when i.cheat_at <=%s and i.cheat_at >=%s then 1 else 0 end) as cheat,
            sum(case when i.cheat_at <=%s and i.cheat_at >=%s then i.payment else 0 end) as cheat_amount,
            sum(case when i.cheat_at <=%s and i.cheat_at >=%s then i.cheat_value-i.purchase_price else 0 end) as cheat_profit
        """

        sql = ''
        sql_foot = ''
        if form.summary_type.value == 'goods_type':
            sql += 'select gc.name category_name, NULL as dsid, ' + common_fields
            sql += """ from item i, goods g, goods_category gct, goods_category gc
                    where i.goods_id = g.id and g.category_id=gct.id and gct.parent_id=gc.id
                  """
            sql_foot = 'group by i.goods_id order by gc.id '
        elif form.summary_type.value == 'distr_shop':
            sql += 'select ds.name distr_shop_name, ds.id dsid, ' + common_fields
            sql += """ from item i, distributor_shop ds where i.distr_shop_id=ds.id """
            sql_foot = 'group by ds.id, i.goods_id order by ds.id '

        sql += ' and (i.created_at <=%s and i.created_at >=%s or ' \
               ' i.used_at <=%s and i.used_at >=%s or ' \
               ' i.refund_at <=%s and i.refund_at >=%s or ' \
               ' i.cheat_at <=%s and i.cheat_at >=%s ) '

        params = []
        # 未指定截止日期,默认为今天
        if not form.end_date.value:
            end = ceiling(datetime.today(), today=True)
            form.end_date.value = end
        else:
            end = form.end_date.value
        # 未指定开始日期,默认为最近7天
        if not form.start_date.value:
            start = truncate(datetime.today() - timedelta(days=6))
            form.start_date.value = start
        else:
            start = form.start_date.value

        for i in range(17):
            params.append(end)
            params.append(start)

        # 指定商户
        if form.supplier.value:
            sql += ' and i.sp_id=%s '
            params.append(form.supplier.value)

        sql += sql_foot

        if form.action.value == 'download':
            distr_shops = self.db.query(
                'select id, name from distributor_shop')
            distr_shops = PropDict([(i.id, i.name) for i in distr_shops])
            page = self.db.query(sql, *params)
            title = [
                u'商品名称', u'销售数量', u'销售金额', u'成本', u'利润', u'已消费或发货', u'消费金额',
                u'未消费退款数量', u'未消费退款金额', u'已消费退款数量', u'已消费退款金额', u'刷单数量',
                u'刷单金额', u'刷单利润'
            ]
            range_list = [
                'goods_name', 'sales_count', 'sales_amount', 'cost', 'profit',
                'used', 'used_amount', 'refund', 'refund_amount', 'vrefund',
                'vrefund_amount', 'cheat', 'cheat_amount', 'cheat_profit'
            ]
            if form.summary_type.value == 'goods_type':
                title.append(u'大类')
                range_list.append('category_name')
            else:
                title.append(u'渠道')
                range_list.append('distr_shop_name')
            self.set_header('Content-type', 'application/excel')
            self.set_header(
                'Content-Disposition', u'attachment; filename=' + u'商品销售报表' +
                start + u'至' + end + u'.xls')
            order_excel = Workbook(encoding='utf-8')
            write_order_excel = order_excel.add_sheet('sheet0')

            for index, content in enumerate(title):
                write_order_excel.write(0, index, content)

            for i, item in enumerate(page):
                for j, content in enumerate(range_list):
                    v = item.get(content, '')
                    v = v if v else 0
                    write_order_excel.write(i + 1, j, v)

            stream = StringIO.StringIO()
            order_excel.save(stream)
            self.write(stream.getvalue())
            pass
        else:
            # 查询
            page = Paginator(self, sql, params)
            self.render('finance/channel_goods_report.html',
                        form=form,
                        page=page,
                        distr_shops=distr_shops)
Exemplo n.º 20
0
    def post(self):
        form = Form(self.request.arguments, add_schema)
        goods_info, shops, properties, img = get_goods_info(self.db, form.id.value)

        if goods_info.supplier_id != self.current_user.supplier_id:
            raise HTTPError(403)

        # 为了下面的 validate 成功 这里必须填入数据
        form.arguments.update({'generate_type': EmptyDict({'value': goods_info.generate_type})})
        img_paths = dict()
        for key in self.request.arguments:
            if key.startswith('var_img_path_'):
                v = self.request.arguments[key][0]
                if v:
                    img_paths[key[key.rindex('_')+1:]] = v
        form.img_paths['value'] = json_dumps(img_paths)
        if not form.validate():
            form.properties.value = properties
            form.shops['value'] = shops
            form.img_paths['value'] = img_paths

            supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0',
                                           self.current_user.supplier_id)
            logging.error(json_dumps(form.errors))
            self.render('wx/mall/goods_add.html', form=form, error='', action='edit', supplier_shops=supplier_shops,
                        img_url=img_url)

        # 获取微信商品手续费
        commission = self.db.get('select value from supplier_property where sp_id=%s and name="wx_commission"',
                                 self.current_user.supplier_id)
        if not commission:
            rate = Decimal((100 - options.wx_min_commission)/100.0)
        else:
            rate = Decimal((100 - int(commission.value))/100.0)
        # 更新结算价
        form.arguments['purchase_price']['value'] = form.arguments['sales_price']['value'] * rate

        fields = ('type', 'generate_type', 'expire_at', 'category_id', 'short_name', 'sms_name',
                  'max_buy', 'on_sale_at', 'off_sale_at', 'face_value', 'sales_price', 'purchase_price',
                  'stock', 'img_path', 'all_shop', 'detail',  'postage')

        update_sql = 'update goods set %s where id=%%s' % ','.join([field + '=%s' for field in fields])

        form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None
        form.on_sale_at['value'] = form.on_sale_at.value if form.off_sale_at.value else None
        form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None
        params = [form.arguments[field]['value'] for field in fields]
        params.append(form.id.value)

        self.db.execute(update_sql, *params)

        self.db.execute('insert into journal(created_at, type, created_by, message, iid) '
                        'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '商户修改了微商城商品', form.id.value)

        # 批量更新关联门店
        self.db.execute('delete from goods_supplier_shop where goods_id=%s', form.id.value)
        if not form.all_shop.value:
            if form.shops.value:
                insert_shops(self.db, form.shops.value, form.id.value)

        self.redirect(self.reverse_url('wx.goods.list'))