示例#1
0
def offline_product(product_id: int,
                    merchant_id: int = Depends(get_login_merchant),
                    session: Session = Depends(create_session)):
    """
    下架商品\n
    :param product_id: 商品id\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    try:
        product_info = redis_client.hget("products", product_id)
        if product_info is None:
            session.commit()
            return make_response(-1, "商品不存在!")
        product = json.loads(product_info)
        if product["merchant_id"] != merchant_id:
            session.commit()
            return make_response(-1, "仅能下架自己商户下的商品!")

        # 更新缓存
        product["status"] = 1
        redis_client.hset("products", product_id, json.dumps(product))

        # 更新db
        session.query(Product).filter(Product.id == product_id).update(
            {Product.status: 1})
        session.commit()
    except Exception as e:
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#2
0
def refuse_deal(deal_no: int,
                merchant_id: int = Depends(get_login_merchant),
                session: Session = Depends(create_session)):
    """
    拒收订单
    :param deal_no:
    :return:
    """
    merchant = json.loads(redis_client.hget("merchants", merchant_id))
    if merchant["merchant_type"] != 2:
        return make_response(-1, "sorry, 您没有此操作权限!")
    ret_code = 0
    ret_msg = "success"
    try:
        merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if merchant["merchant_type"] != 2:
            return make_response(-1, "sorry, 您没有此操作权限!")
        session.query(Deal).filter(Deal.deal_no == deal_no).update(
            {Deal.deal_status: 4})
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#3
0
def delete_merchant(target_merchant_id: int,
                    merchant_id: int = Depends(get_login_merchant),
                    session: Session = Depends(create_session)):
    """
    删除商户(仅管理员有权限)\n
    :param target_merchant_id: 待删除商户id\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"

    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")
        merchant = session.query(Merchant).filter(
            Merchant.id == target_merchant_id)
        session.delete(merchant)
        redis_client.hdel("merchants", merchant.id)
        # todo 删除商户下商品、商户对应评价信息
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#4
0
def delete_activity(activity_id: int,
                    merchant_id: int = Depends(get_login_merchant),
                    session: Session = Depends(create_session)):
    """
    删除营销活动活动\n
    :param activity_id: 活动id\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"

    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")

        session.query(Activity).filter(Activity.id == activity_id).delete()
        # 删除缓存活动信息、商品折扣表
        activity_key = f"activity_{activity_id}"
        discount_key = f"discount_of_activity_{activity_id}"
        pipe = redis_client.pipeline(transaction=True)
        pipe.delete(activity_key)
        pipe.delete(discount_key)
        pipe.execute()
        logger.info("删除活动成功!")
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#5
0
def delete_product(product_id: int,
                   merchant_id: int = Depends(get_login_merchant),
                   session: Session = Depends(create_session)):
    """
    删除商品! \n
    :param product_id: 商品id \n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    try:
        product_info = redis_client.hget("products", product_id)
        if product_info is None:
            session.commit()
            return make_response(-1, "商品不存在!")
        product = json.loads(product_info)
        if product["merchant_id"] != merchant_id:
            session.commit()
            return make_response(-1, "仅能删除自己商户下的商品!")

        # 删除缓存
        redis_client.hdel("products", product_id)
        redis_client.srem(f"products_of_merchant_{merchant_id}", product_id)

        # 删除db
        session.query(Product).filter(Product.id == product_id).delete()
        session.commit()
    except Exception as e:
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#6
0
def handle_apply(target_merchant_id: int,
                 handle_status: int = Query(..., gt=0, lt=3),
                 merchant_id: int = Depends(get_login_merchant),
                 session: Session = Depends(create_session)):
    """
    处理商户接入申请
    :param target_merchant_id: 待接入
    :param handle_status: 通过: 1  拒绝: 2
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")
        merchant = session.query(Merchant).filter(
            Merchant.id == target_merchant_id).one_or_none()
        if merchant is None:
            session.commit()
            return make_response(-1, "申请不存在!")
        merchant.status = handle_status
        if handle_status == 1:
            redis_client.hset("merchants", merchant.id,
                              json.dumps(merchant.to_dict(), cls=JsonEncoder))
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#7
0
def get_merchant_evaluations(target_merchant_id: int,
                             page_no: int = Query(1, gt=-1),
                             page_size: int = Query(20, gt=-1),
                             merchant_id: int = Depends(get_login_merchant),
                             session: Session = Depends(create_session)):
    """
    拉取目标商户的评价列表(仅管理员有权限) \n
    :param target_merchant_id:\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {"total_amount": 0, "evaluation_list": []}
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")
        evaluations = session.query(Evaluation).filter(
            Evaluation.merchant_id == target_merchant_id)
        ret_data["total_amount"] = evaluations.count()
        evaluations = evaluations.order_by(-Evaluation.create_time).offset(
            (page_no - 1) * page_size).limit(page_size)
        ret_data["evaluation_list"] = [
            evaluation.to_dict() for evaluation in evaluations
        ]
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#8
0
def get_merchant_list(page_no: int = Query(1, gt=-1),
                      page_size: int = Query(20, gt=-1),
                      merchant_id: int = Depends(get_login_merchant),
                      session: Session = Depends(create_session)):
    """
    拉取已接入商户列表(仅管理员有权限) \n
    :param page_no: 当前页码\n
    :param page_size: 页面大小\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {"total_count": 0, "merchant_list": []}
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")

        merchants = session.query(Merchant).filter(Merchant.id != merchant_id,
                                                   Merchant.status == 1)
        ret_data["total_count"] = merchants.count()
        merchants = merchants.order_by(-Merchant.create_time).offset(
            (page_no - 1) * page_size).limit(page_size)

        # 查评价星级 evaluation_stars存储商户得星总数  evaluation_times被评星次数
        evaluation_stars = redis_client.hmget(
            "evaluation_stars", [merchant.id for merchant in merchants])
        evaluation_times = redis_client.hmget(
            "evaluation_times", [merchant.id for merchant in merchants])
        merchant_list = []
        for i in range(merchants.count()):
            merchant = merchants[i]
            merchant_detail = merchant.to_dict()
            merchant_detail.pop("password")
            merchant_detail.pop("status")
            merchant_detail["merchant_type"] = MerchantTypeDesc.get(
                merchant_detail["merchant_type"])

            stars = evaluation_stars[i]
            times = evaluation_times[i]
            if stars is None:
                merchant_detail["stars"] = 4  # 初始星级默认为4
            else:
                merchant_detail["stars"] = float(stars) / int(times)
            merchant_list.append(merchant_detail)
        ret_data["merchant_list"] = merchant_list
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#9
0
def add_products_to_activity(actvity_product: ActivityProductModel,
                             merchant_id: int = Depends(get_login_merchant)):
    """
    添加商品到营销活动(必须在活动结束之前) \n
    :param: actvity_product: 活动商品及折扣信息 \n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    try:
        # 查询活动信息
        activity_key = f"activity_{actvity_product.activity_id}"
        activity_info = redis_client.get(activity_key)
        if activity_info is None:
            return make_response(-1, "活动不存在或已结束!")
        activity = json.loads(activity_info)

        # 检查操作合法性(只能操作自己商户下的商品)
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 1:
            return make_response(-1, "权限不足, 仅普通商户能执行此操作!")
        product_ids = actvity_product.product_discount_map.keys()
        pipe = redis_client.pipeline(transaction=False)
        for product_id in product_ids:
            pipe.hget("products", product_id)
        product_infos = pipe.execute()
        for product_info in product_infos:
            if product_info is None:
                return make_response(-1, "请确认商品都存在!")
            product = json.loads(product_info)
            if int(product.get("merchant_id")) != merchant_id:
                return make_response(-1, "非法操作, 仅能操作自己商户下的商品!")

        # 将商品折扣信息添加至活动折扣表, 并建立活动商品与活动的映射关系
        discount_key = f"discount_of_activity_{actvity_product.activity_id}"
        act_endtime = datetime.strptime(activity.get("end_time"),
                                        "%Y-%y-%d %H:%M:%S")
        now = datetime.now()
        expire_time = (act_endtime - now).seconds
        pipe = redis_client.pipeline(transaction=True)
        for product_id, discount in actvity_product.product_discount_map.items(
        ):
            pipe.hset(discount_key, product_id, discount)
            pipe.set(f"activity_of_product_{product_id}",
                     activity.get("id"),
                     ex=expire_time)
        pipe.execute()

        logger.info("新增活动商品成功!")
    except Exception as e:
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#10
0
def get_deals_to_delivery(begin_time: datetime,
                          end_time: datetime,
                          deal_status: int = Query(None, gt=2, lt=6),
                          page_no: int = Query(1, gt=-1),
                          page_size: int = Query(20, gt=-1),
                          merchant_id: int = Depends(get_login_merchant),
                          session: Session = Depends(create_session)):
    """
    拉取需要派送的订单
    :param begin_time: 开始时间
    :param end_time: 结束时间
    :param deal_status: 订单状态 3:派送中 4:已拒收 5:已完成(快递公司只能看到需要派送的订单信息), 不传则拉取全部
    :param page_no: 当前页码
    :param page_size: 页面大小
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {"total_count": 0, "deal_list": []}
    try:
        merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if merchant["merchant_type"] != 2:
            return make_response(-1, "sorry, 您没有此操作权限!")

        if deal_status is None:
            deals = session.query(Deal).filter(
                Deal.create_time.between(begin_time, end_time),
                Deal.deal_status.in_([3, 4, 5]))
        else:
            deals = session.query(Deal).filter(
                Deal.create_time.between(begin_time, end_time),
                Deal.deal_status == deal_status)
        ret_data["total_count"] = deals.count()
        deals = deals.order_by(-Deal.create_time).offset(
            (page_no - 1) * page_size).limit(page_size)
        deal_list = []
        for deal in deals:
            deal_info = deal.to_dict()
            deal_info["need_delivery"] = "是" if deal_info[
                "need_delivery"] == 1 else "否"
            deal_info["deal_status"] = DealStatusDesc.get(
                deal_info["deal_status"])
            deal_list.append(deal_info)
        ret_data["deal_list"] = deal_list
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#11
0
def get_total_deal_list(begin_time: datetime,
                        end_time: datetime,
                        deal_status: int = Query(None, gt=-1, lt=5),
                        page_no: int = Query(1, gt=-1),
                        page_size: int = Query(20, gt=-1),
                        merchant_id: int = Depends(get_login_merchant),
                        session: Session = Depends(create_session)):
    """
    查询商城begin_time到end_time时间段内全部订单列表(仅管理员可见)\n
    :param page_no: 当前页码 (不传默认为1)\n
    :param page_size: 页面大小 (不传默认为20)\n
    :param begin_time: 起始时间\n
    :param end_time: 结束时间\n
    :param deal_status: 订单状态 0: 待支付  1: 待派送 2: 待上门领取 3: 派送中 4: 已完成, 不传则拉取全部\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {"total_count": 0, "deal_list": []}
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")
        if deal_status is None:
            deals = session.query(Deal).filter(
                Deal.create_time.between(begin_time, end_time))
        else:
            deals = session.query(Deal).filter(
                Deal.create_time.between(begin_time, end_time),
                Deal.deal_status == deal_status)

        ret_data["total_count"] = deals.count()
        deals = deals.order_by(-Deal.create_time).offset(
            (page_no - 1) * page_size).limit(page_size)
        deal_list = []
        for deal in deals:
            deal_info = deal.to_dict()
            deal_info["need_delivery"] = "是" if deal_info[
                "need_delivery"] == 1 else "否"
            deal_info["deal_status"] = DealStatusDesc.get(
                deal_info["deal_status"])
            deal_list.append(deal_info)
        ret_data["deal_list"] = deal_list
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#12
0
def get_evaluation_list(page_no: int = Query(1, gt=-1),
                        page_size: int = Query(20, gt=-1),
                        merchant_id: int = Depends(get_login_merchant),
                        session: Session = Depends(create_session)):
    """
    获取我的评价列表 \n
    :param page_no:  当前页码\n
    :param page_size:  页面代销\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {"total_amount": 0, "evaluation_list": []}
    try:
        evaluations = session.query(Evaluation).filter(
            Evaluation.merchant_id == merchant_id)
        ret_data["total_amount"] = evaluations.count()
        evaluations = evaluations.order_by(-Evaluation.create_time).offset(
            (page_no - 1) * page_size).limit(page_size)
        ret_data["evaluation_list"] = [
            evaluation.to_dict() for evaluation in evaluations
        ]
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#13
0
def get_product_list(merchant_id: int = Depends(get_login_merchant)):
    """
    拉取本商户下全部商品列表\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {
        "total_amount": 0,
        "product_list": [],
    }
    # 从redis拉取本商户下全部商品信息
    try:
        product_ids = redis_client.smembers(
            f"products_of_merchant_{merchant_id}")

        products = redis_client.hmget("products", product_ids)

        total_amount = 0
        product_list = []
        for value in products:
            total_amount += 1
            product = json.loads(value)
            product["status"] = ProductStatusDesc[product["status"]]
            product_list.append(product)
        ret_data["total_amount"] = len(products)
        ret_data["product_list"] = product_list
    except Exception as e:
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#14
0
def modify_activity(activity: ActivityModel,
                    merchant_id: int = Depends(get_login_merchant),
                    session: Session = Depends(create_session)):
    """
    修改活动信息\n
    :param activity: 活动信息\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    try:
        now = datetime.now()
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")

        act = session.query(Activity).filter(
            Activity.id == activity.id).one_or_none()
        if act is None:
            session.commit()
            return make_response(-1, "活动不存在!")
        if act.begin_time < now:
            session.commit()
            return make_response(-1, "活动已启动,不允许修改!")

        # 更新缓存
        activity_key = f"activity_{act.id}"
        discount_key = f"discount_of_activity_{act.id}"
        expire_time = (activity.end_time - now).seconds
        redis_client.set(activity_key,
                         json.dumps(act.to_dict(), cls=JsonEncoder),
                         ex=expire_time)
        redis_client.expire(discount_key, expire_time)

        act.act_name = activity.act_name
        act.act_cover = activity.act_cover
        act.begin_time = activity.begin_time
        act.end_time = activity.end_time
        act.update_time = now
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#15
0
def modify_product(product_info: ProductModel,
                   merchant_id: int = Depends(get_login_merchant),
                   session: Session = Depends(create_session)):
    """
    修改商品(只能修改商品名称、商品简介、商品封面图片地址、商品详情图片地址、商品剩余库存、商品价格)\n
    :param product_info: 商品实体,参见ProductModel \n
    :return: 成功返回商品id
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {}
    try:
        if product_info.id is None:
            session.commit()
            return make_response(-1, "商品id不能为空!")
        product = session.query(Product).filter(
            Product.id == product_info.id).one_or_none()
        if product is None:
            session.commit()
            return make_response(-1, f"商品({product_info.id})不存在!")
        if product.merchant_id != merchant_id:
            session.commit()
            return make_response(-1, f"不允许修改他人账户下的商品!")
        product.product_name = product_info.product_name
        product.product_tag = product_info.product_tag
        product.product_cover = product_info.product_cover
        product.product_desc = product_info.product_desc
        product.detail_pictures = json.dumps(product_info.detail_pictures)
        product.has_stock_limit = product_info.has_stock_limit
        product.remain_stock = product_info.remain_stock
        product.price = product_info.price
        product.update_time = datetime.now()

        # 更新缓存
        redis_client.hset("products", product.id,
                          json.dumps(product.to_dict(), cls=JsonEncoder))
        logger.info("更新redis成功!")

        session.commit()
        logger.info(f"商品信息修改成功, product_id: {product.id}")
        ret_data["product_id"] = product.id
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#16
0
def get_advertisments(merchant_id: int = Depends(get_login_merchant)):
    """
    拉取广告位图片\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {"advertis_list": []}
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            return make_response(-1, "权限不足!")
        ret_data["advertis_list"] = redis_client.lrange("advertisments", 0, -1)
    except Exception as e:
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#17
0
def set_advertisments(request: AdvertismentModel,
                      merchant_id: int = Depends(get_login_merchant)):
    """
    设置广告位图片\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            return make_response(-1, "权限不足!")
        redis_client.delete("advertisments")
        redis_client.rpush("advertisments", request.advertis_list)
    except Exception as e:
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#18
0
def add_activity(activity: ActivityModel,
                 merchant_id: int = Depends(get_login_merchant),
                 session: Session = Depends(create_session)):
    """
    新建营销活动\n
    :param activity: 活动信息\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")

        now = datetime.now()
        act = Activity(activity.act_name, activity.act_cover,
                       activity.begin_time, activity.end_time, now, now)
        session.add(act)

        # 活动存入redis并添加商品折扣表
        activity_key = f"activity_{act.id}"
        discount_key = f"discount_of_activity_{act.id}"
        expire_time = (activity.end_time - now).seconds
        pipe = redis_client.pipeline(transaction=True)
        pipe.set(activity_key,
                 json.dumps(act.to_dict(), cls=JsonEncoder),
                 ex=expire_time)
        # 创建一个空的商品折扣表, 插入一条空数据占位符
        pipe.hset(discount_key, "", "")
        pipe.expire(discount_key, expire_time)
        pipe.execute()
        logger.info("活动redis信息初始化成功!")

        session.commit()
        logger.info(f"新建营销活动成功,活动id: {act.id}")
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#19
0
def get_merchant_detail(target_merchant_id: int,
                        merchant_id: int = Depends(get_login_merchant),
                        session: Session = Depends(create_session)):
    """
    查看商户详情\n
    :param target_merchant_id: 商户id\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {}
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")
        merchant = session.query(Merchant).filter(
            Merchant.id == target_merchant_id).one_or_none()
        if merchant is None:
            session.commit()
            return make_response(-1, "商户存在!")
        merchant_detail = merchant.to_dict()
        merchant_detail.pop("password")
        merchant_detail.pop("status")
        merchant_detail["merchant_type"] = MerchantTypeDesc.get(
            merchant_detail["merchant_type"])

        # todo 从redis获取商户评分星级
        stars = redis_client.hget("evaluation_stars", merchant.id)
        times = redis_client.hmget("evaluation_times", merchant.id)
        if stars is None:
            merchant_detail["stars"] = 4  # 初始星级默认为4
        else:
            merchant_detail["stars"] = float(stars) / int(times)
        ret_data["merchant_detail"] = merchant_detail
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#20
0
def get_apply_list(page_no: int = Query(1, gt=-1),
                   page_size: int = Query(20, gt=-1),
                   apply_status: int = Query(..., gt=-1, lt=3),
                   merchant_id: int = Depends(get_login_merchant),
                   session: Session = Depends(create_session)):
    """
    拉取接申请列表\n
    :param apply_status: 申请状态 0: 待审批  1: 已审批  2: 已拒绝\n
    :param page_no: 当前页码 \n
    :param page_size: 页面大小\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {"total_count": 0, "apply_list": []}
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")

        applies = session.query(Merchant).filter(
            Merchant.id != merchant_id, Merchant.status == apply_status)
        ret_data["total_count"] = applies.count()
        applies = applies.order_by(-Merchant.create_time).offset(
            (page_no - 1) * page_size).limit(page_size)
        apply_list = []
        for apply in applies:
            tmp = apply.to_dict()
            tmp.pop("password")
            tmp.pop("status")
            tmp["merchant_type"] = MerchantTypeDesc.get(tmp["merchant_type"])
            apply_list.append(tmp)
        ret_data["merchant_list"] = apply_list
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#21
0
def get_product_tags():
    """
    拉取商品分类标签
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {
        "product_tags": [
            "水果", "食品", "生鲜", "数码", "电器", "洗护", "男装", "女装", "鞋靴", "母婴", "保健",
            "医药", "百货", "其它"
        ]
    }
    return make_response(ret_code, ret_msg, ret_data)
示例#22
0
def get_activity_products(activity_id: int,
                          merchant_id: int = Depends(get_login_merchant)):
    """
    拉取参与某个营销活动的商品列表 \n
    :param activity_id: 活动id \n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {"product_list": []}

    try:
        # 获取活动商品折扣表
        discount_table = redis_client.hgetall(
            f"discount_of_activity_{activity_id}")
        if discount_table is not None:
            discount_table.pop("")
            product_ids = discount_table.keys()

            # 查询活动商品信息
            products = redis_client.hmget("products", product_ids)

            # 查询商户信息
            merchants = redis_client.hgetall("merchants")
            for k, v in merchants.items():
                merchants[k] = json.loads(v)

            product_list = []
            for value in products:
                if value is not None:
                    product = json.loads(value)
                    product_list.append({
                        "product_id":
                        product["id"],
                        "product_name":
                        product["product_name"],
                        "product_cover":
                        product["product_cover"],
                        "discount":
                        discount_table.get(str(product["id"])),
                        "merchant_name":
                        merchants.get(str(
                            product["merchant_id"])).get("merchant_name")
                    })
            ret_data["product_list"] = product_list
    except Exception as e:
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#23
0
def get_activity_list(page_no: int = 1,
                      page_size: int = 10,
                      merchant_id: int = Depends(get_login_merchant),
                      session: Session = Depends(create_session)):
    """
    查询商城营销活动列表\n
    :param: page_no: 当前页码,默认1
    :param: page_size: 页面大小, 默认10
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {"total_count": 0, "activity_list": []}

    try:
        now = datetime.now()
        activities = session.query(Activity).order_by(-Activity.create_time)
        ret_data["total_count"] = activities.count()

        activities = activities.offset(
            (page_no - 1) * page_size).limit(page_size)
        activity_list = []
        for activity in activities:
            activity_list.append({
                "id":
                activity.id,
                "act_name":
                activity.act_name,
                "act_cover":
                activity.act_cover,
                "status":
                get_activity_status_desc(now, activity.begin_time,
                                         activity.end_time),
                "begin_time":
                activity.begin_time,
                "end_time":
                activity.end_time,
            })
        ret_data["activity_list"] = activity_list
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#24
0
def add_product(product_info: ProductModel,
                merchant_id: int = Depends(get_login_merchant),
                session: Session = Depends(create_session)):
    """
    新增商品\n
    :param product_info: 商品实体,参见ProductModel \n
    :return: 成功返回商品id
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {}
    try:
        now = datetime.now()
        product = Product(merchant_id, product_info.product_name,
                          product_info.product_tag, product_info.product_cover,
                          product_info.product_desc,
                          json.dumps(product_info.detail_pictures),
                          product_info.has_stock_limit,
                          product_info.remain_stock, product_info.price, now,
                          now)
        session.add(product)
        session.flush()

        # 商品信息存入缓存
        logger.info(f"redis prduct_info: f{product.to_dict()}")
        redis_client.hset("products", product.id,
                          json.dumps(product.to_dict(), cls=JsonEncoder))

        # 将商品id保存至商户,便于根据商户id查询对应商品
        redis_client.sadd(f"products_of_merchant_{merchant_id}", product.id)
        logger.info("商品存入redis成功!")

        session.commit()
        logger.info(f"新增商品成功, product_id: {product.id}")
        ret_data["product_id"] = product.id
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)
示例#25
0
def complete_deal(deal_no: int,
                  merchant_id: int = Depends(get_login_merchant),
                  session: Session = Depends(create_session)):
    """
    完成订单\n
    :param deal_no: 订单号\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    try:
        session.query(Deal).filter(Deal.deal_no == deal_no,
                                   Deal.merchant_id == merchant_id).update(
                                       {Deal.deal_status: 5})
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)
示例#26
0
def get_sale_statistics(begin_time: datetime,
                        end_time: datetime,
                        merchant_id: int = Depends(get_login_merchant),
                        session: Session = Depends(create_session)):
    """
    获取商城begin_time到end_time时间段内销量统计,含商城订单总数量、总金额,及各商户订单数量、金额分布(仅管理员有权限)\n
    :param begin_time: 开始时间\n
    :param end_time: 结束时间\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    ret_data = {
        "total_deal_amount": 0,
        "total_deal_money": 0,
        "distributions": []
    }

    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")
        statistics = session.query(
            Deal.merchant_id.label("merchant_id"),
            func.count(Deal.deal_no).label("deal_amount"),
            func.sum(Deal.money).label("total_money"),
        ).filter(Deal.create_time.between(begin_time,
                                          end_time)).group_by(Deal.merchant_id)

        merchant_infos = redis_client.hgetall("merchants")
        logger.info(f"商户列表: {merchant_infos}")

        distributions = []
        total_deal_amount = 0
        total_deal_money = 0
        for statistic in statistics:
            total_deal_amount += statistic.deal_amount
            total_deal_money += statistic.total_money
            merchant_info = json.loads(merchant_infos[str(
                statistic.merchant_id)])
            distributions.append({
                "merchant_id":
                statistic.merchant_id,
                "merchant_name":
                merchant_info["merchant_name"],
                "deal_amount":
                statistic.deal_amount,
                "total_money":
                statistic.total_money
            })
        ret_data["total_deal_amount"] = total_deal_amount
        ret_data["total_deal_money"] = total_deal_money
        ret_data["distributions"] = distributions
        session.commit()
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg, ret_data)