@miraiva_test/miravia-order-report 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js ADDED
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Miravia Order Report Skill — CLI Installer
4
+ *
5
+ * Usage:
6
+ * npx @miraiva_test/miravia-order-report install [--target <path>] [--agent <qoder|cursor|claude>]
7
+ * npx @miraiva_test/miravia-order-report upgrade
8
+ * npx @miraiva_test/miravia-order-report auth
9
+ * npx @miraiva_test/miravia-order-report --version
10
+ */
11
+
12
+ 'use strict';
13
+
14
+ const { install, upgrade, runAuth, showVersion, showHelp } = require('../lib/installer');
15
+
16
+ const args = process.argv.slice(2);
17
+ const command = args[0];
18
+
19
+ // Parse flags
20
+ function parseFlags(args) {
21
+ const flags = {};
22
+ for (let i = 1; i < args.length; i++) {
23
+ if (args[i] === '--target' && args[i + 1]) {
24
+ flags.target = args[++i];
25
+ } else if (args[i] === '--agent' && args[i + 1]) {
26
+ flags.agent = args[++i];
27
+ } else if (args[i] === '--no-venv') {
28
+ flags.noVenv = true;
29
+ } else if (args[i] === '--help' || args[i] === '-h') {
30
+ flags.help = true;
31
+ }
32
+ }
33
+ return flags;
34
+ }
35
+
36
+ const flags = parseFlags(args);
37
+
38
+ switch (command) {
39
+ case 'install':
40
+ install(flags);
41
+ break;
42
+ case 'upgrade':
43
+ upgrade(flags);
44
+ break;
45
+ case 'auth':
46
+ runAuth(flags);
47
+ break;
48
+ case '--version':
49
+ case '-v':
50
+ showVersion();
51
+ break;
52
+ case '--help':
53
+ case '-h':
54
+ case undefined:
55
+ showHelp();
56
+ break;
57
+ default:
58
+ console.error(`\x1b[31mUnknown command: ${command}\x1b[0m`);
59
+ showHelp();
60
+ process.exit(1);
61
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "skill_code": "miravia_order_reports",
3
+ "private_key": "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDW2Y41Lm/5JqotCumUEzTtBqJqdU9QyvuM9OpaBJSdDOo0yS2JCszVjCdfGg2FQA9JV/1empo1PsB8//l6VS/rHXPcDv1zhIx8oJcQo3P5YeC8UBeGoh3NMAGUVq9Ka+j7+9h7K4N5k8ewTLOWxpOlu/9AYkpAm1b49dvBimDkWmt4uv4d6bS/0SvnhVtiGxtf9dMbqKmbaQEAw1BIfzxiWeWkaOuCzFX5+jfmcC5h+1QPUaqk1cao/C1lGOZ2AHDISg1YIcCTQ8EsyG1wHb5xP2TcshYf/8Bq+PiqSKjNKRYl5RUm17oaKK0naaD0e37Qz97xlVOKlcTGs/F8gVMPAgMBAAECggEACxBzGVwF2i/aja1FMCH5FMfFr3PRHNkHMVAfjXk06g2TNhqyJJ+QwuKP2H7v+U++Ocm1O5z8mgdcRFOuVlVyvUnsAIYpGTzXO0fN38Z7H3mh6DC7tWw92qZBPpFkP5HlEqz6jgVEpQsuOm8IxJf/XIac84TcTA1z4ihPI91rdfb146+FBK1rehjbNb14y5PA9jeeyfSAj2iJq5w0FZOkdvMs5KYIH1S8pgyPQgT2ix/ivQfsRm6Q0T/XIZCCiWJak3pnfrEsx+2wgahOF35yy/R4cOsC2YQ7UrZS8MAfzkn05HnGWmbsMcEilm3uJg+GiGcm8IMsDVGZWzYvA516yQKBgQD55sw+yxqO1Q3g9qlfy6vI8UvzlK/ll37/dkt2PvCeR80B1bdQZYoBK7iqAM2DuKWH4YuruSVPJa2qfoQ8rI9TB/KZgOysEbYgn4Zs11gtSA+D4f/6qdCUYs+Ja0vxL27PYTlUgbc+Zt5nTSmA58E/Ja6reu12TyL71hb9Rij17QKBgQDcF8e0w979TA42CU7IKAddNJe+fO/tg1Z328p6QMxIMcnPkXytvw/Qw4uP+hlBmZnsRTzBrmnBBwLvHE+hYBeJxvE0zOqiMIH9I/1gHAfDfvSIWtdxqknO49sHs962rLBAD3xvF0NUbv+b02JxNj5DAuoH38cl79m9k5PpE8uNawKBgA4hqQccASJ2ldRU3nsWT16LlpntnIzFJl9X1yiWopCwyr0B0t3vAADU8hpa9UQvmty2Omm5jIyPOuTbRqsPrwMo/eUET13jmoL5wmZBPzFAU/BHRWxtUegyNj41HRREdGWxv8Yxl6UluAnraR9q+5iQjvIPf4IjM30+PAqSfxp5AoGAT4SP9LFn2WAnKkLGoe5EatpbkMkW7lsrXHaeevj6VYMXhNTtlOCY2DYuMECN63ORdxm0z80yDDl6R+WUp5tOJcsozojSpPKdpFXib1zxOSKfOryHZlu9+u+77NaBusI9k4eEz6Y5/0FzPFttD7YnXJKq91lUXFKB+spdADLUsi0CgYAEge8NfRVVzSCgLdeY4aQghLVczHNutvYzLeTe5o0tkJAtrSY/elaLzcjtfZZY/vFkp6OPgqmArj7jTV+ZM3Wbus2ZMGCTGyG8Yp0wCofAx42I7luSOVC91kdqoO0avD/gHTB8+GS0TfhQPAi+icdsl1I7chzDUYKvToSAyoIzXw==",
4
+ "sign_method": "SHA256withRSA"
5
+ }
package/dist/README.md ADDED
@@ -0,0 +1,249 @@
1
+ # Miravia Order Report Skill · Seller Guide
2
+
3
+ > Miravia Skill Hub Beta · Maintained by Miravia Official
4
+ > Seamlessly integrate order queries, Excel exports, and HTML business analytics into your AI Agent.
5
+
6
+ ---
7
+
8
+ ## 1. What This Skill Does
9
+
10
+ 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:
11
+
12
+ | Scenario | Output | Example Prompt |
13
+ |----------|--------|----------------|
14
+ | `export` | Excel/CSV only | "Export all orders from last Monday to Sunday" / "Pull a to-ship spreadsheet" |
15
+ | `refund` | Refund analysis HTML only | "Analyze refund orders for the last 30 days, grouped by reason" |
16
+ | `business` | Business report HTML only | "Generate last month's business report with GMV / category performance / refund rate" |
17
+ | `auto` | Excel + comprehensive HTML | "Show me last week's order situation" (when intent is unclear) |
18
+
19
+ Three typical scenarios:
20
+
21
+ - 📥 **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.
22
+ - 📊 **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.
23
+ - 📈 **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.
24
+
25
+ No Seller Center login required. No code. No API docs.
26
+
27
+ ---
28
+
29
+ ## 2. Installation
30
+
31
+ ### Option 1: Manual Install (zip)
32
+
33
+ 1. Download `miravia-order-report.zip` from the Skill Hub page.
34
+ 2. Extract to your Agent's Skill directory:
35
+ - **Qoder**: `~/.qoder/skills/`
36
+ - **Cursor**: `~/.cursor/skills/`
37
+ - **Claude Code**: `~/.claude/skills/`
38
+ 3. **Navigate to the skill root directory** (the folder containing `SKILL.md`) and install dependencies:
39
+ ```bash
40
+ cd <path-above>/miravia-order-report
41
+ pip install -r requirements.txt
42
+ ```
43
+
44
+ > 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.
45
+
46
+ ### Option 2: Command Install (Recommended)
47
+
48
+ Paste the following into your Agent chat:
49
+ ```
50
+ Please install the miravia-order-report Skill using: npx miravia-skill install miravia-order-report
51
+ ```
52
+
53
+ ---
54
+
55
+ ## 3. Authorization
56
+
57
+ > **Authorization endpoint** (staging): `https://pre-sellercenter.miravia.es/apps/seller/skill/auth`
58
+ > Production: `https://sellercenter.miravia.es/apps/seller/skill/auth`
59
+
60
+ This Skill does **not** ship any mock `appKey` / `appSecret` / `accessToken`, nor does it support the legacy Miravia OAuth (`auth.miravia.com`) flow.
61
+
62
+ Authorization flow:
63
+
64
+ ```mermaid
65
+ graph LR
66
+ A[auth_cli login] --> B[Local callback :8765]
67
+ A --> C[Browser opens auth page]
68
+ C --> D[Seller approves]
69
+ D --> E[Frontend POST /skill/auth]
70
+ E --> F[Backend RSA-encrypts cipher]
71
+ F --> B
72
+ B --> G[CLI decrypts with private key -> credentials.json]
73
+ ```
74
+
75
+ ### 3.1 One-Click Authorization CLI
76
+
77
+ ```bash
78
+ # 1. Save the private key + skillCode from backend generateKeyPair into .keypair.json at the skill root
79
+ # {
80
+ # "skill_code": "<32-char skillCode>",
81
+ # "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----",
82
+ # "sign_method": "SHA256withRSA"
83
+ # }
84
+ chmod 600 .keypair.json
85
+
86
+ # 2. One-click authorization
87
+ python scripts/auth_cli.py login
88
+
89
+ # 3. Check credential status
90
+ python scripts/auth_cli.py status
91
+ ```
92
+
93
+ Common parameters:
94
+
95
+ | Parameter | Default | Description |
96
+ |-----------|---------|-------------|
97
+ | `--port` | `8765` | Local callback port |
98
+ | `--redirect-uri` | `http://127.0.0.1:<port>/callback` | Custom callback URL |
99
+ | `--timeout` | `600` | Timeout in seconds waiting for browser callback (10 min) |
100
+ | `--no-open` | — | Skip auto-opening the browser (for remote/headless environments) |
101
+ | `--encrypted-payload` | — | Directly provide the encryptedPayload ciphertext, skipping the local HTTP callback (for VM/sandbox environments) |
102
+
103
+ The local callback server accepts a single response format from the frontend:
104
+
105
+ - **GET 302 redirect**: `http://127.0.0.1:8765/callback?cipher=<base64url>&state=<state>` (the only method — no cross-origin access to localhost needed).
106
+
107
+ After successful authorization, credentials are written to `credentials.json` in the skill root (already in `.gitignore`):
108
+
109
+ ```json
110
+ {
111
+ "app_key": "enc:v1:...",
112
+ "app_secret": "enc:v1:...",
113
+ "access_token": "enc:v1:...",
114
+ "token_expires_at": "2026-06-16 15:01",
115
+ "last_login_at": "2026-06-16T14:01:45"
116
+ }
117
+ ```
118
+
119
+ To read credentials programmatically, parse the JSON file directly.
120
+
121
+ ### 3.2 Switch Environment
122
+
123
+ ```bash
124
+ # Staging (default)
125
+ export MIRAVIA_SKILL_HUB_AUTH_URL=https://pre-sellercenter.miravia.es/apps/seller/skill/auth
126
+
127
+ # Production
128
+ export MIRAVIA_SKILL_HUB_AUTH_URL=https://sellercenter.miravia.es/apps/seller/skill/auth
129
+ ```
130
+
131
+ > ⚠️ Sub-accounts cannot authorize. Please log in to Seller Center with the Owner Account before navigating to the authorization page.
132
+
133
+ ---
134
+
135
+ ## 4. Usage Examples (by Scenario)
136
+
137
+ ### 4.1 Scenario 1: Order Export (Excel only)
138
+
139
+ > Tell the Agent:
140
+ >
141
+ > "**Export all Miravia orders from last Monday to Sunday**"
142
+
143
+ The Agent resolves to `--scenario export` and outputs:
144
+ ```
145
+ scenario : export (excel=True, report=none)
146
+ output : /Users/.../out/miravia_orders_2026-05-18_2026-05-24_xxx.xlsx
147
+ ```
148
+ Only an Excel file is generated — no HTML.
149
+
150
+ ### 4.2 Scenario 2: Refund Analysis (refund HTML only)
151
+
152
+ > "**Analyze refund orders for the last 30 days, grouped by refund reason**"
153
+
154
+ The Agent resolves to `--scenario refund --last-days 30` and outputs:
155
+ ```
156
+ scenario : refund (excel=False, report=refund)
157
+ report : /Users/.../out/miravia_refund_analysis_xxx.html
158
+ ```
159
+ 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.
160
+
161
+ Need the raw refund data in Excel too? Add `--with-excel`:
162
+ ```bash
163
+ python scripts/export_orders.py --scenario refund --last-days 30 --with-excel --output ./out
164
+ ```
165
+
166
+ ### 4.3 Scenario 3: Monthly Business Report (business HTML only)
167
+
168
+ > "**Generate last month's business analysis report**" or as a scheduled task:
169
+ >
170
+ > "On the 1st of every month, generate last month's report with GMV trends, category performance, and refund rate"
171
+
172
+ The Agent resolves to `--scenario business` and outputs:
173
+ ```
174
+ scenario : business (excel=False, report=business)
175
+ report : /Users/.../out/miravia_order_report_xxx.html
176
+ ```
177
+ The report includes: snapshot (orders / GMV / AOV / top SKUs), diagnostics (cancellation rate / refund rate / carrier mix / daily trends), and recommendations.
178
+
179
+ ### 4.4 To-Ship Orders Only
180
+
181
+ > "**Export all To Ship orders as CSV**"
182
+
183
+ → `--scenario export --status to_ship --format csv`.
184
+
185
+ ---
186
+
187
+ ## 5. Advanced Usage (Direct CLI)
188
+
189
+ ```bash
190
+ # Scenario 1: Export order details
191
+ python scripts/export_orders.py \
192
+ --scenario export \
193
+ --created-after 2026-05-01 --created-before 2026-05-31 \
194
+ --status all --format xlsx --output ./out
195
+
196
+ # Scenario 2: Refund analysis
197
+ python scripts/export_orders.py \
198
+ --scenario refund --last-days 30 --output ./out
199
+
200
+ # Scenario 3: Monthly business report
201
+ python scripts/export_orders.py \
202
+ --scenario business \
203
+ --created-after 2026-05-01 --created-before 2026-05-31 --output ./out
204
+
205
+ # Refund analysis + raw data Excel
206
+ python scripts/export_orders.py \
207
+ --scenario refund --last-days 30 --with-excel --output ./out
208
+ ```
209
+
210
+ | Parameter | Description |
211
+ |-----------|-------------|
212
+ | `--scenario` | `auto` / `export` / `refund` / `business` — determines what output is produced |
213
+ | `--with-excel` | Additionally output a detail Excel in `refund` / `business` scenarios |
214
+ | `--created-after` / `--created-before` | Order creation time range (`YYYY-MM-DD` or ISO 8601) |
215
+ | `--last-days N` | Last N days including today (overrides `--created-after/before`) |
216
+ | `--status` | `all` (all orders) or `to_ship` (pending shipment only) |
217
+ | `--format` | `xlsx` or `csv` |
218
+ | `--output` | Output directory |
219
+ | `--ping` | Health check. Outputs `ping OK` on success; `ping FAIL: <reason>` with exit code 1 on failure |
220
+
221
+ ---
222
+
223
+ ## 6. FAQ
224
+
225
+ | Symptom | Solution |
226
+ |---------|----------|
227
+ | "Authorization timeout" | Re-run `auth_cli.py login` — the browser will redirect to the auth page again |
228
+ | `CredentialMissingError: missing Miravia credentials` | Not authorized or `credentials.json` is corrupted — re-run `auth_cli.py login` |
229
+ | Single export exceeds 5000 orders | Narrow the time range or split into multiple runs |
230
+ | HTML report won't open | The file is self-contained HTML — double-click or drag into a browser (no internet needed) |
231
+ | Signature error / `IncompleteSignature` | Token has expired — re-run `auth_cli.py login` to re-authorize |
232
+ | Decryption failed (DECRYPT_FAILED, exit 7) | Private key in `.keypair.json` doesn't match the server public key — re-sync and retry |
233
+ | AES-GCM decryption failed after changing computer or hostname | Credentials are machine-bound — re-run `auth_cli.py login` on the new machine |
234
+
235
+ ---
236
+
237
+ ## 7. Data Security
238
+
239
+ - All API calls are encrypted over HTTPS.
240
+ - Strict tenant isolation between sellers — you can only access your own shop's data.
241
+ - **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.
242
+ - Changing your computer or OS username will invalidate local credentials — simply re-run `auth_cli.py login` to re-authorize.
243
+ - This Skill does not transmit order data to any location outside Miravia's servers.
244
+
245
+ ---
246
+
247
+ ## 8. Feedback
248
+
249
+ This is a Beta release. We welcome your feedback via the Skill Hub questionnaire to help us improve.
package/dist/SKILL.md ADDED
@@ -0,0 +1,329 @@
1
+ ---
2
+ name: miravia-order-report
3
+ description: Query Miravia seller order data via Open API, export filtered orders to Excel/CSV, and generate an HTML business analysis report. Use when the user mentions Miravia orders, order export, order report, refund analysis, GMV analysis, or asks to download/analyze orders from the Miravia seller backend.
4
+ ---
5
+
6
+ # Miravia Order Report
7
+
8
+ A Skill for Miravia (M2A) sellers. Pulls order, sub-order item and reverse-order data from the official Miravia Open API, then produces **different outputs dynamically based on scenario**:
9
+
10
+ | Scenario | Output | Use Case |
11
+ |----------|--------|----------|
12
+ | `inspect` | **stdout text only** (no files) | Seller asks about specific order status/shipping/refund reason |
13
+ | `export` | **Excel/CSV** only | Ops staff fetches raw data for external reporting |
14
+ | `refund` | **v4 unified dashboard HTML** only | Refund reasons, top refund SKUs, refund trends |
15
+ | `business` | **v4 unified dashboard HTML** only | Monthly/weekly report: GMV, AOV, refund rate, recommendations |
16
+ | `auto` | Excel + v4 HTML | Backward compatible; default when intent is unclear |
17
+
18
+ > **Principle: One output type per invocation.** No HTML in export scenarios, no Excel in refund/business scenarios (use `--with-excel` only when explicitly requested).
19
+
20
+ ---
21
+
22
+ ## Scenario Routing (Agent MUST follow)
23
+
24
+ Priority is top-down; stop at first match:
25
+
26
+ | # | User Intent | scenario | Default Params |
27
+ |---|-------------|----------|----------------|
28
+ | 0 | Explicit order ID(s) — status/shipping/refund inquiry | `inspect` | `--order-ids <ids>` |
29
+ | 1 | Refund, return, refund reason/rate analysis | `refund` | `--last-days 30` |
30
+ | 2 | Business analysis, monthly/weekly report, GMV trend | `business` | Full/last month |
31
+ | 3 | Export, download, Excel, pull N days, raw data | `export` | User-specified range |
32
+ | 4 | Unclear intent, wants both | `auto` | Generates both |
33
+
34
+ **Key rules:**
35
+ - `inspect` has **highest priority** — if user provides order IDs, always use `inspect`.
36
+ - `inspect` MUST NOT combine with `--with-excel` or HTML; stdout is the sole output.
37
+ - "Export refund details" → `--scenario refund --with-excel`
38
+ - "Monthly report + raw data" → `--scenario business --with-excel`
39
+
40
+ ---
41
+
42
+ ## Core Constraints (Single Source of Truth)
43
+
44
+ These rules are referenced throughout the workflow. Each is defined **once** here.
45
+
46
+ | ID | Rule | Summary |
47
+ |----|------|---------|
48
+ | C1 | **Time range mandatory** | Non-inspect scenarios require explicit time range. Ambiguous expressions ("recently", "all") → MUST ask user to clarify. |
49
+ | C2 | **countTotal NEVER shown** | API's `countTotal` is unreliable. Agent MUST NEVER display order counts from this field — not in estimates, progress, or summaries. |
50
+ | C3 | **Time estimate first** | Formula: `ceil(orders / 6000)` minutes. Show only time, not count. |
51
+ | C4 | **Status filter confirmation** | Natural language status → present supported status table, ask user to confirm. Technical values (e.g., `--status canceled`) → no confirmation needed. |
52
+ | C5 | **Auto-open browser** | Always auto-open (auth page, HTML report). Only provide URL as fallback if `open` command fails. |
53
+ | C6 | **Executive Summary = LLM-generated** | The script's rule-engine placeholder MUST NOT be delivered directly. Agent must analyze `metrics.json` and inject AI insights. |
54
+ | C7 | **API retry** | Up to 3 retries per API call; report error only after all 3 fail. |
55
+ | C8 | **Volume limit** | Hard cap 200,000 sub-orders. Exceeded → suggest splitting by month/week. |
56
+ | C9 | **Zero data early-stop** | `no_data: true` → stop immediately, inform merchant, do NOT generate files. |
57
+
58
+ ---
59
+
60
+ ## When to Use
61
+
62
+ - "Check order 30502596014 status" → `inspect --order-ids 30502596014`
63
+ - "Export last week's Miravia orders" → `export`
64
+ - "Analyze refund orders for the last 30 days" → `refund`
65
+ - "Generate monthly business report" → `business`
66
+ - "Show unshipped orders" → `export --status all_to_ship` (after status confirmation per C4)
67
+
68
+ ---
69
+
70
+ ## Prerequisites
71
+
72
+ Credentials are sourced exclusively from Skill Hub authorization:
73
+
74
+ > **Staging URL**: `https://pre-sellercenter.miravia.es/apps/seller/skill/auth`
75
+
76
+ First-time setup (from skill root directory):
77
+
78
+ 1. Save private key + `skillCode` from `generateKeyPair` to `.keypair.json` (`chmod 600`).
79
+ 2. One-click authorization:
80
+ ```bash
81
+ python scripts/auth_cli.py login
82
+ ```
83
+ Opens browser → user authorizes → callback writes `credentials.json`.
84
+
85
+ > **Authorization URL format**: The CSRF `state` must be appended as un-encoded `?state=xxx` after the percent-encoded redirect_uri. See [auth_design.md §4.1](auth_design.md#41-authorization-url-cli--browser).
86
+
87
+ > **Callback i18n**: Frontend may append `&lang=xx` (`en`/`es`/`it`) to callback redirect_uri.
88
+
89
+ Utility: `python auth_cli.py status` — check token validity.
90
+
91
+ Production switch: `export MIRAVIA_SKILL_HUB_AUTH_URL=https://sellercenter.miravia.es/apps/seller/skill/auth`
92
+
93
+ If `IncompleteSignature` / `InvalidAccessToken` → ask user to re-run `auth_cli.py login`.
94
+
95
+ ---
96
+
97
+ ## CLI Reference
98
+
99
+ Entry point: [scripts/export_orders.py](scripts/export_orders.py)
100
+
101
+ ```bash
102
+ pip install -r requirements.txt # Install once
103
+
104
+ # Examples
105
+ python scripts/export_orders.py --agent-type qoder --scenario export --last-days 7 --output ./out
106
+ python scripts/export_orders.py --agent-type qoder --scenario refund --last-days 30 --no-open --output ./out
107
+ python scripts/export_orders.py --agent-type qoder --scenario inspect --order-ids 30502596014
108
+ python3 scripts/estimate_time.py --agent-type qoder --last-days 365
109
+ ```
110
+
111
+ ### Flags
112
+
113
+ | Flag | Required | Default | Description |
114
+ |------|----------|---------|-------------|
115
+ | `--agent-type` | **Yes** | — | Agent identifier (`qoder`/`cursor`/`claude`/custom) |
116
+ | `--created-after` | No | today-6d | Start date (YYYY-MM-DD, aligned 00:00:00) |
117
+ | `--created-before` | No | today | End date (YYYY-MM-DD, aligned 23:59:59) |
118
+ | `--last-days` | No | — | Relative range (overrides after/before) |
119
+ | `--status` | No | `all` | Order status filter (see table below) |
120
+ | `--format` | No | `xlsx` | `xlsx` or `csv` |
121
+ | `--output` | No | `./out` | Output directory |
122
+ | `--scenario` | No | `auto` | `inspect`/`export`/`refund`/`business`/`auto` |
123
+ | `--order-ids` | inspect only | — | Comma-separated order IDs |
124
+ | `--with-excel` | No | `false` | Also output Excel in refund/business scenarios |
125
+ | `--lang` | No | auto | Report language: `en`/`es`/`it`/`zh` (auto-detect from conversation) |
126
+ | `--no-open` | No | — | **Mandatory for report scenarios** (Agent opens after Step 5 injection) |
127
+ | `--ping` | No | — | Health check: outputs `ping OK` or `ping FAIL: <reason>` |
128
+
129
+ ### Supported Status Values
130
+
131
+ | Value | Description |
132
+ |-------|-------------|
133
+ | `all` | All orders (no filter) |
134
+ | `all_to_ship` | To Ship (topack + packed + rts) |
135
+ | `all_shipped` | Shipped (shipped + delivered) |
136
+ | `topack` | Awaiting packaging |
137
+ | `packed` | Awaiting pickup |
138
+ | `rts` | Ready to ship |
139
+ | `canceled` | Already canceled |
140
+ | `shipped` | Shipped / Picked up |
141
+ | `delivered` | Delivered |
142
+
143
+ > Only these 9 values are supported. Unsupported status → inform user and present this table (C4).
144
+
145
+ ---
146
+
147
+ ## Agent Workflow
148
+
149
+ > **Windows users**: See [docs/windows_compat.md](docs/windows_compat.md) for Constrained Language Mode bypass.
150
+
151
+ ### Step 1: Parse User Intent
152
+
153
+ Derive: `--agent-type`, `--scenario`, time range, `--status`, `--format`, `--lang`.
154
+
155
+ - **Scenario**: Follow routing table above (highest priority first).
156
+ - **Language** (`--lang`): Auto-detect from conversation language (Chinese→`zh`, English→`en`, Spanish→`es`, Italian→`it`). Only override if user explicitly specifies.
157
+ - **Time range** (C1): Explicit time → use directly. Ambiguous → ask user. "All orders" → confirm scope.
158
+ - Relative: `--last-days N` (e.g., "last 7 days" → `--last-days 7`)
159
+ - Absolute: `--created-after YYYY-MM-DD --created-before YYYY-MM-DD`
160
+ - **Status** (C4): Natural language → present table, ask confirmation. Technical value → use directly.
161
+
162
+ ### Step 2: Pre-flight Credential Check
163
+
164
+ ```bash
165
+ python scripts/export_orders.py --agent-type <TYPE> --ping
166
+ ```
167
+
168
+ - `ping OK` → proceed to Step 3.
169
+ - `ping FAIL` → launch `python scripts/auth_cli.py login` in background (`is_background=true`).
170
+
171
+ **Authorization flow (automation-first, non-negotiable):**
172
+ 1. Agent launches login in background and sends guidance message to user:
173
+ > 🔐 **Browser authorization required** — I've opened the authorization page. Switch to your browser, find "Skill Authorization", and click "Authorize". I'll continue automatically once done.
174
+ 2. Poll with `GetTerminalOutput(terminal_id, wait_seconds=15)`:
175
+ - `[login] OK` → proceed to Step 3.
176
+ - `[login] DECRYPT_FAILED` → inform user of failure.
177
+ - `webbrowser.open failed` or 2 rounds without `callback GET` → enter [VM fallback](docs/vm_fallback.md).
178
+ - >10 rounds without response → prompt user to check browser.
179
+ 3. Do NOT ask user "have you completed authorization" — zero-confirmation wait.
180
+
181
+ ### Step 3: Estimate Time (C2, C3, C9)
182
+
183
+ ```bash
184
+ python3 scripts/estimate_time.py --agent-type <TYPE> [--last-days N | --created-after X --created-before Y] [--status S]
185
+ ```
186
+
187
+ Parse structured output:
188
+ - `upgrade` line: `need_upgrade: false` → proceed silently. `need_upgrade: true` → inform user, offer upgrade/skip choice.
189
+ - `estimate` line: Show only estimated time (e.g., "Estimated ~2 minutes"). **Never show `total_orders`** (C2). If `no_data: true` → stop and inform merchant (C9).
190
+
191
+ ### Step 4: Execute Export
192
+
193
+ ```bash
194
+ python scripts/export_orders.py \
195
+ --agent-type <TYPE> --scenario <S> \
196
+ [--last-days N | --created-after X --created-before Y] \
197
+ [--status S] [--format F] [--with-excel] [--lang LANG] --no-open --output <DIR>
198
+ ```
199
+
200
+ **Execution rules:**
201
+ - Launch in background (`is_background=true`), poll progress every 5-10s.
202
+ - Progress relay: Only show current fetched count (✅ "Fetched 400 orders..." ❌ "Fetched 400/620 orders").
203
+ - Detect `metrics :` line → **stop polling, enter Step 5** (do NOT announce "report complete" yet).
204
+ - `export` scenario (no `metrics :`) → skip to Step 6.
205
+
206
+ ### Step 5: AI Insights Injection (C6, mandatory for refund/business/auto)
207
+
208
+ > **Full specification**: [executive_summary_prompt_v2.md](executive_summary_prompt_v2.md)
209
+
210
+ **① Read** `metrics.json` (path from stdout `metrics :` line).
211
+
212
+ **② Generate** `insights.json` following ALL rules in `executive_summary_prompt_v2.md`:
213
+ - Filename: replace `metrics_` prefix with `insights_` (same timestamp suffix).
214
+ - Schema: `{ "lang": "<code>", "generated_at": "<ISO8601>", "presets": { "0": { "summary", "highlights[]", "actions[]" }, ... } }`
215
+ - Field constraints: `severity` ∈ {`high`, `medium`, `low`}; `priority` ∈ {`P0`, `P1`, `P2`}; `highlights` need `title` + `detail` + `severity`; `actions` need `text` + `priority`.
216
+ - JSON encoding: ASCII quotes only, no smart quotes/em-dashes/currency symbols. See prompt file §1 for full rules.
217
+
218
+ **③ Validate** JSON:
219
+ ```bash
220
+ python3 -c "import json; json.load(open('<insights_path>'))" && echo 'OK'
221
+ ```
222
+
223
+ **④ Inject** into HTML:
224
+ ```bash
225
+ python3 scripts/inject_insights.py --html <report_path> --insights <insights_path>
226
+ ```
227
+
228
+ **⑤ Validate rendering**:
229
+ ```bash
230
+ python3 scripts/validate_render.py <report_path>
231
+ ```
232
+ - `RENDER_CHECK: OK` → proceed to ⑥.
233
+ - `FAIL: ...` → clear insights and re-inject empty (triggers frontend fallback):
234
+ ```bash
235
+ python3 -c "import json; open('<insights_path>','w').write(json.dumps({'presets':{}}))"
236
+ python3 scripts/inject_insights.py --html <report_path> --insights <insights_path>
237
+ ```
238
+
239
+ **⑥ Open report** (C5):
240
+ ```bash
241
+ open <report_path> # macOS
242
+ xdg-open <report_path> # Linux
243
+ ```
244
+
245
+ ### Step 6: Present Results
246
+
247
+ - `export` → "Export file: `<path>`"
248
+ - `refund`/`business`/`auto` → "Report opened in your browser. File path: `<path>`" (only show path if open fails).
249
+ - **Never mention**: pagination, API internals, offset/limit, time-window slicing.
250
+
251
+ ### Step 7: Secondary Filtering
252
+
253
+ If user requests further filtering after export (e.g., "show only Spain orders"):
254
+ - Load exported Excel with pandas, filter locally. Do NOT re-call API.
255
+ - No Excel available → suggest re-run with `--with-excel`.
256
+
257
+ ---
258
+
259
+ ## Inspect Scenario Details
260
+
261
+ - Trigger: User provides order IDs asking about status/shipping/refund.
262
+ - Required: `--order-ids` (comma-separated). No time params needed.
263
+ - Underlying: `/orders/items/get` + `/reverse/getreverseordersforseller` per order.
264
+ - Agent reorganizes stdout into natural language; does NOT paste raw text.
265
+ - "Not found" → that order doesn't belong to the authorized shop.
266
+
267
+ ---
268
+
269
+ ## Data Scope
270
+
271
+ Sub-order granularity, joining three APIs:
272
+
273
+ | API | Purpose |
274
+ |-----|---------|
275
+ | `/orders/get` | Master order (paginated) |
276
+ | `/orders/items/get` | Sub-order items |
277
+ | `/reverse/getreverseordersforseller` | Refund/reverse info |
278
+
279
+ See [reference.md](reference.md) for field mapping and Excel column definitions.
280
+
281
+ ---
282
+
283
+ ## Limits & Guardrails
284
+
285
+ - 200,000 sub-order hard cap (exit code 2) — suggest splitting.
286
+ - Exit code 3 = zero data — inform merchant, suggest adjusting filters.
287
+ - Auto time-window slicing when >1,000 main orders (transparent to user).
288
+ - `/orders/get` page size = 100; offset+limit ≤ 5000 (mitigated by auto-slicing).
289
+ - Credentials AES-256-GCM encrypted at rest, bound to machine fingerprint.
290
+ - Same-name files get `_1`, `_2` suffix to avoid overwriting.
291
+
292
+ ---
293
+
294
+ ## Stdout Format Reference
295
+
296
+ | Prefix | Meaning | Agent Action |
297
+ |--------|---------|--------------|
298
+ | `range :` | Query time range | "Querying orders from X to Y" |
299
+ | `progress: N orders found` | countTotal (inaccurate) | **Internal only, NEVER show** (C2) |
300
+ | `progress: fetched X orders` | Batch progress | "Fetched X orders..." (strip total) |
301
+ | `progress: M main, N sub-order rows` | Final aggregation | "Retrieved M orders, N records" (safe to show) |
302
+ | `output :` | Excel/CSV path | Show to user |
303
+ | `report :` | HTML path | Internal: proceed to Step 5 |
304
+ | `metrics :` | Metrics JSON path | Internal: read for LLM analysis |
305
+ | `injected :` | Injection success | Internal confirmation |
306
+ | `no_data :` | Zero orders | Inform merchant, stop (C9) |
307
+ | `estimate :` | Time estimate JSON | Show only time (C2, C3) |
308
+ | `ping OK/FAIL` | Credential check | Step 2 flow |
309
+
310
+ ---
311
+
312
+ ## HTML Report Structure (v4 Dashboard)
313
+
314
+ 6 interactive tabs: Overview | Sales Performance | Cancellations & Refunds | Product Insights | Buyers & Markets | Logistics & Fulfillment.
315
+
316
+ Features: Platform filter (All/Miravia/M2A), time filter (all/7d/30d), Chart.js CDN (requires internet).
317
+
318
+ ---
319
+
320
+ ## Related Documents
321
+
322
+ | Document | Purpose |
323
+ |----------|---------|
324
+ | [executive_summary_prompt_v2.md](executive_summary_prompt_v2.md) | Authoritative prompt for AI insights generation |
325
+ | [reference.md](reference.md) | API fields & Excel column mapping |
326
+ | [docs/windows_compat.md](docs/windows_compat.md) | Windows Constrained Language Mode bypass |
327
+ | [docs/vm_fallback.md](docs/vm_fallback.md) | VM/sandbox authorization fallback |
328
+ | [README.md](README.md) | Seller-side installation & authorization guide |
329
+ | [auth_design.md](auth_design.md) | Authorization URL format specification |
package/dist/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.13