Exemplo n.º 1
0
def get_wait_num():
    """获取等待数量"""
    addr = request.args.get("work_addr") 
    #addr = "新津县"
    if not addr:
        return jsonify(errno=RET.PARAMERR, errmsg="缺少地址")
    user_id = request.args.get("user_id")
    if not user_id:
        return jsonify(errno=RET.PARAMERR, errmsg="用户未登陆")
    subject = request.args.get("subject")
    if not subject:
        return jsonify(errno=RET.PARAMERR, errmsg="缺少主题")
    print("++++获取等待数量++++",addr,user_id,subject)
    length = redis_store.llen(addr + subject)
    return jsonify(errno=RET.OK,errmsg='成功',data=length)
Exemplo n.º 2
0
def danmaku():
    import json
    if request.method == 'GET':
        id = request.args.get('id')
        key = 'movie' + str(id)
        if redis_store.llen(key):
            msgs = redis_store.lrange(key, 0, 999)
            print(msgs)
            res = {
                'code': 1,
                "danmaku": [json.loads(v) for v in msgs]
            }
        else:
            res = {
                'code': 1,
                "danmaku": []
            }
        resp = json.dumps(res)
    if request.method == 'POST':
        data = json.loads(request.get_data())
        print(data)
        msg = {
            "id": data['id'],
            "author": data['author'],
            "time": data['time'],
            "text": data['text'],
            "color": data['color'],
            "type": data['type'],
            "ip": request.remote_addr,
            "mid": datetime.datetime.now().strftime('%Y%m%d%H%M%S') + uuid.uuid4().hex,
            # 'player': [
            #     data['player'],
            # ]
        }
        # data.append("'ip':request.remote_addr","'_id':datetime.datetime.now().strftime('%Y%m%d%H%M%S') + uuid.uuid4().hex")
        res = {
            'code': 1,
            'data': msg
        }
        resp = json.dumps(res)
        redis_store.lpush('movie' + str(msg['mid']), json.dumps(msg))
    return Response(resp, mimetype='application/json')
Exemplo n.º 3
0
def subjects():
    addr = request.args.get("work_addr")
    print("++++获取主题++++", addr)
    if not addr:
        return jsonify(errno=RET.PARAMERR, errmsg="缺少地址")
    try:
        subjects = Subject.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if subjects:
        subjects_dict_list = [subject.to_dict() for subject in subjects]
        try:
            for i in subjects_dict_list:
                i.__setitem__("wait", redis_store.llen(addr + i["name"]))
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.SERVERERR, errmsg="内部错误")
        return jsonify(errno=RET.OK,
                       errmsg="成功",
                       data={"subjects": subjects_dict_list})
    return jsonify(errno=RET.NODATA, errmsg="无数据")
Exemplo n.º 4
0
def data_analysis():
    req_dict = request.get_json()
    addr = req_dict.get("work_addr")
    print("++++数据分析++++", addr)
    if not addr:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少地址')
    # 获取今天三周几
    current_day = datetime(datetime.now().year,
                           datetime.now().month,
                           datetime.now().day, 0, 0)
    weekday = int(datetime.now().strftime("%w"))
    weekday = 7 if weekday == 0 else weekday
    this_date_list = list()
    last_date_list = list()
    this_week_data_list = list()
    last_week_data_list = list()
    for i in range(1, 8):
        this_date_list.append(current_day - timedelta(weekday - i))
        last_date_list.append(current_day - timedelta(weekday - i + 7))
    # 从数据库拿出主题和事项
    try:
        subjects = Subject.query.all()
        items = Item.query.all()
        # 获取本周人流量
        for i in this_date_list:
            obj = Business.query.filter(
                Business.create_time.between(i, i + timedelta(1))).all()
            this_week_data_list.append(len(obj))
        # 获取上周人流量
        for i in last_date_list:
            obj = Business.query.filter(
                Business.create_time.between(i, i + timedelta(1))).all()
            last_week_data_list.append(len(obj))
        # 获取总人流量和周天平均值
        daliy_datas = Business.query.all()
        week_avg_data_list = [0 for i in range(7)]
        for i in daliy_datas:
            week_avg_data_list[(int(i.create_time.strftime("%w")) - 1)] += 1
        week_avg_data_list = list(
            map(
                lambda x: int(x / len(daliy_datas) * 7)
                if len(daliy_datas) else 0, week_avg_data_list))
        # 获取上周时间段人流量
        last_week_time_step_list = [0 for i in TIME_STEP_LIST]
        for i in last_date_list:
            for j in TIME_STEP_LIST:
                start_search_time = datetime(i.year, i.month, i.day, j % 24, 0)
                end_search_time = datetime(i.year, i.month, i.day,
                                           (j + 1) % 24, 0)
                ret = Business.query.filter(
                    Business.create_time.between(start_search_time,
                                                 end_search_time)).all()
                last_week_time_step_list[TIME_STEP_LIST.index(j)] += len(ret)
        # 获取时间段平均值
        avg_time_step_data = [0 for i in TIME_STEP_LIST]
        for i in daliy_datas:
            for j in TIME_STEP_LIST:
                if i.create_time.hour == j:
                    avg_time_step_data[TIME_STEP_LIST.index(j)] += 1
                    break
        avg_time_step_data = list(
            map(
                lambda x: int(x / len(daliy_datas) * 7)
                if len(daliy_datas) else 0, avg_time_step_data))
        # 获取当天时间段
        time_step_list = [0 for i in TIME_STEP_LIST]
        for i in daliy_datas:
            for j in TIME_STEP_LIST:
                if i.create_time.hour == j and i.create_time.strftime(
                        "%Y%m%d") == datetime.now().strftime("%Y%m%d"):
                    time_step_list[TIME_STEP_LIST.index(j)] += 1
                    break
        # 获取上周各主题取号量
        last_week_subject_click = [0 for i in subjects]
        subjects_name_list_for_search = [subject.name for subject in subjects]
        for i in subjects_name_list_for_search:
            for j in last_date_list:
                ret = Business.query.filter(
                    Business.addr == addr, Business.subject == i,
                    Business.create_time.between(j, j + timedelta(1))).all()
                last_week_subject_click[subjects_name_list_for_search.index(
                    i)] += len(ret)
        # 获取本周各主题取号量
        this_week_subject_click = [0 for i in subjects]
        for i in subjects_name_list_for_search:
            for j in this_date_list:
                ret = Business.query.filter(
                    Business.addr == addr, Business.subject == i,
                    Business.create_time.between(j, j + timedelta(1))).all()
                this_week_subject_click[subjects_name_list_for_search.index(
                    i)] += len(ret)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    # 从缓存拿出所需数据
    try:
        # 获取历史取号总量,当天取号总量,当天叫号总量,当天接件通过总量,当天转号总量,当天等待总时间,历史省内外比例,历史年龄分段情况
        today_daliy_datas = Business.query.filter(
            Business.create_time.between(current_day,
                                         current_day + timedelta(1))).all()
        history_total = len(daliy_datas)
        total_number = len(today_daliy_datas)
        # 计算省内数量并统计年龄段
        province = 0
        age_step_list = [0 for i in range(10)]
        for i in daliy_datas:
            province += int(i.idno[:2] == '51')
            age_step_list[int(i.idno[8])] += 1
        # 叫号,接件,转号,等待
        total_call, total_deal, total_move, total_wait_seconds = 0, 0, 0, 0
        for i in today_daliy_datas:
            if i.current_user:
                total_call += 1
            if i.current_process != "接件":
                total_deal += 1
            if i.move_times:
                total_move += i.move_times
            if i.wait_seconds:
                total_wait_seconds += i.wait_seconds
        # 年龄分段情况
        age_step_dict_list = list()
        for index, i in enumerate(age_step_list):
            if i:
                age_step_dict_list.append({
                    "value": i,
                    "name": str(index) + "0后"
                })
            elif len(age_step_dict_list
                     ) == 0 and index == len(age_step_list) - 1:
                age_step_dict_list.append({
                    "value": i,
                    "name": str(index) + "0后"
                })
        # 当前等待总人数
        total_wait = 0
        for sub in subjects:
            total_wait += redis_store.llen(addr + sub.name)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SERVERERR, errmsg="内部错误")
    # 当天情况,时间段,男女,省内外,年龄段,主题五,事项五,主题,周数据
    today_data_dict = dict()
    today_province_data_list = list()
    theme_dict_list = list()
    area_dict_list = list()
    today_data_dict.__setitem__("Total", history_total)
    today_data_dict.__setitem__("pickNum", total_number)
    today_data_dict.__setitem__("waitNum", total_wait)
    today_data_dict.__setitem__("didBNum", total_deal)
    today_data_dict.__setitem__("moveNum", total_move)
    today_data_dict.__setitem__(
        "waitTime",
        str(int(total_wait_seconds / total_call / 60) if total_call else 0) +
        "min")
    today_province_data_list.append({"value": province, "name": "省内"})
    today_province_data_list.append({
        "value": history_total - province,
        "name": "省外"
    })
    # 主题值,服务区值
    area_list = list()
    sub_name_list = list()
    area_and_sub_list = list()
    area_dict = dict()
    sub_name_dict = dict()
    for i in subjects:
        sub_name_list.append(i.name)
        sub_name_dict[i.name] = 0
        if i.area not in area_list:
            area_list.append(i.area)
            area_dict[i.area] = 0
    for i in today_daliy_datas:
        for j in subjects:
            if i.subject == j.name:
                sub_name_dict[j.name] += 1
                area_dict[j.area] += 1
                break
    for index, i in enumerate(area_list):
        if area_dict[i]:
            area_dict_list.append({"value": area_dict[i], "name": i})
            area_and_sub_list.append(i)
        elif len(area_dict_list) == 0 and index == len(area_list) - 1:
            area_dict_list.append({"value": area_dict[i], "name": i})
            area_and_sub_list.append(i)
    for index, i in enumerate(sub_name_list):
        if sub_name_dict[i]:
            theme_dict_list.append({"value": sub_name_dict[i], "name": i})
            area_and_sub_list.append(i)
        elif len(theme_dict_list) == 0 and index == len(sub_name_list) - 1:
            theme_dict_list.append({"value": sub_name_dict[i], "name": i})
            area_and_sub_list.append(i)
    theme_dict = dict()
    theme_dict.__setitem__("rAxis", area_and_sub_list)
    theme_dict.__setitem__("data1", area_dict_list)
    theme_dict.__setitem__("data2", theme_dict_list)
    item_click_list = list()
    for i in items:
        ret = Business.query.filter(
            and_(
                Business.create_time.between(current_day,
                                             current_day + timedelta(1)),
                Business.item == i.name,
                Business.current_process != "接件")).all()
        item_click_list.append((len(ret), i.name))
    item_click_list.sort(reverse=True)
    item_click_dict_list = list()
    item_click_total = 0
    for k, v in item_click_list:
        item_click_dict_list.append({"matter": v, "peoperNum": k})
        item_click_total += k
    for i in item_click_dict_list:
        i.__setitem__(
            "per", "%.2f%%" % (i["peoperNum"] / item_click_total *
                               100 if item_click_total else 0))
    matterTop5_dict = dict()
    matterTop5_dict.__setitem__("data", item_click_dict_list[:15])
    # 返回结果
    return jsonify(errno=RET.OK,
                   errmsg="成功",
                   data={
                       "realData": today_data_dict,
                       "pieSeriesData2": today_province_data_list,
                       "pieSeriesData": age_step_dict_list,
                       "matterTop5": matterTop5_dict,
                       "theme": theme_dict,
                       "perWeek": {
                           "legend": ['上周人流量', '本周人流量', '平均值'],
                           "xAxis":
                           ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
                           "yAxis1": {
                               "name": '上周人流量',
                               "data": last_week_data_list
                           },
                           "yAxis2": {
                               "name": '本周人流量',
                               "data": this_week_data_list
                           },
                           "yAxis3": {
                               "name": '平均值',
                               "data": week_avg_data_list
                           }
                       },
                       "timeSlot": {
                           "legend": ['上周时间段人流量', '当天时间段人流量', '平均值'],
                           "xAxis": [
                               '9:00-10:00', '10:00-11:00', '11:00-12:00',
                               '12:00-13:00', '13:00-14:00', '14;00-15:00',
                               '15:00-16:00', '16:00-17:00', '17:00-18:00'
                           ],
                           "yAxis1": {
                               "name": '上周时间段人流量',
                               "data": last_week_time_step_list
                           },
                           "yAxis2": {
                               "name": '当天时间段人流量',
                               "data": time_step_list
                           },
                           "yAxis3": {
                               "name": '平均值',
                               "data": avg_time_step_data
                           },
                       },
                       "preTheme": {
                           "legend": ['上周主题', '本周主题'],
                           "xAxis": subjects_name_list_for_search,
                           "yAxis1": {
                               "name": '上周主题',
                               "data": last_week_subject_click
                           },
                           "yAxis2": {
                               "name": '本周主题',
                               "data": this_week_subject_click
                           },
                       },
                   })
Exemplo n.º 5
0
def deal_end():
    req_dict = request.get_json()
    lingpai = req_dict.get('lingpai', '')  # 大厅人员必须
    reviews = req_dict.get("reviews", '')  # 大厅人员非必须
    p_name = req_dict.get("p_name", '')  # 大厅人员必须
    p_project = req_dict.get("p_project", '')  # 大厅人员必须
    water_num = req_dict.get("water_num", '')
    subject = req_dict.get("subject", '')
    item = req_dict.get("item", '')
    deal_status = req_dict.get("deal_status", '')
    current_process = req_dict.get("current_process", '')
    description = req_dict.get("description", '')
    user_id = req_dict.get("user_id", '')
    addr = req_dict.get('work_addr', "")  # 地址
    print("++++处理++++", req_dict)
    # 校验数据
    param_keys = [
        "water_num", "deal_status", "current_process", "user_id", "work_addr",
        'subject', 'item'
    ]
    if current_process == "接件":
        param_keys.extend(["lingpai"])
    param_dict = dict()
    for i in param_keys:
        param_dict.__setitem__(i, req_dict.get(i, ''))
    for key, value in param_dict.items():
        if not value:
            return jsonify(errno=RET.PARAMERR, errmsg="数据不完整,缺少%s" % key)
    ## 修改用户当前状态
    #lingpai_obj = LingPai.query.filter_by(user_id=user_id).first()
    #if not lingpai_obj:
    #    return jsonify(errno=RET.DBERR,errmsg="未登录")
    #lingpai_obj.status="空闲"
    #db.session.add(lingpai_obj)
    #db.session.commit()
    # 修改当前叫号情况
    current_call_obj = CurrentCall.query.filter_by(water_num=water_num).first()
    if current_call_obj:
        current_call_obj.status = 1
        db.session.add(current_call_obj)
        db.session.commit()
    # 修改当前时间主题和事项,当前流程时限和已用时间
    business = Business.query.filter_by(water_num=water_num).first()
    if business:
        business.subject = subject
        business.item = item
        db.session.add(business)
        db.session.commit()
    else:
        return jsonify(errno=RET.DBERR, errmsg="没有此事件")
    # 检验要素是否属于当前事项
    item_obj = Item.query.filter_by(name=business.item).first()
    if reviews:
        review_id_list = list()
        for i in item_obj.steps.all():
            review_id_list.extend([j.id for j in i.reviews.all()])
        if reviews.split("-")[0] not in review_id_list:
            return jsonify(errno=RET.DATAERR, errmsg="要素与事项不符")
    try:
        current_subject = business.subject
        start_time = business.modify_time
        current_process = business.current_process
        next_process = None
        current_item = business.item
        people = People.query.filter_by(idno=business.idno).first()
        if deal_status == "N":
            business.current_user = user_id
            business.status = "不合格"
            business.in_deal = 0
            business.current_process = "发证"
            if current_process == "接件":
                business.current_process = "接件"  # 如果当前流程为接件则不流到发证处
                business.in_deal = 2
                business.p_name = p_name
                business.p_project = p_project
                business.reviews = reviews if reviews else ""
            if current_process == "发证":  # 如果发证处不合格则直接作废
                business.in_deal = 2
        elif deal_status == "Y":
            business.current_user = user_id
            business.status = "完成"
            business.in_deal = 0
            if current_process == "接件":
                next_process = business.process.split("-")[
                    business.process.split("-").index(current_process) + 1]
                business.current_process = next_process
                business.p_name = p_name
                business.p_project = p_project
                business.reviews = reviews if reviews else ""
            elif current_process == "科室负责人" and business.is_scene == 1:
                next_process = business.process.split("-")[
                    business.process.split("-").index(current_process) + 2]
                business.current_process = next_process
            elif current_process == "踏勘中心":
                next_process = business.process.split("-")[
                    business.process.split("-").index(current_process) - 1]
                business.current_process = next_process
                business.is_scene = 1
            elif current_process != "发证":
                next_process = business.process.split("-")[
                    business.process.split("-").index(current_process) + 1]
                business.current_process = next_process
            elif current_process == "发证":
                next_process = '发证'
                business.in_deal = 3
            item_obj = Item.query.filter_by(name=business.item).first()
            business.current_process_timeout = item_obj.steps.filter_by(
                name=next_process).first().timeout
            business.current_process_start_time = datetime.now()
        # 修改办理已花费时间,添加事件状态记录
        used_time_obj = datetime.now() - start_time
        if current_process == "踏勘中心":
            business.takan_used_time += used_time_obj.seconds / 3600 + used_time_obj.days * 24
        # 查询数据库,如果存在则修改,否则创建
        business_status = BusinessStatus.query.filter_by(
            water_num=water_num, current_process=current_process).first()
        if business_status:
            business_status.addr = addr
            business_status.user_id = user_id
            business_status.subject = current_subject
            business_status.item = current_item
            business_status.starts = start_time
            business_status.ends = datetime.now()
            business_status.result = deal_status
            business_status.description = description
        else:
            business_status = BusinessStatus(addr=addr,
                                             water_num=water_num,
                                             current_process=current_process,
                                             user_id=user_id,
                                             subject=current_subject,
                                             item=current_item,
                                             starts=start_time,
                                             ends=datetime.now(),
                                             result=deal_status,
                                             description=description)
        db.session.add_all([business, business_status])
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    # 是否发送短信
    mobile = people.mobile
    if current_process == "发证":
        pass
    elif next_process == "发证":
        try:
            result = current_app.config['MSG_SENDER'].send_with_param(
                86,
                mobile,
                current_app.config['TEMPLATE_LAST'],
                [3, datetime.now().strftime('%H:%M:%S')],
                sign=current_app.config['SMS_SIGN'],
                extend="",
                ext="")  # 签名参数未提供或者为空时,会使用默认签名发送短信
            pass
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="第三方系统错误")
    elif deal_status == "N":
        if current_app.config["MSG"].get(current_process + "未通过") == "Y":
            print(current_process, "------------未通过")
            description_ret = description
            if description:
                description_obj = json.loads(description)
                description_ret = str(description_obj["checks"].append(
                    description_obj["msg"]))
            try:
                result = current_app.config['MSG_SENDER'].send_with_param(
                    86,
                    mobile,
                    current_app.config['TEMPLATE_UNPASS'], [
                        current_process, description_ret,
                        datetime.now().strftime('%H:%M:%S')
                    ],
                    sign=current_app.config['SMS_SIGN'],
                    extend="",
                    ext="")  # 签名参数未提供或者为空时,会使用默认签名发送短信
                pass
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.THIRDERR, errmsg="第三方系统错误")
    elif deal_status == "Y":
        if current_app.config["MSG"].get(current_process + "通过") == "Y":
            print(current_process, "---------------通过")
            try:
                result = current_app.config['MSG_SENDER'].send_with_param(
                    86,
                    mobile,
                    current_app.config['TEMPLATE_PASS'], [
                        current_process, next_process,
                        datetime.now().strftime('%H:%M:%S')
                    ],
                    sign=current_app.config['SMS_SIGN'],
                    extend="",
                    ext="")  # 签名参数未提供或者为空时,会使用默认签名发送短信
                pass
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.THIRDERR, errmsg="第三方系统错误")
    if current_process == "接件":
        try:
            # 修改用户头顶屏幕显示
            redis_store.rpush(
                'usershead',
                json.dumps({
                    "lingpai": lingpai,
                    "length": redis_store.llen(addr + business.subject),
                    "show": "false"
                }))
            # 修改用户对面屏幕显示
            redis_store.rpush(
                'itemreviews', json.dumps({
                    "lingpai": lingpai,
                    "show": "false"
                }))
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.SERVERERR, errmsg="内部错误")
    return jsonify(errno=RET.OK, errmsg="成功")
Exemplo n.º 6
0
def get_number():
    """排号 涉及办事人员表添加取号记录,办事表查询和添加记录,队列"""
    # 获取数据
    req_dict = request.get_json()
    subject = req_dict.get('subject', "")  # 主题
    item = req_dict.get('item', "")  # 事项
    mobile = req_dict.get('mobile', "")  # 电话
    idno = req_dict.get('idno', "")  # 身份证
    addr = req_dict.get('work_addr', "")  # 地址
    print("++++取号++++", req_dict)
    # 校验数据
    param_keys = ["subject", "item", "mobile", "idno", "work_addr"]
    param_dict = dict()
    for i in param_keys:
        param_dict.__setitem__(i, req_dict.get(i, ''))
    for key, value in param_dict.items():
        if not value:
            return jsonify(errno=RET.PARAMERR, errmsg="数据不完整,缺少%s" % key)
    # 判断手机号格式
    if not re.match(r"1[34578]\d{9}", mobile):
        # 表示格式不对
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误")
    # 判断身份证号
    if not re.match(r"[1-9]\d{16}[0-9a-zA-Z]", idno):
        return jsonify(errno=RET.PARAMERR, errmsg="身份证格式错误")
    # 记录对应主题取号总量
    redis_store.incr(addr + subject + "total_number")
    totle = int(
        redis_store.get(addr + subject + "total_number").decode("utf-8"))
    print("取号总量-----------", totle)
    # 查询办事表检查当事人是否来过
    try:
        current_people = People.query.filter_by(idno=idno).first()
        current_addr = Addr.query.filter_by(name=addr).first()
        current_subject = Subject.query.filter_by(name=subject).first()
        current_item = Item.query.filter_by(name=item).first()
        current_location = Location.query.filter_by(subject=subject).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 生成流水号
    water_num = current_addr.seq + datetime.now().strftime(
        "%Y%m%d%H%M%S") + str(current_item.id).rjust(3, '0')
    # 生成号码
    number = current_subject.seq + str((0 + totle * 1) % 1000).rjust(3, '0')
    # 记录事件
    current_business = Business(water_num=water_num,
                                idno=idno,
                                addr=addr,
                                subject=subject,
                                item=item,
                                process=current_item.process,
                                current_process="接件",
                                in_deal=0,
                                is_scene=0,
                                number=number,
                                timeout=current_item.timeout,
                                takan_used_time=0,
                                wait_seconds=0,
                                move_times=0)
    age = datetime.now().year - int(idno[6:10])
    sex = int(idno[16:17]) % 2
    try:
        db.session.add(current_business)
        if not current_people:
            current_people = People(idno=idno, mobile=mobile)
            db.session.add(current_people)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 添加队列
    try:
        # 发送短信
        length = redis_store.llen(addr + subject)
        location = current_location.location
        try:
            result = current_app.config['MSG_SENDER'].send_with_param(
                86,
                mobile,
                current_app.config['TEMPLATE_NUMBER'], [
                    number, length, location,
                    datetime.now().strftime('%H:%M:%S')
                ],
                sign=current_app.config['SMS_SIGN'],
                extend="",
                ext="")  # 签名参数未提供或者为空时,会使用默认签名发送短信
            pass
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="第三方系统错误")
        # 添加排队队列
        redis_store.rpush(addr + subject, water_num)
        # 添加排队时间队列
        redis_store.rpush(addr + subject + "time",
                          datetime.now().strftime("%H%M%S"))
        # 添加用户头顶屏幕显示人数
        redis_store.rpush(
            'usershead',
            json.dumps({
                "subject": subject,
                "length": length,
                "show": "true"
            }))
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SERVERERR, errmsg="内部错误")
    else:
        # 返回流水号,号码,位置,等待人数
        return jsonify(errno=RET.OK,
                       errmsg="成功",
                       data={
                           "water_num": water_num,
                           "number": number,
                           "location": location,
                           "wait": length
                       })
Exemplo n.º 7
0
def make_call():
    '''叫号'''
    req_dict = request.get_json()
    subject = req_dict.get('subject', '')
    lingpai = req_dict.get("lingpai", '')
    user_id = req_dict.get("user_id", '')
    addr = req_dict.get('work_addr', "")  # 地址
    print("++++叫号++++", req_dict)
    # 校验数据
    param_keys = ["subject", "lingpai", "user_id", "work_addr"]
    param_dict = dict()
    for i in param_keys:
        param_dict.__setitem__(i, req_dict.get(i, ''))
    for key, value in param_dict.items():
        if not value:
            return jsonify(errno=RET.PARAMERR, errmsg="数据不完整,缺少%s" % key)
    # 修改用户当前状态
    lingpai_obj = LingPai.query.filter_by(user_id=user_id).first()
    if not lingpai_obj:
        return jsonify(errno=RET.DBERR, errmsg="未登录")
    lingpai_obj.status = "办理中"
    db.session.add(lingpai_obj)
    db.session.commit()
    window = lingpai_obj.win
    # 获取当前主题等待人数
    current_wait_number = redis_store.llen(addr + subject)
    # 获取当前用户今日办件量
    current_day = datetime(datetime.now().year,
                           datetime.now().month,
                           datetime.now().day, 0, 0)
    current_user_call_number = len(
        Business.query.filter(
            and_(
                Business.create_time.between(current_day,
                                             current_day + timedelta(1)),
                Business.current_user == user_id)).all())
    # 通过比对数据库查看是否有中断事件,如果有则返回中断事件,否则返回队列事件
    # 首先比对数据库查看是否有中断事件
    broken_business = Business.query.filter_by(addr=addr,
                                               subject=subject,
                                               current_user=user_id,
                                               current_process="接件",
                                               in_deal=1).first()
    # 如果有中断事件,则返回中断事件和窗口
    if broken_business:
        # 比对数据库查看是否有上次未完成事件
        before_business = Business.query.filter(
            and_(Business.idno == broken_business.idno,
                 Business.item == broken_business.item,
                 Business.water_num != broken_business.water_num)).order_by(
                     Business.modify_time.desc()).all()
        current_p_comes = 0
        for i in before_business:
            if i.status == "完成":
                break
            current_p_comes += 1
        number = broken_business.number
        current_item = Item.query.filter_by(name=broken_business.item).first()
        people = People.query.filter_by(idno=broken_business.idno).first()
        # 记录当前叫号情况
        current_call_obj = CurrentCall.query.filter_by(
            water_num=broken_business.water_num).first()
        if current_call_obj:
            current_call_obj.win = window
        else:
            current_call_obj = CurrentCall(addr=addr,
                                           water_num=broken_business.water_num,
                                           number=broken_business.number,
                                           win=window,
                                           status=0)
        if current_call_obj:
            db.session.add(current_call_obj)
            db.session.commit()
        # 是否发送短信
        mobile = people.mobile
        try:
            result = current_app.config['MSG_SENDER'].send_with_param(
                86,
                mobile,
                current_app.config['TEMPLATE_CALL'],
                [number, window,
                 datetime.now().strftime('%H:%M:%S')],
                sign=current_app.config['SMS_SIGN'],
                extend="",
                ext="")  # 签名参数未提供或者为空时,会使用默认签名发送短
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="第三方系统错误")
        # 添加语音队列
        redis_store.rpush(addr + "voice",
                          json.dumps({
                              "number": number,
                              "window": window
                          }))
        # 添加用户头顶屏幕队
        redis_store.rpush(
            'usershead',
            json.dumps({
                "number": number,
                "lingpai": lingpai,
                "length": redis_store.llen(addr + subject),
                "show": "true"
            }))
        # 添加用户对面屏幕队列
        step_reviews_list = list()
        for step in current_item.steps.all():
            review_list = [review.to_dict() for review in step.reviews.all()]
            for i in review_list:
                i.__setitem__("father_order", step.order)
                i.__setitem__("process", current_item.process)
            step_reviews_list.extend(review_list)
        print("+" * 100)
        redis_store.rpush(
            "itemreviews",
            json.dumps({
                "lingpai":
                lingpai,
                "itemreviews":
                step_reviews_list,
                "reviewsclick":
                before_business[0].reviews if before_business else "",
                "cometimes":
                len(before_business),
                "show":
                "true",
                "current_click":
                str(step_reviews_list[0]['id']),
                "business":
                add_time_step_to_business(broken_business)
            }))
        print("+" * 100)
        result = add_time_step_to_business(broken_business)
        result.__setitem__(
            "last_reviews",
            before_business[0].reviews if before_business else "")
        result.__setitem__("window", window)
        result.__setitem__("cometimes", current_p_comes)
        return jsonify(errno=RET.OK,
                       errmsg="成功",
                       data={
                           "business": result,
                           "wait": current_wait_number,
                           "called": current_user_call_number
                       })
    # 否则从队列中取第一个消息
    else:
        ret = redis_store.blpop(addr + subject, timeout=2)
        ret1 = redis_store.blpop(addr + subject + "time", timeout=2)
        if ret and ret1:
            water_num = ret[1].decode()
            print("water_num-----", water_num)
            # 查询所需信息
            business = Business.query.filter_by(water_num=water_num).first()
            current_item = Item.query.filter_by(name=business.item).first()
            business.current_user = user_id
            business.current_process_timeout = current_item.steps.filter_by(
                name=business.current_process).first().timeout
            business.wait_seconds = (datetime.now() -
                                     business.create_time).seconds
            business.in_deal = 1
            business.current_process_start_time = datetime.now()
            db.session.add(business)
            db.session.commit()
            # 比对数据库查看是否有上次未完成事件
            before_business = Business.query.filter(
                and_(Business.idno == business.idno,
                     Business.item == business.item,
                     Business.water_num != business.water_num)).order_by(
                         Business.modify_time.desc()).all()
            current_p_comes = 0
            for i in before_business:
                if i.status == "完成":
                    break
                current_p_comes += 1
            number = business.number
            people = People.query.filter_by(idno=business.idno).first()
            # 添加叫号情况
            current_call_obj = CurrentCall.query.filter_by(
                water_num=water_num).first()
            if current_call_obj:
                current_call_obj.win = window
            else:
                current_call_obj = CurrentCall(addr=addr,
                                               water_num=water_num,
                                               number=number,
                                               win=window,
                                               status=0)
            if current_call_obj:
                db.session.add(current_call_obj)
                db.session.commit()
            # 是否发送短信
            mobile = people.mobile
            try:
                result = current_app.config['MSG_SENDER'].send_with_param(
                    86,
                    mobile,
                    current_app.config['TEMPLATE_CALL'], [number, window],
                    sign=current_app.config['SMS_SIGN'],
                    extend="",
                    ext="")  # 签名参数未提供或者为空时,会使用默认签名发送短信
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.THIRDERR, errmsg="第三方系统错误")
            # 添加语音队列
            redis_store.rpush(addr + "voice",
                              json.dumps({
                                  "number": number,
                                  "window": window
                              }))
            # 添加用户头顶屏幕队
            redis_store.rpush(
                'usershead',
                json.dumps({
                    "number": number,
                    "lingpai": lingpai,
                    "length": redis_store.llen(addr + subject),
                    "show": "true"
                }))
            # 添加用户对面屏幕队列
            step_reviews_list = list()
            for step in current_item.steps.all():
                review_list = [
                    review.to_dict() for review in step.reviews.all()
                ]
                for i in review_list:
                    i.__setitem__("father_order", step.order)
                    i.__setitem__("process", current_item.process)
                step_reviews_list.extend(review_list)
            print("-" * 100)
            redis_store.rpush(
                "itemreviews",
                json.dumps({
                    "lingpai":
                    lingpai,
                    "itemreviews":
                    step_reviews_list,
                    "reviewsclick":
                    before_business[0].reviews if before_business else "",
                    "cometimes":
                    len(before_business),
                    "show":
                    "true",
                    "current_click":
                    str(step_reviews_list[0]['id']),
                    "business":
                    add_time_step_to_business(business)
                }))
            print("-" * 100)
            result = add_time_step_to_business(business)
            result.__setitem__(
                "last_reviews",
                before_business[0].reviews if before_business else "")
            result.__setitem__("window", window)
            result.__setitem__("cometimes", current_p_comes)
            return jsonify(errno=RET.OK,
                           errmsg="成功",
                           data={
                               "business": result,
                               "wait": current_wait_number,
                               "called": current_user_call_number
                           })
        return jsonify(errno=RET.DATAERR, errmsg="没人了")
Exemplo n.º 8
0
def move():
    """转移"""
    req_dict = request.get_json()
    lingpai = req_dict.get('lingpai', '')
    subject = req_dict.get('subject', '')  # 主题
    item = req_dict.get('item', '')  # 事项
    water_num = req_dict.get('water_num', '')
    user_id = req_dict.get("user_id", '')
    addr = req_dict.get("work_addr", '')
    print("转移-------", req_dict)
    # 校验数据
    param_keys = [
        "lingpai", "subject", "item", "water_num", "user_id", 'work_addr'
    ]
    param_dict = dict()
    for i in param_keys:
        param_dict.__setitem__(i, req_dict.get(i, ''))
    for key, value in param_dict.items():
        if not value:
            return jsonify(errno=RET.PARAMERR, errmsg="数据不完整,缺少%s" % key)
    # 修改当前叫号情况
    current_call_obj = CurrentCall.query.filter_by(water_num=water_num).first()
    if current_call_obj:
        current_call_obj.status = 1
        db.session.add(current_call_obj)
        db.session.commit()
    # 修改用户当前状态
    lingpai_obj = LingPai.query.filter_by(user_id=user_id).first()
    if not lingpai_obj:
        return jsonify(errno=RET.DBERR, errmsg="未登录")
    lingpai_obj.status = "空闲"
    db.session.add(lingpai_obj)
    db.session.commit()
    # 修改数据
    try:
        business = Business.query.filter_by(water_num=water_num).first()
        old_subject = business.subject
        business.subject = subject
        business.item = item
        business.move_times += 1
        db.session.add(business)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")
    # 根据排队时间将数据放入相应队列
    try:
        time_list = redis_store.lrange(addr + subject + "time", 0, -1)
        if time_list:
            for j in range(len(time_list)):
                if business.create_time.strftime(
                        '%H%M%S').encode() < time_list[j]:
                    redis_store.linsert(addr + subject, 'before',
                                        redis_store.lindex(addr + subject, j),
                                        water_num)
                    redis_store.linsert(
                        addr + subject + "time", 'before',
                        redis_store.lindex(addr + subject + "time", j),
                        business.create_time.strftime('%H%M%S'))
            else:
                print("enter else branch")
                redis_store.rpush(addr + subject, water_num)
                redis_store.rpush(addr + subject + "time",
                                  business.create_time.strftime('%H%M%S'))
        else:
            print("enter no branch")
            redis_store.lpush(addr + subject, water_num)
            redis_store.lpush(addr + subject + "time",
                              business.create_time.strftime('%H%M%S'))
        # 修改用户头顶屏幕显示
        redis_store.rpush(
            'usershead',
            json.dumps({
                "lingpai": lingpai,
                "length": redis_store.llen(addr + old_subject),
                "show": "false"
            }))
        # 修改用户对面屏幕显示
        redis_store.rpush('itemreviews',
                          json.dumps({
                              "lingpai": lingpai,
                              "show": "false"
                          }))
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SERVERERR, errmsg="内部错误")
    return jsonify(errno=RET.OK, errmsg="成功")
Exemplo n.º 9
0
def data_analysis():
    addr = request.cookies.get("addr")
    addr = "新津县"
    if not addr:
        return jsonify(errno=RET.PARAMERR,errmsg="缺少地址")
    # 获取今天三周几
    weekday = datetime.now().strftime("%w")
    date_list = list()
    week_data_list = list()
    if weekday == '1':
        pass
        # 只查询今天的其余的都为0
        # 日期列表
        date_list.append(datetime.now().strftime("%Y-%m-%d"))
    elif weekday == '2':
        pass
        # 查询今天和昨天的,其余的都为0
        date_list.append((datetime.today() + timedelta(-1)).strftime("%Y-%m-%d"))
        date_list.append(datetime.now().strftime("%Y-%m-%d"))
    elif weekday == '3':
        pass
        # 查询今天、昨天、前天,其余的都为0
        date_list.append((datetime.today() + timedelta(-2)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-1)).strftime("%Y-%m-%d"))
        date_list.append(datetime.now().strftime("%Y-%m-%d"))
    elif weekday == '4':
        pass
        date_list.append((datetime.today() + timedelta(-3)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-2)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-1)).strftime("%Y-%m-%d"))
        date_list.append(datetime.now().strftime("%Y-%m-%d"))
    elif weekday == '5':
        pass
        date_list.append((datetime.today() + timedelta(-4)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-3)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-2)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-1)).strftime("%Y-%m-%d"))
        date_list.append(datetime.now().strftime("%Y-%m-%d"))
    elif weekday == '6':
        pass
        date_list.append((datetime.today() + timedelta(-5)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-4)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-3)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-2)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-1)).strftime("%Y-%m-%d"))
        date_list.append(datetime.now().strftime("%Y-%m-%d"))
    elif weekday == '0':
        pass
        date_list.append((datetime.today() + timedelta(-6)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-5)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-4)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-3)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-2)).strftime("%Y-%m-%d"))
        date_list.append((datetime.today() + timedelta(-1)).strftime("%Y-%m-%d"))
        date_list.append(datetime.now().strftime("%Y-%m-%d"))
    print("date_list-----------------------",date_list)
    # 从数据库拿出主题和事项
    try:
        subjects = Subject.query.all()
        subjects = sort_subject_by_click(subjects, addr)
        items = Item.query.all()
        items = sort_item_by_click(items, addr)
        for i in date_list:
            obj = DaliyData.query.filter_by(addr=addr,date=i).first()
            if obj:
                week_data_list.append(obj.total_number)
            else:
                week_data_list.append(0)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if not all([subjects,items]):
        return jsonify(errno=RET.NODATA, errmsg="无数据")
    # 从缓存拿出所需数据
    try:
        # 当天取号总量
        total_number = int(get_data_from_redis(redis_store.get(addr+"total_number")).decode())
        # 时间段取号情况
        time_step_list = [int(get_data_from_redis(redis_store.get(addr+"time_step"+str(i).rjust(2,'0')+"0000")).decode()) for i in TIME_STEP_LIST]
        # 男女比列
        sex = int(get_data_from_redis(redis_store.get(addr+"sex_man_and_woman")).decode())
        # 省内外比列
        province = int(get_data_from_redis(redis_store.get(addr+"province_in_and_out")).decode())
        # 年龄分段情况
        age_step_list0 = [{"value":int(get_data_from_redis(redis_store.get(addr+"age_step"+str(i)[2:])).decode()),"name":str(i)[2:]+"后"} for i in AGE_STEP_LIST]
        age_step_list = list()
        for i in range(len(age_step_list0)):
            if age_step_list0[i].get("value") != 0:
                age_step_list.append(age_step_list0[i])
            elif i == len(age_step_list0)-1 and len(age_step_list) == 0:
                age_step_list.append(age_step_list0[i])
        # 叫号总量
        total_call = int(get_data_from_redis(redis_store.get(addr+"total_call")).decode())
        # 等待总时长
        total_wait_minute = int(get_data_from_redis(redis_store.get(addr+"total_wait_minute")).decode())
        # 接待总量
        total_deal = int(get_data_from_redis(redis_store.get(addr+"total_deal")).decode())
        # 接待通过量
        total_pass_deal = int(get_data_from_redis(redis_store.get(addr+"total_pass_deal")).decode())
        # 主题点击量
        subject_click_list = [(int(get_data_from_redis(redis_store.get(addr+subject.name+"click")).decode()),subject.name,subject.area) for subject in subjects]
        #subject_click_list.sort(reverse=True)
        # 事项点击量
        item_click_list = [(int(get_data_from_redis(redis_store.get(addr+item.name+"click")).decode()),item.name) for item in items]
        item_click_list.sort(reverse=True)
        # 转号量
        total_move = int(get_data_from_redis(redis_store.get(addr+"total_move")).decode())
        total_wait = 0
        for sub in subjects:
            total_wait += redis_store.llen(addr + sub.name)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SERVERERR, errmsg="内部错误")
    # 对数据进行分析计算
    #print(subject_click_list)
    # 准备容器
    realData,quaho,pieSeriesData1,pieSeriesData2,pieSeriesData,themeTop5,matterTop5,theme,weekData={},{},[],[],[],{},{},{},{}
    realData.__setitem__("pickNum",total_number)
    realData.__setitem__("waitNum",total_wait)
    realData.__setitem__("curDoNum",total_number-total_wait-total_deal if total_number-total_wait-total_deal>0 else 0)
    realData.__setitem__("didBNum",total_deal)
    realData.__setitem__("moveNum",total_move)
    if total_call == 0 or total_wait_minute <= 0:
        realData.__setitem__("waitTime", 0)
    else:
        realData.__setitem__("waitTime",str(int(total_wait_minute/total_call))+"min")
    if total_deal == 0:
        realData.__setitem__("didPer", "{}%".format(0))
    else:
        realData.__setitem__("didPer","{:.2f}%".format((total_pass_deal/total_deal)*100))
    quaho.__setitem__("time",[str(i)+":00" for i in TIME_STEP_LIST])
    quaho.__setitem__("Num",time_step_list)
    pieSeriesData1.append({"value":sex,"name":"男"})
    pieSeriesData1.append({"value":total_number-sex,"name":"女"})
    pieSeriesData2.append({"value":province,"name":"省内"})
    pieSeriesData2.append({"value":total_number-province,"name":"省外"})
    pieSeriesData = age_step_list
    xAxis,rAxis,data,data1,data2,area_dict=[],[],[],[],[],{}
    # 服务区字典
    for j in subjects:
        area_dict.__setitem__(j.area,0)
    index0 = 0
    for k,v,area in subject_click_list:
        index0 += 1
        temp = {}
        xAxis.append(v)
        data.append(k)
        temp.__setitem__("value",k)
        temp.__setitem__("name",v)
        if k != 0:
            # 统计主题数据
            data2.append(temp)
        elif index0 == len(subject_click_list)-1 and len(data2) == 0:
            data2.append(temp)
        area_dict[area] += k
    zip_data_xAxis,sort_xAxis,sort_data = [],[],[]
    for i in zip(data,xAxis):
        zip_data_xAxis.append(i)
    zip_data_xAxis.sort(reverse=True)
    for i in zip_data_xAxis:
        sort_data.append(i[0])
        sort_xAxis.append(i[1])
    themeTop5.__setitem__("xAxis",sort_xAxis[0:5])
    themeTop5.__setitem__("data",sort_data[0:5])
    for i in area_dict:
        if area_dict[i]>0:
            rAxis.append(i)
            # 统计服务区数据
            data1.append({"value":area_dict[i],"name":i})
    for i in data2:
        rAxis.append(i["name"])
    theme.__setitem__("rAxis",rAxis)
    theme.__setitem__("data1",data1)
    theme.__setitem__("data2",data2)
    data3,top_total=[],0
    for k,v in item_click_list:
        temp1 = {}
        top_total += k
        temp1.__setitem__("matter",v)
        temp1.__setitem__("peoperNum",k)
        data3.append(temp1)
    for i in data3:
        if top_total == 0:
            i.__setitem__("per", "%.2f%%" % (0))
        else:
            i.__setitem__("per","%.2f%%"%(i["peoperNum"]/top_total*100))
    matterTop5.__setitem__("data",data3[:15])
    weekData.__setitem__("xAxis",['星期一', '星期二', '星期三', '星期四', '星期五'])
    for i in range(1,8):
        if i == int(weekday):
            week_data_list[i-1]=total_number
        # elif i > len(week_data_list):
        #     week_data_list.append(0)
    weekData.__setitem__("data",week_data_list[:5])
    # 返回结果
    return jsonify(errno=RET.OK, errmsg="成功", data={"realData":realData,
                                                    "quaho":quaho,
                                                    "pieseriesData1":pieSeriesData1,
                                                    "pieSeriesData2":pieSeriesData2,
                                                    "pieSeriesData":pieSeriesData,
                                                    "themeTop5":themeTop5,
                                                    "matterTop5":matterTop5,
                                                    "theme":theme,
                                                    "weekData":weekData})