appendImportedData_Financial

PHOTO EMBED

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

Saved by @alfred.roshan

appendImportedData_Financial = async book => {
    try {
      const _selectedAnsweredEntry = this.state.selectedfinancialworkshop.answeredEntries;

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

      const selectedAnsweredEntry = this.state.selectedfinancialworkshop.answeredEntries;

      let _worksheet = this.state.selectedfinancialworkshop.worksheet
        .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 => {
        let verifiedTopic = '';
        if (item.value) {
          if (Array.isArray(item.value)) {
            verifiedTopic = item.value.map(item => item.label).join(', ');
          } else {
            verifiedTopic = item.value;
          }
        }

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

        const riskValue = answer['Risk']?.value || '';
        const oppValue = answer['Opportunities']?.value || '';

        let riskValueColor = '#fff';
        let oppValueColor = '#fff';

        if (riskValue === 'Yes') {
          riskValueColor = '#D1060A';
        } else if (riskValue === 'No') {
          riskValueColor = '#2EB917';
        }

        if (oppValue === 'Yes') {
          oppValueColor = '#2EB917';
        }

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

        let allComments = this.getAllCommentsFromShortSurvey_Financial(
          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 == 'Financial' : item))
            .forEach((commData, commIndex) => {
              let addedEntryTopicName = '';
              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 prevItem2 = Array.from(workshopWithEntry.worksheet || []).find(
                  data => data.id === commData.id,
                );

                if (prevItem2) {
                  addedEntryTopicName = prevItem2;
                }
              }

              const prevItem = Array.from(
                this.state.selectedfinancialworkshop.worksheet || [],
              ).find(data => data.id === commData.id);

              if (prevItem) {
                item = prevItem;
              }

              let verifiedTopic = '';
              if (item.value) {
                if (Array.isArray(item.value)) {
                  verifiedTopic = item.value.map(item => item.label).join(', ');
                } else {
                  verifiedTopic = item.value;
                }
              }

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

              const entryId = `${this.state.surveyId}__${this.state.selectedfinancialworkshop.id}__${item.id}`;
              let entry = {
                topic: item.topic,
                id: entryId,
                surveyId: this.state.surveyId,
                workshopId: this.state.selectedfinancialworkshop.id,
                oldid: item.id,
              };
              const answeredEntryData = this.state.selectedfinancialworkshop?.answeredEntries?.find(
                entry => entry.id === entryId,
              );

              if (answeredEntryData) {
                entry = {
                  ...entry,
                  ...answeredEntryData,
                };
              }

              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[`Type of Impact`] = item[`Type of Impact`] || '';
                  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;
                  }
                  if (item[`Significant Assets`]) {
                    itemFind[`Significant Assets`] =
                      item[`Significant Assets`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  itemFind[`Significant Locations`] = item[`Significant Locations`] || '';
                } 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[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Magnitude`] = item[`Magnitude`] || '';
                  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 - Opportunity Value`] = item[`Opportunity Value`] || '';
                  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[`Type of Impact`] = item[`Type of Impact`] || '';
                  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;
                  }
                  if (item[`Significant Assets`]) {
                    itemFind[`Significant Assets`] =
                      item[`Significant Assets`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  itemFind[`Significant Locations`] = item[`Significant Locations`] || '';
                } 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[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Magnitude`] = item[`Magnitude`] || '';
                  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 - Opportunity Value`] = item[`Opportunity Value`] || '';
                  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, selectedfinancialworkshop } = this.state;
      // const matrixWorkshopsRef = firebase
      //   .firestore()
      //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
      //   .doc(surveyId ? surveyId : currentSurveyId)
      //   .collection('financial-workshops')
      //   .doc(selectedfinancialworkshop.id);

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

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

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

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

      // matrixWorkshopsRef
      //   .update({
      //     answeredEntries: [
      //       ...selectedfinancialworkshop.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