示例#1
0
    def encode(self, api_input, action):
        """Transform input to laposte compatible xml."""
        if not (action in LAPOSTE_ACTIONS):
            raise InvalidApiInput(
                'action %s not in %s' % (action, ', '.join(LAPOSTE_ACTIONS)))

        api = LaposteApi()
        if not api.validate(api_input):
            _logger.warning('Laposte api call exception:')
            raise InvalidApiInput(
                {'api_call_exception': api.errors(api_input)})
        data = api.normalize(api_input)

        data['service']['labelFormat'] = self.lookup_label_format(
            data['service']['labelFormat'])

        env = Environment(
            loader=PackageLoader('roulier', '/carriers/laposte/templates'),
            extensions=['jinja2.ext.with_', 'jinja2.ext.autoescape'],
            autoescape=True)

        template = env.get_template("laposte_%s.xml" % action)
        return {
            "body": template.render(
                service=data['service'],
                parcel=data['parcel'],
                auth=data['auth'],
                sender_address=data['from_address'],
                receiver_address=data['to_address'],
                customs=data['customs']),
            "headers": data['auth'],
            "output_format": data['service']['labelFormat']
        }
示例#2
0
    def encode(self, api_input, action):
        """Transform input to chronopost compatible xml."""
        api = ChronopostApi()
        if not (action in CHRONOPOST_ACTIONS):
            raise InvalidApiInput("action %s not in %s" %
                                  (action, ", ".join(CHRONOPOST_ACTIONS)))
        data = api.normalize(api_input)

        env = Environment(
            loader=PackageLoader("roulier", "/carriers/chronopost/templates"),
            extensions=["jinja2.ext.with_", "jinja2.ext.autoescape"],
            autoescape=True,
        )

        template = env.get_template("chronopost_%s.xml" % action)
        return {
            "body":
            template.render(
                service=data["service"],
                parcel=data["parcels"][0],
                from_address=data["from_address"],
                # TODO manage customer address different from expeditor
                customer_address=data["from_address"],
                to_address=data["to_address"],
                auth=data["auth"],
            ),
            "output_format":
            data['service']['labelFormat'],
        }
示例#3
0
    def get_api(self, action):
        """Get Api object based on action.

        raise if action is not known"""
        if not (action in GEODIS_ACTIONS):
            raise InvalidApiInput('action %s not in %s' %
                                  (action, ', '.join(GEODIS_INFOS)))

        return GEODIS_INFOS[action]['api']()
示例#4
0
    def generate_label(self, api_input):
        """Transform input to trs zpl."""
        api = TrsApi()
        if not api.validate(api_input):
            raise InvalidApiInput('Input error : %s' % api.errors(api_input))
        data = api.normalize(api_input)

        data['to_address']["dept"] = data['to_address']['zip'][0:2]

        return {'body': data, 'header': None}
示例#5
0
    def encode(self, api_input, action):
        """Transform input to geodis compatible xml."""
        if not (action in GEODIS_ACTIONS):
            raise InvalidApiInput('action %s not in %s' %
                                  (action, ', '.join(GEODIS_ACTIONS)))

        api = GeodisApi()
        if not api.validate(api_input):
            raise InvalidApiInput('Input error : %s' % api.errors(api_input))
        data = api.normalize(api_input)

        data['service']['labelFormat'] = self.lookup_label_format(
            data['service']['labelFormat'])
        data['service']['shippingDate'] = data['service'][
            'shippingDate'].replace('/', '')

        is_test = data['service']['is_test']

        env = Environment(
            loader=PackageLoader('roulier', '/carriers/geodis/templates'),
            extensions=['jinja2.ext.with_', 'jinja2.ext.autoescape'],
            autoescape=True)

        template = env.get_template("geodis_%s.xml" % action)
        return {
            "body":
            template.render(service=data['service'],
                            parcel=data['parcel'],
                            sender_address=data['from_address'],
                            receiver_address=data['to_address']),
            "headers":
            data['auth'],
            "is_test":
            is_test,
            "output_format":
            data['service']['labelFormat']
        }
示例#6
0
    def encode(self, api_input):
        api = GeodisApiEdi()
        if not api.validate(api_input):
            raise InvalidApiInput('Input error : %s' % api.errors(api_input))
        data = api.normalize(api_input)

        return {
            "body":
            self.encode_agency(agency_address=data['agency_address'],
                               from_address=data['from_address'],
                               shipments=data['shipments'],
                               service=data['service']),
            "headers":
            data['service'],
        }
    def encode(self, api_input, action):
        api = GEODIS_INFOS[action]['api']()
        if not api.validate(api_input):
            raise InvalidApiInput('Input error : %s' % api.errors(api_input))
        data = api.normalize(api_input)

        infos = {
            'url':
            "%s/%s" % (
                GEODIS_INFOS[action]['endpoint'],
                GEODIS_INFOS[action]['service'],
            ),
            'service':
            GEODIS_INFOS[action]['service'],
            'action':
            action,
        }

        return {
            'headers': data['auth'],
            'body': data['service'],
            'infos': infos,
        }
示例#8
0
    def encode(self, api_input, action):
        api = GEODIS_INFOS[action]["api"]()
        if not api.validate(api_input):
            raise InvalidApiInput("Input error : %s" % api.errors(api_input))
        data = api.normalize(api_input)

        infos = {
            "url":
            "%s/%s" % (
                GEODIS_INFOS[action]["endpoint"],
                GEODIS_INFOS[action]["service"],
            ),
            "service":
            GEODIS_INFOS[action]["service"],
            "action":
            action,
        }

        return {
            "headers": data["auth"],
            "body": data["service"],
            "infos": infos,
        }
示例#9
0
    def encode(self, api_input, action):
        """Transform input to dummy zpl."""
        if not (action in DUMMY_ACTIONS):
            raise Exception('action %s not in %s' %
                            (action, ', '.join(DUMMY_ACTIONS)))

        api = DummyApi()
        if not api.validate(api_input):
            raise InvalidApiInput('Input error : %s' % api.errors(api_input))
        data = api.normalize(api_input)

        data['to_address']['dept'] = data['to_address']['zip'][0:2]

        env = Environment(loader=PackageLoader('roulier',
                                               '/carriers/dummy/templates'),
                          extensions=['jinja2.ext.with_'])

        template = env.get_template("dummy_%s.zpl" % action)
        return template.render(auth=data['auth'],
                               service=data['service'],
                               parcel=data['parcel'],
                               sender_address=data['from_address'],
                               receiver_address=data['to_address'])
示例#10
0
    def encode(self, api_input, action):
        """Transform input to geodis compatible xml."""
        api = self.get_api(action)
        if not api.validate(api_input):
            raise InvalidApiInput('Input error : %s' % api.errors(api_input))
        env = Environment(
            loader=PackageLoader('roulier', '/carriers/geodis/templates'),
            extensions=['jinja2.ext.with_', 'jinja2.ext.autoescape'],
            autoescape=True)
        template = env.get_template("geodis_%s.xml" % action)

        data = api.normalize(api_input)
        infos = {
            'xmlns':
            GEODIS_INFOS[action]['xmlns'],
            'url': (data['service']['is_test']
                    and GEODIS_INFOS[action]['endpoint_test']
                    or GEODIS_INFOS[action]['endpoint']),
            'action':
            action,
        }

        def request_impression_etiquette():
            infos["output_format"] = api_input['service']['labelFormat'],
            data['service']['labelFormat'] = self.lookup_label_format(
                data['service']['labelFormat'])
            data['service']['shippingDate'] = (
                data['service']['shippingDate'].replace('/', ''))
            data['from_address']['departement'] = (
                data['from_address']['zip'][:2])
            return {
                "body":
                template.render(
                    service=data['service'],
                    parcels=data['parcels'],
                    sender_address=data['from_address'],
                    receiver_address=data['to_address'],
                    xmlns=infos['xmlns'],
                ),
                "headers":
                data['auth'],
                "infos":
                infos,
            }

        def request_find_localite():
            return {
                "body":
                template.render(
                    receiver_address=data['to_address'],
                    xmlns=infos['xmlns'],
                ),
                "headers":
                data['auth'],
                "infos":
                infos,
            }

        if action == 'demandeImpressionEtiquette':
            return request_impression_etiquette()
        elif action == 'findLocalite':
            return request_find_localite()
示例#11
0
    def encode(self, api_input, action):
        """Transform input to geodis compatible xml."""
        api = self.get_api(action)
        if not api.validate(api_input):
            raise InvalidApiInput("Input error : %s" % api.errors(api_input))
        env = Environment(
            loader=PackageLoader("roulier", "/carriers/geodis/templates"),
            extensions=["jinja2.ext.with_", "jinja2.ext.autoescape"],
            autoescape=True,
        )
        template = env.get_template("geodis_%s.xml" % action)

        data = api.normalize(api_input)
        infos = {
            "xmlns":
            GEODIS_INFOS[action]["xmlns"],
            "url": (data["service"]["is_test"]
                    and GEODIS_INFOS[action]["endpoint_test"]
                    or GEODIS_INFOS[action]["endpoint"]),
            "action":
            action,
        }

        def request_impression_etiquette():
            infos["output_format"] = (api_input["service"]["labelFormat"], )
            data["service"]["labelFormat"] = self.lookup_label_format(
                data["service"]["labelFormat"])
            data["service"]["shippingDate"] = data["service"][
                "shippingDate"].strftime("%Y%M%d")
            data["from_address"]["departement"] = data["from_address"][
                "zip"][:2]
            return {
                "body":
                template.render(
                    service=data["service"],
                    parcels=data["parcels"],
                    sender_address=data["from_address"],
                    receiver_address=data["to_address"],
                    xmlns=infos["xmlns"],
                ),
                "headers":
                data["auth"],
                "infos":
                infos,
            }

        def request_find_localite():
            return {
                "body":
                template.render(
                    receiver_address=data["to_address"],
                    xmlns=infos["xmlns"],
                ),
                "headers":
                data["auth"],
                "infos":
                infos,
            }

        if action == "demandeImpressionEtiquette":
            return request_impression_etiquette()
        elif action == "findLocalite":
            return request_find_localite()
示例#12
0
    def encode(self, api_input, action):
        """Transform input to dpd compatible xml."""
        if not (action in DPD_ACTIONS):
            raise InvalidApiInput('action %s not in %s' %
                                  (action, ', '.join(DPD_ACTIONS)))

        api = DpdApi()
        if not api.validate(api_input):
            raise InvalidApiInput('Input error : %s' % api.errors(api_input))
        data = api.normalize(api_input)

        # add some rules which are hard to implement with
        # cerberus.
        # TODO: add additional schemas for that
        if data['service']['product'] == 'DPD_Predict':
            if len(data['service']['dropOffLocation']) > 0:
                raise InvalidApiInput(
                    "dropOffLocation can't be used with predict")
            if data['service']['notifications'] != 'Predict':
                log.info('Notification forced to predict because of product')
                data['service']['notifications'] = 'Predict'

        if data['service']['product'] == 'DPD_Classic':
            if len(data['service']['dropOffLocation']) > 0:
                raise InvalidApiInput(
                    "dropOffLocation can't be used with classic")
            if data['service']['notifications'] == 'Predict':
                raise InvalidApiInput(
                    "Predict notifications can't be used with classic")

        if data['service']['product'] == 'DPD_Relais':
            if len(data['service']['dropOffLocation']) < 1:
                raise InvalidApiInput(
                    "dropOffLocation is mandatory for this product")
            if data['service']['notifications'] == 'Predict':
                raise InvalidApiInput(
                    "Predict notifications can't be used with Relais")

        data['service']['shippingDate'] = (datetime.strptime(
            data['service']['shippingDate'], '%Y/%M/%d').strftime('%d/%M/%Y'))

        def reduce_address(address):
            """Concat some fields.

            Because there is no street2 nor company in DPD api.
            append street2 to street1 and truncate at 70
            append company to name
            """
            address['street1'] = (
                "%s, %s" % (address['street1'], address['street2']))[0:70]
            address['name'] = ("%s, %s" %
                               (address['name'], address['company']))[0:35]

        reduce_address(data['to_address'])
        reduce_address(data['from_address'])

        output_format = data['service']['labelFormat']
        if data['service']['labelFormat'] in ('PNG', 'ZPL'):
            # WS doesn't handle zpl yet, we convert it later
            # png is named Default, WTF DPD?
            data['service']['labelFormat'] = 'Default'

        env = Environment(
            loader=PackageLoader('roulier', '/carriers/dpd/templates'),
            extensions=['jinja2.ext.with_', 'jinja2.ext.autoescape'],
            autoescape=True)

        template = env.get_template("dpd_%s.xml" % action)
        return {
            "body":
            template.render(service=data['service'],
                            parcel=data['parcels'][0],
                            sender_address=data['from_address'],
                            receiver_address=data['to_address']),
            "headers":
            data['auth'],
            "output_format":
            output_format
        }