lodash#sum JavaScript Examples

The following examples show how to use lodash#sum. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DataList.js    From hzero-front with Apache License 2.0 4 votes vote down vote up
/**
   * render
   * @returns React.element
   */
  render() {
    const {
      loading,
      dataSource,
      pagination,
      organizationId,
      onSearch,
      onEditRow,
      onDelete,
      onCancel,
      match,
    } = this.props;
    const columns = [
      {
        title: intl.get(`${modelPrompt}.locationCode`).d('库位编码'),
        width: 120,
        dataIndex: 'locationCode',
        render: (text, record) => {
          if (['update', 'create'].includes(record._status)) {
            const { getFieldDecorator } = record.$form;
            return (
              <Form.Item>
                {getFieldDecorator('locationCode', {
                  rules: [
                    {
                      required: true,
                      message: intl.get('hzero.common.validation.notNull', {
                        name: intl.get(`${modelPrompt}.locationCode`).d('库位编码'),
                      }),
                    },
                    {
                      max: 30,
                      message: intl.get('hzero.common.validation.max', {
                        max: 30,
                      }),
                    },
                    {
                      pattern: CODE_UPPER,
                      message: intl
                        .get('hzero.common.validation.codeUpper')
                        .d('全大写及数字,必须以字母、数字开头,可包含“-”、“_”、“.”、“/”'),
                    },
                  ],
                  initialValue: record.locationCode,
                })(
                  <Input
                    typeCase="upper"
                    inputChinese={false}
                    disabled={!!record.isErp || record._status === 'update'}
                  />
                )}
              </Form.Item>
            );
          }
          return text;
        },
      },
      {
        title: intl.get(`${modelPrompt}.locationName`).d('库位名称'),
        width: 140,
        dataIndex: 'locationName',
        render: (text, record) => {
          if (['update', 'create'].includes(record._status)) {
            const { getFieldDecorator } = record.$form;
            return (
              <Form.Item>
                {getFieldDecorator('locationName', {
                  rules: [
                    {
                      required: true,
                      message: intl.get('hzero.common.validation.notNull', {
                        name: intl.get(`${modelPrompt}.locationName`).d('库位名称'),
                      }),
                    },
                    {
                      max: 60,
                      message: intl.get('hzero.common.validation.max', {
                        max: 60,
                      }),
                    },
                  ],
                  initialValue: record.locationName,
                })(<Input disabled={!!record.isErp} />)}
              </Form.Item>
            );
          }
          return text;
        },
      },
      {
        title: intl.get(`${modelPrompt}.inventoryName`).d('库房'),
        dataIndex: 'inventoryName',
        width: 140,
        render: (text, record) => {
          if (['update', 'create'].includes(record._status)) {
            const { getFieldDecorator, setFieldsValue } = record.$form;
            getFieldDecorator('inventoryId', {
              initialValue: record.inventoryId,
            });
            getFieldDecorator('invOrganizationName', {
              initialValue: record.invOrganizationName,
            });
            getFieldDecorator('ouName', { initialValue: record.ouName });
            getFieldDecorator('ouId', { initialValue: record.ouId });
            getFieldDecorator('organizationId', {
              initialValue: record.organizationId,
            });
            return (
              <Form.Item>
                {getFieldDecorator('inventoryName', {
                  rules: [
                    {
                      required: true,
                      message: intl.get('hzero.common.validation.notNull', {
                        name: intl.get(`${modelPrompt}.inventoryName`).d('库房'),
                      }),
                    },
                  ],
                  initialValue: record.inventoryName,
                })(
                  <Lov
                    code="HPFM.LOCATION.INVENTORY"
                    queryParams={{ tenantId: organizationId, enabledFlag: 1 }}
                    textValue={record.inventoryName || ''}
                    disabled={!!record.isErp}
                    onChange={(value, lovRecord) => {
                      const setFormData = {
                        invOrganizationName: lovRecord.invOrganizationName,
                        inventoryId: lovRecord.inventoryId,
                        ouName: lovRecord.ouName,
                        ouId: lovRecord.ouId,
                        organizationId: lovRecord.organizationId,
                      };
                      setFieldsValue(setFormData);
                    }}
                  />
                )}
              </Form.Item>
            );
          }
          return text;
        },
      },
      {
        title: intl.get(`${modelPrompt}.invOrganizationName`).d('库存组织'),
        dataIndex: 'invOrganizationName',
        width: 120,
        render: (text, record) => {
          if (['update', 'create'].includes(record._status)) {
            const { getFieldDecorator } = record.$form;
            return (
              <Form.Item>
                {getFieldDecorator('invOrganizationName', {
                  initialValue: record.invOrganizationName,
                })(<Input disabled />)}
              </Form.Item>
            );
          }
          return text;
        },
      },
      {
        title: intl.get(`${modelPrompt}.ouName`).d('业务实体'),
        dataIndex: 'ouName',
        width: 80,
        render: (text, record) => {
          if (['update', 'create'].includes(record._status)) {
            const { getFieldDecorator } = record.$form;
            return (
              <Form.Item>
                {getFieldDecorator('ouName', {
                  initialValue: record.ouName,
                })(<Input disabled />)}
              </Form.Item>
            );
          }
          return text;
        },
      },
      {
        title: intl.get(`${modelPrompt}.sourceCode`).d('数据来源'),
        width: 75,
        align: 'center',
        dataIndex: 'sourceCode',
      },
      {
        title: intl.get(`${modelPrompt}.externalSystemCode`).d('来源系统'),
        width: 75,
        align: 'center',
        dataIndex: 'externalSystemCode',
      },
      {
        title: intl.get('hzero.common.status').d('状态'),
        width: 75,
        align: 'center',
        dataIndex: 'enabledFlag',
        render: (text, record) => {
          if (['update', 'create'].includes(record._status)) {
            const { getFieldDecorator } = record.$form;
            return (
              <Form.Item>
                {getFieldDecorator('enabledFlag', {
                  initialValue: record.enabledFlag ? 1 : 0,
                })(<Checkbox />)}
              </Form.Item>
            );
          }
          return enableRender(text);
        },
      },
      {
        title: intl.get('hzero.common.button.action').d('操作'),
        align: 'center',
        dataIndex: 'edit',
        width: 75,
        render: (text, record) => {
          const operators = [];
          if (record._status === 'create') {
            operators.push({
              key: 'delete',
              ele: (
                <a onClick={() => onDelete(record)}>
                  {intl.get('hzero.common.button.clean').d('清除')}
                </a>
              ),
              len: 2,
              title: intl.get('hzero.common.button.clean').d('清除'),
            });
          } else if (record._status === 'update') {
            operators.push({
              key: 'cancel',
              ele: (
                <a onClick={() => onCancel(record)}>
                  {intl.get('hzero.common.button.cancel').d('取消')}
                </a>
              ),
              len: 2,
              title: intl.get('hzero.common.button.cancel').d('取消'),
            });
          } else {
            operators.push({
              key: 'edit',
              ele: (
                <ButtonPermission
                  type="text"
                  permissionList={[
                    {
                      code: `${match.path}.button.edit`,
                      type: 'button',
                      meaning: '库位-编辑',
                    },
                  ]}
                  onClick={() => onEditRow(record)}
                >
                  {intl.get('hzero.common.button.edit').d('编辑')}
                </ButtonPermission>
              ),
              len: 2,
              title: intl.get('hzero.common.button.edit').d('编辑'),
            });
          }
          return operatorRender(operators);
        },
      },
    ];
    const scrollX = sum(columns.map(n => (isNumber(n.width) ? n.width : 0))) + 200;
    return (
      <Fragment>
        <EditTable
          bordered
          rowKey="locationId"
          scroll={{ x: scrollX }}
          className={classNames(styles['data-list'])}
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          pagination={pagination}
          onChange={onSearch}
        />
      </Fragment>
    );
  }
Example #2
Source File: DeprecatedRewards.jsx    From v3-ui with MIT License 4 votes vote down vote up
AccountRewardsView = (props) => {
  const { t } = useTranslation()

  const { address } = useOnboard()

  const { data: pools } = useAllPools()

  const { playerDrips } = usePlayerDrips(address)
  const { usersDripData, graphDripData } = useUsersDripData()

  const poolAddresses = map(pools, 'poolAddress')
  const playerRewards = extractPoolRewardsFromUserDrips({ poolAddresses, playerDrips })

  const [activeTxDripIds, setActiveTxDripIds] = useState([])

  const txName = t(`claimRewards`)
  const method = 'updateAndClaimDrips'
  const [txId, setTxId] = useState(0)
  const sendTx = useSendTransactionWrapper()
  const tx = useTransaction(txId)

  const handleClaim = async (drip) => {
    const { comptroller, updatePairs, dripTokens } = getParamsForClaim([drip.id])
    // shim
    // 0x178969a87a78597d303c47198c66f68e8be67dc2 => 0x2f6e61d89d43b3ada4a909935ee05d8ca8db78de
    // old
    // 0xc7c406A867B324b9189b9a7503683eFC9BdCe5BA
    const oldDaiContractPair = {
      measure: updatePairs[0].measure,
      source: '0xc7c406a867b324b9189b9a7503683efc9bdce5ba'
    }
    const params = [[...updatePairs, oldDaiContractPair], usersAddress, dripTokens]

    const id = await sendTx({
      name: txName,
      contractAbi: ComptrollerAbi,
      contractAddress: comptroller,
      method,
      params
    })
    setTxId(id)
  }

  const getParamsForClaim = (drips = []) => {
    const updatePairs = []
    const dripTokens = []
    let comptroller

    for (let i = 0; i < drips.length; i++) {
      let drip = graphDripData.balanceDrips.find(
        (drip) => drip.dripToken.toLowerCase() === drips[i].toLowerCase()
      )
      if (!drip) {
        drip = graphDripData.volumeDrips.find(
          (drip) => drip.dripToken.toLowerCase() === drips[i].toLowerCase()
        )
      }

      let [
        comptrollerAddress,
        sourceAddress,
        measureTokenAddress,
        dripTokenAddress,
        isReferral,
        playerAddress
      ] = drip.id.split('-')

      isReferral = Boolean(parseInt(isReferral, 10))

      updatePairs.push({
        source: sourceAddress,
        measure: measureTokenAddress
      })
      dripTokens.push(dripTokenAddress)
      comptroller = comptroller || comptrollerAddress
    }

    return { comptroller, updatePairs, dripTokens }
  }

  const getFormattedNumber = (value, decimals) => {
    const formatted =
      value && decimals
        ? ethers.utils.formatUnits(value, decimals || DEFAULT_TOKEN_PRECISION)
        : '0.0'

    return (
      <>
        <div className='font-bold text-flashy'>
          <PoolCountUp
            duration={14}
            fontSansRegular
            end={Number.parseFloat(formatted)}
            decimals={8}
          />
          {/* <PoolNumber>
          {numberWithCommas(formatted, { precision: 6 })}
        </PoolNumber> */}
        </div>
      </>
    )
  }

  const getDripDataByAddress = (dripTokenAddress, dripTokenData) => {
    const dripTokens = playerRewards?.allDrips || []

    const zero = ethers.utils.parseEther('0')

    const dripData = defaultTo(
      find(dripTokens, (d) => d.dripToken.address === dripTokenAddress),
      {
        id: dripTokenAddress,
        dripToken: {
          address: dripTokenAddress,
          ...dripTokenData
        },
        claimable: zero,
        balance: zero
      }
    )

    dripData.claimable = usersDripData ? usersDripData[dripTokenAddress].claimable : zero
    dripData.balance = usersDripData ? usersDripData[dripTokenAddress].balance : zero

    return dripData
  }

  const getClaimButton = (dripData) => {
    let disabled

    if (!dripData?.claimable?.gt(0)) {
      disabled = true
    }

    if (tx && !tx.completed && activeTxDripIds.includes(dripData.id)) {
      return (
        <>
          <div className='flex flex-col sm:flex-row items-center justify-end'>
            <span className='order-1 sm:order-2'>
              <ThemedClipSpinner />
              <span className='text-teal font-bold ml-2 mt-1'>{t('claiming')}</span>
            </span>

            <span className='order-2 sm:order-1'>
              {!isEmpty(tx.hash) && (
                <>
                  <BlockExplorerLink
                    chainId={tx.ethersTx.chainId}
                    txHash={tx.hash}
                    className='text-xxxs text-teal sm:mr-3'
                  >
                    Etherscan
                  </BlockExplorerLink>
                </>
              )}
            </span>
          </div>
        </>
      )
    }

    return (
      <>
        <a
          className={classnames('underline cursor-pointer stroke-current font-bold', {
            'cursor-not-allowed opacity-20': disabled
          })}
          onClick={(e) => {
            e.preventDefault()

            if (disabled) {
              return
            }

            setActiveTxDripIds([...activeTxDripIds, dripData.id])

            handleClaim(dripData)
          }}
        >
          {t('claim')}
        </a>
      </>
    )
  }

  const getRewardsDripRows = () => {
    return map(usersDripData, (dripTokenData, dripTokenAddress) => {
      const dripData = getDripDataByAddress(dripTokenAddress, dripTokenData)

      const isPoolDaiTickets =
        dripTokenData.name === 'PoolTogether Dai Ticket (Compound)' ||
        dripTokenData.name === 'DAI Ticket'

      return (
        <tr key={dripData.id}>
          <td className='px-2 sm:px-3 py-2 text-left font-bold'>
            {isPoolDaiTickets && (
              <>
                <PoolCurrencyIcon sm symbol='DAI' />
              </>
            )}{' '}
            {isPoolDaiTickets ? t('daiTickets') : dripData.dripToken.name}
          </td>
          <td className='px-2 sm:px-3 py-2 text-left'>
            {getFormattedNumber(dripData.claimable, dripData.dripToken.decimals)}
          </td>
          <td className='px-2 sm:px-3 py-2 text-right'>{getClaimButton(dripData)}</td>
        </tr>
      )
    })
  }

  const getTotalRewards = () => {
    const amounts = map(usersDripData, (dripTokenData, dripTokenAddress) => {
      const dripData = getDripDataByAddress(dripTokenAddress, dripTokenData)

      return Boolean(dripData.claimable) && Boolean(dripData.dripToken.decimals)
        ? parseFloat(ethers.utils.formatUnits(dripData.claimable, dripData.dripToken.decimals))
        : 0.0
    })

    return sum(amounts)
  }

  if (getTotalRewards() < 1) {
    return null
  }

  return (
    <>
      <div className='xs:mt-3 bg-accent-grey-4 rounded-lg xs:mx-0 px-2 sm:px-6 py-3'>
        <div className='flex justify-between flex-col xs:flex-row xs:pt-4 pb-0 px-2 xs:px-4'>
          <div className='flex-col order-2 xs:order-1'>
            <h6 className='flex items-center font-normal'>{t('totalRewards')}</h6>

            <h3>
              $<PoolNumber>{numberWithCommas(getTotalRewards(), { precision: 2 })}</PoolNumber>
            </h3>
          </div>

          <div className='order-1 xs:order-2 ml-auto'>
            <img src={PrizeIllustration} className='w-32 mx-auto' />
          </div>
        </div>

        <div className='text-inverse flex flex-col justify-between xs:px-2'>
          <table className='table-fixed w-full text-xxs xs:text-base mt-6'>
            <tbody>{getRewardsDripRows()}</tbody>
          </table>
        </div>
      </div>
    </>
  )
}