Initial commit

This commit is contained in:
2026-08-31 16:50:53 +02:00
commit a68c8864b0
80 changed files with 22222 additions and 0 deletions
+109
View File
@@ -0,0 +1,109 @@
import { Redirect, Tabs } from 'expo-router';
import { Home, Clock, ShoppingBag, CircleCheckBig, CalendarRange } 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: '#f1f5f9',
height: 70 + insets.bottom,
paddingBottom: insets.bottom,
paddingTop: 10,
paddingHorizontal: 10,
},
tabBarActiveTintColor: '#1071C2',
tabBarInactiveTintColor: '#94a3b8',
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={28} />,
}}
/>
<Tabs.Screen
name="activity"
options={{
title: 'Attività',
tabBarIcon: ({ color, size }) => <ShoppingBag pointerEvents="none" color={color} size={28} />,
}}
/>
<Tabs.Screen
name="attendance/index"
options={{
title: 'Presenze',
tabBarIcon: ({ color, size }) => <Clock pointerEvents="none" color={color} size={28} />,
}}
/>
<Tabs.Screen
name="quality"
options={{
title: 'Qualità',
tabBarIcon: ({ color, size }) => <CircleCheckBig pointerEvents="none" color={color} size={28} />,
}}
/>
<Tabs.Screen
name="permits/index"
options={{
title: 'Ferie',
tabBarIcon: ({ color, size }) => <CalendarRange pointerEvents="none" color={color} size={28} />,
}}
/>
<Tabs.Screen
name="invoice"
options={{
title: 'Fatture',
href: null,
}}
/>
<Tabs.Screen
name="profile"
options={{
href: null,
title: 'Profilo',
tabBarStyle: { display: 'none' },
}}
/>
<Tabs.Screen
name="dashboard/index"
options={{
href: null,
title: 'Dashboard',
}}
/>
<Tabs.Screen
name="construction-site"
options={{
href: null,
headerShown: false,
tabBarStyle: { display: 'none' },
}}
/>
</Tabs>
);
}
+258
View File
@@ -0,0 +1,258 @@
import { useAlert } from '@/components/AlertComponent';
import LoadingScreen from '@/components/LoadingScreen';
import api from '@/utils/api';
import { Image } from 'expo-image';
import ImageView from "react-native-image-viewing";
import { useLocalSearchParams, useRouter, useFocusEffect } from 'expo-router';
import { ChevronLeft, ImageIcon, Users, HardHat, MapPin, Calendar as CalendarIcon, Briefcase, TextAlignStart, CheckCircle2, Wrench, 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';
import { StatusBar } from 'expo-status-bar';
export default function ActivityDetailScreen() {
const router = useRouter();
const alert = useAlert();
const params = useLocalSearchParams();
const insets = useSafeAreaInsets();
const [activityData, setActivityData] = useState<any>(null);
const [placeName, setPlaceName] = useState<string>('');
const [photos, setPhotos] = useState<{uri: string}[]>([]);
// Labor states
const [operatorLabor, setOperatorLabor] = useState<any[]>([]);
const [subcontractorLabor, setSubcontractorLabor] = useState<any[]>([]);
const [otherOperatorLabor, setOtherOperatorLabor] = useState<any[]>([]);
const [equipmentLabor, setEquipmentLabor] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
// Image Viewer states
const [isVisible, setIsVisible] = useState(false);
const [currentIndex, setCurrentIndex] = useState(0);
const fetchDetails = useCallback(async (isRefreshing = false) => {
try {
if (!isRefreshing) setIsLoading(true);
const paramsData = JSON.stringify({ id: params.id });
const [activityRes, subactivitiesRes] = await Promise.all([
api.post('/activity/get-activity-data', { params: paramsData }),
api.get('/subactivity/get-subactivities')
]);
if (activityRes.data?.success) {
const data = activityRes.data;
setActivityData(data.activity);
setPhotos(data.attachments || []);
setOperatorLabor(data.operator_labor || []);
setSubcontractorLabor(data.subcontractor_labor || []);
setOtherOperatorLabor(data.other_operator_labor || []);
setEquipmentLabor(data.materials || []);
if (subactivitiesRes.data?.success) {
const subactivities = subactivitiesRes.data.subactivities;
const match = subactivities.find((s: any) => s.id === data.activity.id_subactivity);
if (match) {
setPlaceName(match.label);
} else {
setPlaceName('Cantiere Non Specificato');
}
}
} else {
alert.showAlert('error', 'Errore', 'Impossibile caricare i dettagli dell\'attività.');
}
} catch (error) {
console.error('Errore nel recupero del dettaglio attività:', error);
alert.showAlert('error', 'Errore', 'Si è verificato un errore di rete.');
} finally {
setIsLoading(false);
setRefreshing(false);
}
}, [params.id]);
useFocusEffect(
useCallback(() => {
if (params.id) {
fetchDetails(true);
}
}, [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 }));
const renderLaborSection = (title: string, icon: React.ReactNode, laborData: any[]) => {
if (!laborData || laborData.length === 0) return null;
return (
<View className="bg-white rounded-3xl p-5 shadow-sm border border-gray-100 mb-4">
<View className="flex-row items-center border-b border-gray-50 pb-3 mb-3">
<View className="bg-blue-50 p-2 rounded-xl mr-3">
{icon}
</View>
<Text className="text-[#082963] font-bold text-lg">{title}</Text>
</View>
<View className="gap-3">
{laborData.map((labor, idx) => (
<View key={idx} className="flex-row justify-between items-center bg-gray-50 p-3 rounded-2xl">
<Text className="text-gray-800 font-medium flex-1 mr-2" numberOfLines={3}>
{labor.name}
</Text>
<View className="flex-row items-center gap-2">
<View className="bg-white px-3 py-1.5 rounded-xl border border-gray-200">
<Text className="text-[#1071C2] font-bold">
{labor.hours}h {labor.minutes}m
</Text>
</View>
{labor.sync && (
<CheckCircle2 size={16} color="#0F9D58" />
)}
</View>
</View>
))}
</View>
</View>
);
};
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 justify-between px-2'>
<TouchableOpacity onPress={() => router.back()} className="p-2 -ml-2 rounded-full active:bg-gray-100 w-12 items-center justify-center">
<ChevronLeft size={28} color="#4b5563" pointerEvents="none" />
</TouchableOpacity>
<Text
className="text-xl font-bold text-gray-800 leading-tight uppercase flex-1 text-center"
numberOfLines={1}
ellipsizeMode="tail"
>
Dettaglio Attività
</Text>
<TouchableOpacity onPress={() => router.push(`/activity/add?id=${params.id}`)} className="p-2 -mr-2 active:bg-gray-100 rounded-full w-12 items-center justify-center">
<Pencil size={20} color="#082963" />
</TouchableOpacity>
</View>
</SafeAreaView>
</View>
<ScrollView
contentContainerStyle={{ padding: 20 }}
showsVerticalScrollIndicator={false}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />}
>
{/* General Info */}
<View className="bg-white rounded-3xl p-5 shadow-sm border border-gray-100 mb-4">
<View className="flex-row items-center mb-4">
<View className="bg-blue-50 p-3 rounded-2xl mr-4">
<MapPin size={24} color="#082963" />
</View>
<View className="flex-1">
<Text className="text-gray-400 text-sm font-bold uppercase mb-1">Cantiere</Text>
<Text className="text-[#082963] font-bold text-md leading-tight">
{placeName}
</Text>
</View>
</View>
<View className="flex-row items-center mb-4 pt-4 border-t border-gray-50">
<View className="bg-blue-50 p-3 rounded-2xl mr-4">
<CalendarIcon size={24} color="#082963" />
</View>
<View className="flex-1">
<Text className="text-gray-400 text-sm font-bold uppercase mb-1">Data</Text>
<Text className="text-[#082963] font-bold text-md leading-tight">
{activityData?.date ? new Date(activityData.date).toLocaleDateString('it-IT') : '-'}
</Text>
</View>
</View>
<View className="pt-4 border-t border-gray-50">
<View className="flex-row items-center gap-2 mb-2">
<TextAlignStart size={20} color="#9ca3af" className="mr-2" />
<Text className="text-gray-400 text-xs font-bold uppercase">Descrizione</Text>
</View>
<Text className="text-gray-700 text-md font-medium leading-relaxed">
{activityData?.description || 'Nessuna descrizione.'}
</Text>
</View>
</View>
{/* Labor and Materials Sections */}
{renderLaborSection('Operai', <HardHat size={24} color="#082963" />, operatorLabor)}
{renderLaborSection('Subappaltatori', <Briefcase size={24} color="#082963" />, subcontractorLabor)}
{renderLaborSection('Operai Distaccati', <Users size={24} color="#082963" />, otherOperatorLabor)}
{renderLaborSection('Attrezzature', <Wrench size={24} color="#082963" />, equipmentLabor)}
{/* Photos */}
<View className="mt-4 mb-2 flex-row items-center justify-between">
<Text className="text-lg font-bold text-[#082963] ml-2">Allegati</Text>
</View>
{photos.length === 0 ? (
<View className="bg-white p-8 rounded-3xl border border-gray-100 items-center justify-center border-dashed mb-4">
<ImageIcon size={48} color="#d1d5db" />
<Text className="text-gray-400 font-medium text-center mt-4">Nessun allegato presente per questa attività.</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>
</TouchableOpacity>
))}
</View>
)}
</ScrollView>
<ImageView
images={imageSource}
imageIndex={currentIndex}
visible={isVisible}
onRequestClose={() => setIsVisible(false)}
swipeToCloseEnabled={true}
doubleTapToZoomEnabled={true}
presentationStyle="overFullScreen"
/>
</View>
);
}
+11
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>
);
}
+430
View File
@@ -0,0 +1,430 @@
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, TextInput, KeyboardAvoidingView, ScrollView, Platform, Dimensions, ActivityIndicator, Modal } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { ChevronLeft, ImageIcon, Calendar as CalendarIcon } from 'lucide-react-native';
import { AppDatePicker } from '@/components/AppDatePicker';
import { DateType } from 'react-native-ui-datepicker';
import { formatDate, formatPickerDate } from '@/utils/dateTime';
import { Image } from 'expo-image';
import * as ImagePicker from 'expo-image-picker';
import api from '@/utils/api';
import { uploadDocument } from '@/utils/documentUtils';
import { useAlert } from '@/components/AlertComponent';
import GenericDropdown from '@/components/GenericDropdown';
import ActivityLaborCard from '@/components/ActivityLaborCard';
import RemovablePhotoTile from '@/components/RemovablePhotoTile';
import CameraAddTile from '@/components/CameraAddTile';
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller';
export default function ActivityFormScreen() {
const router = useRouter();
const alert = useAlert();
const { id } = useLocalSearchParams();
const isEditing = !!id;
// Data lists
const [subactivities, setSubactivities] = useState<any[]>([]);
// Form states
const [date, setDate] = useState<DateType>(new Date());
const [showDatePicker, setShowDatePicker] = useState(false);
const [selectedSubactivityUuid, setSelectedSubactivityUuid] = useState<string | null>(null);
const [selectedSubactivityId, setSelectedSubactivityId] = useState<number | null>(null);
const [description, setDescription] = useState('');
// Labor states
const [operatorLabor, setOperatorLabor] = useState<any[]>([]);
const [subcontractorLabor, setSubcontractorLabor] = useState<any[]>([]);
const [otherOperatorLabor, setOtherOperatorLabor] = useState<any[]>([]);
const [equipmentLabor, setEquipmentLabor] = useState<any[]>([]);
// Photos
const [photos, setPhotos] = useState<any[]>([]); // New photos
const [existingPhotos, setExistingPhotos] = useState<any[]>([]); // Existing (readonly)
const [isLoading, setIsLoading] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
// Initial load
useEffect(() => {
loadInitialData();
}, []);
const loadInitialData = async () => {
setIsLoading(true);
try {
// Load subactivities
const subRes = await api.get('/subactivity/get-subactivities');
if (subRes.data?.success) {
setSubactivities(subRes.data.subactivities);
}
// If editing, load activity data
if (isEditing) {
const actRes = await api.post('/activity/get-activity-data', {
params: JSON.stringify({ id: id })
});
if (actRes.data?.success) {
const data = actRes.data;
const activity = data.activity;
setDate(new Date(activity.date));
setDescription(activity.description || '');
if (subRes.data?.success) {
const match = subRes.data.subactivities.find((s: any) => s.id === activity.id_subactivity);
if (match) {
setSelectedSubactivityUuid(match.uuid);
setSelectedSubactivityId(match.id);
}
}
setOperatorLabor(data.operator_labor || []);
setSubcontractorLabor(data.subcontractor_labor || []);
setOtherOperatorLabor(data.other_operator_labor || []);
setEquipmentLabor(data.materials || []);
setExistingPhotos(data.attachments || []);
} else {
alert.showAlert('error', 'Errore', 'Impossibile caricare i dati dell\'attività.');
}
}
} catch (error) {
console.error('Error loading data:', error);
alert.showAlert('error', 'Errore', 'Si è verificato un errore di connessione.');
} finally {
setIsLoading(false);
}
};
const handleDateChange = (params: any) => {
setDate(params.date);
setShowDatePicker(false);
};
const pickFromGallery = async () => {
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert.showAlert('error', 'Permessi Negati', 'È necessario consentire l\'accesso alla galleria.');
return;
}
const limit = 50 - photos.length;
if (limit <= 0) return;
try {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'],
allowsMultipleSelection: true,
selectionLimit: limit,
quality: 0.8,
});
if (!result.canceled && result.assets) {
setPhotos(prev => [...prev, ...result.assets]);
}
} catch (error) {
console.error('Errore gallery:', error);
}
};
const takePhoto = async () => {
const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
if (permissionResult.granted === false) {
alert.showAlert('error', 'Permessi Negati', 'È necessario consentire l\'accesso alla fotocamera.');
return;
}
if (photos.length >= 50) return;
try {
const result = await ImagePicker.launchCameraAsync({
mediaTypes: ['images'],
quality: 0.8,
});
if (!result.canceled && result.assets && result.assets.length > 0) {
setPhotos(prev => [...prev, result.assets[0]]);
}
} catch (error) {
console.error('Errore fotocamera:', error);
}
};
const removePhoto = (index: number) => {
setPhotos(prev => prev.filter((_, i) => i !== index));
};
const handleSave = async () => {
if (!selectedSubactivityUuid) {
alert.showAlert('error', 'Campi obbligatori', 'Selezionare un Cantiere.');
return;
}
setIsSubmitting(true);
try {
// Se in edit mode dobbiamo passare subactivity_id, se in add mode subactivity_uuid.
let subactivity_id = selectedSubactivityId;
if (!subactivity_id) {
const match = subactivities.find(s => s.uuid === selectedSubactivityUuid);
if (match) subactivity_id = match.id;
}
const payload: any = {
description: description,
date: date ? formatPickerDate(date) : new Date().toISOString().split('T')[0], // YYYY-MM-DD
n_files: photos.length,
operator_labor: operatorLabor,
subcontractor_labor: subcontractorLabor,
other_operators_labor: otherOperatorLabor,
equipment_labor: equipmentLabor,
};
if (isEditing) {
payload.id = id;
payload.subactivity_id = subactivity_id;
} else {
payload.subactivity_uuid = selectedSubactivityUuid;
}
const params = {
post: JSON.stringify(payload)
};
const endpoint = isEditing ? '/activity/edit' : '/activity/add';
const res = await api.post(endpoint, params);
if (res.data?.success) {
const savedId = res.data.id;
// Upload new photos sequentially
if (photos.length > 0) {
for (const file of photos) {
const fileName = file.fileName || file.uri.split('/').pop() || 'photo.jpg';
const mimeType = file.mimeType || 'image/jpeg';
await uploadDocument({
uri: file.uri,
name: fileName,
mimeType: mimeType
}, {
endpoint: '/activity/upload',
fileKey: 'files',
extraData: {
model_classname: 'Activity',
model_id: savedId.toString(),
method: 'put',
name: fileName,
type: mimeType
}
});
}
}
alert.showAlert('success', 'Salvato', 'Attività salvata con successo.');
if (isEditing) {
router.back();
} else {
router.push('/(protected)/activity');
}
} else {
alert.showAlert('error', 'Errore', res.data?.message || 'Impossibile salvare l\'attività.');
}
} catch (error) {
console.error('Errore salvataggio:', error);
alert.showAlert('error', 'Errore di connessione', 'Verifica la connessione e riprova.');
} finally {
setIsSubmitting(false);
}
};
if (isLoading) {
return (
<View className="flex-1 bg-gray-50 items-center justify-center">
<ActivityIndicator size="large" color="#1071C2" />
</View>
);
}
const windowWidth = Dimensions.get('window').width;
const itemsPerRow = 4;
const padding = 20;
const gap = 12;
const tileWidth = (windowWidth - (padding * 2) - (gap * (itemsPerRow - 1))) / itemsPerRow;
return (
<View className="flex-1 bg-gray-50">
<StatusBar style="dark" />
{/* Header */}
<View className="bg-white px-4 pb-4 shadow-sm border-b border-gray-100">
<SafeAreaView edges={['top']} className="pt-2">
<View className="flex-row items-center justify-between px-2">
<TouchableOpacity onPress={() => router.back()} className="p-2 -ml-2 rounded-full active:bg-gray-100 w-12 items-center justify-center">
<ChevronLeft size={28} color="#4b5563" pointerEvents="none" />
</TouchableOpacity>
<Text className="text-xl font-bold text-gray-800 uppercase flex-1 text-center" numberOfLines={1}>
{isEditing ? 'Modifica Attività' : 'Nuova Attività'}
</Text>
<View className="w-12" />
</View>
</SafeAreaView>
</View>
<KeyboardAwareScrollView
contentContainerStyle={{ padding: 20 }}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
{/* General Info Card */}
<View className="bg-white rounded-3xl p-5 shadow-sm border border-gray-100 mb-4">
<View className="mb-4">
<Text className="text-[#082963] font-bold text-sm mb-2 uppercase">Cantiere <Text className="text-red-500">*</Text></Text>
<View>
<GenericDropdown
options={subactivities.map(s => ({ id: s.uuid, label: s.label }))}
selectedId={selectedSubactivityUuid}
onSelect={(id) => setSelectedSubactivityUuid(id as string)}
placeholder="Seleziona il cantiere"
searchPlaceholder="Cerca cantiere"
/>
</View>
</View>
<View className="mb-4">
<Text className="text-[#082963] font-bold text-sm mb-2 uppercase">Data</Text>
<TouchableOpacity
onPress={() => setShowDatePicker(true)}
className="bg-gray-50 border border-gray-200 p-3 rounded-2xl flex-row items-center justify-between"
>
<Text className="text-gray-800 text-base">{date ? formatDate(formatPickerDate(date) || undefined) : ''}</Text>
<CalendarIcon size={20} color="#9ca3af" />
</TouchableOpacity>
{showDatePicker && (
<Modal visible={showDatePicker} transparent animationType="fade">
<View className="flex-1 bg-black/50 justify-center px-4">
<View className="bg-white rounded-3xl p-5 w-full max-w-sm self-center shadow-lg">
<AppDatePicker
date={date}
mode="single"
onChange={handleDateChange}
/>
<TouchableOpacity
onPress={() => setShowDatePicker(false)}
className="mt-4 p-3 rounded-xl items-center border border-gray-200 active:bg-gray-50"
>
<Text className="text-gray-600 font-bold">Chiudi</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
)}
</View>
<View>
<Text className="text-[#082963] font-bold text-sm mb-2 uppercase">Descrizione</Text>
<TextInput
value={description}
onChangeText={setDescription}
placeholder="Inserisci una descrizione (opzionale)"
multiline
numberOfLines={4}
textAlignVertical="top"
className="bg-gray-50 border border-gray-200 p-4 rounded-2xl text-gray-800 text-base min-h-[100px]"
/>
</View>
</View>
{/* Labor Cards */}
<View>
<ActivityLaborCard
title="Operai"
fetchUrl="/activity/get-operators"
laborList={operatorLabor}
onAddLabor={(labor) => setOperatorLabor([...operatorLabor, labor])}
onRemoveLabor={(idx) => setOperatorLabor(operatorLabor.filter((_, i) => i !== idx))}
/>
<ActivityLaborCard
title="Subappaltatori"
fetchUrl="/activity/get-subcontractors"
laborList={subcontractorLabor}
onAddLabor={(labor) => setSubcontractorLabor([...subcontractorLabor, labor])}
onRemoveLabor={(idx) => setSubcontractorLabor(subcontractorLabor.filter((_, i) => i !== idx))}
/>
<ActivityLaborCard
title="Operai Distaccati"
fetchUrl="/activity/get-other-operators"
laborList={otherOperatorLabor}
onAddLabor={(labor) => setOtherOperatorLabor([...otherOperatorLabor, labor])}
onRemoveLabor={(idx) => setOtherOperatorLabor(otherOperatorLabor.filter((_, i) => i !== idx))}
/>
<ActivityLaborCard
title="Attrezzature"
fetchUrl="/activity/get-equipment"
laborList={equipmentLabor}
onAddLabor={(labor) => setEquipmentLabor([...equipmentLabor, labor])}
onRemoveLabor={(idx) => setEquipmentLabor(equipmentLabor.filter((_, i) => i !== idx))}
/>
</View>
{/* Photos */}
<View className="bg-white rounded-3xl p-5 shadow-sm border border-gray-100 mb-6">
<Text className="text-[#082963] font-bold text-lg mb-4">Allegati</Text>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: gap }}>
{/* Existing Photos (Read-only) */}
{existingPhotos.map((photo, index) => (
<View key={`ext-${index}`} style={{ width: tileWidth, height: tileWidth }} className="rounded-2xl overflow-hidden border border-gray-200">
<Image source={{ uri: photo.uri }} style={{ width: '100%', height: '100%' }} contentFit="cover" />
</View>
))}
{/* New Photos */}
{photos.map((photo, index) => (
<RemovablePhotoTile key={`new-${index}`} uri={photo.uri} onRemove={() => removePhoto(index)} size={tileWidth} />
))}
{/* Add Buttons */}
{(photos.length + existingPhotos.length) < 50 && (
<>
<CameraAddTile onPress={takePhoto} size={tileWidth} />
<TouchableOpacity
onPress={pickFromGallery}
style={{ width: tileWidth, height: tileWidth }}
className="bg-blue-50 items-center justify-center rounded-2xl border border-blue-100 border-dashed"
>
<ImageIcon size={24} color="#1071C2" />
</TouchableOpacity>
</>
)}
</View>
</View>
{/* Submit */}
<TouchableOpacity
onPress={handleSave}
disabled={isSubmitting}
className={`bg-[#1071C2] p-4 rounded-full items-center justify-center mt-2 flex-row gap-2 ${isSubmitting ? 'opacity-70' : 'active:bg-[#0d5a9b]'}`}
>
{isSubmitting ? (
<ActivityIndicator color="white" />
) : (
<Text className="text-white font-bold text-lg uppercase tracking-wider">
{isEditing ? 'Salva Modifiche' : 'Salva Attività'}
</Text>
)}
</TouchableOpacity>
</KeyboardAwareScrollView>
</View>
);
}
+191
View File
@@ -0,0 +1,191 @@
import { useAlert } from '@/components/AlertComponent';
import LoadingScreen from '@/components/LoadingScreen';
import api from '@/utils/api';
import { Plus, Filter, Newspaper, ShoppingBag } 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, ActivityItem } 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<ActivityItem[]>([]);
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('/construction-site/get-construction-sites');
if (response.data?.success) {
setPlaces(response.data.constructionSites || []);
}
} 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, constructionSite: currentPlace };
const response = await api.post('/activity/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">Lista delle attività nei cantieri</Text>
<Text className="text-yellow-400 text-3xl font-bold leading-tight">Attività Cantieri</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 alla lista delle attività di cantiere</Text>
</View>
) : (
<View className="gap-4">
{updates.map((item, index) => (
<TouchableOpacity
key={index}
className="bg-white p-5 rounded-2xl shadow-sm border border-gray-100 active:bg-gray-50"
onPress={() => router.push(`/activity/${item.id}`)}
>
<View className="flex-row items-center mb-3">
<View className="bg-blue-50 p-3 rounded-full items-center justify-center mr-4">
<ShoppingBag size={24} color="#082963" />
</View>
<View className="flex-1">
<Text className="font-bold text-[#082963] text-lg uppercase leading-tight mb-1">
{item.constructionSite}
</Text>
<Text className="text-[#082963] text-sm font-medium leading-tight mb-1">
{item.subactivity ?? '-'}
</Text>
<Text className="text-gray-400 text-sm font-bold">
{item.date}
</Text>
</View>
</View>
{item.description ? (
<View className="flex-row items-center pt-3 border-t border-gray-50">
<Text numberOfLines={4} className="text-[#082963] text-[13px] font-medium leading-tight">
{item.description}
</Text>
</View>
) : null}
</TouchableOpacity>
))}
</View>
)}
</ScrollView>
{/* FAB Add Journal */}
<TouchableOpacity
onPress={() => router.push('/activity/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>
);
}
+248
View File
@@ -0,0 +1,248 @@
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';
import { useLocalSearchParams } from 'expo-router';
export default function AttendanceScreen() {
const alert = useAlert();
const { autoScan } = useLocalSearchParams();
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('/construction-site/get-construction-sites');
if (response.data?.success) {
setPlaces(response.data.constructionSites || []);
}
} 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, constructionSite: 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);
}, []);
useEffect(() => {
if (autoScan === 'true') {
setShowScanner(true);
}
}, [autoScan]);
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>
);
}
@@ -0,0 +1,162 @@
import DocumentListCard from '@/components/DocumentListCard';
import LoadingScreen from '@/components/LoadingScreen';
import { DocumentItem } from '@/types/types';
import api from '@/utils/api';
import * as DocumentPicker from 'expo-document-picker';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { ChevronLeft, AlertCircle } from 'lucide-react-native';
import { useAlert } from '@/components/AlertComponent';
import { uploadDocument } from '@/utils/documentUtils';
import React, { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
export default function ConstructionSiteDocumentsScreen() {
const { id, name } = useLocalSearchParams();
const router = useRouter();
const alert = useAlert();
const [documents, setDocuments] = useState<DocumentItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const [isUploading, setIsUploading] = useState(false);
const fetchDocuments = useCallback(async () => {
try {
const response = await api.get(`/construction-site/get-attachments?id=${id}`);
if (response.data?.success) {
setDocuments(response.data.result || []);
}
} catch (error) {
console.error('Errore nel recupero dei documenti:', error);
alert.showAlert('error', 'Errore', 'Impossibile recuperare la lista dei documenti.');
} finally {
setIsLoading(false);
setIsRefreshing(false);
}
}, [id]);
useEffect(() => {
if (id) {
fetchDocuments();
}
}, [id, fetchDocuments]);
const onRefresh = () => {
setIsRefreshing(true);
fetchDocuments();
};
const handleUpload = async () => {
try {
const result = await DocumentPicker.getDocumentAsync({
type: '*/*',
copyToCacheDirectory: true,
multiple: false,
});
if (result.canceled || !result.assets || result.assets.length === 0) {
return;
}
const file = result.assets[0];
setIsUploading(true);
await uploadDocument(file, {
endpoint: '/construction-site/upload-attachment',
fileKey: 'files',
extraData: {
model_classname: 'ConstructionSite',
model_id: id as string,
method: 'put',
name: file.name,
type: file.mimeType || 'application/octet-stream'
}
});
alert.showAlert('success', 'Successo', 'Documento caricato con successo.');
onRefresh(); // reload list
} catch (error: any) {
console.error('Errore durante l\'upload:', error);
alert.showAlert('error', 'Errore', error.message || 'Si è verificato un errore durante l\'upload del documento.');
} finally {
setIsUploading(false);
}
};
if (isLoading && !isRefreshing) {
return <LoadingScreen />;
}
return (
<View className="flex-1 bg-primary-dark">
<StatusBar style="light" />
<SafeAreaView edges={['top']} className="pt-5">
{/* Header */}
<View className="pb-6 px-6 z-10 flex-row items-center justify-between">
<TouchableOpacity
onPress={() => router.back()}
className="p-2 -ml-2 rounded-full active:bg-white/20 w-12 items-center justify-center"
>
<ChevronLeft size={28} color="white" pointerEvents="none" />
</TouchableOpacity>
<View className="flex-1 px-2">
<Text className="text-white text-xl font-bold text-center leading-tight uppercase" numberOfLines={1}>
{name || 'Allegati Cantiere'}
</Text>
</View>
<View className="w-10" />
</View>
</SafeAreaView>
{/* Content */}
<View className="flex-1 bg-slate-50 rounded-t-[2.5rem] overflow-hidden">
{isUploading && (
<View className="absolute z-10 top-0 left-0 right-0 bottom-0 bg-white/50 justify-center items-center">
<ActivityIndicator size="large" color="#1071C2" />
<Text className="text-primary-dark font-bold mt-2">Caricamento in corso...</Text>
</View>
)}
<ScrollView
className="flex-1 px-6 pt-6"
contentContainerStyle={{ paddingBottom: 100 }}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={isRefreshing} onRefresh={onRefresh} colors={['#1071C2']} />
}
>
<View className="flex-row justify-between items-center mb-6 px-1">
<Text className="text-slate-800 text-xl font-bold">Documenti</Text>
<TouchableOpacity onPress={handleUpload} disabled={isUploading}>
{isUploading ? (
<ActivityIndicator size="small" color="#1071C2" />
) : (
<Text className="text-[#1071C2] text-lg font-semibold">Aggiungi</Text>
)}
</TouchableOpacity>
</View>
{documents.length > 0 ? (
<View className="gap-4">
{documents.map((item, index) => (
<DocumentListCard key={item.id || index} item={item} />
))}
</View>
) : (
<View className="bg-white p-8 rounded-3xl border border-slate-200 items-center justify-center border-dashed mt-4">
<View className="bg-slate-50 p-4 rounded-full mb-3">
<AlertCircle size={32} color="#94a3b8" />
</View>
<Text className="text-slate-500 font-medium text-center">
Nessun documento caricato per questo cantiere.
</Text>
</View>
)}
</ScrollView>
</View>
</View>
);
}
@@ -0,0 +1,177 @@
import LoadingScreen from '@/components/LoadingScreen';
import api from '@/utils/api';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { Building2, ChevronLeft, Paperclip, AlertCircle, FileText } from 'lucide-react-native';
import React, { useEffect, useState } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
const InfoRow = ({
label,
value,
isLast = false,
isCode = false
}: {
label: string;
value?: string | number | null;
isLast?: boolean;
isCode?: boolean
}) => (
<View className={`flex-row justify-between items-start ${!isLast ? 'border-b border-slate-100 pb-3' : ''}`}>
<Text className="text-slate-500 font-medium">{label}</Text>
<Text
selectable={true}
className={`text-primary-dark font-bold text-right flex-1 ${isCode ? 'tracking-widest' : ''}`}
>
{value || '-'}
</Text>
</View>
);
export default function ConstructionSiteDetailsScreen() {
const { id } = useLocalSearchParams();
const router = useRouter();
const [isLoading, setIsLoading] = useState(true);
const [siteData, setSiteData] = useState<any>(null);
const fetchDetails = async () => {
try {
const response = await api.get(`/construction-site/get-info?id=${id}`);
if (response.data?.success) {
setSiteData(response.data.result);
}
} catch (error) {
console.error('Errore nel recupero dei dettagli del cantiere:', error);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
if (id) {
fetchDetails();
}
}, [id]);
if (isLoading) {
return <LoadingScreen />;
}
if (!siteData) {
return (
<View className="flex-1 bg-slate-50 justify-center items-center">
<AlertCircle size={48} color="#94a3b8" />
<Text className="text-slate-500 mt-4 font-medium">Impossibile caricare i dettagli.</Text>
<TouchableOpacity onPress={() => router.back()} className="mt-4 px-6 py-2 bg-primary-dark rounded-full">
<Text className="text-white font-bold">Indietro</Text>
</TouchableOpacity>
</View>
);
}
const { constructionSite, client, subactivities } = siteData;
return (
<View className="flex-1 bg-primary-dark">
<StatusBar style="light" />
<SafeAreaView edges={['top']} className="pt-5">
{/* Header */}
<View className="pb-6 px-6 z-10 flex-row items-center justify-between">
<TouchableOpacity
onPress={() => router.back()}
className="p-2 -ml-2 rounded-full active:bg-white/20 w-12 items-center justify-center"
>
<ChevronLeft size={28} color="white" pointerEvents="none" />
</TouchableOpacity>
<View className="flex-1 px-2">
<Text className="text-white text-xl font-bold text-center leading-tight" numberOfLines={1}>
{constructionSite?.name || 'Dettaglio Cantiere'}
</Text>
</View>
<TouchableOpacity
onPress={() => router.push(`/construction-site/${id}/documents?name=${encodeURIComponent(constructionSite?.name || '')}`)}
className="p-2 -mr-2 rounded-full active:bg-white/20 w-12 items-center justify-center"
>
<Paperclip size={22} color="white" pointerEvents="none" />
</TouchableOpacity>
</View>
</SafeAreaView>
{/* Content */}
<View className="flex-1 bg-slate-50 rounded-t-[2.5rem] overflow-hidden">
<ScrollView
className="flex-1 px-6 pt-8"
contentContainerStyle={{ paddingBottom: 100 }}
showsVerticalScrollIndicator={false}
>
{/* Info Card */}
<View className="bg-white rounded-3xl p-6 shadow-sm border border-slate-100 mb-6">
<View className="flex-row items-center mb-6">
<View className="bg-primary-50 p-3 rounded-xl mr-4">
<Building2 size={24} color="#1071C2" />
</View>
<Text className="text-xl font-bold text-slate-800 flex-1">Informazioni</Text>
</View>
<View className="gap-4">
<InfoRow label="Cliente" value={client} />
<InfoRow label="Indirizzo" value={constructionSite?.address} />
<InfoRow label="CIG" value={constructionSite?.cig} isCode={true} />
<InfoRow label="CUP" value={constructionSite?.cup} isCode={true} />
<InfoRow
label="% Ribasso"
value={constructionSite?.reduction ? `${constructionSite.reduction} %` : undefined}
isLast={true}
/>
</View>
</View>
{/* Subactivities */}
{subactivities && subactivities.length > 0 && (
<View className="mb-6">
<Text className="text-slate-800 text-xl font-bold mb-4 px-2">Sottocommesse</Text>
<View className="gap-3">
{subactivities.map((sub: any, index: number) => {
const hasCodes = sub.cig || sub.cup;
return (
<View key={index} className="bg-white p-5 rounded-2xl shadow-sm border border-slate-100">
<View className={`flex-row items-center ${hasCodes ? 'mb-3 border-b border-slate-50 pb-3' : ''}`}>
<View className="bg-slate-50 p-2 rounded-lg mr-3">
<FileText size={20} color="#64748b" />
</View>
<Text selectable={true} className="text-slate-800 font-bold text-sm uppercase flex-1 leading-tight">
{sub.code} - {sub.description}
</Text>
</View>
{hasCodes && (
<View className="gap-2 px-2">
{sub.cig && (
<View className="flex-row justify-between items-center">
<Text className="text-slate-500 text-xs font-medium">CIG</Text>
<Text selectable={true} className="text-primary-dark font-bold text-sm tracking-widest">{sub.cig}</Text>
</View>
)}
{sub.cup && (
<View className="flex-row justify-between items-center">
<Text className="text-slate-500 text-xs font-medium">CUP</Text>
<Text selectable={true} className="text-primary-dark font-bold text-sm tracking-widest">{sub.cup}</Text>
</View>
)}
</View>
)}
</View>
);
})}
</View>
</View>
)}
</ScrollView>
</View>
</View>
);
}
@@ -0,0 +1,10 @@
import { Stack } from 'expo-router';
export default function ConstructionSiteLayout() {
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="[id]/index" />
<Stack.Screen name="[id]/documents" />
</Stack>
);
}
+337
View File
@@ -0,0 +1,337 @@
import React, { useState, useEffect, useMemo, useRef } from 'react';
import { View, Text, ScrollView, TouchableOpacity, ActivityIndicator, Dimensions } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { ChevronDown, ChevronUp, LayoutDashboard } from 'lucide-react-native';
import api from '@/utils/api';
import { useAlert } from '@/components/AlertComponent';
import EchartWrapper from '@/components/EchartWrapper';
import {
CHART_ENDPOINTS,
CHART_DATA_KEY,
cumulate,
formatEuro,
buildPieOption,
buildSoaBarOption,
commesseLine,
buildAperteChiuseOption
} from '@/utils/dashboardCharts';
const TOOLTIP_BASE = {
renderMode: 'richText',
confine: true,
textStyle: { fontSize: 10 }
};
const screenWidth = Dimensions.get("window").width;
export default function DashboardScreen() {
const router = useRouter();
const alert = useAlert();
const [chartData, setChartData] = useState<any>({
costiRicavi: null,
fatturatoCliente: null,
aperteChiuseCliente: null,
aperteChiuseFornitore: null,
fatturatoSoa: null,
partiteCliente: null,
marginalitaMediaSoa: null,
aggregatiSoa: null
});
const [loadingCharts, setLoadingCharts] = useState<Record<string, boolean>>({});
const [expandedCards, setExpandedCards] = useState<Record<string, boolean>>({
costiRicavi: false,
costiRicaviCum: false,
aperteChiuseCliente: false,
aperteChiuseFornitore: false,
fatturatoSoa: false,
fatturatoCliente: false,
apertoCliente: false,
chiusoCliente: false,
marginalitaMediaSoa: false,
marginalitaCategoriaSoa: false,
pesoFatturatoSoa: false
});
const chartRichiesti = useRef(new Set<string>());
const isLoading = (key: string) => !!loadingCharts[CHART_DATA_KEY[key] || key];
const fetchChart = (key: keyof typeof CHART_ENDPOINTS) => {
const dataKey = CHART_DATA_KEY[key] || key;
const endpoint = CHART_ENDPOINTS[key];
if (!endpoint || chartRichiesti.current.has(dataKey)) { return Promise.resolve(); }
chartRichiesti.current.add(dataKey);
setLoadingCharts(prev => ({ ...prev, [dataKey]: true }));
return api.get(endpoint).then(res => {
if (res.data && res.data.success) {
setChartData((prev: any) => ({ ...prev, [dataKey]: res.data.result }));
}
}).catch(err => {
chartRichiesti.current.delete(dataKey);
console.log("Errore caricamento dashboard:", err);
}).finally(() => {
setLoadingCharts(prev => ({ ...prev, [dataKey]: false }));
});
};
// Sequential Prefetching
useEffect(() => {
let cancelled = false;
const prefetch = async () => {
const richieste: string[] = [];
const visti = new Set<string>();
Object.keys(CHART_ENDPOINTS).forEach(key => {
const dataKey = CHART_DATA_KEY[key] || key;
if (visti.has(dataKey)) { return; }
visti.add(dataKey);
richieste.push(key);
});
for (const key of richieste) {
if (cancelled) { return; }
await fetchChart(key as keyof typeof CHART_ENDPOINTS);
}
};
prefetch();
return () => { cancelled = true; };
}, []);
const toggleCard = (key: string) => {
const isCurrentlyExpanded = expandedCards[key];
setExpandedCards(prev => ({ ...prev, [key]: !prev[key] }));
const dataKey = CHART_DATA_KEY[key] || key;
if (!isCurrentlyExpanded && !chartData[dataKey] && !isLoading(key)) {
fetchChart(key as keyof typeof CHART_ENDPOINTS);
}
};
// --- Chart Options ---
const costiRicaviOption = useMemo(() => !chartData.costiRicavi ? null : {
tooltip: {
...TOOLTIP_BASE,
trigger: 'axis',
valueFormatter: formatEuro
},
legend: {
bottom: 0,
itemGap: 6,
itemWidth: 14,
itemHeight: 10,
textStyle: { fontSize: 12 },
data: [
`Costi Materiali(${chartData.costiRicavi.current_year})`,
`Costi Manodopera(${chartData.costiRicavi.current_year})`,
`Ricavi(${chartData.costiRicavi.current_year})`,
`Utile(${chartData.costiRicavi.current_year})`,
`Costi Materiali(${chartData.costiRicavi.prev_year})`,
`Costi Manodopera(${chartData.costiRicavi.prev_year})`,
`Ricavi(${chartData.costiRicavi.prev_year})`,
`Utile(${chartData.costiRicavi.prev_year})`
],
selected: {
[`Utile(${chartData.costiRicavi.prev_year})`]: false,
[`Ricavi(${chartData.costiRicavi.prev_year})`]: false,
[`Costi Materiali(${chartData.costiRicavi.prev_year})`]: false,
[`Costi Manodopera(${chartData.costiRicavi.prev_year})`]: false
},
},
grid: {
left: '3%',
right: '4%',
top: '8%',
bottom: 95,
containLabel: true
},
xAxis: {
type: 'category',
data: chartData.costiRicavi.mesi
},
yAxis: {
type: 'value'
},
series: [
{ name: `Costi Materiali(${chartData.costiRicavi.current_year})`, type: 'bar', data: chartData.costiRicavi.costi },
{ name: `Costi Manodopera(${chartData.costiRicavi.current_year})`, type: 'bar', data: chartData.costiRicavi.costi_mdo },
{ name: `Ricavi(${chartData.costiRicavi.current_year})`, type: 'bar', data: chartData.costiRicavi.ricavi },
{ name: `Utile(${chartData.costiRicavi.current_year})`, type: 'bar', lineStyle: { width: 2.5, type: 'dashed' }, data: chartData.costiRicavi.utile },
{ name: `Costi Materiali(${chartData.costiRicavi.prev_year})`, type: 'bar', itemStyle: { color: '#b3b3b3' }, data: chartData.costiRicavi.costi_prev },
{ name: `Costi Manodopera(${chartData.costiRicavi.prev_year})`, type: 'bar', itemStyle: { color: '#b3b3b3' }, data: chartData.costiRicavi.costi_mdo_prev },
{ name: `Ricavi(${chartData.costiRicavi.prev_year})`, type: 'bar', itemStyle: { color: '#b3b3b3' }, data: chartData.costiRicavi.ricavi_prev },
{ name: `Utile(${chartData.costiRicavi.prev_year})`, type: 'bar', lineStyle: { width: 1.5, type: 'dashed', color: '#b3b3b3' }, data: chartData.costiRicavi.utile_prev }
]
}, [chartData.costiRicavi]);
const costiRicaviCumOption = useMemo(() => {
if (!chartData.costiRicavi) return null;
const d = chartData.costiRicavi;
return {
tooltip: {
...TOOLTIP_BASE,
trigger: 'axis',
valueFormatter: formatEuro
},
legend: {
bottom: 0,
itemGap: 6,
itemWidth: 14,
itemHeight: 10,
textStyle: { fontSize: 12 },
data: [
`Costi Materiali(${d.current_year})`,
`Costi Manodopera(${d.current_year})`,
`Ricavi(${d.current_year})`,
`Utile(${d.current_year})`,
`Costi Materiali(${d.prev_year})`,
`Costi Manodopera(${d.prev_year})`,
`Ricavi(${d.prev_year})`,
`Utile(${d.prev_year})`
],
selected: {
[`Utile(${d.prev_year})`]: false,
[`Ricavi(${d.prev_year})`]: false,
[`Costi Materiali(${d.prev_year})`]: false,
[`Costi Manodopera(${d.prev_year})`]: false
},
},
grid: {
left: '3%',
right: '4%',
top: '8%',
bottom: 95,
containLabel: true
},
xAxis: {
type: 'category',
data: d.mesi
},
yAxis: {
type: 'value'
},
series: [
{ name: `Costi Materiali(${d.current_year})`, type: 'bar', data: cumulate(d.costi) },
{ name: `Costi Manodopera(${d.current_year})`, type: 'bar', data: cumulate(d.costi_mdo) },
{ name: `Ricavi(${d.current_year})`, type: 'bar', data: cumulate(d.ricavi) },
{ name: `Utile(${d.current_year})`, type: 'bar', lineStyle: { width: 2.5, type: 'dashed' }, data: cumulate(d.utile) },
{ name: `Costi Materiali(${d.prev_year})`, type: 'bar', itemStyle: { color: '#b3b3b3' }, data: cumulate(d.costi_prev) },
{ name: `Costi Manodopera(${d.prev_year})`, type: 'bar', itemStyle: { color: '#b3b3b3' }, data: cumulate(d.costi_mdo_prev) },
{ name: `Ricavi(${d.prev_year})`, type: 'bar', itemStyle: { color: '#b3b3b3' }, data: cumulate(d.ricavi_prev) },
{ name: `Utile(${d.prev_year})`, type: 'bar', lineStyle: { width: 1.5, type: 'dashed', color: '#b3b3b3' }, data: cumulate(d.utile_prev) }
]
};
}, [chartData.costiRicavi]);
const aperteChiuseClienteOption = useMemo(() => chartData.aperteChiuseCliente ? buildAperteChiuseOption(chartData.aperteChiuseCliente) : null, [chartData.aperteChiuseCliente]);
const aperteChiuseFornitoreOption = useMemo(() => chartData.aperteChiuseFornitore ? buildAperteChiuseOption(chartData.aperteChiuseFornitore) : null, [chartData.aperteChiuseFornitore]);
const fatturatoClienteOption = useMemo(() => chartData.fatturatoCliente ? buildPieOption(chartData.fatturatoCliente) : null, [chartData.fatturatoCliente]);
const fatturatoSoaOption = useMemo(() => chartData.fatturatoSoa ? buildPieOption(chartData.fatturatoSoa) : null, [chartData.fatturatoSoa]);
const apertoClienteOption = useMemo(() => chartData.partiteCliente ? buildPieOption(chartData.partiteCliente.aperto) : null, [chartData.partiteCliente]);
const chiusoClienteOption = useMemo(() => chartData.partiteCliente ? buildPieOption(chartData.partiteCliente.chiuso) : null, [chartData.partiteCliente]);
const numItems = chartData.fatturatoCliente?.length || 0;
const dynamicPieHeight = Math.max(260, 200 + (Math.ceil(numItems / 2) * 26));
const numItemsSoa = chartData.fatturatoSoa?.length || 0;
const dynamicSoaHeight = Math.max(260, 200 + (numItemsSoa * 26));
const pieHeightFor = (arr: any) => Math.max(260, 200 + (Math.ceil((arr?.length || 0) / 2) * 26));
const dynamicApertoHeight = pieHeightFor(chartData.partiteCliente?.aperto);
const dynamicChiusoHeight = pieHeightFor(chartData.partiteCliente?.chiuso);
const marginalitaMediaSoaOption = useMemo(() => chartData.marginalitaMediaSoa
? buildSoaBarOption(chartData.marginalitaMediaSoa, { color: '#5470c6', valueLabel: 'Marginalità media', extraLines: commesseLine })
: null, [chartData.marginalitaMediaSoa]);
const marginalitaCategoriaOption = useMemo(() => chartData.aggregatiSoa
? buildSoaBarOption(chartData.aggregatiSoa.marginalitaCategoria, { color: '#3ba272', valueLabel: 'Marginalità categoria', extraLines: commesseLine })
: null, [chartData.aggregatiSoa]);
const pesoFatturatoSoaOption = useMemo(() => chartData.aggregatiSoa
? buildSoaBarOption(chartData.aggregatiSoa.pesoFatturato, {
color: '#fac858', valueLabel: 'Peso', extraLines: (r: any) => [
`Fatturato categoria: ${formatEuro(r.fatturato_tot)}`,
`Commesse: ${r.n_commesse}`
]
}) : null, [chartData.aggregatiSoa]);
const soaBarHeight = (arr: any) => Math.max(280, (arr?.length || 0) * 36 + 80);
const dynamicMarginalitaHeight = soaBarHeight(chartData.marginalitaMediaSoa);
const dynamicMarginalitaCatHeight = soaBarHeight(chartData.aggregatiSoa?.marginalitaCategoria);
const dynamicPesoSoaHeight = soaBarHeight(chartData.aggregatiSoa?.pesoFatturato);
// Render Card Helper
const renderCard = (key: string, title: string, option: any, height: number) => {
const isExpanded = expandedCards[key];
const loading = isLoading(key);
return (
<View className="bg-white rounded-2xl shadow-sm border border-gray-100 w-full mb-4 overflow-hidden" key={key}>
<TouchableOpacity
className="flex-row items-center justify-between p-4 active:bg-gray-50"
onPress={() => toggleCard(key)}
>
<Text className="text-gray-800 font-bold text-lg">{title}</Text>
{isExpanded ? <ChevronUp size={24} color="#082963" /> : <ChevronDown size={24} color="#082963" />}
</TouchableOpacity>
{isExpanded && (
<View className="p-4 pt-0 border-t border-gray-50">
{loading ? (
<ActivityIndicator size="small" color="#1071C2" className="my-6" />
) : option ? (
<View style={{ width: screenWidth - 64, height: height, overflow: 'hidden' }} className="self-center">
<EchartWrapper option={option} width={screenWidth - 64} height={height} />
</View>
) : (
<Text className="text-gray-400 text-center my-4">Nessun dato disponibile</Text>
)}
</View>
)}
</View>
);
};
return (
<View className="flex-1 bg-primary-dark">
<StatusBar style="light" />
<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">Grafici e Statistiche</Text>
<Text className="text-yellow-400 text-3xl font-bold leading-tight">Dashboard</Text>
</View>
<View className="bg-white/10 p-4 rounded-full">
<LayoutDashboard size={32} color="white" pointerEvents="none" />
</View>
</View>
</SafeAreaView>
<View className="flex-1 bg-gray-50 rounded-t-[2.5rem] overflow-hidden">
<ScrollView
className="flex-1"
contentContainerStyle={{ padding: 20 }}
showsVerticalScrollIndicator={false}
>
{renderCard('costiRicavi', 'Costi / Ricavi', costiRicaviOption, 390)}
{renderCard('costiRicaviCum', 'Costi / Ricavi (Cumulati)', costiRicaviCumOption, 390)}
{renderCard('aperteChiuseCliente', 'Aperto / Chiuso Clienti', aperteChiuseClienteOption, 330)}
{renderCard('aperteChiuseFornitore', 'Aperto / Chiuso Fornitori', aperteChiuseFornitoreOption, 330)}
{renderCard('fatturatoSoa', 'Fatturato per SOA', fatturatoSoaOption, dynamicSoaHeight)}
{renderCard('fatturatoCliente', 'Fatturato per Cliente', fatturatoClienteOption, dynamicPieHeight)}
{renderCard('apertoCliente', 'Aperto per Cliente', apertoClienteOption, dynamicApertoHeight)}
{renderCard('chiusoCliente', 'Chiuso per Cliente', chiusoClienteOption, dynamicChiusoHeight)}
{renderCard('marginalitaMediaSoa', 'Marginalità media per SOA', marginalitaMediaSoaOption, dynamicMarginalitaHeight)}
{renderCard('marginalitaCategoriaSoa', 'Marginalità % di categoria SOA', marginalitaCategoriaOption, dynamicMarginalitaCatHeight)}
{renderCard('pesoFatturatoSoa', 'Peso fatturato SOA', pesoFatturatoSoaOption, dynamicPesoSoaHeight)}
</ScrollView>
</View>
</View>
);
}
+229
View File
@@ -0,0 +1,229 @@
import ConstructionSiteCard from '@/components/ConstructionSiteCard';
import FilterModal from '@/components/FilterModal';
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, Filter, QrCode, User, ShoppingBag, ChartNoAxesCombined } 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';
import { Client, ConstructionSite } from '@/types/types';
export default function HomeScreen() {
const router = useRouter();
const { user } = useContext(AuthContext);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
// Construction Sites & Filters state
const [constructionSites, setConstructionSites] = useState<ConstructionSite[]>([]);
const [clients, setClients] = useState<Client[]>([]);
const [filterClient, setFilterClient] = useState<any>(null);
const [isFilterVisible, setIsFilterVisible] = useState(false);
const activeFiltersCount = filterClient ? 1 : 0;
const fetchClients = async () => {
try {
const response = await api.get('/construction-site/get-clients');
if (response.data?.success) {
setClients(response.data.clients || []);
}
} catch (error) {
console.error('Errore nel recupero dei committenti:', error);
}
};
const fetchConstructionSites = async (clientId = filterClient) => {
try {
if (!refreshing) setIsLoading(true);
const params = { id_client: clientId };
const response = await api.post('/construction-site/list', { params });
if (response.data?.success) {
setConstructionSites(response.data.result || []);
}
} catch (error) {
console.error('Errore nel recupero dei cantieri:', error);
} finally {
setIsLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
fetchClients();
fetchConstructionSites();
}, []);
const onRefresh = () => {
setRefreshing(true);
fetchConstructionSites();
};
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-sm font-semibold uppercase tracking-wider mb-2">
Progeco Costruzioni Generali S.R.L.
</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 */}
<View className="flex-1 bg-slate-50 rounded-t-[2.5rem] overflow-hidden">
<ScrollView
className="flex-1 px-5 pt-6"
contentContainerStyle={{ paddingBottom: 100, gap: 24 }}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />
}
>
{/* Quick Actions / Centro di Controllo */}
<View>
<Text className="text-slate-800 text-xl font-bold mb-4 px-1">
{user?.isAdmin ? 'Centro di Controllo' : 'Azioni Rapide'}
</Text>
{user?.isAdmin ? (
<View className="flex-row gap-5">
<TouchableOpacity
onPress={() => router.push('/dashboard')}
className="flex-1 bg-white p-6 rounded-3xl shadow-sm items-center justify-center gap-4 border border-slate-100 active:scale-[0.98]"
>
<View className="w-20 h-20 rounded-full bg-primary-50 items-center justify-center mb-1">
<ChartNoAxesCombined size={40} color="#1071C2" pointerEvents="none"/>
</View>
<Text className="text-lg font-bold text-slate-700 text-center">Dashboard</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => router.push('/invoice')}
className="flex-1 bg-white p-6 rounded-3xl shadow-sm items-center justify-center gap-4 border border-slate-100 active:scale-[0.98]"
>
<View className="w-20 h-20 rounded-full bg-primary-50 items-center justify-center mb-1">
<FileText size={40} color="#1071C2" pointerEvents="none"/>
</View>
<Text className="text-lg font-bold text-slate-700 text-center">Fatture</Text>
</TouchableOpacity>
</View>
) : (
<View className="flex-row gap-5">
<TouchableOpacity
onPress={() => router.push('/attendance?autoScan=true')}
className="flex-1 bg-white p-6 rounded-3xl shadow-sm items-center justify-center gap-4 border border-slate-100 active:scale-[0.98]"
>
<View className="w-20 h-20 rounded-full bg-primary-50 items-center justify-center mb-1">
<QrCode size={40} color="#1071C2" pointerEvents="none"/>
</View>
<Text className="text-lg font-bold text-slate-700 text-center">Nuova Presenza</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => router.push('/activity/add')}
className="flex-1 bg-white p-6 rounded-3xl shadow-sm items-center justify-center gap-4 border border-slate-100 active:scale-[0.98]"
>
<View className="w-20 h-20 rounded-full bg-primary-50 items-center justify-center mb-1">
<ShoppingBag size={40} color="#1071C2" pointerEvents="none"/>
</View>
<Text className="text-lg font-bold text-slate-700 text-center">Nuova{'\n'}Attività</Text>
</TouchableOpacity>
</View>
)}
</View>
{/* Cantieri */}
<View>
<View className="flex-row justify-between items-center px-1 mb-4">
<Text className="text-slate-800 text-xl font-bold">Lista Cantieri</Text>
</View>
<View className="gap-2">
{constructionSites.map((item, index) => (
<ConstructionSiteCard
key={index}
item={item}
onPress={() => router.push(`/construction-site/${item.id}`)}
/>
))}
{!isLoading && constructionSites.length === 0 && (
<View className="bg-white p-6 rounded-3xl border border-slate-200 items-center justify-center border-dashed">
<Text className="text-slate-400 font-medium text-center">Nessun cantiere trovato.</Text>
</View>
)}
{isLoading && constructionSites.length === 0 && (
<View className="bg-white p-5 rounded-3xl border border-slate-100 h-24 justify-center items-center">
<Text className="text-slate-400">Caricamento...</Text>
</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}
clients={clients}
currentClient={filterClient}
showDate={false}
showPlace={false}
showClient={true}
onClose={() => setIsFilterVisible(false)}
onApply={(_, __, client) => {
setFilterClient(client);
setIsFilterVisible(false);
fetchConstructionSites(client);
}}
onReset={() => {
setFilterClient(null);
setIsFilterVisible(false);
fetchConstructionSites(null);
}}
/>
</View>
</View>
);
}
+148
View File
@@ -0,0 +1,148 @@
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">
<CreditCard size={14} color="#8F9BB3" />
<Text className="text-xs uppercase text-gray-500 font-medium flex-1">{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>
);
}
+10
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>
);
}
+161
View File
@@ -0,0 +1,161 @@
import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, FlatList, 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('/construction-site/get-construction-sites');
if (response.data?.success) {
setPlaces(response.data.constructionSites || []);
}
} 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;
// The backend's construction_site_code matches the name (label) of the construction site
const placeCode = currentPlace ? places.find(p => p.id === currentPlace)?.label : 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 Fornitori</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 */}
<FlatList
data={invoices}
keyExtractor={(item) => item.id.toString()}
className="flex-1"
contentContainerStyle={{ padding: 20, paddingBottom: 100, gap: 16 }}
showsVerticalScrollIndicator={true}
scrollIndicatorInsets={{ right: 1 }}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />}
renderItem={({ item }) => (
<InvoiceCard item={item} onPress={handleInvoicePress} />
)}
ListEmptyComponent={
<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>
}
/>
{/* 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>
);
}
+291
View File
@@ -0,0 +1,291 @@
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, CloudRainWind, Cross, Plus, Thermometer, Trash2, Users, FileText } 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';
// 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" />,
Maltempo: (color) => <CloudRainWind size={24} color={color} pointerEvents="none" />,
Infortunio: (color) => <Cross size={24} color={color} pointerEvents="none" />,
CongedoFamiliare: (color) => <Users 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 typesRes = await api.get('/time-off-request/get-types');
const fetchedTypes: TimeOffRequestType[] = (typesRes.data.types || []).map((t: any) => ({
id: t.id,
name: t.label,
time_required: t.time_required,
color: t.label === 'Infortunio' ? '#EAB308' : (t.color || '#8F9BB3')
}));
const response = await api.post('/time-off-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: fetchedTypes.find(t => t.name === r.type) || fetchedTypes[0],
}));
setPermits(mappedPermits);
setTypes(fetchedTypes);
} 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.post('/time-off-request/delete', { id });
if (res.data?.success) {
// 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', res.data?.message || '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] || ((color: string) => <FileText size={24} color={color} pointerEvents="none" />))(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>
);
}
+10
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>
);
}
+188
View File
@@ -0,0 +1,188 @@
import { useAlert } from '@/components/AlertComponent';
import LoadingScreen from '@/components/LoadingScreen';
import api from '@/utils/api';
import DocumentListCard from '@/components/DocumentListCard';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { ChevronDown, ChevronLeft, 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('/documents/get-types');
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(`/documents/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}}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />
}
initialNumToRender={10}
maxToRenderPerBatch={15}
windowSize={5}
removeClippedSubviews={true}
renderItem={({ item: doc }) => (
<DocumentListCard item={doc} />
)}
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>
);
}
+108
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 flex-1">
<View className="w-14 h-14 bg-blue-50 rounded-2xl items-center justify-center flex-shrink-0">
<Mail size={24} color="#1071C2" pointerEvents="none" />
</View>
<View className="flex-1 pr-4">
<Text className="text-lg text-gray-700 font-bold">Email</Text>
<Text className="text-gray-500 text-base" numberOfLines={1} ellipsizeMode="tail">{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>
);
}
+10
View File
@@ -0,0 +1,10 @@
import {Stack} from 'expo-router';
export default function QualityLayout() {
return (
<Stack screenOptions={{headerShown: false}}>
<Stack.Screen name="index" />
<Stack.Screen name="add" />
</Stack>
);
}
+373
View File
@@ -0,0 +1,373 @@
import { useAlert } from '@/components/AlertComponent';
import { AppDatePicker } from '@/components/AppDatePicker';
import GenericDropdown from '@/components/GenericDropdown';
import FileAttachmentCard from '@/components/FileAttachmentCard';
import api from '@/utils/api';
import { formatDate, formatPickerDate } from '@/utils/dateTime';
import { DateType } from 'react-native-ui-datepicker';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { Calendar, CheckSquare, ChevronLeft, Square } from 'lucide-react-native';
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, KeyboardAvoidingView, Modal, Platform, ScrollView, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import * as DocumentPicker from 'expo-document-picker';
export default function AddQualityControlScreen() {
const router = useRouter();
const alert = useAlert();
const [isSubmitting, setIsSubmitting] = useState(false);
const [showDatePicker, setShowDatePicker] = useState(false);
// Form fields
const [date, setDate] = useState<DateType>(new Date());
const [subactivityId, setSubactivityId] = useState<number | null>(null);
const [workType, setWorkType] = useState<number | null>(null);
const [refDoc, setRefDoc] = useState<number | null>(null);
const [controlType, setControlType] = useState('');
const [instrument, setInstrument] = useState<number | null>(null);
const [result, setResult] = useState<number | null>(null);
// Attachments
const [attachments, setAttachments] = useState<DocumentPicker.DocumentPickerAsset[]>([]);
// Checkboxes
const [checkSegnaletica, setCheckSegnaletica] = useState(false);
const [checkSoggettiTerzi, setCheckSoggettiTerzi] = useState(false);
const [checkUtilizzoDPI, setCheckUtilizzoDPI] = useState(false);
const [checkControlloVisivo, setCheckControlloVisivo] = useState(false);
const [checkControlloDim, setCheckControlloDim] = useState(false);
const [checkConformita, setCheckConformita] = useState(false);
const [checkControlloFunz, setCheckControlloFunz] = useState(false);
// Lists
const [subactivities, setSubactivities] = useState<{id: number | string, label: string}[]>([]);
const [workTypeList, setWorkTypeList] = useState<{id: number, label: string}[]>([]);
const [refDocList, setRefDocList] = useState<{id: number, label: string}[]>([]);
const [instrumentList, setInstrumentList] = useState<{id: number, label: string}[]>([]);
const results = [
{ id: 1, label: 'Positivo' },
{ id: 0, label: 'Negativo' },
];
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
try {
// Load Subactivities
const subRes = await api.get('/subactivity/get-subactivities');
if (subRes.data?.success) {
const mappedSubs = subRes.data.subactivities.map((s: any) => ({
id: s.id,
uuid: s.uuid,
label: s.label
}));
setSubactivities(mappedSubs);
}
// Load Related Tables
const relRes = await api.get('/quality-control/get-related-tables');
if (relRes.data?.success) {
setWorkTypeList(relRes.data.data.workType || []);
setRefDocList(relRes.data.data.refDocument || []);
setInstrumentList(relRes.data.data.instrument || []);
}
} catch (error) {
console.error('Errore nel caricamento dei dati iniziali:', error);
alert.showAlert('error', 'Errore', 'Impossibile caricare i dati per il form.');
}
};
const pickDocument = async () => {
try {
const result = await DocumentPicker.getDocumentAsync({
multiple: true,
copyToCacheDirectory: true,
});
if (!result.canceled && result.assets) {
setAttachments(prev => [...prev, ...result.assets]);
}
} catch (error) {
console.error('Errore durante la selezione del documento:', error);
alert.showAlert('error', 'Errore', 'Impossibile selezionare il documento.');
}
};
const removeAttachment = (index: number) => {
setAttachments(prev => prev.filter((_, i) => i !== index));
};
const handleSave = async () => {
if (!subactivityId || !date || result === null) {
alert.showAlert('warning', 'Dati Mancanti', 'Compila tutti i campi obbligatori (Cantiere, Data, Esito).');
return;
}
setIsSubmitting(true);
try {
const formattedDate = formatPickerDate(date);
const selectedSub = subactivities.find(s => s.id === subactivityId) as any;
const payload = {
subactivity_uuid: selectedSub?.uuid,
id_subactivity: subactivityId,
subactivity_id: subactivityId, // just in case
id_work_type: workType,
date: formattedDate,
id_ref_document: refDoc,
control_type: controlType,
id_instrument: instrument,
result: result,
check_segnaletica: checkSegnaletica ? 1 : 0,
check_soggetti_terzi: checkSoggettiTerzi ? 1 : 0,
check_utilizzo_dpi: checkUtilizzoDPI ? 1 : 0,
check_controllo_visivo: checkControlloVisivo ? 1 : 0,
check_controllo_dim: checkControlloDim ? 1 : 0,
check_conformita: checkConformita ? 1 : 0,
check_controllo_funz: checkControlloFunz ? 1 : 0,
};
const response = await api.post('/quality-control/add', { post: JSON.stringify(payload) });
if (response.data?.success) {
const qcId = response.data.id;
// Upload attachments if present
if (attachments.length > 0) {
for (let i = 0; i < attachments.length; i++) {
const file = attachments[i];
const formData = new FormData();
const fileName = file.name || `document_${i}`;
const fileType = file.mimeType || 'application/octet-stream';
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', 'QualityControl');
formData.append('model_id', qcId);
formData.append('method', 'put');
formData.append('name', fileName);
formData.append('type', fileType);
await api.post('/quality-control/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
});
}
}
alert.showAlert('success', 'Salvato', 'Controllo di Qualità salvato con successo.');
router.back();
} else {
alert.showAlert('error', 'Errore', response.data?.message || 'Salvataggio non riuscito.');
}
} catch (error) {
console.error('Errore durante il salvataggio:', error);
alert.showAlert('error', 'Errore', 'Impossibile completare il salvataggio.');
} finally {
setIsSubmitting(false);
}
};
const CheckboxRow = ({ label, value, onChange }: { label: string, value: boolean, onChange: (v: boolean) => void }) => (
<TouchableOpacity
onPress={() => onChange(!value)}
className="flex-row items-center bg-white border border-gray-100 rounded-xl px-4 py-4 mb-3 active:bg-gray-50 shadow-sm"
>
{value ? <CheckSquare size={24} color="#1071C2" /> : <Square size={24} color="#9ca3af" />}
<Text className="ml-3 text-base text-gray-800 flex-1">{label}</Text>
</TouchableOpacity>
);
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 Controllo
</Text>
</View>
</SafeAreaView>
</View>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'padding'}
className="flex-1"
>
<ScrollView
contentContainerStyle={{ padding: 24 }}
showsVerticalScrollIndicator={false}
keyboardShouldPersistTaps="handled"
>
{/* Date */}
<Text className="text-lg font-bold text-primary-dark mb-3">Data <Text className="text-red-500">*</Text></Text>
<TouchableOpacity
onPress={() => setShowDatePicker(true)}
className="flex-row items-center bg-white border border-gray-200 rounded-2xl px-5 py-4 mb-6 active:bg-gray-50 shadow-sm"
>
<Text className="flex-1 text-base text-gray-800 font-medium">
{date ? formatDate(formatPickerDate(date)) : 'Seleziona data...'}
</Text>
<Calendar size={20} color="#6b7280" />
</TouchableOpacity>
{/* Subactivity / Cantiere */}
<Text className="text-lg font-bold text-primary-dark mb-3">Cantiere <Text className="text-red-500">*</Text></Text>
<View className="mb-6 shadow-sm">
<GenericDropdown
options={subactivities}
selectedId={subactivityId}
onSelect={(id) => setSubactivityId(id as number)}
placeholder="Seleziona cantiere..."
searchPlaceholder="Cerca cantiere..."
/>
</View>
{/* Work Type */}
<Text className="text-lg font-bold text-primary-dark mb-3">Tipologia Lavorazione</Text>
<View className="mb-6 shadow-sm">
<GenericDropdown
options={workTypeList}
selectedId={workType}
onSelect={setWorkType}
placeholder="Seleziona tipologia..."
showSearch={false}
/>
</View>
{/* Reference Document */}
<Text className="text-lg font-bold text-primary-dark mb-3">Documento di Riferimento</Text>
<View className="mb-6 shadow-sm">
<GenericDropdown
options={refDocList}
selectedId={refDoc}
onSelect={setRefDoc}
placeholder="Seleziona documento..."
showSearch={false}
/>
</View>
{/* Control Type */}
<Text className="text-lg font-bold text-primary-dark mb-3">Tipo di Controllo</Text>
<View className="bg-white rounded-2xl border border-gray-200 mb-6 shadow-sm">
<TextInput
className="px-5 py-4 text-base text-gray-800 font-medium"
placeholder="Inserisci tipo di controllo"
placeholderTextColor="#6a7282"
value={controlType}
onChangeText={setControlType}
/>
</View>
{/* Instrument */}
<Text className="text-lg font-bold text-primary-dark mb-3">Strumento Utilizzato</Text>
<View className="mb-8 shadow-sm">
<GenericDropdown
options={instrumentList}
selectedId={instrument}
onSelect={setInstrument}
placeholder="Seleziona strumento..."
showSearch={false}
/>
</View>
{/* Checkboxes */}
<Text className="text-lg font-bold text-primary-dark mb-4 mt-2 border-t border-gray-200 pt-6">Checklist Controlli</Text>
<CheckboxRow label="Presenza e visibilità segnaletica" value={checkSegnaletica} onChange={setCheckSegnaletica} />
<CheckboxRow label="Presenza soggetti terzi" value={checkSoggettiTerzi} onChange={setCheckSoggettiTerzi} />
<CheckboxRow label="Corretto utilizzo DPI" value={checkUtilizzoDPI} onChange={setCheckUtilizzoDPI} />
<CheckboxRow label="Controllo visivo" value={checkControlloVisivo} onChange={setCheckControlloVisivo} />
<CheckboxRow label="Controllo Dimensionale/Elaborati" value={checkControlloDim} onChange={setCheckControlloDim} />
<CheckboxRow label="Controllo conformità mat. posato" value={checkConformita} onChange={setCheckConformita} />
<CheckboxRow label="Controllo funzionale" value={checkControlloFunz} onChange={setCheckControlloFunz} />
{/* Result */}
<Text className="text-lg font-bold text-primary-dark mb-3 mt-6 border-t border-gray-200 pt-6">Esito <Text className="text-red-500">*</Text></Text>
<View className="mb-10 shadow-sm">
<GenericDropdown
options={results}
selectedId={result}
onSelect={setResult}
placeholder="Seleziona esito..."
showSearch={false}
/>
</View>
{/* Attachments Section */}
<View className="mb-8">
<View className="flex-row items-center justify-between mb-4 border-t border-gray-200 pt-6">
<Text className="text-lg font-bold text-primary-dark">
Allegati <Text className="text-sm font-normal text-gray-500">({attachments.length})</Text>
</Text>
<TouchableOpacity activeOpacity={0.7} onPress={pickDocument}>
<Text className="text-[#1071C2] font-bold text-base uppercase">Aggiungi</Text>
</TouchableOpacity>
</View>
<View className="mt-2">
{attachments.map((file, index) => (
<FileAttachmentCard
key={index}
file={file}
onRemove={() => removeAttachment(index)}
/>
))}
{attachments.length === 0 && (
<Text className="text-gray-400 font-medium text-center py-4 bg-white border border-gray-200 border-dashed rounded-2xl">
Nessun file allegato
</Text>
)}
</View>
</View>
{/* Save Button */}
<TouchableOpacity
onPress={handleSave}
disabled={isSubmitting || !subactivityId || !date || result === null}
className={`w-full py-4 rounded-2xl shadow-lg flex-row items-center justify-center ${(!subactivityId || !date || result === null || isSubmitting) ? 'bg-gray-300' : 'bg-[#1071C2] active:scale-[0.98]'}`}
>
{isSubmitting ? (
<ActivityIndicator color="white" />
) : (
<Text className="text-white text-lg font-bold uppercase">Salva</Text>
)}
</TouchableOpacity>
</ScrollView>
</KeyboardAvoidingView>
{/* Date Picker Modal */}
<Modal visible={showDatePicker} transparent animationType="fade">
<View className="flex-1 justify-center items-center bg-black/50">
<View className="bg-white rounded-3xl p-6 w-[90%] shadow-2xl">
<Text className="text-lg font-bold text-gray-800 mb-4">Seleziona Data</Text>
<AppDatePicker
mode="single"
date={date}
onChange={(d) => setDate(d.date || new Date())}
/>
<TouchableOpacity
onPress={() => setShowDatePicker(false)}
className="mt-6 w-full py-4 bg-[#1071C2] rounded-xl active:scale-[0.98]"
>
<Text className="text-white text-center font-bold text-lg">Conferma</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</View>
);
}
+169
View File
@@ -0,0 +1,169 @@
import { useAlert } from '@/components/AlertComponent';
import FilterModal from '@/components/FilterModal';
import LoadingScreen from '@/components/LoadingScreen';
import QualityControlCard from '@/components/QualityControlCard';
import { StatusBar } from 'expo-status-bar';
import api from '@/utils/api';
import { ClipboardCheck, Filter, Plus } from 'lucide-react-native';
import React, { useCallback, useEffect, useState } from 'react';
import { RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Place, QualityControlItem } from '@/types/types';
import { useRouter, useFocusEffect } from 'expo-router';
export default function QualityControlScreen() {
const router = useRouter();
const alert = useAlert();
const [qualityControls, setQualityControls] = useState<QualityControlItem[]>([]);
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('/construction-site/get-construction-sites');
if (response.data?.success) {
setPlaces(response.data.constructionSites || []);
}
} catch (error) {
console.error('Errore nel recupero dei cantieri:', error);
}
};
const fetchQualityControls = async (currentRange = filterRange, currentPlace = filterPlace, isSilent = false) => {
try {
if (!refreshing && !isSilent) setIsLoading(true);
const rangeParam = currentRange.startDate ? currentRange : null;
// The API expects 'constructionSite' which is likely the ID. The filterPlace stores the ID or the Place object?
// According to PlaceFilter and InvoiceScreen, currentPlace is the selectedPlaceId.
const params = { range: rangeParam, constructionSite: currentPlace };
const response = await api.post('/quality-control/list', { params });
if (response.data?.success) {
setQualityControls(response.data.result || []);
}
} catch (error) {
console.error('Errore nel recupero dei controlli qualità:', error);
alert.showAlert('error', 'Errore', 'Impossibile recuperare i dati. Riprova più tardi.');
} finally {
setIsLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
fetchPlaces();
}, []);
useFocusEffect(
useCallback(() => {
fetchQualityControls(filterRange, filterPlace, true);
}, [filterRange, filterPlace])
);
const onRefresh = () => {
setRefreshing(true);
fetchQualityControls();
};
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">Lista dei controlli di qualità</Text>
<Text className="text-yellow-400 text-3xl font-bold leading-tight">Controlli di Qualità</Text>
</View>
<View className="bg-white/10 p-4 rounded-full">
<ClipboardCheck 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: 160 }}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />
}
>
<View className="flex-1 p-5 items-center">
<View className="w-full mt-2">
{qualityControls.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 controllo registrato</Text>
</View>
) : (
<View>
{qualityControls.map((item, index) => (
<QualityControlCard key={item.id || index} item={item} />
))}
</View>
)}
</View>
</View>
</ScrollView>
{/* FAB Add */}
<TouchableOpacity
onPress={() => router.push('/quality/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={() => 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>
</View>
{/* Filter Modal */}
<FilterModal
visible={isFilterVisible}
showPlace={true}
showDate={true}
places={places}
currentRange={filterRange}
currentPlace={filterPlace}
onApply={(range, place) => {
setFilterRange(range);
setFilterPlace(place);
setIsFilterVisible(false);
fetchQualityControls(range, place);
}}
onReset={() => {
setFilterRange({ startDate: null, endDate: null });
setFilterPlace(null);
setIsFilterVisible(false);
fetchQualityControls({ startDate: null, endDate: null }, null);
}}
onClose={() => setIsFilterVisible(false)}
/>
</View>
);
}