mirror of
https://github.com/multica-ai/multica.git
synced 2026-07-13 13:18:56 +02:00
* feat(analytics): add PostHog client with async batch shipping Introduces server/internal/analytics, the shipping layer for the product funnel defined in docs/analytics.md. Capture is non-blocking — events are enqueued into a bounded channel and a background worker batches them to PostHog's /batch/ endpoint. A broken backend drops events rather than blocking request handlers. Local dev and self-hosted instances run a noop client until the operator sets POSTHOG_API_KEY. This is PR 1 of MUL-1122; signup and workspace_created emission land in the follow-up commit so this change is independently reviewable. * feat(server): emit signup and workspace_created analytics events Wires analytics.Client through handler.New and main, then emits the first two funnel events: - signup fires from findOrCreateUser (which now reports isNew), covering both the verification-code and Google OAuth entry points — a single emission site guarantees Google signups aren't missed. - workspace_created fires after the CreateWorkspace transaction commits, with is_first_workspace computed from a post-commit ListWorkspaces count so we can distinguish fresh-user activation from returning-user expansion. Tests use analytics.NoopClient so nothing ships from test runs. PR 1 of MUL-1122; runtime_registered and issue_executed follow in later PRs per the plan. * refactor(analytics): drop is_first_workspace from workspace_created Stamping "is this the user's first workspace?" at emit time races under concurrent CreateWorkspace requests: two transactions committing close together can both read a post-commit count greater than one and both emit false. Fixing it at the SQL layer requires a schema change we don't want in PR 1. PostHog answers the same question exactly from the event stream (funnel on "first time user does X" / cohort on $initial_event), so removing the property loses no information and makes the emit side race-free. * docs(analytics): document self-host safety defaults Spell out why self-hosted instances never ship events upstream by default (empty POSTHOG_API_KEY → noop client) and explain how operators can point at their own PostHog project without any code change. * feat(analytics): emit runtime_registered, issue_executed, team_invite_* Three server-side funnel events, all gated on first-time state transitions so retries and re-runs don't inflate the WAW buckets: - runtime_registered fires from DaemonRegister when UpsertAgentRuntime reports (xmax = 0) — i.e. the row was inserted, not updated. Heartbeats and re-registrations stay silent. - issue_executed fires from CompleteTask after an atomic UPDATE issue SET first_executed_at = now() WHERE id = $1 AND first_executed_at IS NULL flips the column for the first time. Retries, re-assignments, and comment-triggered follow-up tasks hit the WHERE clause and no-op. Carries nth_issue_for_workspace so the ≥1/≥2/≥5/≥10 buckets filter without extra queries. - team_invite_sent fires from CreateInvitation and team_invite_accepted from AcceptInvitation, closing the expansion funnel. Adds a 050 migration for issue.first_executed_at plus a partial index so the workspace-scoped executed-count query doesn't scan the never-executed tail. * feat(config): surface PostHog key via /api/config Extends AppConfig with posthog_key / posthog_host sourced from env on every request (so operators can rotate the key via secret refresh without a restart). Reading the key off the server — rather than baking it into the frontend bundle via NEXT_PUBLIC_* — means self-hosted instances inherit the blank key automatically and never ship events upstream. * feat(analytics): wire posthog-js identify + UTM capture on the client Adds @multica/core/analytics — a thin wrapper around posthog-js that owns attribution capture and identity merge. Posthog-js config comes from /api/config (not NEXT_PUBLIC_*), so self-hosted instances whose server returns an empty key automatically run the SDK inert. captureSignupSource stamps a multica_signup_source cookie with UTM params and the referrer's origin (never the full referrer — that can leak OAuth code/state in the callback URL). The backend signup event reads this cookie on new-user creation. Identity flows: - auth-initializer fires identify() right after getMe() resolves, on both cookie and token paths. A getConfig/getMe race is handled by buffering a pending identify inside the analytics module and flushing it once initAnalytics finishes. - auth store calls identify() on verifyCode / loginWithGoogle / loginWithToken and resetAnalytics() on logout so the next login merges cleanly without bleeding events. * docs(analytics): describe runtime_registered, issue_executed, invite events Fills in the schema for the remaining funnel events. Captures the design commentary that belongs next to the contract rather than in a PR description — in particular why issue_executed uses the atomic first_executed_at flip instead of counting task-terminal events, and why runtime_registered relies on xmax = 0 rather than a query-then-write. * fix(analytics): drop non-atomic nth_issue_for_workspace from issue_executed Computing the workspace's Nth-issue ordinal at emit time is not atomic under concurrent first-completions — two transactions can both run MarkIssueFirstExecuted, then both run CountExecutedIssuesInWorkspace, and both observe count=1 before either has committed, so both events go out stamped as n=1. Serialising it would mean a per-workspace advisory lock or a SERIALIZABLE-isolated tx; PostHog answers the same question exactly at query time via row_number() partitioned by workspace_id, so the emit-time property adds risk without adding information. Removes the property from analytics.IssueExecuted, deletes the unused CountExecutedIssuesInWorkspace query, and regenerates sqlc. The partial index stays — any future workspace-scoped executed-issue query will want it. * fix(analytics): wire $pageview and harden signup_source cookie payload Two frontend fixes from the PR review: - PageviewTracker, mounted under WebProviders, fires capturePageview on every Next.js App Router path / query-string change. Without this the capturePageview helper in @multica/core/analytics was never called and the acquisition funnel's / → signup step was empty. - captureSignupSource now caps each UTM / referrer value at 96 chars *before* JSON.stringify, and drops the whole cookie when the serialised payload still exceeds 512 chars. Previously the overall slice(0, 256) could leave a half-JSON string on the wire that neither the backend nor PostHog could parse. Both capturePageview and identify now buffer a single pending call when fired before initAnalytics resolves — otherwise the initial "/" pageview and same-turn login identify race the /api/config fetch and get dropped. resetAnalytics clears both buffers so a logout→login cycle stays clean. * fix(analytics): URL-decode signup_source cookie on read Go does not URL-decode Cookie.Value automatically, so the frontend's JSON-then-encodeURIComponent payload was landing in PostHog as percent-encoded garbage (%7B%22utm_source...). Unescape on read so the backend receives the original JSON string the frontend intended, and drop values that fail to decode or exceed the server-side cap — sending truncated garbage is worse than sending nothing. Oversized-cookie guard matches the frontend's SIGNUP_SOURCE_MAX_LEN. * docs(analytics): reflect nth-issue drop, $pageview wiring, cookie encoding Pulls the schema doc back in line with the code: issue_executed no longer advertises nth_issue_for_workspace (with a note about why PostHog derives it at query time instead), the frontend $pageview section names the actual PageviewTracker component that fires it, and the signup_source section documents the per-value cap / overall drop rule and the encode-on-write / decode-on-read contract. --------- Co-authored-by: Jiang Bohan <bhjiang@outlook.com>
615 lines
18 KiB
Go
615 lines
18 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
"github.com/multica-ai/multica/server/internal/analytics"
|
|
"github.com/multica-ai/multica/server/internal/logger"
|
|
db "github.com/multica-ai/multica/server/pkg/db/generated"
|
|
"github.com/multica-ai/multica/server/pkg/protocol"
|
|
)
|
|
|
|
var nonAlpha = regexp.MustCompile(`[^a-zA-Z]`)
|
|
var workspaceSlugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
|
|
|
|
// generateIssuePrefix produces a 2-5 char uppercase prefix from a workspace name.
|
|
// Examples: "Jiayuan's Workspace" → "JIA", "My Team" → "MYT", "AB" → "AB".
|
|
func generateIssuePrefix(name string) string {
|
|
letters := nonAlpha.ReplaceAllString(name, "")
|
|
if len(letters) == 0 {
|
|
return "WS"
|
|
}
|
|
letters = strings.ToUpper(letters)
|
|
if len(letters) > 3 {
|
|
letters = letters[:3]
|
|
}
|
|
return letters
|
|
}
|
|
|
|
type WorkspaceResponse struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Slug string `json:"slug"`
|
|
Description *string `json:"description"`
|
|
Context *string `json:"context"`
|
|
Settings any `json:"settings"`
|
|
Repos any `json:"repos"`
|
|
IssuePrefix string `json:"issue_prefix"`
|
|
CreatedAt string `json:"created_at"`
|
|
UpdatedAt string `json:"updated_at"`
|
|
}
|
|
|
|
func workspaceToResponse(w db.Workspace) WorkspaceResponse {
|
|
var settings any
|
|
if w.Settings != nil {
|
|
json.Unmarshal(w.Settings, &settings)
|
|
}
|
|
if settings == nil {
|
|
settings = map[string]any{}
|
|
}
|
|
var repos any
|
|
if w.Repos != nil {
|
|
json.Unmarshal(w.Repos, &repos)
|
|
}
|
|
if repos == nil {
|
|
repos = []any{}
|
|
}
|
|
return WorkspaceResponse{
|
|
ID: uuidToString(w.ID),
|
|
Name: w.Name,
|
|
Slug: w.Slug,
|
|
Description: textToPtr(w.Description),
|
|
Context: textToPtr(w.Context),
|
|
Settings: settings,
|
|
Repos: repos,
|
|
IssuePrefix: w.IssuePrefix,
|
|
CreatedAt: timestampToString(w.CreatedAt),
|
|
UpdatedAt: timestampToString(w.UpdatedAt),
|
|
}
|
|
}
|
|
|
|
type MemberResponse struct {
|
|
ID string `json:"id"`
|
|
WorkspaceID string `json:"workspace_id"`
|
|
UserID string `json:"user_id"`
|
|
Role string `json:"role"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
|
|
func memberToResponse(m db.Member) MemberResponse {
|
|
return MemberResponse{
|
|
ID: uuidToString(m.ID),
|
|
WorkspaceID: uuidToString(m.WorkspaceID),
|
|
UserID: uuidToString(m.UserID),
|
|
Role: m.Role,
|
|
CreatedAt: timestampToString(m.CreatedAt),
|
|
}
|
|
}
|
|
|
|
func (h *Handler) ListWorkspaces(w http.ResponseWriter, r *http.Request) {
|
|
userID, ok := requireUserID(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
workspaces, err := h.Queries.ListWorkspaces(r.Context(), parseUUID(userID))
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to list workspaces")
|
|
return
|
|
}
|
|
|
|
resp := make([]WorkspaceResponse, len(workspaces))
|
|
for i, ws := range workspaces {
|
|
resp[i] = workspaceToResponse(ws)
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
func (h *Handler) GetWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
id := workspaceIDFromURL(r, "id")
|
|
|
|
ws, err := h.Queries.GetWorkspace(r.Context(), parseUUID(id))
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "workspace not found")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, workspaceToResponse(ws))
|
|
}
|
|
|
|
type CreateWorkspaceRequest struct {
|
|
Name string `json:"name"`
|
|
Slug string `json:"slug"`
|
|
Description *string `json:"description"`
|
|
Context *string `json:"context"`
|
|
IssuePrefix *string `json:"issue_prefix"`
|
|
}
|
|
|
|
func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
userID, ok := requireUserID(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var req CreateWorkspaceRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
|
|
req.Name = strings.TrimSpace(req.Name)
|
|
req.Slug = strings.ToLower(strings.TrimSpace(req.Slug))
|
|
if req.Name == "" || req.Slug == "" {
|
|
writeError(w, http.StatusBadRequest, "name and slug are required")
|
|
return
|
|
}
|
|
if !workspaceSlugPattern.MatchString(req.Slug) {
|
|
writeError(w, http.StatusBadRequest, "slug must contain only lowercase letters, numbers, and hyphens")
|
|
return
|
|
}
|
|
if isReservedSlug(req.Slug) {
|
|
writeError(w, http.StatusBadRequest, "slug is reserved")
|
|
return
|
|
}
|
|
|
|
tx, err := h.TxStarter.Begin(r.Context())
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to create workspace")
|
|
return
|
|
}
|
|
defer tx.Rollback(r.Context())
|
|
|
|
issuePrefix := generateIssuePrefix(req.Name)
|
|
if req.IssuePrefix != nil && strings.TrimSpace(*req.IssuePrefix) != "" {
|
|
issuePrefix = strings.ToUpper(strings.TrimSpace(*req.IssuePrefix))
|
|
}
|
|
|
|
qtx := h.Queries.WithTx(tx)
|
|
ws, err := qtx.CreateWorkspace(r.Context(), db.CreateWorkspaceParams{
|
|
Name: req.Name,
|
|
Slug: req.Slug,
|
|
Description: ptrToText(req.Description),
|
|
Context: ptrToText(req.Context),
|
|
IssuePrefix: issuePrefix,
|
|
})
|
|
if err != nil {
|
|
if isUniqueViolation(err) {
|
|
writeError(w, http.StatusConflict, "workspace slug already exists")
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "failed to create workspace: "+err.Error())
|
|
return
|
|
}
|
|
|
|
_, err = qtx.CreateMember(r.Context(), db.CreateMemberParams{
|
|
WorkspaceID: ws.ID,
|
|
UserID: parseUUID(userID),
|
|
Role: "owner",
|
|
})
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to add owner: "+err.Error())
|
|
return
|
|
}
|
|
|
|
if err := tx.Commit(r.Context()); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to create workspace")
|
|
return
|
|
}
|
|
|
|
// "Is this the user's first workspace?" is derived in PostHog by looking
|
|
// at whether they have a prior workspace_created event, not stamped at
|
|
// emit time. Stamping here would race under concurrent creates without
|
|
// a schema change, and the event stream answers the question exactly.
|
|
h.Analytics.Capture(analytics.WorkspaceCreated(userID, uuidToString(ws.ID)))
|
|
|
|
slog.Info("workspace created", append(logger.RequestAttrs(r), "workspace_id", uuidToString(ws.ID), "name", ws.Name, "slug", ws.Slug)...)
|
|
writeJSON(w, http.StatusCreated, workspaceToResponse(ws))
|
|
}
|
|
|
|
type UpdateWorkspaceRequest struct {
|
|
Name *string `json:"name"`
|
|
Description *string `json:"description"`
|
|
Context *string `json:"context"`
|
|
Settings any `json:"settings"`
|
|
Repos any `json:"repos"`
|
|
IssuePrefix *string `json:"issue_prefix"`
|
|
}
|
|
|
|
func (h *Handler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
id := workspaceIDFromURL(r, "id")
|
|
|
|
var req UpdateWorkspaceRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
|
|
params := db.UpdateWorkspaceParams{
|
|
ID: parseUUID(id),
|
|
}
|
|
if req.Name != nil {
|
|
name := strings.TrimSpace(*req.Name)
|
|
if name == "" {
|
|
writeError(w, http.StatusBadRequest, "name is required")
|
|
return
|
|
}
|
|
params.Name = pgtype.Text{String: name, Valid: true}
|
|
}
|
|
if req.Description != nil {
|
|
params.Description = pgtype.Text{String: *req.Description, Valid: true}
|
|
}
|
|
if req.Context != nil {
|
|
params.Context = pgtype.Text{String: *req.Context, Valid: true}
|
|
}
|
|
if req.Settings != nil {
|
|
s, _ := json.Marshal(req.Settings)
|
|
params.Settings = s
|
|
}
|
|
if req.Repos != nil {
|
|
reposJSON, _ := json.Marshal(req.Repos)
|
|
params.Repos = reposJSON
|
|
}
|
|
if req.IssuePrefix != nil {
|
|
prefix := strings.ToUpper(strings.TrimSpace(*req.IssuePrefix))
|
|
if prefix != "" {
|
|
params.IssuePrefix = pgtype.Text{String: prefix, Valid: true}
|
|
}
|
|
}
|
|
|
|
ws, err := h.Queries.UpdateWorkspace(r.Context(), params)
|
|
if err != nil {
|
|
slog.Warn("update workspace failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", id)...)
|
|
writeError(w, http.StatusInternalServerError, "failed to update workspace: "+err.Error())
|
|
return
|
|
}
|
|
|
|
slog.Info("workspace updated", append(logger.RequestAttrs(r), "workspace_id", id)...)
|
|
userID := requestUserID(r)
|
|
h.publish(protocol.EventWorkspaceUpdated, id, "member", userID, map[string]any{"workspace": workspaceToResponse(ws)})
|
|
|
|
writeJSON(w, http.StatusOK, workspaceToResponse(ws))
|
|
}
|
|
|
|
func (h *Handler) ListMembers(w http.ResponseWriter, r *http.Request) {
|
|
workspaceID := chi.URLParam(r, "id")
|
|
if _, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found"); !ok {
|
|
return
|
|
}
|
|
|
|
members, err := h.Queries.ListMembers(r.Context(), parseUUID(workspaceID))
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to list members")
|
|
return
|
|
}
|
|
|
|
resp := make([]MemberResponse, len(members))
|
|
for i, m := range members {
|
|
resp[i] = memberToResponse(m)
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
type MemberWithUserResponse struct {
|
|
ID string `json:"id"`
|
|
WorkspaceID string `json:"workspace_id"`
|
|
UserID string `json:"user_id"`
|
|
Role string `json:"role"`
|
|
CreatedAt string `json:"created_at"`
|
|
Name string `json:"name"`
|
|
Email string `json:"email"`
|
|
AvatarURL *string `json:"avatar_url"`
|
|
}
|
|
|
|
func (h *Handler) ListMembersWithUser(w http.ResponseWriter, r *http.Request) {
|
|
workspaceID := workspaceIDFromURL(r, "id")
|
|
|
|
members, err := h.Queries.ListMembersWithUser(r.Context(), parseUUID(workspaceID))
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to list members")
|
|
return
|
|
}
|
|
|
|
resp := make([]MemberWithUserResponse, len(members))
|
|
for i, m := range members {
|
|
resp[i] = MemberWithUserResponse{
|
|
ID: uuidToString(m.ID),
|
|
WorkspaceID: uuidToString(m.WorkspaceID),
|
|
UserID: uuidToString(m.UserID),
|
|
Role: m.Role,
|
|
CreatedAt: timestampToString(m.CreatedAt),
|
|
Name: m.UserName,
|
|
Email: m.UserEmail,
|
|
AvatarURL: textToPtr(m.UserAvatarUrl),
|
|
}
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
type CreateMemberRequest struct {
|
|
Email string `json:"email"`
|
|
Role string `json:"role"`
|
|
}
|
|
|
|
func memberWithUserResponse(member db.Member, user db.User) MemberWithUserResponse {
|
|
return MemberWithUserResponse{
|
|
ID: uuidToString(member.ID),
|
|
WorkspaceID: uuidToString(member.WorkspaceID),
|
|
UserID: uuidToString(member.UserID),
|
|
Role: member.Role,
|
|
CreatedAt: timestampToString(member.CreatedAt),
|
|
Name: user.Name,
|
|
Email: user.Email,
|
|
AvatarURL: textToPtr(user.AvatarUrl),
|
|
}
|
|
}
|
|
|
|
func normalizeMemberRole(role string) (string, bool) {
|
|
if role == "" {
|
|
return "member", true
|
|
}
|
|
|
|
role = strings.TrimSpace(role)
|
|
switch role {
|
|
case "owner", "admin", "member":
|
|
return role, true
|
|
default:
|
|
return "", false
|
|
}
|
|
}
|
|
|
|
func (h *Handler) CreateMember(w http.ResponseWriter, r *http.Request) {
|
|
workspaceID := workspaceIDFromURL(r, "id")
|
|
requester, ok := h.workspaceMember(w, r, workspaceID)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var req CreateMemberRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
|
|
email := strings.ToLower(strings.TrimSpace(req.Email))
|
|
if email == "" {
|
|
writeError(w, http.StatusBadRequest, "email is required")
|
|
return
|
|
}
|
|
|
|
role, valid := normalizeMemberRole(req.Role)
|
|
if !valid {
|
|
writeError(w, http.StatusBadRequest, "invalid member role")
|
|
return
|
|
}
|
|
if role == "owner" && requester.Role != "owner" {
|
|
writeError(w, http.StatusForbidden, "insufficient permissions")
|
|
return
|
|
}
|
|
|
|
user, err := h.Queries.GetUserByEmail(r.Context(), email)
|
|
if err != nil {
|
|
if isNotFound(err) {
|
|
// Auto-create user with email so they can be invited before signing up
|
|
user, err = h.Queries.CreateUser(r.Context(), db.CreateUserParams{
|
|
Name: email,
|
|
Email: email,
|
|
})
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to create user")
|
|
return
|
|
}
|
|
} else {
|
|
writeError(w, http.StatusInternalServerError, "failed to load user")
|
|
return
|
|
}
|
|
}
|
|
|
|
member, err := h.Queries.CreateMember(r.Context(), db.CreateMemberParams{
|
|
WorkspaceID: parseUUID(workspaceID),
|
|
UserID: user.ID,
|
|
Role: role,
|
|
})
|
|
if err != nil {
|
|
if isUniqueViolation(err) {
|
|
writeError(w, http.StatusConflict, "user is already a member")
|
|
return
|
|
}
|
|
slog.Warn("create member failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID, "email", email)...)
|
|
writeError(w, http.StatusInternalServerError, "failed to create member")
|
|
return
|
|
}
|
|
|
|
slog.Info("member added", append(logger.RequestAttrs(r), "member_id", uuidToString(member.ID), "workspace_id", workspaceID, "email", email, "role", role)...)
|
|
userID := requestUserID(r)
|
|
eventPayload := map[string]any{"member": memberWithUserResponse(member, user)}
|
|
if ws, err := h.Queries.GetWorkspace(r.Context(), parseUUID(workspaceID)); err == nil {
|
|
eventPayload["workspace_name"] = ws.Name
|
|
}
|
|
h.publish(protocol.EventMemberAdded, workspaceID, "member", userID, eventPayload)
|
|
|
|
writeJSON(w, http.StatusCreated, memberWithUserResponse(member, user))
|
|
}
|
|
|
|
type UpdateMemberRequest struct {
|
|
Role string `json:"role"`
|
|
}
|
|
|
|
func (h *Handler) UpdateMember(w http.ResponseWriter, r *http.Request) {
|
|
workspaceID := workspaceIDFromURL(r, "id")
|
|
requester, ok := h.workspaceMember(w, r, workspaceID)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
memberID := chi.URLParam(r, "memberId")
|
|
target, err := h.Queries.GetMember(r.Context(), parseUUID(memberID))
|
|
if err != nil || uuidToString(target.WorkspaceID) != workspaceID {
|
|
writeError(w, http.StatusNotFound, "member not found")
|
|
return
|
|
}
|
|
|
|
var req UpdateMemberRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
if strings.TrimSpace(req.Role) == "" {
|
|
writeError(w, http.StatusBadRequest, "role is required")
|
|
return
|
|
}
|
|
|
|
role, valid := normalizeMemberRole(req.Role)
|
|
if !valid {
|
|
writeError(w, http.StatusBadRequest, "invalid member role")
|
|
return
|
|
}
|
|
|
|
if (target.Role == "owner" || role == "owner") && requester.Role != "owner" {
|
|
writeError(w, http.StatusForbidden, "insufficient permissions")
|
|
return
|
|
}
|
|
|
|
if target.Role == "owner" && role != "owner" {
|
|
members, err := h.Queries.ListMembers(r.Context(), target.WorkspaceID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to update member")
|
|
return
|
|
}
|
|
if countOwners(members) <= 1 {
|
|
writeError(w, http.StatusBadRequest, "workspace must have at least one owner")
|
|
return
|
|
}
|
|
}
|
|
|
|
updatedMember, err := h.Queries.UpdateMemberRole(r.Context(), db.UpdateMemberRoleParams{
|
|
ID: target.ID,
|
|
Role: role,
|
|
})
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to update member")
|
|
return
|
|
}
|
|
|
|
user, err := h.Queries.GetUser(r.Context(), updatedMember.UserID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to load member")
|
|
return
|
|
}
|
|
|
|
userID := requestUserID(r)
|
|
h.publish(protocol.EventMemberUpdated, workspaceID, "member", userID, map[string]any{
|
|
"member": memberWithUserResponse(updatedMember, user),
|
|
})
|
|
|
|
writeJSON(w, http.StatusOK, memberWithUserResponse(updatedMember, user))
|
|
}
|
|
|
|
func (h *Handler) DeleteMember(w http.ResponseWriter, r *http.Request) {
|
|
workspaceID := workspaceIDFromURL(r, "id")
|
|
requester, ok := h.workspaceMember(w, r, workspaceID)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
memberID := chi.URLParam(r, "memberId")
|
|
target, err := h.Queries.GetMember(r.Context(), parseUUID(memberID))
|
|
if err != nil || uuidToString(target.WorkspaceID) != workspaceID {
|
|
writeError(w, http.StatusNotFound, "member not found")
|
|
return
|
|
}
|
|
|
|
if target.Role == "owner" && requester.Role != "owner" {
|
|
writeError(w, http.StatusForbidden, "insufficient permissions")
|
|
return
|
|
}
|
|
|
|
if target.Role == "owner" {
|
|
members, err := h.Queries.ListMembers(r.Context(), target.WorkspaceID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to delete member")
|
|
return
|
|
}
|
|
if countOwners(members) <= 1 {
|
|
writeError(w, http.StatusBadRequest, "workspace must have at least one owner")
|
|
return
|
|
}
|
|
}
|
|
|
|
if err := h.Queries.DeleteMember(r.Context(), target.ID); err != nil {
|
|
slog.Warn("delete member failed", append(logger.RequestAttrs(r), "error", err, "member_id", memberID, "workspace_id", workspaceID)...)
|
|
writeError(w, http.StatusInternalServerError, "failed to delete member")
|
|
return
|
|
}
|
|
|
|
slog.Info("member removed", append(logger.RequestAttrs(r), "member_id", uuidToString(target.ID), "workspace_id", workspaceID, "user_id", uuidToString(target.UserID))...)
|
|
userID := requestUserID(r)
|
|
h.publish(protocol.EventMemberRemoved, workspaceID, "member", userID, map[string]any{
|
|
"member_id": uuidToString(target.ID),
|
|
"workspace_id": workspaceID,
|
|
"user_id": uuidToString(target.UserID),
|
|
})
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *Handler) LeaveWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
workspaceID := workspaceIDFromURL(r, "id")
|
|
member, ok := h.workspaceMember(w, r, workspaceID)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
if member.Role == "owner" {
|
|
members, err := h.Queries.ListMembers(r.Context(), member.WorkspaceID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "failed to leave workspace")
|
|
return
|
|
}
|
|
if countOwners(members) <= 1 {
|
|
writeError(w, http.StatusBadRequest, "workspace must have at least one owner")
|
|
return
|
|
}
|
|
}
|
|
|
|
if err := h.Queries.DeleteMember(r.Context(), member.ID); err != nil {
|
|
slog.Warn("leave workspace failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
|
|
writeError(w, http.StatusInternalServerError, "failed to leave workspace")
|
|
return
|
|
}
|
|
|
|
slog.Info("member removed", append(logger.RequestAttrs(r), "member_id", uuidToString(member.ID), "workspace_id", workspaceID, "user_id", uuidToString(member.UserID))...)
|
|
userID := requestUserID(r)
|
|
h.publish(protocol.EventMemberRemoved, workspaceID, "member", userID, map[string]any{
|
|
"member_id": uuidToString(member.ID),
|
|
"workspace_id": workspaceID,
|
|
"user_id": uuidToString(member.UserID),
|
|
})
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
|
|
workspaceID := workspaceIDFromURL(r, "id")
|
|
|
|
if err := h.Queries.DeleteWorkspace(r.Context(), parseUUID(workspaceID)); err != nil {
|
|
slog.Warn("delete workspace failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
|
|
writeError(w, http.StatusInternalServerError, "failed to delete workspace")
|
|
return
|
|
}
|
|
|
|
slog.Info("workspace deleted", append(logger.RequestAttrs(r), "workspace_id", workspaceID)...)
|
|
h.publish(protocol.EventWorkspaceDeleted, workspaceID, "member", requestUserID(r), map[string]any{
|
|
"workspace_id": workspaceID,
|
|
})
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|