Ejemplo n.º 1
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
    }
Ejemplo n.º 2
0
async def check_user_admin(self):
    """查询用户是否是企业联系人"""
    user = self.current_user
    if not user:
        return auth_failed()

    return {"status": True, "code": StatusCode.success.value, "msg": "获取成功", "data": {'is_admin': user.is_admin}}
Ejemplo n.º 3
0
async def get_check_in_records(self, page=1, page_size=10):
    """查询个人签到轨迹"""
    user = self.current_user
    if not user:
        return auth_failed()
    rows = CheckInRecordModel.by_user_id(user.id, page, page_size)

    return {
        "status": True,
        "code": StatusCode.success.value,
        "msg": "获取成功",
        "data": to_json(rows)
    }
Ejemplo n.º 4
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)}
Ejemplo n.º 5
0
async def update_company(self, enterprise_id=None, **kwargs):
    """编辑企业信息"""
    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.admin_rw:  # 该企业下的所有用户均可查看
        return permission_deny()
    company = Company.by_id(enterprise_id)
    if not company:
        return not_found()
    try:
        keys = ['id', 'user', 'createTime', 'updateTime']
        for key in keys:
            if key in kwargs:
                kwargs.pop(key)  # 排除这些key
        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:
                return {
                    'status': False,
                    'msg': 'logo保存失败,请重试',
                    "code": StatusCode.file_save_error.value
                }
            kwargs['logoPic'] = logo_pic
        company = company.update(**kwargs)
        return {
            'status': True,
            'msg': '更新企业成功',
            "code": StatusCode.success.value,
            "data": {
                "enterpriseId": company.id,
                "logoPic": company.logoPic
            }
        }
    except Exception as e:
        logger.error(f"update company In Error: {str(e)}")
        self.db.rollback()
        return {
            'status': False,
            'msg': '更新企业失败',
            "code": StatusCode.db_error.value
        }
Ejemplo n.º 6
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}
Ejemplo n.º 7
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}
Ejemplo n.º 8
0
async def get_company(self, enterprise_id):
    """查询企业"""
    user = self.current_user
    if not user:
        return auth_failed()
    if not enterprise_id:
        rows = Company.by_user_id(user.id)
        if not rows:
            return permission_deny()
    else:
        company_user = CompanyUser.by_company_user_id(user.id, enterprise_id)
        if not company_user:  # 该企业下的所有用户均可查看
            return permission_deny()
        rows = Company.by_id(enterprise_id)
        rows = [rows] if rows else []

    return {
        "status": True,
        "code": StatusCode.success.value,
        "msg": "获取成功",
        "data": to_json(rows)
    }
Ejemplo n.º 9
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
    }
Ejemplo n.º 10
0
async def check_in(self, **kwargs):
    """员工签到"""
    keys = ['province', 'city', 'address', 'latitude', 'longitude', 'status']
    val = validate_error(keys, **kwargs)
    if not val.get('status'):
        return val
    user = self.current_user
    if not user:
        return auth_failed()
    try:
        province = kwargs.get('province')
        city = kwargs.get('city')
        district = kwargs.get('district')
        status = kwargs.get('status')
        CheckInRecordModel.add(userId=user.id,
                               province=province,
                               city=city,
                               district=district,
                               address=kwargs.get('address'),
                               latitude=kwargs.get('latitude'),
                               longitude=kwargs.get('longitude'),
                               status=status)
        user.update(checkedTime=datetime.now(),
                    checkedAddr=f'{province},{city},{district}',
                    checkedStatus=status)  # 更新用户表的签到状态
        return {
            'status': True,
            'msg': '签到成功',
            "code": StatusCode.success.value
        }
    except Exception as e:
        logger.error(f"Check In Error: {str(e)}")
        self.db.rollback()
        return {
            'status': False,
            'msg': '签到失败',
            "code": StatusCode.db_error.value
        }
Ejemplo n.º 11
0
async def delete_company(self, enterprise_id):
    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)
    print(
        f'userid: {user.id}, enterpriseId: {enterprise_id}, com: {company_user}'
    )
    if not company_user or company_user.role_type != RoleTypeEnum.admin_rw:  # 该企业下的所有用户均可查看
        return permission_deny()
    deleted_instance = Company.by_id(enterprise_id)
    if not deleted_instance:
        return not_found()
    query = CompanyUser.count_by_company_id(enterprise_id)
    if query > 1:
        return {
            'status': False,
            'msg': '请先解除当前企业下的其他用户',
            "code": StatusCode.db_error.value
        }
    try:
        company_user.delete()
        deleted_instance.delete()
        return {
            'status': True,
            'msg': '删除企业成功',
            "code": StatusCode.success.value
        }
    except Exception as e:
        logger.error(f"delete company In Error: {str(e)}")
        self.db.rollback()
        return {
            'status': False,
            'msg': '删除企业失败',
            "code": StatusCode.db_error.value
        }
Ejemplo n.º 12
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
    }