fix(m12): user can answer idea-questions — inline + bell support

Two gaps discovered during the first live grill-session of IDEA-002:
the agent posted a question, but the user had no UI to answer it.
1. Idea-questions only appeared on the Timeline-tab as read-only entries
2. Notifications-bell fetched + handled story-questions only

This fix:

**Inline answer-form in IdeaTimeline** (components/ideas/idea-timeline.tsx)
- Open questions now render an AnswerForm directly under the question text
- Multi-choice options become clickable buttons (one-click submit); free-text
  fallback via collapsed details/textarea
- Plain free-text questions render textarea + Verzend
- Calls existing answerQuestion server-action; toast + router.refresh on success

**Notifications-bell extended for idea-questions**
- stores/notifications-store.ts: NotificationQuestion → discriminated union
  (kind: 'story' | 'idea'); forYouCount treats idea-questions as always-for-you
  (idea is strictly user_id-only — only the owner sees them)
- components/notifications/notifications-bridge.tsx: parallel fetch of
  story-questions (productAccessFilter) + idea-questions (idea.user_id ===
  session.userId); merged + sorted by created_at
- components/notifications/notifications-sheet.tsx: renders idea_code/title
  for kind='idea'
- components/notifications/answer-modal.tsx: header + open-link branch on
  kind (idea → /ideas/[id]?tab=timeline; story → existing /sprint link)
- lib/realtime/use-notifications-realtime.ts: idea-question events also
  trigger close+reconnect on 'open' (loads fresh detail) and remove(id) on
  non-open — same pattern story-questions already use
- components/shared/notifications-bell.tsx: badge counts idea-questions as
  for-you regardless of assignee

**Security gap closed (actions/questions.ts answerQuestion)**
Before: accepted any answer if user has product-access.
After: idea-questions require idea.user_id === session.userId; story-
questions keep the existing productAccessFilter path. (Prisma 7 rejects
\`{ not: null }\` in WHERE; routing happens app-level after a single fetch.)

Tests: 546/546 still green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Janpeter Visser 2026-05-05 13:05:39 +02:00
parent 02a7f59897
commit 9e8f33b96e
9 changed files with 281 additions and 52 deletions

View file

@ -16,6 +16,9 @@ vi.mock('@/lib/prisma', () => ({
findFirst: vi.fn(), findFirst: vi.fn(),
updateMany: vi.fn(), updateMany: vi.fn(),
}, },
product: {
findFirst: vi.fn().mockResolvedValue({ id: 'product-1' }),
},
}, },
})) }))
@ -44,7 +47,13 @@ beforeEach(() => {
describe('actions/questions — answerQuestion', () => { describe('actions/questions — answerQuestion', () => {
it('happy: status pending→answered, revalidatePath geroepen', async () => { it('happy: status pending→answered, revalidatePath geroepen', async () => {
mockGetSession.mockResolvedValue(SESSION_USER) mockGetSession.mockResolvedValue(SESSION_USER)
mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({ id: VALID_ID }) // access-check mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({
id: VALID_ID,
story_id: 'story-1',
idea_id: null,
product_id: 'product-1',
idea: null,
})
mockPrisma.claudeQuestion.updateMany.mockResolvedValueOnce({ count: 1 }) mockPrisma.claudeQuestion.updateMany.mockResolvedValueOnce({ count: 1 })
const res = await answerQuestion(VALID_ID, VALID_ANSWER) const res = await answerQuestion(VALID_ID, VALID_ANSWER)
@ -85,7 +94,13 @@ describe('actions/questions — answerQuestion', () => {
it('al-answered: race-error met begrijpelijke melding', async () => { it('al-answered: race-error met begrijpelijke melding', async () => {
mockGetSession.mockResolvedValue(SESSION_USER) mockGetSession.mockResolvedValue(SESSION_USER)
mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({ id: VALID_ID }) // access-check mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({
id: VALID_ID,
story_id: 'story-1',
idea_id: null,
product_id: 'product-1',
idea: null,
})
mockPrisma.claudeQuestion.updateMany.mockResolvedValueOnce({ count: 0 }) mockPrisma.claudeQuestion.updateMany.mockResolvedValueOnce({ count: 0 })
mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({ mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({
status: 'answered', status: 'answered',
@ -99,7 +114,13 @@ describe('actions/questions — answerQuestion', () => {
it('verlopen: updateMany count=0, nog open status maar voorbij expiry', async () => { it('verlopen: updateMany count=0, nog open status maar voorbij expiry', async () => {
mockGetSession.mockResolvedValue(SESSION_USER) mockGetSession.mockResolvedValue(SESSION_USER)
mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({ id: VALID_ID }) mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({
id: VALID_ID,
story_id: 'story-1',
idea_id: null,
product_id: 'product-1',
idea: null,
})
mockPrisma.claudeQuestion.updateMany.mockResolvedValueOnce({ count: 0 }) mockPrisma.claudeQuestion.updateMany.mockResolvedValueOnce({ count: 0 })
mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({ mockPrisma.claudeQuestion.findFirst.mockResolvedValueOnce({
status: 'open', status: 'open',

View file

@ -37,18 +37,43 @@ export async function answerQuestion(
return { ok: false, error: first } return { ok: false, error: first }
} }
// Access-check: gebruiker moet toegang hebben tot het product van de vraag. // Access-check (M12-aware):
// Iedereen met product-membership mag antwoorden — niet alleen de story- // - Story-questions: iedereen met product-membership mag antwoorden
// assignee — consistent met Scrum self-organizing. // (consistent met Scrum self-organizing).
// - Idea-questions: strikt user_id-only — alleen de eigenaar van het
// gekoppelde idee mag antwoorden (M12 grill-keuze 8).
// App-level routing omdat Prisma 7 `{ not: null }` filters in WHERE niet
// accepteert; we fetchen de relevante FK-keys en checken in TS.
const question = await prisma.claudeQuestion.findFirst({ const question = await prisma.claudeQuestion.findFirst({
where: { where: { id: parsed.data.questionId },
id: parsed.data.questionId, select: {
product: productAccessFilter(session.userId), id: true,
story_id: true,
idea_id: true,
product_id: true,
idea: { select: { user_id: true } },
}, },
select: { id: true },
}) })
if (!question) return { ok: false, error: 'Vraag niet gevonden of geen toegang' } if (!question) return { ok: false, error: 'Vraag niet gevonden of geen toegang' }
if (question.idea_id) {
// Idea-question: alleen idea-eigenaar.
if (question.idea?.user_id !== session.userId) {
return { ok: false, error: 'Vraag niet gevonden of geen toegang' }
}
} else if (question.story_id) {
// Story-question: bestaand product-access-pad.
const productAccess = await prisma.product.findFirst({
where: { id: question.product_id, ...productAccessFilter(session.userId) },
select: { id: true },
})
if (!productAccess) {
return { ok: false, error: 'Vraag niet gevonden of geen toegang' }
}
} else {
return { ok: false, error: 'Vraag heeft geen story of idea' }
}
// Atomic state-transitie: alleen open + niet-verlopen vragen worden beantwoord. // Atomic state-transitie: alleen open + niet-verlopen vragen worden beantwoord.
// Concurrent dubbele submit: PostgreSQL row-locking laat één caller count=1 // Concurrent dubbele submit: PostgreSQL row-locking laat één caller count=1
// zien, de rest count=0 → disambiguatie hieronder. // zien, de rest count=0 → disambiguatie hieronder.

View file

@ -5,7 +5,11 @@
// detail-layout dus client is simpler (geen rsc-boundary doorbreken). // detail-layout dus client is simpler (geen rsc-boundary doorbreken).
// //
// Iconen + kleur per log-type voor snelle herkenning. // Iconen + kleur per log-type voor snelle herkenning.
// Open questions krijgen een inline answer-form (M12 hotfix — zie
// notifications-bell-pad in M11; voor idee-vragen blijft de bel buiten beeld).
import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { import {
ClipboardList, ClipboardList,
FileText, FileText,
@ -15,6 +19,11 @@ import {
StickyNote, StickyNote,
Wrench, Wrench,
} from 'lucide-react' } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { answerQuestion } from '@/actions/questions'
import type { IdeaLogType } from '@prisma/client' import type { IdeaLogType } from '@prisma/client'
@ -139,6 +148,10 @@ export function IdeaTimeline({ logs, questions }: Props) {
<time>{time}</time> <time>{time}</time>
</div> </div>
<p className="text-sm">{q.question}</p> <p className="text-sm">{q.question}</p>
{q.status === 'open' ? (
<AnswerForm questionId={q.id} options={q.options} />
) : (
<>
{q.options && q.options.length > 0 ? ( {q.options && q.options.length > 0 ? (
<ul className="text-xs text-muted-foreground list-disc list-inside"> <ul className="text-xs text-muted-foreground list-disc list-inside">
{q.options.map((o, ii) => ( {q.options.map((o, ii) => (
@ -154,6 +167,8 @@ export function IdeaTimeline({ logs, questions }: Props) {
{q.answer} {q.answer}
</p> </p>
) : null} ) : null}
</>
)}
</div> </div>
</li> </li>
) )
@ -161,3 +176,91 @@ export function IdeaTimeline({ logs, questions }: Props) {
</ol> </ol>
) )
} }
// ---------------------------------------------------------------------------
// AnswerForm — inline antwoord op een open Claude-vraag.
// Voor multi-choice (options): knoppen die direct submitten met de gekozen
// optie. Anders: textarea + Submit knop.
function AnswerForm({
questionId,
options,
}: {
questionId: string
options: string[] | null
}) {
const router = useRouter()
const [text, setText] = useState('')
const [pending, startTransition] = useTransition()
function submit(answer: string) {
const trimmed = answer.trim()
if (!trimmed) {
toast.error('Antwoord mag niet leeg zijn')
return
}
startTransition(async () => {
const r = await answerQuestion(questionId, trimmed)
if (!r.ok) {
toast.error(r.error)
return
}
toast.success('Antwoord verzonden — agent gaat door.')
setText('')
router.refresh()
})
}
if (options && options.length > 0) {
return (
<div className="flex flex-col gap-1.5 pt-1">
{options.map((opt, i) => (
<Button
key={i}
size="sm"
variant="outline"
className="justify-start text-left h-auto py-2 whitespace-normal"
disabled={pending}
onClick={() => submit(opt)}
>
{opt}
</Button>
))}
<details className="text-xs text-muted-foreground pt-1">
<summary className="cursor-pointer">Of typ een eigen antwoord</summary>
<div className="space-y-2 pt-2">
<Textarea
value={text}
onChange={(e) => setText(e.target.value)}
rows={3}
placeholder="Eigen antwoord…"
disabled={pending}
/>
<div className="flex justify-end">
<Button size="sm" disabled={pending || !text.trim()} onClick={() => submit(text)}>
Verzend
</Button>
</div>
</div>
</details>
</div>
)
}
return (
<div className="space-y-2 pt-1">
<Textarea
value={text}
onChange={(e) => setText(e.target.value)}
rows={3}
placeholder="Antwoord…"
disabled={pending}
/>
<div className="flex justify-end">
<Button size="sm" disabled={pending || !text.trim()} onClick={() => submit(text)}>
Verzend
</Button>
</div>
</div>
)
}

View file

@ -87,20 +87,26 @@ export function AnswerModal({ question, isDemo, onClose }: AnswerModalProps) {
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
<DialogTitle className="text-xl font-semibold">Beantwoord Claude</DialogTitle> <DialogTitle className="text-xl font-semibold">Beantwoord Claude</DialogTitle>
<DialogDescription> <DialogDescription>
<span className="font-mono">{question.story_code ?? 'story'}</span> <span className="font-mono">
{question.kind === 'idea' ? question.idea_code : (question.story_code ?? 'story')}
</span>
{' — '} {' — '}
{question.story_title} {question.kind === 'idea' ? question.idea_title : question.story_title}
</DialogDescription> </DialogDescription>
</div> </div>
</div> </div>
<div className="flex-1 overflow-y-auto px-6 py-6 space-y-6"> <div className="flex-1 overflow-y-auto px-6 py-6 space-y-6">
<Link <Link
href={`/products/${question.product_id}/sprint`} href={
question.kind === 'idea'
? `/ideas/${question.idea_id}?tab=timeline`
: `/products/${question.product_id}/sprint`
}
className="text-primary inline-flex items-center gap-1 self-start text-xs hover:underline" className="text-primary inline-flex items-center gap-1 self-start text-xs hover:underline"
> >
<ExternalLink className="h-3.5 w-3.5" /> <ExternalLink className="h-3.5 w-3.5" />
<span>Open in Sprint</span> <span>{question.kind === 'idea' ? 'Open idee' : 'Open in Sprint'}</span>
</Link> </Link>
<div className="bg-surface-container-low rounded-md border p-3 text-sm whitespace-pre-wrap"> <div className="bg-surface-container-low rounded-md border p-3 text-sm whitespace-pre-wrap">

View file

@ -48,9 +48,10 @@ export async function NotificationsBridge({ userId }: NotificationsBridgeProps)
}, },
}) })
const initial: NotificationQuestion[] = openQuestions.flatMap((q) => { const storyQuestions: NotificationQuestion[] = openQuestions.flatMap((q) => {
if (!q.story || q.story_id === null) return [] if (!q.story || q.story_id === null) return []
return [{ return [{
kind: 'story' as const,
id: q.id, id: q.id,
product_id: q.product_id, product_id: q.product_id,
story_id: q.story_id, story_id: q.story_id,
@ -65,5 +66,45 @@ export async function NotificationsBridge({ userId }: NotificationsBridgeProps)
}] }]
}) })
// M12 hotfix: idea-questions ook in de bel. user_id-only scope (idee is privé).
const ideaOpenQuestions = await prisma.claudeQuestion.findMany({
where: {
status: 'open',
expires_at: { gt: new Date() },
idea: { user_id: userId },
},
orderBy: { created_at: 'desc' },
take: 100,
select: {
id: true,
product_id: true,
idea_id: true,
question: true,
options: true,
created_at: true,
expires_at: true,
idea: { select: { id: true, code: true, title: true } },
},
})
const ideaQuestions: NotificationQuestion[] = ideaOpenQuestions.flatMap((q) => {
if (!q.idea || q.idea_id === null) return []
return [{
kind: 'idea' as const,
id: q.id,
product_id: q.product_id,
idea_id: q.idea_id,
idea_code: q.idea.code,
idea_title: q.idea.title,
question: q.question,
options: Array.isArray(q.options) ? (q.options as string[]) : null,
created_at: q.created_at.toISOString(),
expires_at: q.expires_at.toISOString(),
}]
})
const initial: NotificationQuestion[] = [...storyQuestions, ...ideaQuestions]
.sort((a, b) => (a.created_at < b.created_at ? 1 : -1))
return <NotificationsRealtimeMount initial={initial} /> return <NotificationsRealtimeMount initial={initial} />
} }

View file

@ -54,7 +54,12 @@ export function NotificationsSheet({
) : ( ) : (
<ul className="mt-4 flex flex-col gap-2 px-4 pb-4"> <ul className="mt-4 flex flex-col gap-2 px-4 pb-4">
{questions.map((q) => { {questions.map((q) => {
const forYou = q.assignee_id === currentUserId // story-questions: forYou wanneer assignee = ingelogd; idee-vragen
// zijn altijd "voor jou" (idee is strikt user_id-only).
const forYou =
q.kind === 'idea' || q.assignee_id === currentUserId
const code = q.kind === 'idea' ? q.idea_code : (q.story_code ?? '—')
const title = q.kind === 'idea' ? q.idea_title : q.story_title
return ( return (
<li key={q.id}> <li key={q.id}>
<button <button
@ -67,12 +72,8 @@ export function NotificationsSheet({
)} )}
> >
<div className="flex items-baseline gap-2"> <div className="flex items-baseline gap-2">
<span className="font-mono text-xs opacity-80"> <span className="font-mono text-xs opacity-80">{code}</span>
{q.story_code ?? '—'} <span className="line-clamp-1 text-sm font-medium">{title}</span>
</span>
<span className="line-clamp-1 text-sm font-medium">
{q.story_title}
</span>
</div> </div>
<p <p
className={cn( className={cn(

View file

@ -20,7 +20,10 @@ interface NotificationsBellProps {
export function NotificationsBell({ currentUserId, isDemo }: NotificationsBellProps) { export function NotificationsBell({ currentUserId, isDemo }: NotificationsBellProps) {
const total = useNotificationsStore((s) => s.questions.length) const total = useNotificationsStore((s) => s.questions.length)
const forYou = useNotificationsStore((s) => const forYou = useNotificationsStore((s) =>
s.questions.filter((q) => q.assignee_id === currentUserId).length, s.questions.filter((q) =>
// story-question: assignee match; idea-question: altijd voor jou (privé)
q.kind === 'idea' ? true : q.assignee_id === currentUserId,
).length,
) )
return ( return (

View file

@ -138,6 +138,14 @@ export function useNotificationsRealtime() {
assignee_id: payload.assignee_id, assignee_id: payload.assignee_id,
status: payload.status, status: payload.status,
}) })
// M12 hotfix: óók in notifications-bel. Open → reconnect zodat
// initial-state de full question-detail levert; non-open → remove.
if (payload.status === 'open') {
close()
connect()
} else {
remove(payload.id)
}
return return
} }

View file

@ -12,7 +12,11 @@
import { create } from 'zustand' import { create } from 'zustand'
export interface NotificationQuestion { // Story-questions en idea-questions delen het bel-paneel sinds M12 hotfix.
// `kind` discrimineert; UI rendert label + link op basis daarvan.
export type NotificationQuestion =
| {
kind: 'story'
id: string id: string
product_id: string product_id: string
story_id: string story_id: string
@ -25,6 +29,18 @@ export interface NotificationQuestion {
created_at: string created_at: string
expires_at: string expires_at: string
} }
| {
kind: 'idea'
id: string
product_id: string
idea_id: string
idea_code: string
idea_title: string
question: string
options: string[] | null
created_at: string
expires_at: string
}
interface NotificationsState { interface NotificationsState {
questions: NotificationQuestion[] questions: NotificationQuestion[]
@ -56,6 +72,11 @@ export const useNotificationsStore = create<NotificationsState>((set, get) => ({
forYouCount: (userId) => { forYouCount: (userId) => {
if (!userId) return 0 if (!userId) return 0
return get().questions.filter((q) => q.assignee_id === userId).length return get().questions.filter((q) => {
// story-questions: assignee = jij; idea-questions: altijd voor jou
// (idee is strikt user_id-only en alleen jij ziet 'm).
if (q.kind === 'story') return q.assignee_id === userId
return true
}).length
}, },
})) }))