The minimalistic document archiving platform.
feat(mobile): dedicated scanning screen (#843)
Corentin Thomasset5fcceb4bc750
diff --git a/apps/mobile/app/(app)/(with-organizations)/_layout.tsx b/apps/mobile/app/(app)/(with-organizations)/_layout.tsxindex e1a64d9e..2d8e86e8 100644--- a/apps/mobile/app/(app)/(with-organizations)/_layout.tsx+++ b/apps/mobile/app/(app)/(with-organizations)/_layout.tsx@@ -7,6 +7,14 @@ export default function WithOrganizationsLayout() {<Stack><Stack.Screen name="organizations/create" options={{ headerShown: false }} /><Stack.Screen name="(tabs)" options={{ headerShown: false }} />+ <Stack.Screen+ name="scan"+ options={{+ headerShown: false,+ presentation: 'modal',+ animation: 'slide_from_bottom',+ }}+ /></Stack></OrganizationsProvider>);diff --git a/apps/mobile/app/(app)/(with-organizations)/scan.tsx b/apps/mobile/app/(app)/(with-organizations)/scan.tsxnew file mode 100644index 00000000..174f9b46--- /dev/null+++ b/apps/mobile/app/(app)/(with-organizations)/scan.tsx@@ -0,0 +1,3 @@+import ScanScreen from '@/modules/documents/documents-scan/screens/scan.screen';++export default ScanScreen;diff --git a/apps/mobile/src/modules/documents/components/import-drawer.tsx b/apps/mobile/src/modules/documents/components/import-drawer.tsxindex 460d0b90..06736d05 100644--- a/apps/mobile/src/modules/documents/components/import-drawer.tsx+++ b/apps/mobile/src/modules/documents/components/import-drawer.tsx@@ -1,8 +1,5 @@-import type { LocalDocument } from '@/modules/api/api.models';import type { ThemeColors } from '@/modules/ui/theme.constants';-import * as DocumentPicker from 'expo-document-picker';-import * as FileSystem from 'expo-file-system/legacy';-import { useState } from 'react';+import { useRouter } from 'expo-router';import {Modal,StyleSheet,@@ -10,18 +7,14 @@ import {TouchableOpacity,View,} from 'react-native';-import DocumentScanner from 'react-native-document-scanner-plugin';import { useApiClient } from '@/modules/api/providers/api.provider';import { queryClient } from '@/modules/api/providers/query.provider';import { useOrganizations } from '@/modules/organizations/organizations.provider';import { Icon } from '@/modules/ui/components/icon';import { useAlert } from '@/modules/ui/providers/alert-provider';import { useThemeColor } from '@/modules/ui/providers/use-theme-color';-import { convertImagesToPdf } from '../documents-scan.services';-import { documentsLocalStorage } from '../documents.local-storage';import { uploadDocument } from '../documents.services';-import { syncUnsyncedDocuments } from '../documents.sync.services';-import { RenameDocumentDialog } from './rename-document-dialog';+import { useImportFromFiles } from '../hooks/use-import-from-files.hook';type ImportDrawerProps = {visible: boolean;@@ -29,14 +22,13 @@ type ImportDrawerProps = {};export function ImportDrawer({ visible, onClose }: ImportDrawerProps) {+ const router = useRouter();const themeColors = useThemeColor();const { showAlert } = useAlert();const styles = createStyles({ themeColors });const apiClient = useApiClient();const { currentOrganizationId } = useOrganizations();- const [renameModalVisible, setRenameModalVisible] = useState(false);- const [scannedImageUris, setScannedImageUris] = useState<string[]>([]);- const [defaultDocumentName, setDefaultDocumentName] = useState('');+ const { importFromFiles } = useImportFromFiles();const handleImportFromFiles = async () => {onClose();@@ -50,41 +42,18 @@ export function ImportDrawer({ visible, onClose }: ImportDrawerProps) {return;}- const result = await DocumentPicker.getDocumentAsync({- type: [- 'application/pdf',- 'image/*',- 'application/msword',- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',- 'application/vnd.ms-excel',- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',- 'text/plain',- ],- copyToCacheDirectory: true,- multiple: false,- });-- if (result.canceled) {- return;- }+ const { localDocument } = await importFromFiles();- const pickerFile = result.assets[0];- if (!pickerFile) {+ if (!localDocument) {return;}- const file: LocalDocument = {- uri: pickerFile.uri,- name: pickerFile.name,- type: pickerFile.mimeType,- };-- await uploadDocument({ file, apiClient, organizationId: currentOrganizationId });+ await uploadDocument({ file: localDocument, apiClient, organizationId: currentOrganizationId });await queryClient.invalidateQueries({ queryKey: ['organizations', currentOrganizationId, 'documents'] });showAlert({title: 'Upload Successful',- message: `Successfully uploaded: ${file.name}`,+ message: `Successfully uploaded: ${localDocument.name}`,});} catch (error) {showAlert({@@ -94,179 +63,71 @@ export function ImportDrawer({ visible, onClose }: ImportDrawerProps) {}};- const processScannedImages = async (imageUris: string[], fileName: string) => {- try {- if (currentOrganizationId == null) {- showAlert({- title: 'No Organization Selected',- message: 'Please select an organization before importing documents.',- });- return;- }-- const timestamp = Date.now();- const finalFileName = fileName.endsWith('.pdf') ? fileName : `${fileName}.pdf`;-- const pdfUri = await convertImagesToPdf(imageUris);-- // Copy PDF to permanent location- const permanentUri = `${FileSystem.documentDirectory}${timestamp}_${finalFileName}`;- await FileSystem.copyAsync({- from: pdfUri,- to: permanentUri,- });-- // Get file size- const fileInfo = await FileSystem.getInfoAsync(permanentUri);- const fileSize = fileInfo.exists && 'size' in fileInfo ? fileInfo.size : 0;-- // Save as unsynced document- const unsyncedDoc = {- id: `local_${timestamp}_${Math.random().toString(36).substring(7)}`,- name: finalFileName,- mimeType: 'application/pdf',- localUri: permanentUri,- organizationId: currentOrganizationId,- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString(),- tags: [],- originalSize: fileSize,- };-- await documentsLocalStorage.addUnsyncedDocument(unsyncedDoc);-- try {- await FileSystem.deleteAsync(pdfUri, { idempotent: true });- } catch (error) {- console.error('Error cleaning up temporary PDF:', error);- }-- await queryClient.invalidateQueries({ queryKey: ['organizations', currentOrganizationId, 'documents'] });- // Trigger background sync- void syncUnsyncedDocuments({ organizationId: currentOrganizationId, apiClient });- } catch (error) {- console.error('Error processing scanned image:', error);- showAlert({- title: 'Scan Error',- message: error instanceof Error ? error.message : 'Failed to process scanned document',- });- }- };-- const handleRenameConfirm = async (name: string) => {- setRenameModalVisible(false);- await processScannedImages(scannedImageUris, name);- setScannedImageUris([]);- setDefaultDocumentName('');- };-- const handleRenameCancel = () => {- setRenameModalVisible(false);- setScannedImageUris([]);- setDefaultDocumentName('');- };-- const handleScanDocument = async () => {+ const handleScanDocument = () => {onClose();-- try {- const { scannedImages, status } = await DocumentScanner.scanDocument({- croppedImageQuality: 100,- });-- if (status === 'cancel') {- return;- }-- if (scannedImages && scannedImages.length > 0) {- const timestamp = Date.now();- setDefaultDocumentName(`scanned_document_${timestamp}`);- setScannedImageUris(scannedImages);- setRenameModalVisible(true);- } else {- showAlert({- title: 'Scan Error',- message: 'No images were scanned',- });- }- } catch (error) {- console.error('Error in handleScan:', error);- showAlert({- title: 'Scan Error',- message: error instanceof Error ? error.message : 'Failed to scan document',- });- }+ router.push('/(app)/(with-organizations)/scan');};return (- <>- <Modal- visible={visible}- transparent- animationType="slide"- onRequestClose={onClose}+ <Modal+ visible={visible}+ transparent+ animationType="slide"+ onRequestClose={onClose}+ >+ <TouchableOpacity+ style={styles.backdrop}+ activeOpacity={1}+ onPress={onClose}>- <TouchableOpacity- style={styles.backdrop}- activeOpacity={1}- onPress={onClose}- >- <View style={styles.drawer}>- <View style={styles.header}>- <Text style={styles.title}>Import Document</Text>- </View>-- <View style={styles.optionsContainer}>- <TouchableOpacity- style={styles.optionItem}- onPress={handleImportFromFiles}- >- <View style={styles.optionIconContainer}>- <Icon name="file-plus" size={24} style={styles.optionIcon} />- </View>- <View style={styles.optionTextContainer}>- <Text style={styles.optionTitle}>Import from Files</Text>- <Text style={styles.optionDescription}>- Choose a document from your device- </Text>- </View>- <Icon name="chevron-right" size={18} style={styles.chevronIcon} />- </TouchableOpacity>+ <View style={styles.drawer}>+ <View style={styles.header}>+ <Text style={styles.title}>Import Document</Text>+ </View>- <TouchableOpacity- style={styles.optionItem}- onPress={handleScanDocument}- >- <View style={styles.optionIconContainer}>- <Icon name="camera" size={24} style={styles.optionIcon} />- </View>- <View style={styles.optionTextContainer}>- <Text style={styles.optionTitle}>Scan Document</Text>- <Text style={styles.optionDescription}>- Use camera to scan a document- </Text>- </View>- <Icon name="chevron-right" size={18} style={styles.chevronIcon} />- </TouchableOpacity>- </View>+ <View style={styles.optionsContainer}>+ <TouchableOpacity+ style={styles.optionItem}+ onPress={handleImportFromFiles}+ >+ <View style={styles.optionIconContainer}>+ <Icon name="file-plus" size={24} style={styles.optionIcon} />+ </View>+ <View style={styles.optionTextContainer}>+ <Text style={styles.optionTitle}>Import from Files</Text>+ <Text style={styles.optionDescription}>+ Choose a document from your device+ </Text>+ </View>+ <Icon name="chevron-right" size={18} style={styles.chevronIcon} />+ </TouchableOpacity><TouchableOpacity- style={styles.cancelButton}- onPress={onClose}+ style={styles.optionItem}+ onPress={handleScanDocument}>- <Text style={styles.cancelButtonText}>Cancel</Text>+ <View style={styles.optionIconContainer}>+ <Icon name="camera" size={24} style={styles.optionIcon} />+ </View>+ <View style={styles.optionTextContainer}>+ <Text style={styles.optionTitle}>Scan Document</Text>+ <Text style={styles.optionDescription}>+ Use camera to scan a document+ </Text>+ </View>+ <Icon name="chevron-right" size={18} style={styles.chevronIcon} /></TouchableOpacity></View>- </TouchableOpacity>- </Modal>- <RenameDocumentDialog- visible={renameModalVisible}- defaultName={defaultDocumentName}- onConfirm={handleRenameConfirm}- onCancel={handleRenameCancel}- />- </>+ <TouchableOpacity+ style={styles.cancelButton}+ onPress={onClose}+ >+ <Text style={styles.cancelButtonText}>Cancel</Text>+ </TouchableOpacity>+ </View>+ </TouchableOpacity>+ </Modal>);}diff --git a/apps/mobile/src/modules/documents/documents-scan.services.ts b/apps/mobile/src/modules/documents/documents-scan.services.tsdeleted file mode 100644index 5061fd27..00000000--- a/apps/mobile/src/modules/documents/documents-scan.services.ts+++ /dev/null@@ -1,82 +0,0 @@-import * as FileSystem from 'expo-file-system/legacy';-import * as Print from 'expo-print';--export async function convertImagesToPdf(imageUris: string[]): Promise<string> {- const images = imageUris.map(async (imageUri) => {- try {- // Read the image file- const base64Image = await FileSystem.readAsStringAsync(imageUri, {- encoding: FileSystem.EncodingType.Base64,- });-- // Detect image format from URI- let imageType = 'jpeg';- if (imageUri.toLowerCase().includes('.png')) {- imageType = 'png';- } else if (imageUri.toLowerCase().includes('.jpg') || imageUri.toLowerCase().includes('.jpeg')) {- imageType = 'jpeg';- }-- return { imageType, base64Image };- } catch (error) {- console.error('Error converting image to PDF:', error);- throw error;- }- });-- // Create HTML with the image embedded- const html = `- <!DOCTYPE html>- <html>- <head>- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <style>- @page {- margin: 0;- size: A4;- }- body {- margin: 0;- padding: 0;- }- .page {- page-break-after: always;- display: flex;- justify-content: center;- align-items: center;- width: 100vw;- height: 100vh;- min-height: 100vh;- }- img {- max-width: 100%;- max-height: 100vh;- object-fit: contain;- display: block;- }- </style>- </head>- <body>- ${(- await Promise.all(images)- )- .map(- image => `- <div class="page">- <img src="data:image/${image.imageType};base64,${image.base64Image}" />- </div>- `,- )- .join('')}- </body>- </html>-`;-- // Generate PDF from HTML- const { uri: pdfUri } = await Print.printToFileAsync({- html,- base64: false,- });-- return pdfUri;-}diff --git a/apps/mobile/src/modules/documents/documents-scan/components/document-name-input.tsx b/apps/mobile/src/modules/documents/documents-scan/components/document-name-input.tsxnew file mode 100644index 00000000..ec726e07--- /dev/null+++ b/apps/mobile/src/modules/documents/documents-scan/components/document-name-input.tsx@@ -0,0 +1,74 @@+import type { ScanOutputFormat } from '../documents-scan.types';+import type { ThemeColors } from '@/modules/ui/theme.constants';+import { StyleSheet, Text, TextInput, View } from 'react-native';+import { useThemeColor } from '@/modules/ui/providers/use-theme-color';++type DocumentNameInputProps = {+ value: string;+ onChangeText: (text: string) => void;+ format: ScanOutputFormat;+};++function getFileExtension(format: ScanOutputFormat): string {+ return format === 'images' ? '.jpg' : '.pdf';+}++export function DocumentNameInput({ value, onChangeText, format }: DocumentNameInputProps) {+ const themeColors = useThemeColor();+ const styles = createStyles({ themeColors });++ return (+ <View style={styles.container}>+ <Text style={styles.label}>Document name</Text>+ <View style={styles.inputContainer}>+ <TextInput+ style={styles.input}+ value={value}+ onChangeText={onChangeText}+ placeholder="Enter document name"+ placeholderTextColor={themeColors.mutedForeground}+ autoCapitalize="none"+ autoCorrect={false}+ />+ <Text style={styles.suffix}>{getFileExtension(format)}</Text>+ </View>++ </View>+ );+}++function createStyles({ themeColors }: { themeColors: ThemeColors }) {+ return StyleSheet.create({+ container: {+ marginBottom: 20,+ },+ label: {+ fontSize: 14,+ fontWeight: '600',+ color: themeColors.foreground,+ marginBottom: 8,+ },+ inputContainer: {+ flexDirection: 'row',+ alignItems: 'center',++ backgroundColor: themeColors.secondaryBackground,+ borderRadius: 8,+ borderWidth: 1,+ borderColor: themeColors.border,+ paddingHorizontal: 16,+ paddingVertical: 12,+ color: themeColors.foreground,+ },+ input: {+ fontSize: 16,+ padding: 0,+ margin: 0,+ color: themeColors.foreground,+ },+ suffix: {+ color: themeColors.mutedForeground,+ },++ });+}diff --git a/apps/mobile/src/modules/documents/documents-scan/components/format-selector.tsx b/apps/mobile/src/modules/documents/documents-scan/components/format-selector.tsxnew file mode 100644index 00000000..d6bc1d02--- /dev/null+++ b/apps/mobile/src/modules/documents/documents-scan/components/format-selector.tsx@@ -0,0 +1,165 @@+import type { ScanOutputFormat } from '../documents-scan.types';+import type { IconName } from '@/modules/ui/components/icon';+import type { ThemeColors } from '@/modules/ui/theme.constants';+import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';+import { Icon } from '@/modules/ui/components/icon';+import { useThemeColor } from '@/modules/ui/providers/use-theme-color';++export const formatOptions: {+ key: ScanOutputFormat;+ icon: IconName;+ singleScan: {+ label: string;+ description: string;+ };+ multiScan: {+ label: string;+ description: string;+ };+}[] = [+ {+ key: 'pdf-merged',+ icon: 'file-text',+ singleScan: {+ label: 'PDF',+ description: 'Save scan as a PDF',+ },+ multiScan: {+ label: 'PDF',+ description: 'All scans merged into a single multi-page PDF',+ },+ },+ {+ key: 'pdf-per-page',+ icon: 'copy',+ singleScan: {+ label: 'PDF',+ description: 'Save scan as a PDF',+ },+ multiScan: {+ label: 'PDFs',+ description: 'Save each scan as individual PDF',+ },+ },+ {+ key: 'images',+ icon: 'image',+ singleScan: {+ label: 'Image',+ description: 'Save scan as an image',+ },+ multiScan: {+ label: 'Images',+ description: 'Save each scan as individual images',+ },+ },+];++type FormatSelectorProps = {+ isSinglePage: boolean;+ selectedFormat: ScanOutputFormat;+ onFormatChange: (format: ScanOutputFormat) => void;+};++export function FormatSelector({ isSinglePage, selectedFormat, onFormatChange }: FormatSelectorProps) {+ const themeColors = useThemeColor();+ const styles = createStyles({ themeColors });++ const options = formatOptions+ .filter(option => !isSinglePage || option.key !== 'pdf-per-page')+ .map(option => ({+ key: option.key,+ icon: option.icon,+ label: isSinglePage ? option.singleScan.label : option.multiScan.label,+ description: isSinglePage ? option.singleScan.description : option.multiScan.description,+ }));++ const selectedOption = options.find(opt => opt.key === selectedFormat);++ return (+ <View style={styles.container}>+ <Text style={styles.label}>Output Format</Text>++ <View style={styles.segmentedControl}>+ {options.map(option => (+ <TouchableOpacity+ key={option.key}+ style={[+ styles.segment,+ selectedFormat === option.key && styles.segmentSelected,+ ]}+ onPress={() => onFormatChange(option.key)}+ >+ <Icon+ name={option.icon}+ size={18}+ color={selectedFormat === option.key ? themeColors.primaryForeground : themeColors.foreground}+ />+ <Text+ style={[+ styles.segmentText,+ selectedFormat === option.key && styles.segmentTextSelected,+ ]}+ >+ {option.label}+ </Text>+ </TouchableOpacity>+ ))}+ </View>++ {selectedOption && (+ <View style={styles.descriptionCard}>+ <Text style={styles.descriptionText}>{selectedOption.description}</Text>+ </View>+ )}+ </View>+ );+}++function createStyles({ themeColors }: { themeColors: ThemeColors }) {+ return StyleSheet.create({+ container: {+ marginBottom: 20,+ },+ label: {+ fontSize: 14,+ fontWeight: '600',+ color: themeColors.foreground,+ marginBottom: 8,+ },+ segmentedControl: {+ flexDirection: 'row',+ backgroundColor: themeColors.secondaryBackground,+ borderRadius: 8,+ padding: 4,+ },+ segment: {+ flex: 1,+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'center',+ paddingVertical: 10,+ paddingHorizontal: 8,+ borderRadius: 6,+ gap: 6,+ },+ segmentSelected: {+ backgroundColor: themeColors.primary,+ },+ segmentText: {+ fontSize: 14,+ fontWeight: '600',+ color: themeColors.foreground,+ },+ segmentTextSelected: {+ color: themeColors.primaryForeground,+ },+ descriptionCard: {+ marginTop: 8,+ },+ descriptionText: {+ fontSize: 13,+ color: themeColors.mutedForeground,+ },+ });+}diff --git a/apps/mobile/src/modules/documents/documents-scan/components/image-preview-carousel.tsx b/apps/mobile/src/modules/documents/documents-scan/components/image-preview-carousel.tsxnew file mode 100644index 00000000..2bb4c54f--- /dev/null+++ b/apps/mobile/src/modules/documents/documents-scan/components/image-preview-carousel.tsx@@ -0,0 +1,98 @@+import type { ThemeColors } from '@/modules/ui/theme.constants';+import { useState } from 'react';+import { Dimensions, FlatList, Image, StyleSheet, View } from 'react-native';+import { useThemeColor } from '@/modules/ui/providers/use-theme-color';++type ImagePreviewCarouselProps = {+ imageUris: string[];+};++const { width: SCREEN_WIDTH } = Dimensions.get('window');+const IMAGE_WIDTH = SCREEN_WIDTH - 48; // 24px padding on each side++export function ImagePreviewCarousel({ imageUris }: ImagePreviewCarouselProps) {+ const themeColors = useThemeColor();+ const styles = createStyles({ themeColors });+ const [activeIndex, setActiveIndex] = useState(0);++ const handleScroll = (event: { nativeEvent: { contentOffset: { x: number } } }) => {+ const scrollPosition = event.nativeEvent.contentOffset.x;+ const index = Math.round(scrollPosition / IMAGE_WIDTH);+ setActiveIndex(index);+ };++ return (+ <View style={styles.container}>+ <FlatList+ data={imageUris}+ keyExtractor={(_, index) => index.toString()}+ horizontal+ pagingEnabled+ showsHorizontalScrollIndicator={false}+ onScroll={handleScroll}+ scrollEventThrottle={16}+ snapToInterval={IMAGE_WIDTH}+ decelerationRate="fast"+ contentContainerStyle={styles.listContent}+ renderItem={({ item }) => (+ <View style={styles.imageContainer}>+ <Image source={{ uri: item }} style={styles.image} resizeMode="contain" />+ </View>+ )}+ />++ {imageUris.length > 1 && (+ <View style={styles.dotsContainer}>+ {imageUris.map((_, index) => (+ <View+ key={index}+ style={[+ styles.dot,+ index === activeIndex && styles.dotActive,+ ]}+ />+ ))}+ </View>+ )}+ </View>+ );+}++function createStyles({ themeColors }: { themeColors: ThemeColors }) {+ return StyleSheet.create({+ container: {+ marginBottom: 20,+ },+ listContent: {+ paddingHorizontal: 0,+ },+ imageContainer: {+ width: IMAGE_WIDTH,+ height: 280,+ backgroundColor: themeColors.secondaryBackground,+ borderRadius: 12,+ overflow: 'hidden',+ },+ image: {+ width: '100%',+ height: '100%',+ },+ dotsContainer: {+ flexDirection: 'row',+ justifyContent: 'center',+ alignItems: 'center',+ marginTop: 12,+ gap: 8,+ },+ dot: {+ width: 8,+ height: 8,+ borderRadius: 4,+ backgroundColor: themeColors.border,+ },+ dotActive: {+ backgroundColor: themeColors.primary,+ width: 20,+ },+ });+}diff --git a/apps/mobile/src/modules/documents/documents-scan/documents-scan.constants.ts b/apps/mobile/src/modules/documents/documents-scan/documents-scan.constants.tsnew file mode 100644index 00000000..7829ebf1--- /dev/null+++ b/apps/mobile/src/modules/documents/documents-scan/documents-scan.constants.ts@@ -0,0 +1,4 @@+import { joinUrlPaths } from '@corentinth/chisels';+import * as FileSystem from 'expo-file-system/legacy';++export const SCANS_DIRECTORY_PATH = joinUrlPaths(FileSystem.documentDirectory, 'scans');diff --git a/apps/mobile/src/modules/documents/documents-scan/documents-scan.processing.services.ts b/apps/mobile/src/modules/documents/documents-scan/documents-scan.processing.services.tsnew file mode 100644index 00000000..c7728a83--- /dev/null+++ b/apps/mobile/src/modules/documents/documents-scan/documents-scan.processing.services.ts@@ -0,0 +1,139 @@+import type { ScanOutputFormat } from './documents-scan.types';+import type { LocalDocument } from '@/modules/api/api.models';+import { joinUrlPaths } from '@corentinth/chisels';+import * as FileSystem from 'expo-file-system/legacy';+import * as Print from 'expo-print';+import { getMimeTypeForExtension } from '@/modules/lib/file/file.models';+import { fileToBase64DataUrl } from '@/modules/lib/file/file.services';+import { getExtension } from '@/modules/lib/path/path.models';+import { SCANS_DIRECTORY_PATH } from './documents-scan.constants';++export async function processScannedImages({ imageUris, format, baseName }: { imageUris: string[]; format: ScanOutputFormat; baseName: string }): Promise<{ localDocuments: LocalDocument[] }> {+ if (format === 'pdf-merged') {+ const { pdfUri } = await convertImagesToPdf({ imageUris });+ const fileName = `${baseName}.pdf`;+ const { permanentUri } = await moveToPermanentScanStorage({ fileUri: pdfUri, fileName });++ return {+ localDocuments: [+ {+ uri: permanentUri,+ name: fileName,+ type: 'application/pdf',+ },+ ],+ };+ }++ if (format === 'pdf-per-page') {+ const localDocuments: LocalDocument[] = [];++ for (const [i, imageUri] of imageUris.entries()) {+ const { pdfUri } = await convertImagesToPdf({ imageUris: [imageUri] });+ const fileName = `${baseName}_${i + 1}.pdf`;+ const { permanentUri } = await moveToPermanentScanStorage({ fileUri: pdfUri, fileName });++ localDocuments.push({+ uri: permanentUri,+ name: fileName,+ type: 'application/pdf',+ });+ }++ return { localDocuments };+ }++ if (format === 'images') {+ const localDocuments: LocalDocument[] = [];++ for (const [i, imageUri] of imageUris.entries()) {+ const extension = getExtension(imageUri) ?? 'jpg';+ const mimeType = getMimeTypeForExtension({ extension });+ const fileName = `${baseName}_${i + 1}.${extension}`;++ const { permanentUri } = await moveToPermanentScanStorage({ fileUri: imageUri, fileName });++ localDocuments.push({+ uri: permanentUri,+ name: fileName,+ type: mimeType,+ });+ }++ return { localDocuments };+ }++ // This should not happen due to typing, but safeguard+ throw new Error(`Unsupported scan output format: ${format as string}`);+}++async function ensureScansDirectory(): Promise<void> {+ const { exists } = await FileSystem.getInfoAsync(SCANS_DIRECTORY_PATH);++ if (!exists) {+ await FileSystem.makeDirectoryAsync(SCANS_DIRECTORY_PATH, { intermediates: true });+ }+}++export async function moveToPermanentScanStorage({ fileUri, fileName }: { fileUri: string; fileName: string }): Promise<{ permanentUri: string }> {+ await ensureScansDirectory();++ const permanentUri = joinUrlPaths(SCANS_DIRECTORY_PATH, fileName);++ await FileSystem.moveAsync({+ from: fileUri,+ to: permanentUri,+ });++ return { permanentUri };+}++export async function convertImagesToPdf({ imageUris }: { imageUris: string[] }): Promise<{ pdfUri: string }> {+ const imagesDataUrls = await Promise.all(imageUris.map(async imageUri => fileToBase64DataUrl({ fileUri: imageUri })));++ const html = `+ <!DOCTYPE html>+ <html>+ <head>+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <style>+ @page {+ margin: 0;+ size: A4;+ }+ body {+ margin: 0;+ padding: 0;+ }+ .page {+ page-break-after: always;+ display: flex;+ justify-content: center;+ align-items: center;+ width: 100vw;+ height: 100vh;+ min-height: 100vh;+ }+ img {+ max-width: 100%;+ max-height: 100vh;+ object-fit: contain;+ display: block;+ }+ </style>+ </head>+ <body>+ ${imagesDataUrls+ .map(imageDataUrl => `<div class="page"><img src="${imageDataUrl}" /></div>`)+ .join('')}+ </body>+ </html>+ `;++ const { uri: pdfUri } = await Print.printToFileAsync({+ html,+ base64: false,+ });++ return { pdfUri };+}diff --git a/apps/mobile/src/modules/documents/documents-scan/documents-scan.services.ts b/apps/mobile/src/modules/documents/documents-scan/documents-scan.services.tsnew file mode 100644index 00000000..d68d87bc--- /dev/null+++ b/apps/mobile/src/modules/documents/documents-scan/documents-scan.services.ts@@ -0,0 +1,17 @@+import DocumentScanner from 'react-native-document-scanner-plugin';++export async function scanDocuments(): Promise<{ scannedImageUris?: string[] }> {+ const { scannedImages, status } = await DocumentScanner.scanDocument({+ croppedImageQuality: 100,+ });++ if (status !== 'success') {+ return { scannedImageUris: undefined };+ }++ if (!scannedImages || scannedImages.length === 0) {+ return { scannedImageUris: undefined };+ }++ return { scannedImageUris: scannedImages };+}diff --git a/apps/mobile/src/modules/documents/documents-scan/documents-scan.types.ts b/apps/mobile/src/modules/documents/documents-scan/documents-scan.types.tsnew file mode 100644index 00000000..2c9853b3--- /dev/null+++ b/apps/mobile/src/modules/documents/documents-scan/documents-scan.types.ts@@ -0,0 +1 @@+export type ScanOutputFormat = 'pdf-merged' | 'pdf-per-page' | 'images';diff --git a/apps/mobile/src/modules/documents/documents-scan/screens/scan.screen.tsx b/apps/mobile/src/modules/documents/documents-scan/screens/scan.screen.tsxnew file mode 100644index 00000000..66e44fc1--- /dev/null+++ b/apps/mobile/src/modules/documents/documents-scan/screens/scan.screen.tsx@@ -0,0 +1,363 @@+import type { ScanOutputFormat } from '../documents-scan.types';+import type { ThemeColors } from '@/modules/ui/theme.constants';+import { useRouter } from 'expo-router';+import { useEffect, useState } from 'react';+import { ActivityIndicator, KeyboardAvoidingView, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';+import { SafeAreaView } from 'react-native-safe-area-context';+import { OrganizationPickerButton } from '@/modules/organizations/components/organization-picker-button';+import { OrganizationPickerDrawer } from '@/modules/organizations/components/organization-picker-drawer';+import { useOrganizations } from '@/modules/organizations/organizations.provider';+import { Icon } from '@/modules/ui/components/icon';+import { useAlert } from '@/modules/ui/providers/alert-provider';+import { useThemeColor } from '@/modules/ui/providers/use-theme-color';+import { useScanProcessor } from '../../hooks/use-scan-processor.hook';+import { DocumentNameInput } from '../components/document-name-input';+import { FormatSelector } from '../components/format-selector';+import { ImagePreviewCarousel } from '../components/image-preview-carousel';+import { scanDocuments } from '../documents-scan.services';++function generateDefaultBaseName({ now = new Date() }: { now?: Date } = {}): string {+ return `scan-${now.getTime()}`;+}++export default function ScanReviewScreen() {+ const router = useRouter();+ const themeColors = useThemeColor();+ const styles = createStyles({ themeColors });+ const { showAlert } = useAlert();+ const { currentOrganizationId } = useOrganizations();+ const { processAndUpload, isProcessing } = useScanProcessor();++ const [imageUris, setImageUris] = useState<string[]>([]);+ const [isScanning, setIsScanning] = useState(true);+ const [format, setFormat] = useState<ScanOutputFormat>('pdf-merged');+ const [documentName, setDocumentName] = useState(() => generateDefaultBaseName());+ const [isOrgPickerVisible, setIsOrgPickerVisible] = useState(false);++ const pageCount = imageUris.length;++ useEffect(() => {+ const performScan = async () => {+ try {+ const { scannedImageUris } = await scanDocuments();++ if (!scannedImageUris || scannedImageUris.length === 0) {+ // User cancelled or no images scanned+ router.back();+ return;+ }++ setImageUris(scannedImageUris);+ } catch (error) {+ showAlert({+ title: 'Scan Error',+ message: error instanceof Error ? error.message : 'Failed to scan document',+ });+ router.back();+ } finally {+ setIsScanning(false);+ }+ };++ void performScan();+ }, [router, showAlert]);++ const handleClose = () => {+ router.back();+ };++ const handleConfirm = async () => {+ const baseName = documentName.trim();+ const organizationId = currentOrganizationId;++ if (organizationId == null) {+ showAlert({+ title: 'No Organization Selected',+ message: 'Please select an organization before uploading.',+ });+ return;+ }++ if (!baseName) {+ showAlert({+ title: 'Name Required',+ message: 'Please enter a document name.',+ });+ return;+ }++ const result = await processAndUpload({+ imageUris,+ format,+ baseName,+ organizationId,+ });++ if (result.success) {+ showAlert({+ title: 'Upload Successful',+ message: `Successfully uploaded ${result.documentCount} document${result.documentCount > 1 ? 's' : ''}.`,+ });+ router.back();+ } else {+ showAlert({+ title: 'Upload Failed',+ message: result.error ?? 'Failed to upload documents. Please try again.',+ buttons: [+ { text: 'Cancel', style: 'cancel' },+ { text: 'Retry', onPress: () => void handleConfirm() },+ ],+ });+ }+ };++ if (isScanning) {+ return (+ <SafeAreaView style={styles.container}>+ <View style={styles.centeredContainer}>+ <ActivityIndicator size="large" color={themeColors.primary} />+ <Text style={styles.loadingText}>Opening scanner...</Text>+ </View>+ </SafeAreaView>+ );+ }++ if (imageUris.length === 0) {+ return (+ <SafeAreaView style={styles.container}>+ <View style={styles.centeredContainer}>+ <Text style={styles.errorText}>No images to review</Text>+ <TouchableOpacity style={styles.actionButton} onPress={handleClose}>+ <Text style={styles.actionButtonText}>Go Back</Text>+ </TouchableOpacity>+ </View>+ </SafeAreaView>+ );+ }++ return (+ <SafeAreaView style={styles.container}>+ {/* Header */}+ <View style={styles.header}>+ <TouchableOpacity style={styles.headerButton} onPress={handleClose}>+ <Icon name="x" size={24} color={themeColors.foreground} />+ </TouchableOpacity>+ <Text style={styles.headerTitle}>Review Scan</Text>+ <Text style={styles.pageCount}>+ {pageCount}+ {' '}+ page+ {pageCount > 1 ? 's' : ''}+ </Text>+ </View>++ <KeyboardAvoidingView+ style={styles.keyboardAvoidingView}+ behavior={Platform.OS === 'ios' ? 'padding' : 'height'}+ >+ {/* Content */}+ <ScrollView+ style={styles.content}+ contentContainerStyle={styles.contentContainer}+ keyboardShouldPersistTaps="handled"+ >+ <ImagePreviewCarousel imageUris={imageUris} />++ <FormatSelector selectedFormat={format} onFormatChange={setFormat} isSinglePage={pageCount === 1} />++ <DocumentNameInput+ value={documentName}+ onChangeText={setDocumentName}+ format={format}+ />++ <View style={styles.orgSection}>+ <Text style={styles.sectionLabel}>Upload to</Text>+ <OrganizationPickerButton onPress={() => setIsOrgPickerVisible(true)} />+ </View>+ </ScrollView>+ </KeyboardAvoidingView>++ {/* Footer */}+ <View style={styles.footer}>+ <TouchableOpacity+ style={styles.cancelButton}+ onPress={handleClose}+ disabled={isProcessing}+ >+ <Text style={styles.cancelButtonText}>Cancel</Text>+ </TouchableOpacity>++ <TouchableOpacity+ style={[styles.confirmButton, isProcessing && styles.confirmButtonDisabled]}+ onPress={() => void handleConfirm()}+ disabled={isProcessing}+ >+ {isProcessing+ ? (+ <ActivityIndicator size="small" color={themeColors.primaryForeground} />+ )+ : (+ <>+ <Icon name="upload" size={18} color={themeColors.primaryForeground} />+ <Text style={styles.confirmButtonText}>Confirm</Text>+ </>+ )}+ </TouchableOpacity>+ </View>++ {isProcessing && (+ <View style={styles.loadingOverlay}>+ <View style={styles.loadingCard}>+ <ActivityIndicator size="large" color={themeColors.primary} />+ <Text style={styles.loadingText}>Processing and uploading...</Text>+ </View>+ </View>+ )}++ <OrganizationPickerDrawer+ visible={isOrgPickerVisible}+ onClose={() => setIsOrgPickerVisible(false)}+ />+ </SafeAreaView>+ );+}++function createStyles({ themeColors }: { themeColors: ThemeColors }) {+ return StyleSheet.create({+ container: {+ flex: 1,+ backgroundColor: themeColors.background,+ },+ keyboardAvoidingView: {+ flex: 1,+ flexShrink: 1,+ },+ header: {+ flexDirection: 'row',+ alignItems: 'center',+ paddingHorizontal: 24,+ paddingVertical: 16,+ borderBottomWidth: 1,+ borderBottomColor: themeColors.border,+ },+ headerButton: {+ width: 40,+ height: 40,+ borderRadius: 20,+ backgroundColor: themeColors.secondaryBackground,+ justifyContent: 'center',+ alignItems: 'center',+ },+ headerTitle: {+ flex: 1,+ fontSize: 18,+ fontWeight: 'bold',+ color: themeColors.foreground,+ marginLeft: 16,+ },+ pageCount: {+ fontSize: 14,+ color: themeColors.mutedForeground,+ backgroundColor: themeColors.secondaryBackground,+ paddingHorizontal: 12,+ paddingVertical: 6,+ borderRadius: 16,+ },+ content: {+ flex: 1,+ },+ contentContainer: {+ padding: 24,+ },+ orgSection: {+ marginBottom: 20,+ },+ sectionLabel: {+ fontSize: 14,+ fontWeight: '600',+ color: themeColors.foreground,+ marginBottom: 8,+ },+ footer: {+ flexDirection: 'row',+ paddingHorizontal: 24,+ paddingVertical: 16,+ borderTopWidth: 1,+ borderTopColor: themeColors.border,+ gap: 12,+ },+ cancelButton: {+ flex: 1,+ paddingVertical: 14,+ borderWidth: 1,+ borderColor: themeColors.border,+ borderRadius: 8,+ alignItems: 'center',+ justifyContent: 'center',+ },+ cancelButtonText: {+ fontSize: 16,+ fontWeight: '600',+ color: themeColors.foreground,+ },+ confirmButton: {+ flex: 1,+ flexDirection: 'row',+ paddingVertical: 14,+ backgroundColor: themeColors.primary,+ borderRadius: 8,+ alignItems: 'center',+ justifyContent: 'center',+ gap: 8,+ },+ confirmButtonDisabled: {+ opacity: 0.6,+ },+ confirmButtonText: {+ fontSize: 16,+ fontWeight: '600',+ color: themeColors.primaryForeground,+ },+ loadingOverlay: {+ ...StyleSheet.absoluteFillObject,+ backgroundColor: 'rgba(0, 0, 0, 0.5)',+ justifyContent: 'center',+ alignItems: 'center',+ },+ loadingCard: {+ backgroundColor: themeColors.background,+ padding: 32,+ borderRadius: 16,+ alignItems: 'center',+ gap: 16,+ },+ loadingText: {+ fontSize: 16,+ color: themeColors.foreground,+ fontWeight: '500',+ },+ centeredContainer: {+ flex: 1,+ justifyContent: 'center',+ alignItems: 'center',+ padding: 32,+ },+ errorText: {+ fontSize: 16,+ color: themeColors.mutedForeground,+ marginBottom: 16,+ },+ actionButton: {+ paddingHorizontal: 24,+ paddingVertical: 12,+ backgroundColor: themeColors.primary,+ borderRadius: 8,+ },+ actionButtonText: {+ fontSize: 16,+ fontWeight: '600',+ color: themeColors.primaryForeground,+ },+ });+}diff --git a/apps/mobile/src/modules/documents/hooks/use-import-from-files.hook.ts b/apps/mobile/src/modules/documents/hooks/use-import-from-files.hook.tsnew file mode 100644index 00000000..41938a90--- /dev/null+++ b/apps/mobile/src/modules/documents/hooks/use-import-from-files.hook.ts@@ -0,0 +1,46 @@+import * as DocumentPicker from 'expo-document-picker';++const SUPPORTED_DOCUMENT_TYPES = [+ 'image/*',+ 'text/*',+ 'application/pdf',+ 'application/msword',+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ 'application/vnd.ms-excel',+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+];++export function useImportFromFiles() {+ const importFromFiles = async ({ selectableTypes = SUPPORTED_DOCUMENT_TYPES }: { selectableTypes?: string[] } = {}) => {+ const result = await DocumentPicker.getDocumentAsync({+ type: selectableTypes,+ copyToCacheDirectory: true,+ multiple: false,+ });++ if (result.canceled) {+ return { localDocument: undefined };+ }++ if (result.assets.length === 0) {+ return { localDocument: undefined };+ }++ const firstAsset = result.assets[0];++ if (!firstAsset) {+ // For type safety, array length was already checked+ return { localDocument: undefined };+ }++ return {+ localDocument: {+ uri: firstAsset.uri,+ name: firstAsset.name,+ type: firstAsset.mimeType,+ },+ };+ };++ return { importFromFiles };+}diff --git a/apps/mobile/src/modules/documents/hooks/use-scan-processor.hook.ts b/apps/mobile/src/modules/documents/hooks/use-scan-processor.hook.tsnew file mode 100644index 00000000..d27ee78f--- /dev/null+++ b/apps/mobile/src/modules/documents/hooks/use-scan-processor.hook.ts@@ -0,0 +1,66 @@+import type { ScanOutputFormat } from '../documents-scan/documents-scan.types';+import { castError } from '@corentinth/chisels';+import { useState } from 'react';+import { useApiClient } from '@/modules/api/providers/api.provider';+import { queryClient } from '@/modules/api/providers/query.provider';+import { processScannedImages } from '../documents-scan/documents-scan.processing.services';+import { uploadDocument } from '../documents.services';++export function useScanProcessor() {+ const apiClient = useApiClient();+ const [isProcessing, setIsProcessing] = useState(false);++ const processAndUpload = async ({+ imageUris,+ format,+ baseName,+ organizationId,+ }: {+ imageUris: string[];+ format: ScanOutputFormat;+ baseName: string;+ organizationId: string;+ }): Promise<{+ success: boolean;+ documentCount: number;+ error?: string;+ }> => {+ setIsProcessing(true);++ try {+ const { localDocuments } = await processScannedImages({+ imageUris,+ format,+ baseName,+ });++ for (const localDocument of localDocuments) {+ await uploadDocument({+ file: localDocument,+ apiClient,+ organizationId,+ });+ }++ await queryClient.invalidateQueries({ queryKey: ['organizations', organizationId, 'documents'] });++ return {+ success: true,+ documentCount: localDocuments.length,+ };+ } catch (error) {+ return {+ success: false,+ documentCount: 0,+ error: castError(error).message,+ };+ } finally {+ setIsProcessing(false);+ }+ };++ return {+ processAndUpload,+ isProcessing,+ };+}diff --git a/apps/mobile/src/modules/lib/file/file.models.test.ts b/apps/mobile/src/modules/lib/file/file.models.test.tsnew file mode 100644index 00000000..726e4a6e--- /dev/null+++ b/apps/mobile/src/modules/lib/file/file.models.test.ts@@ -0,0 +1,23 @@+import { describe, expect, test } from 'vitest';+import { getMimeTypeForExtension } from './file.models';++describe('file.services', () => {+ describe('getMimeTypeForExtension', () => {+ test('given a known extension, returns its mime type', () => {+ expect(getMimeTypeForExtension({ extension: 'png' })).toBe('image/png');+ expect(getMimeTypeForExtension({ extension: 'jpg' })).toBe('image/jpeg');+ expect(getMimeTypeForExtension({ extension: 'jpeg' })).toBe('image/jpeg');+ expect(getMimeTypeForExtension({ extension: 'pdf' })).toBe('application/pdf');+ });++ test('given an unknown extension, returns the fallback mime type', () => {+ expect(getMimeTypeForExtension({ extension: 'foo' })).toBe('application/octet-stream');+ expect(getMimeTypeForExtension({ extension: undefined })).toBe('application/octet-stream');+ });++ test('the fallback mime type can be customized', () => {+ expect(getMimeTypeForExtension({ extension: 'foo', fallbackMimeType: 'text/plain' })).toBe('text/plain');+ expect(getMimeTypeForExtension({ extension: undefined, fallbackMimeType: 'text/plain' })).toBe('text/plain');+ });+ });+});diff --git a/apps/mobile/src/modules/lib/file/file.models.ts b/apps/mobile/src/modules/lib/file/file.models.tsnew file mode 100644index 00000000..9a42a335--- /dev/null+++ b/apps/mobile/src/modules/lib/file/file.models.ts@@ -0,0 +1,21 @@+// At the moment, only these mime types are needed, will switch to mime-db if needed later+const mimeTypes: Record<string, string> = {+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ pdf: 'application/pdf',+};++export function getMimeTypeForExtension({+ extension,+ fallbackMimeType = 'application/octet-stream',+}: {+ extension: string | undefined;+ fallbackMimeType?: string;+}): string {+ if (extension === undefined) {+ return fallbackMimeType;+ }++ return mimeTypes[extension] ?? fallbackMimeType;+}diff --git a/apps/mobile/src/modules/lib/file/file.services.ts b/apps/mobile/src/modules/lib/file/file.services.tsnew file mode 100644index 00000000..b735c43f--- /dev/null+++ b/apps/mobile/src/modules/lib/file/file.services.ts@@ -0,0 +1,14 @@+import * as FileSystem from 'expo-file-system/legacy';+import { getExtension } from '../path/path.models';+import { getMimeTypeForExtension } from './file.models';++export async function fileToBase64DataUrl({ fileUri }: { fileUri: string }) {+ const base64 = await FileSystem.readAsStringAsync(fileUri, { encoding: FileSystem.EncodingType.Base64 });++ const extension = getExtension(fileUri);+ const mimeType = getMimeTypeForExtension({ extension });++ const base64DataUrl = `data:${mimeType};base64,${base64}`;++ return base64DataUrl;+}diff --git a/apps/mobile/src/modules/lib/path/path.models.test.ts b/apps/mobile/src/modules/lib/path/path.models.test.tsnew file mode 100644index 00000000..0a77f391--- /dev/null+++ b/apps/mobile/src/modules/lib/path/path.models.test.ts@@ -0,0 +1,23 @@+import { describe, expect, test } from 'vitest';+import { getExtension } from './path.models';++describe('path models', () => {+ describe('getExtension', () => {+ test('extracts the extension from a file name', () => {+ expect(getExtension('file.txt')).to.eql('txt');+ expect(getExtension('file.test.txt')).to.eql('txt');+ });++ test('file name without extension returns no extension', () => {+ expect(getExtension('file')).to.eql(undefined);+ expect(getExtension('file.')).to.eql(undefined);+ expect(getExtension('')).to.eql(undefined);+ expect(getExtension('.')).to.eql(undefined);+ });++ test('extensions are lowercased', () => {+ expect(getExtension('file.TXT')).to.eql('txt');+ expect(getExtension('file.Test.TxT')).to.eql('txt');+ });+ });+});diff --git a/apps/mobile/src/modules/lib/path/path.models.ts b/apps/mobile/src/modules/lib/path/path.models.tsnew file mode 100644index 00000000..98e336e3--- /dev/null+++ b/apps/mobile/src/modules/lib/path/path.models.ts@@ -0,0 +1,14 @@+export function getExtension(path: string): string | undefined {+ const parts = path.split('.');+ if (parts.length <= 1) {+ return undefined;+ }++ const extension = parts.at(-1)?.toLowerCase();++ if (extension === '') {+ return undefined;+ }++ return extension;+}