Skip to content

Commit

Permalink
fix: make shipping labels private + error handling [CU-3f9cyq] (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alchez authored Jun 22, 2021
1 parent 2e966d1 commit 63d2b7c
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 36 deletions.
14 changes: 1 addition & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ The following workflows are available in this application:
- Configure individual stores in each ShipStation account to different companies, warehouses, cost centers and account heads.
- Periodically fetch products, orders and shipments from all ShipStation accounts.
- Identify stores connected to the Amazon marketplace, and add hooks for other Frappe applications to process Amazon orders.

## In-Progress

- Shipping label generation (currently disabled in hooks, but can be enabled and tested manually)
- Shipping label generation (can be enabled per Shipstation account)

## Installation

Expand All @@ -25,15 +22,6 @@ bench get-app https://github.com/ParsimonyGit/shipstation_integration
bench --site <site_name> install-app shipstation_integration
```

For new sites, the custom ShipStation fields will be added after the completion of the setup wizard.

For existing sites, execute the following function to setup the custom fields:

```bash
# execute the following function to setup the custom fields
bench execute --site <site_name> shipstation_integration.setup.setup_shipstation
```

## Dependencies

- [ShipStation Python client](https://github.com/agritheory/shipstation-client) by [AgriTheory](https://github.com/agritheory)
Expand Down
9 changes: 8 additions & 1 deletion shipstation_integration/orders.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import datetime
from typing import TYPE_CHECKING, Union

from httpx import HTTPError

import frappe
from frappe.utils import getdate

Expand Down Expand Up @@ -63,7 +65,12 @@ def list_orders(
if update_parameter_hook:
parameters = frappe.get_attr(update_parameter_hook[0])(parameters)

orders = client.list_orders(parameters=parameters)
try:
orders = client.list_orders(parameters=parameters)
except HTTPError as e:
frappe.log_error(title="Error while fetching Shipstation orders", message=e)
continue

order: "ShipStationOrder"
for order in orders:
if validate_order(sss_doc, order, store):
Expand Down
33 changes: 23 additions & 10 deletions shipstation_integration/public/js/shipping.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ shipping.build_carrier_options = (frm) => {
frappe.call({
method: "shipstation_integration.shipping.get_carrier_services",
args: { settings: r.message },
callback: (r) => {
if (r.message) {
shipping.carrier_options = r.message;
callback: (services) => {
if (services.message) {
shipping.carrier_options = services.message;
}
}
});
Expand All @@ -34,14 +34,27 @@ shipping.add_label_button = (frm) => {

if (frm.doc.docstatus !== 1) return;

frm.add_custom_button(`<i class="fa fa-tags"></i> Shipping Label`, () => {
if (!shipping.carrier_options) {
frappe.throw(__(`No carriers found to process labels. Please ensure the current
document is connected to Shipstation.`))
frappe.call({
method: "shipstation_integration.shipping.get_shipstation_settings",
args: { doc: frm.doc },
callback: (r) => {
if (r.message) {
frappe.db.get_value("Shipstation Settings", { name: r.message }, "enable_label_generation")
.then((settings) => {
if (settings.message.enable_label_generation) {
frm.add_custom_button(`<i class="fa fa-tags"></i> Shipping Label`, () => {
if (!shipping.carrier_options) {
frappe.throw(__(`No carriers found to process labels. Please ensure the current
document is connected to Shipstation.`))
} else {
shipping.dialog(frm);
}
});
}
})
}
}

shipping.dialog(frm);
});
})
}

shipping.dialog = (frm) => {
Expand Down
30 changes: 19 additions & 11 deletions shipstation_integration/shipping.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import base64
import json
from io import BytesIO
from typing import TYPE_CHECKING, Dict, List, Optional
from typing import TYPE_CHECKING, Dict, List, NoReturn, Optional

from httpx import HTTPError
from shipstation.models import ShipStationAddress, ShipStationOrder, ShipStationWeight

import frappe
Expand Down Expand Up @@ -75,7 +76,11 @@ def _create_shipping_label(doc: str, values: str, user: str = str()):

# build the shipstation label payload
if doc.shipstation_order_id:
shipstation_order = client.get_order(doc.shipstation_order_id)
try:
shipstation_order = client.get_order(doc.shipstation_order_id)
except HTTPError as e:
response = e.response.json()
process_error(response)
else:
shipstation_order = make_shipstation_order(doc)

Expand All @@ -91,7 +96,12 @@ def _create_shipping_label(doc: str, values: str, user: str = str()):
)

# generate and save the shipping label for the order
shipment = client.create_label_for_order(shipstation_order, test_label=True)
try:
shipment = client.create_label_for_order(shipstation_order)
except HTTPError as e:
response = e.response.json()
process_error(response)

if isinstance(shipment, dict) and shipment.get("ExceptionMessage"):
process_error(
shipment,
Expand Down Expand Up @@ -119,20 +129,18 @@ def attach_shipping_label(pdf: BytesIO, doctype: str, name: str):
)

file: "File" = save_file(
name + "_shipstation.pdf",
pdf.getvalue(),
doctype,
name,
fname=name + "_shipstation.pdf",
content=pdf.getvalue(),
dt=doctype,
dn=name,
folder="Home/Shipstation Labels",
decode=False,
is_private=0,
df=None
is_private=True
)

return file


def process_error(response: Dict, message: str = str()):
def process_error(response: Dict, message: str = str()) -> NoReturn:
if not message:
message = "There was an error processing the request. Please contact your administrator."
if isinstance(response, dict) and response.get("ExceptionMessage"):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"engine": "InnoDB",
"field_order": [
"enabled",
"enable_label_generation",
"api_key",
"api_secret",
"default_item_group",
Expand Down Expand Up @@ -127,10 +128,17 @@
"fieldname": "since_date",
"fieldtype": "Date",
"label": "Since Date"
},
{
"default": "0",
"depends_on": "eval:doc.enabled",
"fieldname": "enable_label_generation",
"fieldtype": "Check",
"label": "Enable Label Generation"
}
],
"hide_toolbar": 1,
"modified": "2021-04-07 06:20:38.594518",
"modified": "2021-06-04 07:34:34.161535",
"modified_by": "Administrator",
"module": "Shipstation Integration",
"name": "Shipstation Settings",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def onload(self):
self.set_onload('carriers', self._carrier_data())

def validate(self):
self.validate_label_generation()
self.validate_enabled_stores()

def after_insert(self):
Expand All @@ -59,6 +60,10 @@ def client(self):
timeout=30
)

def validate_label_generation(self):
if not self.enabled and self.enable_label_generation:
self.enable_label_generation = False

def validate_enabled_stores(self):
for store in self.shipstation_stores:
if store.enable_shipments and not store.enable_orders:
Expand Down

0 comments on commit 63d2b7c

Please sign in to comment.