mirror of
https://github.com/siop-spelev/siop2.git
synced 2026-08-08 20:51:53 +00:00
feat(r4.3): file d'écriture, verrou optimiste D2, Synchro & conflits
Serveur : updatedAt exposé au détail OT ; baseUpdatedAt optionnel sur transition/coche/bilan → 409 « Conflit de version » contextualisé (qui, quand) ; toute écriture secondaire (coche, bilan, commentaire, conso, MO) fait avancer la version — sans version fournie, le web est inchangé. ADR-003 : sécurité & protocole de routage mobile (qui vit où sur l'appareil, purge complète à la déconnexion — correctif réel : la file et le cache persisté survivaient au logout). Mobile : file persistée AsyncStorage rejouée dans l'ordre — succès → propagation de la version fraîche aux saisies restantes du même OT (nos écritures ne se conflictent pas entre elles, un écart étranger reste détecté) ; coupure → tout attend ; refus → CONFLIT, la file s'arrête, l'humain tranche (voir l'OT / rejouer sur version à jour / abandonner). Transitions, coches, bilan et photos (D5, compressées ~1600 px) passent par la file avec patch optimiste du cache ; écran Synchro (badge tabbar ambre/rouge) ; préchargement parc + référentiels (le bilan hors-ligne a ses vocabulaires). Recette « mode avion » 13/13 en Expo web piloté : gestes hors-ligne → 3 en file → modification concurrente de Salma → conflit tranché → serveur Terminé avec bilan. 17 tests jest-expo, 74 tests API. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -34,6 +34,18 @@ export function useAsset(id: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export function useDocumentsOT(workOrderId: string) {
|
||||
return useQuery({
|
||||
queryKey: ['documents', workOrderId],
|
||||
queryFn: async () =>
|
||||
(
|
||||
await unwrap(
|
||||
await api.GET('/documents', { params: { query: { workOrderId } } }),
|
||||
)
|
||||
).documents,
|
||||
});
|
||||
}
|
||||
|
||||
export function useReferenceValues() {
|
||||
return useQuery({
|
||||
queryKey: ['reference-values'],
|
||||
|
||||
8
apps/mobile/src/api/schema.d.ts
vendored
8
apps/mobile/src/api/schema.d.ts
vendored
@@ -1776,6 +1776,8 @@ export interface components {
|
||||
};
|
||||
allowedTransitions: ("OPEN" | "IN_PROGRESS" | "ON_HOLD" | "DONE" | "CANCELLED")[];
|
||||
closureBlockers: string[];
|
||||
/** Format: date-time */
|
||||
updatedAt: string;
|
||||
};
|
||||
ConsumePart: {
|
||||
/** Format: uuid */
|
||||
@@ -1945,6 +1947,8 @@ export interface components {
|
||||
/** @enum {string} */
|
||||
to: "OPEN" | "IN_PROGRESS" | "ON_HOLD" | "DONE" | "CANCELLED";
|
||||
comment?: string;
|
||||
/** Format: date-time */
|
||||
baseUpdatedAt?: string;
|
||||
};
|
||||
CommentCreate: {
|
||||
message: string;
|
||||
@@ -1960,6 +1964,8 @@ export interface components {
|
||||
externalCauseId?: string | null;
|
||||
actionTakenId?: string | null;
|
||||
componentConcernedId?: string | null;
|
||||
/** Format: date-time */
|
||||
baseUpdatedAt?: string;
|
||||
};
|
||||
ChecklistItem: {
|
||||
/** Format: uuid */
|
||||
@@ -1978,6 +1984,8 @@ export interface components {
|
||||
ChecklistPatch: {
|
||||
/** @enum {string} */
|
||||
state: "PENDING" | "DONE" | "NA";
|
||||
/** Format: date-time */
|
||||
baseUpdatedAt?: string;
|
||||
};
|
||||
RequestsResponse: {
|
||||
requests: {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { createContext, useContext, type ReactNode } from 'react';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { api, unwrap } from '@/api/client';
|
||||
import { ecrireJeton, effacerJeton } from '@/api/jeton';
|
||||
import { viderFile } from '@/file/store';
|
||||
|
||||
/** Session mobile — mêmes règles que le web : le sélecteur démo n'existe
|
||||
* que si l'API répond (ADR-002 : 404 sinon, une seule source de vérité). */
|
||||
@@ -57,8 +59,12 @@ export function useDemoLogin() {
|
||||
export function useLogout() {
|
||||
const queryClient = useQueryClient();
|
||||
return async () => {
|
||||
// Rien ne survit à la session sur l'appareil : jeton (trousseau), file
|
||||
// d'écriture, cache OT persisté (loi 09-08 — minimisation).
|
||||
await effacerJeton();
|
||||
viderFile();
|
||||
queryClient.clear();
|
||||
await AsyncStorage.removeItem('siop.cache');
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
98
apps/mobile/src/composants/carte-photos.tsx
Normal file
98
apps/mobile/src/composants/carte-photos.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import * as ImageManipulator from 'expo-image-manipulator';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import { Alert, Pressable, Text, View } from 'react-native';
|
||||
import type { WorkOrderDetail } from '@siop/shared';
|
||||
import { useDocumentsOT } from '@/api/exploitation';
|
||||
import { Carte } from '@/composants/ui';
|
||||
import { enfilerPhoto } from '@/file/actions';
|
||||
import { useFile } from '@/file/store';
|
||||
import { useTokens } from '@/theme/tokens';
|
||||
|
||||
/** Photos d'intervention (D5) : compressées côté app (~1 600 px) puis mises
|
||||
* EN FILE comme le reste — rattachées à l'OT dans la bibliothèque R3.
|
||||
* Ni audio ni géolocalisation en R4 (loi 09-08, minimisation). */
|
||||
export function CartePhotos({ ot }: { ot: WorkOrderDetail }) {
|
||||
const t = useTokens();
|
||||
const queryClient = useQueryClient();
|
||||
const file = useFile();
|
||||
const { data: documents } = useDocumentsOT(ot.id);
|
||||
|
||||
const photosServeur = (documents ?? []).filter((d) => d.contentType.startsWith('image/'));
|
||||
const photosEnFile = file.filter((s) => s.otId === ot.id && s.type === 'PHOTO');
|
||||
|
||||
const prendre = async () => {
|
||||
const resultat = await ImagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ['images'],
|
||||
quality: 0.9,
|
||||
});
|
||||
const image = resultat.assets?.[0];
|
||||
if (!image) return;
|
||||
try {
|
||||
// Compression D5 : jamais un original de 12 Mo dans la file.
|
||||
const contexte = ImageManipulator.ImageManipulator.manipulate(image.uri);
|
||||
if (image.width > 1600) contexte.resize({ width: 1600 });
|
||||
const rendu = await contexte.renderAsync();
|
||||
const sauve = await rendu.saveAsync({
|
||||
compress: 0.7,
|
||||
format: ImageManipulator.SaveFormat.JPEG,
|
||||
});
|
||||
enfilerPhoto(queryClient, ot, {
|
||||
uri: sauve.uri,
|
||||
nom: `intervention-${ot.reference}-${Date.now().toString(36)}.jpg`,
|
||||
mime: 'image/jpeg',
|
||||
});
|
||||
} catch (e) {
|
||||
Alert.alert('Photo impossible', e instanceof Error ? e.message : 'Erreur inconnue');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Carte titre={`Photos (${photosServeur.length + photosEnFile.length})`}>
|
||||
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 8 }}>
|
||||
{photosServeur.map((d) => (
|
||||
<View key={d.id} style={vignette(t.surface2, t.bordure)}>
|
||||
<Text style={{ fontSize: 18 }}>🖼</Text>
|
||||
</View>
|
||||
))}
|
||||
{photosEnFile.map((s) => (
|
||||
<View key={s.id} style={vignette(t.stAttenteFond, t.stAttente)}>
|
||||
<Text style={{ fontSize: 18 }}>🖼</Text>
|
||||
<Text
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: 2,
|
||||
fontFamily: 'Manrope_800ExtraBold',
|
||||
fontSize: 8,
|
||||
color: t.stAttente,
|
||||
}}
|
||||
>
|
||||
en file
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Ajouter une photo"
|
||||
onPress={() => void prendre()}
|
||||
style={vignette('transparent', t.bordureForte, true)}
|
||||
>
|
||||
<Text style={{ fontSize: 22, color: t.primaire }}>+</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</Carte>
|
||||
);
|
||||
}
|
||||
|
||||
const vignette = (fond: string, bordure: string, pointille = false) =>
|
||||
({
|
||||
width: 56,
|
||||
height: 56,
|
||||
borderRadius: 9,
|
||||
backgroundColor: fond,
|
||||
borderWidth: 1.5,
|
||||
borderColor: bordure,
|
||||
borderStyle: pointille ? ('dashed' as const) : ('solid' as const),
|
||||
alignItems: 'center' as const,
|
||||
justifyContent: 'center' as const,
|
||||
}) as const;
|
||||
125
apps/mobile/src/file/actions.ts
Normal file
125
apps/mobile/src/file/actions.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
WORK_ORDER_STATUS_LABELS,
|
||||
WORK_ORDER_TRANSITIONS,
|
||||
type ChecklistState,
|
||||
type ReportUpsert,
|
||||
type WorkOrderDetail,
|
||||
type WorkOrderStatus,
|
||||
} from '@siop/shared';
|
||||
import { enfiler, lireFile } from './store';
|
||||
import { rejouer } from './synchro';
|
||||
|
||||
/** Chaque geste terrain = une saisie en file + un patch OPTIMISTE du cache
|
||||
* (le technicien voit son travail tout de suite, même en mode avion — le
|
||||
* cache persisté garde ce patch après redémarrage). En ligne, la file se
|
||||
* vide dans la foulée : le comportement R4.2 est conservé. */
|
||||
|
||||
function patchDetail(
|
||||
queryClient: QueryClient,
|
||||
otId: string,
|
||||
patch: (ot: WorkOrderDetail) => WorkOrderDetail,
|
||||
): void {
|
||||
queryClient.setQueryData<WorkOrderDetail>(['work-orders', otId], (courant) =>
|
||||
courant ? patch(courant) : courant,
|
||||
);
|
||||
}
|
||||
|
||||
export function enfilerTransition(
|
||||
queryClient: QueryClient,
|
||||
ot: WorkOrderDetail,
|
||||
to: WorkOrderStatus,
|
||||
): void {
|
||||
enfiler({
|
||||
type: 'TRANSITION',
|
||||
otId: ot.id,
|
||||
otReference: ot.reference,
|
||||
libelle:
|
||||
to === 'DONE' ? 'Clôture de l’intervention' : `Passage à « ${WORK_ORDER_STATUS_LABELS[to]} »`,
|
||||
baseUpdatedAt: ot.updatedAt,
|
||||
payload: { to },
|
||||
});
|
||||
patchDetail(queryClient, ot.id, (c) => ({
|
||||
...c,
|
||||
status: to,
|
||||
allowedTransitions: WORK_ORDER_TRANSITIONS[to],
|
||||
}));
|
||||
void rejouer(queryClient);
|
||||
}
|
||||
|
||||
export function enfilerCoche(
|
||||
queryClient: QueryClient,
|
||||
ot: WorkOrderDetail,
|
||||
item: { id: string; label: string },
|
||||
state: ChecklistState,
|
||||
): void {
|
||||
enfiler({
|
||||
type: 'COCHE',
|
||||
otId: ot.id,
|
||||
otReference: ot.reference,
|
||||
libelle: `Coche « ${item.label} » → ${state === 'DONE' ? 'fait' : state === 'NA' ? 'N/A' : 'à faire'}`,
|
||||
baseUpdatedAt: ot.updatedAt,
|
||||
payload: { itemId: item.id, state },
|
||||
});
|
||||
patchDetail(queryClient, ot.id, (c) => ({
|
||||
...c,
|
||||
checklist: c.checklist.map((i) => (i.id === item.id ? { ...i, state } : i)),
|
||||
}));
|
||||
void rejouer(queryClient);
|
||||
}
|
||||
|
||||
export function enfilerBilan(
|
||||
queryClient: QueryClient,
|
||||
ot: WorkOrderDetail,
|
||||
corps: Omit<ReportUpsert, 'baseUpdatedAt'>,
|
||||
labels: Partial<Record<keyof ReportUpsert, { id: string; label: string } | null>>,
|
||||
): void {
|
||||
enfiler({
|
||||
type: 'BILAN',
|
||||
otId: ot.id,
|
||||
otReference: ot.reference,
|
||||
libelle: 'Bilan d’intervention codé',
|
||||
baseUpdatedAt: ot.updatedAt,
|
||||
payload: corps,
|
||||
});
|
||||
patchDetail(queryClient, ot.id, (c) => ({
|
||||
...c,
|
||||
report: {
|
||||
note: c.report?.note ?? null,
|
||||
doorState: labels.doorStateId !== undefined ? (labels.doorStateId ?? null) : (c.report?.doorState ?? null),
|
||||
cabinPosition:
|
||||
labels.cabinPositionId !== undefined ? (labels.cabinPositionId ?? null) : (c.report?.cabinPosition ?? null),
|
||||
anomaly: labels.anomalyId !== undefined ? (labels.anomalyId ?? null) : (c.report?.anomaly ?? null),
|
||||
externalCause:
|
||||
labels.externalCauseId !== undefined ? (labels.externalCauseId ?? null) : (c.report?.externalCause ?? null),
|
||||
actionTaken:
|
||||
labels.actionTakenId !== undefined ? (labels.actionTakenId ?? null) : (c.report?.actionTaken ?? null),
|
||||
componentConcerned:
|
||||
labels.componentConcernedId !== undefined
|
||||
? (labels.componentConcernedId ?? null)
|
||||
: (c.report?.componentConcerned ?? null),
|
||||
},
|
||||
}));
|
||||
void rejouer(queryClient);
|
||||
}
|
||||
|
||||
export function enfilerPhoto(
|
||||
queryClient: QueryClient,
|
||||
ot: WorkOrderDetail,
|
||||
fichier: { uri: string; nom: string; mime: string },
|
||||
): void {
|
||||
enfiler({
|
||||
type: 'PHOTO',
|
||||
otId: ot.id,
|
||||
otReference: ot.reference,
|
||||
libelle: `Photo — ${fichier.nom}`,
|
||||
baseUpdatedAt: ot.updatedAt,
|
||||
payload: fichier,
|
||||
});
|
||||
void rejouer(queryClient);
|
||||
}
|
||||
|
||||
/** Ce que la file porte encore pour cet OT — chips « en file » des écrans. */
|
||||
export function saisiesPour(otId: string) {
|
||||
return lireFile().filter((s) => s.otId === otId);
|
||||
}
|
||||
93
apps/mobile/src/file/store.ts
Normal file
93
apps/mobile/src/file/store.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import type { ChecklistState, ReportUpsert, WorkOrderStatus } from '@siop/shared';
|
||||
|
||||
/** La file d'écriture (D1) : chaque geste hors-ligne devient une saisie
|
||||
* datée, persistée dans AsyncStorage — elle survit au redémarrage — et
|
||||
* rejouée DANS L'ORDRE au retour du réseau. Chaque saisie porte la version
|
||||
* de l'OT lue au moment du geste (D2, verrou optimiste). */
|
||||
|
||||
export type Saisie = {
|
||||
id: string;
|
||||
creeA: string; // ISO — affiché à l'écran Synchro
|
||||
otId: string;
|
||||
otReference: string;
|
||||
libelle: string; // « Coche “Jeu des coulisseaux” »
|
||||
baseUpdatedAt: string; // version lue (D2)
|
||||
statut: 'EN_ATTENTE' | 'ENVOI' | 'CONFLIT';
|
||||
erreur?: string; // message du 409 / refus métier — montré tel quel
|
||||
} & (
|
||||
| { type: 'TRANSITION'; payload: { to: WorkOrderStatus } }
|
||||
| { type: 'COCHE'; payload: { itemId: string; state: ChecklistState } }
|
||||
| { type: 'BILAN'; payload: Omit<ReportUpsert, 'baseUpdatedAt'> }
|
||||
| { type: 'PHOTO'; payload: { uri: string; nom: string; mime: string } }
|
||||
);
|
||||
|
||||
const CLE = 'siop.file.v1';
|
||||
let file: Saisie[] = [];
|
||||
const abonnes = new Set<() => void>();
|
||||
|
||||
function notifier(): void {
|
||||
for (const a of abonnes) a();
|
||||
void AsyncStorage.setItem(CLE, JSON.stringify(file));
|
||||
}
|
||||
|
||||
/** À l'ouverture de l'app : la file survit au redémarrage (D1). */
|
||||
export async function chargerFile(): Promise<void> {
|
||||
const brut = await AsyncStorage.getItem(CLE);
|
||||
if (brut) {
|
||||
// Un ENVOI interrompu par un crash redevient EN_ATTENTE (rejouable).
|
||||
file = (JSON.parse(brut) as Saisie[]).map((s) =>
|
||||
s.statut === 'ENVOI' ? { ...s, statut: 'EN_ATTENTE' } : s,
|
||||
);
|
||||
for (const a of abonnes) a();
|
||||
}
|
||||
}
|
||||
|
||||
export const lireFile = (): Saisie[] => file;
|
||||
|
||||
export function enfiler(saisie: Omit<Saisie, 'id' | 'creeA' | 'statut'>): Saisie {
|
||||
const complete = {
|
||||
...saisie,
|
||||
id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
creeA: new Date().toISOString(),
|
||||
statut: 'EN_ATTENTE',
|
||||
} as Saisie;
|
||||
file = [...file, complete];
|
||||
notifier();
|
||||
return complete;
|
||||
}
|
||||
|
||||
export function majSaisie(id: string, patch: Partial<Pick<Saisie, 'statut' | 'erreur' | 'baseUpdatedAt'>>): void {
|
||||
file = file.map((s) => (s.id === id ? ({ ...s, ...patch } as Saisie) : s));
|
||||
notifier();
|
||||
}
|
||||
|
||||
export function retirer(id: string): void {
|
||||
file = file.filter((s) => s.id !== id);
|
||||
notifier();
|
||||
}
|
||||
|
||||
export function useFile(): Saisie[] {
|
||||
return useSyncExternalStore(
|
||||
(cb) => {
|
||||
abonnes.add(cb);
|
||||
return () => abonnes.delete(cb);
|
||||
},
|
||||
lireFile,
|
||||
lireFile,
|
||||
);
|
||||
}
|
||||
|
||||
/** Déconnexion : la file appartient à la SESSION — on la purge (sécurité :
|
||||
* un autre compte sur le même téléphone ne doit jamais rejouer les saisies
|
||||
* du précédent), avec sa persistance. */
|
||||
export function viderFile(): void {
|
||||
file = [];
|
||||
notifier();
|
||||
}
|
||||
|
||||
/** Réservé aux tests : repartir d'une file vide (sans persistance). */
|
||||
export function _viderPourTests(): void {
|
||||
file = [];
|
||||
}
|
||||
93
apps/mobile/src/file/synchro.test.ts
Normal file
93
apps/mobile/src/file/synchro.test.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
import { enfiler, lireFile, retirer, _viderPourTests, type Saisie } from './store';
|
||||
import { rejouer, type ResultatEnvoi } from './synchro';
|
||||
|
||||
/** Le contrat D1/D2 de la file, testé sans réseau : rejeu DANS L'ORDRE,
|
||||
* arrêt sur conflit (l'humain tranche), reprise après coupure. */
|
||||
|
||||
const qc = new QueryClient();
|
||||
|
||||
const saisie = (libelle: string): Saisie =>
|
||||
enfiler({
|
||||
type: 'TRANSITION',
|
||||
otId: 'ot-1',
|
||||
otReference: 'OT-TEST',
|
||||
libelle,
|
||||
baseUpdatedAt: '2026-07-17T10:00:00.000Z',
|
||||
payload: { to: 'IN_PROGRESS' },
|
||||
}) && lireFile().at(-1)!;
|
||||
|
||||
beforeEach(() => _viderPourTests());
|
||||
|
||||
describe('rejouer (file D1/D2)', () => {
|
||||
it('rejoue dans l’ordre et vide la file quand tout passe', async () => {
|
||||
saisie('a');
|
||||
saisie('b');
|
||||
const envoyes: string[] = [];
|
||||
await rejouer(qc, async (s) => {
|
||||
envoyes.push(s.libelle);
|
||||
return { ok: true };
|
||||
});
|
||||
expect(envoyes).toEqual(['a', 'b']);
|
||||
expect(lireFile()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('conflit : la saisie passe en CONFLIT et la file S’ARRÊTE là — rien n’est perdu', async () => {
|
||||
saisie('a');
|
||||
saisie('b');
|
||||
saisie('c');
|
||||
const envoyer = async (s: Saisie): Promise<ResultatEnvoi> =>
|
||||
s.libelle === 'b'
|
||||
? { ok: false, reseau: false, message: 'Conflit de version : modifié par Salma à 14 h 38' }
|
||||
: { ok: true };
|
||||
await rejouer(qc, envoyer);
|
||||
const file = lireFile();
|
||||
expect(file.map((s) => [s.libelle, s.statut])).toEqual([
|
||||
['b', 'CONFLIT'],
|
||||
['c', 'EN_ATTENTE'], // derrière le conflit : on attend l'humain
|
||||
]);
|
||||
expect(file[0]!.erreur).toContain('Salma');
|
||||
});
|
||||
|
||||
it('coupure réseau : tout reste EN_ATTENTE, rejouable au retour', async () => {
|
||||
saisie('a');
|
||||
saisie('b');
|
||||
await rejouer(qc, async () => ({ ok: false, reseau: true, message: 'Réseau indisponible' }));
|
||||
expect(lireFile().map((s) => s.statut)).toEqual(['EN_ATTENTE', 'EN_ATTENTE']);
|
||||
// le réseau revient
|
||||
await rejouer(qc, async () => ({ ok: true }));
|
||||
expect(lireFile()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('après « abandonner » le conflit, le reste de la file repart', async () => {
|
||||
saisie('a');
|
||||
saisie('b');
|
||||
await rejouer(qc, async (s) =>
|
||||
s.libelle === 'a' ? { ok: false, reseau: false, message: 'refus métier' } : { ok: true },
|
||||
);
|
||||
expect(lireFile()).toHaveLength(2);
|
||||
retirer(lireFile()[0]!.id); // l'humain abandonne la saisie en conflit
|
||||
await rejouer(qc, async () => ({ ok: true }));
|
||||
expect(lireFile()).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('propagation de version (nos écritures ne se conflictent pas entre elles)', () => {
|
||||
it('au succès, la version fraîche se propage aux saisies restantes du même OT', async () => {
|
||||
saisie('a');
|
||||
saisie('b');
|
||||
await rejouer(qc, async (s) =>
|
||||
s.libelle === 'a' ? { ok: true, nouvelleVersion: '2026-07-17T11:00:00.000Z' } : { ok: true },
|
||||
);
|
||||
// b a été envoyée après propagation — vérifions via un rejeu espion
|
||||
_viderPourTests();
|
||||
saisie('c');
|
||||
saisie('d');
|
||||
const basesVues: string[] = [];
|
||||
await rejouer(qc, async (s) => {
|
||||
basesVues.push(s.baseUpdatedAt);
|
||||
return { ok: true, nouvelleVersion: 'V-FRAICHE' };
|
||||
});
|
||||
expect(basesVues).toEqual(['2026-07-17T10:00:00.000Z', 'V-FRAICHE']);
|
||||
});
|
||||
});
|
||||
160
apps/mobile/src/file/synchro.ts
Normal file
160
apps/mobile/src/file/synchro.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/api/client';
|
||||
import { lireJeton } from '@/api/jeton';
|
||||
import { API_URL } from '@/api/client';
|
||||
import { lireFile, majSaisie, retirer, type Saisie } from './store';
|
||||
|
||||
/** Rejeu de la file (D1/D2) : dans l'ordre, une saisie à la fois.
|
||||
* - succès → la saisie sort de la file ;
|
||||
* - coupure réseau → tout reste EN_ATTENTE, on réessaiera ;
|
||||
* - refus (409 verrou, garde métier) → la saisie passe en CONFLIT et la
|
||||
* file S'ARRÊTE LÀ : l'humain tranche à l'écran Synchro. */
|
||||
|
||||
export type ResultatEnvoi =
|
||||
| { ok: true; nouvelleVersion?: string }
|
||||
| { ok: false; reseau: boolean; message: string };
|
||||
|
||||
export async function envoyerSaisie(s: Saisie): Promise<ResultatEnvoi> {
|
||||
try {
|
||||
let status: number;
|
||||
let message = '';
|
||||
let nouvelleVersion: string | undefined;
|
||||
if (s.type === 'TRANSITION') {
|
||||
const res = await api.POST('/work-orders/{id}/transition', {
|
||||
params: { path: { id: s.otId } },
|
||||
body: { to: s.payload.to, baseUpdatedAt: s.baseUpdatedAt },
|
||||
});
|
||||
status = res.response.status;
|
||||
message = messageDe(res.error);
|
||||
nouvelleVersion = res.data?.updatedAt;
|
||||
} else if (s.type === 'COCHE') {
|
||||
const res = await api.PATCH('/work-orders/{id}/checklist/{itemId}', {
|
||||
params: { path: { id: s.otId, itemId: s.payload.itemId } },
|
||||
body: { state: s.payload.state, baseUpdatedAt: s.baseUpdatedAt },
|
||||
});
|
||||
status = res.response.status;
|
||||
message = messageDe(res.error);
|
||||
} else if (s.type === 'BILAN') {
|
||||
const res = await api.PUT('/work-orders/{id}/report', {
|
||||
params: { path: { id: s.otId } },
|
||||
body: { ...s.payload, baseUpdatedAt: s.baseUpdatedAt },
|
||||
});
|
||||
status = res.response.status;
|
||||
message = messageDe(res.error);
|
||||
nouvelleVersion = res.data?.updatedAt;
|
||||
} else {
|
||||
// PHOTO — multipart hors client typé (D5) : fichier compressé en file.
|
||||
const form = new FormData();
|
||||
form.append('kind', 'PHOTO');
|
||||
form.append('workOrderId', s.otId);
|
||||
if (s.payload.uri.startsWith('http') || s.payload.uri.startsWith('blob:') || s.payload.uri.startsWith('data:')) {
|
||||
const blob = await (await fetch(s.payload.uri)).blob();
|
||||
form.append('file', new File([blob], s.payload.nom, { type: s.payload.mime }));
|
||||
} else {
|
||||
// URI de fichier natif : React Native sait téléverser {uri, name, type}
|
||||
form.append('file', {
|
||||
uri: s.payload.uri,
|
||||
name: s.payload.nom,
|
||||
type: s.payload.mime,
|
||||
} as unknown as Blob);
|
||||
}
|
||||
const jeton = await lireJeton();
|
||||
const res = await fetch(`${API_URL}/documents`, {
|
||||
method: 'POST',
|
||||
headers: jeton ? { Authorization: `Bearer ${jeton}` } : undefined,
|
||||
body: form,
|
||||
});
|
||||
status = res.status;
|
||||
if (!res.ok) {
|
||||
const corps = (await res.json().catch(() => null)) as { message?: string } | null;
|
||||
message = corps?.message ?? `Téléversement refusé (${res.status})`;
|
||||
}
|
||||
}
|
||||
if (status < 400) {
|
||||
// Coche/photo ne renvoient pas le détail : on relit la version pour
|
||||
// que les saisies suivantes du lot ne se heurtent pas à NOS écritures.
|
||||
if (!nouvelleVersion) {
|
||||
const frais = await api.GET('/work-orders/{id}', { params: { path: { id: s.otId } } });
|
||||
nouvelleVersion = frais.data?.updatedAt;
|
||||
}
|
||||
return { ok: true, nouvelleVersion };
|
||||
}
|
||||
return { ok: false, reseau: false, message: message || `Refus (${status})` };
|
||||
} catch {
|
||||
return { ok: false, reseau: true, message: 'Réseau indisponible' };
|
||||
}
|
||||
}
|
||||
|
||||
function messageDe(erreur: unknown): string {
|
||||
return erreur && typeof erreur === 'object' && 'message' in erreur
|
||||
? String((erreur as { message: unknown }).message)
|
||||
: '';
|
||||
}
|
||||
|
||||
let enCours = false;
|
||||
|
||||
export async function rejouer(
|
||||
queryClient: QueryClient,
|
||||
envoyer: (s: Saisie) => Promise<ResultatEnvoi> = envoyerSaisie,
|
||||
): Promise<void> {
|
||||
if (enCours) return;
|
||||
enCours = true;
|
||||
try {
|
||||
for (;;) {
|
||||
const suivante = lireFile().find((s) => s.statut === 'EN_ATTENTE');
|
||||
if (!suivante) break;
|
||||
// Un conflit plus ancien barre la route : l'ordre est la promesse D1.
|
||||
const conflitAvant = lireFile().some(
|
||||
(s) => s.statut === 'CONFLIT' && s.creeA <= suivante.creeA,
|
||||
);
|
||||
if (conflitAvant) break;
|
||||
|
||||
majSaisie(suivante.id, { statut: 'ENVOI' });
|
||||
const resultat = await envoyer(suivante);
|
||||
if (resultat.ok) {
|
||||
retirer(suivante.id);
|
||||
// Notre propre écriture a fait avancer la version : les saisies
|
||||
// restantes du même OT repartent de là (un écart ÉTRANGER ultérieur
|
||||
// restera détecté par le verrou).
|
||||
if (resultat.nouvelleVersion) {
|
||||
for (const s of lireFile()) {
|
||||
if (s.otId === suivante.otId && s.statut === 'EN_ATTENTE') {
|
||||
majSaisie(s.id, { baseUpdatedAt: resultat.nouvelleVersion });
|
||||
}
|
||||
}
|
||||
}
|
||||
await queryClient.invalidateQueries({ queryKey: ['work-orders'] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['documents'] });
|
||||
} else if (resultat.reseau) {
|
||||
majSaisie(suivante.id, { statut: 'EN_ATTENTE' });
|
||||
break; // le réseau reviendra — rien n'est perdu
|
||||
} else {
|
||||
majSaisie(suivante.id, { statut: 'CONFLIT', erreur: resultat.message });
|
||||
break; // l'humain tranche (D2)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
enCours = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Résolutions du conflit (maquette écran 7). */
|
||||
export async function rejouerSurVersionAJour(
|
||||
saisieId: string,
|
||||
queryClient: QueryClient,
|
||||
): Promise<void> {
|
||||
const saisie = lireFile().find((s) => s.id === saisieId);
|
||||
if (!saisie) return;
|
||||
const frais = await api.GET('/work-orders/{id}', { params: { path: { id: saisie.otId } } });
|
||||
if (frais.data) {
|
||||
majSaisie(saisieId, { statut: 'EN_ATTENTE', baseUpdatedAt: frais.data.updatedAt, erreur: undefined });
|
||||
await rejouer(queryClient);
|
||||
}
|
||||
}
|
||||
|
||||
export async function abandonnerSaisie(saisieId: string, queryClient: QueryClient): Promise<void> {
|
||||
retirer(saisieId);
|
||||
// On recharge la vérité serveur : le patch optimiste local est annulé.
|
||||
await queryClient.invalidateQueries({ queryKey: ['work-orders'] });
|
||||
await rejouer(queryClient);
|
||||
}
|
||||
Reference in New Issue
Block a user