Skip to content

Commit

Permalink
(consolidate) allied_express integration with live tests
Browse files Browse the repository at this point in the history
  • Loading branch information
danh91 committed Dec 14, 2023
1 parent 9a293f6 commit e6370f8
Show file tree
Hide file tree
Showing 9 changed files with 110 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ def get_rates(self, request: lib.Serializable) -> lib.Deserializable[str]:
data=request.serialize(),
trace=self.trace_as("json"),
method="POST",
headers={"Authorization": f"Basic {self.settings.authorization}"},
headers={
"Authorization": f"Basic {self.settings.authorization}",
"Content-Type": "application/json",
},
)

return lib.Deserializable(response, provider_utils.parse_response)
Expand All @@ -26,7 +29,10 @@ def create_shipment(self, request: lib.Serializable) -> lib.Deserializable[str]:
data=request.serialize(),
trace=self.trace_as("json"),
method="POST",
headers={"Authorization": f"Basic {self.settings.authorization}"},
headers={
"Authorization": f"Basic {self.settings.authorization}",
"Content-Type": "application/json",
},
)

return lib.Deserializable(response, provider_utils.parse_response, request.ctx)
Expand All @@ -37,7 +43,10 @@ def cancel_shipment(self, request: lib.Serializable) -> lib.Deserializable[str]:
url=f"{self.settings.server_url}/cancelJob/{payload['shipmentno']}/{payload['postalcode']}",
trace=self.trace_as("json"),
method="POST",
headers={"Authorization": f"Basic {self.settings.authorization}"},
headers={
"Authorization": f"Basic {self.settings.authorization}",
"Content-Type": "application/json",
},
)

return lib.Deserializable(response, provider_utils.parse_response)
Expand All @@ -50,7 +59,10 @@ def get_tracking(self, request: lib.Serializable) -> lib.Deserializable[str]:
url=f"{self.settings.server_url}/getShipmentsStatus/{payload['shipmentno']}",
trace=self.trace_as("json"),
method="POST",
headers={"Authorization": f"Basic {self.settings.authorization}"},
headers={
"Authorization": f"Basic {self.settings.authorization}",
"Content-Type": "application/json",
},
),
),
request.serialize(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ def parse_error_response(
errors.append(["500", response.error])

if response.is_error and response.data is not None:
errors.append(["400", response.data["result"]["statusError"]])
errors.append(
[
"400",
response.data["result"].get("statusError")
or response.data["result"].get("errors"),
]
)

return [
models.Message(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,11 @@ def rate_request(
request = allied.RateRequestType(
bookedBy=shipper.contact,
account=settings.account,
instructions=options.instructions.state,
instructions=options.instructions.state or "N/A",
itemCount=len(packages),
items=[
allied.ItemType(
dangerous=pkg.options.dangerous_good.state,
dangerous=(True if pkg.options.dangerous_good.state else False),
height=pkg.height.CM,
length=pkg.length.CM,
width=pkg.width.CM,
Expand All @@ -98,7 +98,7 @@ def rate_request(
emailAddress=shipper.email,
geographicAddress=allied.GeographicAddressType(
address1=shipper.address_line1,
address2=shipper.address_line2,
address2=shipper.address_line2 or " ",
country=shipper.country_code,
postCode=shipper.postal_code,
state=shipper.state_code,
Expand All @@ -112,17 +112,15 @@ def rate_request(
emailAddress=recipient.email,
geographicAddress=allied.GeographicAddressType(
address1=recipient.address_line1,
address2=recipient.address_line2,
address2=recipient.address_line2 or " ",
country=recipient.country_code,
postCode=recipient.postal_code,
state=recipient.state_code,
suburb=recipient.city,
),
phoneNumber=recipient.phone_number,
),
referenceNumbers=(
[payload.reference] if any(payload.reference or "") else None
),
referenceNumbers=([payload.reference] if any(payload.reference or "") else []),
serviceLevel=(service.value if service else "R"),
weight=packages.weight.KG,
volume=packages.volume,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ def shipment_request(
request = allied.LabelRequestType(
bookedBy=shipper.contact,
account=settings.account,
instructions=options.instructions.state,
instructions=options.instructions.state or "N/A",
itemCount=len(packages),
items=[
allied.ItemType(
dangerous=pkg.options.dangerous_good.state,
dangerous=(True if pkg.options.dangerous_good.state else False),
height=pkg.height.CM,
length=pkg.length.CM,
width=pkg.width.CM,
Expand All @@ -89,7 +89,7 @@ def shipment_request(
emailAddress=shipper.email,
geographicAddress=allied.GeographicAddressType(
address1=shipper.address_line1,
address2=shipper.address_line2,
address2=shipper.address_line2 or " ",
country=shipper.country_code,
postCode=shipper.postal_code,
state=shipper.state_code,
Expand All @@ -103,17 +103,15 @@ def shipment_request(
emailAddress=recipient.email,
geographicAddress=allied.GeographicAddressType(
address1=recipient.address_line1,
address2=recipient.address_line2,
address2=recipient.address_line2 or " ",
country=recipient.country_code,
postCode=recipient.postal_code,
state=recipient.state_code,
suburb=recipient.city,
),
phoneNumber=recipient.phone_number,
),
referenceNumbers=(
[payload.reference] if any(payload.reference or "") else None
),
referenceNumbers=([payload.reference] if any(payload.reference or "") else []),
weight=packages.weight.KG,
volume=packages.volume,
serviceLevel=service,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ def _extract_details(
description=description,
date=lib.fdate(
result.statusBarcodesList.scannnedTimestamp,
"%Y-%m-%dT%H%M%S.%f%z",
"%Y-%m-%dT%H:%M:%S.%f%z",
),
time=lib.ftime(
result.statusBarcodesList.scannnedTimestamp,
"%Y-%m-%dT%H%M%S.%f%z",
"%Y-%m-%dT%H:%M:%S.%f%z",
),
)
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ class AlliedResponse:
def parse_response(response: str) -> AlliedResponse:
_response = lib.failsafe(
lambda: lib.to_dict(
response.replace(": ", "$$ ")
.replace("@xmlns", "xmlns")
.replace(":", "")
.replace("$$ ", ": ")
(
response.replace("soapenv:", "soapenv")
.replace("@xmlns:", "xmlns")
.replace("ns1:", "ns1")
)
)
)

Expand All @@ -67,7 +68,10 @@ def parse_response(response: str) -> AlliedResponse:
body=_body,
envelope=_envelope,
response=_response,
is_error=("statusError" in (_data or {}).get("result", {})),
is_error=(
("statusError" in (_data or {}).get("result", {}))
or ("errors" in (_data or {}).get("result", {}))
),
)

if "ns1calculatePriceResponse" in _body:
Expand All @@ -77,7 +81,10 @@ def parse_response(response: str) -> AlliedResponse:
body=_body,
envelope=_envelope,
response=_response,
is_error=("statusError" in (_data or {}).get("result", {})),
is_error=(
("statusError" in (_data or {}).get("result", {}))
or ("errors" in (_data or {}).get("result", {}))
),
)

if "ns1cancelDispatchJobResponse" in _body:
Expand All @@ -87,7 +94,11 @@ def parse_response(response: str) -> AlliedResponse:
body=_body,
envelope=_envelope,
response=_response,
is_error=((_data or {}).get("result") != "0"),
is_error=(
((_data or {}).get("result") != "0")
or ("statusError" in (_data or {}).get("result", {}))
or ("errors" in (_data or {}).get("result", {}))
),
)

if "ns1getLabelResponse" in _body:
Expand All @@ -97,7 +108,10 @@ def parse_response(response: str) -> AlliedResponse:
body=_body,
envelope=_envelope,
response=_response,
is_error=("statusError" in (_data or {}).get("result", {})),
is_error=(
("statusError" in (_data or {}).get("result", {}))
or ("errors" in (_data or {}).get("result", {}))
),
)

return AlliedResponse(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ def test_parse_rate_response(self):

self.assertListEqual(lib.to_dict(parsed_response), ParsedRateResponse)

def test_parse_error_response(self):
with patch("karrio.mappers.allied_express.proxy.lib.request") as mock:
mock.return_value = ErrorResponse
parsed_response = (
karrio.Rating.fetch(self.RateRequest).from_(gateway).parse()
)

self.assertListEqual(lib.to_dict(parsed_response), ParsedErrorResponse)


if __name__ == "__main__":
unittest.main()
Expand Down Expand Up @@ -108,6 +117,21 @@ def test_parse_rate_response(self):
[],
]

ParsedErrorResponse = [
[],
[
{
"carrier_id": "allied_express",
"carrier_name": "allied_express",
"code": "400",
"details": {},
"message": "Validation failed: java.lang.Exception: Exception thrown in "
"SuburbDAO.getSuburb :java.lang.Exception: No valid JNDI name "
"found for state UM",
}
],
]


RateRequest = {
"account": "ACCOUNT",
Expand Down Expand Up @@ -153,6 +177,7 @@ def test_parse_rate_response(self):
"emailAddress": "test@gmail.com",
"geographicAddress": {
"address1": "17 VULCAN RD",
"address2": " ",
"country": "AU",
"postCode": "6155",
"state": "WA",
Expand Down Expand Up @@ -215,3 +240,22 @@ def test_parse_rate_response(self):
}
}
"""

ErrorResponse = """{
"soapenv:Envelope": {
"@xmlns:soapenv": "http://schemas.xmlsoap.org/soap/envelope/",
"@xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"soapenv:Body": {
"ns1:calculatePriceResponse": {
"@xmlns:ns1": "http://neptune.alliedexpress.com.au/ttws-ejb",
"result": {
"errors": "Validation failed: java.lang.Exception: Exception thrown in SuburbDAO.getSuburb :java.lang.Exception: No valid JNDI name found for state UM",
"jobCharge": "0.0",
"totalCharge": "0.0"
}
}
}
}
}
"""
2 changes: 1 addition & 1 deletion packages/ui/components/expanded-sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export const ExpandedSidebar: React.FC<ExpandedSidebarComponent> = () => {
</AppLink>

<AppLink href="/developers/logs" className={"menu-item ml-5 " + activeClass("/developers/logs")} shallow={false} prefetch={false}>
<span className="has-text-weight-semibold">Logs</span>
<span className="has-text-weight-semibold">API Logs</span>
</AppLink>

<AppLink href="/developers/docs" className={"menu-item ml-5 " + activeClass("/developers/docs")} shallow={false} prefetch={false}>
Expand Down
8 changes: 8 additions & 0 deletions packages/ui/modals/connect-provider-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,13 @@ export const ConnectProviderModal: React.FC<ConnectProviderModalComponent> = ({
required={field("account_number").required}
/>}

{field("account").exists && <InputField label="Account" value={payload.account}
name="account"
onChange={handleChange}
className="is-small"
required={field("account").required}
/>}

{field("billing_account").exists && <InputField label="Billing Account" value={payload.billing_account}
name="billing_account"
onChange={handleChange}
Expand Down Expand Up @@ -722,6 +729,7 @@ export const ConnectProviderModal: React.FC<ConnectProviderModalComponent> = ({
function fieldState(carrier_name: CarrierNameType, property: string) {
const field = (
({
[CarrierSettingsCarrierNameEnum.AlliedExpress]: [["carrier_id", true], ["username", true], ["password", true], ["account", false]],
[CarrierSettingsCarrierNameEnum.AmazonShipping]: [["carrier_id", true], ["seller_id", true], ["developer_id", true], ["mws_auth_token", true], ["aws_region"]],
[CarrierSettingsCarrierNameEnum.Aramex]: [["carrier_id", true], ["username", true], ["password", true], ["account_pin", true], ["account_entity", true], ["account_number", true], ["account_country_code"]],
[CarrierSettingsCarrierNameEnum.Australiapost]: [["carrier_id", true], ["api_key", true], ["password", true], ["account_number", true]],
Expand Down

0 comments on commit e6370f8

Please sign in to comment.