Download.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import React from 'react'
  2. import { get, forEach, reverse, round, sortBy } from 'lodash'
  3. import ExportIcon from '@material-ui/icons/GetApp'
  4. import IconButton from '@material-ui/core/IconButton'
  5. import Tooltip from '@material-ui/core/Tooltip'
  6. const columns = [
  7. {
  8. head: "Name",
  9. prop: "name",
  10. currency: false,
  11. }, {
  12. head: "CPU",
  13. prop: "cpuCost",
  14. currency: true,
  15. }, {
  16. head: "GPU",
  17. prop: "gpuCost",
  18. currency: true,
  19. }, {
  20. head: "RAM",
  21. prop: "ramCost",
  22. currency: true,
  23. }, {
  24. head: "PV",
  25. prop: "pvCost",
  26. currency: true,
  27. }, {
  28. head: "Network",
  29. prop: "networkCost",
  30. currency: true,
  31. }, {
  32. head: "Shared",
  33. prop: "sharedCost",
  34. currency: true,
  35. }, {
  36. head: "Total",
  37. prop: "totalCost",
  38. currency: true,
  39. }
  40. ]
  41. const toCSVLine = (datum) => {
  42. let cols = []
  43. forEach(columns, c => {
  44. if (c.currency) {
  45. cols.push(round(get(datum, c.prop, 0.0), 2))
  46. } else {
  47. cols.push(`"${get(datum, c.prop, "")}"`)
  48. }
  49. })
  50. return cols.join(',')
  51. }
  52. const DownloadControl = ({
  53. cumulativeData,
  54. title,
  55. }) => {
  56. // downloadReport downloads a CSV of the cumulative allocation data
  57. function downloadReport() {
  58. // Build CSV
  59. const head = columns.map(c => c.head).join(',')
  60. const body = reverse(sortBy(cumulativeData, 'totalCost')).map(toCSVLine).join('\r\n')
  61. const csv = `${head}\r\n${body}`
  62. // Create download link
  63. const a = document.createElement("a")
  64. a.href = URL.createObjectURL(new Blob([csv], { type: "text/csv" }))
  65. const filename = title.toLowerCase().replace(/\s/gi, '-')
  66. a.setAttribute("download", `${filename}-${Date.now()}.csv`)
  67. // Click the link
  68. document.body.appendChild(a)
  69. a.click()
  70. document.body.removeChild(a)
  71. }
  72. return (
  73. <Tooltip title="Download CSV">
  74. <IconButton onClick={downloadReport}>
  75. <ExportIcon />
  76. </IconButton>
  77. </Tooltip>
  78. )
  79. }
  80. export default React.memo(DownloadControl)