Beispiel #1
0
 def __init__(self):
     from Fansti.services.SGoods import SGoods
     self.sgoods = SGoods()
     from Fansti.services.SUsers import SUsers
     self.susers = SUsers()
Beispiel #2
0
 def __init__(self):
     from Fansti.services.SVotes import SVotes
     self.svotes = SVotes()
     from Fansti.services.SUsers import SUsers
     self.susers = SUsers()
     self.title = '============{0}============'
Beispiel #3
0
class CControl():
    def __init__(self):
        from Fansti.services.SGoods import SGoods
        self.sgoods = SGoods()
        from Fansti.services.SUsers import SUsers
        self.susers = SUsers()

    def get_today_list(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = [
            'login_name', "page_size", "page_num", "time_use", "select_name"
        ]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        wts_filter = set()
        from Fansti.models.model import AIR_HWYS_WTS

        user = self.susers.get_user_type(args.get("login_name"))
        if not user:
            return import_status("ERROR_NONE_USER", "FANSTI_ERROR",
                                 "ERROR_NONE_USER")
        usertype = user.user_type
        if usertype:
            try:
                usertype = int(usertype)
            except Exception as e:
                make_log('get good list error', e)
                return SYSTEM_ERROR

        # 根据usertype判断login_name的场景
        from sqlalchemy import or_
        if usertype == 10:
            wts_filter.add(
                or_(AIR_HWYS_WTS.czr == args.get("login_name"),
                    AIR_HWYS_WTS.xsr == args.get("login_name")))
        elif usertype == 0:
            pass
        elif usertype in [3, 4, 5, 6, 7, 8, 9]:
            wts_filter.add(AIR_HWYS_WTS.location == user.location)
        else:
            accounts = get_model_return_dict(
                self.susers.get_compnay_by_loginname(args["login_name"]))
            make_log("accounts", accounts)
            wts_filter.add(AIR_HWYS_WTS.accounts == accounts.get("compnay"))
        if args["select_name"]:
            wts_filter.add(
                or_(
                    AIR_HWYS_WTS.jcno.like("%{0}%".format(
                        args["select_name"])),
                    AIR_HWYS_WTS.ydno.like("%{0}%".format(
                        args["select_name"])),
                    AIR_HWYS_WTS.destination.like("%{0}%".format(
                        args["select_name"]))))
        # 处理当前时间 时间格式为2019-04-29
        if args["time_use"]:
            args["time_use"] = datetime.datetime.strptime(
                args["time_use"], "%Y-%m-%d")
            today_date = args["time_use"]
            wts_filter.add(AIR_HWYS_WTS.arrivetime == today_date)

        goods_list = get_model_return_list(
            self.sgoods.get_all_goods_by_filter(wts_filter,
                                                int(args["page_size"]),
                                                int(args["page_num"])))

        for row in goods_list:
            if row["createtime"]:
                row["createtime"] = row["createtime"].strftime("%Y-%m-%d")
            if row["flag_date"]:
                row["flag_date"] = row["flag_date"].strftime("%Y-%m-%d")
                row["backcolor"] = "灰色"
                if row["transtime"]:
                    row["transtime"] = row["transtime"].strftime("%Y-%m-%d")
            else:
                if row["transtime"]:
                    if row["transtime"] == datetime.datetime.now().date():
                        row["backcolor"] = "黄色"
                    else:
                        row["backcolor"] = "白色"
                    row["transtime"] = row["transtime"].strftime("%Y-%m-%d")
            if "backcolor" not in row.keys():
                row["backcolor"] = "白色"
            if row["isphoto"]:
                row["backcolor"] = "红色"
                if row["isphoto"] == "直接交货!":
                    row["icon"] = "交货"
                elif row["isphoto"] == "拍照等确认!":
                    row["icon"] = "拍照"
            else:
                row["icon"] = None

        make_log("goods_list", goods_list)
        response = import_status("SUCCESS_GET_GOODS", "OK")
        response["data"] = goods_list
        return response

    def get_jc_abo(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        jc_abo = get_model_return_dict(
            self.sgoods.get_control_goods(args["jcno"]))

        user_type = get_model_return_dict(
            self.susers.get_user_type(args["login_name"]))["user_type"]
        if user_type in ["0", "3", "4"]:
            royaltys = get_model_return_list(
                self.sgoods.get_royalty_by_jcno(args["jcno"]))
            for row in royaltys:
                jc_abo["packer_leader"] = row["packer_leader"]
            jc_abo["packer_list"] = royaltys
            if user_type == "4" and not royaltys:
                jc_abo["save_button"] = 1
            else:
                jc_abo["save_button"] = 0
        elif user_type in ["5"]:
            royaltys = get_model_return_list(
                self.sgoods.get_royalty_by_jcno(args["jcno"]))
            for row in royaltys:
                jc_abo["packer_leader"] = row["packer_leader"]
                if row["packer_confrim"] == "是":
                    jc_abo["retrue_packer_button"] = 0
                else:
                    jc_abo["retrue_packer_button"] = 1
                if row["packer_ok"] == "是":
                    jc_abo["retrue_ok_button"] = 0
                else:
                    jc_abo["retrue_ok_button"] = 1
            jc_abo["packer_list"] = royaltys

        dzjjd = get_model_return_dict(self.sgoods.get_dzjjd(args["jcno"]))
        if dzjjd:
            jc_abo["wh_require"] = jc_abo["wh_require"] or dzjjd["kf_bz"]
            jc_abo["instruction"] = jc_abo["instruction"] or dzjjd["hc_bz"]
        jc_abo["jd_date"] = jc_abo["jd_date"] or jc_abo["jd_time"]
        jc_abo["jd_time"] = None
        if jc_abo["arrivetime"]:
            jc_abo["arrivetime"] = jc_abo["arrivetime"].strftime("%Y/%m/%d")
        if jc_abo["jd_date"]:
            print(jc_abo["jd_date"])
            jc_abo["jd_date"] = jc_abo["jd_date"].strftime("%Y/%m/%d %H:%M:%S")
            jc_abo["show_button"] = 0
        else:
            jc_abo["show_button"] = 1

        dcd = get_model_return_dict(self.sgoods.get_dcd_flight(args["jcno"]))
        if dcd:
            jc_abo["contract"] = dcd["flight"]
            jc_abo["contract_time"] = dcd["hbdate1"] or dcd["flightdate"]
            if jc_abo["contract_time"]:
                jc_abo["contract_time"] = jc_abo["contract_time"].strftime(
                    "%Y/%m/%d")
        else:
            jc_abo["contract"] = None
            jc_abo["contract_time"] = None
        if not jc_abo["ydno"]:
            jc_abo["ydno"] = "暂无运单号"
        print(jc_abo)
        response = import_status("SUCCESS_GET_JC", "OK")
        response["data"] = jc_abo
        return response

    def get_handover_list(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        handover_list = get_model_return_dict(
            self.sgoods.get_wts_handover(args["jcno"]))
        dzjjd_handover = self.sgoods.get_dzjjd_handover(args["jcno"])
        if dzjjd_handover:
            handover_list.update(get_model_return_dict(dzjjd_handover))
        else:
            handover_list.update({
                "kfqr_date": None,
                "hcqr_date": None,
                "rkd_flag": None,
                "ungoods_flag": None,
                "sjwj_flag": None,
                "goods_file": None,
                "tp_mass": None,
                "state_goods": None,
                "tp_size": None,
                "temperature": None,
                "dtp": None,
                "gb_flag": None,
                "gb_num": None,
                "lb_flag": None,
                "lb_num": None,
                "in_mark": None,
                "out_mark": None,
                "ybzbl_flag": None,
                "nbzsm": None,
                "bzpm": None,
                "kf_ry": None,
                "kf_bz": None,
                "hc_ry": None,
                "hc_bz": None,
                "xfcl": None,
                "yjlxr": None,
                "wdjly": None,
                "cell_type": None
            })

        # 库房确认时间/货场确认时间处理
        if handover_list["kfqr_date"]:
            handover_list["kfqr_date"] = handover_list["kfqr_date"].strftime(
                "%Y-%m-%d %H:%M:%S")
            handover_list["kf_button"] = 0
        else:
            handover_list["kfqr_date"] = "没有确认"
            handover_list["kf_button"] = 1

        if handover_list["hcqr_date"]:
            handover_list["hcqr_date"] = handover_list["hcqr_date"].strftime(
                "%Y-%m-%d %H:%M:%S")
            handover_list["hc_button"] = 0
        else:
            handover_list["hcqr_date"] = "没有确认"
            handover_list["hc_button"] = 1

        # 是否加冰判断
        if handover_list["gb_flag"] or handover_list["lb_flag"]:
            handover_list["is_ice"] = "是"
        else:
            handover_list["is_ice"] = "否"
        # 加冰种类判断
        handover_list["ice_type"] = ""
        if handover_list["gb_flag"]:
            handover_list["ice_type"] = handover_list["ice_type"] + "干冰"
        if handover_list["lb_flag"]:
            handover_list["ice_type"] = handover_list["ice_type"] + "蓝冰"
        # 加冰用量
        handover_list["ice_num"] = ""
        if handover_list["gb_flag"]:
            if not handover_list["gb_num"]:
                handover_list["gb_num"] = "0"
            handover_list["ice_num"] = handover_list[
                "ice_num"] + "干冰," + handover_list["gb_num"]
        if handover_list["lb_flag"]:
            if not handover_list["lb_num"]:
                handover_list["lb_num"] = "0"
            if handover_list["ice_num"]:
                handover_list["ice_num"] = handover_list["ice_num"] + ";"
            handover_list["ice_num"] = handover_list[
                "ice_num"] + "蓝冰," + handover_list["lb_num"]

        # TODO 判断展示button
        # TODO 三个文件位置

        return {"status": 200, "message": "获取电子交接单成功", "data": handover_list}

    def get_jc_pic_in(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno", "photo_head"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        photoheadid = get_model_return_dict(
            self.sgoods.get_photoheadid_by_head_jcno(args["jcno"],
                                                     args["photo_head"]))
        photos = get_model_return_list(
            self.sgoods.get_photo_by_headid(photoheadid["id"]))
        for row in photos:
            row["createtime"] = row["createtime"].strftime("%Y/%m/%d %H:%M:%S")
        return {"status": 200, "message": "获取入仓照片成功", "data": photos}

    def get_jc_in_photohead(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        photoheadid = get_model_return_dict(
            self.sgoods.get_ckmxd_abo(args["jcno"]))
        print(photoheadid)
        photo_dict = []
        if not photoheadid:
            photohead = 1
        else:
            photohead = photoheadid["photo_head"]
        if photohead:
            photohead = int(photohead)
        else:
            photohead = 1
        for row in range(1, photohead + 1):
            photo_dict.append(row)

        return {"status": 200, "message": "获取入仓照片批次成功", "data": photo_dict}

    def get_jc_pic(self):
        # TODO 入仓照片分批次,这个需要设计
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        jc_abo = {}
        jc_abo["jcno"] = args["jcno"]
        jc_abo["in"] = []
        jc_abo["out"] = []
        jc_abo["weight"] = []
        jc_abo["by"] = []
        make_log("jc_abo", jc_abo)
        if not jc_abo:
            return SYSTEM_ERROR
        quantity_weight = get_model_return_dict(
            self.sgoods.get_quantity_weight_by_jcno(args["jcno"]))
        if quantity_weight:
            jc_abo_in = get_model_return_list(
                self.sgoods.get_in_order_by_jcno(args["jcno"]))
            make_log("jc_abo_in", jc_abo_in)
            if jc_abo_in:
                for in_order in jc_abo_in:
                    in_order["createtime"] = in_order["createtime"].strftime(
                        "%Y-%m-%d %H:%M:%S")
                jc_abo["in"] = jc_abo_in
            jc_abo_out = get_model_return_list(
                self.sgoods.get_out_order_by_jcno(args["jcno"]))
            make_log("jc_abo_out", jc_abo_out)
            if jc_abo_out:
                for out_order in jc_abo_out:
                    out_order["createtime"] = out_order["createtime"].strftime(
                        "%Y-%m-%d %H:%M:%S")
                jc_abo["out"] = jc_abo_out
            jc_abo_weight = get_model_return_list(
                self.sgoods.get_weight_order_by_jcno(args["jcno"]))
            make_log("jc_abo_weight", jc_abo_weight)
            if jc_abo_weight:
                for weight_order in jc_abo_weight:
                    weight_order["createtime"] = weight_order[
                        "createtime"].strftime("%Y-%m-%d %H:%M:%S")
                jc_abo["weight"] = jc_abo_weight

            jc_abo_by = get_model_return_list(
                self.sgoods.get_by_order_by_jcno(args["jcno"]))
            make_log("jc_abo_by", jc_abo_by)
            if jc_abo_by:
                for by_order in jc_abo_by:
                    by_order["createtime"] = by_order["createtime"].strftime(
                        "%Y-%m-%d %H:%M:%S")
                jc_abo["by"] = jc_abo_by

        response = import_status("SUCCESS_GET_JC", "OK")
        response["data"] = jc_abo
        return response

    def get_jc_cb(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")
        wts = get_model_return_dict(self.sgoods.get_control_goods(
            args["jcno"]))
        user = get_model_return_dict(
            self.susers.get_user_type(args["login_name"]))
        user_type = user["user_type"]
        if user_type in ['4', '5', '6', '7', '8', '9']:
            qrd = get_model_return_list(
                self.sgoods.get_jc_qrd_by_loginname(args["jcno"],
                                                    args["login_name"]))
        elif user_type in ['0', '10', '3']:
            qrd = get_model_return_list(self.sgoods.get_jc_qrd(args["jcno"]))
        else:
            qrd = []
        print(qrd)
        cw_lock = get_model_return_dict(self.sgoods.get_cw_lock(args["jcno"]))

        jc_cb = {}
        jc_cb["jcno"] = args["jcno"]
        jc_cb["ydno"] = wts["ydno"]
        jc_cb["company"] = wts["accounts"]
        jc_cb["price"] = []
        if cw_lock and cw_lock["cb_flag"] == "1":
            jc_cb["is_insert"] = 0  # 不可新增
        elif cw_lock and not cw_lock["cb_flag"]:
            jc_cb["is_insert"] = 1
        elif not cw_lock:
            jc_cb["is_insert"] = 1  # 可以新增
        else:
            jc_cb["is_insert"] = 2  # 数据库特殊情况
        if qrd:
            for row in qrd:
                price_dict = {}
                price_dict["curr"] = "%.2f" % float(row["curr"])
                price_dict["amount"] = row["amount"]
                price_dict["doc"] = row["doc"]
                price_dict["id"] = row["id"]
                price_dict["fkdw"] = row["fkdw"]
                if not row["byzd3"]:
                    price_dict["is_update"] = 1  #  可以编辑
                elif row["byzd3"] == "1":
                    price_dict["is_update"] = 0  #  不可以编辑
                else:
                    price_dict["is_update"] = 2  #  数据库异常
                jc_cb["price"].append(price_dict)
        return {"status": 200, "message": "获取成本成功", "data": jc_cb}

    def get_fkdw(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ["fkdw"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        fkdw = get_model_return_list(self.sgoods.get_fkdw(args["fkdw"]))

        return {"status": 200, "message": "获取付款单位成功", "data": fkdw}

    def get_fyzl(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ["fyzl"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        fkdw = get_model_return_list(self.sgoods.get_fkzl(args["fyzl"]))

        return {"status": 200, "message": "获取费用种类成功", "data": fkdw}

    def get_in_abo(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        wts = get_model_return_dict(self.sgoods.get_ckmxd_wts(args["jcno"]))
        ckmxd = get_model_return_dict(self.sgoods.get_ckmxd_abo(args["jcno"]))
        if ckmxd:
            if ckmxd["enter_time"]:
                ckmxd["enter_time"] = ckmxd["enter_time"].strftime(
                    "%Y-%m-%d %H:%M:%S")
            wts.update(ckmxd)
        else:
            wts.update({
                "warehouse_address": None,
                "enter_time": None,
                "goods_quantity": None,
                "delivery_unit": None,
                "goods_weight": None,
                "cargo_size": None,
                "client_name": None,
                "remark": None
            })
        return {"status": 200, "message": "获取入库明细成功", "data": wts}

    def get_out_abo(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        #accounts = get_model_return_dict(self.sgoods.get_accounts_by_jcno(args["jcno"]))
        #make_log("accounts", accounts)
        #if args["login_name"] == accounts:
        #return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR", "ERROR_NONE_PERMISSION")

        wts = get_model_return_dict(
            self.sgoods.get_ckmxd_wts_ydno(args["jcno"]))
        if wts:
            outwarehouse = get_model_return_dict(
                self.sgoods.get_outwarehouse(args["jcno"]))
            if outwarehouse:
                wts["is_button"] = 0
                if outwarehouse["submit_time"]:
                    outwarehouse["submit_time"] = outwarehouse[
                        "submit_time"].strftime("%Y/%m/%d %H:%M:%S")
                wts.update(outwarehouse)
            else:
                wts["is_button"] = 1
                wts.update({"submitter": None, "submit_time": None})
        else:
            wts["is_button"] = 1
            wts.update({"submitter": None, "submit_time": None})

        return {"status": 200, "message": "获取出库确认详情成功", "data": wts}

    def get_hc_abo(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        #accounts = get_model_return_dict(self.sgoods.get_accounts_by_jcno(args["jcno"]))
        #make_log("accounts", accounts)
        #if args["login_name"] == accounts:
        #return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR", "ERROR_NONE_PERMISSION")

        wts = get_model_return_dict(
            self.sgoods.get_ckmxd_wts_ydno(args["jcno"]))
        if wts:
            ingoodyard = get_model_return_dict(
                self.sgoods.get_ingoodyard(args["jcno"]))
            if ingoodyard:
                wts["is_button"] = 0
                if ingoodyard["submit_time"]:
                    ingoodyard["submit_time"] = ingoodyard[
                        "submit_time"].strftime("%Y/%m/%d %H:%M:%S")
                wts.update(ingoodyard)
            else:
                wts["is_button"] = 1
                wts.update({"submitter": None, "submit_time": None})
        else:
            wts["is_button"] = 1
            wts.update({"submitter": None, "submit_time": None})

        return {"status": 200, "message": "获取出库确认详情成功", "data": wts}

    def get_sb_list(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        file_list = get_model_return_list(self.sgoods.get_sb_list(
            args["jcno"]))
        return {"status": 200, "message": "获取文件列表成功", "data": file_list}

    def get_bzsm_list(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        file_list = get_model_return_list(
            self.sgoods.get_bzsm_list(args["jcno"]))
        return {"status": 200, "message": "获取文件列表成功", "data": file_list}

    def get_jd_list(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        file_list = get_model_return_list(self.sgoods.get_jd_list(
            args["jcno"]))
        return {"status": 200, "message": "获取文件列表成功", "data": file_list}

    def get_sbno_list(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ["select_name", "page_size", "page_num"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        sbno_list = get_model_return_list(
            self.sgoods.get_sbno_list_like_ydno_jcno(args["select_name"],
                                                     int(args["page_size"]),
                                                     int(args["page_num"])))
        return {"status": 200, "message": "搜索成功", "data": sbno_list}

    def update_wts(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        data = json.loads(request.data)
        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")
        if "wts_type" not in data.keys():
            return {"status": 405, "status_code": 405001, "message": "参数缺失"}
        if data["wts_type"] == "jd":
            wts = get_model_return_dict(
                self.sgoods.get_id_by_jcno(args["jcno"]))
            wts_id = wts["id"]
            update_wts = self.sgoods.update_wts(
                wts_id, {
                    "jd_time": datetime.datetime.now(),
                    "ydno": wts["ydno"]
                })
            if not update_wts:
                return SYSTEM_ERROR
        return {"status": 200, "message": "交单成功"}

    def update_dzjjd(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        data = json.loads(request.data)
        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")
        if "dzjjd_type" not in data.keys():
            return {"status": 405, "status_code": 405001, "message": "参数缺失"}

        if data["dzjjd_type"] == "kfqr":
            dzjjd = get_model_return_dict(
                self.sgoods.get_jjdid_by_jcno(args["jcno"]))
            print(dzjjd)
            user = get_model_return_dict(
                self.susers.get_user_name(args["login_name"]))
            update_dzjjd = self.sgoods.update_dzjjd(
                dzjjd["jjd_id"], {
                    "kf_ry": user["username"],
                    "kfqr_date": datetime.datetime.now(),
                    "kf_bz": data["bz"]
                })
            if not update_dzjjd:
                return SYSTEM_ERROR
        if data["dzjjd_type"] == "hcqr":
            dzjjd = get_model_return_dict(
                self.sgoods.get_jjdid_by_jcno(args["jcno"]))
            user = get_model_return_dict(
                self.susers.get_user_name(args["login_name"]))
            update_dzjjd = self.sgoods.update_dzjjd(
                dzjjd["jjd_id"], {
                    "hc_ry": user["username"],
                    "hcqr_date": datetime.datetime.now(),
                    "hc_bz": data["bz"]
                })
            if not update_dzjjd:
                return SYSTEM_ERROR

        return {"status": 200, "message": str(data["dzjjd_type"]) + "成功"}

    def upload_files(self):
        formdata = request.form
        make_log("formdata", formdata)
        files = request.files.get("file")

        import platform
        from Fansti.config import Inforcode
        if platform.system() == "Windows":
            rootdir = Inforcode.WindowsRoot + "/" + str(formdata.get("jcno"))
        else:
            rootdir = Inforcode.LinuxRoot + Inforcode.LinuxImgs
        print(rootdir)
        if not os.path.isdir(rootdir):
            os.mkdir(rootdir)
        rootdir = rootdir + "/" + str(formdata.get("FileType"))
        if not os.path.isdir(rootdir):
            os.mkdir(rootdir)
        if "FileType" not in formdata or "jcno" not in formdata:
            return {"status": 405, "status_code": 405001, "message": "参数缺失"}
        filessuffix = str(files.filename).split(".")[-1]
        index = formdata.get("index", 1)
        # filename = formdata.get("FileType") + str(index) + "." + filessuffix
        filename = formdata.get("FileType") + "_" + str(index) + "_" + str(
            uuid.uuid1()) + "." + filessuffix
        filepath = os.path.join(rootdir, filename)
        print(filepath)
        files.save(filepath)
        response = import_status("SUCCESS_MESSAGE_SAVE_FILE", "OK")
        url = Inforcode.ip + Inforcode.WindowsImag + "/" + str(
            formdata.get("jcno")) + "/" + str(
                formdata.get("FileType")) + "/" + filename

        print(url)
        response["data"] = url
        return response

    def add_in(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        data = json.loads(request.data)
        make_log("data", data)

        wts = get_model_return_dict(self.sgoods.get_control_goods(
            args["jcno"]))
        # wts中获取jcno/czr/hwpm
        user = get_model_return_dict(
            self.susers.get_user_name(args["login_name"]))
        ckmxd = get_model_return_dict(self.sgoods.get_ckmxd_abo(args["jcno"]))
        if ckmxd:
            photo_head = ckmxd["photo_head"]
            print(photo_head)
        else:
            photo_head = None
        if photo_head:
            if photo_head == "6":
                photo_head = int(photo_head)
            else:
                photo_head = int(photo_head) + 1
        else:
            photo_head = 1

        add_model(
            "AIR_HWYS_CKMXD", **{
                "list_id":
                str(uuid.uuid1()),
                "jcno":
                args["jcno"],
                "salesman":
                wts["czr"],
                "hwpm":
                data["hwpm"],
                "warehouse_address":
                data["warehouse_address"],
                "enter_time":
                datetime.datetime.strptime(data["enter_time"],
                                           "%Y-%m-%d %H:%M:%S"),
                "create_time":
                datetime.datetime.now(),
                "goods_quantity":
                data["goods_quantity"],
                "delivery_unit":
                data["delivery_unit"],
                "goods_weight":
                data["goods_weight"],
                "cargo_size":
                data["cargo_size"],
                "client_name":
                data["client_name"],
                "remark":
                data["remark"],
                "photo_head":
                str(photo_head)
            })
        photoheadid = str(uuid.uuid1())
        add_model(
            "AIR_HWYS_PHOTO_HEAD", **{
                "id": photoheadid,
                "photohead": str(photo_head),
                "jcno": args["jcno"],
                "type": "in",
                "createtime": datetime.datetime.now(),
                "czr": user["username"],
                "photocount": len(data["pic_list"])
            })
        for row in data["pic_list"]:
            add_model(
                "AIR_HWYS_PHOTOS", **{
                    "id": str(uuid.uuid1()),
                    "jcno": args["jcno"],
                    "phototype": "in",
                    "photourl": row["url"],
                    "createtime": datetime.datetime.now(),
                    "czr": user["username"],
                    "filename": row["filename"],
                    "photoheadid": photoheadid
                })
        return {"status": 200, "message": "提交成功"}

    def retrue_outhc(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        data = json.loads(request.data)
        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")
        if "retrue_type" not in data.keys():
            return {"status": 405, "status_code": 405001, "message": "参数缺失"}
        user = get_model_return_dict(
            self.susers.get_user_name(args["login_name"]))
        print(user)
        wts = get_model_return_dict(self.sgoods.get_control_goods(
            args["jcno"]))
        if data["retrue_type"] == "out":
            add_model(
                "AIR_HWYS_OUTWAREHOUSE", **{
                    "id": str(uuid.uuid1()),
                    "ydno": wts["ydno"],
                    "submitter": user["username"],
                    "submit_time": datetime.datetime.now(),
                    "create_time": datetime.datetime.now()
                })
        if data["retrue_type"] == "hc":
            add_model(
                "AIR_HWYS_INGOODYARD", **{
                    "id": str(uuid.uuid1()),
                    "ydno": wts["ydno"],
                    "submitter": user["username"],
                    "submit_time": datetime.datetime.now(),
                    "create_time": datetime.datetime.now()
                })

        return {"status": 200, "message": "确认成功"}

    def make_sb(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        data = json.loads(request.data)
        user = get_model_return_dict(
            self.susers.get_user_name(args["login_name"]))
        wts = get_model_return_dict(self.sgoods.get_control_goods(
            args["jcno"]))
        for row in data["jd_list"]:
            add_model(
                "AIR_HWYS_DGD_UPLOAD", **{
                    "id": str(uuid.uuid1()),
                    "jcno": args["jcno"],
                    "ydno": wts["ydno"],
                    "file_type": "鉴定文件",
                    "file_url": row["url"],
                    "create_time": datetime.datetime.now(),
                    "create_user": user["username"],
                    "file_name": row["file_name"]
                })
        for row in data["sb_list"]:
            add_model(
                "AIR_HWYS_DGD_UPLOAD", **{
                    "id": str(uuid.uuid1()),
                    "jcno": args["jcno"],
                    "ydno": wts["ydno"],
                    "file_type": "申报单",
                    "file_url": row["url"],
                    "create_time": datetime.datetime.now(),
                    "create_user": user["username"],
                    "file_name": row["file_name"]
                })
        for row in data["bzmx_list"]:
            add_model(
                "AIR_HWYS_DGD_UPLOAD", **{
                    "id": str(uuid.uuid1()),
                    "jcno": args["jcno"],
                    "ydno": wts["ydno"],
                    "file_type": "包装明细",
                    "file_url": row["url"],
                    "create_time": datetime.datetime.now(),
                    "create_user": user["username"],
                    "file_name": row["file_name"]
                })
        for row in data["jdfj_list"]:
            add_model(
                "AIR_HWYS_DGD_UPLOAD", **{
                    "id": str(uuid.uuid1()),
                    "jcno": args["jcno"],
                    "ydno": wts["ydno"],
                    "file_type": "鉴定附件",
                    "file_url": row["url"],
                    "create_time": datetime.datetime.now(),
                    "create_user": user["username"],
                    "file_name": row["file_name"]
                })

        return {"status": 200, "message": "上传完毕"}

    def update_qrd(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno", "qrd_type"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        data = json.loads(request.data)
        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        user = get_model_return_dict(
            self.susers.get_user_name(args["login_name"]))
        wts = get_model_return_dict(self.sgoods.get_control_goods(
            args["jcno"]))
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")
        if args["qrd_type"] == "add":
            add_model(
                "AIR_HWYS_QRD", **{
                    "id": str(uuid.uuid1()),
                    "ydno": wts["ydno"],
                    "jcno": args["jcno"],
                    "doc": data["charge_cname"],
                    "curr": data["curr"],
                    "amount": data["amount"],
                    "fkdw": data["company"],
                    "createtime": datetime.datetime.now(),
                    "byzd1": "1",
                    "byzd2": args["login_name"],
                    "rate": "1",
                    "currcode": "CNY"
                })
        if args["qrd_type"] == "update":
            update_qrd = self.sgoods.update_qrd_by_id(
                data["id"], {
                    "ydno": wts["ydno"],
                    "jcno": args["jcno"],
                    "doc": data["charge_cname"],
                    "curr": data["curr"],
                    "amount": data["amount"],
                    "fkdw": data["company"],
                    "createtime": datetime.datetime.now(),
                    "byzd1": "1",
                    "byzd2": args["login_name"]
                })
            if not update_qrd:
                return SYSTEM_ERROR

        if args["qrd_type"] == "delete":
            delete = self.sgoods.delete_qrd_by_id(data["id"])
            if not delete:
                return SYSTEM_ERROR
        return {"status": 200, "message": "编辑成功"}

    def get_packer(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ["select_name", "login_name"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        location = get_model_return_dict(
            self.susers.get_user_type(args["login_name"]))["location"]
        all_packer = get_model_return_list(
            self.susers.get_packer_by_select(args["select_name"], location))
        return {"status": 200, "message": "获取包装人员列表成功", "data": all_packer}

    def save_royalty(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        data = json.loads(request.data)
        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        user = get_model_return_dict(
            self.susers.get_user_name(args["login_name"]))
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")
        user_type_location = get_model_return_dict(
            self.susers.get_user_type(args["login_name"]))
        if user_type_location["user_type"] not in ["0", "3", "4"]:
            return {"status": 405, "status_code": 405999, "message": "无权限"}
        packer_leader = data["packer_leader"]
        for row in data["packer_list"]:
            add_model(
                "AIR_HWYS_PACK_ROYALTY", **{
                    "id": str(uuid.uuid1()),
                    "jcno": args["jcno"],
                    "packer_leader": packer_leader,
                    "packer": row["packer"],
                    "royalty_rate": None,
                    "create_date": datetime.datetime.now(),
                    "create_user": user["username"]
                })
        return {"status": 200, "message": "保存成功"}

    def update_royalty(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        data = json.loads(request.data)
        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")
        if data["royalty_type"] == 0:
            royaltys = data["packer_list"]
            for row in royaltys:
                update_response = self.sgoods.update_royalty(
                    row["id"], {
                        "packer_confrim": "是",
                        "royalty_rate": row["royalty_rate"]
                    })
                if not update_response:
                    return SYSTEM_ERROR
        elif data["royalty_type"] == 1:
            royaltys = get_model_return_list(
                self.sgoods.get_royalty_by_jcno(args["jcno"]))
            for row in royaltys:
                update_response = self.sgoods.update_royalty(
                    row["id"], {"packer_ok": "是"})
                if not update_response:
                    return SYSTEM_ERROR
        return {"status": 200, "message": "更新成功"}

    def add_new_file(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno", "file_type"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        data = json.loads(request.data)
        user = get_model_return_dict(
            self.susers.get_user_name(args["login_name"]))
        wts = get_model_return_dict(self.sgoods.get_control_goods(
            args["jcno"]))
        if args["file_type"] in ["sb", "jd", "bzwj", "jdfj"]:
            if args["file_type"] == "sb":
                file_type = "申报单"
            elif args["file_type"] == "jd":
                file_type = "鉴定文件"
            elif args["file_type"] == "bzwj":
                file_type = "包装明细"
            elif args["file_type"] == "jdfj":
                file_type = "鉴定附件"
            else:
                file_type = "未知文件"
            add_model(
                "AIR_HWYS_DGD_UPLOAD", **{
                    "id": str(uuid.uuid1()),
                    "jcno": args["jcno"],
                    "ydno": wts["ydno"],
                    "file_type": file_type,
                    "file_url": data["url"],
                    "create_time": datetime.datetime.now(),
                    "create_user": user["username"],
                    "file_name": data["file_name"]
                })
        if args["file_type"] in ["out", "weight", "by"]:
            add_model(
                "AIR_HWYS_PHOTOS", **{
                    "id": str(uuid.uuid1()),
                    "jcno": args["jcno"],
                    "phototype": args["file_type"],
                    "photourl": data["url"],
                    "createtime": datetime.datetime.now(),
                    "czr": user["username"],
                    "filename": data["file_name"]
                })
        if args["file_type"] == "in":
            print(">>>>>>>>>>>>>>>>>")
            head = data["head"]
            print(head)
            heads = get_model_return_dict(
                self.sgoods.get_photoheadid_by_head_jcno(
                    args["jcno"], str(head)))
            print(heads)
            if not heads:
                return {
                    "status": 405,
                    "status_code": 405992,
                    "message": "未找到对应批次"
                }
            else:
                headid = heads["id"]
                add_model(
                    "AIR_HWYS_PHOTOS", **{
                        "id": str(uuid.uuid1()),
                        "jcno": args["jcno"],
                        "phototype": args["file_type"],
                        "photourl": data["url"],
                        "createtime": datetime.datetime.now(),
                        "czr": user["username"],
                        "filename": data["file_name"],
                        "photoheadid": headid
                    })
        return {"status": 200, "message": "保存成功"}

    def delete_file(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno", "file_type"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        data = json.loads(request.data)
        user = get_model_return_dict(
            self.susers.get_user_name(args["login_name"]))
        wts = get_model_return_dict(self.sgoods.get_control_goods(
            args["jcno"]))
        if args["file_type"] in ["sb", "jd", "bzwj", "jdfj"]:
            if args["file_type"] == "sb":
                file_type = "申报单"
            elif args["file_type"] == "jd":
                file_type = "鉴定文件"
            elif args["file_type"] == "bzwj":
                file_type = "包装明细"
            elif args["file_type"] == "jdfj":
                file_type = "鉴定附件"
            else:
                file_type = "未知文件"
            id = get_model_return_dict(
                self.sgoods.get_dgdid_by_url(data["photourl"]))
            dgd_upload = get_model_return_dict(
                self.sgoods.get_dgd_by_id(id["id"]))
            print(dgd_upload)
            add_model(
                "AIR_HWYS_DGD_UPLOAD_BAK", **{
                    "id": str(uuid.uuid1()),
                    "jcno": args["jcno"],
                    "ydno": wts["ydno"],
                    "file_type": file_type,
                    "file_url": data["photourl"],
                    "upload_create_time": dgd_upload["create_time"],
                    "uploade_create_user": dgd_upload["create_user"],
                    "delet_time": datetime.datetime.now(),
                    "delet_user": user["username"],
                    "file_name": data["file_name"]
                })
            delete_photo = self.sgoods.delete_dgd_by_id(id["id"])
            if not delete_photo:
                return {
                    "status": 405,
                    "status_code": 405989,
                    "message": "删除失败"
                }

        if args["file_type"] in ["out", "weight", "by", "in"]:
            id = get_model_return_dict(
                self.sgoods.get_photosid_by_url(data["photourl"]))
            delete_photo = self.sgoods.delete_photos_by_id(id["id"])
            if not delete_photo:
                return {
                    "status": 405,
                    "status_code": 405989,
                    "message": "删除失败"
                }

        return {"status": 200, "message": "删除成功"}
Beispiel #4
0
 def __init__(self):
     self.title = "=========={0}=========="
     from Fansti.services.SUsers import SUsers
     self.suser = SUsers()
     from Fansti.services.SGoods import SGoods
     self.sgoods = SGoods()
Beispiel #5
0
class CGoods():
    def __init__(self):
        from Fansti.services.SGoods import SGoods
        self.sgoods = SGoods()
        from Fansti.services.SUsers import SUsers
        self.susers = SUsers()

    def get_goods_list(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "page_size", "page_num"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())
        wts_filter = set()
        from Fansti.models.model import AIR_HWYS_WTS
        if args.get("ydno"):
            wts_filter.add(
                AIR_HWYS_WTS.ydno.like("%{0}%".format(args.get('ydno'))))
        if args.get("hxno"):
            wts_filter.add(
                AIR_HWYS_WTS.hxno.like("%{0}%".format(args.get("hxno"))))
        if args.get("destination"):
            wts_filter.add(
                AIR_HWYS_WTS.destination.like("%{0}%".format(
                    args.get("destination"))))
        if args.get("accounts"):
            wts_filter.add(
                AIR_HWYS_WTS.accounts.like("%{0}%".format(
                    args.get("accounts"))))
        if args.get("jcno"):
            wts_filter.add(
                AIR_HWYS_WTS.jcno.like("%{0}%".format(args.get("jcno"))))

        user = self.susers.get_user_type(args.get("login_name"))
        if not user:
            return import_status("ERROR_NONE_USER", "FANSTI_ERROR",
                                 "ERROR_NONE_USER")
        user_message = get_model_return_dict(
            self.susers.get_user_name(args.get("login_name")))
        usertype = user.user_type
        if usertype:
            try:
                usertype = int(usertype)
            except Exception as e:
                make_log('get good list error', e)
                return SYSTEM_ERROR

        if usertype == 10:
            from sqlalchemy import or_
            wts_filter.add(
                or_(AIR_HWYS_WTS.czr == args.get("login_name"),
                    AIR_HWYS_WTS.xsr == args.get("login_name")))
        elif usertype == 0:
            pass
        elif usertype == 30:
            wts_filter.add(AIR_HWYS_WTS.dmczlx == user_message["username"])
        elif usertype == 20:
            accounts = get_model_return_dict(
                self.susers.get_compnay_by_loginname(args["login_name"]))
            make_log("accounts", accounts)
            wts_filter.add(AIR_HWYS_WTS.company == user_message["username"])
        elif usertype == 3:
            from sqlalchemy import or_
            wts_filter.add(
                or_(AIR_HWYS_WTS.location == user.location,
                    AIR_HWYS_WTS.czr == args["login_name"],
                    AIR_HWYS_WTS.xsr == args["login_name"]))
        else:
            accounts = get_model_return_dict(
                self.susers.get_compnay_by_loginname(args["login_name"]))
            make_log("accounts", accounts)
            wts_filter.add(AIR_HWYS_WTS.accounts == accounts.get("compnay"))
        import datetime
        from calendar import monthrange
        two_month_ago = datetime.datetime.now() + \
                        datetime.timedelta(days=-monthrange(datetime.datetime.now().year, datetime.datetime.now().month)[1])
        goods_list = get_model_return_list(
            self.sgoods.get_all_goods_by_filter(wts_filter,
                                                int(args["page_size"]),
                                                int(args["page_num"])))

        make_log("goods_list", goods_list)
        i = len(goods_list) - 1
        while i >= 0:
            goods = goods_list[i]
            if goods["transtime"]:
                goods["transtime"] = goods["transtime"].strftime("%Y-%m-%d")
            if goods["flag_date"]:
                goods["flag_date"] = goods["flag_date"].strftime("%Y-%m-%d")
            yupei = get_model_return_dict(
                self.sgoods.get_dctime_by_jcno(goods["jcno"]))
            make_log("yupei", yupei)
            if not yupei:
                goods["yupei"] = "0"
            elif "hbdate1" in yupei.keys() and not yupei["hbdate1"]:
                goods["yupei"] = "0"
            else:
                goods["yupei"] = "1"
            jincang = get_model_return_list(
                self.sgoods.get_in_order_by_jcno(goods["jcno"]))
            make_log("jincang", jincang)
            #for row in jincang:
            if not jincang:
                goods["jincang"] = "0"
            else:
                goods["jincang"] = "1"
            chucang = get_model_return_list(
                self.sgoods.get_out_order_by_jcno(goods["jcno"]))
            make_log("chucang", chucang)
            #for row in chucang:
            if not chucang:
                goods["chucang"] = "0"
            else:
                goods["chucang"] = "1"
            chengzhong = get_model_return_list(
                self.sgoods.get_weight_order_by_jcno(goods["jcno"]))
            make_log("chengzhong", chengzhong)
            #for row in chengzhong:
            if not chengzhong:
                goods["chengzhong"] = "0"
            else:
                goods["chengzhong"] = "1"
            baoguan = get_model_return_dict(
                self.sgoods.get_content_by_jcno(goods["jcno"]))
            make_log("baoguan", baoguan)
            #for row in baoguan:
            if not baoguan:
                goods["baoguan"] = "0"
            elif "content" in baoguan.keys() and not baoguan["content"]:
                goods["baoguan"] = "0"
            else:
                goods['baoguan'] = "1"
            yundan = get_model_return_dict(
                self.sgoods.get_awb_by_jcno(goods["jcno"]))
            make_log("yundan", yundan)
            #for row in yundan:
            if not yundan:
                goods["yundan"] = "0"
            elif "content" in yundan.keys() and not yundan["content"]:
                goods["yundan"] = "0"
            else:
                goods["yundan"] = "1"
            jdtime = self.sgoods.get_jd_by_jcno(goods["jcno"])
            make_log("jiaodan", jdtime)
            jdtime = jdtime.jd_time or jdtime.jd_date
            if not jdtime:
                goods["jiaodan"] = "0"
                if two_month_ago > goods["createtime"]:
                    goods_list.remove(goods)
            else:
                goods["jiaodan"] = "1"
            if goods["createtime"]:
                goods["createtime"] = goods["createtime"].strftime("%Y-%m-%d")
            qifei = get_model_return_dict(self.sgoods.get_std(goods["jcno"]))
            make_log("qifei", qifei)
            if not qifei:
                goods["qifei"] = "0"
            elif "mes1" in qifei.keys() and not qifei["mes1"]:
                goods["qifei"] = "0"
            else:
                goods["qifei"] = "1"
            dida = get_model_return_dict(
                self.sgoods.get_dhmes_by_jcno(goods["jcno"]))
            make_log("dida", dida)
            if not dida:
                goods["dida"] = "0"
            elif "dhmes" in dida.keys() and not dida["dhmes"]:
                goods["dhmes"] = "0"
            else:
                goods["dida"] = "1"
            yanwu = get_model_return_list(
                self.sgoods.get_yanwu_by_jcno(goods["jcno"]))
            if not yanwu:
                goods["yanwu"] = "0"
            else:
                goods["yanwu"] = "1"
            i = i - 1
        response = import_status("SUCCESS_GET_GOODS", "OK")
        response["data"] = goods_list
        return response

    def get_jc_abo(self):
        args = request.args.to_dict()
        make_log("args", args)
        not_null_params = ['login_name', "jcno"]
        if judge_keys(not_null_params, args.keys()) != 200:
            return judge_keys(not_null_params, args.keys())

        accounts = get_model_return_dict(
            self.sgoods.get_accounts_by_jcno(args["jcno"]))
        make_log("accounts", accounts)
        if args["login_name"] == accounts:
            return import_status("ERROR_NONE_PERMISSION", "FANSTI_ERROR",
                                 "ERROR_NONE_PERMISSION")

        jc_abo = get_model_return_dict(
            self.sgoods.get_goods_abo_by_jcno(args["jcno"]))
        make_log("jc_abo", jc_abo)
        if not jc_abo:
            return SYSTEM_ERROR
        quantity_weight = get_model_return_dict(
            self.sgoods.get_quantity_weight_by_jcno(args["jcno"]))
        if quantity_weight:
            jc_abo["quantity"] = quantity_weight["quantity"]
            jc_abo["weight"] = quantity_weight["weight"]
            jc_abo["in"] = {}
            jc_abo["in"]["picture"] = []
            jc_abo["out"] = {}
            jc_abo["out"]["picture"] = []
            jc_abo["weight_pic"] = {}
            jc_abo["weight_pic"]["picture"] = []
            jc_abo_in = get_model_return_list(
                self.sgoods.get_in_order_by_jcno(args["jcno"]))
            make_log("jc_abo_in", jc_abo_in)
            if jc_abo_in:
                for in_order in jc_abo_in:
                    jc_abo["in"]["createtime"] = in_order[
                        "createtime"].strftime("%Y-%m-%d %H:%M:%S")
                    # jc_abo["in"]["czr"] = in_order["czr"].decode("gbk").encode("utf8")
                    jc_abo["in"]["czr"] = in_order["czr"]
                    jc_abo["in"]["picture"].append(in_order["photourl"])
            jc_abo_out = get_model_return_list(
                self.sgoods.get_out_order_by_jcno(args["jcno"]))
            make_log("jc_abo_out", jc_abo_out)
            if jc_abo_out:
                for out_order in jc_abo_out:
                    jc_abo["out"]["createtime"] = out_order[
                        "createtime"].strftime("%Y-%m-%d %H:%M:%S")
                    # jc_abo["out"]["czr"] = out_order["czr"].decode("gbk").encode("utf8")
                    jc_abo["out"]["czr"] = out_order["czr"]
                    jc_abo["out"]["picture"].append(out_order["photourl"])
            jc_abo_weight = get_model_return_list(
                self.sgoods.get_weight_order_by_jcno(args["jcno"]))
            make_log("jc_abo_weight", jc_abo_weight)
            if jc_abo_weight:
                for weight_order in jc_abo_weight:
                    jc_abo["weight_pic"]["createtime"] = weight_order[
                        "createtime"].strftime("%Y-%m-%d %H:%M:%S")
                    # jc_abo["weight_pic"]["czr"] = weight_order["czr"].decode("gbk").encode("utf8")
                    jc_abo["weight_pic"]["czr"] = weight_order["czr"]
                    jc_abo["weight_pic"]["picture"].append(
                        weight_order["photourl"])

            in_out_weight_status = get_model_return_list(
                self.sgoods.get_in_out_weight_by_jcno(args["jcno"]))
            jc_abo["in_status"] = "0"
            jc_abo["out_status"] = "0"
            jc_abo["weight_status"] = "0"
            for row in in_out_weight_status:
                if row["in_pic"] == "1":
                    jc_abo["in_status"] = "1"
                if row["out_pic"] == "1":
                    jc_abo["out_status"] = "1"
                if row["weight_pic"] == "1":
                    jc_abo["weight_status"] = "1"

        import datetime
        # 起飞
        jcno = args.get("jcno")
        make_log("jcno", jcno)
        jc_abo.update(get_model_return_dict(self.sgoods.get_std(jcno)))
        # 预配
        hbdate1 = get_model_return_dict(self.sgoods.get_dctime_by_jcno(jcno))
        make_log("hbdate1", hbdate1)
        if not hbdate1:
            jc_abo["hbdate1"] = None
        elif "hbdate1" in hbdate1.keys() and not hbdate1["hbdate1"]:
            jc_abo["hbdate1"] = None
        else:
            jc_abo["hbdate1"] = hbdate1["hbdate1"].strftime('%Y-%m-%d')
        # 交单
        jdtime = self.sgoods.get_jd_by_jcno(jcno)
        make_log("jdtime", jdtime)
        jdtime = jdtime.jd_time or jdtime.jd_date
        if not jdtime:
            jc_abo['supporttime'] = None
        else:
            jc_abo['supporttime'] = jdtime.strftime('%Y-%m-%d')

        # 送达
        jc_abo.update(
            get_model_return_dict(
                self.sgoods.get_dhmes_by_jcno(args.get("jcno"))))
        # 运单文件
        ydfile = get_model_return_list(
            self.sgoods.get_awbfile_by_jcno(args.get("jcno")))
        jc_abo['ydfile'] = ydfile
        # 报关单文件
        contentfile = get_model_return_list(
            self.sgoods.get_contentfile_by_jcno(args.get("jcno")))
        jc_abo['contentfile'] = contentfile
        # 申报单文件
        contentsb = get_model_return_dict(
            self.sgoods.get_contentsb_by_jcno(args.get("jcno")))
        jc_abo["contentsb"] = contentsb
        # 放行单文件
        contentfx = get_model_return_list(
            self.sgoods.get_contentfx_by_jcno(args.get("jcno")))
        jc_abo["contentfx"] = contentfx
        # DGD文件
        contentdgd = get_model_return_list(
            self.sgoods.get_contentdgd_by_jcno(args.get("jcno")))
        jc_abo["contentdgd"] = contentdgd
        # 销售人xsr

        # 客服人员
        if "czr" in jc_abo.keys() and jc_abo["czr"]:
            user_abo = get_model_return_dict(
                self.susers.get_custom_by_xsr(jc_abo["czr"]))
            if "user_name" in user_abo.keys():
                jc_abo["custom_name"] = user_abo["user_name"]
            else:
                jc_abo["custom_name"] = ""
        else:
            jc_abo["custom_name"] = ""
        response = import_status("SUCCESS_GET_JC", "OK")
        response["data"] = jc_abo
        return response

    def retrue_goods(self):
        args = request.args.to_dict()
        make_log("args", args)
        data = json.loads(request.data)
        make_log("data", data)
        true_args = ["login_name", "jcno"]
        true_data = ["retrue_name"]
        if judge_keys(true_args, args.keys()) != 200:
            return judge_keys(true_args, args.keys())
        if judge_keys(true_data, data.keys()) != 200:
            return judge_keys(true_data, data.keys())
        jcno = args["jcno"]
        goods_retrue = get_model_return_list(
            self.sgoods.get_in_out_weight_by_jcno(jcno))
        if not goods_retrue:
            in_pic = "0"
            out_pic = "0"
            weight_pic = "0"
            if data["retrue_name"] == "in":
                in_pic = "1"
            if data["retrue_name"] == "out":
                out_pic = "1"
                import datetime
                air_hwys_wts = get_model_return_dict(
                    self.sgoods.get_AIR_HWYS_WTS_by_jcno(jcno))
                if air_hwys_wts and air_hwys_wts.get(
                        "jd_time") is None and air_hwys_wts.get(
                            "jd_date") is None:
                    # if not(air_hwys_wts and air_hwys_wts.get('jd_time') and air_hwys_wts.get('jd_date')):
                    new_reds = add_model(
                        "GET_RED_COIN", **{
                            "id": str(uuid.uuid1()),
                            "login_name": args["login_name"],
                            "createtime": datetime.datetime.now(),
                            "red_id": 2,
                            "status": 1
                        })
                    if not new_reds:
                        return SYSTEM_ERROR
            if data["retrue_name"] == "weight":
                weight_pic = "1"
            new_goods_retrue = add_model(
                "GOODS_RETRUE", **{
                    "id": str(uuid.uuid4()),
                    "login_name": args["login_name"],
                    "in_pic": in_pic,
                    "out_pic": out_pic,
                    "weight_pic": weight_pic,
                    "jcno": args["jcno"]
                })
            if not new_goods_retrue:
                return SYSTEM_ERROR
        else:
            if data["retrue_name"] == "in":
                id = get_model_return_dict(
                    self.sgoods.get_retrue_by_jcno_in(args["jcno"]))
                if id:
                    return import_status("ERROR_FAIL_RETRUE", "FANSTI_ERROR",
                                         "ERROR_FAIL_RETRUE")
                else:
                    id_name = get_model_return_dict(
                        self.sgoods.get_retrue_by_jcno_loginname(
                            args["jcno"], args["login_name"]))
                    if not id_name:
                        new_goods_retrue = add_model(
                            "GOODS", **{
                                "id": str(uuid.uuid4()),
                                "login_name": args["login_name"],
                                "in_pic": "1",
                                "out_pic": "0",
                                "weight_pic": "0",
                                "jcno": args["jcno"]
                            })
                        if not new_goods_retrue:
                            return SYSTEM_ERROR
                    else:
                        update_goods_retrue = self.sgoods.update_goods_retrue_by_id(
                            id_name["id"], {"in_pic": "1"})
                        if not update_goods_retrue:
                            return SYSTEM_ERROR
            elif data["retrue_name"] == "out":
                id = get_model_return_dict(
                    self.sgoods.get_retrue_by_jcno_out(args["jcno"]))
                if id:
                    return import_status("ERROR_FAIL_RETRUE", "FANSTI_ERROR",
                                         "ERROR_FAIL_RETRUE")
                else:
                    id_name = get_model_return_dict(
                        self.sgoods.get_retrue_by_jcno_loginname(
                            args["jcno"], args["login_name"]))
                    if not id_name:
                        new_goods_retrue = add_model(
                            "GOODS", **{
                                "id": str(uuid.uuid4()),
                                "login_name": args["login_name"],
                                "in_pic": "0",
                                "out_pic": "1",
                                "weight_pic": "0",
                                "jcno": args["jcno"]
                            })
                        if not new_goods_retrue:
                            return SYSTEM_ERROR
                    else:
                        update_goods_retrue = self.sgoods.update_goods_retrue_by_id(
                            id_name["id"], {"out_pic": "1"})
                        if not update_goods_retrue:
                            return SYSTEM_ERROR
                    import datetime
                    air_hwys_wts = get_model_return_dict(
                        self.sgoods.get_AIR_HWYS_WTS_by_jcno(jcno))
                    if air_hwys_wts and air_hwys_wts.get(
                            "jd_time") is None and air_hwys_wts.get(
                                "jd_date") is None:
                        # if not(air_hwys_wts and air_hwys_wts.get('jd_time') and air_hwys_wts.get('jd_date')):
                        new_reds = add_model(
                            "GET_RED_COIN", **{
                                "id": str(uuid.uuid1()),
                                "login_name": args["login_name"],
                                "createtime": datetime.datetime.now(),
                                "red_id": 2,
                                "status": 1
                            })
                        if not new_reds:
                            return SYSTEM_ERROR
            elif data["retrue_name"] == "weight":
                id = get_model_return_dict(
                    self.sgoods.get_retrue_by_jcno_weight(args["jcno"]))
                if id:
                    return import_status("ERROR_FAIL_RETRUE", "FANSTI_ERROR",
                                         "ERROR_FAIL_RETRUE")
                else:
                    id_name = get_model_return_dict(
                        self.sgoods.get_retrue_by_jcno_loginname(
                            args["jcno"], args["login_name"]))
                    if not id_name:
                        new_goods_retrue = add_model(
                            "GOODS", **{
                                "id": str(uuid.uuid4()),
                                "login_name": args["login_name"],
                                "in_pic": "0",
                                "out_pic": "0",
                                "weight_pic": "1",
                                "jcno": args["jcno"]
                            })
                        if not new_goods_retrue:
                            return SYSTEM_ERROR
                    else:
                        update_goods_retrue = self.sgoods.update_goods_retrue_by_id(
                            id_name["id"], {"weight_pic": "1"})
                        if not update_goods_retrue:
                            return SYSTEM_ERROR
            else:
                return import_status("ERROR_WRONG_VALUE", "FANSTI_ERROR",
                                     "ERROR_WRONG_VALUE")
        # TODO 如果存在红包未领取,则修改红包状态
        return import_status("SUCCESS_RETRUE_GOODS", "OK")

    def get_retrue_num(self):
        args = request.args.to_dict()
        make_log("args", args)
        true_args = ["login_name"]
        if judge_keys(true_args, args.keys()) != 200:
            return judge_keys(true_args, args.keys())
        if not args["login_name"]:
            retrue_num = 0
        all_retrue = get_model_return_list(
            self.sgoods.get_retrue_by_login_name(args["login_name"]))
        make_log("all_retrue", all_retrue)
        if not all_retrue:
            return SYSTEM_ERROR
        retrue_num = len(all_retrue)
        response = import_status("SUCCESS_GET_RETRUE", "OK")
        response["data"] = {}
        response["data"]["retrue_num"] = retrue_num
        return response

    def export_zip(self):
        args = request.args.to_dict()
        jcno = args["jcno"]
        type = args["type"]
        rcptto = args["rcptto"]
        import zipfile
        if type == "in":
            jctype = "入仓"
            zip_name = "in.zip"
            zip_dir = 'E:\\fstfile\\photo\\{0}\\in\\in.zip'.format(jcno)
            f = zipfile.ZipFile(
                'E:\\fstfile\\photo\\{0}\\in\\in.zip'.format(jcno), 'w',
                zipfile.ZIP_STORED)
            photo_files = get_model_return_list(
                self.sgoods.get_in_order_by_jcno(args["jcno"]))
            for row in photo_files:
                abs_dir = "E:\\fstfile\\photo\\{0}\\in\\{1}".format(
                    jcno, row["filename"])
                f.write(abs_dir)
            f.close()
        elif type == "out":
            jctype = "出仓"
            zip_name = "out.zip"
            zip_dir = 'E:\\fstfile\\photo\\{0}\\out\\out.zip'.format(jcno)
            f = zipfile.ZipFile(
                'E:\\fstfile\\photo\\{0}\\out\\out.zip'.format(jcno), 'w',
                zipfile.ZIP_STORED)
            photo_files = get_model_return_list(
                self.sgoods.get_out_order_by_jcno(args["jcno"]))
            for row in photo_files:
                abs_dir = "E:\\fstfile\\photo\\{0}\\out\\{1}".format(
                    jcno, row["filename"])
                f.write(abs_dir)
            f.close()
        else:
            jctype = "称重"
            zip_name = "weight.zip"
            zip_dir = 'E:\\fstfile\\photo\\{0}\\weight\\weight.zip'.format(
                jcno)
            f = zipfile.ZipFile(
                'E:\\fstfile\\photo\\{0}\\weight\\weight.zip'.format(jcno),
                'w', zipfile.ZIP_STORED)
            photo_files = get_model_return_list(
                self.sgoods.get_weight_order_by_jcno(args["jcno"]))
            for row in photo_files:
                abs_dir = "E:\\fstfile\\photo\\{0}\\weight\\{1}".format(
                    jcno, row["filename"])
                f.write(abs_dir)
            f.close()

        # 引入邮件所需要的包
        import smtplib
        import email
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText
        from email.mime.image import MIMEImage
        from email.mime.base import MIMEBase
        from email.mime.application import MIMEApplication
        from email.header import Header
        print(1)
        # 发件人地址,通过控制台创建的发件人地址
        username = '******'
        # 发件人密码,通过控制台创建的发件人密码
        from Fansti.config.Inforcode import email_pwd
        password = email_pwd
        # 自定义的回复地址
        replyto = '*****@*****.**'
        # 收件人地址或是地址列表,支持多个收件人,最多30个
        # rcptto = '***,***'
        # rcptto = '*****@*****.**'
        # 构建alternative结构
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header('泛思特{0}照片'.format(jctype))
        msg['From'] = '%s <%s>' % (Header('泛思特客服'), username)
        msg['To'] = rcptto
        msg['Reply-to'] = replyto
        msg['Message-id'] = email.utils.make_msgid()
        msg['Date'] = email.utils.formatdate()
        # 构建alternative的text/html部分
        texthtml = MIMEText(
            '<html>'
            '<body>'
            '<div><a>进仓单号为{0}的{1}照片已经确认并发送到您邮箱,请点击下方链接下载</a>'
            '</div><div><a href="https://fstwechat.com/fansti/download/{2}/{3}">下载地址</a></div>'
            '</body></html>'.format(jcno, jctype, jcno, type),
            _subtype='html',
            _charset='UTF-8')
        msg.attach(texthtml)
        # 发送邮件
        try:
            print(2)
            client = smtplib.SMTP()
            # python 2.7以上版本,若需要使用SSL,可以这样创建client
            # client = smtplib.SMTP_SSL()
            # SMTP普通端口为25或80
            print(3)
            client.connect('smtpdm.aliyun.com', 80)
            # 开启DEBUG模式
            print(4)
            client.set_debuglevel(0)
            print(5)
            client.login(username, password)
            # 发件人和认证地址必须一致
            # 备注:若想取到DATA命令返回值,可参考smtplib的sendmaili封装方法:
            #      使用SMTP.mail/SMTP.rcpt/SMTP.data方法
            print(6)
            a = client.sendmail(username, rcptto, msg.as_string())
            # print(str(client.))
            print(str(a))
            client.quit()
            return {"status": 200, "message": "发送成功"}
        except Exception as e:
            print(e)
            return {"status": 405, "status_code": 405899, "message": str(e)}
Beispiel #6
0
class FSother(Resource):
    def __init__(self):
        self.title = "=========={0}=========="
        from Fansti.services.SUsers import SUsers
        self.suser = SUsers()
        from Fansti.services.SGoods import SGoods
        self.sgoods = SGoods()

    def get(self, other):
        print(self.title.format("api is" + other))
        if other == "get_custom":
            args = request.args.to_dict()
            make_log("args", args)
            true_params = ["login_name"]
            if judge_keys(true_params, args.keys()) != 200:
                return judge_keys(true_params, args.keys())

            if args["login_name"] not in ["", None]:
                accounts = get_model_return_dict(self.suser.get_compnay_by_loginname(args["login_name"]))
                if not accounts:
                    return import_status("ERROR_GET_CUSTOM", "FANSTI_ERROR", "ERROR_GET_CUSTOM")
                make_log("accounts", accounts)
                xsr = get_model_return_dict(self.sgoods.get_xsr_by_user(accounts["compnay"]))["xsr"]
                make_log("xsr", xsr)
                user_abo = get_model_return_dict(self.suser.get_custom_by_xsr(xsr))
                user_abo["user_name"] = user_abo["user_name"]
                make_log("user_abo", user_abo)
                data = user_abo
            else:
                cf = configparser.ConfigParser()
                cf.read(FANSTICONFIG)
                make_log("selector", cf.sections())
                name = cf.get("custom", "name")

                qq = cf.get("custom", "qq")
                telphone = cf.get("custom", "telphone")
                email = cf.get("custom", "email")
                data = {
                    "user_name": name.replace("\"", ""),
                    "qq": qq.replace("\"", ""),
                    "telephone": telphone.replace("\"", ""),
                    "email": email.replace("\"", "")
                }
            response = import_status("SUCCESS_GET_CUSTOM", "OK")
            response["data"] = data
            return response

        if other == "get_phone":
            cf = configparser.ConfigParser()
            cf.read(FANSTICONFIG)
            phone_list = cf.get("phone", "whitelist")
            if str(phone_list) == "[]":
                phone_list = str(phone_list).replace("[", "").replace("]", "")
                phone_list = list(phone_list)
            else:
                phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\"", "") \
                    .replace("\'", "").replace("\\", "").replace(" ", "").replace("u", "").split(",")
                print(phone_list)
            response = import_status("SUCCESS_GET_NEWS", "OK")
            response["data"] = phone_list
            return response

        if other == "get_enquiry":
            cf = configparser.ConfigParser()
            cf.read(FANSTICONFIG)
            phone_list = cf.get("enquiry", "whitelist")
            if str(phone_list) == "[]":
                phone_list = str(phone_list).replace("[", "").replace("]", "")
                phone_list = list(phone_list)
            else:
                phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\"", "") \
                    .replace("\'", "").replace("\\", "").replace(" ", "").replace("u", "").split(",")
                print(phone_list)
            response = import_status("SUCCESS_GET_NEWS", "OK")
            response["data"] = phone_list
            return response

        return APIS_WRONG

    def post(self, other):
        print(self.title.format("api is" + other))
        if other == "update_custom":
            data = json.loads(request.data)
            make_log("data", data)
            true_params = ["name", "qq", "telphone", "email"]
            if judge_keys(true_params, data.keys()) != 200:
                return judge_keys(true_params, data.keys())
            cf = configparser.ConfigParser()
            cf.read(FANSTICONFIG)
            cf.set("custom", "name", data["name"])
            cf.set("custom", "qq", data["qq"])
            cf.set("custom", "telphone", data["telphone"])
            cf.set("custom", "email", data["email"])
            cf.write(open(FANSTICONFIG, "w"))

            return import_status("SUCCESS_UPDATE_CUSTOM", "OK")

        if other == "update_phone":
            data = json.loads(request.data)
            true_params = ["control", "phone_list"]
            if judge_keys(true_params, data.keys()) != 200:
                return judge_keys(true_params, data.keys())
            cf = configparser.ConfigParser()
            cf.read(FANSTICONFIG)
            phone_list = cf.get("phone", "whitelist")
            for row in data["phone_list"]:
                if data["control"] == "delete":
                    if str(phone_list) == "[]":
                        phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\r", "").replace("\n", "")\
                            .replace("\'", "")
                        phone_list = list(phone_list)
                    else:
                        phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\"", "")\
                            .replace("\'", "").replace("\\", "").replace(" ", "").replace("u", "").split(",")
                        print(phone_list)
                    if row in phone_list:
                        phone_list.remove(row)
                if data["control"] == "add":
                    if str(phone_list) == "[]":
                        phone_list = str(phone_list).replace("[", "").replace("]", "")
                        phone_list = list(phone_list)
                    else:
                        phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\"", "")\
                            .replace("\'", "").replace("\\", "").replace(" ", "").replace("u", "").split(",")
                        print(phone_list)
                    if row not in phone_list:
                        phone_list.append(row)
            print(phone_list)
            cf.set("phone", "whitelist", str(phone_list))
            cf.write(open(FANSTICONFIG, "w"))

            return import_status("SUCCESS_UPDATE_PHONE", "OK")

        if other == "update_enquiry":
            data = json.loads(request.data)
            true_params = ["control", "phone_list"]
            if judge_keys(true_params, data.keys()) != 200:
                return judge_keys(true_params, data.keys())
            cf = configparser.ConfigParser()
            cf.read(FANSTICONFIG)
            phone_list = cf.get("enquiry", "whitelist")
            for row in data["phone_list"]:
                if data["control"] == "delete":
                    if str(phone_list) == "[]":
                        phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\r", "").replace("\n", "")\
                            .replace("\'", "")
                        phone_list = list(phone_list)
                    else:
                        phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\"", "")\
                            .replace("\'", "").replace("\\", "").replace(" ", "").replace("u", "").split(",")
                        print(phone_list)
                    if row in phone_list:
                        phone_list.remove(row)
                if data["control"] == "add":
                    if str(phone_list) == "[]":
                        phone_list = str(phone_list).replace("[", "").replace("]", "")
                        phone_list = list(phone_list)
                    else:
                        phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\"", "")\
                            .replace("\'", "").replace("\\", "").replace(" ", "").replace("u", "").split(",")
                        print(phone_list)
                    if row not in phone_list:
                        phone_list.append(row)
            print(phone_list)
            cf.set("enquiry", "whitelist", str(phone_list))
            cf.write(open(FANSTICONFIG, "w"))

            return import_status("SUCCESS_UPDATE_PHONE", "OK")
        return APIS_WRONG
Beispiel #7
0
 def __init__(self):
     from Fansti.services.SUsers import SUsers
     self.susers = SUsers()
     from Fansti.services.SReds import SReds
     self.sreds = SReds()
Beispiel #8
0
class CUsers():
    def __init__(self):
        from Fansti.services.SUsers import SUsers
        self.susers = SUsers()
        from Fansti.services.SReds import SReds
        self.sreds = SReds()

    def user_binding(self):
        data = json.loads(request.data)
        make_log("data", data)
        true_data = ["phone", "openid"]
        null_data = [
            "login_name", "login_password", "name", "usex", "city", "province"
        ]
        wl_key = [
            'status', 'openid', 'province', 'name', 'user_introduction',
            'city', 'work_goodat', 'qq', 'login_name', 'work_year', 'phone',
            'email', 'wechat', 'user_name', 'id', 'usex'
        ]

        wl = {k: data.get(k) for k in wl_key if k in data}
        import configparser
        from Fansti.config.Inforcode import FANSTICONFIG
        cfg = configparser.ConfigParser()
        cfg.read(FANSTICONFIG)
        usertype = -111
        phone_list = eval(cfg.get("phone", "whitelist"))
        data["name"] = None
        if str(data.get("phone")) in phone_list:
            wechat_login_tmp = get_model_return_dict(
                self.susers.get_wechat_login_by_phone(data.get("phone")))
            if not wechat_login_tmp:
                if "login_name" in data and "login_password" in data:
                    check_result = self.check_name_password(
                        data.get("login_name"), data.get("login_password"))
                    if check_result:
                        return check_result

                self.susers.add_model(
                    "WECHAT_LOGIN", **{
                        "id": str(uuid.uuid1()),
                        "openid": data.get("openid", ""),
                        "login_name": data.get("login_name", ""),
                        "name": data.get("name", ""),
                        "phone": data.get("phone"),
                        "status": data.get("status", "1"),
                        "usex": data.get("usex", ""),
                        "city": data.get("city", ""),
                        "province": data.get("province", "")
                    })

            else:
                if "login_name" in data and "login_password" in data:
                    check_result = self.check_name_password(
                        data.get("login_name"), data.get("login_password"))
                    if check_result:
                        return check_result
                    usertype = get_model_return_dict(
                        self.susers.get_user_type(
                            data.get("login_name"))).get("user_type")
                update_result = self.susers.update_wechat_login_by_phone(
                    data.get("phone"), wl)
                if not update_result:
                    return import_status("ERROR_UPDATE_DATA", "FANSTI_ERROR",
                                         "ERROR_UPDATE_DATA")
            response = import_status("SUCCESS_USER_BINDING", "OK")
            response['data'] = usertype
            return response
        if judge_keys(true_data, data.keys(), null_data) != 200:
            return judge_keys(true_data, data.keys(), null_data)
        # if self.get_wechat_phone(data["phone"]) != 200:
        # return self.get_wechat_phone(data["phone"]
        wl_tmp = get_model_return_dict(
            self.susers.get_wechat_login_by_phone(data["phone"]))

        if "login_name" in data and "login_password" in data:
            check_result = self.check_name_password(data.get("login_name"),
                                                    data.get("login_password"))
            if check_result:
                return check_result
            usertype = get_model_return_dict(
                self.susers.get_user_type(
                    data.get("login_name"))).get("user_type")

        if "login_name" not in data:
            data["login_name"] = None
        if "name" not in data:
            data["name"] = None
        if "usex" not in data:
            data["usex"] = None
        if "city" not in data:
            data["city"] = None
        if "province" not in data:
            data["province"] = None
        if "id" in wl_tmp:
            self.susers.update_wechat_login_by_phone(data['phone'], wl)
        else:
            add_wechat_login = add_model(
                "WECHAT_LOGIN", **{
                    "id": str(uuid.uuid1()),
                    "login_name": data["login_name"],
                    "openid": data["openid"],
                    "status": "1",
                    "phone": data["phone"],
                    "name": data["name"],
                    "usex": data["usex"],
                    "city": data["city"],
                    "province": data["province"]
                })
            make_log("add_wechat_login", add_wechat_login)
            if not add_wechat_login:
                return SYSTEM_ERROR
        # else:
        #     add_wechat_login = add_model("WECHAT_LOGIN",
        #                                  **{
        #                                      "id": str(uuid.uuid1()),
        #                                      "openid": data["openid"],
        #                                      "status": "1",
        #                                      "phone": data["phone"],
        #                                       "name": data["name"],
        #                                       "usex": data["usex"],
        #                                       "city": data["city"],
        #                                       "province": data["province"]
        #                                  })
        #     make_log("add_wechat_login", add_wechat_login)
        #     if not add_wechat_login:
        #         return SYSTEM_ERROR
        response = import_status("SUCCESS_USER_BINDING", "OK")
        from Fansti.config.Inforcode import FANSTICONFIG
        import configparser
        cf = configparser.ConfigParser()
        cf.read(FANSTICONFIG)
        phone_list = cf.get("enquiry", "whitelist")
        if str(phone_list) == "[]":
            phone_list = str(phone_list).replace("[", "").replace("]", "")
            phone_list = list(phone_list)
        else:
            phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\"", "") \
                .replace("\'", "").replace("\\", "").replace(" ", "").replace("u", "").split(",")
            print(phone_list)
        response["data"] = {}
        response['data']["user_type"] = usertype
        if data["login_name"] not in phone_list:
            response["data"]["is_show"] = 0
        else:
            response["data"]["is_show"] = 1
        return response

    def get_wechat_phone(self, phone):
        id = get_model_return_dict(
            self.susers.get_wechat_login_by_phone(phone))
        make_log("id", id)
        if "id" in id and not id["login_name"]:
            return import_status("ERROR_SOMEONE_BINDING", "FANSTI_ERROR",
                                 "ERROR_SOMEONE_BINDING")
        return 200

    def get_binding(self):
        args = request.args.to_dict()
        make_log("args", args)
        true_params = ["openid"]
        if judge_keys(true_params, args.keys()) != 200:
            return judge_keys(true_params, args.keys())
        get_status_by_openid = get_model_return_dict(
            self.susers.get_wechat_login_by_openid(args["openid"]))
        make_log("get_status_by_openid", get_status_by_openid)
        if not get_status_by_openid:
            return SYSTEM_ERROR
        else:
            if not get_status_by_openid["login_name"]:
                user_type = -111
            else:
                user_type = get_model_return_dict(
                    self.susers.get_user_type(
                        get_status_by_openid["login_name"]))["user_type"]

        from Fansti.config.Inforcode import FANSTICONFIG
        import configparser
        cf = configparser.ConfigParser()
        cf.read(FANSTICONFIG)
        phone_list = cf.get("enquiry", "whitelist")
        if str(phone_list) == "[]":
            phone_list = str(phone_list).replace("[", "").replace("]", "")
            phone_list = list(phone_list)
        else:
            phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\"", "") \
                .replace("\'", "").replace("\\", "").replace(" ", "").replace("u", "").split(",")
            print(phone_list)

        response = import_status("ERROR_HAVE_BINDING", "OK")
        response["data"] = {}
        if get_status_by_openid["login_name"] not in phone_list:
            response["data"]["is_show"] = 0
        else:
            response["data"]["is_show"] = 1
        response["data"]["login_name"] = get_status_by_openid["login_name"]
        response["data"]["user_type"] = user_type
        return response

    def get_openid(self):
        args = request.args.to_dict()
        make_log("args", args)
        true_params = ["code"]
        if judge_keys(true_params, args.keys()) != 200:
            return judge_keys(true_params, args.keys())
        from Fansti.config.Inforcode import APP_ID, APP_SECRET_KEY
        request_url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type={3}" \
            .format(APP_ID, APP_SECRET_KEY, args["code"], "authorization_code")
        strResult = None
        try:
            import urllib.request
            req = urllib.request.urlopen(request_url)
            strResult = req.read().decode("utf8")
            req.close()
            make_log("strResult", strResult)
        except Exception as e:
            print(e)
            return NETWORK_ERROR
        jsonResult = json.loads(strResult)
        if "openid" not in strResult or "session_key" not in strResult:
            return jsonResult
        openid = jsonResult["openid"]
        response = import_status("SUCCESS_GET_OPENID", "OK")
        response["data"] = {}
        response["data"]["openid"] = openid
        return response

    def get_openid2(self):
        args = request.args.to_dict()
        make_log("args", args)
        true_params = ["code"]
        if judge_keys(true_params, args.keys()) != 200:
            return judge_keys(true_params, args.keys())
        request_url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type={3}" \
            .format("wxd1facdac814bb86f", "d92626eb3dc8e0e0f1cff7d511d28b0a", args["code"], "authorization_code")
        strResult = None
        try:
            import urllib.request
            req = urllib.request.urlopen(request_url)
            strResult = req.read().decode("utf8")
            req.close()
            make_log("strResult", strResult)
        except Exception as e:
            print(e)
            return NETWORK_ERROR
        jsonResult = json.loads(strResult)
        if "openid" not in strResult or "session_key" not in strResult:
            return jsonResult
        openid = jsonResult["openid"]
        response = import_status("SUCCESS_GET_OPENID", "OK")
        response["data"] = {}
        response["data"]["openid"] = openid
        return response

    def make_user_message(self):
        args = request.args.to_dict()
        make_log("args", args)
        data = json.loads(request.data)
        make_log("data", data)
        true_args_params = ["openid"]
        true_data_params = ["message"]
        if judge_keys(true_args_params, args.keys()) != 200:
            return judge_keys(true_args_params, args.keys())
        if judge_keys(true_data_params, data.keys()) != 200:
            return judge_keys(true_data_params, data.keys())
        phone = get_model_return_dict(
            self.susers.get_wechat_login(args["openid"]))["phone"]
        new_message = add_model(
            "USER_MESSAGE", **{
                "id": str(uuid.uuid4()),
                "phone": phone,
                "message": data["message"]
            })
        if not new_message:
            return SYSTEM_ERROR
        return import_status("SUCCESS_MAKE_MESSAGE", "OK")

    def get_user_message(self):
        args = request.args.to_dict()
        make_log("args", args)
        true_args = ["page_size", "page_num"]
        if judge_keys(true_args, args.keys()) != 200:
            return judge_keys(true_args, args.keys())
        page_size = int(args.get("page_size"))
        page_num = int(args.get("page_num"))
        all_message = get_model_return_list(
            self.susers.get_user_message(page_size, page_num))
        make_log("all_message", all_message)
        response = import_status("SUCCESS_GET_RETRUE", "OK")
        response["data"] = {}
        response["data"]["message_list"] = all_message
        response["data"]["count"] = len(
            get_model_return_list(self.susers.get_all_user_message()))
        return response

    def add_invate(self):
        args = request.args.to_dict()
        make_log("args", args)
        data = json.loads(request.data)
        make_log("data", data)
        true_args = ["openid"]
        true_data = ["openid"]
        if judge_keys(true_args, args.keys()) != 200:
            return judge_keys(true_args, args.keys())
        if judge_keys(true_data, data.keys()) != 200:
            return judge_keys(true_data, data.keys())
        wechat_login = get_model_return_dict(
            self.susers.get_wechat_login_by_openid(data["openid"]))
        user_invate = get_model_return_dict(
            self.susers.get_id_by_openid(data["openid"]))
        if user_invate:
            return import_status("ERROR_MESSAGE_CLICK", "FANSTI_ERROR",
                                 "ERROR_HAVE_INVATED")
        if wechat_login:
            return import_status("ERROR_HAVE_INVATED", "FANSTI_ERROR",
                                 "ERROR_HAVE_INVATED")
        new_user_invate = add_model(
            "USER_INVATE", **{
                "id": str(uuid.uuid4()),
                "args_openid": args["openid"],
                "invate_openid": data["openid"]
            })
        if not new_user_invate:
            return SYSTEM_ERROR
        return import_status("SUCCESS_NEW_INVATE", "OK")

    def get_invate_list(self):
        args = request.args.to_dict()
        make_log("args", args)
        true_args = ["openid", "page_size", "page_num"]
        if judge_keys(true_args, args.keys()) != 200:
            return judge_keys(true_args, args.keys())
        all_invate = get_model_return_list(
            self.susers.get_invate_by_login_name(args["openid"],
                                                 int(args["page_size"]),
                                                 int(args["page_num"])))
        make_log("all_invate", all_invate)
        for row in all_invate:
            a_invate = get_model_return_dict(
                self.susers.get_invate_abo_by_openid(row["invate_openid"]))
            if a_invate:
                make_log("a_invate", a_invate)
                row["name"] = a_invate["name"]
                #.decode("gbk").encode("utf8")
                row["phone"] = a_invate["phone"]

        phone = get_model_return_dict(
            self.susers.get_wechat_login(args["openid"]))
        make_log("phone", phone)
        if not phone:
            return SYSTEM_ERROR
        phone = phone["phone"]
        response = import_status("SUCCESS_GET_INVATE", "OK")
        top_phone = args.get("top_phone")

        if top_phone:
            phone = top_phone

        if self.check_role(phone):
            response["top_phone"] = phone
            for row in all_invate:
                invate_openid = row["invate_openid"]
                second_all_invate = get_model_return_list(
                    self.susers.get_invate_by_login_name(
                        invate_openid, int(args["page_size"]),
                        int(args["page_num"])))
                make_log("second_all_invate", second_all_invate)
                row["second_invate"] = False
                if second_all_invate:
                    row["second_invate"] = True

        response["data"] = all_invate
        return response

    def get_my_info(self):
        args = request.args.to_dict()
        make_log("args", args)
        true_args = ["openid"]
        if judge_keys(true_args, args.keys()) != 200:
            return judge_keys(true_args, args.keys())
        my_info = get_model_return_dict(
            self.susers.get_personal_by_openid(args["openid"]))
        make_log("my_info", my_info)
        for row in my_info.keys():
            if my_info[row]:
                my_info[row] = my_info[row]
        response = import_status("SUCCESS_GET_RETRUE", "OK")
        response["data"] = my_info
        return response

    def update_my_info(self):
        args = request.args.to_dict()
        make_log("args", args)
        true_args = ["openid"]
        if judge_keys(true_args, args.keys()) != 200:
            return judge_keys(true_args, args.keys())
        data = json.loads(request.data)
        make_log("data", data)
        true_data = ["user_name"]
        null_data = [
            "work_year", "work_goodat", "user_introduction", "qq", "wechat",
            "email"
        ]
        if judge_keys(true_data, data.keys(), null_data) != 200:
            return judge_keys(true_data, data.keys(), null_data)
        phone = get_model_return_dict(
            self.susers.get_wechat_login(args["openid"]))["phone"]
        make_log("phone", phone)
        if not phone:
            return SYSTEM_ERROR
        my_info = get_model_return_dict(
            self.susers.get_personal_by_openid(args["openid"]))
        make_log("myinfo", my_info)
        if not my_info:
            return SYSTEM_ERROR
        for key in null_data:
            if key not in data.keys():
                data[key] = None
        update_info = self.susers.update_wechat_login(
            args["openid"], {
                "user_name": data["user_name"],
                "work_year": data["work_year"],
                "work_goodat": data["work_goodat"],
                "user_introduction": data["user_introduction"],
                "qq": data["qq"],
                "wechat": data["wechat"],
                "email": data["email"]
            })
        if not update_info:
            return SYSTEM_ERROR
        response = import_status("SUCCESS_GET_RETRUE", "OK")
        return response

    def check_name_password(self, name, password):
        # TODO 判断是否存在当前月红包,存在的话
        import hashlib
        login_password = hashlib.md5()
        login_password.update(password.encode("utf8"))
        password = login_password.hexdigest()
        name_password_phone = get_model_return_dict(
            self.susers.get_name_password_phone(name))
        make_log("name_password_phone", name_password_phone)
        if not name_password_phone:
            return import_status("ERROR_NONE_USER", "FANSTI_ERROR",
                                 "ERROR_NONE_USER")
        if password != name_password_phone["login_password"]:
            return import_status("ERROR_WRONG_PASSWORD", "FANSTI_ERROR",
                                 "ERROR_WRONG_PASSWORD")
        else:
            # 用户名密码没问题 增加红包
            red_conis = self.sreds.get_red_all()
            for red_coin in red_conis:
                my_red_coin = self.sreds.get_myred_by_redid(red_coin.id)
                if my_red_coin:
                    continue
                import datetime
                self.sreds.add_model(
                    "GET_RED_COIN", **{
                        "id": str(uuid.uuid1()),
                        "login_name": name,
                        "createtime": datetime.datetime.now(),
                        "red_id": red_coin.id,
                        "status": 0
                    })

            return False

    def check_username_phone(self, name, phone):
        name_password_phone = get_model_return_dict(
            self.susers.get_name_password_phone(name))
        if name_password_phone and name_password_phone["phone"] == phone:
            return True
        else:
            return False

    def check_role(self, phone):
        import configparser
        from Fansti.config.Inforcode import FANSTICONFIG
        cf = configparser.ConfigParser()
        cf.read(FANSTICONFIG)
        phone_list = cf.get("phone", "whitelist")
        if str(phone_list) == "[]":
            phone_list = str(phone_list).replace("[", "").replace("]", "")
            phone_list = list(phone_list)
        else:
            phone_list = str(phone_list).replace("[", "").replace("]", "").replace("\"", "") \
                .replace("\'", "").replace("\\", "").replace(" ", "").replace("u", "").split(",")

        return phone in phone_list

    def user_login_local(self):
        data = json.loads(request.data)
        make_log("data", data)
        true_data = ["phone", "login_name", "login_password", "openid"]
        if judge_keys(true_data, data.keys()) != 200:
            return judge_keys(true_data, data.keys())

        if "login_name" in data and "login_password" in data:
            check_result = self.check_name_password(data.get("login_name"),
                                                    data.get("login_password"))
            if check_result:
                return check_result

        openid = get_model_return_dict(
            self.susers.get_user_openid(data.get("login_name")))["open_id"]
        if openid and openid != data.get("openid"):
            return {"status": 405, "status_code": 405939, "message": "该账号已被授权"}
        if not openid:
            id = get_model_return_dict(
                self.susers.get_id_by_name(data.get("login_name")))["id"]
            update_user = self.susers.update_d_message_user(
                id, {"open_id": data.get("openid")})
            if not update_user:
                return {
                    "status": 405,
                    "status_code": 405976,
                    "message": "绑定失败"
                }
        usertype = get_model_return_dict(
            self.susers.get_user_type(data.get("login_name"))).get("user_type")
        if not self.check_username_phone(data["login_name"], data["phone"]):
            return {"status": 405, "status_code": 405601, "message": "手机号错误"}
        return {
            "status": 200,
            "message": "登陆成功",
            "data": {
                "user_type": usertype
            }
        }
Beispiel #9
0
 def __init__(self):
     from Fansti.services.SNews import SNews
     self.snews = SNews()
     from Fansti.services.SUsers import SUsers
     self.susers = SUsers()
Beispiel #10
0
class CReds():
    def __init__(self):
        from Fansti.services.SReds import SReds
        self.sred = SReds()
        from Fansti.services.SUsers import SUsers
        self.suser = SUsers()

    def get_all_red(self):
        args = request.args.to_dict()
        make_log("args", args)
        true_params = ["login_name"]
        if judge_keys(true_params, args.keys()) != 200:
            return judge_keys(true_params, args.keys())
        all_red = get_model_return_list(
            self.sred.get_my_red_status(args["login_name"]))
        make_log("all_red", all_red)
        response = import_status("SUCCESS_GET_RED", "OK")
        response["data"] = {}
        response["data"]["red_list"] = []
        for red in all_red:
            red_id = red["red_id"]
            red_abo = get_model_return_dict(self.sred.get_red_by_id(red_id))
            make_log("red_abo", red_abo)
            if not red_abo:
                return SYSTEM_ERROR
            red["name"] = red_abo["name"]
            red["price"] = red_abo["price"]
            #red["createtime"] = red["createtime"].strftime("%Y-%m-%d")
            response["data"]["red_list"].append(red_abo)
        response["data"]["red_num"] = len(
            get_model_return_list(
                self.sred.get_my_red_rereceive(args["login_name"])))
        response["data"]["red_list"] = all_red
        my_red = get_model_return_list(
            self.sred.get_my_red_receive(args["login_name"]))
        response["data"]["my_red_num"] = len(my_red)
        all_price = 0
        for red in my_red:
            a_red = get_model_return_dict(
                self.sred.get_red_by_id(red["red_id"]))
            make_log("a_red", a_red)
            red["createtime"] = red["createtime"].strftime("%Y-%m-%d")
            if not a_red:
                return SYSTEM_ERROR
            red["name"] = a_red["name"]
            red["price"] = a_red["price"]
            all_price = all_price + float(a_red["price"])

        response["data"]["my_red_list"] = my_red
        response["data"]["my_red_coin"] = all_price
        response["data"]["month_red"] = []
        month = 1
        while month < 13:
            my_red_month = get_model_return_list(
                self.sred.get_my_red_by_time(
                    datetime.datetime(datetime.datetime.now().year, month, 1,
                                      0, 0, 0),
                    datetime.datetime(
                        datetime.datetime.now().year, month,
                        calendar.monthrange(datetime.datetime.now().year,
                                            month)[1], 23, 59, 59)))
            month_red = {"month": month, "count": len(my_red_month)}
            response["data"]["month_red"].append(month_red)
            month = month + 1
        print(response)
        return response

    def receive_red(self):
        """红包提现"""
        data = request.json or {}
        make_log("args", data)
        red_id = data.get('red_id')
        response = import_status("SUCCESS_GET_INFO", "OK")
        # 判断用户是否有这个红包
        openid = data.get('openid')
        user = self.suser.get_user_by_openid(openid)
        if not user:
            return jsonify({"status": 404, "message": "非法用户"})
        login_name = user.login_name
        user_red = self.sred.get_userred_by_loginname_redid(login_name, red_id)
        if not user_red:
            return jsonify({"status": 404, "message": "红包状态错误"})
        red = self.sred.get_red_new_by_id(user_red.red_id)
        if not red:
            return jsonify({"status": 404, "message": "不存在的红包"})
        # 计算金额, 退款
        amount = int(red.price) * 100
        desc = '红包领取'
        partner_trade_no = user_red.id.replace('-', '')
        # data = self.wx_login.jscode2session(openid)
        try:
            raw = self.pay.pay_individual(openid=openid,
                                          amount=amount,
                                          partner_trade_no=partner_trade_no,
                                          spbill_create_ip=request.remote_addr,
                                          desc=desc)
        except WeixinError as e:
            return jsonify({"status": 404, "message": e.args})
        # 改状态
        user_red = self.sred.update_user_red_by_id(user_red.id, {'status': 2})
        response['data'] = raw
        return response

    def receive_red_query(self):
        """"""
        data = request.json or {}
        # red_id = data.get('red_id')
        id = data.get('id')
        # 判断用户是否有这个红包
        openid = data.get('openid')
        # user = self.suser.get_user_by_openid(openid)
        # if not user:
        #     return jsonify({
        #         "status": 404,
        #         "message": "非法用户"
        #     })
        # login_name = user.login_name
        # user_red = self.sred.get_userred_by_loginname_redid(login_name, red_id, status=2)
        user_red = self.sred.get_userred_by_id(id)
        if not user_red:
            return jsonify({"status": 404, "message": "红包状态错误"})
        response = import_status("SUCCESS_GET_INFO", "OK")
        partner_trade_no = user_red.id.replace('-', '')
        try:
            raw = self.pay.pay_individual_query(
                partner_trade_no=partner_trade_no)
        except WeixinError as e:
            return jsonify({"status": 404, "message": e.args})
        response['data'] = raw
        return response

    @property
    def pay(self):
        return WeixinPay(APP_ID,
                         mch_id,
                         mch_key,
                         key='./apiclient_key.pem',
                         cert='./apiclient_cert.pem')

    @property
    def wx_login(self):
        return WeixinLogin(APP_ID, APP_SECRET_KEY)