From 62201a2dd339a57e04353b3ad2423de3ffd4fe9e Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 19 Sep 2026 09:24:09 -0700 Subject: [PATCH 1/3] feat: let each member choose, reorder and persist the contact list's columns (custom fields included) and sort on any of them: a user_view_preferences table (migration 000187) behind GET/PUT/DELETE /v1/me/views/:view, a column registry that renders the contacts and campaign Leads tables from a saved layout, a Columns chooser with drag reorder and a Sort menu on both toolbars, click-to-sort headers, sort_by custom: plus company and phone sorts in POST /contacts/search resolved once for Search and SearchIDs with a nullable keyset cursor, and the contacts guide, API reference, openapi, error codes and export-import docs updated --- cmd/backend/main.go | 15 +- docs/content/docs/api/endpoints.mdx | 1 + docs/content/docs/api/error-codes.mdx | 3 + docs/content/docs/api/reference/contacts.mdx | 2 +- docs/content/docs/guides/contacts-crm.mdx | 14 +- .../docs/guides/workspace-export-import.mdx | 1 + docs/public/openapi.json | 2 +- internal/api/handler/handler.go | 3 + internal/api/handler/view_preferences.go | 83 +++ internal/api/routes.go | 7 + internal/app/contact/handler.go | 18 + internal/app/orgtransfer/spec.go | 1 + internal/app/viewprefs/service.go | 133 +++++ internal/app/viewprefs/service_test.go | 52 ++ .../000187_user_view_preferences.down.sql | 1 + .../000187_user_view_preferences.up.sql | 23 + internal/models/contact.go | 4 +- internal/models/view_preferences.go | 63 +++ .../contact_custom_sort_live_test.go | 190 +++++++ internal/repository/contact_sort_test.go | 52 ++ internal/repository/pg_contact.go | 90 ++-- internal/repository/pg_view_preferences.go | 94 ++++ .../components/app/contacts/ContactsTable.tsx | 503 ++++-------------- .../components/app/contacts/ViewControls.tsx | 288 ++++++++++ web/src/components/app/contacts/cells.tsx | 149 ++++++ .../components/app/contacts/columns.test.ts | 47 ++ web/src/components/app/contacts/columns.tsx | 444 ++++++++++++++++ .../components/app/contacts/useContactView.ts | 54 ++ web/src/lib/api/client/app/views/views.ts | 33 ++ .../api/hooks/app/views/useViewPreferences.ts | 107 ++++ .../app/contacts/search-contacts.types.ts | 13 +- .../api/models/app/views/ViewPreferences.ts | 28 + 32 files changed, 2082 insertions(+), 436 deletions(-) create mode 100644 internal/api/handler/view_preferences.go create mode 100644 internal/app/viewprefs/service.go create mode 100644 internal/app/viewprefs/service_test.go create mode 100644 internal/infrastructure/db/migrations/000187_user_view_preferences.down.sql create mode 100644 internal/infrastructure/db/migrations/000187_user_view_preferences.up.sql create mode 100644 internal/models/view_preferences.go create mode 100644 internal/repository/contact_custom_sort_live_test.go create mode 100644 internal/repository/contact_sort_test.go create mode 100644 internal/repository/pg_view_preferences.go create mode 100644 web/src/components/app/contacts/ViewControls.tsx create mode 100644 web/src/components/app/contacts/cells.tsx create mode 100644 web/src/components/app/contacts/columns.test.ts create mode 100644 web/src/components/app/contacts/columns.tsx create mode 100644 web/src/components/app/contacts/useContactView.ts create mode 100644 web/src/lib/api/client/app/views/views.ts create mode 100644 web/src/lib/api/hooks/app/views/useViewPreferences.ts create mode 100644 web/src/lib/api/models/app/views/ViewPreferences.ts diff --git a/cmd/backend/main.go b/cmd/backend/main.go index 6ec4bfde4..2a364d535 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -101,6 +101,7 @@ import ( "github.com/warmbly/warmbly/internal/app/unibox" "github.com/warmbly/warmbly/internal/app/updates" "github.com/warmbly/warmbly/internal/app/user" + "github.com/warmbly/warmbly/internal/app/viewprefs" warmupapp "github.com/warmbly/warmbly/internal/app/warmup" "github.com/warmbly/warmbly/internal/app/warmupcontent" "github.com/warmbly/warmbly/internal/app/webhook" @@ -314,6 +315,7 @@ func main() { var oauthService *oauth.Service var notificationService notification.Service var twofaService twofa.Service + var viewPreferencesService viewprefs.Service var contactRepoForHandler repository.ContactRepository var attachmentRepoForHandler repository.AttachmentRepository var emailImageRepoForHandler repository.EmailImageRepository @@ -1512,6 +1514,8 @@ func main() { // onto the backend's advanced service (deliverability webhooks can ingest // here too). notificationService = notification.NewService(repository.NewNotificationRepository(primaryDB.Pool), streamingPublisher) + // Saved list layouts: each member's columns and sort per dashboard list. + viewPreferencesService = viewprefs.NewService(repository.NewViewPreferencesRepository(primaryDB.Pool)) notificationService.WireDelivery(emailNotificationService, integrationServiceForHandler, userRepostory, organizationRepoForHandler) // Mobile push (APNs): device registration always works; delivery only // activates when the APNS_* env is configured. The Redis client backs @@ -1945,11 +1949,12 @@ func main() { TagService: tagService, CategoryService: categoryService, - TzService: tzService, - SocketService: socketService, - TasksService: tasksService, - NotificationService: notificationService, - TwoFAService: twofaService, + TzService: tzService, + SocketService: socketService, + TasksService: tasksService, + NotificationService: notificationService, + TwoFAService: twofaService, + ViewPreferencesService: viewPreferencesService, // API Keys APIKeyService: apiKeyService, diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index eff98b8e2..c254d126f 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -436,6 +436,7 @@ Alongside them, `api_url` is this API's own public base (for a copyable example - `POST /getaway` (websocket bootstrap) - `GET /realtime/info` - `GET /me/danger-zone`, `POST /me/danger-zone/delete`, `DELETE /me/danger-zone/delete` +- `GET /me/views/:view`, `PUT /me/views/:view`, `DELETE /me/views/:view` (the signed-in member's own column layout and sort for a dashboard list in the current workspace; `view` is `contacts` or `campaign_leads`. Personal to the session, so no API scope reaches it) - `GET /invitations`, `POST /invitations/accept` - All of `/organization/*` (create, switch, members, invitations, transfer ownership, avatar, danger zone) - `GET /website-tracking/settings`, `PATCH /website-tracking/settings`, `POST /website-tracking/settings/rotate-key` (the [website tracking](/guides/website-tracking/) snippet's consent mode, location precision, allowed hosts and retention; JWT permission `MANAGE_SETTINGS`. The rotate is bodyless and safe to repeat, each call issues a new key) diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index a0536d3a3..04988f9ea 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -76,6 +76,9 @@ Returned when the request cannot be processed due to invalid syntax. | `code` | Meaning | |--------|---------| | `invalid_lead_status` | `POST /contacts/search` or `POST /contacts/export` was given a `lead_status` that is not one of the documented values | +| `invalid_sort_by` | `POST /contacts/search` was given a `sort_by` of the form `custom:` whose key could never be a custom-field name (letters, numbers, underscores, spaces or dashes) | +| `unknown_view` | `/me/views/:view` was given a view name other than `contacts` or `campaign_leads` (answered `404`) | +| `invalid_column`, `duplicate_column`, `too_many_columns`, `invalid_sort` | `PUT /me/views/:view` was given a column id the dashboard cannot render, the same column twice, more than 64 columns, or a sort that names neither a built-in column nor a well-formed `custom:` | | `invalid_engagement` | `POST /contacts/search` or `POST /contacts/export` was given an `engagement` that is not one of the documented values | | `lead_filter_requires_campaign` | `lead_status` or `engagement` was set without exactly one `campaign_ids` entry; both filters describe a contact inside one campaign | | `unknown_verification_status` | A contact's `verification_status` is not a value any known verification service writes | diff --git a/docs/content/docs/api/reference/contacts.mdx b/docs/content/docs/api/reference/contacts.mdx index b07124b7c..87c89bdaa 100644 --- a/docs/content/docs/api/reference/contacts.mdx +++ b/docs/content/docs/api/reference/contacts.mdx @@ -40,7 +40,7 @@ Every field is optional; an empty body matches all contacts in the organization. | `created_before` | string (RFC 3339) | No | Created on or before this time. | | `updated_after` | string (RFC 3339) | No | Updated on or after this time. | | `updated_before` | string (RFC 3339) | No | Updated on or before this time. | -| `sort_by` | string | No | Sort column: `created_at` (the default), `updated_at`, `first_name`, `last_name`, `email`, or `campaign_count`. Any other value falls back to `created_at`. | +| `sort_by` | string | No | Sort column: `created_at` (the default), `updated_at`, `first_name`, `last_name`, `email`, `company`, `phone`, or `campaign_count`. `custom:` sorts on a custom field, as text, with contacts that lack the field (or have it blank) grouped last when ascending and first when descending. A custom-field name that could never exist is rejected with `invalid_sort_by`; any other unknown value falls back to `created_at`. | | `reverse` | boolean | No | Ascending when true. The default is descending. | ```json diff --git a/docs/content/docs/guides/contacts-crm.mdx b/docs/content/docs/guides/contacts-crm.mdx index 5d9a10ee0..7e3f53fc5 100644 --- a/docs/content/docs/guides/contacts-crm.mdx +++ b/docs/content/docs/guides/contacts-crm.mdx @@ -71,10 +71,22 @@ See [Personalization & expressions](/guides/expressions/) for the full templatin ## Filtering the list -A filter bar sits above the contact list. **Category**, **Segment**, **Status** and **Campaign** are always there; open one, tick values, and the list updates immediately with the matching count next to the bar. **Add filter** adds a custom-field condition (field, contains/is/starts with/ends with, value), a date-added or last-updated range, a number-of-campaigns range, the address verification verdict and, on a campaign's Leads tab, lead status and engagement. Each active filter is a pill you can reopen to change or remove with its cross; **Clear** drops them all, and **Save as segment** turns the current set into a [segment](/guides/segments/). Free-text search and sort stay in the toolbar. +A filter bar sits above the contact list. **Category**, **Segment**, **Status** and **Campaign** are always there; open one, tick values, and the list updates immediately with the matching count next to the bar. **Add filter** adds a custom-field condition (field, contains/is/starts with/ends with, value), a date-added or last-updated range, a number-of-campaigns range, the address verification verdict and, on a campaign's Leads tab, lead status and engagement. Each active filter is a pill you can reopen to change or remove with its cross; **Clear** drops them all, and **Save as segment** turns the current set into a [segment](/guides/segments/). Free-text search, sort and the column chooser stay in the toolbar. Free-text search matches first name, last name, email, company and phone. Every word you type has to match one of those, so `Test Demo` finds the contact whose first name is Test and last name is Demo, and `Demo Acme` finds everyone named Demo at Acme. Words can be in any order, and only the first six count. +## Choosing columns + +**Columns** in the toolbar opens the column chooser. Tick a column to show it, untick it to hide it, and drag the grip beside a shown column to change the order. Name is always the first column. Under **Custom fields** every custom field in the workspace is offered as a column, so a list imported from Apollo or Clay can show the fields you triage on (industry, title, employee count) without opening each contact. + +The layout is yours: it is saved to your account for this workspace, so it follows you to another browser, and a teammate looking at the same list keeps their own columns. The campaign Leads tab has its own layout, separate from the contacts page. **Reset to default** at the bottom of the chooser puts the standard columns back. + +## Sorting + +Click a column header to sort by it, and click it again to flip the direction. Text columns (name, company, phone, custom fields) start ascending; dates and counts start with the newest or largest first. The **Sort** menu in the toolbar reaches the same orderings, including columns that are hidden or that a phone screen has no room for, and every custom field in the workspace. + +A sort on a custom field orders the values as text. Contacts that do not have the field, or have it blank, are grouped at the end when ascending and at the start when descending. The sort is saved with your layout, so the list opens the way you left it. + ## Selecting rows Tick a row's checkbox to select it, or the one in the table header to select every row loaded so far. Contact lists load in pages as you scroll, so the header checkbox on its own only ever covers what is on screen. diff --git a/docs/content/docs/guides/workspace-export-import.mdx b/docs/content/docs/guides/workspace-export-import.mdx index e24d42d74..cbe4224c1 100644 --- a/docs/content/docs/guides/workspace-export-import.mdx +++ b/docs/content/docs/guides/workspace-export-import.mdx @@ -99,6 +99,7 @@ Some things belong to an instance rather than to a workspace, so they are not ap | Scheduled deletions | A pending deletion from the source must never follow the workspace to its new home | | Failure and delivery counters | A webhook endpoint's failure streak and auto-disable state, and whether a notification's email already went out, describe what happened on the source. They start fresh, so an endpoint is not pre-disabled on the new instance and a notification is not re-sent | | Sends still in flight | A campaign step handed to a worker on the source has no worker on the destination to report back, so it arrives queued and is sent there instead of waiting forever. Steps already sent keep their history | +| Personal list layouts | Which columns each member shows on the contacts list and how they sort it belongs to the person, not the workspace. Everyone starts from the default view on the new instance and picks their columns again | An import runs as one transaction. If anything fails, nothing lands and the workspace is untouched. diff --git a/docs/public/openapi.json b/docs/public/openapi.json index cef0f2f79..f329bdbb1 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -23993,7 +23993,7 @@ }, "sort_by": { "type": "string", - "description": "Sort column: created_at (the default), updated_at, first_name, last_name, email, or campaign_count. Any other value falls back to created_at." + "description": "Sort column: created_at (the default), updated_at, first_name, last_name, email, company, phone, or campaign_count. custom: sorts on a custom field as text, with contacts lacking the field grouped last when ascending and first when descending; a custom-field name that could never exist is rejected with 400 invalid_sort_by. Any other unknown value falls back to created_at." }, "reverse": { "type": "boolean", diff --git a/internal/api/handler/handler.go b/internal/api/handler/handler.go index 1f1575b9d..c3a9f9391 100644 --- a/internal/api/handler/handler.go +++ b/internal/api/handler/handler.go @@ -64,6 +64,7 @@ import ( "github.com/warmbly/warmbly/internal/app/unsublink" "github.com/warmbly/warmbly/internal/app/updates" "github.com/warmbly/warmbly/internal/app/user" + "github.com/warmbly/warmbly/internal/app/viewprefs" "github.com/warmbly/warmbly/internal/app/warmup" "github.com/warmbly/warmbly/internal/app/warmupcontent" "github.com/warmbly/warmbly/internal/app/webhook" @@ -119,6 +120,8 @@ type Handler struct { TasksService tasks.TasksService NotificationService notification.Service TwoFAService twofa.Service + // ViewPreferencesService keeps each member's saved list layouts. + ViewPreferencesService viewprefs.Service // New services APIKeyService apikey.APIKeyService diff --git a/internal/api/handler/view_preferences.go b/internal/api/handler/view_preferences.go new file mode 100644 index 000000000..7601c79cf --- /dev/null +++ b/internal/api/handler/view_preferences.go @@ -0,0 +1,83 @@ +package handler + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/api/middleware" + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" +) + +// viewActor resolves the member and workspace a saved layout belongs to. +func viewActor(c *gin.Context) (uuid.UUID, uuid.UUID, bool) { + uid, err := middleware.GetUserUUID(c) + if err != nil { + errx.Handle(c, errx.ErrUser) + return uuid.Nil, uuid.Nil, false + } + orgID := middleware.GetOrganizationID(c) + if orgID == nil { + errx.Handle(c, errx.New(errx.BadRequest, "no organization selected")) + return uuid.Nil, uuid.Nil, false + } + return uid, *orgID, true +} + +// GetViewPreferences returns the caller's saved layout for one dashboard list +// in the current workspace, or the empty layout when none is saved. +// GET /me/views/:view +func (h *Handler) GetViewPreferences(c *gin.Context) { + uid, orgID, ok := viewActor(c) + if !ok { + return + } + prefs, xerr := h.ViewPreferencesService.Get(c.Request.Context(), uid, orgID, c.Param("view")) + if xerr != nil { + errx.Handle(c, xerr) + return + } + c.JSON(http.StatusOK, gin.H{"preferences": prefs}) +} + +type updateViewPreferencesRequest struct { + Columns []string `json:"columns"` + Sort *models.ViewSort `json:"sort"` +} + +// UpdateViewPreferences replaces the caller's saved layout for one list. +// PUT /me/views/:view +func (h *Handler) UpdateViewPreferences(c *gin.Context) { + uid, orgID, ok := viewActor(c) + if !ok { + return + } + var req updateViewPreferencesRequest + if err := c.ShouldBindJSON(&req); err != nil { + errx.Handle(c, errx.ErrInvalid) + return + } + prefs := &models.ViewPreferences{View: c.Param("view"), Columns: req.Columns, Sort: req.Sort} + saved, xerr := h.ViewPreferencesService.Put(c.Request.Context(), uid, orgID, prefs) + if xerr != nil { + errx.Handle(c, xerr) + return + } + c.JSON(http.StatusOK, gin.H{"preferences": saved}) +} + +// ResetViewPreferences forgets the caller's saved layout for one list. +// DELETE /me/views/:view +func (h *Handler) ResetViewPreferences(c *gin.Context) { + uid, orgID, ok := viewActor(c) + if !ok { + return + } + if xerr := h.ViewPreferencesService.Reset(c.Request.Context(), uid, orgID, c.Param("view")); xerr != nil { + errx.Handle(c, xerr) + return + } + c.Status(http.StatusNoContent) +} diff --git a/internal/api/routes.go b/internal/api/routes.go index 8c20e7914..6e8e1c469 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -1300,6 +1300,13 @@ func Run( account.GET("/danger-zone", h.GetAccountDangerZone) account.POST("/danger-zone/delete", middleware.RequireFreshAuth(), h.ScheduleAccountDeletion) account.DELETE("/danger-zone/delete", h.CancelAccountDeletion) + + // A member's own layout of a dashboard list (columns, order, + // sort) in the current workspace. Personal, so JWT only: an API + // key has no screen to lay out. + account.GET("/views/:view", m.RequireOrganization(), h.GetViewPreferences) + account.PUT("/views/:view", m.RequireOrganization(), h.UpdateViewPreferences) + account.DELETE("/views/:view", m.RequireOrganization(), h.ResetViewPreferences) } jwtOnly.GET("/invitations", h.GetMyPendingInvitations) diff --git a/internal/app/contact/handler.go b/internal/app/contact/handler.go index f67a09601..3ebe62acf 100644 --- a/internal/app/contact/handler.go +++ b/internal/app/contact/handler.go @@ -10,6 +10,7 @@ import ( "github.com/warmbly/warmbly/internal/config" "github.com/warmbly/warmbly/internal/errx" "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/utils" "github.com/warmbly/warmbly/internal/utils/paging" "github.com/warmbly/warmbly/internal/utils/validate" ) @@ -114,10 +115,27 @@ func (s *contactService) Search(ctx context.Context, orgID, cursor, category, li if err := validateLeadFilters(filters); err != nil { return nil, err } + if err := validateSort(filters); err != nil { + return nil, err + } return s.contactRepository.Search(ctx, orgID, categoryId, cursorPos, filters, limitN) } +// validateSort rejects a custom-field sort whose key could never name a field. +// A bare column name that is unknown still falls back to created_at, which is +// the published behaviour; the custom form is new and can be strict. +func validateSort(filters models.SearchContacts) *errx.Error { + key, ok := models.ContactSortCustomField(filters.SortBy) + if !ok { + return nil + } + if !utils.IsValidJSONKey(key) { + return errx.NewWithIdentifier(errx.BadRequest, "invalid_sort_by", "invalid sort_by: custom field name must "+utils.JSONKeyRules) + } + return nil +} + // validateLeadFilters gates the single-campaign Leads-view filters: an unknown // value or the wrong campaign cardinality is a client contract error (400 with // a stable code), not a silently-ignored no-op. diff --git a/internal/app/orgtransfer/spec.go b/internal/app/orgtransfer/spec.go index e0a3adcf8..ac9a7d020 100644 --- a/internal/app/orgtransfer/spec.go +++ b/internal/app/orgtransfer/spec.go @@ -839,6 +839,7 @@ var ExcludedTables = map[string]string{ "sessions": "Live login sessions. They are bound to the source instance's signing key and must not survive a move.", "mailbox_erasures": "Erasure still owed for a mailbox this instance deleted: a grant to revoke at the provider, and message bodies to remove from this instance's blob store. Both name work on the instance that wrote the row, and the mailboxes are already gone.", "login_history": "Where people signed in from, kept only to compare a new sign-in against recent ones. It belongs to the person rather than the workspace, and a destination must build its own baseline before it can call anything anomalous.", + "user_view_preferences": "Each member's own column layout and sort for the dashboard's lists. It belongs to the person rather than the workspace: members are matched by account on import and a layout names custom fields the destination may not hold yet, so everyone starts from the default view and picks their columns again.", } // TableByName indexes Tables for lookup during import. diff --git a/internal/app/viewprefs/service.go b/internal/app/viewprefs/service.go new file mode 100644 index 000000000..cbcfeee6a --- /dev/null +++ b/internal/app/viewprefs/service.go @@ -0,0 +1,133 @@ +// Package viewprefs keeps each member's own layout of the dashboard's lists: +// which columns show, in what order, and the sort. A layout is personal and +// per workspace, so two members of one workspace can look at the same contacts +// through different columns. +package viewprefs + +import ( + "context" + "regexp" + "strings" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/observability/errs" + "github.com/warmbly/warmbly/internal/repository" + "github.com/warmbly/warmbly/internal/utils" +) + +// Service reads and writes a member's saved list layouts. +type Service interface { + // Get returns the saved layout, or the empty layout (default columns, + // default sort) when none is saved. + Get(ctx context.Context, userID, orgID uuid.UUID, view string) (*models.ViewPreferences, *errx.Error) + // Put replaces the saved layout. + Put(ctx context.Context, userID, orgID uuid.UUID, prefs *models.ViewPreferences) (*models.ViewPreferences, *errx.Error) + // Reset forgets the saved layout, so the list shows its defaults again. + Reset(ctx context.Context, userID, orgID uuid.UUID, view string) *errx.Error +} + +type service struct { + repo repository.ViewPreferencesRepository +} + +func NewService(repo repository.ViewPreferencesRepository) Service { + return &service{repo: repo} +} + +// A built-in column id is a snake_case name the dashboard defines. +var builtinColumnPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) + +func (s *service) Get(ctx context.Context, userID, orgID uuid.UUID, view string) (*models.ViewPreferences, *errx.Error) { + if !models.KnownViews[view] { + return nil, errx.NewWithIdentifier(errx.NotFound, "unknown_view", "unknown view") + } + prefs, err := s.repo.Get(ctx, userID, orgID, view) + if err != nil { + errs.CaptureException(err) + return nil, errx.InternalError() + } + if prefs == nil { + return &models.ViewPreferences{View: view, Columns: []string{}}, nil + } + return prefs, nil +} + +func (s *service) Put(ctx context.Context, userID, orgID uuid.UUID, prefs *models.ViewPreferences) (*models.ViewPreferences, *errx.Error) { + if !models.KnownViews[prefs.View] { + return nil, errx.NewWithIdentifier(errx.NotFound, "unknown_view", "unknown view") + } + if xerr := validate(prefs); xerr != nil { + return nil, xerr + } + if err := s.repo.Upsert(ctx, userID, orgID, prefs); err != nil { + errs.CaptureException(err) + return nil, errx.InternalError() + } + return s.Get(ctx, userID, orgID, prefs.View) +} + +func (s *service) Reset(ctx context.Context, userID, orgID uuid.UUID, view string) *errx.Error { + if !models.KnownViews[view] { + return errx.NewWithIdentifier(errx.NotFound, "unknown_view", "unknown view") + } + if err := s.repo.Delete(ctx, userID, orgID, view); err != nil { + errs.CaptureException(err) + return errx.InternalError() + } + return nil +} + +// validate checks the layout the way the contacts search will read it: every +// column id is one the dashboard can render, listed once, and the sort names a +// built-in column or a well-formed custom field. Custom-field ids are +// normalized in place so the same field saved with different spacing is one +// column. +func validate(prefs *models.ViewPreferences) *errx.Error { + if len(prefs.Columns) > models.ViewPreferencesMaxColumns { + return errx.NewWithIdentifier(errx.BadRequest, "too_many_columns", "too many columns") + } + seen := make(map[string]bool, len(prefs.Columns)) + for i, id := range prefs.Columns { + norm, ok := normalizeColumnID(id) + if !ok { + return errx.NewWithIdentifier(errx.BadRequest, "invalid_column", "invalid column: "+id) + } + if seen[norm] { + return errx.NewWithIdentifier(errx.BadRequest, "duplicate_column", "column listed twice: "+norm) + } + seen[norm] = true + prefs.Columns[i] = norm + } + if prefs.Sort != nil { + by := strings.TrimSpace(prefs.Sort.By) + if by == "" { + prefs.Sort = nil + } else { + norm, ok := normalizeColumnID(by) + if !ok { + return errx.NewWithIdentifier(errx.BadRequest, "invalid_sort", "invalid sort: "+by) + } + prefs.Sort.By = norm + } + } + return nil +} + +func normalizeColumnID(id string) (string, bool) { + if len(id) > models.ViewColumnIDMaxLength { + return "", false + } + if key, ok := models.ContactSortCustomField(id); ok { + if !utils.IsValidJSONKey(key) { + return "", false + } + return models.ContactSortCustomPrefix + key, true + } + if !builtinColumnPattern.MatchString(id) { + return "", false + } + return id, true +} diff --git a/internal/app/viewprefs/service_test.go b/internal/app/viewprefs/service_test.go new file mode 100644 index 000000000..15a3c1c76 --- /dev/null +++ b/internal/app/viewprefs/service_test.go @@ -0,0 +1,52 @@ +package viewprefs + +import ( + "strings" + "testing" + + "github.com/warmbly/warmbly/internal/models" +) + +func TestValidateNormalizesAndRejects(t *testing.T) { + ok := &models.ViewPreferences{ + View: models.ViewContacts, + Columns: []string{"company", "custom:Company Mobile", "phone"}, + Sort: &models.ViewSort{By: " custom:Industry ", Reverse: true}, + } + if xerr := validate(ok); xerr != nil { + t.Fatalf("valid layout rejected: %v", xerr) + } + if ok.Columns[1] != "custom:Company Mobile" { + t.Fatalf("custom column not normalized: %q", ok.Columns[1]) + } + if ok.Sort.By != "custom:Industry" { + t.Fatalf("sort not normalized: %q", ok.Sort.By) + } + + blank := &models.ViewPreferences{View: models.ViewContacts, Sort: &models.ViewSort{By: " "}} + if xerr := validate(blank); xerr != nil || blank.Sort != nil { + t.Fatalf("a blank sort means the default: %v %+v", xerr, blank.Sort) + } + + for name, prefs := range map[string]*models.ViewPreferences{ + "duplicate": {Columns: []string{"company", "custom:A", "custom:A"}}, + "bad builtin": {Columns: []string{"Company"}}, + "bad custom key": {Columns: []string{"custom:Revenue ($)"}}, + "too long": {Columns: []string{"custom:" + strings.Repeat("a", 300)}}, + "bad sort": {Sort: &models.ViewSort{By: "drop table"}}, + "too many": {Columns: manyColumns(models.ViewPreferencesMaxColumns + 1)}, + } { + prefs.View = models.ViewContacts + if xerr := validate(prefs); xerr == nil { + t.Errorf("%s: accepted", name) + } + } +} + +func manyColumns(n int) []string { + out := make([]string, n) + for i := range out { + out[i] = "custom:f" + strings.Repeat("x", i%5) + string(rune('a'+i%26)) + strings.Repeat("y", i/26) + } + return out +} diff --git a/internal/infrastructure/db/migrations/000187_user_view_preferences.down.sql b/internal/infrastructure/db/migrations/000187_user_view_preferences.down.sql new file mode 100644 index 000000000..21d6f438e --- /dev/null +++ b/internal/infrastructure/db/migrations/000187_user_view_preferences.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS public.user_view_preferences; diff --git a/internal/infrastructure/db/migrations/000187_user_view_preferences.up.sql b/internal/infrastructure/db/migrations/000187_user_view_preferences.up.sql new file mode 100644 index 000000000..518cddbfe --- /dev/null +++ b/internal/infrastructure/db/migrations/000187_user_view_preferences.up.sql @@ -0,0 +1,23 @@ +-- One member's own layout for one of the dashboard's lists: which columns show, +-- in what order, and how the list is sorted. Keyed by person and workspace, +-- because the columns a list can carry (custom fields) differ per workspace. +-- +-- The column list is a jsonb array of column ids the dashboard defines +-- ("company", "custom:Industry"); it is read back whole and never filtered in +-- SQL. The sort is typed so it can be validated and read like any other column. + +CREATE TABLE IF NOT EXISTS public.user_view_preferences ( + user_id uuid NOT NULL REFERENCES public.users (id) ON DELETE CASCADE, + organization_id uuid NOT NULL REFERENCES public.organizations (id) ON DELETE CASCADE, + view text NOT NULL, + columns jsonb NOT NULL DEFAULT '[]'::jsonb, + sort_by text NOT NULL DEFAULT '', + sort_reverse boolean NOT NULL DEFAULT false, + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, organization_id, view), + CONSTRAINT user_view_preferences_view_check CHECK (view ~ '^[a-z][a-z0-9_]{0,63}$'), + CONSTRAINT user_view_preferences_columns_check CHECK (jsonb_typeof(columns) = 'array') +); + +COMMENT ON TABLE public.user_view_preferences IS + 'A member''s own column layout and sort for one dashboard list, per workspace. Read by GET /v1/me/views/:view.'; diff --git a/internal/models/contact.go b/internal/models/contact.go index c1a5ebd75..dd447c0cb 100644 --- a/internal/models/contact.go +++ b/internal/models/contact.go @@ -802,8 +802,8 @@ type SearchContacts struct { CreatedBefore *time.Time `json:"created_before"` // Contacts created before this date UpdatedAfter *time.Time `json:"updated_after"` // Contacts updated after this date UpdatedBefore *time.Time `json:"updated_before"` // Contacts updated before this date - SortBy string `json:"sort_by"` // e.g., "first_name ASC", "campaign_count DESC" - Reverse bool `json:"reverse"` // ASC or DESC + SortBy string `json:"sort_by"` // A column name (created_at, first_name, company, ...) or "custom:" for a custom field + Reverse bool `json:"reverse"` // Ascending when true; the default is descending } type BulkEditContactsFieldType string diff --git a/internal/models/view_preferences.go b/internal/models/view_preferences.go new file mode 100644 index 000000000..d9e9f0f2e --- /dev/null +++ b/internal/models/view_preferences.go @@ -0,0 +1,63 @@ +package models + +import ( + "strings" + "time" +) + +// Dashboard lists whose layout a member can save. A new list gets a constant +// here before the dashboard can persist a layout for it. +const ( + ViewContacts = "contacts" + ViewCampaignLeads = "campaign_leads" +) + +// KnownViews is the set of view names GET/PUT /me/views/:view accepts. +var KnownViews = map[string]bool{ + ViewContacts: true, + ViewCampaignLeads: true, +} + +// ViewPreferencesMaxColumns bounds one layout; no list here has anywhere near +// this many columns to show. +const ViewPreferencesMaxColumns = 64 + +// ViewColumnIDMaxLength fits "custom:" plus the longest custom-field key. +const ViewColumnIDMaxLength = 300 + +// ViewColumnCustomPrefix marks a column that shows a contact custom field, the +// same addressing the export uses ("custom:Industry"). +const ViewColumnCustomPrefix = "custom:" + +// ViewSort is the saved ordering of a list, in the contacts search's terms. +type ViewSort struct { + By string `json:"by"` + Reverse bool `json:"reverse"` +} + +// ViewPreferences is one member's saved layout for one list in one workspace. +// An empty Columns means "the default layout"; a nil Sort means "the default +// sort". +type ViewPreferences struct { + View string `json:"view"` + Columns []string `json:"columns"` + Sort *ViewSort `json:"sort,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +// ContactSortCustomPrefix is the sort_by form that orders the contacts list on +// a custom field: "custom:". The key is normalized the way custom-field +// names are on write, so "custom:Company Mobile" and "custom:Company Mobile" +// are the same sort. +const ContactSortCustomPrefix = "custom:" + +// ContactSortCustomField returns the custom-field key a sort_by names, or +// false when sort_by is not the custom form. Whether the key is a valid +// custom-field name is the caller's check. +func ContactSortCustomField(sortBy string) (string, bool) { + if !strings.HasPrefix(sortBy, ContactSortCustomPrefix) { + return "", false + } + key := strings.Join(strings.Fields(strings.TrimPrefix(sortBy, ContactSortCustomPrefix)), " ") + return key, true +} diff --git a/internal/repository/contact_custom_sort_live_test.go b/internal/repository/contact_custom_sort_live_test.go new file mode 100644 index 000000000..f8158090b --- /dev/null +++ b/internal/repository/contact_custom_sort_live_test.go @@ -0,0 +1,190 @@ +package repository + +import ( + "context" + "testing" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/warmbly/warmbly/internal/models" +) + +// The contacts list sorts on a custom field with sort_by "custom:". The +// value is text in jsonb, nullable by nature (most rows lack most fields), so +// the keyset cursor has to walk the NULL block correctly in both directions and +// SearchIDs has to hand back the rows in the order the list showed them. +// +// Run against the dev stack: +// +// WARMBLY_TEST_DB=postgres://warmbly:warmbly@localhost:15432/warmbly_dev?sslmode=disable \ +// go test ./internal/repository/ -run LiveContactCustomFieldSort -v + +type customSortFixture struct { + org uuid.UUID + user uuid.UUID + total int +} + +func newCustomSortFixture(t *testing.T, pool *pgxpool.Pool, total int) *customSortFixture { + t.Helper() + ctx := context.Background() + f := &customSortFixture{org: uuid.New(), user: uuid.New(), total: total} + + exec := func(sql string, args ...any) { + t.Helper() + if _, err := pool.Exec(ctx, sql, args...); err != nil { + t.Fatalf("fixture %q: %v", sql[:min(60, len(sql))], err) + } + } + tag := f.org.String()[:8] + exec(`INSERT INTO users (id, first_name, last_name, email, password_hash) + VALUES ($1, 'Sort', 'Live', $2, 'x')`, f.user, "i605-"+tag+"@test.local") + exec(`INSERT INTO organizations (id, name, slug, owner_user_id) + VALUES ($1, 'Issue 605', $2, $3)`, f.org, "i605-"+tag, f.user) + exec(`INSERT INTO organization_members (organization_id, user_id, role, accepted_at) + VALUES ($1, $2, 'owner', NOW())`, f.org, f.user) + + // Every third row lacks the field, every seventh carries it blank, and the + // rest share four values so the id tiebreak carries most of the order. + exec(` + INSERT INTO contacts (id, user_id, organization_id, email, first_name, last_name, company, phone, custom_fields, updated_at, created_at) + SELECT gen_random_uuid(), $1, $2, + 'i605-' || i || '-' || $3 || '@test.local', + 'Lead' || i, 'Batch', '', '', + CASE + WHEN i % 3 = 0 THEN '{"Other Field": "x"}'::jsonb + WHEN i % 7 = 0 THEN '{"Industry": ""}'::jsonb + ELSE jsonb_build_object('Industry', (ARRAY['Fintech','Health','Retail','SaaS'])[(i % 4) + 1]) + END, + NOW(), NOW() - (i || ' seconds')::interval + FROM generate_series(1, $4) AS i`, + f.user, f.org, tag, total) + + t.Cleanup(func() { + c := context.Background() + for _, step := range []struct { + sql string + arg any + }{ + {`DELETE FROM contacts WHERE organization_id = $1`, f.org}, + {`DELETE FROM organization_members WHERE organization_id = $1`, f.org}, + {`DELETE FROM organizations WHERE id = $1`, f.org}, + {`DELETE FROM users WHERE id = $1`, f.user}, + } { + if _, err := pool.Exec(c, step.sql, step.arg); err != nil { + t.Errorf("cleanup %q: %v", step.sql, err) + } + } + }) + return f +} + +func TestLiveContactCustomFieldSortPagesEveryRow(t *testing.T) { + handle, pool := liveContactDB(t) + f := newCustomSortFixture(t, pool, 131) + repo := NewContactRepostory(handle) + ctx := context.Background() + + for _, reverse := range []bool{false, true} { + filters := models.SearchContacts{SortBy: "custom:Industry", Reverse: reverse} + + whole, xerr := repo.Search(ctx, f.org.String(), nil, nil, filters, int32(f.total)) + if xerr != nil { + t.Fatalf("reverse=%v single page: %v", reverse, xerr) + } + if len(whole.Data) != f.total { + t.Fatalf("reverse=%v single page returned %d rows, want %d", reverse, len(whole.Data), f.total) + } + + // The order the list shows: values sorted as text, with rows that lack + // the field or carry it blank in one block, first when descending and + // last when ascending. + want := make([]uuid.UUID, 0, f.total) + var prev string + sawValue := false + for i, c := range whole.Data { + want = append(want, c.ID) + v := c.CustomFields["Industry"] + missing := v == "" + switch { + case !reverse && !missing && i > 0 && whole.Data[i-1].CustomFields["Industry"] == "": + // DESC: once a value appears, no blank may follow it. + case reverse && missing: + sawValue = sawValue || false + } + if !missing { + if sawValue && ((reverse && v < prev) || (!reverse && v > prev)) { + t.Fatalf("reverse=%v values out of order at %d: %q after %q", reverse, i, v, prev) + } + prev = v + sawValue = true + } + } + firstMissing := whole.Data[0].CustomFields["Industry"] == "" + lastMissing := whole.Data[f.total-1].CustomFields["Industry"] == "" + if !reverse && !firstMissing { + t.Fatalf("descending should put the rows without the field first") + } + if reverse && !lastMissing { + t.Fatalf("ascending should put the rows without the field last") + } + if !reverse && lastMissing { + t.Fatalf("descending should end on a row that has the field") + } + if reverse && firstMissing { + t.Fatalf("ascending should start on a row that has the field") + } + + seen, _ := pageThrough(t, repo, f.org.String(), filters, 10) + assertExactlyOnce(t, seen, f.total) + for i := range want { + if i < len(seen) && seen[i] != want[i] { + t.Fatalf("reverse=%v paged order diverges from the whole-list order at %d", reverse, i) + } + } + + ids, xerr := repo.SearchIDs(ctx, f.org.String(), filters, f.total) + if xerr != nil { + t.Fatalf("reverse=%v SearchIDs: %v", reverse, xerr) + } + if len(ids) != f.total { + t.Fatalf("reverse=%v SearchIDs returned %d ids, want %d", reverse, len(ids), f.total) + } + for i := range want { + if ids[i] != want[i] { + t.Fatalf("reverse=%v SearchIDs order diverges from Search at %d", reverse, i) + } + } + } +} + +// A custom-field sort combined with a filter on the same field still pages +// every match once, and a sort on a field no row carries is one NULL block. +func TestLiveContactCustomFieldSortWithFilters(t *testing.T) { + handle, pool := liveContactDB(t) + f := newCustomSortFixture(t, pool, 60) + repo := NewContactRepostory(handle) + + filtered := models.SearchContacts{ + SortBy: "custom:Industry", + CustomFieldFilters: []models.SearchContactsFilter{ + {Name: "Industry", Value: "a", Type: models.SearchContactsFilterTypeContains}, + }, + } + seen, _ := pageThrough(t, repo, f.org.String(), filtered, 7) + want := 0 + for i := 1; i <= f.total; i++ { + if i%3 == 0 || i%7 == 0 { + continue + } + switch []string{"Fintech", "Health", "Retail", "SaaS"}[i%4] { + case "Health", "Retail", "SaaS": + want++ + } + } + assertExactlyOnce(t, seen, want) + + nobody, _ := pageThrough(t, repo, f.org.String(), models.SearchContacts{SortBy: "custom:Nobody Has This", Reverse: true}, 9) + assertExactlyOnce(t, nobody, f.total) +} diff --git a/internal/repository/contact_sort_test.go b/internal/repository/contact_sort_test.go new file mode 100644 index 000000000..de359e94e --- /dev/null +++ b/internal/repository/contact_sort_test.go @@ -0,0 +1,52 @@ +package repository + +import "testing" + +// resolveContactSort is the one place sort_by becomes SQL, for the list and for +// "select all matching" alike. +func TestResolveContactSort(t *testing.T) { + t.Run("built-in column", func(t *testing.T) { + args := []any{"org"} + idx := 2 + name, spec := resolveContactSort("company", &args, &idx) + if name != "company" || spec.expr != "c.company" || spec.nullable { + t.Fatalf("got %q %+v", name, spec) + } + if len(args) != 1 || idx != 2 { + t.Fatalf("a built-in sort must bind nothing: args=%v idx=%d", args, idx) + } + }) + t.Run("custom field binds its key", func(t *testing.T) { + args := []any{"org"} + idx := 2 + name, spec := resolveContactSort("custom:Company Mobile", &args, &idx) + if name != "custom:Company Mobile" { + t.Fatalf("name %q: the key must be normalized so the cursor's sort key is stable", name) + } + if !spec.nullable || spec.kind != sortText { + t.Fatalf("a custom field is nullable text: %+v", spec) + } + if spec.expr != "NULLIF(c.custom_fields ->> $2::text, '')" { + t.Fatalf("expr %q", spec.expr) + } + if len(args) != 2 || args[1] != "Company Mobile" || idx != 3 { + t.Fatalf("the key must be bound once: args=%v idx=%d", args, idx) + } + }) + t.Run("malformed custom key falls back", func(t *testing.T) { + args := []any{} + idx := 1 + name, _ := resolveContactSort("custom:Revenue ($)", &args, &idx) + if name != "created_at" || len(args) != 0 || idx != 1 { + t.Fatalf("got %q args=%v idx=%d", name, args, idx) + } + }) + t.Run("unknown column falls back", func(t *testing.T) { + args := []any{} + idx := 1 + name, _ := resolveContactSort("nope", &args, &idx) + if name != "created_at" { + t.Fatalf("got %q", name) + } + }) +} diff --git a/internal/repository/pg_contact.go b/internal/repository/pg_contact.go index 87ec5c8ee..6c9ecfeb7 100644 --- a/internal/repository/pg_contact.go +++ b/internal/repository/pg_contact.go @@ -1035,11 +1035,40 @@ var contactSorts = map[string]contactSort{ "first_name": {expr: "c.first_name", kind: sortText}, "last_name": {expr: "c.last_name", kind: sortText}, "email": {expr: "c.email", kind: sortText}, + "company": {expr: "c.company", kind: sortText}, + "phone": {expr: "c.phone", kind: sortText}, "created_at": {expr: "c.created_at", kind: sortTimestamp}, "updated_at": {expr: "c.updated_at", kind: sortTimestamp}, "campaign_count": {expr: "COALESCE(cl.campaign_count,0)", kind: sortNumber}, } +// resolveContactSort turns a request's sort_by into the column the list orders +// on. Search and SearchIDs both go through it, so "select all matching" walks +// the rows in the order the list showed them. +// +// A custom field ("custom:") sorts on its jsonb value as text, with a +// blank value treated as missing so it sits with the rows that lack the field. +// The key is a bound parameter, never written into the SQL: it is user data. +// The placeholder is appended to args here, so the same expression serves the +// cursor comparison, the sort_value column and ORDER BY. Anything unknown +// falls back to created_at, the documented behaviour. +func resolveContactSort(sortBy string, args *[]any, argIndex *int) (string, contactSort) { + if spec, ok := contactSorts[sortBy]; ok { + return sortBy, spec + } + if key, ok := models.ContactSortCustomField(sortBy); ok && utils.IsValidJSONKey(key) { + spec := contactSort{ + expr: fmt.Sprintf("NULLIF(c.custom_fields ->> $%d::text, '')", *argIndex), + kind: sortText, + nullable: true, + } + *args = append(*args, key) + *argIndex++ + return models.ContactSortCustomPrefix + key, spec + } + return "created_at", contactSorts["created_at"] +} + // contactFilter is a compiled contact search: the WHERE terms, the args they // bind, the next free placeholder, and (single-campaign Leads view only) the // placeholder the lead-progress subquery reuses. @@ -1303,11 +1332,7 @@ func (r *contactRepository) Search( // ----------------------------- // campaign_count is a computed column, so the cursor compares against the // expression rather than the SELECT alias, which WHERE cannot see. - sortName := "created_at" - if _, ok := contactSorts[filters.SortBy]; ok { - sortName = filters.SortBy - } - spec := contactSorts[sortName] + sortName, spec := resolveContactSort(filters.SortBy, &args, &argIndex) direction := "DESC" nulls := "NULLS FIRST" if filters.Reverse { @@ -1335,13 +1360,6 @@ func (r *contactRepository) Search( if cursor.Value != nil && !spec.wellFormed(*cursor.Value) { return nil, errx.New(errx.BadRequest, "invalid cursor") } - bound := spec.bound(fmt.Sprintf("$%d", argIndex)) - args = append(args, cursor.Value) - argIndex++ - idArg := fmt.Sprintf("$%d", argIndex) - args = append(args, cursor.ID) - argIndex++ - // The tiebreak follows the sort direction, so one index serves both ways // round; the boundary row itself is included because it is this page's // first row. @@ -1349,17 +1367,28 @@ func (r *contactRepository) Search( if direction == "ASC" { cmp, tie = ">", ">=" } - after := fmt.Sprintf("(%[1]s %[2]s %[3]s OR (%[1]s = %[3]s AND c.id %[5]s %[4]s))", sortBy, cmp, bound, idArg, tie) - if spec.nullable { - switch { - case cursor.Value == nil: - // The boundary sits in the NULL block: the rest of that block by - // id, plus every non-NULL row when NULLs come first. - after = fmt.Sprintf("(%s IS NULL AND c.id %s %s)", sortBy, tie, idArg) - if nulls == "NULLS FIRST" { - after += fmt.Sprintf(" OR %s IS NOT NULL", sortBy) - } - case nulls == "NULLS LAST": + var after string + if spec.nullable && cursor.Value == nil { + // The boundary sits in the NULL block: the rest of that block by + // id, plus every non-NULL row when NULLs come first. No value is + // bound here, because a parameter the clause never names is one + // Postgres cannot type. + idArg := fmt.Sprintf("$%d", argIndex) + args = append(args, cursor.ID) + argIndex++ + after = fmt.Sprintf("(%s IS NULL AND c.id %s %s)", sortBy, tie, idArg) + if nulls == "NULLS FIRST" { + after += fmt.Sprintf(" OR %s IS NOT NULL", sortBy) + } + } else { + bound := spec.bound(fmt.Sprintf("$%d", argIndex)) + args = append(args, cursor.Value) + argIndex++ + idArg := fmt.Sprintf("$%d", argIndex) + args = append(args, cursor.ID) + argIndex++ + after = fmt.Sprintf("(%[1]s %[2]s %[3]s OR (%[1]s = %[3]s AND c.id %[5]s %[4]s))", sortBy, cmp, bound, idArg, tie) + if spec.nullable && nulls == "NULLS LAST" { // Past the non-NULL rows, the NULL block still follows. after += fmt.Sprintf(" OR %s IS NULL", sortBy) } @@ -1527,8 +1556,12 @@ func (r *contactRepository) Search( %s %s `, countJoin, whereSQL) + // The count sees the filter terms only: no cursor on a first page, and + // the sort's own parameter (a custom field's key) is not referenced by + // the WHERE, so passing it would leave Postgres a placeholder it cannot + // type. var tmp int64 - if err := r.DB.QueryRow(ctx, countQuery, args[:argIndex-1]...).Scan(&tmp); err != nil { + if err := r.DB.QueryRow(ctx, countQuery, fq.args...).Scan(&tmp); err != nil { db.CaptureError(err, "countQuery", args, "queryrow") return nil, errx.InternalError() } @@ -1736,12 +1769,9 @@ func (r *contactRepository) SearchIDs(ctx context.Context, orgID string, filters return nil, ferr } args := fq.args + argIndex := fq.nextArg - sortName := "created_at" - if _, ok := contactSorts[filters.SortBy]; ok { - sortName = filters.SortBy - } - spec := contactSorts[sortName] + sortName, spec := resolveContactSort(filters.SortBy, &args, &argIndex) direction, nulls := "DESC", "NULLS FIRST" if filters.Reverse { direction, nulls = "ASC", "NULLS LAST" @@ -1767,7 +1797,7 @@ func (r *contactRepository) SearchIDs(ctx context.Context, orgID string, filters %s ORDER BY %s %s %s, c.id %s LIMIT $%d - `, campaignCountJoin, whereSQL, spec.expr, direction, nulls, direction, fq.nextArg) + `, campaignCountJoin, whereSQL, spec.expr, direction, nulls, direction, argIndex) args = append(args, max+1) rows, err := r.DB.Query(ctx, query, args...) diff --git a/internal/repository/pg_view_preferences.go b/internal/repository/pg_view_preferences.go new file mode 100644 index 000000000..433272f51 --- /dev/null +++ b/internal/repository/pg_view_preferences.go @@ -0,0 +1,94 @@ +package repository + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/warmbly/warmbly/internal/models" +) + +// ViewPreferencesRepository stores one member's saved layout per dashboard +// list per workspace. +type ViewPreferencesRepository interface { + // Get returns nil, nil when the member has never saved this view. + Get(ctx context.Context, userID, orgID uuid.UUID, view string) (*models.ViewPreferences, error) + Upsert(ctx context.Context, userID, orgID uuid.UUID, prefs *models.ViewPreferences) error + Delete(ctx context.Context, userID, orgID uuid.UUID, view string) error +} + +type viewPreferencesRepository struct { + db *pgxpool.Pool +} + +func NewViewPreferencesRepository(db *pgxpool.Pool) ViewPreferencesRepository { + return &viewPreferencesRepository{db: db} +} + +func (r *viewPreferencesRepository) Get(ctx context.Context, userID, orgID uuid.UUID, view string) (*models.ViewPreferences, error) { + var ( + raw []byte + sortBy string + reverse bool + updatedAt time.Time + ) + err := r.db.QueryRow(ctx, ` + SELECT columns, sort_by, sort_reverse, updated_at + FROM user_view_preferences + WHERE user_id = $1 AND organization_id = $2 AND view = $3`, + userID, orgID, view).Scan(&raw, &sortBy, &reverse, &updatedAt) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil + } + return nil, err + } + prefs := &models.ViewPreferences{View: view, Columns: []string{}, UpdatedAt: &updatedAt} + if len(raw) > 0 { + if err := json.Unmarshal(raw, &prefs.Columns); err != nil { + return nil, err + } + } + if sortBy != "" { + prefs.Sort = &models.ViewSort{By: sortBy, Reverse: reverse} + } + return prefs, nil +} + +func (r *viewPreferencesRepository) Upsert(ctx context.Context, userID, orgID uuid.UUID, prefs *models.ViewPreferences) error { + cols := prefs.Columns + if cols == nil { + cols = []string{} + } + raw, err := json.Marshal(cols) + if err != nil { + return err + } + sortBy, reverse := "", false + if prefs.Sort != nil { + sortBy, reverse = prefs.Sort.By, prefs.Sort.Reverse + } + _, err = r.db.Exec(ctx, ` + INSERT INTO user_view_preferences (user_id, organization_id, view, columns, sort_by, sort_reverse, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, now()) + ON CONFLICT (user_id, organization_id, view) DO UPDATE + SET columns = EXCLUDED.columns, + sort_by = EXCLUDED.sort_by, + sort_reverse = EXCLUDED.sort_reverse, + updated_at = now()`, + userID, orgID, prefs.View, raw, sortBy, reverse) + return err +} + +func (r *viewPreferencesRepository) Delete(ctx context.Context, userID, orgID uuid.UUID, view string) error { + _, err := r.db.Exec(ctx, ` + DELETE FROM user_view_preferences + WHERE user_id = $1 AND organization_id = $2 AND view = $3`, + userID, orgID, view) + return err +} diff --git a/web/src/components/app/contacts/ContactsTable.tsx b/web/src/components/app/contacts/ContactsTable.tsx index 8add33693..fdb567faf 100644 --- a/web/src/components/app/contacts/ContactsTable.tsx +++ b/web/src/components/app/contacts/ContactsTable.tsx @@ -14,26 +14,21 @@ import React from "react"; import { useNavigate, useSearchParams } from "react-router-dom"; import { AlertTriangleIcon, - BanIcon, - Building2Icon, + ArrowDownIcon, + ArrowUpIcon, CableIcon, CheckIcon, - ClockIcon, CornerUpLeftIcon, DownloadIcon, - InfoIcon, LayersIcon, Loader2Icon, - MailIcon, MailOpenIcon, MoreHorizontalIcon, MousePointerClickIcon, PauseIcon, - PhoneIcon, PlayIcon, PlusIcon, RefreshCcwIcon, - Settings2Icon, ShieldCheckIcon, SheetIcon, SparklesIcon, @@ -51,7 +46,6 @@ import useSearchContacts from "@/lib/api/hooks/app/contacts/useSearchContacts"; import type SearchContacts from "@/lib/api/models/app/contacts/SearchContacts"; import useDeleteContacts from "@/lib/api/hooks/app/contacts/useDeleteContacts"; import { useRequestContactVerification } from "@/lib/api/hooks/app/contacts/useContactVerification"; -import VerificationBadge from "./VerificationBadge"; import { useBatchResearch } from "@/lib/api/hooks/app/contacts/useContactResearch"; import useIntegrationConnections from "@/lib/api/hooks/app/integrations/useIntegrationConnections"; import { usePushContacts } from "@/lib/api/hooks/app/integrations/usePushContacts"; @@ -63,14 +57,13 @@ import { import toast from "react-hot-toast"; import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; -import clippedTitle from "@/lib/helper/clippedTitle"; import FilterBar from "./filters/FilterBar"; import { hasNarrowingFilters, isCompleteCustomFilter, scopeSearch } from "./filters/helpers"; import ContactEdit from "./ContactEdit"; import type { ContactSlideTab } from "./contact-edit/tabs"; import type MiniCampaign from "@/lib/api/models/app/campaigns/MiniCampaign"; import { holdSummary } from "@/lib/api/models/app/contacts/Contact"; -import type { ContactCampaignProgress, LeadEngagement, LeadStatus, VerificationSource, VerificationStatus } from "@/lib/api/models/app/contacts/Contact"; +import type { ContactCampaignProgress, LeadEngagement, LeadStatus } from "@/lib/api/models/app/contacts/Contact"; import type { CampaignLeadCounts } from "@/lib/api/models/app/contacts/SearchContactsResult"; import ContactsEditBulk from "./ContactsEditBulk"; import PauseLeadDialog from "./PauseLeadDialog"; @@ -96,7 +89,12 @@ import type { ExportScopeContext } from "./ExportDialog"; import useUpdateContactsBulk from "@/lib/api/hooks/app/contacts/useUpdateContactsBulk"; import useAiMetered from "@/hooks/useAiMetered"; import SyncSourcesPanel from "./SyncSourcesPanel"; -import { CategoryChip } from "./CategoryPicker"; +import { columnClass, sortOptions, type ContactColumn, type ContactRow } from "./columns"; +import { ColumnChooser, SortMenu, type ViewSortState } from "./ViewControls"; +import { useContactView } from "./useContactView"; +import { readCachedView } from "@/lib/api/hooks/app/views/useViewPreferences"; +import type { SearchContactsSortBy } from "@/lib/api/models/app/contacts/search-contacts.types"; +import type { ViewName } from "@/lib/api/models/app/views/ViewPreferences"; import { EmptyBlock, @@ -114,7 +112,6 @@ import { PopoverMenuContent, PopoverMenuItem, PopoverMenuLabel, - PopoverMenuSeparator, PopoverMenuTrigger, SelectButton, } from "@/components/ui/popover-menu"; @@ -162,14 +159,70 @@ export default function ContactsTable({ // ?category= pre-filters the list (the Categories tab links here). const [params] = useSearchParams(); + // The member's saved layout for this list: its columns and its sort. The + // Leads tab and the contacts page are two views with two layouts. + const viewName: ViewName = current_campaign ? "campaign_leads" : "contacts"; + const view = useContactView(viewName); + const [searchProps, setSearchProps] = React.useState(() => { const category = params.get("category"); + // The browser's copy of the saved sort seeds the first request, so the + // list does not load in one order and then reload in another. + const cached = readCachedView(view.orgId, viewName)?.sort; return { ...scopeSearch({ campaignId: current_campaign?.id, segmentId: segment?.id }), category_ids: category && !segment && !current_campaign ? [category] : undefined, + ...(cached ? { sort_by: cached.by as SearchContactsSortBy, reverse: cached.reverse } : {}), }; }); + // The saved sort applies once the server's copy is in hand, and only when + // it differs from what is already applied, so a change made here (which + // writes the same sort back) does not re-apply itself. + const appliedSortRef = React.useRef(null); + React.useEffect(() => { + if (!view.loaded) return; + const saved = view.savedSort; + const sig = saved ? `${saved.by}:${saved.reverse}` : "default"; + if (appliedSortRef.current === sig) return; + appliedSortRef.current = sig; + setSearchProps((prev) => ({ + ...prev, + sort_by: (saved?.by ?? "created_at") as SearchContactsSortBy, + reverse: saved?.reverse ?? false, + })); + }, [view.loaded, view.savedSort]); + const sortState: ViewSortState = { by: searchProps.sort_by, reverse: searchProps.reverse }; + function changeSort(next: ViewSortState) { + appliedSortRef.current = `${next.by}:${next.reverse}`; + setSearchProps((s) => ({ ...s, sort_by: next.by, reverse: next.reverse })); + view.setSort({ by: next.by, reverse: next.reverse }); + } + // A header click: the same column flips direction, a new one starts the + // way its kind reads best (A to Z for text, newest or most first otherwise). + function sortByColumn(col: ContactColumn) { + if (!col.sortKey) return; + if (searchProps.sort_by === col.sortKey) changeSort({ by: col.sortKey, reverse: !searchProps.reverse }); + else changeSort({ by: col.sortKey, reverse: !!col.sortAsc }); + } + function resetView() { + view.reset(); + appliedSortRef.current = "default"; + setSearchProps((s) => ({ ...s, sort_by: "created_at", reverse: false })); + } + const viewControls = ( + <> + + + + ); + function saveAsSegment(draft: SearchContacts) { const { conditions, dropped } = filtersToSegment(draft, current_campaign?.id); if (dropped.length > 0) toast(`Not carried over: ${dropped.join(", ")}. Add a condition for it in the editor.`); @@ -496,6 +549,9 @@ export default function ContactsTable({ onRetry={() => contactsData.refetch()} isRefetching={contactsData.isFetching && !contactsData.isPending} contacts={rows} + columns={view.columns} + sort={sortState} + onSort={sortByColumn} isRowSelected={isRowSelected} onToggle={(id, on) => setRowSel((s) => rowSelection.toggleRow(s, id, on))} isSelectedAll={loadedAllSelected} @@ -656,6 +712,7 @@ export default function ContactsTable({ placeholder="Search leads…" className="w-full sm:w-56" /> + {viewControls} } @@ -926,45 +983,7 @@ export default function ContactsTable({ placeholder="Search by name, email, company…" className="w-full sm:w-72" /> - - - } - label="Sort" - /> - - - Sort by - {[ - ["created_at", "Date added"], - ["email", "Email"], - ["first_name", "First name"], - ["last_name", "Last name"], - ["company", "Company"], - ].map(([key, label]) => ( - - setSearchProps((s) => ({ - ...s, - sort_by: key as SearchContacts["sort_by"], - })) - } - > - {label} - - ))} - - setSearchProps((s) => ({ ...s, reverse: !s.reverse }))} - closeOnSelect={false} - > - Reverse order - - - + {viewControls} void; isRefetching: boolean; - contacts: { - id: string; - first_name: string; - last_name: string; - email: string; - company: string; - phone: string; - subscribed: boolean; - campaigns: { id: string }[]; - categories?: { id: string; title: string; color: string }[]; - campaign_lead?: ContactCampaignProgress | null; - verification_status?: VerificationStatus; - verification_sub_status?: string; - verification_source?: VerificationSource; - verification_provider?: string; - verification_checked_at?: string | null; - verification_confidence?: number; - created_at: Date; - }[]; + contacts: ContactRow[]; + // The saved view: the columns in order (Name first) and the current sort. + columns: ContactColumn[]; + sort: ViewSortState; + onSort: (col: ContactColumn) => void; isRowSelected: (id: string) => boolean; onToggle: (id: string, on: boolean) => void; isSelectedAll: boolean; @@ -1129,15 +1137,6 @@ function ContactsTableBody({ loadedCount: number; totalCount: number; }) { - // Name is the only auto-width column, so it takes every pixel the sized - // columns leave — under table-fixed a second auto column would split that - // slack with it and size the name like a phone number. Which breakpoint each - // sized column appears at is then just "does Name still clear ~170px": Leads - // carries five campaign columns Contacts does not, so company waits longer - // for room there, and a phone number is no part of reading a campaign, so - // Leads drops that column and the contact drawer keeps the address. - const companyCol = embedded ? "w-40 hidden xl:table-cell" : "w-36 hidden lg:table-cell"; - const phoneCol = "w-36 hidden xl:table-cell"; if (isLoading) { return ( @@ -1274,54 +1273,9 @@ function ContactsTableBody({ onChange={onToggleAll} /> - Name - Company - {!embedded && Phone} - - {/* Below sm the pill is its icon alone, so the column - narrows to it and the label waits for the room — - but never leaves the accessibility tree. */} - {embedded ? "Progress" : "Status"} - {embedded ? "Progress" : "Status"} - - {embedded && ( - <> - - - Opened - - - - - - Clicked - Replied - - )} - {embedded ? ( - <> - Current step - - - Sender - - - - - - - ) : ( - Campaigns - )} - - {embedded ? "Last activity" : "Added"} - + {columns.map((col) => ( + + ))} @@ -1377,152 +1331,14 @@ function ContactsTableBody({ onChange={() => onToggle(c.id, !isSel)} /> - -
-
- - {(c.first_name || c.email)?.slice(0, 2).toUpperCase()} - -
- {/* flex-1, not shrink-to-fit: the chip cap below is a - percentage, so this has to be the column's width and - not the name's. */} -
-
- {name} - {/* One tag, then a count. The Name column is a fixed width - now, and two tags sharing it with a name left each of them - about three legible characters. The tags take at most 45% - of the line, and the +N tooltip names the rest in full. */} - {c.categories && c.categories.length > 0 && ( - - - {c.categories.length > 1 && ( - x.title).join(", ")} - > - +{c.categories.length - 1} - - )} - - )} -
-
- - {c.email} - -
-
-
- - - {c.company ? ( -
- - - {c.company} - -
- ) : ( - — - )} - - {!embedded && ( - - {c.phone ? ( -
- - - {c.phone} - -
- ) : ( - — - )} + {columns.map((col) => ( + + {col.cell({ c, lead, processed: !!processed, embedded: !!embedded })} - )} - - {embedded ? ( - - ) : ( - - )} - - {embedded && ( - <> - 0} - Icon={MailOpenIcon} - label="opened" - auto={(lead?.machine_opened ?? 0) > 0} - /> - 0} - Icon={MousePointerClickIcon} - label="clicked" - /> - 0} - Icon={CornerUpLeftIcon} - label="replied" - /> - - )} - {embedded ? ( - <> - - {lead?.current_step ? ( - - {lead.current_step} - - ) : ( - Not started - )} - - - {lead?.sender ? ( - - {lead.sender} - - ) : ( - Not assigned - )} - - - ) : ( - - {c.campaigns?.length ?? 0} - - )} - - {embedded - ? lead?.last_activity_at - ? new Date(lead.last_activity_at).toLocaleDateString("en-US", { - month: "short", - day: "numeric", - }) - : "—" - : c.created_at - ? new Date(c.created_at).toLocaleDateString("en-US", { - month: "short", - day: "numeric", - }) - : "—"} - + ))} e.stopPropagation()}> {/* Touch-safe: always visible on mobile, hover-reveal on desktop. */}
@@ -1586,134 +1402,31 @@ function ContactsTableBody({ ); } -function Th({ children, className }: { children: React.ReactNode; className?: string }) { +// A header cell. A sortable column's header is the sort control: the arrow +// shows on hover, and stays while the column is the active sort. +function Th({ col, sort, onSort }: { col: ContactColumn; sort: ViewSortState; onSort: (col: ContactColumn) => void }) { + const base = `px-3 py-2 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em] truncate ${columnClass(col)}`; + const content = col.header ?? col.label; + if (!col.sortKey) return {content}; + const active = sort.by === col.sortKey; + const Dir = sort.reverse ? ArrowUpIcon : ArrowDownIcon; return ( - - {children} + + ); } -function StatusPill({ subscribed }: { subscribed: boolean }) { - const label = subscribed ? "subscribed" : "unsubscribed"; - return ( - - - {/* The dot carries the state on its own below sm, so the word stays - for screen readers at every width and the visible copy is the - one that comes and goes. */} - {label} - - {label} - - - ); -} - -// One engagement column of the Leads view. A count of steps engaged, a dash -// for a lead that was sent but never did, and blank for a lead never emailed. -// A machine-only open (Apple MPP prefetch) reads "auto" so it is not mistaken -// for a person. -function EngagementCell({ - n, - sent, - Icon, - label, - auto = false, -}: { - n: number; - sent: boolean; - Icon: typeof MailOpenIcon; - label: string; - auto?: boolean; -}) { - return ( - - {n > 0 ? ( - - - {n} - - ) : auto ? ( - - auto - - ) : sent ? ( - - — - - ) : null} - - ); -} - -// Per-lead processing state inside a campaign (campaign Leads view only). -// `active` renders the animated dot-grid loader (the same "processing" motif -// used across the app); every other state is a distinct lucide icon. -const LEAD_META: Record< - LeadStatus, - { label: string; dot: string; text: string; Icon: typeof ClockIcon } -> = { - pending: { label: "Queued", dot: "bg-slate-300", text: "text-slate-500", Icon: ClockIcon }, - active: { label: "Processing", dot: "bg-sky-500", text: "text-sky-700", Icon: ClockIcon }, - completed: { label: "Done", dot: "bg-indigo-500", text: "text-indigo-700", Icon: CheckIcon }, - replied: { label: "Replied", dot: "bg-emerald-500", text: "text-emerald-700", Icon: CornerUpLeftIcon }, - bounced: { label: "Bounced", dot: "bg-rose-500", text: "text-rose-600", Icon: AlertTriangleIcon }, - failed: { label: "Failed", dot: "bg-rose-500", text: "text-rose-600", Icon: AlertTriangleIcon }, - unsubscribed: { label: "Unsubscribed", dot: "bg-slate-300", text: "text-slate-400", Icon: BanIcon }, - paused: { label: "Paused", dot: "bg-violet-400", text: "text-violet-600", Icon: PauseIcon }, - undeliverable: { label: "Undeliverable", dot: "bg-amber-500", text: "text-amber-600", Icon: AlertTriangleIcon }, -}; - -function LeadStatusPill({ lead }: { lead?: ContactCampaignProgress | null }) { - const status: LeadStatus = lead?.status ?? "pending"; - const meta = LEAD_META[status]; - const Icon = meta.Icon; - // A failed lead carries the worker's reason; surface it on hover since the - // pill itself only has room for the word. - const title = - status === "failed" && lead?.failure_reason - ? `Could not send: ${lead.failure_reason}` - : status === "undeliverable" - ? "Address verification refused this recipient, so the campaign skips it" - : lead?.hold - ? holdSummary(lead.hold) - : undefined; - return ( - - {status === "active" ? ( - - ) : ( - - )} - {meta.label} - {/* The reason, when there is one, is worth more than the word it - covers — and React owning the attribute is what clears any word - the tooltip helper left here before the lead changed state. */} - - {meta.label} - - - ); -} - // Compact campaign-state strip above the Leads list: a segmented bar + per-state // counts, so you can see at a glance how the campaign is processing its leads. // diff --git a/web/src/components/app/contacts/ViewControls.tsx b/web/src/components/app/contacts/ViewControls.tsx new file mode 100644 index 000000000..41ea0666b --- /dev/null +++ b/web/src/components/app/contacts/ViewControls.tsx @@ -0,0 +1,288 @@ +// The toolbar controls of a saved view: which columns the contacts table shows +// (with drag to reorder) and how it sorts. Both write through the member's view +// preferences, so the list looks the same on their next visit and on their +// other devices. + +import React from "react"; +import { Reorder, useDragControls } from "framer-motion"; +import { ArrowDownIcon, ArrowUpIcon, CheckIcon, Columns3Icon, GripVerticalIcon, LockIcon, RotateCcwIcon } from "lucide-react"; +import type { SearchContactsSortBy } from "@/lib/api/models/app/contacts/search-contacts.types"; +import { + PopoverMenu, + PopoverMenuContent, + PopoverMenuItem, + PopoverMenuLabel, + PopoverMenuSeparator, + PopoverMenuTrigger, + SelectButton, +} from "@/components/ui/popover-menu"; +import { customColumnId, type ContactColumn } from "./columns"; + +export interface ViewSortState { + by: SearchContactsSortBy; + reverse: boolean; +} + +function CheckSquare({ checked }: { checked: boolean }) { + return ( + + {checked && } + + ); +} + +function ColumnLabel({ col }: { col: ContactColumn }) { + return ( + <> + {col.label} + {col.custom && ( + custom + )} + + ); +} + +// A shown column: drag by the grip, click the rest of the row to hide it. +function ShownRow({ col, onHide }: { col: ContactColumn; onHide: () => void }) { + const controls = useDragControls(); + return ( + +
+ controls.start(e)} + className="size-5 flex items-center justify-center cursor-grab active:cursor-grabbing text-slate-300 hover:text-slate-500 touch-none" + aria-label={`Drag to move ${col.label}`} + role="button" + > + + + +
+
+ ); +} + +function PlainRow({ col, checked, onClick }: { col: ContactColumn; checked: boolean; onClick: () => void }) { + return ( + + ); +} + +function GroupLabel({ children }: { children: React.ReactNode }) { + return ( +
{children}
+ ); +} + +export function ColumnChooser({ + visible, + available, + customized, + onChange, + onReset, +}: { + // In display order, Name first. + visible: ContactColumn[]; + // Built-in columns not shown, then custom fields not shown. + available: ContactColumn[]; + customized: boolean; + // The ids of the shown columns after Name, in order. + onChange: (ids: string[]) => void; + onReset: () => void; +}) { + const [open, setOpen] = React.useState(false); + const [query, setQuery] = React.useState(""); + const q = query.trim().toLowerCase(); + const matches = (c: ContactColumn) => !q || c.label.toLowerCase().includes(q); + + const locked = visible.filter((c) => c.locked); + const shown = visible.filter((c) => !c.locked); + const ids = () => shown.map((c) => c.id); + const hide = (id: string) => onChange(ids().filter((x) => x !== id)); + const show = (id: string) => onChange([...ids(), id]); + + const builtinAvail = available.filter((c) => !c.custom && matches(c)); + const customAvail = available.filter((c) => !!c.custom && matches(c)); + const shownMatches = shown.filter(matches); + const nothing = shownMatches.length === 0 && builtinAvail.length === 0 && customAvail.length === 0 && !locked.some(matches); + + return ( + { setOpen(o); if (!o) setQuery(""); }}> + + } + label="Columns" + className={customized ? "border-sky-200 text-sky-700 hover:text-sky-800" : undefined} + aria-label="Choose columns" + /> + + +
+ setQuery(e.target.value)} + placeholder="Search columns…" + autoFocus + className="w-full h-5 bg-transparent text-[12px] text-slate-900 placeholder:text-slate-400 outline-none" + /> +
+
+ {nothing && ( +
No column matches.
+ )} + {(locked.some(matches) || shownMatches.length > 0) && ( + {q ? "Shown" : "Shown · drag to reorder"} + )} + {locked.filter(matches).map((col) => ( +
+ + + + + {col.label} +
+ ))} + {q ? ( + shownMatches.map((col) => ( + hide(col.id)} /> + )) + ) : ( + onChange(next.map((c) => c.id))} + > + {shown.map((col) => ( + hide(col.id)} /> + ))} + + )} + {builtinAvail.length > 0 && ( + <> + Available + {builtinAvail.map((col) => ( + show(col.id)} /> + ))} + + )} + {customAvail.length > 0 && ( + <> + Custom fields + {customAvail.map((col) => ( + show(col.id)} /> + ))} + + )} +
+
+ + {visible.length} of {visible.length + available.length} shown + + +
+
+
+ ); +} + +// The sort menu: every built-in sort, then the workspace's custom fields. A +// header click reaches the same state for the columns on screen; this is how +// the hidden ones, and a phone, get there. +export function SortMenu({ + sort, + options, + customKeys, + onChange, +}: { + sort: ViewSortState; + options: { key: SearchContactsSortBy; label: string }[]; + customKeys: string[]; + onChange: (next: ViewSortState) => void; +}) { + const active = [...options, ...customKeys.map((k) => ({ key: customColumnId(k) as SearchContactsSortBy, label: k }))] + .find((o) => o.key === sort.by); + const Dir = sort.reverse ? ArrowUpIcon : ArrowDownIcon; + return ( + + + } + label={active ? active.label : "Sort"} + aria-label="Sort" + /> + + + Sort by + {options.map((o) => ( + onChange({ by: o.key, reverse: sort.by === o.key ? sort.reverse : false })} + > + {o.label} + + ))} + {customKeys.length > 0 && ( + <> + + Custom fields + {customKeys.map((k) => { + const key = customColumnId(k) as SearchContactsSortBy; + return ( + onChange({ by: key, reverse: sort.by === key ? sort.reverse : true })} + > + {k} + + ); + })} + + )} + + onChange({ ...sort, reverse: !sort.reverse })} + closeOnSelect={false} + > + Reverse order + + + + ); +} diff --git a/web/src/components/app/contacts/cells.tsx b/web/src/components/app/contacts/cells.tsx new file mode 100644 index 000000000..b5a40582b --- /dev/null +++ b/web/src/components/app/contacts/cells.tsx @@ -0,0 +1,149 @@ +// Cell content shared by the contacts table's columns: the subscription pill, +// the per-lead processing pill, and the engagement counts of the Leads view. +// They live apart from the table so the column registry can render them +// without importing the table that renders the registry. + +import { AlertTriangleIcon, BanIcon, CheckIcon, ClockIcon, CornerUpLeftIcon, InfoIcon, PauseIcon, type LucideIcon } from "lucide-react"; +import clippedTitle from "@/lib/helper/clippedTitle"; +import { holdSummary } from "@/lib/api/models/app/contacts/Contact"; +import type { ContactCampaignProgress, LeadStatus } from "@/lib/api/models/app/contacts/Contact"; + +// The empty-value mark every optional column shares. +export function Dash() { + return —; +} + +// A header with an info tooltip beside the label. +export function InfoHeader({ label, title, aria }: { label: string; title: string; aria: string }) { + return ( + + {label} + + + + + ); +} + +export function StatusPill({ subscribed }: { subscribed: boolean }) { + const label = subscribed ? "subscribed" : "unsubscribed"; + return ( + + + {/* The dot carries the state on its own below sm, so the word stays + for screen readers at every width and the visible copy is the + one that comes and goes. */} + {label} + + {label} + + + ); +} + +// One engagement count of the Leads view. A count of steps engaged, a dash +// for a lead that was sent but never did, and blank for a lead never emailed. +// A machine-only open (Apple MPP prefetch) reads "auto" so it is not mistaken +// for a person. +export function EngagementValue({ + n, + sent, + Icon, + label, + auto = false, +}: { + n: number; + sent: boolean; + Icon: LucideIcon; + label: string; + auto?: boolean; +}) { + if (n > 0) { + return ( + + + {n} + + ); + } + if (auto) { + return ( + + auto + + ); + } + if (sent) { + return ( + + — + + ); + } + return null; +} + +// Per-lead processing state inside a campaign (campaign Leads view only). +// `active` renders the animated dot-grid loader (the same "processing" motif +// used across the app); every other state is a distinct lucide icon. +const LEAD_META: Record< + LeadStatus, + { label: string; dot: string; text: string; Icon: LucideIcon } +> = { + pending: { label: "Queued", dot: "bg-slate-300", text: "text-slate-500", Icon: ClockIcon }, + active: { label: "Processing", dot: "bg-sky-500", text: "text-sky-700", Icon: ClockIcon }, + completed: { label: "Done", dot: "bg-indigo-500", text: "text-indigo-700", Icon: CheckIcon }, + replied: { label: "Replied", dot: "bg-emerald-500", text: "text-emerald-700", Icon: CornerUpLeftIcon }, + bounced: { label: "Bounced", dot: "bg-rose-500", text: "text-rose-600", Icon: AlertTriangleIcon }, + failed: { label: "Failed", dot: "bg-rose-500", text: "text-rose-600", Icon: AlertTriangleIcon }, + unsubscribed: { label: "Unsubscribed", dot: "bg-slate-300", text: "text-slate-400", Icon: BanIcon }, + paused: { label: "Paused", dot: "bg-violet-400", text: "text-violet-600", Icon: PauseIcon }, + undeliverable: { label: "Undeliverable", dot: "bg-amber-500", text: "text-amber-600", Icon: AlertTriangleIcon }, +}; + +export function LeadStatusPill({ lead }: { lead?: ContactCampaignProgress | null }) { + const status: LeadStatus = lead?.status ?? "pending"; + const meta = LEAD_META[status]; + const Icon = meta.Icon; + // A failed lead carries the worker's reason; surface it on hover since the + // pill itself only has room for the word. + const title = + status === "failed" && lead?.failure_reason + ? `Could not send: ${lead.failure_reason}` + : status === "undeliverable" + ? "Address verification refused this recipient, so the campaign skips it" + : lead?.hold + ? holdSummary(lead.hold) + : undefined; + return ( + + {status === "active" ? ( + + ) : ( + + )} + {meta.label} + {/* The reason, when there is one, is worth more than the word it + covers — and React owning the attribute is what clears any word + the tooltip helper left here before the lead changed state. */} + + {meta.label} + + + ); +} diff --git a/web/src/components/app/contacts/columns.test.ts b/web/src/components/app/contacts/columns.test.ts new file mode 100644 index 000000000..9b568fcfc --- /dev/null +++ b/web/src/components/app/contacts/columns.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_COLUMNS, builtinColumns, customColumnId, resolveColumns } from "./columns"; + +describe("resolveColumns", () => { + it("shows the default layout with Name first when nothing is saved", () => { + const { visible, available } = resolveColumns("contacts", undefined, ["Industry"]); + expect(visible.map((c) => c.id)).toEqual(["name", ...DEFAULT_COLUMNS.contacts]); + // Everything the view knows and is not shown is offered, custom fields last. + expect(available.map((c) => c.id)).toEqual(["updated_at", customColumnId("Industry")]); + }); + + it("follows the saved order and keeps Name pinned first", () => { + const { visible } = resolveColumns("contacts", ["phone", "name", "company"], []); + expect(visible.map((c) => c.id)).toEqual(["name", "phone", "company"]); + }); + + it("renders a saved custom field even when no contact carries it any more", () => { + const { visible, available } = resolveColumns("contacts", ["custom:Old Field"], ["Industry"]); + expect(visible.map((c) => c.id)).toEqual(["name", "custom:Old Field"]); + expect(visible[1].label).toBe("Old Field"); + expect(visible[1].custom).toBe("Old Field"); + expect(available.map((c) => c.id)).toContain(customColumnId("Industry")); + expect(available.map((c) => c.id)).not.toContain("custom:Old Field"); + }); + + it("drops ids the view does not know and duplicates", () => { + const { visible } = resolveColumns("campaign_leads", ["status", "opened", "opened", "sender"], []); + // "status" belongs to the contacts view; the Leads view has "progress". + expect(visible.map((c) => c.id)).toEqual(["name", "opened", "sender"]); + }); + + it("gives every non-Name column a width, because the table is table-fixed", () => { + for (const view of ["contacts", "campaign_leads"] as const) { + for (const col of builtinColumns(view)) { + if (col.locked) continue; + expect(col.width, `${view}/${col.id}`).not.toBe(""); + } + } + }); + + it("reads a custom field's value and sorts on it as text", () => { + const { visible } = resolveColumns("contacts", ["custom:Industry"], []); + const col = visible[1]; + expect(col.sortKey).toBe("custom:Industry"); + expect(col.sortAsc).toBe(true); + }); +}); diff --git a/web/src/components/app/contacts/columns.tsx b/web/src/components/app/contacts/columns.tsx new file mode 100644 index 000000000..5be179ab0 --- /dev/null +++ b/web/src/components/app/contacts/columns.tsx @@ -0,0 +1,444 @@ +// The contacts table's column registry. Every column the standalone list and +// the campaign Leads view can show is defined once here: its header, width, +// breakpoint, sort key and cell. The table renders whatever ordered subset the +// member's saved view names, so the header and the rows can never drift apart, +// and a custom field becomes a column by naming it ("custom:Industry"). + +import React from "react"; +import { + Building2Icon, + CornerUpLeftIcon, + MailIcon, + MailOpenIcon, + MousePointerClickIcon, + PhoneIcon, + type LucideIcon, +} from "lucide-react"; +import clippedTitle from "@/lib/helper/clippedTitle"; +import type { ContactCampaignProgress, VerificationSource, VerificationStatus } from "@/lib/api/models/app/contacts/Contact"; +import type { SearchContactsSortBy } from "@/lib/api/models/app/contacts/search-contacts.types"; +import type { ViewName } from "@/lib/api/models/app/views/ViewPreferences"; +import { CategoryChip } from "./CategoryPicker"; +import VerificationBadge from "./VerificationBadge"; +import { Dash, EngagementValue, InfoHeader, LeadStatusPill, StatusPill } from "./cells"; + +// The fields a row needs to render any column. Structural rather than the full +// Contact so the campaign pickers' lighter rows still fit. +export interface ContactRow { + id: string; + first_name: string; + last_name: string; + email: string; + company: string; + phone: string; + subscribed: boolean; + campaigns: { id: string }[]; + categories?: { id: string; title: string; color: string }[]; + campaign_lead?: ContactCampaignProgress | null; + custom_fields?: Record; + verification_status?: VerificationStatus; + verification_sub_status?: string; + verification_source?: VerificationSource; + verification_provider?: string; + verification_checked_at?: string | null; + verification_confidence?: number; + created_at: Date; + updated_at?: Date; +} + +export interface CellContext { + c: ContactRow; + lead: ContactCampaignProgress | null | undefined; + // A terminal lead in the Leads view renders muted. + processed: boolean; + embedded: boolean; +} + +export type Breakpoint = "sm" | "md" | "lg" | "xl" | "2xl"; + +export interface ContactColumn { + id: string; + label: string; + // Richer header content (an info tooltip); the label stays the plain name. + header?: React.ReactNode; + // A Tailwind width class. Every column but Name carries one: the table is + // table-fixed (issue #461), and Name takes whatever the sized ones leave. + width: string; + // The breakpoint the column appears at. Below it the column is hidden and + // the drawer still has the value. + hideBelow?: Breakpoint; + align?: "right"; + sortKey?: SearchContactsSortBy; + // Whether the first click on the header sorts ascending (text) rather than + // descending (dates and counts, where newest or most is what people want). + sortAsc?: boolean; + cellClassName?: string; + cell: (ctx: CellContext) => React.ReactNode; + // Name: always shown, always first, never offered in the chooser. + locked?: boolean; + // The custom-field key this column shows, for the custom columns. + custom?: string; +} + +const HIDE: Record = { + sm: "hidden sm:table-cell", + md: "hidden md:table-cell", + lg: "hidden lg:table-cell", + xl: "hidden xl:table-cell", + "2xl": "hidden 2xl:table-cell", +}; + +// The classes a column's header and cells share: width, breakpoint, alignment. +export function columnClass(col: ContactColumn): string { + return [col.width, col.hideBelow ? HIDE[col.hideBelow] : "", col.align === "right" ? "text-right" : ""] + .filter(Boolean) + .join(" "); +} + +export const CUSTOM_COLUMN_PREFIX = "custom:"; +export const customColumnId = (key: string) => `${CUSTOM_COLUMN_PREFIX}${key}`; +export const isCustomColumnId = (id: string) => id.startsWith(CUSTOM_COLUMN_PREFIX); +export const customKeyOf = (id: string) => id.slice(CUSTOM_COLUMN_PREFIX.length); + +function shortDate(d: Date | string | null | undefined): string { + if (!d) return "—"; + return new Date(d).toLocaleDateString("en-US", { month: "short", day: "numeric" }); +} + +const nameColumn: ContactColumn = { + id: "name", + label: "Name", + width: "", + sortKey: "first_name", + sortAsc: true, + locked: true, + cell: ({ c, processed }) => { + const name = + (c.first_name || c.last_name) + ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() + : c.email; + return ( +
+
+ + {(c.first_name || c.email)?.slice(0, 2).toUpperCase()} + +
+ {/* flex-1, not shrink-to-fit: the chip cap below is a + percentage, so this has to be the column's width and + not the name's. */} +
+
+ {name} + {/* One tag, then a count. The Name column is a fixed width + now, and two tags sharing it with a name left each of them + about three legible characters. The tags take at most 45% + of the line, and the +N tooltip names the rest in full. */} + {c.categories && c.categories.length > 0 && ( + + + {c.categories.length > 1 && ( + x.title).join(", ")} + > + +{c.categories.length - 1} + + )} + + )} +
+
+ + {c.email} + +
+
+
+ ); + }, +}; + +// Name is the only auto-width column, so it takes every pixel the sized columns +// leave. Which breakpoint each sized column appears at is then just "does Name +// still clear ~170px": Leads carries five campaign columns Contacts does not, so +// company waits longer for room there. +function companyColumn(view: ViewName): ContactColumn { + return { + id: "company", + label: "Company", + width: view === "campaign_leads" ? "w-40" : "w-36", + hideBelow: view === "campaign_leads" ? "xl" : "lg", + sortKey: "company", + sortAsc: true, + cellClassName: "text-[12px] text-slate-600", + cell: ({ c }) => + c.company ? ( +
+ + {c.company} +
+ ) : ( + + ), + }; +} + +const phoneColumn: ContactColumn = { + id: "phone", + label: "Phone", + width: "w-36", + hideBelow: "xl", + sortKey: "phone", + sortAsc: true, + cellClassName: "text-[12px] text-slate-600 font-mono", + cell: ({ c }) => + c.phone ? ( +
+ + {c.phone} +
+ ) : ( + + ), +}; + +// Below sm the pill is its icon alone, so the column narrows to it and the +// label waits for the room, but never leaves the accessibility tree. +function statusHeader(label: string) { + return ( + <> + {label} + {label} + + ); +} + +const statusColumn: ContactColumn = { + id: "status", + label: "Status", + header: statusHeader("Status"), + width: "w-12 sm:w-32", + cell: ({ c }) => , +}; + +const progressColumn: ContactColumn = { + id: "progress", + label: "Progress", + header: statusHeader("Progress"), + width: "w-12 sm:w-32", + cell: ({ lead }) => , +}; + +const engagement = ( + id: "opened" | "clicked" | "replied", + label: string, + Icon: LucideIcon, + header?: React.ReactNode, +): ContactColumn => ({ + id, + label, + header, + width: "w-24", + hideBelow: "lg", + cell: ({ lead }) => ( + 0} + Icon={Icon} + label={id} + auto={id === "opened" && (lead?.machine_opened ?? 0) > 0} + /> + ), +}); + +const currentStepColumn: ContactColumn = { + id: "current_step", + label: "Current step", + width: "w-32", + hideBelow: "xl", + cell: ({ lead, processed }) => + lead?.current_step ? ( + + {lead.current_step} + + ) : ( + Not started + ), +}; + +const senderColumn: ContactColumn = { + id: "sender", + label: "Sender", + header: ( + + ), + width: "w-36", + hideBelow: "2xl", + cell: ({ lead }) => + lead?.sender ? ( + + {lead.sender} + + ) : ( + Not assigned + ), +}; + +const campaignsColumn: ContactColumn = { + id: "campaigns", + label: "Campaigns", + width: "w-28", + hideBelow: "lg", + align: "right", + sortKey: "campaign_count", + cellClassName: "font-mono text-[12px] text-slate-600 tabular-nums", + cell: ({ c }) => c.campaigns?.length ?? 0, +}; + +const dateCell = "font-mono text-[11px] text-slate-500 tabular-nums"; + +const addedColumn = (view: ViewName): ContactColumn => ({ + id: "created_at", + label: "Added", + width: view === "campaign_leads" ? "w-32" : "w-24", + hideBelow: view === "campaign_leads" ? "2xl" : "md", + align: "right", + sortKey: "created_at", + cellClassName: dateCell, + cell: ({ c }) => shortDate(c.created_at), +}); + +const updatedColumn: ContactColumn = { + id: "updated_at", + label: "Updated", + width: "w-24", + hideBelow: "md", + align: "right", + sortKey: "updated_at", + cellClassName: dateCell, + cell: ({ c }) => shortDate(c.updated_at), +}; + +const lastActivityColumn: ContactColumn = { + id: "last_activity", + label: "Last activity", + width: "w-32", + hideBelow: "2xl", + align: "right", + cellClassName: dateCell, + cell: ({ lead }) => shortDate(lead?.last_activity_at), +}; + +// A contact custom field as a column. Text, sortable, and hidden below md so +// the phone layout stays a name-and-status list. +export function customColumn(key: string): ContactColumn { + return { + id: customColumnId(key), + label: key, + width: "w-36", + hideBelow: "md", + sortKey: customColumnId(key) as SearchContactsSortBy, + sortAsc: true, + custom: key, + cellClassName: "text-[12px] text-slate-600", + cell: ({ c }) => { + const v = c.custom_fields?.[key]; + return v ? {v} : ; + }, + }; +} + +// Every built-in column a view can show, in its natural order. The chooser +// lists them in this order under "Available". +export function builtinColumns(view: ViewName): ContactColumn[] { + if (view === "campaign_leads") { + return [ + nameColumn, + companyColumn(view), + phoneColumn, + progressColumn, + engagement( + "opened", + "Opened", + MailOpenIcon, + , + ), + engagement("clicked", "Clicked", MousePointerClickIcon), + engagement("replied", "Replied", CornerUpLeftIcon), + currentStepColumn, + senderColumn, + lastActivityColumn, + addedColumn(view), + updatedColumn, + ]; + } + return [nameColumn, companyColumn(view), phoneColumn, statusColumn, campaignsColumn, addedColumn(view), updatedColumn]; +} + +// The layout a member sees before choosing anything, Name implied first. +export const DEFAULT_COLUMNS: Record = { + contacts: ["company", "phone", "status", "campaigns", "created_at"], + campaign_leads: ["company", "progress", "opened", "clicked", "replied", "current_step", "sender", "last_activity"], +}; + +// The columns to render for a saved layout, and the ones the chooser can still +// add. Unknown built-in ids (a column an older build offered) are dropped; a +// custom field is kept even when no contact currently carries it, so the +// column the member picked does not vanish because an import replaced the +// field's name. +export function resolveColumns( + view: ViewName, + saved: string[] | undefined, + customKeys: string[], +): { visible: ContactColumn[]; available: ContactColumn[] } { + const catalogue = builtinColumns(view); + const byId = new Map(catalogue.map((c) => [c.id, c])); + const chosen = saved && saved.length > 0 ? saved : DEFAULT_COLUMNS[view]; + const visible: ContactColumn[] = []; + const seen = new Set(); + for (const id of chosen) { + if (seen.has(id)) continue; + const col = byId.get(id) ?? (isCustomColumnId(id) ? customColumn(customKeyOf(id)) : undefined); + if (!col || col.locked) continue; + visible.push(col); + seen.add(id); + } + visible.unshift(nameColumn); + const available = [ + ...catalogue.filter((c) => !c.locked && !seen.has(c.id)), + ...customKeys.filter((k) => !seen.has(customColumnId(k))).map(customColumn), + ]; + return { visible, available }; +} + +// The sort choices the toolbar menu offers, beyond what a header click reaches. +export function sortOptions(view: ViewName): { key: SearchContactsSortBy; label: string }[] { + const base: { key: SearchContactsSortBy; label: string }[] = [ + { key: "created_at", label: "Date added" }, + { key: "updated_at", label: "Last updated" }, + { key: "first_name", label: "First name" }, + { key: "last_name", label: "Last name" }, + { key: "email", label: "Email" }, + { key: "company", label: "Company" }, + { key: "phone", label: "Phone" }, + ]; + if (view === "contacts") base.push({ key: "campaign_count", label: "Campaigns" }); + return base; +} diff --git a/web/src/components/app/contacts/useContactView.ts b/web/src/components/app/contacts/useContactView.ts new file mode 100644 index 000000000..49ac43c61 --- /dev/null +++ b/web/src/components/app/contacts/useContactView.ts @@ -0,0 +1,54 @@ +// The member's saved layout of a contacts list, resolved against the column +// registry and the workspace's custom fields. One hook, so the table, the +// chooser and the sort menu read the same view. + +import React from "react"; +import { useCurrentOrg } from "@/stores/useAppStore"; +import useCustomFieldKeys from "@/lib/api/hooks/app/contacts/useCustomFieldKeys"; +import { + useResetViewPreferences, + useUpdateViewPreferences, + useViewPreferences, +} from "@/lib/api/hooks/app/views/useViewPreferences"; +import type { ViewName, ViewSort } from "@/lib/api/models/app/views/ViewPreferences"; +import { resolveColumns } from "./columns"; + +export function useContactView(view: ViewName) { + const org = useCurrentOrg(); + const orgId = org?.id ?? ""; + const prefs = useViewPreferences(view, orgId); + const update = useUpdateViewPreferences(view, orgId); + const reset = useResetViewPreferences(view, orgId); + const keys = useCustomFieldKeys(); + + const saved = prefs.data; + const savedColumns = saved?.columns; + const customKeys = React.useMemo(() => keys.data ?? [], [keys.data]); + const { visible, available } = React.useMemo( + () => resolveColumns(view, savedColumns, customKeys), + [view, savedColumns, customKeys], + ); + + const setColumns = React.useCallback( + (ids: string[]) => update.mutate({ columns: ids, sort: saved?.sort ?? null }), + [update, saved?.sort], + ); + const setSort = React.useCallback( + (sort: ViewSort) => update.mutate({ columns: saved?.columns ?? [], sort }), + [update, saved?.columns], + ); + + return { + orgId, + columns: visible, + available, + customKeys, + savedSort: saved?.sort ?? null, + // True once the server's copy is in hand (not the browser's cached one). + loaded: prefs.isSuccess && !prefs.isPlaceholderData, + customized: (savedColumns?.length ?? 0) > 0, + setColumns, + setSort, + reset: () => reset.mutate(), + }; +} diff --git a/web/src/lib/api/client/app/views/views.ts b/web/src/lib/api/client/app/views/views.ts new file mode 100644 index 000000000..e6810a34d --- /dev/null +++ b/web/src/lib/api/client/app/views/views.ts @@ -0,0 +1,33 @@ +import type { + UpdateViewPreferences, + ViewName, + ViewPreferencesEnvelope, +} from "@/lib/api/models/app/views/ViewPreferences"; +import Request from "../../Request"; + +// GET /me/views/:view — the caller's saved layout for one list, or the empty +// layout when none is saved. Scoped to the current workspace by the org header. +export async function getViewPreferences(view: ViewName): Promise { + return await Request({ + method: "GET", + url: `/me/views/${view}`, + authorization: true, + }); +} + +export async function updateViewPreferences(view: ViewName, body: UpdateViewPreferences): Promise { + return await Request({ + method: "PUT", + url: `/me/views/${view}`, + data: body, + authorization: true, + }); +} + +export async function resetViewPreferences(view: ViewName): Promise { + await Request({ + method: "DELETE", + url: `/me/views/${view}`, + authorization: true, + }); +} diff --git a/web/src/lib/api/hooks/app/views/useViewPreferences.ts b/web/src/lib/api/hooks/app/views/useViewPreferences.ts new file mode 100644 index 000000000..61456ab15 --- /dev/null +++ b/web/src/lib/api/hooks/app/views/useViewPreferences.ts @@ -0,0 +1,107 @@ +import React from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import toast from "react-hot-toast"; +import { + getViewPreferences, + resetViewPreferences, + updateViewPreferences, +} from "@/lib/api/client/app/views/views"; +import type { + UpdateViewPreferences, + ViewName, + ViewPreferences, +} from "@/lib/api/models/app/views/ViewPreferences"; + +const queryKey = (orgId: string, view: ViewName) => ["views", orgId, view]; +const cacheKey = (orgId: string, view: ViewName) => `warmbly:view:${orgId}:${view}`; + +// The server is the source of truth; the browser keeps a copy so the list +// paints with the member's columns on the first frame instead of flashing the +// defaults while the request is in flight. Anything malformed is ignored. +export function readCachedView(orgId: string, view: ViewName): ViewPreferences | undefined { + if (!orgId) return undefined; + try { + const raw = localStorage.getItem(cacheKey(orgId, view)); + if (!raw) return undefined; + const p = JSON.parse(raw) as Partial | null; + if (!p || !Array.isArray(p.columns)) return undefined; + const sort = + p.sort && typeof p.sort.by === "string" && p.sort.by + ? { by: p.sort.by, reverse: !!p.sort.reverse } + : null; + return { view, columns: p.columns.filter((c): c is string => typeof c === "string"), sort }; + } catch { + return undefined; + } +} + +function writeCachedView(orgId: string, view: ViewName, prefs: ViewPreferences | null) { + if (!orgId) return; + try { + if (!prefs) localStorage.removeItem(cacheKey(orgId, view)); + else localStorage.setItem(cacheKey(orgId, view), JSON.stringify({ columns: prefs.columns, sort: prefs.sort ?? null })); + } catch { + /* storage full or blocked: the server copy still applies */ + } +} + +export function useViewPreferences(view: ViewName, orgId: string) { + const q = useQuery({ + queryKey: queryKey(orgId, view), + queryFn: async () => (await getViewPreferences(view)).preferences, + enabled: !!orgId, + staleTime: 5 * 60 * 1000, + placeholderData: () => readCachedView(orgId, view), + }); + React.useEffect(() => { + if (q.data && !q.isPlaceholderData) writeCachedView(orgId, view, q.data); + }, [q.data, q.isPlaceholderData, orgId, view]); + return q; +} + +// Optimistic: the table re-lays out on the click, and the row is written +// behind it. A failure puts the previous layout back and says so. +export function useUpdateViewPreferences(view: ViewName, orgId: string) { + const qc = useQueryClient(); + const key = queryKey(orgId, view); + return useMutation({ + mutationFn: (body: UpdateViewPreferences) => updateViewPreferences(view, body), + onMutate: async (body) => { + await qc.cancelQueries({ queryKey: key }); + const previous = qc.getQueryData(key); + const next: ViewPreferences = { view, columns: body.columns, sort: body.sort }; + qc.setQueryData(key, next); + writeCachedView(orgId, view, next); + return { previous }; + }, + onError: (_err, _body, ctx) => { + qc.setQueryData(key, ctx?.previous); + writeCachedView(orgId, view, ctx?.previous ?? null); + toast.error("Couldn't save your view. It will reset when you reload."); + }, + onSuccess: (envelope) => { + qc.setQueryData(key, envelope.preferences); + writeCachedView(orgId, view, envelope.preferences); + }, + }); +} + +export function useResetViewPreferences(view: ViewName, orgId: string) { + const qc = useQueryClient(); + const key = queryKey(orgId, view); + return useMutation({ + mutationFn: () => resetViewPreferences(view), + onMutate: async () => { + await qc.cancelQueries({ queryKey: key }); + const previous = qc.getQueryData(key); + qc.setQueryData(key, { view, columns: [], sort: null }); + writeCachedView(orgId, view, null); + return { previous }; + }, + onError: (_err, _v, ctx) => { + qc.setQueryData(key, ctx?.previous); + writeCachedView(orgId, view, ctx?.previous ?? null); + toast.error("Couldn't reset the view."); + }, + }); +} diff --git a/web/src/lib/api/models/app/contacts/search-contacts.types.ts b/web/src/lib/api/models/app/contacts/search-contacts.types.ts index b06ddb603..8ef4d7194 100644 --- a/web/src/lib/api/models/app/contacts/search-contacts.types.ts +++ b/web/src/lib/api/models/app/contacts/search-contacts.types.ts @@ -1,5 +1,16 @@ +// A built-in sort column, or "custom:" to order on a contact custom +// field. Custom fields sort as text with rows lacking the field grouped at the +// end when ascending and the start when descending. export type SearchContactsSortBy = - 'created_at' | 'updated_at' | 'first_name' | 'last_name' | 'email' | 'campaign_count'; + | 'created_at' + | 'updated_at' + | 'first_name' + | 'last_name' + | 'email' + | 'company' + | 'phone' + | 'campaign_count' + | `custom:${string}`; export type SearchContactsFilterType = 'equal' | 'starts_with' | 'ends_with' | 'contains'; diff --git a/web/src/lib/api/models/app/views/ViewPreferences.ts b/web/src/lib/api/models/app/views/ViewPreferences.ts new file mode 100644 index 000000000..d05894cc4 --- /dev/null +++ b/web/src/lib/api/models/app/views/ViewPreferences.ts @@ -0,0 +1,28 @@ +// A member's own layout of one dashboard list in the current workspace: the +// columns shown (in order, Name implied first) and the sort. Mirrors +// models.ViewPreferences on the backend. + +export type ViewName = "contacts" | "campaign_leads"; + +export interface ViewSort { + by: string; + reverse: boolean; +} + +export interface ViewPreferences { + view: ViewName; + // Column ids in display order. Empty means the list's default layout. + columns: string[]; + // Null or absent means the list's default sort. + sort?: ViewSort | null; + updated_at?: string | null; +} + +export interface ViewPreferencesEnvelope { + preferences: ViewPreferences; +} + +export interface UpdateViewPreferences { + columns: string[]; + sort: ViewSort | null; +} From ed50c278fa1a448d34594996b20115c491cf2174 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 19 Sep 2026 09:38:59 -0700 Subject: [PATCH 2/3] feat: make view-preference writes partial so a sort click before the layout loads keeps the saved columns (PUT /me/views/:view coalesces on the bound parameter and returns the row in one query, with a live test), validate column ids against each view's known columns and sorts against the contacts search's, reject a malformed custom sort on the bulk select-all and export paths too, key the browser's layout cache by user as well as workspace, commit a drag reorder once on drop instead of once per crossed row, save a Name-only layout as ["name"] so it cannot read as the default, start text sorts ascending from the Sort menu as a header click does, and share the pickers' checkbox square as a ui primitive --- docs/content/docs/api/error-codes.mdx | 4 +- internal/api/handler/view_preferences.go | 11 +- internal/app/contact/export.go | 3 + internal/app/contact/selection.go | 5 + internal/app/viewprefs/service.go | 99 +++++++++-------- internal/app/viewprefs/service_test.go | 60 +++++++---- internal/models/view_preferences.go | 22 ++++ internal/repository/pg_view_preferences.go | 72 ++++++++----- .../repository/view_preferences_live_test.go | 102 ++++++++++++++++++ .../components/app/contacts/ContactsTable.tsx | 2 +- .../components/app/contacts/ViewControls.tsx | 64 +++++------ .../components/app/contacts/columns.test.ts | 8 +- web/src/components/app/contacts/columns.tsx | 43 +++++--- .../components/app/contacts/useContactView.ts | 34 +++--- web/src/components/ui/check-square.tsx | 17 +++ .../api/hooks/app/views/useViewPreferences.ts | 67 +++++++----- .../api/models/app/views/ViewPreferences.ts | 6 +- 17 files changed, 428 insertions(+), 191 deletions(-) create mode 100644 internal/repository/view_preferences_live_test.go create mode 100644 web/src/components/ui/check-square.tsx diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index 04988f9ea..3082cf77a 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -76,9 +76,9 @@ Returned when the request cannot be processed due to invalid syntax. | `code` | Meaning | |--------|---------| | `invalid_lead_status` | `POST /contacts/search` or `POST /contacts/export` was given a `lead_status` that is not one of the documented values | -| `invalid_sort_by` | `POST /contacts/search` was given a `sort_by` of the form `custom:` whose key could never be a custom-field name (letters, numbers, underscores, spaces or dashes) | +| `invalid_sort_by` | `POST /contacts/search`, `POST /contacts/export` or a bulk action's `all` selection was given a `sort_by` of the form `custom:` whose key could never be a custom-field name (letters, numbers, underscores, spaces or dashes) | | `unknown_view` | `/me/views/:view` was given a view name other than `contacts` or `campaign_leads` (answered `404`) | -| `invalid_column`, `duplicate_column`, `too_many_columns`, `invalid_sort` | `PUT /me/views/:view` was given a column id the dashboard cannot render, the same column twice, more than 64 columns, or a sort that names neither a built-in column nor a well-formed `custom:` | +| `invalid_column`, `duplicate_column`, `too_many_columns`, `invalid_sort` | `PUT /me/views/:view` was given a column id that view cannot render, the same column twice, more than 64 columns, or a sort that names neither a sortable contact column nor a well-formed `custom:` | | `invalid_engagement` | `POST /contacts/search` or `POST /contacts/export` was given an `engagement` that is not one of the documented values | | `lead_filter_requires_campaign` | `lead_status` or `engagement` was set without exactly one `campaign_ids` entry; both filters describe a contact inside one campaign | | `unknown_verification_status` | A contact's `verification_status` is not a value any known verification service writes | diff --git a/internal/api/handler/view_preferences.go b/internal/api/handler/view_preferences.go index 7601c79cf..938c2fafb 100644 --- a/internal/api/handler/view_preferences.go +++ b/internal/api/handler/view_preferences.go @@ -42,12 +42,15 @@ func (h *Handler) GetViewPreferences(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"preferences": prefs}) } +// A field left out keeps its saved value; "columns": [] is the default layout +// and "sort": {"by": ""} the default sort. type updateViewPreferencesRequest struct { - Columns []string `json:"columns"` + Columns *[]string `json:"columns"` Sort *models.ViewSort `json:"sort"` } -// UpdateViewPreferences replaces the caller's saved layout for one list. +// UpdateViewPreferences writes the caller's saved layout for one list: the +// columns, the sort, or both. // PUT /me/views/:view func (h *Handler) UpdateViewPreferences(c *gin.Context) { uid, orgID, ok := viewActor(c) @@ -59,8 +62,8 @@ func (h *Handler) UpdateViewPreferences(c *gin.Context) { errx.Handle(c, errx.ErrInvalid) return } - prefs := &models.ViewPreferences{View: c.Param("view"), Columns: req.Columns, Sort: req.Sort} - saved, xerr := h.ViewPreferencesService.Put(c.Request.Context(), uid, orgID, prefs) + upd := models.ViewPreferencesUpdate{Columns: req.Columns, Sort: req.Sort} + saved, xerr := h.ViewPreferencesService.Put(c.Request.Context(), uid, orgID, c.Param("view"), upd) if xerr != nil { errx.Handle(c, xerr) return diff --git a/internal/app/contact/export.go b/internal/app/contact/export.go index 159374f42..f5de6343d 100644 --- a/internal/app/contact/export.go +++ b/internal/app/contact/export.go @@ -70,6 +70,9 @@ func (s *contactService) Export( searchFilters = req.Filters } if searchFilters != nil { + if err := validateSort(*searchFilters); err != nil { + return "", "", 0, err + } if err := validateLeadFilters(*searchFilters); err != nil { return "", "", 0, err } diff --git a/internal/app/contact/selection.go b/internal/app/contact/selection.go index 8de2220f0..f60a8a3be 100644 --- a/internal/app/contact/selection.go +++ b/internal/app/contact/selection.go @@ -25,6 +25,11 @@ func (s *contactService) ResolveSelection(ctx context.Context, orgID uuid.UUID, if sel.Filters == nil { return nil, errx.New(errx.BadRequest, "a select-all request must carry the filters it applies to") } + // The same contract as the list: a sort the list would have refused is + // refused here too, rather than quietly acting on a different order. + if xerr := validateSort(*sel.Filters); xerr != nil { + return nil, xerr + } ids, xerr := s.contactRepository.SearchIDs(ctx, orgID.String(), *sel.Filters, models.MaxContactBulkSelection) if xerr != nil { diff --git a/internal/app/viewprefs/service.go b/internal/app/viewprefs/service.go index cbcfeee6a..242dc17f8 100644 --- a/internal/app/viewprefs/service.go +++ b/internal/app/viewprefs/service.go @@ -6,7 +6,6 @@ package viewprefs import ( "context" - "regexp" "strings" "github.com/google/uuid" @@ -23,8 +22,9 @@ type Service interface { // Get returns the saved layout, or the empty layout (default columns, // default sort) when none is saved. Get(ctx context.Context, userID, orgID uuid.UUID, view string) (*models.ViewPreferences, *errx.Error) - // Put replaces the saved layout. - Put(ctx context.Context, userID, orgID uuid.UUID, prefs *models.ViewPreferences) (*models.ViewPreferences, *errx.Error) + // Put writes the fields the update carries and keeps the rest, so the + // columns and the sort can be saved independently. + Put(ctx context.Context, userID, orgID uuid.UUID, view string, upd models.ViewPreferencesUpdate) (*models.ViewPreferences, *errx.Error) // Reset forgets the saved layout, so the list shows its defaults again. Reset(ctx context.Context, userID, orgID uuid.UUID, view string) *errx.Error } @@ -37,12 +37,13 @@ func NewService(repo repository.ViewPreferencesRepository) Service { return &service{repo: repo} } -// A built-in column id is a snake_case name the dashboard defines. -var builtinColumnPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) +func unknownView() *errx.Error { + return errx.NewWithIdentifier(errx.NotFound, "unknown_view", "unknown view") +} func (s *service) Get(ctx context.Context, userID, orgID uuid.UUID, view string) (*models.ViewPreferences, *errx.Error) { if !models.KnownViews[view] { - return nil, errx.NewWithIdentifier(errx.NotFound, "unknown_view", "unknown view") + return nil, unknownView() } prefs, err := s.repo.Get(ctx, userID, orgID, view) if err != nil { @@ -55,23 +56,24 @@ func (s *service) Get(ctx context.Context, userID, orgID uuid.UUID, view string) return prefs, nil } -func (s *service) Put(ctx context.Context, userID, orgID uuid.UUID, prefs *models.ViewPreferences) (*models.ViewPreferences, *errx.Error) { - if !models.KnownViews[prefs.View] { - return nil, errx.NewWithIdentifier(errx.NotFound, "unknown_view", "unknown view") +func (s *service) Put(ctx context.Context, userID, orgID uuid.UUID, view string, upd models.ViewPreferencesUpdate) (*models.ViewPreferences, *errx.Error) { + if !models.KnownViews[view] { + return nil, unknownView() } - if xerr := validate(prefs); xerr != nil { + if xerr := validate(view, &upd); xerr != nil { return nil, xerr } - if err := s.repo.Upsert(ctx, userID, orgID, prefs); err != nil { + saved, err := s.repo.Upsert(ctx, userID, orgID, view, upd) + if err != nil { errs.CaptureException(err) return nil, errx.InternalError() } - return s.Get(ctx, userID, orgID, prefs.View) + return saved, nil } func (s *service) Reset(ctx context.Context, userID, orgID uuid.UUID, view string) *errx.Error { if !models.KnownViews[view] { - return errx.NewWithIdentifier(errx.NotFound, "unknown_view", "unknown view") + return unknownView() } if err := s.repo.Delete(ctx, userID, orgID, view); err != nil { errs.CaptureException(err) @@ -80,43 +82,53 @@ func (s *service) Reset(ctx context.Context, userID, orgID uuid.UUID, view strin return nil } -// validate checks the layout the way the contacts search will read it: every -// column id is one the dashboard can render, listed once, and the sort names a -// built-in column or a well-formed custom field. Custom-field ids are -// normalized in place so the same field saved with different spacing is one -// column. -func validate(prefs *models.ViewPreferences) *errx.Error { - if len(prefs.Columns) > models.ViewPreferencesMaxColumns { - return errx.NewWithIdentifier(errx.BadRequest, "too_many_columns", "too many columns") - } - seen := make(map[string]bool, len(prefs.Columns)) - for i, id := range prefs.Columns { - norm, ok := normalizeColumnID(id) - if !ok { - return errx.NewWithIdentifier(errx.BadRequest, "invalid_column", "invalid column: "+id) +// validate checks the update the way the dashboard will read it: every column +// id is one this view can render or a well-formed custom field, listed once; +// the sort names a column the contacts search knows or a well-formed custom +// field. Custom-field ids are normalized in place so the same field saved with +// different spacing is one column. +func validate(view string, upd *models.ViewPreferencesUpdate) *errx.Error { + if upd.Columns != nil { + cols := *upd.Columns + if len(cols) > models.ViewPreferencesMaxColumns { + return errx.NewWithIdentifier(errx.BadRequest, "too_many_columns", "too many columns") } - if seen[norm] { - return errx.NewWithIdentifier(errx.BadRequest, "duplicate_column", "column listed twice: "+norm) + known := make(map[string]bool, len(models.ViewBuiltinColumns[view])) + for _, id := range models.ViewBuiltinColumns[view] { + known[id] = true } - seen[norm] = true - prefs.Columns[i] = norm - } - if prefs.Sort != nil { - by := strings.TrimSpace(prefs.Sort.By) - if by == "" { - prefs.Sort = nil - } else { - norm, ok := normalizeColumnID(by) + seen := make(map[string]bool, len(cols)) + for i, id := range cols { + norm, ok := normalizeID(id, known) if !ok { - return errx.NewWithIdentifier(errx.BadRequest, "invalid_sort", "invalid sort: "+by) + return errx.NewWithIdentifier(errx.BadRequest, "invalid_column", "invalid column: "+id) } - prefs.Sort.By = norm + if seen[norm] { + return errx.NewWithIdentifier(errx.BadRequest, "duplicate_column", "column listed twice: "+norm) + } + seen[norm] = true + cols[i] = norm } } + if upd.Sort != nil { + by := strings.TrimSpace(upd.Sort.By) + if by == "" { + // The default sort is stored as no sort at all. + upd.Sort = &models.ViewSort{} + return nil + } + norm, ok := normalizeID(by, models.ContactBuiltinSorts) + if !ok { + return errx.NewWithIdentifier(errx.BadRequest, "invalid_sort", "invalid sort: "+by) + } + upd.Sort.By = norm + } return nil } -func normalizeColumnID(id string) (string, bool) { +// normalizeID accepts a known built-in id as is, or a custom field with a +// valid key, normalized. +func normalizeID(id string, known map[string]bool) (string, bool) { if len(id) > models.ViewColumnIDMaxLength { return "", false } @@ -126,8 +138,5 @@ func normalizeColumnID(id string) (string, bool) { } return models.ContactSortCustomPrefix + key, true } - if !builtinColumnPattern.MatchString(id) { - return "", false - } - return id, true + return id, known[id] } diff --git a/internal/app/viewprefs/service_test.go b/internal/app/viewprefs/service_test.go index 15a3c1c76..9e823d18c 100644 --- a/internal/app/viewprefs/service_test.go +++ b/internal/app/viewprefs/service_test.go @@ -7,46 +7,68 @@ import ( "github.com/warmbly/warmbly/internal/models" ) +func cols(v ...string) *[]string { return &v } + func TestValidateNormalizesAndRejects(t *testing.T) { - ok := &models.ViewPreferences{ - View: models.ViewContacts, - Columns: []string{"company", "custom:Company Mobile", "phone"}, + ok := models.ViewPreferencesUpdate{ + Columns: cols("name", "company", "custom:Company Mobile", "phone"), Sort: &models.ViewSort{By: " custom:Industry ", Reverse: true}, } - if xerr := validate(ok); xerr != nil { + if xerr := validate(models.ViewContacts, &ok); xerr != nil { t.Fatalf("valid layout rejected: %v", xerr) } - if ok.Columns[1] != "custom:Company Mobile" { - t.Fatalf("custom column not normalized: %q", ok.Columns[1]) + if (*ok.Columns)[2] != "custom:Company Mobile" { + t.Fatalf("custom column not normalized: %q", (*ok.Columns)[2]) } if ok.Sort.By != "custom:Industry" { t.Fatalf("sort not normalized: %q", ok.Sort.By) } - blank := &models.ViewPreferences{View: models.ViewContacts, Sort: &models.ViewSort{By: " "}} - if xerr := validate(blank); xerr != nil || blank.Sort != nil { + blank := models.ViewPreferencesUpdate{Sort: &models.ViewSort{By: " ", Reverse: true}} + if xerr := validate(models.ViewContacts, &blank); xerr != nil || blank.Sort == nil || blank.Sort.By != "" || blank.Sort.Reverse { t.Fatalf("a blank sort means the default: %v %+v", xerr, blank.Sort) } - for name, prefs := range map[string]*models.ViewPreferences{ - "duplicate": {Columns: []string{"company", "custom:A", "custom:A"}}, - "bad builtin": {Columns: []string{"Company"}}, - "bad custom key": {Columns: []string{"custom:Revenue ($)"}}, - "too long": {Columns: []string{"custom:" + strings.Repeat("a", 300)}}, - "bad sort": {Sort: &models.ViewSort{By: "drop table"}}, - "too many": {Columns: manyColumns(models.ViewPreferencesMaxColumns + 1)}, + partial := models.ViewPreferencesUpdate{} + if xerr := validate(models.ViewContacts, &partial); xerr != nil { + t.Fatalf("an empty update keeps everything: %v", xerr) + } + + leads := models.ViewPreferencesUpdate{Columns: cols("progress", "opened", "sender")} + if xerr := validate(models.ViewCampaignLeads, &leads); xerr != nil { + t.Fatalf("leads columns rejected: %v", xerr) + } + + for name, tc := range map[string]struct { + view string + upd models.ViewPreferencesUpdate + code string + }{ + "duplicate": {models.ViewContacts, models.ViewPreferencesUpdate{Columns: cols("company", "custom:A", "custom:A")}, "duplicate_column"}, + "unknown builtin": {models.ViewContacts, models.ViewPreferencesUpdate{Columns: cols("nonexistent_col")}, "invalid_column"}, + "other view's column": {models.ViewContacts, models.ViewPreferencesUpdate{Columns: cols("opened")}, "invalid_column"}, + "bad case": {models.ViewContacts, models.ViewPreferencesUpdate{Columns: cols("Company")}, "invalid_column"}, + "bad custom key": {models.ViewContacts, models.ViewPreferencesUpdate{Columns: cols("custom:Revenue ($)")}, "invalid_column"}, + "too long": {models.ViewContacts, models.ViewPreferencesUpdate{Columns: cols("custom:" + strings.Repeat("a", 300))}, "invalid_column"}, + "bad sort": {models.ViewContacts, models.ViewPreferencesUpdate{Sort: &models.ViewSort{By: "drop table"}}, "invalid_sort"}, + "column as sort": {models.ViewContacts, models.ViewPreferencesUpdate{Sort: &models.ViewSort{By: "status"}}, "invalid_sort"}, + "too many": {models.ViewContacts, models.ViewPreferencesUpdate{Columns: manyColumns(models.ViewPreferencesMaxColumns + 1)}, "too_many_columns"}, } { - prefs.View = models.ViewContacts - if xerr := validate(prefs); xerr == nil { + xerr := validate(tc.view, &tc.upd) + if xerr == nil { t.Errorf("%s: accepted", name) + continue + } + if xerr.Identifier != tc.code { + t.Errorf("%s: code %q, want %q", name, xerr.Identifier, tc.code) } } } -func manyColumns(n int) []string { +func manyColumns(n int) *[]string { out := make([]string, n) for i := range out { out[i] = "custom:f" + strings.Repeat("x", i%5) + string(rune('a'+i%26)) + strings.Repeat("y", i/26) } - return out + return &out } diff --git a/internal/models/view_preferences.go b/internal/models/view_preferences.go index d9e9f0f2e..f4beb4751 100644 --- a/internal/models/view_preferences.go +++ b/internal/models/view_preferences.go @@ -18,6 +18,21 @@ var KnownViews = map[string]bool{ ViewCampaignLeads: true, } +// ViewBuiltinColumns lists the built-in column ids each view can render, in +// step with the dashboard's column registry (web/src/components/app/contacts/ +// columns.tsx). A saved layout may name only these and custom fields. +var ViewBuiltinColumns = map[string][]string{ + ViewContacts: {"name", "company", "phone", "status", "campaigns", "created_at", "updated_at"}, + ViewCampaignLeads: {"name", "company", "phone", "progress", "opened", "clicked", "replied", "current_step", "sender", "last_activity", "created_at", "updated_at"}, +} + +// ContactBuiltinSorts are the sort_by values the contacts search knows besides +// "custom:", the same set contactSorts holds in the repository. +var ContactBuiltinSorts = map[string]bool{ + "created_at": true, "updated_at": true, "first_name": true, "last_name": true, + "email": true, "company": true, "phone": true, "campaign_count": true, +} + // ViewPreferencesMaxColumns bounds one layout; no list here has anywhere near // this many columns to show. const ViewPreferencesMaxColumns = 64 @@ -45,6 +60,13 @@ type ViewPreferences struct { UpdatedAt *time.Time `json:"updated_at,omitempty"` } +// ViewPreferencesUpdate is a partial write: a nil field keeps what is saved, +// so a sort click made before the layout has loaded cannot erase the columns. +type ViewPreferencesUpdate struct { + Columns *[]string + Sort *ViewSort +} + // ContactSortCustomPrefix is the sort_by form that orders the contacts list on // a custom field: "custom:". The key is normalized the way custom-field // names are on write, so "custom:Company Mobile" and "custom:Company Mobile" diff --git a/internal/repository/pg_view_preferences.go b/internal/repository/pg_view_preferences.go index 433272f51..fd773ad0f 100644 --- a/internal/repository/pg_view_preferences.go +++ b/internal/repository/pg_view_preferences.go @@ -18,7 +18,9 @@ import ( type ViewPreferencesRepository interface { // Get returns nil, nil when the member has never saved this view. Get(ctx context.Context, userID, orgID uuid.UUID, view string) (*models.ViewPreferences, error) - Upsert(ctx context.Context, userID, orgID uuid.UUID, prefs *models.ViewPreferences) error + // Upsert writes the fields the update carries, keeps the rest, and returns + // the row as saved. + Upsert(ctx context.Context, userID, orgID uuid.UUID, view string, upd models.ViewPreferencesUpdate) (*models.ViewPreferences, error) Delete(ctx context.Context, userID, orgID uuid.UUID, view string) error } @@ -30,22 +32,15 @@ func NewViewPreferencesRepository(db *pgxpool.Pool) ViewPreferencesRepository { return &viewPreferencesRepository{db: db} } -func (r *viewPreferencesRepository) Get(ctx context.Context, userID, orgID uuid.UUID, view string) (*models.ViewPreferences, error) { +// scanPrefs reads one row's columns, sort and updated_at. +func scanPrefs(view string, row pgx.Row) (*models.ViewPreferences, error) { var ( raw []byte sortBy string reverse bool updatedAt time.Time ) - err := r.db.QueryRow(ctx, ` - SELECT columns, sort_by, sort_reverse, updated_at - FROM user_view_preferences - WHERE user_id = $1 AND organization_id = $2 AND view = $3`, - userID, orgID, view).Scan(&raw, &sortBy, &reverse, &updatedAt) - if err != nil { - if errors.Is(err, pgx.ErrNoRows) { - return nil, nil - } + if err := row.Scan(&raw, &sortBy, &reverse, &updatedAt); err != nil { return nil, err } prefs := &models.ViewPreferences{View: view, Columns: []string{}, UpdatedAt: &updatedAt} @@ -60,29 +55,48 @@ func (r *viewPreferencesRepository) Get(ctx context.Context, userID, orgID uuid. return prefs, nil } -func (r *viewPreferencesRepository) Upsert(ctx context.Context, userID, orgID uuid.UUID, prefs *models.ViewPreferences) error { - cols := prefs.Columns - if cols == nil { - cols = []string{} +func (r *viewPreferencesRepository) Get(ctx context.Context, userID, orgID uuid.UUID, view string) (*models.ViewPreferences, error) { + prefs, err := scanPrefs(view, r.db.QueryRow(ctx, ` + SELECT columns, sort_by, sort_reverse, updated_at + FROM user_view_preferences + WHERE user_id = $1 AND organization_id = $2 AND view = $3`, + userID, orgID, view)) + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil } - raw, err := json.Marshal(cols) - if err != nil { - return err + return prefs, err +} + +func (r *viewPreferencesRepository) Upsert(ctx context.Context, userID, orgID uuid.UUID, view string, upd models.ViewPreferencesUpdate) (*models.ViewPreferences, error) { + // A nil field binds NULL and COALESCE keeps the saved value, reading the + // bound parameter rather than EXCLUDED: the VALUES row has already turned + // that NULL into the default, so EXCLUDED would never be NULL. + var raw []byte + if upd.Columns != nil { + cols := *upd.Columns + if cols == nil { + cols = []string{} + } + var err error + if raw, err = json.Marshal(cols); err != nil { + return nil, err + } } - sortBy, reverse := "", false - if prefs.Sort != nil { - sortBy, reverse = prefs.Sort.By, prefs.Sort.Reverse + var sortBy *string + var reverse *bool + if upd.Sort != nil { + sortBy, reverse = &upd.Sort.By, &upd.Sort.Reverse } - _, err = r.db.Exec(ctx, ` + return scanPrefs(view, r.db.QueryRow(ctx, ` INSERT INTO user_view_preferences (user_id, organization_id, view, columns, sort_by, sort_reverse, updated_at) - VALUES ($1, $2, $3, $4, $5, $6, now()) + VALUES ($1, $2, $3, COALESCE($4::jsonb, '[]'::jsonb), COALESCE($5::text, ''), COALESCE($6::boolean, false), now()) ON CONFLICT (user_id, organization_id, view) DO UPDATE - SET columns = EXCLUDED.columns, - sort_by = EXCLUDED.sort_by, - sort_reverse = EXCLUDED.sort_reverse, - updated_at = now()`, - userID, orgID, prefs.View, raw, sortBy, reverse) - return err + SET columns = COALESCE($4::jsonb, user_view_preferences.columns), + sort_by = COALESCE($5::text, user_view_preferences.sort_by), + sort_reverse = COALESCE($6::boolean, user_view_preferences.sort_reverse), + updated_at = now() + RETURNING columns, sort_by, sort_reverse, updated_at`, + userID, orgID, view, raw, sortBy, reverse)) } func (r *viewPreferencesRepository) Delete(ctx context.Context, userID, orgID uuid.UUID, view string) error { diff --git a/internal/repository/view_preferences_live_test.go b/internal/repository/view_preferences_live_test.go new file mode 100644 index 000000000..92e1d885c --- /dev/null +++ b/internal/repository/view_preferences_live_test.go @@ -0,0 +1,102 @@ +package repository + +import ( + "context" + "testing" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/models" +) + +// A saved layout is written in parts: the chooser sends columns, a header +// click sends the sort, and neither may erase the other. The COALESCE in the +// upsert is what keeps them apart, and only a database can check it. +// +// Run against the dev stack: +// +// WARMBLY_TEST_DB=postgres://warmbly:warmbly@localhost:15432/warmbly_dev?sslmode=disable \ +// go test ./internal/repository/ -run LiveViewPreferences -v +func TestLiveViewPreferencesPartialWrites(t *testing.T) { + handle, pool := liveContactDB(t) + ctx := context.Background() + user, org := uuid.New(), uuid.New() + tag := org.String()[:8] + exec := func(sql string, args ...any) { + t.Helper() + if _, err := pool.Exec(ctx, sql, args...); err != nil { + t.Fatalf("fixture %q: %v", sql[:min(60, len(sql))], err) + } + } + exec(`INSERT INTO users (id, first_name, last_name, email, password_hash) VALUES ($1, 'View', 'Live', $2, 'x')`, user, "i605v-"+tag+"@test.local") + exec(`INSERT INTO organizations (id, name, slug, owner_user_id) VALUES ($1, 'Issue 605 views', $2, $3)`, org, "i605v-"+tag, user) + t.Cleanup(func() { + c := context.Background() + _, _ = pool.Exec(c, `DELETE FROM organizations WHERE id = $1`, org) + _, _ = pool.Exec(c, `DELETE FROM users WHERE id = $1`, user) + }) + repo := NewViewPreferencesRepository(handle.Pool) + + none, err := repo.Get(ctx, user, org, models.ViewContacts) + if err != nil || none != nil { + t.Fatalf("nothing saved yet: %v %+v", err, none) + } + + // A sort click before any layout exists creates the row with the default + // columns, not with nothing. + got, err := repo.Upsert(ctx, user, org, models.ViewContacts, models.ViewPreferencesUpdate{Sort: &models.ViewSort{By: "company", Reverse: true}}) + if err != nil { + t.Fatalf("sort-only insert: %v", err) + } + if len(got.Columns) != 0 || got.Sort == nil || got.Sort.By != "company" || !got.Sort.Reverse { + t.Fatalf("sort-only insert saved %+v", got) + } + + cols := []string{"name", "custom:Industry", "company"} + got, err = repo.Upsert(ctx, user, org, models.ViewContacts, models.ViewPreferencesUpdate{Columns: &cols}) + if err != nil { + t.Fatalf("columns-only update: %v", err) + } + if got.Sort == nil || got.Sort.By != "company" { + t.Fatalf("a columns-only write erased the sort: %+v", got) + } + if len(got.Columns) != 3 || got.Columns[1] != "custom:Industry" { + t.Fatalf("columns not saved: %+v", got.Columns) + } + + got, err = repo.Upsert(ctx, user, org, models.ViewContacts, models.ViewPreferencesUpdate{Sort: &models.ViewSort{By: "custom:Industry"}}) + if err != nil { + t.Fatalf("sort-only update: %v", err) + } + if len(got.Columns) != 3 { + t.Fatalf("a sort-only write erased the columns: %+v", got) + } + if got.Sort == nil || got.Sort.By != "custom:Industry" || got.Sort.Reverse { + t.Fatalf("sort not updated: %+v", got.Sort) + } + + // The blank sort is the default sort, read back as none. + got, err = repo.Upsert(ctx, user, org, models.ViewContacts, models.ViewPreferencesUpdate{Sort: &models.ViewSort{}}) + if err != nil { + t.Fatalf("sort reset: %v", err) + } + if got.Sort != nil || len(got.Columns) != 3 { + t.Fatalf("sort reset saved %+v", got) + } + + // Each view is its own row, and Get sees what Upsert returned. + if other, err := repo.Get(ctx, user, org, models.ViewCampaignLeads); err != nil || other != nil { + t.Fatalf("leads view leaked: %v %+v", err, other) + } + again, err := repo.Get(ctx, user, org, models.ViewContacts) + if err != nil || again == nil || len(again.Columns) != 3 || again.Sort != nil { + t.Fatalf("Get after writes: %v %+v", err, again) + } + + if err := repo.Delete(ctx, user, org, models.ViewContacts); err != nil { + t.Fatalf("delete: %v", err) + } + if gone, err := repo.Get(ctx, user, org, models.ViewContacts); err != nil || gone != nil { + t.Fatalf("delete left a row: %v %+v", err, gone) + } +} diff --git a/web/src/components/app/contacts/ContactsTable.tsx b/web/src/components/app/contacts/ContactsTable.tsx index fdb567faf..9cf9a8f31 100644 --- a/web/src/components/app/contacts/ContactsTable.tsx +++ b/web/src/components/app/contacts/ContactsTable.tsx @@ -168,7 +168,7 @@ export default function ContactsTable({ const category = params.get("category"); // The browser's copy of the saved sort seeds the first request, so the // list does not load in one order and then reload in another. - const cached = readCachedView(view.orgId, viewName)?.sort; + const cached = readCachedView(view.scope, viewName)?.sort; return { ...scopeSearch({ campaignId: current_campaign?.id, segmentId: segment?.id }), category_ids: category && !segment && !current_campaign ? [category] : undefined, diff --git a/web/src/components/app/contacts/ViewControls.tsx b/web/src/components/app/contacts/ViewControls.tsx index 41ea0666b..fc8aa9c91 100644 --- a/web/src/components/app/contacts/ViewControls.tsx +++ b/web/src/components/app/contacts/ViewControls.tsx @@ -5,7 +5,8 @@ import React from "react"; import { Reorder, useDragControls } from "framer-motion"; -import { ArrowDownIcon, ArrowUpIcon, CheckIcon, Columns3Icon, GripVerticalIcon, LockIcon, RotateCcwIcon } from "lucide-react"; +import { ArrowDownIcon, ArrowUpIcon, Columns3Icon, GripVerticalIcon, LockIcon, RotateCcwIcon } from "lucide-react"; +import { CheckSquare } from "@/components/ui/check-square"; import type { SearchContactsSortBy } from "@/lib/api/models/app/contacts/search-contacts.types"; import { PopoverMenu, @@ -16,25 +17,13 @@ import { PopoverMenuTrigger, SelectButton, } from "@/components/ui/popover-menu"; -import { customColumnId, type ContactColumn } from "./columns"; +import { customColumnId, type ContactColumn, type SortOption } from "./columns"; export interface ViewSortState { by: SearchContactsSortBy; reverse: boolean; } -function CheckSquare({ checked }: { checked: boolean }) { - return ( - - {checked && } - - ); -} - function ColumnLabel({ col }: { col: ContactColumn }) { return ( <> @@ -46,8 +35,9 @@ function ColumnLabel({ col }: { col: ContactColumn }) { ); } -// A shown column: drag by the grip, click the rest of the row to hide it. -function ShownRow({ col, onHide }: { col: ContactColumn; onHide: () => void }) { +// A shown column: drag by the grip, click the rest of the row to hide it. The +// new order is committed when the drag ends, not on every position crossed. +function ShownRow({ col, onHide, onDragEnd }: { col: ContactColumn; onHide: () => void; onDragEnd: () => void }) { const controls = useDragControls(); return ( void }) { value={col} dragListener={false} dragControls={controls} + onDragEnd={onDragEnd} className="relative bg-white" >
@@ -107,7 +98,7 @@ export function ColumnChooser({ // Built-in columns not shown, then custom fields not shown. available: ContactColumn[]; customized: boolean; - // The ids of the shown columns after Name, in order. + // The ids of every shown column in order, Name first. onChange: (ids: string[]) => void; onReset: () => void; }) { @@ -118,9 +109,27 @@ export function ColumnChooser({ const locked = visible.filter((c) => c.locked); const shown = visible.filter((c) => !c.locked); - const ids = () => shown.map((c) => c.id); - const hide = (id: string) => onChange(ids().filter((x) => x !== id)); - const show = (id: string) => onChange([...ids(), id]); + // A saved layout names every shown column including Name, so hiding the + // last optional one saves ["name"] rather than [], which would mean the + // default layout and bring every column back. + const layout = (cols: ContactColumn[]) => [...locked.map((c) => c.id), ...cols.map((c) => c.id)]; + const hide = (id: string) => onChange(layout(shown.filter((x) => x.id !== id))); + const show = (id: string) => onChange(layout([...shown, ...available.filter((c) => c.id === id)])); + + // The order being dragged lives here until the drop, so one drag is one + // write. It follows the saved order whenever that changes from outside. + const [order, setOrder] = React.useState(shown); + const shownKey = shown.map((c) => c.id).join("|"); + React.useEffect(() => { + setOrder(shown); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [shownKey]); + const orderRef = React.useRef(order); + orderRef.current = order; + const commitOrder = () => { + const next = layout(orderRef.current); + if (next.join("|") !== layout(shown).join("|")) onChange(next); + }; const builtinAvail = available.filter((c) => !c.custom && matches(c)); const customAvail = available.filter((c) => !!c.custom && matches(c)); @@ -172,14 +181,9 @@ export function ColumnChooser({ hide(col.id)} /> )) ) : ( - onChange(next.map((c) => c.id))} - > - {shown.map((col) => ( - hide(col.id)} /> + + {order.map((col) => ( + hide(col.id)} onDragEnd={commitOrder} /> ))} )} @@ -229,7 +233,7 @@ export function SortMenu({ onChange, }: { sort: ViewSortState; - options: { key: SearchContactsSortBy; label: string }[]; + options: SortOption[]; customKeys: string[]; onChange: (next: ViewSortState) => void; }) { @@ -251,7 +255,7 @@ export function SortMenu({ onChange({ by: o.key, reverse: sort.by === o.key ? sort.reverse : false })} + onSelect={() => onChange({ by: o.key, reverse: sort.by === o.key ? sort.reverse : o.asc })} > {o.label} diff --git a/web/src/components/app/contacts/columns.test.ts b/web/src/components/app/contacts/columns.test.ts index 9b568fcfc..f242ace06 100644 --- a/web/src/components/app/contacts/columns.test.ts +++ b/web/src/components/app/contacts/columns.test.ts @@ -4,7 +4,7 @@ import { DEFAULT_COLUMNS, builtinColumns, customColumnId, resolveColumns } from describe("resolveColumns", () => { it("shows the default layout with Name first when nothing is saved", () => { const { visible, available } = resolveColumns("contacts", undefined, ["Industry"]); - expect(visible.map((c) => c.id)).toEqual(["name", ...DEFAULT_COLUMNS.contacts]); + expect(visible.map((c) => c.id)).toEqual(DEFAULT_COLUMNS.contacts); // Everything the view knows and is not shown is offered, custom fields last. expect(available.map((c) => c.id)).toEqual(["updated_at", customColumnId("Industry")]); }); @@ -14,6 +14,12 @@ describe("resolveColumns", () => { expect(visible.map((c) => c.id)).toEqual(["name", "phone", "company"]); }); + it("shows Name alone for a layout that names only Name", () => { + const { visible, available } = resolveColumns("contacts", ["name"], []); + expect(visible.map((c) => c.id)).toEqual(["name"]); + expect(available.map((c) => c.id)).toContain("company"); + }); + it("renders a saved custom field even when no contact carries it any more", () => { const { visible, available } = resolveColumns("contacts", ["custom:Old Field"], ["Industry"]); expect(visible.map((c) => c.id)).toEqual(["name", "custom:Old Field"]); diff --git a/web/src/components/app/contacts/columns.tsx b/web/src/components/app/contacts/columns.tsx index 5be179ab0..f03296218 100644 --- a/web/src/components/app/contacts/columns.tsx +++ b/web/src/components/app/contacts/columns.tsx @@ -392,17 +392,18 @@ export function builtinColumns(view: ViewName): ContactColumn[] { return [nameColumn, companyColumn(view), phoneColumn, statusColumn, campaignsColumn, addedColumn(view), updatedColumn]; } -// The layout a member sees before choosing anything, Name implied first. +// The layout a member sees before choosing anything. export const DEFAULT_COLUMNS: Record = { - contacts: ["company", "phone", "status", "campaigns", "created_at"], - campaign_leads: ["company", "progress", "opened", "clicked", "replied", "current_step", "sender", "last_activity"], + contacts: ["name", "company", "phone", "status", "campaigns", "created_at"], + campaign_leads: ["name", "company", "progress", "opened", "clicked", "replied", "current_step", "sender", "last_activity"], }; // The columns to render for a saved layout, and the ones the chooser can still -// add. Unknown built-in ids (a column an older build offered) are dropped; a -// custom field is kept even when no contact currently carries it, so the -// column the member picked does not vanish because an import replaced the -// field's name. +// add. A saved layout always names "name", so a layout of Name alone is +// `["name"]` and never the empty list, which means "the default". Unknown +// built-in ids (a column an older build offered) are dropped; a custom field +// is kept even when no contact currently carries it, so the column the member +// picked does not vanish because an import replaced the field's name. export function resolveColumns( view: ViewName, saved: string[] | undefined, @@ -428,17 +429,25 @@ export function resolveColumns( return { visible, available }; } +export interface SortOption { + key: SearchContactsSortBy; + label: string; + // Whether picking it starts ascending, as a header click on the same + // column would (text does, dates and counts do not). + asc: boolean; +} + // The sort choices the toolbar menu offers, beyond what a header click reaches. -export function sortOptions(view: ViewName): { key: SearchContactsSortBy; label: string }[] { - const base: { key: SearchContactsSortBy; label: string }[] = [ - { key: "created_at", label: "Date added" }, - { key: "updated_at", label: "Last updated" }, - { key: "first_name", label: "First name" }, - { key: "last_name", label: "Last name" }, - { key: "email", label: "Email" }, - { key: "company", label: "Company" }, - { key: "phone", label: "Phone" }, +export function sortOptions(view: ViewName): SortOption[] { + const base: SortOption[] = [ + { key: "created_at", label: "Date added", asc: false }, + { key: "updated_at", label: "Last updated", asc: false }, + { key: "first_name", label: "First name", asc: true }, + { key: "last_name", label: "Last name", asc: true }, + { key: "email", label: "Email", asc: true }, + { key: "company", label: "Company", asc: true }, + { key: "phone", label: "Phone", asc: true }, ]; - if (view === "contacts") base.push({ key: "campaign_count", label: "Campaigns" }); + if (view === "contacts") base.push({ key: "campaign_count", label: "Campaigns", asc: false }); return base; } diff --git a/web/src/components/app/contacts/useContactView.ts b/web/src/components/app/contacts/useContactView.ts index 49ac43c61..d00ae4b71 100644 --- a/web/src/components/app/contacts/useContactView.ts +++ b/web/src/components/app/contacts/useContactView.ts @@ -3,22 +3,27 @@ // chooser and the sort menu read the same view. import React from "react"; -import { useCurrentOrg } from "@/stores/useAppStore"; +import { useCurrentOrg, useUser } from "@/stores/useAppStore"; import useCustomFieldKeys from "@/lib/api/hooks/app/contacts/useCustomFieldKeys"; import { useResetViewPreferences, useUpdateViewPreferences, useViewPreferences, + type ViewScope, } from "@/lib/api/hooks/app/views/useViewPreferences"; import type { ViewName, ViewSort } from "@/lib/api/models/app/views/ViewPreferences"; import { resolveColumns } from "./columns"; export function useContactView(view: ViewName) { const org = useCurrentOrg(); - const orgId = org?.id ?? ""; - const prefs = useViewPreferences(view, orgId); - const update = useUpdateViewPreferences(view, orgId); - const reset = useResetViewPreferences(view, orgId); + const user = useUser(); + const scope = React.useMemo( + () => ({ userId: user?.id ?? "", orgId: org?.id ?? "" }), + [user?.id, org?.id], + ); + const prefs = useViewPreferences(view, scope); + const update = useUpdateViewPreferences(view, scope); + const reset = useResetViewPreferences(view, scope); const keys = useCustomFieldKeys(); const saved = prefs.data; @@ -29,17 +34,16 @@ export function useContactView(view: ViewName) { [view, savedColumns, customKeys], ); - const setColumns = React.useCallback( - (ids: string[]) => update.mutate({ columns: ids, sort: saved?.sort ?? null }), - [update, saved?.sort], - ); - const setSort = React.useCallback( - (sort: ViewSort) => update.mutate({ columns: saved?.columns ?? [], sort }), - [update, saved?.columns], - ); + // Each write names only what changed, so the columns and the sort never + // overwrite each other, whatever has or has not loaded yet. + const { mutate } = update; + const setColumns = React.useCallback((ids: string[]) => mutate({ columns: ids }), [mutate]); + const setSort = React.useCallback((sort: ViewSort) => mutate({ sort }), [mutate]); + const { mutate: resetMutate } = reset; + const resetView = React.useCallback(() => resetMutate(), [resetMutate]); return { - orgId, + scope, columns: visible, available, customKeys, @@ -49,6 +53,6 @@ export function useContactView(view: ViewName) { customized: (savedColumns?.length ?? 0) > 0, setColumns, setSort, - reset: () => reset.mutate(), + reset: resetView, }; } diff --git a/web/src/components/ui/check-square.tsx b/web/src/components/ui/check-square.tsx new file mode 100644 index 000000000..c8d561662 --- /dev/null +++ b/web/src/components/ui/check-square.tsx @@ -0,0 +1,17 @@ +// The checkbox square of the app's pickers (category, tag and column +// choosers): a filled slate square with a white check when on, a bordered +// white square when off. Purely visual; the row it sits in is the control. + +import { CheckIcon } from "lucide-react"; + +export function CheckSquare({ checked }: { checked: boolean }) { + return ( + + {checked && } + + ); +} diff --git a/web/src/lib/api/hooks/app/views/useViewPreferences.ts b/web/src/lib/api/hooks/app/views/useViewPreferences.ts index 61456ab15..0d74d6029 100644 --- a/web/src/lib/api/hooks/app/views/useViewPreferences.ts +++ b/web/src/lib/api/hooks/app/views/useViewPreferences.ts @@ -12,16 +12,24 @@ import type { ViewPreferences, } from "@/lib/api/models/app/views/ViewPreferences"; -const queryKey = (orgId: string, view: ViewName) => ["views", orgId, view]; -const cacheKey = (orgId: string, view: ViewName) => `warmbly:view:${orgId}:${view}`; +// A layout belongs to one member in one workspace, so the cache is keyed by +// both: two accounts sharing a browser never see each other's columns. +export interface ViewScope { + userId: string; + orgId: string; +} + +const queryKey = (scope: ViewScope, view: ViewName) => ["views", scope.userId, scope.orgId, view]; +const cacheKey = (scope: ViewScope, view: ViewName) => `warmbly:view:${scope.userId}:${scope.orgId}:${view}`; +const scoped = (scope: ViewScope) => !!scope.userId && !!scope.orgId; // The server is the source of truth; the browser keeps a copy so the list // paints with the member's columns on the first frame instead of flashing the // defaults while the request is in flight. Anything malformed is ignored. -export function readCachedView(orgId: string, view: ViewName): ViewPreferences | undefined { - if (!orgId) return undefined; +export function readCachedView(scope: ViewScope, view: ViewName): ViewPreferences | undefined { + if (!scoped(scope)) return undefined; try { - const raw = localStorage.getItem(cacheKey(orgId, view)); + const raw = localStorage.getItem(cacheKey(scope, view)); if (!raw) return undefined; const p = JSON.parse(raw) as Partial | null; if (!p || !Array.isArray(p.columns)) return undefined; @@ -35,72 +43,79 @@ export function readCachedView(orgId: string, view: ViewName): ViewPreferences | } } -function writeCachedView(orgId: string, view: ViewName, prefs: ViewPreferences | null) { - if (!orgId) return; +function writeCachedView(scope: ViewScope, view: ViewName, prefs: ViewPreferences | null) { + if (!scoped(scope)) return; try { - if (!prefs) localStorage.removeItem(cacheKey(orgId, view)); - else localStorage.setItem(cacheKey(orgId, view), JSON.stringify({ columns: prefs.columns, sort: prefs.sort ?? null })); + if (!prefs) localStorage.removeItem(cacheKey(scope, view)); + else localStorage.setItem(cacheKey(scope, view), JSON.stringify({ columns: prefs.columns, sort: prefs.sort ?? null })); } catch { /* storage full or blocked: the server copy still applies */ } } -export function useViewPreferences(view: ViewName, orgId: string) { +export function useViewPreferences(view: ViewName, scope: ViewScope) { const q = useQuery({ - queryKey: queryKey(orgId, view), + queryKey: queryKey(scope, view), queryFn: async () => (await getViewPreferences(view)).preferences, - enabled: !!orgId, + enabled: scoped(scope), staleTime: 5 * 60 * 1000, - placeholderData: () => readCachedView(orgId, view), + placeholderData: () => readCachedView(scope, view), }); React.useEffect(() => { - if (q.data && !q.isPlaceholderData) writeCachedView(orgId, view, q.data); - }, [q.data, q.isPlaceholderData, orgId, view]); + if (q.data && !q.isPlaceholderData) writeCachedView(scope, view, q.data); + }, [q.data, q.isPlaceholderData, scope, view]); return q; } // Optimistic: the table re-lays out on the click, and the row is written -// behind it. A failure puts the previous layout back and says so. -export function useUpdateViewPreferences(view: ViewName, orgId: string) { +// behind it. The body is partial (columns, sort, or both) and the server keeps +// whatever it does not name, so a click made before the saved layout has +// loaded cannot erase the rest of it. A failure puts the previous layout back +// and says so; the server's reply is what stays in the cache. +export function useUpdateViewPreferences(view: ViewName, scope: ViewScope) { const qc = useQueryClient(); - const key = queryKey(orgId, view); + const key = queryKey(scope, view); return useMutation({ mutationFn: (body: UpdateViewPreferences) => updateViewPreferences(view, body), onMutate: async (body) => { await qc.cancelQueries({ queryKey: key }); const previous = qc.getQueryData(key); - const next: ViewPreferences = { view, columns: body.columns, sort: body.sort }; + const next: ViewPreferences = { + view, + columns: body.columns ?? previous?.columns ?? [], + sort: body.sort !== undefined ? (body.sort.by ? body.sort : null) : (previous?.sort ?? null), + }; qc.setQueryData(key, next); - writeCachedView(orgId, view, next); + writeCachedView(scope, view, next); return { previous }; }, onError: (_err, _body, ctx) => { qc.setQueryData(key, ctx?.previous); - writeCachedView(orgId, view, ctx?.previous ?? null); + writeCachedView(scope, view, ctx?.previous ?? null); toast.error("Couldn't save your view. It will reset when you reload."); }, onSuccess: (envelope) => { qc.setQueryData(key, envelope.preferences); - writeCachedView(orgId, view, envelope.preferences); + writeCachedView(scope, view, envelope.preferences); }, }); } -export function useResetViewPreferences(view: ViewName, orgId: string) { +export function useResetViewPreferences(view: ViewName, scope: ViewScope) { const qc = useQueryClient(); - const key = queryKey(orgId, view); + const key = queryKey(scope, view); return useMutation({ mutationFn: () => resetViewPreferences(view), onMutate: async () => { await qc.cancelQueries({ queryKey: key }); const previous = qc.getQueryData(key); qc.setQueryData(key, { view, columns: [], sort: null }); - writeCachedView(orgId, view, null); + writeCachedView(scope, view, null); return { previous }; }, onError: (_err, _v, ctx) => { qc.setQueryData(key, ctx?.previous); - writeCachedView(orgId, view, ctx?.previous ?? null); + writeCachedView(scope, view, ctx?.previous ?? null); toast.error("Couldn't reset the view."); }, }); diff --git a/web/src/lib/api/models/app/views/ViewPreferences.ts b/web/src/lib/api/models/app/views/ViewPreferences.ts index d05894cc4..ae3e48527 100644 --- a/web/src/lib/api/models/app/views/ViewPreferences.ts +++ b/web/src/lib/api/models/app/views/ViewPreferences.ts @@ -22,7 +22,9 @@ export interface ViewPreferencesEnvelope { preferences: ViewPreferences; } +// A partial write: a field left out keeps its saved value. `columns: []` is +// the default layout; `sort: { by: "" }` the default sort. export interface UpdateViewPreferences { - columns: string[]; - sort: ViewSort | null; + columns?: string[]; + sort?: ViewSort; } From c73b30c112d7cb6b18ad3dd61902654c11b20af5 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 19 Sep 2026 09:46:08 -0700 Subject: [PATCH 3/3] feat: make the column chooser's reorder grip a focusable button that moves a column with the arrow keys, count a saved sort alone as a customised view so Reset to default stays available, and list unknown_view under the 404 codes rather than the 400 table --- docs/content/docs/api/error-codes.mdx | 7 ++- .../components/app/contacts/ViewControls.tsx | 51 +++++++++++++++---- .../components/app/contacts/useContactView.ts | 3 +- 3 files changed, 50 insertions(+), 11 deletions(-) diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index 3082cf77a..1272c0233 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -77,7 +77,6 @@ Returned when the request cannot be processed due to invalid syntax. |--------|---------| | `invalid_lead_status` | `POST /contacts/search` or `POST /contacts/export` was given a `lead_status` that is not one of the documented values | | `invalid_sort_by` | `POST /contacts/search`, `POST /contacts/export` or a bulk action's `all` selection was given a `sort_by` of the form `custom:` whose key could never be a custom-field name (letters, numbers, underscores, spaces or dashes) | -| `unknown_view` | `/me/views/:view` was given a view name other than `contacts` or `campaign_leads` (answered `404`) | | `invalid_column`, `duplicate_column`, `too_many_columns`, `invalid_sort` | `PUT /me/views/:view` was given a column id that view cannot render, the same column twice, more than 64 columns, or a sort that names neither a sortable contact column nor a well-formed `custom:` | | `invalid_engagement` | `POST /contacts/search` or `POST /contacts/export` was given an `engagement` that is not one of the documented values | | `lead_filter_requires_campaign` | `lead_status` or `engagement` was set without exactly one `campaign_ids` entry; both filters describe a contact inside one campaign | @@ -285,6 +284,12 @@ Returned when the requested resource doesn't exist. - Check that the resource hasn't been deleted - Ensure you're using the correct endpoint +**Specific 404 codes:** + +| `code` | Meaning | +|--------|---------| +| `unknown_view` | `/me/views/:view` was given a view name other than `contacts` or `campaign_leads` | + ### 409 Conflict Returned when the request conflicts with existing data. diff --git a/web/src/components/app/contacts/ViewControls.tsx b/web/src/components/app/contacts/ViewControls.tsx index fc8aa9c91..742d9a65b 100644 --- a/web/src/components/app/contacts/ViewControls.tsx +++ b/web/src/components/app/contacts/ViewControls.tsx @@ -35,9 +35,20 @@ function ColumnLabel({ col }: { col: ContactColumn }) { ); } -// A shown column: drag by the grip, click the rest of the row to hide it. The -// new order is committed when the drag ends, not on every position crossed. -function ShownRow({ col, onHide, onDragEnd }: { col: ContactColumn; onHide: () => void; onDragEnd: () => void }) { +// A shown column: drag by the grip (or focus it and press the arrow keys), +// click the rest of the row to hide it. A drag commits its order once, on the +// drop, not on every position crossed; a key press commits at once. +function ShownRow({ + col, + onHide, + onDragEnd, + onMove, +}: { + col: ContactColumn; + onHide: () => void; + onDragEnd: () => void; + onMove: (delta: -1 | 1) => void; +}) { const controls = useDragControls(); return (
- controls.start(e)} - className="size-5 flex items-center justify-center cursor-grab active:cursor-grabbing text-slate-300 hover:text-slate-500 touch-none" - aria-label={`Drag to move ${col.label}`} - role="button" + onKeyDown={(e) => { + if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return; + e.preventDefault(); + onMove(e.key === "ArrowUp" ? -1 : 1); + }} + className="size-5 flex items-center justify-center rounded cursor-grab active:cursor-grabbing text-slate-300 hover:text-slate-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-200 focus-visible:text-slate-600 touch-none" + aria-label={`Move ${col.label}: drag, or press the up and down arrow keys`} > - +