MonEspacePro/pro/app/campaigns.tsx

179 lines
7.6 KiB
TypeScript

import { useCallback, useState } from 'react';
import { Alert, ScrollView, TextInput, View } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { api } from '../src/api';
import { describe } from '../src/errors';
import { useStore } from '../src/session';
import { Banner, Button, Card, T } from '../src/ui';
import { font, useColors } from '../src/theme';
import { Icon } from '../src/icons';
interface Overview {
defaultTitle: string;
allowed: boolean;
maxLength: number;
minIntervalHours: number;
audience: { cards: number; appleDevices: number };
nextAllowedAt: string | null;
items: { id: string; title: string | null; message: string; sentByName: string; cards: number; createdAt: string }[];
}
const when = (d: string) =>
new Date(d).toLocaleString('fr-FR', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
/** Campagnes (dirigeants, formule Pro) : un message envoyé en notification à toutes les cartes du magasin. */
export default function Campaigns() {
const c = useColors();
const store = useStore();
const [data, setData] = useState<Overview | null>(null);
const [message, setMessage] = useState('');
const [title, setTitle] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [sent, setSent] = useState(false);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
try {
setData(await api.get<Overview>('/api/staff/campaigns'));
} catch (e) {
setError(describe(e).detail);
}
}, []);
useFocusEffect(
useCallback(() => {
load();
}, [load]),
);
const text = message.trim();
const blocked = !data || !data.allowed || !!data.nextAllowedAt;
const send = () =>
Alert.alert('Envoyer la campagne ?', `${data!.audience.cards} cartes de ${store.name} recevront :\n\n${(title ?? data!.defaultTitle).trim()}\n« ${text} »`, [
{ text: 'Annuler', style: 'cancel' },
{
text: 'Envoyer',
onPress: async () => {
setBusy(true);
setError(null);
try {
await api.post('/api/staff/campaigns', { message: text, title: (title ?? data!.defaultTitle).trim() });
setMessage('');
setSent(true);
await load();
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
},
},
]);
const shownTitle = (title ?? data?.defaultTitle ?? '').trim() || store.name;
const maxLength = data?.maxLength ?? 160;
const input = {
borderWidth: 1,
borderColor: c.border,
borderRadius: 14,
padding: 14,
backgroundColor: c.bg,
color: c.text,
fontFamily: font.regular,
fontSize: 17,
opacity: blocked ? 0.6 : 1,
} as const;
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 18 }} keyboardShouldPersistTaps="handled" bounces={false} overScrollMode="never">
{error && <Banner tone="error">{error}</Banner>}
{sent && <Banner tone="ok">Campagne envoyée. Les cartes de vos clients se mettent à jour dans les minutes qui suivent.</Banner>}
{data && !data.allowed && <Banner tone="warn">Le module Campagnes n'est pas actif : activez-le dans Configuration → Modules, ou contactez MonEspacePro s'il n'est pas inclus dans votre formule.</Banner>}
{data?.nextAllowedAt && <Banner tone="warn">Prochain envoi possible le {when(data.nextAllowedAt)}.</Banner>}
{/* Audience */}
<View style={{ backgroundColor: c.primary, borderRadius: 22, padding: 20, flexDirection: 'row', alignItems: 'center', gap: 14 }}>
<View style={{ width: 52, height: 52, borderRadius: 16, backgroundColor: 'rgba(255,255,255,0.18)', alignItems: 'center', justifyContent: 'center' }}>
<Icon name="megaphone" size={26} color="#FFFFFF" />
</View>
<View style={{ flex: 1 }}>
<T style={{ color: c.onPrimary, fontFamily: font.extrabold, fontSize: 28 }}>{data?.audience.cards ?? '—'}</T>
<T style={{ color: c.onPrimary, opacity: 0.85, fontSize: 14 }}>clients recevront la notification sur leur téléphone</T>
</View>
</View>
{/* Rédaction */}
<Card style={{ gap: 12 }}>
<T v="h2">Nouvelle campagne</T>
<T v="label">Titre</T>
<TextInput
value={title ?? data?.defaultTitle ?? ''}
onChangeText={setTitle}
editable={!blocked && !busy}
maxLength={40}
placeholder={store.name}
placeholderTextColor={c.text3}
accessibilityLabel="Titre de la notification"
style={input}
/>
<T v="label">Message</T>
<TextInput
value={message}
onChangeText={setMessage}
editable={!blocked && !busy}
multiline
maxLength={maxLength}
placeholder="Ex. : -20 % sur les viennoiseries ce samedi !"
placeholderTextColor={c.text3}
accessibilityLabel="Message de la campagne"
style={{ ...input, minHeight: 110, textAlignVertical: 'top' }}
/>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<T v="muted" style={{ fontSize: 13 }}>1 campagne toutes les {data?.minIntervalHours ?? 24} h maximum</T>
<T style={{ fontSize: 13, fontFamily: font.semibold, color: text.length > maxLength - 15 ? c.warn : c.text3 }}>
{text.length} / {maxLength}
</T>
</View>
</Card>
{/* Aperçu de la notification */}
<View style={{ gap: 8 }}>
<T v="label" style={{ color: c.text3, textTransform: 'uppercase', fontSize: 13, letterSpacing: 0.5 }}>Aperçu</T>
<View style={{ backgroundColor: c.surface2, borderRadius: 22, padding: 14, flexDirection: 'row', gap: 12, alignItems: 'flex-start' }}>
<View style={{ width: 40, height: 40, borderRadius: 10, backgroundColor: store.design.backgroundColor, alignItems: 'center', justifyContent: 'center' }}>
<T style={{ color: store.design.foregroundColor, fontFamily: font.extrabold, fontSize: 18 }}>{store.name.charAt(0).toUpperCase()}</T>
</View>
<View style={{ flex: 1, gap: 2 }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<T v="label" numberOfLines={1} style={{ flex: 1 }}>{shownTitle}</T>
<T v="muted" style={{ fontSize: 12 }}>maintenant</T>
</View>
<T style={{ fontSize: 15, lineHeight: 20, color: text ? c.text : c.text3 }}>{text || 'Votre message apparaîtra ici.'}</T>
</View>
</View>
<T v="muted" style={{ fontSize: 12 }}>Sur iPhone, le nom du magasin remplace toujours le titre.</T>
</View>
<Button large label="Envoyer la campagne" onPress={send} disabled={blocked || text.length < 5} loading={busy} />
{!!data?.items.length && (
<View style={{ gap: 10, marginTop: 6 }}>
<T v="h2">Campagnes envoyées</T>
{data.items.map((i) => (
<Card key={i.id} style={{ padding: 14, gap: 6 }}>
{!!i.title && <T v="label">{i.title}</T>}
<T style={{ fontSize: 15, lineHeight: 21 }}>{i.message}</T>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6, marginTop: 2 }}>
{[when(i.createdAt), i.sentByName, `${i.cards} cartes`].map((chip) => (
<View key={chip} style={{ paddingHorizontal: 8, paddingVertical: 2, borderRadius: 999, backgroundColor: c.surface2 }}>
<T v="muted" style={{ fontSize: 12 }}>{chip}</T>
</View>
))}
</View>
</Card>
))}
</View>
)}
</ScrollView>
);
}