mirror of
https://github.com/siop-spelev/siop2.git
synced 2026-08-08 12:41:54 +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:
@@ -199,6 +199,7 @@ export class WorkOrdersService {
|
||||
user: AuthenticatedUser,
|
||||
): Promise<WorkOrderDetail> {
|
||||
const detail = await this.get(id, user);
|
||||
await this.assertVersion(id, dto.baseUpdatedAt);
|
||||
if (!WORK_ORDER_TRANSITIONS[detail.status].includes(dto.to)) {
|
||||
throw new ConflictException(
|
||||
`Transition interdite : ${WORK_ORDER_STATUS_LABELS[detail.status]} → ${WORK_ORDER_STATUS_LABELS[dto.to]}`,
|
||||
@@ -245,6 +246,7 @@ export class WorkOrdersService {
|
||||
await this.prisma.workOrderEvent.create({
|
||||
data: { workOrderId: id, kind: 'COMMENT', message, byId: user.userId },
|
||||
});
|
||||
await this.toucher(id);
|
||||
return this.get(id, user);
|
||||
}
|
||||
|
||||
@@ -284,6 +286,7 @@ export class WorkOrdersService {
|
||||
user: AuthenticatedUser,
|
||||
): Promise<WorkOrderDetail> {
|
||||
await this.get(id, user);
|
||||
await this.assertVersion(id, dto.baseUpdatedAt);
|
||||
// Chaque valeur fournie doit appartenir au référentiel de SON champ (et être active)
|
||||
for (const [colonne, field] of Object.entries(REPORT_FIELDS)) {
|
||||
const valeur = dto[colonne as keyof ReportUpsert];
|
||||
@@ -310,6 +313,7 @@ export class WorkOrdersService {
|
||||
update: donnees,
|
||||
create: { workOrderId: id, ...donnees },
|
||||
});
|
||||
await this.toucher(id);
|
||||
return this.get(id, user);
|
||||
}
|
||||
|
||||
@@ -320,6 +324,7 @@ export class WorkOrdersService {
|
||||
user: AuthenticatedUser,
|
||||
): Promise<ChecklistItemDto> {
|
||||
await this.get(id, user);
|
||||
await this.assertVersion(id, dto.baseUpdatedAt);
|
||||
const { count } = await this.prisma.checklistItem.updateMany({
|
||||
where: { id: itemId, workOrderId: id },
|
||||
data: {
|
||||
@@ -329,6 +334,7 @@ export class WorkOrdersService {
|
||||
},
|
||||
});
|
||||
if (count === 0) throw new NotFoundException('Tâche inconnue');
|
||||
await this.toucher(id);
|
||||
const item = await this.prisma.checklistItem.findUniqueOrThrow({
|
||||
where: { id: itemId },
|
||||
include: { doneBy: true },
|
||||
@@ -368,6 +374,7 @@ export class WorkOrdersService {
|
||||
byId: user.userId,
|
||||
},
|
||||
});
|
||||
await this.toucher(id);
|
||||
return this.get(id, user);
|
||||
}
|
||||
|
||||
@@ -398,6 +405,7 @@ export class WorkOrdersService {
|
||||
note: dto.note,
|
||||
},
|
||||
});
|
||||
await this.toucher(id);
|
||||
return this.get(id, user);
|
||||
}
|
||||
|
||||
@@ -522,6 +530,43 @@ export class WorkOrdersService {
|
||||
},
|
||||
allowedTransitions: WORK_ORDER_TRANSITIONS[row.status as WorkOrderStatus],
|
||||
closureBlockers: blockers,
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Verrou optimiste (D2 mobile) : si l'appelant fournit la version lue et
|
||||
* que l'OT a changé depuis, 409 avec le contexte (qui, quand) — rien
|
||||
* n'est écrasé en silence. Sans version fournie (web), comportement
|
||||
* inchangé. */
|
||||
private async assertVersion(id: string, baseUpdatedAt?: string): Promise<void> {
|
||||
if (!baseUpdatedAt) return;
|
||||
const wo = await this.prisma.workOrder.findUniqueOrThrow({
|
||||
where: { id },
|
||||
select: {
|
||||
updatedAt: true,
|
||||
events: {
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 1,
|
||||
include: { by: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (wo.updatedAt.getTime() > new Date(baseUpdatedAt).getTime()) {
|
||||
const dernier = wo.events[0];
|
||||
const qui = dernier?.by?.displayName ?? 'quelqu’un';
|
||||
const quand = new Intl.DateTimeFormat('fr-FR', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(wo.updatedAt);
|
||||
throw new ConflictException(
|
||||
`Conflit de version : cet OT a été modifié par ${qui} à ${quand} — votre saisie n'a pas été appliquée.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Toute écriture « secondaire » (coche, bilan, commentaire, coûts) fait
|
||||
* avancer la version de l'OT — sinon le verrou D2 ne verrait rien. */
|
||||
private async toucher(id: string): Promise<void> {
|
||||
await this.prisma.workOrder.update({ where: { id }, data: { updatedAt: new Date() } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,3 +139,109 @@ describe('Recherche globale & corrections de recette R3 (e2e)', () => {
|
||||
.expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Verrou optimiste D2 (e2e) — la version protège les saisies mobiles', () => {
|
||||
let app: INestApplication;
|
||||
let salma: string;
|
||||
let ahmed: string;
|
||||
let otId: string;
|
||||
const prisma = new PrismaClient();
|
||||
const http = () => request(app.getHttpServer());
|
||||
const auth = (t: string) => ({ Authorization: `Bearer ${t}` });
|
||||
const suffix = `verrou-${Date.now().toString(36)}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule.forRoot()],
|
||||
}).compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
await app.init();
|
||||
const { body } = await http().get('/auth/demo-accounts');
|
||||
const login = async (roleName: string) => {
|
||||
const compte = body.accounts.find((a: { roleName: string }) => a.roleName === roleName);
|
||||
return (await http().post('/auth/demo-login').send({ userId: compte.id })).body
|
||||
.accessToken as string;
|
||||
};
|
||||
salma = await login('Dispatcher');
|
||||
ahmed = await login('Technicien');
|
||||
const { body: assets } = await http().get('/assets').set(auth(salma));
|
||||
const a1 = assets.assets.find((a: { reference: string }) => a.reference === 'A1');
|
||||
const technicien = body.accounts.find((a: { roleName: string }) => a.roleName === 'Technicien');
|
||||
const cree = await http()
|
||||
.post('/work-orders')
|
||||
.set(auth(salma))
|
||||
.send({
|
||||
title: `Verrou E2E ${suffix}`,
|
||||
type: 'CORRECTIVE',
|
||||
assetId: a1.id,
|
||||
assigneeIds: [technicien.id],
|
||||
})
|
||||
.expect(201);
|
||||
otId = cree.body.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prisma.workOrder.deleteMany({ where: { title: { contains: suffix } } });
|
||||
await app?.close();
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
it('version à jour : la transition passe ; le détail expose updatedAt', async () => {
|
||||
const detail = await http().get(`/work-orders/${otId}`).set(auth(ahmed)).expect(200);
|
||||
expect(detail.body.updatedAt).toBeTruthy();
|
||||
await http()
|
||||
.post(`/work-orders/${otId}/transition`)
|
||||
.set(auth(ahmed))
|
||||
.send({ to: 'IN_PROGRESS', baseUpdatedAt: detail.body.updatedAt })
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('OT modifié entre-temps (commentaire) : 409 « Conflit de version » contextualisé', async () => {
|
||||
const detail = await http().get(`/work-orders/${otId}`).set(auth(ahmed)).expect(200);
|
||||
const versionLue = detail.body.updatedAt as string;
|
||||
// Salma commente pendant qu'Ahmed est « hors-ligne » — la version avance
|
||||
await http()
|
||||
.post(`/work-orders/${otId}/comments`)
|
||||
.set(auth(salma))
|
||||
.send({ message: 'Réassigné après appel du syndic' })
|
||||
.expect(201);
|
||||
const refus = await http()
|
||||
.post(`/work-orders/${otId}/transition`)
|
||||
.set(auth(ahmed))
|
||||
.send({ to: 'ON_HOLD', baseUpdatedAt: versionLue })
|
||||
.expect(409);
|
||||
expect(refus.body.message).toContain('Conflit de version');
|
||||
expect(refus.body.message).toContain('Salma');
|
||||
// L'OT n'a PAS bougé — rien d'écrasé en silence
|
||||
const apres = await http().get(`/work-orders/${otId}`).set(auth(ahmed)).expect(200);
|
||||
expect(apres.body.status).toBe('IN_PROGRESS');
|
||||
});
|
||||
|
||||
it('le bilan et la coche font avancer la version (sinon le verrou est aveugle)', async () => {
|
||||
const avant = (await http().get(`/work-orders/${otId}`).set(auth(ahmed))).body.updatedAt;
|
||||
const { body: refs } = await http().get('/reference-values').set(auth(ahmed));
|
||||
const porte = refs.referenceValues.find(
|
||||
(v: { field: string; isActive: boolean }) => v.field === 'DOOR_STATE' && v.isActive,
|
||||
);
|
||||
await http()
|
||||
.put(`/work-orders/${otId}/report`)
|
||||
.set(auth(ahmed))
|
||||
.send({ doorStateId: porte.id })
|
||||
.expect(200);
|
||||
const apres = (await http().get(`/work-orders/${otId}`).set(auth(ahmed))).body.updatedAt;
|
||||
expect(new Date(apres).getTime()).toBeGreaterThan(new Date(avant).getTime());
|
||||
});
|
||||
|
||||
it('sans baseUpdatedAt (web) : comportement inchangé, même après modification', async () => {
|
||||
await http()
|
||||
.post(`/work-orders/${otId}/comments`)
|
||||
.set(auth(salma))
|
||||
.send({ message: 'Nouvelle note' })
|
||||
.expect(201);
|
||||
await http()
|
||||
.post(`/work-orders/${otId}/transition`)
|
||||
.set(auth(ahmed))
|
||||
.send({ to: 'ON_HOLD' })
|
||||
.expect(200);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Tabs } from 'expo-router';
|
||||
import { Text, type ColorValue } from 'react-native';
|
||||
import { useAssets, useReferenceValues } from '@/api/exploitation';
|
||||
import { useFile } from '@/file/store';
|
||||
import { useTokens } from '@/theme/tokens';
|
||||
|
||||
/** La tabbar de la maquette R4. Les onglets à venir restent visibles
|
||||
@@ -12,6 +14,12 @@ function Pic({ glyphe, couleur }: { glyphe: string; couleur: ColorValue }) {
|
||||
|
||||
export default function CoquilleTabs() {
|
||||
const t = useTokens();
|
||||
const file = useFile();
|
||||
const conflits = file.some((s) => s.statut === 'CONFLIT');
|
||||
// D1 « lecture locale » : le parc (scan D4) et les référentiels du bilan
|
||||
// se préchargent dès l'entrée — le sous-sol n'attend pas qu'on y pense.
|
||||
useAssets();
|
||||
useReferenceValues();
|
||||
return (
|
||||
<Tabs
|
||||
screenOptions={{
|
||||
@@ -49,6 +57,13 @@ export default function CoquilleTabs() {
|
||||
options={{
|
||||
title: 'Synchro',
|
||||
tabBarIcon: ({ color }) => <Pic glyphe="⇅" couleur={color} />,
|
||||
tabBarBadge: file.length || undefined,
|
||||
tabBarBadgeStyle: {
|
||||
backgroundColor: conflits ? t.prioBloque : t.stAttente,
|
||||
color: '#fff',
|
||||
fontFamily: 'Manrope_800ExtraBold',
|
||||
fontSize: 10,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Tabs>
|
||||
|
||||
@@ -1,11 +1,182 @@
|
||||
import { AVenir } from '@/composants/a-venir';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { router } from 'expo-router';
|
||||
import { FlatList, Pressable, Text, View } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useHorsLigne } from '@/auth/session';
|
||||
import { BoutonTel } from '@/composants/ui';
|
||||
import { useFile, type Saisie } from '@/file/store';
|
||||
import { abandonnerSaisie, rejouer, rejouerSurVersionAJour } from '@/file/synchro';
|
||||
import { useTokens } from '@/theme/tokens';
|
||||
|
||||
/** Écran 7 de la maquette R4 : la file VISIBLE et honnête. Rejeu dans
|
||||
* l'ordre ; un conflit (verrou D2) arrête la file sur l'élément, montre le
|
||||
* message de l'API (qui, quand) et VOUS tranchez — rien n'est écrasé ni
|
||||
* perdu en silence. */
|
||||
|
||||
const ICONES: Record<Saisie['type'], string> = {
|
||||
TRANSITION: '🏁',
|
||||
COCHE: '✓',
|
||||
BILAN: '📋',
|
||||
PHOTO: '🖼',
|
||||
};
|
||||
|
||||
export default function PageSynchro() {
|
||||
const t = useTokens();
|
||||
const horsLigne = useHorsLigne();
|
||||
const file = useFile();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const conflit = file.find((s) => s.statut === 'CONFLIT');
|
||||
const heure = (iso: string) =>
|
||||
new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit' }).format(new Date(iso));
|
||||
|
||||
return (
|
||||
<AVenir
|
||||
titre="Synchro"
|
||||
release="R4.3"
|
||||
detail="La file d'attente visible et honnête : vos saisies hors-ligne, rejouées dans l'ordre — et les conflits que VOUS tranchez (verrou optimiste, décision D2)."
|
||||
/>
|
||||
<SafeAreaView style={{ flex: 1, backgroundColor: t.fond }} edges={['top']}>
|
||||
<View style={{ flex: 1, padding: 14, gap: 10 }}>
|
||||
<View style={{ flexDirection: 'row', alignItems: 'baseline', gap: 8 }}>
|
||||
<Text style={{ fontFamily: 'Manrope_800ExtraBold', fontSize: 19, color: t.encre }}>
|
||||
Synchro
|
||||
</Text>
|
||||
<Text style={{ marginLeft: 'auto', fontFamily: 'Manrope_600SemiBold', fontSize: 11, color: t.encre3 }}>
|
||||
{conflit ? 'arrêtée sur le conflit' : file.length ? 'rejouée dans l’ordre' : ''}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{conflit ? (
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: t.prioBloqueFond,
|
||||
borderColor: t.danger,
|
||||
borderWidth: 1.5,
|
||||
borderRadius: 12,
|
||||
padding: 12,
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: t.danger, fontFamily: 'Manrope_800ExtraBold', fontSize: 13 }}>
|
||||
⚠ Conflit sur {conflit.otReference}
|
||||
</Text>
|
||||
<Text style={{ color: t.encre, fontFamily: 'Manrope_600SemiBold', fontSize: 12.5 }}>
|
||||
{conflit.erreur ?? 'L’OT a été modifié pendant que vous étiez hors-ligne.'}
|
||||
</Text>
|
||||
<Text style={{ color: t.encre2, fontFamily: 'Manrope_400Regular', fontSize: 11.5 }}>
|
||||
Votre saisie (« {conflit.libelle} », {heure(conflit.creeA)}) est conservée telle
|
||||
quelle dans la file — rien n’est perdu.
|
||||
</Text>
|
||||
<BoutonTel
|
||||
libelle="Voir l’OT à jour"
|
||||
variante="contour"
|
||||
surAppui={() => router.push(`/ot/${conflit.otId}`)}
|
||||
/>
|
||||
<BoutonTel
|
||||
libelle="Rejouer ma saisie sur la version à jour"
|
||||
surAppui={() => void rejouerSurVersionAJour(conflit.id, queryClient)}
|
||||
/>
|
||||
<BoutonTel
|
||||
libelle="Abandonner ma saisie"
|
||||
variante="gris"
|
||||
surAppui={() => void abandonnerSaisie(conflit.id, queryClient)}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<FlatList
|
||||
data={file}
|
||||
keyExtractor={(s) => s.id}
|
||||
contentContainerStyle={{ gap: 8, paddingBottom: 12 }}
|
||||
ListEmptyComponent={
|
||||
<View style={{ padding: 24, alignItems: 'center', gap: 6 }}>
|
||||
<Text style={{ fontFamily: 'Manrope_800ExtraBold', fontSize: 15, color: t.encre }}>
|
||||
Rien en attente
|
||||
</Text>
|
||||
<Text
|
||||
style={{
|
||||
fontFamily: 'Manrope_400Regular',
|
||||
fontSize: 12.5,
|
||||
color: t.encre2,
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
Toutes vos saisies sont sur le serveur. Les gestes faits hors-ligne apparaîtront
|
||||
ici, rejoués dans l’ordre au retour du réseau.
|
||||
</Text>
|
||||
</View>
|
||||
}
|
||||
renderItem={({ item: s }) => (
|
||||
<View
|
||||
style={{
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
backgroundColor: t.surface,
|
||||
borderColor: s.statut === 'CONFLIT' ? t.danger : t.bordure,
|
||||
borderWidth: 1,
|
||||
borderRadius: 10,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 10,
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
width: 28,
|
||||
height: 28,
|
||||
borderRadius: 8,
|
||||
backgroundColor: t.surface2,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<Text style={{ fontSize: 13 }}>{ICONES[s.type]}</Text>
|
||||
</View>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text numberOfLines={1} style={{ fontFamily: 'Manrope_700Bold', fontSize: 12.5, color: t.encre }}>
|
||||
{s.libelle}
|
||||
</Text>
|
||||
<Text style={{ fontFamily: 'Manrope_400Regular', fontSize: 11, color: t.encre2 }}>
|
||||
{s.otReference} · {heure(s.creeA)}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
style={{
|
||||
fontFamily: 'Manrope_700Bold',
|
||||
fontSize: 10.5,
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 2,
|
||||
borderRadius: 999,
|
||||
overflow: 'hidden',
|
||||
color:
|
||||
s.statut === 'CONFLIT' ? t.danger : s.statut === 'ENVOI' ? t.stOuvert : t.stAttente,
|
||||
backgroundColor:
|
||||
s.statut === 'CONFLIT'
|
||||
? t.prioBloqueFond
|
||||
: s.statut === 'ENVOI'
|
||||
? t.stOuvertFond
|
||||
: t.stAttenteFond,
|
||||
}}
|
||||
>
|
||||
{s.statut === 'CONFLIT' ? 'conflit' : s.statut === 'ENVOI' ? 'envoi…' : 'en attente'}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
|
||||
{file.length && !horsLigne ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => void rejouer(queryClient)}
|
||||
style={{ backgroundColor: t.primaire, borderRadius: 10, padding: 12, alignItems: 'center' }}
|
||||
>
|
||||
<Text style={{ color: '#fff', fontFamily: 'Manrope_700Bold', fontSize: 14 }}>
|
||||
Rejouer la file maintenant
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{horsLigne ? (
|
||||
<Text style={{ color: t.stAttente, fontFamily: 'Manrope_600SemiBold', fontSize: 12, textAlign: 'center' }}>
|
||||
Hors-ligne — la file repartira seule au retour du réseau.
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import { Stack } from 'expo-router';
|
||||
import { StatusBar } from 'expo-status-bar';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { HorsLigneProvider } from '@/auth/session';
|
||||
import { chargerFile } from '@/file/store';
|
||||
import { rejouer } from '@/file/synchro';
|
||||
import { useTokens } from '@/theme/tokens';
|
||||
|
||||
/** Racine de l'app (D1 validée) : le cache TanStack est PERSISTÉ dans
|
||||
@@ -46,15 +48,16 @@ export default function RacineApp() {
|
||||
Manrope_800ExtraBold,
|
||||
});
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
NetInfo.addEventListener((etat) => {
|
||||
const enLigne = !!etat.isConnected;
|
||||
onlineManager.setOnline(enLigne);
|
||||
setHorsLigne(!enLigne);
|
||||
}),
|
||||
[],
|
||||
);
|
||||
useEffect(() => {
|
||||
// D1 : la file survit au redémarrage — on la recharge avant tout.
|
||||
void chargerFile().then(() => rejouer(queryClient));
|
||||
return NetInfo.addEventListener((etat) => {
|
||||
const enLigne = !!etat.isConnected;
|
||||
onlineManager.setOnline(enLigne);
|
||||
setHorsLigne(!enLigne);
|
||||
if (enLigne) void rejouer(queryClient); // le retour du réseau vide la file
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!polices) return null;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { useState } from 'react';
|
||||
import { Alert, ScrollView, Text, View } from 'react-native';
|
||||
import { ScrollView, Text, View } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import {
|
||||
BILAN_FIELD_LABELS,
|
||||
@@ -9,16 +9,27 @@ import {
|
||||
type BilanField,
|
||||
type ReportUpsert,
|
||||
} from '@siop/shared';
|
||||
import { useBilan, useReferenceValues, useTransition, useWorkOrder } from '@/api/exploitation';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useReferenceValues, 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 (les MESSAGES viennent de l'API : une seule
|
||||
* source de vérité, comme le web). Clôture en ligne en R4.2. */
|
||||
* 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é). */
|
||||
|
||||
const CHAMP_VERS_ID: Record<BilanField, keyof ReportUpsert> = {
|
||||
type ChampBilanId =
|
||||
| 'doorStateId'
|
||||
| 'cabinPositionId'
|
||||
| 'anomalyId'
|
||||
| 'externalCauseId'
|
||||
| 'actionTakenId'
|
||||
| 'componentConcernedId';
|
||||
|
||||
const CHAMP_VERS_ID: Record<BilanField, ChampBilanId> = {
|
||||
DOOR_STATE: 'doorStateId',
|
||||
CABIN_POSITION: 'cabinPositionId',
|
||||
ANOMALY: 'anomalyId',
|
||||
@@ -41,8 +52,7 @@ export default function PageCloture() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const { data: ot } = useWorkOrder(id);
|
||||
const { data: valeurs } = useReferenceValues();
|
||||
const bilan = useBilan(id);
|
||||
const transition = useTransition(id);
|
||||
const queryClient = useQueryClient();
|
||||
const [choix, setChoix] = useState<Partial<Record<BilanField, string | null>>>({});
|
||||
|
||||
if (!ot) return null;
|
||||
@@ -61,27 +71,23 @@ export default function PageCloture() {
|
||||
return ot.report?.[CHAMP_VERS_VALEUR[champ]] ?? null;
|
||||
};
|
||||
|
||||
const enregistrer = (apres?: () => void) => {
|
||||
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;
|
||||
if (champ in choix) {
|
||||
corps[CHAMP_VERS_ID[champ]] = choix[champ] ?? null;
|
||||
labels[CHAMP_VERS_ID[champ]] = valeurDe(champ);
|
||||
}
|
||||
}
|
||||
bilan.mutate(corps, {
|
||||
onSuccess: apres,
|
||||
onError: (e) => Alert.alert('Bilan refusé', e.message),
|
||||
});
|
||||
enfilerBilan(queryClient, ot, corps, labels);
|
||||
};
|
||||
|
||||
const cloturer = () =>
|
||||
enregistrer(() =>
|
||||
transition.mutate(
|
||||
{ to: 'DONE' },
|
||||
{
|
||||
onSuccess: () => router.replace(`/ot/${id}`),
|
||||
onError: (e) => Alert.alert('Clôture bloquée', e.message),
|
||||
},
|
||||
),
|
||||
);
|
||||
const cloturer = () => {
|
||||
enregistrer();
|
||||
enfilerTransition(queryClient, ot, 'DONE');
|
||||
router.replace(`/ot/${id}`);
|
||||
};
|
||||
|
||||
const manquants = REQUIRED_BILAN_FIELDS.filter((c) => !valeurDe(c));
|
||||
|
||||
@@ -116,26 +122,29 @@ export default function PageCloture() {
|
||||
</Carte>
|
||||
|
||||
<BoutonTel
|
||||
libelle={bilan.isPending ? 'Enregistrement…' : 'Enregistrer le bilan'}
|
||||
libelle="Enregistrer le bilan"
|
||||
variante="contour"
|
||||
desactive={horsLigne || bilan.isPending}
|
||||
surAppui={() => enregistrer()}
|
||||
surAppui={() => {
|
||||
enregistrer();
|
||||
router.replace(`/ot/${id}`);
|
||||
}}
|
||||
/>
|
||||
<BoutonTel
|
||||
libelle={
|
||||
manquants.length
|
||||
? 'Clôturer (bilan incomplet)'
|
||||
: transition.isPending
|
||||
? 'Clôture…'
|
||||
: horsLigne
|
||||
? 'Clôturer — partira à la synchro'
|
||||
: "Clôturer l'intervention"
|
||||
}
|
||||
variante={manquants.length ? 'gris' : 'vert'}
|
||||
desactive={horsLigne || manquants.length > 0 || bilan.isPending || transition.isPending}
|
||||
desactive={manquants.length > 0}
|
||||
surAppui={cloturer}
|
||||
/>
|
||||
{horsLigne ? (
|
||||
<Text style={{ color: t.stAttente, fontFamily: 'Manrope_600SemiBold', fontSize: 12 }}>
|
||||
Hors-ligne : la clôture en file arrive en R4.3 — pour l’instant, revenez au réseau.
|
||||
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 l’OT a changé entre-temps, VOUS trancherez (écran Synchro).
|
||||
</Text>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
|
||||
@@ -1,30 +1,38 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useLocalSearchParams } from 'expo-router';
|
||||
import { Alert, Pressable, ScrollView, Text, View } from 'react-native';
|
||||
import { Pressable, ScrollView, Text, View } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useCocheChecklist, useWorkOrder } from '@/api/exploitation';
|
||||
import { useWorkOrder } from '@/api/exploitation';
|
||||
import { useHorsLigne } from '@/auth/session';
|
||||
import { EnteteFiche } from '@/composants/ui';
|
||||
import { enfilerCoche } from '@/file/actions';
|
||||
import { useFile } from '@/file/store';
|
||||
import { prochainEtat, progression } from '@/lib/checklist';
|
||||
import { useTokens } from '@/theme/tokens';
|
||||
|
||||
/** Écran 6 de la maquette R4 : la grille au pouce. Appui simple = coche,
|
||||
* appui long = non-applicable. En R4.2 chaque coche part immédiatement à
|
||||
* l'API (hors-ligne : lecture seule — la file individuelle arrive en R4.3). */
|
||||
* appui long = non-applicable. Chaque coche part en file INDIVIDUELLEMENT
|
||||
* (D1) : 7 coches faites = 7 coches sauvées, réseau ou pas. */
|
||||
export default function PageGrille() {
|
||||
const t = useTokens();
|
||||
const horsLigne = useHorsLigne();
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const { data: ot } = useWorkOrder(id);
|
||||
const coche = useCocheChecklist(id);
|
||||
const queryClient = useQueryClient();
|
||||
const file = useFile();
|
||||
|
||||
if (!ot) return null;
|
||||
const { faits, total, pct } = progression(ot.checklist);
|
||||
const enFile = new Set(
|
||||
file.flatMap((s) => (s.otId === ot.id && s.type === 'COCHE' ? [s.payload.itemId] : [])),
|
||||
);
|
||||
|
||||
const basculer = (itemId: string, etat: Parameters<typeof prochainEtat>[0], versNA = false) => {
|
||||
if (horsLigne) return;
|
||||
coche.mutate(
|
||||
{ itemId, state: versNA ? (etat === 'NA' ? 'PENDING' : 'NA') : prochainEtat(etat) },
|
||||
{ onError: (e) => Alert.alert('Coche refusée', e.message) },
|
||||
const basculer = (item: { id: string; label: string }, etat: Parameters<typeof prochainEtat>[0], versNA = false) => {
|
||||
enfilerCoche(
|
||||
queryClient,
|
||||
ot,
|
||||
item,
|
||||
versNA ? (etat === 'NA' ? 'PENDING' : 'NA') : prochainEtat(etat),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -55,8 +63,7 @@ export default function PageGrille() {
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: t.stAttente, fontFamily: 'Manrope_700Bold', fontSize: 12 }}>
|
||||
⚠ Hors-ligne — les coches en file arrivent en R4.3 ; pour l’instant la grille est en
|
||||
lecture.
|
||||
⚠ Hors-ligne — chaque coche part en file et se synchronisera au retour du réseau.
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
@@ -66,9 +73,8 @@ export default function PageGrille() {
|
||||
accessibilityRole="checkbox"
|
||||
aria-checked={item.state === 'DONE'}
|
||||
accessibilityLabel={item.label}
|
||||
disabled={horsLigne || coche.isPending}
|
||||
onPress={() => basculer(item.id, item.state)}
|
||||
onLongPress={() => basculer(item.id, item.state, true)}
|
||||
onPress={() => basculer(item, item.state)}
|
||||
onLongPress={() => basculer(item, item.state, true)}
|
||||
style={{
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
@@ -109,7 +115,21 @@ export default function PageGrille() {
|
||||
>
|
||||
{item.label}
|
||||
</Text>
|
||||
{item.doneBy ? (
|
||||
{enFile.has(item.id) ? (
|
||||
<Text
|
||||
style={{
|
||||
fontFamily: 'Manrope_800ExtraBold',
|
||||
fontSize: 9,
|
||||
color: t.stAttente,
|
||||
backgroundColor: t.stAttenteFond,
|
||||
paddingHorizontal: 6,
|
||||
borderRadius: 999,
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
en file
|
||||
</Text>
|
||||
) : item.doneBy ? (
|
||||
<Text style={{ fontFamily: 'Manrope_400Regular', fontSize: 10.5, color: t.encre3 }}>
|
||||
{item.doneBy.displayName.split(' ')[0]}
|
||||
</Text>
|
||||
|
||||
@@ -1,45 +1,70 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { Alert, ScrollView, Text, View } from 'react-native';
|
||||
import { ScrollView, Text, View } from 'react-native';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import {
|
||||
WORK_ORDER_PRIORITY_LABELS,
|
||||
WORK_ORDER_TYPE_LABELS,
|
||||
} from '@siop/shared';
|
||||
import { useTransition, useWorkOrder } from '@/api/exploitation';
|
||||
import { useWorkOrder } from '@/api/exploitation';
|
||||
import { useHorsLigne } from '@/auth/session';
|
||||
import { BoutonTel, Carte, ChipStatut, EnteteFiche, LigneInfo } from '@/composants/ui';
|
||||
import { CartePhotos } from '@/composants/carte-photos';
|
||||
import { enfilerTransition } from '@/file/actions';
|
||||
import { useFile } from '@/file/store';
|
||||
import { progression } from '@/lib/checklist';
|
||||
import { useTokens } from '@/theme/tokens';
|
||||
|
||||
const fmt = new Intl.NumberFormat('fr-FR');
|
||||
|
||||
/** Écran 2 de la maquette R4 : la même machine à états que le web — UN
|
||||
* bouton principal selon l'état, la garde de clôture visible. En R4.2 les
|
||||
* écritures restent en ligne (la file arrive en R4.3 — assumé à l'écran). */
|
||||
* bouton principal selon l'état. Depuis R4.3, chaque geste part en file
|
||||
* (D1) : l'écran montre l'état local tout de suite, la synchro suit. */
|
||||
export default function PageFicheOT() {
|
||||
const t = useTokens();
|
||||
const horsLigne = useHorsLigne();
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const { data: ot } = useWorkOrder(id);
|
||||
const transition = useTransition(id);
|
||||
const queryClient = useQueryClient();
|
||||
const file = useFile();
|
||||
|
||||
if (!ot) return null;
|
||||
|
||||
const grille = progression(ot.checklist);
|
||||
const enFile = file.filter((s) => s.otId === ot.id);
|
||||
const peutDemarrer = ot.allowedTransitions.includes('IN_PROGRESS');
|
||||
const peutCloturer = ot.allowedTransitions.includes('DONE');
|
||||
const peutSuspendre = ot.allowedTransitions.includes('ON_HOLD');
|
||||
|
||||
const demarrer = () =>
|
||||
transition.mutate(
|
||||
{ to: 'IN_PROGRESS' },
|
||||
{ onError: (e) => Alert.alert('Transition refusée', e.message) },
|
||||
);
|
||||
const demarrer = () => enfilerTransition(queryClient, ot, 'IN_PROGRESS');
|
||||
|
||||
return (
|
||||
<SafeAreaView style={{ flex: 1, backgroundColor: t.fond }} edges={['top']}>
|
||||
<ScrollView contentContainerStyle={{ padding: 14, gap: 10 }}>
|
||||
<EnteteFiche titre={ot.reference} apres={<ChipStatut statut={ot.status} />} />
|
||||
<EnteteFiche
|
||||
titre={ot.reference}
|
||||
apres={
|
||||
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
|
||||
{enFile.length ? (
|
||||
<Text
|
||||
style={{
|
||||
fontFamily: 'Manrope_800ExtraBold',
|
||||
fontSize: 10,
|
||||
color: t.stAttente,
|
||||
backgroundColor: t.stAttenteFond,
|
||||
paddingHorizontal: 7,
|
||||
paddingVertical: 2,
|
||||
borderRadius: 999,
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{enFile.length} en file
|
||||
</Text>
|
||||
) : null}
|
||||
<ChipStatut statut={ot.status} />
|
||||
</View>
|
||||
}
|
||||
/>
|
||||
<Text style={{ fontFamily: 'Manrope_800ExtraBold', fontSize: 17, color: t.encre }}>
|
||||
{ot.title}
|
||||
</Text>
|
||||
@@ -54,7 +79,7 @@ export default function PageFicheOT() {
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: t.stAttente, fontFamily: 'Manrope_700Bold', fontSize: 12 }}>
|
||||
⚠ Hors-ligne — lecture seule pour l’instant : les saisies hors réseau arrivent en R4.3 (file).
|
||||
⚠ Hors-ligne — vos gestes partent en file et se synchroniseront au retour du réseau.
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
@@ -129,7 +154,6 @@ export default function PageFicheOT() {
|
||||
{peutDemarrer ? (
|
||||
<BoutonTel
|
||||
libelle={ot.status === 'ON_HOLD' ? 'Reprendre' : 'Démarrer'}
|
||||
desactive={horsLigne || transition.isPending}
|
||||
surAppui={demarrer}
|
||||
/>
|
||||
) : null}
|
||||
@@ -137,7 +161,6 @@ export default function PageFicheOT() {
|
||||
<BoutonTel
|
||||
libelle="Clôturer l'intervention"
|
||||
variante="vert"
|
||||
desactive={horsLigne}
|
||||
surAppui={() => router.push(`/ot/${ot.id}/cloture`)}
|
||||
/>
|
||||
) : null}
|
||||
@@ -145,16 +168,12 @@ export default function PageFicheOT() {
|
||||
<BoutonTel
|
||||
libelle="Mettre en attente"
|
||||
variante="contour"
|
||||
desactive={horsLigne || transition.isPending}
|
||||
surAppui={() =>
|
||||
transition.mutate(
|
||||
{ to: 'ON_HOLD' },
|
||||
{ onError: (e) => Alert.alert('Transition refusée', e.message) },
|
||||
)
|
||||
}
|
||||
surAppui={() => enfilerTransition(queryClient, ot, 'ON_HOLD')}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<CartePhotos ot={ot} />
|
||||
|
||||
<Carte titre="Activité">
|
||||
{ot.events.slice(0, 5).map((e) => (
|
||||
<View key={e.id} style={{ gap: 1 }}>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* recette sur appareil. */
|
||||
module.exports = {
|
||||
preset: 'jest-expo',
|
||||
setupFiles: ['./jest.setup.js'],
|
||||
moduleNameMapper: {
|
||||
'^@/(.*)$': '<rootDir>/src/$1',
|
||||
},
|
||||
|
||||
4
apps/mobile/jest.setup.js
Normal file
4
apps/mobile/jest.setup.js
Normal file
@@ -0,0 +1,4 @@
|
||||
/* AsyncStorage : mock officiel du paquet (pas de natif sous jest). */
|
||||
jest.mock('@react-native-async-storage/async-storage', () =>
|
||||
require('@react-native-async-storage/async-storage/jest/async-storage-mock'),
|
||||
);
|
||||
@@ -14,6 +14,8 @@
|
||||
"expo-camera": "~57.0.3",
|
||||
"expo-constants": "~57.0.5",
|
||||
"expo-font": "~57.0.1",
|
||||
"expo-image-manipulator": "~57.0.4",
|
||||
"expo-image-picker": "~57.0.4",
|
||||
"expo-linking": "~57.0.3",
|
||||
"expo-router": "~57.0.6",
|
||||
"expo-secure-store": "~57.0.1",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
8
apps/web/src/api/schema.d.ts
vendored
8
apps/web/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: {
|
||||
|
||||
Reference in New Issue
Block a user