Merge pull request #611 from warmbly/feature/contact-list-column-chooser

feat: choose, reorder and persist contact list columns (custom fields included) and sort on any column
This commit is contained in:
Matthew Meszaros
2026-09-19 16:51:28 +00:00
committed by GitHub
36 changed files with 2358 additions and 436 deletions
+10 -5
View File
@@ -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,
+1
View File
@@ -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)
+8
View File
@@ -76,6 +76,8 @@ 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`, `POST /contacts/export` or a bulk action's `all` selection was given a `sort_by` of the form `custom:<key>` whose key could never be a custom-field name (letters, numbers, underscores, spaces or dashes) |
| `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:<key>` |
| `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 |
@@ -282,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.
+1 -1
View File
@@ -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:<key>` 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
+13 -1
View File
@@ -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.
@@ -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.
+1 -1
View File
@@ -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:<key> 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",
+3
View File
@@ -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
+86
View File
@@ -0,0 +1,86 @@
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})
}
// 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"`
Sort *models.ViewSort `json:"sort"`
}
// 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)
if !ok {
return
}
var req updateViewPreferencesRequest
if err := c.ShouldBindJSON(&req); err != nil {
errx.Handle(c, errx.ErrInvalid)
return
}
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
}
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)
}
+7
View File
@@ -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)
+3
View File
@@ -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
}
+18
View File
@@ -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.
+5
View File
@@ -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 {
+1
View File
@@ -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.
+142
View File
@@ -0,0 +1,142 @@
// 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"
"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 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
}
type service struct {
repo repository.ViewPreferencesRepository
}
func NewService(repo repository.ViewPreferencesRepository) Service {
return &service{repo: repo}
}
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, unknownView()
}
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, view string, upd models.ViewPreferencesUpdate) (*models.ViewPreferences, *errx.Error) {
if !models.KnownViews[view] {
return nil, unknownView()
}
if xerr := validate(view, &upd); xerr != nil {
return nil, xerr
}
saved, err := s.repo.Upsert(ctx, userID, orgID, view, upd)
if err != nil {
errs.CaptureException(err)
return nil, errx.InternalError()
}
return saved, nil
}
func (s *service) Reset(ctx context.Context, userID, orgID uuid.UUID, view string) *errx.Error {
if !models.KnownViews[view] {
return unknownView()
}
if err := s.repo.Delete(ctx, userID, orgID, view); err != nil {
errs.CaptureException(err)
return errx.InternalError()
}
return nil
}
// 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")
}
known := make(map[string]bool, len(models.ViewBuiltinColumns[view]))
for _, id := range models.ViewBuiltinColumns[view] {
known[id] = true
}
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_column", "invalid column: "+id)
}
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
}
// 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
}
if key, ok := models.ContactSortCustomField(id); ok {
if !utils.IsValidJSONKey(key) {
return "", false
}
return models.ContactSortCustomPrefix + key, true
}
return id, known[id]
}
+74
View File
@@ -0,0 +1,74 @@
package viewprefs
import (
"strings"
"testing"
"github.com/warmbly/warmbly/internal/models"
)
func cols(v ...string) *[]string { return &v }
func TestValidateNormalizesAndRejects(t *testing.T) {
ok := models.ViewPreferencesUpdate{
Columns: cols("name", "company", "custom:Company Mobile", "phone"),
Sort: &models.ViewSort{By: " custom:Industry ", Reverse: true},
}
if xerr := validate(models.ViewContacts, &ok); xerr != nil {
t.Fatalf("valid layout rejected: %v", xerr)
}
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.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)
}
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"},
} {
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 {
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
}
@@ -0,0 +1 @@
DROP TABLE IF EXISTS public.user_view_preferences;
@@ -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.';
+2 -2
View File
@@ -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:<key>" for a custom field
Reverse bool `json:"reverse"` // Ascending when true; the default is descending
}
type BulkEditContactsFieldType string
+85
View File
@@ -0,0 +1,85 @@
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,
}
// 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:<key>", 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
// 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"`
}
// 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:<key>". 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
}
@@ -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:<key>". 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)
}
+52
View File
@@ -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)
}
})
}
+60 -30
View File
@@ -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:<key>") 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...)
+108
View File
@@ -0,0 +1,108 @@
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 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
}
type viewPreferencesRepository struct {
db *pgxpool.Pool
}
func NewViewPreferencesRepository(db *pgxpool.Pool) ViewPreferencesRepository {
return &viewPreferencesRepository{db: db}
}
// 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
)
if err := row.Scan(&raw, &sortBy, &reverse, &updatedAt); err != 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) 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
}
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
}
}
var sortBy *string
var reverse *bool
if upd.Sort != nil {
sortBy, reverse = &upd.Sort.By, &upd.Sort.Reverse
}
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, COALESCE($4::jsonb, '[]'::jsonb), COALESCE($5::text, ''), COALESCE($6::boolean, false), now())
ON CONFLICT (user_id, organization_id, view) DO UPDATE
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 {
_, 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
}
@@ -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)
}
}
+108 -395
View File
@@ -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=<id> 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<SearchContacts>(() => {
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.scope, 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<string | null>(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 = (
<>
<SortMenu sort={sortState} options={sortOptions(viewName)} customKeys={view.customKeys} onChange={changeSort} />
<ColumnChooser
visible={view.columns}
available={view.available}
customized={view.customized}
onChange={view.setColumns}
onReset={resetView}
/>
</>
);
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}
<TopbarAction
variant="ghost"
icon={<LayersIcon className="w-3 h-3" />}
@@ -926,45 +983,7 @@ export default function ContactsTable({
placeholder="Search by name, email, company…"
className="w-full sm:w-72"
/>
<PopoverMenu align="end">
<PopoverMenuTrigger asChild>
<SelectButton
icon={<Settings2Icon className="w-3.5 h-3.5" />}
label="Sort"
/>
</PopoverMenuTrigger>
<PopoverMenuContent>
<PopoverMenuLabel>Sort by</PopoverMenuLabel>
{[
["created_at", "Date added"],
["email", "Email"],
["first_name", "First name"],
["last_name", "Last name"],
["company", "Company"],
].map(([key, label]) => (
<PopoverMenuItem
key={key}
selected={searchProps.sort_by === key}
onSelect={() =>
setSearchProps((s) => ({
...s,
sort_by: key as SearchContacts["sort_by"],
}))
}
>
{label}
</PopoverMenuItem>
))}
<PopoverMenuSeparator />
<PopoverMenuItem
selected={searchProps.reverse}
onSelect={() => setSearchProps((s) => ({ ...s, reverse: !s.reverse }))}
closeOnSelect={false}
>
Reverse order
</PopoverMenuItem>
</PopoverMenuContent>
</PopoverMenu>
{viewControls}
</SectionBar>
<FilterBar
@@ -1055,6 +1074,9 @@ function ContactsTableBody({
onRetry,
isRefetching,
contacts,
columns,
sort,
onSort,
isRowSelected,
onToggle,
isSelectedAll,
@@ -1081,25 +1103,11 @@ function ContactsTableBody({
errorMessage: string;
onRetry: () => 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}
/>
</th>
<Th>Name</Th>
<Th className={companyCol}>Company</Th>
{!embedded && <Th className={phoneCol}>Phone</Th>}
<Th className="w-12 sm:w-32">
{/* 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. */}
<span className="sr-only">{embedded ? "Progress" : "Status"}</span>
<span aria-hidden className="hidden sm:inline">{embedded ? "Progress" : "Status"}</span>
</Th>
{embedded && (
<>
<Th className="w-24 hidden lg:table-cell">
<span className="inline-flex items-center gap-1">
Opened
<span
className="inline-flex cursor-help text-slate-300 hover:text-slate-500"
title="Opens rely on the mail client loading images. Clients that block images show no open even when the email was read. A click by the person always counts as an open."
>
<InfoIcon className="w-3 h-3" aria-label="How opens are counted" />
</span>
</span>
</Th>
<Th className="w-24 hidden lg:table-cell">Clicked</Th>
<Th className="w-24 hidden lg:table-cell">Replied</Th>
</>
)}
{embedded ? (
<>
<Th className="w-32 hidden xl:table-cell">Current step</Th>
<Th className="w-36 hidden 2xl:table-cell">
<span className="inline-flex items-center gap-1">
Sender
<span
className="inline-flex cursor-help text-slate-300 hover:text-slate-500"
title="The mailbox this lead's whole sequence sends from. It is picked when the first email goes out and every follow-up keeps it, so the contact always hears from one address."
>
<InfoIcon className="w-3 h-3" aria-label="How the sender is chosen" />
</span>
</span>
</Th>
</>
) : (
<Th className="w-28 text-right hidden lg:table-cell">Campaigns</Th>
)}
<Th className={`text-right ${embedded ? "w-32 hidden 2xl:table-cell" : "w-24 hidden md:table-cell"}`}>
{embedded ? "Last activity" : "Added"}
</Th>
{columns.map((col) => (
<Th key={col.id} col={col} sort={sort} onSort={onSort} />
))}
<th className="px-3 py-2 w-[76px]"></th>
</tr>
</thead>
@@ -1377,152 +1331,14 @@ function ContactsTableBody({
onChange={() => onToggle(c.id, !isSel)}
/>
</td>
<td className="px-3 overflow-hidden">
<div className="flex items-center gap-2.5 min-w-0">
<div className="w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center shrink-0">
<span className="text-[9.5px] font-semibold text-slate-600">
{(c.first_name || c.email)?.slice(0, 2).toUpperCase()}
</span>
</div>
{/* 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. */}
<div className="flex-1 min-w-0">
<div className={`text-[12.5px] font-medium truncate leading-tight flex items-center gap-1.5 ${processed ? "text-slate-400" : "text-slate-900"}`}>
<span className="truncate" {...clippedTitle}>{name}</span>
{/* 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 && (
<span className="inline-flex items-center gap-0.5 min-w-0 max-w-[45%]">
<CategoryChip category={c.categories[0]} compact />
{c.categories.length > 1 && (
<span
className="inline-flex items-center h-4 px-1 shrink-0 rounded text-[10px] font-medium bg-slate-100 text-slate-500"
title={c.categories.slice(1).map((x) => x.title).join(", ")}
>
+{c.categories.length - 1}
</span>
)}
</span>
)}
</div>
<div className="text-[10.5px] text-slate-400 truncate font-mono leading-tight flex items-center gap-1">
<MailIcon className="w-2.5 h-2.5 shrink-0" />
<span className="truncate" {...clippedTitle}>{c.email}</span>
<VerificationBadge contact={c} />
</div>
</div>
</div>
</td>
<td className={`px-3 overflow-hidden text-[12px] text-slate-600 ${companyCol}`}>
{c.company ? (
<div className="flex items-center gap-1.5 min-w-0">
<Building2Icon className="w-3 h-3 shrink-0 text-slate-400" />
<span className="truncate" {...clippedTitle}>
{c.company}
</span>
</div>
) : (
<span className="text-slate-300">—</span>
)}
</td>
{!embedded && (
<td className={`px-3 overflow-hidden text-[12px] text-slate-600 font-mono ${phoneCol}`}>
{c.phone ? (
<div className="flex items-center gap-1.5 min-w-0">
<PhoneIcon className="w-3 h-3 shrink-0 text-slate-400" />
<span className="truncate" {...clippedTitle}>
{c.phone}
</span>
</div>
) : (
<span className="text-slate-300">—</span>
)}
{columns.map((col) => (
<td
key={col.id}
className={`px-3 overflow-hidden ${columnClass(col)} ${col.cellClassName ?? ""}`}
>
{col.cell({ c, lead, processed: !!processed, embedded: !!embedded })}
</td>
)}
<td className="px-3 overflow-hidden">
{embedded ? (
<LeadStatusPill lead={lead} />
) : (
<StatusPill subscribed={c.subscribed} />
)}
</td>
{embedded && (
<>
<EngagementCell
n={lead?.opened ?? 0}
sent={(lead?.sent ?? 0) > 0}
Icon={MailOpenIcon}
label="opened"
auto={(lead?.machine_opened ?? 0) > 0}
/>
<EngagementCell
n={lead?.clicked ?? 0}
sent={(lead?.sent ?? 0) > 0}
Icon={MousePointerClickIcon}
label="clicked"
/>
<EngagementCell
n={lead?.replied ?? 0}
sent={(lead?.sent ?? 0) > 0}
Icon={CornerUpLeftIcon}
label="replied"
/>
</>
)}
{embedded ? (
<>
<td className="px-3 overflow-hidden hidden xl:table-cell">
{lead?.current_step ? (
<span
title={lead.current_step}
className={`inline-flex items-center h-5 px-1.5 rounded text-[11px] font-medium max-w-full ${
processed
? "bg-slate-100 text-slate-400"
: "bg-sky-100 text-sky-700"
}`}
>
<span className="truncate">{lead.current_step}</span>
</span>
) : (
<span className="text-[11px] text-slate-300">Not started</span>
)}
</td>
<td className="px-3 overflow-hidden hidden 2xl:table-cell">
{lead?.sender ? (
<span
title={`Every step of this lead's sequence sends from ${lead.sender}`}
className="block truncate text-[11.5px] text-slate-600"
>
{lead.sender}
</span>
) : (
<span className="text-[11px] text-slate-300">Not assigned</span>
)}
</td>
</>
) : (
<td className="px-3 text-right font-mono text-[12px] text-slate-600 tabular-nums hidden lg:table-cell">
{c.campaigns?.length ?? 0}
</td>
)}
<td className={`px-3 text-right font-mono text-[11px] text-slate-500 tabular-nums ${embedded ? "hidden 2xl:table-cell" : "hidden md:table-cell"}`}>
{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",
})
: "—"}
</td>
))}
<td className="px-3" onClick={(e) => e.stopPropagation()}>
{/* Touch-safe: always visible on mobile, hover-reveal on desktop. */}
<div className="flex items-center gap-0.5 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity">
@@ -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 <th className={base}>{content}</th>;
const active = sort.by === col.sortKey;
const Dir = sort.reverse ? ArrowUpIcon : ArrowDownIcon;
return (
<th
className={`px-3 py-2 text-[10px] font-medium text-slate-400 uppercase tracking-[0.14em] truncate ${className ?? ""}`}
>
{children}
<th className={base} aria-sort={active ? (sort.reverse ? "ascending" : "descending") : "none"}>
<button
type="button"
onClick={() => onSort(col)}
title={`Sort by ${col.label}`}
className={`group/th inline-flex items-center gap-1 max-w-full uppercase tracking-[0.14em] hover:text-slate-700 transition-colors ${
active ? "text-slate-700" : ""
} ${col.align === "right" ? "flex-row-reverse" : ""}`}
>
<span className="truncate">{content}</span>
<Dir className={`w-3 h-3 shrink-0 ${active ? "" : "opacity-0 group-hover/th:opacity-60"}`} aria-hidden />
</button>
</th>
);
}
function StatusPill({ subscribed }: { subscribed: boolean }) {
const label = subscribed ? "subscribed" : "unsubscribed";
return (
<span
className={`inline-flex items-center gap-1 max-w-full text-[10.5px] font-medium uppercase tracking-[0.08em] ${
subscribed ? "text-emerald-700" : "text-slate-500"
}`}
>
<span
className={`size-1.5 shrink-0 rounded-full ${subscribed ? "bg-emerald-500" : "bg-slate-300"}`}
/>
{/* 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. */}
<span className="sr-only">{label}</span>
<span aria-hidden className="hidden sm:inline truncate" {...clippedTitle}>
{label}
</span>
</span>
);
}
// 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 (
<td className="px-3 overflow-hidden hidden lg:table-cell">
{n > 0 ? (
<span
className="inline-flex items-center gap-1 text-[11px] font-medium text-emerald-700 tabular-nums"
title={`${label} ${n} ${n === 1 ? "email" : "emails"}`}
>
<Icon className="w-3 h-3 shrink-0" />
{n}
</span>
) : auto ? (
<span
className="text-[10.5px] text-slate-400"
title="Opened by a mail client automatically, not by a person"
>
auto
</span>
) : sent ? (
<span className="text-slate-300 text-[11px]" aria-label={`not ${label}`}>
—
</span>
) : null}
</td>
);
}
// 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 (
<span
className={`inline-flex items-center gap-1.5 max-w-full text-[10.5px] font-medium uppercase tracking-[0.08em] ${meta.text}`}
title={title}
>
{status === "active" ? (
<span className="campaign-grid text-sky-600 shrink-0" aria-hidden />
) : (
<Icon className="w-3 h-3 shrink-0" />
)}
<span className="sr-only">{meta.label}</span>
{/* 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. */}
<span aria-hidden className="hidden sm:inline truncate" title={title} {...(title ? {} : clippedTitle)}>
{meta.label}
</span>
</span>
);
}
// 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.
//
@@ -0,0 +1,325 @@
// 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, 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,
PopoverMenuContent,
PopoverMenuItem,
PopoverMenuLabel,
PopoverMenuSeparator,
PopoverMenuTrigger,
SelectButton,
} from "@/components/ui/popover-menu";
import { customColumnId, type ContactColumn, type SortOption } from "./columns";
export interface ViewSortState {
by: SearchContactsSortBy;
reverse: boolean;
}
function ColumnLabel({ col }: { col: ContactColumn }) {
return (
<>
<span className="truncate">{col.label}</span>
{col.custom && (
<span className="ml-auto shrink-0 text-[10px] uppercase tracking-[0.08em] text-slate-400">custom</span>
)}
</>
);
}
// 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 (
<Reorder.Item
as="div"
value={col}
dragListener={false}
dragControls={controls}
onDragEnd={onDragEnd}
className="relative bg-white"
>
<div className="mx-1 h-7 pl-1 pr-2 flex items-center gap-1.5 rounded text-[12px] text-slate-700 hover:bg-slate-100 transition-colors">
<button
type="button"
onPointerDown={(e) => controls.start(e)}
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`}
>
<GripVerticalIcon className="w-3 h-3" />
</button>
<button type="button" onClick={onHide} className="flex-1 min-w-0 h-full flex items-center gap-2 text-left">
<CheckSquare checked />
<ColumnLabel col={col} />
</button>
</div>
</Reorder.Item>
);
}
function PlainRow({ col, checked, onClick }: { col: ContactColumn; checked: boolean; onClick: () => void }) {
return (
<button
type="button"
onClick={onClick}
className="w-[calc(100%-8px)] mx-1 h-7 pl-1 pr-2 flex items-center gap-1.5 rounded text-[12px] text-slate-700 hover:bg-slate-100 transition-colors text-left"
>
<span className="size-5 shrink-0" />
<CheckSquare checked={checked} />
<ColumnLabel col={col} />
</button>
);
}
function GroupLabel({ children }: { children: React.ReactNode }) {
return (
<div className="px-3 pt-2 pb-1 text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium">{children}</div>
);
}
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 every shown column in order, Name first.
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);
// 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);
};
// The keyboard path: one step up or down, saved at once.
const moveBy = (id: string, delta: -1 | 1) => {
const cur = orderRef.current;
const from = cur.findIndex((c) => c.id === id);
const to = from + delta;
if (from < 0 || to < 0 || to >= cur.length) return;
const next = [...cur];
[next[from], next[to]] = [next[to], next[from]];
setOrder(next);
onChange(layout(next));
};
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 (
<PopoverMenu align="end" open={open} onOpenChange={(o) => { setOpen(o); if (!o) setQuery(""); }}>
<PopoverMenuTrigger asChild>
<SelectButton
icon={<Columns3Icon className="w-3.5 h-3.5" />}
label="Columns"
className={customized ? "border-sky-200 text-sky-700 hover:text-sky-800" : undefined}
aria-label="Choose columns"
/>
</PopoverMenuTrigger>
<PopoverMenuContent minWidth={272} className="py-0 w-[272px]">
<div className="px-2 py-1.5 border-b border-slate-200">
<input
value={query}
onChange={(e) => 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"
/>
</div>
<div className="max-h-[min(60vh,420px)] overflow-y-auto pb-1">
{nothing && (
<div className="px-3 py-4 text-[11.5px] text-slate-400 text-center">No column matches.</div>
)}
{(locked.some(matches) || shownMatches.length > 0) && (
<GroupLabel>{q ? "Shown" : "Shown · drag to reorder"}</GroupLabel>
)}
{locked.filter(matches).map((col) => (
<div
key={col.id}
className="mx-1 h-7 pl-1 pr-2 flex items-center gap-1.5 rounded text-[12px] text-slate-500"
title="Always shown"
>
<span className="size-5 flex items-center justify-center text-slate-300">
<LockIcon className="w-3 h-3" />
</span>
<CheckSquare checked />
<span className="truncate">{col.label}</span>
</div>
))}
{q ? (
shownMatches.map((col) => (
<PlainRow key={col.id} col={col} checked onClick={() => hide(col.id)} />
))
) : (
<Reorder.Group as="div" axis="y" values={order} onReorder={setOrder}>
{order.map((col) => (
<ShownRow
key={col.id}
col={col}
onHide={() => hide(col.id)}
onDragEnd={commitOrder}
onMove={(d) => moveBy(col.id, d)}
/>
))}
</Reorder.Group>
)}
{builtinAvail.length > 0 && (
<>
<GroupLabel>Available</GroupLabel>
{builtinAvail.map((col) => (
<PlainRow key={col.id} col={col} checked={false} onClick={() => show(col.id)} />
))}
</>
)}
{customAvail.length > 0 && (
<>
<GroupLabel>Custom fields</GroupLabel>
{customAvail.map((col) => (
<PlainRow key={col.id} col={col} checked={false} onClick={() => show(col.id)} />
))}
</>
)}
</div>
<div className="px-2 py-1.5 border-t border-slate-200 flex items-center justify-between gap-2">
<span className="text-[11px] text-slate-400 tabular-nums">
{visible.length} of {visible.length + available.length} shown
</span>
<button
type="button"
disabled={!customized}
onClick={() => { onReset(); setOpen(false); }}
className="h-6 px-2 rounded inline-flex items-center gap-1 text-[11.5px] text-slate-600 hover:text-slate-900 hover:bg-slate-100 disabled:opacity-40 disabled:hover:bg-transparent transition-colors"
>
<RotateCcwIcon className="w-3 h-3" />
Reset to default
</button>
</div>
</PopoverMenuContent>
</PopoverMenu>
);
}
// 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: SortOption[];
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 (
<PopoverMenu align="end">
<PopoverMenuTrigger asChild>
<SelectButton
icon={<Dir className="w-3.5 h-3.5" />}
label={active ? active.label : "Sort"}
aria-label="Sort"
/>
</PopoverMenuTrigger>
<PopoverMenuContent className="max-h-[min(60vh,420px)] overflow-y-auto">
<PopoverMenuLabel>Sort by</PopoverMenuLabel>
{options.map((o) => (
<PopoverMenuItem
key={o.key}
selected={sort.by === o.key}
onSelect={() => onChange({ by: o.key, reverse: sort.by === o.key ? sort.reverse : o.asc })}
>
{o.label}
</PopoverMenuItem>
))}
{customKeys.length > 0 && (
<>
<PopoverMenuSeparator />
<PopoverMenuLabel>Custom fields</PopoverMenuLabel>
{customKeys.map((k) => {
const key = customColumnId(k) as SearchContactsSortBy;
return (
<PopoverMenuItem
key={key}
selected={sort.by === key}
onSelect={() => onChange({ by: key, reverse: sort.by === key ? sort.reverse : true })}
>
{k}
</PopoverMenuItem>
);
})}
</>
)}
<PopoverMenuSeparator />
<PopoverMenuItem
selected={sort.reverse}
onSelect={() => onChange({ ...sort, reverse: !sort.reverse })}
closeOnSelect={false}
>
Reverse order
</PopoverMenuItem>
</PopoverMenuContent>
</PopoverMenu>
);
}
+149
View File
@@ -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 <span className="text-slate-300">—</span>;
}
// A header with an info tooltip beside the label.
export function InfoHeader({ label, title, aria }: { label: string; title: string; aria: string }) {
return (
<span className="inline-flex items-center gap-1">
{label}
<span className="inline-flex cursor-help text-slate-300 hover:text-slate-500" title={title}>
<InfoIcon className="w-3 h-3" aria-label={aria} />
</span>
</span>
);
}
export function StatusPill({ subscribed }: { subscribed: boolean }) {
const label = subscribed ? "subscribed" : "unsubscribed";
return (
<span
className={`inline-flex items-center gap-1 max-w-full text-[10.5px] font-medium uppercase tracking-[0.08em] ${
subscribed ? "text-emerald-700" : "text-slate-500"
}`}
>
<span
className={`size-1.5 shrink-0 rounded-full ${subscribed ? "bg-emerald-500" : "bg-slate-300"}`}
/>
{/* 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. */}
<span className="sr-only">{label}</span>
<span aria-hidden className="hidden sm:inline truncate" {...clippedTitle}>
{label}
</span>
</span>
);
}
// 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 (
<span
className="inline-flex items-center gap-1 text-[11px] font-medium text-emerald-700 tabular-nums"
title={`${label} ${n} ${n === 1 ? "email" : "emails"}`}
>
<Icon className="w-3 h-3 shrink-0" />
{n}
</span>
);
}
if (auto) {
return (
<span
className="text-[10.5px] text-slate-400"
title="Opened by a mail client automatically, not by a person"
>
auto
</span>
);
}
if (sent) {
return (
<span className="text-slate-300 text-[11px]" aria-label={`not ${label}`}>
—
</span>
);
}
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 (
<span
className={`inline-flex items-center gap-1.5 max-w-full text-[10.5px] font-medium uppercase tracking-[0.08em] ${meta.text}`}
title={title}
>
{status === "active" ? (
<span className="campaign-grid text-sky-600 shrink-0" aria-hidden />
) : (
<Icon className="w-3 h-3 shrink-0" />
)}
<span className="sr-only">{meta.label}</span>
{/* 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. */}
<span aria-hidden className="hidden sm:inline truncate" title={title} {...(title ? {} : clippedTitle)}>
{meta.label}
</span>
</span>
);
}
@@ -0,0 +1,53 @@
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(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("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"]);
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);
});
});
+453
View File
@@ -0,0 +1,453 @@
// 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<string, string>;
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<Breakpoint, string> = {
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 (
<div className="flex items-center gap-2.5 min-w-0">
<div className="w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center shrink-0">
<span className="text-[9.5px] font-semibold text-slate-600">
{(c.first_name || c.email)?.slice(0, 2).toUpperCase()}
</span>
</div>
{/* 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. */}
<div className="flex-1 min-w-0">
<div className={`text-[12.5px] font-medium truncate leading-tight flex items-center gap-1.5 ${processed ? "text-slate-400" : "text-slate-900"}`}>
<span className="truncate" {...clippedTitle}>{name}</span>
{/* 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 && (
<span className="inline-flex items-center gap-0.5 min-w-0 max-w-[45%]">
<CategoryChip category={c.categories[0]} compact />
{c.categories.length > 1 && (
<span
className="inline-flex items-center h-4 px-1 shrink-0 rounded text-[10px] font-medium bg-slate-100 text-slate-500"
title={c.categories.slice(1).map((x) => x.title).join(", ")}
>
+{c.categories.length - 1}
</span>
)}
</span>
)}
</div>
<div className="text-[10.5px] text-slate-400 truncate font-mono leading-tight flex items-center gap-1">
<MailIcon className="w-2.5 h-2.5 shrink-0" />
<span className="truncate" {...clippedTitle}>{c.email}</span>
<VerificationBadge contact={c} />
</div>
</div>
</div>
);
},
};
// 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 ? (
<div className="flex items-center gap-1.5 min-w-0">
<Building2Icon className="w-3 h-3 shrink-0 text-slate-400" />
<span className="truncate" {...clippedTitle}>{c.company}</span>
</div>
) : (
<Dash />
),
};
}
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 ? (
<div className="flex items-center gap-1.5 min-w-0">
<PhoneIcon className="w-3 h-3 shrink-0 text-slate-400" />
<span className="truncate" {...clippedTitle}>{c.phone}</span>
</div>
) : (
<Dash />
),
};
// 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 (
<>
<span className="sr-only">{label}</span>
<span aria-hidden className="hidden sm:inline">{label}</span>
</>
);
}
const statusColumn: ContactColumn = {
id: "status",
label: "Status",
header: statusHeader("Status"),
width: "w-12 sm:w-32",
cell: ({ c }) => <StatusPill subscribed={c.subscribed} />,
};
const progressColumn: ContactColumn = {
id: "progress",
label: "Progress",
header: statusHeader("Progress"),
width: "w-12 sm:w-32",
cell: ({ lead }) => <LeadStatusPill lead={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 }) => (
<EngagementValue
n={lead?.[id] ?? 0}
sent={(lead?.sent ?? 0) > 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 ? (
<span
title={lead.current_step}
className={`inline-flex items-center h-5 px-1.5 rounded text-[11px] font-medium max-w-full ${
processed ? "bg-slate-100 text-slate-400" : "bg-sky-100 text-sky-700"
}`}
>
<span className="truncate">{lead.current_step}</span>
</span>
) : (
<span className="text-[11px] text-slate-300">Not started</span>
),
};
const senderColumn: ContactColumn = {
id: "sender",
label: "Sender",
header: (
<InfoHeader
label="Sender"
title="The mailbox this lead's whole sequence sends from. It is picked when the first email goes out and every follow-up keeps it, so the contact always hears from one address."
aria="How the sender is chosen"
/>
),
width: "w-36",
hideBelow: "2xl",
cell: ({ lead }) =>
lead?.sender ? (
<span
title={`Every step of this lead's sequence sends from ${lead.sender}`}
className="block truncate text-[11.5px] text-slate-600"
>
{lead.sender}
</span>
) : (
<span className="text-[11px] text-slate-300">Not assigned</span>
),
};
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 ? <span className="block truncate" {...clippedTitle}>{v}</span> : <Dash />;
},
};
}
// 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,
<InfoHeader
label="Opened"
title="Opens rely on the mail client loading images. Clients that block images show no open even when the email was read. A click by the person always counts as an open."
aria="How opens are counted"
/>,
),
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.
export const DEFAULT_COLUMNS: Record<ViewName, string[]> = {
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. 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,
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<string>();
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 };
}
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): 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", asc: false });
return base;
}
@@ -0,0 +1,59 @@
// 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, 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 user = useUser();
const scope = React.useMemo<ViewScope>(
() => ({ 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;
const savedColumns = saved?.columns;
const customKeys = React.useMemo(() => keys.data ?? [], [keys.data]);
const { visible, available } = React.useMemo(
() => resolveColumns(view, savedColumns, customKeys),
[view, savedColumns, customKeys],
);
// 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 {
scope,
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,
// A saved sort alone is a customisation too: reset is what clears it.
customized: (savedColumns?.length ?? 0) > 0 || saved?.sort != null,
setColumns,
setSort,
reset: resetView,
};
}
+17
View File
@@ -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 (
<span
className={`size-3.5 rounded border flex items-center justify-center transition-colors shrink-0 ${
checked ? "border-slate-900 bg-slate-900" : "border-slate-300 bg-white"
}`}
>
{checked && <CheckIcon className="w-2 h-2 text-white" />}
</span>
);
}
+33
View File
@@ -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<ViewPreferencesEnvelope> {
return await Request<ViewPreferencesEnvelope>({
method: "GET",
url: `/me/views/${view}`,
authorization: true,
});
}
export async function updateViewPreferences(view: ViewName, body: UpdateViewPreferences): Promise<ViewPreferencesEnvelope> {
return await Request<ViewPreferencesEnvelope>({
method: "PUT",
url: `/me/views/${view}`,
data: body,
authorization: true,
});
}
export async function resetViewPreferences(view: ViewName): Promise<void> {
await Request<void>({
method: "DELETE",
url: `/me/views/${view}`,
authorization: true,
});
}
@@ -0,0 +1,122 @@
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";
// 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(scope: ViewScope, view: ViewName): ViewPreferences | undefined {
if (!scoped(scope)) return undefined;
try {
const raw = localStorage.getItem(cacheKey(scope, view));
if (!raw) return undefined;
const p = JSON.parse(raw) as Partial<ViewPreferences> | 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(scope: ViewScope, view: ViewName, prefs: ViewPreferences | null) {
if (!scoped(scope)) return;
try {
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, scope: ViewScope) {
const q = useQuery({
queryKey: queryKey(scope, view),
queryFn: async () => (await getViewPreferences(view)).preferences,
enabled: scoped(scope),
staleTime: 5 * 60 * 1000,
placeholderData: () => readCachedView(scope, view),
});
React.useEffect(() => {
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. 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(scope, view);
return useMutation({
mutationFn: (body: UpdateViewPreferences) => updateViewPreferences(view, body),
onMutate: async (body) => {
await qc.cancelQueries({ queryKey: key });
const previous = qc.getQueryData<ViewPreferences>(key);
const next: ViewPreferences = {
view,
columns: body.columns ?? previous?.columns ?? [],
sort: body.sort !== undefined ? (body.sort.by ? body.sort : null) : (previous?.sort ?? null),
};
qc.setQueryData<ViewPreferences>(key, next);
writeCachedView(scope, view, next);
return { previous };
},
onError: (_err, _body, ctx) => {
qc.setQueryData(key, ctx?.previous);
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(scope, view, envelope.preferences);
},
});
}
export function useResetViewPreferences(view: ViewName, scope: ViewScope) {
const qc = useQueryClient();
const key = queryKey(scope, view);
return useMutation({
mutationFn: () => resetViewPreferences(view),
onMutate: async () => {
await qc.cancelQueries({ queryKey: key });
const previous = qc.getQueryData<ViewPreferences>(key);
qc.setQueryData<ViewPreferences>(key, { view, columns: [], sort: null });
writeCachedView(scope, view, null);
return { previous };
},
onError: (_err, _v, ctx) => {
qc.setQueryData(key, ctx?.previous);
writeCachedView(scope, view, ctx?.previous ?? null);
toast.error("Couldn't reset the view.");
},
});
}
@@ -1,5 +1,16 @@
// A built-in sort column, or "custom:<key>" 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';
@@ -0,0 +1,30 @@
// 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;
}
// 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;
}