Skip to content

Commit

Permalink
Download csv file on click
Browse files Browse the repository at this point in the history
  • Loading branch information
AbdulrhmnGhanem committed Oct 7, 2024
1 parent 47093d6 commit a15efb1
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 11 deletions.
34 changes: 25 additions & 9 deletions frontend/src/components/Board/BuyParts/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,34 @@ const BuyParts = ({ projectFullName, lines, parts }: BuyPartsProps) => {
const [mult, setMult] = useState(1)
const [buyAddPercent, setBuyAddPercent] = useState(0)

const buyParts = distributor => {
const downloadBom = (retailer: string) => {
window.plausible('Buy Parts', {
props: {
project: projectFullName,
vendor: distributor,
vendor: retailer,
multiplier: mult,
},
})

const data = [
['Reference', 'Quantity', 'Distributor'],
[1, 2, 3],
]
const csvContent = data.map(e => e.join(',')).join('\n')
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
const url = URL.createObjectURL(blob)

const link = document
.getElementById(`retailer-${retailer}`)
.closest('a').parentElement
link.setAttribute('href', url)
link.setAttribute('download', `${retailer}-kitspace-bom.csv`)
link.click()
}

const retailerList = OneClickBom.getRetailers()
const retailerList: Array<string> = OneClickBom.getRetailers()
const retailerButtons = retailerList
.map(name => {
.map((name: string): React.ReactElement | null => {
const [numberOfLines, numberOfParts] = lines.reduce(
([numOfLines, numOfParts], line) => {
if (line.retailers[name]) {
Expand All @@ -37,7 +52,7 @@ const BuyParts = ({ projectFullName, lines, parts }: BuyPartsProps) => {
return (
<RetailerButton
key={name}
buyParts={() => buyParts(name)}
downloadBom={() => downloadBom(name)}
name={name}
numberOfLines={numberOfLines}
numberOfParts={numberOfParts}
Expand Down Expand Up @@ -165,14 +180,15 @@ const AdjustQuantity = ({

const RetailerButton = ({
name,
buyParts,
downloadBom,
numberOfLines,
totalLines,
numberOfParts,
}: RetailerButtonProps) => {
const color = 'green'
return (
<Button
as={'a'}
className={`${styles.retailerButton} ${styles[color]}`}
color={color}
content={
Expand All @@ -182,10 +198,10 @@ const RetailerButton = ({
</div>
}
label={{
as: 'a',
className: `${styles.retailerLabel} ${styles[color]} `,
content: (
<div
id={`retailer-${name}`}
style={{
width: '100%',
display: 'flex',
Expand All @@ -203,7 +219,7 @@ const RetailerButton = ({
),
}}
labelPosition="right"
onClick={buyParts}
onClick={downloadBom}
/>
)
}
Expand Down Expand Up @@ -241,7 +257,7 @@ interface AdjustQuantityProps {

interface RetailerButtonProps {
name: string
buyParts: () => void
downloadBom: () => void
numberOfLines: number
totalLines: number
numberOfParts: number
Expand Down
48 changes: 46 additions & 2 deletions frontend/test/BuyParts.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, expect, it } from 'vitest'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'

import BuyParts from '@components/Board/BuyParts'
Expand Down Expand Up @@ -46,14 +46,58 @@ it('still displays BuyParts if there are no purchasable parts', () => {
expect(BomRowsCollapsed).toHaveLength(63)
})

it.skip('downloads `kitspace-bom.csv` on click', async () => {
it('downloads `kitspace-bom.csv` on click', async () => {
const mockPlausible = vi.fn()
window.plausible = mockPlausible // Mocking plausible method

// Mock the createObjectURL and link click functionality
const mockCreateObjectURL = vi
.spyOn(URL, 'createObjectURL')
.mockReturnValue('mocked-url')
const mockClick = vi.fn()

render(
<BuyParts
lines={fixture.purchasableParts.lines}
parts={fixture.purchasableParts.parts}
projectFullName="username/name"
/>,
)

const storeButton = screen.getAllByRole('button').at(-1)

// Mock anchor element and simulate the CSV download behavior
const mockLinkElement = {
setAttribute: vi.fn(),
click: mockClick,
}
const mockGetElementById = vi.spyOn(document, 'getElementById').mockReturnValue({
closest: vi.fn().mockReturnValue({
parentElement: mockLinkElement,
}),
} as unknown as HTMLElement)

// Simulate button click
storeButton.click()

expect(mockPlausible).toHaveBeenCalledWith('Buy Parts', {
props: {
project: 'username/name',
vendor: expect.any(String),
multiplier: expect.any(Number),
},
})
expect(mockCreateObjectURL).toHaveBeenCalledOnce() // Check if the URL was created
expect(mockLinkElement.setAttribute).toHaveBeenCalledWith('href', 'mocked-url')
expect(mockLinkElement.setAttribute).toHaveBeenCalledWith(
'download',
expect.stringContaining('kitspace-bom.csv'),
)
expect(mockClick).toHaveBeenCalledOnce() // Check if the link click was triggered

// cleanup
mockCreateObjectURL.mockRestore()
mockGetElementById.mockRestore()
})

afterEach(() => {
Expand Down

0 comments on commit a15efb1

Please sign in to comment.