Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/web/e2e/tests/platform/rest-people.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -927,7 +927,8 @@ test.describe('REST segment members', () => {
}),
200
)
expect(again.data).toEqual({ added: 1, failed: [] })
// Already a member: nothing is added, and the manual row is kept.
expect(again.data).toEqual({ added: 0, failed: [] })
expect((await segmentRows(seg.uuid)).get(toUuid(u3.principalId))).toBe('manual')
await admin.api.dispose()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ const m = vi.hoisted(() => {
companyCreate: make(),
companyUpdate: make(),
companyDelete: make(),
toastError: vi.fn(),
}
})

vi.mock('@/lib/client/error-notice', () => ({ toastError: m.toastError }))

vi.mock('@/lib/client/mutations', () => ({
useCreateUserAttribute: () => m.userCreate,
useUpdateUserAttribute: () => m.userUpdate,
Expand Down Expand Up @@ -104,6 +107,57 @@ describe.each(ENTITIES)('ScalarAttributeList for $name', (entity) => {
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
})

it('keeps the dialog open and says why when the server refuses the key', async () => {
const { create } = entity.mocks()
create.mutateAsync.mockRejectedValue(new Error('An attribute with that key already exists'))
const user = userEvent.setup()
renderList([])
await user.click(screen.getAllByRole('button', { name: /new attribute/i })[0])
const dialog = await screen.findByRole('dialog')
await user.type(within(dialog).getByLabelText(/^Key/), 'seats')
await user.type(within(dialog).getByLabelText('Display label'), 'Seats again')
await user.click(within(dialog).getByRole('button', { name: 'Create attribute' }))
expect((await within(dialog).findByRole('alert')).textContent).toBe(
'An attribute with that key already exists'
)
expect(screen.getByRole('dialog')).toBeTruthy()

// Reopening starts clean.
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
await user.click(screen.getAllByRole('button', { name: /new attribute/i })[0])
expect(within(await screen.findByRole('dialog')).queryByRole('alert')).toBeNull()
})

it('says why when the server refuses an edit', async () => {
const { update } = entity.mocks()
update.mutateAsync.mockRejectedValue(new Error('Attribute not found'))
const user = userEvent.setup()
renderList()
await user.click(screen.getByRole('button', { name: 'Actions for Seats' }))
await user.click(await screen.findByRole('menuitem', { name: 'Edit' }))
const dialog = await screen.findByRole('dialog')
await user.click(within(dialog).getByRole('button', { name: 'Save changes' }))
expect((await within(dialog).findByRole('alert')).textContent).toBe('Attribute not found')
})

it('toasts a refused delete and keeps the row', async () => {
const { del } = entity.mocks()
del.mutateAsync.mockRejectedValue(new Error('Attribute not found'))
const user = userEvent.setup()
renderList()
await user.click(screen.getByRole('button', { name: 'Actions for Seats' }))
await user.click(await screen.findByRole('menuitem', { name: 'Delete' }))
await user.click(
within(await screen.findByRole('alertdialog')).getByRole('button', {
name: 'Delete attribute',
})
)
await waitFor(() => expect(m.toastError).toHaveBeenCalledTimes(1))
expect(m.toastError.mock.calls[0][0]).toMatchObject({ message: 'Attribute not found' })
expect(screen.getByText('Seats')).toBeTruthy()
})

it('edits an attribute with the key locked and saves the new label', async () => {
const { update } = entity.mocks()
update.mutateAsync.mockResolvedValue(stored({ label: 'Active seats' }))
Expand Down
29 changes: 27 additions & 2 deletions apps/web/src/components/admin/settings/scalar-attribute-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import {
DialogFooter,
} from '@/components/ui/dialog'
import { ConfirmDialog } from '@/components/shared/confirm-dialog'
import { errorText } from '@/lib/client/error-text'
import { toastError } from '@/lib/client/error-notice'
import { AttributeList, type AttributeListItem } from './attribute-list'

const ATTRIBUTE_TYPES = [
Expand Down Expand Up @@ -131,9 +133,11 @@ function AttributeFormDialog({
const [type, setType] = useState<ScalarAttributeType>(initialValues?.type ?? 'string')
const [currencyCode, setCurrencyCode] = useState(initialValues?.currencyCode ?? 'USD')
const [externalKey, setExternalKey] = useState(initialValues?.externalKey ?? '')
const [error, setError] = useState<string | null>(null)

useEffect(() => {
if (open) {
setError(null)
setKey(initialValues?.key ?? '')
setLabel(initialValues?.label ?? '')
setDescription(initialValues?.description ?? '')
Expand All @@ -146,7 +150,17 @@ function AttributeFormDialog({

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
await onSubmit({ key, label, description, type, currencyCode, externalKey })
setError(null)
try {
await onSubmit({ key, label, description, type, currencyCode, externalKey })
} catch (err) {
setError(
errorText(
err,
isEditing ? "Couldn't save the attribute." : "Couldn't create the attribute."
)
)
}
}

const canSubmit = key.trim().length > 0 && label.trim().length > 0
Expand Down Expand Up @@ -253,6 +267,12 @@ function AttributeFormDialog({
<p className="text-[11px] text-muted-foreground">{copy.externalHint}</p>
</div>

{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}

<DialogFooter>
<Button
type="button"
Expand Down Expand Up @@ -311,7 +331,12 @@ export function ScalarAttributeList<T extends ScalarAttribute>({

const handleDelete = async () => {
if (!deleteTarget) return
await onDelete(deleteTarget.id)
try {
await onDelete(deleteTarget.id)
} catch (err) {
toastError(err, "Couldn't delete the attribute.")
return
}
setAttributes((prev) => prev.filter((a) => a.id !== deleteTarget.id))
setDeleteTarget(null)
}
Expand Down
8 changes: 8 additions & 0 deletions apps/web/src/lib/server/__tests__/principal-merge-db-mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,17 @@ interface MockTx {
delete: (table: { __name?: string }) => { where: Mock }
update: (table: { __name?: string }) => { set: Mock }
query: { principal: { findFirst: Mock } }
execute: Mock
}

/** Raw statements (the vote-count withdrawal on merge); logged as `execute`. */
export const mockExecute: Mock = vi.fn(async () => {
operations.push('execute')
return []
})

export const mockTx: MockTx = {
execute: mockExecute,
select: (..._args: unknown[]) => ({ from: mockSelectFrom }),
delete: (table: { __name?: string }) => {
operations.push(`delete:${table.__name || 'unknown'}`)
Expand Down
60 changes: 60 additions & 0 deletions apps/web/src/lib/server/auth/__tests__/merge-anonymous.db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,66 @@ describe.skipIf(!fixture.available)('principal merge (real DB, rolled back)', ()
).resolves.toHaveLength(0)
})

it('takes a dropped colliding vote off the post count', async () => {
const anon = await seedIdentity({ type: 'anonymous', name: 'Curious Penguin' })
const target = await seedIdentity({
type: 'user',
name: 'Jane Doe',
email: `jane-${runSuffix()}@example.com`,
})
const { postId } = await seedBoardWithPost(target.principalId)
await testDb.update(posts).set({ voteCount: 2 }).where(eq(posts.id, postId))
await testDb.insert(postVotes).values([
{ postId, principalId: anon.principalId },
{ postId, principalId: target.principalId },
])

await mergeAnonymousToIdentified({
anonPrincipalId: anon.principalId,
targetPrincipalId: target.principalId,
anonUserId: anon.userId,
anonDisplayName: 'Curious Penguin',
targetDisplayName: 'Jane Doe',
})

const [row] = await testDb
.select({ voteCount: posts.voteCount })
.from(posts)
.where(eq(posts.id, postId))
expect(row.voteCount).toBe(1)
})

it("takes a counted vote off when the vote that survives is a test customer's", async () => {
const owner = await seedIdentity({ type: 'user', name: 'Teammate' })
const anon = await seedIdentity({ type: 'anonymous', name: 'Curious Penguin' })
const target = await seedIdentity({ type: 'user', name: 'Test customer' })
await testDb
.update(principal)
.set({ testOwnerPrincipalId: owner.principalId })
.where(eq(principal.id, target.principalId))
const { postId } = await seedBoardWithPost(owner.principalId)
// Only the visitor's vote was counted; the test customer's never is.
await testDb.update(posts).set({ voteCount: 1 }).where(eq(posts.id, postId))
await testDb.insert(postVotes).values([
{ postId, principalId: anon.principalId },
{ postId, principalId: target.principalId },
])

await mergeAnonymousToIdentified({
anonPrincipalId: anon.principalId,
targetPrincipalId: target.principalId,
anonUserId: anon.userId,
anonDisplayName: 'Curious Penguin',
targetDisplayName: 'Test customer',
})

const [row] = await testDb
.select({ voteCount: posts.voteCount })
.from(posts)
.where(eq(posts.id, postId))
expect(row.voteCount).toBe(0)
})

it('never overwrites a populated target contact_email and merges a no-activity anon cleanly', async () => {
const anonCompany = await seedCompany('Lead Co')
const targetCompany = await seedCompany('Existing Co')
Expand Down
41 changes: 40 additions & 1 deletion apps/web/src/lib/server/domains/posts/post.merge-ids.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* client holding the source still mutates the surviving thread.
*/
import { db, posts, postVotes, postComments, boards, eq, sql } from '@/lib/server/db'
import { isValidTypeId, toUuid, type PostId } from '@quackback/ids'
import { isValidTypeId, toUuid, type PostId, type PrincipalId } from '@quackback/ids'
import { getExecuteRows } from '@/lib/server/utils'
import { notTestPrincipal } from '@/lib/server/test-data'

Expand Down Expand Up @@ -78,6 +78,45 @@ export async function adjustCanonicalCommentCount(
`)
}

/** The merge threads (canonical post ids) a principal holds a vote row in. */
function votedThreadIdsSql(principalId: PrincipalId) {
return sql`
SELECT COALESCE(p.canonical_post_id, p.id)
FROM ${postVotes} v
INNER JOIN ${posts} p ON p.id = v.post_id
WHERE v.principal_id = ${toUuid(principalId)}::uuid
`
}

/**
* Take a principal's vote off the stored count of every merge thread it voted
* in, ahead of its vote rows going away. `vote_count` lives on the thread's
* canonical post and counts each voter once, and a test customer's votes were
* never counted. With `keptBy`, only the threads that principal also voted in
* lose a vote: elsewhere the leaving vote is re-pointed, not dropped.
*
* A delta rather than a recount: an imported post can carry a count with no
* vote rows behind it.
*/
export async function withdrawThreadVotes(
conn: TransactionalDb,
principalId: PrincipalId,
options: { keptBy?: PrincipalId } = {}
): Promise<void> {
const { keptBy } = options
const threads = keptBy
? sql`${votedThreadIdsSql(principalId)} INTERSECT ${votedThreadIdsSql(keptBy)}`
: votedThreadIdsSql(principalId)
// Whether the count drops depends only on the vote leaving it: a kept test
// customer's vote was never counted, so it does not stand in for this one.
await conn.execute(sql`
UPDATE ${posts}
SET vote_count = GREATEST(0, vote_count - 1)
WHERE id IN (${threads})
AND ${notTestPrincipal(sql`${toUuid(principalId)}::uuid`)}
`)
}

/**
* Recount unique voters and public comments across a canonical + its sources.
* Runs via the transaction handle when called from merge/unmerge so the
Expand Down
30 changes: 24 additions & 6 deletions apps/web/src/lib/server/domains/principals/principal-repoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
*/
import { toUuid, type PrincipalId } from '@quackback/ids'
import { forgetRequestSegmentIds } from '@/lib/server/auth/request-session'
import { withdrawThreadVotes } from '@/lib/server/domains/posts/post.merge-ids'
import {
slackUserLinks,
postVotes,
Expand Down Expand Up @@ -169,6 +170,21 @@ function collisionRepoint(
}
}

/**
* Wraps the post_votes step: the source's and target's votes in one merge
* thread become one voter's, so the thread's stored vote_count loses one
* before the rows are dropped or re-pointed.
*/
function withdrawCollidingVotes(step: RepointStep): RepointStep {
return {
...step,
async run(tx, ctx) {
await withdrawThreadVotes(tx, ctx.from, { keptBy: ctx.to })
await step.run(tx, ctx)
},
}
}

/**
* A fill-if-empty attribute consolidation on the principal itself (not a
* re-point): the source value fills the target only when the target's own
Expand Down Expand Up @@ -217,12 +233,14 @@ export const REPOINT_STEPS: RepointStep[] = [
'principal_id',
'Preserve Slack identity links when a principal is absorbed; uniqueness is on Slack team and user, not principal.'
),
collisionRepoint(
'post_votes',
postVotes,
'principal_id',
['post_id'],
'Votes; unique (post_id, principal_id). The identified vote wins: colliding anon votes are dropped.'
withdrawCollidingVotes(
collisionRepoint(
'post_votes',
postVotes,
'principal_id',
['post_id'],
'Votes; unique (post_id, principal_id). The identified vote wins: colliding anon votes are dropped. Where both voted in one merge thread, the stored vote_count loses the vote first.'
)
),
collisionRepoint(
'post_comment_reactions',
Expand Down
Loading
Loading