Exemplo n.º 1
0
async def get_user(self, enterprise_id=None, user_id=None):
    if user_id:
        rows = [User.by_id(user_id)]
    elif enterprise_id:
        rows = User.by_enterprise_id(enterprise_id)     # 查询该企业下的所有用户
    else:
        rows = User.all()
    return {"status": True, "code": StatusCode.success.value, "msg": "获取成功", "data": to_json(rows)}
Exemplo n.º 2
0
async def add_user(self, **kwargs):
    """员工注册"""
    keys = ['userName', 'userPhone', 'enterpriseId']
    val = validate_error(keys, **kwargs)
    if not val.get('status'):
        return val
    if not self.openid:
        return openid_null()
    try:
        company = Company.by_id(kwargs.get('enterpriseId'))
        if not company:
            return {'status': False, 'msg': '该企业不存在', "code": StatusCode.not_found_error.value}
        user = self.current_user
        query = check_user_exist(user)
        if not query.get('status'):
            return query
        name = kwargs.get('userName').strip()
        phone = kwargs.get('userPhone').strip()
        instance = User.by_name_phone(name, phone)
        if instance:
            if not user or (user and instance.id != int(user.id)):
                return {'status': False, 'msg': '当前姓名和手机号已占用', "code": StatusCode.exist_error.value}
        employee_id = kwargs.get('employeeId')
        if employee_id:
            employee_id = employee_id.strip()
        avatar_pic = kwargs.get('avatarPic')
        if avatar_pic:
            avatar_pic = await save_pic(avatar_pic.strip(), 'avatar', f'avatar_{self.openid}')
            if not avatar_pic:
                return {'status': False, 'msg': '头像保存失败,请重试', "code": StatusCode.file_save_error.value}
        if not query.get('existed'):  # 如果当前用户不存在,则注册用户时需要记录openid
            user = User.add(
                userName=name,
                employeeId=employee_id,
                userPhone=phone,
                avatarPic=avatar_pic,
                openid=self.openid
            )
        else:
            user = user.update(
                userName=name,
                employeeId=employee_id,
                userPhone=phone,
                avatarPic=avatar_pic
            )
        company_user = CompanyUser.by_company_user_id(user.id, company.id)
        if not company_user:
            CompanyUser.add(company_id=company.id, user_id=user.id)
        return {'status': True, 'msg': '注册成功', "code": StatusCode.success.value,
                "data": {"userId": user.id, "avatarPic": user.avatarPic, 'openid': user.openid}}
    except Exception as e:
        logger.error(f"add user In Error: {str(e)}")
        self.db.rollback()
        return {'status': False, 'msg': '注册失败', "code": StatusCode.db_error.value}
Exemplo n.º 3
0
async def get_user(self, userid=None):
    if userid:
        rows = User.by_id(userid)
    else:
        rows = User.all()
    return {
        "status": True,
        "code": StatusCode.success.value,
        "msg": "获取成功",
        "data": to_json(rows)
    }
Exemplo n.º 4
0
async def get_statistics_unchecked(self,
                                   page=1,
                                   page_size=10,
                                   enterprise_id=None):
    """统计未签到数据"""
    user = self.current_user
    if not user:
        return auth_failed()
    if not enterprise_id:
        return param_missing('enterpriseId')
    company_user = CompanyUser.by_company_user_id(user.id, enterprise_id)
    if not company_user or company_user.role_type == RoleTypeEnum.member:  # 该企业的管理员可查看
        return permission_deny()
    unchecked = []
    unchecked_data = User.by_enterprise_id_unchecked_today(
        enterprise_id, page, page_size)  # 根据企业搜索用户
    for item in unchecked_data:
        unchecked.append({
            "userName": item.userName,
            "employeeId": item.employeeId,
            "userPhone": item.userPhone,
            "avatarPic": item.avatarPic,
            "checkedTime": item.checkedTime,
            "checkedAddr": item.checkedAddr,
            "checkedStatus": item.checkedStatus
        })
    return {
        "status": True,
        "code": StatusCode.success.value,
        "msg": "获取成功",
        "data": unchecked
    }
Exemplo n.º 5
0
async def add_company(self, **kwargs):
    """企业注册"""
    keys = ['companyName', 'companyAddr', 'userName', 'userPhone']
    state, msg = validate(keys, kwargs)
    if not state:
        return {
            'status': False,
            'msg': '数据入参验证失败',
            "code": StatusCode.params_error.value
        }
    try:
        user = User(userName=kwargs.get('userName').strip(),
                    userPhone=kwargs.get('userPhone').strip(),
                    is_admin=True,
                    createTime=datetime.now())
        company = Company(companyName=kwargs.get('companyName').strip(),
                          companyAddr=kwargs.get('companyAddr').strip(),
                          createTime=datetime.now())
        company.user = [user]
        self.db.add(user)
        self.db.add(company)
        self.db.commit()
        return {
            'status': True,
            'msg': '注册成功',
            "code": StatusCode.success.value
        }
    except Exception as e:
        logger.error(f"add Company In Error: {str(e)}")
        self.db.rollback()
        return {
            'status': False,
            'msg': '注册失败',
            "code": StatusCode.db_error.value
        }
Exemplo n.º 6
0
async def add_company(self, **kwargs):
    """企业注册"""
    keys = ['companyName', 'companyAddr', 'userName', 'userPhone']
    state, msg = validate(keys, kwargs)
    if not state:
        return {'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value}
    try:
        company = Company.by_name(kwargs.get('companyName'))
        if company:
            return {'status': False, 'msg': '该企业已注册', "code": StatusCode.exist_error.value}
        passed, query = check_user_exist(self)
        if not passed:
            return query
        user = User(
            userName=kwargs.get('userName').strip(),
            userPhone=kwargs.get('userPhone').strip(),
            is_admin=True,
            createTime=datetime.now()
        )
        company = Company(
            companyName=kwargs.get('companyName').strip(),
            companyAddr=kwargs.get('companyAddr').strip(),
            createTime=datetime.now()
        )
        company.user = [user]
        self.db.add(user)
        self.db.add(company)
        self.db.commit()
        return {'status': True, 'msg': '注册成功', "code": StatusCode.success.value,
                "data": {"enterpriseId": company.id}}
    except Exception as e:
        logger.error(f"add Company In Error: {str(e)}")
        self.db.rollback()
        return {'status': False, 'msg': '注册失败', "code": StatusCode.db_error.value}
Exemplo n.º 7
0
async def get_user(self, token, openid):
    user = User.by_openid(openid)
    if user:
        return {'status': True, 'data': user.to_dict()}
    else:
        return await get_user_info(self,
                                   access_token=token,
                                   openid=openid,
                                   auth=True)
Exemplo n.º 8
0
async def delete_user(self, enterprise_id=None, user_id=None):
    user = self.current_user
    if not user:
        return auth_failed()
    if not enterprise_id or not user_id:
        return param_missing('enterpriseId或userId')
    company_user = CompanyUser.by_company_user_id(user.id, enterprise_id)
    if not company_user or company_user.role_type != RoleTypeEnum.admin_rw or user.id == int(user_id):
        return permission_deny()
    deleted_instance = CompanyUser.by_company_user_id(user_id, enterprise_id)
    if not deleted_instance:
        return not_found()
    try:
        deleted_instance.delete()
        User.by_id(user_id).delete()
        return {'status': True, 'msg': '删除用户成功', "code": StatusCode.success.value}
    except Exception as e:
        logger.error(f"delete user In Error: {str(e)}")
        self.db.rollback()
        return {'status': False, 'msg': '删除用户失败', "code": StatusCode.db_error.value}
Exemplo n.º 9
0
async def update_user(self, enterprise_id=None, user_id=None, **kwargs):
    """编辑用户信息"""
    user = self.current_user
    if not user:
        return auth_failed()
    if not enterprise_id:
        return param_missing('enterpriseId')
    userid = user.id
    if user_id:
        userid = user_id
    user = User.by_id(userid)
    if not user:
        return not_found()
    company_user = CompanyUser.by_company_user_id(userid, enterprise_id)
    if not company_user or (not user_id and company_user.role_type != RoleTypeEnum.admin_rw):
        return permission_deny()
    try:
        keys = ['id', 'openid', 'is_admin', 'company', 'createTime', 'updateTime', 'enterpriseId']
        for key in keys:
            if key in kwargs:
                kwargs.pop(key)     # 排除这些key
        name = kwargs.get('userName').strip()
        phone = kwargs.get('userPhone').strip()
        instance = User.by_name_phone(name, phone)
        if instance and instance.id != int(userid):
            return {'status': False, 'msg': '当前姓名和手机号已占用', "code": StatusCode.exist_error.value}
        avatar_pic = kwargs.get('avatarPic')
        if avatar_pic:
            avatar_pic = await save_pic(avatar_pic.strip(), 'avatar', f'avatar_{user.openid}')
            if not avatar_pic:
                return {'status': False, 'msg': '头像保存失败,请重试', "code": StatusCode.file_save_error.value}
            kwargs['avatarPic'] = avatar_pic
        user = user.update(**kwargs)
        return {'status': True, 'msg': '更新用户成功', "code": StatusCode.success.value,
                "data": {"userId": user.id, "avatarPic": user.avatarPic, 'openid': user.openid}}
    except Exception as e:
        logger.error(f"update user In Error: {str(e)}")
        self.db.rollback()
        return {'status': False, 'msg': '更新用户失败', "code": StatusCode.db_error.value}
Exemplo n.º 10
0
async def get_statistics_total(self, enterprise_id=None):
    """统计该企业所有用户个数"""
    user = self.current_user
    if not user:
        return auth_failed()
    if not enterprise_id:
        return param_missing('enterpriseId')
    company_user = CompanyUser.by_company_user_id(user.id, enterprise_id)
    if not company_user:  # 该企业下的所有用户均可查看
        return permission_deny()

    total_count = CompanyUser.count_by_company_id(enterprise_id)

    checked_data = User.by_enterprise_id_checked_today(
        enterprise_id)  # 根据企业搜索用户
    checked_count = len(checked_data)
    isolated_count = User.count_status_checked_today(enterprise_id,
                                                     StatusEnum.isolated)
    suspected_count = User.count_status_checked_today(enterprise_id,
                                                      StatusEnum.suspected)
    confirmed_count = User.count_status_checked_today(enterprise_id,
                                                      StatusEnum.confirmed)

    reuslt = {
        'total_count': total_count,
        'checked_count': checked_count,
        'unchecked_count': total_count - checked_count,
        'isolated_count': isolated_count,
        'suspected_count': suspected_count,
        'confirmed_count': confirmed_count
    }

    return {
        "status": True,
        "code": StatusCode.success.value,
        "msg": "获取成功",
        "data": reuslt
    }
Exemplo n.º 11
0
async def get_statistics_checked(self, enterprise_id=None):
    """统计数据"""
    if enterprise_id:
        users = User.by_enterprise_id(enterprise_id)    # 根据企业搜索用户
    else:
        users = User.all()
    checked_data = []
    for user in users:
        checked_models = CheckInRecordModel.by_user_id_today(user.id)
        if checked_models:
            checked_data.extend(to_json([checked_models]))

    checked_data.sort(key=itemgetter('province'))   # 按省排序
    logger.debug(f'checked_data: {checked_data}')
    result = []
    for province, items in groupby(checked_data, key=itemgetter('province')):   # 按省分割
        isolated_count = 0
        suspected_count = 0
        confirmed_count = 0
        items = list(items)
        items.sort(key=itemgetter('status'))  # 按健康状态分割
        logger.debug(f'items sort by {province}: {items}')
        for status, sub_items in groupby(items, key=itemgetter('status')):
            length = get_length(sub_items)
            if status == StatusEnum.isolated:
                isolated_count = length
            elif status == StatusEnum.suspected:
                suspected_count = length
            elif status == StatusEnum.confirmed:
                confirmed_count = length

        checked_count = get_length(items)  # 打卡数量
        result.append({
            'province': province, 'checked_count': checked_count, 'isolated_count': isolated_count,
            'suspected_count': suspected_count, 'confirmed_count': confirmed_count
        })

    return {"status": True, "code": StatusCode.success.value, "msg": "获取成功", "data": result}
Exemplo n.º 12
0
async def get_user(self, page=1, page_size=10, enterprise_id=None):
    """查询用户"""
    user = self.current_user
    if not user:
        return auth_failed()
    if not enterprise_id:
        rows = user
        rows = [rows] if rows else []
    else:
        company_user = CompanyUser.by_company_user_id(user.id, enterprise_id)
        if not company_user or company_user.role_type == RoleTypeEnum.member:   # 该企业下的管理员可查看
            return permission_deny()
        rows = User.by_enterprise_id(enterprise_id, page=page, page_size=page_size)     # 查询该企业下的所有用户
    return {"status": True, "code": StatusCode.success.value, "msg": "获取成功", "data": to_json(rows)}
Exemplo n.º 13
0
async def add_user(self, **kwargs):
    """员工注册"""
    keys = ['userName', 'userPhone', 'enterpriseId']
    state, msg = validate(keys, kwargs)
    if not state:
        return {'status': False, 'msg': '数据入参验证失败', "code": StatusCode.params_error.value}
    try:
        company = Company.by_id(kwargs.get('enterpriseId'))
        if not company:
            return {'status': False, 'msg': '该企业不存在', "code": StatusCode.not_found_error.value}
        passed, query = check_user_exist(self)
        if not passed:
            return query
        employee_id = kwargs.get('employeeId')
        if employee_id:
            employee_id = employee_id.stirp()
        avatar_pic = kwargs.get('avatarPic')
        if avatar_pic:
            avatar_pic = avatar_pic.strip()
        user = User(
            userName=kwargs.get('userName').strip(),
            employeeId=employee_id,
            userPhone=kwargs.get('userPhone').strip(),
            avatarPic=avatar_pic,
            createTime=datetime.now()
        )
        company.user += [user]
        self.db.add(user)
        self.db.add(company)
        self.db.commit()
        return {'status': True, 'msg': '注册成功', "code": StatusCode.success.value,
                "data": {"userId": user.id}}
    except Exception as e:
        logger.error(f"add user In Error: {str(e)}")
        self.db.rollback()
        return {'status': False, 'msg': '注册失败', "code": StatusCode.db_error.value}
Exemplo n.º 14
0
async def get_statistics_checked(self, enterprise_id=None, by_type='province'):
    """统计签到数据"""
    user = self.current_user
    if not user:
        return auth_failed()
    if not enterprise_id:
        return param_missing('enterpriseId')
    company_user = CompanyUser.by_company_user_id(user.id, enterprise_id)
    if not company_user:  # 该企业下的所有用户均可查看
        return permission_deny()
    checked = []
    raw_checked_data = User.by_enterprise_id_checked_today(
        enterprise_id)  # 根据企业搜索用户
    if not raw_checked_data:
        return {
            "status": True,
            "code": StatusCode.success.value,
            "msg": "获取成功",
            "data": checked
        }
    checked_data = []
    for ch in raw_checked_data:
        row = ch.to_dict()
        addr = row['checkedAddr'].split(',')
        if by_type == 'province':  # 是否根据城市统计
            row['checkedAddr'] = ''.join(s for k, s in enumerate(addr)
                                         if k < 1)
        elif by_type == 'city':  # 是否根据城市统计
            row['checkedAddr'] = ''.join(s for k, s in enumerate(addr)
                                         if k < 2)
        else:
            row['checkedAddr'] = ''.join(s for s in addr)
        checked_data.append(row)

    checked_data.sort(key=itemgetter('checkedAddr'))  # 按省排序
    for checked_address, items in groupby(
            checked_data, key=itemgetter('checkedAddr')):  # 按省分割
        isolated_count = 0
        suspected_count = 0
        confirmed_count = 0
        items = list(items)
        items.sort(key=itemgetter('checkedStatus'))  # 按健康状态分割
        logger.debug(f'items sort by {checked_address}: {items}')
        for status, sub_items in groupby(items,
                                         key=itemgetter('checkedStatus')):
            length = utils.get_length(sub_items)
            if status == StatusEnum.isolated:
                isolated_count = length
            elif status == StatusEnum.suspected:
                suspected_count = length
            elif status == StatusEnum.confirmed:
                confirmed_count = length

        checked_count = utils.get_length(items)  # 打卡数量
        checked.append({
            'checked_address': checked_address,
            'checked_count': checked_count,
            'isolated_count': isolated_count,
            'suspected_count': suspected_count,
            'confirmed_count': confirmed_count
        })

    return {
        "status": True,
        "code": StatusCode.success.value,
        "msg": "获取成功",
        "data": checked
    }
Exemplo n.º 15
0
async def add_company(self, **kwargs):
    """企业注册"""
    keys = ['companyName', 'companyAddr', 'userName', 'userPhone']
    val = validate_error(keys, **kwargs)
    if not val.get('status'):
        return val
    if not self.openid:
        return openid_null()
    try:
        company = Company.by_name(kwargs.get('companyName'))
        if company:
            return {
                'status': False,
                'msg': '该企业已注册',
                "code": StatusCode.exist_error.value
            }
        user = self.current_user
        query = check_user_exist(user)
        if not query.get('status'):
            return query
        user_flag = False
        if not query.get('existed'):  # 如果当前用户不存在,则注册用户时需要记录openid
            name = kwargs.get('userName').strip()
            phone = kwargs.get('userPhone').strip()
            user = User.by_name_phone(name, phone)
            if not user:
                user = User.add(userName=name,
                                userPhone=phone,
                                openid=self.openid,
                                is_admin=True)
                user_flag = True
        company = Company.add(companyName=kwargs.get('companyName').strip(),
                              companyAddr=kwargs.get('companyAddr').strip())
        logo_pic = kwargs.get('logoPic')
        if logo_pic:
            logo_pic = await save_pic(logo_pic.strip(), 'logo',
                                      f'logo_{company.id}')
            if not logo_pic:
                if user_flag:
                    user.delete()
                company.delete()
                return {
                    'status': False,
                    'msg': 'logo保存失败,请重试',
                    "code": StatusCode.file_save_error.value
                }
            company = company.update(logoPic=logo_pic)
        company_user = CompanyUser.by_company_user_id(user.id, company.id)
        if not company_user:
            CompanyUser.add(company_id=company.id,
                            user_id=user.id,
                            role_type=RoleTypeEnum.admin_rw)
        return {
            'status': True,
            'msg': '注册成功',
            "code": StatusCode.success.value,
            "data": {
                "enterpriseId": company.id,
                "logoPic": company.logoPic
            }
        }
    except Exception as e:
        logger.error(f"add Company In Error: {str(e)}")
        self.db.rollback()
        return {
            'status': False,
            'msg': '注册失败',
            "code": StatusCode.db_error.value
        }
Exemplo n.º 16
0
async def get_user(self, openid):
    return User.by_openid(openid)