0016 — Customer support desk¶
Status: accepted (2026-09-29). Builds on 0012 (verified email) and 0007 (provisioned alerts). Amended by 0018: the dashboard and ticket screens moved to the support portal, and agents may be Support-role users.
Context¶
Support before this change was a thin ticket inbox:
- The ticket schema came from the untracked, hand-applied
aim-backend/scripts/postgres/tickets.sql: four statuses, three priorities, a free-textcategory, and nothing else. There was no SLA, no record of how a ticket was resolved, and no link to the order it was about. The file is hash-frozen byTestLegacyMigrationsUnmodified, and CI databases do not have the table at all. - Nine routes. Customers could create, list, read and reply. Admins could
list the latest 100, read, set any status, and reply. Each new ticket fired
SendTicketNotificationfrom a bare goroutine inside the request: plain-text SMTP with no timeout, the customer's subject copied raw into a mail header, and failures silently lost. - Admin replies were returned to customers joined to
users.display_name, which exposed the agent's real name. - The website contact page only built a
mailto:link. The Help Centre was sixteen FAQs hard-coded inaim-store-website/src/pages/FaqPage.jsx. - The Grievance Redressal page publishes statutory commitments from the Consumer Protection (E-Commerce) Rules, 2020: acknowledgement within 48 hours "with a reference number", redress within 30 days, and a three-level escalation. Nothing in the system tracked any of them.
- Production SMTP is blank today. The app has no push notifications, and SMS is used only for OTPs.
The goal has two sides. Customers browse a configurable Help Centre, raise a ticket (optionally linked to an order), follow and reply to it, confirm or reopen the resolution, rate it, and escalate to the Grievance Officer. Agents work a queue with SLA state, assignment, internal notes, canned replies and a resolution form, plus a dashboard and an email log. Every piece of content (topics, FAQs, templates, resolution codes, settings) is editable in the admin portal.
Decision¶
Build the support desk inside the existing Go API, admin portal, website and app, with no new service, no third-party helpdesk and no new dependency.
- Scope: signed-in customers only, in the app and on the website. The
website contact page now creates a real ticket for a signed-in customer.
The page's old comment argued that a submission API would be a form that
silently fails; the ticket API now exists. Guests keep the
mailto:form, because a public contact POST needs anti-abuse measures, and the privacy policy rules out a third-party captcha. Support never moves money. Refunds and cancellations stay on their existing flows. A ticket links an order and shows its state read-only. - Help Centre:
support_topicshas two levels. Every attribute comes from the selected topic's own row, with no inheritance. FAQs live insupport_faqs.- Both are served by the one public route
GET /api/v1/support/help. It sendsCache-Control: public, max-age=60, keeps a 30s in-process cache, and returns active rows only, never templates or SLA data. - A topic may carry a
feature_key. The topic is hidden while thatfeature_togglesrow is off, and a missing row counts as on. The exception iskarat24, which stays hidden unless the row is explicitly enabled, the same fail-closed rule the app and website apply. - The website keeps its static FAQ as the fallback when the call fails.
- FAQ
link_pathaccepts in-app paths only, so a//hostredirect is impossible.
- Lifecycle:
- Five statuses:
open,in_progress,awaiting_customer,resolved,closed. Four priorities, addingurgent. - The backend is the authority. Every transition runs in one transaction:
SELECT … FOR UPDATE, a move to the current state is a no-op, and theUPDATE … WHERE status = $fromis guarded. Every customer payload carries server-computedcan_reply,can_confirm,can_reopen,can_rateandcan_escalateflags, which the UIs mirror. - Resolving requires a resolution code and a customer-facing summary. A
resolved ticket closes when the customer confirms it, or automatically
after
auto_close_after_days. The customer can reopen it withinreopen_window_days. - A ticket waiting on the customer gets a reminder, and is eventually
auto-resolved as
no_response. Grievances are never auto-resolved. - Creation is idempotent per
(user_id, client_request_id), and a customer can have at mostmax_open_tickets_per_customeractive tickets.
- Five statuses:
- SLA:
- Targets are calendar hours per priority, stored as settings, for first
response and for resolution. The clock pauses while a ticket is
awaiting_customerand restarts on reopen. - One SQL
CASEfragment computessla_statefor the list, the filters, the dashboard and the gauges. A Go mirror is tested against it. - A delay notice (a reason and a revised date) tells the customer about a delay without moving the target.
- Targets are calendar hours per priority, stored as settings, for first
response and for resolution. The clock pauses while a ticket is
- Grievances:
- Every path that makes a ticket a grievance goes through one helper: creation under the grievance topic, agent create, an agent PATCH, a topic change, and customer escalation.
- The helper sets priority
urgentand the statutory deadlinegrievance_due_at = LEAST(receipt + 30 days, receipt + 1 month), since E-Commerce Rules rule 4(5) says "within one month" and February is shorter than 30 days. It records a public timeline event and sends an acknowledgement email with the reference number. The notification settings cannot switch that email off. - The grievance clock never pauses.
- A "grievance breach" means only that statutory date: an active
grievance, including one awaiting the customer, past
grievance_due_at. The dashboard'sgrievance_breachedcount, the queue'sstatus=active&sla=grievance_overduefilter and theaim_support_tickets_grievance_breachedgauge behind the critical alert all use that one predicate. Being urgent, a grievance often misses its internal SLA weeks earlier (an old ticket escalated today can be breached at once). That is an ordinary SLA breach insla_state, and must not page as a regulatory one. - Closing and decline messages include the Level-3 escalation sentence
exactly as written in
aim-store-website/src/pages/GrievancePage.jsx.
- Emails through a transactional outbox, never SMTP inside a request:
- A ticket action inserts its
support_email_outboxrows in the same transaction as the ticket change. Each row carries a dedupe key taken from the event that caused it. Staff "customer replied" mail collapses to one email per agent turn. - A worker in the API process (
aim-backend/internal/supportops/) claims rows withFOR UPDATE SKIP LOCKED, at most 5 per batch and 20 per tick. It sends throughSendHTML, which has a 15s timeout, retries with capped exponential backoff, and gives up after 8 attempts. Delivery is at-least-once. - Without a working mailer the worker never claims a row. On every tick,
mailer or not, it marks unsent rows older than
email_max_age_hours(72 by default) as dead, so turning SMTP on later never sends a stale backlog. - The same worker also auto-closes, auto-resolves, sends reminders and exports the gauges, in that order. Auto-resolve runs before reminders, and reminders skip any ticket already past the auto-resolve threshold, so a customer never gets a "we're waiting for you" email moments before a "resolved" one.
SendTicketNotificationand its goroutine are removed.
- A ticket action inserts its
- Templates:
support_templateshas three kinds.replyandresolutiontemplates are canned text that the admin portal renders, and it disables Send while any{{placeholder}}is still unfilled.emailtemplates are rendered by the server.- Rendering is plain replacement from an allow-list, followed by HTML
escaping. Go
text/templateis never run on admin-written text. - Email templates may use only the documented server placeholders.
Staff-only placeholders such as the customer's phone and email are
allowed only in
staff_*templates. - Subjects may use only
ticket_number,ticket_status,topic_nameandresolution_label. The rendered subject has CR/LF stripped, is capped at 200 runes, and is Q-encoded.
- Security and privacy:
- A customer email goes only to one of two addresses. The first is an
OTP-verified
users.email(0012). The second is acontact_emailthat an agent typed when creating a ticket on the customer's behalf. Customers cannot choose a recipient, so tickets cannot relay AIM-signed mail to third parties. Any other email is stored asskipped, as is any email beyond 20 to the same customer address in 24 hours. - Customers never see an agent's identity. Every agent reply and every
{{agent_name}}renders theagent_display_namesetting, on the server and in the portal alike. - Internal notes live in their own table,
ticket_internal_notes, which no customer query touches. Neither an API image rollback nor a schema rollback can turn a note into a public reply. Notes never change status and never send email. ticket_events.is_publicdefaults to false. The customer timeline shows only an explicit allow-list of event types, and no event stores a person's name in its from/to values.SUPPORT_*audit rows carry only ids, enums, changed field names and booleans. They never hold message text or contact data, because audit rows outlive account deletion.- Only a super admin can change the staff inbox or the public support email and phone settings.
- A request for another customer's ticket gets
404. - Every free-text field is trimmed and length-capped, and NUL bytes are rejected.
- Customer writes have body-size caps and per-user rate limits.
- A 500 response never echoes a driver error.
- A customer email goes only to one of two addresses. The first is an
OTP-verified
-
Schema: one tracked, idempotent migration,
aim-backend/scripts/postgres/migrations/090_support_desk.sql. It:- re-declares the legacy
ticketsandticket_repliestables verbatim, so fresh and CI databases get them, instead of editing the frozentickets.sql; - adds the config tables,
ticket_internal_notes,ticket_events,support_email_outboxand the seed content; - widens the status and priority CHECKs. It drops whichever CHECK constrains those columns, whatever name it was hand-applied under, and raises an error if any other constraint still references them. A mismatched production schema therefore fails the deploy instead of failing at runtime;
- makes
ticket_replies.user_idnullable withON DELETE SET NULL. Deleting an admin no longer deletes their replies, andDeleteUserCascadenow deletes a customer's replies by ticket; - backfills the legacy rows.
aim-backend/scripts/postgres/rollback/rollback_090.sqldrops the support tables and columns. It deliberately leaves the widened CHECKs, the nullable author column and theticket_numberunique index;deploy/README.mdexplains why. - Agent tooling (admin portal): a Support dashboard whose tiles each open the matching filtered queue; a ticket queue whose filters live in the URL; a ticket page with a conversation, internal notes, templates, the resolution and delay dialogs, a linked-order card and the timeline; and editors for topics and FAQs, templates, resolution codes and settings, plus an email log with retry. - Guards and compliance: - ThedeliberateCommerceAdditionsallow-list inTestRouteSurfaceFrozengains 30 routes: the public help route, four customer ticket actions, and 25 admin ticket and support routes. The nine existing ticket routes keep their method and path. - TheTestLegacyMigrationsUnmodifiedmanifest gains exactly one line, for 090.tickets.sql,schema.sqland every earlier migration are untouched. - Dynamic list SQL followsTestNoFormattedSQL. - The seed text uses only the registered legal name, AIM ORIGINATORS PRIVATE LIMITED, and contains no GSTIN-shaped string (deploy/tests/legal-identity-test.sh). - Contact strings are copied exactly fromaim-store-website/src/data/company.js. - No template asks for a password, a full card number, a CVV or a UPI PIN. - Nofeature_togglesrow is added, because a test pins that key set. - Configuration and monitoring: - Five env vars:SUPPORT_WORKER_ENABLED,SUPPORT_WORKER_INTERVAL_SECONDS,SUPPORT_EMAIL_MAX_PER_TICK,SUPPORT_TICKET_URL_BASEandSUPPORT_ADMIN_TICKET_URL_BASE. None is secret, and all have working defaults (deploy/gen-env.sh,aim-backend/.env.example). Everything else the support team tunes is asupport_settingsrow. -aim_support_*metrics cover worker liveness, sends and failures by recipient kind, outbox depth and age, SLA and grievance breaches, auto-close and auto-resolve counts, andaim_support_mailer_enabled. - Five provisioned alerts use them. The outbox-backlog and send-failure alerts fire only while a mailer is configured. The others cover an unavailable mailer, SLA breaches (more than 10 for an hour), and grievances past their statutorygrievance_due_at, which is critical. - CI pins the alerts withdeploy/tests/support-alerts-contract-test.sh. - re-declares the legacy
Rollout order¶
deploy-backend. It applies 090 before recreating the API, and the old image works against the new schema in between.deploy-admin-portal, in the same window. Until it lands, resolving an active ticket, or closing one, from the old portal returns409 RESOLUTION_REQUIRED. Called without paging, the list endpoint still returns up to 100 rows, as the old page expects.deploy-website, then an app release. Older clients keep working, because the existing ticket routes are unchanged and every new field is additive.deploy-monitoring, at any point, to provision the support alerts.
Consequences¶
- Customer-facing policy text moves from code into rows that admins edit. Topic, FAQ and template wording becomes an editorial responsibility, to be checked against the published policies before activation. The seed was written to match them.
- Production sends no support email until SMTP is configured. The
SupportMailerUnavailablealert and the portal banner keep that visible. Meanwhile customers still see every update in the app and on the website, with an unread badge. - Grievance deadlines are now tracked, shown on the dashboard, and alerted on.
- Tickets now reference orders, users (assignee, creating agent and
resolver), topics and resolution codes, all
ON DELETE SET NULL, and every new child table cascades fromtickets. Admin Delete User keeps working and does not bring back the foreign-key violation that PR #83 fixed. - Timeline events and outbox rows grow with use, and neither has a retention job yet.
- Rolling back only the API image is the safe rollback: everything 090 adds is
invisible to, or tolerant of, the pre-090 code (
chk_tickets_awaiting_sinceis one-directional for exactly this reason). Seedeploy/README.md.
Non-goals (v1) and follow-ups¶
- Guest (signed-out) tickets, or a public contact POST.
- Attachments. Push notifications and SMS updates (there is no push infrastructure, and SMS is OTP-only).
- Business-hours SLAs and a holiday calendar (targets are calendar hours). Per-topic SLA overrides.
- Emailing unverified addresses. Inbound email threading: replying to a support email does not reach the ticket.
- Account-deletion behaviour for support records (see question 7).
Open questions (product owner)¶
- Gift cards: purchase is a client-only stub, with no payment and no server credit, yet its toggle is on. The gift-card topic is seeded inactive until this is resolved.
- E-vouchers: the app says they can be redeemed at checkout, but no backend path does that. The FAQ wording is neutral.
- Credit expiry: the 30-day and 365-day expiry lines are app copy only, and nothing enforces them. The seed does not repeat them.
- Delivery fee: the Shipping Policy says delivery is free on every order, but migration 071 seeds a ₹99 fee on orders under ₹999. Confirm the live setting, then align the policy or the setting.
- 7-day cancellation: the policy limits cancellation to 7 days, but the backend allows cancelling until the order ships.
- KARAT 24 payouts: there is no live payout rail, so the seed never promises a payout timeline.
-
Ticket retention on account deletion, and the open-dispute blocker:
- The Privacy Policy says dispute and grievance records are kept and separated from the profile after deletion, but Admin Delete User hard-deletes a customer's tickets.
- The Terms say an open dispute blocks deletion, but the eligibility check looks only at orders and pending requests.
Both need a decision before anyone relies on either statement. 8. IT Rules timelines: the Grievance page also cites the IT (Intermediary Guidelines and Digital Media Ethics Code) Rules, 2021. As amended, those rules give privacy and content complaints shorter timelines (24 hours and 15 days) than the 48-hour / 30-day defaults. Confirm with counsel whether those complaints need their own targets. 9. Grievance Officer identity:
company.jsnames the role but no person. The E-Commerce Rules (rule 4(4)) require the officer's name and designation. 10. Production SMTP: it is blank today, so no support email is sent. Configure it before telling customers they will get email updates.