ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 7m0s
ci / test (pull_request) Successful in 12m1s
ci / build (pull_request) Successful in 18m14s
ci / image (pull_request) Successful in 5m9s
Accounts open tickets under Support and admins answer them under Admin → Support tickets. - A ticket is open while it waits for the admins and answered while it waits for the account. Either side can close or reopen it, and a reply reopens it. - The admins are mailed about new tickets and replies, and the account about answers. - A ticket can name the active organization and point at a monitor, notification channel, alert group, status page or incident in it. Each must be something the account can read. - Next to the conversation, admins see the account at a glance: state, sign-in, organizations with their limits and usage, and open tickets. - Admins switch support off and limit how many tickets an account has open at once. - Suspended accounts and those yet to accept the terms reach support too; a suspended account opens one ticket. - Tickets are part of the account export and are deleted with the account. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
861 lines
25 KiB
Go
861 lines
25 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
|
)
|
|
|
|
// Support tickets: an account asks the platform's admins for help, also
|
|
// while it is suspended or has yet to accept the terms. A ticket is open
|
|
// while it waits for the admins and answered while it waits for the
|
|
// account; a reply from either side moves it accordingly, also out of
|
|
// closed.
|
|
|
|
const (
|
|
ticketOpen = "open"
|
|
ticketAnswered = "answered"
|
|
ticketClosed = "closed"
|
|
)
|
|
|
|
type supportTicketRequest struct {
|
|
Subject string `json:"subject" binding:"required,max=200"`
|
|
Message string `json:"message" binding:"required,max=10000"`
|
|
// AttachOrg names the active organization in the ticket. Anything else
|
|
// attached comes from it and names it too.
|
|
AttachOrg bool `json:"attach_org"`
|
|
Monitor string `json:"monitor_id" binding:"max=36"`
|
|
Channel string `json:"channel_id" binding:"max=36"`
|
|
AlertGroup string `json:"alert_group_id" binding:"max=36"`
|
|
StatusPage string `json:"status_page_id" binding:"max=36"`
|
|
Incident string `json:"incident_id" binding:"max=36"`
|
|
}
|
|
|
|
// supportReference is something a ticket points at, by kind: org,
|
|
// monitor, channel, alert_group, status_page or incident.
|
|
type supportReference struct {
|
|
Kind string `json:"kind"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
type supportMessageRequest struct {
|
|
Message string `json:"message" binding:"required,max=10000"`
|
|
}
|
|
|
|
type supportStatusRequest struct {
|
|
Status string `json:"status" binding:"required,oneof=open answered closed"`
|
|
}
|
|
|
|
type supportMessageView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
FromStaff bool `json:"from_staff"`
|
|
// Author is the admin who answered, shown to admins only.
|
|
Author string `json:"author,omitempty"`
|
|
Body string `json:"body"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
type supportTicketView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Subject string `json:"subject"`
|
|
Status string `json:"status"`
|
|
// Org is the organization the account was in when it opened the ticket.
|
|
Org *string `json:"org,omitempty"`
|
|
// User is the account's email, shown to admins only.
|
|
User string `json:"user,omitempty"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
References []supportReference `json:"references,omitempty"`
|
|
Messages []supportMessageView `json:"messages,omitempty"`
|
|
}
|
|
|
|
// cleanSupportText trims text and reports whether anything is left.
|
|
func cleanSupportText(c *gin.Context, texts ...*string) bool {
|
|
for _, t := range texts {
|
|
*t = strings.TrimSpace(*t)
|
|
if *t == "" {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// loadTicket reads a ticket with its messages in scope, which decides
|
|
// whose tickets are visible.
|
|
func (s *Server) loadTicket(ctx context.Context, scope tenant.Scope, id uuid.UUID, staff bool) (supportTicketView, error) {
|
|
var v supportTicketView
|
|
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
|
t, err := q.GetSupportTicket(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
v = supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, Org: t.OrgName, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt}
|
|
if staff {
|
|
v.User = t.UserEmail
|
|
}
|
|
msgs, err := q.SupportMessages(ctx, id)
|
|
for _, m := range msgs {
|
|
mv := supportMessageView{ID: m.ID, FromStaff: m.FromStaff, Body: m.Body, CreatedAt: m.CreatedAt}
|
|
if staff && m.FromStaff {
|
|
mv.Author = m.AuthorEmail
|
|
}
|
|
v.Messages = append(v.Messages, mv)
|
|
}
|
|
return err
|
|
})
|
|
if err != nil {
|
|
return v, err
|
|
}
|
|
v.References, err = s.ticketReferences(ctx, id)
|
|
return v, err
|
|
}
|
|
|
|
// ticketReferences names what a ticket points at. The account may no
|
|
// longer see those things, so this reads past row-level security, after
|
|
// the caller saw the ticket itself.
|
|
func (s *Server) ticketReferences(ctx context.Context, id uuid.UUID) ([]supportReference, error) {
|
|
var out []supportReference
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
r, err := q.SupportTicketReferences(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
add := func(kind string, name *string, extra ...*string) {
|
|
if name == nil {
|
|
return
|
|
}
|
|
n := *name
|
|
for _, e := range extra {
|
|
if e != nil && *e != "" {
|
|
n += " (" + *e + ")"
|
|
}
|
|
}
|
|
out = append(out, supportReference{Kind: kind, Name: n})
|
|
}
|
|
add("org", r.OrgName, r.OrgSlug)
|
|
add("monitor", r.MonitorName, r.MonitorType)
|
|
add("channel", r.ChannelName, r.ChannelType)
|
|
add("alert_group", r.AlertGroupName)
|
|
add("status_page", r.StatusPageTitle, r.StatusPageSlug)
|
|
if r.IncidentStartedAt != nil {
|
|
name := deref(r.IncidentMonitor)
|
|
if t := deref(r.IncidentTitle); t != "" {
|
|
name = t + " · " + name
|
|
}
|
|
name += " · " + r.IncidentStartedAt.UTC().Format(timeLayout)
|
|
add("incident", &name)
|
|
}
|
|
return nil
|
|
})
|
|
return out, err
|
|
}
|
|
|
|
func ticketID(c *gin.Context) (uuid.UUID, bool) {
|
|
id, err := uuid.Parse(c.Param("id"))
|
|
if err != nil {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
}
|
|
return id, err == nil
|
|
}
|
|
|
|
func (s *Server) listMyTickets(c *gin.Context) {
|
|
sess := auth.Current(c)
|
|
ctx := c.Request.Context()
|
|
var rows []store.SupportTicket
|
|
if err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
|
var err error
|
|
rows, err = q.ListUserSupportTickets(ctx, sess.UserID)
|
|
return err
|
|
}); err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
out := make([]supportTicketView, len(rows))
|
|
for i, t := range rows {
|
|
out[i] = supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt}
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"tickets": out})
|
|
}
|
|
|
|
// optionalID parses a form's optional reference; empty is none.
|
|
func optionalID(v string) (*uuid.UUID, bool) {
|
|
if v = strings.TrimSpace(v); v == "" {
|
|
return nil, true
|
|
}
|
|
id, err := uuid.Parse(v)
|
|
return &id, err == nil
|
|
}
|
|
|
|
// ticketRefs resolves what a new ticket points at. Everything comes from
|
|
// the active organization, which the account has to be able to read.
|
|
func (s *Server) ticketRefs(c *gin.Context, req supportTicketRequest) (store.CreateSupportTicketParams, bool) {
|
|
var p store.CreateSupportTicketParams
|
|
ids := []struct {
|
|
raw string
|
|
dst **uuid.UUID
|
|
perm authz.Permission
|
|
}{
|
|
{req.Monitor, &p.MonitorID, authz.MonitorsRead},
|
|
{req.Channel, &p.ChannelID, authz.NotificationsRead},
|
|
{req.AlertGroup, &p.AlertGroupID, authz.NotificationsRead},
|
|
{req.StatusPage, &p.StatusPageID, authz.StatusPagesRead},
|
|
{req.Incident, &p.IncidentID, authz.IncidentsRead},
|
|
}
|
|
any := req.AttachOrg
|
|
for _, r := range ids {
|
|
id, ok := optionalID(r.raw)
|
|
if !ok {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
|
return p, false
|
|
}
|
|
*r.dst = id
|
|
any = any || id != nil
|
|
}
|
|
if !any {
|
|
return p, true
|
|
}
|
|
sess := auth.Current(c)
|
|
_, principal, err := s.consoleMe(c, sess)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return p, false
|
|
}
|
|
if principal == nil {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
|
return p, false
|
|
}
|
|
for _, r := range ids {
|
|
if *r.dst != nil && !principal.Grants.Can(r.perm) {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
|
return p, false
|
|
}
|
|
}
|
|
ctx := c.Request.Context()
|
|
var exists *bool
|
|
if err := s.db.Tx(ctx, principal.scope(), func(q *store.Queries) error {
|
|
var err error
|
|
exists, err = q.SupportReferencesExist(ctx, store.SupportReferencesExistParams{
|
|
OrgID: principal.Org.ID, MonitorID: p.MonitorID, ChannelID: p.ChannelID,
|
|
AlertGroupID: p.AlertGroupID, StatusPageID: p.StatusPageID, IncidentID: p.IncidentID,
|
|
})
|
|
return err
|
|
}); err != nil {
|
|
internalError(c, err)
|
|
return p, false
|
|
}
|
|
if exists == nil || !*exists {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
|
return p, false
|
|
}
|
|
p.OrgID = &principal.Org.ID
|
|
return p, true
|
|
}
|
|
|
|
// errTicketLimit and errSuspendedTicket refuse tickets beyond what the
|
|
// platform allows; the error code says which.
|
|
var (
|
|
errTicketLimit = errors.New("api: too many open tickets")
|
|
errSuspendedTicket = errors.New("api: suspended accounts open one ticket")
|
|
)
|
|
|
|
// checkTicketLimits refuses another open ticket for user: more than the
|
|
// platform allows at the same time, or a second since a suspension.
|
|
func checkTicketLimits(ctx context.Context, q *store.Queries, user uuid.UUID, maxOpen int, newTicket bool) error {
|
|
if newTicket {
|
|
u, err := q.GetUser(ctx, user)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if u.DisabledAt != nil {
|
|
n, err := q.CountSupportTicketsSince(ctx, store.CountSupportTicketsSinceParams{UserID: user, CreatedAt: *u.DisabledAt})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n > 0 {
|
|
return errSuspendedTicket
|
|
}
|
|
}
|
|
}
|
|
if maxOpen <= 0 {
|
|
return nil
|
|
}
|
|
n, err := q.CountOpenSupportTickets(ctx, user)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n >= int64(maxOpen) {
|
|
return errTicketLimit
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// failTicketLimit answers err if it is one of the ticket limits.
|
|
func failTicketLimit(c *gin.Context, err error, maxOpen int) bool {
|
|
switch {
|
|
case errors.Is(err, errSuspendedTicket):
|
|
fail(c, http.StatusConflict, "suspended_ticket_limit")
|
|
case errors.Is(err, errTicketLimit):
|
|
fail(c, http.StatusConflict, "too_many_tickets", "Count", maxOpen)
|
|
default:
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (s *Server) createTicket(c *gin.Context) {
|
|
var req supportTicketRequest
|
|
if !bind(c, &req) || !cleanSupportText(c, &req.Subject, &req.Message) {
|
|
return
|
|
}
|
|
sess := auth.Current(c)
|
|
if !s.limit(c, "support:user:"+sess.UserID.String(), 10, time.Hour) {
|
|
return
|
|
}
|
|
params, ok := s.ticketRefs(c, req)
|
|
if !ok {
|
|
return
|
|
}
|
|
params.UserID, params.Subject = sess.UserID, req.Subject
|
|
ctx := c.Request.Context()
|
|
maxOpen := s.supportSettings(ctx).MaxOpen
|
|
var t store.SupportTicket
|
|
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
|
if err := checkTicketLimits(ctx, q, sess.UserID, maxOpen, true); err != nil {
|
|
return err
|
|
}
|
|
var err error
|
|
if t, err = q.CreateSupportTicket(ctx, params); err != nil {
|
|
return err
|
|
}
|
|
_, err = q.AddSupportMessage(ctx, store.AddSupportMessageParams{TicketID: t.ID, AuthorID: &sess.UserID, Body: req.Message})
|
|
return err
|
|
})
|
|
if failTicketLimit(c, err, maxOpen) {
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
auditDetail(c, "ticket", t.ID.String())
|
|
s.mailAdmins(ctx, t.ID, t.Subject)
|
|
c.JSON(http.StatusCreated, supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt})
|
|
}
|
|
|
|
func (s *Server) getMyTicket(c *gin.Context) {
|
|
id, ok := ticketID(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
v, err := s.loadTicket(c.Request.Context(), tenant.User(auth.Current(c).UserID), id, false)
|
|
s.respondTicket(c, v, err)
|
|
}
|
|
|
|
func (s *Server) respondTicket(c *gin.Context, v supportTicketView, err error) {
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
case err != nil:
|
|
internalError(c, err)
|
|
default:
|
|
c.JSON(http.StatusOK, v)
|
|
}
|
|
}
|
|
|
|
// replyTicket adds a message and moves the ticket to the side that has to
|
|
// answer next.
|
|
func (s *Server) replyTicket(c *gin.Context, scope tenant.Scope, author uuid.UUID, staff bool) (store.GetSupportTicketRow, bool) {
|
|
maxOpen := 0
|
|
if !staff {
|
|
maxOpen = s.supportSettings(c.Request.Context()).MaxOpen
|
|
}
|
|
id, ok := ticketID(c)
|
|
if !ok {
|
|
return store.GetSupportTicketRow{}, false
|
|
}
|
|
var req supportMessageRequest
|
|
if !bind(c, &req) || !cleanSupportText(c, &req.Message) {
|
|
return store.GetSupportTicketRow{}, false
|
|
}
|
|
status := ticketOpen
|
|
if staff {
|
|
status = ticketAnswered
|
|
}
|
|
ctx := c.Request.Context()
|
|
var t store.GetSupportTicketRow
|
|
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
|
var err error
|
|
if t, err = q.GetSupportTicket(ctx, id); err != nil {
|
|
return err
|
|
}
|
|
if !staff && t.Status == ticketClosed {
|
|
if err := checkTicketLimits(ctx, q, t.UserID, maxOpen, false); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if _, err = q.AddSupportMessage(ctx, store.AddSupportMessageParams{TicketID: id, AuthorID: &author, FromStaff: staff, Body: req.Message}); err != nil {
|
|
return err
|
|
}
|
|
_, err = q.SetSupportTicketStatus(ctx, store.SetSupportTicketStatusParams{ID: id, Status: status})
|
|
return err
|
|
})
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return t, false
|
|
case failTicketLimit(c, err, maxOpen):
|
|
return t, false
|
|
case err != nil:
|
|
internalError(c, err)
|
|
return t, false
|
|
}
|
|
auditDetail(c, "ticket", id.String())
|
|
c.JSON(http.StatusCreated, gin.H{"status": status})
|
|
return t, true
|
|
}
|
|
|
|
func (s *Server) replyMyTicket(c *gin.Context) {
|
|
sess := auth.Current(c)
|
|
if !s.limit(c, "support:reply:"+sess.UserID.String(), 60, time.Hour) {
|
|
return
|
|
}
|
|
if t, ok := s.replyTicket(c, tenant.User(sess.UserID), sess.UserID, false); ok {
|
|
s.mailAdmins(c.Request.Context(), t.ID, t.Subject)
|
|
}
|
|
}
|
|
|
|
// setTicketStatus closes or reopens a ticket in scope; accounts can only
|
|
// close theirs or reopen them for the admins.
|
|
func (s *Server) setTicketStatus(c *gin.Context, scope tenant.Scope, maxOpen int, allowed ...string) {
|
|
id, ok := ticketID(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
var req supportStatusRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
if len(allowed) > 0 && !slices.Contains(allowed, req.Status) {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
var n int64
|
|
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
|
if req.Status != ticketClosed && maxOpen > 0 {
|
|
cur, err := q.SupportTicketStatus(ctx, id)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if cur == ticketClosed {
|
|
if err := checkTicketLimits(ctx, q, auth.Current(c).UserID, maxOpen, false); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
var err error
|
|
n, err = q.SetSupportTicketStatus(ctx, store.SetSupportTicketStatusParams{ID: id, Status: req.Status})
|
|
return err
|
|
})
|
|
switch {
|
|
case failTicketLimit(c, err, maxOpen):
|
|
case err != nil:
|
|
internalError(c, err)
|
|
case n == 0:
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
default:
|
|
auditDetail(c, "status", req.Status)
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
func (s *Server) setMyTicketStatus(c *gin.Context) {
|
|
s.setTicketStatus(c, tenant.User(auth.Current(c).UserID), s.supportSettings(c.Request.Context()).MaxOpen, ticketOpen, ticketClosed)
|
|
}
|
|
|
|
// supportStatusFilter reads the status filter of the admins' list; empty
|
|
// lists every ticket.
|
|
func supportStatusFilter(c *gin.Context) *string {
|
|
switch st := c.Query("status"); st {
|
|
case ticketOpen, ticketAnswered, ticketClosed:
|
|
return &st
|
|
case "all":
|
|
return nil
|
|
default:
|
|
open := ticketOpen
|
|
return &open
|
|
}
|
|
}
|
|
|
|
func (s *Server) adminListTickets(c *gin.Context) {
|
|
rows, err := s.supportTickets(c.Request.Context(), supportStatusFilter(c))
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
out := make([]supportTicketView, len(rows))
|
|
for i, t := range rows {
|
|
out[i] = supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, Org: t.OrgName, User: t.UserEmail, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt}
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"tickets": out})
|
|
}
|
|
|
|
// supportTickets lists the latest 200 tickets with status, or all.
|
|
func (s *Server) supportTickets(ctx context.Context, status *string) ([]store.ListSupportTicketsRow, error) {
|
|
var rows []store.ListSupportTicketsRow
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
var err error
|
|
rows, err = q.ListSupportTickets(ctx, status)
|
|
return err
|
|
})
|
|
return rows, err
|
|
}
|
|
|
|
func (s *Server) adminGetTicket(c *gin.Context) {
|
|
id, ok := ticketID(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
v, err := s.loadTicket(c.Request.Context(), tenant.System(), id, true)
|
|
s.respondTicket(c, v, err)
|
|
}
|
|
|
|
func (s *Server) adminReplyTicket(c *gin.Context) {
|
|
sess := auth.Current(c)
|
|
if t, ok := s.replyTicket(c, tenant.System(), sess.UserID, true); ok {
|
|
s.mailTicketOwner(c.Request.Context(), t)
|
|
}
|
|
}
|
|
|
|
func (s *Server) adminSetTicketStatus(c *gin.Context) {
|
|
s.setTicketStatus(c, tenant.System(), 0)
|
|
}
|
|
|
|
func (s *Server) ticketLink(path string) string {
|
|
return strings.TrimSuffix(s.cfg.PublicURL, "/") + path
|
|
}
|
|
|
|
// mailAdmins tells the platform's admins that a ticket waits for them.
|
|
// Mail is a courtesy: the ticket stands without it.
|
|
func (s *Server) mailAdmins(ctx context.Context, id uuid.UUID, subject string) {
|
|
if s.smtp == nil {
|
|
return
|
|
}
|
|
var to []string
|
|
if err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
var err error
|
|
to, err = q.AdminEmails(ctx)
|
|
return err
|
|
}); err != nil || len(to) == 0 {
|
|
return
|
|
}
|
|
l := s.catalog.Match("")
|
|
data := map[string]any{"Subject": subject, "Link": s.ticketLink("/admin/support/" + id.String())}
|
|
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T("email.support_admin.subject", data), Body: l.T("email.support_admin.body", data)}); err != nil {
|
|
slog.WarnContext(ctx, "support: mail to admins failed", "ticket", id, "err", err)
|
|
}
|
|
}
|
|
|
|
// mailTicketOwner tells the account that its ticket was answered.
|
|
func (s *Server) mailTicketOwner(ctx context.Context, t store.GetSupportTicketRow) {
|
|
if s.smtp == nil {
|
|
return
|
|
}
|
|
var locale string
|
|
_ = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
u, err := q.GetUser(ctx, t.UserID)
|
|
locale = deref(u.Locale)
|
|
return err
|
|
})
|
|
l := s.catalog.Match(locale)
|
|
data := map[string]any{"Subject": t.Subject, "Link": s.ticketLink("/support/" + t.ID.String())}
|
|
if err := s.smtp.Send(ctx, notify.Mail{To: []string{t.UserEmail}, Subject: l.T("email.support_reply.subject", data), Body: l.T("email.support_reply.body", data)}); err != nil {
|
|
slog.WarnContext(ctx, "support: mail to account failed", "ticket", t.ID, "err", err)
|
|
}
|
|
}
|
|
|
|
// Pages.
|
|
|
|
func toWebTicket(v supportTicketView) web.SupportTicket {
|
|
t := web.SupportTicket{ID: v.ID.String(), Subject: v.Subject, Status: v.Status, User: v.User, Updated: v.UpdatedAt.UTC().Format(timeLayout)}
|
|
if v.Org != nil {
|
|
t.Org = *v.Org
|
|
}
|
|
for _, r := range v.References {
|
|
t.References = append(t.References, web.SupportReference{Kind: r.Kind, Name: r.Name})
|
|
}
|
|
for _, m := range v.Messages {
|
|
html, err := web.RenderMarkdown(m.Body)
|
|
if err != nil {
|
|
html = ""
|
|
}
|
|
t.Messages = append(t.Messages, web.SupportMessage{FromStaff: m.FromStaff, Author: m.Author, HTML: html, At: m.CreatedAt.UTC().Format(timeLayout)})
|
|
}
|
|
return t
|
|
}
|
|
|
|
// supportMe is the console frame of the support pages, which accounts
|
|
// reach also while restricted.
|
|
func (s *Server) supportMe(c *gin.Context) (*auth.Session, web.Me, *principal, bool) {
|
|
sess := auth.Current(c)
|
|
if sess == nil {
|
|
c.Redirect(http.StatusSeeOther, "/login?next="+c.Request.URL.Path)
|
|
return nil, web.Me{}, nil, false
|
|
}
|
|
me, p, err := s.consoleMe(c, sess)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return nil, web.Me{}, nil, false
|
|
}
|
|
if !me.Support {
|
|
web.Render(c, http.StatusOK, web.SupportDisabledPage(s.pageFor(c, "support.title"), me))
|
|
return nil, web.Me{}, nil, false
|
|
}
|
|
return sess, me, p, true
|
|
}
|
|
|
|
// supportOptions lists what of the active organization a new ticket can
|
|
// point at, as far as the account may read it.
|
|
func (s *Server) supportOptions(ctx context.Context, p *principal) (web.SupportOptions, error) {
|
|
var o web.SupportOptions
|
|
if p == nil {
|
|
return o, nil
|
|
}
|
|
o.Org = p.Org.Name
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
if p.Grants.Can(authz.MonitorsRead) {
|
|
rows, err := q.SupportOptionsMonitors(ctx, p.Org.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, r := range rows {
|
|
o.Monitors = append(o.Monitors, web.SupportOption{ID: r.ID.String(), Name: r.Name})
|
|
}
|
|
}
|
|
if p.Grants.Can(authz.NotificationsRead) {
|
|
chans, err := q.SupportOptionsChannels(ctx, p.Org.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, r := range chans {
|
|
o.Channels = append(o.Channels, web.SupportOption{ID: r.ID.String(), Name: r.Name + " (" + r.Type + ")"})
|
|
}
|
|
groups, err := q.SupportOptionsAlertGroups(ctx, p.Org.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, r := range groups {
|
|
o.AlertGroups = append(o.AlertGroups, web.SupportOption{ID: r.ID.String(), Name: r.Name})
|
|
}
|
|
}
|
|
if p.Grants.Can(authz.StatusPagesRead) {
|
|
rows, err := q.SupportOptionsStatusPages(ctx, p.Org.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, r := range rows {
|
|
o.StatusPages = append(o.StatusPages, web.SupportOption{ID: r.ID.String(), Name: r.Title})
|
|
}
|
|
}
|
|
if p.Grants.Can(authz.IncidentsRead) {
|
|
rows, err := q.SupportOptionsIncidents(ctx, p.Org.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, r := range rows {
|
|
name := r.MonitorName
|
|
if r.Title != "" {
|
|
name = r.Title + " · " + name
|
|
}
|
|
o.Incidents = append(o.Incidents, web.SupportOption{ID: r.ID.String(), Name: name + " · " + r.StartedAt.UTC().Format(timeLayout)})
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
return o, err
|
|
}
|
|
|
|
func (s *Server) supportPage(c *gin.Context) {
|
|
sess, me, p, ok := s.supportMe(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
opts, err := s.supportOptions(ctx, p)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
var rows []store.SupportTicket
|
|
if err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
|
var err error
|
|
rows, err = q.ListUserSupportTickets(ctx, sess.UserID)
|
|
return err
|
|
}); err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
tickets := make([]web.SupportTicket, len(rows))
|
|
for i, t := range rows {
|
|
tickets[i] = toWebTicket(supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, UpdatedAt: t.UpdatedAt})
|
|
}
|
|
web.Render(c, http.StatusOK, web.SupportPage(s.pageFor(c, "support.title"), me, tickets, opts))
|
|
}
|
|
|
|
func (s *Server) supportTicketPage(c *gin.Context) {
|
|
sess, me, _, ok := s.supportMe(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
s.renderTicket(c, me, tenant.User(sess.UserID), false)
|
|
}
|
|
|
|
func (s *Server) renderTicket(c *gin.Context, me web.Me, scope tenant.Scope, staff bool) {
|
|
id, err := uuid.Parse(c.Param("id"))
|
|
var v supportTicketView
|
|
if err == nil {
|
|
v, err = s.loadTicket(c.Request.Context(), scope, id, staff)
|
|
}
|
|
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if err != nil {
|
|
back := "/support"
|
|
if staff {
|
|
back = "/admin/support"
|
|
}
|
|
c.Redirect(http.StatusSeeOther, back)
|
|
return
|
|
}
|
|
var account *web.SupportAccount
|
|
if staff {
|
|
a, err := s.ticketAccount(c.Request.Context(), id)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
account = &a
|
|
}
|
|
web.Render(c, http.StatusOK, web.SupportTicketPage(s.pageFor(c, "support.title"), me, toWebTicket(v), account))
|
|
}
|
|
|
|
func (s *Server) adminSupportPage(c *gin.Context) {
|
|
me, ok := s.adminMe(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
status := supportStatusFilter(c)
|
|
rows, err := s.supportTickets(c.Request.Context(), status)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
tickets := make([]web.SupportTicket, len(rows))
|
|
for i, t := range rows {
|
|
tickets[i] = toWebTicket(supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, Org: t.OrgName, User: t.UserEmail, UpdatedAt: t.UpdatedAt})
|
|
}
|
|
filter := "all"
|
|
if status != nil {
|
|
filter = *status
|
|
}
|
|
settings := s.supportSettings(c.Request.Context())
|
|
web.Render(c, http.StatusOK, web.AdminSupportPage(s.pageFor(c, "support.admin_title"), me, tickets, filter, web.SupportSettings{Enabled: settings.Enabled, MaxOpen: settings.MaxOpen}))
|
|
}
|
|
|
|
func (s *Server) adminSupportTicketPage(c *gin.Context) {
|
|
me, ok := s.adminMe(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
s.renderTicket(c, me, tenant.System(), true)
|
|
}
|
|
|
|
// ticketAccount gathers what admins need to answer a ticket: the account,
|
|
// its organizations with their limits and usage, and its other tickets.
|
|
func (s *Server) ticketAccount(ctx context.Context, ticket uuid.UUID) (web.SupportAccount, error) {
|
|
var a web.SupportAccount
|
|
platform := s.platformLimits(ctx)
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
t, err := q.GetSupportTicket(ctx, ticket)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
u, err := q.GetUser(ctx, t.UserID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
a = web.SupportAccount{
|
|
ID: u.ID.String(), Email: u.Email, Name: u.DisplayName, Created: u.CreatedAt.UTC().Format(timeLayout),
|
|
Verified: u.EmailVerifiedAt != nil, TOTP: u.TotpEnabledAt != nil, Password: u.PasswordHash != nil,
|
|
Admin: u.IsAdmin, Locale: deref(u.Locale),
|
|
}
|
|
if u.DisabledAt != nil {
|
|
a.Suspended = true
|
|
a.SuspendedReason = u.DisabledReason
|
|
}
|
|
a.OrgLimit = platform.OrgsPerAccount
|
|
if u.LimitOrgs != nil {
|
|
a.OrgLimit = int(*u.LimitOrgs)
|
|
}
|
|
owned, err := q.CountOwnedOrgs(ctx, u.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
a.OrgsOwned = int(owned)
|
|
if a.OpenTickets, err = q.CountOpenSupportTickets(ctx, u.ID); err != nil {
|
|
return err
|
|
}
|
|
ms, err := q.UserMemberships(ctx, u.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, m := range ms {
|
|
o, err := q.GetOrg(ctx, m.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
mon, err := q.CountMonitors(ctx, o.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pages, err := q.CountStatusPages(ctx, o.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
l := s.orgLimits(ctx, o)
|
|
org := web.SupportOrg{
|
|
Name: o.Name, Slug: o.Slug, Owner: m.IsOwner, Current: t.OrgID != nil && *t.OrgID == o.ID,
|
|
Monitors: int(mon), MonitorLimit: l.Monitors, StatusPages: int(pages), StatusPageLimit: l.StatusPages,
|
|
RegionsPerMonitor: l.RegionsPerMonitor,
|
|
}
|
|
if o.SuspendedAt != nil {
|
|
org.Suspended = true
|
|
org.SuspendedReason = o.SuspendedReason
|
|
}
|
|
a.Orgs = append(a.Orgs, org)
|
|
}
|
|
return nil
|
|
})
|
|
return a, err
|
|
}
|