Initial commit

This commit is contained in:
2026-07-31 16:53:16 +02:00
commit e49d6f0e5b
67 changed files with 20163 additions and 0 deletions

View File

@@ -0,0 +1,95 @@
import { Redirect, Tabs } from 'expo-router';
import { Home, Clock, CalendarIcon, FileText, Image as ImageIcon, Car } from 'lucide-react-native';
import { useContext } from 'react';
import { AuthContext } from '@/utils/authContext';
import { useSafeAreaInsets } from "react-native-safe-area-context";
export default function ProtectedLayout() {
const authState = useContext(AuthContext);
const insets = useSafeAreaInsets();
if (!authState.isReady) {
return null;
}
if (!authState.isAuthenticated) {
return <Redirect href="/login" />;
}
return (
<Tabs
screenOptions={{
headerShown: false,
tabBarStyle: {
backgroundColor: '#ffffff',
borderTopWidth: 1,
borderTopColor: '#f3f4f6',
height: 70 + insets.bottom,
paddingBottom: insets.bottom,
paddingTop: 10,
paddingHorizontal: 10,
},
tabBarActiveTintColor: '#1071C2',
tabBarInactiveTintColor: '#9ca3af',
tabBarLabelStyle: {
fontSize: 12,
fontWeight: '600',
marginTop: 4
}
}}
backBehavior='history'
>
<Tabs.Screen
name="index"
options={{
title: 'Home',
tabBarIcon: ({ color, size }) => <Home pointerEvents="none" color={color} size={24} />,
}}
/>
<Tabs.Screen
name="attendance/index"
options={{
title: 'Presenze',
tabBarIcon: ({ color, size }) => <Clock pointerEvents="none" color={color} size={24} />,
}}
/>
<Tabs.Screen
name="journal"
options={{
title: 'Giornale',
tabBarIcon: ({ color, size }) => <ImageIcon pointerEvents="none" color={color} size={24} />,
}}
/>
<Tabs.Screen
name="permits/index"
options={{
title: 'Ferie',
tabBarIcon: ({ color, size }) => <CalendarIcon pointerEvents="none" color={color} size={24} />,
}}
/>
<Tabs.Screen
name="invoice"
options={{
title: 'Fatture',
tabBarIcon: ({ color, size }) => <FileText pointerEvents="none" color={color} size={24} />,
href: authState.user?.isAdmin ? undefined : null,
}}
/>
<Tabs.Screen
name="machine/index"
options={{
title: 'Macchine',
tabBarIcon: ({ color, size }) => <Car pointerEvents="none" color={color} size={24} />,
href: authState.user?.isAdmin ? undefined : null,
}}
/>
<Tabs.Screen
name="profile"
options={{
href: null,
title: 'Profilo',
}}
/>
</Tabs>
);
}

View File

@@ -0,0 +1,240 @@
import { useAlert } from '@/components/AlertComponent';
import AttendanceCard from '@/components/AttendanceCard';
import FilterModal from '@/components/FilterModal';
import LoadingScreen from '@/components/LoadingScreen';
import QrScanModal from '@/components/QrScanModal';
import api from '@/utils/api';
import { formatTime } from '@/utils/dateTime';
import { StatusBar } from 'expo-status-bar';
import { CheckCircle2, Filter, IdCardLanyard, QrCode } from 'lucide-react-native';
import React, { useEffect, useState } from 'react';
import { RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Place, AttendanceRecord } from '@/types/types';
export default function AttendanceScreen() {
const alert = useAlert();
const [showScanner, setShowScanner] = useState(false);
const [lastScan, setLastScan] = useState<{ type: string; time: string; site: string } | null>(null);
const [attendances, setAttendances] = useState<AttendanceRecord[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
// Filters state
const [isFilterVisible, setIsFilterVisible] = useState(false);
const [places, setPlaces] = useState<Place[]>([]);
const [filterRange, setFilterRange] = useState<{ startDate: string | null; endDate: string | null }>({ startDate: null, endDate: null });
const [filterPlace, setFilterPlace] = useState<any>(null);
const activeFiltersCount = (filterRange.startDate ? 1 : 0) + (filterPlace ? 1 : 0);
const fetchPlaces = async () => {
try {
const response = await api.get('/place/get-places');
if (response.data?.success) {
setPlaces(response.data.places || []);
}
} catch (error) {
console.error('Errore nel recupero dei cantieri:', error);
}
};
const fetchAttendances = async (currentRange = filterRange, currentPlace = filterPlace) => {
try {
if (!refreshing) setIsLoading(true);
// Pass range directly as an object { startDate, endDate } or null
const rangeParam = currentRange.startDate ? currentRange : null;
const params = { range: rangeParam, place: currentPlace };
const response = await api.post('/attendance/list', { params });
if (response.data?.success) {
setAttendances(response.data.result || []);
}
} catch (error) {
console.error('Errore nel recupero delle presenze:', error);
alert.showAlert('error', 'Errore', 'Impossibile recuperare le presenze. Riprova più tardi.');
} finally {
setIsLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
fetchPlaces();
fetchAttendances();
setLastScan(null);
}, []);
const onRefresh = () => {
setRefreshing(true);
fetchAttendances();
setLastScan(null);
};
const handleStartScan = () => {
setShowScanner(true);
};
const onScan = async (data: string) => {
console.log('Scanned data:', data);
try {
const response = await api.post('/attendance/scan', { uuid: data });
if (response.data?.success) {
console.log('Scan data sent successfully:', response.data);
fetchAttendances();
setLastScan({
type: response.data.type,
time: formatTime(response.data.time),
site: response.data.site
});
} else {
alert.showAlert('error', 'Errore', response.data?.message || 'Impossibile registrare la presenza.');
}
} catch (error) {
console.error('Errore nell\'invio dei dati di scansione:', error);
alert.showAlert('error', 'Errore', 'Impossibile registrare la presenza. Riprova più tardi.');
return;
}
};
if (isLoading && !refreshing) {
return <LoadingScreen />;
}
return (
<View className="flex-1 bg-primary-dark">
<StatusBar style="light" />
{/* Header */}
<SafeAreaView edges={['top']} className='pt-5'>
<View className="pb-6 px-6 z-10 flex-row justify-between items-center">
<View>
<Text className="text-white text-md font-semibold uppercase tracking-wider mb-1">Elenco delle tue presenze</Text>
<Text className="text-yellow-400 text-3xl font-bold leading-tight">Presenze</Text>
</View>
<View className="bg-white/10 p-4 rounded-full">
<IdCardLanyard size={32} color="white" pointerEvents="none" />
</View>
</View>
</SafeAreaView>
<View className="flex-1 bg-gray-50 rounded-t-[2.5rem] overflow-hidden">
<ScrollView
contentContainerStyle={{ paddingBottom: 100 }}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />
}
>
<View className="flex-1 p-5 items-center pt-8">
{/* Feedback Card */}
{lastScan ? (
<View className="w-full bg-green-50 border border-green-200 rounded-3xl p-5 mb-8 flex-row items-center gap-4 shadow-sm">
<View className="bg-green-500 rounded-full p-3 shadow-lg shadow-green-500/40 flex-shrink-0">
<CheckCircle2 size={32} color="white" pointerEvents="none" />
</View>
<View className="flex-1">
<Text
className="font-bold text-green-800 text-xl leading-tight"
numberOfLines={1}
ellipsizeMode="tail"
>
{lastScan.type} Registrata
</Text>
<Text
className="text-base text-green-700 font-medium mt-0.5 leading-snug"
numberOfLines={2}
ellipsizeMode="tail"
>
{lastScan.site} alle {lastScan.time}
</Text>
</View>
</View>
) : null}
{/* Scanner Section */}
<View className="w-full mb-6">
<View className="bg-white rounded-3xl p-8 shadow-sm border border-gray-100">
<Text className="text-2xl font-bold text-gray-800 mb-6 text-center">Scansione QR Code</Text>
<TouchableOpacity
onPress={handleStartScan}
className="bg-[#1071C2] rounded-2xl py-6 flex-row items-center justify-center active:bg-blue-700 shadow-lg shadow-blue-900/20 active:scale-[0.98]"
>
<QrCode color="white" size={32} pointerEvents="none" />
<Text className="text-white text-xl font-bold ml-3 uppercase">Scansiona Codice</Text>
</TouchableOpacity>
<Text className="text-gray-500 text-center mt-6 text-base px-2 leading-relaxed">
Posiziona il codice QR davanti alla fotocamera per registrare l'ingresso o l'uscita dal cantiere
</Text>
</View>
</View>
{/* History using AttendanceCard component */}
<View className="w-full mt-4">
<Text className="text-gray-500 font-bold text-base mb-4 uppercase tracking-wider px-2">Ultime Presenze</Text>
{attendances.length === 0 ? (
<View className="bg-white p-6 rounded-3xl border border-gray-100 items-center justify-center border-dashed">
<Text className="text-gray-400 font-medium">Nessuna presenza registrata</Text>
</View>
) : (
<View>
{attendances.map((item, index) => (
<AttendanceCard key={index} item={item} />
))}
</View>
)}
</View>
</View>
</ScrollView>
{/* FAB Filter */}
<TouchableOpacity
onPress={() => setIsFilterVisible(true)}
className="absolute bottom-8 right-6 w-16 h-16 bg-[#1071C2] rounded-full shadow-lg items-center justify-center active:scale-90"
>
<Filter size={28} color="white" pointerEvents="none" />
{activeFiltersCount > 0 && (
<View className="absolute top-0 right-0 bg-red-500 w-6 h-6 rounded-full items-center justify-center border-2 border-white">
<Text className="text-white text-xs font-bold">{activeFiltersCount}</Text>
</View>
)}
</TouchableOpacity>
{/* Filter Modal */}
<FilterModal
visible={isFilterVisible}
places={places}
currentRange={filterRange}
currentPlace={filterPlace}
onClose={() => setIsFilterVisible(false)}
onApply={(range, place) => {
setFilterRange(range);
setFilterPlace(place);
setIsFilterVisible(false);
fetchAttendances(range, place);
}}
onReset={() => {
const emptyRange = { startDate: null, endDate: null };
setFilterRange(emptyRange);
setFilterPlace(null);
setIsFilterVisible(false);
fetchAttendances(emptyRange, null);
}}
/>
{/* Qr Scanner Modal */}
<QrScanModal
visible={showScanner}
onClose={() => setShowScanner(false)}
onScan={onScan}
/>
</View>
</View>
);
}

192
app/(protected)/index.tsx Normal file
View File

@@ -0,0 +1,192 @@
import AttendanceCard from '@/components/AttendanceCard';
import LoadingScreen from '@/components/LoadingScreen';
import api from '@/utils/api';
import { AuthContext } from '@/utils/authContext';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { FileText, QrCode, User } from 'lucide-react-native';
import React, { useContext, useEffect, useState } from 'react';
import { RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
export default function HomeScreen() {
const router = useRouter();
const { user } = useContext(AuthContext);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [updates, setUpdates] = useState<any[]>([]);
const [attendances, setAttendances] = useState<any[]>([]);
const fetchDashboardData = async () => {
try {
if (!refreshing) setIsLoading(true);
const params = { range: null, place: null };
// Parallel requests for journal and attendance data
const [journalRes, attendanceRes] = await Promise.all([
api.post('/journal/list', { params }),
api.post('/attendance/list', { params })
]);
// Select first element of journal (slice 0,1)
if (journalRes.data?.success) {
setUpdates(journalRes.data.result.slice(0, 1));
}
// Select first 2 elements of attendances (slice 0,2)
if (attendanceRes.data?.success) {
setAttendances(attendanceRes.data.result.slice(0, 2));
}
} catch (error) {
console.error('Errore nel recupero dei dati della dashboard:', error);
} finally {
setIsLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
fetchDashboardData();
}, []);
const onRefresh = () => {
setRefreshing(true);
fetchDashboardData();
};
if (isLoading && !refreshing) {
return (
<LoadingScreen />
);
}
return (
<View className="flex-1 bg-primary-dark">
<StatusBar style="light" />
<SafeAreaView edges={['top']} className='pt-5'>
{/* Custom Banner */}
<View className="pb-6 px-6 shadow-sm z-10">
<View className="flex-row justify-between items-start">
<View className="flex-row items-center gap-4 flex-1 mr-4">
<View className="flex-1">
<Text className="text-neutral-50 text-md font-semibold uppercase tracking-wider mb-2">
IP Costruzioni SRL
</Text>
<Text className="text-white text-4xl font-bold leading-tight">
Ciao <Text className="text-yellow-400">{user?.firstName}</Text>
</Text>
</View>
</View>
<View className="flex-row gap-4 flex-shrink-0 items-center">
{/* Profile Avatar */}
<TouchableOpacity className="p-3 bg-white/10 rounded-full active:bg-white/20" onPress={() => router.push('/profile')}>
<User size={28} color="white" pointerEvents="none"/>
</TouchableOpacity>
</View>
</View>
</View>
</SafeAreaView>
{/* Scrollable Content */}
<ScrollView
className="flex-1 bg-gray-50 rounded-t-[2.5rem] px-5 pt-6"
contentContainerStyle={{ paddingBottom: 50, gap: 24 }}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />
}
>
{/* Quick Actions */}
<View>
<Text className="text-gray-800 text-xl font-bold mb-4 px-1">Azioni Rapide</Text>
<View className="flex-row gap-5">
<TouchableOpacity
onPress={() => router.push('/attendance')}
className="flex-1 bg-white p-6 rounded-3xl shadow-sm items-center justify-center gap-4 border border-gray-100 active:scale-[0.98]"
>
<View className="w-20 h-20 rounded-full bg-blue-50 items-center justify-center mb-1">
<QrCode size={40} color="#1071C2" pointerEvents="none"/>
</View>
<Text className="text-lg font-bold text-gray-700 text-center">Nuova Presenza</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => router.push('/journal/add')}
className="flex-1 bg-white p-6 rounded-3xl shadow-sm items-center justify-center gap-4 border border-gray-100 active:scale-[0.98]"
>
<View className="w-20 h-20 rounded-full bg-blue-50 items-center justify-center mb-1">
<FileText size={40} color="#1071C2" pointerEvents="none"/>
</View>
<Text className="text-lg font-bold text-gray-700 text-center">Nuovo{'\n'} Giornale</Text>
</TouchableOpacity>
</View>
</View>
{/* Journal */}
<View>
<View className="flex-row justify-between items-center px-1 mb-4">
<Text className="text-gray-800 text-xl font-bold">Giornale di Cantiere</Text>
</View>
<View className="gap-4">
{updates.map((item, index) => (
<View key={index} className="bg-white p-5 rounded-3xl shadow-sm border border-gray-100 flex-row items-center">
<View className="bg-blue-50 p-4 rounded-full mr-4 flex-shrink-0">
<FileText size={24} color="#1071C2" pointerEvents="none"/>
</View>
<View className="flex-1 mr-2">
<Text className="text-base font-bold text-primary-dark mb-1 leading-tight uppercase" numberOfLines={2}>
{item.place_name}
</Text>
<Text className="text-xs font-medium text-primary-dark mb-1 leading-tight" numberOfLines={2}>
{item.place_address}
</Text>
<Text className="text-xs font-bold text-gray-400 mt-1">
{item.date}
</Text>
</View>
</View>
))}
{!isLoading && updates.length === 0 && (
<View className="bg-white p-6 rounded-3xl border border-gray-100 items-center justify-center border-dashed">
<Text className="text-gray-400 font-medium">Nessun aggiornamento recente</Text>
</View>
)}
{isLoading && updates.length === 0 && (
<View className="bg-white p-5 rounded-3xl border border-gray-100 h-24 justify-center items-center">
<Text className="text-gray-400">Caricamento...</Text>
</View>
)}
</View>
</View>
{/* Attendance */}
<View>
<View className="flex-row justify-between items-center px-1 mb-4">
<Text className="text-gray-800 text-xl font-bold">Presenze</Text>
</View>
<View className="gap-4">
{attendances.map((item, index) => (
<AttendanceCard key={index} item={item} />
))}
{!isLoading && attendances.length === 0 && (
<View className="bg-white p-6 rounded-3xl border border-gray-100 items-center justify-center border-dashed">
<Text className="text-gray-400 font-medium">Nessuna presenza recente</Text>
</View>
)}
{isLoading && attendances.length === 0 && (
<View className="bg-white p-5 rounded-3xl border border-gray-100 h-24 justify-center items-center">
<Text className="text-gray-400">Caricamento...</Text>
</View>
)}
</View>
</View>
</ScrollView>
</View>
);
}

View File

@@ -0,0 +1,153 @@
import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Linking } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { ChevronLeft, Download, CheckCircle2, XCircle, Calendar, CreditCard } from 'lucide-react-native';
import api from '@/utils/api';
import { useAlert } from '@/components/AlertComponent';
import LoadingScreen from '@/components/LoadingScreen';
import { InvoiceInfo, InvoiceAccounting } from '@/types/types';
export default function InvoiceDetailScreen() {
const router = useRouter();
const { id } = useLocalSearchParams();
const alert = useAlert();
const [invoiceInfo, setInvoiceInfo] = useState<InvoiceInfo | null>(null);
const [partite, setPartite] = useState<InvoiceAccounting[]>([]);
const [isLoading, setIsLoading] = useState(true);
const fetchInvoiceInfo = async () => {
try {
const response = await api.get(`/invoice-supplier/get-info?id=${id}`);
if (response.data?.success) {
setInvoiceInfo(response.data.result.info);
// Map backend keys to our frontend types
const mappedPartite: InvoiceAccounting[] = response.data.result.partite.map((p: any) => ({
expiry: p.scadenza,
tpa_description: p.tpa_descrizione,
amount: p.importo_dovuto,
isPaid: p.pagata
}));
setPartite(mappedPartite);
}
} catch (error) {
console.error('Error fetching invoice info:', error);
alert.showAlert('error', 'Errore', 'Impossibile recuperare il dettaglio della fattura.');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
if (id) {
fetchInvoiceInfo();
}
}, [id]);
const handleDownload = () => {
if (invoiceInfo?.link) {
Linking.openURL(invoiceInfo.link);
} else {
alert.showAlert('error', 'Nessun Documento', 'Non è presente un documento allegato per questa fattura.');
}
};
if (isLoading || !invoiceInfo) {
return <LoadingScreen />;
}
return (
<View className="flex-1 bg-gray-50">
<StatusBar style="dark" />
{/* Header */}
<View className="bg-white px-6 pb-6 shadow-sm border-b border-gray-100">
<SafeAreaView edges={['top']} className="pt-5 flex-row items-center justify-between">
<TouchableOpacity onPress={() => router.back()} className="p-2 bg-gray-50 rounded-full active:bg-gray-100">
<ChevronLeft size={24} color="#082963" />
</TouchableOpacity>
<Text className="text-xl font-bold text-gray-800 text-center flex-1">Dettaglio Fattura</Text>
<TouchableOpacity onPress={handleDownload} className="p-2.5 bg-blue-50 rounded-full active:bg-blue-100 shadow-sm">
<Download size={22} color="#1071C2" />
</TouchableOpacity>
</SafeAreaView>
</View>
<ScrollView contentContainerStyle={{ padding: 20, paddingBottom: 100, gap: 16 }} showsVerticalScrollIndicator={false}>
{/* General Info Card */}
<View className="bg-white p-6 rounded-3xl shadow-sm border border-gray-100">
<Text className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">Informazioni</Text>
<View className="mb-4">
<Text className="text-xs font-bold text-gray-400 uppercase mb-1">Numero Documento</Text>
<Text className="text-base font-bold text-gray-800">{invoiceInfo.documentNumber}</Text>
</View>
<View className="mb-4">
<Text className="text-xs font-bold text-gray-400 uppercase mb-1">Fornitore</Text>
<Text className="text-xl font-bold text-[#082963]">{invoiceInfo.supplier}</Text>
</View>
<View className="mb-4">
<Text className="text-xs font-bold text-gray-400 uppercase mb-1">Cantiere</Text>
<Text className="text-base font-bold text-gray-800">{invoiceInfo.placeName}</Text>
</View>
<View className="flex-row justify-between bg-gray-50 p-4 rounded-2xl mb-2">
<View>
<Text className="text-xs font-bold text-gray-400 uppercase mb-1">Data Documento</Text>
<Text className="font-bold text-gray-800">{invoiceInfo.date}</Text>
</View>
<View className="items-end">
<Text className="text-xs font-bold text-gray-400 uppercase mb-1">Importo</Text>
<Text className="font-bold text-[#1071C2]">{invoiceInfo.totalAmount}</Text>
</View>
</View>
</View>
{/* Expiries */}
{partite && partite.length > 0 && (
<View className="bg-white p-6 rounded-3xl shadow-sm border border-gray-100">
<Text className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">Scadenze</Text>
<View className="gap-4">
{partite.map((item, idx) => (
<View key={idx} className={`border border-gray-100 rounded-2xl p-4 ${item.isPaid ? 'bg-green-50/30' : 'bg-red-50/30'}`}>
<View className="flex-row justify-between items-center mb-3">
<View className="flex-row items-center gap-2">
<Calendar size={16} color="#082963" />
<Text className="font-bold text-[#082963]">{item.expiry}</Text>
</View>
<View className={`px-2 py-1 rounded-md flex-row items-center gap-1 ${item.isPaid ? 'bg-green-100' : 'bg-red-100'}`}>
{item.isPaid ? <CheckCircle2 size={12} color="#109D59" /> : <XCircle size={12} color="#DC4437" />}
<Text className={`text-[10px] font-bold uppercase ${item.isPaid ? 'text-green-700' : 'text-red-700'}`}>
{item.isPaid ? 'Pagata' : 'Da Pagare'}
</Text>
</View>
</View>
<View className="flex-row justify-between items-center pt-3 border-t border-gray-100 gap-2">
<View className="flex-row items-center gap-2 flex-1 mr-2">
<View className="mt-0.5">
<CreditCard size={14} color="#8F9BB3" />
</View>
<Text className="text-xs uppercase text-gray-500 font-medium shrink flex-wrap">{item.tpa_description}</Text>
</View>
<Text className={`font-bold text-base whitespace-nowrap ${item.isPaid ? 'text-[#109D59]' : 'text-[#DC4437]'}`}>
{item.amount}
</Text>
</View>
</View>
))}
</View>
</View>
)}
</ScrollView>
</View>
);
}

View File

@@ -0,0 +1,10 @@
import {Stack} from 'expo-router';
export default function InvoiceLayout() {
return (
<Stack screenOptions={{headerShown: false}}>
<Stack.Screen name="index" />
<Stack.Screen name="[id]" />
</Stack>
);
}

View File

@@ -0,0 +1,159 @@
import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, ScrollView, TouchableOpacity, RefreshControl } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { Filter, ReceiptText } from 'lucide-react-native';
import api from '@/utils/api';
import { useAlert } from '@/components/AlertComponent';
import LoadingScreen from '@/components/LoadingScreen';
import FilterModal from '@/components/FilterModal';
import InvoiceCard from '@/components/InvoiceCard';
import { InvoiceItem, Place } from '@/types/types';
export default function InvoiceScreen() {
const router = useRouter();
const alert = useAlert();
const [invoices, setInvoices] = useState<InvoiceItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
// Filters state
const [showFilterModal, setShowFilterModal] = useState(false);
const [places, setPlaces] = useState<Place[]>([]);
const [filterRange, setFilterRange] = useState<{ startDate: string | null; endDate: string | null }>({ startDate: null, endDate: null });
const [filterPlace, setFilterPlace] = useState<any>(null);
const [filterSupplier, setFilterSupplier] = useState<any>(null);
const activeFiltersCount = (filterRange.startDate ? 1 : 0) + (filterPlace ? 1 : 0) + (filterSupplier ? 1 : 0);
const fetchPlaces = async () => {
try {
const response = await api.get('/place/get-places');
if (response.data?.success) {
setPlaces(response.data.places || []);
}
} catch (error) {
console.error('Errore nel recupero dei cantieri:', error);
}
};
const fetchInvoices = async (currentRange = filterRange, currentPlace = filterPlace, currentSupplier = filterSupplier) => {
try {
if (!refreshing) setIsLoading(true);
const rangeParam = currentRange.startDate ? currentRange : null;
const placeCode = currentPlace ? places.find(p => p.id === currentPlace)?.code : null;
const params = { date: rangeParam, place: placeCode, supplier: currentSupplier };
const response = await api.post('/invoice-supplier/list', { params });
if (response.data?.success) {
// The backend already returns data matching InvoiceItem mostly
setInvoices(response.data.result || []);
}
} catch (error) {
console.error('Error fetching invoices:', error);
alert.showAlert('error', 'Errore', 'Impossibile recuperare la lista delle fatture.');
} finally {
setIsLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
fetchPlaces();
fetchInvoices();
}, []);
const onRefresh = () => {
setRefreshing(true);
fetchInvoices();
};
// Stable reference: keeps InvoiceCard memoization effective across page re-renders
const handleInvoicePress = useCallback((id: number) => {
router.push(`/invoice/${id}`);
}, [router]);
const handleApplyFilters = (range: any, place: any, supplier: any) => {
setFilterRange(range);
setFilterPlace(place);
setFilterSupplier(supplier);
setShowFilterModal(false);
fetchInvoices(range, place, supplier);
};
const handleResetFilters = () => {
const emptyRange = { startDate: null, endDate: null };
setFilterRange(emptyRange);
setFilterPlace(null);
setFilterSupplier(null);
setShowFilterModal(false);
fetchInvoices(emptyRange, null, null);
};
if (isLoading && !refreshing) {
return <LoadingScreen />;
}
return (
<View className="flex-1 bg-primary-dark">
<StatusBar style="light" />
{/* Header */}
<SafeAreaView edges={['top']} className="pt-5">
<View className="pb-6 px-6 z-10 flex-row justify-between items-center">
<View>
<Text className="text-white text-md font-semibold uppercase tracking-wider mb-1">Elenco delle fatture</Text>
<Text className="text-yellow-400 text-3xl font-bold leading-tight">Fatture</Text>
</View>
<View className="bg-white/10 p-4 rounded-full">
<ReceiptText size={32} color="white" pointerEvents="none" />
</View>
</View>
</SafeAreaView>
<View className="flex-1 bg-gray-50 rounded-t-[2.5rem] overflow-hidden">
{/* List */}
<ScrollView
className="flex-1"
contentContainerStyle={{ padding: 20, paddingBottom: 100, gap: 16 }}
showsVerticalScrollIndicator={true}
scrollIndicatorInsets={{ right: 1 }}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />}
>
{invoices.length === 0 ? (
<View className="bg-white p-8 rounded-3xl border border-gray-100 items-center justify-center border-dashed mt-4">
<Text className="text-gray-400 font-medium text-center">Nessuna fattura trovata</Text>
</View>
) : (
invoices.map((invoice) => (
<InvoiceCard key={invoice.id} item={invoice} onPress={handleInvoicePress} />
)))}
</ScrollView>
{/* FAB Filter */}
<TouchableOpacity
onPress={() => setShowFilterModal(true)}
className="absolute bottom-8 right-6 w-16 h-16 bg-[#1071C2] rounded-full shadow-lg items-center justify-center active:scale-90"
>
<Filter size={28} color="white" pointerEvents="none" />
{activeFiltersCount > 0 && (
<View className="absolute top-0 right-0 bg-red-500 w-6 h-6 rounded-full items-center justify-center border-2 border-white">
<Text className="text-white text-xs font-bold">{activeFiltersCount}</Text>
</View>
)}
</TouchableOpacity>
<FilterModal
visible={showFilterModal}
places={places}
currentRange={filterRange}
currentPlace={filterPlace}
currentSupplier={filterSupplier}
showSupplier={true}
onClose={() => setShowFilterModal(false)}
onApply={handleApplyFilters}
onReset={handleResetFilters}
/>
</View>
</View>
);
}

View File

@@ -0,0 +1,282 @@
import { useAlert } from '@/components/AlertComponent';
import LoadingScreen from '@/components/LoadingScreen';
import SetDescriptionModal from '@/components/SetDescriptionModal';
import api from '@/utils/api';
import { Image } from 'expo-image';
import { downloadAndShareDocument } from '@/utils/documentUtils';
import ImageView from "react-native-image-viewing";
import { useLocalSearchParams, useRouter } from 'expo-router';
import { ChevronLeft, ImageIcon, Share2, Trash2, Pencil } from 'lucide-react-native';
import React, { useCallback, useEffect, useState } from 'react';
import { Dimensions, RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
export default function JournalDetailScreen() {
const router = useRouter();
const alert = useAlert();
const params = useLocalSearchParams();
const insets = useSafeAreaInsets();
const [placeName, setPlaceName] = useState<string>('');
const [photos, setPhotos] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [isVisible, setIsVisible] = useState(false);
const [currentIndex, setCurrentIndex] = useState(0);
const [descModalVisible, setDescModalVisible] = useState(false);
const [editIndex, setEditIndex] = useState<number | null>(null);
const handleDescription = async (desc: string) => {
if (editIndex === null) return;
const photo = photos[editIndex];
if (!photo) return;
setDescModalVisible(false);
try {
const response = await api.post('/journal/save-description', {
id: photo.id,
description: desc,
});
if (response.data?.success) {
fetchDetails(true);
alert.showAlert('success', 'Salvato', 'Descrizione aggiornata con successo.');
} else {
alert.showAlert('error', 'Errore', response.data?.message || 'Impossibile salvare la descrizione.');
}
} catch (error) {
console.error(error);
alert.showAlert('error', 'Errore', 'Si è verificato un errore durante il salvataggio.');
}
};
const [isSharing, setIsSharing] = useState(false);
const handleShare = async (uri: string) => {
if (isSharing) return; // Prevent multiple share actions
setIsSharing(true);
try {
const fileName = uri.split('/').pop() || 'immagine.jpg';
await downloadAndShareDocument('image/jpeg', fileName, uri);
} catch (error) {
console.error('Error sharing image:', error);
alert.showAlert('error', 'Errore', 'Si è verificato un errore durante la condivisione.');
} finally {
setIsSharing(false);
}
};
const handleDelete = (id: string) => {
alert.showConfirm(
'Sei sicuro?',
'Vuoi davvero eliminare questa foto?',
[
{ text: 'Annulla', style: 'cancel', onPress: () => {} },
{
text: 'Elimina',
style: 'destructive',
onPress: async () => {
try {
const response = await api.post('/journal/delete-attachment', { id });
if (response.data?.success) {
setIsVisible(false);
fetchDetails(true);
alert.showAlert('success', 'Eliminata', 'La foto è stata rimossa con successo.');
} else {
alert.showAlert('error', 'Errore', response.data?.message || 'Impossibile eliminare la foto.');
}
} catch (error) {
console.error(error);
alert.showAlert('error', 'Errore', 'Impossibile eliminare la foto.');
}
}
}
]
);
};
const fetchDetails = useCallback(async (isRefreshing = false) => {
try {
if (!isRefreshing) setIsLoading(true);
const response = await api.get(`/journal/get-journal-items?id=${params.id}`);
if (response.data?.success) {
setPlaceName(response.data.result?.place_name || '');
setPhotos(response.data.result?.photos || []);
} else {
alert.showAlert('error', 'Errore', 'Impossibile caricare i dettagli.');
}
} catch (error) {
console.error('Errore nel recupero del dettaglio giornale:', error);
alert.showAlert('error', 'Errore', 'Si è verificato un errore di rete.');
} finally {
setIsLoading(false);
setRefreshing(false);
}
}, [params.id]);
useEffect(() => {
if (params.id) {
fetchDetails();
}
}, [params.id, fetchDetails]);
const onRefresh = () => {
setRefreshing(true);
fetchDetails(true);
};
if (isLoading && !refreshing) {
return <LoadingScreen />;
}
// Calculate dimensions for the grid layout of photos
const windowWidth = Dimensions.get('window').width;
const padding = 40;
const gap = 8;
const itemSize = (windowWidth - padding - (gap * 2)) / 3;
const imageSource = photos.map(photo => ({ uri: photo.uri }));
// Custom Header for the ImageView
const CustomHeader = ({ imageIndex }: { imageIndex: number }) => {
const currentPhoto = photos[imageIndex];
if (!currentPhoto) return null;
return (
<View
className="bg-white/95 shadow-sm border-b border-gray-100"
style={{ paddingTop: insets.top }}
>
<View className="flex-row items-center justify-between px-4 py-3">
<View className="flex-row items-center gap-3 flex-1 mr-4">
<TouchableOpacity onPress={() => setIsVisible(false)} className="p-2 -ml-2 active:opacity-70">
<ChevronLeft size={28} color="#082963" />
</TouchableOpacity>
<Text className="text-[#082963] text-lg font-bold flex-1" numberOfLines={2}>{currentPhoto.date || 'Dettaglio'}</Text>
</View>
<View className="flex-row items-center gap-1">
<TouchableOpacity onPress={() => {
setEditIndex(imageIndex);
setDescModalVisible(true);
}} className="p-2 active:opacity-70">
<Pencil size={24} color="#082963" />
</TouchableOpacity>
<TouchableOpacity onPress={() => handleShare(currentPhoto.uri)} disabled={isSharing} className={`p-2 active:opacity-70 ${isSharing ? 'opacity-50' : ''}`}>
<Share2 size={24} color="#082963" />
</TouchableOpacity>
<TouchableOpacity onPress={() => handleDelete(currentPhoto.id)} className="p-2 active:opacity-70">
<Trash2 size={24} color="#082963" />
</TouchableOpacity>
</View>
</View>
</View>
);
};
// Custom Footer for the ImageView
const CustomFooter = ({ imageIndex }: { imageIndex: number }) => {
const currentPhoto = photos[imageIndex];
if (!currentPhoto || !currentPhoto.description) return null;
return (
<View
className="bg-black/60"
style={{ paddingBottom: insets.bottom }}
>
<View className="px-6 py-5">
<Text className="text-white text-center text-base font-medium leading-relaxed">
{currentPhoto.description}
</Text>
</View>
</View>
);
};
return (
<View className="flex-1 bg-gray-50">
{/* Header */}
<View className="bg-white px-4 pb-6 shadow-sm border-b border-gray-100">
<SafeAreaView edges={['top']} className='pt-5'>
<View className='flex-row items-center gap-4 px-2'>
<TouchableOpacity onPress={() => router.back()} className="p-2 -ml-2 rounded-full active:bg-gray-100">
<ChevronLeft size={28} color="#4b5563" pointerEvents="none" />
</TouchableOpacity>
<Text
className="text-xl font-bold text-gray-800 leading-tight uppercase flex-1 pr-4"
numberOfLines={2}
ellipsizeMode="tail"
>
{placeName || 'Dettaglio Giornale'}
</Text>
</View>
</SafeAreaView>
</View>
<ScrollView
contentContainerStyle={{ padding: 20, paddingBottom: 100 }}
showsVerticalScrollIndicator={false}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />}
>
{photos.length === 0 ? (
<View className="bg-white p-8 rounded-3xl border border-gray-100 items-center justify-center border-dashed mt-4">
<ImageIcon size={48} color="#d1d5db" />
<Text className="text-gray-400 font-medium text-center mt-4">Nessuna foto presente per questo giornale.</Text>
</View>
) : (
<View className="flex-row flex-wrap" style={{ gap: gap }}>
{photos.map((item, index) => (
<TouchableOpacity
key={index}
activeOpacity={0.8}
onPress={() => {
setCurrentIndex(index);
setIsVisible(true);
}}
style={{ width: itemSize }}
className="mb-2"
>
<View className="bg-gray-100 rounded-2xl overflow-hidden shadow-sm border border-gray-200 aspect-square items-center justify-center">
<Image
source={{ uri: item.uri }}
style={{ width: '100%', height: '100%' }}
contentFit="cover"
transition={200}
/>
</View>
{item.description && (
<Text className="text-xs text-gray-500 mt-2 text-center" numberOfLines={1}>
{item.description}
</Text>
)}
</TouchableOpacity>
))}
</View>
)}
</ScrollView>
{/* Lightbox / Fullscreen viewer */}
<ImageView
images={imageSource}
imageIndex={currentIndex}
visible={isVisible}
onRequestClose={() => setIsVisible(false)}
HeaderComponent={CustomHeader}
FooterComponent={CustomFooter}
backgroundColor={"#EDF1F7"}
presentationStyle={'fullScreen'}
/>
<SetDescriptionModal
visible={descModalVisible}
initialDescription={editIndex !== null ? (photos[editIndex]?.description || '') : ''}
onClose={() => setDescModalVisible(false)}
onSave={handleDescription}
/>
</View>
);
}

View File

@@ -0,0 +1,11 @@
import {Stack} from 'expo-router';
export default function JournalLayout() {
return (
<Stack screenOptions={{headerShown: false}}>
<Stack.Screen name="index" />
<Stack.Screen name="add" />
<Stack.Screen name="[id]" />
</Stack>
);
}

View File

@@ -0,0 +1,292 @@
import { ChevronLeft } from 'lucide-react-native';
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, TextInput, KeyboardAvoidingView, ScrollView, Platform, Dimensions, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import PlaceFilter from '@/components/PlaceFilter';
import { Place } from '@/types/types';
import api from '@/utils/api';
import { useAlert } from '@/components/AlertComponent';
import RemovablePhotoTile from '@/components/RemovablePhotoTile';
import CameraAddTile from '@/components/CameraAddTile';
import * as ImagePicker from 'expo-image-picker';
export default function AddJournalScreen() {
const router = useRouter();
const alert = useAlert();
const [places, setPlaces] = useState<Place[]>([]);
const [selectedPlaceId, setSelectedPlaceId] = useState<any>(null);
const [description, setDescription] = useState('');
const [photos, setPhotos] = useState<any[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const [uploadProgress, setUploadProgress] = useState<{ current: number, total: number } | null>(null);
// Dynamic calculation of grid items (4 items per row)
const windowWidth = Dimensions.get('window').width;
const padding = 24;
const gap = 12;
const itemsPerRow = 4;
const itemSize = (windowWidth - (padding * 2) - (gap * (itemsPerRow - 1))) / itemsPerRow;
// Function to pick images from the gallery
const pickFromGallery = async () => {
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert.showAlert('error', 'Permessi Negati', 'È necessario consentire l\'accesso alla galleria per caricare foto.');
return;
}
const limit = 50 - photos.length;
if (limit <= 0) return;
try {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'], // Only images
allowsMultipleSelection: true,
selectionLimit: limit,
quality: 0.8, // Apply light compression and permanently fix the correct orientation
});
if (!result.canceled && result.assets) {
setPhotos(prev => [...prev, ...result.assets]);
}
} catch (error) {
console.error('Errore nella galleria:', error);
alert.showAlert('error', 'Errore', 'Impossibile accedere alla galleria.');
}
};
// Function to take a photo using the camera
const takePhoto = async () => {
const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
if (permissionResult.granted === false) {
alert.showAlert('error', 'Permessi Negati', 'È necessario consentire l\'accesso alla fotocamera per scattare foto.');
return;
}
if (photos.length >= 50) return;
try {
const result = await ImagePicker.launchCameraAsync({
mediaTypes: ['images'],
quality: 0.8, // Apply light compression and permanently fix the correct orientation
});
if (!result.canceled && result.assets && result.assets.length > 0) {
setPhotos(prev => [...prev, result.assets[0]]);
}
} catch (error) {
console.error('Errore nella fotocamera:', error);
alert.showAlert('error', 'Errore', 'Impossibile accedere alla fotocamera.');
}
};
const removePhoto = (index: number) => {
setPhotos(prev => prev.filter((_, i) => i !== index));
};
const handleSave = async () => {
if (!selectedPlaceId) return;
setIsSubmitting(true);
setUploadProgress(null);
try {
// Create record in the database first
const params = {
place: selectedPlaceId,
description: description,
n_files: photos.length
};
const response = await api.post('/journal/add', params);
if (response.data?.success) {
const journalId = response.data.id;
// Sequential asynchronous upload
if (photos.length > 0) {
setUploadProgress({ current: 0, total: photos.length });
for (let i = 0; i < photos.length; i++) {
const file = photos[i];
let formData = new FormData();
const fileName = file.fileName || file.uri.split('/').pop() || `photo_${i}.jpg`;
const fileType = file.mimeType || 'image/jpeg';
const fileUri = Platform.OS === 'android' ? file.uri : file.uri.replace('file://', '');
formData.append("files", {
name: fileName,
type: fileType,
uri: fileUri
} as any);
formData.append('model_classname', 'JournalUpdate');
formData.append('model_id', journalId);
formData.append('method', 'put');
formData.append('name', fileName);
formData.append('type', fileType);
await api.post('/journal/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
});
setUploadProgress({ current: i + 1, total: photos.length });
}
}
alert.showAlert('success', 'Ottimo Lavoro', 'Aggiornamento caricato con successo!');
router.replace('/(protected)/journal');
} else {
alert.showAlert('error', 'Errore', response.data?.message || 'Impossibile creare l\'avanzamento.');
}
} catch (error: any) {
console.error('Errore durante il salvataggio:', error);
alert.showAlert('error', 'Errore di connessione', 'Verifica la tua connessione e riprova.');
} finally {
setIsSubmitting(false);
setUploadProgress(null);
}
};
useEffect(() => {
fetchPlaces();
}, []);
const fetchPlaces = async () => {
try {
// This endpoint returns the UUID of the construction site necessary for saving
const response = await api.get('/journal/get-places');
if (response.data?.success) {
const mappedPlaces = response.data.places.map((p: any) => ({
id: p.value, // value = UUID
label: p.label,
code: ''
}));
setPlaces(mappedPlaces);
}
} catch (error) {
console.error('Errore nel recupero dei cantieri:', error);
}
};
return (
<View className="flex-1 bg-gray-50">
<StatusBar style="dark" />
{/* Header */}
<View className="bg-white px-4 pb-6 shadow-sm border-b border-gray-100">
<SafeAreaView edges={['top']} className='pt-5'>
<View className='flex-row items-center gap-4 px-2'>
<TouchableOpacity onPress={() => router.back()} className="p-2 -ml-2 rounded-full active:bg-gray-100">
<ChevronLeft size={28} color="#4b5563" pointerEvents="none" />
</TouchableOpacity>
<Text className="text-xl font-bold text-gray-800 leading-tight uppercase flex-1 pr-4">
Nuovo Aggiornamento
</Text>
</View>
</SafeAreaView>
</View>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'padding'}
className="flex-1"
>
<ScrollView
contentContainerStyle={{ padding: 24, paddingBottom: 100 }}
showsVerticalScrollIndicator={false}
keyboardShouldPersistTaps="handled"
>
{/* Place Filter Component */}
<View className="border-b border-gray-200 mb-4">
<PlaceFilter
places={places}
selectedPlaceId={selectedPlaceId}
onPlaceSelect={setSelectedPlaceId}
textColor="text-primary-dark"
/>
</View>
{/* Description Area */}
<View className="pb-8 border-b border-gray-200 mb-6">
<Text className="text-lg font-bold text-primary-dark mb-3">Descrizione</Text>
<View className="bg-white rounded-2xl shadow-sm border border-gray-200">
<TextInput
className="p-4 text-base text-gray-800"
placeholder="(opzionale)"
placeholderTextColor="#9ca3af"
multiline
value={description}
onChangeText={setDescription}
style={{ minHeight: 80, textAlignVertical: 'top' }}
/>
</View>
</View>
{/* Attachments Area */}
<View className="pb-8 border-b border-transparent mb-6">
<View className="flex-row items-center justify-between mb-4">
<Text className="text-lg font-bold text-gray-700">Allegati <Text className="text-sm font-normal text-gray-500">({photos.length}/50)</Text></Text>
{photos.length < 50 && (
<TouchableOpacity activeOpacity={0.7} onPress={pickFromGallery}>
<Text className="text-[#1071C2] font-bold text-base">Aggiungi</Text>
</TouchableOpacity>
)}
</View>
<View className="flex-row flex-wrap" style={{ gap: gap }}>
{photos.map((photo, index) => (
<RemovablePhotoTile
key={index}
uri={photo.uri}
size={itemSize}
onRemove={() => removePhoto(index)}
/>
))}
{photos.length < 50 && (
<CameraAddTile
size={itemSize}
onPress={takePhoto}
/>
)}
</View>
</View>
</ScrollView>
{/* Save Button */}
<View className="px-6 pt-2 pb-8">
<TouchableOpacity
className={`w-full py-4 rounded-[2rem] shadow-sm active:scale-[0.98] ${selectedPlaceId ? 'bg-[#1071C2]' : 'bg-gray-300'}`}
disabled={!selectedPlaceId || isSubmitting}
onPress={handleSave}
>
<Text className={`text-center uppercase font-bold text-lg ${selectedPlaceId ? 'text-white' : 'text-gray-500'}`}>Salva</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
{/* Loading Overlay */}
{isSubmitting && (
<View className="absolute inset-0 bg-black/60 items-center justify-center z-50">
<View className="bg-white p-8 rounded-3xl items-center shadow-2xl min-w-[200px]">
<ActivityIndicator size="large" color="#1071C2" className="mb-4" />
<Text className="text-gray-800 text-lg font-bold text-center mb-1">
{uploadProgress ? 'Caricamento foto...' : 'Salvataggio...'}
</Text>
{uploadProgress && (
<Text className="text-[#1071C2] font-black text-xl text-center mt-2">
{uploadProgress.current} / {uploadProgress.total}
</Text>
)}
</View>
</View>
)}
</View>
);
}

View File

@@ -0,0 +1,196 @@
import { useAlert } from '@/components/AlertComponent';
import LoadingScreen from '@/components/LoadingScreen';
import api from '@/utils/api';
import { ImageIcon, Plus, Filter, Newspaper } from 'lucide-react-native';
import React, { useEffect, useState } from 'react';
import { RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import FilterModal from '@/components/FilterModal';
import { Place } from '@/types/types';
import { useRouter, useFocusEffect } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { useCallback } from 'react';
export default function JournalScreen() {
const router = useRouter();
const alert = useAlert();
const [updates, setUpdates] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
// Filters state
const [showFilterModal, setShowFilterModal] = useState(false);
const [places, setPlaces] = useState<Place[]>([]);
const [filterRange, setFilterRange] = useState<{ startDate: string | null; endDate: string | null }>({ startDate: null, endDate: null });
const [filterPlace, setFilterPlace] = useState<any>(null);
const activeFiltersCount = (filterRange.startDate ? 1 : 0) + (filterPlace ? 1 : 0);
const fetchPlaces = async () => {
try {
const response = await api.get('/place/get-places');
if (response.data?.success) {
setPlaces(response.data.places || []);
}
} catch (error) {
console.error('Errore nel recupero dei cantieri:', error);
}
};
const fetchUpdates = async (currentRange = filterRange, currentPlace = filterPlace) => {
try {
if (!refreshing) setIsLoading(true);
const rangeParam = currentRange.startDate ? currentRange : null;
const params = { range: rangeParam, place: currentPlace };
const response = await api.post('/journal/list', { params });
if (response.data?.success) {
setUpdates(response.data.result || []);
}
} catch (error) {
console.error('Errore nel recupero del giornale:', error);
alert.showAlert('error', 'Errore', 'Impossibile recuperare il giornale di cantiere.');
} finally {
setIsLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
fetchPlaces();
}, []);
useFocusEffect(
useCallback(() => {
fetchUpdates();
}, [filterRange, filterPlace])
);
const onRefresh = () => {
setRefreshing(true);
fetchUpdates();
};
// The fetch is triggered by useFocusEffect, which reacts to filter changes:
// calling fetchUpdates here too would fire a second, identical request.
const handleApplyFilters = (range: any, place: any) => {
setFilterRange(range);
setFilterPlace(place);
setShowFilterModal(false);
};
const handleResetFilters = () => {
setFilterRange({ startDate: null, endDate: null });
setFilterPlace(null);
setShowFilterModal(false);
};
if (isLoading && !refreshing) {
return <LoadingScreen />;
}
return (
<View className="flex-1 bg-primary-dark">
<StatusBar style="light" />
{/* Header */}
<SafeAreaView edges={['top']} className='pt-5'>
<View className="pb-6 px-6 z-10 flex-row justify-between items-center">
<View>
<Text className="text-white text-md font-semibold uppercase tracking-wider mb-1">Elenco invii al giornale</Text>
<Text className="text-yellow-400 text-3xl font-bold leading-tight">Giornale di Cantiere</Text>
</View>
<View className="bg-white/10 p-4 rounded-full">
<Newspaper size={32} color="white" pointerEvents="none" />
</View>
</View>
</SafeAreaView>
<View className="flex-1 bg-gray-50 rounded-t-[2.5rem] overflow-hidden">
{/* List */}
<ScrollView
contentContainerStyle={{ padding: 20, paddingBottom: 180 }}
showsVerticalScrollIndicator={false}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />}
>
{updates.length === 0 ? (
<View className="bg-white p-8 rounded-3xl border border-gray-100 items-center justify-center border-dashed mt-4">
<Text className="text-gray-400 font-medium text-center">Nessun invio registrato al giornale di cantiere</Text>
</View>
) : (
<View className="gap-4">
{updates.map((item, index) => (
<View key={index} className="bg-white p-5 rounded-3xl shadow-sm border border-gray-100">
<View className="mb-3">
<Text className="font-bold text-[#082963] text-lg uppercase tracking-wide leading-tight">
{item.place_name}
</Text>
<Text className="text-gray-500 text-sm font-medium mt-1">
{item.place_address}
</Text>
<Text className="text-gray-400 text-base leading-relaxed mt-1">
{item.description}
</Text>
</View>
<View className="flex-row items-center justify-between border-t border-gray-50 pt-4">
<View className="flex-row items-center gap-4">
<View className="bg-blue-50 p-3 rounded-2xl">
<ImageIcon size={24} color="#082963" />
</View>
<View>
<Text className="font-bold text-primary text-lg">
{item.n_files} File Inviati
</Text>
<Text className="text-gray-400 font-bold text-sm mt-0.5">{item.date}</Text>
</View>
</View>
{item.n_files > 0 && (
<TouchableOpacity
className="bg-gray-100 px-4 py-2 rounded-xl active:bg-gray-200"
onPress={() => router.push(`/journal/${item.id}`)}
>
<Text className="text-gray-600 font-bold text-sm">Vedi</Text>
</TouchableOpacity>
)}
</View>
</View>
))}
</View>
)}
</ScrollView>
{/* FAB Add Journal */}
<TouchableOpacity
onPress={() => router.push('/journal/add')}
className="absolute bottom-[6.5rem] right-6 w-16 h-16 bg-white border border-[#1071C2] rounded-full shadow-lg items-center justify-center active:scale-90"
>
<Plus size={32} color="#1071C2" pointerEvents="none" />
</TouchableOpacity>
{/* FAB Filter */}
<TouchableOpacity
onPress={() => setShowFilterModal(true)}
className="absolute bottom-8 right-6 w-16 h-16 bg-[#1071C2] rounded-full shadow-lg items-center justify-center active:scale-90"
>
<Filter size={28} color="white" pointerEvents="none" />
{activeFiltersCount > 0 && (
<View className="absolute top-0 right-0 bg-red-500 w-6 h-6 rounded-full items-center justify-center border-2 border-white">
<Text className="text-white text-xs font-bold">{activeFiltersCount}</Text>
</View>
)}
</TouchableOpacity>
<FilterModal
visible={showFilterModal}
places={places}
currentRange={filterRange}
currentPlace={filterPlace}
onClose={() => setShowFilterModal(false)}
onApply={handleApplyFilters}
onReset={handleResetFilters}
/>
</View>
</View>
);
}

View File

@@ -0,0 +1,249 @@
import { useAlert } from '@/components/AlertComponent';
import MachineCard from '@/components/MachineCard';
import FilterModal from '@/components/FilterModal';
import LoadingScreen from '@/components/LoadingScreen';
import QrScanModal from '@/components/QrScanModal';
import { StatusBar } from 'expo-status-bar';
import api from '@/utils/api';
import { formatTime } from '@/utils/dateTime';
import { CarFront, CheckCircle2, Filter, QrCode } from 'lucide-react-native';
import React, { useEffect, useState } from 'react';
import { RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { MachineAttendanceItem } from '@/types/types';
export default function MachineScreen() {
const alert = useAlert();
const [showScanner, setShowScanner] = useState(false);
const [lastScan, setLastScan] = useState<{ type: string; time: string; site: string } | null>(null);
const [attendances, setAttendances] = useState<MachineAttendanceItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
// Filters state
const [isFilterVisible, setIsFilterVisible] = useState(false);
const [filterRange, setFilterRange] = useState<{ startDate: string | null; endDate: string | null }>({ startDate: null, endDate: null });
const [filterMachine, setFilterMachine] = useState<any>(null);
const activeFiltersCount = (filterRange.startDate ? 1 : 0) + (filterMachine ? 1 : 0);
const fetchAttendances = async (currentRange = filterRange, currentMachine = filterMachine) => {
try {
if (!refreshing) setIsLoading(true);
const rangeParam = currentRange.startDate ? currentRange : null;
const params = { range: rangeParam, machine: currentMachine };
const response = await api.post('/machine-attendance/list', { params });
if (response.data?.success) {
setAttendances(response.data.data || []);
}
} catch (error) {
console.error('Errore nel recupero degli utilizzi macchine:', error);
alert.showAlert('error', 'Errore', 'Impossibile recuperare i dati. Riprova più tardi.');
} finally {
setIsLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
fetchAttendances();
setLastScan(null);
}, []);
const onRefresh = () => {
setRefreshing(true);
fetchAttendances();
setLastScan(null);
};
const handleStartScan = () => {
setShowScanner(true);
};
const onScan = async (data: string) => {
console.log('Scanned data:', data);
try {
const response = await api.post('/machine-attendance/scan', { uuid: data });
if (response.data?.success) {
console.log('Scan data sent successfully:', response.data);
fetchAttendances();
setLastScan({
type: response.data.type,
time: formatTime(response.data.time),
site: response.data.site
});
} else {
alert.showAlert('error', 'Errore', response.data?.message || 'Impossibile registrare operazione.');
}
} catch (error) {
console.error('Errore nell\'invio dei dati di scansione:', error);
alert.showAlert('error', 'Errore', 'Impossibile registrare operazione. Riprova più tardi.');
return;
}
};
const handleExitPress = (item: MachineAttendanceItem) => {
alert.showConfirm(
'Conferma Uscita',
`Vuoi davvero registrare l'uscita da ${item.name}?`,
[
{ text: 'Annulla', onPress: () => {}, style: 'cancel' },
{ text: 'Conferma', style: 'default', onPress: async () => {
try {
const response = await api.post('/machine-attendance/out', { uuid: item.machine_uuid });
if (response.data?.success) {
fetchAttendances();
} else {
alert.showAlert('error', 'Errore', response.data?.message || 'Impossibile registrare l\'uscita.');
}
} catch (error) {
alert.showAlert('error', 'Errore', 'Impossibile registrare l\'uscita. Riprova più tardi.');
}
}}
]
);
};
if (isLoading && !refreshing) {
return <LoadingScreen />;
}
return (
<View className="flex-1 bg-gray-50">
<StatusBar style="light" />
{/* Header */}
<SafeAreaView edges={['top']} className='pt-5 bg-primary-dark'>
<View className="pb-6 px-6 z-10 flex-row justify-between items-center">
<View>
<Text className="text-white text-md font-semibold uppercase tracking-wider mb-1">Elenco degli utilizzi dei mezzi</Text>
<Text className="text-yellow-400 text-3xl font-bold leading-tight">Macchine</Text>
</View>
<View className="bg-white/10 p-4 rounded-full">
<CarFront size={32} color="white" pointerEvents="none" />
</View>
</View>
</SafeAreaView>
<View className="flex-1 bg-gray-50 rounded-t-[2.5rem] overflow-hidden">
<ScrollView
contentContainerStyle={{ paddingBottom: 100 }}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />
}
>
<View className="flex-1 p-5 items-center">
{/* Feedback Card */}
{lastScan ? (
<View className="w-full bg-green-50 border border-green-200 rounded-3xl p-5 mb-8 flex-row items-center gap-4 shadow-sm">
<View className="bg-green-500 rounded-full p-3 shadow-lg shadow-green-500/40 flex-shrink-0">
<CheckCircle2 size={32} color="white" pointerEvents="none" />
</View>
<View className="flex-1">
<Text
className="font-bold text-green-800 text-xl leading-tight"
numberOfLines={1}
ellipsizeMode="tail"
>
{lastScan.type} Registrata
</Text>
<Text
className="text-base text-green-700 font-medium mt-0.5 leading-snug"
numberOfLines={2}
ellipsizeMode="tail"
>
{lastScan.site} alle {lastScan.time}
</Text>
</View>
</View>
) : null}
{/* Scanner Section */}
<View className="w-full mb-6">
<View className="bg-white rounded-3xl p-8 shadow-sm border border-gray-100">
<Text className="text-2xl font-bold text-gray-800 mb-6 text-center">Scansione QR Code</Text>
<TouchableOpacity
onPress={handleStartScan}
className="bg-[#1071C2] rounded-2xl py-6 flex-row items-center justify-center active:bg-blue-700 shadow-lg shadow-blue-900/20 active:scale-[0.98]"
>
<QrCode color="white" size={32} pointerEvents="none" />
<Text className="text-white text-xl font-bold ml-3 uppercase">Scansiona Codice</Text>
</TouchableOpacity>
<Text className="text-gray-500 text-center mt-6 text-base px-2 leading-relaxed">
Posiziona il codice QR davanti alla fotocamera per registrare l'ingresso o l'uscita dalla macchina
</Text>
</View>
</View>
{/* History using MachineCard component */}
<View className="w-full mt-4">
<Text className="text-gray-500 font-bold text-base mb-4 uppercase tracking-wider px-2">Ultimi Utilizzi</Text>
{attendances.length === 0 ? (
<View className="bg-white p-6 rounded-3xl border border-gray-100 items-center justify-center border-dashed">
<Text className="text-gray-400 font-medium">Nessun utilizzo registrato</Text>
</View>
) : (
<View>
{attendances.map((item, index) => (
<MachineCard key={index} item={item} onExitPress={handleExitPress} />
))}
</View>
)}
</View>
</View>
</ScrollView>
{/* FAB Filter */}
<TouchableOpacity
onPress={() => setIsFilterVisible(true)}
className="absolute bottom-8 right-6 w-16 h-16 bg-[#1071C2] rounded-full shadow-lg items-center justify-center active:scale-90"
>
<Filter size={28} color="white" pointerEvents="none" />
{activeFiltersCount > 0 && (
<View className="absolute top-0 right-0 bg-red-500 w-6 h-6 rounded-full items-center justify-center border-2 border-white">
<Text className="text-white text-xs font-bold">{activeFiltersCount}</Text>
</View>
)}
</TouchableOpacity>
{/* Filter Modal */}
<FilterModal
visible={isFilterVisible}
showPlace={false}
showMachine={true}
currentRange={filterRange}
currentMachine={filterMachine}
onClose={() => setIsFilterVisible(false)}
onApply={(range, place, supplier, machine) => {
setFilterRange(range);
setFilterMachine(machine);
setIsFilterVisible(false);
fetchAttendances(range, machine);
}}
onReset={() => {
const emptyRange = { startDate: null, endDate: null };
setFilterRange(emptyRange);
setFilterMachine(null);
setIsFilterVisible(false);
fetchAttendances(emptyRange, null);
}}
/>
{/* Scanner Modal */}
<QrScanModal
visible={showScanner}
onClose={() => setShowScanner(false)}
onScan={onScan}
/>
</View>
</View>
);
}

View File

@@ -0,0 +1,288 @@
import { useAlert } from '@/components/AlertComponent';
import CalendarWidget from '@/components/CalendarWidget';
import LoadingScreen from '@/components/LoadingScreen';
import RequestPermitModal from '@/components/RequestPermitModal';
import { TimeOffRequest, TimeOffRequestType } from '@/types/types';
import api from '@/utils/api';
import { formatDate, formatTime } from '@/utils/dateTime';
import { StatusBar } from 'expo-status-bar';
import { Calendar as CalendarIcon, CalendarRange, CalendarX, Clock, Plus, Thermometer, Trash2 } from 'lucide-react-native';
import React, { JSX, useEffect, useMemo, useState } from 'react';
import { RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import Swipeable from 'react-native-gesture-handler/ReanimatedSwipeable';
export const hardcodedTypes: TimeOffRequestType[] = [
{ id: 1, name: 'Ferie', color: '#1071C2', time_required: 0 },
{ id: 2, name: 'Permesso', color: '#FCBE1F', time_required: 1 },
{ id: 3, name: 'Malattia', color: '#DC4437', time_required: 0 },
{ id: 4, name: 'Assenza', color: '#8F9BB3', time_required: 0 },
];
// Icon Mapping
const typeIcons: Record<string, (color: string) => JSX.Element> = {
Ferie: (color) => <CalendarIcon size={24} color={color} pointerEvents="none" />,
Permesso: (color) => <Clock size={24} color={color} pointerEvents="none" />,
Malattia: (color) => <Thermometer size={24} color={color} pointerEvents="none" />,
Assenza: (color) => <CalendarX size={24} color={color} pointerEvents="none" />,
};
export default function PermitsScreen() {
const [showModal, setShowModal] = useState(false);
const alert = useAlert();
const [permits, setPermits] = useState<TimeOffRequest[]>([]);
const [types, setTypes] = useState<TimeOffRequestType[]>([]);
const [currentMonthDate, setCurrentMonthDate] = useState(new Date());
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const fetchPermits = async () => {
try {
const response = await api.post('/request/list', { params: { range: '' } });
const mappedPermits: TimeOffRequest[] = (response.data.result || []).map((r: any) => ({
id: r.id,
type: r.type,
start_date: r.start_date,
end_date: r.end_date,
start_time: r.start_time,
end_time: r.end_time,
message: r.message,
status: r.status,
timeOffRequestType: hardcodedTypes.find(t => t.name === r.type) || hardcodedTypes[0],
}));
setPermits(mappedPermits);
setTypes(hardcodedTypes);
} catch (error) {
console.error('Errore nel recupero dei permessi:', error);
alert.showAlert('error', 'Errore', 'Impossibile recuperare i permessi. Riprova più tardi.');
} finally {
setIsLoading(false);
setRefreshing(false);
}
};
const filteredPermits = useMemo(() => {
if (!permits.length) return [];
// Calculate start and end of the current month
const year = currentMonthDate.getFullYear();
const month = currentMonthDate.getMonth();
const startOfMonth = new Date(year, month, 1);
// Day 0 of the next month = last day of the current month
const endOfMonth = new Date(year, month + 1, 0, 23, 59, 59);
return permits.filter(item => {
const itemStart = new Date(item.start_date?.toString() ?? '');
// If there's no end_date, assume it's a single day (so end = start)
const itemEnd = item.end_date ? new Date(item.end_date?.toString() ?? '') : new Date(item.start_date?.toString() ?? '');
// The permit is visible if it starts before the end of the month
// And ends after the start of the month.
return itemStart <= endOfMonth && itemEnd >= startOfMonth;
});
}, [permits, currentMonthDate]);
useEffect(() => {
fetchPermits();
}, []);
const onRefresh = () => {
setRefreshing(true);
fetchPermits();
};
// Funzione per eliminare una richiesta
const deletePermitRequest = async (id: number, itemRef?: React.ElementRef<typeof Swipeable> | null) => {
try {
itemRef?.close();
const res = await api.get(`/request/delete-request?id=${id}`);
if (res.data.code === 200) {
// Optimistic update
setPermits(prevPermits => prevPermits.filter(p => p.id !== id));
alert.showAlert('success', 'Richiesta eliminata', 'La richiesta è stata eliminata con successo.');
} else {
alert.showAlert('error', 'Errore', 'Impossibile eliminare la richiesta.');
}
// Refresh
fetchPermits();
} catch (error: any) {
console.error('Errore eliminazione richiesta:', error);
const errorMessage = error?.response?.data?.message || 'Impossibile eliminare la richiesta.';
alert.showAlert('error', 'Errore', errorMessage);
fetchPermits(); // Ripristina stato corretto
}
};
// Dialogo di conferma
const confirmDelete = (item: TimeOffRequest, itemRef?: React.ElementRef<typeof Swipeable> | null) => {
const requestType = item.timeOffRequestType.name;
const dateRange = item.end_date
? `${formatDate(item.start_date?.toLocaleString())} - ${formatDate(item.end_date.toLocaleString())}`
: formatDate(item.start_date?.toLocaleString());
alert.showConfirm(
'Conferma eliminazione',
`Sei sicuro di voler eliminare questa richiesta?\n\n${requestType}\n${dateRange}`,
[
{
text: 'Annulla',
style: 'cancel',
onPress: () => itemRef?.close()
},
{
text: 'Elimina',
style: 'destructive',
onPress: () => deletePermitRequest(item.id, itemRef)
}
]
);
};
// Renderizza pulsante DELETE al swipe
const renderRightActions = (
progress: any,
dragX: any,
item: TimeOffRequest,
swipeableRef: React.RefObject<React.ElementRef<typeof Swipeable> | null>
) => {
return (
<TouchableOpacity
onPress={() => confirmDelete(item, swipeableRef.current)}
className="bg-red-500 justify-center items-center px-6 rounded-3xl ml-3"
activeOpacity={0.7}
style={{ margin: 2 }}
>
<View className="items-center gap-1">
<Trash2 size={24} color="white" strokeWidth={2.5} pointerEvents="none" />
<Text className="text-white font-bold text-sm">Elimina</Text>
</View>
</TouchableOpacity>
);
};
if (isLoading && !refreshing) {
return <LoadingScreen />;
}
return (
<View className="flex-1 bg-primary-dark">
<StatusBar style="light" />
<RequestPermitModal
visible={showModal}
types={types}
onClose={() => setShowModal(false)}
onSubmit={(data) => { console.log('Richiesta:', data); fetchPermits(); }}
/>
{/* Header */}
<SafeAreaView edges={['top']} className='pt-5'>
<View className="pb-6 px-6 z-10 flex-row justify-between items-center">
<View>
<Text className="text-white text-md font-semibold uppercase tracking-wider mb-1">Elenco delle tue richieste</Text>
<Text className="text-yellow-400 text-3xl font-bold leading-tight">Ferie e Permessi</Text>
</View>
<View className="bg-white/10 p-4 rounded-full">
<CalendarRange size={32} color="white" pointerEvents="none" />
</View>
</View>
</SafeAreaView>
<View className="flex-1 bg-gray-50 rounded-t-[2.5rem] overflow-hidden">
<ScrollView
contentContainerStyle={{ padding: 20, paddingBottom: 100, gap: 24 }}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />
}
>
{/* Calendar Widget */}
<CalendarWidget initialDate={currentMonthDate} events={permits} types={types} onMonthChange={(date) => setCurrentMonthDate(date)} />
{/* Recent Requests List */}
<View>
{filteredPermits.length === 0 ? (
<Text className="text-center text-gray-500 mt-8">Nessuna richiesta di permesso questo mese</Text>
) : (
<View className="gap-4">
<Text className="text-xl font-bold text-gray-800 px-1">Le tue richieste</Text>
{filteredPermits.map((item) => {
const swipeableRef = React.createRef<React.ElementRef<typeof Swipeable>>();
const canDelete = item.status === null; // Solo "In Attesa"
const cardContent = (
<View className="bg-white p-5 rounded-3xl shadow-sm border border-gray-100 flex-row justify-between items-center">
<View className="flex-row items-center gap-4">
<View className={`p-4 rounded-2xl`} style={{ backgroundColor: item.timeOffRequestType.color ? `${item.timeOffRequestType.color}25` : '#E5E7EB' }}>
{typeIcons[item.timeOffRequestType.name]?.(item.timeOffRequestType.color)}
</View>
<View className='flex-1'>
<View className="flex-row justify-between items-center">
<Text className="font-bold text-gray-800 text-lg">{item.timeOffRequestType.name}</Text>
<View className={`px-3 py-1.5 rounded-lg ${item.status === 1 ? 'bg-green-100' : item.status === 0 ? 'bg-red-100' : 'bg-yellow-100'}`}>
<Text className={`text-xs font-bold uppercase tracking-wide ${item.status === 1 ? 'text-green-700' : item.status === 0 ? 'text-red-700' : 'text-yellow-700'}`}>
{item.status === 1 ? 'Approvata' : item.status === 0 ? 'Rifiutata' : 'In Attesa'}
</Text>
</View>
</View>
{item.message ? (
<Text className="text-sm text-gray-600 mt-0.5 leading-tight">{item.message}</Text>
) : null}
<Text className="text-base text-gray-500 mt-0.5">
{formatDate(item.start_date?.toLocaleString())} {item.end_date ? `- ${formatDate(item.end_date.toLocaleString())}` : ''}
</Text>
{item.timeOffRequestType.name === 'Permesso' && (
<Text className="text-sm text-orange-600 font-bold mt-0.5">
{formatTime(item.start_time)} - {formatTime(item.end_time)}
</Text>
)}
</View>
</View>
</View>
);
// Wrappa solo richieste "In Attesa" con Swipeable
if (canDelete) {
return (
<Swipeable
key={item.id}
ref={swipeableRef}
renderRightActions={(progress, dragX) =>
renderRightActions(progress, dragX, item, swipeableRef)
}
rightThreshold={40}
friction={2}
overshootFriction={8}
containerStyle={{ padding: 2 }}
>
{cardContent}
</Swipeable>
);
}
// Richieste approvate senza swipe
return <View key={item.id}>{cardContent}</View>;
})}
</View>
)}
</View>
</ScrollView>
{/* FAB */}
<TouchableOpacity
onPress={() => setShowModal(true)}
className="absolute bottom-8 right-6 w-16 h-16 bg-white border border-[#1071C2] rounded-full shadow-lg items-center justify-center active:scale-90"
>
<Plus size={32} color="#1071C2" pointerEvents="none" />
</TouchableOpacity>
</View>
</View>
);
}

View File

@@ -0,0 +1,10 @@
import { Stack } from "expo-router";
export default function ProfileLayout() {
return (
<Stack screenOptions={{headerShown: false}}>
<Stack.Screen name="index" />
<Stack.Screen name="documents" options={{ animation: 'slide_from_right' }} />
</Stack>
);
}

View File

@@ -0,0 +1,205 @@
import { useAlert } from '@/components/AlertComponent';
import LoadingScreen from '@/components/LoadingScreen';
import api from '@/utils/api';
import { downloadAndShareDocument } from '@/utils/documentUtils';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { ChevronDown, ChevronLeft, Download, FileText, X } from 'lucide-react-native';
import React, { useEffect, useState } from 'react';
import { Modal, RefreshControl, FlatList, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
export default function DocumentsScreen() {
const router = useRouter();
const alert = useAlert();
const [documents, setDocuments] = useState<any[]>([]);
const [categories, setCategories] = useState<any[]>([]);
const [selectedCategory, setSelectedCategory] = useState<any>(null);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [showPicker, setShowPicker] = useState(false);
// Fetch document categories
const fetchCategories = async () => {
try {
const response = await api.get('/registry/get-categories');
if (response.data?.success) {
setCategories([{ label: 'Tutte le tipologie', value: null }, ...response.data.categories]);
}
} catch (error) {
console.error('Errore nel recupero delle categorie:', error);
}
};
// Fetch user documents based on selected category
const fetchUserDocuments = async (filterValue: any = null) => {
try {
if (!refreshing) setIsLoading(true);
const params = { filter: filterValue };
const response = await api.get(`/registry/list`, { params });
if (response.data?.success) {
setDocuments(response.data.result || []);
}
} catch (error) {
console.error('Errore nel recupero dei documenti utente:', error);
alert.showAlert('error', 'Errore', 'Impossibile recuperare i documenti. Riprova più tardi.');
} finally {
setIsLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
const init = async () => {
setIsLoading(true);
await fetchCategories();
await fetchUserDocuments(selectedCategory);
};
init();
}, []);
const onRefresh = () => {
setRefreshing(true);
fetchUserDocuments(selectedCategory);
};
const handleCategorySelect = (value: any) => {
setSelectedCategory(value);
fetchUserDocuments(value);
setShowPicker(false);
};
if (isLoading && !refreshing) {
return (
<LoadingScreen />
);
}
// Get label for the selected category or default text
const selectedLabel = selectedCategory
? categories.find(c => c.value === selectedCategory)?.label
: 'Filtra per tipologia...';
return (
<View className="flex-1 bg-gray-50">
<StatusBar style="dark" />
{/* Header */}
<View className="bg-white px-4 pb-6 shadow-sm border-b border-gray-100">
<SafeAreaView edges={['top']} className='pt-5'>
<View className='flex-row items-center gap-4 mb-4'>
<TouchableOpacity onPress={() => router.back()} className="p-2 rounded-full active:bg-gray-100">
<ChevronLeft size={28} color="#4b5563" pointerEvents="none" />
</TouchableOpacity>
<View className="flex-1">
<Text className="text-3xl font-bold text-gray-800">Documenti</Text>
</View>
</View>
{/* Select / Dropdown Trigger and Reset */}
<View className="flex-row items-center mx-1 gap-3">
<TouchableOpacity
onPress={() => setShowPicker(true)}
className="flex-1 flex-row items-center justify-between bg-white px-5 py-3 rounded-2xl border border-gray-200 shadow-sm"
>
<Text className="text-gray-700 font-medium text-base flex-1 mr-2" numberOfLines={1}>
{selectedLabel}
</Text>
<ChevronDown size={20} color="#6b7280" pointerEvents="none" />
</TouchableOpacity>
{selectedCategory !== null && (
<TouchableOpacity
onPress={() => handleCategorySelect(null)}
className="bg-gray-50 p-3.5 rounded-2xl border border-gray-200 shadow-sm justify-center items-center"
>
<X size={22} color="#4b5563" pointerEvents="none" />
</TouchableOpacity>
)}
</View>
</SafeAreaView>
</View>
<View className="p-5 flex-1 pt-4">
{/* Documents List */}
<FlatList
data={documents}
keyExtractor={(item, index) => index.toString()}
contentContainerStyle={{ gap: 16, paddingBottom: 100 }}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />
}
initialNumToRender={10}
maxToRenderPerBatch={15}
windowSize={5}
removeClippedSubviews={true}
renderItem={({ item: doc }) => (
<View className="bg-white p-5 rounded-3xl shadow-sm flex-row items-center justify-between border border-gray-100">
<View className="flex-row items-center gap-5 flex-1">
<View className="bg-blue-50 p-4 rounded-2xl flex-shrink-0">
<FileText size={32} color="#1071C2" pointerEvents="none" />
</View>
<View className="flex-1 mr-2">
<Text className="font-bold text-gray-800 text-base leading-tight uppercase" numberOfLines={3}>{doc.filename}</Text>
<View className="flex-row items-center mt-2">
<Text className="text-sm text-gray-400 font-bold">{doc.date}</Text>
</View>
</View>
</View>
<TouchableOpacity
onPress={() => downloadAndShareDocument(doc.mimetype, doc.filename, doc.url)}
className="p-4 bg-gray-50 rounded-2xl active:bg-gray-100 flex-shrink-0 border border-gray-100">
<Download size={24} color="#1071C2" pointerEvents="none" />
</TouchableOpacity>
</View>
)}
ListEmptyComponent={() => (
!isLoading ? (
<View className="bg-white p-8 rounded-3xl border border-gray-100 items-center justify-center border-dashed mt-4">
<Text className="text-gray-400 font-medium text-center">Nessun documento trovato in questa categoria</Text>
</View>
) : null
)}
/>
</View>
{/* Modal Picker (Dropdown Custom) */}
<Modal visible={showPicker} transparent={true} animationType="fade" onRequestClose={() => setShowPicker(false)}>
<TouchableOpacity
activeOpacity={1}
onPress={() => setShowPicker(false)}
className="flex-1 bg-black/50 justify-end"
>
<View className="bg-white rounded-t-3xl p-5 max-h-[70%]" onStartShouldSetResponder={() => true}>
<View className="flex-row justify-between items-center mb-4 border-b border-gray-100 pb-4">
<Text className="text-xl font-bold text-gray-800">Filtra per tipologia</Text>
<TouchableOpacity onPress={() => setShowPicker(false)} className="p-2 bg-gray-100 rounded-full">
<X size={20} color="#4b5563" pointerEvents="none" />
</TouchableOpacity>
</View>
<FlatList
showsVerticalScrollIndicator={false}
contentContainerStyle={{ paddingBottom: 30 }}
data={categories}
keyExtractor={(item, index) => index.toString()}
initialNumToRender={10}
maxToRenderPerBatch={15}
windowSize={5}
removeClippedSubviews={true}
renderItem={({ item: cat }) => (
<TouchableOpacity
className={`py-4 px-4 rounded-xl flex-row justify-between items-center mb-2 ${selectedCategory === cat.value ? 'bg-blue-50' : ''}`}
onPress={() => handleCategorySelect(cat.value)}
>
<Text className={`text-lg ${selectedCategory === cat.value ? 'font-bold text-primary-dark' : 'text-gray-700'}`}>
{cat.label}
</Text>
</TouchableOpacity>
)}
/>
</View>
</TouchableOpacity>
</Modal>
</View>
);
}

View File

@@ -0,0 +1,108 @@
import { AuthContext } from '@/utils/authContext';
import { useRouter } from 'expo-router';
import { ChevronLeft, FileText, LogOut, Mail, User } from 'lucide-react-native';
import { StatusBar } from 'expo-status-bar';
import React, { useContext } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
export default function ProfileScreen() {
const authContext = useContext(AuthContext);
const { user } = authContext;
const router = useRouter();
// Generate user initials
const initials = `${user?.firstName?.[0] ?? ''}${user?.lastName?.[0] ?? ''}`.toUpperCase();
return (
<View className="flex-1 bg-primary-dark">
<StatusBar style="light" />
<SafeAreaView edges={['top']} className='pt-5'>
{/* Header Section */}
<View className="pb-6 px-4">
<View className="flex-row justify-start items-center gap-4">
<TouchableOpacity
onPress={() => router.back()}
>
<ChevronLeft size={28} color="white" pointerEvents="none"/>
</TouchableOpacity>
<View className="flex-row items-center gap-4">
<View className="w-16 h-16 rounded-full bg-white/20 items-center justify-center">
<Text className="text-white font-bold text-2xl">{initials}</Text>
</View>
<View>
<Text className="text-gray-300 text-lg font-medium uppercase tracking-wider mb-1">Profilo</Text>
<Text className="text-white text-2xl font-bold">{user?.firstName} {user?.lastName}</Text>
</View>
</View>
</View>
</View>
</SafeAreaView>
<ScrollView
className="flex-1 bg-gray-50 rounded-t-[2.5rem] px-5 pt-8"
contentContainerStyle={{ paddingBottom: 60, gap: 24 }}
showsVerticalScrollIndicator={false}
>
{/* Info Card - Enlarged Texts */}
<View className="bg-white p-7 rounded-3xl shadow-sm border border-gray-100">
{/* Section title */}
<Text className="text-2xl font-bold text-gray-800">Informazioni</Text>
<View className="mt-6 gap-5">
<View className="flex-row items-center gap-5">
<View className="w-14 h-14 bg-blue-50 rounded-2xl items-center justify-center">
<Mail size={24} color="#1071C2" pointerEvents="none" />
</View>
<View>
<Text className="text-lg text-gray-700 font-bold">Email</Text>
<Text className="text-gray-500 text-base">{user?.email}</Text>
</View>
</View>
<View className="flex-row items-center gap-5">
<View className="w-14 h-14 bg-blue-50 rounded-2xl items-center justify-center">
<User size={24} color="#1071C2" pointerEvents="none" />
</View>
<View>
<Text className="text-lg text-gray-700 font-bold">Ruolo</Text>
<Text className="text-gray-500 text-base capitalize">{user?.isAdmin ? 'Amministratore' : 'Utente'}</Text>
</View>
</View>
</View>
</View>
{/* Actions */}
<View>
<Text className="text-gray-800 text-2xl font-bold mb-5 px-1">Azioni</Text>
<TouchableOpacity onPress={() => router.push('/profile/documents')} className="bg-white p-4 rounded-3xl shadow-sm flex-row items-center justify-between border border-gray-100 mb-4">
<View className="flex-row items-center gap-5">
<View className="bg-blue-50 p-3.5 rounded-2xl">
<FileText size={26} color="#1071C2" pointerEvents="none" />
</View>
<View>
<Text className="text-lg text-gray-800 font-bold">I miei documenti</Text>
<Text className="text-base text-gray-400 mt-0.5">Visualizza i tuoi documenti</Text>
</View>
</View>
<Text className="text-primary text-base font-bold">Apri</Text>
</TouchableOpacity>
<TouchableOpacity onPress={authContext.logOut} className="bg-white p-4 rounded-3xl shadow-sm flex-row items-center justify-between border border-gray-100">
<View className="flex-row items-center gap-5">
<View className="bg-red-50 p-3.5 rounded-2xl">
<LogOut size={26} color="#ef4444" pointerEvents="none" />
</View>
<View>
<Text className="text-lg text-gray-800 font-bold">Esci</Text>
<Text className="text-base text-gray-400 mt-0.5">Chiudi la sessione corrente</Text>
</View>
</View>
<Text className="text-red-500 text-base font-bold">Esci</Text>
</TouchableOpacity>
</View>
</ScrollView>
</View>
);
}

32
app/_layout.tsx Normal file
View File

@@ -0,0 +1,32 @@
import '../global.css';
import { AuthProvider } from '@/utils/authContext';
import { Stack } from 'expo-router';
import { AlertProvider } from '@/components/AlertComponent';
import { NetworkProvider } from '@/utils/networkProvider';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { KeyboardProvider } from "react-native-keyboard-controller";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { ConfigProvider } from '@/utils/configProvider';
export default function AppLayout() {
return (
<SafeAreaProvider>
<GestureHandlerRootView>
<KeyboardProvider>
<NetworkProvider>
<ConfigProvider>
<AuthProvider>
<AlertProvider>
<Stack screenOptions={{ headerShown: false, animation: 'flip' }}>
<Stack.Screen name="(protected)" />
<Stack.Screen name="login" />
</Stack>
</AlertProvider>
</AuthProvider>
</ConfigProvider>
</NetworkProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</SafeAreaProvider>
);
}

168
app/login.tsx Normal file
View File

@@ -0,0 +1,168 @@
import { useAlert } from '@/components/AlertComponent';
import api from '@/utils/api';
import { AuthContext } from '@/utils/authContext';
import { Eye, EyeOff, Lock, LogIn, User } from 'lucide-react-native';
import { StatusBar } from 'expo-status-bar';
import React, { useContext, useState } from 'react';
import { Image, Platform, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller';
export default function LoginScreen() {
const alert = useAlert();
const authContext = useContext(AuthContext);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
// Login Handler function
const handleLogin = async () => {
if (!username || !password) {
alert.showAlert('error', 'Attenzione', 'Inserisci username e password');
return;
}
setIsLoading(true);
try {
username.trim();
password.trim();
// Execute login request
const response = await api.post("/user/login", {
username: username,
password: password
});
if (response.data && response.data.success === false) {
alert.showAlert('error', 'Login Fallito', 'Credenziali non valide.');
setIsLoading(false);
return;
}
const token = response.data.auth_key;
const user = {
firstName: response.data.nome,
lastName: response.data.cognome,
email: response.data.email,
isAdmin: response.data.isAdmin
};
console.log("Login riuscito. Token:", token);
console.log("Dati utente:", user);
// Pass token and user data to the context which will handle saving and redirect
authContext.logIn(token, user);
} catch (error: any) {
let message = "Si è verificato un errore durante l'accesso.";
if (error.response) {
if (error.response.status === 401) {
message = "Credenziali non valide."
} else {
console.error("Login Error:", error);
message = `Errore Server: ${error.response.data.message || error.response.status}`;
}
} else if (error.request) {
// Server not reachable
console.error("Login Error:", error);
message = "Impossibile contattare il server. Controlla la connessione.";
} else {
console.error("Login Error:", error);
}
alert.showAlert('error', "Login Fallito", message);
} finally {
setIsLoading(false);
}
};
return (
<View className="flex-1 bg-primary-dark h-screen overflow-hidden">
<StatusBar style="light" />
{/* Header with Logo/Title */}
<View className="h-[30%] flex-column justify-center items-center">
<View className="bg-white rounded-full w-32 h-32 justify-center items-center overflow-hidden shadow-lg">
<Image
source={require('@/assets/images/react-logo.png')}
className='h-20 w-20'
resizeMode="contain"
/>
</View>
</View>
{/* Form Container */}
<View className="flex-1 bg-white rounded-t-[2.5rem] px-8 pt-8 shadow-xl w-full">
<KeyboardAwareScrollView
bottomOffset={Platform.OS === 'ios' ? 50 : 80}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
contentContainerStyle={{ paddingBottom: 40, flexGrow: 1, justifyContent: 'space-between' }}
className="flex-1"
>
<View className="flex-1 flex-col justify-between">
<View>
<Text className="text-primary-dark text-5xl font-bold text-center mb-3">Accedi</Text>
<Text className="text-base font-semibold text-center text-text-secondary mb-10">
Inserisci le tue credenziali per accedere
</Text>
<View className="gap-6 flex flex-col" style={{ gap: '1.5rem' }}>
{/* Input Username */}
<View>
<View className="flex-row items-center bg-gray-50 border border-gray-100 rounded-2xl h-16 px-4 flex">
<User size={24} color="#9ca3af" pointerEvents="none" />
<TextInput
className="flex-1 ml-4 text-gray-800 text-lg font-medium h-full w-full"
placeholder="Username"
placeholderTextColor="#9ca3af"
value={username}
onChangeText={setUsername}
autoCapitalize="none"
/>
</View>
</View>
{/* Input Password */}
<View>
<View className="flex-row items-center bg-gray-50 border border-gray-100 rounded-2xl h-16 px-4 flex">
<Lock size={24} color="#9ca3af" pointerEvents="none" />
<TextInput
className="flex-1 ml-4 text-gray-800 text-lg font-medium h-full w-full"
placeholder="Password"
placeholderTextColor="#9ca3af"
value={password}
onChangeText={setPassword}
secureTextEntry={!showPassword}
/>
<TouchableOpacity onPress={() => setShowPassword(!showPassword)}>
{showPassword ? (
<EyeOff size={24} color="#6b7280" pointerEvents="none" />
) : (
<Eye size={24} color="#6b7280" pointerEvents="none" />
)}
</TouchableOpacity>
</View>
</View>
</View>
</View>
{/* Login Button */}
<View className="mt-8">
<TouchableOpacity
onPress={handleLogin}
activeOpacity={0.8}
className={`bg-primary h-16 rounded-2xl flex-row justify-center items-center shadow-md flex ${isLoading ? 'opacity-70' : ''}`}
disabled={isLoading}
>
<Text className="text-white text-xl font-bold mr-2">
{isLoading ? 'ACCESSO IN CORSO...' : 'LOGIN'}
</Text>
{!isLoading && <LogIn size={24} color="white" pointerEvents="none" />}
</TouchableOpacity>
</View>
</View>
</KeyboardAwareScrollView>
</View>
</View>
);
}