Files
siop2/apps/mobile/app/ot/[id]/cloture.tsx
pr-daaif 28eecc1fb9 feat(r5.3): écrans IA — assistant web, corpus administrable, suggestions OT/mobile
- Contrat (76 opérations) : Document expose inCorpus/indexedAt/chunkCount,
  PATCH /documents/{id}/corpus (ASSETS.edit), POST /assistant/reindex
  (bilan chiffré) ; ci-contract vérifie désormais aussi le client mobile.
- Web : page /assistant (chat sourcé — extraits exacts cités, Ouvrir vers
  PDF authentifié ou fiche OT, avertissement permanent ; refus honnête
  chiffré avec action utile) ; Bibliothèque = corpus (bandeau 09-08,
  statut d'indexation par document, interrupteur d'exclusion PDF,
  Réindexer tout) ; fiche OT : « Décrire pour suggérer » (Appliquer =
  geste humain, liseré « suggéré » retiré au choix manuel).
- Mobile : chips de suggestion dans la clôture (un appui = un champ
  pré-rempli, « réseau requis » hors-ligne — la file R4 n'en dépend pas).
- apps/ai : seuils AI_SEUIL_* configurables par env (CI + calibrage).
- CI e2e : service siop2-ai (embeddeur déterministe, seuils calibrés sur
  mesures : match 0,66 vs bruit 0,11) + parcours R5 Playwright (PDF généré
  xref valide → réindexation → réponse sourcée → refus → suggestion).
- Vérifié : 16/16 Playwright, 78 tests API, 23 pytest, 17 jest-expo ;
  chaîne réelle au vrai modèle ONNX (web 7/7, mobile Expo web 6/6).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 17:26:22 +01:00

274 lines
9.7 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 { router, useLocalSearchParams } from 'expo-router';
import { useState } from 'react';
import { Pressable, ScrollView, Text, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import {
BILAN_FIELD_LABELS,
BILAN_FIELDS,
REQUIRED_BILAN_FIELDS,
type BilanField,
type BilanSuggestion,
type ReportUpsert,
} from '@siop/shared';
import { useQueryClient } from '@tanstack/react-query';
import { useReferenceValues, useSuggestionBilan, useWorkOrder } from '@/api/exploitation';
import { useHorsLigne } from '@/auth/session';
import { BoutonTel, Carte, ChoixTel, EnteteFiche } from '@/composants/ui';
import { enfilerBilan, enfilerTransition } from '@/file/actions';
import { useTokens } from '@/theme/tokens';
/** Écran 3 de la maquette R4 : le bilan codé R2 au pouce — 3 champs requis,
* garde visible et bloquante. Depuis R4.3, bilan et clôture partent EN
* FILE (D1) : hors-ligne, l'OT passe localement à « Terminé (en file) »
* et le serveur tranchera au rejeu (verrou D2 si l'OT a bougé). */
type ChampBilanId =
| 'doorStateId'
| 'cabinPositionId'
| 'anomalyId'
| 'externalCauseId'
| 'actionTakenId'
| 'componentConcernedId';
const CHAMP_VERS_ID: Record<BilanField, ChampBilanId> = {
DOOR_STATE: 'doorStateId',
CABIN_POSITION: 'cabinPositionId',
ANOMALY: 'anomalyId',
EXTERNAL_CAUSE: 'externalCauseId',
ACTION_TAKEN: 'actionTakenId',
COMPONENT_CONCERNED: 'componentConcernedId',
};
const CHAMP_VERS_VALEUR = {
DOOR_STATE: 'doorState',
CABIN_POSITION: 'cabinPosition',
ANOMALY: 'anomaly',
EXTERNAL_CAUSE: 'externalCause',
ACTION_TAKEN: 'actionTaken',
COMPONENT_CONCERNED: 'componentConcerned',
} as const;
export default function PageCloture() {
const t = useTokens();
const horsLigne = useHorsLigne();
const { id } = useLocalSearchParams<{ id: string }>();
const { data: ot } = useWorkOrder(id);
const { data: valeurs } = useReferenceValues();
const queryClient = useQueryClient();
const [choix, setChoix] = useState<Partial<Record<BilanField, string | null>>>({});
if (!ot) return null;
const optionsDe = (champ: BilanField) =>
(valeurs ?? []).filter((v: { field: string; isActive: boolean }) => v.field === champ && v.isActive);
/** Valeur affichée : le choix local s'il existe, sinon le bilan serveur. */
const valeurDe = (champ: BilanField): { id: string; label: string } | null => {
if (champ in choix) {
const vid = choix[champ];
if (!vid) return null;
const v = (valeurs ?? []).find((x) => x.id === vid);
return v ? { id: v.id, label: v.label } : null;
}
return ot.report?.[CHAMP_VERS_VALEUR[champ]] ?? null;
};
const enregistrer = () => {
const corps: ReportUpsert = {};
const labels: Parameters<typeof enfilerBilan>[3] = {};
for (const champ of BILAN_FIELDS) {
if (champ in choix) {
corps[CHAMP_VERS_ID[champ]] = choix[champ] ?? null;
labels[CHAMP_VERS_ID[champ]] = valeurDe(champ);
}
}
enfilerBilan(queryClient, ot, corps, labels);
};
const cloturer = () => {
enregistrer();
enfilerTransition(queryClient, ot, 'DONE');
router.replace(`/ot/${id}`);
};
const manquants = REQUIRED_BILAN_FIELDS.filter((c) => !valeurDe(c));
return (
<SafeAreaView style={{ flex: 1, backgroundColor: t.fond }} edges={['top']}>
<ScrollView contentContainerStyle={{ padding: 14, gap: 10 }}>
<EnteteFiche titre={`Clôturer ${ot.reference}`} />
<CarteSuggestion
horsLigne={horsLigne}
surApplication={(s) => setChoix((c) => ({ ...c, [s.field]: s.valueId }))}
/>
<Carte titre="Bilan d'intervention — requis pour clôturer">
<View style={{ gap: 10 }}>
{[0, 2, 4].map((rang) => (
<View key={rang} style={{ flexDirection: 'row', gap: 8 }}>
{[BILAN_FIELDS[rang]!, BILAN_FIELDS[rang + 1]!].map((champ) => (
<ChoixTel
key={champ}
libelle={BILAN_FIELD_LABELS[champ]}
requis={REQUIRED_BILAN_FIELDS.includes(champ)}
valeur={valeurDe(champ)}
options={optionsDe(champ)}
surChoix={(vid) => setChoix((c) => ({ ...c, [champ]: vid }))}
/>
))}
</View>
))}
</View>
{manquants.length ? (
<Text style={{ color: t.alerte, fontFamily: 'Manrope_600SemiBold', fontSize: 12 }}>
{manquants.map((c) => `« ${BILAN_FIELD_LABELS[c]} »`).join(', ')}{' '}
{manquants.length > 1 ? 'manquent' : 'manque'} la clôture restera bloquée (même garde
que le web).
</Text>
) : null}
</Carte>
<BoutonTel
libelle="Enregistrer le bilan"
variante="contour"
surAppui={() => {
enregistrer();
router.replace(`/ot/${id}`);
}}
/>
<BoutonTel
libelle={
manquants.length
? 'Clôturer (bilan incomplet)'
: horsLigne
? 'Clôturer — partira à la synchro'
: "Clôturer l'intervention"
}
variante={manquants.length ? 'gris' : 'vert'}
desactive={manquants.length > 0}
surAppui={cloturer}
/>
{horsLigne ? (
<Text style={{ color: t.stAttente, fontFamily: 'Manrope_600SemiBold', fontSize: 12 }}>
Hors-ligne : la clôture est enregistrée sur le téléphone et sera rejouée telle quelle
au retour du réseau. Si lOT a changé entre-temps, VOUS trancherez (écran Synchro).
</Text>
) : null}
</ScrollView>
</SafeAreaView>
);
}
/** Écran 4 des maquettes R5 : décrire au pouce → chips suggérées (D1 — un
* appui = un choix humain, les chips ne font que pré-remplir les sélecteurs).
* L'IA est un service serveur : hors-ligne, la suggestion attend le réseau
* — la clôture en file R4, elle, n'en a pas besoin. */
function CarteSuggestion({
horsLigne,
surApplication,
}: {
horsLigne: boolean;
surApplication: (s: BilanSuggestion) => void;
}) {
const t = useTokens();
const suggerer = useSuggestionBilan();
const [description, setDescription] = useState('');
const [appliquees, setAppliquees] = useState<Set<BilanField>>(new Set());
const suggestions = suggerer.data?.suggestions ?? [];
return (
<Carte titre="Décrire pour suggérer (optionnel)">
<TextInput
multiline
value={description}
onChangeText={setDescription}
maxLength={2000}
placeholder="Décrivez la panne et ce que vous avez fait…"
placeholderTextColor={t.encre3}
accessibilityLabel="Décrire pour suggérer"
style={{
minHeight: 64,
borderWidth: 1.5,
borderColor: t.bordureForte,
borderRadius: 9,
backgroundColor: t.surface,
padding: 9,
color: t.encre,
fontFamily: 'Manrope_500Medium',
fontSize: 13,
textAlignVertical: 'top',
}}
/>
<BoutonTel
libelle={
horsLigne
? 'Suggérer — réseau requis'
: suggerer.isPending
? 'Analyse…'
: '✨ Suggérer les codes'
}
variante="contour"
desactive={horsLigne || suggerer.isPending || description.trim().length < 10}
surAppui={() => {
setAppliquees(new Set());
suggerer.mutate(description.trim());
}}
/>
{suggerer.isError ? (
<Text style={{ color: t.danger, fontFamily: 'Manrope_600SemiBold', fontSize: 12 }}>
{suggerer.error.message}
</Text>
) : null}
{suggerer.isSuccess && suggestions.length === 0 ? (
<Text style={{ color: t.encre2, fontFamily: 'Manrope_500Medium', fontSize: 12 }}>
Aucun code assez proche lIA ne devine pas : choisissez dans les sélecteurs.
</Text>
) : null}
{suggestions.length > 0 ? (
<>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6 }}>
{suggestions.map((s) => {
const faite = appliquees.has(s.field);
return (
<Pressable
key={s.field}
accessibilityRole="button"
accessibilityLabel={`Appliquer ${BILAN_FIELD_LABELS[s.field]} : ${s.label}`}
disabled={faite}
onPress={() => {
surApplication(s);
setAppliquees((avant) => new Set([...avant, s.field]));
}}
style={{
flexDirection: 'row',
alignItems: 'center',
gap: 5,
borderWidth: 1.5,
borderColor: t.primaire,
backgroundColor: faite ? t.primaire : t.primaireDoux,
borderRadius: 999,
paddingVertical: 6,
paddingHorizontal: 10,
}}
>
<Text
style={{
color: faite ? '#fff' : t.primaire,
fontFamily: 'Manrope_700Bold',
fontSize: 12,
}}
>
{faite ? '✓' : '✨'} {BILAN_FIELD_LABELS[s.field]} : {s.label}
</Text>
</Pressable>
);
})}
</View>
<Text style={{ color: t.encre3, fontFamily: 'Manrope_500Medium', fontSize: 11 }}>
Rien ne senregistre sans votre geste les chips pré-remplissent les sélecteurs
ci-dessous.
</Text>
</>
) : null}
</Carte>
);
}