chahinebrini 1dfb0c647c feat(mail-page): polish v3 + shared HalfDonut + status-dot heartbeat-aware
User-Feedback nach Live-Test:

Frontend (mail page):
- HalfDonut als shared component in components/common/HalfDonut.tsx
  extrahiert (vorher local in ProtectionDetailsSheet). Mail-Page nutzt
  jetzt dieselbe SVG-Math, Animation und Stroke-Style wie der
  Blocker-Schutz-Details-Sheet — visuelle Konsistenz auf einen Blick.
  Mail-Donut: width=168 (kompakter als die 220 in Blocker, weil Legend
  rechts daneben sitzt).
- Donut zeigt Total in der Mitte mit kompaktem Format:
  < 1000 → "999", >=1000 → "1.2k+" / "12k+" / "27k+"
  Headline-Zahl oben links entfällt — Total ist im Donut-Center.
- "Mehr Infos" + "Kürzlich blockiert" zu EINER Top-Level-Collapsible
  zusammengefasst. Beim Aufklappen: Bar-Chart direkt sichtbar, nested
  Collapsible "Kürzlich blockiert" darunter (default zu).
- Account-Card Expanded: per-Connection-Bar-Chart mit adaptive
  Granularität nach Connection-Age:
  · <24h → Empty-State "Daten werden gesammelt, Auswertung nach 24h"
  · 1-14d → Day-Buckets (echte Daten via /api/mail/stats/blocked-by-day
    ?connectionId=)
  · 15-90d → Week-Buckets (client-aggregiert)
  · >90d → Month-Buckets (client-aggregiert)
- Settings-Sheet komplett refactored: State-Machine `mode: 'list' |
  'edit-title' | 'edit-email' | 'edit-password'` mit Back-Pfeil. Inline-
  Edit im selben Sheet statt Sub-Sheet öffnen (FormSheet-Pattern).
  Email-Edit-Row vorbereitet (Backend-PATCH-Endpoint kommt separat).
- Pen-Icons app-weit entfernt: SheetFieldStack-Row, alle Settings-Rows
  auf chevron-forward (Memory-Konvention).

Frontend (MailAccountCard status fix):
- resolveStatusDot nutzt jetzt heartbeat-as-fallback. Vorher: "waiting"
  wenn lastScannedAt=null, egal ob Daemon längst connected war. Jetzt:
  "waiting" nur wenn weder lebendiger Heartbeat noch vergangener Scan
  existiert → frisch verbundene Connections (z.B. OAuth-Outlook 5s nach
  Connect) zeigen direkt "live".
- Behebt User-Beobachtung: "wartet auf erste verbindung" bei Outlook
  obwohl Daemon-Log "connected, auth=xoauth2" zeigt.

Backend (imap-idle daemon):
- getMailboxLock("INBOX") jetzt mit 30s Promise.race-Timeout gewrappt.
- Outlook/XOAUTH2 hat den Edge-Case, dass der Mailbox-Lock lautlos
  hängt nach erfolgreichem connect — die Session bleibt offen ohne
  Fortschritt bis der Renew-Timer (10min) ein imap.close() schickt.
  Mit Timeout wird das Failure-Mode explizit → Auth-Retry-Loop greift
  sauber + last_connect_error mit klarem Text (statt stiller Hänger).
- Root-Cause "warum hängt es" noch nicht behoben — Diagnose nach
  Deploy in Logs (mo).

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

559 lines
18 KiB
TypeScript

import { useState } from 'react';
import {
ActivityIndicator,
Alert,
LayoutAnimation,
Platform,
ScrollView,
Text,
TouchableOpacity,
UIManager,
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 { MailAccountCard } from '../../components/mail/MailAccountCard';
import { MailEmptyState } from '../../components/mail/MailEmptyState';
import { MailActivityLogBody } from '../../components/mail/MailActivityLog';
import { MailBlockedByDayChart } from '../../components/mail/MailBlockedByDayChart';
import { MailDistributionChart } from '../../components/mail/MailDistributionChart';
import { ConnectMailSheet } from '../../components/mail/ConnectMailSheet';
import { EditMailTitleSheet } from '../../components/mail/EditMailTitleSheet';
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';
import { useMailConnectDraft } from '../../stores/mailConnectDraft';
if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
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>
);
}
function MoreInfosSection({
expanded,
onToggle,
blockedByDay,
providers,
colors,
}: {
expanded: boolean;
onToggle: () => void;
blockedByDay: import('../../hooks/useMailStats').BlockedByDayEntry[];
providers: string[];
colors: import('../../lib/theme').ColorScheme;
}) {
const { t } = useTranslation();
const [activityExpanded, setActivityExpanded] = useState(false);
function handleToggle() {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
onToggle();
}
function handleActivityToggle() {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setActivityExpanded((p) => !p);
}
return (
<View
style={{
backgroundColor: colors.surface,
borderRadius: 16,
borderWidth: 1,
borderColor: colors.border,
overflow: 'hidden',
}}
>
<TouchableOpacity onPress={handleToggle} activeOpacity={0.85}>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 14,
paddingVertical: 14,
}}
>
<View
style={{
width: 32,
height: 32,
borderRadius: 8,
backgroundColor: '#eff6ff',
alignItems: 'center',
justifyContent: 'center',
marginRight: 12,
}}
>
<Ionicons name="bar-chart-outline" size={15} color="#2563eb" />
</View>
<View style={{ flex: 1, minWidth: 0, marginRight: 8 }}>
<Text
style={{ fontSize: 14, fontFamily: 'Nunito_700Bold', color: colors.text }}
numberOfLines={1}
>
{t('mail.more_infos_title')}
</Text>
<Text
style={{
fontSize: 11,
fontFamily: 'Nunito_400Regular',
color: colors.textMuted,
marginTop: 2,
}}
numberOfLines={1}
>
{t('mail.more_infos_subtitle')}
</Text>
</View>
<Ionicons
name={expanded ? 'chevron-up' : 'chevron-down'}
size={18}
color={colors.textMuted}
/>
</View>
</TouchableOpacity>
{expanded && (
<View
style={{
borderTopWidth: 1,
borderTopColor: colors.border,
paddingHorizontal: 12,
paddingTop: 12,
paddingBottom: 12,
gap: 10,
}}
>
{/* Bar-Chart direkt sichtbar */}
<MailBlockedByDayChart data={blockedByDay} />
{/* Nested: Kürzlich blockiert — default collapsed */}
<View
style={{
backgroundColor: colors.surfaceElevated ?? colors.surface,
borderRadius: 12,
borderWidth: 1,
borderColor: colors.border,
overflow: 'hidden',
}}
>
<TouchableOpacity onPress={handleActivityToggle} activeOpacity={0.85}>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 12,
paddingVertical: 12,
}}
>
<View
style={{
width: 28,
height: 28,
borderRadius: 7,
backgroundColor: '#fef2f2',
alignItems: 'center',
justifyContent: 'center',
marginRight: 10,
}}
>
<Ionicons name="trash" size={13} color="#dc2626" />
</View>
<View style={{ flex: 1, minWidth: 0, marginRight: 8 }}>
<Text
style={{ fontSize: 13, fontFamily: 'Nunito_700Bold', color: colors.text }}
numberOfLines={1}
>
{t('mail.activity_log_title')}
</Text>
<Text
style={{
fontSize: 11,
fontFamily: 'Nunito_400Regular',
color: colors.textMuted,
marginTop: 1,
}}
numberOfLines={1}
>
{t('mail.activity_log_subtitle')}
</Text>
</View>
<Ionicons
name={activityExpanded ? 'chevron-up' : 'chevron-down'}
size={16}
color={colors.textMuted}
/>
</View>
</TouchableOpacity>
{activityExpanded && (
<MailActivityLogBody providers={providers} colors={colors} />
)}
</View>
</View>
)}
</View>
);
}
export default function MailScreen() {
const { t } = useTranslation();
const tabBarHeight = useBottomTabBarHeight();
const colors = useColors();
const { plan } = useUserPlan();
const { 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 [moreInfosExpanded, setMoreInfosExpanded] = useState(false);
const [oauthTitleSheetConnectionId, setOauthTitleSheetConnectionId] = useState<string | null>(null);
const { pendingOAuthConnectionId, setPendingOAuthConnectionId } = useMailConnectDraft();
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())),
];
// Show distribution chart only when ≥2 accounts have data
const showDistributionHero = blockedByConnection.length >= 2;
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() {
refresh();
if (pendingOAuthConnectionId) {
setOauthTitleSheetConnectionId(pendingOAuthConnectionId);
setPendingOAuthConnectionId(null);
} else {
setSuccessVisible(true);
}
}
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}
>
{/* Over-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}
/>
)}
{/* 1. HERO — Half-Donut with integrated title row */}
{hasAccounts && showDistributionHero && (
<View style={{ marginBottom: 14 }}>
<MailDistributionChart
data={blockedByConnection}
hero
totalBlocked={totalBlocked}
accountCount={accounts.length}
isLegend={plan === 'legend'}
/>
</View>
)}
{/* Fallback stats row when donut is not shown (0-1 accounts with data) */}
{hasAccounts && !showDistributionHero && (
<View
style={{
backgroundColor: colors.surface,
borderRadius: 16,
borderWidth: 1,
borderColor: colors.border,
paddingHorizontal: 16,
paddingVertical: 16,
marginBottom: 14,
flexDirection: 'row',
alignItems: 'center',
}}
>
<View style={{ flex: 1 }}>
<Text
style={{
fontSize: 22,
fontFamily: 'Nunito_800ExtraBold',
color: colors.error,
lineHeight: 26,
}}
>
{totalBlocked.toLocaleString()}
</Text>
<Text
style={{
fontSize: 12,
fontFamily: 'Nunito_400Regular',
color: colors.textMuted,
marginTop: 2,
}}
>
{t('mail.stats_account_summary', { count: accounts.length })}
</Text>
</View>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 10,
paddingVertical: 5,
borderRadius: 999,
backgroundColor: plan === 'legend' ? '#f0fdf4' : '#eff6ff',
}}
>
<View
style={{
width: 6,
height: 6,
borderRadius: 3,
backgroundColor: plan === 'legend' ? '#16a34a' : '#2563eb',
marginRight: 6,
}}
/>
<Text
style={{
fontSize: 12,
fontFamily: 'Nunito_700Bold',
color: plan === 'legend' ? '#16a34a' : '#2563eb',
}}
>
{plan === 'legend' ? t('mail.live') : t('mail.scheduled')}
</Text>
</View>
</View>
)}
{/* 2. ACCOUNT LIST */}
{hasAccounts && (
<View style={{ marginBottom: 10, paddingHorizontal: 2 }}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<View style={{ flex: 1 }}>
<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}
activeOpacity={0.7}
accessibilityLabel={t('mail.add_account_a11y')}
style={{
flexDirection: 'row',
alignItems: 'center',
gap: 4,
paddingVertical: 4,
paddingLeft: 8,
}}
>
<Ionicons name="add-circle-outline" size={18} color={colors.brandOrange} />
<Text
style={{
fontSize: 13,
fontFamily: 'Nunito_600SemiBold',
color: colors.brandOrange,
}}
>
{t('mail.add_account')}
</Text>
</TouchableOpacity>
</View>
</View>
)}
{accounts.length === 0 ? (
<MailEmptyState onConnectPress={handleAddPress} />
) : (
<View style={{ gap: 10 }}>
{accounts.map((account) => {
const connStat = blockedByConnection.find((c) => c.connectionId === account.id);
return (
<MailAccountCard
key={account.id}
account={account}
plan={plan}
expanded={expandedAccount === account.id}
onToggle={() => toggleAccount(account.id)}
onDisconnect={handleDisconnect}
onIntervalChanged={refresh}
onEditSuccess={handleConnectSuccess}
disconnecting={disconnectingId === account.id && disconnecting}
blockedLast30d={connStat?.count}
/>
);
})}
</View>
)}
{/* 3. COLLAPSIBLE "MEHR INFOS" — Bar-Chart + nested Kürzlich blockiert */}
{hasAccounts && (
<View style={{ marginTop: 14 }}>
<MoreInfosSection
expanded={moreInfosExpanded}
onToggle={() => setMoreInfosExpanded((p) => !p)}
blockedByDay={blockedByDay}
providers={distinctProviders}
colors={colors}
/>
</View>
)}
</ScrollView>
<ConnectMailSheet
visible={sheetVisible}
onClose={() => setSheetVisible(false)}
onSuccess={handleConnectSuccess}
/>
{oauthTitleSheetConnectionId && (
<EditMailTitleSheet
visible={!!oauthTitleSheetConnectionId}
connectionId={oauthTitleSheetConnectionId}
currentTitle={null}
onClose={() => { setOauthTitleSheetConnectionId(null); setSuccessVisible(true); }}
onSuccess={() => { setOauthTitleSheetConnectionId(null); setSuccessVisible(true); refresh(); }}
/>
)}
<SuccessAlert
visible={successVisible}
title={t('mail.connect_success_title')}
message={t('mail.connect_success_message')}
onClose={() => setSuccessVisible(false)}
/>
</View>
);
}