Ai knowledge and logicHelpers

prestashop_get_order / prestashop_find_orders

Look up PrestaShop orders by order number or email from Python, returning the raw PrestaShop order.

prestashop_get_order(context: dict, order_number: str) -> dict | None
prestashop_find_orders(context: dict, email: str, limit: int = 10) -> list[dict]

Thin helpers for the most common PrestaShop read: finding a customer's order. They read the business's PrestaShop connection with get_integration_credentials, call the PrestaShop webservice, through Octocom's proxy and return the orders as PrestaShop returns them; see the PrestaShop API reference for every field. Each order also carries its current state's name under status.

prestashop_get_order matches the internal order ID first, then the printed reference. prestashop_find_orders finds the customer account with that email; guest checkouts have no account and aren't found. Both helpers raise ValueError if PrestaShop isn't connected and requests.HTTPError if PrestaShop rejects the request.

The full source is below. Copy it into your own action when you need something it doesn't do.


prestashop_get_order

NameTypeDescription
contextdictThe context object passed to your action
order_numberstrThe order ID or printed reference as the customer gave it. Spaces and a leading # are ignored

Returns the matching order, or None.

prestashop_find_orders

NameTypeDescription
contextdictThe context object passed to your action
emailstrThe customer's email address
limitintMaximum number of orders, newest first (10)

Returns a list of orders, newest first. Empty if there are none.


Example

def execute_action(context):
    order = prestashop_get_order(context, context["args"]["orderId"])
    if order is None:
        return {"success": False, "message": "The order could not be found."}
    return {"success": True, "orders": [order]}

Businesses moved off the built-in order lookups get this as their getOrderDetailsByOrderId action, together with a getOrderDetailsByEmail action that calls prestashop_find_orders. They are ordinary Python actions you can read and change.


Read-only sidebar

prestashop_order_widget(context) renders the saved order ID and customer email lookups as a basic sidebar panel without order buttons. See Order widgets for setup, custom mappings and the shared presentation source.

Source

import re


def _prestashop_store(context):
    """The current business's PrestaShop connection: {"storeUrl", "apiKey"}."""
    business = context.get("business") or {}
    slug = business.get("slug") or (context.get("conversation") or {}).get("businessSlug")
    if not slug:
        raise ValueError("The business is not available in the context")
    store = (get_integration_credentials(context).get(slug) or {}).get("prestaShop")
    if not store:
        raise ValueError("PrestaShop is not connected for this business")
    return store


def _prestashop_get(store, resource, params):
    # PrestaShop stores allowlist Octocom's proxy IP, like the connector.
    response = proxy_request(
        "GET",
        store["storeUrl"].rstrip("/") + "/api/" + resource,
        params={"ws_key": store["apiKey"], "output_format": "JSON", **params},
        timeout=20,
    )
    response.raise_for_status()
    body = response.json() if response.content.strip() else {}
    # An empty result is "[]" rather than an object.
    items = body.get(resource) if isinstance(body, dict) else None
    if isinstance(items, dict):
        items = [items]
    return items or []


def _prestashop_with_status(store, order):
    """The order with its current state's name under "status"."""
    states = _prestashop_get(store, "order_states", {"filter[id]": order.get("current_state"), "display": "[name]"})
    name = states[0].get("name") if states else None
    # Multilingual stores return [{"id": language, "value": name}, ...].
    if isinstance(name, list):
        name = name[0].get("value") if name else None
    elif isinstance(name, dict):
        name = name.get("value")
    order["status"] = name
    return order


def _prestashop_orders(store, field, value, limit):
    orders = _prestashop_get(store, "orders", {
        f"filter[{field}]": value, "display": "full", "sort": "[id_DESC]", "limit": limit,
    })
    return [_prestashop_with_status(store, order) for order in orders[:limit]]


def prestashop_get_order(context, order_number):
    """The PrestaShop order with this ID or reference, or None."""
    store = _prestashop_store(context)
    number = re.sub(r"\s+", "", str(order_number)).lstrip("#")
    if not number:
        return None
    # Customers quote either the internal ID or the printed reference.
    orders = _prestashop_orders(store, "id", number, 1) if number.isdigit() else []
    orders = orders or _prestashop_orders(store, "reference", number, 1)
    return orders[0] if orders else None


def prestashop_find_orders(context, email, limit=10):
    """The customer's PrestaShop orders by account email, newest first."""
    store = _prestashop_store(context)
    customers = _prestashop_get(store, "customers", {"filter[email]": email.strip(), "display": "[id]"})
    if not customers:
        return []
    return _prestashop_orders(store, "id_customer", customers[0]["id"], limit)


def _prestashop_widget_order(order):
    return {
        "id": order.get("id"), "number": order.get("reference"), "status": order.get("status"),
        "total": order.get("total_paid_tax_incl"), "placed_at": order.get("date_add"),
        "products": [{"name": p.get("product_name"), "quantity": p.get("product_quantity"), "sku": p.get("product_reference")}
                     for p in (order.get("associations") or {}).get("order_rows") or []],
        "shipments": [{"tracking_number": order["shipping_number"]}] if order.get("shipping_number") else [],
    }


def prestashop_order_widget(context):
    """Read-only sidebar orders from the saved order ID and customer's email.

    The raw order has only a currency ID, so no currency code is invented.
    """
    return order_widget(context, get_order=prestashop_get_order, find_orders=prestashop_find_orders, map_order=_prestashop_widget_order)

On this page