def test_list_stores(ss: ShipStation, mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_stores"]
    response = ss.list_stores(marketplace_id=2)
    assert request.called
    assert isinstance(response[0], ShipStationStore)
    assert response[0].store_name == "Mexico Amazon Store"
    assert response[1].account_name == "DEF123456789"
def test_get_product(ss: ShipStation, mocked_api: respx.MockTransport) -> None:
    request = mocked_api["get_product"]
    response = ss.get_product(123456789)
    assert request.called
    assert isinstance(response, ShipStationItem)
    assert response.create_date == datetime.datetime(2016, 10, 31, 7, 43, 0,
                                                     203000)
def test_list_services(ss: ShipStation,
                       mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_services"]
    response = ss.list_services(carrier_code="stamps_com")
    assert request.called
    assert isinstance(response[0], ShipStationCarrierService)
    assert response[1].international is False
def test_list_tags(ss: ShipStation, mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_tags"]
    response = ss.list_tags()
    assert request.called
    assert isinstance(response[0], ShipStationOrderTag)
    assert response[0].tag_id == 12345
    assert response[0].name == "Amazon Prime Order"
def test_get_stores(ss: ShipStation, mocked_api: respx.MockTransport) -> None:
    request = mocked_api["get_store"]
    response = ss.get_store(12345)
    assert request.called
    assert isinstance(response, ShipStationStore)
    assert response.store_name == "US Amazon Store"
    assert response.account_name == "GHI123456789"
def test_list_users(ss: ShipStation, mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_users"]
    response = ss.list_users()
    assert request.called
    assert isinstance(response[0], ShipStationUser)
    assert response[0].name == "Merchandising"
    assert isinstance(response[1].user_id, UUID)
    assert response[1].user_id == UUID("0dbc3f54-5cd4-4054-b2b5-92427e18d6cd")
def test_list_marketplaces(ss: ShipStation,
                           mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_marketplaces"]
    response = ss.list_marketplaces()
    assert request.called
    assert isinstance(response[0], ShipStationMarketplace)
    assert response[0].name == "3dcart"
    assert response[1].name == "Acumatica"
def test_list_carriers(ss: ShipStation,
                       mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_carriers"]
    response = ss.list_carriers()
    assert request.called
    assert isinstance(response[0], ShipStationCarrier)
    assert response[0].code == "stamps_com"
    assert response[0].balance == Decimal("15.01")
def test_get_carrier(ss: ShipStation, mocked_api: respx.MockTransport) -> None:
    request = mocked_api["get_carrier"]
    response = ss.get_carrier("stamps_com")
    assert request.called
    assert isinstance(response, ShipStationCarrier)
    assert isinstance(response.primary, bool)
    assert response.name == "Stamps.com"
    assert response.account_number == "example"
def test_get_warehouse(ss: ShipStation,
                       mocked_api: respx.MockTransport) -> None:
    request = mocked_api["get_warehouse"]
    response = ss.get_warehouse(456789)
    assert request.called
    assert isinstance(response, ShipStationWarehouse)
    assert isinstance(response.return_address, ShipStationAddress)
    assert response.warehouse_name == "Test Company"
def test_list_packages(ss: ShipStation,
                       mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_packages"]
    response = ss.list_packages(carrier_code="stamps_com")
    assert request.called
    assert isinstance(response[0], ShipStationCarrierPackage)
    assert isinstance(response[0].domestic, bool)
    assert response[1].domestic is True
    assert response[1].code == "flat_rate_envelope"
def test_list_warehouses(ss: ShipStation,
                         mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_warehouses"]
    response = ss.list_warehouses()
    assert request.called
    assert isinstance(response[0], ShipStationWarehouse)
    assert isinstance(response[0].origin_address, ShipStationAddress)
    assert response[0].origin_address.name == "Warehouse 1"
    assert response[0].warehouse_id == "456789"
    assert response[0].origin_address.street2 == "Unit 4"
def test_get_customer(ss: ShipStation,
                      mocked_api: respx.MockTransport) -> None:
    request = mocked_api["get_customer"]
    response = ss.get_customer(123456789)
    assert request.called
    assert isinstance(response, ShipStationCustomer)
    assert isinstance(response.address_verified, bool)
    assert response.address_verified is True
    assert response.create_date == datetime.datetime(2017, 12, 16, 18, 49, 16,
                                                     7000)
    assert response.marketplace_usernames[0].customer_id == 123456789
def test_list_fulfillments(ss: ShipStation,
                           mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_fulfillments"]
    response = ss.list_fulfillments()
    assert request.called
    assert isinstance(response[0], ShipStationFulfillment)
    assert isinstance(response[0].ship_to, ShipStationAddress)
    assert isinstance(response[0].user_id, UUID)
    assert response[0].create_date == datetime.datetime(
        2020, 6, 19, 7, 21, 51, 773000)
    assert response[1].notify_error_message is not None
def test_get_order(ss: ShipStation, mocked_api: respx.MockTransport) -> None:
    request = mocked_api["get_order"]
    response = ss.get_order(123456789)
    assert request.called
    assert isinstance(response, ShipStationOrder)
    assert isinstance(response.ship_to, ShipStationAddress)
    assert isinstance(response.advanced_options, ShipStationAdvancedOptions)
    assert isinstance(response.international_options,
                      ShipStationInternationalOptions)
    assert isinstance(response.insurance_options, ShipStationInsuranceOptions)
    assert response.create_date == datetime.datetime(2015, 6, 30, 15, 20, 26,
                                                     723000)
def test_get_rates(ss: ShipStation, mocked_api: respx.MockTransport) -> None:
    request = mocked_api["get_rates"]
    response = ss.get_rates(
        ShipStationRateOptions(
            carrier_code="stamps_com",
            from_postal_code="20500",
            to_postal_code="20500",
            to_country="US",
            weight=ShipStationWeight(units="ounces", value=12),
        ))
    assert request.called
    assert isinstance(response[0], ShipStationRate)
    assert response[0].service_code == "usps_first_class_mail"
    assert response[0].shipment_cost == Decimal("3.2")
def test_list_shipments(ss: ShipStation,
                        mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_shipments"]
    response = ss.list_shipments()
    assert request.called
    assert isinstance(response, Page)
    assert isinstance(response[0], ShipStationOrder)
    assert isinstance(response[0].ship_to, ShipStationAddress)
    assert isinstance(response[0].advanced_options, ShipStationAdvancedOptions)
    assert isinstance(response[0].weight, ShipStationWeight)
    assert response[0].create_date == datetime.datetime(
        2015, 6, 29, 14, 29, 28, 583000)
    assert response[0].shipment_cost == Decimal("2.35")
    assert response[0].tracking_number == "9400111899562764298812"
def test_list_orders(ss: ShipStation, mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_orders"]
    response = ss.list_orders()
    assert request.called
    # for order in response:
    print("items", response[0].items)
    assert isinstance(response[0], ShipStationOrder)
    assert isinstance(response[0].ship_to, ShipStationAddress)
    # assert isinstance(response[0].items[0], ShipStationOrderItem)
    assert isinstance(response[0].advanced_options, ShipStationAdvancedOptions)
    assert isinstance(response[0].weight, ShipStationWeight)
    assert isinstance(response[1].international_options,
                      ShipStationInternationalOptions)
    assert isinstance(response[1].international_options.customs_items[0],
                      ShipStationCustomsItem)
    assert response[1].create_date == datetime.datetime(
        2015, 6, 30, 15, 20, 26, 723000)
    assert response[1].shipping_amount == Decimal("0.0")
import os
import gspread
from dotenv import load_dotenv
load_dotenv()

gc = gspread.service_account('service-account.json')
sheet = gc.open('Awards w2021')
worksheet = sheet.get_worksheet(0)
records = worksheet.get_all_records()

from shipstation.api import ShipStation, ShipStationOrder, ShipStationAddress, ShipStationWeight, ShipStationContainer
ss = ShipStation(key=os.getenv('API_KEY'), secret=os.getenv('API_SECRET'))
for record in records:
    if record['Status'] == 'awaiting shipment':
        ss_order = ShipStationOrder(order_number='w2021award')
        ss_order.set_status('awaiting_shipment')
        ss_weight = ShipStationWeight(units='ounces', value=4)
        ss_container = ShipStationContainer(
            units='inches',
            length=12.25,
            width=9.75,
            height=0.25
        )
        ss_container.set_weight(ss_weight)
        shipping_address = ShipStationAddress(
            name=record['Name'],
            street1=record['addrline1'],
            street2=record['addrline2'],
            city=record['City'],
            state=record['State'],
            postal_code=record['ZIP'],
Beispiel #20
0
import os
from flask import Flask, request
from shipstation.api import ShipStation, ShipStationOrder, ShipStationAddress, ShipStationItem, ShipStationWeight

no_weight = ShipStationWeight(units='ounces',value=0)
app = Flask(__name__)
ss = ShipStation(key=os.getenv('SHIPSTATION_API_KEY'), secret=os.getenv('SHIPSTATION_API_SECRET'))
shirts = {
    'S':  ShipStationItem(sku=os.getenv('SHIRT_S_SKU', '605925771853'),quantity=1),
    'M':  ShipStationItem(sku=os.getenv('SHIRT_M_SKU', '605925771860'),quantity=1),
    'L':  ShipStationItem(sku=os.getenv('SHIRT_L_SKU', '605925771877'),quantity=1),
    'XL': ShipStationItem(sku=os.getenv('SHIRT_XL_SKU', '605925771884'),quantity=1)
}


@app.route('/send', methods=['POST'])
def tshirt_cannon():
    body = request.json
    print(body)
    ss_order = ShipStationOrder(order_number=f'tshirt-cannon-{str(body["Entry"]["Number"])}')
    shipping_address = ShipStationAddress(
        name=body['YourName2']['FirstAndLast'],
        street1=body['Address']['Line1'],
        street2=body['Address']['Line2'],
        street3=body['Address']['Line3'],
        city=body['Address']['City'],
        state=body['Address']['State'],
        postal_code=body['Address']['PostalCode'],
        country=body['Address']['Country']
    )
    ss_order.set_billing_address(shipping_address)
Beispiel #21
0
class ShipStationClient():
    'Handles order creation and check on shipstation.'

    def __init__(self) -> None:
        self.client = ShipStation(key=settings.SHIPSTATION_API_KEY,
                                  secret=settings.SHIPSTATION_API_SECRET)

    def get_client(self) -> ShipStation:
        'Get native shipstation client'
        return self.client

    def add_lead_order(
            self,
            lead: Lead,
            status: typing.Optional[str] = None) -> ShipStationOrder:
        'Create order for given lead.'
        if not lead.shipstation_order_number:
            random_str = str(uuid.uuid4()).replace('-', '')[:10]
            lead.shipstation_order_number = '{}__{}'.format(
                lead.raspberry_pi.rpid, random_str)
            lead.save()

        order = ShipStationOrder(order_key=lead.shipstation_order_number,
                                 order_number=lead.shipstation_order_number)
        order.set_customer_details(
            username=lead.safe_name(),
            email=lead.email,
        )

        if status:
            order.set_status(status)

        shipping_address = ShipStationAddress(
            name=lead.safe_name(),
            # company=sf_lead.company,
            street1=lead.street,
            street2=lead.apartment,
            city=lead.city,
            postal_code=lead.postal_code,
            # country=sf_lead.country,
            country='US',
            state=lead.state or '',
            phone=lead.phone,
        )
        order.set_shipping_address(shipping_address)
        order.set_billing_address(shipping_address)

        item = ShipStationItem(
            name=lead.raspberry_pi.rpid,
            quantity=1,
            unit_price=0,
        )
        item.set_weight(ShipStationWeight(units='ounces', value=0))
        order.add_item(item)

        order.set_status('awaiting_shipment')

        self.client.add_order(order)
        self.submit_orders()
        return order

    def submit_orders(self) -> None:
        'Submit all created or changed orders.'
        for order in self.client.orders:
            self.post(endpoint='/orders/createorder', data=order.as_dict())

    def post(self, endpoint: str, data: typing.Dict) -> None:
        'Rewrite original shipstaion.post method to catch exceptions.'
        url = '{}{}'.format(self.client.url, endpoint)
        headers = {'content-type': 'application/json'}
        response = requests.post(
            url,
            auth=(self.client.key, self.client.secret),
            data=json.dumps(data),
            headers=headers,
        )
        if response.status_code not in [200, 201]:
            raise ValueError('Shipstation Error', response.status_code, data,
                             response.text)

    @staticmethod
    def get_lead_order_data(lead: Lead) -> typing.Optional[typing.Dict]:
        'Get order data for lead.'
        if not lead.shipstation_order_number:
            return None
        data = requests.get(
            'https://ssapi.shipstation.com/orders',
            params={
                'orderNumber': lead.shipstation_order_number
            },
            auth=requests.auth.HTTPBasicAuth(settings.SHIPSTATION_API_KEY,
                                             settings.SHIPSTATION_API_SECRET),
        ).json().get('orders')
        data = data[0] if data else None
        return data
Beispiel #22
0
 def __init__(self) -> None:
     self.client = ShipStation(key=settings.SHIPSTATION_API_KEY,
                               secret=settings.SHIPSTATION_API_SECRET)
def test_list_shipments_error(ss: ShipStation,
                              mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_shipments_error"]
    with pytest.raises(httpx.HTTPStatusError):
        ss.list_shipments()
def test_list_webhooks(ss: ShipStation,
                       mocked_api: respx.MockTransport) -> None:
    request = mocked_api["list_webhooks"]
    response = ss.list_webhooks()
    assert request.called
Beispiel #25
0
def ss() -> ShipStation:
    yield ShipStation(key="123456789",
                      secret="123456789",
                      debug=False,
                      timeout=1)