All files / src/form/cells ImportRecord.tsx

100% Statements 22/22
75% Branches 27/36
100% Functions 8/8
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202                                                                      66x                 66x                     66x 16x                         66x             2x 2x   12x 2x 2x   2x   2x 2x 2x   2x       2x           8x         11x                                         2x         2x   2x                                                                                                                                          
import React, { ReactElement, useEffect, useState } from 'react';
import { Alert, Badge, Card, Col, Row, Space, Statistic } from 'antd';
import {
  MinusSquareOutlined, PlusSquareOutlined, CheckSquareOutlined, AppstoreOutlined,
  WarningOutlined, ExclamationCircleOutlined
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { CsvOperateComponentPanelMaxWidth, CustomIcon } from '@config/base';
import { fetchFormIdAndExtInfoByType } from '@utils/FetchUtils';
import { random } from 'lodash';
import { ExpandableContentComponent } from '../../components';
import ObjectPopup from './ObjectPopup';
 
export type ImportRecordProps = {
  insertedIds: string;
  updatedIds: string;
  deletedIds: string;
  noUpdateIds: string;
  conflictIds: string;
  dbUpdatedCsvNoUpdateIds: string;
  failedLines: string;
  skippedLines: string;
  conflictLines: string;
  logs: string;
  status: "SUCCESS" | "PARTIALLY_FAIL" | "FAILED" | "RUNNING" | "NO_DATA_IMPORTED" | "NOT_START";
  insertedRecord: number;
  failedRecord: number;
  noUpdateRecord: number;
  skippedRecord: number;
  updatedRecord: number;
  deletedRecord: number;
  conflictRecord: number;
  dbUpdatedCsvNoUpdateRecord: number;
};
 
const statusMapping = [
  { value: "SUCCESS", label: "has succeed" },
  { value: "PARTIALLY_FAIL", label: "has partially failed" },
  { value: "FAILED", label: "has failed" },
  { value: "RUNNING", label: "is still running" },
  { value: "NO_DATA_IMPORTED", label: " imported nothing" },
  { value: "NOT_START", label: "was not started" },
];
 
const statusToAlertTypeMapping = {
  SUCCESS: "success",
  PARTIALLY_FAIL: "warning",
  FAILED: "error",
  RUNNING: "info",
  NO_DATA_IMPORTED: "warning",
  NOT_START: "error"
} as { [id: string]: string };
 
export type AlertStatus = "success" | "warning" | "error" | "info" | "default" | undefined;
 
const colElem = (title: string, value: number, status: AlertStatus, col?: number): ReactElement => (
  <Col span={col ?? 6}>
    <Card className="import-record-card">
      <Statistic
        title={title}
        value={value}
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        prefix={<Badge status={status} />}
      />
    </Card>
  </Col>
);
 
const ImportRecordComponent = (props: {
  domainName: string;
  importRecord: ImportRecordProps;
  uploaded: boolean;
  defaultMaxWidth?: string;
  zIndex: number;
}): ReactElement => {
  const { importRecord, uploaded, domainName, defaultMaxWidth, zIndex } = props;
  const { t } = useTranslation();
 
  const statusObj = statusMapping.filter(s => s.value === importRecord?.status);
  const displayMsg = (statusObj.length > 0) ? statusObj[0].label : "";
  const type = ((statusObj.length > 0) ?
    statusToAlertTypeMapping[statusObj[0].value] : "warning") as AlertStatus;
  const [formId, setFormId] = useState<number>(-1);
 
  useEffect(() => {
    fetchFormIdAndExtInfoByType(domainName, "Update").then((json) => {
      setFormId(json.id);
    }).catch(e => {
      console.error(`Failed to get Update form of domain ${domainName}: ${e}`);
    });
  }, [domainName, formId]);
 
  const expandableElem = (
    title: string, content: string,
    showDownload: boolean,
    showAsTag: boolean,
    icon?: ReactElement
  ): ReactElement | undefined => {
    return (content != null && content.length > 0) ?
      (<ExpandableContentComponent
        content={showAsTag ? (
          <div>
            {content.split(',').map(id => (
              <ObjectPopup
                domainName={domainName}
                id={id}
                formId={formId}
                key={id}
                zIndex={zIndex + 1}
              />
            ))}
          </div>
        ) : content}
        // Use random to generate a random number,
        // This is to auto open the import log section if it has content
        // everytime when a new upload finishes
        initDisplay={uploaded ? random(0, 1) : -1}
        title={title}
        icon={icon}
        breakLine={!showDownload}
        showDownload={showDownload}
      />) : undefined;
  };
 
  const maxWidth = defaultMaxWidth ?? CsvOperateComponentPanelMaxWidth;
 
  const {
    deletedIds, updatedIds, failedLines, insertedIds, conflictIds, logs,
    dbUpdatedCsvNoUpdateIds
  } = importRecord;
 
  return (
    <div style={{
      margin: "auto",
      width: "100%",
      maxWidth
    }}>
      <Space size="small"
        direction="vertical"
        className="expandable-content-space"
      >
        <ExpandableContentComponent
          customStyle={{ marginTop: "8px" }}
          fixHeight={242}
          // Use random to generate a random number,
          // This is to auto open the import summary
          //everytime when a new upload finishes
          initDisplay={uploaded ? random(0, 1) : -1}
          icon={<AppstoreOutlined />}
          content={
            <div style={{ marginTop: "10px" }}>
              <Alert
                message={
                  t('ImportSummary', {
                    domainTitle: t(`status:${type}` ?? ""),
                    displayMsg: t(`status:${displayMsg}`)
                  })}
                showIcon={true}
                type={(type === 'default') ? 'info' : type}
                closable={false}
                className="expandable-content-alert"
              />
              <Row gutter={16}>
                {colElem(t("Inserted"), importRecord?.insertedRecord, "success")}
                {colElem(t("Updated"), importRecord?.updatedRecord, "success")}
                {colElem(t("Deleted"), importRecord?.deletedRecord, "warning")}
                {colElem(t("No changes"), importRecord?.noUpdateRecord, "default")}
              </Row>
              <Row gutter={16}>
                {colElem(t("Conflicted"), importRecord?.conflictRecord, "error")}
                {colElem(t("Failed"), importRecord?.failedRecord, "error")}
                {colElem(t("Db updated csv no update"), importRecord?.dbUpdatedCsvNoUpdateRecord, "default")}
                {colElem(t("Skipped"), importRecord?.skippedRecord, "error")}
              </Row>
            </div>
          }
          title={t("Import summary")}
          breakLine={true}
          showDownload={false}
        />
        {conflictIds && expandableElem(t("Conflicted records"),
          conflictIds, false, true, <ExclamationCircleOutlined />)}
        {deletedIds && expandableElem(t("Deleted records"),
          deletedIds, false, true, <MinusSquareOutlined />)}
        {updatedIds && expandableElem(t("Updated records"),
          updatedIds, false, true, <CheckSquareOutlined />)}
        {insertedIds && expandableElem(t("Inserted records"),
          insertedIds, false, true, <PlusSquareOutlined />)}
        {dbUpdatedCsvNoUpdateIds && expandableElem(t("Db updated csv no update records"),
          dbUpdatedCsvNoUpdateIds, false, true, <CheckSquareOutlined />)}
        {failedLines && expandableElem(t("Import failed lines"),
          failedLines, true, false, <WarningOutlined />)}
        {logs && expandableElem(t("Import error logs"),
            logs, true, false, <CustomIcon type="icon-icon_log" />)}
        </Space>
    </div >
  );
};
 
export default ImportRecordComponent;