appendImportedData_Impact

PHOTO EMBED

Thu Sep 19 2024 11:26:24 GMT+0000 (Coordinated Universal Time)

Saved by @alfred.roshan

 appendImportedData_Impact = async book => {
    console.log("appendImportedData_Impact function called")
    try {
      const _selectedAnsweredEntry = this.state.selectedworkshop.answeredEntries;

      if (!_selectedAnsweredEntry) {
        this.state.selectedworkshop.answeredEntries = [];
        this.setState({
          selectedworkshop: { ...this.state.selectedworkshop, answeredEntries: [] },
        });
      }

      const selectedAnsweredEntry = this.state.selectedworkshop.answeredEntries;

      let _worksheet = this.state.selectedworkshop.worksheet
        .filter((item, index, self) => index === self.findIndex(t => t.id === item.id))
        .sort((a, b) => {
          if (a.framework == 'CSRD') {
            let _a =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == a['mainId'] && item2['topic'] == a['topic'],
              )?.sortIndex || 0;
            let _b =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == b['mainId'] && item2['topic'] == b['topic'],
              )?.sortIndex || 0;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.framework == 'GRI') {
            let _a = a.id;
            let _b = b.id;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.topic < b.topic) return -1;
          if (a.topic > b.topic) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .filter((item, index) => {
          return item.entryType !== 'comment' && item.entryType !== 'added-entry';
        });

      let allAnsweredEntries = [];
      _worksheet.forEach(item => {
        const answerData = this.state.answeredTopics.find(data => data.id === item.id);
        let answer = '';
        if (answerData) {
          answer = answerData;
        }

        const topicResult = this.state.surveyResultsIROComments.filter(
          item2 => item2.id == item.id,
        );

        let allComments = this.getAllCommentsFromShortSurvey_Impact(
          topicResult,
          Array.from(this.state.financialConsolidatedReports || []),
          Array.from(this.state.addedCommentTopics || []),
        );

        if (allComments.length > 0) {
          allComments
            .filter((v, i, a) => a.findIndex(t => t.id === v.id) === i)
            .filter(item => (item.assessmentType ? item.assessmentType == 'Impact' : item))
            .forEach((commData, commIndex) => {
              let item = commData;

              const workshopWithEntry = Array.from(this.state.workshops || [])
                .concat(Array.from(this.state.financialworkshops || []))
                .find(ws => {
                  return Array.from(ws.worksheet || []).find(data => data.id === commData.id);
                });

              if (workshopWithEntry) {
                const prevItem = Array.from(workshopWithEntry.worksheet || []).find(
                  data => data.id === commData.id,
                );

                if (prevItem) {
                  item = prevItem;
                }
              }

              const answerData = this.state.answeredTopics.find(data => data.id === item.id);
              let answer = '';
              if (answerData) {
                answer = answerData;
              }

              const entryId = `${this.state.surveyId}__${this.state.selectedworkshop.id}__${item.id}`;
              let entry = {
                topic: item.topic,
                id: entryId,
                surveyId: this.state.surveyId,
                workshopId: this.state.selectedworkshop.id,
                oldid: item.id,
              };

              if (
                item?.entryType == 'comment' &&
                (!answer?.['Verification'] ||
                  answer?.['Verification']?.value == 'No' ||
                  answer?.['Verification']?.value == '')
              ) {
                return null;
              }

              allAnsweredEntries.push(entry);
            });
        }
      });

      if (book && book.SheetNames) {
        book.SheetNames.forEach((parentitem, parentindex) => {
          const data = xlsx2.utils.sheet_to_json(book.Sheets[parentitem]);

          data.forEach(item => {
            const itemFind = selectedAnsweredEntry?.find(item2 => item2.topic == item['Topic']);

            if (item?.['Comment or Added Entry'] == 'Yes') {
              if (itemFind) {
                if (parentindex == 0) {
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`People or Environmental`] = item[`People or Environmental`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Remediability`] = item[`Remediability`] || '';
                  itemFind[`Scale`] = item[`Scale`] || '';
                  itemFind[`Scope`] = item[`Scope`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }
              } else {
                let itemFind = {};
                let answeredEntryFind = allAnsweredEntries.find(
                  item2 => item2['topic'] == item['Topic'],
                );
                if (answeredEntryFind) {
                  itemFind = {
                    ...itemFind,
                    ...answeredEntryFind,
                  };
                }

                if (parentindex == 0) {
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`People or Environmental`] = item[`People or Environmental`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Remediability`] = item[`Remediability`] || '';
                  itemFind[`Scale`] = item[`Scale`] || '';
                  itemFind[`Scope`] = item[`Scope`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }

                selectedAnsweredEntry.push(itemFind);
              }
            }
          });
        });
      }

      const { surveyId, currentSurveyId, consultantId, selectedworkshop } = this.state;
      // const matrixWorkshopsRef = firebase
      //   .firestore()
      //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
      //   .doc(surveyId ? surveyId : currentSurveyId)
      //   .collection('workshops')
      //   .doc(selectedworkshop.id);

      const updatedWorkshop = {
        ...selectedworkshop,
        answeredEntries: [...selectedworkshop.answeredEntries, ...selectedAnsweredEntry].filter(
          (item, index, self) => index === self.findIndex(t => t.id === item.id),
        ),
      };

      console.log('updatedWorkshop', updatedWorkshop);

      this.setState({
        selectedworkshop: updatedWorkshop,
        loading: false,
      });

      const payload = [...selectedworkshop.answeredEntries, ...selectedAnsweredEntry].filter(
        (item, index, self) => index === self.findIndex(t => t.id === item.id),
      )


      updateWorkshopProperty({
        surveyId,
        consultantId,
        workshopId: selectedworkshop.id,
        type: "impact",
        property: "answeredEntries"
      }, payload).then((res) => {
        console.log("submitted to api", res)
      }).catch(error => {
        console.log('error saving answered entries');
      });

      // matrixWorkshopsRef
      //   .update({
      //     answeredEntries: [...selectedworkshop.answeredEntries, ...selectedAnsweredEntry].filter(
      //       (item, index, self) => index === self.findIndex(t => t.id === item.id),
      //     ),
      //   })
      //   .then(() => {
      //     console.log(`saved answered entries`);
      //   })
      //   .catch(error => {
      //     console.log('error saving answered entries');
      //   });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
    } catch (ex) {
      console.log(ex.message);
      this.setState({ loading: false });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
      return;
    }
  };
content_copyCOPY