Skip to content

Commit

Permalink
Refactor file imports and add useGlobals hook and split provider (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
sensasi-delight authored Oct 9, 2024
1 parent 8130e76 commit 9dffb72
Show file tree
Hide file tree
Showing 11 changed files with 322 additions and 307 deletions.
Binary file removed bun.lockb
Binary file not shown.
27 changes: 12 additions & 15 deletions src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import Stepper from './components/stepper'
import SavedCalculation from './components/saved-calculation'
// import Notification from './components/Notification';

import vars from './helpers/vars'
import { useGlobals } from './hooks/use-globals'

const INPUT_CODES = [
[
Expand All @@ -33,8 +33,7 @@ const INPUT_CODES = [
]

export default function App() {
vars.formValues = useState({})
vars.activeStep = useState(0)
const { activeStep, setActiveStep, formValues } = useGlobals()

// const [notifications, setNotifications] = useState([])

Expand All @@ -56,10 +55,8 @@ export default function App() {
const [isTextFieldErrors, setIsTextFieldErrors] = useState({})

const getInvalidTextFieldIds = () => {
return INPUT_CODES[vars.activeStep[0]].filter(
inputId =>
vars.formValues[0][inputId] === '' ||
isNaN(vars.formValues[0][inputId]),
return INPUT_CODES[activeStep].filter(
inputId => formValues[inputId] === '' || isNaN(formValues[inputId]),
)
}

Expand All @@ -86,11 +83,11 @@ export default function App() {

const handleNext = () => {
if (isFormValuesValid()) {
return vars.activeStep[1](vars.activeStep[0] + 1)
return setActiveStep(prev => prev + 1)
}
}

const handlePrev = () => vars.activeStep[1]((prev: number) => prev - 1)
const handlePrev = () => setActiveStep((prev: number) => prev - 1)

return (
<Container maxWidth="sm">
Expand All @@ -110,7 +107,7 @@ export default function App() {

<Box>
<Fade
in={vars.activeStep[0] === 0}
in={activeStep === 0}
timeout={{
enter: 500,
exit: 0,
Expand All @@ -120,14 +117,14 @@ export default function App() {
<Form
inputCodes={INPUT_CODES[0]}
handleNext={handleNext}
values={vars.formValues[0]}
values={formValues}
isErrors={isTextFieldErrors}
/>
</Box>
</Fade>

<Fade
in={vars.activeStep[0] === 1}
in={activeStep === 1}
timeout={{
enter: 500,
exit: 0,
Expand All @@ -137,14 +134,14 @@ export default function App() {
<Form
inputCodes={INPUT_CODES[1]}
handleNext={handleNext}
values={vars.formValues[0]}
values={formValues}
isErrors={isTextFieldErrors}
/>
</Box>
</Fade>

<Fade
in={vars.activeStep[0] === 2}
in={activeStep === 2}
timeout={{
enter: 500,
exit: 0,
Expand All @@ -157,7 +154,7 @@ export default function App() {
</Box>

<Stepper
activeStep={vars.activeStep[0]}
activeStep={activeStep}
handleNext={handleNext}
handlePrev={handlePrev}
/>
Expand Down
203 changes: 95 additions & 108 deletions src/components/result-box/result-box.tsx
Original file line number Diff line number Diff line change
@@ -1,70 +1,27 @@
// vendors
import { useRef, useState, useEffect, useMemo } from 'react'

import Box from '@mui/system/Box'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'

import { Box, Button, IconButton, Tooltip } from '@mui/material'
import moment from 'moment'
// icons
import { Save as SaveIcon } from '@mui/icons-material'
// helpers
import { currencyFormat, numberFormat } from '../../helpers'
import calculatePalmGrade from '../../helpers/calculate-palm-grade'
// import { GALog } from "../helpers/firebaseClient";
// components
import DetailDialog from './components/detail-dialog'
import SummaryTable from './components/summary-table'
import TextField from '../text-field'

// import { GALog } from "../helpers/firebaseClient";
import {
currencyFormat,
getSavedDatasets,
numberFormat,
} from '../../helpers/index'
import vars from '../../helpers/vars'
import moment from 'moment'

import SaveIcon from '@mui/icons-material/Save'

const getSummaryData = (detailsCalculation: AnuType[]) => {
const dataset = vars.formValues[0]

const summaryDataset: TypeB[] = [
{
name: 'Tandan Buah Segar',
weight: dataset.totalWeight,
worth: dataset.totalWeight * dataset.pricePerKg,
tooltip: `${numberFormat(dataset.totalWeight)} × ${currencyFormat(
dataset.pricePerKg,
)}`,
},
]

const { totalCutWorth, totalAddWorth } = detailsCalculation.reduce(
(acc, detail) => ({
totalCutWorth: acc.totalCutWorth + detail.cutWorth,
totalAddWorth: acc.totalAddWorth + detail.addWorth,
}),
{
totalCutWorth: 0,
totalAddWorth: 0,
},
)

summaryDataset.push({
name: 'Potongan',
weight: totalCutWorth / dataset.pricePerKg,
worth: totalCutWorth,
})

summaryDataset.push({
name: 'Insentif',
weight: totalAddWorth / dataset.pricePerKg,
worth: totalAddWorth,
})

return summaryDataset
}
// hooks
import { useGlobals } from '../../hooks/use-globals'
// functions
import { getSavedDatasets } from '../../functions/get-saved-datasets'

let calculationResults: AnuType[] = []

const ResultBox = () => {
const temp = vars.formValues[0]
export default function ResultBox() {
const { formValues: temp, setFormValues, setActiveStep } = useGlobals()

const dataset = useMemo(() => {
return { ...temp }
}, [temp])
Expand All @@ -76,18 +33,52 @@ const ResultBox = () => {
const detailBtnRef = useRef<HTMLButtonElement>(null)

useEffect(() => {
vars.formValues[0].pricePerKg = pricePerKg
vars.formValues[1]({ ...vars.formValues[0] })
setFormValues({ ...temp, pricePerKg })

calculationResults = calculatePalmGrade(vars.formValues[0])
calculationResults = calculatePalmGrade(temp)

setSummaryData(getSummaryData(calculationResults))
setSummaryData(getSummaryData(calculationResults, temp))
}, [pricePerKg])

useEffect(() => {
setPricePerKg(dataset.pricePerKg || '')
}, [dataset.savedAt, dataset.pricePerKg])

const isSaveDisabled =
!pricePerKg ||
JSON.stringify(dataset) ===
JSON.stringify(
getSavedDatasets().find(
data => data.savedAt === dataset.savedAt,
),
)

function handleSave() {
const savedDatasets = getSavedDatasets()

if (dataset.savedAt) {
const delIndex = savedDatasets.findIndex(
data => data.savedAt === dataset.savedAt,
)
savedDatasets.splice(delIndex, 1)
}

dataset.savedAt = moment().format()
dataset.finalWeight =
summaryData[0]?.weight -
summaryData[1]?.weight +
summaryData[2]?.weight
dataset.finalWorth =
summaryData[0]?.worth -
summaryData[1]?.worth +
summaryData[2]?.worth

setFormValues({ ...dataset })
savedDatasets.push({ ...dataset } as any)

localStorage.setItem('savedDatasets', JSON.stringify(savedDatasets))
}

return (
<>
<Box
Expand All @@ -114,8 +105,8 @@ const ResultBox = () => {
variant="outlined"
onClick={() => {
// GALog('click_reset');
vars.activeStep[1](0)
vars.formValues[1]({})
setActiveStep(0)
setFormValues({})
}}>
Ulangi
</Button>
Expand All @@ -126,48 +117,8 @@ const ResultBox = () => {
<span>
<IconButton
color="primary"
disabled={
!pricePerKg ||
JSON.stringify(dataset) ===
JSON.stringify(
getSavedDatasets().find(
data =>
data.savedAt ===
dataset.savedAt,
),
)
}
onClick={() => {
const savedDatasets = getSavedDatasets()

if (dataset.savedAt) {
const delIndex =
savedDatasets.findIndex(
data =>
data.savedAt ===
dataset.savedAt,
)
savedDatasets.splice(delIndex, 1)
}

dataset.savedAt = moment().format()
dataset.finalWeight =
summaryData[0]?.weight -
summaryData[1]?.weight +
summaryData[2]?.weight
dataset.finalWorth =
summaryData[0]?.worth -
summaryData[1]?.worth +
summaryData[2]?.worth

vars.formValues[1]({ ...dataset })
savedDatasets.push({ ...dataset })

window.localStorage.setItem(
'savedDatasets',
JSON.stringify(savedDatasets),
)
}}>
disabled={isSaveDisabled}
onClick={handleSave}>
<SaveIcon />
</IconButton>
</span>
Expand Down Expand Up @@ -195,7 +146,43 @@ const ResultBox = () => {
)
}

export default ResultBox
function getSummaryData(detailsCalculation: AnuType[], dataset: any) {
const summaryDataset: TypeB[] = [
{
name: 'Tandan Buah Segar',
weight: dataset.totalWeight,
worth: dataset.totalWeight * dataset.pricePerKg,
tooltip: `${numberFormat(dataset.totalWeight)} × ${currencyFormat(
dataset.pricePerKg,
)}`,
},
]

const { totalCutWorth, totalAddWorth } = detailsCalculation.reduce(
(acc, detail) => ({
totalCutWorth: acc.totalCutWorth + detail.cutWorth,
totalAddWorth: acc.totalAddWorth + detail.addWorth,
}),
{
totalCutWorth: 0,
totalAddWorth: 0,
},
)

summaryDataset.push({
name: 'Potongan',
weight: totalCutWorth / dataset.pricePerKg,
worth: totalCutWorth,
})

summaryDataset.push({
name: 'Insentif',
weight: totalAddWorth / dataset.pricePerKg,
worth: totalAddWorth,
})

return summaryDataset
}

interface AnuType {
qty: number
Expand Down
Loading

0 comments on commit 9dffb72

Please sign in to comment.