feat(integrations): align shopify parity
This commit is contained in:
@@ -233,6 +233,9 @@ var criticalRoutes = []route{
|
||||
{Method: "GET", Path: "/api/v1/accounts/:account_id/integrations/slack/list_all_channels", Controller: "api/v1/accounts/integrations/slack#list_all_channels", Source: "routes.rb:352"},
|
||||
{Method: "POST", Path: "/api/v1/accounts/:account_id/integrations/dyte/create_a_meeting", Controller: "api/v1/accounts/integrations/dyte#create_a_meeting", Source: "routes.rb:357"},
|
||||
{Method: "POST", Path: "/api/v1/accounts/:account_id/integrations/dyte/add_participant_to_meeting", Controller: "api/v1/accounts/integrations/dyte#add_participant_to_meeting", Source: "routes.rb:358"},
|
||||
{Method: "DELETE", Path: "/api/v1/accounts/:account_id/integrations/shopify", Controller: "api/v1/accounts/integrations/shopify#destroy", Source: "routes.rb:361"},
|
||||
{Method: "POST", Path: "/api/v1/accounts/:account_id/integrations/shopify/auth", Controller: "api/v1/accounts/integrations/shopify#auth", Source: "routes.rb:363"},
|
||||
{Method: "GET", Path: "/api/v1/accounts/:account_id/integrations/shopify/orders", Controller: "api/v1/accounts/integrations/shopify#orders", Source: "routes.rb:364"},
|
||||
{Method: "DELETE", Path: "/api/v1/accounts/:account_id/integrations/linear", Controller: "api/v1/accounts/integrations/linear#destroy", Source: "routes.rb:366"},
|
||||
{Method: "GET", Path: "/api/v1/accounts/:account_id/integrations/linear/teams", Controller: "api/v1/accounts/integrations/linear#teams", Source: "routes.rb:367"},
|
||||
{Method: "GET", Path: "/api/v1/accounts/:account_id/integrations/linear/team_entities", Controller: "api/v1/accounts/integrations/linear#team_entities", Source: "routes.rb:368"},
|
||||
|
||||
@@ -49,16 +49,16 @@ Hermes task landing checklist:
|
||||
|
||||
## Current Baseline
|
||||
|
||||
- Current tracking checkpoint: 2026-06-06 Linear integration parity checkpoint, prepared as `feat(integrations): align linear parity`.
|
||||
- Latest implementation checkpoint: this checkpoint, prepared as `feat(integrations): align linear parity`.
|
||||
- Current tracking checkpoint: 2026-06-06 Shopify integration parity checkpoint, prepared as `feat(integrations): align shopify parity`.
|
||||
- Latest implementation checkpoint: this checkpoint, prepared as `feat(integrations): align shopify parity`.
|
||||
- Latest documentation/tooling checkpoint: this tracker update for P3.24 plus the landed parity tracker history; this document is the active follow-up plan and supersedes `.hermes/plans/*`.
|
||||
- Plan landing status: complete for the current known Hermes plans and user-confirmed scope. Future work should update this file directly instead of opening a parallel tracker.
|
||||
- Worktree status at this implementation checkpoint: Linear integration account routes from `reference/chatwoot/config/routes.rb:365-373`, `Api::V1::Accounts::Integrations::LinearController`, `Integrations::Linear::ProcessorService`, `Linear`, `Linear::Queries`, `Linear::Mutations`, `Linear::ActivityMessageService`, request specs, and the reused dashboard `linear.js` API are implemented. GoChat now exposes no-trailing and trailing Linear destroy plus teams/team-entities/create/link/unlink/search/linked-issues routes, proxies Linear GraphQL through fakeable provider clients, returns raw Chatwoot payloads instead of local envelopes, maps provider failures to `422 { error }`, resolves conversations by account-scoped `display_id`, builds Chatwoot frontend conversation links, creates Linear activity messages, revokes tokens on delete, and returns empty `200 OK` deletes. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack.
|
||||
- Worktree status at this implementation checkpoint: Shopify integration account routes from `reference/chatwoot/config/routes.rb:361-364`, `Api::V1::Accounts::Integrations::ShopifyController`, `Shopify::IntegrationHelper`, Shopify callback behavior, request specs, and reused dashboard `integrations.js`/`shopify.js` API are implemented. GoChat now exposes no-trailing and trailing Shopify destroy, returns raw `{ redirect_url }` auth payloads with Chatwoot's missing-domain `422 { error }`, returns raw `{ orders: [...] }`, resolves account-scoped contacts, rejects contacts without email/phone with `422 { error: "Contact information missing" }`, queries Shopify customers by email/phone then orders by customer ID through fakeable REST clients, adds Chatwoot `admin_url`, finds hooks by `app_id: shopify`, and returns empty `200 OK` deletes. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack.
|
||||
- Next executable implementation checkpoint: continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke from fresh reference/smoke evidence.
|
||||
- `go test ./...` passes when run outside the restricted socket sandbox; focused Linear handler/service tests pass in the sandbox.
|
||||
- Route dump succeeds with `939` registered routes after Linear no-trailing destroy tracking.
|
||||
- `go test ./...` passes when run outside the restricted socket sandbox; focused Shopify handler/service tests pass in the sandbox.
|
||||
- Route dump succeeds with `940` registered routes after Shopify no-trailing destroy tracking.
|
||||
- Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`.
|
||||
- Tracked frontend-critical route audit covers 400 Chatwoot routes: 387 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher.
|
||||
- Tracked frontend-critical route audit covers 403 Chatwoot routes: 390 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher.
|
||||
- `/api/v1/widget` stubs are burned down and public inbox/contact/conversation/message core flows are backed by real handlers.
|
||||
- Handler test stability fixes are committed into the baseline before feature parity work continues.
|
||||
- `.codegraph/` is generated indexing output and is not part of tracked product code.
|
||||
@@ -140,11 +140,12 @@ This table is the shortest authoritative handoff view. If an older lower section
|
||||
|
||||
| Priority | Workstream | Current state | Next checkpoint | Commit close rule |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 0 | P3.26 Shopify integration parity | Implemented for reused dashboard Shopify integration and customer-order panel: no-trailing and trailing destroy routes are registered, auth returns raw `{ redirect_url }`, missing shop domains return Chatwoot's `422 { error: "Shop domain is required" }`, orders returns raw `{ orders: [...] }`, account-scoped contacts are required, contacts without email/phone return `422 { error: "Contact information missing" }`, Shopify customers/search and orders REST calls are made through fakeable clients, order payloads include `admin_url`, callback-created hooks are found by `app_id: shopify`, and delete returns empty `200 OK`. | Keep in Review; reopen only if live Shopify OAuth/order smoke exposes token/session setup drift, REST API version drift, Shopify error-body wording, or frontend order payload drift beyond the inspected controller/helper/spec/frontend contract. | Focused Shopify handler/service tests, route dump/parity regeneration (`940` routes; `390 exact`, `13 parameter-compatible`, `0 missing out of 403`), sandbox package tests, escalated full `go test ./...`, and `git diff --check` passed. |
|
||||
| 0 | P3.25 Linear integration parity | Implemented for reused dashboard Linear issue flow: no-trailing and trailing destroy routes are registered, teams/team_entities/search/linked/create/link/unlink return raw Chatwoot payloads, provider errors return `422 { error }`, blank search returns Chatwoot's exact search-string error, requests proxy Linear GraphQL via fakeable clients, delete revokes Linear tokens and returns empty `200 OK`, create/link/unlink resolve conversations by account display ID, conversation links use the reused frontend URL, and successful mutations create Chatwoot-style Linear activity messages. | Keep in Review; reopen only if live Linear OAuth/GraphQL smoke exposes token refresh behavior, GraphQL query/mutation field drift, activity job queue semantics, or frontend payload drift beyond the inspected controller/processor/client/spec contract. | Focused Linear handler/service tests, route dump/parity regeneration (`939` routes; `387 exact`, `13 parameter-compatible`, `0 missing out of 400`), sandbox package tests, escalated full `go test ./...`, and `git diff --check` passed. |
|
||||
| 0 | P3.24 Slack integration parity | Implemented for reused dashboard Slack settings flow: no-trailing and trailing singleton routes are registered for create/update/delete, `PUT` and `PATCH` update both work, create accepts frontend `code` and exchanges it for a Slack access token, hooks are persisted with `app_id: slack` and disabled status, update accepts frontend `reference_id`, fetches real private/public Slack channels with pagination, joins public channels, persists `reference_id/settings.channel_name/status`, create/update return raw Chatwoot app payloads with hooks, list-all returns raw channel arrays, invalid channels return Chatwoot's `422 { error }`, and delete returns empty `200 OK`. | Keep in Review; reopen only if live Slack OAuth/channel smoke exposes OAuth redirect, provider error, app serializer, or Slack channel pagination drift beyond the inspected controller/builder/spec/frontend contract. | Focused Slack handler/service tests, route dump/parity regeneration, sandbox focused `go test`, escalated full `go test ./...`, and `git diff --check` passed. |
|
||||
| 0 | P3.23 nested contact inbox creation API | Implemented for Chatwoot nested contact inbox creation: raw JSON/form/query params are accepted, contact and inbox are account-scoped, missing source IDs are generated through Chatwoot channel rules, duplicate contact+inbox+source rows are returned idempotently, `hmac_verified` is persisted on creation, and the response is raw `{ source_id, inbox }` rather than the local model/envelope. | Keep in Review; reopen only if live CRM/new-conversation smoke exposes inbox access-policy, unsupported channel, or serializer drift beyond the inspected controller/builder/Jbuilder contract. | Focused nested ContactInbox handler/service/repository tests, route parity check, full `go test ./...`, and `git diff --check` passed. |
|
||||
| 1 | P3.2a invitation/confirmation mail parity | Implemented for current non-SSO reference behavior: profile resend is no longer a TODO-only log, new invited agents and unconfirmed invited profile resends generate reset-password invitation links, normal unconfirmed profile resends generate confirmation links, `users.unconfirmed_email` is modeled for email-update routing, and fakeable/environment SMTP mailers keep default tests offline. | Keep in Review; reopen only if reused frontend smoke or fresh reference evidence exposes additional Devise confirmation states outside excluded SSO/SAML/LDAP/OIDC variants. | Focused profile and agent invitation tests, combined handler/service/repository/router/migrate/app tests, full `go test ./...`, and `git diff --check` passed. |
|
||||
| 2 | Phase 2/3 drift | Tracked route parity is 0 missing for the current 400-route critical set; dashboard `/app` shell routes from `routes.rb:19-20`, `.well-known` app association and custom-domain challenge routes from `routes.rb:657-660`, Twilio callback routes from `routes.rb:639-640`, enterprise Twilio voice routes from `routes.rb:643-646`, root Linear/Shopify/Notion OAuth callback routes from `routes.rb:630/634/654`, root Twitter/Google/Microsoft/Instagram/TikTok callback routes from `routes.rb:626/649-652`, assignment policy routes from `routes.rb:306-313`, help-center portal/category/article routes from `routes.rb:385-404`, public help-center portal/sitemap/article/category/search/article-detail routes from `routes.rb:590-601`, enterprise contact outbound voice call from `routes.rb:216`, account agent-bot routes from `routes.rb:94-97`, account webhook routes from `routes.rb:342`, account integration app/hook routes from `routes.rb:345-348`, account Slack routes from `routes.rb:350-352`, account Dyte routes from `routes.rb:357-358`, account Linear routes from `routes.rb:365-373`, dashboard app routes from `routes.rb:130`, canned response routes from `routes.rb:114`, notification subscription routes from `routes.rb:440`, team/team-member routes from `routes.rb:296-300`, conversation participant routes from `routes.rb:150`, conversation direct upload route from `routes.rb:151`, conversation draft message routes from `routes.rb:152`, conversation inbox assistant route from `routes.rb:165`, conversation reporting events route from `routes.rb:166`, and account reporting events route from `routes.rb:234` are now explicitly tracked. Notification list/action serializers, user notification-settings raw payloads, campaigns raw payload/display-id routes, Devise password reset/confirmation payloads, CRM shared attachment payloads plus fixed 100-row attachment pagination, account/settings payloads, assignable-agent payloads, agent index full-list behavior, agent create/update/delete defaults/errors/scope, account agent-bot route/payload/mutation behavior, account webhook payload/mutation behavior, integration app/hook payload behavior, account Slack OAuth/channel payload behavior, account Dyte create/join payload behavior, account Linear GraphQL issue payload behavior, dashboard app raw payload/serializer behavior, canned response raw payload/search/delete behavior, notification subscription payload behavior, team update/frontend route behavior, conversation participant route/payload/final-set update behavior, conversation direct upload ActiveStorage behavior, conversation draft message Redis-key-equivalent behavior, conversation inbox assistant Copilot payload behavior, conversation reporting-event raw array behavior, account reporting-events payload/filter/pagination behavior, label CRUD payloads, custom filters, custom attribute definitions, contact outbound voice calls, assignment policy CRUD and inbox binding payloads, Twilio inbound/status callbacks, enterprise Twilio voice callbacks, Linear/Shopify/Notion root integration callbacks, Shopify OAuth auth redirects, root channel OAuth callbacks, help-center portal/category/article payloads, dashboard app shell route behavior, app association JSON payloads, Cloudflare custom hostname verification, public widget popular-article lists, public help-center category list/show payloads, public portal show/default-locale payloads, public portal search payloads, public article show/markdown/tracking routes, and public sitemap XML now match the inspected Chatwoot contract. | Continue the next evidence-backed route/controller/serializer drift after Linear parity or from B12 findings. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. |
|
||||
| 2 | Phase 2/3 drift | Tracked route parity is 0 missing for the current 403-route critical set; dashboard `/app` shell routes from `routes.rb:19-20`, `.well-known` app association and custom-domain challenge routes from `routes.rb:657-660`, Twilio callback routes from `routes.rb:639-640`, enterprise Twilio voice routes from `routes.rb:643-646`, root Linear/Shopify/Notion OAuth callback routes from `routes.rb:630/634/654`, root Twitter/Google/Microsoft/Instagram/TikTok callback routes from `routes.rb:626/649-652`, assignment policy routes from `routes.rb:306-313`, help-center portal/category/article routes from `routes.rb:385-404`, public help-center portal/sitemap/article/category/search/article-detail routes from `routes.rb:590-601`, enterprise contact outbound voice call from `routes.rb:216`, account agent-bot routes from `routes.rb:94-97`, account webhook routes from `routes.rb:342`, account integration app/hook routes from `routes.rb:345-348`, account Slack routes from `routes.rb:350-352`, account Dyte routes from `routes.rb:357-358`, account Shopify routes from `routes.rb:361-364`, account Linear routes from `routes.rb:365-373`, dashboard app routes from `routes.rb:130`, canned response routes from `routes.rb:114`, notification subscription routes from `routes.rb:440`, team/team-member routes from `routes.rb:296-300`, conversation participant routes from `routes.rb:150`, conversation direct upload route from `routes.rb:151`, conversation draft message routes from `routes.rb:152`, conversation inbox assistant route from `routes.rb:165`, conversation reporting events route from `routes.rb:166`, and account reporting events route from `routes.rb:234` are now explicitly tracked. Notification list/action serializers, user notification-settings raw payloads, campaigns raw payload/display-id routes, Devise password reset/confirmation payloads, CRM shared attachment payloads plus fixed 100-row attachment pagination, account/settings payloads, assignable-agent payloads, agent index full-list behavior, agent create/update/delete defaults/errors/scope, account agent-bot route/payload/mutation behavior, account webhook payload/mutation behavior, integration app/hook payload behavior, account Slack OAuth/channel payload behavior, account Dyte create/join payload behavior, account Shopify customer-order payload behavior, account Linear GraphQL issue payload behavior, dashboard app raw payload/serializer behavior, canned response raw payload/search/delete behavior, notification subscription payload behavior, team update/frontend route behavior, conversation participant route/payload/final-set update behavior, conversation direct upload ActiveStorage behavior, conversation draft message Redis-key-equivalent behavior, conversation inbox assistant Copilot payload behavior, conversation reporting-event raw array behavior, account reporting-events payload/filter/pagination behavior, label CRUD payloads, custom filters, custom attribute definitions, contact outbound voice calls, assignment policy CRUD and inbox binding payloads, Twilio inbound/status callbacks, enterprise Twilio voice callbacks, Linear/Shopify/Notion root integration callbacks, Shopify OAuth auth redirects, root channel OAuth callbacks, help-center portal/category/article payloads, dashboard app shell route behavior, app association JSON payloads, Cloudflare custom hostname verification, public widget popular-article lists, public help-center category list/show payloads, public portal show/default-locale payloads, public portal search payloads, public article show/markdown/tracking routes, and public sitemap XML now match the inspected Chatwoot contract. | Continue the next evidence-backed route/controller/serializer drift after Shopify parity or from B12 findings. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. |
|
||||
| 3 | Phase 6 placeholder audit | Widget/public/webhook critical placeholders are burned down; inbox WhatsApp health/register-webhook and sync-template drift are closed; refreshed `docs/parity/placeholder_audit.md` shows only webhook nil-handler fallbacks still call `chatwootParityStub`; dashboard conversation transcript/custom-attribute response drift and message retry status drift are closed. | Keep in Review; reopen only if fresh `rg`, route smoke, or B12 finds a frontend-reachable placeholder/stub in account/contact/conversation/message/inbox/widget/public paths. | `rg` placeholder audit and `scripts/parity_frontend_smoke.sh --check` are recorded; no reused-frontend blocker is ownerless. |
|
||||
| 4 | P3.9 account agent-bot API | Implemented for the reused dashboard AgentBots settings route with no-trailing-slash routes, PATCH update, raw Jbuilder-style payloads, account mutation scope, system-bot show/list visibility, empty `200 OK` delete, and full reset/avatar action payloads. | Keep in Review; reopen only if live settings smoke exposes avatar upload storage or administrator-secret gating drift. | Focused AgentBot handler tests, service/router focused tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. |
|
||||
| 5 | P3.10 account webhooks API | Implemented for the reused dashboard Webhooks settings route with PATCH update, Chatwoot `{ payload }` list/mutation serializers, nested `{ webhook: ... }` bodies, generated secret, account-scoped mutations, URL/subscription validation, optional inbox serialization, and empty `200 OK` delete. | Keep in Review; reopen only if live settings smoke exposes audit writer or delivery-signature drift beyond the existing delivery service boundary. | Focused webhook handler/service/router tests, migration test, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. |
|
||||
@@ -2441,3 +2442,4 @@ Verification milestone gates:
|
||||
- 2026-06-06: P3.23 nested contact inbox creation checkpoint prepared as `feat(contacts): align contact inbox creation`; audited Chatwoot nested contact inbox controller/specs, `ContactInboxBuilder`, `HmacConcern`, route `212`, and contact inbox Jbuilder serializer. GoChat now account-scopes nested contact/inbox creation, accepts raw JSON/form/query `inbox_id`, `source_id`, and `hmac_verified`, generates missing source IDs for API/WebWidget/Email/Sms/Whatsapp/Twilio channels, returns existing contact+inbox+source rows idempotently, persists HMAC verification on creation, and returns raw `{ source_id, inbox }`. Focused handler/service/repository tests passed; route parity and full `go test ./...` plus `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke.
|
||||
- 2026-06-06: P3.24 Slack integration checkpoint prepared as `feat(integrations): align slack parity`; audited Chatwoot Slack singleton routes/controller/request specs, `Integrations::Slack::HookBuilder`, `Integrations::Slack::ChannelBuilder`, app/hook Jbuilder partials, and reused dashboard integrations API/store. GoChat now exposes no-trailing and trailing Slack singleton routes, supports `PUT` and `PATCH` update, creates disabled Slack hooks from OAuth `code`, returns raw app payloads, fetches Slack private/public channels with cursor pagination, joins public channels, persists selected channel `reference_id/settings/status`, returns raw channel arrays, maps invalid channels to Chatwoot's `422 { error }`, and deletes with empty `200 OK`. Focused handler/service tests, route dump/parity regeneration (`939` routes; `379 exact`, `13 parameter-compatible`, `0 missing out of 392`), escalated full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke.
|
||||
- 2026-06-06: P3.25 Linear integration checkpoint prepared as `feat(integrations): align linear parity`; audited Chatwoot Linear controller/request specs, processor service, GraphQL client queries/mutations, activity-message service, account routes `365-373`, and reused dashboard Linear API. GoChat now exposes no-trailing and trailing Linear destroy plus teams/team_entities/create/link/unlink/search/linked routes, calls Linear GraphQL through fakeable clients, returns raw Chatwoot data payloads, maps provider failures to `422 { error }`, resolves conversations by account display ID, builds frontend conversation links, creates Linear activity messages for create/link/unlink, revokes tokens on delete, and returns empty `200 OK`. Focused Linear handler/service tests, route dump/parity regeneration (`939` routes; `387 exact`, `13 parameter-compatible`, `0 missing out of 400`), sandbox package tests, escalated full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke.
|
||||
- 2026-06-06: P3.26 Shopify integration checkpoint prepared as `feat(integrations): align shopify parity`; audited Chatwoot Shopify account controller/specs, integration helper, callback behavior, routes `361-364`, and reused dashboard integrations/Shopify APIs. GoChat now exposes no-trailing and trailing Shopify destroy, returns raw auth/order payloads, uses Chatwoot `422 { error }` bodies for missing shop domains and missing contact info, resolves account-scoped contacts, calls Shopify customer search and orders REST endpoints through fakeable clients, appends order `admin_url`, finds callback-created hooks by `app_id: shopify`, and deletes with empty `200 OK`. Focused Shopify handler/service tests, route dump/parity regeneration (`940` routes; `390 exact`, `13 parameter-compatible`, `0 missing out of 403`), sandbox package tests, escalated full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke.
|
||||
|
||||
@@ -74,6 +74,7 @@ DELETE /api/v1/accounts/:account_id/integrations/hooks/:id
|
||||
DELETE /api/v1/accounts/:account_id/integrations/linear
|
||||
DELETE /api/v1/accounts/:account_id/integrations/linear/
|
||||
DELETE /api/v1/accounts/:account_id/integrations/notion/
|
||||
DELETE /api/v1/accounts/:account_id/integrations/shopify
|
||||
DELETE /api/v1/accounts/:account_id/integrations/shopify/
|
||||
DELETE /api/v1/accounts/:account_id/integrations/slack
|
||||
DELETE /api/v1/accounts/:account_id/integrations/slack/
|
||||
@@ -937,4 +938,4 @@ PUT /public/api/v1/csat_survey/:id
|
||||
PUT /public/api/v1/inboxes/:inbox_id/contacts/:contact_id
|
||||
PUT /public/api/v1/inboxes/:inbox_id/contacts/:contact_id/conversations/:conversation_id/messages/:message_id
|
||||
PUT /widget/direct_uploads/:upload_uuid
|
||||
TOTAL: 939
|
||||
TOTAL: 940
|
||||
|
||||
@@ -7,7 +7,7 @@ Generated from:
|
||||
|
||||
This report covers tracked frontend-critical Chatwoot routes from `reference/chatwoot/config/routes.rb`, including API v1 account routes, Captain/Copilot, assignment policies, widget/public APIs, and API v2 reports. Ruby is not installed in the workspace, so Chatwoot routes are sourced from static route declarations instead of `bin/rails routes`.
|
||||
|
||||
Summary: 387 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 400 tracked critical routes.
|
||||
Summary: 390 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 403 tracked critical routes.
|
||||
|
||||
## Missing Critical Routes
|
||||
|
||||
@@ -78,6 +78,7 @@ These routes exist with equivalent method and path shape but different parameter
|
||||
| DELETE | `/api/v1/accounts/:account_id/inboxes/:inbox_id/avatar` | `/api/v1/accounts/:account_id/inboxes/:inbox_id/avatar` | `api/v1/accounts/inboxes#avatar` | `routes.rb:257` | exact |
|
||||
| DELETE | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `/api/v1/accounts/:account_id/integrations/hooks/:id` | `api/v1/accounts/integrations/hooks#destroy` | `routes.rb:346` | exact |
|
||||
| DELETE | `/api/v1/accounts/:account_id/integrations/linear` | `/api/v1/accounts/:account_id/integrations/linear` | `api/v1/accounts/integrations/linear#destroy` | `routes.rb:366` | exact |
|
||||
| DELETE | `/api/v1/accounts/:account_id/integrations/shopify` | `/api/v1/accounts/:account_id/integrations/shopify` | `api/v1/accounts/integrations/shopify#destroy` | `routes.rb:361` | exact |
|
||||
| DELETE | `/api/v1/accounts/:account_id/integrations/slack` | `/api/v1/accounts/:account_id/integrations/slack` | `api/v1/accounts/integrations/slack#destroy` | `routes.rb:350` | exact |
|
||||
| DELETE | `/api/v1/accounts/:account_id/labels/:tag_id` | `/api/v1/accounts/:account_id/labels/:tag_id` | `api/v1/accounts/labels#destroy` | `routes.rb:281` | exact |
|
||||
| DELETE | `/api/v1/accounts/:account_id/macros/:macro_id` | `/api/v1/accounts/:account_id/macros/:macro_id` | `api/v1/accounts/macros#destroy` | `routes.rb:118` | exact |
|
||||
@@ -179,6 +180,7 @@ These routes exist with equivalent method and path shape but different parameter
|
||||
| GET | `/api/v1/accounts/:account_id/integrations/linear/search_issue` | `/api/v1/accounts/:account_id/integrations/linear/search_issue` | `api/v1/accounts/integrations/linear#search_issue` | `routes.rb:372` | exact |
|
||||
| GET | `/api/v1/accounts/:account_id/integrations/linear/team_entities` | `/api/v1/accounts/:account_id/integrations/linear/team_entities` | `api/v1/accounts/integrations/linear#team_entities` | `routes.rb:368` | exact |
|
||||
| GET | `/api/v1/accounts/:account_id/integrations/linear/teams` | `/api/v1/accounts/:account_id/integrations/linear/teams` | `api/v1/accounts/integrations/linear#teams` | `routes.rb:367` | exact |
|
||||
| GET | `/api/v1/accounts/:account_id/integrations/shopify/orders` | `/api/v1/accounts/:account_id/integrations/shopify/orders` | `api/v1/accounts/integrations/shopify#orders` | `routes.rb:364` | exact |
|
||||
| GET | `/api/v1/accounts/:account_id/integrations/slack/list_all_channels` | `/api/v1/accounts/:account_id/integrations/slack/list_all_channels` | `api/v1/accounts/integrations/slack#list_all_channels` | `routes.rb:352` | exact |
|
||||
| GET | `/api/v1/accounts/:account_id/labels/` | `/api/v1/accounts/:account_id/labels/` | `api/v1/accounts/labels#index` | `routes.rb:281` | exact |
|
||||
| GET | `/api/v1/accounts/:account_id/labels/:tag_id` | `/api/v1/accounts/:account_id/labels/:tag_id` | `api/v1/accounts/labels#show` | `routes.rb:281` | exact |
|
||||
@@ -349,6 +351,7 @@ These routes exist with equivalent method and path shape but different parameter
|
||||
| POST | `/api/v1/accounts/:account_id/integrations/linear/create_issue` | `/api/v1/accounts/:account_id/integrations/linear/create_issue` | `api/v1/accounts/integrations/linear#create_issue` | `routes.rb:369` | exact |
|
||||
| POST | `/api/v1/accounts/:account_id/integrations/linear/link_issue` | `/api/v1/accounts/:account_id/integrations/linear/link_issue` | `api/v1/accounts/integrations/linear#link_issue` | `routes.rb:370` | exact |
|
||||
| POST | `/api/v1/accounts/:account_id/integrations/linear/unlink_issue` | `/api/v1/accounts/:account_id/integrations/linear/unlink_issue` | `api/v1/accounts/integrations/linear#unlink_issue` | `routes.rb:371` | exact |
|
||||
| POST | `/api/v1/accounts/:account_id/integrations/shopify/auth` | `/api/v1/accounts/:account_id/integrations/shopify/auth` | `api/v1/accounts/integrations/shopify#auth` | `routes.rb:363` | exact |
|
||||
| POST | `/api/v1/accounts/:account_id/integrations/slack` | `/api/v1/accounts/:account_id/integrations/slack` | `api/v1/accounts/integrations/slack#create` | `routes.rb:350` | exact |
|
||||
| POST | `/api/v1/accounts/:account_id/labels/` | `/api/v1/accounts/:account_id/labels/` | `api/v1/accounts/labels#create` | `routes.rb:281` | exact |
|
||||
| POST | `/api/v1/accounts/:account_id/macros/` | `/api/v1/accounts/:account_id/macros/` | `api/v1/accounts/macros#create` | `routes.rb:118` | exact |
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -30,10 +32,10 @@ func (h *ShopifyIntegrationHandler) Delete(c *gin.Context) {
|
||||
}
|
||||
|
||||
if svcErr := h.svc.Delete(c.Request.Context(), accountID); svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
handleShopifyServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"message": "Shopify integration deleted"})
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// Auth returns the Shopify OAuth authorize URL.
|
||||
@@ -46,17 +48,21 @@ func (h *ShopifyIntegrationHandler) Auth(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req service.CreateShopifyAuthRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.ShopDomain) == "" {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Shop domain is required"})
|
||||
return
|
||||
}
|
||||
|
||||
redirect, svcErr := h.svc.BuildAuthRedirect(c.Request.Context(), accountID, req)
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
handleShopifyServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
response.OK(c, redirect)
|
||||
c.JSON(http.StatusOK, redirect)
|
||||
}
|
||||
|
||||
// GetOrders retrieves Shopify orders for an account.
|
||||
@@ -68,16 +74,22 @@ func (h *ShopifyIntegrationHandler) GetOrders(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
orders, svcErr := h.svc.GetOrders(c.Request.Context(), accountID)
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
contactID, err := parseOptionalUintQueryParam(c, "contact_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid contact_id")
|
||||
return
|
||||
}
|
||||
response.OK(c, orders)
|
||||
orders, svcErr := h.svc.GetOrders(c.Request.Context(), accountID, contactID)
|
||||
if svcErr != nil {
|
||||
handleShopifyServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"orders": orders})
|
||||
}
|
||||
|
||||
// RegisterShopifyIntegrationRoutes registers Shopify integration routes.
|
||||
func RegisterShopifyIntegrationRoutes(g *gin.RouterGroup, h *ShopifyIntegrationHandler) {
|
||||
g.DELETE("/shopify", h.Delete)
|
||||
shopify := g.Group("/shopify")
|
||||
{
|
||||
shopify.DELETE("/", h.Delete)
|
||||
@@ -85,3 +97,12 @@ func RegisterShopifyIntegrationRoutes(g *gin.RouterGroup, h *ShopifyIntegrationH
|
||||
shopify.GET("/orders", h.GetOrders)
|
||||
}
|
||||
}
|
||||
|
||||
func handleShopifyServiceError(c *gin.Context, err error) {
|
||||
var providerErr *service.ShopifyProviderError
|
||||
if errors.As(err, &providerErr) {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": providerErr.Message})
|
||||
return
|
||||
}
|
||||
handleServiceError(c, err)
|
||||
}
|
||||
|
||||
@@ -74,6 +74,21 @@ func TestShopifyIntegration_Auth_InvalidJSON(t *testing.T) {
|
||||
assert.False(t, resp["success"].(bool))
|
||||
}
|
||||
|
||||
func TestShopifyIntegration_Auth_MissingShopDomain(t *testing.T) {
|
||||
r := setupShopifyIntegrationRouter()
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/shopify/auth", bytes.NewReader([]byte(`{}`)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, w.Code)
|
||||
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
assert.Equal(t, "Shop domain is required", resp["error"])
|
||||
}
|
||||
|
||||
func TestShopifyIntegration_GetOrders_BadAccountID(t *testing.T) {
|
||||
r := setupShopifyIntegrationRouter()
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -15,22 +17,34 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type ShopifyProviderError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *ShopifyProviderError) Error() string { return e.Message }
|
||||
|
||||
// ShopifyIntegrationService implements Shopify integration business logic.
|
||||
// Reference: Chatwoot Integrations::ShopifyController
|
||||
// Shopify integration links customer order information to conversations.
|
||||
type ShopifyIntegrationService struct {
|
||||
hookRepo *repository.IntegrationHookRepo
|
||||
hookRepo *repository.IntegrationHookRepo
|
||||
contactRepo *repository.ContactRepo
|
||||
client *shopifyAPIClient
|
||||
}
|
||||
|
||||
// NewShopifyIntegrationService creates a new ShopifyIntegrationService.
|
||||
func NewShopifyIntegrationService(hookRepo *repository.IntegrationHookRepo) *ShopifyIntegrationService {
|
||||
return &ShopifyIntegrationService{hookRepo: hookRepo}
|
||||
svc := &ShopifyIntegrationService{hookRepo: hookRepo, client: newShopifyAPIClientFromEnv()}
|
||||
if hookRepo != nil && hookRepo.DB() != nil {
|
||||
svc.contactRepo = repository.NewContactRepo(hookRepo.DB())
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
// CreateShopifyAuthRequest is the DTO for Shopify OAuth auth.
|
||||
type CreateShopifyAuthRequest struct {
|
||||
ShopDomain string `json:"shop_domain" validate:"required"`
|
||||
AccessToken string `json:"access_token,omitempty"`
|
||||
ShopDomain string `json:"shop_domain" form:"shop_domain"`
|
||||
AccessToken string `json:"access_token,omitempty" form:"access_token"`
|
||||
}
|
||||
|
||||
type ShopifyAuthResponse struct {
|
||||
@@ -39,7 +53,7 @@ type ShopifyAuthResponse struct {
|
||||
|
||||
// Delete removes a Shopify integration hook for an account.
|
||||
func (s *ShopifyIntegrationService) Delete(ctx context.Context, accountID uint) error {
|
||||
hooks, err := s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeShopify)
|
||||
hooks, err := s.findShopifyHooks(ctx, accountID)
|
||||
if err != nil || len(hooks) == 0 {
|
||||
return fmt.Errorf("Shopify integration not found for account %d", accountID)
|
||||
}
|
||||
@@ -76,6 +90,9 @@ func (s *ShopifyIntegrationService) Auth(ctx context.Context, accountID uint, re
|
||||
if len(hooks) > 0 {
|
||||
// Update existing hook
|
||||
hook := &hooks[0]
|
||||
hook.AppID = "shopify"
|
||||
hook.ReferenceID = req.ShopDomain
|
||||
hook.AccessToken = req.AccessToken
|
||||
hook.Settings = settingsJSON
|
||||
hook.URL = fmt.Sprintf("https://%s/admin/api/webhooks.json", req.ShopDomain)
|
||||
if err := s.hookRepo.Update(ctx, hook); err != nil {
|
||||
@@ -87,11 +104,14 @@ func (s *ShopifyIntegrationService) Auth(ctx context.Context, accountID uint, re
|
||||
|
||||
// Create new hook
|
||||
hook := &model.IntegrationHook{
|
||||
AccountID: accountID,
|
||||
HookType: model.HookTypeShopify,
|
||||
Status: model.HookStatusActive,
|
||||
URL: fmt.Sprintf("https://%s/admin/api/webhooks.json", req.ShopDomain),
|
||||
Settings: settingsJSON,
|
||||
AccountID: accountID,
|
||||
AppID: "shopify",
|
||||
HookType: model.HookTypeShopify,
|
||||
Status: model.HookStatusActive,
|
||||
URL: fmt.Sprintf("https://%s/admin/api/webhooks.json", req.ShopDomain),
|
||||
AccessToken: req.AccessToken,
|
||||
ReferenceID: req.ShopDomain,
|
||||
Settings: settingsJSON,
|
||||
}
|
||||
|
||||
if err := s.hookRepo.Create(ctx, hook); err != nil {
|
||||
@@ -138,20 +158,146 @@ func (s *ShopifyIntegrationService) BuildAuthRedirect(_ context.Context, account
|
||||
|
||||
// GetOrders retrieves Shopify orders for an account (proxy to Shopify API).
|
||||
// GET /api/v1/accounts/:account_id/integrations/shopify/orders
|
||||
func (s *ShopifyIntegrationService) GetOrders(ctx context.Context, accountID uint) ([]map[string]interface{}, error) {
|
||||
hooks, err := s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeShopify)
|
||||
func (s *ShopifyIntegrationService) GetOrders(ctx context.Context, accountID, contactID uint) ([]map[string]interface{}, error) {
|
||||
hooks, err := s.findShopifyHooks(ctx, accountID)
|
||||
if err != nil || len(hooks) == 0 {
|
||||
return nil, fmt.Errorf("Shopify integration not found for account %d", accountID)
|
||||
}
|
||||
|
||||
var settings model.ShopifySettings
|
||||
if err := json.Unmarshal(hooks[0].Settings, &settings); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal Shopify settings: %w", err)
|
||||
if s.contactRepo == nil {
|
||||
return nil, fmt.Errorf("contact repository not configured")
|
||||
}
|
||||
contact, err := s.contactRepo.FindByAccountAndID(ctx, accountID, contactID)
|
||||
if err != nil || (strings.TrimSpace(contact.Email) == "" && strings.TrimSpace(contact.PhoneNumber) == "") {
|
||||
return nil, &ShopifyProviderError{Message: "Contact information missing"}
|
||||
}
|
||||
|
||||
// In production, this would call the Shopify API using settings.AccessToken.
|
||||
applogger.L().Infof("Listing Shopify orders for account=%d, shop=%s", accountID, settings.ShopDomain)
|
||||
return []map[string]interface{}{
|
||||
{"shop_domain": settings.ShopDomain, "status": "configured"},
|
||||
}, nil
|
||||
hook := hooks[0]
|
||||
shopDomain := strings.TrimSpace(hook.ReferenceID)
|
||||
if shopDomain == "" {
|
||||
var settings model.ShopifySettings
|
||||
if err := json.Unmarshal(hook.Settings, &settings); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal Shopify settings: %w", err)
|
||||
}
|
||||
shopDomain = settings.ShopDomain
|
||||
if hook.AccessToken == "" {
|
||||
hook.AccessToken = settings.AccessToken
|
||||
}
|
||||
}
|
||||
|
||||
customers, err := s.client.SearchCustomers(ctx, shopDomain, hook.AccessToken, contact.Email, contact.PhoneNumber)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(customers) == 0 {
|
||||
return []map[string]interface{}{}, nil
|
||||
}
|
||||
orders, err := s.client.GetOrders(ctx, shopDomain, hook.AccessToken, fmt.Sprint(customers[0]["id"]))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, order := range orders {
|
||||
order["admin_url"] = fmt.Sprintf("https://%s/admin/orders/%v", shopDomain, order["id"])
|
||||
}
|
||||
applogger.L().Infof("Listing Shopify orders for account=%d, shop=%s", accountID, shopDomain)
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (s *ShopifyIntegrationService) findShopifyHooks(ctx context.Context, accountID uint) ([]model.IntegrationHook, error) {
|
||||
hooks, err := s.hookRepo.FindByAccountAndApp(ctx, accountID, "shopify")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(hooks) > 0 {
|
||||
return hooks, nil
|
||||
}
|
||||
return s.hookRepo.FindByAccountAndType(ctx, accountID, model.HookTypeShopify)
|
||||
}
|
||||
|
||||
type shopifyAPIClient struct {
|
||||
apiVersion string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func newShopifyAPIClientFromEnv() *shopifyAPIClient {
|
||||
apiVersion := strings.TrimSpace(os.Getenv("SHOPIFY_API_VERSION"))
|
||||
if apiVersion == "" {
|
||||
apiVersion = "2025-01"
|
||||
}
|
||||
return &shopifyAPIClient{apiVersion: apiVersion, httpClient: &http.Client{Timeout: 15 * time.Second}}
|
||||
}
|
||||
|
||||
func (c *shopifyAPIClient) SearchCustomers(ctx context.Context, shopDomain, token, email, phone string) ([]map[string]interface{}, error) {
|
||||
queryParts := []string{}
|
||||
if strings.TrimSpace(email) != "" {
|
||||
queryParts = append(queryParts, "email:"+strings.TrimSpace(email))
|
||||
}
|
||||
if strings.TrimSpace(phone) != "" {
|
||||
queryParts = append(queryParts, "phone:"+strings.TrimSpace(phone))
|
||||
}
|
||||
query := url.Values{}
|
||||
query.Set("query", strings.Join(queryParts, " OR "))
|
||||
query.Set("fields", "id,email,phone")
|
||||
|
||||
payload, err := c.get(ctx, shopDomain, token, "customers/search.json", query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shopifyMapSlice(payload, "customers"), nil
|
||||
}
|
||||
|
||||
func (c *shopifyAPIClient) GetOrders(ctx context.Context, shopDomain, token, customerID string) ([]map[string]interface{}, error) {
|
||||
query := url.Values{}
|
||||
query.Set("customer_id", customerID)
|
||||
query.Set("status", "any")
|
||||
query.Set("fields", "id,email,created_at,total_price,currency,fulfillment_status,financial_status")
|
||||
payload, err := c.get(ctx, shopDomain, token, "orders.json", query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shopifyMapSlice(payload, "orders"), nil
|
||||
}
|
||||
|
||||
func (c *shopifyAPIClient) get(ctx context.Context, shopDomain, token, path string, query url.Values) (map[string]interface{}, error) {
|
||||
shopDomain = strings.TrimSpace(shopDomain)
|
||||
if shopDomain == "" || strings.TrimSpace(token) == "" {
|
||||
return nil, &ShopifyProviderError{Message: "Shopify integration credentials missing"}
|
||||
}
|
||||
endpoint := fmt.Sprintf("https://%s/admin/api/%s/%s", shopDomain, c.apiVersion, path)
|
||||
if encoded := query.Encode(); encoded != "" {
|
||||
endpoint += "?" + encoded
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("X-Shopify-Access-Token", token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, &ShopifyProviderError{Message: strings.TrimSpace(string(body))}
|
||||
}
|
||||
var payload map[string]interface{}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func shopifyMapSlice(payload map[string]interface{}, key string) []map[string]interface{} {
|
||||
rawItems, _ := payload[key].([]interface{})
|
||||
items := make([]map[string]interface{}, 0, len(rawItems))
|
||||
for _, raw := range rawItems {
|
||||
if item, ok := raw.(map[string]interface{}); ok {
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -27,6 +30,7 @@ func setupShopifyIntegrationServiceTestDB(t *testing.T) *gorm.DB {
|
||||
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.Contact{},
|
||||
&model.IntegrationHook{},
|
||||
&model.IntegrationApp{},
|
||||
), "failed to auto-migrate models")
|
||||
@@ -44,6 +48,7 @@ func setupShopifyIntegrationService(t *testing.T) (*ShopifyIntegrationService, *
|
||||
db := setupShopifyIntegrationServiceTestDB(t)
|
||||
hookRepo := repository.NewIntegrationHookRepo(db)
|
||||
svc := NewShopifyIntegrationService(hookRepo)
|
||||
svc.client = &shopifyAPIClient{apiVersion: "2025-01", httpClient: fakeShopifyHTTPClient(t, false)}
|
||||
return svc, db
|
||||
}
|
||||
|
||||
@@ -54,6 +59,44 @@ func seedShopifyAccount(db *gorm.DB, t *testing.T) uint {
|
||||
return account.ID
|
||||
}
|
||||
|
||||
func seedShopifyContact(db *gorm.DB, t *testing.T, accountID uint, email, phone string) *model.Contact {
|
||||
t.Helper()
|
||||
contact := &model.Contact{AccountID: accountID, Name: "Shopper", Email: email, PhoneNumber: phone}
|
||||
require.NoError(t, db.Create(contact).Error)
|
||||
return contact
|
||||
}
|
||||
|
||||
type shopifyRoundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f shopifyRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }
|
||||
|
||||
func fakeShopifyHTTPClient(t *testing.T, emptyCustomers bool) *http.Client {
|
||||
t.Helper()
|
||||
return &http.Client{Transport: shopifyRoundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
assert.Equal(t, "shpat_abc123", req.Header.Get("X-Shopify-Access-Token"))
|
||||
switch req.URL.Path {
|
||||
case "/admin/api/2025-01/customers/search.json":
|
||||
assert.Equal(t, "email:test@example.com OR phone:+1234567890", req.URL.Query().Get("query"))
|
||||
assert.Equal(t, "id,email,phone", req.URL.Query().Get("fields"))
|
||||
if emptyCustomers {
|
||||
return shopifyHTTPResponse(http.StatusOK, `{"customers":[]}`), nil
|
||||
}
|
||||
return shopifyHTTPResponse(http.StatusOK, `{"customers":[{"id":"123","email":"test@example.com","phone":"+1234567890"}]}`), nil
|
||||
case "/admin/api/2025-01/orders.json":
|
||||
assert.Equal(t, "123", req.URL.Query().Get("customer_id"))
|
||||
assert.Equal(t, "any", req.URL.Query().Get("status"))
|
||||
assert.Equal(t, "id,email,created_at,total_price,currency,fulfillment_status,financial_status", req.URL.Query().Get("fields"))
|
||||
return shopifyHTTPResponse(http.StatusOK, `{"orders":[{"id":"456","email":"test@example.com","created_at":"2026-06-06T00:00:00Z","total_price":"100.00","currency":"USD","fulfillment_status":"fulfilled","financial_status":"paid"}]}`), nil
|
||||
default:
|
||||
return shopifyHTTPResponse(http.StatusNotFound, `{"error":"not found"}`), nil
|
||||
}
|
||||
})}
|
||||
}
|
||||
|
||||
func shopifyHTTPResponse(status int, body string) *http.Response {
|
||||
return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(bytes.NewBufferString(body))}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// ShopifyIntegrationService — Auth tests
|
||||
// ========================================
|
||||
@@ -191,3 +234,49 @@ func TestShopifyIntegrationService_Delete_NotFound(t *testing.T) {
|
||||
assert.Error(t, err, "Delete should fail when no Shopify integration exists")
|
||||
assert.Contains(t, err.Error(), "not found", "error should indicate integration not found")
|
||||
}
|
||||
|
||||
func TestShopifyIntegrationService_GetOrders_ChatwootPayload(t *testing.T) {
|
||||
svc, db := setupShopifyIntegrationService(t)
|
||||
accountID := seedShopifyAccount(db, t)
|
||||
contact := seedShopifyContact(db, t, accountID, "test@example.com", "+1234567890")
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := svc.Auth(ctx, accountID, CreateShopifyAuthRequest{ShopDomain: "test-store.myshopify.com", AccessToken: "shpat_abc123"})
|
||||
require.NoError(t, err)
|
||||
|
||||
orders, err := svc.GetOrders(ctx, accountID, contact.ID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, orders, 1)
|
||||
assert.Equal(t, "456", orders[0]["id"])
|
||||
assert.Equal(t, "https://test-store.myshopify.com/admin/orders/456", orders[0]["admin_url"])
|
||||
}
|
||||
|
||||
func TestShopifyIntegrationService_GetOrders_ContactInformationMissing(t *testing.T) {
|
||||
svc, db := setupShopifyIntegrationService(t)
|
||||
accountID := seedShopifyAccount(db, t)
|
||||
contact := seedShopifyContact(db, t, accountID, "", "")
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := svc.Auth(ctx, accountID, CreateShopifyAuthRequest{ShopDomain: "test-store.myshopify.com", AccessToken: "shpat_abc123"})
|
||||
require.NoError(t, err)
|
||||
|
||||
orders, err := svc.GetOrders(ctx, accountID, contact.ID)
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, orders)
|
||||
assert.Contains(t, err.Error(), "Contact information missing")
|
||||
}
|
||||
|
||||
func TestShopifyIntegrationService_GetOrders_EmptyCustomers(t *testing.T) {
|
||||
svc, db := setupShopifyIntegrationService(t)
|
||||
svc.client = &shopifyAPIClient{apiVersion: "2025-01", httpClient: fakeShopifyHTTPClient(t, true)}
|
||||
accountID := seedShopifyAccount(db, t)
|
||||
contact := seedShopifyContact(db, t, accountID, "test@example.com", "+1234567890")
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := svc.Auth(ctx, accountID, CreateShopifyAuthRequest{ShopDomain: "test-store.myshopify.com", AccessToken: "shpat_abc123"})
|
||||
require.NoError(t, err)
|
||||
|
||||
orders, err := svc.GetOrders(ctx, accountID, contact.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, orders)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user