From 03951531b69eaa85c185a9664e3d5dbc73a4977d Mon Sep 17 00:00:00 2001 From: yoen-velt Date: Fri, 19 Dec 2025 15:37:42 -0500 Subject: [PATCH 1/2] Postgres Self-hosting Dashboard Demo --- .../dashboard-postgres-demo/.gitignore | 35 +++ .../app/api/velt/comments/delete/route.ts | 20 ++ .../app/api/velt/comments/get/route.ts | 22 ++ .../app/api/velt/comments/save/route.ts | 23 ++ .../app/api/velt/comments/store.ts | 179 ++++++++++++ .../app/api/velt/token/route.ts | 40 +++ .../app/document/DocumentContext.tsx | 77 +++++ .../app/document/useCurrentDocument.ts | 4 + .../dashboard-postgres-demo/app/layout.tsx | 22 ++ .../dashboard-postgres-demo/app/page.tsx | 30 ++ .../app/userAuth/AppProviders.tsx | 15 + .../app/userAuth/AppUserContext.tsx | 182 ++++++++++++ .../app/userAuth/useAppUser.ts | 3 + .../dashboard-postgres-demo/components.json | 17 ++ .../components/document/ActionModal.tsx | 221 +++++++++++++++ .../components/document/Avatar.tsx | 20 ++ .../components/document/CommentsSidebar.tsx | 40 +++ .../components/document/DueBadge.tsx | 31 +++ .../components/document/JobDetailModal.tsx | 252 +++++++++++++++++ .../components/document/JobsTable.tsx | 118 ++++++++ .../components/document/Pagination.tsx | 43 +++ .../components/document/StatusBadge.tsx | 49 ++++ .../components/document/SummaryCards.tsx | 34 +++ .../components/document/document-canvas.tsx | 114 ++++++++ .../components/document/icons.tsx | 107 +++++++ .../components/document/jobs-data.ts | 252 +++++++++++++++++ .../components/document/types.ts | 22 ++ .../components/header/header.tsx | 14 + .../components/sidebar/sidebar.tsx | 202 ++++++++++++++ .../components/velt/VeltCollaboration.tsx | 41 +++ .../velt/VeltCommentDataProvider.ts | 101 +++++++ .../velt/VeltInitializeDocument.tsx | 22 ++ .../components/velt/VeltInitializeUser.tsx | 54 ++++ .../components/velt/VeltTools.tsx | 18 ++ .../ui-customization/VeltCommentBubbleWf.tsx | 21 ++ .../ui-customization/VeltCommentToolWf.tsx | 18 ++ .../VeltCommentsSidebarHeaderWf.tsx | 22 ++ .../ui-customization/VeltCustomization.tsx | 21 ++ .../VeltNotificationsToolWf.tsx | 31 +++ .../ui-customization/VeltSidebarButtonWf.tsx | 16 ++ .../velt/ui-customization/styles.css | 70 +++++ .../dashboard-postgres-demo/hooks/.gitkeep | 0 .../dashboard-postgres-demo/lib/utils.ts | 6 + .../dashboard-postgres-demo/next.config.js | 4 + .../dashboard-postgres-demo/package.json | 33 +++ .../dashboard-postgres-demo/postcss.config.js | 6 + .../dashboard-postgres-demo/public/.gitkeep | 0 .../public/icons/bell-icon.svg | 5 + .../public/icons/inbox-icon.svg | 3 + .../public/icons/sidebar/accounts-payable.svg | 3 + .../public/icons/sidebar/activity.svg | 3 + .../public/icons/sidebar/all.svg | 3 + .../public/icons/sidebar/automation.svg | 3 + .../public/icons/sidebar/basic-expense.svg | 3 + .../public/icons/sidebar/copy.svg | 3 + .../public/icons/sidebar/divider.svg | 3 + .../public/icons/sidebar/documents.svg | 3 + .../public/icons/sidebar/folder.svg | 3 + .../public/icons/sidebar/help.svg | 3 + .../public/icons/sidebar/home.svg | 3 + .../public/icons/sidebar/inbox.svg | 3 + .../public/icons/sidebar/invoice-match.svg | 3 + .../public/icons/sidebar/notifications.svg | 3 + .../public/icons/sidebar/open-envoy-logo.svg | 21 ++ .../public/icons/sidebar/search.svg | 3 + .../public/icons/sidebar/settings.svg | 3 + .../styles/globals.css | 262 ++++++++++++++++++ .../tailwind.config.js | 54 ++++ .../dashboard-postgres-demo/tsconfig.json | 40 +++ pnpm-lock.yaml | 174 ++++++++++++ 70 files changed, 3279 insertions(+) create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/.gitignore create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/delete/route.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/get/route.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/save/route.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/store.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/token/route.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/document/DocumentContext.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/document/useCurrentDocument.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/layout.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/page.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/AppProviders.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/AppUserContext.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/useAppUser.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components.json create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/ActionModal.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/Avatar.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/CommentsSidebar.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/DueBadge.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/JobDetailModal.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/JobsTable.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/Pagination.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/StatusBadge.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/SummaryCards.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/document-canvas.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/icons.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/jobs-data.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/types.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/header/header.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/sidebar/sidebar.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/VeltCollaboration.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/VeltCommentDataProvider.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/VeltInitializeDocument.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/VeltInitializeUser.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/VeltTools.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/ui-customization/VeltCommentBubbleWf.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/ui-customization/VeltCommentToolWf.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/ui-customization/VeltCommentsSidebarHeaderWf.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/ui-customization/VeltCustomization.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/ui-customization/VeltNotificationsToolWf.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/ui-customization/VeltSidebarButtonWf.tsx create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/velt/ui-customization/styles.css create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/hooks/.gitkeep create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/lib/utils.ts create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/next.config.js create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/package.json create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/postcss.config.js create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/.gitkeep create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/bell-icon.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/inbox-icon.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/accounts-payable.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/activity.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/all.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/automation.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/basic-expense.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/copy.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/divider.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/documents.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/folder.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/help.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/home.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/inbox.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/invoice-match.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/notifications.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/open-envoy-logo.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/search.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/public/icons/sidebar/settings.svg create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/styles/globals.css create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/tailwind.config.js create mode 100644 apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/tsconfig.json diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/.gitignore b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/.gitignore new file mode 100644 index 00000000..8f322f0d --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/.gitignore @@ -0,0 +1,35 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/delete/route.ts b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/delete/route.ts new file mode 100644 index 00000000..17844060 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/delete/route.ts @@ -0,0 +1,20 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { deleteComment } from '../store'; + +export async function POST(request: NextRequest) { + try { + const body = await request.json(); + const { commentAnnotationId } = body; + + console.log('[Velt API] DELETE comment:', commentAnnotationId); + + if (commentAnnotationId) { + await deleteComment(commentAnnotationId); + } + + return NextResponse.json({ success: true }); + } catch (error) { + console.error('[Velt API] Error deleting comment:', error); + return NextResponse.json({ success: false, error: 'Failed to delete' }, { status: 500 }); + } +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/get/route.ts b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/get/route.ts new file mode 100644 index 00000000..aa7a2427 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/get/route.ts @@ -0,0 +1,22 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { getComments } from '../store'; + +export async function POST(request: NextRequest) { + try { + const body = await request.json(); + const { organizationId, commentAnnotationIds, documentIds } = body; + + console.log('[Velt API] GET comments:', { organizationId, commentAnnotationIds, documentIds }); + + const result = await getComments({ + organizationId, + commentAnnotationIds, + documentIds, + }); + + return NextResponse.json({ result, success: true }); + } catch (error) { + console.error('[Velt API] Error getting comments:', error); + return NextResponse.json({ result: {}, success: true }, { status: 200 }); + } +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/save/route.ts b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/save/route.ts new file mode 100644 index 00000000..7f4b665d --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/save/route.ts @@ -0,0 +1,23 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { saveComments } from '../store'; + +export async function POST(request: NextRequest) { + try { + const body = await request.json(); + const { commentAnnotation, metadata } = body; + + console.log('[Velt API] SAVE comments:', { commentAnnotation, metadata }); + + if (commentAnnotation) { + // Extract documentId and organizationId from metadata + const documentId = metadata?.documentId; + const organizationId = metadata?.organizationId; + await saveComments(commentAnnotation, { documentId, organizationId }); + } + + return NextResponse.json({ success: true }); + } catch (error) { + console.error('[Velt API] Error saving comments:', error); + return NextResponse.json({ success: false, error: 'Failed to save' }, { status: 500 }); + } +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/store.ts b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/store.ts new file mode 100644 index 00000000..277ffab9 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/store.ts @@ -0,0 +1,179 @@ +// PostgreSQL store for Velt comments +// Docs: https://docs.velt.dev/self-host-data/comments + +import { Pool } from 'pg'; + +export type CommentAnnotation = { + annotationId: string; + documentId?: string; + organizationId?: string; + metadata?: unknown; + comments: Record; +}; + +// PostgreSQL connection string +const DATABASE_URL = process.env.DATABASE_URL; + +if (!DATABASE_URL && process.env.NODE_ENV === 'production') { + console.warn('[PostgreSQL] WARNING: DATABASE_URL not set. Database operations will fail.'); +} + +const TABLE_NAME = 'comment_annotations'; + +// Create a connection pool for serverless environments +let pool: Pool | null = null; +let initPromise: Promise | null = null; + +function getPool(): Pool { + if (!pool) { + pool = new Pool({ + connectionString: DATABASE_URL, + ssl: DATABASE_URL?.includes('sslmode=require') ? { rejectUnauthorized: false } : false, + max: 10, + idleTimeoutMillis: 30000, + connectionTimeoutMillis: 10000, + }); + } + return pool; +} + +async function ensureInitialized(): Promise { + if (!initPromise) { + initPromise = initializeTable(); + } + return initPromise; +} + +async function initializeTable(): Promise { + const client = await getPool().connect(); + try { + await client.query(` + CREATE TABLE IF NOT EXISTS ${TABLE_NAME} ( + annotation_id TEXT PRIMARY KEY, + document_id TEXT, + organization_id TEXT, + data JSONB NOT NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() + ) + `); + + // Create indexes for faster queries + await client.query(` + CREATE INDEX IF NOT EXISTS idx_${TABLE_NAME}_document_id ON ${TABLE_NAME}(document_id) + `); + await client.query(` + CREATE INDEX IF NOT EXISTS idx_${TABLE_NAME}_organization_id ON ${TABLE_NAME}(organization_id) + `); + + console.log('[PostgreSQL] Table initialized:', TABLE_NAME); + } finally { + client.release(); + } +} + +export async function getComments(filters: { + organizationId?: string; + commentAnnotationIds?: string[]; + documentIds?: string[]; +}): Promise> { + await ensureInitialized(); + const client = await getPool().connect(); + try { + const conditions: string[] = []; + const values: unknown[] = []; + let paramIndex = 1; + + if (filters.commentAnnotationIds?.length) { + conditions.push(`annotation_id = ANY($${paramIndex})`); + values.push(filters.commentAnnotationIds); + paramIndex++; + } + if (filters.documentIds?.length) { + conditions.push(`document_id = ANY($${paramIndex})`); + values.push(filters.documentIds); + paramIndex++; + } + if (filters.organizationId) { + conditions.push(`organization_id = $${paramIndex}`); + values.push(filters.organizationId); + paramIndex++; + } + + const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''; + const query = `SELECT annotation_id, data FROM ${TABLE_NAME} ${whereClause}`; + + const result = await client.query(query, values); + + // Convert to Record format expected by Velt + const annotations: Record = {}; + for (const row of result.rows) { + const annotation = row.data as CommentAnnotation; + annotations[row.annotation_id] = annotation; + } + + return annotations; + } finally { + client.release(); + } +} + +export async function saveComments( + annotations: Record, + context?: { documentId?: string; organizationId?: string } +): Promise { + if (Object.keys(annotations).length === 0) return; + + await ensureInitialized(); + const client = await getPool().connect(); + try { + // Use a transaction for batch upserts + await client.query('BEGIN'); + + for (const [id, annotation] of Object.entries(annotations)) { + const documentId = context?.documentId || annotation.documentId || null; + const organizationId = context?.organizationId || annotation.organizationId || null; + + // Store the full annotation with annotationId included + const data = { + ...annotation, + annotationId: id, + documentId, + organizationId, + }; + + await client.query( + `INSERT INTO ${TABLE_NAME} (annotation_id, document_id, organization_id, data, updated_at) + VALUES ($1, $2, $3, $4, NOW()) + ON CONFLICT (annotation_id) + DO UPDATE SET + document_id = EXCLUDED.document_id, + organization_id = EXCLUDED.organization_id, + data = EXCLUDED.data, + updated_at = NOW()`, + [id, documentId, organizationId, JSON.stringify(data)] + ); + } + + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } +} + +export async function deleteComment(annotationId: string): Promise { + await ensureInitialized(); + const client = await getPool().connect(); + try { + const result = await client.query( + `DELETE FROM ${TABLE_NAME} WHERE annotation_id = $1`, + [annotationId] + ); + return (result.rowCount ?? 0) > 0; + } finally { + client.release(); + } +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/token/route.ts b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/token/route.ts new file mode 100644 index 00000000..e409e0a0 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/token/route.ts @@ -0,0 +1,40 @@ +import { NextRequest, NextResponse } from 'next/server'; + +// [Velt] API key and auth token from environment variables +const NEXT_PUBLIC_VELT_API_KEY = "6xTcUFtlYAlCdh11zrKB"; +const VELT_AUTH_TOKEN = "bd4d5226050470b6c658054fcdf1092a"; + +export async function POST(req: NextRequest) { + try { + const { userId, organizationId, email, isAdmin } = await req.json(); + if (!userId || !organizationId) { + return NextResponse.json({ error: 'Missing userId or organizationId' }, { status: 400 }); + } + if (!VELT_AUTH_TOKEN) { + return NextResponse.json({ error: 'Server configuration error: missing VELT_AUTH_TOKEN' }, { status: 500 }); + } + const body = { + data: { + userId, + userProperties: { + organizationId, + ...(typeof isAdmin === 'boolean' ? { isAdmin } : {}), + ...(email ? { email } : {}), + }, + }, + }; + const res = await fetch('https://api.velt.dev/v2/auth/token/get', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-velt-api-key': NEXT_PUBLIC_VELT_API_KEY, 'x-velt-auth-token': VELT_AUTH_TOKEN }, + body: JSON.stringify(body), + }); + const json = await res.json(); + const token = json?.result?.data?.token; + if (!res.ok || !token) { + return NextResponse.json({ error: json?.error?.message || 'Failed to generate token' }, { status: 500 }); + } + return NextResponse.json({ token }); + } catch { + return NextResponse.json({ error: 'Internal error' }, { status: 500 }); + } +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/document/DocumentContext.tsx b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/document/DocumentContext.tsx new file mode 100644 index 00000000..38ccffe0 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/document/DocumentContext.tsx @@ -0,0 +1,77 @@ +'use client'; +import { useMemo, useEffect, useState, useRef } from 'react'; + +/** + * ⚠️ IMPORTANT DISCLAIMER FOR DEVELOPERS ⚠️ + * + * This documentId logic using URL parameters is ONLY for demo sharing purposes. + * It allows users to share a link to a specific document in this demo app. + * + * IN YOUR REAL APPLICATION: + * - Use your own document ID system (e.g., from your database, CMS, or file system) + * - You do NOT need to use URLs as document IDs + * - You do NOT need to store document IDs in localStorage or URL params + * - Simply pass your existing document identifier to Velt + * + * Examples of real-world document IDs: + * - Database record ID: "user-doc-12345" + * - File path: "/projects/my-project/document.txt" + * - UUID: "550e8400-e29b-41d4-a716-446655440000" + * - Any unique identifier from your system + * + * The URL-based approach here is purely for convenience in this demo environment + * to enable sharing and collaboration testing. Do not feel obligated to replicate + * this pattern in your production application. + */ + +// [Velt] Minimal hard-coded current document hook +export type CurrentDocument = { + documentId: string | null; + documentName: string; +}; + +export function useCurrentDocument(): CurrentDocument { + const [documentId, setDocumentId] = useState(null); + const isInitialized = useRef(false); + + useEffect(() => { + // Prevent double initialization (React Strict Mode, HMR, etc.) + if (isInitialized.current) return; + + // 1. Check URL for documentId parameter first + const urlParams = new URLSearchParams(window.location.search); + let docId = urlParams.get('documentId'); + + if (docId) { + // Use document ID from URL (shareable link) + setDocumentId(docId); + localStorage.setItem('velt-demo-document-id', docId); + } else { + // 2. Check localStorage for existing document + const stored = localStorage.getItem('velt-inline-comments-demo-doc-id'); + if (stored) { + docId = stored; + } else { + // 3. Generate new document ID + docId = `doc-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`; + localStorage.setItem('velt-inline-comments-demo-doc-id', docId); + } + + // Update URL with document ID for shareability + const newUrl = `${window.location.pathname}?documentId=${docId}`; + window.history.pushState({}, '', newUrl); + + setDocumentId(docId); + } + + isInitialized.current = true; + }, []); + + return useMemo( + () => ({ + documentId: documentId, + documentName: "My Document", + }), + [documentId] + ); +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/document/useCurrentDocument.ts b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/document/useCurrentDocument.ts new file mode 100644 index 00000000..b36de938 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/document/useCurrentDocument.ts @@ -0,0 +1,4 @@ +'use client'; + +export { useCurrentDocument } from './DocumentContext'; +export type { CurrentDocument } from './DocumentContext'; diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/layout.tsx b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/layout.tsx new file mode 100644 index 00000000..8f5ea9fe --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/layout.tsx @@ -0,0 +1,22 @@ +import type { Metadata } from 'next' +import '../styles/globals.css' +import { AppProviders } from "@/app/userAuth/AppProviders" + +export const metadata: Metadata = { + title: 'Dashboard Inline Demo', + description: 'inline-comments demo for comments', +} + +export default function RootLayout({ + children, +}: { + children: React.ReactNode +}) { + return ( + + + {children} + + + ) +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/page.tsx b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/page.tsx new file mode 100644 index 00000000..7c10df8e --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/page.tsx @@ -0,0 +1,30 @@ +"use client"; +// [Velt] Provider + collaboration +import { VeltProvider } from "@veltdev/react"; +import { useVeltAuthProvider } from "@/components/velt/VeltInitializeUser"; +import { VeltCollaboration } from "@/components/velt/VeltCollaboration"; +import DocumentCanvas from '@/components/document/document-canvas' +import { commentDataProvider } from "@/components/velt/VeltCommentDataProvider"; + +// [Velt] Replace with your own API key from https://console.velt.dev +const NEXT_PUBLIC_VELT_API_KEY = "6xTcUFtlYAlCdh11zrKB"; + +// [Velt] Self-hosting: set to true to enable self-hosted comment storage +const SELF_HOSTING_ENABLED = true; + +export default function Home() { + // [Velt] Auth provider (reads from app/userAuth/useAppUser) + const { authProvider } = useVeltAuthProvider(); + + return ( + // [Velt] Wrap app with VeltProvider + + + + + ); +} \ No newline at end of file diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/AppProviders.tsx b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/AppProviders.tsx new file mode 100644 index 00000000..a17dc9e8 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/AppProviders.tsx @@ -0,0 +1,15 @@ +"use client"; + +import React from "react"; +import { AppUserProvider } from "./AppUserContext"; + +/** + * Client component wrapper for AppUserProvider + */ +export function AppProviders({ children }: { children: React.ReactNode }) { + return ( + + {children} + + ); +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/AppUserContext.tsx b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/AppUserContext.tsx new file mode 100644 index 00000000..6f157cc7 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/AppUserContext.tsx @@ -0,0 +1,182 @@ +"use client"; + +import type { User } from "@veltdev/types"; +import React, { useCallback, useContext, useEffect, useState } from "react"; + +/** + * ⚠️ IMPORTANT DISCLAIMER FOR DEVELOPERS ⚠️ + * + * This user authentication logic is ONLY for demo purposes. + * It generates random users and stores them in localStorage/sessionStorage to simulate + * a multi-user collaboration environment for demonstration. + * + * IN YOUR REAL APPLICATION: + * - Fetch the currently logged in user from YOUR existing authentication system + * - Use your own user management (Auth0, Firebase Auth, custom backend, etc.) + * - Simply pass your authenticated user object to Velt's identify() method + * - You do NOT need to generate random users or store users in localStorage + * + * Example of real-world usage: + * ```typescript + * // Get your authenticated user from your auth system + * const currentUser = await yourAuthSystem.getCurrentUser(); + * + * // Pass it to Velt via authProvider (see VeltInitializeUser.tsx for full implementation) + * const authProvider: VeltAuthProvider = { user: currentUser, generateToken: ... }; + * ``` + * + * The random user generation and storage logic here is purely for demo convenience + * to simulate multiple users without requiring actual authentication infrastructure. + * Do not replicate this pattern in your production application. + */ + +type AppUserContextValue = { + user: User | undefined; + login: (u: User) => void; + logout: () => void; + isUserLoggedIn?: boolean; +}; + +const AppUserContext = React.createContext( + undefined +); + +// Simple hash function to convert userId to a consistent number +function hashStringToIndex(str: string, arrayLength: number): number { + let hash = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = ((hash << 5) - hash) + char; + hash = hash & hash; // Convert to 32-bit integer + } + return Math.abs(hash) % arrayLength; +} + +// Generate a deterministic hash from a string (for userId generation) +function hashString(str: string): string { + let hash = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = ((hash << 5) - hash) + char; + hash = hash & hash; // Convert to 32-bit integer + } + // Convert to base36 and pad to ensure consistent length + return Math.abs(hash).toString(36).padStart(8, '0'); +} + +// Generate a random user with deterministic ID based on name +function generateRandomUser(): User { + const avatarColors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E2']; + + const firstNames = ['Alex', 'Sam', 'Jordan', 'Taylor', 'Casey', 'Morgan', 'Riley', 'Avery']; + const lastNames = ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis']; + + // Randomly select first and last name + const firstName = firstNames[Math.floor(Math.random() * firstNames.length)]; + const lastName = lastNames[Math.floor(Math.random() * lastNames.length)]; + const fullName = `${firstName} ${lastName}`; + + // Generate deterministic userId from the full name + // This ensures "Alex Smith" always gets the same ID + const userId = `user-${hashString(fullName)}`; + + // Use deterministic color based on userId for consistent photoUrl + const colorIndex = hashStringToIndex(userId, avatarColors.length); + const avatarColor = avatarColors[colorIndex]; + + return { + userId: userId, + name: fullName, + email: `${firstName.toLowerCase()}.${lastName.toLowerCase()}@example.com`, + organizationId: "sample-apps-demo-org", + photoUrl: `https://ui-avatars.com/api/?name=${encodeURIComponent(fullName)}&background=${avatarColor.substring(1)}&color=fff&size=128`, + }; +} + +export function AppUserProvider({ + children +}: { + children: React.ReactNode; +}) { + const [user, setUser] = useState(undefined); + const [isUserLoggedIn, setIsUserLoggedIn] = useState( + undefined + ); + + useEffect(() => { + if (typeof window === 'undefined') return; // Guard against SSR + + try { + // Detect if running in iframe (for master-sample-app dual view) + const isInIframe = window.self !== window.top; + + // Choose storage based on iframe context: + // - In iframe: use sessionStorage (each origin/port is isolated automatically) + // - Not in iframe: use localStorage (same user across tabs) + const storage = isInIframe ? sessionStorage : localStorage; + const STORAGE_KEY = 'velt-demo-user'; + + // Check storage for existing user + const stored = storage.getItem(STORAGE_KEY); + + let selectedUser: User; + if (stored) { + // Use existing user from storage + selectedUser = JSON.parse(stored); + } else { + // Generate NEW random user + selectedUser = generateRandomUser(); + storage.setItem(STORAGE_KEY, JSON.stringify(selectedUser)); + } + + setUser(selectedUser); + setIsUserLoggedIn(true); + } catch {} + }, []); + + const login = useCallback((next: User) => { + if (typeof window === 'undefined') return; + + try { + const isInIframe = window.self !== window.top; + const storage = isInIframe ? sessionStorage : localStorage; + const STORAGE_KEY = 'velt-demo-user'; + + setUser(next); + setIsUserLoggedIn(true); + storage.setItem(STORAGE_KEY, JSON.stringify(next)); + } catch {} + }, []); + + const logout = useCallback(() => { + if (typeof window === 'undefined') return; + + try { + const isInIframe = window.self !== window.top; + const storage = isInIframe ? sessionStorage : localStorage; + const STORAGE_KEY = 'velt-demo-user'; + + setUser(undefined); + setIsUserLoggedIn(false); + storage.removeItem(STORAGE_KEY); + } catch {} + }, []); + + // Memoize the context value to prevent unnecessary re-renders + const contextValue = React.useMemo( + () => ({ user, login, logout, isUserLoggedIn }), + [user, login, logout, isUserLoggedIn] + ); + + return ( + + {children} + + ); +} + +export function useAppUser() { + const ctx = useContext(AppUserContext); + if (!ctx) throw new Error("useAppUser must be used within AppUserProvider"); + return ctx; +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/useAppUser.ts b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/useAppUser.ts new file mode 100644 index 00000000..aa7ef0aa --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/userAuth/useAppUser.ts @@ -0,0 +1,3 @@ +'use client'; + +export { AppUserProvider, useAppUser } from './AppUserContext'; diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components.json b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components.json new file mode 100644 index 00000000..0ad98211 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "default", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "tailwind.config.js", + "css": "styles/globals.css", + "baseColor": "slate", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils" + } +} diff --git a/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/ActionModal.tsx b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/ActionModal.tsx new file mode 100644 index 00000000..4aba55b5 --- /dev/null +++ b/apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/components/document/ActionModal.tsx @@ -0,0 +1,221 @@ +'use client' + +import { useState } from 'react' + +interface ActionModalProps { + jobId: string + actionType: string + actionLabel: string + onClose: () => void + onSubmit: () => void +} + +const CloseIcon = () => ( + + + +) + +const CheckIcon = () => ( + + + +) + +export default function ActionModal({ jobId, actionType, actionLabel, onClose, onSubmit }: ActionModalProps) { + const [comment, setComment] = useState('') + const [isSubmitting, setIsSubmitting] = useState(false) + const [showSuccess, setShowSuccess] = useState(false) + + const actionTargetId = `action-${jobId}-${actionType}` + + // Get action-specific styling and messaging + const getActionConfig = () => { + switch (actionType) { + case 'approve': + return { + title: `Approve Job ${jobId}`, + description: 'Add an optional comment explaining your approval decision.', + buttonText: 'Approve', + buttonClass: 'bg-green-600 hover:bg-green-700 text-white', + iconColor: 'text-green-600', + } + case 'reject': + return { + title: `Reject Job ${jobId}`, + description: 'Please provide a reason for rejecting this job.', + buttonText: 'Reject', + buttonClass: 'bg-red-600 hover:bg-red-700 text-white', + iconColor: 'text-red-600', + required: true, + } + case 'dispute': + return { + title: `Resolve Dispute - Job ${jobId}`, + description: 'Add details about how this dispute was resolved.', + buttonText: 'Resolve Dispute', + buttonClass: 'bg-blue-600 hover:bg-blue-700 text-white', + iconColor: 'text-blue-600', + required: true, + } + case 'shortpay': + return { + title: `Short Pay - Job ${jobId}`, + description: 'Explain the reason for short payment and the adjusted amount.', + buttonText: 'Submit Short Pay', + buttonClass: 'bg-amber-600 hover:bg-amber-700 text-white', + iconColor: 'text-amber-600', + required: true, + } + case 'resolve': + return { + title: `Resolve Conflict - Job ${jobId}`, + description: 'Document how this conflict was resolved.', + buttonText: 'Resolve Conflict', + buttonClass: 'bg-blue-600 hover:bg-blue-700 text-white', + iconColor: 'text-blue-600', + required: true, + } + case 'submit': + return { + title: `Submit for Approval - Job ${jobId}`, + description: 'Add any notes for the approver.', + buttonText: 'Submit', + buttonClass: 'bg-blue-600 hover:bg-blue-700 text-white', + iconColor: 'text-blue-600', + } + default: + return { + title: `${actionLabel} - Job ${jobId}`, + description: 'Add a comment for this action.', + buttonText: actionLabel, + buttonClass: 'bg-blue-600 hover:bg-blue-700 text-white', + iconColor: 'text-blue-600', + } + } + } + + const config = getActionConfig() + + const handleSubmit = async () => { + if (config.required && !comment.trim()) { + return // Don't submit if comment is required but empty + } + + setIsSubmitting(true) + + // Simulate API call + await new Promise(resolve => setTimeout(resolve, 500)) + + setIsSubmitting(false) + setShowSuccess(true) + + // Show success for a moment then close + setTimeout(() => { + onSubmit() + }, 1500) + } + + if (showSuccess) { + return ( + <> +
+
+
+
+ +
+

+ {actionLabel} Complete +

+

+ {comment.trim() + ? 'Your comment has been added to this job.' + : 'Action completed successfully.'} +

+
+
+ + ) + } + + return ( + <> + {/* Backdrop */} +
+ + {/* Modal */} +
+
e.stopPropagation()}> + {/* Header */} +
+

{config.title}

+ +
+ + {/* Content */} +
+

{config.description}

+ + {/* Comment input - action comments are stored but not deletable */} +
+ +
+