Untitled

 avatar
unknown
plain_text
a year ago
8.6 kB
11
Indexable
Title(R1 C1)
Description(R2 C1)
Offering(R3 C1)
Program(R4 C1)
Category(R5 C1)
Needed By(R6 C1)

State(R7 C1)
(R7 C) consists of all the headers like state, question 1, question 2 ...

Update the below code to implement the Check mandatory headers for title,offering,needed by and state fields. 
update Check for mandatory fields for title(R1 C2),offering(R3 C2),needed by(R6 C2)






import React, { useRef, useState } from 'react';
import { Lift } from '@d-lift/core';

import {
    SimpleFileUpload,
    Label,
    Button,
    Group,
    Section,
    ListItem,
    List,
} from '@d-lift/uxcomponents';
import * as XLSX from 'xlsx';
import moment from 'moment';
import ConstantKeys from '@/Constants/ConstantKeys';
import webService from '@/Services/WebService';

const ExcelUpload = () => {
    const [status, setStatus] = useState('initial');
    const [uploadedFiles, setUploadedFiles] = useState([]);
    const fileInputRef = useRef(null);
    const [selectedFile, setSelectedFile] = useState(null);

    const handleFileChange = (e) => {
        if (Array.isArray(e) && e.length > 0) {
            const newFile = e[0];
            setSelectedFile(newFile);
            handleUpload(newFile);
        } else {
            console.log('No file selected');
        }
    };

    const handleUpload = async (file) => {
        try {
            if (!file) {
                console.error('No file selected');
                setStatus('fail');
                return;
            }

            console.log('Processing file:', file);
            const reader = new FileReader();
            reader.onload = (event) => {
                const data = new Uint8Array(event.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

                const validationResult = validateData(jsonData);
                if (validationResult.isValid) {
                    convertToJSONAndUpload(jsonData);
                } else {
                    console.log('validationResult:', validationResult);
                    console.log('errors:', validationResult.errors);

                    Lift.Application.Notification.error(`${validationResult.errors}`);
                    setStatus('fail');
                }
            };
            reader.readAsArrayBuffer(file);

            setUploadedFiles((prevFiles) => [
                ...prevFiles,
                {
                    id: Math.random() * 100 + 1,
                    name: file.name,
                },
            ]);

            setStatus('success');
        } catch (error) {
            console.error(error);
            setStatus('fail');
        }
    };

    const validateData = (data) => {
        let isValid = true;
        let errors = [];

        const headers = data[0].map((header) => header.toLowerCase());
        const requiredFields = ['rfi title', 'question 1', 'state', 'needed by', 'offering'];

        // Check mandatory headers
        requiredFields.forEach((field) => {
            if (!headers.includes(field)) {
                isValid = false;
                errors.push(`Missing mandatory field: ${field}`);
            }
        });

        // Validate each row
        data.slice(1).forEach((row, rowIndex) => {
            // Check mandatory fields
            requiredFields.forEach((field) => {
                const fieldIndex = headers.indexOf(field);
                if (row[fieldIndex] === '' || row[fieldIndex] === undefined) {
                    isValid = false;
                    errors.push(`Error in row ${rowIndex + 2}: ${field} is a mandatory field`);
                }
                if (field === 'needed by') {
                    const dateValue = row[fieldIndex];
                    let date;

                    // Check if the date is in Excel date format (numeric)
                    if (typeof dateValue === 'number') {
                        date = moment('1900-01-01').add(dateValue - 2, 'days'); // Excel date system
                    } else {
                        date = moment(dateValue, 'MM/DD/YYYY', true);
                    }

                    if (!date.isValid() || date.isBefore(moment(), 'day')) {
                        isValid = false;
                        errors.push(
                            `Error in row ${
                                rowIndex + 2
                            }: ${field} cannot be in the past or an invalid date`,
                        );
                    }
                }
            });
        });

        return { isValid, errors };
    };

    const convertToJSONAndUpload = (data) => {
        const jsonData = data.slice(1).map((row, index) => {
            const rowData = {};
            data[0].forEach((header, i) => {
                rowData[header] = row[i];
            });
            return rowData;
        });

        console.log('jsonData:', jsonData);
        //callAPIToInsertData(jsonData);
    };

    const callAPIToInsertData = async (data) => {
        try {
            Lift.spinner.show();
            //------- will need to convert "needed by" field value before service call.---------

            // const requestFromExcel = {
            //     ...data,data.needed by = moment('1900-01-01').add(dateValue - 2, 'days');
            // };

            const response = await webService.createRFIRequest({
                requestBody: data,
            });

            if (response.message.code === ConstantKeys.RESPONSE_CODES.success) {
                Lift.Application.Notification.success(
                    ConstantKeys.NOTIFICATION.MSG.SUCCESS.EXCEL_UPLOAD_SUCCESS,
                );
            }
        } catch (error) {
            Lift.Application.Notification.error(
                ConstantKeys.NOTIFICATION.MSG.ERR.EXCEL_UPLOAD_FAILURE,
            );
        } finally {
            Lift.spinner.hide();
        }
    };

    return (
        <>
            <div className="ux-rfi-attachment-container ux-rfi-green-border">
                <Group width="6,6">
                    <Label
                        className="mb-0"
                        model="AddAttachments.fileList"
                        labelKey="attachments"></Label>
                    <a
                        href="/images/sample-format.xlsx"
                        download="sample-format.xlsx"
                        style={{ textDecoration: 'none' }}>
                        <Button
                            size="small"
                            className="ux-rfi-green-button float-right"
                            labelKey="download_sample"
                            postIconClass="fa fa-download"></Button>
                    </a>
                </Group>

                <Section className="pt-4">
                    <List>
                        {uploadedFiles.length > 0 ? (
                            uploadedFiles.map((file) => (
                                <ListItem key={file.id} iconKey={null}>
                                    {file.name}
                                </ListItem>
                            ))
                        ) : (
                            <ListItem iconKey={null} labelKey="empty_err"></ListItem>
                        )}
                    </List>
                    <SimpleFileUpload
                        model="AddAttachments.uploadedFiles"
                        allowDragAndDrop={false}
                        inputDisplayType="custom"
                        ref={fileInputRef}
                        style={{ display: 'none' }}
                        onDropAccepted={handleFileChange}
                        accept=".xls,.xlsx">
                        <Button
                            size="small"
                            click={() => fileInputRef.current && fileInputRef.current.click()}
                            className="ux-rfi-green-button"
                            preIconClass="fa fa-plus"
                            labelKey="add_attachment"></Button>
                    </SimpleFileUpload>
                </Section>
            </div>
        </>
    );
};

export default ExcelUpload;
Editor is loading...
Leave a Comment