Example #1
0
 def get_representative_request_result(request_id: int,
                                       representative_id: int,
                                       substring: str, page: int,
                                       size: int):
     with create_session() as session:
         try:
             representative = (
                 session.query(ContractorRepresentative).filter(
                     ContractorRepresentative.id ==
                     representative_id).one())
         except NoResultFound:
             raise DALError(HTTPStatus.NOT_FOUND.value)
         request = RequestsDAL._get_request(request_id, session)
         if request not in representative.contractor.requests:
             raise DALError(HTTPStatus.FORBIDDEN.value)
         if request.status != RequestStatus.WAITING_FOR_READINESS:
             raise DALError(HTTPStatus.NOT_FOUND.value)
         workers = map(
             lambda worker_in_request: worker_in_request.worker,
             request.workers_in_request,
         )
         res = [
             RequestsDAL.serialize_worker(worker) for worker in workers
             if substring and substring in f''
             f'{worker.last_name} {worker.first_name} {worker.patronymic}'
             or not substring
         ]
         return get_pagination(res, page, size)
Example #2
0
    def get_worker_from_requests(representative_id: int, request_id: int,
                                 substring: str, page: int, size: int):
        with create_session() as session:
            request = RequestsDAL._get_request(request_id, session)
            try:
                representative = (
                    session.query(ContractorRepresentative).filter(
                        ContractorRepresentative.id ==
                        representative_id).one())

            except NoResultFound:
                raise DALError(HTTPStatus.NOT_FOUND.value)
            if request not in representative.contractor.requests:
                raise DALError(HTTPStatus.FORBIDDEN.value)
            res = []
            for worker_in_request in request.workers_in_request:
                worker = worker_in_request.worker
                if (substring and substring not in
                        f'{worker.last_name} {worker.first_name} {worker.patronymic}'
                    ):
                    continue
                res.append(
                    RequestsDAL.serialize_worker_with_request_info(
                        worker, worker_in_request))
            return get_pagination(res, page, size)
Example #3
0
 def _validate_data(request, worker):
     if request.status != RequestStatus.WAITING_FOR_VERIFICATION:
         raise DALError(HTTPStatus.BAD_REQUEST.value)
     if worker not in request.workers_in_request:
         raise DALError(HTTPStatus.BAD_REQUEST.value)
     if worker.status != WorkerInRequestStatus.WAITING_FOR_VERIFICATION:
         raise DALError(HTTPStatus.BAD_REQUEST.value)
Example #4
0
 def close(request_id: int) -> Awaitable[RequestOut]:
     with create_session() as session:
         request = RequestsDAL._get_request(request_id, session)
         if request.status != RequestStatus.WAITING_FOR_VERIFICATION:
             raise DALError(HTTPStatus.BAD_REQUEST.value)
         if WorkerInRequestStatus.WAITING_FOR_VERIFICATION in map(
                 lambda worker: worker.status, request.workers_in_request):
             raise DALError(HTTPStatus.BAD_REQUEST.value)
         request.status = RequestStatus.CLOSED
         return RequestOut.from_orm(request)  # type: ignore
Example #5
0
def _authenticate_user(username: str, password: str) -> Awaitable[OutUser]:
    message = Message.INCORRECT_USERNAME_OR_PASSWORD.value
    with create_session() as session:
        user: Optional[UserDB] = session.query(UserDB).filter(
            UserDB.username == username
        ).first()
        if user is None:
            raise DALError(HTTPStatus.NOT_FOUND.value, message)
        if _is_password_correct(password, user.password_hash):
            return OutUser.from_orm(user)  # type: ignore
        raise DALError(HTTPStatus.NOT_FOUND.value, message)
Example #6
0
def _get_user_id(token: str) -> int:
    try:
        payload: Dict[str, Any] = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        user_id = payload.get('sub')
        if not user_id or not isinstance(user_id, int):
            raise DALError(
                HTTPStatus.BAD_REQUEST.value, Message.NOT_EXPECTING_PAYLOAD.value
            )
        return user_id
    except PyJWTError:
        raise DALError(
            HTTPStatus.BAD_REQUEST.value, Message.COULD_NOT_VALIDATE_CREDENTIALS.value
        )
 def get_worker(representative_id: int,
                worker_id: int) -> Awaitable[WorkerComplexOut]:
     with create_session() as session:
         try:
             representative: ContractorRepresentative = (
                 session.query(ContractorRepresentative).filter(
                     ContractorRepresentative.id ==
                     representative_id).one())
             worker: Worker = session.query(Worker).filter(
                 Worker.id == worker_id).one()
         except NoResultFound:
             raise DALError(HTTPStatus.NOT_FOUND.value)
         if worker not in representative.contractor.workers:
             raise DALError(HTTPStatus.FORBIDDEN.value)
         return RequestsDAL._serialize_worker(worker)
Example #8
0
 def reset_worker_in_request_status(
         request_id: int, worker_id: int) -> Awaitable[WorkerInRequestOut]:
     with create_session() as session:
         worker = RequestsDAL._get_worker(session, worker_id)
         request = RequestsDAL._get_request(request_id, session)
         if worker not in request.workers_in_request:
             raise DALError(HTTPStatus.BAD_REQUEST.value)
         if (worker.status != WorkerInRequestStatus.ACCEPTED
                 and worker.status != WorkerInRequestStatus.CANCELLED):
             raise DALError(HTTPStatus.BAD_REQUEST.value)
         if worker.status == WorkerInRequestStatus.CANCELLED:
             worker.reason_for_rejection = None
             worker.comment = None
         worker.status = WorkerInRequestStatus.WAITING_FOR_VERIFICATION
         return WorkerInRequestOut.from_orm(worker)
Example #9
0
 def _get_request(request_id, session):
     try:
         request = session.query(Request).filter(
             Request.id == request_id).one()
     except NoResultFound:
         raise DALError(HTTPStatus.NOT_FOUND.value)
     return request
 async def add_worker(contractor_representative: OutUser, last_name: str,
                      first_name: str, patronymic: str, birthday: date,
                      profession: str, **kwargs) -> WorkerWithProfessionOut:
     with create_session() as session:
         try:
             profession = (session.query(Profession).filter(
                 Profession.data == profession).one())
         except NoResultFound:
             raise DALError(
                 HTTPStatus.BAD_REQUEST.value,
                 Message.PROFESSION_DOES_NOT_EXITS.value,
             )
         contractor_representative_from_db = await RepresentativesDAL._get_contractor_representative(
             contractor_representative, session)
         worker = Worker(
             patronymic=patronymic,
             last_name=last_name,
             first_name=first_name,
             birth_date=birthday,
             profession=profession,
             contractor_id=contractor_representative_from_db.contractor_id,
         )
         for key, value in kwargs.items():
             if hasattr(Worker, key) and value:
                 await DocumentsDAL.add_worker_document(
                     session, worker, key, SimpleDocumentIn(file=value))
         session.flush()
         worker_out = WorkerOut.from_orm(worker)
         return WorkerWithProfessionOut(**worker_out.dict(),
                                        profession=worker.profession.data)
Example #11
0
 def get_representative_requests(
     representative_id: int,
     substring: str,
     page: int,
     size: int,
     solved: bool = False,
 ) -> Awaitable[ListWithPagination[RequestForTemplateOut]]:
     with create_session() as session:
         try:
             representative: ContractorRepresentative = session.query(
                 ContractorRepresentative).filter(
                     ContractorRepresentative.id ==
                     representative_id).one()
         except NoResultFound:
             raise DALError(HTTPStatus.NOT_FOUND.value)
         res = []
         for request in representative.contractor.requests:
             if substring and substring not in request.object_of_work.data:
                 continue
             if solved and request.status != RequestStatus.CLOSED:
                 continue
             if (not solved and request.status !=
                     RequestStatus.WAITING_FOR_VERIFICATION):
                 continue
             res.append(RequestsDAL._serialize_request(request))
         return get_pagination(res, page, size)
Example #12
0
 def send_request(representative: OutUser,
                  request_id: int) -> Awaitable[RequestOut]:
     with create_session() as session:
         representative = RequestsDAL._get_contractor_representatives(
             representative, session)
         request = RequestsDAL._get_request(request_id, session)
         if len(request.workers_in_request) == 0:
             raise DALError(HTTPStatus.BAD_REQUEST.value,
                            'Вы не можете создать пустую заявку')
         if (request not in representative.contractor.requests
                 or request.status != RequestStatus.WAITING_FOR_READINESS):
             raise DALError(HTTPStatus.BAD_REQUEST.value)
         request.status = RequestStatus.WAITING_FOR_VERIFICATION
         for worker in request.workers_in_request:
             worker.status = WorkerInRequestStatus.WAITING_FOR_VERIFICATION
         return RequestOut.from_orm(request)  # type: ignore
Example #13
0
def get_user(req: Request) -> Awaitable[OutUser]:
    tokens = get_tokens(req)
    with create_session() as session:
        user = (session.query(User).filter(
            User.access_token == tokens.access_token).first())
        if user:
            return OutUser.from_orm(user)  # type: ignore
        raise DALError(HTTPStatus.UNAUTHORIZED.value)
Example #14
0
 def remove_user_to_register(uuid: str) -> None:
     with create_session() as session:
         user = (session.query(UserToRegister).filter(
             UserToRegister.uuid == uuid).first())
         if not user:
             raise DALError(HTTPStatus.BAD_REQUEST.value,
                            Message.USER_DOES_NOT_EXISTS.value)
         session.delete(user)
Example #15
0
 def get(self, uuid: str) -> Awaitable[TOutModel]:
     with create_session() as session:
         try:
             document = session.query(Document).filter(
                 Document.uuid == uuid).one()
             out_model = get_document_out_model(document.type)
             return out_model.from_orm(document)  # type: ignore
         except NoResultFound:
             raise DALError(HTTPStatus.NOT_FOUND.value)
Example #16
0
 def delete_catalog(catalog_id: int) -> Awaitable[None]:  # type: ignore
     with create_session() as session:
         try:
             catalog = session.query(Catalog).filter(
                 Catalog.id == catalog_id).one()
             session.delete(catalog)
         except NoResultFound:
             raise DALError(HTTPStatus.NOT_FOUND.value,
                            Message.CATALOG_DOES_NOT_EXISTS.value)
Example #17
0
 def delete_worker_from_request(representative: OutUser, request_id: int,
                                worker_id: int) -> None:
     with create_session() as session:
         request = RequestsDAL._get_request(request_id, session)
         representative_from_db = RequestsDAL._get_contractor_representatives(
             representative, session)
         if request not in representative_from_db.contractor.requests:
             raise DALError(HTTPStatus.BAD_REQUEST.value)
         try:
             worker = session.query(Worker).filter(
                 Worker.id == worker_id).one()
             for worker_in_request in request.workers_in_request:
                 if worker_in_request.worker == worker:
                     session.delete(worker_in_request)
                     return
             raise DALError(HTTPStatus.NOT_FOUND.value)
         except NoResultFound:
             raise DALError(HTTPStatus.NOT_FOUND.value)
 async def _get_contractor_representative(contractor_representative,
                                          session):
     contractor_representative_from_db: ContractorRepresentative = session.query(
         ContractorRepresentative).filter(
             ContractorRepresentative.id ==
             contractor_representative.id).first()
     if not contractor_representative_from_db:
         raise DALError(HTTPStatus.BAD_REQUEST.value,
                        'contractor representative not found')
     return contractor_representative_from_db
Example #19
0
    async def add_item(catalog_type: CatalogType, data: str,
                       value: Optional[int], out_model: Type[T]) -> T:
        catalog = get_catalog(catalog_type, out_model)
        if catalog_type.structure_type() == CatalogStructureType.int_value:
            if value is None:
                raise DALError(HTTPStatus.BAD_REQUEST.value)
            return await catalog.add_data(
                CatalogWithIntValueIn(data=data, value=value))

        return await catalog.add_data(SimpleCatalogIn(data=data))
 def add(
     self,
     catalog_type: CatalogType,
     params: CatalogWithIntValueIn,
     out_model: Type[CatalogWithIntValueOut],
 ) -> Awaitable[CatalogWithIntValueOut]:
     if params.value <= 0:
         raise DALError(HTTPStatus.BAD_REQUEST.value,
                        Message.INVALID_CATALOG_VALUE.value)
     self._check_data(params.data)
     return self._add_obj_to_db(catalog_type, out_model, **params.dict())
Example #21
0
async def refresh_tokens(refresh_token: str) -> TokensResponse:
    '''
    Проверяет refresh_token и возвращает новую пару токенов
    '''
    user_id = _get_user_id(refresh_token)
    user = await _get_user_from_db(user_id)
    if not _is_valid_token(refresh_token, user.refresh_token.decode()):
        raise DALError(
            HTTPStatus.BAD_REQUEST.value, Message.INVALID_REFRESH_TOKEN.value
        )
    return await _create_tokens(user)
Example #22
0
    def get_representative_workers_in_request(
        representative_id: int,
        request_id: int,
        substring: str,
        page: int,
        size: int,
        is_result: bool = False,
    ):
        with create_session() as session:
            request = RequestsDAL._get_request(request_id, session)

            try:
                representative: ContractorRepresentative = session.query(
                    ContractorRepresentative).filter(
                        ContractorRepresentative.id ==
                        representative_id).one()
            except NoResultFound:
                raise DALError(HTTPStatus.NOT_FOUND.value)
            if request not in representative.contractor.requests:
                raise DALError(HTTPStatus.FORBIDDEN.value)
            res = []
            was_broken: bool = False
            for worker in representative.contractor.workers:
                if was_broken:
                    was_broken = False
                if (substring and substring not in
                        f'{worker.last_name} {worker.first_name} {worker.patronymic}'
                    ):
                    continue
                for worker_in_request in worker.worker_requests:
                    request_ = worker_in_request.request
                    if (request_.object_of_work_id == request.object_of_work_id
                            and request_.contract_id == request.contract_id
                            and worker_in_request.status !=
                            WorkerInRequestStatus.CANCELLED):
                        was_broken = True
                        break
                if not was_broken:
                    res.append(RequestsDAL.serialize_worker(worker))
        return get_pagination(res, page, size)
Example #23
0
 def add_worker_to_request(representative: OutUser, request_id: int,
                           worker_id: int) -> Awaitable[WorkerInRequestOut]:
     with create_session() as session:
         try:
             representative_from_db = RequestsDAL._get_contractor_representatives(
                 representative, session)
             request = RequestsDAL._get_request(request_id, session)
             contractor = representative_from_db.contractor
             worker = session.query(Worker).filter(
                 Worker.id == worker_id).one()
             if worker not in contractor.workers:
                 raise DALError(HTTPStatus.BAD_REQUEST.value)
             if request not in contractor.requests:
                 raise DALError(HTTPStatus.BAD_REQUEST.value)
             if worker in request.workers_in_request:
                 raise DALError(HTTPStatus.BAD_REQUEST.value)
             for worker_request in worker.worker_requests:
                 request_: Request = worker_request.request
                 if (request_.contract_id == request.contract_id
                         and request_.object_of_work_id
                         == request.object_of_work_id
                         and request_.contractor_id == request.contractor_id
                         and worker_request.status
                         == WorkerInRequestStatus.ACCEPTED):
                     raise DALError(
                         HTTPStatus.BAD_REQUEST.value,
                         'Этот пользователь уже участвует в заявке по '
                         'этому документы и на этом участке',
                     )
             worker_in_request = WorkerInRequest(
                 worker_id=worker_id,
                 request_id=request_id,
                 status=WorkerInRequestStatus.WAITING_FOR_READINESS,
             )
             session.add(worker_in_request)
             session.flush()
             return WorkerInRequestOut.from_orm(
                 worker_in_request)  # type: ignore
         except NoResultFound:
             raise DALError(HTTPStatus.BAD_REQUEST.value)
Example #24
0
 def get(file_id: str) -> Awaitable[FileResponse]:
     with create_session() as session:
         try:
             file: Document = session.query(Document).filter(
                 Document.uuid == file_id).one()
         except NoResultFound:
             raise DALError(HTTPStatus.NOT_FOUND.value)
         if file.type == 'contract':
             file = cast(Contract, file)
             return FileResponse(file.path_to_document,
                                 filename=file.title +
                                 '.pdf')  # type: ignore
         return FileResponse(file.path_to_document)  # type: ignore
Example #25
0
 def get_worker(request_id: int,
                worker_id: int) -> Awaitable[WorkerComplexOut]:
     with create_session() as session:
         RequestsDAL._get_request(request_id,
                                  session)  # checking existence of request
         worker_in_request = RequestsDAL._get_worker(session, worker_id)
         if (worker_in_request.status !=
                 WorkerInRequestStatus.WAITING_FOR_VERIFICATION):
             raise DALError(HTTPStatus.BAD_REQUEST.value)
         worker = worker_in_request.worker
         res = RequestsDAL._serialize_worker(worker)
         res.id = worker_in_request.id
         return res  # type: ignore
 def _add_obj_to_db(self, catalog_type: CatalogType, out_model: Type[TOut],
                    **kwargs) -> TOut:
     db_obj = get_catalog_db_obj(catalog_type)
     with create_session() as session:
         obj = db_obj(**kwargs)
         session.add(obj)
         try:
             session.flush()
             return out_model.from_orm(obj)
         except IntegrityError:
             raise DALError(
                 HTTPStatus.BAD_REQUEST.value,
                 Message.ELEMENT_OF_CATALOG_ALREADY_EXISTS.value,
             )
Example #27
0
 async def add_contract(contractor_id: int, title: str,
                        file: UploadFile) -> DocumentWithTitleOut:
     with create_session() as session:
         try:
             contractor = (session.query(Contractor).filter(
                 Contractor.id == contractor_id).one())
         except NoResultFound:
             raise DALError(HTTPStatus.NOT_FOUND.value)
         return await ContractDocument().add(
             session,
             contractor,
             'contract',
             DocumentWithTitleIn(file=file, title=title),
         )
Example #28
0
    def make(
        self,
        operation_type: OperationType,
        user: User,
        currency: UserCurrency,
        amount: Decimal,
    ) -> None:
        if (operation_type == OperationType.BUY
                and user.money < amount * currency.purchasing_price):
            raise DALError('У вас недостаточно средств')
        if operation_type == OperationType.SELL and amount > currency.amount:
            raise DALError('У вас нет такого кол-ва валюты')

        response: Response = requests.post(
            f'{Urls.USERS.value}/{user.id}/currencies',
            json={
                'currency_id': currency.id,
                'operation': operation_type.value,
                'amount': str(amount),
                'time': datetime.strftime(currency.time, '%Y-%m-%d %H:%M:%S'),
            },
        )
        if response.status_code == HTTPStatus.BAD_REQUEST:
            raise DALError('Данные устарели, обновите и попробуйте еще раз')
Example #29
0
 def _add_user(self, session: Session, username: str, password: str,
               db_obj: Type[User]) -> User:
     password_hash = get_password_hash(password)
     user = db_obj(
         username=username,
         password_hash=password_hash,
     )
     session.add(user)
     try:
         session.flush()
     except IntegrityError as e:
         print(e)
         raise DALError(HTTPStatus.BAD_REQUEST.value,
                        Message.USER_ALREADY_EXISTS.value)
     return user
Example #30
0
async def authorize(
    grant_type: GrantType,
    username: Optional[str],
    password: Optional[str],
    refresh_token: Optional[str],
) -> TokensResponse:
    if grant_type == GrantType.refresh:
        if refresh_token:
            return await refresh_tokens(refresh_token)
    if grant_type == GrantType.password:
        if username and password:
            return await generate_tokens(username, password)
    raise DALError(
        HTTPStatus.UNAUTHORIZED.value, Message.INVALID_PARAMS_FOR_GETTING_TOKEN.value
    )