generate pdf, organize pages

This commit is contained in:
m
2026-07-12 15:56:23 +02:00
parent db3d18cf33
commit 380866e919
5 changed files with 422 additions and 98 deletions
+2
View File
@@ -8,6 +8,7 @@ import { UploadScreen } from './app/upload';
import { ScanScreen } from './app/scan'; import { ScanScreen } from './app/scan';
import { SearchScreen } from './app/search'; import { SearchScreen } from './app/search';
import { BatchReviewScreen } from './app/batch-review'; import { BatchReviewScreen } from './app/batch-review';
import { PendingReviewScreen } from './app/pending-review';
const Stack = createNativeStackNavigator(); const Stack = createNativeStackNavigator();
const queryClient = new QueryClient(); const queryClient = new QueryClient();
@@ -22,6 +23,7 @@ export default function App() {
<Stack.Screen name="Scan" component={ScanScreen} options={{ title: 'Scan' }} /> <Stack.Screen name="Scan" component={ScanScreen} options={{ title: 'Scan' }} />
<Stack.Screen name="Search" component={SearchScreen} options={{ title: 'Recherche' }} /> <Stack.Screen name="Search" component={SearchScreen} options={{ title: 'Recherche' }} />
<Stack.Screen name="BatchReview" component={BatchReviewScreen} options={{ title: 'Revue du lot' }} /> <Stack.Screen name="BatchReview" component={BatchReviewScreen} options={{ title: 'Revue du lot' }} />
<Stack.Screen name="PendingReview" component={PendingReviewScreen} options={{ title: 'Réorganisation' }} />
</Stack.Navigator> </Stack.Navigator>
</NavigationContainer> </NavigationContainer>
<StatusBar style="auto" /> <StatusBar style="auto" />
+59 -90
View File
@@ -1,24 +1,27 @@
import React, { useState } from 'react'; import React, { useState, useCallback } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, Alert, ActivityIndicator, Share } from 'react-native'; import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, Alert, ActivityIndicator } from 'react-native';
import { useRoute, useNavigation, RouteProp } from '@react-navigation/native'; import { useRoute, useNavigation, RouteProp } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useBatchStore } from '../hooks/useBatchStore'; import { useBatchStore } from '../hooks/useBatchStore';
import { usePdfGeneration } from '../hooks/usePdfGeneration'; import { usePdfGeneration } from '../hooks/usePdfGeneration';
type BatchReviewRouteParams = { type RootStackParamList = {
Home: undefined;
BatchReview: { batchId: string }; BatchReview: { batchId: string };
PendingReview: { batchId: string; photoIds: string[] };
}; };
type NavigationProp = NativeStackNavigationProp<RootStackParamList>;
type BatchReviewRouteParams = { BatchReview: { batchId: string } };
export function BatchReviewScreen() { export function BatchReviewScreen() {
const route = useRoute<RouteProp<BatchReviewRouteParams, 'BatchReview'>>(); const route = useRoute<RouteProp<BatchReviewRouteParams, 'BatchReview'>>();
const navigation = useNavigation(); const navigation = useNavigation<NavigationProp>();
const { getBatch, addTagToBatch, removeTagFromBatch } = useBatchStore(); const { getBatch, removePhotoFromBatch } = useBatchStore();
const { generatePdf, generating } = usePdfGeneration();
const batch = getBatch(route.params.batchId); const batch = getBatch(route.params.batchId);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set()); const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [editingTags, setEditingTags] = useState(false);
const [tagInput, setTagInput] = useState('');
if (!batch) { if (!batch) {
return ( return (
@@ -37,44 +40,39 @@ export function BatchReviewScreen() {
}); });
}; };
const selectedPhotos = batch.photos.filter((p) => selectedIds.has(p.id));
const selectedCount = selectedIds.size; const selectedCount = selectedIds.size;
const handleGeneratePdf = async () => { const handleDelete = () => {
const photos = selectedCount > 0 ? selectedPhotos : batch.photos; if (selectedCount === 0) return;
if (photos.length === 0) return; const label = selectedCount === 1 ? 'cette photo' : `ces ${selectedCount} photos`;
Alert.alert(
const uri = await generatePdf(photos); 'Supprimer',
if (uri) { `Retirer ${label} du lot ?`,
Alert.alert('PDF généré', 'Voulez-vous partager le fichier ?', [ [
{ text: 'Annuler', style: 'cancel' }, { text: 'Annuler', style: 'cancel' },
{ {
text: 'Partager', text: 'Supprimer',
style: 'destructive',
onPress: () => { onPress: () => {
Share.share({ url: uri, title: batch.name }); selectedIds.forEach((id) => removePhotoFromBatch(batch.id, id));
setSelectedIds(new Set());
}, },
}, },
]); ]
} else { );
Alert.alert('Erreur', 'Impossible de générer le PDF');
}
}; };
const handleAddTag = () => { const handleGroup = () => {
const tag = tagInput.trim().toLowerCase(); if (selectedCount === 0) return;
if (!tag || batch.tags.includes(tag)) return; const ids = Array.from(selectedIds);
addTagToBatch(batch.id, tag); navigation.navigate('PendingReview', { batchId: batch.id, photoIds: ids });
setTagInput('');
}; };
const formatDate = (iso: string) => { const formatDate = (iso: string) => {
const d = new Date(iso); const d = new Date(iso);
return d.toLocaleDateString('fr-FR', { return d.toLocaleDateString('fr-FR', {
day: '2-digit', day: '2-digit', month: '2-digit', year: 'numeric',
month: '2-digit', hour: '2-digit', minute: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
}); });
}; };
@@ -111,36 +109,25 @@ export function BatchReviewScreen() {
/> />
<View style={styles.footer}> <View style={styles.footer}>
<View style={styles.tagSection}>
<View style={styles.tagRow}>
{batch.tags.map((tag) => (
<TouchableOpacity
key={tag}
style={styles.tagChip}
onPress={() => removeTagFromBatch(batch.id, tag)}
>
<Text style={styles.tagText}>{tag} </Text>
</TouchableOpacity>
))}
</View>
<Text style={styles.disabledNote}>Tags disponibles avec le backend (bientôt)</Text>
</View>
<View style={styles.actions}>
<Text style={styles.selectionInfo}> <Text style={styles.selectionInfo}>
{selectedCount > 0 ? `${selectedCount} sélectionnée${selectedCount > 1 ? 's' : ''}` : 'Toutes les photos'} {selectedCount > 0 ? `${selectedCount} sélectionnée${selectedCount > 1 ? 's' : ''}` : 'Touchez une photo pour sélectionner'}
</Text> </Text>
<View style={styles.actions}>
<TouchableOpacity <TouchableOpacity
style={[styles.actionButton, generating && styles.actionButtonDisabled]} style={[styles.actionBtn, styles.deleteBtn, selectedCount === 0 && styles.actionBtnDisabled]}
onPress={handleGeneratePdf} onPress={handleDelete}
disabled={generating} disabled={selectedCount === 0}
> >
{generating ? ( <Text style={styles.actionText}>🗑 Supprimer</Text>
<ActivityIndicator size="small" color="#fff" /> </TouchableOpacity>
) : (
<Text style={styles.actionText}>📄 Générer PDF</Text> <TouchableOpacity
)} style={[styles.actionBtn, styles.groupBtn, selectedCount === 0 && styles.actionBtnDisabled]}
onPress={handleGroup}
disabled={selectedCount === 0}
>
<Text style={styles.actionText}>📦 Regrouper</Text>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> </View>
@@ -212,47 +199,29 @@ const styles = StyleSheet.create({
borderTopColor: '#e0e0e0', borderTopColor: '#e0e0e0',
gap: 12, gap: 12,
}, },
tagSection: {
gap: 8,
},
tagRow: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 6,
},
tagChip: {
backgroundColor: '#E3F2FD',
paddingHorizontal: 10,
paddingVertical: 4,
borderRadius: 12,
},
tagText: {
fontSize: 13,
color: '#1976D2',
},
disabledNote: {
fontSize: 12,
color: '#999',
fontStyle: 'italic',
},
actions: {
gap: 8,
alignItems: 'center',
},
selectionInfo: { selectionInfo: {
fontSize: 14, fontSize: 14,
color: '#666', color: '#666',
textAlign: 'center',
}, },
actionButton: { actions: {
backgroundColor: '#1976D2', flexDirection: 'row',
paddingHorizontal: 24, gap: 12,
},
actionBtn: {
flex: 1,
paddingVertical: 12, paddingVertical: 12,
borderRadius: 8, borderRadius: 8,
width: '100%',
alignItems: 'center', alignItems: 'center',
}, },
actionButtonDisabled: { actionBtnDisabled: {
opacity: 0.6, opacity: 0.4,
},
deleteBtn: {
backgroundColor: '#F44336',
},
groupBtn: {
backgroundColor: '#4CAF50',
}, },
actionText: { actionText: {
color: '#fff', color: '#fff',
+339
View File
@@ -0,0 +1,339 @@
import React, { useState, useCallback } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, TextInput, Alert, ActivityIndicator } from 'react-native';
import { useRoute, useNavigation, RouteProp } from '@react-navigation/native';
import { useBatchStore } from '../hooks/useBatchStore';
import { usePdfGeneration } from '../hooks/usePdfGeneration';
import { useUpload } from '../hooks/useUpload';
import { CapturedPhoto } from '../types';
type PendingReviewRouteParams = {
PendingReview: { batchId: string; photoIds: string[] };
};
export function PendingReviewScreen() {
const route = useRoute<RouteProp<PendingReviewRouteParams, 'PendingReview'>>();
const navigation = useNavigation();
const { getBatch, addTagToBatch, removeTagFromBatch } = useBatchStore();
const { generatePdf, generating, progress } = usePdfGeneration();
const upload = useUpload();
const batch = getBatch(route.params.batchId);
const initialPhotos = (batch?.photos ?? []).filter((p) =>
route.params.photoIds.includes(p.id)
);
const [photos, setPhotos] = useState<CapturedPhoto[]>(initialPhotos);
const [batchTags, setBatchTags] = useState<string[]>(batch?.tags ?? []);
const [tagInput, setTagInput] = useState('');
const moveUp = useCallback((index: number) => {
if (index === 0) return;
setPhotos((prev) => {
const next = [...prev];
[next[index - 1], next[index]] = [next[index], next[index - 1]];
return next;
});
}, []);
const moveDown = useCallback((index: number) => {
if (index >= photos.length - 1) return;
setPhotos((prev) => {
const next = [...prev];
[next[index], next[index + 1]] = [next[index + 1], next[index]];
return next;
});
}, [photos.length]);
const handleAddTag = () => {
const tag = tagInput.trim().toLowerCase();
if (!tag || batchTags.includes(tag)) return;
setBatchTags((prev) => [...prev, tag]);
addTagToBatch(route.params.batchId, tag);
setTagInput('');
};
const handleRemoveTag = (tag: string) => {
setBatchTags((prev) => prev.filter((t) => t !== tag));
removeTagFromBatch(route.params.batchId, tag);
};
const handleFinalize = async () => {
if (photos.length === 0) return;
const pdfUri = await generatePdf(photos.map((p) => ({ uri: p.uri })));
if (!pdfUri) {
Alert.alert('Erreur', 'Échec de la génération du PDF');
return;
}
Alert.alert(
'PDF généré',
'Voulez-vous uploader le fichier ?',
[
{ text: 'Annuler', style: 'cancel', onPress: () => navigation.goBack() },
{
text: 'Uploader',
onPress: async () => {
try {
await upload.mutateAsync([
{
uri: 'file://' + pdfUri,
type: 'application/pdf',
name: `${batch?.name ?? 'document'}.pdf`,
},
]);
Alert.alert('Succès', 'PDF uploadé avec succès', [
{ text: 'OK', onPress: () => navigation.navigate('Home' as never) },
]);
} catch {
Alert.alert('Erreur', "Échec de l'upload du PDF");
}
},
},
]
);
};
if (!batch) {
return (
<View style={styles.center}>
<Text style={styles.errorText}>Lot introuvable</Text>
</View>
);
}
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>Réorganiser les photos</Text>
<Text style={styles.subtitle}>{photos.length} photo{photos.length > 1 ? 's' : ''}</Text>
</View>
<FlatList
data={photos}
keyExtractor={(item) => item.id}
contentContainerStyle={styles.list}
renderItem={({ item, index }) => (
<View style={styles.photoRow}>
<Image source={{ uri: item.uri }} style={styles.thumb} />
<Text style={styles.photoIndex}>#{index + 1}</Text>
<View style={styles.arrows}>
<TouchableOpacity
style={[styles.arrowBtn, index === 0 && styles.arrowDisabled]}
onPress={() => moveUp(index)}
disabled={index === 0}
>
<Text style={styles.arrowText}></Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.arrowBtn, index >= photos.length - 1 && styles.arrowDisabled]}
onPress={() => moveDown(index)}
disabled={index >= photos.length - 1}
>
<Text style={styles.arrowText}></Text>
</TouchableOpacity>
</View>
</View>
)}
/>
<View style={styles.tagSection}>
<Text style={styles.sectionTitle}>Tags</Text>
<View style={styles.tagRow}>
{batchTags.map((tag) => (
<TouchableOpacity key={tag} style={styles.tagChip} onPress={() => handleRemoveTag(tag)}>
<Text style={styles.tagText}>{tag} </Text>
</TouchableOpacity>
))}
</View>
<View style={styles.tagInputRow}>
<TextInput
style={styles.tagInput}
placeholder="Ajouter un tag..."
value={tagInput}
onChangeText={setTagInput}
onSubmitEditing={handleAddTag}
returnKeyType="done"
/>
<TouchableOpacity style={styles.tagAddBtn} onPress={handleAddTag}>
<Text style={styles.tagAddText}>+</Text>
</TouchableOpacity>
</View>
</View>
<View style={styles.footer}>
{generating && (
<View style={styles.progressRow}>
<ActivityIndicator size="small" color="#1976D2" />
<Text style={styles.progressText}>Génération du PDF... {progress}%</Text>
</View>
)}
<TouchableOpacity
style={[styles.finalizeBtn, generating && styles.finalizeBtnDisabled]}
onPress={handleFinalize}
disabled={generating}
>
{generating ? (
<ActivityIndicator size="small" color="#fff" />
) : (
<Text style={styles.finalizeText}>📄 Finaliser et uploader le PDF</Text>
)}
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
errorText: {
fontSize: 16,
color: '#666',
},
header: {
padding: 16,
borderBottomWidth: 1,
borderBottomColor: '#e0e0e0',
},
title: {
fontSize: 20,
fontWeight: '700',
marginBottom: 4,
},
subtitle: {
fontSize: 14,
color: '#666',
},
list: {
padding: 16,
},
photoRow: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 12,
backgroundColor: '#f9f9f9',
borderRadius: 8,
padding: 8,
},
thumb: {
width: 60,
height: 60,
borderRadius: 6,
backgroundColor: '#e0e0e0',
},
photoIndex: {
marginLeft: 12,
fontSize: 16,
fontWeight: '600',
color: '#333',
flex: 1,
},
arrows: {
gap: 4,
},
arrowBtn: {
width: 36,
height: 28,
borderRadius: 4,
backgroundColor: '#e0e0e0',
justifyContent: 'center',
alignItems: 'center',
},
arrowDisabled: {
opacity: 0.3,
},
arrowText: {
fontSize: 14,
color: '#333',
},
tagSection: {
padding: 16,
borderTopWidth: 1,
borderTopColor: '#e0e0e0',
},
sectionTitle: {
fontSize: 16,
fontWeight: '600',
marginBottom: 8,
},
tagRow: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 6,
marginBottom: 8,
},
tagChip: {
backgroundColor: '#E3F2FD',
paddingHorizontal: 10,
paddingVertical: 4,
borderRadius: 12,
},
tagText: {
fontSize: 13,
color: '#1976D2',
},
tagInputRow: {
flexDirection: 'row',
gap: 8,
},
tagInput: {
flex: 1,
borderWidth: 1,
borderColor: '#e0e0e0',
borderRadius: 8,
padding: 10,
fontSize: 14,
},
tagAddBtn: {
width: 40,
height: 40,
borderRadius: 8,
backgroundColor: '#1976D2',
justifyContent: 'center',
alignItems: 'center',
},
tagAddText: {
color: '#fff',
fontSize: 20,
fontWeight: '700',
},
footer: {
padding: 16,
borderTopWidth: 1,
borderTopColor: '#e0e0e0',
gap: 8,
},
progressRow: {
flexDirection: 'row',
alignItems: 'center',
gap: 8,
},
progressText: {
fontSize: 14,
color: '#666',
},
finalizeBtn: {
backgroundColor: '#1976D2',
paddingHorizontal: 24,
paddingVertical: 14,
borderRadius: 8,
alignItems: 'center',
},
finalizeBtnDisabled: {
opacity: 0.6,
},
finalizeText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
});
+12
View File
@@ -48,6 +48,17 @@ export function useBatchStore() {
setBatchIds((batchIds ?? []).filter((id) => id !== batchId)); setBatchIds((batchIds ?? []).filter((id) => id !== batchId));
}, [batchIds, setBatchIds]); }, [batchIds, setBatchIds]);
const removePhotoFromBatch = useCallback((batchId: string, photoId: string) => {
const batch = getBatch(batchId);
if (!batch) return;
batch.photos = batch.photos.filter((p) => p.id !== photoId);
if (batch.photos.length === 0) {
deleteBatch(batchId);
} else {
storage.set(`batch_${batchId}`, JSON.stringify(batch));
}
}, [getBatch, deleteBatch]);
return { return {
saveBatch, saveBatch,
getBatch, getBatch,
@@ -55,5 +66,6 @@ export function useBatchStore() {
addTagToBatch, addTagToBatch,
removeTagFromBatch, removeTagFromBatch,
deleteBatch, deleteBatch,
removePhotoFromBatch,
}; };
} }
+10 -8
View File
@@ -1,22 +1,21 @@
import { useState, useCallback } from 'react'; import { useState, useCallback } from 'react';
import * as Print from 'expo-print'; import * as Print from 'expo-print';
import * as FileSystem from 'expo-file-system';
import { CapturedPhoto } from '../types';
export function usePdfGeneration() { export function usePdfGeneration() {
const [generating, setGenerating] = useState(false); const [generating, setGenerating] = useState(false);
const [progress, setProgress] = useState(0);
const generatePdf = useCallback(async (photos: CapturedPhoto[]): Promise<string | null> => { const generatePdf = useCallback(async (items: { uri: string }[], progressCb?: (pct: number) => void): Promise<string | null> => {
if (photos.length === 0) return null; if (items.length === 0) return null;
setGenerating(true); setGenerating(true);
setProgress(0);
progressCb?.(0);
try { try {
const imagesHtml = photos.map((p) => { const imagesHtml = items.map((item) => {
const ext = p.filePath.split('.').pop()?.toLowerCase() || 'jpeg';
const mime = ext === 'png' ? 'image/png' : 'image/jpeg';
return `<div style="page-break-after: always; display: flex; justify-content: center; align-items: center; height: 100vh;"> return `<div style="page-break-after: always; display: flex; justify-content: center; align-items: center; height: 100vh;">
<img src="${p.uri}" style="max-width: 100%; max-height: 100vh; object-fit: contain;" /> <img src="${item.uri}" style="max-width: 100%; max-height: 100vh; object-fit: contain;" />
</div>`; </div>`;
}).join(''); }).join('');
@@ -37,6 +36,8 @@ export function usePdfGeneration() {
</html>`; </html>`;
const { uri } = await Print.printToFileAsync({ html }); const { uri } = await Print.printToFileAsync({ html });
setProgress(100);
progressCb?.(100);
return uri; return uri;
} catch (err) { } catch (err) {
console.error('PDF generation failed:', err); console.error('PDF generation failed:', err);
@@ -49,5 +50,6 @@ export function usePdfGeneration() {
return { return {
generatePdf, generatePdf,
generating, generating,
progress,
}; };
} }