async def get(request, json={}): user = load_auth(request) if 'userId' in json: selected_user = User.from_id(json['userId']) if not selected_user.parent_id == user.id: raise Exception('Пользователь не является Вашим подчиненным') else: selected_user = user query = { 0: { 'employer_id' if selected_user.get_depth() in [0, 1] else 'employee_id': selected_user.id } if 'userId' in json else {}, 1: { 'employee_id': selected_user.id, 'employer_id': user.id } if 'userId' in json else { 'employer_id': selected_user.id }, 2: { 'employee_id': selected_user.id } }[user.get_depth()] if 'status' in json: query['status'] = json['status'] return [ Task(task_object).get_json() for task_object in db.tasks.find(query).sort("modified", -1).skip( int(json["offset"]) if "offset" in json else 0).limit( int(json["limit"]) if "limit" in json else 100) ]
async def edit(request, json={}): user = load_auth(request) selected_task = Task.from_id(json['id']) if user.get_depth() == 2 and not user.id == selected_task.employee.id: raise Exception('Это задание не предназначено для Вас') if user.get_depth() == 1 and not user.id == selected_task.employer.id: raise Exception('Это задание создали не Вы') updates = {} for key in ['title', 'description', 'difficulty', 'deadline', 'status']: if key in json: value = json[key] if key == 'deadline': try: value = from_isoformat(value) except Exception as e: raise Exception('Указан неверный дедлайн') elif key == 'status': if value not in [ 'created', 'accepted', 'rejected', 'completed' ]: raise Exception('Недопустимый статус') STATUS_VARIANTS = { 'created': 0, 'accepted': 1, 'rejected': 1, 'completed': 2 } if STATUS_VARIANTS[value] <= STATUS_VARIANTS[ selected_task.status]: raise Exception( 'Задача не может быть изменена в обратную сторону') elif key == 'difficulty': if not (0 <= value <= 1): raise Exception('Сложность должна быть от 0 до 1') if user.get_depth() == 2 and user.id == selected_task.employee.id: if key in ['status']: updates[key] = value elif (user.get_depth() == 1 and user.id == selected_task.employer.id) or user.get_depth() == 0: if key in [ 'title', 'description', 'difficulty', 'deadline', 'status' ]: updates[key] = value updates[key] = value updates['modified'] = datetime.now() db.tasks.update_one({'_id': selected_task._id}, {'$set': updates}) return Task.from_id(json['id']).get_json()
async def add_employee(request, json={}): user = load_auth(request) created_user = create_user(json['fullName'], json['login'], json['password'], parent=user) return created_user.get_json()
async def get_childs(request, json={}): user = load_auth(request) childs = user.get_childs() return { 'childs': [child.get_json() for child in childs], 'depth': user.get_depth() }
async def remove_employee(request, json={}): user = load_auth(request) selected_user = User.from_id(json['userId']) depth = user.get_depth() if depth in [1, 2] and not selected_user.parent_id == user.id: raise Exception('Вы не можете удалить этого пользователя') selected_user.drop() return response.empty(status=200)
async def send_message(request, json={}): user = load_auth(request) _send_message(user, json['message'], incoming=True) handle_message(user, json['message']) await asyncio.sleep(0.5) return response.empty(status=200)
async def get_messages(request, json={}): user = load_auth(request) return [{ 'id': message['id'], 'message': message['message'], 'keyboard': message['keyboard'], 'incoming': message['incoming'], 'created': to_isoformat(message['_id'].generation_time), } for message in db.messages.find({ 'user_id': user.id }).sort("id", -1).skip(int(json["offset"]) if "offset" in json else 0). limit(int(json["limit"]) if "limit" in json else 100)]
async def _get(request, json={}): user = load_auth(request) if 'userId' in json: user = User.from_id(json['userId']) users, _users = [], [User(user_obj) for user_obj in db.users.find({})] for i, _user in enumerate(_users): if _user.get_depth() != 2: continue _user.score = _user.calculate_score() users.append(_user) if not users: raise Exception('Недостаточно данных') scoreboard = [x for x in reversed(sorted(users, key=lambda x: x.score))] for i, _user in enumerate(scoreboard): _user.place = i + 1 try: relevant_number = next(i for i, _user in enumerate(scoreboard) if user == _user) # +1 except Exception as e: print('rn', e) relevant_number = None formatted_scoreboard = [] if relevant_number: for _user in scoreboard[(relevant_number - 14) if (relevant_number - 14) >= 0 else None:( relevant_number + 14) if (relevant_number + 14) <= len(scoreboard) else None]: user_obj = _user.get_json() user_obj['score'] = _user.score user_obj['place'] = _user.place formatted_scoreboard.append(user_obj) else: for _user in scoreboard[:100]: user_obj = _user.get_json() user_obj['score'] = _user.score user_obj['place'] = _user.place formatted_scoreboard.append(user_obj) return { 'place': relevant_number + 1 if relevant_number != None else -1, 'scoreboard': formatted_scoreboard }
async def create(request, json={}): user = load_auth(request) selected_user = User.from_id(json['userId']) created_task = create_task( user, selected_user, json['title'], difficulty=json['difficulty'] if 'difficulty' in json else 0.5, description=json['description'] if 'description' in json else None, deadline=from_isoformat(json['deadline']) if 'deadline' in json else None, ) return created_task.get_json()