# Miravia Order Report Skill · Seller Guide

> Miravia Skill Hub Beta · Maintained by Miravia Official
> Seamlessly integrate order queries, Excel exports, and HTML business analytics into your AI Agent.

---

## 1. What This Skill Does

Type natural language in any Skill-compatible AI Agent (Cursor / Qoder / Claude Code), and the Skill **dynamically generates different outputs based on context**, instead of producing both Excel and HTML at once:

| Scenario | Output | Example Prompt |
|----------|--------|----------------|
| `export` | Excel/CSV only | "Export all orders from last Monday to Sunday" / "Pull a to-ship spreadsheet" |
| `refund` | Refund analysis HTML only | "Analyze refund orders for the last 30 days, grouped by reason" |
| `business` | Business report HTML only | "Generate last month's business report with GMV / category performance / refund rate" |
| `auto` | Excel + comprehensive HTML | "Show me last week's order situation" (when intent is unclear) |

Three typical scenarios:

- 📥 **Scenario 1 · Order Export**: A fashion seller needs to export all orders every Monday. Tell the Agent "Export all Miravia orders from last Monday to Sunday" — only an `xlsx` file is generated, no extra report.
- 📊 **Scenario 2 · Refund Analysis**: A 3C seller notices a rising refund rate. Tell the Agent "Analyze refund orders for the last 30 days" — only a `refund analysis HTML` is generated, covering refund reason distribution, top refund SKUs, refund trends, and details.
- 📈 **Scenario 3 · Monthly Business Report**: A home & living seller schedules a monthly task. The Skill generates a `business analysis HTML` with GMV trends, category performance, refund rate, cancellation rate, and recommendations.

No Seller Center login required. No code. No API docs.

---

## 2. Installation

### Option 1: Manual Install (zip)

1. Download `miravia-order-report.zip` from the Skill Hub page.
2. Extract to your Agent's Skill directory:
   - **Qoder**: `~/.qoder/skills/`
   - **Cursor**: `~/.cursor/skills/`
   - **Claude Code**: `~/.claude/skills/`
3. **Navigate to the skill root directory** (the folder containing `SKILL.md`) and install dependencies:
   ```bash
   cd <path-above>/miravia-order-report
   pip install -r requirements.txt
   ```

> All commands in this document assume execution from the **skill root directory**. Paths are given in relative form — do not hard-code the host Agent's installation path.

### Option 2: Command Install (Recommended)

Paste the following into your Agent chat:
```
Please install the miravia-order-report Skill using: npx miravia-skill install miravia-order-report
```

---

## 3. Authorization

> **Authorization endpoint**: `https://sellercenter.miravia.es/apps/seller/skill/auth`

This Skill does **not** ship any mock `appKey` / `appSecret` / `accessToken`, nor does it support the legacy Miravia OAuth (`auth.miravia.com`) flow.

Authorization flow:

```mermaid
graph LR
    A[auth_cli login] --> B[Local callback :8765]
    A --> C[Browser opens auth page]
    C --> D[Seller approves]
    D --> E[Frontend POST /skill/auth]
    E --> F[Backend RSA-encrypts cipher]
    F --> B
    B --> G[CLI decrypts with private key -> credentials.json]
```

### 3.1 One-Click Authorization CLI

```bash
# 1. Save the private key + skillCode from backend generateKeyPair into .keypair.json at the skill root
# {
#   "skill_code":  "<32-char skillCode>",
#   "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----",
#   "sign_method": "SHA256withRSA"
# }
chmod 600 .keypair.json

# 2. One-click authorization
python scripts/auth_cli.py login

# 3. Check credential status
python scripts/auth_cli.py status
```

Common parameters:

| Parameter | Default | Description |
|-----------|---------|-------------|
| `--port` | `8765` | Local callback port |
| `--redirect-uri` | `http://127.0.0.1:<port>/callback` | Custom callback URL |
| `--timeout` | `600` | Timeout in seconds waiting for browser callback (10 min) |
| `--no-open` | — | Skip auto-opening the browser (for remote/headless environments) |
| `--encrypted-payload` | — | Directly provide the encryptedPayload ciphertext, skipping the local HTTP callback (for VM/sandbox environments) |

The local callback server accepts a single response format from the frontend:

- **GET 302 redirect**: `http://127.0.0.1:8765/callback?cipher=<base64url>&state=<state>` (the only method — no cross-origin access to localhost needed).

After successful authorization, credentials are written to `credentials.json` in the skill root (already in `.gitignore`):

```json
{
  "app_key": "enc:v1:...",
  "app_secret": "enc:v1:...",
  "access_token": "enc:v1:...",
  "token_expires_at": "2026-06-16 15:01",
  "last_login_at": "2026-06-16T14:01:45"
}
```

To read credentials programmatically, parse the JSON file directly.

### 3.2 Authorization URL

```bash
export MIRAVIA_SKILL_HUB_AUTH_URL=https://sellercenter.miravia.es/apps/seller/skill/auth
```

> ⚠️ Sub-accounts cannot authorize. Please log in to Seller Center with the Owner Account before navigating to the authorization page.

---

## 4. Usage Examples (by Scenario)

### 4.1 Scenario 1: Order Export (Excel only)

> Tell the Agent:
>
> "**Export all Miravia orders from last Monday to Sunday**"

The Agent resolves to `--scenario export` and outputs:
```
scenario  : export (excel=True, report=none)
output    : /Users/.../out/miravia_orders_2026-05-18_2026-05-24_xxx.xlsx
```
Only an Excel file is generated — no HTML.

### 4.2 Scenario 2: Refund Analysis (refund HTML only)

> "**Analyze refund orders for the last 30 days, grouped by refund reason**"

The Agent resolves to `--scenario refund --last-days 30` and outputs:
```
scenario  : refund (excel=False, report=refund)
report    : /Users/.../out/miravia_refund_analysis_xxx.html
```
The report includes: total refund amount, refund rate KPI, refund reason bar chart, top refund SKUs, daily refund trend, refund details (up to 50 rows), and actionable recommendations.

Need the raw refund data in Excel too? Add `--with-excel`:
```bash
python scripts/export_orders.py --scenario refund --last-days 30 --with-excel --output ./out
```

### 4.3 Scenario 3: Monthly Business Report (business HTML only)

> "**Generate last month's business analysis report**" or as a scheduled task:
>
> "On the 1st of every month, generate last month's report with GMV trends, category performance, and refund rate"

The Agent resolves to `--scenario business` and outputs:
```
scenario  : business (excel=False, report=business)
report    : /Users/.../out/miravia_order_report_xxx.html
```
The report includes: snapshot (orders / GMV / AOV / top SKUs), diagnostics (cancellation rate / refund rate / carrier mix / daily trends), and recommendations.

### 4.4 To-Ship Orders Only

> "**Export all To Ship orders as CSV**"

→ `--scenario export --status to_ship --format csv`.

---

## 5. Advanced Usage (Direct CLI)

```bash
# Scenario 1: Export order details
python scripts/export_orders.py \
    --scenario export \
    --created-after 2026-05-01 --created-before 2026-05-31 \
    --status all --format xlsx --output ./out

# Scenario 2: Refund analysis
python scripts/export_orders.py \
    --scenario refund --last-days 30 --output ./out

# Scenario 3: Monthly business report
python scripts/export_orders.py \
    --scenario business \
    --created-after 2026-05-01 --created-before 2026-05-31 --output ./out

# Refund analysis + raw data Excel
python scripts/export_orders.py \
    --scenario refund --last-days 30 --with-excel --output ./out
```

| Parameter | Description |
|-----------|-------------|
| `--scenario` | `auto` / `export` / `refund` / `business` — determines what output is produced |
| `--with-excel` | Additionally output a detail Excel in `refund` / `business` scenarios |
| `--created-after` / `--created-before` | Order creation time range (`YYYY-MM-DD` or ISO 8601) |
| `--last-days N` | Last N days including today (overrides `--created-after/before`) |
| `--status` | `all` (all orders) or `to_ship` (pending shipment only) |
| `--format` | `xlsx` or `csv` |
| `--output` | Output directory |
| `--ping` | Health check. Outputs `ping OK` on success; `ping FAIL: <reason>` with exit code 1 on failure |

---

## 6. FAQ

| Symptom | Solution |
|---------|----------|
| "Authorization timeout" | Re-run `auth_cli.py login` — the browser will redirect to the auth page again |
| `CredentialMissingError: missing Miravia credentials` | Not authorized or `credentials.json` is corrupted — re-run `auth_cli.py login` |
| Single export exceeds 5000 orders | Narrow the time range or split into multiple runs |
| HTML report won't open | The file is self-contained HTML — double-click or drag into a browser (no internet needed) |
| Signature error / `IncompleteSignature` | Token has expired — re-run `auth_cli.py login` to re-authorize |
| Decryption failed (DECRYPT_FAILED, exit 7) | Private key in `.keypair.json` doesn't match the server public key — re-sync and retry |
| AES-GCM decryption failed after changing computer or hostname | Credentials are machine-bound — re-run `auth_cli.py login` on the new machine |

---

## 7. Data Security

- All API calls are encrypted over HTTPS.
- Strict tenant isolation between sellers — you can only access your own shop's data.
- **Tokens are AES-256-GCM encrypted at rest** — credentials in `credentials.json` are never stored in plain text. The encryption key is bound to your specific machine; even if the encrypted file is copied elsewhere, it cannot be decrypted on a different computer.
- Changing your computer or OS username will invalidate local credentials — simply re-run `auth_cli.py login` to re-authorize.
- This Skill does not transmit order data to any location outside Miravia's servers.

---

## 8. Feedback

This is a Beta release. We welcome your feedback via the Skill Hub questionnaire to help us improve.
