feat: sistema completo de notificacoes por e-mail

Implementa sistema de notificacoes por e-mail com:

- Notificacoes de ciclo de vida (abertura, resolucao, atribuicao, status)
- Sistema de avaliacao de chamados com estrelas (1-5)
- Deep linking via protocolo raven:// para abrir chamados no desktop
- Tokens de acesso seguro para visualizacao sem login
- Preferencias de notificacao configuraveis por usuario
- Templates HTML responsivos com design tokens da plataforma
- API completa para preferencias, tokens e avaliacoes

Modelos Prisma:
- TicketRating: avaliacoes de chamados
- TicketAccessToken: tokens de acesso direto
- NotificationPreferences: preferencias por usuario

Turbopack como bundler padrao (Next.js 16)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
esdrasrenan 2025-12-07 20:45:37 -03:00
parent cb6add1a4a
commit f2c0298285
23 changed files with 4387 additions and 9 deletions

View file

@ -1,9 +1,11 @@
"use client"
import { FormEvent, useMemo, useState } from "react"
import Link from "next/link"
import { toast } from "sonner"
import { Bell } from "lucide-react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
@ -115,11 +117,24 @@ export function PortalProfileSettings({ initialEmail }: PortalProfileSettingsPro
</div>
<div className="flex justify-end">
<Button type="submit" disabled={isSubmitting || !hasChanges}>
{isSubmitting ? "Salvando..." : "Salvar alterações"}
{isSubmitting ? "Salvando..." : "Salvar alteracoes"}
</Button>
</div>
</form>
</CardContent>
<CardFooter className="border-t bg-muted/30 px-6 py-4">
<div className="flex items-center justify-between w-full">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Bell className="h-4 w-4" />
<span>Configurar notificacoes por e-mail</span>
</div>
<Button variant="outline" size="sm" asChild>
<Link href="/portal/profile/notifications">
Preferencias
</Link>
</Button>
</div>
</CardFooter>
</Card>
)
}

View file

@ -0,0 +1,361 @@
"use client"
import { useEffect, useState } from "react"
import { toast } from "sonner"
import { Loader2, Bell, BellOff, Clock, Mail, Lock } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Separator } from "@/components/ui/separator"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
interface NotificationType {
type: string
label: string
enabled: boolean
required: boolean
canDisable: boolean
}
interface NotificationPreferences {
emailEnabled: boolean
quietHoursStart: string | null
quietHoursEnd: string | null
timezone: string
digestFrequency: string
types: NotificationType[]
categoryPreferences: Record<string, boolean>
isStaff: boolean
}
interface NotificationPreferencesFormProps {
isPortal?: boolean
}
// Agrupamento de tipos de notificacao
const TYPE_GROUPS = {
lifecycle: {
label: "Ciclo de vida do chamado",
description: "Notificacoes sobre abertura, resolucao e mudancas de status",
types: ["ticket_created", "ticket_assigned", "ticket_resolved", "ticket_reopened", "ticket_status_changed", "ticket_priority_changed"],
},
communication: {
label: "Comunicacao",
description: "Comentarios e respostas nos chamados",
types: ["comment_public", "comment_response", "comment_mention"],
},
sla: {
label: "SLA e alertas",
description: "Alertas de prazo e metricas",
types: ["sla_at_risk", "sla_breached", "sla_daily_digest"],
},
security: {
label: "Seguranca",
description: "Notificacoes de autenticacao e acesso",
types: ["security_password_reset", "security_email_verify", "security_email_change", "security_new_login", "security_invite"],
},
}
export function NotificationPreferencesForm({ isPortal = false }: NotificationPreferencesFormProps) {
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [preferences, setPreferences] = useState<NotificationPreferences | null>(null)
const [localTypePrefs, setLocalTypePrefs] = useState<Record<string, boolean>>({})
useEffect(() => {
loadPreferences()
}, [])
async function loadPreferences() {
try {
const response = await fetch("/api/notifications/preferences")
if (!response.ok) {
throw new Error("Erro ao carregar preferencias")
}
const data = await response.json()
setPreferences(data)
// Inicializa preferencias locais
const typePrefs: Record<string, boolean> = {}
data.types.forEach((t: NotificationType) => {
typePrefs[t.type] = t.enabled
})
setLocalTypePrefs(typePrefs)
} catch (error) {
console.error("Erro ao carregar preferencias:", error)
toast.error("Nao foi possivel carregar suas preferencias")
} finally {
setLoading(false)
}
}
async function savePreferences() {
if (!preferences) return
setSaving(true)
try {
const response = await fetch("/api/notifications/preferences", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
emailEnabled: preferences.emailEnabled,
quietHoursStart: preferences.quietHoursStart,
quietHoursEnd: preferences.quietHoursEnd,
timezone: preferences.timezone,
digestFrequency: preferences.digestFrequency,
typePreferences: localTypePrefs,
}),
})
if (!response.ok) {
throw new Error("Erro ao salvar preferencias")
}
toast.success("Preferencias salvas com sucesso")
} catch (error) {
console.error("Erro ao salvar preferencias:", error)
toast.error("Nao foi possivel salvar suas preferencias")
} finally {
setSaving(false)
}
}
function toggleType(type: string, enabled: boolean) {
setLocalTypePrefs(prev => ({ ...prev, [type]: enabled }))
}
function toggleEmailEnabled(enabled: boolean) {
setPreferences(prev => prev ? { ...prev, emailEnabled: enabled } : null)
}
function setQuietHours(start: string | null, end: string | null) {
setPreferences(prev => prev ? { ...prev, quietHoursStart: start, quietHoursEnd: end } : null)
}
function setDigestFrequency(frequency: string) {
setPreferences(prev => prev ? { ...prev, digestFrequency: frequency } : null)
}
if (loading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
if (!preferences) {
return (
<Card>
<CardContent className="py-8">
<p className="text-center text-muted-foreground">
Nao foi possivel carregar suas preferencias de notificacao.
</p>
<div className="flex justify-center mt-4">
<Button onClick={loadPreferences}>Tentar novamente</Button>
</div>
</CardContent>
</Card>
)
}
// Filtra tipos visiveis para o usuario
const visibleTypes = preferences.types
// Agrupa tipos por categoria
const groupedTypes: Record<string, NotificationType[]> = {}
for (const [groupKey, group] of Object.entries(TYPE_GROUPS)) {
const types = visibleTypes.filter(t => group.types.includes(t.type))
if (types.length > 0) {
groupedTypes[groupKey] = types
}
}
return (
<div className="space-y-6">
{/* Configuracao global de e-mail */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Mail className="h-5 w-5" />
Notificacoes por e-mail
</CardTitle>
<CardDescription>
Controle se deseja receber notificacoes por e-mail.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label className="text-base">Receber e-mails</Label>
<p className="text-sm text-muted-foreground">
{preferences.emailEnabled
? "Voce recebera notificacoes por e-mail conforme suas preferencias"
: "Todas as notificacoes por e-mail estao desativadas"}
</p>
</div>
<Switch
checked={preferences.emailEnabled}
onCheckedChange={toggleEmailEnabled}
/>
</div>
{preferences.emailEnabled && preferences.isStaff && (
<>
<Separator />
{/* Horario de silencio - apenas staff */}
<div className="space-y-4">
<div className="flex items-center gap-2">
<Clock className="h-4 w-4 text-muted-foreground" />
<Label className="text-base">Horario de silencio</Label>
</div>
<p className="text-sm text-muted-foreground">
Durante este periodo, notificacoes nao urgentes serao adiadas.
</p>
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<Label htmlFor="quietStart" className="text-sm">Das</Label>
<Input
id="quietStart"
type="time"
value={preferences.quietHoursStart || ""}
onChange={(e) => setQuietHours(e.target.value || null, preferences.quietHoursEnd)}
className="w-32"
/>
</div>
<div className="flex items-center gap-2">
<Label htmlFor="quietEnd" className="text-sm">as</Label>
<Input
id="quietEnd"
type="time"
value={preferences.quietHoursEnd || ""}
onChange={(e) => setQuietHours(preferences.quietHoursStart, e.target.value || null)}
className="w-32"
/>
</div>
{(preferences.quietHoursStart || preferences.quietHoursEnd) && (
<Button
variant="ghost"
size="sm"
onClick={() => setQuietHours(null, null)}
>
Limpar
</Button>
)}
</div>
</div>
<Separator />
{/* Frequencia de resumo - apenas staff */}
<div className="space-y-4">
<Label className="text-base">Frequencia de resumo</Label>
<p className="text-sm text-muted-foreground">
Como voce prefere receber as notificacoes nao urgentes.
</p>
<Select
value={preferences.digestFrequency}
onValueChange={setDigestFrequency}
>
<SelectTrigger className="w-[200px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="immediate">Imediato</SelectItem>
<SelectItem value="daily">Resumo diario</SelectItem>
<SelectItem value="weekly">Resumo semanal</SelectItem>
</SelectContent>
</Select>
</div>
</>
)}
</CardContent>
</Card>
{/* Tipos de notificacao */}
{preferences.emailEnabled && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Bell className="h-5 w-5" />
Tipos de notificacao
</CardTitle>
<CardDescription>
Escolha quais tipos de notificacao deseja receber.
{!preferences.isStaff && (
<span className="block mt-1 text-amber-600">
Algumas notificacoes sao obrigatorias e nao podem ser desativadas.
</span>
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-8">
{Object.entries(groupedTypes).map(([groupKey, types]) => {
const group = TYPE_GROUPS[groupKey as keyof typeof TYPE_GROUPS]
return (
<div key={groupKey} className="space-y-4">
<div>
<h3 className="font-medium">{group.label}</h3>
<p className="text-sm text-muted-foreground">{group.description}</p>
</div>
<div className="space-y-3">
{types.map((notifType) => (
<div
key={notifType.type}
className="flex items-center justify-between rounded-lg border p-4"
>
<div className="flex items-center gap-3">
{notifType.required ? (
<Lock className="h-4 w-4 text-muted-foreground" />
) : localTypePrefs[notifType.type] ? (
<Bell className="h-4 w-4 text-primary" />
) : (
<BellOff className="h-4 w-4 text-muted-foreground" />
)}
<div>
<Label className="text-sm font-medium">
{notifType.label}
</Label>
{notifType.required && (
<Badge variant="secondary" className="ml-2 text-xs">
Obrigatorio
</Badge>
)}
</div>
</div>
<Switch
checked={localTypePrefs[notifType.type] ?? notifType.enabled}
onCheckedChange={(checked) => toggleType(notifType.type, checked)}
disabled={!notifType.canDisable}
/>
</div>
))}
</div>
</div>
)
})}
</CardContent>
</Card>
)}
{/* Botao de salvar */}
<div className="flex justify-end">
<Button onClick={savePreferences} disabled={saving}>
{saving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Salvando...
</>
) : (
"Salvar preferencias"
)}
</Button>
</div>
</div>
)
}

View file

@ -84,10 +84,18 @@ const SETTINGS_ACTIONS: SettingsAction[] = [
icon: MessageSquareText,
},
{
title: "Preferências da equipe",
description: "Defina padrões de notificação e comportamento do modo play para toda a equipe.",
title: "Notificacoes por e-mail",
description: "Configure quais notificacoes por e-mail deseja receber e como recebe-las.",
href: "/settings/notifications",
cta: "Configurar notificacoes",
requiredRole: "staff",
icon: BellRing,
},
{
title: "Preferencias da equipe",
description: "Defina padroes de notificacao e comportamento do modo play para toda a equipe.",
href: "#preferencias",
cta: "Ajustar preferências",
cta: "Ajustar preferencias",
requiredRole: "staff",
icon: Settings2,
},