Amitkasar commited on
Commit
f1c3c6d
·
1 Parent(s): 1e24842

solved issue

Browse files
.claude/settings.local.json CHANGED
@@ -23,7 +23,10 @@
23
  "Bash(python -c \"import ast, sys; content = open\\('backend/integrations/llm/client.py'\\).read\\(\\); ast.parse\\(content\\); print\\('client.py: OK'\\)\")",
24
  "Bash(python -c \"import ast; [print\\(f'{f}: OK'\\) or ast.parse\\(open\\(f\\).read\\(\\)\\) for f in ['backend/database.py','backend/main.py','backend/services/asset_service.py','backend/app/api/routes/execution.py','backend/app/api/routes/chat.py','backend/app/api/routes/usage.py','backend/core/config.py']]\")",
25
  "Bash(python *)",
26
- "Bash(del *)"
 
 
 
27
  ]
28
  }
29
  }
 
23
  "Bash(python -c \"import ast, sys; content = open\\('backend/integrations/llm/client.py'\\).read\\(\\); ast.parse\\(content\\); print\\('client.py: OK'\\)\")",
24
  "Bash(python -c \"import ast; [print\\(f'{f}: OK'\\) or ast.parse\\(open\\(f\\).read\\(\\)\\) for f in ['backend/database.py','backend/main.py','backend/services/asset_service.py','backend/app/api/routes/execution.py','backend/app/api/routes/chat.py','backend/app/api/routes/usage.py','backend/core/config.py']]\")",
25
  "Bash(python *)",
26
+ "Bash(del *)",
27
+ "Bash(node test_hosted.js)",
28
+ "Bash(curl -s -o /dev/null -w \"%{http_code}\" --cookie \"PHPSESSID=6iaecoahpl756qt8o39f1kepvd\" \"https://staging.excelhearing.co.uk/crm-dev/backend/admin_api.php?action=me\")",
29
+ "Bash(curl -s http://localhost:8001/api/v1/specs)"
30
  ]
31
  }
32
  }
Plans/multi-llm-configuration.md CHANGED
@@ -240,7 +240,7 @@ State managed locally, saved on blur/submit.
240
  2. Alembic migration — create both tables, seed `llm_task_config` with 4 rows (provider_id=NULL)
241
  3. `registry.py`, `providers.py`, `factory.py` — pure logic, no DB
242
  4. `resolver.py` — ties DB + factory together
243
- 5. Update 4 service files — swap import, add `db` param
244
  6. `settings.py` route — CRUD + cache invalidation
245
  7. Wire router in `main.py`
246
  8. Frontend settings tab
 
240
  2. Alembic migration — create both tables, seed `llm_task_config` with 4 rows (provider_id=NULL)
241
  3. `registry.py`, `providers.py`, `factory.py` — pure logic, no DB
242
  4. `resolver.py` — ties DB + factory together
243
+ 5. Update 4 service files — swap import, add `db` param
244
  6. `settings.py` route — CRUD + cache invalidation
245
  7. Wire router in `main.py`
246
  8. Frontend settings tab
Plans/plan 6.md ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Plan 6 — Real ID Resolution for Path & Body Parameters
2
+
3
+ > **Problem:** Some API calls require real IDs (e.g. `bus_id`, `product_id`, `seat_id`) embedded
4
+ > directly in the URL or request body. These IDs cannot be guessed or randomly generated by the AI —
5
+ > they must come from a prior API response or be provided manually by the user.
6
+ > This plan covers detection, planner-level fixes, executor-level guards, and frontend handling.
7
+ >
8
+ > **Scope:** Backend (`llm_planner.py`, `api_executor.py`, `execution.py`, `schemas.py`) +
9
+ > Frontend (`WorkflowPage.jsx`, `SelectionModal.jsx`, `services/api.js`)
10
+ >
11
+ > **Status:** Completed — 2026-05-10
12
+
13
+ ---
14
+
15
+ ## Table of Contents
16
+
17
+ 1. [Problem Statement](#1-problem-statement)
18
+ 2. [Root Cause Analysis](#2-root-cause-analysis)
19
+ 3. [Solution Architecture](#3-solution-architecture)
20
+ 4. [Phase 1 — Schemas](#4-phase-1--schemas)
21
+ 5. [Phase 2 — Planner Prompt](#5-phase-2--planner-prompt)
22
+ 6. [Phase 3 — Executor Guard](#6-phase-3--executor-guard)
23
+ 7. [Phase 4 — Frontend Intercept](#7-phase-4--frontend-intercept)
24
+ 8. [Phase 5 — SelectionModal Manual Input Mode](#8-phase-5--selectionmodal-manual-input-mode)
25
+ 9. [End-to-End Flow](#9-end-to-end-flow)
26
+ 10. [File-by-File Changes](#10-file-by-file-changes)
27
+ 11. [Execution Checklist](#11-execution-checklist)
28
+
29
+ ---
30
+
31
+ ## 1. Problem Statement
32
+
33
+ When the AI builds an HTTP request in `api_executor.py`, it fills path/body parameters using
34
+ this priority order (from `STEP_PROMPT`):
35
+
36
+ ```
37
+ Priority 1: Context Variables (from previous steps)
38
+ Priority 2: User Credentials
39
+ Priority 3: Step Definition / Scenario data
40
+ ```
41
+
42
+ **Two failure scenarios:**
43
+
44
+ **Scenario A — ID needed at step 1, context is empty**
45
+ ```
46
+ Step 1: POST /buses/{bus_id}/book
47
+ Context: {} ← empty, no prior steps ran
48
+
49
+ AI hallucinates: bus_id = 123
50
+ API returns: 404 Not Found
51
+ ```
52
+
53
+ **Scenario B — ID comes from a list, AI picks wrong one**
54
+ ```
55
+ Step 1: GET /buses → returns [{ id: 42, name: "Express" }, { id: 99, name: "Local" }]
56
+ Step 2: POST /bookings → needs bus_id
57
+
58
+ Analyzer sets is_selection_required: true ✅ (already works)
59
+ BUT: if analyzer is skipped or times out, executor uses bus_id = 42 blindly
60
+ ```
61
+
62
+ **Result in both cases:** The test fails not because the API is broken, but because the AI used
63
+ a fake or wrong ID. This gives false negatives and makes the tool unreliable for real-world APIs.
64
+
65
+ ---
66
+
67
+ ## 2. Root Cause Analysis
68
+
69
+ ### Why the planner doesn't catch it
70
+
71
+ `llm_planner.py` receives a condensed spec (method + path + summary only) and generates a plan.
72
+ It has no instruction to detect unresolvable path parameters or insert prerequisite fetch steps.
73
+
74
+ The current `PLANNER_PROMPT` says nothing about:
75
+ - Detecting `{param}` in endpoint paths that require real DB values
76
+ - Inserting a GET/list step before a step that needs a real ID
77
+ - Flagging which context keys each step depends on
78
+
79
+ ### Why the executor doesn't block it
80
+
81
+ `api_executor.py` (`STEP_PROMPT`) says:
82
+ > "You MUST replace all path variables like `{id}` or `{bus_id}` with actual values from Context
83
+ > or Step Definition."
84
+
85
+ But it does **not** say what to do when the value is genuinely missing. The AI guesses.
86
+ There is no sentinel value, no guard in `execution.py`, and no way for the frontend to know
87
+ that an ID was hallucinated.
88
+
89
+ ### Why the existing selection flow isn't enough
90
+
91
+ `response_analyzer.py` already detects `is_selection_required` after a GET/list step responds.
92
+ This works — but only when:
93
+ 1. A list-returning step ran immediately before
94
+ 2. The analyzer ran successfully (not timed out or parse-failed)
95
+ 3. The planner actually included the prerequisite GET step
96
+
97
+ When any of these conditions fails, the executor proceeds with a guessed ID.
98
+
99
+ ---
100
+
101
+ ## 3. Solution Architecture
102
+
103
+ The fix has four layers working together:
104
+
105
+ ```
106
+ ┌─────────────────────────────────────────────────────────┐
107
+ │ LAYER 1: Planner (llm_planner.py) │
108
+ │ Detects unresolvable path params at plan-generation │
109
+ │ time. Inserts prerequisite GET steps automatically. │
110
+ │ Adds required_context_keys to each StepDefinition. │
111
+ └─────────────────────────────────────────────────────────┘
112
+ ↓
113
+ ┌─────────────────────────────────────────────────────────┐
114
+ │ LAYER 2: Executor (api_executor.py) │
115
+ │ Emits "__MISSING__{param}__" sentinel when a required │
116
+ │ path/body param is absent from context, instead of │
117
+ │ hallucinating a value. │
118
+ └─────────────────────────────────────────────────────────┘
119
+ ↓
120
+ ┌─────────────────────────────────────────────────────────┐
121
+ │ LAYER 3: Route Guard (execution.py) │
122
+ │ Detects "__MISSING__" in the resolved URL or body. │
123
+ │ Returns HTTP 400 with a structured error instead of │
124
+ │ firing a broken request to the real API. │
125
+ └─────────────────────────────────────────────────────────┘
126
+ ↓
127
+ ┌─────────────────────────────────────────────────────────┐
128
+ │ LAYER 4: Frontend (WorkflowPage + SelectionModal) │
129
+ │ Intercepts the 400 / missing-key detection before │
130
+ │ calling execute-step. Shows a manual input modal. │
131
+ │ User provides the real ID → saved to context → │
132
+ │ execution proceeds with the real value. │
133
+ └─────────────────────────────────────────────────────────┘
134
+ ```
135
+
136
+ ---
137
+
138
+ ## 4. Phase 1 — Schemas
139
+
140
+ **File:** `backend/schemas.py`
141
+
142
+ Add `required_context_keys` to `StepDefinition` so the planner can annotate each step
143
+ with the context keys it needs that cannot be auto-generated.
144
+
145
+ ### Change
146
+
147
+ ```python
148
+ # BEFORE
149
+ class StepDefinition(BaseModel):
150
+ step: int
151
+ endpoint: str
152
+ purpose: str
153
+
154
+ # AFTER
155
+ class StepDefinition(BaseModel):
156
+ step: int
157
+ endpoint: str
158
+ purpose: str
159
+ required_context_keys: Optional[List[str]] = []
160
+ # e.g. ["bus_id", "route_id"] — keys that must exist in context before this step runs
161
+ # populated by the planner when a path/body param cannot be resolved automatically
162
+ ```
163
+
164
+ No DB migration needed — `StepDefinition` is only used in `execution_plan` (JSON column in
165
+ `SpecDocument`) and in request/response Pydantic models. The `[]` default is backward-compatible
166
+ with existing saved plans.
167
+
168
+ ---
169
+
170
+ ## 5. Phase 2 — Planner Prompt
171
+
172
+ **File:** `backend/services/llm_planner.py`
173
+
174
+ ### 2a — Update PLANNER_PROMPT
175
+
176
+ Add two new rules at the end of the existing `PLANNER_PROMPT`:
177
+
178
+ ```python
179
+ PLANNER_PROMPT = """
180
+ ... (existing content) ...
181
+
182
+ DEPENDENCY RULE (CRITICAL):
183
+ - Inspect every endpoint in your plan for path parameters (e.g. {bus_id}, {product_id}, {seat_id}).
184
+ - If a path parameter cannot be known in advance (not in USER CREDENTIALS, not a UUID to generate,
185
+ not derivable from a prior step in THIS plan), you MUST insert a GET/list step immediately before
186
+ the step that needs it. That GET step should fetch the list of available options.
187
+ - Example: "POST /buses/{bus_id}/book" at step 1 → insert "GET /buses" at step 1, shift booking to step 2.
188
+ - Example: "GET /routes/{route_id}/stops" where route_id comes from a previous GET /routes → no insertion needed.
189
+
190
+ REQUIRED_CONTEXT_KEYS RULE:
191
+ - For each step, set "required_context_keys" to a list of context variable names that MUST be present
192
+ before this step can run and that the AI cannot safely generate (real IDs, external references).
193
+ - If the step needs no special context, set "required_context_keys" to [].
194
+ - Example: step "POST /bookings/{bus_id}" → required_context_keys: ["bus_id"]
195
+ - Example: step "POST /auth/login" with email/password from credentials → required_context_keys: []
196
+ """
197
+ ```
198
+
199
+ ### 2b — Update the expected JSON format in the prompt
200
+
201
+ ```json
202
+ {
203
+ "execution_plan": [
204
+ {
205
+ "step": 1,
206
+ "endpoint": "GET /buses",
207
+ "purpose": "Fetch available buses so user can select a real bus_id",
208
+ "required_context_keys": []
209
+ },
210
+ {
211
+ "step": 2,
212
+ "endpoint": "POST /buses/{bus_id}/book",
213
+ "purpose": "Book the selected bus",
214
+ "required_context_keys": ["bus_id"]
215
+ }
216
+ ],
217
+ "suggested_credentials": { ... }
218
+ }
219
+ ```
220
+
221
+ ### 2c — No changes to `generate_execution_plan()` function
222
+
223
+ The existing `JsonOutputParser` + retry logic handles the new field automatically since
224
+ `StepDefinition` now includes `required_context_keys`. No function body changes needed.
225
+
226
+ ---
227
+
228
+ ## 6. Phase 3 — Executor Guard
229
+
230
+ ### 3a — STEP_PROMPT addition
231
+
232
+ **File:** `backend/services/api_executor.py`
233
+
234
+ Add this rule to `STEP_PROMPT` after the existing "NO TEMPLATE STRINGS" rule:
235
+
236
+ ```
237
+ MISSING ID RULE (CRITICAL):
238
+ - If a required path parameter (e.g. {bus_id}) or required body field is an ID that is NOT present
239
+ in Context Variables and cannot be reasonably generated (it is a real DB record ID, not a UUID
240
+ you create), do NOT guess a value.
241
+ - Instead, set the parameter to the literal string "__MISSING__{param_name}__"
242
+ (e.g. "__MISSING__bus_id__") so the caller can detect and block execution.
243
+ - Examples of IDs you MUST NOT guess: bus_id, product_id, order_id, seat_id, route_id, ticket_id.
244
+ - Examples of IDs you CAN generate: new UUIDs for user registration, random test email addresses.
245
+ ```
246
+
247
+ ### 3b — Guard in execution route
248
+
249
+ **File:** `backend/app/api/routes/execution.py`
250
+
251
+ After `prepare_step_request` returns, add a guard before the HTTP call:
252
+
253
+ ```python
254
+ # After: req_plan, executor_token_usage = await asyncio.to_thread(prepare_step_request, ...)
255
+
256
+ # Guard: detect sentinel values that mean the AI couldn't resolve a real ID
257
+ import re as _re
258
+ _MISSING_PATTERN = _re.compile(r"__MISSING__(\w+)__")
259
+
260
+ missing_in_url = _MISSING_PATTERN.findall(req_plan.request.url)
261
+ missing_in_body = _MISSING_PATTERN.findall(json.dumps(req_plan.request.body or {}))
262
+ all_missing = list(set(missing_in_url + missing_in_body))
263
+
264
+ if all_missing:
265
+ raise HTTPException(
266
+ status_code=400,
267
+ detail={
268
+ "error": "missing_context_keys",
269
+ "message": f"Step requires real IDs that are not in context: {all_missing}. "
270
+ f"Please provide them manually before executing this step.",
271
+ "missing_keys": all_missing,
272
+ }
273
+ )
274
+ ```
275
+
276
+ This surfaces a clean, structured error to the frontend instead of sending a broken request
277
+ to the real API.
278
+
279
+ ---
280
+
281
+ ## 7. Phase 4 — Frontend Intercept
282
+
283
+ **File:** `frontend-react/src/pages/WorkflowPage.jsx`
284
+
285
+ ### 4a — Pre-execution check using `required_context_keys`
286
+
287
+ Before calling `PlanService.executeStep()`, check if the step's `required_context_keys`
288
+ are all present in `sessionContextVars`:
289
+
290
+ ```javascript
291
+ const executeStep = async (stepDef) => {
292
+ // NEW: Check for required context keys before attempting execution
293
+ const requiredKeys = stepDef.required_context_keys || [];
294
+ const missingKeys = requiredKeys.filter(key => !sessionContextVars[key]);
295
+
296
+ if (missingKeys.length > 0) {
297
+ setSelectionPrompt({
298
+ type: 'manual_input',
299
+ step: stepDef,
300
+ missingKeys,
301
+ // No options — user must type the real value
302
+ });
303
+ return; // Don't proceed until user provides the values
304
+ }
305
+
306
+ // existing execution logic continues...
307
+ setExecutingStep(stepDef.step);
308
+ try { ... }
309
+ };
310
+ ```
311
+
312
+ ### 4b — Handle `missing_context_keys` error from backend
313
+
314
+ The executor guard (Phase 3) returns HTTP 400 with `error: "missing_context_keys"`.
315
+ Catch this in the executeStep error handler:
316
+
317
+ ```javascript
318
+ } catch (err) {
319
+ // NEW: Handle structured missing-key error from backend
320
+ if (err.response?.data?.error === 'missing_context_keys') {
321
+ const missing = err.response.data.missing_keys || [];
322
+ setSelectionPrompt({
323
+ type: 'manual_input',
324
+ step: stepDef,
325
+ missingKeys: missing,
326
+ });
327
+ return;
328
+ }
329
+ // existing error handling...
330
+ addToast('error', err.message || 'Step execution failed.');
331
+ }
332
+ ```
333
+
334
+ ### 4c — Handle manual input confirmation
335
+
336
+ When the user submits values in the manual input modal, save each key to context and retry:
337
+
338
+ ```javascript
339
+ const handleManualInputConfirm = async (values) => {
340
+ // values = { bus_id: "42", route_id: "7" }
341
+ for (const [key, value] of Object.entries(values)) {
342
+ await SessionService.updateContext(sessionId, key, value);
343
+ }
344
+ await refreshSessionContext(); // reload sessionContextVars from DB
345
+ setSelectionPrompt(null);
346
+
347
+ // Retry the step now that context is populated
348
+ await executeStep(selectionPrompt.step);
349
+ };
350
+ ```
351
+
352
+ ---
353
+
354
+ ## 8. Phase 5 — SelectionModal Manual Input Mode
355
+
356
+ **File:** `frontend-react/src/components/workflow/SelectionModal.jsx`
357
+
358
+ The existing `SelectionModal` handles `is_selection_required` (picking from a list).
359
+ Add a second mode: `manual_input` (user types in unknown IDs).
360
+
361
+ ### New prop: `type`
362
+
363
+ ```
364
+ type = 'selection' → existing behavior (radio list from selection_options)
365
+ type = 'manual_input' → new behavior (text inputs for each missing key)
366
+ ```
367
+
368
+ ### New render branch
369
+
370
+ ```jsx
371
+ {type === 'manual_input' && (
372
+ <div className="manual-input-section">
373
+ <p className="modal-description">
374
+ This step requires real IDs that could not be determined automatically.
375
+ Please enter the correct values from your system or database.
376
+ </p>
377
+ {missingKeys.map(key => (
378
+ <div key={key} className="input-row">
379
+ <label className="input-label">{key}</label>
380
+ <input
381
+ type="text"
382
+ className="input-field"
383
+ placeholder={`Enter real value for ${key}`}
384
+ value={inputValues[key] || ''}
385
+ onChange={e => setInputValues(prev => ({ ...prev, [key]: e.target.value }))}
386
+ />
387
+ </div>
388
+ ))}
389
+ <div className="modal-actions">
390
+ <button
391
+ className="btn-primary"
392
+ disabled={missingKeys.some(k => !inputValues[k]?.trim())}
393
+ onClick={() => onConfirm(inputValues)}
394
+ >
395
+ Save & Execute
396
+ </button>
397
+ <button className="btn-secondary" onClick={onClose}>Cancel</button>
398
+ </div>
399
+ </div>
400
+ )}
401
+ ```
402
+
403
+ The `disabled` check ensures the user can't confirm with empty fields — every missing key
404
+ must be filled before execution proceeds.
405
+
406
+ ---
407
+
408
+ ## 9. End-to-End Flow
409
+
410
+ ### Flow A — Planner inserts prerequisite step (happy path)
411
+
412
+ ```
413
+ User uploads spec with: POST /buses/{bus_id}/book
414
+
415
+ Planner runs (with new DEPENDENCY RULE)
416
+ └── Detects {bus_id} in path, not in credentials, no prior step provides it
417
+ └── Inserts: Step 1 = GET /buses (purpose: "fetch available buses")
418
+ └── Original becomes: Step 2 = POST /buses/{bus_id}/book
419
+ required_context_keys: ["bus_id"]
420
+
421
+ User executes Step 1 (GET /buses)
422
+ └── Response: [{ id: 42, name: "Express" }, { id: 99, name: "Local" }]
423
+ └── Analyzer: is_selection_required = true, selection_options = [...]
424
+ └── SelectionModal (existing behavior) appears → user picks Bus 42
425
+ └── bus_id = 42 saved to context
426
+
427
+ User executes Step 2 (POST /buses/42/book)
428
+ └── Frontend pre-check: required_context_keys = ["bus_id"], context has bus_id ✅
429
+ └── Executor: finds bus_id=42 in context → URL resolves to /buses/42/book
430
+ └── Real API call succeeds ✅
431
+ ```
432
+
433
+ ### Flow B — ID needed at step 1, no list endpoint exists in spec
434
+
435
+ ```
436
+ User uploads spec with only: POST /bookings/{bus_id}
437
+ (No GET /buses endpoint in this spec)
438
+
439
+ Planner runs
440
+ └── Tries to insert GET /buses but it's not in spec → cannot insert
441
+ └── Marks Step 1 required_context_keys: ["bus_id"]
442
+ └── Step 1: POST /bookings/{bus_id}, required_context_keys: ["bus_id"]
443
+
444
+ User clicks Execute on Step 1
445
+ └── Frontend pre-check: required_context_keys = ["bus_id"]
446
+ └── sessionContextVars has no bus_id → missingKeys = ["bus_id"]
447
+ └── SelectionModal opens in manual_input mode
448
+ └── User types: bus_id = "42" (from their own system/dashboard)
449
+ └── SessionService.updateContext(sessionId, "bus_id", "42") called
450
+ └── context refreshed → bus_id = 42 now in sessionContextVars
451
+
452
+ User clicks Execute again (auto-triggered after modal confirm)
453
+ └── Frontend pre-check: bus_id ✅ in context
454
+ └── Executor resolves URL to /bookings/42
455
+ └── Real API call succeeds ✅
456
+ ```
457
+
458
+ ### Flow C — Executor catches a hallucinated ID (safety net)
459
+
460
+ ```
461
+ (Planner didn't insert a prerequisite step, and required_context_keys is empty/missing)
462
+
463
+ Executor prompt receives: context = {}, step = POST /buses/{bus_id}/book
464
+
465
+ With new MISSING ID RULE:
466
+ └── AI cannot find bus_id in context
467
+ └── AI sets URL to: /buses/__MISSING__bus_id__/book
468
+
469
+ execution.py guard fires:
470
+ └── Detects "__MISSING__bus_id__" in URL
471
+ └── Returns HTTP 400: { error: "missing_context_keys", missing_keys: ["bus_id"] }
472
+
473
+ Frontend catches 400:
474
+ └── Opens SelectionModal in manual_input mode
475
+ └── User provides bus_id → context updated → step retried ✅
476
+ ```
477
+
478
+ ---
479
+
480
+ ## 10. File-by-File Changes
481
+
482
+ | File | Change | Effort |
483
+ |------|--------|--------|
484
+ | `backend/schemas.py` | Add `required_context_keys: Optional[List[str]] = []` to `StepDefinition` | 5 min |
485
+ | `backend/services/llm_planner.py` | Add DEPENDENCY RULE + REQUIRED_CONTEXT_KEYS RULE to `PLANNER_PROMPT`. Update JSON format example. | 20 min |
486
+ | `backend/services/api_executor.py` | Add MISSING ID RULE to `STEP_PROMPT` | 10 min |
487
+ | `backend/app/api/routes/execution.py` | Add `__MISSING__` sentinel guard after `prepare_step_request` | 15 min |
488
+ | `frontend-react/src/pages/WorkflowPage.jsx` | Add pre-execution `required_context_keys` check. Add `missing_context_keys` error handler. Add `handleManualInputConfirm`. | 30 min |
489
+ | `frontend-react/src/components/workflow/SelectionModal.jsx` | Add `manual_input` mode with text inputs per missing key | 20 min |
490
+
491
+ **Total estimated effort: ~1.5 hours**
492
+
493
+ No database migrations required.
494
+ No new dependencies required.
495
+ No new API endpoints required.
496
+
497
+ ---
498
+
499
+ ## 11. Execution Checklist
500
+
501
+ ### Backend
502
+
503
+ - [x] `schemas.py` — add `required_context_keys` field to `StepDefinition`
504
+ - [x] `llm_planner.py` — add DEPENDENCY RULE to `PLANNER_PROMPT`
505
+ - [x] `llm_planner.py` — add REQUIRED_CONTEXT_KEYS RULE to `PLANNER_PROMPT`
506
+ - [x] `llm_planner.py` — update JSON format example to include `required_context_keys`
507
+ - [x] `api_executor.py` — add MISSING ID RULE to `STEP_PROMPT`
508
+ - [x] `execution.py` — add `__MISSING__` sentinel detection guard
509
+ - [x] `execution.py` — return structured `{ error: "missing_context_keys", missing_keys: [...] }`
510
+
511
+ ### Frontend
512
+
513
+ - [x] `WorkflowPage.jsx` — add `required_context_keys` pre-execution check in `executeStep`
514
+ - [x] `WorkflowPage.jsx` — add `missing_context_keys` error catch + trigger manual input modal
515
+ - [x] `WorkflowPage.jsx` — add `handleManualInputConfirm` (saves each key to context, retries step)
516
+ - [x] `SelectionModal.jsx` — add `manual_input` mode prop
517
+ - [x] `SelectionModal.jsx` — render text inputs for each `missingKey`
518
+ - [x] `SelectionModal.jsx` — disable confirm button until all fields are filled
519
+
520
+ ### Testing
521
+
522
+ - [ ] Test with a spec where step 1 has a path param (e.g. `GET /items/{item_id}`)
523
+ - [ ] Verify planner inserts a prerequisite GET step automatically
524
+ - [ ] Verify `required_context_keys` appears correctly on the dependent step
525
+ - [ ] Test manual input modal appears when context is empty and keys are required
526
+ - [ ] Test values entered in modal are saved to context via `SessionService.updateContext`
527
+ - [ ] Test step auto-retries with correct context after modal confirm
528
+ - [ ] Test `__MISSING__` sentinel triggers the 400 guard (for cases planner misses)
529
+ - [ ] Test the 400 error triggers the manual input modal as a fallback
530
+
531
+ ---
532
+
533
+ *Plan 6 | Real ID Resolution | Completed 2026-05-10 | Est. 1.5 hrs*
Plans/plan 7.md ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Plan 7 — Cookie Management (Postman-style)
2
+
3
+ > **Problem:** Many real-world APIs set cookies in `Set-Cookie` response headers (session tokens,
4
+ > CSRF tokens, auth cookies) and expect those cookies to be sent back in the `Cookie` header on
5
+ > subsequent requests. The app currently captures response headers but does nothing with
6
+ > `Set-Cookie`. Cookies are never forwarded, so any API that relies on cookie-based sessions
7
+ > will fail from step 2 onward.
8
+ >
9
+ > **Scope:** Backend (`execution.py`, `response_analyzer.py`, `api_executor.py`, `schemas.py`,
10
+ > `context_manager.py`, `database.py`) + Frontend (`WorkflowPage.jsx`, `ContextPanel.jsx`,
11
+ > `StepCard.jsx`)
12
+ >
13
+ > **Status:** Not started
14
+
15
+ ---
16
+
17
+ ## Table of Contents
18
+
19
+ 1. [Problem Statement](#1-problem-statement)
20
+ 2. [How Postman Handles Cookies](#2-how-postman-handles-cookies)
21
+ 3. [Root Cause Analysis](#3-root-cause-analysis)
22
+ 4. [Solution Architecture](#4-solution-architecture)
23
+ 5. [Phase 1 — Cookie Jar in Session Context](#5-phase-1--cookie-jar-in-session-context)
24
+ 6. [Phase 2 — Extract Cookies from Responses](#6-phase-2--extract-cookies-from-responses)
25
+ 7. [Phase 3 — Forward Cookies on Requests](#7-phase-3--forward-cookies-on-requests)
26
+ 8. [Phase 4 — Teach the Executor About Cookies](#8-phase-4--teach-the-executor-about-cookies)
27
+ 9. [Phase 5 — Frontend Cookie Visibility](#9-phase-5--frontend-cookie-visibility)
28
+ 10. [Edge Cases](#10-edge-cases)
29
+ 11. [End-to-End Flow](#11-end-to-end-flow)
30
+ 12. [File-by-File Changes](#12-file-by-file-changes)
31
+ 13. [Execution Checklist](#13-execution-checklist)
32
+
33
+ ---
34
+
35
+ ## 1. Problem Statement
36
+
37
+ A typical cookie-based auth flow looks like this:
38
+
39
+ ```
40
+ Step 1: POST /auth/login
41
+ → Response headers: Set-Cookie: session_id=abc123; HttpOnly; Path=/
42
+ → Response body: { "message": "Login successful" }
43
+
44
+ Step 2: GET /user/profile
45
+ → Request headers: Cookie: session_id=abc123 ← MUST be sent
46
+ → Response body: { "name": "Amit", ... }
47
+ ```
48
+
49
+ **What the app does today:**
50
+
51
+ ```
52
+ Step 1: POST /auth/login
53
+ → Response captured: { status_code: 200, body: "...", headers: { "set-cookie": "session_id=abc123..." } }
54
+ → set-cookie is saved in resp_data["headers"] but NOTHING HAPPENS WITH IT
55
+
56
+ Step 2: GET /user/profile
57
+ → Request built by AI with no Cookie header
58
+ → API returns: 401 Unauthorized ← false negative
59
+ ```
60
+
61
+ The test fails not because the API is broken — the AI simply never learned about the cookie.
62
+
63
+ This affects every API that uses:
64
+ - Session-based authentication (`session_id`, `PHPSESSID`, `connect.sid`)
65
+ - CSRF protection (`csrftoken`, `XSRF-TOKEN`)
66
+ - Remember-me tokens
67
+ - Any cookie set by frameworks (Django, Rails, Laravel, Express)
68
+
69
+ ---
70
+
71
+ ## 2. How Postman Handles Cookies
72
+
73
+ Postman has a **Cookie Jar** — a per-domain store of cookies that works like a browser:
74
+
75
+ 1. Every response's `Set-Cookie` headers are parsed and stored in the jar.
76
+ 2. Every subsequent request to the same domain automatically includes all matching cookies
77
+ in the `Cookie` header, respecting `Path`, `Domain`, and expiry.
78
+ 3. The Cookie Jar is visible in the Postman UI — users can view, edit, and delete cookies.
79
+ 4. Cookies persist across requests in a collection run (equivalent to our session).
80
+
81
+ **Our implementation goal:** replicate this behavior within a session.
82
+
83
+ We won't implement full browser-level cookie spec (no `SameSite`, no expiry enforcement,
84
+ no cross-domain matching) — the pragmatic scope is:
85
+
86
+ - Parse `Set-Cookie` from every response
87
+ - Store cookies per domain in the session's context
88
+ - Forward all matching cookies on every subsequent request to the same domain
89
+ - Show cookies in the UI (ContextPanel)
90
+ - Allow the AI executor to know cookies exist and reference them
91
+
92
+ ---
93
+
94
+ ## 3. Root Cause Analysis
95
+
96
+ ### Why cookies are lost today
97
+
98
+ In `execution.py`, the response is captured as:
99
+
100
+ ```python
101
+ resp_data = {
102
+ "status_code": response.status_code,
103
+ "body": body_text,
104
+ "headers": dict(response.headers), # set-cookie IS here
105
+ }
106
+ ```
107
+
108
+ `dict(response.headers)` with httpx only returns the **last** `Set-Cookie` value if multiple
109
+ cookies are set (httpx uses a case-insensitive multi-dict internally). The cookies are in
110
+ `headers["set-cookie"]` but:
111
+
112
+ 1. Nothing parses them out of the header string
113
+ 2. Nothing saves them to the session's `context_variables`
114
+ 3. The executor (`api_executor.py`) has no instruction to include a `Cookie` header
115
+ 4. The response analyzer (`response_analyzer.py`) has no instruction to extract cookies
116
+
117
+ ### Why the AI doesn't add Cookie headers
118
+
119
+ `STEP_PROMPT` in `api_executor.py` says to use Authorization headers for auth — but says
120
+ nothing about cookies. The AI has no way to know a cookie was set in a prior step unless it's
121
+ explicitly in the context variables and the prompt tells it to use cookies.
122
+
123
+ ### Why `response_analyzer.py` doesn't catch cookies
124
+
125
+ `ANALYSIS_PROMPT` only looks at the response body. It has no instruction to inspect
126
+ `Set-Cookie` headers and extract them as context variables.
127
+
128
+ ---
129
+
130
+ ## 4. Solution Architecture
131
+
132
+ ```
133
+ ┌──────────────────────────────────────────────────────────────────┐
134
+ │ STEP EXECUTION (execution.py) │
135
+ │ │
136
+ │ After response received: │
137
+ │ 1. Call parse_cookies(response) → { name: value, ... } │
138
+ │ 2. Merge into session's cookie_jar: { "api.example.com": {...} }│
139
+ │ 3. Save cookie_jar back to session context_variables │
140
+ │ 4. Include cookies in resp_data for frontend display │
141
+ └──────────────────────────────────────────────────────────────────┘
142
+ ↑ reads before request ↓ writes after response
143
+ ┌──────────────────────────────────────────────────────────────────┐
144
+ │ COOKIE JAR (context_variables["__cookie_jar__"]) │
145
+ │ │
146
+ │ Structure: │
147
+ │ { │
148
+ │ "api.example.com": { │
149
+ │ "session_id": "abc123", │
150
+ │ "csrftoken": "xyz789" │
151
+ │ } │
152
+ │ } │
153
+ │ Stored as a special key in the existing JSON context column. │
154
+ │ No schema migration needed. │
155
+ └──────────────────────────────────────────────────────────────────┘
156
+ ↑ reads before request
157
+ ┌──────────────────────────────────────────────────────────────────┐
158
+ │ REQUEST BUILDING (execution.py, before executor call) │
159
+ │ │
160
+ │ Before calling prepare_step_request: │
161
+ │ 1. Extract hostname from base_url │
162
+ │ 2. Look up cookie_jar[hostname] │
163
+ │ 3. Build Cookie header string: "session_id=abc123; csrf=xyz" │
164
+ │ 4. Inject into context_variables as "__cookies__" key │
165
+ │ 5. Executor sees "__cookies__" and adds Cookie header │
166
+ └──────────────────────────────────────────────────────────────────┘
167
+ ↓ visible in
168
+ ┌──────────────────────────────────────────────────────────────────┐
169
+ │ FRONTEND (ContextPanel.jsx, StepCard.jsx) │
170
+ │ │
171
+ │ ContextPanel: shows cookie jar entries under "Cookies" section │
172
+ │ StepCard: shows "Cookie" header in sent request panel │
173
+ │ shows parsed Set-Cookie in response headers panel │
174
+ └──────────────────────────────────────────────────────────────────┘
175
+ ```
176
+
177
+ **Key design decision:** We store the cookie jar in `context_variables["__cookie_jar__"]`.
178
+ This reuses the existing JSON column, the existing `set_context_variables` function, and the
179
+ existing `GET /context/{session_id}` endpoint. No DB migration. No new tables. No new API
180
+ endpoints.
181
+
182
+ ---
183
+
184
+ ## 5. Phase 1 — Cookie Jar in Session Context
185
+
186
+ **File:** `backend/services/context_manager.py`
187
+
188
+ Add two helper functions that read/write the cookie jar within the existing `context_variables`
189
+ JSON column. The jar key is `__cookie_jar__` — double underscores to avoid collision with
190
+ real API-extracted variables.
191
+
192
+ ### New helpers
193
+
194
+ ```python
195
+ COOKIE_JAR_KEY = "__cookie_jar__"
196
+
197
+ def get_cookie_jar(db: Session, session_id: str) -> dict:
198
+ """Returns the full cookie jar: { hostname: { name: value } }"""
199
+ context = get_context(db, session_id)
200
+ return context.get(COOKIE_JAR_KEY, {})
201
+
202
+
203
+ def set_cookies_for_host(db: Session, session_id: str, hostname: str, cookies: dict) -> None:
204
+ """Merge new cookies for a hostname into the jar. Existing cookies for other
205
+ hosts are preserved. Existing cookies for this host are merged (not replaced)."""
206
+ context = get_context(db, session_id)
207
+ jar = context.get(COOKIE_JAR_KEY, {})
208
+ if hostname not in jar:
209
+ jar[hostname] = {}
210
+ jar[hostname].update(cookies)
211
+ set_context_variables(db, session_id, {COOKIE_JAR_KEY: jar})
212
+
213
+
214
+ def get_cookies_for_host(db: Session, session_id: str, hostname: str) -> dict:
215
+ """Returns cookies for a specific hostname. Returns {} if none."""
216
+ jar = get_cookie_jar(db, session_id)
217
+ return jar.get(hostname, {})
218
+
219
+
220
+ def clear_cookies_for_host(db: Session, session_id: str, hostname: str) -> None:
221
+ """Remove all cookies for a hostname (e.g. after logout)."""
222
+ context = get_context(db, session_id)
223
+ jar = context.get(COOKIE_JAR_KEY, {})
224
+ jar.pop(hostname, None)
225
+ set_context_variables(db, session_id, {COOKIE_JAR_KEY: jar})
226
+ ```
227
+
228
+ ### Cookie parsing utility
229
+
230
+ Add a standalone parser (no external dependency — Python's stdlib `http.cookies` handles this):
231
+
232
+ ```python
233
+ from http.cookies import SimpleCookie
234
+ from urllib.parse import urlparse
235
+
236
+ def parse_set_cookie_headers(headers: dict) -> dict:
237
+ """
238
+ Parse Set-Cookie header(s) from a response headers dict.
239
+ httpx collapses multiple Set-Cookie values with a comma separator in some versions,
240
+ so we handle both the single-value and multi-value cases.
241
+
242
+ Returns: { cookie_name: cookie_value } — just name/value, no attributes.
243
+ """
244
+ cookies = {}
245
+ raw = headers.get("set-cookie", "")
246
+ if not raw:
247
+ return cookies
248
+
249
+ # httpx may join multiple Set-Cookie headers with \n
250
+ for line in raw.split("\n"):
251
+ line = line.strip()
252
+ if not line:
253
+ continue
254
+ try:
255
+ c = SimpleCookie()
256
+ c.load(line)
257
+ for name, morsel in c.items():
258
+ cookies[name] = morsel.value
259
+ except Exception:
260
+ # Malformed cookie — skip, don't crash
261
+ pass
262
+
263
+ return cookies
264
+
265
+
266
+ def hostname_from_url(url: str) -> str:
267
+ """Extract just the hostname from a full URL."""
268
+ try:
269
+ return urlparse(url).hostname or ""
270
+ except Exception:
271
+ return ""
272
+ ```
273
+
274
+ **Why stdlib `SimpleCookie` instead of a library:**
275
+ No new dependency. `SimpleCookie` handles the `name=value; Path=/; HttpOnly` format correctly.
276
+ We only need name + value — we ignore `Path`, `Domain`, `Expires`, `HttpOnly`, `Secure` for now.
277
+
278
+ ---
279
+
280
+ ## 6. Phase 2 — Extract Cookies from Responses
281
+
282
+ **File:** `backend/app/api/routes/execution.py`
283
+
284
+ After the HTTP response is received and `resp_data` is built, add cookie extraction:
285
+
286
+ ```python
287
+ from backend.services.context_manager import (
288
+ set_cookies_for_host, get_cookies_for_host,
289
+ parse_set_cookie_headers, hostname_from_url
290
+ )
291
+
292
+ # After: resp_data = { "status_code": ..., "body": ..., "headers": ... }
293
+
294
+ # NEW: Extract and persist any Set-Cookie headers from this response
295
+ response_cookies = parse_set_cookie_headers(dict(response.headers))
296
+ if response_cookies:
297
+ host = hostname_from_url(url)
298
+ if host:
299
+ set_cookies_for_host(db, body.session_id, host, response_cookies)
300
+ logger.info(
301
+ "Step %s set %d cookie(s) for host '%s': %s",
302
+ req_plan.step, len(response_cookies), host, list(response_cookies.keys())
303
+ )
304
+
305
+ # Add cookies to resp_data so frontend can display them
306
+ resp_data["cookies"] = response_cookies # { name: value } — sanitized for display
307
+ ```
308
+
309
+ This is the only place where `Set-Cookie` headers are parsed. It happens immediately after
310
+ every step execution, before the DB write, so the cookies are available for the next step.
311
+
312
+ **Important:** `httpx` by default does **not** follow redirects or share a cookie jar between
313
+ requests (each `AsyncClient` is independent). We handle the jar manually, which gives us
314
+ full visibility and control — matching Postman's behavior.
315
+
316
+ ---
317
+
318
+ ## 7. Phase 3 — Forward Cookies on Requests
319
+
320
+ **File:** `backend/app/api/routes/execution.py`
321
+
322
+ Before calling `prepare_step_request`, look up any stored cookies for the target host
323
+ and inject them into the context variables that get passed to the executor:
324
+
325
+ ```python
326
+ from backend.services.context_manager import get_cookies_for_host, hostname_from_url
327
+
328
+ # After: effective_credentials resolved, before: step_llm = get_llm_for_task(...)
329
+
330
+ # NEW: Look up cookies for this host and inject into context for the executor
331
+ host = hostname_from_url(body.base_url)
332
+ host_cookies = get_cookies_for_host(db, body.session_id, host)
333
+
334
+ # Build context that includes cookies as a special key
335
+ execution_context = dict(body.context_variables or {})
336
+ if host_cookies:
337
+ # Format as a ready-to-use Cookie header string
338
+ cookie_header_value = "; ".join(f"{k}={v}" for k, v in host_cookies.items())
339
+ execution_context["__cookie_header__"] = cookie_header_value
340
+ logger.info(
341
+ "Injecting %d cookie(s) for step %s: %s",
342
+ len(host_cookies), req_plan_step_num, list(host_cookies.keys())
343
+ )
344
+
345
+ # Pass execution_context (with cookies) instead of body.context_variables
346
+ step_llm = get_llm_for_task("step_execution", db)
347
+ req_plan, executor_token_usage = await asyncio.to_thread(
348
+ prepare_step_request,
349
+ ...
350
+ context_variables=execution_context, # ← was: body.context_variables
351
+ ...
352
+ )
353
+ ```
354
+
355
+ The executor now sees `__cookie_header__` in its context variables and will include it
356
+ as the `Cookie` header (taught in Phase 4).
357
+
358
+ ---
359
+
360
+ ## 8. Phase 4 — Teach the Executor About Cookies
361
+
362
+ **File:** `backend/services/api_executor.py`
363
+
364
+ Add an explicit rule to `STEP_PROMPT` so the AI knows how to handle cookies:
365
+
366
+ ```
367
+ COOKIE RULE:
368
+ - If Context Variables contains the key "__cookie_header__", you MUST include it as the
369
+ value of the "Cookie" request header. Do not modify or reformat it.
370
+ - Example: if __cookie_header__ = "session_id=abc123; csrftoken=xyz", add:
371
+ "headers": { "Cookie": "session_id=abc123; csrftoken=xyz" }
372
+ - Never include a Cookie header if __cookie_header__ is absent from context.
373
+ - Some APIs also require CSRF tokens in the request body or as a separate header
374
+ (e.g. "X-CSRFToken"). If the spec requires this and a csrftoken cookie exists,
375
+ include it in the appropriate location as well.
376
+ ```
377
+
378
+ This is the minimal change. The AI doesn't need to know about the cookie jar structure —
379
+ it just sees a pre-built `Cookie` header string and adds it.
380
+
381
+ **Why pre-build the string in execution.py instead of letting the AI build it:**
382
+ The AI would need to know the cookie jar format, filter by domain, format correctly, etc.
383
+ By building `__cookie_header__` in execution.py, we keep the AI's job simple — it just
384
+ copies a string into a header. Less hallucination risk, more reliable.
385
+
386
+ ---
387
+
388
+ ## 9. Phase 5 — Frontend Cookie Visibility
389
+
390
+ ### 9a — ContextPanel.jsx
391
+
392
+ **File:** `frontend-react/src/components/workflow/ContextPanel.jsx`
393
+
394
+ The `ContextPanel` already shows `sessionContextVars`. Add a dedicated "Cookies" section
395
+ that reads `__cookie_jar__` from context and renders it cleanly, separate from regular
396
+ context variables:
397
+
398
+ ```jsx
399
+ // Filter out internal keys from the regular context display
400
+ const regularVars = Object.entries(sessionContextVars || {})
401
+ .filter(([k]) => !k.startsWith('__'));
402
+
403
+ // Parse cookie jar
404
+ const cookieJar = sessionContextVars?.['__cookie_jar__'] || {};
405
+ const allCookies = Object.entries(cookieJar).flatMap(([host, cookies]) =>
406
+ Object.entries(cookies).map(([name, value]) => ({ host, name, value }))
407
+ );
408
+
409
+ // In render:
410
+ {allCookies.length > 0 && (
411
+ <div className="context-section">
412
+ <div className="context-section-title">
413
+ 🍪 Cookies ({allCookies.length})
414
+ </div>
415
+ {allCookies.map(({ host, name, value }) => (
416
+ <div className="context-row" key={`${host}-${name}`}>
417
+ <span className="context-key">{name}</span>
418
+ <span className="context-eq">=</span>
419
+ <span className="context-val">{value.slice(0, 50)}{value.length > 50 ? '…' : ''}</span>
420
+ <span className="context-host">{host}</span>
421
+ </div>
422
+ ))}
423
+ </div>
424
+ )}
425
+ ```
426
+
427
+ ### 9b — StepCard.jsx
428
+
429
+ **File:** `frontend-react/src/components/workflow/StepCard.jsx`
430
+
431
+ The StepCard already shows request headers and response body. Add two small enhancements:
432
+
433
+ **1. Show sent Cookie header in request section:**
434
+
435
+ ```jsx
436
+ {res.request.headers?.Cookie && (
437
+ <>
438
+ <span className="kv-label">Cookies Sent</span>
439
+ <div className="kv-block" style={{ marginBottom: 8 }}>
440
+ {res.request.headers.Cookie.split('; ').map(pair => {
441
+ const [k, ...rest] = pair.split('=');
442
+ return (
443
+ <div className="kv-row" key={k}>
444
+ <span className="k">{k}:</span>
445
+ <span className="v">{rest.join('=')}</span>
446
+ </div>
447
+ );
448
+ })}
449
+ </div>
450
+ </>
451
+ )}
452
+ ```
453
+
454
+ **2. Show received cookies in response section:**
455
+
456
+ ```jsx
457
+ {res.response?.cookies && Object.keys(res.response.cookies).length > 0 && (
458
+ <>
459
+ <span className="kv-label">Cookies Received</span>
460
+ <div className="kv-block" style={{ marginBottom: 8 }}>
461
+ {Object.entries(res.response.cookies).map(([k, v]) => (
462
+ <div className="kv-row" key={k}>
463
+ <span className="k">{k}:</span>
464
+ <span className="v">{v}</span>
465
+ <span style={{ fontSize: 10, color: 'var(--fg-3)', marginLeft: 6 }}>saved</span>
466
+ </div>
467
+ ))}
468
+ </div>
469
+ </>
470
+ )}
471
+ ```
472
+
473
+ The "saved" label confirms to the user that the cookie was persisted to the jar.
474
+
475
+ ---
476
+
477
+ ## 10. Edge Cases
478
+
479
+ ### Multiple Set-Cookie headers
480
+
481
+ HTTP allows multiple `Set-Cookie` response headers (one per cookie). `httpx` collapses
482
+ these differently depending on version. The `parse_set_cookie_headers` function
483
+ handles this by splitting on `\n` and parsing each line individually.
484
+
485
+ ### CSRF tokens (double-submit cookie pattern)
486
+
487
+ Many APIs (Django, Rails) use CSRF protection where:
488
+ - `Set-Cookie: csrftoken=abc` is sent in a response
489
+ - Subsequent POST/PUT/DELETE requests must send both:
490
+ - `Cookie: csrftoken=abc` (in the cookie header)
491
+ - `X-CSRFToken: abc` (in a custom header) or `_token: abc` (in request body)
492
+
493
+ The `COOKIE RULE` in Phase 4 already handles the `Cookie` header. For the additional
494
+ header/body injection, the AI executor already handles this naturally if the spec
495
+ documents it — and the `__cookie_header__` context gives it the raw values to reference.
496
+
497
+ ### Cookie expiry / logout
498
+
499
+ Cookies are stored in the session's context_variables. When the session is cleared
500
+ (existing `DELETE /session/{id}` route) or a new plan is generated (`startNewSession()`
501
+ is called in WorkflowPage), the context is wiped — so all cookies are cleared. This matches
502
+ Postman's behavior of resetting the cookie jar per collection run.
503
+
504
+ For explicit logout detection: if a response sets a cookie with an empty value
505
+ (`Set-Cookie: session_id=; Max-Age=0`), the parser will store `session_id = ""`
506
+ which will send `Cookie: session_id=` — effectively a cleared cookie. This is correct behavior.
507
+
508
+ ### `HttpOnly` cookies
509
+
510
+ `HttpOnly` is a browser security attribute — it prevents JavaScript from reading the cookie.
511
+ It has no meaning in our server-side context. We correctly ignore it and store/forward
512
+ all cookies regardless of `HttpOnly` or `Secure` flags.
513
+
514
+ ### Multiple domains in one test
515
+
516
+ If a test calls `api.example.com` and also `auth.example.com`, cookies are stored
517
+ per-hostname so they don't cross-contaminate. The `hostname_from_url(body.base_url)`
518
+ lookup in Phase 3 will match cookies to the base URL's host only.
519
+
520
+ ---
521
+
522
+ ## 11. End-to-End Flow
523
+
524
+ ### Cookie-based session auth (Django/Rails/Express)
525
+
526
+ ```
527
+ User uploads spec: POST /auth/login, GET /dashboard, POST /logout
528
+
529
+ Step 1: POST /auth/login
530
+ Request: { "username": "amit", "password": "..." }
531
+ Response: 200 OK
532
+ Set-Cookie: sessionid=abc123xyz; HttpOnly; Path=/
533
+ Set-Cookie: csrftoken=def456; Path=/
534
+ Body: { "message": "Logged in" }
535
+
536
+ execution.py:
537
+ → parse_set_cookie_headers(headers)
538
+ → { "sessionid": "abc123xyz", "csrftoken": "def456" }
539
+ → set_cookies_for_host(db, session_id, "api.example.com",
540
+ { "sessionid": "abc123xyz", "csrftoken": "def456" })
541
+ → resp_data["cookies"] = { "sessionid": "abc123xyz", "csrftoken": "def456" }
542
+
543
+ ContextPanel shows:
544
+ 🍪 Cookies (2)
545
+ sessionid = abc123xyz api.example.com
546
+ csrftoken = def456 api.example.com
547
+
548
+ StepCard shows:
549
+ Cookies Received
550
+ sessionid: abc123xyz [saved]
551
+ csrftoken: def456 [saved]
552
+
553
+ Step 2: GET /dashboard
554
+ execution.py (before executor call):
555
+ → get_cookies_for_host(db, session_id, "api.example.com")
556
+ → { "sessionid": "abc123xyz", "csrftoken": "def456" }
557
+ → execution_context["__cookie_header__"] = "sessionid=abc123xyz; csrftoken=def456"
558
+
559
+ Executor (api_executor.py):
560
+ → Sees __cookie_header__ in context
561
+ → COOKIE RULE: include as Cookie header
562
+ → Request headers: { "Cookie": "sessionid=abc123xyz; csrftoken=def456" }
563
+
564
+ Request: GET /dashboard
565
+ Cookie: sessionid=abc123xyz; csrftoken=def456
566
+ Response: 200 OK
567
+ Body: { "name": "Amit", "dashboard": [...] }
568
+
569
+ StepCard shows:
570
+ Cookies Sent
571
+ sessionid: abc123xyz
572
+ csrftoken: def456
573
+
574
+ Step 3: POST /logout
575
+ → Same Cookie header forwarded
576
+ → Server clears session (may respond with Set-Cookie: sessionid=; Max-Age=0)
577
+ → Cookie jar updated: sessionid = ""
578
+ ```
579
+
580
+ ### JWT + Cookie hybrid (some APIs return JWT in a cookie)
581
+
582
+ ```
583
+ Step 1: POST /auth/login
584
+ Response: Set-Cookie: access_token=eyJhbG...; HttpOnly
585
+
586
+ Cookie jar: { "api.example.com": { "access_token": "eyJhbG..." } }
587
+
588
+ Step 2: GET /protected
589
+ Cookie header: access_token=eyJhbG...
590
+ → API accepts cookie-based JWT ✅
591
+ ```
592
+
593
+ ---
594
+
595
+ ## 12. File-by-File Changes
596
+
597
+ | File | Change | Effort |
598
+ |------|--------|--------|
599
+ | `backend/services/context_manager.py` | Add `parse_set_cookie_headers`, `hostname_from_url`, `get_cookie_jar`, `set_cookies_for_host`, `get_cookies_for_host`, `clear_cookies_for_host` | 30 min |
600
+ | `backend/app/api/routes/execution.py` | Phase 2: extract cookies after response. Phase 3: inject `__cookie_header__` into context before executor call | 25 min |
601
+ | `backend/services/api_executor.py` | Add COOKIE RULE to `STEP_PROMPT` | 10 min |
602
+ | `frontend-react/src/components/workflow/ContextPanel.jsx` | Add Cookies section, filter `__` keys from regular vars display | 20 min |
603
+ | `frontend-react/src/components/workflow/StepCard.jsx` | Show "Cookies Sent" in request panel. Show "Cookies Received" in response panel | 15 min |
604
+
605
+ **Total estimated effort: ~1.5 hours**
606
+
607
+ No database migrations required.
608
+ No new API endpoints required.
609
+ No new dependencies required (uses stdlib `http.cookies`).
610
+
611
+ ---
612
+
613
+ ## 13. Execution Checklist
614
+
615
+ ### Backend
616
+
617
+ - [ ] `context_manager.py` — add `COOKIE_JAR_KEY = "__cookie_jar__"` constant
618
+ - [ ] `context_manager.py` — add `parse_set_cookie_headers(headers: dict) -> dict`
619
+ - [ ] `context_manager.py` — add `hostname_from_url(url: str) -> str`
620
+ - [ ] `context_manager.py` — add `get_cookie_jar(db, session_id) -> dict`
621
+ - [ ] `context_manager.py` — add `set_cookies_for_host(db, session_id, hostname, cookies)`
622
+ - [ ] `context_manager.py` — add `get_cookies_for_host(db, session_id, hostname) -> dict`
623
+ - [ ] `context_manager.py` — add `clear_cookies_for_host(db, session_id, hostname)`
624
+ - [ ] `execution.py` — import new cookie helpers from `context_manager`
625
+ - [ ] `execution.py` — after response: call `parse_set_cookie_headers` and `set_cookies_for_host`
626
+ - [ ] `execution.py` — add `resp_data["cookies"]` with parsed cookie dict
627
+ - [ ] `execution.py` — before executor: call `get_cookies_for_host` and build `__cookie_header__`
628
+ - [ ] `execution.py` — pass `execution_context` (with `__cookie_header__`) to `prepare_step_request`
629
+ - [ ] `api_executor.py` — add COOKIE RULE to `STEP_PROMPT`
630
+
631
+ ### Frontend
632
+
633
+ - [ ] `ContextPanel.jsx` — filter `__` prefixed keys from regular context vars display
634
+ - [ ] `ContextPanel.jsx` — add dedicated "🍪 Cookies" section that reads `__cookie_jar__`
635
+ - [ ] `ContextPanel.jsx` — show hostname alongside each cookie entry
636
+ - [ ] `StepCard.jsx` — add "Cookies Sent" section in request panel (parse `Cookie` header)
637
+ - [ ] `StepCard.jsx` — add "Cookies Received" section in response panel (from `resp_data.cookies`)
638
+
639
+ ### Testing
640
+
641
+ - [ ] Test with a Django/Rails/Express API that uses session cookies
642
+ - [ ] Verify `Set-Cookie` from step 1 appears in ContextPanel under Cookies section
643
+ - [ ] Verify step 2 request includes correct `Cookie` header
644
+ - [ ] Verify step 2 succeeds (200) where it previously failed (401)
645
+ - [ ] Test with multiple cookies set in one response
646
+ - [ ] Test CSRF token forwarding (cookie + X-CSRFToken header)
647
+ - [ ] Test cookie jar is cleared when a new session is started (`startNewSession`)
648
+ - [ ] Test `__cookie_jar__` key is hidden from regular context vars display in ContextPanel
649
+ - [ ] Test StepCard shows "saved" badge next to received cookies
650
+
651
+ ---
652
+
653
+ *Plan 7 | Cookie Management | Not started | Est. 1.5 hrs*
backend/app/api/routes/execution.py CHANGED
@@ -3,7 +3,7 @@ import json
3
  import os
4
  import re
5
  import traceback
6
- from urllib.parse import parse_qsl, urlparse
7
 
8
  import httpx
9
  from fastapi import APIRouter, Depends, HTTPException, Request
@@ -18,7 +18,9 @@ from backend.core.logging import get_logger
18
  from backend.core.url_guard import resolve_safe_ip
19
  from backend.services.api_executor import prepare_step_request
20
  from backend.services.asset_service import AssetService, storage
21
- from backend.services.context_manager import set_context_variables
 
 
22
  from backend.integrations.llm.resolver import get_llm_for_task
23
  from backend.services.llm_planner import generate_execution_plan
24
  from backend.services.response_analyzer import analyze_api_response
@@ -93,6 +95,35 @@ def _is_placeholder(url: str) -> bool:
93
  return False
94
 
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  @router.post("/plan", response_model=schemas.ExecutionPlan)
97
  @limiter.limit("10/minute")
98
  async def generate_plan(request: Request, body: schemas.PlanRequest, db: Session = Depends(database.get_db)):
@@ -272,6 +303,8 @@ async def execute_step(request: Request, body: schemas.ExecuteStepRequest, db: S
272
  effective_credentials = decrypt_credentials(spec.login_credentials)
273
  logger.info("Using stored credentials for spec '%s'", spec.name)
274
 
 
 
275
  step_llm = get_llm_for_task("step_execution", db)
276
  req_plan, executor_token_usage = await asyncio.to_thread(
277
  prepare_step_request,
@@ -279,48 +312,111 @@ async def execute_step(request: Request, body: schemas.ExecuteStepRequest, db: S
279
  base_url=body.base_url,
280
  scenario="",
281
  step_definition=body.step_definition,
282
- context_variables=body.context_variables,
283
  user_credentials=effective_credentials,
284
  available_assets=rich_assets,
285
  llm=step_llm,
286
  )
287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  url = req_plan.request.url.strip()
289
  if url.startswith("/"):
290
  url = body.base_url.rstrip("/") + url
 
291
  elif _is_placeholder(url):
292
  parsed = urlparse(url)
293
  path = parsed.path or "/"
294
  url = body.base_url.rstrip("/") + path
295
  if parsed.query:
296
  url += "?" + parsed.query
297
- logger.info("Placeholder URL replaced: %s", url)
298
  elif not url.startswith("http"):
299
  url = f"https://{url}"
 
 
 
300
 
 
 
301
  parsed = urlparse(url)
302
- if parsed.query:
303
- url_keys = {k for k, _ in parse_qsl(parsed.query)}
304
- for k in [k for k in req_plan.request.query_params if k in url_keys]:
305
- del req_plan.request.query_params[k]
 
 
 
 
 
 
 
 
 
 
 
 
 
306
 
307
  # Resolve IP once to block private/internal addresses (SSRF guard).
308
  # We use the original hostname URL for the actual request so TLS certificate
309
  # verification works correctly against the hostname (not the raw IP).
310
  resolve_safe_ip(url)
311
 
312
- async with httpx.AsyncClient(timeout=120.0) as client:
313
- req_headers = dict(req_plan.request.headers)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
  http_req = client.build_request(
316
  method=req_plan.request.method.strip().upper(),
317
- url=url,
318
  headers=req_headers,
319
- params=req_plan.request.query_params,
320
  data=req_plan.request.form_data if req_plan.request.form_data else None,
321
  json=req_plan.request.body if req_plan.request.body and not req_plan.request.form_data else None,
322
  )
323
 
 
 
 
 
 
 
 
 
 
 
324
  files_payload = {}
325
  opened_files = []
326
  try:
@@ -347,9 +443,8 @@ async def execute_step(request: Request, body: schemas.ExecuteStepRequest, db: S
347
  if files_payload:
348
  response = await client.request(
349
  method=req_plan.request.method.strip().upper(),
350
- url=url,
351
  headers=req_headers,
352
- params=req_plan.request.query_params,
353
  data=req_plan.request.form_data if req_plan.request.form_data else None,
354
  files=files_payload,
355
  )
@@ -378,11 +473,20 @@ async def execute_step(request: Request, body: schemas.ExecuteStepRequest, db: S
378
  "headers": dict(response.headers),
379
  }
380
 
 
 
 
 
 
 
 
 
 
381
  # Log a clear error line for 4xx/5xx so it's visible in the backend console
382
  if response.status_code >= 400:
383
  snippet = body_text[:300].replace("\n", " ")
384
  logger.warning(
385
- "Step %s returned %s from %s: %s",
386
  req_plan.step, response.status_code, url, snippet,
387
  )
388
 
 
3
  import os
4
  import re
5
  import traceback
6
+ from urllib.parse import parse_qsl, urlencode, urlparse
7
 
8
  import httpx
9
  from fastapi import APIRouter, Depends, HTTPException, Request
 
18
  from backend.core.url_guard import resolve_safe_ip
19
  from backend.services.api_executor import prepare_step_request
20
  from backend.services.asset_service import AssetService, storage
21
+ from backend.services.context_manager import (
22
+ set_context_variables,
23
+ )
24
  from backend.integrations.llm.resolver import get_llm_for_task
25
  from backend.services.llm_planner import generate_execution_plan
26
  from backend.services.response_analyzer import analyze_api_response
 
95
  return False
96
 
97
 
98
+ def _strip_phantom_path(url: str, base_url: str) -> str:
99
+ """Remove path segments the LLM appended beyond a file-based base URL.
100
+
101
+ Single-file APIs (e.g. admin_api.php) route via ?action=, not URL paths.
102
+ When the OpenAPI spec defines /auth/me and the LLM appends that to
103
+ admin_api.php, the result is admin_api.php/auth/me which 404s.
104
+ We detect this by checking whether the base URL's last path segment has
105
+ a file extension — if so, strip any extra segments the LLM added.
106
+ """
107
+ try:
108
+ base_parsed = urlparse(base_url if "://" in base_url else "https://" + base_url)
109
+ base_file = base_parsed.path.rstrip("/").split("/")[-1]
110
+ # Only act when base URL ends with a file (has an extension)
111
+ if "." not in base_file:
112
+ return url
113
+ base_path = base_parsed.path.rstrip("/")
114
+ url_parsed = urlparse(url)
115
+ if url_parsed.path.startswith(base_path) and url_parsed.path != base_path:
116
+ from urllib.parse import urlunparse
117
+ # Preserve the query string — the caller's merged_query will merge it
118
+ # with any explicit query_params from the LLM, so action= etc. survive.
119
+ fixed = urlunparse(url_parsed._replace(path=base_path))
120
+ logger.info("Stripped phantom path '%s' → '%s'", url, fixed)
121
+ return fixed
122
+ except Exception:
123
+ pass
124
+ return url
125
+
126
+
127
  @router.post("/plan", response_model=schemas.ExecutionPlan)
128
  @limiter.limit("10/minute")
129
  async def generate_plan(request: Request, body: schemas.PlanRequest, db: Session = Depends(database.get_db)):
 
303
  effective_credentials = decrypt_credentials(spec.login_credentials)
304
  logger.info("Using stored credentials for spec '%s'", spec.name)
305
 
306
+ execution_context = dict(body.context_variables or {})
307
+
308
  step_llm = get_llm_for_task("step_execution", db)
309
  req_plan, executor_token_usage = await asyncio.to_thread(
310
  prepare_step_request,
 
312
  base_url=body.base_url,
313
  scenario="",
314
  step_definition=body.step_definition,
315
+ context_variables=execution_context,
316
  user_credentials=effective_credentials,
317
  available_assets=rich_assets,
318
  llm=step_llm,
319
  )
320
 
321
+ # Guard: detect sentinel values that mean the AI couldn't resolve a real ID
322
+ _MISSING_PATTERN = re.compile(r"__MISSING__(\w+)__")
323
+ missing_in_url = _MISSING_PATTERN.findall(req_plan.request.url)
324
+ missing_in_body = _MISSING_PATTERN.findall(json.dumps(req_plan.request.body or {}))
325
+ all_missing = list(set(missing_in_url + missing_in_body))
326
+ if all_missing:
327
+ raise HTTPException(
328
+ status_code=400,
329
+ detail={
330
+ "error": "missing_context_keys",
331
+ "message": f"Step requires real IDs that are not in context: {all_missing}. Please provide them manually before executing this step.",
332
+ "missing_keys": all_missing,
333
+ },
334
+ )
335
+
336
  url = req_plan.request.url.strip()
337
  if url.startswith("/"):
338
  url = body.base_url.rstrip("/") + url
339
+ logger.info("[ROUTE] Relative URL resolved to: %s", url)
340
  elif _is_placeholder(url):
341
  parsed = urlparse(url)
342
  path = parsed.path or "/"
343
  url = body.base_url.rstrip("/") + path
344
  if parsed.query:
345
  url += "?" + parsed.query
346
+ logger.info("[ROUTE] Placeholder URL replaced : %s", url)
347
  elif not url.startswith("http"):
348
  url = f"https://{url}"
349
+ logger.info("[ROUTE] Scheme-prefixed URL : %s", url)
350
+
351
+ url = _strip_phantom_path(url, body.base_url)
352
 
353
+ # Merge query params from the URL and from the LLM's query_params dict into
354
+ # a single authoritative dict, then strip the query string from the URL.
355
  parsed = urlparse(url)
356
+ merged_query = dict(parse_qsl(parsed.query))
357
+ merged_query.update(req_plan.request.query_params or {})
358
+ url_no_query = url.split("?")[0]
359
+ logger.info("[ROUTE] URL (no query) : %s", url_no_query)
360
+ logger.info("[ROUTE] Merged query : %s", merged_query)
361
+
362
+ # PHP single-file APIs that read the action from php://input instead of $_GET:
363
+ # inject action into the JSON body for mutating methods only. GET requests
364
+ # pass action via query string ($_GET) — adding a body to GET is non-standard
365
+ # and may confuse the server or proxies.
366
+ _method_upper = req_plan.request.method.strip().upper()
367
+ if url_no_query.endswith(".php") and "action" in merged_query and _method_upper != "GET":
368
+ _action = merged_query["action"]
369
+ if isinstance(req_plan.request.body, dict):
370
+ req_plan.request.body.setdefault("action", _action)
371
+ elif req_plan.request.body is None:
372
+ req_plan.request.body = {"action": _action}
373
 
374
  # Resolve IP once to block private/internal addresses (SSRF guard).
375
  # We use the original hostname URL for the actual request so TLS certificate
376
  # verification works correctly against the hostname (not the raw IP).
377
  resolve_safe_ip(url)
378
 
379
+ async with httpx.AsyncClient(timeout=120.0, follow_redirects=True) as client:
380
+ req_headers = {k: v for k, v in req_plan.request.headers.items() if k.lower() != "cookie"}
381
+
382
+ # Browser User-Agent to pass WAF/Cloudflare checks.
383
+ if not any(k.lower() == "user-agent" for k in req_headers):
384
+ req_headers["User-Agent"] = (
385
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
386
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
387
+ "Chrome/120.0.0.0 Safari/537.36"
388
+ )
389
+
390
+ if not any(k.lower() == "accept" for k in req_headers):
391
+ req_headers["Accept"] = "application/json"
392
+
393
+ if not any(k.lower() == "accept-language" for k in req_headers):
394
+ req_headers["Accept-Language"] = "en-US,en;q=0.9"
395
+
396
+ # Embed query params directly into the URL string — same approach as
397
+ # the Node.js test script which hardcodes ?action=me in the URL literal.
398
+ final_url = (
399
+ f"{url_no_query}?{urlencode(merged_query)}" if merged_query else url_no_query
400
+ )
401
 
402
  http_req = client.build_request(
403
  method=req_plan.request.method.strip().upper(),
404
+ url=final_url,
405
  headers=req_headers,
 
406
  data=req_plan.request.form_data if req_plan.request.form_data else None,
407
  json=req_plan.request.body if req_plan.request.body and not req_plan.request.form_data else None,
408
  )
409
 
410
+ # Log the ACTUAL URL and headers httpx will send — check backend console
411
+ logger.info("="*70)
412
+ logger.info("[ROUTE] >>> OUTGOING %s %s", http_req.method, http_req.url)
413
+ logger.info("[ROUTE] >>> HEADERS %s", dict(http_req.headers))
414
+ if req_plan.request.body:
415
+ logger.info("[ROUTE] >>> BODY %s", json.dumps(req_plan.request.body))
416
+ if req_plan.request.form_data:
417
+ logger.info("[ROUTE] >>> FORMDATA %s", json.dumps(req_plan.request.form_data))
418
+ logger.info("="*70)
419
+
420
  files_payload = {}
421
  opened_files = []
422
  try:
 
443
  if files_payload:
444
  response = await client.request(
445
  method=req_plan.request.method.strip().upper(),
446
+ url=final_url,
447
  headers=req_headers,
 
448
  data=req_plan.request.form_data if req_plan.request.form_data else None,
449
  files=files_payload,
450
  )
 
473
  "headers": dict(response.headers),
474
  }
475
 
476
+ resp_data["cookies"] = {}
477
+
478
+ # Log incoming response — always visible in terminal
479
+ logger.info("="*70)
480
+ logger.info("[ROUTE] <<< INCOMING STATUS %s from %s", response.status_code, url_no_query)
481
+ logger.info("[ROUTE] <<< RESPONSE HEADERS %s", dict(response.headers))
482
+ logger.info("[ROUTE] <<< RESPONSE BODY (first 1000 chars):\n%s", body_text[:1000])
483
+ logger.info("="*70)
484
+
485
  # Log a clear error line for 4xx/5xx so it's visible in the backend console
486
  if response.status_code >= 400:
487
  snippet = body_text[:300].replace("\n", " ")
488
  logger.warning(
489
+ "[ROUTE] Step %s returned %s from %s: %s",
490
  req_plan.step, response.status_code, url, snippet,
491
  )
492
 
backend/app/api/routes/specs.py CHANGED
@@ -49,18 +49,27 @@ async def upload_spec(file: UploadFile = File(...), db: Session = Depends(databa
49
  await file.seek(0)
50
  storage.save(file.file, file_path)
51
 
 
 
 
52
  spec_doc = database.SpecDocument(
53
  id=spec_id,
54
  name=file.filename,
55
  raw_content=decoded_content,
56
  parsed_json=safe_spec,
57
  file_path=file_path,
 
58
  )
59
  db.add(spec_doc)
60
  db.commit()
61
 
62
  safe_spec["id"] = spec_id
63
- return {"status": "success", "spec_id": spec_id, "parsed_spec": safe_spec}
 
 
 
 
 
64
  except Exception as e:
65
  logger.error("Failed to parse spec: %s", traceback.format_exc())
66
  raise HTTPException(status_code=400, detail=f"Failed to parse spec: {str(e)}")
@@ -145,7 +154,11 @@ def save_credentials(spec_id: str, payload: schemas.CredentialUpdate, db: Sessio
145
  db.refresh(spec)
146
  return {"status": "cleared", "credentials": {}}
147
 
148
- current: dict = dict(spec.login_credentials or {})
 
 
 
 
149
  if payload.name is not None:
150
  current["name"] = payload.name
151
  if payload.username is not None:
 
49
  await file.seek(0)
50
  storage.save(file.file, file_path)
51
 
52
+ # Auto-populate base URL from the spec's servers list if present
53
+ auto_base_url = safe_spec.get("suggested_base_url") or ""
54
+
55
  spec_doc = database.SpecDocument(
56
  id=spec_id,
57
  name=file.filename,
58
  raw_content=decoded_content,
59
  parsed_json=safe_spec,
60
  file_path=file_path,
61
+ base_url=auto_base_url or None,
62
  )
63
  db.add(spec_doc)
64
  db.commit()
65
 
66
  safe_spec["id"] = spec_id
67
+ return {
68
+ "status": "success",
69
+ "spec_id": spec_id,
70
+ "parsed_spec": safe_spec,
71
+ "suggested_base_url": auto_base_url,
72
+ }
73
  except Exception as e:
74
  logger.error("Failed to parse spec: %s", traceback.format_exc())
75
  raise HTTPException(status_code=400, detail=f"Failed to parse spec: {str(e)}")
 
154
  db.refresh(spec)
155
  return {"status": "cleared", "credentials": {}}
156
 
157
+ # Decrypt first so we merge into plaintext — merging into the encrypted
158
+ # blob and re-encrypting creates a double-encrypted nest.
159
+ current: dict = decrypt_credentials(dict(spec.login_credentials or {}))
160
+ current.pop("__enc__", None) # remove any legacy stale __enc__ key
161
+
162
  if payload.name is not None:
163
  current["name"] = payload.name
164
  if payload.username is not None:
backend/core/crypto.py CHANGED
@@ -26,11 +26,19 @@ def encrypt_credentials(data: dict) -> dict:
26
 
27
 
28
  def decrypt_credentials(data: dict) -> dict:
29
- """Decrypt a stored credentials dict. Transparently handles legacy plaintext dicts."""
 
 
 
 
30
  if not isinstance(data, dict):
31
  return data
32
  if _ENCRYPTED_KEY not in data:
33
  return data # legacy plaintext — return as-is
34
  if not settings.ENCRYPTION_KEY:
35
  raise ValueError("ENCRYPTION_KEY is not set — cannot decrypt stored credentials.")
36
- return json.loads(_fernet().decrypt(data[_ENCRYPTED_KEY].encode()))
 
 
 
 
 
26
 
27
 
28
  def decrypt_credentials(data: dict) -> dict:
29
+ """Decrypt a stored credentials dict. Transparently handles legacy plaintext dicts.
30
+
31
+ Recursively unwraps nested __enc__ layers that can occur when save_credentials
32
+ previously merged into an already-encrypted blob instead of decrypting first.
33
+ """
34
  if not isinstance(data, dict):
35
  return data
36
  if _ENCRYPTED_KEY not in data:
37
  return data # legacy plaintext — return as-is
38
  if not settings.ENCRYPTION_KEY:
39
  raise ValueError("ENCRYPTION_KEY is not set — cannot decrypt stored credentials.")
40
+ inner = json.loads(_fernet().decrypt(data[_ENCRYPTED_KEY].encode()))
41
+ # Recursively unwrap any nested __enc__ from historical double-encryption
42
+ if isinstance(inner, dict) and _ENCRYPTED_KEY in inner:
43
+ return decrypt_credentials(inner)
44
+ return inner
backend/schemas.py CHANGED
@@ -20,6 +20,7 @@ class StepDefinition(BaseModel):
20
  step: int
21
  endpoint: str
22
  purpose: str
 
23
 
24
  class ExecutionPlan(BaseModel):
25
  execution_plan: List[StepDefinition]
 
20
  step: int
21
  endpoint: str
22
  purpose: str
23
+ required_context_keys: Optional[List[str]] = []
24
 
25
  class ExecutionPlan(BaseModel):
26
  execution_plan: List[StepDefinition]
backend/services/api_executor.py CHANGED
@@ -72,6 +72,18 @@ CORE EXECUTION RULES:
72
  7. FILES: Use 'files' object {{"field": "filename"}} using names from the provided Assets.
73
  8. NO TEMPLATE STRINGS:
74
  - Do not leave {{var}} or <var> syntax in the final 'request' JSON. Fully resolve variables.
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  RETURN JSON ONLY:
77
  {{
@@ -109,6 +121,19 @@ def prepare_step_request(
109
  input_variables=["endpoint_spec", "base_url", "scenario", "step_definition", "user_credentials", "context_variables", "available_assets"],
110
  )
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  msg = prompt.format_prompt(
113
  endpoint_spec=json.dumps(endpoint_spec, separators=(',', ':')),
114
  base_url=base_url,
@@ -119,15 +144,40 @@ def prepare_step_request(
119
  available_assets=json.dumps(available_assets, separators=(',', ':'))
120
  ).to_messages()
121
 
 
 
122
  content, token_usage = llm.invoke(msg)
 
 
 
 
 
 
123
  try:
124
  parsed_response = parser.parse(content)
125
  except Exception as e:
126
- logger.warning("Step request parse failed, retrying: %s", e)
127
  content, token_usage = llm.invoke(msg)
 
 
 
 
128
  try:
129
  parsed_response = parser.parse(content)
130
  except Exception as e2:
131
  raise AppError(500, f"LLM returned unparseable output after 2 attempts: {e2}")
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  return StepExecutionPlan(**parsed_response), token_usage
 
72
  7. FILES: Use 'files' object {{"field": "filename"}} using names from the provided Assets.
73
  8. NO TEMPLATE STRINGS:
74
  - Do not leave {{var}} or <var> syntax in the final 'request' JSON. Fully resolve variables.
75
+ 9. COOKIE RULE:
76
+ - Do NOT add a Cookie header unless the spec explicitly requires it. Bearer token auth does not use cookies.
77
+ 10. PHP SINGLE-FILE API RULE:
78
+ - When the Base URL path ends with a .php filename (e.g. mobile_api.php), the `action` routing parameter MUST be in `query_params` (e.g. {{"action": "login", "v": 1}}).
79
+ - For POST/PUT/PATCH requests you may also include `action` in the JSON body, but it is NOT needed for GET requests.
80
+ - NEVER append the semantic OpenAPI path (e.g. /auth/login) after the .php filename — the URL must stay exactly at the .php file and route via ?action= only.
81
+ - Correct URL for login: "https://host/mobile_api.php", query_params: {{"action": "login", "v": 1}}
82
+ 11. MISSING ID RULE (CRITICAL):
83
+ - If a required path parameter (e.g. {{bus_id}}) or required body field is an ID that is NOT present in Context Variables and cannot be reasonably generated (it is a real DB record ID, not a UUID you create), do NOT guess a value.
84
+ - Instead, set the parameter to the literal string "__MISSING__<param_name>__" (e.g. "__MISSING__bus_id__") so the caller can detect and block execution.
85
+ - Examples of IDs you MUST NOT guess: bus_id, product_id, order_id, seat_id, route_id, ticket_id.
86
+ - Examples of IDs you CAN generate: new UUIDs for user registration, random test email addresses.
87
 
88
  RETURN JSON ONLY:
89
  {{
 
121
  input_variables=["endpoint_spec", "base_url", "scenario", "step_definition", "user_credentials", "context_variables", "available_assets"],
122
  )
123
 
124
+ # ── PHASE 1: LOG EXECUTOR INPUTS ─────────────────────────────────────────────
125
+ step_num = step_definition.get("step", "?")
126
+ endpoint_label = step_definition.get("endpoint", "?")
127
+ logger.info("="*70)
128
+ logger.info("[EXECUTOR] ▶ STEP %s PREPARATION STARTED: %s", step_num, endpoint_label)
129
+ logger.info("[EXECUTOR] Base URL : %s", base_url)
130
+ logger.info("[EXECUTOR] Step Definition : %s", json.dumps(step_definition))
131
+ logger.info("[EXECUTOR] Credentials : %s", json.dumps(user_credentials))
132
+ logger.info("[EXECUTOR] Context Variables : %s", json.dumps(context_variables))
133
+ logger.info("[EXECUTOR] Endpoint Spec : %s", json.dumps(endpoint_spec) if isinstance(endpoint_spec, dict) else str(endpoint_spec))
134
+ logger.info("[EXECUTOR] Available Assets : %s", json.dumps(list(available_assets.keys()) if isinstance(available_assets, dict) else []))
135
+ logger.info("="*70)
136
+
137
  msg = prompt.format_prompt(
138
  endpoint_spec=json.dumps(endpoint_spec, separators=(',', ':')),
139
  base_url=base_url,
 
144
  available_assets=json.dumps(available_assets, separators=(',', ':'))
145
  ).to_messages()
146
 
147
+ # ── PHASE 2: LLM CALL ────────────────────────────────────────────────────
148
+ logger.info("[EXECUTOR] ↑ Sending prompt to LLM...")
149
  content, token_usage = llm.invoke(msg)
150
+ logger.info("[EXECUTOR] ↓ Raw LLM response:")
151
+ logger.info("-"*70)
152
+ logger.info("%s", content)
153
+ logger.info("-"*70)
154
+
155
+ # ── PHASE 3: PARSE ───────────────────────────────────────────────────────
156
  try:
157
  parsed_response = parser.parse(content)
158
  except Exception as e:
159
+ logger.warning("[EXECUTOR] ⚠ Step request parse failed, retrying: %s", e)
160
  content, token_usage = llm.invoke(msg)
161
+ logger.info("[EXECUTOR] ↓ Raw LLM response (retry):")
162
+ logger.info("-"*70)
163
+ logger.info("%s", content)
164
+ logger.info("-"*70)
165
  try:
166
  parsed_response = parser.parse(content)
167
  except Exception as e2:
168
  raise AppError(500, f"LLM returned unparseable output after 2 attempts: {e2}")
169
 
170
+ # ── PHASE 4: LOG FINAL REQUEST ──────────────────────────────────────────────
171
+ req = parsed_response.get("request", {})
172
+ logger.info("[EXECUTOR] ✔ Request plan generated for step %s:", step_num)
173
+ logger.info("[EXECUTOR] Method : %s", req.get("method"))
174
+ logger.info("[EXECUTOR] URL : %s", req.get("url"))
175
+ logger.info("[EXECUTOR] Query Params: %s", json.dumps(req.get("query_params", {})))
176
+ logger.info("[EXECUTOR] Headers : %s", json.dumps(req.get("headers", {})))
177
+ logger.info("[EXECUTOR] Body : %s", json.dumps(req.get("body", {})))
178
+ logger.info("[EXECUTOR] Form Data : %s", json.dumps(req.get("form_data", {})))
179
+ logger.info("[EXECUTOR] Files : %s", json.dumps(req.get("files", {})))
180
+ logger.info("[EXECUTOR] Token usage : %s", token_usage)
181
+ logger.info("="*70)
182
+
183
  return StepExecutionPlan(**parsed_response), token_usage
backend/services/context_manager.py CHANGED
@@ -1,8 +1,8 @@
1
- import json
2
  from sqlalchemy.orm import Session
3
  from sqlalchemy.orm.attributes import flag_modified
4
  from backend.database import SessionModel
5
 
 
6
  def get_context(db: Session, session_id: str) -> dict:
7
  session = db.query(SessionModel).filter(SessionModel.id == session_id).first()
8
  if not session:
 
 
1
  from sqlalchemy.orm import Session
2
  from sqlalchemy.orm.attributes import flag_modified
3
  from backend.database import SessionModel
4
 
5
+
6
  def get_context(db: Session, session_id: str) -> dict:
7
  session = db.query(SessionModel).filter(SessionModel.id == session_id).first()
8
  if not session:
backend/services/llm_planner.py CHANGED
@@ -30,13 +30,15 @@ You must return ONLY a JSON object representing the execution plan. DO NOT inclu
30
  "execution_plan": [
31
  {{
32
  "step": 1,
33
- "endpoint": "POST /auth/register",
34
- "purpose": "Register a new user"
 
35
  }},
36
  {{
37
  "step": 2,
38
- "endpoint": "POST /auth/login",
39
- "purpose": "Authenticate the user"
 
40
  }}
41
  ],
42
  "suggested_credentials": {{
@@ -46,6 +48,18 @@ You must return ONLY a JSON object representing the execution plan. DO NOT inclu
46
  }}
47
  }}
48
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  API DOCUMENTATION:
50
  {parsed_spec}
51
 
@@ -115,6 +129,17 @@ def generate_execution_plan(parsed_spec: Dict[str, Any], base_url: str, scenario
115
  condensed = _condense_spec_for_planning(parsed_spec)
116
  spec_payload = condensed if condensed else parsed_spec.get("endpoints", parsed_spec)
117
 
 
 
 
 
 
 
 
 
 
 
 
118
  msg = prompt.format_prompt(
119
  parsed_spec=json.dumps(spec_payload, separators=(',', ':')),
120
  base_url=base_url,
@@ -122,15 +147,39 @@ def generate_execution_plan(parsed_spec: Dict[str, Any], base_url: str, scenario
122
  user_credentials_str=json.dumps(user_credentials or {}, separators=(',', ':'))
123
  ).to_messages()
124
 
125
- # Invoke with one retry on parse failure
 
126
  content, token_usage = llm.invoke(msg)
 
 
 
 
 
 
127
  try:
128
  parsed_response = parser.parse(content)
129
  except Exception as parse_err:
130
- logger.warning("Plan parse failed, retrying: %s", parse_err)
131
  content, token_usage = llm.invoke(msg)
 
 
 
 
132
  parsed_response = parser.parse(content)
133
-
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  # Return as Pydantic model
135
  return ExecutionPlan(
136
  execution_plan=parsed_response["execution_plan"],
 
30
  "execution_plan": [
31
  {{
32
  "step": 1,
33
+ "endpoint": "GET /buses",
34
+ "purpose": "Fetch available buses so user can select a real bus_id",
35
+ "required_context_keys": []
36
  }},
37
  {{
38
  "step": 2,
39
+ "endpoint": "POST /buses/{{bus_id}}/book",
40
+ "purpose": "Book the selected bus",
41
+ "required_context_keys": ["bus_id"]
42
  }}
43
  ],
44
  "suggested_credentials": {{
 
48
  }}
49
  }}
50
 
51
+ DEPENDENCY RULE (CRITICAL):
52
+ - Inspect every endpoint in your plan for path parameters (e.g. {{bus_id}}, {{product_id}}, {{seat_id}}).
53
+ - If a path parameter cannot be known in advance (not in USER CREDENTIALS, not a UUID to generate, not derivable from a prior step in THIS plan), you MUST insert a GET/list step immediately before the step that needs it. That GET step should fetch the list of available options.
54
+ - Example: "POST /buses/{{bus_id}}/book" at step 1 → insert "GET /buses" at step 1, shift booking to step 2.
55
+ - Example: "GET /routes/{{route_id}}/stops" where route_id comes from a previous GET /routes → no insertion needed.
56
+
57
+ REQUIRED_CONTEXT_KEYS RULE:
58
+ - For each step, set "required_context_keys" to a list of context variable names that MUST be present before this step can run and that the AI cannot safely generate (real IDs, external references).
59
+ - If the step needs no special context, set "required_context_keys" to [].
60
+ - Example: step "POST /bookings/{{bus_id}}" → required_context_keys: ["bus_id"]
61
+ - Example: step "POST /auth/login" with email/password from credentials → required_context_keys: []
62
+
63
  API DOCUMENTATION:
64
  {parsed_spec}
65
 
 
129
  condensed = _condense_spec_for_planning(parsed_spec)
130
  spec_payload = condensed if condensed else parsed_spec.get("endpoints", parsed_spec)
131
 
132
+ # ── PHASE 1: LOG PLANNING INPUTS ─────────────────────────────────────────
133
+ logger.info("="*70)
134
+ logger.info("[PLANNER] ▶ PLAN GENERATION STARTED")
135
+ logger.info("[PLANNER] Base URL : %s", base_url)
136
+ logger.info("[PLANNER] Scenario : %s", scenario)
137
+ logger.info("[PLANNER] Credentials : %s", json.dumps(user_credentials or {}))
138
+ logger.info("[PLANNER] Condensed Spec (%d endpoints):", len(condensed))
139
+ for ep in condensed:
140
+ logger.info("[PLANNER] %s %s — %s", ep.get("method",""), ep.get("path",""), ep.get("summary","")[:80])
141
+ logger.info("="*70)
142
+
143
  msg = prompt.format_prompt(
144
  parsed_spec=json.dumps(spec_payload, separators=(',', ':')),
145
  base_url=base_url,
 
147
  user_credentials_str=json.dumps(user_credentials or {}, separators=(',', ':'))
148
  ).to_messages()
149
 
150
+ # ── PHASE 2: LLM CALL ────────────────────────────────────────────────────
151
+ logger.info("[PLANNER] ↑ Sending prompt to LLM...")
152
  content, token_usage = llm.invoke(msg)
153
+ logger.info("[PLANNER] ↓ Raw LLM response:")
154
+ logger.info("-"*70)
155
+ logger.info("%s", content)
156
+ logger.info("-"*70)
157
+
158
+ # ── PHASE 3: PARSE ───────────────────────────────────────────────────────
159
  try:
160
  parsed_response = parser.parse(content)
161
  except Exception as parse_err:
162
+ logger.warning("[PLANNER] ⚠ Plan parse failed, retrying: %s", parse_err)
163
  content, token_usage = llm.invoke(msg)
164
+ logger.info("[PLANNER] ↓ Raw LLM response (retry):")
165
+ logger.info("-"*70)
166
+ logger.info("%s", content)
167
+ logger.info("-"*70)
168
  parsed_response = parser.parse(content)
169
+
170
+ # ── PHASE 4: LOG FINAL PLAN ──────────────────────────────────────────────
171
+ logger.info("[PLANNER] ✔ Execution plan generated — %d step(s):", len(parsed_response.get("execution_plan", [])))
172
+ for step in parsed_response.get("execution_plan", []):
173
+ logger.info(
174
+ "[PLANNER] Step %s: %s | purpose: %s | required_context: %s",
175
+ step.get("step"), step.get("endpoint"), step.get("purpose", "")[:80],
176
+ step.get("required_context_keys", [])
177
+ )
178
+ if parsed_response.get("suggested_credentials"):
179
+ logger.info("[PLANNER] Suggested credentials: %s", json.dumps(parsed_response["suggested_credentials"]))
180
+ logger.info("[PLANNER] Token usage: %s", token_usage)
181
+ logger.info("="*70)
182
+
183
  # Return as Pydantic model
184
  return ExecutionPlan(
185
  execution_plan=parsed_response["execution_plan"],
backend/services/response_analyzer.py CHANGED
@@ -58,22 +58,36 @@ def analyze_api_response(
58
  half = limit // 2
59
  response_body = response_body[:half] + "\n... [TRUNCATED] ...\n" + response_body[-half:]
60
 
 
 
 
 
 
 
 
 
61
  msg = prompt.format_prompt(
62
  step_info=f"Step {step}: {endpoint} - {purpose}",
63
  status_code=str(status_code),
64
  response_body=response_body
65
  ).to_messages()
66
 
 
67
  content, token_usage = llm.invoke(msg)
 
 
 
 
 
68
  try:
69
  parsed_response = parser.parse(content)
70
  except Exception as parse_err:
71
- logger.warning("Analysis parse failed, retrying: %s", parse_err)
72
  try:
73
  content, token_usage = llm.invoke(msg)
74
  parsed_response = parser.parse(content)
75
  except Exception as retry_err:
76
- logger.error("Analysis failed after retry, returning safe fallback: %s", retry_err)
77
  return AnalyzeResponse(
78
  step=step,
79
  status="unknown",
@@ -85,4 +99,17 @@ def analyze_api_response(
85
  parsed_response["step"] = step
86
  parsed_response["token_usage"] = token_usage
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  return AnalyzeResponse(**parsed_response)
 
58
  half = limit // 2
59
  response_body = response_body[:half] + "\n... [TRUNCATED] ...\n" + response_body[-half:]
60
 
61
+ # ── LOG ANALYSIS INPUTS ──────────────────────────────────────────────────
62
+ logger.info("="*70)
63
+ logger.info("[ANALYZER] ▶ RESPONSE ANALYSIS STARTED for Step %s", step)
64
+ logger.info("[ANALYZER] Endpoint : %s %s", endpoint, purpose)
65
+ logger.info("[ANALYZER] Status Code : %s", status_code)
66
+ logger.info("[ANALYZER] Response Body (first 500 chars):\n%s", response_body[:500])
67
+ logger.info("="*70)
68
+
69
  msg = prompt.format_prompt(
70
  step_info=f"Step {step}: {endpoint} - {purpose}",
71
  status_code=str(status_code),
72
  response_body=response_body
73
  ).to_messages()
74
 
75
+ logger.info("[ANALYZER] ↑ Sending response to LLM for analysis...")
76
  content, token_usage = llm.invoke(msg)
77
+ logger.info("[ANALYZER] ↓ Raw LLM response:")
78
+ logger.info("-"*70)
79
+ logger.info("%s", content)
80
+ logger.info("-"*70)
81
+
82
  try:
83
  parsed_response = parser.parse(content)
84
  except Exception as parse_err:
85
+ logger.warning("[ANALYZER] ⚠ Analysis parse failed, retrying: %s", parse_err)
86
  try:
87
  content, token_usage = llm.invoke(msg)
88
  parsed_response = parser.parse(content)
89
  except Exception as retry_err:
90
+ logger.error("[ANALYZER] ✗ Analysis failed after retry, returning safe fallback: %s", retry_err)
91
  return AnalyzeResponse(
92
  step=step,
93
  status="unknown",
 
99
  parsed_response["step"] = step
100
  parsed_response["token_usage"] = token_usage
101
 
102
+ # ── LOG ANALYSIS RESULTS ───────────────────────────────────────────────
103
+ logger.info("[ANALYZER] ✔ Analysis complete for Step %s:", step)
104
+ logger.info("[ANALYZER] Status : %s", parsed_response.get("status"))
105
+ logger.info("[ANALYZER] Extracted Variables : %s", json.dumps(parsed_response.get("extracted_variables", {})))
106
+ logger.info("[ANALYZER] OTP Required : %s", parsed_response.get("is_otp_required"))
107
+ logger.info("[ANALYZER] Selection Required : %s", parsed_response.get("is_selection_required"))
108
+ if parsed_response.get("is_selection_required"):
109
+ logger.info("[ANALYZER] Selection Field : %s", parsed_response.get("selection_field_name"))
110
+ opts = parsed_response.get("selection_options") or []
111
+ logger.info("[ANALYZER] Selection Options : %s", json.dumps(opts[:5])) # max 5 for brevity
112
+ logger.info("[ANALYZER] Token usage: %s", token_usage)
113
+ logger.info("="*70)
114
+
115
  return AnalyzeResponse(**parsed_response)
backend/services/swagger_parser.py CHANGED
@@ -40,6 +40,15 @@ def parse_spec(spec_content: str) -> Dict[str, Any]:
40
  }
41
  simplified_endpoints.append(endpoint_info)
42
 
 
 
 
 
 
 
 
 
 
43
  return {
44
  # Raw spec — used by executor to look up and resolve specific schemas on-the-fly
45
  "paths": paths,
@@ -49,5 +58,7 @@ def parse_spec(spec_content: str) -> Dict[str, Any]:
49
  "title": spec_dict.get("info", {}).get("title", "API Spec"),
50
  "version": spec_dict.get("info", {}).get("version", "1.0"),
51
  # Simplified list — used by planner LLM
52
- "endpoints": simplified_endpoints
 
 
53
  }
 
40
  }
41
  simplified_endpoints.append(endpoint_info)
42
 
43
+ # Extract the first server URL so the frontend can auto-populate the base URL field.
44
+ # We expose it even if it looks like a placeholder — the user can edit it.
45
+ servers = spec_dict.get("servers", [])
46
+ suggested_base_url = None
47
+ if servers and isinstance(servers, list):
48
+ first_url = servers[0].get("url", "") if isinstance(servers[0], dict) else ""
49
+ if first_url:
50
+ suggested_base_url = first_url.rstrip("/")
51
+
52
  return {
53
  # Raw spec — used by executor to look up and resolve specific schemas on-the-fly
54
  "paths": paths,
 
58
  "title": spec_dict.get("info", {}).get("title", "API Spec"),
59
  "version": spec_dict.get("info", {}).get("version", "1.0"),
60
  # Simplified list — used by planner LLM
61
+ "endpoints": simplified_endpoints,
62
+ # Server URL hint for the frontend
63
+ "suggested_base_url": suggested_base_url,
64
  }
frontend-react/src/components/AppContext.jsx CHANGED
@@ -60,7 +60,9 @@ export const AppProvider = ({ children }) => {
60
  setParsedSpec(data.parsed_spec);
61
  setActiveSpecName(data.name);
62
  setActiveSpecId(data.id);
63
- setActiveBaseUrl(data.base_url || '');
 
 
64
 
65
  // Keep testing workspace fresh; history preserves past runs
66
  setExecutionPlan(null);
 
60
  setParsedSpec(data.parsed_spec);
61
  setActiveSpecName(data.name);
62
  setActiveSpecId(data.id);
63
+ // Use saved base_url; fall back to the suggested URL extracted from the spec's servers list
64
+ const resolvedBaseUrl = data.base_url || data.parsed_spec?.suggested_base_url || '';
65
+ setActiveBaseUrl(resolvedBaseUrl);
66
 
67
  // Keep testing workspace fresh; history preserves past runs
68
  setExecutionPlan(null);
frontend-react/src/components/SpecsPage.jsx CHANGED
@@ -1,7 +1,7 @@
1
  import React, { useRef, useState } from 'react';
2
  import { Database, Upload, Trash2, LayoutTemplate, Search, RefreshCw, Plus, Check } from 'lucide-react';
3
  import { useAppContext } from './AppContext';
4
- import { SpecService } from '../services/api';
5
 
6
  const SpecsPage = ({ onSpecSelected }) => {
7
  const {
@@ -19,7 +19,11 @@ const SpecsPage = ({ onSpecSelected }) => {
19
 
20
  setIsUploading(true);
21
  try {
22
- await SpecService.uploadSpec(file);
 
 
 
 
23
  await fetchSpecs();
24
  addToast('success', `"${file.name}" uploaded successfully.`);
25
  } catch (err) {
 
1
  import React, { useRef, useState } from 'react';
2
  import { Database, Upload, Trash2, LayoutTemplate, Search, RefreshCw, Plus, Check } from 'lucide-react';
3
  import { useAppContext } from './AppContext';
4
+ import { SpecService, api } from '../services/api';
5
 
6
  const SpecsPage = ({ onSpecSelected }) => {
7
  const {
 
19
 
20
  setIsUploading(true);
21
  try {
22
+ const result = await SpecService.uploadSpec(file);
23
+ // If the spec declares a server URL, save it immediately so loadSpec picks it up
24
+ if (result.spec_id && result.suggested_base_url) {
25
+ await SpecService.updateBaseUrl(result.spec_id, result.suggested_base_url);
26
+ }
27
  await fetchSpecs();
28
  addToast('success', `"${file.name}" uploaded successfully.`);
29
  } catch (err) {
frontend-react/src/components/workflow/ContextPanel.jsx CHANGED
@@ -2,6 +2,8 @@ import React from 'react';
2
  import { Circle, RefreshCw } from 'lucide-react';
3
 
4
  export default function ContextPanel({ sessionContextVars, storedCredentials, onRefresh }) {
 
 
5
  return (
6
  <div style={{ flex: 1, overflowY: 'auto', padding: 14, display: 'flex', flexDirection: 'column', gap: 16 }}>
7
  <section>
@@ -12,13 +14,13 @@ export default function ContextPanel({ sessionContextVars, storedCredentials, on
12
  </button>
13
  </div>
14
  <div className="panel" style={{ overflow: 'hidden' }}>
15
- {Object.keys(sessionContextVars || {}).length === 0 ? (
16
  <div style={{ padding: 14, textAlign: 'center' }}>
17
  <Circle size={18} style={{ margin: '0 auto 6px', color: 'var(--fg-4)', display: 'block' }} strokeWidth={1.5}/>
18
  <p style={{ fontSize: 11, color: 'var(--fg-3)', margin: 0, fontStyle: 'italic' }}>No variables extracted</p>
19
  </div>
20
  ) : (
21
- Object.entries(sessionContextVars).map(([k, v]) => (
22
  <div key={k} style={{ padding: '6px 12px', borderBottom: '1px solid var(--line-1)' }}>
23
  <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--accent)', marginBottom: 2 }}>{k}</div>
24
  <div style={{ fontSize: 11, color: 'var(--fg-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{String(v)}</div>
 
2
  import { Circle, RefreshCw } from 'lucide-react';
3
 
4
  export default function ContextPanel({ sessionContextVars, storedCredentials, onRefresh }) {
5
+ const regularVars = Object.entries(sessionContextVars || {}).filter(([k]) => !k.startsWith('__'));
6
+
7
  return (
8
  <div style={{ flex: 1, overflowY: 'auto', padding: 14, display: 'flex', flexDirection: 'column', gap: 16 }}>
9
  <section>
 
14
  </button>
15
  </div>
16
  <div className="panel" style={{ overflow: 'hidden' }}>
17
+ {regularVars.length === 0 ? (
18
  <div style={{ padding: 14, textAlign: 'center' }}>
19
  <Circle size={18} style={{ margin: '0 auto 6px', color: 'var(--fg-4)', display: 'block' }} strokeWidth={1.5}/>
20
  <p style={{ fontSize: 11, color: 'var(--fg-3)', margin: 0, fontStyle: 'italic' }}>No variables extracted</p>
21
  </div>
22
  ) : (
23
+ regularVars.map(([k, v]) => (
24
  <div key={k} style={{ padding: '6px 12px', borderBottom: '1px solid var(--line-1)' }}>
25
  <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--accent)', marginBottom: 2 }}>{k}</div>
26
  <div style={{ fontSize: 11, color: 'var(--fg-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{String(v)}</div>
frontend-react/src/components/workflow/SelectionModal.jsx CHANGED
@@ -1,49 +1,110 @@
1
- import React from 'react';
2
- import { Layers, X, Code } from 'lucide-react';
 
 
 
 
 
 
 
 
3
 
4
- export default function SelectionModal({ selectionPrompt, onSelect, onCancel }) {
5
  return (
6
  <div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)', padding: 16 }}>
7
  <div style={{ background: 'var(--bg-1)', border: '1px solid var(--line-3)', borderRadius: 10, width: '100%', maxWidth: 480, maxHeight: '80vh', overflow: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: 'var(--shadow-md)' }}>
 
 
8
  <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--line-1)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
9
  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
10
- <Layers size={14} style={{ color: 'var(--accent)' }}/>
11
- <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-0)' }}>Choose an Option</span>
 
 
 
 
12
  </div>
13
  <button onClick={onCancel} className="ico-btn"><X size={14}/></button>
14
  </div>
 
15
  <div style={{ padding: 20, overflowY: 'auto' }}>
16
- <p style={{ fontSize: 12, color: 'var(--fg-2)', marginBottom: 14, lineHeight: 1.6 }}>
17
- Select one to save as <code style={{ color: 'var(--accent)' }}>{selectionPrompt.fieldName}</code>.
18
- </p>
19
- <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
20
- {selectionPrompt.options.map((opt, idx) => (
21
- <button
22
- key={idx}
23
- onClick={() => onSelect(opt)}
24
- className="col-card"
25
- style={{ textAlign: 'left', padding: '10px 14px', borderRadius: 6, cursor: 'pointer' }}
26
- >
27
- <div style={{ fontSize: 13, color: 'var(--fg-0)', fontWeight: 500, marginBottom: 2 }}>{opt.label || 'Option'}</div>
28
- <div style={{ fontSize: 10.5, color: 'var(--fg-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
29
- {typeof opt.value === 'object' ? JSON.stringify(opt.value) : String(opt.value)}
30
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  </button>
32
- ))}
33
- </div>
34
- {selectionPrompt.responseBody && (
35
- <details style={{ cursor: 'pointer' }}>
36
- <summary style={{ fontSize: 11, color: 'var(--fg-3)', display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
37
- <Code size={12}/> Raw response
38
- </summary>
39
- <pre className="code" style={{ maxHeight: 160 }}>
40
- {(() => { try { return JSON.stringify(JSON.parse(selectionPrompt.responseBody), null, 2); } catch { return selectionPrompt.responseBody; } })()}
41
- </pre>
42
- </details>
43
  )}
44
- <button onClick={onCancel} className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 8 }}>
45
- Cancel
46
- </button>
47
  </div>
48
  </div>
49
  </div>
 
1
+ import React, { useState } from 'react';
2
+ import { Layers, X, Code, KeyRound } from 'lucide-react';
3
+
4
+ export default function SelectionModal({ selectionPrompt, onSelect, onConfirm, onCancel }) {
5
+ const [inputValues, setInputValues] = useState({});
6
+
7
+ const type = selectionPrompt.type || 'selection';
8
+ const missingKeys = selectionPrompt.missingKeys || [];
9
+
10
+ const allFilled = missingKeys.every(k => inputValues[k]?.trim());
11
 
 
12
  return (
13
  <div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)', padding: 16 }}>
14
  <div style={{ background: 'var(--bg-1)', border: '1px solid var(--line-3)', borderRadius: 10, width: '100%', maxWidth: 480, maxHeight: '80vh', overflow: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: 'var(--shadow-md)' }}>
15
+
16
+ {/* Header */}
17
  <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--line-1)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
18
  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
19
+ {type === 'manual_input'
20
+ ? <KeyRound size={14} style={{ color: 'var(--accent)' }}/>
21
+ : <Layers size={14} style={{ color: 'var(--accent)' }}/>}
22
+ <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-0)' }}>
23
+ {type === 'manual_input' ? 'Provide Missing IDs' : 'Choose an Option'}
24
+ </span>
25
  </div>
26
  <button onClick={onCancel} className="ico-btn"><X size={14}/></button>
27
  </div>
28
+
29
  <div style={{ padding: 20, overflowY: 'auto' }}>
30
+
31
+ {/* ── Manual input mode ── */}
32
+ {type === 'manual_input' && (
33
+ <>
34
+ <p style={{ fontSize: 12, color: 'var(--fg-2)', marginBottom: 16, lineHeight: 1.6 }}>
35
+ This step requires real IDs that could not be determined automatically.
36
+ Enter the correct values from your system or database.
37
+ </p>
38
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 20 }}>
39
+ {missingKeys.map(key => (
40
+ <div key={key}>
41
+ <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--fg-2)', marginBottom: 5, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
42
+ {key}
43
+ </label>
44
+ <input
45
+ type="text"
46
+ className="input"
47
+ placeholder={`Enter real value for ${key}`}
48
+ value={inputValues[key] || ''}
49
+ onChange={e => setInputValues(prev => ({ ...prev, [key]: e.target.value }))}
50
+ style={{ width: '100%', boxSizing: 'border-box' }}
51
+ />
52
+ </div>
53
+ ))}
54
+ </div>
55
+ <div style={{ display: 'flex', gap: 8 }}>
56
+ <button
57
+ className="btn-primary"
58
+ disabled={!allFilled}
59
+ onClick={() => onConfirm(inputValues)}
60
+ style={{ flex: 1, justifyContent: 'center', opacity: allFilled ? 1 : 0.45 }}
61
+ >
62
+ Save &amp; Execute
63
+ </button>
64
+ <button onClick={onCancel} className="btn" style={{ flex: 1, justifyContent: 'center' }}>
65
+ Cancel
66
+ </button>
67
+ </div>
68
+ </>
69
+ )}
70
+
71
+ {/* ── Selection mode (existing behaviour) ── */}
72
+ {type === 'selection' && (
73
+ <>
74
+ <p style={{ fontSize: 12, color: 'var(--fg-2)', marginBottom: 14, lineHeight: 1.6 }}>
75
+ Select one to save as <code style={{ color: 'var(--accent)' }}>{selectionPrompt.fieldName}</code>.
76
+ </p>
77
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
78
+ {(selectionPrompt.options || []).map((opt, idx) => (
79
+ <button
80
+ key={idx}
81
+ onClick={() => onSelect(opt)}
82
+ className="col-card"
83
+ style={{ textAlign: 'left', padding: '10px 14px', borderRadius: 6, cursor: 'pointer' }}
84
+ >
85
+ <div style={{ fontSize: 13, color: 'var(--fg-0)', fontWeight: 500, marginBottom: 2 }}>{opt.label || 'Option'}</div>
86
+ <div style={{ fontSize: 10.5, color: 'var(--fg-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
87
+ {typeof opt.value === 'object' ? JSON.stringify(opt.value) : String(opt.value)}
88
+ </div>
89
+ </button>
90
+ ))}
91
+ </div>
92
+ {selectionPrompt.responseBody && (
93
+ <details style={{ cursor: 'pointer' }}>
94
+ <summary style={{ fontSize: 11, color: 'var(--fg-3)', display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
95
+ <Code size={12}/> Raw response
96
+ </summary>
97
+ <pre className="code" style={{ maxHeight: 160 }}>
98
+ {(() => { try { return JSON.stringify(JSON.parse(selectionPrompt.responseBody), null, 2); } catch { return selectionPrompt.responseBody; } })()}
99
+ </pre>
100
+ </details>
101
+ )}
102
+ <button onClick={onCancel} className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 8 }}>
103
+ Cancel
104
  </button>
105
+ </>
 
 
 
 
 
 
 
 
 
 
106
  )}
107
+
 
 
108
  </div>
109
  </div>
110
  </div>
frontend-react/src/components/workflow/StepCard.jsx CHANGED
@@ -19,6 +19,11 @@ export default function StepCard({ step, isRunning, isRunningAll, res, onExecute
19
  : isRunning ? ' is-running'
20
  : '';
21
 
 
 
 
 
 
22
  return (
23
  <div className={`step${stateClass}`}>
24
  <div className="step-row">
@@ -31,9 +36,9 @@ export default function StepCard({ step, isRunning, isRunningAll, res, onExecute
31
 
32
  <div className="step-main">
33
  <div className="step-title">
34
- <span className={`method m-${step.method}`}>{step.method}</span>
35
  <span className="endpoint">
36
- <span className="path">{step.endpoint}</span>
37
  </span>
38
  {isRunning && <span className="pill pill-acc">running</span>}
39
  </div>
@@ -107,11 +112,11 @@ export default function StepCard({ step, isRunning, isRunningAll, res, onExecute
107
  <span className="v">{res.request.url}</span>
108
  </div>
109
  </div>
110
- {res.request.headers && Object.keys(res.request.headers).length > 0 && (
111
  <>
112
  <span className="kv-label">Headers</span>
113
  <div className="kv-block" style={{ marginBottom: 8 }}>
114
- {Object.entries(res.request.headers).map(([k, v]) => (
115
  <div className="kv-row" key={k}><span className="k">{k}:</span><span className="v">{v}</span></div>
116
  ))}
117
  </div>
@@ -148,7 +153,9 @@ export default function StepCard({ step, isRunning, isRunningAll, res, onExecute
148
  {!res.response ? (
149
  <div style={{ fontSize: 11, color: 'var(--fg-3)', fontStyle: 'italic' }}>Waiting…</div>
150
  ) : (
151
- <pre className="code">{pretty(res.response.body)}</pre>
 
 
152
  )}
153
  </div>
154
  </div>
 
19
  : isRunning ? ' is-running'
20
  : '';
21
 
22
+ // endpoint is "METHOD /path" — split out method and path for display
23
+ const endpointParts = (step.endpoint || '').trim().split(/\s+/);
24
+ const method = endpointParts.length >= 2 ? endpointParts[0].toUpperCase() : '';
25
+ const endpointPath = endpointParts.length >= 2 ? endpointParts.slice(1).join(' ') : step.endpoint;
26
+
27
  return (
28
  <div className={`step${stateClass}`}>
29
  <div className="step-row">
 
36
 
37
  <div className="step-main">
38
  <div className="step-title">
39
+ {method && <span className={`method m-${method}`}>{method}</span>}
40
  <span className="endpoint">
41
+ <span className="path">{endpointPath}</span>
42
  </span>
43
  {isRunning && <span className="pill pill-acc">running</span>}
44
  </div>
 
112
  <span className="v">{res.request.url}</span>
113
  </div>
114
  </div>
115
+ {res.request.headers && Object.keys(res.request.headers).filter(k => k.toLowerCase() !== 'cookie').length > 0 && (
116
  <>
117
  <span className="kv-label">Headers</span>
118
  <div className="kv-block" style={{ marginBottom: 8 }}>
119
+ {Object.entries(res.request.headers).filter(([k]) => k.toLowerCase() !== 'cookie').map(([k, v]) => (
120
  <div className="kv-row" key={k}><span className="k">{k}:</span><span className="v">{v}</span></div>
121
  ))}
122
  </div>
 
153
  {!res.response ? (
154
  <div style={{ fontSize: 11, color: 'var(--fg-3)', fontStyle: 'italic' }}>Waiting…</div>
155
  ) : (
156
+ <>
157
+ <pre className="code">{pretty(res.response.body)}</pre>
158
+ </>
159
  )}
160
  </div>
161
  </div>
frontend-react/src/pages/WorkflowPage.jsx CHANGED
@@ -93,6 +93,13 @@ export default function WorkflowPage() {
93
 
94
  /* ── Step execution ────────────────────────────────────────── */
95
  const executeStep = async (stepDef) => {
 
 
 
 
 
 
 
96
  setExecutingStep(stepDef.step);
97
  try {
98
  if (!sessionId) { addToast('error', 'Session not initialized. Please refresh.'); return; }
@@ -158,6 +165,11 @@ export default function WorkflowPage() {
158
  });
159
  }
160
  } catch (err) {
 
 
 
 
 
161
  console.error(`Execution failed for step ${stepDef.step}`, err);
162
  addToast('error', `Step ${stepDef.step} failed: ${err.message}`);
163
  setStepResults(prev => ({
@@ -254,6 +266,21 @@ export default function WorkflowPage() {
254
  }
255
  };
256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  const handleSelectionSubmit = async (option) => {
258
  if (!selectionPrompt) return;
259
  try {
@@ -382,6 +409,7 @@ export default function WorkflowPage() {
382
  <SelectionModal
383
  selectionPrompt={selectionPrompt}
384
  onSelect={handleSelectionSubmit}
 
385
  onCancel={() => setSelectionPrompt(null)}
386
  />
387
  )}
 
93
 
94
  /* ── Step execution ────────────────────────────────────────── */
95
  const executeStep = async (stepDef) => {
96
+ const requiredKeys = stepDef.required_context_keys || [];
97
+ const missingKeys = requiredKeys.filter(key => !sessionContextVars[key]);
98
+ if (missingKeys.length > 0) {
99
+ setSelectionPrompt({ type: 'manual_input', step: stepDef, missingKeys });
100
+ return;
101
+ }
102
+
103
  setExecutingStep(stepDef.step);
104
  try {
105
  if (!sessionId) { addToast('error', 'Session not initialized. Please refresh.'); return; }
 
165
  });
166
  }
167
  } catch (err) {
168
+ if (err.response?.data?.error === 'missing_context_keys') {
169
+ const missing = err.response.data.missing_keys || [];
170
+ setSelectionPrompt({ type: 'manual_input', step: stepDef, missingKeys: missing });
171
+ return;
172
+ }
173
  console.error(`Execution failed for step ${stepDef.step}`, err);
174
  addToast('error', `Step ${stepDef.step} failed: ${err.message}`);
175
  setStepResults(prev => ({
 
266
  }
267
  };
268
 
269
+ const handleManualInputConfirm = async (values) => {
270
+ if (!selectionPrompt) return;
271
+ try {
272
+ for (const [key, value] of Object.entries(values)) {
273
+ await SessionService.updateContext(sessionId, key, value);
274
+ }
275
+ const stepToRetry = selectionPrompt.step;
276
+ setSelectionPrompt(null);
277
+ await refreshSessionContext();
278
+ await executeStep(stepToRetry);
279
+ } catch {
280
+ addToast('error', 'Failed to save context values.');
281
+ }
282
+ };
283
+
284
  const handleSelectionSubmit = async (option) => {
285
  if (!selectionPrompt) return;
286
  try {
 
409
  <SelectionModal
410
  selectionPrompt={selectionPrompt}
411
  onSelect={handleSelectionSubmit}
412
+ onConfirm={handleManualInputConfirm}
413
  onCancel={() => setSelectionPrompt(null)}
414
  />
415
  )}
openapi.yaml CHANGED
@@ -1,1078 +1,1517 @@
1
- openapi: 3.0.1
 
2
  info:
3
- title: The ParaBank REST API
4
- description: This API provides access to various ParaBank internal operations
5
- termsOfService: /parabank/about.htm
6
- contact:
7
- name: ParaBank Web Administrator
8
- url: http://www.parasoft.com
9
- email: webadmin@parabank.parasoft.com
10
- license:
11
- name: Apache 2.0
12
- url: http://www.apache.org/licenses/LICENSE-2.0
13
- version: 3.0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  servers:
15
- - url: /parabank/services/bank
 
 
 
 
 
16
  tags:
17
- - name: Accounts
18
- description: account centric operations
19
- - name: Customers
20
- description: customer centric operations
21
- - name: Database
22
- description: data management operations
23
- - name: JMS
24
- description: message service operations
25
- - name: Loans
26
- description: request loan operations
27
- - name: Misc
28
- description: miscelaneous operations
29
- - name: Positions
30
- description: stock centric operations
31
- - name: Transactions
32
- description: banking transactions centric operations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  paths:
34
- /billpay:
 
 
 
35
  post:
36
- tags:
37
- - Accounts
38
- summary: Pay bill
39
- operationId: billPay
 
 
 
40
  parameters:
41
- - name: accountId
42
- in: query
43
- description: Bill payment source account
44
- required: true
45
- schema:
46
- type: integer
47
- format: int32
48
- - name: amount
49
- in: query
50
- description: Amount
51
- required: true
52
- schema:
53
- type: number
54
  requestBody:
55
- description: Payee
56
  content:
57
  application/json:
58
  schema:
59
- $ref: "#/components/schemas/Payee"
60
- application/xml:
61
- schema:
62
- $ref: "#/components/schemas/Payee"
63
- required: true
64
  responses:
65
- default:
66
- description: default response
67
  content:
68
- application/xml:
69
- schema:
70
- $ref: "#/components/schemas/BillPayResult"
71
  application/json:
72
  schema:
73
- $ref: "#/components/schemas/BillPayResult"
74
- /customers/{customerId}/buyPosition:
 
 
 
 
 
 
 
 
 
 
 
 
75
  post:
76
- tags:
77
- - Positions
78
- summary: Buy a Position
79
- operationId: buyPosition
 
 
 
80
  parameters:
81
- - name: customerId
82
- in: path
83
- description: Customer's id
84
- required: true
85
- schema:
86
- type: integer
87
- format: int32
88
- - name: accountId
89
- in: query
90
- description: Customer funds source account
91
- required: true
92
- schema:
93
- type: integer
94
- format: int32
95
- - name: name
96
- in: query
97
- description: Instrument's Name
98
- required: true
99
- schema:
100
- type: string
101
- - name: symbol
102
- in: query
103
- description: Instrument's exchange symbol
104
- required: true
105
- schema:
106
- type: string
107
- - name: shares
108
- in: query
109
- description: number of shares
110
- required: true
111
- schema:
112
- type: integer
113
- format: int32
114
- - name: pricePerShare
115
- in: query
116
- description: Price of each share
117
  required: true
118
- schema:
119
- type: number
 
 
 
 
 
120
  responses:
121
- default:
122
- description: default response
123
  content:
124
- application/xml:
125
- schema:
126
- type: array
127
- items:
128
- $ref: "#/components/schemas/Position"
129
  application/json:
130
  schema:
131
- type: array
132
- items:
133
- $ref: "#/components/schemas/Position"
134
- /cleanDB:
 
 
 
 
135
  post:
136
- tags:
137
- - Database
138
- summary: Clean the Database
139
- operationId: cleanDB
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  responses:
141
- default:
142
- description: default response
143
- content:
144
- application/xml: {}
145
- application/json: {}
146
- /createAccount:
147
- post:
148
- tags:
149
- - Customers
150
- - Accounts
151
- summary: Create a new account
152
- operationId: createAccount
153
  parameters:
154
- - name: customerId
155
- in: query
156
- description: Customer's id
157
- required: true
158
- schema:
159
- type: integer
160
- format: int32
161
- - name: newAccountType
162
- in: query
163
- description: "Account type (CHECKING, SAVINGS, LOAN)"
164
- required: true
165
- schema:
166
- type: integer
167
- format: int32
168
- - name: fromAccountId
169
- in: query
170
- description: Customer funds source account
171
- required: true
172
- schema:
173
- type: integer
174
- format: int32
175
  responses:
176
- default:
177
- description: default response
178
  content:
179
- application/xml:
180
- schema:
181
- $ref: "#/components/schemas/Account"
182
  application/json:
183
  schema:
184
- $ref: "#/components/schemas/Account"
185
- /deposit:
 
 
 
 
 
 
 
 
 
186
  post:
187
- tags:
188
- - Accounts
189
- summary: Deposit funds
190
- operationId: deposit
 
 
191
  parameters:
192
- - name: accountId
193
- in: query
194
- description: Customer funds target account
195
- required: true
196
- schema:
197
- type: integer
198
- format: int32
199
- - name: amount
200
- in: query
201
- description: Amount
202
  required: true
203
- schema:
204
- type: number
 
 
 
 
 
 
 
205
  responses:
206
- default:
207
- description: default response
208
  content:
209
- application/xml:
210
- schema:
211
- type: string
212
  application/json:
213
  schema:
214
- type: string
215
- /accounts/{accountId}:
216
- get:
217
- tags:
218
- - Accounts
219
- summary: Get Account by Id
220
- operationId: getAccount
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  parameters:
222
- - name: accountId
223
- in: path
224
- description: Account id
 
 
 
225
  required: true
226
- schema:
227
- type: integer
228
- format: int32
 
 
 
 
 
229
  responses:
230
- default:
231
- description: default response
232
- content:
233
- application/xml:
234
- schema:
235
- $ref: "#/components/schemas/Account"
236
- application/json:
237
- schema:
238
- $ref: "#/components/schemas/Account"
239
- /customers/{customerId}/accounts:
240
  get:
241
- tags:
242
- - Customers
243
- - Accounts
244
- summary: Get Customer Accounts
245
- operationId: getAccounts
246
  parameters:
247
- - name: customerId
248
- in: path
249
- description: Customer's id
250
- required: true
251
- schema:
252
- type: integer
253
- format: int32
 
 
 
 
 
 
 
 
 
 
 
254
  responses:
255
- default:
256
- description: default response
257
  content:
258
- application/xml:
259
- schema:
260
- type: array
261
- items:
262
- $ref: "#/components/schemas/Account"
263
  application/json:
264
  schema:
265
- type: array
266
- items:
267
- $ref: "#/components/schemas/Account"
268
- /customers/{customerId}:
 
 
 
 
269
  get:
270
- tags:
271
- - Customers
272
- summary: Get Customer Details
273
- operationId: getCustomer
274
  parameters:
275
- - name: customerId
276
- in: path
277
- description: Customer's id
278
- required: true
279
- schema:
280
- type: integer
281
- format: int32
282
  responses:
283
- default:
284
- description: default response
285
  content:
286
- application/xml:
287
- schema:
288
- $ref: "#/components/schemas/Customer"
289
  application/json:
290
  schema:
291
- $ref: "#/components/schemas/Customer"
292
- /positions/{positionId}:
293
- get:
294
- tags:
295
- - Positions
296
- summary: Get Position by id
297
- operationId: getPosition
 
 
 
 
 
 
 
 
 
298
  parameters:
299
- - name: positionId
300
- in: path
301
- description: Unique identifier for the position
 
 
 
302
  required: true
303
- schema:
304
- type: integer
305
- format: int32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  responses:
307
- default:
308
- description: default response
309
  content:
310
- application/xml:
311
- schema:
312
- $ref: "#/components/schemas/Position"
313
  application/json:
314
  schema:
315
- $ref: "#/components/schemas/Position"
316
- /positions/{positionId}/{startDate}/{endDate}:
317
- get:
318
- tags:
319
- - Positions
320
- summary: Get Position history by id within a date range
321
- operationId: getPositionHistory
 
 
 
 
 
 
 
 
 
 
 
 
 
322
  parameters:
323
- - name: positionId
324
- in: path
325
- description: Unique identifier for the position
 
 
 
326
  required: true
327
- schema:
328
- type: integer
329
- format: int32
330
- - name: startDate
331
- in: path
332
- description: Search starting date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  required: true
334
- schema:
335
- type: string
336
- - name: endDate
337
- in: path
338
- description: Search ending date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  required: true
340
- schema:
341
- type: string
 
 
 
 
 
 
342
  responses:
343
- default:
344
- description: default response
345
- content:
346
- application/xml:
347
- schema:
348
- type: array
349
- items:
350
- $ref: "#/components/schemas/HistoryPoint"
351
- application/json:
352
- schema:
353
- type: array
354
- items:
355
- $ref: "#/components/schemas/HistoryPoint"
356
- /customers/{customerId}/positions:
357
- get:
358
- tags:
359
- - Customers
360
- - Positions
361
- summary: Get Positions for Customer
362
- operationId: getPositions
363
  parameters:
364
- - name: customerId
365
- in: path
366
- description: Customer's id
 
 
 
367
  required: true
368
- schema:
369
- type: integer
370
- format: int32
 
 
 
 
 
371
  responses:
372
- default:
373
- description: default response
374
- content:
375
- application/xml:
376
- schema:
377
- type: array
378
- items:
379
- $ref: "#/components/schemas/Position"
380
- application/json:
381
- schema:
382
- type: array
383
- items:
384
- $ref: "#/components/schemas/Position"
385
- /transactions/{transactionId}:
386
  get:
387
- tags:
388
- - Transactions
389
- summary: Get the transaction for the id
390
- operationId: getTransaction
391
  parameters:
392
- - name: transactionId
393
- in: path
394
- description: Unique identifier for the transaction
395
- required: true
396
- schema:
397
- type: integer
398
- format: int32
 
 
 
 
 
 
 
 
 
 
 
399
  responses:
400
- default:
401
- description: default response
402
  content:
403
- application/xml:
404
- schema:
405
- $ref: "#/components/schemas/Transaction"
406
  application/json:
407
  schema:
408
- $ref: "#/components/schemas/Transaction"
409
- /accounts/{accountId}/transactions:
 
 
 
 
 
 
410
  get:
411
- tags:
412
- - Accounts
413
- - Transactions
414
- summary: Get the list of Transactions for the account
415
- operationId: getTransactions
416
  parameters:
417
- - name: accountId
418
- in: path
419
- description: Account id
420
- required: true
421
- schema:
422
- type: integer
423
- format: int32
424
  responses:
425
- default:
426
- description: default response
427
  content:
428
- application/xml:
429
- schema:
430
- type: array
431
- items:
432
- $ref: "#/components/schemas/Transaction"
433
  application/json:
434
  schema:
435
- type: array
436
- items:
437
- $ref: "#/components/schemas/Transaction"
438
- /accounts/{accountId}/transactions/amount/{amount}:
439
- get:
440
- tags:
441
- - Accounts
442
- - Transactions
443
- summary: Create transactions by amount for account
444
- operationId: getTransactionsByAmount
 
 
 
 
 
 
 
 
445
  parameters:
446
- - name: accountId
447
- in: path
448
- description: Account id
449
- required: true
450
- schema:
451
- type: integer
452
- format: int32
453
- - name: amount
454
- in: path
455
- description: Amount
456
  required: true
457
- schema:
458
- type: number
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  responses:
460
- default:
461
- description: default response
462
  content:
463
- application/xml:
464
- schema:
465
- type: array
466
- items:
467
- $ref: "#/components/schemas/Transaction"
468
  application/json:
469
  schema:
470
- type: array
471
- items:
472
- $ref: "#/components/schemas/Transaction"
473
- /accounts/{accountId}/transactions/month/{month}/type/{type}:
474
- get:
475
- tags:
476
- - Accounts
477
- - Transactions
478
- summary: Fetch transactions by month and type for account
479
- operationId: getTransactionsByMonthAndType
 
 
 
 
 
 
 
 
 
 
 
 
480
  parameters:
481
- - name: accountId
482
- in: path
483
- description: Account id
 
 
 
484
  required: true
485
- schema:
486
- type: integer
487
- format: int32
488
- - name: month
489
- in: path
490
- description: Month to use for the search range
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
  required: true
492
- schema:
493
- type: string
494
- - name: type
495
- in: path
496
- description: "Transaction type (CREDIT, DEBIT)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
  required: true
498
- schema:
499
- type: string
 
 
 
 
 
 
500
  responses:
501
- default:
502
- description: default response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503
  content:
504
- application/xml:
505
- schema:
506
- type: array
507
- items:
508
- $ref: "#/components/schemas/Transaction"
509
  application/json:
510
  schema:
511
- type: array
512
- items:
513
- $ref: "#/components/schemas/Transaction"
514
- /accounts/{accountId}/transactions/fromDate/{fromDate}/toDate/{toDate}:
 
 
 
 
 
 
 
 
 
515
  get:
516
- tags:
517
- - Accounts
518
- - Transactions
519
- summary: Fetch transactions for date range for account
520
- operationId: getTransactionsByToFromDate
 
521
  parameters:
522
- - name: accountId
523
- in: path
524
- description: Account id
525
- required: true
526
- schema:
527
- type: integer
528
- format: int32
529
- - name: fromDate
530
- in: path
531
- description: Search starting date
532
- required: true
533
- schema:
534
- type: string
535
- - name: toDate
536
- in: path
537
- description: Search ending date
538
- required: true
539
- schema:
540
- type: string
541
  responses:
542
- default:
543
- description: default response
544
  content:
545
- application/xml:
546
- schema:
547
- type: array
548
- items:
549
- $ref: "#/components/schemas/Transaction"
550
  application/json:
551
  schema:
552
- type: array
553
- items:
554
- $ref: "#/components/schemas/Transaction"
555
- /accounts/{accountId}/transactions/onDate/{onDate}:
 
 
 
 
 
 
 
 
 
 
 
556
  get:
557
- tags:
558
- - Accounts
559
- - Transactions
560
- summary: Fetch transactions for a specific date for account
561
- operationId: getTransactionsOnDate
 
562
  parameters:
563
- - name: accountId
564
- in: path
565
- description: Account id
566
- required: true
567
- schema:
568
- type: integer
569
- format: int32
570
- - name: onDate
571
- in: path
572
- description: Search specific date
573
- required: true
574
- schema:
575
- type: string
576
  responses:
577
- default:
578
- description: default response
579
  content:
580
- application/xml:
581
- schema:
582
- type: array
583
- items:
584
- $ref: "#/components/schemas/Transaction"
585
  application/json:
586
  schema:
587
- type: array
588
- items:
589
- $ref: "#/components/schemas/Transaction"
590
- /initializeDB:
591
- post:
592
- tags:
593
- - Database
594
- summary: Initialize the Database
595
- operationId: initializeDB
596
- responses:
597
- default:
598
- description: default response
599
- content:
600
- application/xml: {}
601
- application/json: {}
602
- /login/{username}/{password}:
603
  get:
604
- tags:
605
- - Misc
606
- summary: Login (john/demo)
607
- operationId: login
 
 
608
  parameters:
609
- - name: username
610
- in: path
611
- description: Customer's user name
612
- required: true
613
- schema:
614
- type: string
615
- - name: password
616
- in: path
617
- description: Customer's password
618
- required: true
619
- schema:
620
- type: string
 
621
  responses:
622
- default:
623
- description: default response
624
  content:
625
- application/xml:
626
- schema:
627
- $ref: "#/components/schemas/Customer"
628
  application/json:
629
  schema:
630
- $ref: "#/components/schemas/Customer"
631
- /requestLoan:
632
- post:
633
- tags:
634
- - Loans
635
- summary: Request a loan
636
- operationId: requestLoan
 
 
 
 
 
 
 
 
 
637
  parameters:
638
- - name: customerId
639
- in: query
640
- description: Customer's id
641
- required: true
642
- schema:
643
- type: integer
644
- format: int32
645
- - name: amount
646
- in: query
647
- description: Amount
648
- required: true
649
- schema:
650
- type: number
651
- - name: downPayment
652
- in: query
653
- description: Downpayment for the loan
654
- required: true
655
- schema:
656
- type: number
657
- - name: fromAccountId
658
- in: query
659
- description: Customer funds source account
660
- required: true
661
- schema:
662
- type: integer
663
- format: int32
664
  responses:
665
- default:
666
- description: default response
667
  content:
668
- application/xml:
669
- schema:
670
- $ref: "#/components/schemas/LoanResponse"
671
  application/json:
672
  schema:
673
- $ref: "#/components/schemas/LoanResponse"
674
- /customers/{customerId}/sellPosition:
 
 
 
 
 
 
 
 
 
 
 
675
  post:
676
- tags:
677
- - Positions
678
- summary: Sell a Position
679
- operationId: sellPosition
680
  parameters:
681
- - name: customerId
682
- in: path
683
- description: Customer's id
684
- required: true
685
- schema:
686
- type: integer
687
- format: int32
688
- - name: accountId
689
- in: query
690
- description: Customer funds target account
691
- required: true
692
- schema:
693
- type: integer
694
- format: int32
695
- - name: positionId
696
- in: query
697
- description: Unique identifier for the position
698
- required: true
699
- schema:
700
- type: integer
701
- format: int32
702
- - name: shares
703
- in: query
704
- description: number of shares
705
- required: true
706
- schema:
707
- type: integer
708
- format: int32
709
- - name: pricePerShare
710
- in: query
711
- description: Price of each share
712
  required: true
713
- schema:
714
- type: number
 
 
 
 
 
 
 
 
 
715
  responses:
716
- default:
717
- description: default response
718
  content:
719
- application/xml:
720
- schema:
721
- type: array
722
- items:
723
- $ref: "#/components/schemas/Position"
724
  application/json:
725
  schema:
726
- type: array
727
- items:
728
- $ref: "#/components/schemas/Position"
729
- /setParameter/{name}/{value}:
 
 
 
 
 
 
 
 
 
 
730
  post:
731
- tags:
732
- - Misc
733
- summary: Set Parameters
734
- operationId: setParameter
735
  parameters:
736
- - name: name
737
- in: path
738
- description: Parameter Name
739
- required: true
740
- schema:
741
- type: string
742
- - name: value
743
- in: path
744
- description: Parameter Value
745
  required: true
746
- schema:
747
- type: string
748
- responses:
749
- default:
750
- description: default response
751
- content:
752
- application/xml: {}
753
- application/json: {}
754
- /shutdownJmsListener:
755
- post:
756
- tags:
757
- - JMS
758
- summary: Stop JMS Listener
759
- operationId: shutdownJmsListener
760
- responses:
761
- default:
762
- description: default response
763
- content:
764
- application/xml: {}
765
- application/json: {}
766
- /startupJmsListener:
767
- post:
768
- tags:
769
- - JMS
770
- summary: Start JMS Listener
771
- operationId: startupJmsListener
772
  responses:
773
- default:
774
- description: default response
775
- content:
776
- application/xml: {}
777
- application/json: {}
778
- /transfer:
 
 
779
  post:
780
- tags:
781
- - Accounts
782
- summary: Transfer funds
783
- operationId: transfer
 
 
 
784
  parameters:
785
- - name: fromAccountId
786
- in: query
787
- description: Customer funds source account
788
- required: true
789
- schema:
790
- type: integer
791
- format: int32
792
- - name: toAccountId
793
- in: query
794
- description: Customer funds target account
795
- required: true
796
- schema:
797
- type: integer
798
- format: int32
799
- - name: amount
800
- in: query
801
- description: Amount
802
  required: true
803
- schema:
804
- type: number
 
 
 
 
 
 
805
  responses:
806
- default:
807
- description: default response
808
- content:
809
- application/xml:
810
- schema:
811
- type: string
812
- application/json:
813
- schema:
814
- type: string
815
- /customers/update/{customerId}:
816
  post:
817
- tags:
818
- - Customers
819
- summary: Update customer information
820
- operationId: updateCustomer
 
 
 
821
  parameters:
822
- - name: customerId
823
- in: path
824
- description: Customer's id
825
- required: true
826
- schema:
827
- type: integer
828
- format: int32
829
- - name: firstName
830
- in: query
831
- description: Customer's given (first) name
832
- required: true
833
- schema:
834
- type: string
835
- - name: lastName
836
- in: query
837
- description: Customer's surname (last name)
838
- required: true
839
- schema:
840
- type: string
841
- - name: street
842
- in: query
843
- description: Street Address including bilding number and apartment (if any)
844
- required: true
845
- schema:
846
- type: string
847
- - name: city
848
- in: query
849
- description: City
850
- required: true
851
- schema:
852
- type: string
853
- - name: state
854
- in: query
855
- description: US state or Region name
856
- required: true
857
- schema:
858
- type: string
859
- - name: zipCode
860
- in: query
861
- description: ZIP code or province id
862
- required: true
863
- schema:
864
- type: string
865
- - name: phoneNumber
866
- in: query
867
- description: Contact Phone Number
868
- required: true
869
- schema:
870
- type: string
871
- - name: ssn
872
- in: query
873
- description: Social Security Number
874
- required: true
875
- schema:
876
- type: string
877
- - name: username
878
- in: query
879
- description: Customer's user name
880
- required: true
881
- schema:
882
- type: string
883
- - name: password
884
- in: query
885
- description: Customer's password
886
  required: true
887
- schema:
888
- type: string
 
 
 
 
 
 
 
889
  responses:
890
- default:
891
- description: default response
892
- content:
893
- application/xml:
894
- schema:
895
- type: string
896
- application/json:
897
- schema:
898
- type: string
899
- /withdraw:
900
  post:
901
- tags:
902
- - Accounts
903
- summary: Withdraw funds
904
- operationId: withdraw
 
 
905
  parameters:
906
- - name: accountId
907
- in: query
908
- description: Customer funds source account
909
- required: true
910
- schema:
911
- type: integer
912
- format: int32
913
- - name: amount
914
- in: query
915
- description: Amount
916
  required: true
917
- schema:
918
- type: number
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
919
  responses:
920
- default:
921
- description: default response
 
 
 
922
  content:
923
- application/xml:
924
- schema:
925
- type: string
926
- application/json:
927
- schema:
928
- type: string
929
- components:
930
- schemas:
931
- BillPayResult:
932
- type: object
933
- properties:
934
- payeeName:
935
- type: string
936
- amount:
937
- type: number
938
- accountId:
939
- type: integer
940
- format: int32
941
- xml:
942
- name: billPayResult
943
- Address:
944
- type: object
945
- properties:
946
- street:
947
- type: string
948
- city:
949
- type: string
950
- state:
951
- type: string
952
- zipCode:
953
- type: string
954
- Payee:
955
- type: object
956
- properties:
957
- name:
958
- type: string
959
- address:
960
- $ref: "#/components/schemas/Address"
961
- phoneNumber:
962
- type: string
963
- accountNumber:
964
- type: integer
965
- format: int32
966
- Position:
967
- type: object
968
- properties:
969
- positionId:
970
- type: integer
971
- format: int32
972
- customerId:
973
- type: integer
974
- format: int32
975
- name:
976
- type: string
977
- symbol:
978
- type: string
979
- shares:
980
- type: integer
981
- format: int32
982
- purchasePrice:
983
- type: number
984
- xml:
985
- name: position
986
- Account:
987
- type: object
988
- properties:
989
- id:
990
- type: integer
991
- format: int32
992
- customerId:
993
- type: integer
994
- format: int32
995
- type:
996
- type: string
997
- enum:
998
- - CHECKING
999
- - SAVINGS
1000
- - LOAN
1001
- balance:
1002
- type: number
1003
- xml:
1004
- name: account
1005
- Customer:
1006
- type: object
1007
- properties:
1008
- id:
1009
- type: integer
1010
- format: int32
1011
- firstName:
1012
- type: string
1013
- lastName:
1014
- type: string
1015
- address:
1016
- $ref: "#/components/schemas/Address"
1017
- phoneNumber:
1018
- type: string
1019
- ssn:
1020
- type: string
1021
- xml:
1022
- name: customer
1023
- HistoryPoint:
1024
- type: object
1025
- properties:
1026
- symbol:
1027
- type: string
1028
- date:
1029
- type: string
1030
- format: date-time
1031
- closingPrice:
1032
- type: number
1033
- xml:
1034
- name: historyPoint
1035
- namespace: http://service.parabank.parasoft.com/
1036
- Transaction:
1037
- type: object
1038
- properties:
1039
- id:
1040
- type: integer
1041
- format: int32
1042
- accountId:
1043
- type: integer
1044
- format: int32
1045
- type:
1046
- type: string
1047
- enum:
1048
- - Credit
1049
- - Debit
1050
- date:
1051
- type: string
1052
- format: date-time
1053
- amount:
1054
- type: number
1055
- description:
1056
- type: string
1057
- xml:
1058
- name: transaction
1059
- LoanResponse:
1060
- required:
1061
- - loanProviderName
1062
- type: object
1063
- properties:
1064
- responseDate:
1065
- type: string
1066
- format: date-time
1067
- loanProviderName:
1068
- type: string
1069
- approved:
1070
- type: boolean
1071
- message:
1072
- type: string
1073
- accountId:
1074
- type: integer
1075
- format: int32
1076
- xml:
1077
- name: loanResponse
1078
- namespace: http://service.parabank.parasoft.com/
 
1
+ openapi: "3.0.3"
2
+
3
  info:
4
+ title: EarWax CRM Mobile API
5
+ version: "1"
6
+ description: |
7
+ JWT-authenticated REST API for the React Native mobile app.
8
+ All protected routes require `Authorization: Bearer <access_token>`.
9
+
10
+ **URL mapping:** All endpoints share one PHP entry point. The semantic paths
11
+ in this spec (e.g. `/auth/login`) map to the `?action=` query parameter on
12
+ the real server URL. Always append `&v=1` (optional for v1, required for
13
+ future versions).
14
+
15
+ **Example:** `POST https://yourcrm.com/crm/backend/mobile_api.php?action=login&v=1`
16
+
17
+ **Error codes** returned in `error_code` on every failure response:
18
+
19
+ | Code | Meaning |
20
+ |------|---------|
21
+ | `ERR_AUTH` | Invalid or expired token / wrong credentials |
22
+ | `ERR_FORBIDDEN` | Authenticated but role is insufficient |
23
+ | `ERR_NOT_FOUND` | Resource does not exist |
24
+ | `ERR_VALIDATION` | Missing or invalid input field |
25
+ | `ERR_CONFLICT` | Uniqueness constraint violated |
26
+ | `ERR_METHOD` | Wrong HTTP method for this action |
27
+ | `ERR_VERSION` | Unsupported API version |
28
+ | `ERR_RATE_LIMIT` | Too many requests (100 / 60 s per IP) |
29
+ | `ERR_DB` | Database error |
30
+ | `ERR_SERVER` | Unexpected server error |
31
+
32
  servers:
33
+ - url: https://yourcrm.com/crm/backend/mobile_api.php
34
+ description: "Production — every path maps to ?action=<action>&v=1"
35
+
36
+ security:
37
+ - bearerAuth: []
38
+
39
  tags:
40
+ - { name: Auth, description: Authentication and token management }
41
+ - { name: Leads, description: Lead CRUD }
42
+ - { name: Appointments, description: Appointment CRUD }
43
+ - { name: Courses, description: Course catalogue (read-only) }
44
+ - { name: Users, description: CRM user management (admin only) }
45
+ - { name: Stats, description: Dashboard and analytics }
46
+ - { name: Search, description: Cross-entity search }
47
+ - { name: Notifications, description: Push notification device registration }
48
+ - { name: Invoice, description: PDF invoice generation }
49
+
50
+ # ═══════════════════════════════════════════════════════════════════════════════
51
+ # Reusable components
52
+ # ═══════════════════════════════════════════════════════════════════════════════
53
+
54
+ components:
55
+
56
+ securitySchemes:
57
+ bearerAuth:
58
+ type: http
59
+ scheme: bearer
60
+ bearerFormat: JWT
61
+
62
+ # ── Reusable parameters ────────────────────────────────────────────────────
63
+
64
+ parameters:
65
+
66
+ ApiVersion:
67
+ name: v
68
+ in: query
69
+ description: "API version (only 1 is supported)"
70
+ schema: { type: integer, enum: [1], default: 1 }
71
+
72
+ PageParam:
73
+ name: page
74
+ in: query
75
+ schema: { type: integer, minimum: 1, default: 1 }
76
+
77
+ IdQuery:
78
+ name: id
79
+ in: query
80
+ required: true
81
+ schema: { type: integer }
82
+
83
+ # ── Schemas ────────────────────────────────────────────────────────────────
84
+
85
+ schemas:
86
+
87
+ # ── Response envelopes ───────────────────────────────────────────────────
88
+
89
+ SuccessEnvelope:
90
+ type: object
91
+ properties:
92
+ success: { type: boolean, example: true }
93
+ message: { type: string }
94
+ data: { type: object }
95
+
96
+ ErrorEnvelope:
97
+ type: object
98
+ properties:
99
+ success:
100
+ type: boolean
101
+ example: false
102
+ message:
103
+ type: string
104
+ example: "Lead not found."
105
+ error_code:
106
+ type: string
107
+ enum:
108
+ - ERR_AUTH
109
+ - ERR_FORBIDDEN
110
+ - ERR_NOT_FOUND
111
+ - ERR_VALIDATION
112
+ - ERR_CONFLICT
113
+ - ERR_METHOD
114
+ - ERR_VERSION
115
+ - ERR_RATE_LIMIT
116
+ - ERR_DB
117
+ - ERR_SERVER
118
+ - ERR_UNKNOWN
119
+ data:
120
+ type: object
121
+
122
+ # ── Domain entities ──────────────────────────────────────────────────────
123
+
124
+ Lead:
125
+ type: object
126
+ properties:
127
+ id: { type: integer, readOnly: true }
128
+ first_name: { type: string }
129
+ last_name: { type: string }
130
+ email: { type: string, format: email }
131
+ phone: { type: string }
132
+ gender: { type: string }
133
+ preferred_name: { type: string }
134
+ qualification: { type: string }
135
+ experience: { type: string }
136
+ device_type: { type: string }
137
+ source: { type: string }
138
+ status:
139
+ type: string
140
+ enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed]
141
+ address_line1: { type: string }
142
+ address_line2: { type: string }
143
+ city: { type: string }
144
+ county: { type: string }
145
+ postcode: { type: string }
146
+ country: { type: string }
147
+ shipping_address_line1: { type: string }
148
+ shipping_address_line2: { type: string }
149
+ shipping_city: { type: string }
150
+ shipping_county: { type: string }
151
+ shipping_postcode: { type: string }
152
+ shipping_country: { type: string }
153
+ shipping_phone: { type: string }
154
+ notes: { type: string }
155
+ archived: { type: integer, enum: [0, 1] }
156
+ lead_date: { type: string, format: date }
157
+ created_at: { type: string, format: date-time, readOnly: true }
158
+ updated_at: { type: string, format: date-time, readOnly: true }
159
+ appointment_count:
160
+ type: integer
161
+ readOnly: true
162
+ description: "Present on list responses only"
163
+
164
+ Appointment:
165
+ type: object
166
+ properties:
167
+ id: { type: integer, readOnly: true }
168
+ appointment_ref: { type: string, readOnly: true, example: "APT-A3B2C1" }
169
+ lead_id: { type: integer }
170
+ course_id: { type: integer, nullable: true }
171
+ appointment_date: { type: string, format: date }
172
+ appointment_time: { type: string, example: "09:00" }
173
+ duration: { type: string, example: "1 day" }
174
+ status:
175
+ type: string
176
+ enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show]
177
+ amount_paid: { type: number, format: float }
178
+ transaction_fee: { type: number, format: float }
179
+ payment_method: { type: string }
180
+ payment_ref: { type: string }
181
+ payment_date: { type: string, format: date, nullable: true }
182
+ training_location: { type: string, nullable: true }
183
+ training_address: { type: string, nullable: true }
184
+ course_type: { type: string, nullable: true }
185
+ course_name:
186
+ type: string
187
+ readOnly: true
188
+ description: "Resolved from course_id or woo_product_name"
189
+ notes: { type: string }
190
+ archived: { type: integer, enum: [0, 1] }
191
+ status_changed_at: { type: string, format: date-time, readOnly: true, nullable: true }
192
+ created_at: { type: string, format: date-time, readOnly: true }
193
+ updated_at: { type: string, format: date-time, readOnly: true }
194
+
195
+ AppointmentSummary:
196
+ description: "Lightweight row returned in list and dashboard responses"
197
+ type: object
198
+ properties:
199
+ id: { type: integer }
200
+ appointment_ref: { type: string }
201
+ appointment_date: { type: string, format: date }
202
+ appointment_time: { type: string }
203
+ status: { type: string }
204
+ amount_paid: { type: number }
205
+ payment_method: { type: string }
206
+ training_location: { type: string }
207
+ course_type: { type: string }
208
+ duration: { type: string }
209
+ course_name: { type: string }
210
+ lead_id: { type: integer }
211
+ student_name: { type: string }
212
+ student_email: { type: string }
213
+ student_phone: { type: string }
214
+
215
+ Course:
216
+ type: object
217
+ properties:
218
+ id: { type: integer }
219
+ name: { type: string }
220
+ location: { type: string }
221
+ course_type: { type: string }
222
+ price: { type: number }
223
+ duration: { type: string }
224
+ max_capacity: { type: integer }
225
+ description: { type: string }
226
+
227
+ User:
228
+ type: object
229
+ properties:
230
+ id: { type: integer, readOnly: true }
231
+ username: { type: string }
232
+ full_name: { type: string }
233
+ email: { type: string, format: email, nullable: true }
234
+ role: { type: string, enum: [admin, staff] }
235
+ is_active: { type: boolean }
236
+ last_login: { type: string, format: date-time, readOnly: true, nullable: true }
237
+
238
+ ActivityEntry:
239
+ type: object
240
+ properties:
241
+ action: { type: string }
242
+ description: { type: string }
243
+ created_by: { type: string }
244
+ created_at: { type: string, format: date-time }
245
+
246
+ SearchResult:
247
+ type: object
248
+ properties:
249
+ id: { type: integer }
250
+ first_name: { type: string }
251
+ last_name: { type: string }
252
+ email: { type: string }
253
+ phone: { type: string }
254
+ status: { type: string }
255
+ city: { type: string }
256
+ created_at: { type: string, format: date-time }
257
+ appointment_count:{ type: integer }
258
+
259
+ TokenPair:
260
+ type: object
261
+ properties:
262
+ access_token: { type: string }
263
+ refresh_token: { type: string }
264
+ expires_in: { type: integer, description: "Access token TTL in seconds (3600)" }
265
+ refresh_expires_in: { type: integer, description: "Refresh token TTL in seconds (2592000)" }
266
+
267
+ # ── Pagination ───────────────────────────────────────────────────────────
268
+
269
+ Pagination:
270
+ type: object
271
+ properties:
272
+ total: { type: integer }
273
+ page: { type: integer }
274
+ per_page: { type: integer, example: 20 }
275
+ total_pages: { type: integer }
276
+
277
+ PaginatedLeads:
278
+ allOf:
279
+ - $ref: '#/components/schemas/Pagination'
280
+ - type: object
281
+ properties:
282
+ leads:
283
+ type: array
284
+ items: { $ref: '#/components/schemas/Lead' }
285
+
286
+ PaginatedAppointments:
287
+ allOf:
288
+ - $ref: '#/components/schemas/Pagination'
289
+ - type: object
290
+ properties:
291
+ appointments:
292
+ type: array
293
+ items: { $ref: '#/components/schemas/AppointmentSummary' }
294
+
295
+ # ── Composite response data ──────────────────────────────────────────────
296
+
297
+ LeadDetail:
298
+ type: object
299
+ properties:
300
+ lead:
301
+ $ref: '#/components/schemas/Lead'
302
+ appointments:
303
+ type: array
304
+ items: { $ref: '#/components/schemas/Appointment' }
305
+ activity:
306
+ type: array
307
+ items: { $ref: '#/components/schemas/ActivityEntry' }
308
+
309
+ AppointmentDetail:
310
+ type: object
311
+ properties:
312
+ appointment:
313
+ allOf:
314
+ - $ref: '#/components/schemas/Appointment'
315
+ - type: object
316
+ description: "Includes joined lead fields and course_location"
317
+ properties:
318
+ course_location: { type: string }
319
+ first_name: { type: string }
320
+ last_name: { type: string }
321
+ email: { type: string }
322
+ phone: { type: string }
323
+ gender: { type: string }
324
+ qualification: { type: string }
325
+ activity:
326
+ type: array
327
+ items: { $ref: '#/components/schemas/ActivityEntry' }
328
+
329
+ DashboardStats:
330
+ type: object
331
+ properties:
332
+ total_leads: { type: integer }
333
+ enrolled: { type: integer }
334
+ new_today: { type: integer }
335
+ upcoming_appointments: { type: integer }
336
+ today_appointments: { type: integer }
337
+ total_revenue: { type: number, description: "Admin only" }
338
+ month_revenue: { type: number, description: "Admin only" }
339
+
340
+ DashboardData:
341
+ type: object
342
+ properties:
343
+ stats:
344
+ $ref: '#/components/schemas/DashboardStats'
345
+ upcoming:
346
+ type: array
347
+ description: "Next 5 upcoming appointments"
348
+ items: { $ref: '#/components/schemas/AppointmentSummary' }
349
+ recent_leads:
350
+ type: array
351
+ description: "5 most recently created leads"
352
+ items: { $ref: '#/components/schemas/Lead' }
353
+
354
+ RevenueByMonth:
355
+ type: object
356
+ properties:
357
+ month: { type: string, example: "2026-01" }
358
+ bookings: { type: integer }
359
+ revenue: { type: number }
360
+
361
+ StatusCount:
362
+ type: object
363
+ properties:
364
+ status: { type: string }
365
+ count: { type: integer }
366
+
367
+ SourceCount:
368
+ type: object
369
+ properties:
370
+ source: { type: string }
371
+ count: { type: integer }
372
+
373
+ StatsData:
374
+ type: object
375
+ properties:
376
+ revenue_by_month:
377
+ type: array
378
+ items: { $ref: '#/components/schemas/RevenueByMonth' }
379
+ lead_breakdown:
380
+ type: array
381
+ items: { $ref: '#/components/schemas/StatusCount' }
382
+ appointment_breakdown:
383
+ type: array
384
+ items: { $ref: '#/components/schemas/StatusCount' }
385
+ top_sources:
386
+ type: array
387
+ items: { $ref: '#/components/schemas/SourceCount' }
388
+ filters:
389
+ type: object
390
+ properties:
391
+ date_from: { type: string, format: date, nullable: true }
392
+ date_to: { type: string, format: date, nullable: true }
393
+
394
+ # ── Reusable responses ─────────────────────────────────────────────────────
395
+
396
+ responses:
397
+
398
+ Unauthorised:
399
+ description: Invalid or expired access token
400
+ content:
401
+ application/json:
402
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
403
+ example: { success: false, message: "Unauthorised — invalid or expired token.", error_code: ERR_AUTH, data: {} }
404
+
405
+ Forbidden:
406
+ description: Authenticated but role is insufficient (admin required)
407
+ content:
408
+ application/json:
409
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
410
+ example: { success: false, message: "Admin access required.", error_code: ERR_FORBIDDEN, data: {} }
411
+
412
+ NotFound:
413
+ description: Resource does not exist
414
+ content:
415
+ application/json:
416
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
417
+ example: { success: false, message: "Lead not found.", error_code: ERR_NOT_FOUND, data: {} }
418
+
419
+ ValidationError:
420
+ description: Missing or invalid input field
421
+ content:
422
+ application/json:
423
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
424
+ example: { success: false, message: "email is required.", error_code: ERR_VALIDATION, data: {} }
425
+
426
+ Conflict:
427
+ description: Uniqueness constraint violated (e.g. duplicate username)
428
+ content:
429
+ application/json:
430
+ schema: { $ref: '#/components/schemas/ErrorEnvelope' }
431
+ example: { success: false, message: "Username already exists.", error_code: ERR_CONFLICT, data: {} }
432
+
433
+ SimpleOk:
434
+ description: Action completed successfully
435
+ content:
436
+ application/json:
437
+ schema:
438
+ type: object
439
+ properties:
440
+ success: { type: boolean, example: true }
441
+ message: { type: string }
442
+ data: { type: object }
443
+
444
+ # ═══════════════════════════════════════════════════════════════════════════════
445
+ # Paths
446
+ # ═══════════════════════════════════════════════════════════════════════════════
447
+
448
  paths:
449
+
450
+ # ── Auth ───────────────────────────────────────────────────────────────────
451
+
452
+ /auth/login:
453
  post:
454
+ operationId: login
455
+ summary: Authenticate and receive token pair
456
+ description: |
457
+ Returns a 1-hour access token and a 30-day refresh token.
458
+ **Real URL:** `POST ?action=login`
459
+ security: []
460
+ tags: [Auth]
461
  parameters:
462
+ - name: action
463
+ in: query
464
+ required: true
465
+ schema: { type: string, enum: [login] }
466
+ - $ref: '#/components/parameters/ApiVersion'
 
 
 
 
 
 
 
 
467
  requestBody:
468
+ required: true
469
  content:
470
  application/json:
471
  schema:
472
+ type: object
473
+ required: [username, password]
474
+ properties:
475
+ username: { type: string, example: exceladmin }
476
+ password: { type: string, format: password }
477
  responses:
478
+ "200":
479
+ description: Login successful
480
  content:
 
 
 
481
  application/json:
482
  schema:
483
+ type: object
484
+ properties:
485
+ success: { type: boolean, example: true }
486
+ message: { type: string }
487
+ data:
488
+ allOf:
489
+ - $ref: '#/components/schemas/TokenPair'
490
+ - type: object
491
+ properties:
492
+ user: { $ref: '#/components/schemas/User' }
493
+ "400": { $ref: '#/components/responses/ValidationError' }
494
+ "401": { $ref: '#/components/responses/Unauthorised' }
495
+
496
+ /auth/refresh:
497
  post:
498
+ operationId: refreshToken
499
+ summary: Rotate refresh token and issue new access token
500
+ description: |
501
+ The old refresh token is invalidated on use (rotation).
502
+ **Real URL:** `POST ?action=refresh`
503
+ security: []
504
+ tags: [Auth]
505
  parameters:
506
+ - name: action
507
+ in: query
508
+ required: true
509
+ schema: { type: string, enum: [refresh] }
510
+ - $ref: '#/components/parameters/ApiVersion'
511
+ requestBody:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  required: true
513
+ content:
514
+ application/json:
515
+ schema:
516
+ type: object
517
+ required: [refresh_token]
518
+ properties:
519
+ refresh_token: { type: string }
520
  responses:
521
+ "200":
522
+ description: New token pair issued
523
  content:
 
 
 
 
 
524
  application/json:
525
  schema:
526
+ type: object
527
+ properties:
528
+ success: { type: boolean, example: true }
529
+ message: { type: string }
530
+ data: { $ref: '#/components/schemas/TokenPair' }
531
+ "401": { $ref: '#/components/responses/Unauthorised' }
532
+
533
+ /auth/logout:
534
  post:
535
+ operationId: logout
536
+ summary: Invalidate all tokens for this user
537
+ description: |
538
+ Increments `token_version`, immediately invalidating all active access tokens
539
+ on all devices. Pass `push_token` to also remove that device's push registration;
540
+ omit to remove all push tokens for this user.
541
+ **Real URL:** `POST ?action=logout`
542
+ tags: [Auth]
543
+ parameters:
544
+ - name: action
545
+ in: query
546
+ required: true
547
+ schema: { type: string, enum: [logout] }
548
+ - $ref: '#/components/parameters/ApiVersion'
549
+ requestBody:
550
+ required: false
551
+ content:
552
+ application/json:
553
+ schema:
554
+ type: object
555
+ properties:
556
+ push_token:
557
+ type: string
558
+ description: "If provided, removes only this device token; otherwise removes all."
559
  responses:
560
+ "200": { $ref: '#/components/responses/SimpleOk' }
561
+ "401": { $ref: '#/components/responses/Unauthorised' }
562
+
563
+ /auth/me:
564
+ get:
565
+ operationId: getMe
566
+ summary: Get current user profile
567
+ description: "**Real URL:** `GET ?action=me`"
568
+ tags: [Auth]
 
 
 
569
  parameters:
570
+ - name: action
571
+ in: query
572
+ required: true
573
+ schema: { type: string, enum: [me] }
574
+ - $ref: '#/components/parameters/ApiVersion'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575
  responses:
576
+ "200":
577
+ description: Current user profile
578
  content:
 
 
 
579
  application/json:
580
  schema:
581
+ type: object
582
+ properties:
583
+ success: { type: boolean, example: true }
584
+ message: { type: string }
585
+ data:
586
+ type: object
587
+ properties:
588
+ user: { $ref: '#/components/schemas/User' }
589
+ "401": { $ref: '#/components/responses/Unauthorised' }
590
+
591
+ /auth/update-profile:
592
  post:
593
+ operationId: updateProfile
594
+ summary: Update own profile (patch-style)
595
+ description: |
596
+ Only send fields you want to change; omitted fields are left as-is.
597
+ **Real URL:** `POST ?action=update_profile`
598
+ tags: [Auth]
599
  parameters:
600
+ - name: action
601
+ in: query
602
+ required: true
603
+ schema: { type: string, enum: [update_profile] }
604
+ - $ref: '#/components/parameters/ApiVersion'
605
+ requestBody:
 
 
 
 
606
  required: true
607
+ content:
608
+ application/json:
609
+ schema:
610
+ type: object
611
+ minProperties: 1
612
+ properties:
613
+ full_name: { type: string }
614
+ email: { type: string, format: email }
615
+ username: { type: string }
616
  responses:
617
+ "200":
618
+ description: Profile updated; returns updated user object
619
  content:
 
 
 
620
  application/json:
621
  schema:
622
+ type: object
623
+ properties:
624
+ success: { type: boolean, example: true }
625
+ message: { type: string }
626
+ data:
627
+ type: object
628
+ properties:
629
+ user: { $ref: '#/components/schemas/User' }
630
+ "400": { $ref: '#/components/responses/ValidationError' }
631
+ "401": { $ref: '#/components/responses/Unauthorised' }
632
+ "409": { $ref: '#/components/responses/Conflict' }
633
+
634
+ /auth/change-password:
635
+ post:
636
+ operationId: changePassword
637
+ summary: Change own password
638
+ description: |
639
+ Invalidates all tokens on all devices after a successful change. The user
640
+ must log in again.
641
+ **Real URL:** `POST ?action=change_password`
642
+ tags: [Auth]
643
  parameters:
644
+ - name: action
645
+ in: query
646
+ required: true
647
+ schema: { type: string, enum: [change_password] }
648
+ - $ref: '#/components/parameters/ApiVersion'
649
+ requestBody:
650
  required: true
651
+ content:
652
+ application/json:
653
+ schema:
654
+ type: object
655
+ required: [current_password, new_password]
656
+ properties:
657
+ current_password: { type: string, format: password }
658
+ new_password: { type: string, format: password, minLength: 8 }
659
  responses:
660
+ "200": { $ref: '#/components/responses/SimpleOk' }
661
+ "400": { $ref: '#/components/responses/ValidationError' }
662
+ "401": { $ref: '#/components/responses/Unauthorised' }
663
+
664
+ # ── Leads ──────────────────────────────────────────────────────────────────
665
+
666
+ /leads:
 
 
 
667
  get:
668
+ operationId: listLeads
669
+ summary: Paginated lead list
670
+ description: "**Real URL:** `GET ?action=leads`"
671
+ tags: [Leads]
 
672
  parameters:
673
+ - name: action
674
+ in: query
675
+ required: true
676
+ schema: { type: string, enum: [leads] }
677
+ - $ref: '#/components/parameters/ApiVersion'
678
+ - $ref: '#/components/parameters/PageParam'
679
+ - name: status
680
+ in: query
681
+ schema: { type: string, enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed] }
682
+ - name: search
683
+ in: query
684
+ schema: { type: string, description: "Matches first_name, last_name, email, or phone" }
685
+ - name: sort
686
+ in: query
687
+ schema: { type: string, enum: [created_at, lead_date, first_name, status], default: created_at }
688
+ - name: dir
689
+ in: query
690
+ schema: { type: string, enum: [asc, desc], default: desc }
691
  responses:
692
+ "200":
693
+ description: Paginated lead list
694
  content:
 
 
 
 
 
695
  application/json:
696
  schema:
697
+ type: object
698
+ properties:
699
+ success: { type: boolean, example: true }
700
+ message: { type: string }
701
+ data: { $ref: '#/components/schemas/PaginatedLeads' }
702
+ "401": { $ref: '#/components/responses/Unauthorised' }
703
+
704
+ /leads/detail:
705
  get:
706
+ operationId: getLead
707
+ summary: Single lead with appointments and activity log
708
+ description: "**Real URL:** `GET ?action=lead&id=<id>`"
709
+ tags: [Leads]
710
  parameters:
711
+ - name: action
712
+ in: query
713
+ required: true
714
+ schema: { type: string, enum: [lead] }
715
+ - $ref: '#/components/parameters/ApiVersion'
716
+ - $ref: '#/components/parameters/IdQuery'
 
717
  responses:
718
+ "200":
719
+ description: Lead detail
720
  content:
 
 
 
721
  application/json:
722
  schema:
723
+ type: object
724
+ properties:
725
+ success: { type: boolean, example: true }
726
+ message: { type: string }
727
+ data: { $ref: '#/components/schemas/LeadDetail' }
728
+ "401": { $ref: '#/components/responses/Unauthorised' }
729
+ "404": { $ref: '#/components/responses/NotFound' }
730
+
731
+ /leads/create:
732
+ post:
733
+ operationId: createLead
734
+ summary: Create a new lead
735
+ description: |
736
+ Triggers a push notification to all admin users.
737
+ **Real URL:** `POST ?action=lead_create`
738
+ tags: [Leads]
739
  parameters:
740
+ - name: action
741
+ in: query
742
+ required: true
743
+ schema: { type: string, enum: [lead_create] }
744
+ - $ref: '#/components/parameters/ApiVersion'
745
+ requestBody:
746
  required: true
747
+ content:
748
+ application/json:
749
+ schema:
750
+ type: object
751
+ required: [first_name, email]
752
+ properties:
753
+ first_name: { type: string }
754
+ last_name: { type: string }
755
+ email: { type: string, format: email }
756
+ phone: { type: string }
757
+ gender: { type: string }
758
+ qualification: { type: string }
759
+ address_line1: { type: string }
760
+ city: { type: string }
761
+ postcode: { type: string }
762
+ country: { type: string, default: "United Kingdom" }
763
+ status: { type: string, enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed], default: new }
764
+ source: { type: string, default: "Mobile App" }
765
+ notes: { type: string }
766
+ lead_date: { type: string, format: date }
767
  responses:
768
+ "201":
769
+ description: Lead created
770
  content:
 
 
 
771
  application/json:
772
  schema:
773
+ type: object
774
+ properties:
775
+ success: { type: boolean, example: true }
776
+ message: { type: string }
777
+ data:
778
+ type: object
779
+ properties:
780
+ lead_id: { type: integer }
781
+ "400": { $ref: '#/components/responses/ValidationError' }
782
+ "401": { $ref: '#/components/responses/Unauthorised' }
783
+
784
+ /leads/update:
785
+ post:
786
+ operationId: updateLead
787
+ summary: Update lead fields (patch-style)
788
+ description: |
789
+ Only send the fields you want to change. If `status` changes, email/SMS
790
+ triggers fire automatically.
791
+ **Real URL:** `POST ?action=lead_update`
792
+ tags: [Leads]
793
  parameters:
794
+ - name: action
795
+ in: query
796
+ required: true
797
+ schema: { type: string, enum: [lead_update] }
798
+ - $ref: '#/components/parameters/ApiVersion'
799
+ requestBody:
800
  required: true
801
+ content:
802
+ application/json:
803
+ schema:
804
+ type: object
805
+ required: [id]
806
+ properties:
807
+ id: { type: integer }
808
+ first_name: { type: string }
809
+ last_name: { type: string }
810
+ email: { type: string, format: email }
811
+ phone: { type: string }
812
+ gender: { type: string }
813
+ preferred_name: { type: string }
814
+ qualification: { type: string }
815
+ experience: { type: string }
816
+ device_type: { type: string }
817
+ source: { type: string }
818
+ address_line1: { type: string }
819
+ address_line2: { type: string }
820
+ city: { type: string }
821
+ county: { type: string }
822
+ postcode: { type: string }
823
+ country: { type: string }
824
+ shipping_address_line1: { type: string }
825
+ shipping_address_line2: { type: string }
826
+ shipping_city: { type: string }
827
+ shipping_county: { type: string }
828
+ shipping_postcode: { type: string }
829
+ shipping_country: { type: string }
830
+ shipping_phone: { type: string }
831
+ notes: { type: string }
832
+ status:
833
+ type: string
834
+ enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed]
835
+ responses:
836
+ "200": { $ref: '#/components/responses/SimpleOk' }
837
+ "400": { $ref: '#/components/responses/ValidationError' }
838
+ "401": { $ref: '#/components/responses/Unauthorised' }
839
+ "404": { $ref: '#/components/responses/NotFound' }
840
+
841
+ /leads/update-status:
842
+ post:
843
+ operationId: updateLeadStatus
844
+ summary: Update lead status (fires email/SMS triggers)
845
+ description: "**Real URL:** `POST ?action=lead_update_status`"
846
+ tags: [Leads]
847
+ parameters:
848
+ - name: action
849
+ in: query
850
+ required: true
851
+ schema: { type: string, enum: [lead_update_status] }
852
+ - $ref: '#/components/parameters/ApiVersion'
853
+ requestBody:
854
  required: true
855
+ content:
856
+ application/json:
857
+ schema:
858
+ type: object
859
+ required: [id, status]
860
+ properties:
861
+ id: { type: integer }
862
+ status: { type: string, enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed] }
863
+ responses:
864
+ "200": { $ref: '#/components/responses/SimpleOk' }
865
+ "400": { $ref: '#/components/responses/ValidationError' }
866
+ "401": { $ref: '#/components/responses/Unauthorised' }
867
+ "404": { $ref: '#/components/responses/NotFound' }
868
+
869
+ /leads/add-note:
870
+ post:
871
+ operationId: addLeadNote
872
+ summary: Append a timestamped note to a lead
873
+ description: |
874
+ Appends to the plain-text `notes` column and writes an activity log entry.
875
+ **Real URL:** `POST ?action=lead_add_note`
876
+ tags: [Leads]
877
+ parameters:
878
+ - name: action
879
+ in: query
880
+ required: true
881
+ schema: { type: string, enum: [lead_add_note] }
882
+ - $ref: '#/components/parameters/ApiVersion'
883
+ requestBody:
884
  required: true
885
+ content:
886
+ application/json:
887
+ schema:
888
+ type: object
889
+ required: [id, note]
890
+ properties:
891
+ id: { type: integer }
892
+ note: { type: string }
893
  responses:
894
+ "200": { $ref: '#/components/responses/SimpleOk' }
895
+ "400": { $ref: '#/components/responses/ValidationError' }
896
+ "401": { $ref: '#/components/responses/Unauthorised' }
897
+ "404": { $ref: '#/components/responses/NotFound' }
898
+
899
+ /leads/archive:
900
+ post:
901
+ operationId: archiveLead
902
+ summary: Archive or unarchive a lead (admin only)
903
+ description: |
904
+ Cascades to all appointments and cancels pending emails when archiving.
905
+ Send `archive: false` to reverse.
906
+ **Real URL:** `POST ?action=lead_archive`
907
+ tags: [Leads]
 
 
 
 
 
 
908
  parameters:
909
+ - name: action
910
+ in: query
911
+ required: true
912
+ schema: { type: string, enum: [lead_archive] }
913
+ - $ref: '#/components/parameters/ApiVersion'
914
+ requestBody:
915
  required: true
916
+ content:
917
+ application/json:
918
+ schema:
919
+ type: object
920
+ required: [id]
921
+ properties:
922
+ id: { type: integer }
923
+ archive: { type: boolean, default: true }
924
  responses:
925
+ "200": { $ref: '#/components/responses/SimpleOk' }
926
+ "401": { $ref: '#/components/responses/Unauthorised' }
927
+ "403": { $ref: '#/components/responses/Forbidden' }
928
+ "404": { $ref: '#/components/responses/NotFound' }
929
+
930
+ # ── Appointments ───────────────────────────────────────────────────────────
931
+
932
+ /appointments:
 
 
 
 
 
 
933
  get:
934
+ operationId: listAppointments
935
+ summary: Paginated appointment list
936
+ description: "**Real URL:** `GET ?action=appointments`"
937
+ tags: [Appointments]
938
  parameters:
939
+ - name: action
940
+ in: query
941
+ required: true
942
+ schema: { type: string, enum: [appointments] }
943
+ - $ref: '#/components/parameters/ApiVersion'
944
+ - $ref: '#/components/parameters/PageParam'
945
+ - name: status
946
+ in: query
947
+ schema: { type: string, enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show] }
948
+ - name: date_from
949
+ in: query
950
+ schema: { type: string, format: date }
951
+ - name: date_to
952
+ in: query
953
+ schema: { type: string, format: date }
954
+ - name: upcoming
955
+ in: query
956
+ schema: { type: boolean, description: "Filter to future non-cancelled/refunded appointments" }
957
  responses:
958
+ "200":
959
+ description: Paginated appointment list
960
  content:
 
 
 
961
  application/json:
962
  schema:
963
+ type: object
964
+ properties:
965
+ success: { type: boolean, example: true }
966
+ message: { type: string }
967
+ data: { $ref: '#/components/schemas/PaginatedAppointments' }
968
+ "401": { $ref: '#/components/responses/Unauthorised' }
969
+
970
+ /appointments/detail:
971
  get:
972
+ operationId: getAppointment
973
+ summary: Single appointment with joined lead fields and activity log
974
+ description: "**Real URL:** `GET ?action=appointment&id=<id>`"
975
+ tags: [Appointments]
 
976
  parameters:
977
+ - name: action
978
+ in: query
979
+ required: true
980
+ schema: { type: string, enum: [appointment] }
981
+ - $ref: '#/components/parameters/ApiVersion'
982
+ - $ref: '#/components/parameters/IdQuery'
 
983
  responses:
984
+ "200":
985
+ description: Appointment detail
986
  content:
 
 
 
 
 
987
  application/json:
988
  schema:
989
+ type: object
990
+ properties:
991
+ success: { type: boolean, example: true }
992
+ message: { type: string }
993
+ data: { $ref: '#/components/schemas/AppointmentDetail' }
994
+ "401": { $ref: '#/components/responses/Unauthorised' }
995
+ "404": { $ref: '#/components/responses/NotFound' }
996
+
997
+ /appointments/create:
998
+ post:
999
+ operationId: createAppointment
1000
+ summary: Create an appointment
1001
+ description: |
1002
+ If `course_id` is provided, `training_location` and `training_address` default
1003
+ to the course's values. Fires email/SMS triggers for the initial status and
1004
+ sends a push notification to all admin users.
1005
+ **Real URL:** `POST ?action=appointment_create`
1006
+ tags: [Appointments]
1007
  parameters:
1008
+ - name: action
1009
+ in: query
1010
+ required: true
1011
+ schema: { type: string, enum: [appointment_create] }
1012
+ - $ref: '#/components/parameters/ApiVersion'
1013
+ requestBody:
 
 
 
 
1014
  required: true
1015
+ content:
1016
+ application/json:
1017
+ schema:
1018
+ type: object
1019
+ required: [lead_id, appointment_date]
1020
+ properties:
1021
+ lead_id: { type: integer }
1022
+ course_id: { type: integer }
1023
+ appointment_date: { type: string, format: date }
1024
+ appointment_time: { type: string, default: "09:00", example: "09:00" }
1025
+ duration: { type: string, default: "1 day" }
1026
+ amount_paid: { type: number, default: 0 }
1027
+ transaction_fee: { type: number, default: 0 }
1028
+ payment_method: { type: string, default: "Card" }
1029
+ payment_ref: { type: string }
1030
+ payment_date: { type: string, format: date }
1031
+ status: { type: string, enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show], default: pending }
1032
+ notes: { type: string }
1033
+ training_location:{ type: string }
1034
+ training_address: { type: string }
1035
  responses:
1036
+ "201":
1037
+ description: Appointment created
1038
  content:
 
 
 
 
 
1039
  application/json:
1040
  schema:
1041
+ type: object
1042
+ properties:
1043
+ success: { type: boolean, example: true }
1044
+ message: { type: string }
1045
+ data:
1046
+ type: object
1047
+ properties:
1048
+ appointment_id: { type: integer }
1049
+ appointment_ref: { type: string, example: "APT-A3B2C1" }
1050
+ "400": { $ref: '#/components/responses/ValidationError' }
1051
+ "401": { $ref: '#/components/responses/Unauthorised' }
1052
+ "404": { $ref: '#/components/responses/NotFound' }
1053
+
1054
+ /appointments/update:
1055
+ post:
1056
+ operationId: updateAppointment
1057
+ summary: Update appointment fields (patch-style)
1058
+ description: |
1059
+ Only send the fields you want to change. If `status` changes, email/SMS
1060
+ triggers fire and admins receive a push notification.
1061
+ **Real URL:** `POST ?action=appointment_update`
1062
+ tags: [Appointments]
1063
  parameters:
1064
+ - name: action
1065
+ in: query
1066
+ required: true
1067
+ schema: { type: string, enum: [appointment_update] }
1068
+ - $ref: '#/components/parameters/ApiVersion'
1069
+ requestBody:
1070
  required: true
1071
+ content:
1072
+ application/json:
1073
+ schema:
1074
+ type: object
1075
+ required: [id]
1076
+ properties:
1077
+ id: { type: integer }
1078
+ appointment_date: { type: string, format: date }
1079
+ appointment_time: { type: string }
1080
+ duration: { type: string }
1081
+ training_location:{ type: string }
1082
+ training_address: { type: string }
1083
+ amount_paid: { type: number }
1084
+ transaction_fee: { type: number }
1085
+ payment_method: { type: string }
1086
+ payment_ref: { type: string }
1087
+ payment_date: { type: string, format: date }
1088
+ notes: { type: string }
1089
+ course_id: { type: integer }
1090
+ status: { type: string, enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show] }
1091
+ responses:
1092
+ "200": { $ref: '#/components/responses/SimpleOk' }
1093
+ "400": { $ref: '#/components/responses/ValidationError' }
1094
+ "401": { $ref: '#/components/responses/Unauthorised' }
1095
+ "404": { $ref: '#/components/responses/NotFound' }
1096
+
1097
+ /appointments/update-status:
1098
+ post:
1099
+ operationId: updateAppointmentStatus
1100
+ summary: Update appointment status (fires triggers + push)
1101
+ description: "**Real URL:** `POST ?action=appointment_update_status`"
1102
+ tags: [Appointments]
1103
+ parameters:
1104
+ - name: action
1105
+ in: query
1106
+ required: true
1107
+ schema: { type: string, enum: [appointment_update_status] }
1108
+ - $ref: '#/components/parameters/ApiVersion'
1109
+ requestBody:
1110
  required: true
1111
+ content:
1112
+ application/json:
1113
+ schema:
1114
+ type: object
1115
+ required: [id, status]
1116
+ properties:
1117
+ id: { type: integer }
1118
+ status: { type: string, enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show] }
1119
+ responses:
1120
+ "200": { $ref: '#/components/responses/SimpleOk' }
1121
+ "400": { $ref: '#/components/responses/ValidationError' }
1122
+ "401": { $ref: '#/components/responses/Unauthorised' }
1123
+ "404": { $ref: '#/components/responses/NotFound' }
1124
+
1125
+ /appointments/archive:
1126
+ post:
1127
+ operationId: archiveAppointment
1128
+ summary: Archive or unarchive an appointment (admin only)
1129
+ description: |
1130
+ Cancels pending emails when archiving. Send `archive: false` to reverse.
1131
+ **Real URL:** `POST ?action=appointment_archive`
1132
+ tags: [Appointments]
1133
+ parameters:
1134
+ - name: action
1135
+ in: query
1136
+ required: true
1137
+ schema: { type: string, enum: [appointment_archive] }
1138
+ - $ref: '#/components/parameters/ApiVersion'
1139
+ requestBody:
1140
  required: true
1141
+ content:
1142
+ application/json:
1143
+ schema:
1144
+ type: object
1145
+ required: [id]
1146
+ properties:
1147
+ id: { type: integer }
1148
+ archive: { type: boolean, default: true }
1149
  responses:
1150
+ "200": { $ref: '#/components/responses/SimpleOk' }
1151
+ "401": { $ref: '#/components/responses/Unauthorised' }
1152
+ "403": { $ref: '#/components/responses/Forbidden' }
1153
+ "404": { $ref: '#/components/responses/NotFound' }
1154
+
1155
+ # ── Courses ────────────────────────────────────────────────────────────────
1156
+
1157
+ /courses:
1158
+ get:
1159
+ operationId: listCourses
1160
+ summary: Active course catalogue
1161
+ description: "**Real URL:** `GET ?action=courses`"
1162
+ tags: [Courses]
1163
+ parameters:
1164
+ - name: action
1165
+ in: query
1166
+ required: true
1167
+ schema: { type: string, enum: [courses] }
1168
+ - $ref: '#/components/parameters/ApiVersion'
1169
+ responses:
1170
+ "200":
1171
+ description: Active courses
1172
  content:
 
 
 
 
 
1173
  application/json:
1174
  schema:
1175
+ type: object
1176
+ properties:
1177
+ success: { type: boolean, example: true }
1178
+ message: { type: string }
1179
+ data:
1180
+ type: object
1181
+ properties:
1182
+ courses: { type: array, items: { $ref: '#/components/schemas/Course' } }
1183
+ "401": { $ref: '#/components/responses/Unauthorised' }
1184
+
1185
+ # ── Search ─────────────────────────────────────────────────────────────────
1186
+
1187
+ /search:
1188
  get:
1189
+ operationId: search
1190
+ summary: Search leads by name, email, or phone
1191
+ description: |
1192
+ Returns up to 30 matching non-archived leads. Minimum query length is 2 characters.
1193
+ **Real URL:** `GET ?action=search&q=<query>`
1194
+ tags: [Search]
1195
  parameters:
1196
+ - name: action
1197
+ in: query
1198
+ required: true
1199
+ schema: { type: string, enum: [search] }
1200
+ - $ref: '#/components/parameters/ApiVersion'
1201
+ - name: q
1202
+ in: query
1203
+ required: true
1204
+ schema: { type: string, minLength: 2 }
 
 
 
 
 
 
 
 
 
 
1205
  responses:
1206
+ "200":
1207
+ description: Search results
1208
  content:
 
 
 
 
 
1209
  application/json:
1210
  schema:
1211
+ type: object
1212
+ properties:
1213
+ success: { type: boolean, example: true }
1214
+ message: { type: string }
1215
+ data:
1216
+ type: object
1217
+ properties:
1218
+ results: { type: array, items: { $ref: '#/components/schemas/SearchResult' } }
1219
+ count: { type: integer }
1220
+ "400": { $ref: '#/components/responses/ValidationError' }
1221
+ "401": { $ref: '#/components/responses/Unauthorised' }
1222
+
1223
+ # ── Stats & Dashboard ──────────────────────────────────────────────────────
1224
+
1225
+ /stats/dashboard:
1226
  get:
1227
+ operationId: getDashboard
1228
+ summary: Summary stats, upcoming appointments, and recent leads
1229
+ description: |
1230
+ `total_revenue` and `month_revenue` are included only for admin users.
1231
+ **Real URL:** `GET ?action=dashboard`
1232
+ tags: [Stats]
1233
  parameters:
1234
+ - name: action
1235
+ in: query
1236
+ required: true
1237
+ schema: { type: string, enum: [dashboard] }
1238
+ - $ref: '#/components/parameters/ApiVersion'
 
 
 
 
 
 
 
 
1239
  responses:
1240
+ "200":
1241
+ description: Dashboard data
1242
  content:
 
 
 
 
 
1243
  application/json:
1244
  schema:
1245
+ type: object
1246
+ properties:
1247
+ success: { type: boolean, example: true }
1248
+ message: { type: string }
1249
+ data: { $ref: '#/components/schemas/DashboardData' }
1250
+ "401": { $ref: '#/components/responses/Unauthorised' }
1251
+
1252
+ /stats:
 
 
 
 
 
 
 
 
1253
  get:
1254
+ operationId: getStats
1255
+ summary: Revenue by month and status breakdowns (admin only)
1256
+ description: |
1257
+ Revenue chart defaults to the last 6 months. Use `date_from` / `date_to` to override.
1258
+ **Real URL:** `GET ?action=stats`
1259
+ tags: [Stats]
1260
  parameters:
1261
+ - name: action
1262
+ in: query
1263
+ required: true
1264
+ schema: { type: string, enum: [stats] }
1265
+ - $ref: '#/components/parameters/ApiVersion'
1266
+ - name: date_from
1267
+ in: query
1268
+ schema: { type: string, format: date }
1269
+ description: "Start of revenue date range (inclusive). Defaults to 6 months ago."
1270
+ - name: date_to
1271
+ in: query
1272
+ schema: { type: string, format: date }
1273
+ description: "End of revenue date range (inclusive)."
1274
  responses:
1275
+ "200":
1276
+ description: Analytics data
1277
  content:
 
 
 
1278
  application/json:
1279
  schema:
1280
+ type: object
1281
+ properties:
1282
+ success: { type: boolean, example: true }
1283
+ message: { type: string }
1284
+ data: { $ref: '#/components/schemas/StatsData' }
1285
+ "401": { $ref: '#/components/responses/Unauthorised' }
1286
+ "403": { $ref: '#/components/responses/Forbidden' }
1287
+
1288
+ # ── Users (admin only) ─────────────────────────────────────────────────────
1289
+
1290
+ /users:
1291
+ get:
1292
+ operationId: listUsers
1293
+ summary: List all CRM users (admin only)
1294
+ description: "**Real URL:** `GET ?action=user_list`"
1295
+ tags: [Users]
1296
  parameters:
1297
+ - name: action
1298
+ in: query
1299
+ required: true
1300
+ schema: { type: string, enum: [user_list] }
1301
+ - $ref: '#/components/parameters/ApiVersion'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1302
  responses:
1303
+ "200":
1304
+ description: All CRM users
1305
  content:
 
 
 
1306
  application/json:
1307
  schema:
1308
+ type: object
1309
+ properties:
1310
+ success: { type: boolean, example: true }
1311
+ message: { type: string }
1312
+ data:
1313
+ type: object
1314
+ properties:
1315
+ users: { type: array, items: { $ref: '#/components/schemas/User' } }
1316
+ total: { type: integer }
1317
+ "401": { $ref: '#/components/responses/Unauthorised' }
1318
+ "403": { $ref: '#/components/responses/Forbidden' }
1319
+
1320
+ /users/create:
1321
  post:
1322
+ operationId: createUser
1323
+ summary: Create a CRM user (admin only)
1324
+ description: "**Real URL:** `POST ?action=user_create`"
1325
+ tags: [Users]
1326
  parameters:
1327
+ - name: action
1328
+ in: query
1329
+ required: true
1330
+ schema: { type: string, enum: [user_create] }
1331
+ - $ref: '#/components/parameters/ApiVersion'
1332
+ requestBody:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1333
  required: true
1334
+ content:
1335
+ application/json:
1336
+ schema:
1337
+ type: object
1338
+ required: [username, password, full_name]
1339
+ properties:
1340
+ username: { type: string }
1341
+ password: { type: string, format: password, minLength: 8 }
1342
+ full_name: { type: string }
1343
+ email: { type: string, format: email }
1344
+ role: { type: string, enum: [admin, staff], default: staff }
1345
  responses:
1346
+ "201":
1347
+ description: User created
1348
  content:
 
 
 
 
 
1349
  application/json:
1350
  schema:
1351
+ type: object
1352
+ properties:
1353
+ success: { type: boolean, example: true }
1354
+ message: { type: string }
1355
+ data:
1356
+ type: object
1357
+ properties:
1358
+ user_id: { type: integer }
1359
+ "400": { $ref: '#/components/responses/ValidationError' }
1360
+ "401": { $ref: '#/components/responses/Unauthorised' }
1361
+ "403": { $ref: '#/components/responses/Forbidden' }
1362
+ "409": { $ref: '#/components/responses/Conflict' }
1363
+
1364
+ /users/update:
1365
  post:
1366
+ operationId: updateUser
1367
+ summary: Update a CRM user (admin only, patch-style)
1368
+ description: "**Real URL:** `POST ?action=user_update`"
1369
+ tags: [Users]
1370
  parameters:
1371
+ - name: action
1372
+ in: query
1373
+ required: true
1374
+ schema: { type: string, enum: [user_update] }
1375
+ - $ref: '#/components/parameters/ApiVersion'
1376
+ requestBody:
 
 
 
1377
  required: true
1378
+ content:
1379
+ application/json:
1380
+ schema:
1381
+ type: object
1382
+ required: [id]
1383
+ properties:
1384
+ id: { type: integer }
1385
+ full_name: { type: string }
1386
+ email: { type: string, format: email }
1387
+ username: { type: string }
1388
+ role: { type: string, enum: [admin, staff] }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1389
  responses:
1390
+ "200": { $ref: '#/components/responses/SimpleOk' }
1391
+ "400": { $ref: '#/components/responses/ValidationError' }
1392
+ "401": { $ref: '#/components/responses/Unauthorised' }
1393
+ "403": { $ref: '#/components/responses/Forbidden' }
1394
+ "404": { $ref: '#/components/responses/NotFound' }
1395
+ "409": { $ref: '#/components/responses/Conflict' }
1396
+
1397
+ /users/deactivate:
1398
  post:
1399
+ operationId: deactivateUser
1400
+ summary: Deactivate or reactivate a user (admin only)
1401
+ description: |
1402
+ Cannot target your own account. Deactivating immediately revokes all active tokens.
1403
+ Send `active: true` to reactivate.
1404
+ **Real URL:** `POST ?action=user_deactivate`
1405
+ tags: [Users]
1406
  parameters:
1407
+ - name: action
1408
+ in: query
1409
+ required: true
1410
+ schema: { type: string, enum: [user_deactivate] }
1411
+ - $ref: '#/components/parameters/ApiVersion'
1412
+ requestBody:
 
 
 
 
 
 
 
 
 
 
 
1413
  required: true
1414
+ content:
1415
+ application/json:
1416
+ schema:
1417
+ type: object
1418
+ required: [id]
1419
+ properties:
1420
+ id: { type: integer }
1421
+ active: { type: boolean, description: "true to reactivate; omit or false to deactivate" }
1422
  responses:
1423
+ "200": { $ref: '#/components/responses/SimpleOk' }
1424
+ "401": { $ref: '#/components/responses/Unauthorised' }
1425
+ "403": { $ref: '#/components/responses/Forbidden' }
1426
+ "404": { $ref: '#/components/responses/NotFound' }
1427
+
1428
+ # ── Push Notifications ─────────────────────────────────────────────────────
1429
+
1430
+ /devices/register:
 
 
1431
  post:
1432
+ operationId: registerDevice
1433
+ summary: Register or refresh a push token for this device
1434
+ description: |
1435
+ Uses INSERT … ON DUPLICATE KEY UPDATE — safe to call on every app launch.
1436
+ Expo push tokens look like `ExponentPushToken[xxxxxxxxxxxxxxxxxxxx]`.
1437
+ **Real URL:** `POST ?action=register_device`
1438
+ tags: [Notifications]
1439
  parameters:
1440
+ - name: action
1441
+ in: query
1442
+ required: true
1443
+ schema: { type: string, enum: [register_device] }
1444
+ - $ref: '#/components/parameters/ApiVersion'
1445
+ requestBody:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1446
  required: true
1447
+ content:
1448
+ application/json:
1449
+ schema:
1450
+ type: object
1451
+ required: [push_token]
1452
+ properties:
1453
+ push_token: { type: string, example: "ExponentPushToken[xxxxxxxxxxxxxxxxxxxx]" }
1454
+ platform: { type: string, enum: [ios, android, web], default: android }
1455
+ device_name: { type: string, example: "Sarah's iPhone 15" }
1456
  responses:
1457
+ "200": { $ref: '#/components/responses/SimpleOk' }
1458
+ "400": { $ref: '#/components/responses/ValidationError' }
1459
+ "401": { $ref: '#/components/responses/Unauthorised' }
1460
+
1461
+ /devices/unregister:
 
 
 
 
 
1462
  post:
1463
+ operationId: unregisterDevice
1464
+ summary: Remove a push token (stop notifications on this device)
1465
+ description: |
1466
+ The `logout` endpoint also accepts `push_token` to remove the token in one call.
1467
+ **Real URL:** `POST ?action=unregister_device`
1468
+ tags: [Notifications]
1469
  parameters:
1470
+ - name: action
1471
+ in: query
1472
+ required: true
1473
+ schema: { type: string, enum: [unregister_device] }
1474
+ - $ref: '#/components/parameters/ApiVersion'
1475
+ requestBody:
 
 
 
 
1476
  required: true
1477
+ content:
1478
+ application/json:
1479
+ schema:
1480
+ type: object
1481
+ required: [push_token]
1482
+ properties:
1483
+ push_token: { type: string }
1484
+ responses:
1485
+ "200": { $ref: '#/components/responses/SimpleOk' }
1486
+ "400": { $ref: '#/components/responses/ValidationError' }
1487
+ "401": { $ref: '#/components/responses/Unauthorised' }
1488
+
1489
+ # ── Invoice ────────────────────────────────────────────────────────────────
1490
+
1491
+ /invoice/pdf:
1492
+ get:
1493
+ operationId: downloadInvoicePdf
1494
+ summary: Download appointment invoice as PDF
1495
+ description: |
1496
+ Streams a dompdf-rendered A4 PDF. Response `Content-Type` is `application/pdf`,
1497
+ not JSON. Pass the JWT in the `Authorization` header as usual.
1498
+ **Real URL:** `GET ?action=invoice_pdf&id=<id>`
1499
+ tags: [Invoice]
1500
+ parameters:
1501
+ - name: action
1502
+ in: query
1503
+ required: true
1504
+ schema: { type: string, enum: [invoice_pdf] }
1505
+ - $ref: '#/components/parameters/ApiVersion'
1506
+ - $ref: '#/components/parameters/IdQuery'
1507
  responses:
1508
+ "200":
1509
+ description: PDF file download
1510
+ headers:
1511
+ Content-Disposition:
1512
+ schema: { type: string, example: 'attachment; filename="invoice-APT-A3B2C1.pdf"' }
1513
  content:
1514
+ application/pdf:
1515
+ schema: { type: string, format: binary }
1516
+ "401": { $ref: '#/components/responses/Unauthorised' }
1517
+ "404": { $ref: '#/components/responses/NotFound' }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ref doc/admin_openapi.yaml ADDED
The diff for this file is too large to render. See raw diff