chahinebrini b7909d77e4 feat(mail): custom title + settings collapsible + stats charts + provider filter
Mail-Page-Refactor — Privacy-friendly + DiGA-tauglich:

- Custom title pro mail-connection (z.B. "Privat-Gmail" statt voller E-Mail).
  Memory-Pattern: Anonymität via Nickname jetzt auch für Mail-Adressen
  sichtbar, Datenminimierung. Title nullable, Fallback auf Email-Domain.
- Schema-Migration mail_connection_title (additiv, NULL default für Bestand)
- Endpoint PATCH /api/mail-connections/:id mit title-Validation (max 60,
  trim, leerer String → NULL)
- "Passwort ändern"-Collapsible → vollwertige "Einstellungen"-Sektion:
  Title editieren · Email read-only · Passwort neu setzen · Verbindung
  trennen (mit Confirm-Dialog)
- EditMailTitleSheet als FormSheet-Pattern für Title-Edit
- mailConnectDraft-Store kriegt Title-Feld für Pre-Fill bei Re-Open

Zwei neue Stats-Charts auf der Mail-Page:

- MailBlockedByDayChart — 30-Tage-Bar-Chart, Plain-View-Bars (Pattern wie
  Sparkline-Profile), Empty-State bei 0 Cooldowns
  · Backend: GET /api/mail/stats/blocked-by-day?days=30
- MailDistributionChart — Half-Donut via react-native-svg, Top-5 Connections
  + "Sonstige", rendert nicht bei ≤1 Connection
  · Backend: GET /api/mail/stats/blocked-by-connection

Activity-Log mit Provider-Filter:

- Filter-Chips Mo Gmail/Outlook/iCloud/etc. über bestehendem Activity-Log
- GET /api/mail/results?provider=X (war vorher hardcoded all)
- Endpoint-Naming-Fix in useMailResults (war /api/mail/blocked, jetzt
  korrekt /api/mail/results — UI-Agent hatte falschen Path geraten)

Backend-Side-Effects:

- imap-providers util resolveProviderMeta(host) — gibt {provider, label,
  isCustomDomain} zurück, von 3 Endpoints konsumiert
- /api/mail/status erweitert: title, provider, providerLabel,
  isCustomDomain im Account-Shape
- /api/mail/results erweitert: connection-Sub-Objekt pro Entry +
  provider-Filter-Query

Open follow-ups (TODOs):

- deleteOldMailBlocked-Cron löscht <24h → Bar-Chart-Daten weg. Retention
  auf 90 Tage hochsetzen oder Cron stoppen.
- POST /api/mail/connect könnte die neue connection.id im Response
  mitliefern → Title-PATCH direkt ohne Extra-GET (UI-Agent-Empfehlung).
- /api/mail/status zeigt nur active Connections — paused mit Title wären
  unsichtbar. Entscheiden.

18 neue i18n-Keys (mail.title_*, mail.settings_*, mail.row_*,
mail.disconnect_confirm_*, mail.stats.*, mail.filter.all) in DE + EN.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 19:06:01 +02:00

320 lines
10 KiB
TypeScript

import { useState } from 'react';
import {
ActivityIndicator,
Alert,
ScrollView,
Text,
TouchableOpacity,
View,
} from 'react-native';
import { useBottomTabBarHeight } from 'react-native-bottom-tabs';
import { useTranslation } from 'react-i18next';
import { Ionicons } from '@expo/vector-icons';
import { AppHeader } from '../../components/AppHeader';
import { MailStatsRow } from '../../components/mail/MailStatsRow';
import { MailAccountCard } from '../../components/mail/MailAccountCard';
import { MailEmptyState } from '../../components/mail/MailEmptyState';
import { MailActivityLog } from '../../components/mail/MailActivityLog';
import { MailBlockedByDayChart } from '../../components/mail/MailBlockedByDayChart';
import { MailDistributionChart } from '../../components/mail/MailDistributionChart';
import { ConnectMailSheet } from '../../components/mail/ConnectMailSheet';
import { SuccessAlert } from '../../components/SuccessAlert';
import { useMailStatus } from '../../hooks/useMailStatus';
import { useMailDisconnect } from '../../hooks/useMailDisconnect';
import { useMailStats } from '../../hooks/useMailStats';
import { useUserPlan } from '../../hooks/useUserPlan';
import { useColors } from '../../lib/theme';
const PLAN_LABEL: Record<string, string> = { free: 'Free', pro: 'Pro', legend: 'Legend' };
function MailOverLimitBanner({
usedCount,
maxAccounts,
planLabel,
pausedEmails,
colors,
}: {
usedCount: number;
maxAccounts: number;
planLabel: string;
pausedEmails: string[];
colors: import('../../lib/theme').ColorScheme;
}) {
const { t } = useTranslation();
const over = usedCount - maxAccounts;
if (over <= 0) return null;
return (
<View
style={{
backgroundColor: 'rgba(217,119,6,0.08)',
borderRadius: 14,
padding: 14,
marginBottom: 14,
borderWidth: 1,
borderColor: 'rgba(217,119,6,0.2)',
gap: 6,
}}
>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<Ionicons name="warning-outline" size={16} color="#d97706" />
<Text style={{ fontSize: 14, fontFamily: 'Nunito_700Bold', color: '#d97706', flex: 1 }}>
{t('plan_limit.mail_banner_title')}
</Text>
</View>
<Text style={{ fontSize: 13, color: colors.text, fontFamily: 'Nunito_400Regular', lineHeight: 18 }}>
{t(over === 1 ? 'plan_limit.mail_banner_body_one' : 'plan_limit.mail_banner_body_other', {
used: usedCount,
plan: planLabel,
max: maxAccounts,
over,
})}
</Text>
{pausedEmails.length > 0 && (
<Text style={{ fontSize: 12, color: colors.textMuted, fontFamily: 'Nunito_400Regular' }}>
{pausedEmails.join(', ')}
</Text>
)}
</View>
);
}
export default function MailScreen() {
const { t } = useTranslation();
const tabBarHeight = useBottomTabBarHeight();
const colors = useColors();
const { plan } = useUserPlan();
const { connected, accounts, totalBlocked, maxAccounts, loading, refresh } =
useMailStatus(plan);
const { disconnect, disconnecting } = useMailDisconnect();
const hasAccounts = accounts.length > 0;
const { blockedByDay, blockedByConnection } = useMailStats(hasAccounts);
const [sheetVisible, setSheetVisible] = useState(false);
const [successVisible, setSuccessVisible] = useState(false);
const [disconnectingId, setDisconnectingId] = useState<string | null>(null);
const [expandedAccount, setExpandedAccount] = useState<string | null>(null);
const [activityLogExpanded, setActivityLogExpanded] = useState(false);
const nextScanAt =
accounts
.map((a) => a.nextScanAt)
.filter((v): v is string => v !== null)
.sort()[0] ?? null;
const pausedAccounts = accounts.filter((a) => a.paused === true);
const overLimit = maxAccounts !== Infinity && accounts.length > maxAccounts;
const limitReached = maxAccounts !== Infinity && accounts.length >= maxAccounts;
const distinctProviders = [
...new Set(accounts.map((a) => a.provider.toLowerCase())),
];
function handleAddPress() {
if (limitReached) {
Alert.alert(t('mail.upgrade_alert_title'), t('mail.upgrade_alert_desc'));
return;
}
setSheetVisible(true);
}
async function handleDisconnect(id: string) {
setDisconnectingId(id);
await disconnect(id);
setDisconnectingId(null);
if (expandedAccount === id) setExpandedAccount(null);
refresh();
}
function handleConnectSuccess() {
setSuccessVisible(true);
refresh();
}
function toggleAccount(id: string) {
setExpandedAccount((prev) => (prev === id ? null : id));
}
if (loading) {
return (
<View style={{ flex: 1, backgroundColor: colors.bg }}>
<AppHeader />
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<ActivityIndicator size="large" color="#007AFF" />
</View>
</View>
);
}
return (
<View style={{ flex: 1, backgroundColor: colors.bg }}>
<AppHeader />
<ScrollView
contentContainerStyle={{
paddingHorizontal: 16,
paddingTop: 16,
paddingBottom: tabBarHeight + 24,
}}
showsVerticalScrollIndicator={false}
>
{/* Über-Limit-Banner */}
{overLimit && pausedAccounts.length > 0 && (
<MailOverLimitBanner
usedCount={accounts.length}
maxAccounts={maxAccounts}
planLabel={PLAN_LABEL[plan] ?? plan}
pausedEmails={pausedAccounts.map((a) => a.email)}
colors={colors}
/>
)}
{/* Stats card */}
{hasAccounts && (
<View style={{ marginBottom: 14 }}>
<MailStatsRow
totalBlocked={totalBlocked}
accountCount={accounts.length}
isLegend={plan === 'legend'}
/>
</View>
)}
{/* Section header + add button */}
{hasAccounts && (
<View
style={{
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10,
paddingHorizontal: 2,
}}
>
<View style={{ flex: 1, marginRight: 10 }}>
<Text
style={{
fontSize: 11,
fontFamily: 'Nunito_700Bold',
color: colors.textMuted,
textTransform: 'uppercase',
letterSpacing: 0.8,
}}
>
{t('mail.section_accounts')}
</Text>
<Text
style={{
fontSize: 11,
fontFamily: 'Nunito_400Regular',
color: colors.textMuted,
marginTop: 2,
}}
>
{maxAccounts === Infinity
? t('mail.section_accounts_count_unlimited', { used: accounts.length })
: t('mail.section_accounts_count', {
used: accounts.length,
max: maxAccounts,
})}
</Text>
</View>
<TouchableOpacity
onPress={handleAddPress}
disabled={limitReached}
activeOpacity={limitReached ? 1 : 0.8}
accessibilityLabel={t('mail.add_account_a11y')}
style={{
backgroundColor: limitReached ? colors.surfaceElevated : '#007AFF',
borderRadius: 12,
opacity: limitReached ? 0.7 : 1,
shadowColor: '#007AFF',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: limitReached ? 0 : 0.25,
shadowRadius: 8,
elevation: limitReached ? 0 : 4,
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 14,
paddingVertical: 10,
}}
>
<Ionicons
name="add"
size={18}
color={limitReached ? colors.textMuted : '#fff'}
style={{ marginRight: 6 }}
/>
<Text
style={{
fontSize: 13,
fontFamily: 'Nunito_700Bold',
color: limitReached ? colors.textMuted : '#fff',
}}
>
{t('mail.add_account')}
</Text>
</TouchableOpacity>
</View>
)}
{/* Account cards or empty */}
{accounts.length === 0 ? (
<MailEmptyState onConnectPress={handleAddPress} />
) : (
<View>
{accounts.map((account, idx) => (
<View key={account.id} style={{ marginTop: idx === 0 ? 0 : 10 }}>
<MailAccountCard
account={account}
plan={plan}
expanded={expandedAccount === account.id}
onToggle={() => toggleAccount(account.id)}
onDisconnect={handleDisconnect}
onIntervalChanged={refresh}
onEditSuccess={handleConnectSuccess}
disconnecting={disconnectingId === account.id && disconnecting}
/>
</View>
))}
</View>
)}
{/* Charts — nur wenn Accounts vorhanden */}
{hasAccounts && (
<View style={{ gap: 12, marginTop: 14 }}>
<MailBlockedByDayChart data={blockedByDay} />
<MailDistributionChart data={blockedByConnection} />
</View>
)}
{/* Activity log */}
{hasAccounts && (
<View style={{ marginTop: 14 }}>
<MailActivityLog
expanded={activityLogExpanded}
onToggle={() => setActivityLogExpanded((p) => !p)}
providers={distinctProviders}
/>
</View>
)}
</ScrollView>
<ConnectMailSheet
visible={sheetVisible}
onClose={() => setSheetVisible(false)}
onSuccess={handleConnectSuccess}
/>
<SuccessAlert
visible={successVisible}
title={t('mail.connect_success_title')}
message={t('mail.connect_success_message')}
onClose={() => setSuccessVisible(false)}
/>
</View>
);
}