# AGENTS.md — ShipStation for WooCommerce

This file is the primary instruction source for coding agents in this repository.

Plugin slug `woocommerce-shipstation-integration`. Connects WooCommerce to ShipStation via two API surfaces: **Legacy XML API** (`/?wc-api=wc_shipstation`, ShipStation auth key, `export`/`shipnotify`) and **REST API** (`/wp-json/wc-shipstation/v1/`, WC consumer key/secret).

---

## CRITICAL Rules

- MUST use full hook names (e.g. `woocommerce_shipstation_export_get_order`) — never abbreviate with a leading underscore.
- MUST apply any export logic fix to **both** `class-wc-shipstation-api-export.php` (XML) and `class-orders-controller.php` (REST) — they are separate implementations sharing the same hooks.
- MUST apply any shipnotify logic fix to **both** `class-wc-shipstation-api-shipnotify.php` (XML) and `class-orders-controller.php` (REST).
- MUST use WC CRUD methods on orders (`$order->get_meta()`, `$order->get_billing_address()`, etc.) — never `get_post_meta()` or `$wpdb` on order data (HPOS is declared).
- MUST NOT remove `nocache_headers()` or `DONOTCACHEPAGE` from XML responses — they are intentional.
- MUST NOT edit `.phpstan/dist/` stubs manually — they are generated by `lucasbustamante/stubz`.
- MUST NOT modernise legacy classes (`WC_Shipstation_*`, `WC_ShipStation_*`) without a migration plan.
- MUST NOT use PHP 8.0+ syntax — the plugin must remain compatible with PHP 7.4. Forbidden: named arguments, match expressions, union types, nullsafe operator (`?->`), `readonly` properties, `never` return type, fibers, enums, and any other feature not available in PHP 7.4.
- MUST ask before making breaking changes to existing XML or REST API request/response schemas.

---

## Project Knowledge

- **Product:** ShipStation integration for WooCommerce — order export and shipment notification.
- **Stack:**
  - PHP, WordPress, WooCommerce (version requirements in plugin headers and `package.json`)
  - Node + pnpm (build tooling only — no runtime JS dependencies)
  - Sass + uglify-js for assets, gettext for .pot generation
- **Composer dev deps:** `squizlabs/php_codesniffer` · `woocommerce/woocommerce-sniffs` · `phpstan/phpstan` · `lucasbustamante/stubz`
- **Key directories:**
  - `includes/` — all plugin PHP source; bootstrap, integration settings, auth, shared utilities, checkout, logging, and privacy classes live here at the top level
  - `includes/api/requests/` — legacy XML API handlers (export and shipnotify); touch both files when changing export or shipnotify logic
  - `includes/api/rest/` — REST API controllers (orders, inventory, diagnostics) plus a shared base controller
  - `includes/data/` — static settings field definitions

- **Docs:** `changelog.txt` (manual, pre-release) · `readme.txt` (WordPress.org listing, keep in sync with plugin headers)

---

## Common Commands

```bash
# Install dependencies
composer install
pnpm install

# Environment (requires Docker + pnpm)
pnpm run env:start / env:stop / env:destroy
pnpm run env:cli <wp-cli-args>              # WP-CLI inside container

# Build
pnpm run build:dev   # Dev (no zip): composer deps + minify JS/CSS + .pot
pnpm run build       # Production zip — deletes vendor/; re-run composer install after
pnpm run watchsass   # Watch/recompile SASS (dev only)

# Lint / static analysis
composer run check-php       # PHPCS (WC-Core + WP-Core + WP-Extra)
composer run check-php:fix   # Auto-fix
composer run check-security  # PHPCS security ruleset
composer run phpstan         # Level 2 — requires build:dev first (.phpstan/dist/ stubs)

# Tests — no local unit or E2E suite
# CI via QIT on merge to trunk: activation · security · PHP compat · PHPStan · validation
# composer run qit:security / qit:plugin-check  (requires partner credentials)

# Debugging
pnpm run env:cli config set WP_DEBUG true --raw
pnpm run env:cli config set WP_DEBUG_LOG true --raw
pnpm run env:cli config set WP_DEBUG_DISPLAY false --raw
# Log file written to wp-content/debug.log inside the container

# Verify XML API is responding (replace AUTH_KEY with the key from WC settings)
curl -s "http://localhost:8888/?wc-api=wc_shipstation&auth_key=AUTH_KEY&action=export&page=1"
```

Admin: http://localhost:8888/wp-admin · `admin` / `password`

---

## Conventions To Follow

- Branch naming: `fix/issue-<SHIPSTN-XX>` or `feat/issue-<SHIPSTN-XX>` → PR to `trunk`.
- Commits: imperative tone, optionally prefixed `[SHIPSTN-XX]`.
- CI (QIT) runs **on merge to trunk only** — not on PR open. PHPCS + PHPStan level 2 must pass before merging.
- New PHP code belongs in `WooCommerce\Shipping\ShipStation\*` namespace; legacy global-namespace classes stay as-is.
- Use WordPress coding and security standards: sanitize and validate input, escape output, enforce capability checks where relevant.
- Keep PRs focused; include test evidence for changed behavior where possible.

---

## API Reference

### REST (`wc-shipstation/v1`)

| Method | Route | Key params |
|---|---|---|
| GET | `/orders` | `modified_after` (ISO8601 UTC), `page`, `per_page` (1–500, default 100), `status_mapping[]` (overrides WC→SS map) |
| GET | `/inventory` | `page` |
| GET | `/diagnostics/details` | — |
| POST | `/diagnostics/validate` | — |
| POST | `/orders/shipments` | REST alternative to XML shipnotify; carries extended metadata (ship_from, return_address, fulfillment_cost, notes) |

Auth: WC consumer key/secret stored via AJAX in `woocommerce_shipstation_api_key_id`. All endpoints gated by `wc_shipstation_user_can_manage_wc` filter `(bool $can, $result)`.

### XML API

Required: `auth_key`, `action` (`export`|`shipnotify`). Optional: `start_date`/`end_date` (`MM/dd/yyyy HH:mm` UTC or `MMDDYYYYxHHMM`), `page` (default 1). Page size: 100 (`WC_SHIPSTATION_EXPORT_LIMIT`). Response: `<Orders page="N" pages="N">`, sorted `date_modified DESC`.

**Date parsing:** always use `WC_Shipstation_API_Export::parse_shipstation_date( $date_string )` — never `strtotime()` directly on ShipStation dates.

---

## Status Mapping

`WC_ShipStation_Integration` constants: `AWAITING_PAYMENT_STATUS` · `AWAITING_SHIPMENT_STATUS` · `ON_HOLD_STATUS` · `COMPLETED_STATUS` · `CANCELLED_STATUS` · `PAYMENT_CANCELLED_STATUS` · `PAYMENT_FAILED_STATUS` · `PAID_STATUS`. WC prefix: `wc-`. Default export statuses: `processing`, `on-hold`, `completed`, `cancelled`. Default shipped: `completed`. Meta keys: `shipstation_is_gift`, `shipstation_gift_message`.

---

## Hooks (Public Filters/Actions)

**Both APIs:**
- `woocommerce_shipstation_export_order` `(bool, $order_id)` — return false to skip an order
- `woocommerce_shipstation_export_get_order` `($order)` — modify the order object before export
- `woocommerce_shipstation_export_currency_code` / `woocommerce_shipstation_export_exchange_rate` — override currency code / exchange rate
- `woocommerce_shipstation_export_discounts_as_separate_item` `(bool)` — default true; false embeds discounts in item prices
- `woocommerce_shipstation_no_shipping_item` `(bool, $product, $item)` — return true to skip a non-shippable line item
- `woocommerce_shipstation_export_custom_field_2` / `woocommerce_shipstation_export_custom_field_3` — meta key for custom field
- `woocommerce_shipstation_export_custom_field_2_value` / `woocommerce_shipstation_export_custom_field_3_value` — filter the fetched value
- `woocommerce_shipstation_export_address_data` `($address, $order, $is_export)` — filter address data before export; applied inside `Order_Util::get_address_data()`
- `woocommerce_shipstation_get_order_id_from_order_number` `($order_id, $order_number)` — resolve order ID (for sequential order number plugins); inner utility filter
- `woocommerce_shipstation_get_orders_before_process_request` (action) `($params)` — fires before the order query runs

**XML only:**
- `woocommerce_shipstation_export_order_xml` `($xml_node)` — modify the final XML node per order

**XML shipnotify only:**
- `woocommerce_shipstation_get_order_id` `($order_id)` — wraps the result of `get_order_id_from_order_number`; intercept order ID resolution at the XML entry point

**REST only:**
- `woocommerce_shipstation_orders_controller_get_order_data` `($data, $order)` — modify the full order response shape
- `woocommerce_shipstation_fulfillment_item` `($item, $order, $line_item, $args)` — modify an individual line item
- `woocommerce_shipstation_diagnostics_controller_get_details` `($info, $request)` — modify the diagnostics response

**Shipnotify (XML + REST):**
- `woocommerce_shipstation_shipnotify_tracking_note` `($note, $order, $data)` — modify tracking note text
- `woocommerce_shipstation_shipnotify_send_tracking_note` `(bool, $note, $order, $data)` — control whether note is sent to customer
- `woocommerce_shipstation_shipnotify_order_shipped` `(bool, $order, $data)` — override the shipped flag determination
- `woocommerce_shipstation_shipnotify` (action) `($order, $data)` — fires when a shipment notification is received
- `woocommerce_shipstation_shipnotify_status_updated` (action) `($order, $data)` — fires after order status is updated

**Other:**
- `woocommerce_shipstation_gift_message_max_length` `(int)` — max gift message length, default 255 (range 1–1000)
- `wc_shipstation_user_can_manage_wc` `(bool, $result)` — gates all REST endpoint permission checks

---

## Architectural Decisions

- **Dual API, same hooks.** `class-wc-shipstation-api-export.php` (XML) and `class-orders-controller.php` (REST) are intentionally separate implementations that call identical filter hooks, so both surfaces return consistent data. This is a deliberate design — not duplication to clean up.
- **Shipnotify has two entry points.** XML `?action=shipnotify` and REST `POST /orders/shipments` both fire the same shipnotify hooks. Do not assume the XML path is the only one.
- **Namespace mix is intentional.** New code (REST controllers, auth controller, logger) uses `WooCommerce\Shipping\ShipStation\*` namespace. Legacy classes (`WC_Shipstation_*`, `WC_ShipStation_*`) remain in the global namespace for backwards compatibility. Do not modernise legacy classes without a migration plan.
- **HPOS declared.** The plugin declares HPOS compatibility. Always use WC order CRUD methods — never `get_post_meta()` or raw `$wpdb` queries on order data.
- **Auth key timing.** `WC_ShipStation_Integration` statics (`$auth_key`, `$export_statuses`, `$shipped_status`) are populated during `plugins_loaded`. Reading them before that hook fires returns nulls.
- **No caching on XML responses.** `nocache_headers()` + `DONOTCACHEPAGE` are set intentionally to prevent stale ShipStation exports. Do not remove.
- **PHPStan stubs are generated.** `.phpstan/dist/` is produced by `lucasbustamante/stubz` from WooCommerce source. Never edit these files manually — regenerate by running `pnpm run build:dev`.

---

## Compatibility Contracts

Treat these as stability contracts unless the task explicitly requests a behavior change. Call out any potential impact and confirm intent before proceeding:

- XML export response shape (`<Orders>` envelope, per-order fields, pagination)
- XML shipnotify accepted parameters and order status transition behavior
- All REST endpoint request/response schemas (`/orders`, `/inventory`, `/diagnostics/*`, `/orders/shipments`)
- All public filter and action hook signatures listed in the Hooks section above
- Order status mapping defaults and constants on `WC_ShipStation_Integration`

---

## Common Pitfalls

- **Permalinks.** Fresh wp-env starts on "Plain" permalinks — the XML API won't respond. Fix: `pnpm run env:cli option update permalink_structure '/%postname%/'`
- **`pnpm run build` deletes `vendor/`.** Re-run `composer install` to restore dev tools after a production build.
- **PHPStan needs stubs.** Run `pnpm run build:dev` once before running `composer run phpstan` — the `.phpstan/dist/` stubs must exist first.
- **Version lives in two places.** `woocommerce-shipstation.php` header and `package.json` — bump both on release.
- **Custom field hooks are pairs.** `woocommerce_shipstation_export_custom_field_2` sets the meta key; `woocommerce_shipstation_export_custom_field_2_value` filters the fetched value. Same pattern for `_3`.
- **`.wp-env.json` pulls latest stable WooCommerce** (not pinned). Pin the version in `.wp-env.json` if WooCommerce releases a breaking change during development.
- **Fixing one API isn't enough.** XML and REST share hook names but are separate code paths. A logic fix must be applied to both — see CRITICAL Rules.

---

## E2E / CI Status

No local test suite. Not covered: settings UI, XML/REST response contracts, shipnotify round-trip, order status transitions. CI runs via QIT on merge to trunk only (activation · security · PHP compat · PHPStan · validation).

---

## Maintenance

- Keep this file updated when recurring review feedback reveals missing guidance.
- Prefer concise, high-signal entries over verbose generic instructions.
- When a hook, file, or constraint changes, update the relevant section here in the same PR.
