Untitled

 avatar
unknown
plain_text
a year ago
9.2 kB
7
Indexable
Update the below code to add another field directly in jsondata as "Status":"CL". Also from the ecel, for program and category we will get values as AU,SNAP,TAC , so pick the value from excel and covert these to ["AU","SNAP","TC"] array like format to make the sevice call.
so, update the jsonData['Program'] = data[3][1];
        jsonData['Category'] = data[4][1]; before pushing them as jsonData




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;
            }

            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, defval: '' });

                const validationResult = validateData(jsonData);
                if (validationResult.isValid) {
                    convertToJSONAndUpload(jsonData);
                } else {
                    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.map((row) => row[0] && row[0].toLowerCase());
        const requiredHeaders = ['title', 'offering', 'needed by', 'state', 'requested by'];

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

        // Map the indexes of required headers
        const headerIndexes = {
            title: headers.indexOf('title'),
            description: headers.indexOf('description'),
            offering: headers.indexOf('offering'),
            program: headers.indexOf('program'),
            category: headers.indexOf('category'),
            neededBy: headers.indexOf('needed by'),
        };

        // Validate each mandatory field
        Object.keys(headerIndexes).forEach((key) => {
            const rowIndex = headerIndexes[key];
            const fieldValue = data[rowIndex][1]; // Value in the second column

            if (fieldValue === '' || fieldValue === undefined) {
                isValid = false;
                errors.push(`Error in row ${rowIndex + 1}: ${key} is a mandatory field`);
            }

            //Specific validation for 'needed by' field
            if (key === 'neededBy') {
                const dateValue = fieldValue;
                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 + 1
                        }: ${key} cannot be in the past or an invalid date`,
                    );
                }
            }
        });

        return { isValid, errors };
    };

    const convertToJSONAndUpload = (data) => {
        const jsonData = {};

        // Extract the main fields
        jsonData['Title'] = data[0][1];
        jsonData['Description'] = data[1][1];
        jsonData['Offering'] = data[2][1];
        jsonData['Program'] = data[3][1];
        jsonData['Category'] = data[4][1];
        jsonData['DueDT'] = moment('1900-01-01')
            .add(data[5][1] - 2, 'days')
            .format('DD/MM/YYYY');
        jsonData['Requested By'] = data[6][1];

        // Extract the questions and responses
        const questionStartRow = 8;
        const descriptionStartRow = 9;
        const questions = [];
        const states = data.slice(questionStartRow + 1).map((row) => row[0]);

        for (let col = 1; col < data[questionStartRow].length; col++) {
            let questionText = data[questionStartRow][col];
            const colonIndex = questionText.indexOf(':');
            if (colonIndex !== -1) {
                questionText = questionText.substring(colonIndex + 1).trim();
            }

            const question = {
                question: questionText,
                description: data[descriptionStartRow][col],
                answers: [],
            };

            for (let row = questionStartRow + 3; row < data.length; row++) {
                const state = states[row - questionStartRow - 1];
                const answer = data[row][col];
                if (answer) {
                    question.answers.push({
                        answer: answer,
                        state: state,
                    });
                }
            }

            questions.push(question);
        }

        jsonData['questions'] = questions;

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

    const callAPIToInsertData = async (data) => {
        try {
            Lift.spinner.show();

            const response = await webService.saveRFIFromExcel({
                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>
                </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