feat(captain): align scenario and tool payloads
This commit is contained in:
@@ -16,9 +16,9 @@ Build GoChat as a Go backend that can directly reuse the frontend from `referenc
|
||||
|
||||
## Current Baseline
|
||||
|
||||
- Latest implementation checkpoint: `feat(captain): align assistant resources`.
|
||||
- Latest documentation checkpoint: this checkpoint, recorded with the B11.1a Captain assistant resource implementation.
|
||||
- Worktree status at this implementation checkpoint: B11.1a aligns Captain assistant CRUD, tools, account-scoped show/update/delete, and assistant inbox binding/list/delete payloads with the reused Chatwoot frontend; next active slice is B11.1b Captain documents/scenarios/responses/custom tools payload depth.
|
||||
- Latest implementation checkpoint: `feat(captain): align scenario and tool payloads`.
|
||||
- Latest documentation checkpoint: this checkpoint, recorded with the B11.1b Captain scenario/custom-tool implementation.
|
||||
- Worktree status at this implementation checkpoint: B11.1a aligns Captain assistant CRUD/tools/inbox bindings; B11.1b now aligns Captain scenarios and custom tools. Next active slice is B11.1c Captain documents, assistant responses, and bulk actions payload depth.
|
||||
- `go test ./...` passes.
|
||||
- Route dump succeeds with `TOTAL: 830` after adding the Chatwoot-compatible applied-SLA index route.
|
||||
- Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`.
|
||||
@@ -147,12 +147,13 @@ This ledger records the committed parity checkpoints that future slices should b
|
||||
| `docs: land inbox limit handoff tracker` | Landed the B10.4 reference findings and implementation contract: Chatwoot account inbox limits come from `Current.account.usage_limits[:inboxes]`, over-limit create returns `402 { error: "Account limit exceeded. Upgrade to a higher plan" }`, and capacity-policy `InboxCapacityLimit` is explicitly separate assignment-capacity data. | Documentation-only checkpoint; `git diff --check` passed. | Start B10.4 implementation from the recorded guard, migration, handler, and test plan. |
|
||||
| `feat(inboxes): enforce chatwoot inbox limits` | Completed B10.4 account-level inbox limit parity: `accounts.inbox_limit` now represents Chatwoot `usage_limits[:inboxes]`, `InboxService.EnsureCanCreateInbox` blocks over-limit creates before persistence, generic inbox and dedicated channel create paths return `402 { error: "Account limit exceeded. Upgrade to a higher plan" }`, and LINE/email/Twilio plus other channel handlers avoid orphan channel rows. | `go test ./internal/handler/api/v1 -run 'Inbox\|Channel\|Capacity\|Limit' -count=1`; `go test ./internal/service -run 'Inbox\|Channel\|Capacity\|Limit' -count=1`; handler and service packages passed; full verification recorded below. No route changes; route dump remains `TOTAL: 830`. | Continue B11 Captain/Copilot persistence, safe disabled states, and frontend payload parity. |
|
||||
| `feat(captain): align assistant resources` | Completed B11.1a Captain assistant resource parity for the reused dashboard assistant client: assistant list/show/create/update/delete now use raw Chatwoot/Jbuilder payloads, nested `{ assistant: ... }` bodies are accepted, assistant access is account-scoped, `/captain/assistants/tools` returns the built-in tool array, and assistant inbox bind/list/delete routes use Chatwoot `{ payload, meta }`, raw inbox, and `204` contracts. | `go test ./internal/handler/api/v1 -run CaptainAssistant -count=1`; `go test ./internal/service -run CaptainAssistant -count=1`; route dump/parity regenerated with unchanged `TOTAL: 830`; focused handler fixtures cover account scoping, tools, inbox binding, and no local `{ success, data }` envelopes. | Continue B11.1b with Captain documents, scenarios, assistant responses, bulk actions, and custom tools payload depth; B11 stays Doing until Copilot, LLM/document gates, and smoke coverage land. |
|
||||
| `feat(captain): align scenario and tool payloads` | Advanced B11.1b for Captain scenarios and custom tools: scenario create/list/show/update/delete now accept nested `{ scenario }`, enforce account/assistant scope, return Chatwoot raw scenario serializers and `{ payload, meta }` lists, hide disabled scenarios from index, and return `204` on delete; custom tools now accept nested `{ custom_tool }`, auto-generate slugs from title, enforce account scope, and return raw tool serializers or `{ payload, meta }` lists. | `go test ./internal/handler/api/v1 -run 'CaptainScenario\|CaptainCustomTool\|CaptainResource' -count=1`; `go test ./internal/handler/api/v1 -run 'Captain\|Copilot' -count=1`; `go test ./internal/service -run 'Captain\|Copilot' -count=1`; focused fixtures cover nested frontend bodies, account scoping, disabled scenario filtering, raw payloads, custom-tool slug generation, and no local envelopes. | Continue B11.1c with Captain documents, assistant responses, and bulk actions; custom-tool `test` still needs the reference unsaved-tool execution contract and safe network boundary before B11 leaves Review. |
|
||||
|
||||
## Next Slice Contract
|
||||
|
||||
Completed implementation slice: B11.1a now aligns Captain assistant CRUD, tools, and assistant inbox bindings with Chatwoot frontend payloads.
|
||||
Completed implementation slice: B11.1b now aligns Captain scenarios and custom tools with Chatwoot frontend payloads, building on B11.1a assistant resources.
|
||||
|
||||
Next implementation slice: continue B11.1b Captain documents, scenarios, assistant responses, bulk actions, and custom tools payload depth before moving to B11.2 Copilot persistence and safe LLM/document gates. B9.3 delayed/durable worker scheduling and B9.4 macro attachment depth remain named Phase 5 follow-ups.
|
||||
Next implementation slice: continue B11.1c Captain documents, assistant responses, bulk actions, and custom-tool test execution before moving to B11.2 Copilot persistence and safe LLM/document gates. B9.3 delayed/durable worker scheduling and B9.4 macro attachment depth remain named Phase 5 follow-ups.
|
||||
|
||||
| Step | Required result | Reference source | Verification |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -173,7 +174,8 @@ Next implementation slice: continue B11.1b Captain documents, scenarios, assista
|
||||
| N15 | Keep B9.2 macro CRUD/execute parity as current macro baseline. | Chatwoot `MacrosController`, `Macro`, `MacrosExecutionJob`, `Macros::ExecutionService`, dashboard macro API/store. | Done by `feat(macros): align chatwoot macro payloads`; frontend payloads, visibility/authorization, display-ID execution, and real conversation/message/label/status side effects are covered. |
|
||||
| N16 | Keep B10.4 account inbox limits as current limit baseline. | Chatwoot account `usage_limits[:inboxes]` and request exception handler. | Done by `feat(inboxes): enforce chatwoot inbox limits`; generic and dedicated channel create paths return the exact over-limit `402` response and avoid orphan rows. |
|
||||
| N17 | Keep B11.1a Captain assistant resources as current Captain baseline. | `reference/chatwoot/enterprise/app/controllers/api/v1/accounts/captain/assistants_controller.rb`, Captain inboxes controller, assistant Jbuilder views, dashboard Captain assistant/inbox API clients, `config/agents/tools.yml`. | Done by `feat(captain): align assistant resources`; assistant CRUD/tools/inbox binding payloads are account-scoped and frontend-shaped. |
|
||||
| N18 | Update this tracker after every implementation checkpoint. | This document. | `git diff --check`; `go test ./...` for Go changes. |
|
||||
| N18 | Keep B11.1b Captain scenario/custom-tool resources as current Captain baseline. | Captain scenarios/custom tools controllers, Jbuilder views, and dashboard clients. | Done by `feat(captain): align scenario and tool payloads`; scenarios and custom tools use nested frontend bodies, account scoping, raw payloads, and Chatwoot list meta. |
|
||||
| N19 | Update this tracker after every implementation checkpoint. | This document. | `git diff --check`; `go test ./...` for Go changes. |
|
||||
|
||||
Current B2 profile checkpoint:
|
||||
|
||||
@@ -402,7 +404,7 @@ Upcoming enterprise task boards:
|
||||
| B10 | B10.2 | Add audit writer coverage for representative core and enterprise mutations: inbox, conversation assignment/status, SLA policy, capacity policy, custom role, automation, macro, CSAT review notes. | Chatwoot audit hooks and current Go service mutation points. | Mutation tests assert audit rows with actor, auditable type/id, account, IP/request metadata where available. | Done by `feat(audit): record enterprise mutations` and `feat(audit): cover operational mutations` |
|
||||
| B10 | B10.3 | Align CustomRole permission keys, account-user role resolution, deletion nullification, and authorization failure payloads. | Chatwoot custom role controllers/policies and permission constants. | Permission matrix tests for admin/non-admin/custom-role access. | Done by `feat(custom-roles): align chatwoot permissions` |
|
||||
| B10 | B10.4 | Review remaining InboxLimit/account-limit create-path enforcement outside capacity policies. | Chatwoot enterprise account/inbox limit policies. | Inbox/channel create tests for over-limit behavior and frontend-readable errors. | Done by `feat(inboxes): enforce chatwoot inbox limits` |
|
||||
| B11 | B11.1 | Align Captain assistant CRUD, inbox bindings, responses, documents, scenarios, and custom tools payloads. | Captain controllers/services/frontend clients under `reference/chatwoot`. | Handler/service fixtures for every Captain dashboard client path. | Doing; assistant CRUD/tools/inbox binding landed by `feat(captain): align assistant resources` |
|
||||
| B11 | B11.1 | Align Captain assistant CRUD, inbox bindings, responses, documents, scenarios, and custom tools payloads. | Captain controllers/services/frontend clients under `reference/chatwoot`. | Handler/service fixtures for every Captain dashboard client path. | Doing; assistant CRUD/tools/inbox binding and scenario/custom-tool payloads are landed |
|
||||
| B11 | B11.2 | Align Copilot threads, messages, tasks, preferences, playground/tool-call behavior, and disabled-state feature gates. | Copilot controllers/services/frontend clients under `reference/chatwoot`. | Copilot handler/service tests for persistence, disabled LLM state, and frontend payloads. | Todo |
|
||||
| B11 | B11.3 | Add document sync/embedding/LLM job boundaries where external dependencies are required. | Captain/Copilot jobs and document services. | Worker tests or explicit feature-gated fallback tests. | Todo |
|
||||
| B12 | B12.1 | Add a repeatable command to run the reused Chatwoot frontend against GoChat. | `reference/chatwoot` frontend boot/auth/API clients. | Smoke command documented and runnable locally. | Todo |
|
||||
@@ -762,7 +764,8 @@ B11 Captain/Copilot breakdown:
|
||||
| Step | Implementation target | Reference source | Required tests | Status |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| B11.1a | Align Captain assistant CRUD, tools, and inbox binding/list/delete payloads used by `assistant.js` and `inboxes.js`. | Assistant controller, inboxes controller, assistant Jbuilder views, `config/agents/tools.yml`, dashboard Captain assistant/inbox clients. | Handler tests for assistant lifecycle, account scoping, tools array, raw inbox binding, list meta, and `204` delete. | Done by `feat(captain): align assistant resources` |
|
||||
| B11.1b | Align Captain documents, scenarios, assistant responses, bulk actions, and custom tools payloads. | `documents_controller.rb`, `scenarios_controller.rb`, `assistant_responses_controller.rb`, `bulk_actions_controller.rb`, `custom_tools_controller.rb`, dashboard Captain clients. | Handler/service fixtures for list/show/create/update/delete, account scoping, sync status, and no local response envelopes. | Todo |
|
||||
| B11.1b | Align Captain scenario and custom-tool CRUD/list payloads. | `scenarios_controller.rb`, `custom_tools_controller.rb`, scenario/custom-tool Jbuilder views, dashboard Captain clients. | Handler fixtures for nested bodies, list/show/create/update/delete, account scoping, disabled scenario filtering, and no local response envelopes. | Done by `feat(captain): align scenario and tool payloads` |
|
||||
| B11.1c | Align Captain documents, assistant responses, bulk actions, and custom-tool test execution. | `documents_controller.rb`, `assistant_responses_controller.rb`, `bulk_actions_controller.rb`, `custom_tools_controller#test`, dashboard Captain clients. | Handler/service fixtures for document list/create/show/sync/delete, response list/show/create/update/delete, bulk-action payloads, test execution errors, account scoping, sync status, and no local response envelopes. | Todo |
|
||||
| B11.2 | Implement document sync/indexing gates for Meilisearch or the chosen embedding/search backend without blocking the frontend when LLM config is absent. | Captain document and embedding services. | Tests cover disabled state, failed sync observability, and successful fake backend indexing. | Todo |
|
||||
| B11.3 | Align Copilot thread/message/task APIs, tool calls, preferences, and streaming fallback. | Copilot controllers/services/frontend clients. | Handler tests cover thread/message/task lifecycle, tool-call persistence, disabled-state payloads, and non-streaming fallback. | Todo |
|
||||
|
||||
@@ -776,6 +779,14 @@ B11.1a current checkpoint:
|
||||
- Assistant inbox binding accepts `{ inbox: { inbox_id } }`, validates both assistant and inbox account ownership, returns the raw inbox serializer on create, returns `{ payload, meta }` on list, and returns `204` for account-scoped delete.
|
||||
- Route dump/parity were regenerated after the router handler remap; external route count remains `TOTAL: 830` and tracked route parity remains unchanged.
|
||||
|
||||
B11.1b current checkpoint:
|
||||
|
||||
- Reference files inspected for this slice: enterprise Captain `scenarios_controller.rb`, `custom_tools_controller.rb`, scenario/custom-tool Jbuilder partials, dashboard `scenarios.js`, and `customTools.js`.
|
||||
- Scenario create/update now accept nested `{ scenario: ... }`, show/update/delete are scoped by account plus assistant, index returns enabled scenarios only with `{ payload, meta }`, and single-resource mutations return the raw scenario serializer with assistant ID/name.
|
||||
- Custom-tool create/update now accept nested `{ custom_tool: ... }`; create auto-generates the Chatwoot-style slug from title when the frontend omits `slug`; list returns `{ payload, meta }`; show/update/delete are account-scoped; single-resource mutations return the raw custom-tool serializer with Unix timestamps and JSON `auth_config`/`param_schema` values.
|
||||
- Focused tests cover nested frontend bodies, account-scope isolation, disabled scenario filtering, custom-tool slug generation, and absence of local `{ success, data }` envelopes.
|
||||
- Remaining B11.1c gaps: Captain documents, assistant responses, bulk actions, and `custom_tools#test` still need the current reference payload and safe external-call contract.
|
||||
|
||||
B11 landing rules:
|
||||
|
||||
| Area | Landing requirement | Done signal |
|
||||
@@ -1174,7 +1185,7 @@ Included checklist:
|
||||
- [x] Custom roles and permission checks.
|
||||
- [x] Agent capacity and assignment limits.
|
||||
- [ ] Assignment policies and auto-assignment compatibility.
|
||||
- [ ] Captain/Copilot assistant, custom tools, scenarios, documents, responses, and inbox bindings. Assistant CRUD/tools/inbox binding are landed; the rest remains active.
|
||||
- [ ] Captain/Copilot assistant, custom tools, scenarios, documents, responses, and inbox bindings. Assistant CRUD/tools/inbox binding plus scenario/custom-tool CRUD payloads are landed; documents, responses, bulk actions, custom-tool test, and Copilot remain active.
|
||||
- [x] CSAT survey response flow, metrics, filters, and review notes.
|
||||
- [x] Inbox limits and account/inbox usage enforcement.
|
||||
- [x] Automation rules, macros, execution logs, and action side effects.
|
||||
@@ -1193,7 +1204,7 @@ Enterprise tracking table:
|
||||
| P4.3 | Custom roles/permissions | `internal/model/custom_role.go`, `internal/service/custom_role_service.go`, `internal/middleware/role_check.go`, `internal/handler/api/v1/custom_role_handler.go` | Permission arrays, raw admin payloads, administrator gates, account-user resolution, profile permissions, and delete nullification are implemented; keep in Review until frontend smoke covers enterprise settings. | Review |
|
||||
| P4.4 | Agent capacity | `internal/model/agent_capacity_policy.go`, `internal/service/agent_capacity_policy_service.go`, `internal/handler/api/v1/agent_capacity_handler.go`, `internal/autoassignment/*` | First align AgentCapacityPolicy API, serializers, nested users, and `InboxCapacityLimit` data contracts; then enforce capacity in manual/auto assignment. | Review |
|
||||
| P4.5 | Inbox limits | `internal/model/agent_capacity_policy.go` `InboxCapacityLimit`, plus legacy `internal/model/inbox_limit.go`, `internal/service/inbox_limit_service.go`, `internal/repository/inbox_limit_repo.go`, `internal/handler/api/v1/inbox_limit_handler.go` | Chatwoot enterprise nested `agent_capacity_policies/:policy_id/inbox_limits`, assignment-path enforcement, and account-level `usage_limits[:inboxes]` create-path enforcement are covered. | Review |
|
||||
| P4.6 | Captain/Copilot | `internal/model/captain_models.go`, `internal/model/copilot_models.go`, `internal/service/captain_*`, `internal/service/copilot_*`, `internal/handler/api/v1/captain_*`, `internal/handler/api/v1/copilot_handler.go` | Assistant CRUD/tools/inbox binding payloads are aligned; complete Captain documents/scenarios/responses/custom tools, Copilot threads/messages/tasks, suggestions, document/LLM gates, and streaming compatibility. | Doing |
|
||||
| P4.6 | Captain/Copilot | `internal/model/captain_models.go`, `internal/model/copilot_models.go`, `internal/service/captain_*`, `internal/service/copilot_*`, `internal/handler/api/v1/captain_*`, `internal/handler/api/v1/copilot_handler.go` | Assistant CRUD/tools/inbox binding and scenario/custom-tool CRUD payloads are aligned; complete Captain documents/responses/bulk actions/custom-tool test, Copilot threads/messages/tasks, suggestions, document/LLM gates, and streaming compatibility. | Doing |
|
||||
| P4.7 | CSAT | `internal/csat/*`, `internal/automation/csat_survey_*`, `internal/handler/api/v1/csat_*`, `internal/service/csat_metrics_service.go` | Account-side list/metrics/review-note payloads, public update depth, resolve-triggered generic survey send, and download CSV are aligned; channel-specific template send hooks remain Phase 5 integration work. | Review |
|
||||
| P4.8 | Automation and macros | `internal/automation/*`, `internal/handler/api/v1/automation_rule_handler.go`, `internal/handler/api/v1/macro_handler.go` | Automation-rule CRUD/listener/log/external-action delivery and macro CRUD/display-ID execution parity are implemented; durable delayed actions and deeper macro attachment/file parity remain B9.3/B9.4 follow-ups. | Review |
|
||||
| P4.9 | Assignment policies | `internal/autoassignment/*`, `internal/automation/agent_bot_rule_listener.go` | Match Chatwoot assignment policy behavior and availability/capacity rules. | Doing |
|
||||
@@ -1210,7 +1221,7 @@ Enterprise work package breakdown:
|
||||
| Audit | Audit model parity, mutating action coverage, request metadata, filters/pagination, admin endpoint payloads. | List/admin payload parity is covered by `feat(audit): align chatwoot audit log payloads`; named representative writer coverage is covered by `feat(audit): record enterprise mutations` and `feat(audit): cover operational mutations`. | Review |
|
||||
| Custom roles | Permission-key parity, account-user role resolution, policy middleware, create/update/delete behavior. | Permission arrays, raw admin payloads, admin gates, RBAC/account-scope/profile resolution, and delete nullification are covered by `feat(custom-roles): align chatwoot permissions`. | Review |
|
||||
| Inbox limits | Account/inbox limit models, create/update enforcement, UI-readable limit responses, admin overrides. | Chatwoot nested capacity-limit API, assignment-path enforcement, and account-level create-limit `402` behavior are covered by B5/B7/B10.4. | Review |
|
||||
| Captain/Copilot | Assistants, inbox bindings, scenarios, responses, documents, tools, copilot threads/messages, tasks, streaming/tool-call behavior. | Assistant CRUD/tools/inbox binding fixtures are covered by `feat(captain): align assistant resources`; route fixtures, feature gates for external LLM dependencies, and frontend smoke screens remain for deeper Captain/Copilot paths. | Doing |
|
||||
| Captain/Copilot | Assistants, inbox bindings, scenarios, responses, documents, tools, copilot threads/messages, tasks, streaming/tool-call behavior. | Assistant CRUD/tools/inbox binding fixtures are covered by `feat(captain): align assistant resources`; scenario/custom-tool fixtures are covered by `feat(captain): align scenario and tool payloads`; route fixtures, feature gates for external LLM dependencies, and frontend smoke screens remain for deeper Captain/Copilot paths. | Doing |
|
||||
|
||||
Enterprise acceptance gates:
|
||||
|
||||
@@ -1446,3 +1457,4 @@ Verification milestone gates:
|
||||
- 2026-06-05: B10.4 handoff tracker prepared as `docs: land inbox limit handoff tracker`; the active plan now records the exact Chatwoot account inbox-limit source (`usage_limits[:inboxes]`), the `402 { error: "Account limit exceeded. Upgrade to a higher plan" }` response contract, the separation from capacity-policy `InboxCapacityLimit`, the required account schema guard, dedicated-channel precheck, no-orphan persistence tests, and updated enterprise status rows. Documentation-only checkpoint; `git diff --check` passed.
|
||||
- 2026-06-05: B10.4 InboxLimit checkpoint prepared as `feat(inboxes): enforce chatwoot inbox limits`; account-level `inbox_limit` now gates generic inbox and dedicated channel creation with Chatwoot's exact `402` error body, service and handler tests cover unlimited, below-limit, over-limit, and no-orphan LINE channel behavior, and B10 moves to Review. Focused inbox/channel/limit tests, handler/service package tests, escalated full `go test ./...`, and `git diff --check` passed. Next slice is B11 Captain/Copilot.
|
||||
- 2026-06-05: B11.1a Captain assistant checkpoint prepared as `feat(captain): align assistant resources`; assistant CRUD now returns Chatwoot raw assistant payloads and list meta, nested assistant request bodies are accepted, account-scoped get/update/delete prevents cross-account access, tools returns the raw built-in tool array, and assistant inbox create/list/delete use raw inbox/list/204 contracts. Focused CaptainAssistant handler/service tests passed, route dump/parity regenerated with unchanged `TOTAL: 830`, and `git diff --check` passed. Next slice is B11.1b Captain documents/scenarios/responses/custom tools.
|
||||
- 2026-06-05: B11.1b Captain scenario/custom-tool checkpoint prepared as `feat(captain): align scenario and tool payloads`; scenarios now accept nested frontend bodies, enforce account/assistant scope, list only enabled scenarios, and return raw scenario/list/204 payloads. Custom tools now accept nested frontend bodies, auto-generate slugs, enforce account scope, and return raw tool/list/204 payloads. Focused CaptainScenario/CaptainCustomTool/CaptainResource tests plus Captain/Copilot focused handler/service tests passed. Next slice is B11.1c documents, assistant responses, bulk actions, and custom-tool test execution.
|
||||
|
||||
@@ -561,7 +561,7 @@ func Bootstrap(env string) (*App, error) {
|
||||
// Captain services (P10 M10 — Captain AI + Copilot)
|
||||
captainAssistantService := service.NewCaptainAssistantService(captainAssistantRepo, captainInboxRepo, captainDocumentRepo, captainAssistantResponseRepo, llmProvider)
|
||||
captainDocumentService := service.NewCaptainDocumentService(captainDocumentRepo, llmProvider)
|
||||
captainScenarioService := service.NewCaptainScenarioService(captainScenarioRepo)
|
||||
captainScenarioService := service.NewCaptainScenarioService(captainScenarioRepo, captainAssistantRepo)
|
||||
captainCustomToolService := service.NewCaptainCustomToolService(captainCustomToolRepo)
|
||||
copilotService := service.NewCopilotService(copilotThreadRepo, copilotMessageRepo, copilotSuggestionRepo, llmProvider)
|
||||
copilotContextService := service.NewCopilotContextService(messageRepo, conversationRepo, contactRepo, llmProvider)
|
||||
|
||||
@@ -347,11 +347,15 @@ func (h *CaptainAssistantHandler) GenerateResponse(c *gin.Context) {
|
||||
}
|
||||
|
||||
func bindCaptainAssistantPayload(c *gin.Context, dst any) error {
|
||||
return bindNestedJSONPayload(c, "assistant", dst)
|
||||
}
|
||||
|
||||
func bindNestedJSONPayload(c *gin.Context, key string, dst any) error {
|
||||
var raw map[string]json.RawMessage
|
||||
if err := c.ShouldBindJSON(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if nested, ok := raw["assistant"]; ok {
|
||||
if nested, ok := raw[key]; ok {
|
||||
return json.Unmarshal(nested, dst)
|
||||
}
|
||||
body, err := json.Marshal(raw)
|
||||
|
||||
@@ -115,12 +115,11 @@ func (s *CaptainCustomToolCRUDTestSuite) createToolAndGetID(title, slug, endpoin
|
||||
"endpoint_url": endpointURL,
|
||||
}
|
||||
w := s.makeRequest("POST", s.accountPath()+"/captain/custom_tools/", body)
|
||||
s.Require().Equal(http.StatusCreated, w.Code)
|
||||
s.Require().Equal(http.StatusOK, w.Code)
|
||||
|
||||
var resp map[string]interface{}
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
|
||||
data := resp["data"].(map[string]interface{})
|
||||
return strconv.FormatFloat(data["id"].(float64), 'f', -1, 64)
|
||||
return strconv.FormatFloat(resp["id"].(float64), 'f', -1, 64)
|
||||
}
|
||||
|
||||
// ========== 创建自定义工具测试 ==========
|
||||
@@ -135,18 +134,16 @@ func (s *CaptainCustomToolCRUDTestSuite) TestCreate_成功创建自定义工具(
|
||||
|
||||
w := s.makeRequest("POST", s.accountPath()+"/captain/custom_tools/", body)
|
||||
|
||||
assert.Equal(s.T(), http.StatusCreated, w.Code)
|
||||
assert.Equal(s.T(), http.StatusOK, w.Code)
|
||||
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
assert.True(s.T(), resp["success"].(bool))
|
||||
|
||||
data := resp["data"].(map[string]interface{})
|
||||
assert.Equal(s.T(), "测试工具", data["title"])
|
||||
assert.Equal(s.T(), "test-tool", data["slug"])
|
||||
assert.Equal(s.T(), "https://example.com/api", data["endpoint_url"])
|
||||
assert.Equal(s.T(), "POST", data["http_method"])
|
||||
assert.Equal(s.T(), true, data["enabled"]) // default true
|
||||
assert.NotContains(s.T(), resp, "success")
|
||||
assert.Equal(s.T(), "测试工具", resp["title"])
|
||||
assert.Equal(s.T(), "test-tool", resp["slug"])
|
||||
assert.Equal(s.T(), "https://example.com/api", resp["endpoint_url"])
|
||||
assert.Equal(s.T(), "POST", resp["http_method"])
|
||||
assert.Equal(s.T(), true, resp["enabled"]) // default true
|
||||
}
|
||||
|
||||
func (s *CaptainCustomToolCRUDTestSuite) TestCreate_默认GET方法() {
|
||||
@@ -158,12 +155,11 @@ func (s *CaptainCustomToolCRUDTestSuite) TestCreate_默认GET方法() {
|
||||
|
||||
w := s.makeRequest("POST", s.accountPath()+"/captain/custom_tools/", body)
|
||||
|
||||
assert.Equal(s.T(), http.StatusCreated, w.Code)
|
||||
assert.Equal(s.T(), http.StatusOK, w.Code)
|
||||
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
data := resp["data"].(map[string]interface{})
|
||||
assert.Equal(s.T(), "GET", data["http_method"]) // default HTTP method
|
||||
assert.Equal(s.T(), "GET", resp["http_method"]) // default HTTP method
|
||||
}
|
||||
|
||||
func (s *CaptainCustomToolCRUDTestSuite) TestCreate_无效JSON返回400() {
|
||||
@@ -195,11 +191,9 @@ func (s *CaptainCustomToolCRUDTestSuite) TestGet_成功获取自定义工具() {
|
||||
|
||||
var getResp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &getResp)
|
||||
assert.True(s.T(), getResp["success"].(bool))
|
||||
|
||||
data := getResp["data"].(map[string]interface{})
|
||||
assert.Equal(s.T(), "获取测试工具", data["title"])
|
||||
assert.Equal(s.T(), "get-test-tool", data["slug"])
|
||||
assert.NotContains(s.T(), getResp, "success")
|
||||
assert.Equal(s.T(), "获取测试工具", getResp["title"])
|
||||
assert.Equal(s.T(), "get-test-tool", getResp["slug"])
|
||||
}
|
||||
|
||||
func (s *CaptainCustomToolCRUDTestSuite) TestGet_不存在的ID返回404() {
|
||||
@@ -218,7 +212,7 @@ func (s *CaptainCustomToolCRUDTestSuite) TestList_成功列出自定义工具()
|
||||
"endpoint_url": "https://example.com/list" + strconv.Itoa(i),
|
||||
}
|
||||
w := s.makeRequest("POST", s.accountPath()+"/captain/custom_tools/", body)
|
||||
s.Require().Equal(http.StatusCreated, w.Code)
|
||||
s.Require().Equal(http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
// 列出工具 — 使用 accountRouter
|
||||
@@ -227,14 +221,12 @@ func (s *CaptainCustomToolCRUDTestSuite) TestList_成功列出自定义工具()
|
||||
|
||||
var listResp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &listResp)
|
||||
assert.True(s.T(), listResp["success"].(bool))
|
||||
|
||||
data := listResp["data"].([]interface{})
|
||||
assert.NotContains(s.T(), listResp, "success")
|
||||
data := listResp["payload"].([]interface{})
|
||||
assert.Equal(s.T(), 3, len(data))
|
||||
|
||||
meta := listResp["meta"].(map[string]interface{})
|
||||
assert.Equal(s.T(), float64(1), meta["page"])
|
||||
assert.Equal(s.T(), float64(25), meta["per_page"]) // DefaultPerPage = 25
|
||||
assert.Equal(s.T(), float64(3), meta["total_count"])
|
||||
}
|
||||
|
||||
@@ -257,11 +249,9 @@ func (s *CaptainCustomToolCRUDTestSuite) TestUpdate_成功更新自定义工具(
|
||||
|
||||
var updateResp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &updateResp)
|
||||
assert.True(s.T(), updateResp["success"].(bool))
|
||||
|
||||
data := updateResp["data"].(map[string]interface{})
|
||||
assert.Equal(s.T(), "更新后标题", data["title"])
|
||||
assert.Equal(s.T(), "https://example.com/after", data["endpoint_url"])
|
||||
assert.NotContains(s.T(), updateResp, "success")
|
||||
assert.Equal(s.T(), "更新后标题", updateResp["title"])
|
||||
assert.Equal(s.T(), "https://example.com/after", updateResp["endpoint_url"])
|
||||
}
|
||||
|
||||
func (s *CaptainCustomToolCRUDTestSuite) TestUpdate_更新enabled字段() {
|
||||
@@ -276,8 +266,7 @@ func (s *CaptainCustomToolCRUDTestSuite) TestUpdate_更新enabled字段() {
|
||||
|
||||
var updateResp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &updateResp)
|
||||
data := updateResp["data"].(map[string]interface{})
|
||||
assert.Equal(s.T(), false, data["enabled"])
|
||||
assert.Equal(s.T(), false, updateResp["enabled"])
|
||||
}
|
||||
|
||||
func (s *CaptainCustomToolCRUDTestSuite) TestUpdate_不存在的ID返回500() {
|
||||
@@ -307,8 +296,7 @@ func (s *CaptainCustomToolCRUDTestSuite) TestDelete_成功删除自定义工具(
|
||||
func (s *CaptainCustomToolCRUDTestSuite) TestDelete_不存在的ID() {
|
||||
w := s.makeRequest("DELETE", s.accountPath()+"/captain/custom_tools/999999", nil)
|
||||
// Delete of non-existent tool: handler returns 500 or 204 depending on service behavior
|
||||
assert.True(s.T(), w.Code == http.StatusUnprocessableEntity || w.Code == http.StatusNoContent,
|
||||
"expected 500 or 204 for non-existent tool delete, got %d", w.Code)
|
||||
assert.Equal(s.T(), http.StatusNotFound, w.Code)
|
||||
}
|
||||
|
||||
func TestCaptainCustomToolCRUDSuite(t *testing.T) {
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
"github.com/gochat/gochat/pkg/pagination"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
)
|
||||
|
||||
@@ -31,7 +31,7 @@ func (h *CaptainCustomToolHandler) Create(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req service.CreateCustomToolRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindNestedJSONPayload(c, "custom_tool", &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -43,31 +43,41 @@ func (h *CaptainCustomToolHandler) Create(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.Created(c, tool)
|
||||
c.JSON(http.StatusOK, captainCustomToolPayload(tool))
|
||||
}
|
||||
|
||||
// Get retrieves a custom tool by ID.
|
||||
// GET /api/v1/accounts/:account_id/captain_custom_tools/:id
|
||||
func (h *CaptainCustomToolHandler) Get(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintAnyParam(c, "tool_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
tool, err := h.svc.Get(c.Request.Context(), id)
|
||||
tool, err := h.svc.GetByAccount(c.Request.Context(), accountID, id)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Get captain custom tool: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "custom tool not found")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, tool)
|
||||
c.JSON(http.StatusOK, captainCustomToolPayload(tool))
|
||||
}
|
||||
|
||||
// Update updates an existing custom tool.
|
||||
// PUT /api/v1/accounts/:account_id/captain_custom_tools/:id
|
||||
func (h *CaptainCustomToolHandler) Update(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintAnyParam(c, "tool_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
@@ -75,33 +85,38 @@ func (h *CaptainCustomToolHandler) Update(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req service.UpdateCustomToolRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindNestedJSONPayload(c, "custom_tool", &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
tool, err := h.svc.Update(c.Request.Context(), id, &req)
|
||||
tool, err := h.svc.UpdateByAccount(c.Request.Context(), accountID, id, &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Update captain custom tool: %v", err)
|
||||
handleServiceError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, tool)
|
||||
c.JSON(http.StatusOK, captainCustomToolPayload(tool))
|
||||
}
|
||||
|
||||
// Delete deletes a custom tool.
|
||||
// DELETE /api/v1/accounts/:account_id/captain_custom_tools/:id
|
||||
func (h *CaptainCustomToolHandler) Delete(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintAnyParam(c, "tool_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.Delete(c.Request.Context(), id); err != nil {
|
||||
if err := h.svc.DeleteByAccount(c.Request.Context(), accountID, id); err != nil {
|
||||
applogger.L().Errorf("Delete captain custom tool: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to delete custom tool")
|
||||
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to delete custom tool")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -117,15 +132,18 @@ func (h *CaptainCustomToolHandler) List(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
p := pagination.Parse(c)
|
||||
tools, count, err := h.svc.List(c.Request.Context(), accountID, p.Offset, p.PerPage)
|
||||
tools, count, err := h.svc.List(c.Request.Context(), accountID, 0, 1000)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("List captain custom tools: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to list custom tools")
|
||||
return
|
||||
}
|
||||
|
||||
response.OKWithMeta(c, tools, p.Page, p.PerPage, count)
|
||||
payload := make([]gin.H, 0, len(tools))
|
||||
for i := range tools {
|
||||
payload = append(payload, captainCustomToolPayload(&tools[i]))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"payload": payload, "meta": gin.H{"total_count": count, "page": 1}})
|
||||
}
|
||||
|
||||
// ExecuteTool calls the external HTTP endpoint of a custom tool.
|
||||
@@ -163,7 +181,7 @@ func (h *CaptainCustomToolHandler) TestTool(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req service.TestToolRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindNestedJSONPayload(c, "custom_tool", &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -175,5 +193,25 @@ func (h *CaptainCustomToolHandler) TestTool(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, result)
|
||||
c.JSON(http.StatusOK, result)
|
||||
}
|
||||
|
||||
func captainCustomToolPayload(tool *model.CaptainCustomTool) gin.H {
|
||||
return gin.H{
|
||||
"id": tool.ID,
|
||||
"slug": tool.Slug,
|
||||
"title": tool.Title,
|
||||
"description": tool.Description,
|
||||
"endpoint_url": tool.EndpointURL,
|
||||
"http_method": tool.HTTPMethod,
|
||||
"request_template": tool.RequestTemplate,
|
||||
"response_template": tool.ResponseTemplate,
|
||||
"auth_type": tool.AuthType,
|
||||
"auth_config": rawJSONValue(tool.AuthConfig),
|
||||
"param_schema": rawJSONValue(tool.ParamSchema),
|
||||
"enabled": tool.Enabled,
|
||||
"account_id": tool.AccountID,
|
||||
"created_at": tool.CreatedAt.Unix(),
|
||||
"updated_at": tool.UpdatedAt.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,9 +113,7 @@ func (s *CaptainCustomToolTestHandlerTestSuite) TestTestTool_成功测试工具(
|
||||
if w.Code == http.StatusOK {
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
assert.True(s.T(), resp["success"].(bool))
|
||||
data := resp["data"].(map[string]interface{})
|
||||
assert.Contains(s.T(), data, "success")
|
||||
assert.Contains(s.T(), resp, "success")
|
||||
} else {
|
||||
// 即使外部请求失败,也应该返回 InternalServerError 格式
|
||||
assert.Equal(s.T(), http.StatusUnprocessableEntity, w.Code)
|
||||
@@ -199,7 +197,7 @@ func (s *CaptainCustomToolTestHandlerTestSuite) TestTestTool_带POST方法和参
|
||||
if w.Code == http.StatusOK {
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
assert.True(s.T(), resp["success"].(bool))
|
||||
assert.Contains(s.T(), resp, "success")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func setupCaptainResourceParityTest(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.Account, *model.CaptainAssistant) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dbName := fmt.Sprintf("file:%s?mode=memory&cache=private", t.Name())
|
||||
db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.CaptainAssistant{},
|
||||
&model.CaptainScenario{},
|
||||
&model.CaptainCustomTool{},
|
||||
))
|
||||
t.Cleanup(func() {
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.Close()
|
||||
})
|
||||
|
||||
account := &model.Account{Name: "Captain Account", Locale: "en", Active: true}
|
||||
otherAccount := &model.Account{Name: "Other Account", Locale: "en", Active: true}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
require.NoError(t, db.Create(otherAccount).Error)
|
||||
assistant := &model.CaptainAssistant{AccountID: account.ID, Name: "Fin", Description: "Support", Config: json.RawMessage(`{}`), Status: model.AssistantStatusActive}
|
||||
require.NoError(t, db.Create(assistant).Error)
|
||||
|
||||
assistantRepo := repository.NewCaptainAssistantRepo(db)
|
||||
scenarioRepo := repository.NewCaptainScenarioRepo(db)
|
||||
scenarioSvc := service.NewCaptainScenarioService(scenarioRepo, assistantRepo)
|
||||
scenarioHandler := NewCaptainScenarioHandler(scenarioSvc)
|
||||
|
||||
toolRepo := repository.NewCaptainCustomToolRepo(db)
|
||||
toolSvc := service.NewCaptainCustomToolService(toolRepo)
|
||||
toolHandler := NewCaptainCustomToolHandler(toolSvc)
|
||||
|
||||
router := gin.New()
|
||||
accountGroup := router.Group("/api/v1/accounts/:account_id/captain")
|
||||
assistantScenarios := accountGroup.Group("/assistants/:assistant_id/scenarios")
|
||||
assistantScenarios.GET("/", scenarioHandler.List)
|
||||
assistantScenarios.POST("/", scenarioHandler.Create)
|
||||
assistantScenarios.GET("/:scenario_id", scenarioHandler.Get)
|
||||
assistantScenarios.PUT("/:scenario_id", scenarioHandler.Update)
|
||||
assistantScenarios.DELETE("/:scenario_id", scenarioHandler.Delete)
|
||||
|
||||
customTools := accountGroup.Group("/custom_tools")
|
||||
customTools.GET("/", toolHandler.List)
|
||||
customTools.POST("/", toolHandler.Create)
|
||||
customTools.GET("/:tool_id", toolHandler.Get)
|
||||
customTools.PUT("/:tool_id", toolHandler.Update)
|
||||
customTools.DELETE("/:tool_id", toolHandler.Delete)
|
||||
|
||||
return router, db, account, otherAccount, assistant
|
||||
}
|
||||
|
||||
func captainResourceJSONRequest(t *testing.T, router *gin.Engine, method, path string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var payload []byte
|
||||
if body != nil {
|
||||
data, err := json.Marshal(body)
|
||||
require.NoError(t, err)
|
||||
payload = data
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, path, bytes.NewReader(payload))
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
router.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestCaptainScenarioHandler_ChatwootScenarioPayloadsAndScope(t *testing.T) {
|
||||
router, db, account, otherAccount, assistant := setupCaptainResourceParityTest(t)
|
||||
basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants/" + strconv.FormatUint(uint64(assistant.ID), 10) + "/scenarios"
|
||||
otherBasePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(otherAccount.ID), 10) + "/captain/assistants/" + strconv.FormatUint(uint64(assistant.ID), 10) + "/scenarios"
|
||||
|
||||
body := map[string]any{"scenario": map[string]any{
|
||||
"title": "Escalate billing",
|
||||
"description": "Billing handoff",
|
||||
"instruction": "Ask for invoice ID",
|
||||
"tools": []string{"handoff"},
|
||||
}}
|
||||
w := captainResourceJSONRequest(t, router, http.MethodPost, basePath+"/", body)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var created map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &created))
|
||||
assert.NotContains(t, created, "success")
|
||||
assert.Equal(t, "Escalate billing", created["title"])
|
||||
assert.Equal(t, float64(account.ID), created["account_id"])
|
||||
assert.Equal(t, float64(assistant.ID), created["assistant_id"])
|
||||
assert.Equal(t, "Fin", created["assistant"].(map[string]any)["name"])
|
||||
scenarioID := uint(created["id"].(float64))
|
||||
|
||||
disabled := &model.CaptainScenario{AccountID: account.ID, AssistantID: assistant.ID, Title: "Disabled", Enabled: false}
|
||||
require.NoError(t, db.Create(disabled).Error)
|
||||
require.NoError(t, db.Model(disabled).Update("enabled", false).Error)
|
||||
w = captainResourceJSONRequest(t, router, http.MethodGet, basePath+"/", nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var listResp map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &listResp))
|
||||
assert.Len(t, listResp["payload"], 1)
|
||||
assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["total_count"])
|
||||
|
||||
w = captainResourceJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", otherBasePath, scenarioID), nil)
|
||||
assert.Equal(t, http.StatusNotFound, w.Code)
|
||||
|
||||
updateBody := map[string]any{"scenario": map[string]any{"enabled": false, "instruction": "Updated"}}
|
||||
w = captainResourceJSONRequest(t, router, http.MethodPut, fmt.Sprintf("%s/%d", basePath, scenarioID), updateBody)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var updated map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &updated))
|
||||
assert.Equal(t, false, updated["enabled"])
|
||||
assert.Equal(t, "Updated", updated["instruction"])
|
||||
|
||||
w = captainResourceJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d", basePath, scenarioID), nil)
|
||||
assert.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
|
||||
func TestCaptainCustomToolHandler_ChatwootToolPayloadsAndScope(t *testing.T) {
|
||||
router, _, account, otherAccount, _ := setupCaptainResourceParityTest(t)
|
||||
basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/custom_tools"
|
||||
otherBasePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(otherAccount.ID), 10) + "/captain/custom_tools"
|
||||
|
||||
body := map[string]any{"custom_tool": map[string]any{
|
||||
"title": "Lookup Order",
|
||||
"description": "Fetch order status",
|
||||
"endpoint_url": "https://example.com/orders",
|
||||
"http_method": "POST",
|
||||
"auth_type": "none",
|
||||
"param_schema": []map[string]any{{"name": "order_id", "type": "string", "required": true}},
|
||||
"request_template": "{\"id\":\"{{.order_id}}\"}",
|
||||
}}
|
||||
w := captainResourceJSONRequest(t, router, http.MethodPost, basePath+"/", body)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var created map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &created))
|
||||
assert.NotContains(t, created, "success")
|
||||
assert.Equal(t, "lookup-order", created["slug"])
|
||||
assert.Equal(t, "POST", created["http_method"])
|
||||
toolID := uint(created["id"].(float64))
|
||||
|
||||
w = captainResourceJSONRequest(t, router, http.MethodGet, basePath+"/", nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var listResp map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &listResp))
|
||||
assert.Len(t, listResp["payload"], 1)
|
||||
assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["page"])
|
||||
|
||||
w = captainResourceJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", otherBasePath, toolID), nil)
|
||||
assert.Equal(t, http.StatusNotFound, w.Code)
|
||||
|
||||
updateBody := map[string]any{"custom_tool": map[string]any{"enabled": false, "title": "Lookup Order V2"}}
|
||||
w = captainResourceJSONRequest(t, router, http.MethodPut, fmt.Sprintf("%s/%d", basePath, toolID), updateBody)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var updated map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &updated))
|
||||
assert.Equal(t, false, updated["enabled"])
|
||||
assert.Equal(t, "Lookup Order V2", updated["title"])
|
||||
|
||||
w = captainResourceJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d", basePath, toolID), nil)
|
||||
assert.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
@@ -2,12 +2,11 @@ package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
"github.com/gochat/gochat/pkg/pagination"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
)
|
||||
|
||||
@@ -25,89 +24,119 @@ func NewCaptainScenarioHandler(svc *service.CaptainScenarioService) *CaptainScen
|
||||
// Create creates a new scenario under an assistant.
|
||||
// POST /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios
|
||||
func (h *CaptainScenarioHandler) Create(c *gin.Context) {
|
||||
accountID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
assistantID, err := strconv.ParseUint(c.Param("assistant_id"), 10, 64)
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant_id")
|
||||
return
|
||||
}
|
||||
|
||||
var req service.CreateScenarioRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindNestedJSONPayload(c, "scenario", &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
scenario, err := h.svc.Create(c.Request.Context(), uint(accountID), uint(assistantID), &req)
|
||||
scenario, err := h.svc.Create(c.Request.Context(), accountID, assistantID, &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Create captain scenario: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to create scenario")
|
||||
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to create scenario")
|
||||
return
|
||||
}
|
||||
|
||||
response.Created(c, scenario)
|
||||
c.JSON(http.StatusOK, captainScenarioPayload(scenario))
|
||||
}
|
||||
|
||||
// Get retrieves a scenario by ID.
|
||||
// GET /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios/:id
|
||||
func (h *CaptainScenarioHandler) Get(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintAnyParam(c, "scenario_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
scenario, err := h.svc.GetByID(c.Request.Context(), uint(id))
|
||||
scenario, err := h.svc.Get(c.Request.Context(), accountID, assistantID, id)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Get captain scenario: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "scenario not found")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, scenario)
|
||||
c.JSON(http.StatusOK, captainScenarioPayload(scenario))
|
||||
}
|
||||
|
||||
// Update updates an existing scenario.
|
||||
// PUT /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios/:id
|
||||
func (h *CaptainScenarioHandler) Update(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintAnyParam(c, "scenario_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
var req service.UpdateScenarioRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindNestedJSONPayload(c, "scenario", &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
scenario, err := h.svc.Update(c.Request.Context(), uint(id), &req)
|
||||
scenario, err := h.svc.UpdateScoped(c.Request.Context(), accountID, assistantID, id, &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Update captain scenario: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update scenario")
|
||||
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to update scenario")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, scenario)
|
||||
c.JSON(http.StatusOK, captainScenarioPayload(scenario))
|
||||
}
|
||||
|
||||
// Delete deletes a scenario.
|
||||
// DELETE /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios/:id
|
||||
func (h *CaptainScenarioHandler) Delete(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintAnyParam(c, "scenario_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.Delete(c.Request.Context(), uint(id)); err != nil {
|
||||
if err := h.svc.DeleteScoped(c.Request.Context(), accountID, assistantID, id); err != nil {
|
||||
applogger.L().Errorf("Delete captain scenario: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to delete scenario")
|
||||
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to delete scenario")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -117,19 +146,46 @@ func (h *CaptainScenarioHandler) Delete(c *gin.Context) {
|
||||
// List retrieves scenarios for an assistant.
|
||||
// GET /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios
|
||||
func (h *CaptainScenarioHandler) List(c *gin.Context) {
|
||||
assistantID, err := strconv.ParseUint(c.Param("assistant_id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant_id")
|
||||
return
|
||||
}
|
||||
|
||||
p := pagination.Parse(c)
|
||||
scenarios, count, err := h.svc.ListByAssistant(c.Request.Context(), uint(assistantID), p.Offset, p.PerPage)
|
||||
scenarios, count, err := h.svc.ListByAccountAssistant(c.Request.Context(), accountID, assistantID)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("List captain scenarios: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to list scenarios")
|
||||
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to list scenarios")
|
||||
return
|
||||
}
|
||||
|
||||
response.OKWithMeta(c, scenarios, p.Page, p.PerPage, count)
|
||||
}
|
||||
payload := make([]gin.H, 0, len(scenarios))
|
||||
for i := range scenarios {
|
||||
payload = append(payload, captainScenarioPayload(&scenarios[i]))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"payload": payload, "meta": gin.H{"total_count": count, "page": 1}})
|
||||
}
|
||||
|
||||
func captainScenarioPayload(scenario *model.CaptainScenario) gin.H {
|
||||
payload := gin.H{
|
||||
"id": scenario.ID,
|
||||
"title": scenario.Title,
|
||||
"description": scenario.Description,
|
||||
"instruction": scenario.Instruction,
|
||||
"tools": rawJSONValue(scenario.Tools),
|
||||
"enabled": scenario.Enabled,
|
||||
"assistant_id": scenario.AssistantID,
|
||||
"account_id": scenario.AccountID,
|
||||
"created_at": scenario.CreatedAt,
|
||||
"updated_at": scenario.UpdatedAt,
|
||||
}
|
||||
if scenario.Assistant.ID != 0 {
|
||||
payload["assistant"] = gin.H{"id": scenario.Assistant.ID, "name": scenario.Assistant.Name}
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -232,6 +232,8 @@ type CaptainScenario struct {
|
||||
Instruction string `gorm:"type:text" json:"instruction,omitempty"`
|
||||
Enabled bool `gorm:"default:true;not null;index" json:"enabled"`
|
||||
Tools json.RawMessage `gorm:"type:jsonb;serializer:json" json:"tools,omitempty"` // array of tool names
|
||||
|
||||
Assistant CaptainAssistant `gorm:"foreignKey:AssistantID" json:"assistant,omitempty"`
|
||||
}
|
||||
|
||||
func (CaptainScenario) TableName() string { return "captain_scenarios" }
|
||||
|
||||
@@ -28,6 +28,14 @@ func (r *CaptainCustomToolRepo) GetByID(ctx context.Context, id uint) (*model.Ca
|
||||
return &tool, nil
|
||||
}
|
||||
|
||||
func (r *CaptainCustomToolRepo) GetByAccountAndID(ctx context.Context, accountID, id uint) (*model.CaptainCustomTool, error) {
|
||||
var tool model.CaptainCustomTool
|
||||
if err := r.db.WithContext(ctx).Where("account_id = ? AND id = ?", accountID, id).First(&tool).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tool, nil
|
||||
}
|
||||
|
||||
func (r *CaptainCustomToolRepo) GetBySlug(ctx context.Context, accountID uint, slug string) (*model.CaptainCustomTool, error) {
|
||||
var tool model.CaptainCustomTool
|
||||
if err := r.db.WithContext(ctx).Where("account_id = ? AND slug = ?", accountID, slug).First(&tool).Error; err != nil {
|
||||
@@ -44,6 +52,10 @@ func (r *CaptainCustomToolRepo) Delete(ctx context.Context, id uint) error {
|
||||
return r.db.WithContext(ctx).Delete(&model.CaptainCustomTool{}, id).Error
|
||||
}
|
||||
|
||||
func (r *CaptainCustomToolRepo) DeleteByAccount(ctx context.Context, accountID, id uint) error {
|
||||
return r.db.WithContext(ctx).Where("account_id = ? AND id = ?", accountID, id).Delete(&model.CaptainCustomTool{}).Error
|
||||
}
|
||||
|
||||
func (r *CaptainCustomToolRepo) ListByAccount(ctx context.Context, accountID uint, offset, limit int) ([]model.CaptainCustomTool, int64, error) {
|
||||
var tools []model.CaptainCustomTool
|
||||
var count int64
|
||||
@@ -61,4 +73,4 @@ func (r *CaptainCustomToolRepo) CountByAccount(ctx context.Context, accountID ui
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,18 @@ func (r *CaptainScenarioRepo) Create(ctx context.Context, scenario *model.Captai
|
||||
|
||||
func (r *CaptainScenarioRepo) GetByID(ctx context.Context, id uint) (*model.CaptainScenario, error) {
|
||||
var scenario model.CaptainScenario
|
||||
if err := r.db.WithContext(ctx).First(&scenario, id).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Preload("Assistant").First(&scenario, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &scenario, nil
|
||||
}
|
||||
|
||||
func (r *CaptainScenarioRepo) GetByAccountAssistantAndID(ctx context.Context, accountID, assistantID, id uint) (*model.CaptainScenario, error) {
|
||||
var scenario model.CaptainScenario
|
||||
if err := r.db.WithContext(ctx).
|
||||
Preload("Assistant").
|
||||
Where("account_id = ? AND assistant_id = ? AND id = ?", accountID, assistantID, id).
|
||||
First(&scenario).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &scenario, nil
|
||||
@@ -36,12 +47,30 @@ func (r *CaptainScenarioRepo) Delete(ctx context.Context, id uint) error {
|
||||
return r.db.WithContext(ctx).Delete(&model.CaptainScenario{}, id).Error
|
||||
}
|
||||
|
||||
func (r *CaptainScenarioRepo) DeleteByAccountAssistant(ctx context.Context, accountID, assistantID, id uint) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("account_id = ? AND assistant_id = ? AND id = ?", accountID, assistantID, id).
|
||||
Delete(&model.CaptainScenario{}).Error
|
||||
}
|
||||
|
||||
func (r *CaptainScenarioRepo) ListByAssistant(ctx context.Context, assistantID uint, offset, limit int) ([]model.CaptainScenario, int64, error) {
|
||||
var scenarios []model.CaptainScenario
|
||||
var count int64
|
||||
db := r.db.WithContext(ctx).Model(&model.CaptainScenario{}).Where("assistant_id = ?", assistantID)
|
||||
db.Count(&count)
|
||||
if err := db.Offset(offset).Limit(limit).Find(&scenarios).Error; err != nil {
|
||||
if err := db.Preload("Assistant").Offset(offset).Limit(limit).Find(&scenarios).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return scenarios, count, nil
|
||||
}
|
||||
|
||||
func (r *CaptainScenarioRepo) ListEnabledByAccountAssistant(ctx context.Context, accountID, assistantID uint) ([]model.CaptainScenario, int64, error) {
|
||||
var scenarios []model.CaptainScenario
|
||||
var count int64
|
||||
db := r.db.WithContext(ctx).Model(&model.CaptainScenario{}).
|
||||
Where("account_id = ? AND assistant_id = ? AND enabled = ?", accountID, assistantID, true)
|
||||
db.Count(&count)
|
||||
if err := db.Preload("Assistant").Order("created_at ASC").Find(&scenarios).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return scenarios, count, nil
|
||||
@@ -56,4 +85,4 @@ func (r *CaptainScenarioRepo) FindEnabled(ctx context.Context, assistantID uint)
|
||||
return nil, err
|
||||
}
|
||||
return scenarios, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
@@ -32,7 +33,7 @@ func NewCaptainCustomToolService(toolRepo *repository.CaptainCustomToolRepo) *Ca
|
||||
// CreateCustomToolRequest is the DTO for creating a custom tool.
|
||||
type CreateCustomToolRequest struct {
|
||||
Title string `json:"title" validate:"required"`
|
||||
Slug string `json:"slug" validate:"required"`
|
||||
Slug string `json:"slug"`
|
||||
Description string `json:"description"`
|
||||
EndpointURL string `json:"endpoint_url" validate:"required"`
|
||||
HTTPMethod string `json:"http_method"`
|
||||
@@ -70,11 +71,15 @@ func (s *CaptainCustomToolService) Create(ctx context.Context, accountID uint, r
|
||||
if authType == "" {
|
||||
authType = "none"
|
||||
}
|
||||
slug := req.Slug
|
||||
if slug == "" {
|
||||
slug = customToolSlug(req.Title)
|
||||
}
|
||||
|
||||
tool := &model.CaptainCustomTool{
|
||||
AccountID: accountID,
|
||||
Title: req.Title,
|
||||
Slug: req.Slug,
|
||||
Slug: slug,
|
||||
Description: req.Description,
|
||||
EndpointURL: req.EndpointURL,
|
||||
HTTPMethod: httpMethod,
|
||||
@@ -103,6 +108,15 @@ func (s *CaptainCustomToolService) Get(ctx context.Context, id uint) (*model.Cap
|
||||
return tool, nil
|
||||
}
|
||||
|
||||
func (s *CaptainCustomToolService) GetByAccount(ctx context.Context, accountID, id uint) (*model.CaptainCustomTool, error) {
|
||||
tool, err := s.toolRepo.GetByAccountAndID(ctx, accountID, id)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Get captain custom tool: %v", err)
|
||||
return nil, fmt.Errorf("get custom tool: %w", err)
|
||||
}
|
||||
return tool, nil
|
||||
}
|
||||
|
||||
// Update updates an existing custom tool.
|
||||
func (s *CaptainCustomToolService) Update(ctx context.Context, id uint, req *UpdateCustomToolRequest) (*model.CaptainCustomTool, error) {
|
||||
tool, err := s.toolRepo.GetByID(ctx, id)
|
||||
@@ -148,6 +162,19 @@ func (s *CaptainCustomToolService) Update(ctx context.Context, id uint, req *Upd
|
||||
return tool, nil
|
||||
}
|
||||
|
||||
func (s *CaptainCustomToolService) UpdateByAccount(ctx context.Context, accountID, id uint, req *UpdateCustomToolRequest) (*model.CaptainCustomTool, error) {
|
||||
tool, err := s.toolRepo.GetByAccountAndID(ctx, accountID, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("custom tool not found: %w", err)
|
||||
}
|
||||
applyCustomToolUpdate(tool, req)
|
||||
if err := s.toolRepo.Update(ctx, tool); err != nil {
|
||||
applogger.L().Errorf("Update captain custom tool: %v", err)
|
||||
return nil, fmt.Errorf("update custom tool: %w", err)
|
||||
}
|
||||
return tool, nil
|
||||
}
|
||||
|
||||
// Delete deletes a custom tool by ID.
|
||||
func (s *CaptainCustomToolService) Delete(ctx context.Context, id uint) error {
|
||||
if err := s.toolRepo.Delete(ctx, id); err != nil {
|
||||
@@ -157,6 +184,17 @@ func (s *CaptainCustomToolService) Delete(ctx context.Context, id uint) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CaptainCustomToolService) DeleteByAccount(ctx context.Context, accountID, id uint) error {
|
||||
if _, err := s.toolRepo.GetByAccountAndID(ctx, accountID, id); err != nil {
|
||||
return fmt.Errorf("custom tool not found: %w", err)
|
||||
}
|
||||
if err := s.toolRepo.DeleteByAccount(ctx, accountID, id); err != nil {
|
||||
applogger.L().Errorf("Delete captain custom tool: %v", err)
|
||||
return fmt.Errorf("delete custom tool: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// List retrieves custom tools for an account with pagination.
|
||||
func (s *CaptainCustomToolService) List(ctx context.Context, accountID uint, offset, limit int) ([]model.CaptainCustomTool, int64, error) {
|
||||
tools, count, err := s.toolRepo.ListByAccount(ctx, accountID, offset, limit)
|
||||
@@ -167,6 +205,49 @@ func (s *CaptainCustomToolService) List(ctx context.Context, accountID uint, off
|
||||
return tools, count, nil
|
||||
}
|
||||
|
||||
func applyCustomToolUpdate(tool *model.CaptainCustomTool, req *UpdateCustomToolRequest) {
|
||||
if req.Title != "" {
|
||||
tool.Title = req.Title
|
||||
}
|
||||
if req.Description != "" {
|
||||
tool.Description = req.Description
|
||||
}
|
||||
if req.EndpointURL != "" {
|
||||
tool.EndpointURL = req.EndpointURL
|
||||
}
|
||||
if req.HTTPMethod != "" {
|
||||
tool.HTTPMethod = req.HTTPMethod
|
||||
}
|
||||
if req.AuthType != "" {
|
||||
tool.AuthType = model.ToolAuthType(req.AuthType)
|
||||
}
|
||||
if len(req.AuthConfig) > 0 && string(req.AuthConfig) != "null" {
|
||||
tool.AuthConfig = req.AuthConfig
|
||||
}
|
||||
if len(req.ParamSchema) > 0 && string(req.ParamSchema) != "null" {
|
||||
tool.ParamSchema = req.ParamSchema
|
||||
}
|
||||
if req.RequestTemplate != "" {
|
||||
tool.RequestTemplate = req.RequestTemplate
|
||||
}
|
||||
if req.ResponseTemplate != "" {
|
||||
tool.ResponseTemplate = req.ResponseTemplate
|
||||
}
|
||||
if req.Enabled != nil {
|
||||
tool.Enabled = *req.Enabled
|
||||
}
|
||||
}
|
||||
|
||||
func customToolSlug(title string) string {
|
||||
slug := strings.ToLower(strings.TrimSpace(title))
|
||||
slug = regexp.MustCompile(`[^a-z0-9]+`).ReplaceAllString(slug, "-")
|
||||
slug = strings.Trim(slug, "-")
|
||||
if slug == "" {
|
||||
return "custom-tool"
|
||||
}
|
||||
return slug
|
||||
}
|
||||
|
||||
// --- Tool Execution ---
|
||||
|
||||
// ExecuteToolResult holds the result of executing a custom tool.
|
||||
@@ -330,8 +411,8 @@ func applyAuth(req *http.Request, tool *model.CaptainCustomTool) error {
|
||||
return nil
|
||||
case model.ToolAuthTypeApiKey:
|
||||
var authCfg struct {
|
||||
Key string `json:"key"`
|
||||
Value string `json:"value"`
|
||||
Key string `json:"key"`
|
||||
Value string `json:"value"`
|
||||
Header string `json:"header"` // default: "X-API-Key"
|
||||
}
|
||||
if err := json.Unmarshal(tool.AuthConfig, &authCfg); err != nil {
|
||||
@@ -381,4 +462,4 @@ func (s *CaptainCustomToolService) TestTool(ctx context.Context, accountID uint,
|
||||
}, nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,12 +13,17 @@ import (
|
||||
// CaptainScenarioService implements business logic for CaptainScenario operations.
|
||||
// Reference: Chatwoot enterprise/app/controllers/api/v1/captain/scenarios_controller.rb
|
||||
type CaptainScenarioService struct {
|
||||
scenarioRepo *repository.CaptainScenarioRepo
|
||||
scenarioRepo *repository.CaptainScenarioRepo
|
||||
assistantRepo *repository.CaptainAssistantRepo
|
||||
}
|
||||
|
||||
// NewCaptainScenarioService creates a new CaptainScenarioService.
|
||||
func NewCaptainScenarioService(scenarioRepo *repository.CaptainScenarioRepo) *CaptainScenarioService {
|
||||
return &CaptainScenarioService{scenarioRepo: scenarioRepo}
|
||||
func NewCaptainScenarioService(scenarioRepo *repository.CaptainScenarioRepo, assistantRepo ...*repository.CaptainAssistantRepo) *CaptainScenarioService {
|
||||
s := &CaptainScenarioService{scenarioRepo: scenarioRepo}
|
||||
if len(assistantRepo) > 0 {
|
||||
s.assistantRepo = assistantRepo[0]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// --- Request DTOs ---
|
||||
@@ -28,7 +33,7 @@ type CreateScenarioRequest struct {
|
||||
Title string `json:"title" validate:"required"`
|
||||
Description string `json:"description"`
|
||||
Instruction string `json:"instruction"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
Tools json.RawMessage `json:"tools"`
|
||||
}
|
||||
|
||||
@@ -45,13 +50,22 @@ type UpdateScenarioRequest struct {
|
||||
|
||||
// Create creates a new scenario for an assistant.
|
||||
func (s *CaptainScenarioService) Create(ctx context.Context, accountID, assistantID uint, req *CreateScenarioRequest) (*model.CaptainScenario, error) {
|
||||
if s.assistantRepo != nil {
|
||||
if _, err := s.assistantRepo.GetByAccountAndID(ctx, accountID, assistantID); err != nil {
|
||||
return nil, fmt.Errorf("assistant not found: %w", err)
|
||||
}
|
||||
}
|
||||
enabled := true
|
||||
if req.Enabled != nil {
|
||||
enabled = *req.Enabled
|
||||
}
|
||||
scenario := &model.CaptainScenario{
|
||||
AccountID: accountID,
|
||||
AssistantID: assistantID,
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
Instruction: req.Instruction,
|
||||
Enabled: req.Enabled,
|
||||
Enabled: enabled,
|
||||
Tools: req.Tools,
|
||||
}
|
||||
|
||||
@@ -59,6 +73,18 @@ func (s *CaptainScenarioService) Create(ctx context.Context, accountID, assistan
|
||||
applogger.L().Errorf("Create captain scenario: %v", err)
|
||||
return nil, fmt.Errorf("create scenario: %w", err)
|
||||
}
|
||||
if created, err := s.scenarioRepo.GetByAccountAssistantAndID(ctx, accountID, assistantID, scenario.ID); err == nil {
|
||||
return created, nil
|
||||
}
|
||||
return scenario, nil
|
||||
}
|
||||
|
||||
func (s *CaptainScenarioService) Get(ctx context.Context, accountID, assistantID, id uint) (*model.CaptainScenario, error) {
|
||||
scenario, err := s.scenarioRepo.GetByAccountAssistantAndID(ctx, accountID, assistantID, id)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Get captain scenario: %v", err)
|
||||
return nil, fmt.Errorf("get scenario: %w", err)
|
||||
}
|
||||
return scenario, nil
|
||||
}
|
||||
|
||||
@@ -102,6 +128,35 @@ func (s *CaptainScenarioService) Update(ctx context.Context, id uint, req *Updat
|
||||
return scenario, nil
|
||||
}
|
||||
|
||||
func (s *CaptainScenarioService) UpdateScoped(ctx context.Context, accountID, assistantID, id uint, req *UpdateScenarioRequest) (*model.CaptainScenario, error) {
|
||||
scenario, err := s.scenarioRepo.GetByAccountAssistantAndID(ctx, accountID, assistantID, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scenario not found: %w", err)
|
||||
}
|
||||
|
||||
if req.Title != "" {
|
||||
scenario.Title = req.Title
|
||||
}
|
||||
if req.Description != "" {
|
||||
scenario.Description = req.Description
|
||||
}
|
||||
if req.Instruction != "" {
|
||||
scenario.Instruction = req.Instruction
|
||||
}
|
||||
if req.Enabled != nil {
|
||||
scenario.Enabled = *req.Enabled
|
||||
}
|
||||
if len(req.Tools) > 0 && string(req.Tools) != "null" {
|
||||
scenario.Tools = req.Tools
|
||||
}
|
||||
|
||||
if err := s.scenarioRepo.Update(ctx, scenario); err != nil {
|
||||
applogger.L().Errorf("Update captain scenario: %v", err)
|
||||
return nil, fmt.Errorf("update scenario: %w", err)
|
||||
}
|
||||
return scenario, nil
|
||||
}
|
||||
|
||||
// Delete deletes a scenario by ID.
|
||||
func (s *CaptainScenarioService) Delete(ctx context.Context, id uint) error {
|
||||
if err := s.scenarioRepo.Delete(ctx, id); err != nil {
|
||||
@@ -111,6 +166,17 @@ func (s *CaptainScenarioService) Delete(ctx context.Context, id uint) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CaptainScenarioService) DeleteScoped(ctx context.Context, accountID, assistantID, id uint) error {
|
||||
if _, err := s.scenarioRepo.GetByAccountAssistantAndID(ctx, accountID, assistantID, id); err != nil {
|
||||
return fmt.Errorf("scenario not found: %w", err)
|
||||
}
|
||||
if err := s.scenarioRepo.DeleteByAccountAssistant(ctx, accountID, assistantID, id); err != nil {
|
||||
applogger.L().Errorf("Delete captain scenario: %v", err)
|
||||
return fmt.Errorf("delete scenario: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListByAssistant retrieves scenarios for an assistant with pagination.
|
||||
func (s *CaptainScenarioService) ListByAssistant(ctx context.Context, assistantID uint, offset, limit int) ([]model.CaptainScenario, int64, error) {
|
||||
scenarios, count, err := s.scenarioRepo.ListByAssistant(ctx, assistantID, offset, limit)
|
||||
@@ -119,4 +185,18 @@ func (s *CaptainScenarioService) ListByAssistant(ctx context.Context, assistantI
|
||||
return nil, 0, fmt.Errorf("list scenarios: %w", err)
|
||||
}
|
||||
return scenarios, count, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CaptainScenarioService) ListByAccountAssistant(ctx context.Context, accountID, assistantID uint) ([]model.CaptainScenario, int64, error) {
|
||||
if s.assistantRepo != nil {
|
||||
if _, err := s.assistantRepo.GetByAccountAndID(ctx, accountID, assistantID); err != nil {
|
||||
return nil, 0, fmt.Errorf("assistant not found: %w", err)
|
||||
}
|
||||
}
|
||||
scenarios, count, err := s.scenarioRepo.ListEnabledByAccountAssistant(ctx, accountID, assistantID)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("List captain scenarios: %v", err)
|
||||
return nil, 0, fmt.Errorf("list scenarios: %w", err)
|
||||
}
|
||||
return scenarios, count, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user