def execute(self, house_id: int, pk: int, contact_id: int, attribute: str, value: Any) -> ResultE['Reservation']: ctx = Context( house_id=house_id, pk=pk, contact_id=cf.get_int_or_none(contact_id) or 0, attribute=(attribute or '').strip().lower(), value=value, ) if ctx.contact_id <= 0: return self._error( f"Missed Contact ID for update Guest information in Reservation ID={ctx.pk}", ctx, self._case_errors.error, ) if ctx.attribute == '': return self._error( f"Missed attribute for update Guest information in Reservation ID={ctx.pk}", ctx, self._case_errors.error, ) if ctx.attribute not in ('name', 'email', 'phone'): return self._error( f"Unsupported attribute [{ctx.attribute}] for update Guest information in Reservation ID={ctx.pk}", ctx, self._case_errors.error, ) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.make_reservation_from_data), bind_result(self.save_reservation), bind_result(lambda x: Success(x.reservation)), )
def execute( self, house_id: int, room_id: int, start_date: datetime.date, end_date: datetime.date, reason: RoomCloseReasons, user: '******', notes: str = '', ) -> ResultE[Reservation]: ctx = Context( house_id=house_id, room_id=room_id, start_date=start_date, end_date=end_date, reason=reason, user=user, notes=notes, ) return flow( ctx, self.select_house, bind_result(self.select_room), bind_result(self.check_room_is_free), bind_result(self.make_reservation_from_date), bind_result(self.save_reservation), bind_result(self.accept_reservation), bind_result(self.write_changelog), bind_result(lambda x: Success(x.reservation)), )
def execute( self, pk: str, house_id: int, room_id: int, start_date: datetime.date, end_date: datetime.date, reason: RoomCloseReasons, user: '******', notes: str = '', ) -> ResultE[ReservationUpdateContext]: pk = cf.get_int_or_none((pk or '').split('-')[0]) or 0 ctx = Context( pk=pk, house_id=house_id, room_id=room_id, start_date=start_date, end_date=end_date, reason=reason, user=user, notes=notes, ) return flow( ctx, self.select_house, bind_result(self.select_room), bind_result(self.select_reservation), bind_result(self.check_room_is_free), bind_result(self.make_reservation_from_data), bind_result(self.save_reservation), bind_result(self.accept_reservation), bind_result(self.write_changelog), bind_result(self.make_result), )
def __call__(self, user_id: int) -> IO[Result[float, Exception]]: """Fetches `UserProfile` TypedDict from foreign API.""" return flow( user_id, self._make_request, IO.lift(bind(self._parse_json)), )
def apply_casting( value_to_cast: Optional[AnyType], casting: Casting, ) -> ResultE[AnyType]: """Casting one type of code to another. :param casting: :term:`casting` object :type casting: dict :param value_to_cast: The value to cast to casting['to'] :type value_to_cast: AnyType :return: Success/Failure containers :rtype: AnyType Example >>> apply_casting('123', Casting(**{'to': 'integer'})).unwrap() 123 >>> apply_casting('123.12', Casting(**{'to': 'decimal'})).unwrap() Decimal('123.12') """ if value_to_cast is None: return Failure(ValueError('value_to_cast is empty')) return flow( casting.to, get_casting_function, bind( # type: ignore lambda function: function( # type: ignore value_to_cast, casting.original_format, ), ), )
def execute( self, house_id: int, pk: int, room_id: int, plan_id: int, user: '******', prices: Dict[datetime.date, Dict[str, Any]] = None, ) -> ResultE['Reservation']: ctx = Context(house_id=house_id, pk=pk, room_id=room_id, user=user, plan_id=plan_id, prices=prices) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.select_reservation_room), bind_result(self.is_allow_update_period), bind_result(self.select_rate_plan), bind_result(self.select_cancellation_policy), bind_result(self.select_room_types), bind_result(self.select_rooms), bind_result(self.make_reservation_from_data), bind_result(self.save_reservation), bind_result(self.write_changelog), bind_result(lambda x: Success(x.reservation)), )
def execute( self, pk: str, reservation_id: int, house_id: int, roomtype_id: int = None, room_id: int = None, user: '******' = None, ) -> ResultE[None]: ctx = Context( pk=pk, reservation_id=reservation_id, house_id=house_id, roomtype_id=roomtype_id, room_id=room_id, user=user, ) return flow( ctx, self.select_house, bind_result(self.select_reservation_from_cache), bind_result(self.select_reservation_from_db), bind_result(self.select_room_type), bind_result(self.select_room), bind_result(self.update_reservation), bind_result(self.save), bind_result(self.write_changelog), bind_result(lambda x: Success(None)), )
def _upload(self, library: str, **kwargs) -> Result[str, Exception]: if [kwargs["metadata_query"], kwargs["metadata_source"]].count(None) == 1: if kwargs[ "metadata_source"] is None and self.metadata_source is not None: kwargs["metadata_source"] = self.metadata_source else: raise LibgenUploadException( "Both metadata_source and metadata_query are required to fetch metadata." ) upload_url: Result[str, Exception] = flow( kwargs["file_path"], self._validate_file, bind(partial(self._upload_file, library=library)), bind(check_upload_form_response), map_(lambda *_: self._browser.get_form()), # type: ignore bind( partial( self._fetch_metadata, metadata_query=kwargs["metadata_query"], metadata_source=kwargs["metadata_source"], )), bind(partial( self._update_metadata, metadata=kwargs["metadata"], )), bind(self._validate_metadata), bind(self._submit_and_check_form), lash(self._handle_save_failure), ) return upload_url
def docstring_to_violation(docstring: str) -> Violation: """Clean up and parse the docstring into Violation instance.""" violation = Violation( description=docstring, code='', internal_name='', title='', ) violation = flow( violation, # It appears the .. seealso:: block is invalid and is skipped Replace(find='\.\. seealso::', replace='See Also::'), Pypandoc(), # Convert .. [1] lists to Markdown lists Replace(find=r' +.. \[\d+\]', replace='*'), # Replace ``` sourceCode yaml with just ```yaml for mkdocs compatibility Replace(find=' sourceCode ', replace=''), # ```none is not a valid lang specifier. Replace(find='```none', replace='```'), ExtractCodeAndTitle(), ) return violation
def newnames_with_ext(urls, oldnames_with_ext, newnames: 'list[str]') -> 'list[str]': return flow( urls, len, range, lambda r: map(_prefix_filename, oldnames_with_ext, newnames, r), list, )
def get_prices(self, query: PriceGetterQuery) -> Result[List[PricePoint], Exception]: self.query = query return flow( query, self._generate_query, bind(self._send_query), bind(self._validate_response), bind(self._parse_response) )
def handle_attribute( collection: Union[Dict[str, Any], List[Any]], cfg: dict, ) -> ResultE[MapValue]: """Handle one attribute with mappings, ifs, casting and default value. :param collection: The collection of data to find data in :type collection: Union[Dict[str, Any], List[Any]] :param configuration: :term:`configuration` data to use when mapping :type configuration: Dict[str, Any] :return: Success/Failure containers :rtype: MapValue configuration expected to look like this: .. code-block:: json { "mappings": [], # array of mapping objects "separator": None, "if_statements": [], # array of if statement objects "casting": {} # casting object, for casting types "default": "default value" } flow description: Map all objects in cfg[MAPPINGS] -> Apply separator to values if there are more than 1 Failure -> fix to Success(None) Apply if statements Success -> Cast Value Failure -> apply default value Return Result """ mapped_values = [ mapped.unwrap() for mapped in [ handle_mapping(collection, mapping) for mapping in cfg.get(MAPPINGS, []) ] if is_successful(mapped) ] # partially declare if statement and casting functions ifs = partial(apply_if_statements, if_objects=cfg.get(IF_STATEMENTS, [])) cast = partial(apply_casting, casting=cfg.get(CASTING, {})) return flow( apply_separator(mapped_values, separator=cfg.get(SEPARATOR, '')), fix(lambda _: None), # type: ignore bind(ifs), bind(cast), rescue(lambda _: apply_default(default=cfg.get(DEFAULT)), ), )
def run(self, cluster_spec: ClusterSpec) -> Result[ExecutedJob, InvalidJob]: do_filter_columns = partial(self.df_filter_columns, cluster_spec) do_partition_and_write = partial(self.partition_and_write, cluster_spec) final = flow( df_from(self.input_paths, self.input_format, self.line_terminator), bind(do_filter_columns), bind(do_partition_and_write) ) return final
def execute(self, house_id: int, pk: int, user: '******') -> ResultE[ReservationVerifyContext]: ctx = Context(house_id=house_id, pk=pk, user=user) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.populate_with_plans), bind_result(self.populate_with_room_types), bind_result(self.make_result), )
def handle_mapping( collection: Union[Dict[str, Any], List[Any]], cfg: Dict[str, Any], ) -> ResultE[MapValue]: """Find data in path and apply if statements or default value. .. versionadded:: 0.0.1 :param configuration: :term:`configuration` data to use when mapping :type configuration: Dict[str, Any] :param collection: The collection of data to find data in :type collection: Union[Dict[str, Any], List[Any]] :return: Success/Failure containers :rtype: GoResult configuration expected to look like this: .. code-block:: json { "path": [], "if_statementss": [{}, {}], "default": 'val' } Flow description: find data from path or None -> apply if statements -> return default value if Failure else mapped value """ return flow( collection, partial(fetch_data_by_keys, path=cfg.get(PATH, [])), fix(lambda _: None), # type: ignore bind(partial( apply_regexp, regexp=cfg.get(REGEXP, {}), ), ), fix(lambda _: None), # type: ignore map_(partial( apply_slicing, slicing=cfg.get(SLICING, {}), )), bind( partial( apply_if_statements, if_objects=cfg.get(IF_STATEMENTS, []), )), rescue( # type: ignore lambda _: apply_default(cfg.get(DEFAULT)), ), )
def execute(self, house_id: int, pk: int, user: '******') -> ResultE['Reservation']: ctx = Context(house_id=house_id, pk=pk, user=user) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.cancel_reservation), bind_result(self.write_changelog), bind_result(lambda x: Success(ctx.reservation)), )
def execute(self, house_id: int, pk: int, contact_id: int) -> ResultE[bool]: ctx = Context(house_id=house_id, pk=pk, contact_id=contact_id) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.add_contact), bind_result(self.save), bind_result(lambda x: Success(True)), )
def __call__( self, value_to_cast: MapValue, original_format: Optional[str] = None, ) -> ResultE[int]: """Make this object callable.""" return flow( value_to_cast, self._cast_to_decimal, map_(quantize_decimal), map_(int), )
def execute(self, house_id: int, pk: int, user: '******') -> ResultE[bool]: ctx = Context(house_id=house_id, pk=pk, user=user) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.accept_reservation), bind_result(self.confirm_quotation), bind_result(self.write_changelog), bind_result(lambda x: Success(True)), )
def execute(self, pk: int, base_date: Optional[datetime.date], user: '******' = None) -> ResultE[OccupanciesContext]: ctx = Context(house_id=pk, base_date=base_date, user=user) return flow( ctx, self.select_house, bind_result(self.get_calendar_period), bind_result(self.select_roomtypes), bind_result(self.select_occupancies), bind_result(self.make_result), )
def execute(self, pk: str, house_id: int, user: '******') -> ResultE['Reservation']: pk = cf.get_int_or_none((pk or '').split('-')[0]) or 0 ctx = Context(pk=pk, house_id=house_id, user=user) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.make_reservation_from_data), bind_result(self.save_reservation), bind_result(self.write_changelog), bind_result(lambda x: Success(x.reservation)), )
def execute(self, house_id: int, pk: int, room_id: int, user: '******') -> ResultE[ReservationPricesUpdateContext]: ctx = Context(house_id=house_id, pk=pk, room_id=room_id, user=user) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.select_reservation_room), bind_result(self.select_rate_plans), bind_result(self.select_cancellation_policies), bind_result(self.select_room_types), bind_result(self.select_rooms), bind_result(self.make_result), )
def execute(self, house_id: int, pk: int, user_id: int = None) -> ResultE[bool]: ctx = Context(house_id=house_id, pk=pk, user_id=user_id) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.select_user), bind_result(self.cancel_quotation), bind_result(self.cancel_opportunity), bind_result(lambda x: Success(True)), )
def __call__( self, value_to_cast: MapValue, original_format: str, ) -> ResultE[MapValue]: r""" purpose: Convert string date into ISO format date. :input value_to_cast: the string to be converted to a date :input original_format: a string describing the format the data string is before convertion. :raises ValueError: when not able to convert or value_to_cast does not match original_format. regex_tips ^ = start of string $ = end of string [^[0-9]] = matches anything not [0-9] [^\d] = matches anything not digits \d = matches digits {n} = matches previous match n amount of times () = grouper, groups up stuff for use in replace. """ date_value: str = str(value_to_cast) return flow( date_value, self._value_is_iso, rescue( # type: ignore lambda _: self._cast_with_millennia( date_value, original_format=original_format, ), ), rescue( # type: ignore lambda _: self._cast_with_no_millennia( date_value, original_format=original_format, ), ), bind(self._validate_date), alt( # type: ignore lambda failure: ValueError( self._error_message.format( value=date_value, failure=failure, ), ), ), )
def __call__(self, stream_id: UUID) -> Result[StreamDetails, FailureDetails]: stream = self.__find_stream_by_stream_id(stream_id).bind( self.__verify_if_stream_exist ) partial_projects = partial(stream.bind, self.__find_projects_by_stream) partial_ksql = partial( stream.bind, lambda stream_: self.__get_stream_by_name(stream_.name) ) # TODO: Removes every `type: ignore` after resolution of # https://github.com/dry-python/returns/issues/410 return flow( # type: ignore Result.from_value(StreamDetails.build), # type: ignore stream.apply, bind(self.__call_and_apply(partial_projects)), bind(self.__call_and_apply(partial_ksql)), )
def execute(self, house_id: int, pk: int, user_id: int = None) -> ResultE[bool]: ctx = Context(house_id=house_id, pk=pk, user_id=user_id) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.select_user), bind_result(self.update_opportunity), bind_result(self.check_need_update_quotation), bind_result(self.get_quotation_state), bind_result(self.unlock_quotation), bind_result(self.update_quotation), bind_result(self.lock_back_quotation), bind_result(lambda x: Success(True)), )
def execute(self, house_id: int, pk: int, user: '******', price_ids: List[int] = None) -> ResultE['Reservation']: ctx = Context(house_id=house_id, pk=pk, user=user, price_ids=price_ids or []) return flow( ctx, self.select_house, bind_result(self.select_reservation), bind_result(self.check_reservation), bind_result(self.accept_changes), bind_result(self.write_changelog), bind_result(lambda x: Success(ctx.reservation)), )
def execute(self, house_id: int, request: ReservationRequest, user: '******') -> ResultE[Reservation]: ctx = Context(house_id=house_id, request=request, user=user) if not isinstance(ctx.request, ReservationRequest): return self._error('Missed Reservation data', ctx, self._case_errors.missed_reservation) return flow( ctx, self.select_house, bind_result(self.select_room_type), bind_result(self.select_rate_plan), bind_result(self.select_rate), bind_result(self.select_cancellation_policy), bind_result(self.make_reservation_from_date), bind_result(self.save_reservation), bind_result(self.accept_reservation), bind_result(self.write_changelog), bind_result(lambda x: Success(x.reservation)), )
def handle_data_fetcher( collection: Union[Dict[str, Any], List[Any]], cfg: DataFetcher, ) -> ResultE[AnyType]: """Find a data at path or produce a value. return value can be: - value found at path - value found but sliced - value found applied to regular expression - conditional value depending on if statements - default value if all the above still produces `None` Flow description: find data from path or None -> apply regular expression -> apply slicing -> apply if statements -> return default value if Failure else mapped value """ return flow( collection, partial(fetch_data_by_keys, path=cfg.path), fix(lambda _: None), # type: ignore bind(partial( apply_regex, regex=cfg.regex, ), ), fix(lambda _: None), # type: ignore map_(partial( apply_slicing, slicing=cfg.slicing, )), bind(partial( apply_if_statements, statements=cfg.if_statements, )), rescue( # type: ignore lambda _: apply_default(cfg.default), ), )
def execute(self, house_id: int, pk: int = None, start_date: datetime.date = None, end_date: datetime.date = None) -> ResultE[None]: ctx = Context(house_id=house_id, pk=pk, start_date=start_date, end_date=end_date) return flow( ctx, self.select_house, bind_result(self.select_reservations), bind_result(self.select_bot_user), bind_result(self.select_rate_plans), bind_result(self.select_payed_amounts), bind_result(self.process_reservations), bind_result(self.remove_canceled_reservations), bind_result(self.save_cache), bind_result(lambda x: Success(None)), )