MonEspacePro/pro/app/module/[id].tsx
Tony AVERTY 5064421c48 Modules complémentaires personnalisables à 100 %
- Catalogue des modules (src/modules/catalog.ts) : Campagnes, Relance des inactifs,
  Offre d'anniversaire, Avis Google, Parrainage, Statistiques & export, Marque blanche
- Chaque formule liste ses modules ; l'admin peut ajouter ou retirer un module sur mesure
- Tous les textes (messages, titres de notification, libellés des cartes et des pages)
  et tous les réglages (délais, heures d'envoi, plafonds, points) sont modifiables
- Réglages stockés en JSON par magasin (Store.modules / moduleOverrides),
  migration 2026-10-08-modules.sql (reprise des réglages existants)
- API générique admin et gérant : /modules, /modules/:id, /modules/:id/override
- Admin : onglet Modules (formulaires générés), formules avec modules inclus
- App Pro : liste des modules et écran de réglages générique
- Site : modules inclus sur chaque formule et tableau comparatif sur la page Tarif

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:04:25 +02:00

153 lines
6.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Switch, TextInput, View } from 'react-native';
import { router, Stack, useFocusEffect, useLocalSearchParams } from 'expo-router';
import { api } from '../../src/api';
import { describe } from '../../src/errors';
import { FieldDef, ModuleInfo, Value } from '../../src/modules';
import { Banner, Button, Card, T } from '../../src/ui';
import { font, useColors } from '../../src/theme';
function Field({ f, value, onChange }: { f: FieldDef; value: Value; onChange: (v: Value) => void }) {
const c = useColors();
const input = { borderWidth: 1, borderColor: c.border, borderRadius: 14, padding: 14, backgroundColor: c.surface, color: c.text, fontFamily: font.regular, fontSize: 16 } as const;
const help = [f.help, 'variables' in f && f.variables?.length ? `Variables : ${f.variables.join(' ')}` : null].filter(Boolean).join(' ');
if (f.type === 'boolean') {
return (
<Card style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16, gap: 12 }}>
<View style={{ flex: 1 }}>
<T v="label">{f.label}</T>
{!!f.help && <T v="muted" style={{ fontSize: 13 }}>{f.help}</T>}
</View>
<Switch value={!!value} onValueChange={onChange} accessibilityLabel={f.label} />
</Card>
);
}
if (f.type === 'int' || f.type === 'hour') {
const n = Number(value);
const set = (v: number) => onChange(Math.max(f.min, Math.min(f.max, v)));
const btn = (d: number) => (
<Pressable
accessibilityRole="button"
accessibilityLabel={`${f.label} : ${d > 0 ? 'plus' : 'moins'}`}
onPress={() => set(n + d)}
style={{ width: 44, height: 44, borderRadius: 22, borderWidth: 1, borderColor: c.border, backgroundColor: c.surface, alignItems: 'center', justifyContent: 'center' }}
>
<T style={{ fontFamily: font.bold, fontSize: 20 }}>{d > 0 ? '+' : '−'}</T>
</Pressable>
);
return (
<View style={{ gap: 6 }}>
<T v="label">{f.label}</T>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
{btn(-1)}
<TextInput
value={String(n)}
onChangeText={(t) => set(Math.floor(Number(t.replace(/\D/g, '')) || 0))}
keyboardType="number-pad"
accessibilityLabel={f.label}
style={{ ...input, width: 76, textAlign: 'center', paddingVertical: 10 }}
/>
{btn(1)}
<T v="muted" style={{ flex: 1 }}>{f.type === 'hour' ? 'h' : f.unit}</T>
</View>
{!!help && <T v="muted" style={{ fontSize: 13 }}>{help}</T>}
</View>
);
}
const t = f as Extract<FieldDef, { maxLength: number }>;
const text = String(value ?? '');
return (
<View style={{ gap: 6 }}>
<T v="label">{t.label}</T>
<TextInput
value={text}
onChangeText={onChange}
multiline={t.type === 'textarea'}
maxLength={t.maxLength}
autoCapitalize={t.type === 'url' ? 'none' : 'sentences'}
autoCorrect={t.type !== 'url'}
keyboardType={t.type === 'url' ? 'url' : 'default'}
accessibilityLabel={t.label}
style={{ ...input, ...(t.type === 'textarea' && { minHeight: 90, textAlignVertical: 'top' as const }) }}
/>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', gap: 8 }}>
<T v="muted" style={{ fontSize: 13, flex: 1 }}>{help}</T>
<T v="muted" style={{ fontSize: 12 }}>{text.length}/{t.maxLength}</T>
</View>
{t.type !== 'url' && text !== t.default && (
<Pressable accessibilityRole="button" onPress={() => onChange(t.default)}>
<T style={{ color: c.primary, fontSize: 14 }}>Remettre le texte par défaut</T>
</Pressable>
)}
</View>
);
}
/** Réglages complets d'un module (gérants). */
export default function ModuleScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const [m, setM] = useState<ModuleInfo | null>(null);
const [values, setValues] = useState<Record<string, Value>>({});
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const apply = (next: ModuleInfo) => {
setM(next);
setValues(next.config);
};
useFocusEffect(
useCallback(() => {
api.get<ModuleInfo>(`/api/staff/modules/${id}`).then(apply).catch((e) => setError(describe(e).detail));
}, [id]),
);
async function save() {
setBusy(true);
setError(null);
setSaved(false);
try {
apply(await api.put<ModuleInfo>(`/api/staff/modules/${id}`, values));
setSaved(true);
} catch (e) {
setError(describe(e).detail);
} finally {
setBusy(false);
}
}
if (!m) return <View style={{ padding: 20 }}>{error ? <Banner tone="error">{error}</Banner> : <T v="muted">Chargement…</T>}</View>;
const dirty = JSON.stringify(values) !== JSON.stringify(m.config);
return (
<ScrollView contentContainerStyle={{ padding: 20, gap: 16 }} keyboardShouldPersistTaps="handled">
<Stack.Screen options={{ title: m.name }} />
{error && <Banner tone="error">{error}</Banner>}
{saved && <Banner tone="ok">Réglages enregistrés.</Banner>}
{!m.available && <Banner tone="warn">Ce module n'est pas inclus dans votre formule. Contactez MonEspacePro pour l'ajouter.</Banner>}
<T v="muted">{m.description}</T>
{m.available && m.config.enabled && m.id === 'campaigns' && <Button label="Envoyer une campagne" onPress={() => router.push('/campaigns')} />}
{m.available && m.config.enabled && m.id === 'stats' && <Button label="Voir les statistiques" onPress={() => router.push('/stats')} />}
<Field f={{ key: 'enabled', type: 'boolean', label: 'Module activé', default: false }} value={values.enabled} onChange={(v) => setValues({ ...values, enabled: v })} />
{m.fields.map((f) => (
<Field key={f.key} f={f} value={values[f.key]} onChange={(v) => setValues({ ...values, [f.key]: v })} />
))}
<Button label="Enregistrer" onPress={save} loading={busy} disabled={!dirty} />
{m.stats && (
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 12 }}>
{Object.entries(m.stats).map(([k, v]) => (
<Card key={k} style={{ width: '47%', flexGrow: 1, padding: 14, gap: 2 }}>
<T style={{ fontFamily: font.extrabold, fontSize: 22 }}>{v ?? '—'}</T>
<T v="muted" style={{ fontSize: 13 }}>{k}</T>
</Card>
))}
</View>
)}
</ScrollView>
);
}