Skip to content

An AI-powered search engine with a generative UI

feat: add site feedback system with sentiment tracking

Yoshiki Miura53a05f903507
diff --git a/components/feedback-modal.tsx b/components/feedback-modal.tsx
new file mode 100644
index 00000000..d4306874
--- /dev/null
+++ b/components/feedback-modal.tsx
@@ -0,0 +1,142 @@
+'use client'
+
+import { useState, useTransition } from 'react'
+
+import { Frown, Meh, Smile } from 'lucide-react'
+import { toast } from 'sonner'
+
+import { submitFeedback } from '@/lib/actions/site-feedback'
+import { cn } from '@/lib/utils'
+
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle
+} from '@/components/ui/dialog'
+import { Textarea } from '@/components/ui/textarea'
+
+type Sentiment = 'positive' | 'neutral' | 'negative'
+
+interface FeedbackModalProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}
+
+export function FeedbackModal({ open, onOpenChange }: FeedbackModalProps) {
+ const [sentiment, setSentiment] = useState<Sentiment | null>(null)
+ const [message, setMessage] = useState('')
+ const [isPending, startTransition] = useTransition()
+
+ const handleSubmit = () => {
+ if (!sentiment || !message.trim()) {
+ toast.error('Please select your sentiment and write a message')
+ return
+ }
+
+ startTransition(async () => {
+ const result = await submitFeedback({
+ sentiment,
+ message: message.trim(),
+ pageUrl: window.location.href
+ })
+
+ if (result.success) {
+ toast.success('Thank you for your feedback!')
+ // Reset form and close modal
+ setSentiment(null)
+ setMessage('')
+ onOpenChange(false)
+ } else {
+ toast.error('Failed to submit feedback. Please try again later.')
+ }
+ })
+ }
+
+ const handleCancel = () => {
+ setSentiment(null)
+ setMessage('')
+ onOpenChange(false)
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[550px]">
+ <DialogHeader>
+ <DialogTitle>Give feedback</DialogTitle>
+ <DialogDescription>
+ Your feedback helps us improve Morphic. Let us know what you think!
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 mt-4">
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ variant={sentiment === 'positive' ? 'default' : 'outline'}
+ size="icon"
+ onClick={() => setSentiment('positive')}
+ className={cn(
+ 'h-12 w-12',
+ sentiment === 'positive' && 'bg-green-500 hover:bg-green-600'
+ )}
+ >
+ <Smile className="h-6 w-6" />
+ </Button>
+ <Button
+ type="button"
+ variant={sentiment === 'neutral' ? 'default' : 'outline'}
+ size="icon"
+ onClick={() => setSentiment('neutral')}
+ className={cn(
+ 'h-12 w-12',
+ sentiment === 'neutral' && 'bg-yellow-500 hover:bg-yellow-600'
+ )}
+ >
+ <Meh className="h-6 w-6" />
+ </Button>
+ <Button
+ type="button"
+ variant={sentiment === 'negative' ? 'default' : 'outline'}
+ size="icon"
+ onClick={() => setSentiment('negative')}
+ className={cn(
+ 'h-12 w-12',
+ sentiment === 'negative' && 'bg-red-500 hover:bg-red-600'
+ )}
+ >
+ <Frown className="h-6 w-6" />
+ </Button>
+ </div>
+
+ <Textarea
+ placeholder="Your feedback"
+ value={message}
+ onChange={e => setMessage(e.target.value)}
+ className="min-h-[150px] resize-none"
+ />
+
+ <div className="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleCancel}
+ disabled={isPending}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ onClick={handleSubmit}
+ disabled={isPending || !sentiment || !message.trim()}
+ >
+ {isPending ? 'Submitting...' : 'Submit'}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/components/header.tsx b/components/header.tsx
index 4ef7c491..44b62aa7 100644
--- a/components/header.tsx
+++ b/components/header.tsx
@@ -1,7 +1,8 @@
'use client'
// import Link from 'next/link' // No longer needed directly here for Sign In button
-import React from 'react'
+import React, { useState } from 'react'
+import { usePathname } from 'next/navigation'
import { User } from '@supabase/supabase-js'
@@ -9,6 +10,8 @@ import { cn } from '@/lib/utils'
import { useSidebar } from '@/components/ui/sidebar'
+import { Button } from './ui/button'
+import { FeedbackModal } from './feedback-modal'
// import { Button } from './ui/button' // No longer needed directly here for Sign In button
import GuestMenu from './guest-menu' // Import the new GuestMenu component
import UserMenu from './user-menu'
@@ -19,21 +22,40 @@ interface HeaderProps {
export const Header: React.FC<HeaderProps> = ({ user }) => {
const { open } = useSidebar()
+ const pathname = usePathname()
+ const [feedbackOpen, setFeedbackOpen] = useState(false)
+ const isRootPage = pathname === '/'
+
return (
- <header
- className={cn(
- 'absolute top-0 right-0 p-3 flex justify-between items-center z-10 backdrop-blur-sm lg:backdrop-blur-none bg-background/80 lg:bg-transparent transition-[width] duration-200 ease-linear',
- open ? 'md:w-[calc(100%-var(--sidebar-width))]' : 'md:w-full',
- 'w-full'
+ <>
+ <header
+ className={cn(
+ 'absolute top-0 right-0 p-3 flex justify-between items-center z-10 backdrop-blur-sm lg:backdrop-blur-none bg-background/80 lg:bg-transparent transition-[width] duration-200 ease-linear',
+ open ? 'md:w-[calc(100%-var(--sidebar-width))]' : 'md:w-full',
+ 'w-full'
+ )}
+ >
+ {/* This div can be used for a logo or title on the left if needed */}
+ <div></div>
+
+ <div className="flex items-center gap-2">
+ {isRootPage && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setFeedbackOpen(true)}
+ >
+ Feedback
+ </Button>
+ )}
+ {user ? <UserMenu user={user} /> : <GuestMenu />}
+ </div>
+ </header>
+
+ {isRootPage && (
+ <FeedbackModal open={feedbackOpen} onOpenChange={setFeedbackOpen} />
)}
- >
- {/* This div can be used for a logo or title on the left if needed */}
- <div></div>
-
- <div className="flex items-center gap-2">
- {user ? <UserMenu user={user} /> : <GuestMenu />}
- </div>
- </header>
+ </>
)
}
diff --git a/drizzle/0003_heavy_whirlwind.sql b/drizzle/0003_heavy_whirlwind.sql
new file mode 100644
index 00000000..a29b1052
--- /dev/null
+++ b/drizzle/0003_heavy_whirlwind.sql
@@ -0,0 +1,12 @@
+CREATE TABLE "feedback" (
+ "id" varchar(191) PRIMARY KEY NOT NULL,
+ "user_id" varchar(255),
+ "sentiment" varchar(256) NOT NULL,
+ "message" text NOT NULL,
+ "page_url" text NOT NULL,
+ "user_agent" text,
+ "created_at" timestamp DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE INDEX "feedback_user_id_idx" ON "feedback" USING btree ("user_id");--> statement-breakpoint
+CREATE INDEX "feedback_created_at_idx" ON "feedback" USING btree ("created_at");
\ No newline at end of file
diff --git a/drizzle/meta/0003_snapshot.json b/drizzle/meta/0003_snapshot.json
new file mode 100644
index 00000000..e0efb630
--- /dev/null
+++ b/drizzle/meta/0003_snapshot.json
@@ -0,0 +1,570 @@
+{
+ "id": "c9b8dd61-7cb9-4f3b-9e5f-811592e56563",
+ "prevId": "8e9de712-037f-4132-8f06-b3d2f57dd68a",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.chats": {
+ "name": "chats",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.feedback": {
+ "name": "feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sentiment": {
+ "name": "sentiment",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_url": {
+ "name": "page_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feedback_user_id_idx": {
+ "name": "feedback_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_created_at_idx": {
+ "name": "feedback_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "messages_chat_id_idx": {
+ "name": "messages_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_chat_id_created_at_idx": {
+ "name": "messages_chat_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_chat_id_chats_id_fk": {
+ "name": "messages_chat_id_chats_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.parts": {
+ "name": "parts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text_text": {
+ "name": "text_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reasoning_text": {
+ "name": "reasoning_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_media_type": {
+ "name": "file_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_filename": {
+ "name": "file_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_url": {
+ "name": "file_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_source_id": {
+ "name": "source_url_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_url": {
+ "name": "source_url_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_title": {
+ "name": "source_url_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_source_id": {
+ "name": "source_document_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_media_type": {
+ "name": "source_document_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_title": {
+ "name": "source_document_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_filename": {
+ "name": "source_document_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_url": {
+ "name": "source_document_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_snippet": {
+ "name": "source_document_snippet",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_tool_call_id": {
+ "name": "tool_tool_call_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_state": {
+ "name": "tool_state",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_error_text": {
+ "name": "tool_error_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_input": {
+ "name": "tool_search_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_output": {
+ "name": "tool_search_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_input": {
+ "name": "tool_fetch_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_output": {
+ "name": "tool_fetch_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_input": {
+ "name": "tool_question_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_output": {
+ "name": "tool_question_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_input": {
+ "name": "tool_todoWrite_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_output": {
+ "name": "tool_todoWrite_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_input": {
+ "name": "tool_todoRead_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_output": {
+ "name": "tool_todoRead_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_input": {
+ "name": "tool_dynamic_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_output": {
+ "name": "tool_dynamic_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_name": {
+ "name": "tool_dynamic_name",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_type": {
+ "name": "tool_dynamic_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_prefix": {
+ "name": "data_prefix",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_content": {
+ "name": "data_content",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_id": {
+ "name": "data_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_metadata": {
+ "name": "provider_metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "parts_message_id_idx": {
+ "name": "parts_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "parts_message_id_order_idx": {
+ "name": "parts_message_id_order_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "parts_message_id_messages_id_fk": {
+ "name": "parts_message_id_messages_id_fk",
+ "tableFrom": "parts",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "text_text_required": {
+ "name": "text_text_required",
+ "value": "(type != 'text' OR text_text IS NOT NULL)"
+ },
+ "reasoning_text_required": {
+ "name": "reasoning_text_required",
+ "value": "(type != 'reasoning' OR reasoning_text IS NOT NULL)"
+ },
+ "file_fields_required": {
+ "name": "file_fields_required",
+ "value": "(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND file_url IS NOT NULL))"
+ },
+ "tool_state_valid": {
+ "name": "tool_state_valid",
+ "value": "(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))"
+ },
+ "tool_fields_required": {
+ "name": "tool_fields_required",
+ "value": "(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))"
+ }
+ },
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index bec9a626..56e1d742 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -22,6 +22,13 @@
"when": 1754822051273,
"tag": "0002_material_crystal",
"breakpoints": true
+ },
+ {
+ "idx": 3,
+ "version": "7",
+ "when": 1754832999921,
+ "tag": "0003_heavy_whirlwind",
+ "breakpoints": true
}
]
}
diff --git a/lib/actions/site-feedback.ts b/lib/actions/site-feedback.ts
new file mode 100644
index 00000000..10beae72
--- /dev/null
+++ b/lib/actions/site-feedback.ts
@@ -0,0 +1,115 @@
+'use server'
+
+import { db } from '@/lib/db'
+import { feedback } from '@/lib/db/schema'
+import { createClient } from '@/lib/supabase/server'
+
+export async function submitFeedback(data: {
+ sentiment: 'positive' | 'neutral' | 'negative'
+ message: string
+ pageUrl: string
+}) {
+ try {
+ // Get current user if logged in
+ let userId: string | undefined
+ let userEmail: string | undefined
+ const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
+ const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
+
+ if (supabaseUrl && supabaseAnonKey) {
+ const supabase = await createClient()
+ const {
+ data: { user }
+ } = await supabase.auth.getUser()
+ userId = user?.id
+ userEmail = user?.email
+ }
+
+ // Get user agent from headers
+ const { headers } = await import('next/headers')
+ const headersList = await headers()
+ const userAgent = headersList.get('user-agent') || undefined
+
+ // Save to database
+ const [newFeedback] = await db
+ .insert(feedback)
+ .values({
+ userId,
+ sentiment: data.sentiment,
+ message: data.message,
+ pageUrl: data.pageUrl,
+ userAgent
+ })
+ .returning()
+
+ // Send to Slack if webhook URL is configured
+ const slackWebhookUrl = process.env.SLACK_WEBHOOK_URL
+ if (slackWebhookUrl) {
+ try {
+ const sentimentEmoji = {
+ positive: '😊',
+ neutral: '😐',
+ negative: '😞'
+ }[data.sentiment]
+
+ const slackMessage = {
+ text: `New feedback received ${sentimentEmoji}`,
+ blocks: [
+ {
+ type: 'header',
+ text: {
+ type: 'plain_text',
+ text: `New Feedback ${sentimentEmoji}`
+ }
+ },
+ {
+ type: 'section',
+ fields: [
+ {
+ type: 'mrkdwn',
+ text: `*Sentiment:*\n${data.sentiment}`
+ },
+ {
+ type: 'mrkdwn',
+ text: `*From:*\n${userEmail || 'Anonymous'}`
+ }
+ ]
+ },
+ {
+ type: 'section',
+ text: {
+ type: 'mrkdwn',
+ text: `*Message:*\n${data.message}`
+ }
+ },
+ {
+ type: 'context',
+ elements: [
+ {
+ type: 'mrkdwn',
+ text: `Page: ${data.pageUrl} | Time: ${new Date().toISOString()}`
+ }
+ ]
+ }
+ ]
+ }
+
+ await fetch(slackWebhookUrl, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(slackMessage)
+ })
+ } catch (slackError) {
+ // Log Slack error but don't fail the request
+ console.error('Failed to send Slack notification:', slackError)
+ }
+ }
+
+ return { success: true, id: newFeedback.id }
+ } catch (error) {
+ console.error('Failed to save feedback:', error)
+ return { success: false, error: 'Failed to save feedback' }
+ }
+}
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 5ed8f216..06669207 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -189,3 +189,29 @@ export const parts = pgTable(
export type Part = InferSelectModel<typeof parts>
export type NewPart = typeof parts.$inferInsert
+
+// Feedback table
+export const feedback = pgTable(
+ 'feedback',
+ {
+ id: varchar('id', { length: ID_LENGTH })
+ .primaryKey()
+ .$defaultFn(() => generateId()),
+ userId: varchar('user_id', { length: USER_ID_LENGTH }),
+ sentiment: varchar('sentiment', {
+ length: VARCHAR_LENGTH,
+ enum: ['positive', 'neutral', 'negative']
+ }).notNull(),
+ message: text('message').notNull(),
+ pageUrl: text('page_url').notNull(),
+ userAgent: text('user_agent'),
+ createdAt: timestamp('created_at').notNull().defaultNow()
+ },
+ table => ({
+ userIdIdx: index('feedback_user_id_idx').on(table.userId),
+ createdAtIdx: index('feedback_created_at_idx').on(table.createdAt),
+ enableRls: true
+ })
+)
+
+export type Feedback = InferSelectModel<typeof feedback>