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

476 lines
15 KiB
TypeScript

import { useState } from 'react';
import {
LayoutAnimation,
Linking,
Modal,
Platform,
TouchableOpacity,
Text,
UIManager,
View,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { ConfirmAlert } from '../ConfirmAlert';
import { MailAccountSettingsSheet } from './MailAccountSettingsSheet';
import { MailBlockedByDayChart } from './MailBlockedByDayChart';
import { useMailConnectionStats } from '../../hooks/useMailStats';
import type { MailAccount } from '../../hooks/useMailStatus';
if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
type Props = {
account: MailAccount;
plan: 'free' | 'pro' | 'legend';
expanded: boolean;
onToggle: () => void;
onDisconnect: (id: string) => Promise<void>;
onIntervalChanged: () => void;
onEditSuccess: () => void;
disconnecting?: boolean;
blockedLast30d?: number;
};
function OAuthDisconnectHintModal({
visible,
onClose,
t,
}: {
visible: boolean;
onClose: () => void;
t: (key: string) => string;
}) {
return (
<Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
<TouchableOpacity
activeOpacity={1}
onPress={onClose}
style={{
flex: 1,
backgroundColor: 'rgba(0,0,0,0.35)',
justifyContent: 'center',
alignItems: 'center',
padding: 24,
}}
>
<TouchableOpacity activeOpacity={1} onPress={() => {}} style={{ width: '88%', maxWidth: 340 }}>
<View
style={{
backgroundColor: '#fff',
borderRadius: 22,
padding: 22,
gap: 14,
shadowColor: '#000',
shadowOffset: { width: 0, height: 8 },
shadowOpacity: 0.18,
shadowRadius: 24,
elevation: 16,
}}
>
<View
style={{
width: 52,
height: 52,
borderRadius: 26,
backgroundColor: '#16a34a',
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
}}
>
<Ionicons name="checkmark" size={28} color="#fff" />
</View>
<Text
style={{
fontSize: 17,
fontFamily: 'Nunito_700Bold',
color: '#0a0a0a',
textAlign: 'center',
}}
>
{t('mail.oauth.disconnect_hint_title')}
</Text>
<Text
style={{
fontSize: 13,
fontFamily: 'Nunito_400Regular',
color: '#525252',
lineHeight: 19,
textAlign: 'center',
}}
>
{t('mail.oauth.disconnect_hint_body')}
</Text>
<View style={{ flexDirection: 'row', gap: 10 }}>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => Linking.openURL('https://account.microsoft.com/consent').catch(() => {})}
style={{
flex: 1,
paddingVertical: 10,
borderRadius: 10,
backgroundColor: '#eff6ff',
borderWidth: 1,
borderColor: '#bfdbfe',
alignItems: 'center',
}}
>
<Text style={{ fontSize: 13, fontFamily: 'Nunito_700Bold', color: '#007AFF' }}>
{t('mail.oauth.disconnect_hint_open_ms')}
</Text>
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.7}
onPress={onClose}
style={{
flex: 1,
paddingVertical: 10,
borderRadius: 10,
backgroundColor: '#f5f5f5',
alignItems: 'center',
}}
>
<Text style={{ fontSize: 13, fontFamily: 'Nunito_700Bold', color: '#0a0a0a' }}>
OK
</Text>
</TouchableOpacity>
</View>
</View>
</TouchableOpacity>
</TouchableOpacity>
</Modal>
);
}
function resolveProviderIcon(provider: string): {
icon: React.ComponentProps<typeof Ionicons>['name'];
color: string;
} {
const p = provider.toLowerCase();
if (p.includes('gmail') || p.includes('google')) return { icon: 'mail', color: '#EA4335' };
if (p.includes('icloud') || p.includes('apple')) return { icon: 'cloud', color: '#007AFF' };
if (p.includes('outlook') || p.includes('hotmail') || p.includes('microsoft'))
return { icon: 'mail-open', color: '#0078D4' };
if (p.includes('yahoo')) return { icon: 'at', color: '#7C3AED' };
if (p.includes('gmx') || p.includes('web.de'))
return { icon: 'mail-unread', color: '#E87A22' };
return { icon: 'server', color: '#737373' };
}
function isOAuthProvider(provider: string): boolean {
return provider === 'outlook_oauth';
}
const STALE_THRESHOLD_MS = 5 * 60 * 1_000;
const IDLE_HEARTBEAT_STALE_MS = STALE_THRESHOLD_MS;
function idleHeartbeatAlive(lastIdleHeartbeatAt: string | null | undefined): boolean {
if (!lastIdleHeartbeatAt) return false;
return Date.now() - new Date(lastIdleHeartbeatAt).getTime() < IDLE_HEARTBEAT_STALE_MS;
}
function domainFromEmail(email: string): string {
return email.split('@')[1] ?? email;
}
type StatusDot = 'live' | 'stale' | 'error' | 'waiting';
function resolveStatusDot(account: MailAccount): StatusDot {
if (account.lastConnectError) return 'error';
// 'waiting' nur wenn weder ein lebendiger Heartbeat noch ein vergangener Scan
// existiert. Bei frisch verbundenen Connections (z.B. OAuth-Outlook nach
// ersten 5-30s) hat der Daemon schon einen Heartbeat geschrieben, aber
// lastScannedAt bleibt NULL bis die erste Gambling-Mail trifft. Wir wollen
// dann 'live' anzeigen, nicht 'waiting'.
const heartbeatAlive = idleHeartbeatAlive(account.lastIdleHeartbeatAt);
if (!account.lastScannedAt && !heartbeatAlive) return 'waiting';
if (account.lastScannedAt) {
const scannedAgo = Date.now() - new Date(account.lastScannedAt).getTime();
if (!heartbeatAlive && scannedAgo > STALE_THRESHOLD_MS) return 'stale';
}
return 'live';
}
function StatusDotRow({
account,
isLegend,
blockedLast30d,
t,
}: {
account: MailAccount;
isLegend: boolean;
blockedLast30d: number | undefined;
t: (k: string) => string;
}) {
const dot = resolveStatusDot(account);
const dotColor =
dot === 'live' ? '#16a34a' :
dot === 'stale' ? '#d97706' :
dot === 'error' ? '#dc2626' :
'#a3a3a3';
const label =
dot === 'live' ? (isLegend ? t('mail.live') : t('mail.account_active')) :
dot === 'stale' ? t('mail.status_stale') :
dot === 'error' ? t('mail.status_auth_error') :
t('mail.status_waiting_first_connect');
const blockedLabel =
blockedLast30d !== undefined
? `${blockedLast30d}`
: account.totalBlocked > 0
? `${account.totalBlocked}`
: '0';
return (
<View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 3 }}>
<View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: dotColor, marginRight: 5 }} />
<Text
style={{ fontSize: 11, fontFamily: 'Nunito_600SemiBold', color: dotColor, flex: 1 }}
numberOfLines={1}
>
{label}
</Text>
<Text style={{ fontSize: 12, fontFamily: 'Nunito_700Bold', color: '#525252', marginRight: 6 }}>
{blockedLabel}
</Text>
<Ionicons name="shield-checkmark" size={11} color="#a3a3a3" />
</View>
);
}
export function MailAccountCard({
account,
plan,
expanded,
onToggle,
onDisconnect,
onIntervalChanged,
onEditSuccess,
disconnecting,
blockedLast30d,
}: Props) {
const { t } = useTranslation();
const [settingsVisible, setSettingsVisible] = useState(false);
const [confirmVisible, setConfirmVisible] = useState(false);
const [oauthDisconnectHintVisible, setOauthDisconnectHintVisible] = useState(false);
const [localTitle, setLocalTitle] = useState<string | null>(account.title ?? null);
const { icon, color } = resolveProviderIcon(account.provider);
const { data: connStats, granularity, loading: statsLoading } = useMailConnectionStats(
account.id,
account.createdAt ?? null,
expanded,
);
const isOAuth = isOAuthProvider(account.provider);
const isLegend = plan === 'legend';
const isPaused = account.paused === true;
const hasError = !!account.lastConnectError;
const displayTitle = localTitle ?? domainFromEmail(account.email);
function handleToggle() {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
onToggle();
}
function handleTitleSaved(newTitle: string | null) {
setLocalTitle(newTitle);
onEditSuccess();
}
return (
<>
<View
style={{
backgroundColor: isPaused ? '#fafafa' : '#fff',
borderRadius: 16,
borderWidth: 1,
borderColor: hasError ? '#fecaca' : isPaused ? '#d4d4d4' : '#e5e5e5',
overflow: 'hidden',
opacity: isPaused ? 0.75 : 1,
}}
>
{/* Header */}
<TouchableOpacity onPress={handleToggle} activeOpacity={0.85}>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 14,
paddingVertical: 13,
}}
>
<View
style={{
width: 38,
height: 38,
borderRadius: 10,
backgroundColor: color + '18',
alignItems: 'center',
justifyContent: 'center',
marginRight: 12,
}}
>
<Ionicons name={icon} size={18} color={color} />
</View>
<View style={{ flex: 1, minWidth: 0 }}>
<Text
style={{
fontSize: 15,
fontFamily: 'Nunito_700Bold',
color: isPaused ? '#a3a3a3' : '#0a0a0a',
}}
numberOfLines={1}
>
{displayTitle}
</Text>
{isPaused ? (
<View style={{ marginTop: 3 }}>
<Text style={{ fontSize: 11, fontFamily: 'Nunito_600SemiBold', color: '#737373' }}>
{t('plan_limit.mail_account_paused')}
</Text>
</View>
) : (
<StatusDotRow
account={account}
isLegend={isLegend}
blockedLast30d={blockedLast30d}
t={t}
/>
)}
</View>
<Ionicons
name={expanded ? 'chevron-up' : 'chevron-down'}
size={18}
color="#a3a3a3"
style={{ marginLeft: 8 }}
/>
</View>
</TouchableOpacity>
{/* Expanded body */}
{expanded && (
<View style={{ borderTopWidth: 1, borderTopColor: '#f5f5f5' }}>
{/* Per-connection bar chart */}
<View style={{ paddingHorizontal: 14, paddingTop: 14, paddingBottom: 4 }}>
{granularity === 'too-new' ? (
<View
style={{
borderRadius: 12,
backgroundColor: '#f9fafb',
borderWidth: 1,
borderColor: '#e5e5e5',
paddingHorizontal: 14,
paddingVertical: 20,
alignItems: 'center',
gap: 4,
}}
>
<Text style={{ fontSize: 13, fontFamily: 'Nunito_600SemiBold', color: '#525252' }}>
{t('mail.account_chart_collecting_title')}
</Text>
<Text style={{ fontSize: 12, fontFamily: 'Nunito_400Regular', color: '#a3a3a3', textAlign: 'center' }}>
{t('mail.account_chart_collecting_body')}
</Text>
</View>
) : statsLoading && connStats.length === 0 ? (
<View
style={{
borderRadius: 12,
backgroundColor: '#f9fafb',
borderWidth: 1,
borderColor: '#e5e5e5',
paddingHorizontal: 14,
paddingVertical: 16,
alignItems: 'center',
}}
>
<Text style={{ fontSize: 12, fontFamily: 'Nunito_400Regular', color: '#a3a3a3' }}>
{t('mail.loading')}
</Text>
</View>
) : (
<MailBlockedByDayChart data={connStats} granularity={granularity} />
)}
</View>
{/* Einstellungen tap-row */}
<TouchableOpacity
activeOpacity={0.7}
onPress={() => setSettingsVisible(true)}
style={{
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 14,
paddingVertical: 13,
borderTopWidth: 1,
borderTopColor: '#f5f5f5',
marginTop: 8,
}}
>
<Text
style={{
flex: 1,
fontSize: 14,
fontFamily: 'Nunito_600SemiBold',
color: '#0a0a0a',
}}
>
{t('mail.settings_section_label')}
</Text>
<Ionicons name="chevron-forward" size={16} color="#a3a3a3" />
</TouchableOpacity>
</View>
)}
</View>
{/* Settings sub-sheet — inline edit, no nested sheets */}
<MailAccountSettingsSheet
visible={settingsVisible}
account={account}
localTitle={localTitle}
isOAuth={isOAuth}
plan={plan}
disconnecting={disconnecting}
onClose={() => setSettingsVisible(false)}
onTitleSaved={handleTitleSaved}
onPasswordSaved={onEditSuccess}
onDisconnectRequest={() => { setSettingsVisible(false); setConfirmVisible(true); }}
onIntervalChanged={onIntervalChanged}
/>
<ConfirmAlert
visible={confirmVisible}
title={t('mail.disconnect_confirm_title')}
message={t('mail.disconnect_confirm_body', { email: account.email })}
confirmLabel={t('mail.account_disconnect_confirm_btn')}
destructive
icon="trash"
iconColor="#FF3B30"
onConfirm={async () => {
setConfirmVisible(false);
await onDisconnect(account.id);
if (isOAuth) setOauthDisconnectHintVisible(true);
}}
onCancel={() => setConfirmVisible(false)}
/>
<OAuthDisconnectHintModal
visible={oauthDisconnectHintVisible}
onClose={() => setOauthDisconnectHintVisible(false)}
t={t}
/>
</>
);
}