Scrum4Me/components/ideas/idea-timeline.tsx
Madhura68 9e8f33b96e 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>
2026-05-05 13:05:39 +02:00

266 lines
8.4 KiB
TypeScript

'use client'
// IdeaTimeline — chronologische merge van IdeaLog + ClaudeQuestion entries.
// Server-component zou ook kunnen, maar we mounten dit binnen de client-side
// detail-layout dus client is simpler (geen rsc-boundary doorbreken).
//
// 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 {
ClipboardList,
FileText,
HelpCircle,
Lightbulb,
RefreshCw,
StickyNote,
Wrench,
} 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'
export interface TimelineLog {
id: string
type: string
content: string
metadata: unknown
created_at: string
}
export interface TimelineQuestion {
id: string
question: string
options: string[] | null
status: 'open' | 'answered' | 'cancelled' | 'expired'
answer: string | null
created_at: string
expires_at: string
}
interface Props {
logs: TimelineLog[]
questions: TimelineQuestion[]
}
const LOG_ICON: Record<IdeaLogType, React.ReactNode> = {
DECISION: <Lightbulb className="size-4" />,
NOTE: <StickyNote className="size-4" />,
GRILL_RESULT: <FileText className="size-4" />,
PLAN_RESULT: <ClipboardList className="size-4" />,
STATUS_CHANGE: <RefreshCw className="size-4" />,
JOB_EVENT: <Wrench className="size-4" />,
}
const LOG_LABEL: Record<IdeaLogType, string> = {
DECISION: 'Beslissing',
NOTE: 'Notitie',
GRILL_RESULT: 'Grill-resultaat',
PLAN_RESULT: 'Plan-resultaat',
STATUS_CHANGE: 'Status',
JOB_EVENT: 'Job-event',
}
const QUESTION_STATUS_LABEL: Record<TimelineQuestion['status'], string> = {
open: 'Open',
answered: 'Beantwoord',
cancelled: 'Geannuleerd',
expired: 'Verlopen',
}
export function IdeaTimeline({ logs, questions }: Props) {
const merged = [
...logs.map((l) => ({
kind: 'log' as const,
created_at: l.created_at,
data: l,
})),
...questions.map((q) => ({
kind: 'question' as const,
created_at: q.created_at,
data: q,
})),
].sort((a, b) => (a.created_at < b.created_at ? 1 : -1))
if (merged.length === 0) {
return (
<p className="text-sm text-muted-foreground py-8 text-center italic">
Nog geen activiteit op dit idee.
</p>
)
}
return (
<ol className="border-l-2 border-input pl-4 space-y-3 ml-2">
{merged.map((entry, i) => {
const time = new Date(entry.created_at).toLocaleString()
if (entry.kind === 'log') {
const type = entry.data.type as IdeaLogType
return (
<li key={`l-${entry.data.id}`} className="relative">
<span className="absolute -left-[26px] top-1 flex size-5 items-center justify-center rounded-full bg-surface-container text-muted-foreground">
{LOG_ICON[type] ?? <StickyNote className="size-4" />}
</span>
<div className="rounded-md border border-input bg-surface-container p-3 space-y-1">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="font-medium uppercase tracking-wide">
{LOG_LABEL[type] ?? type}
</span>
<span>·</span>
<time>{time}</time>
</div>
<p className="text-sm whitespace-pre-wrap">{entry.data.content}</p>
{entry.data.metadata != null &&
typeof entry.data.metadata === 'object' &&
Object.keys(entry.data.metadata as object).length > 0 ? (
<details className="text-xs text-muted-foreground">
<summary className="cursor-pointer">metadata</summary>
<pre className="mt-1 whitespace-pre-wrap font-mono text-[10px]">
{JSON.stringify(entry.data.metadata, null, 2)}
</pre>
</details>
) : null}
</div>
</li>
)
}
const q = entry.data
return (
<li key={`q-${q.id}-${i}`} className="relative">
<span className="absolute -left-[26px] top-1 flex size-5 items-center justify-center rounded-full bg-surface-container text-status-review">
<HelpCircle className="size-4" />
</span>
<div className="rounded-md border border-input bg-surface-container p-3 space-y-2">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="font-medium uppercase tracking-wide">Vraag</span>
<span>·</span>
<span>{QUESTION_STATUS_LABEL[q.status]}</span>
<span>·</span>
<time>{time}</time>
</div>
<p className="text-sm">{q.question}</p>
{q.status === 'open' ? (
<AnswerForm questionId={q.id} options={q.options} />
) : (
<>
{q.options && q.options.length > 0 ? (
<ul className="text-xs text-muted-foreground list-disc list-inside">
{q.options.map((o, ii) => (
<li key={ii}>{o}</li>
))}
</ul>
) : null}
{q.answer ? (
<p className="text-sm border-l-2 border-primary pl-2 text-foreground">
<span className="text-xs font-medium uppercase tracking-wide text-primary mr-2">
Antwoord
</span>
{q.answer}
</p>
) : null}
</>
)}
</div>
</li>
)
})}
</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>
)
}