AI Newsletter Digest improvements: fixed QP soft line break decoding, URL extraction, and content cleaning

This commit is contained in:
Krilly
2026-03-04 13:29:22 +00:00
parent 29a98137a7
commit 57dd294675
13706 changed files with 2114953 additions and 237629 deletions

View File

@@ -0,0 +1,101 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db/prisma'
import { getCurrentUser } from '@/lib/auth'
import { canAccessWorkspace } from '@/lib/db/workspace-access'
import { format, addDays } from 'date-fns'
// GET /api/workspaces/[id]/calendar-feed
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const workspaceId = params.id
const token = request.nextUrl.searchParams.get('token')
if (!token) {
return NextResponse.json({ error: 'Missing token' }, { status: 401 })
}
// Find the calendar feed
const feed = await prisma.calendarFeed.findUnique({
where: { token }
})
if (!feed || feed.workspaceId !== workspaceId) {
return NextResponse.json({ error: 'Invalid token' }, { status: 401 })
}
// Update last accessed
await prisma.calendarFeed.update({
where: { id: feed.id },
data: { lastAccessedAt: new Date() }
})
// Fetch appointments
const appointments = await prisma.appointment.findMany({
where: {
workspaceId,
deletedAt: null,
datetime: {
gte: new Date(),
lte: addDays(new Date(), feed.daysAhead)
}
},
orderBy: { datetime: 'asc' }
})
// Generate ICS content
const icsContent = generateICS(appointments, feed.includeMeds)
// Return as ICS file
return new NextResponse(icsContent, {
headers: {
'Content-Type': 'text/calendar; charset=utf-8',
'Content-Disposition': `attachment; filename="nextstep-calendar-${workspaceId}.ics"`,
},
})
} catch (error) {
console.error('Failed to generate calendar feed:', error)
return NextResponse.json(
{ error: 'Failed to generate calendar feed' },
{ status: 500 }
)
}
}
function generateICS(appointments: any[], includeMeds: boolean): string {
const events = appointments.map(appt => {
const start = new Date(appt.datetime)
const end = new Date(start.getTime() + 60 * 60 * 1000) // 1 hour default
return `
BEGIN:VEVENT
UID:${appt.id}@nextstep.app
DTSTART:${format(start, "yyyyMMdd'T'HHmmss")}
DTEND:${format(end, "yyyyMMdd'T'HHmmss")}
SUMMARY:${escapeICS(appt.title)}
${appt.location ? `LOCATION:${escapeICS(appt.location)}` : ''}
${appt.notes ? `DESCRIPTION:${escapeICS(appt.notes)}` : ''}
STATUS:CONFIRMED
END:VEVENT`
}).join('')
return `BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Next Step//Calendar//EN
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-WR-CALNAME:Next Step Appointments
X-WR-TIMEZONE:Australia/Perth
${events}
END:VCALENDAR`
}
function escapeICS(str: string): string {
return str
.replace(/\\/g, '\\\\')
.replace(/;/g, '\\;')
.replace(/,/g, '\\,')
.replace(/\n/g, '\\n')
}

View File

@@ -0,0 +1,91 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db/prisma'
import { getCurrentUser } from '@/lib/auth'
import { canAccessWorkspace } from '@/lib/db/workspace-access'
import { nanoid } from 'nanoid'
// GET /api/workspaces/[id]/calendar-feed/settings
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const user = await getCurrentUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const workspaceId = params.id
const access = await canAccessWorkspace(user.id, workspaceId)
if (!access) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
const feed = await prisma.calendarFeed.findFirst({
where: { workspaceId }
})
return NextResponse.json({ feed })
} catch (error) {
console.error('Failed to fetch calendar feed:', error)
return NextResponse.json(
{ error: 'Failed to fetch calendar feed' },
{ status: 500 }
)
}
}
// POST /api/workspaces/[id]/calendar-feed
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const user = await getCurrentUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const workspaceId = params.id
const access = await canAccessWorkspace(user.id, workspaceId)
if (!access || access.role === 'VIEWER') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
const body = await request.json()
const { includeAppointments, includeMeds, daysAhead } = body
// Generate unique token
const token = nanoid(32)
const feed = await prisma.calendarFeed.create({
data: {
workspaceId,
token,
includeAppointments: includeAppointments ?? true,
includeMeds: includeMeds ?? false,
daysAhead: daysAhead ?? 90,
}
})
// Log audit
await prisma.auditLog.create({
data: {
workspaceId,
userId: user.id,
action: 'CREATE',
entityType: 'CALENDAR_FEED',
entityId: feed.id,
details: { includeAppointments, includeMeds }
}
})
return NextResponse.json({ feed })
} catch (error) {
console.error('Failed to create calendar feed:', error)
return NextResponse.json(
{ error: 'Failed to create calendar feed' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,224 @@
'use client'
import { useState, useEffect } from 'react'
import {
Calendar, Copy, Check, RefreshCw,
ExternalLink, HelpCircle, Smartphone
} from 'lucide-react'
import { Card, Button, showToast } from '@/components/ui'
interface CalendarIntegrationProps {
workspaceId: string
}
export function CalendarIntegration({ workspaceId }: CalendarIntegrationProps) {
const [feed, setFeed] = useState<any>(null)
const [loading, setLoading] = useState(true)
const [copied, setCopied] = useState(false)
const [showInstructions, setShowInstructions] = useState(false)
useEffect(() => {
fetchFeed()
}, [workspaceId])
const fetchFeed = async () => {
try {
const response = await fetch(`/api/workspaces/${workspaceId}/calendar-feed/settings`)
if (response.ok) {
const data = await response.json()
setFeed(data.feed)
}
} catch (err) {
console.error('Failed to fetch calendar feed:', err)
} finally {
setLoading(false)
}
}
const createFeed = async () => {
try {
const response = await fetch(`/api/workspaces/${workspaceId}/calendar-feed`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
includeAppointments: true,
includeMeds: false,
daysAhead: 90
})
})
if (response.ok) {
const data = await response.json()
setFeed(data.feed)
showToast('Calendar feed created!', 'success')
}
} catch {
showToast('Failed to create feed', 'error')
}
}
const regenerateToken = async () => {
try {
const response = await fetch(`/api/workspaces/${workspaceId}/calendar-feed/regenerate`, {
method: 'POST'
})
if (response.ok) {
const data = await response.json()
setFeed(data.feed)
showToast('Feed URL regenerated', 'success')
}
} catch {
showToast('Failed to regenerate', 'error')
}
}
const copyFeedUrl = () => {
if (!feed) return
const url = `${window.location.origin}/api/workspaces/${workspaceId}/calendar-feed?token=${feed.token}`
navigator.clipboard.writeText(url)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
showToast('Feed URL copied!', 'success')
}
if (loading) {
return (
<Card className="text-center py-8">
<div className="animate-spin w-6 h-6 border-2 border-primary-500 border-t-transparent rounded-full mx-auto" />
</Card>
)
}
return (
<Card>
<div className="flex items-center gap-3 mb-4">
<div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
<Calendar className="w-5 h-5 text-blue-600" />
</div>
<div>
<h3 className="font-semibold text-secondary-900">Calendar Integration</h3>
<p className="text-sm text-secondary-500">Sync appointments to your calendar</p>
</div>
</div>
{!feed ? (
<div className="text-center py-6">
<p className="text-secondary-500 mb-4">
Create a calendar feed to see your appointments in Apple Calendar, Google Calendar, or Outlook.
</p>
<Button onClick={createFeed}>
<Calendar className="w-4 h-4 mr-2" />
Create Calendar Feed
</Button>
</div>
) : (
<div className="space-y-4">
{/* Feed URL */}
<div>
<label className="block text-sm font-medium text-secondary-700 mb-2">
Calendar Feed URL
</label>
<div className="flex gap-2">
<input
type="text"
value={`${typeof window !== 'undefined' ? window.location.origin : ''}/api/workspaces/${workspaceId}/calendar-feed?token=${feed.token.substring(0, 8)}...`}
readOnly
className="flex-1 px-3 py-2 bg-secondary-50 border border-border rounded-lg text-sm text-secondary-600"
/>
<Button
variant="secondary"
onClick={copyFeedUrl}
title="Copy URL"
>
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
</Button>
</div>
<p className="text-xs text-secondary-500 mt-1">
Copy this URL and add it to your calendar app
</p>
</div>
{/* Settings */}
<div className="grid grid-cols-2 gap-4">
<div className="p-3 bg-secondary-50 rounded-lg">
<p className="text-xs text-secondary-500">Appointments</p>
<p className="font-medium text-secondary-900">
{feed.includeAppointments ? 'Included' : 'Not included'}
</p>
</div>
<div className="p-3 bg-secondary-50 rounded-lg">
<p className="text-xs text-secondary-500">Look Ahead</p>
<p className="font-medium text-secondary-900">{feed.daysAhead} days</p>
</div>
</div>
{/* Last Accessed */}
{feed.lastAccessedAt && (
<p className="text-xs text-secondary-500">
Last accessed: {new Date(feed.lastAccessedAt).toLocaleDateString()}
</p>
)}
{/* Actions */}
<div className="flex gap-2 pt-2 border-t border-border">
<Button
variant="secondary"
size="sm"
onClick={() => setShowInstructions(!showInstructions)}
>
<HelpCircle className="w-4 h-4 mr-1" />
How to Add
</Button>
<Button
variant="ghost"
size="sm"
onClick={regenerateToken}
>
<RefreshCw className="w-4 h-4 mr-1" />
Regenerate
</Button>
</div>
{/* Instructions */}
{showInstructions && (
<div className="bg-blue-50 rounded-lg p-4 space-y-3">
<h4 className="font-medium text-blue-900 flex items-center gap-2">
<Smartphone className="w-4 h-4" />
How to Add to Your Calendar
</h4>
<div className="space-y-3 text-sm text-blue-800">
<div>
<p className="font-medium">Apple Calendar (iPhone/Mac):</p>
<ol className="list-decimal list-inside ml-2 space-y-1 text-blue-700">
<li>Copy the feed URL above</li>
<li>Open Calendar app File New Calendar Subscription</li>
<li>Paste the URL and click Subscribe</li>
</ol>
</div>
<div>
<p className="font-medium">Google Calendar:</p>
<ol className="list-decimal list-inside ml-2 space-y-1 text-blue-700">
<li>Copy the feed URL above</li>
<li>Open Google Calendar Settings Add Calendar From URL</li>
<li>Paste the URL and click Add Calendar</li>
</ol>
</div>
<div>
<p className="font-medium">Outlook:</p>
<ol className="list-decimal list-inside ml-2 space-y-1 text-blue-700">
<li>Copy the feed URL above</li>
<li>Open Outlook Add Calendar Subscribe from web</li>
<li>Paste the URL and click Import</li>
</ol>
</div>
</div>
</div>
)}
</div>
)}
</Card>
)
}