Ejemplo n.º 1
0
        def action(gateways: List[Gateway]):
            def process(gateway: Gateway):
                is_valid, abortion = check_operation(
                    gateway,
                    'get_rates',
                    origin_country_code=payload.shipper.country_code)
                if not is_valid:
                    return abortion

                request: Serializable = gateway.mapper.create_rate_request(
                    payload)
                response: Deserializable = gateway.proxy.get_rates(request)

                @fail_safe(gateway)
                def deserialize():
                    return gateway.mapper.parse_rate_response(response)

                return IDeserialize(deserialize)

            deserializable_collection: List[IDeserialize] = exec_async(
                lambda g: fail_safe(g)(process)(g), gateways)

            def flatten():
                responses = [p.parse() for p in deserializable_collection]
                flattened_rates = sum(
                    (r for r, _ in responses if r is not None), [])
                messages = sum((m for _, m in responses), [])
                return flattened_rates, messages

            return IDeserialize(flatten)
Ejemplo n.º 2
0
    def get_tracking(self,
                     request: Serializable[List[str]]) -> Deserializable[str]:
        """
        get_tracking make parallel request for each pin
        """
        _throttle = 0.0

        def track(tracking_pin: str) -> str:
            nonlocal _throttle
            time.sleep(_throttle)
            _throttle += 0.025

            return http(
                url=
                f"{self.settings.server_url}/vis/track/pin/{tracking_pin}/detail",
                headers={
                    "Accept": "application/vnd.cpc.track-v2+xml",
                    "Authorization": f"Basic {self.settings.authorization}",
                    "Accept-language": f"{self.settings.language}-CA",
                },
                method="GET",
            )

        response: List[str] = exec_async(track, request.serialize())

        return Deserializable(XP.bundle_xml(xml_strings=response), XP.to_xml)
Ejemplo n.º 3
0
def notify_subscribers(webhooks: typing.List[models.Webhook], payload: dict):
    def notify_subscriber(webhook: models.Webhook):
        response = identity(lambda: requests.post(
            webhook.url,
            json=payload,
            headers={'Content-type': 'application/json'}))

        return webhook.id, response

    return utils.exec_async(notify_subscriber, webhooks)
Ejemplo n.º 4
0
    def get_tracking(self, request: Serializable) -> Deserializable:

        def _get_tracking(tracking_number: str):
            return http(
                url=f"{self.settings.server_url}/v1/tracking/{tracking_number}",
                headers={
                    "Accept": "application/json",
                    "Authorization": f"Basic {self.settings.authorization}"
                },
                method="GET",
            )

        responses: List[dict] = exec_async(_get_tracking, request.serialize())
        return Deserializable(responses, lambda res: [DP.to_dict(r) for r in res if any(r.strip())])
Ejemplo n.º 5
0
    def get_tracking(self, request: Serializable) -> Deserializable[str]:
        def _get_tracking(tracking_request: dict):
            query = urllib.parse.urlencode(tracking_request)
            return http(
                url=f"{self.settings.server_url}/track/shipments?{query}",
                headers={
                    "Accept": "application/json",
                    "DHL-API-Key": self.settings.consumer_key
                },
                method="GET",
            )

        responses: List[dict] = exec_async(_get_tracking, request.serialize())
        return Deserializable(responses,
                              lambda res: [DP.to_dict(r) for r in res])
Ejemplo n.º 6
0
    def get_tracking(self, request: Serializable) -> Deserializable:
        def _get_tracking(mail_piece_id: str):
            return http(
                url=
                f"{self.settings.server_url}/mailpieces/v2/{mail_piece_id}/events",
                headers={
                    "Accept": "application/json",
                    "X-IBM-Client-Id": self.settings.client_id,
                    "X-IBM-Client-Secret": self.settings.client_secret,
                    "X-Accept-RMG-Terms": "yes"
                },
                method="GET",
            )

        responses: List[dict] = exec_async(_get_tracking, request.serialize())
        return Deserializable(
            responses,
            lambda res: [DP.to_dict(r) for r in res if any(r.strip())])
Ejemplo n.º 7
0
    def get_tracking(self, request: Serializable) -> Deserializable[List[Tuple[str, str]]]:

        def _get_tracking(ref: str):
            response = http(
                url=f"{self.settings.server_url}/api/tracking/{ref}",
                headers={
                    "Accept": "application/json",
                    "Authorization": f"Basic {self.settings.authorization}"
                },
                method="GET",
            )
            return ref, response

        responses: List[Tuple[str, str]] = exec_async(_get_tracking, request.serialize())
        return Deserializable(
            responses,
            lambda res: [(num, DP.to_dict(track)) for num, track in res if any(track.strip())]
        )
Ejemplo n.º 8
0
def fetch_rates(
    payload: dict, carrier_settings_list: List[CarrierSettings]
) -> Union[RateResponse, ErrorResponse]:
    request = api.Rating.fetch(ShipmentRate(**payload))

    def process(carrier_settings: CarrierSettings):
        try:
            gateway = api.gateway[carrier_settings.carrier_name].create(
                carrier_settings.settings)
            return request.from_(gateway).parse()
        except Exception as e:
            logger.exception(e)
            return [
                [],
                [
                    Message(
                        code="500",
                        carrier_name=carrier_settings.carrier_name,
                        carrier_id=carrier_settings.settings.get('carrier_id'),
                        message=str(e))
                ]
            ]

    results = exec_async(process, carrier_settings_list)
    rates = sum((r for r, _ in results if r is not None), [])
    messages = sum((m for _, m in results), [])

    if len(rates) == 0:
        return ErrorResponse(messages=messages)

    return RateResponse(shipment=ShipmentRate(
        **{
            **payload, 'rates': [{
                **{
                    **to_dict(r), 'id': str(uuid.uuid4())
                }
            } for r in rates]
        }) if len(rates) > 0 else None,
                        messages=messages)