Untitled

 avatar
unknown
plain_text
2 years ago
12 kB
5
Indexable
import React, { useState, useEffect  } from 'react';
import { View, TextInput, Button, Text, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import DateTimePicker from '@react-native-community/datetimepicker';
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
    width: '100%',
  },
  label: {
    marginRight: 10,
    fontWeight: 'bold',
    width: 120,
  },
  input: {
    flex: 1,
    borderWidth: 1,
    padding: 10,
  },
  button: {
    width: '100%',
    marginTop: 10,
  },
  logoutButton: {
    position: 'absolute',
    top: 10,
    right: 10,
  },
  welcomeText: {
    marginBottom: 10,
    fontSize: 18,
    fontWeight: 'bold',
  },
  tableContainer: {
    marginTop: 20,
    width: 390,
    borderWidth: 1,
    borderColor: 'black',
    borderCollapse: 'collapse', // Add this line to collapse borders
  },
  tableHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderBottomWidth: 1,
    borderBottomColor: 'black', // Update the property name to borderBottomColor
    borderRightWidth: 1, // Add a right border to the last cell in the header row
    borderRightColor: 'black', // Set the color of the right border
    backgroundColor: 'lightgray',
  },
  tableHeaderText: {
    fontWeight: 'bold',
    width: 78, // Adjust the width to distribute evenly
    borderRightWidth: 1, // Add a right border to each cell in the header row
    borderRightColor: 'black', // Set the color of the right border
   
  },
  tableRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderBottomWidth: 1,
    borderBottomColor: 'black', // Update the property name to borderBottomColor
    borderRightWidth: 1, // Add a right border to the last cell in each row
    borderRightColor: 'black', // Set the color of the right border
  
  },
  tableCell: {
    width: 78, // Adjust the width to distribute evenly
    textAlign: 'center',
    borderRightWidth: 1, // Add a right border to each cell
    borderRightColor: 'black', // Set the color of the right border
    
  },

});

const LeavesToBeApprovedTable = ({ leavesToBeApproved, onApproveLeave, onDeleteLeave }) => {
    return (
      <View style={styles.tableContainer}>
        <View style={styles.tableHeader}>
        <Text style={styles.tableHeaderText}>id</Text>
        <Text style={styles.tableHeaderText}>username</Text>
          <Text style={styles.tableHeaderText}>StartDate</Text>
          <Text style={styles.tableHeaderText}>EndDate</Text>
       
       
         
          <Text style={styles.tableHeaderText}>Action</Text>
        </View>
        {leavesToBeApproved.map((leave, index) => (
          <View style={styles.tableRow} key={index}>
            <Text style={styles.tableCell}>{leave.id}</Text>
            <Text style={styles.tableCell}>{leave.username}</Text>
            <Text style={styles.tableCell}>{leave.startDate}</Text>
            <Text style={styles.tableCell}>{leave.endDate}</Text>
            <Button
              title="Approve"
              onPress={() => onApproveLeave(leave.username, leave.id)} // Pass username and id as arguments
              style={styles.approveButton}
              disabled={leave.leaveStatus !== 'Pending'}
            />
          </View>
        ))}
      </View>
    );
  };
const AppliedLeavesTable = ({ appliedLeaves }) => {
  return (
    <View style={styles.tableContainer}>
      <View style={styles.tableHeader}>
        <Text style={styles.tableHeaderText}>StartDate</Text>
        <Text style={styles.tableHeaderText}>EndDate</Text>
        <Text style={styles.tableHeaderText}>Number of Leaves</Text>
        <Text style={styles.tableHeaderText}>Reason</Text>
        <Text style={styles.tableHeaderText}>Leave Status</Text>
      </View>
      {appliedLeaves.map((leave, index) => (
        <View style={styles.tableRow} key={index}>
          <Text style={styles.tableCell}>{leave.startDate}</Text>
          <Text style={styles.tableCell}>{leave.endDate}</Text>
          <Text style={styles.tableCell}>{leave.numberOfLeaves}</Text>
          <Text style={styles.tableCell}>{leave.reason}</Text>
          <Text style={styles.tableCell}>{leave.leaveStatus}</Text>
        </View>
      ))}
    </View>
  );
};

const LoginPage = ({ onLogout, username, onEnterLeaveReason }) => {

  const [reason, setReason] = useState('');
  const [appliedLeaves, setAppliedLeaves] = useState([]);
  const [leavesToBeApproved, setLeavesToBeApproved] = useState([]);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [showStartDatePicker, setShowStartDatePicker] = useState(false);
  const [showEndDatePicker, setShowEndDatePicker] = useState(false);

  const handleStartDateChange = (event, selectedDate) => {
    setShowStartDatePicker(false);
    if (selectedDate) {
      const formattedDate = selectedDate.toISOString().split('T')[0];
      setStartDate(formattedDate);
    }
  };

  const handleEndDateChange = (event, selectedDate) => {
    setShowEndDatePicker(false);
    if (selectedDate) {
      const formattedDate = selectedDate.toISOString().split('T')[0];
      setEndDate(formattedDate);
    }
  };

  const showStartDatePickerModal = () => {
    setShowStartDatePicker(true);
  };

  const showEndDatePickerModal = () => {
    setShowEndDatePicker(true);
  };

  useEffect(() => {
    // clearAsyncStorage();

    loadAppliedLeaves();

    loadLeavesToBeApproved();
  });
  const clearAsyncStorage = async () => {
    try {
      await AsyncStorage.clear();
      console.log('AsyncStorage cleared successfully.');
    } catch (error) {
      console.error('Error while clearing AsyncStorage:', error);
    }
  };
const approveLeave = async (username, id) => {
  const updatedLeaves = leavesToBeApproved.map(leave => {
    if (leave.username === username && leave.id === id) {
      return {
        ...leave,
        leaveStatus: 'Approved',
      };
    }
    return leave;
  });

  setLeavesToBeApproved(updatedLeaves);

  try {
    const leavesData = await AsyncStorage.getItem('leaves');
    if (leavesData) {
      const leaves = JSON.parse(leavesData);
      leaves[username] = updatedLeaves; // Update the leaves data for the particular user
      await AsyncStorage.setItem('leaves', JSON.stringify(leaves));
    }
  } catch (error) {
    console.error('Error occurred while saving leaves data:', error);
  }
};


  const loadAppliedLeaves = async () => {
    try {
      const leavesData = await AsyncStorage.getItem('leaves');
      if (leavesData) {
        const leaves = JSON.parse(leavesData);
       console.log(username)
        const userLeaves = leaves[username] || []; // Retrieve leaves for the particular user
        console.log(userLeaves)
        setAppliedLeaves(userLeaves);
      }
    } catch (error) {
      console.error('Error occurred while loading applied leaves:', error);
    }
  };
  
  const loadLeavesToBeApproved = async () => {
    try {
      const leavesData = await AsyncStorage.getItem('leaves');
  
      if (leavesData) {
        const leaves = JSON.parse(leavesData);
        const allLeavesToBeApproved = Object.entries(leaves).flatMap(([username, leavesArray]) =>
          leavesArray.map(leave => ({ username, ...leave }))
        );
        console.log(allLeavesToBeApproved)
        setLeavesToBeApproved(allLeavesToBeApproved);
      }
    } catch (error) {
      console.error('Error occurred while loading leaves to be approved:', error);
    }
  };
  
  
  const saveAppliedLeaves = async (leavesData) => {
    try {
      const existingLeavesData = await AsyncStorage.getItem('leaves');
      const existingLeaves = existingLeavesData ? JSON.parse(existingLeavesData) : {};
      const updatedLeaves = {
        ...existingLeaves,
        [username]: leavesData // Store leaves data for the particular user
      };
      await AsyncStorage.setItem('leaves', JSON.stringify(updatedLeaves));
    } catch (error) {
      console.error('Error occurred while saving applied leaves:', error);
    }
  };
  
  const applyLeave = () => {
    const leave = {
      id: generateRandomId(),
      startDate,
      endDate,
      reason,
      numberOfLeaves: calculateNumberOfDays(),
      leaveStatus : 'Pending'
    };
 // Function to generate a random 2-digit ID

    const updatedLeaves = [...appliedLeaves, leave];
    setAppliedLeaves(updatedLeaves);
    saveAppliedLeaves(updatedLeaves);

    // Reset the input fields
    setStartDate('');
    setEndDate('');
    setReason('');
  };
  const generateRandomId = () => {
    const min = 10; // Minimum value for 2-digit number
    const max = 99; // Maximum value for 2-digit number
    return Math.floor(Math.random() * (max - min + 1)) + min;
  };
  const calculateNumberOfDays = () => {
    const start = new Date(startDate);
    const end = new Date(endDate);
    const days = Math.floor((end - start) / (1000 * 60 * 60 * 24)) + 1;
    return days >= 0 ? days : 0;
  };

  const isStartDateValid = () => {
    return startDate !== '' && new Date(startDate) <= new Date(endDate);
  };

  const isEndDateValid = () => {
    return endDate !== '' && new Date(startDate) <= new Date(endDate);
  };

  
  const deleteLeave = index => {
    const updatedLeaves = [...leavesToBeApproved];
    updatedLeaves.splice(index, 1);
    setLeavesToBeApproved(updatedLeaves);
  };


  return (
    <View style={styles.container}>
      <View style={styles.logoutButton}>
        <Button title="Logout" onPress={onLogout} color="red" />
      </View>
      <Text style={styles.welcomeText}>Welcome, {username}!</Text>
         <View style={styles.inputContainer}>
        <Text style={styles.label}>Start of Leave:</Text>
        <TextInput
          placeholder="YYYY-MM-DD"
          value={startDate}
          onFocus={showStartDatePickerModal}
          style={styles.input}
        />
        {showStartDatePicker && (
          <DateTimePicker
            value={startDate ? new Date(startDate) : new Date()}
            mode="date"
            display="default"
            onChange={handleStartDateChange}
          />
        )}
      </View>
      <View style={styles.inputContainer}>
        <Text style={styles.label}>End of Leave:</Text>
        <TextInput
          placeholder="YYYY-MM-DD"
          value={endDate}
          onFocus={showEndDatePickerModal}
          style={styles.input}
        />
        {showEndDatePicker && (
          <DateTimePicker
            value={endDate ? new Date(endDate) : new Date()}
            mode="date"
            display="default"
            onChange={handleEndDateChange}
          />
        )}
      </View>
      <View style={styles.inputContainer}>
        <Text style={styles.label}>Reason for Leave:</Text>
        <TextInput
          placeholder="Enter reason"
          value={reason}
          onChangeText={setReason}
          style={styles.input}
        />
      </View>
      <View style={styles.inputContainer}>
        <Text style={styles.label}>Number of Leaves:</Text>
        <TextInput
          value={calculateNumberOfDays().toString()}
          editable={false}
          style={[styles.input, { backgroundColor: '#ddd' }]}
        />
      </View>
      <Button
        title="Submit"
        onPress={applyLeave}
        style={styles.button}
        color="blue"
        disabled={!isStartDateValid() || !isEndDateValid()}
      />
      <AppliedLeavesTable appliedLeaves={appliedLeaves} />
      {username === 'sridhar' && (
        <LeavesToBeApprovedTable
          leavesToBeApproved={leavesToBeApproved}
          onApproveLeave={approveLeave}
          onDeleteLeave={deleteLeave}
        />
      )}
    </View>
  );
};

export default LoginPage;
Editor is loading...