From e983c4d06fd0bd59d999c3074a6d83e9961e10b0 Mon Sep 17 00:00:00 2001 From: SP Date: Mon, 10 Apr 2023 00:01:38 -0300 Subject: [PATCH] prettier pass --- components/Form/components/CountrySelect.js | 34 +-- components/Form/components/DateSelect.js | 42 ++-- components/Form/components/SalaryInput.js | 36 ++- components/Form/index.js | 18 +- components/Form/useFormData.js | 23 +- .../components/BuyingPowerGraph.js | 216 +++++++++--------- components/ResultsSummary/index.js | 19 +- pages/api/country/[code].js | 52 +++-- pages/index.js | 5 +- pages/results.js | 91 ++++---- 10 files changed, 283 insertions(+), 253 deletions(-) diff --git a/components/Form/components/CountrySelect.js b/components/Form/components/CountrySelect.js index ba8f52a..d9b2e47 100644 --- a/components/Form/components/CountrySelect.js +++ b/components/Form/components/CountrySelect.js @@ -8,32 +8,35 @@ const ItemTemplate = ({ item }) => { const secondaryName = item.names.length > 1 ? item.names[0] : ''; return (
-
{primaryName}{secondaryName}
-
+
+ {primaryName} + {secondaryName} +
+ ); }; const buildCountryLookup = (countries = []) => { return countries.map((country) => ({ - ...country, search: country.names - .join('||') - .toLowerCase() - + ...country, + search: country.names.join('||').toLowerCase(), })); }; -const compareByName = (country = {}, query = '') => country.search.includes(query); +const compareByName = (country = {}, query = '') => + country.search.includes(query); export default function CountrySelect({ value, countries, onChange }) { const [selectedCountry, setSelectedCountry] = useState(null); - const [countriesLookup] = useState((buildCountryLookup(countries))); + const [countriesLookup] = useState(buildCountryLookup(countries)); const [filteredCountries, setFilteredCountries] = useState([]); const searchCountry = (event) => { const query = event.query.trim().toLowerCase(); - const result = query ? - countriesLookup.filter((country) => compareByName(country, query)) : [...countriesLookup]; + const result = query + ? countriesLookup.filter((country) => compareByName(country, query)) + : [...countriesLookup]; setFilteredCountries(result); }; @@ -48,7 +51,7 @@ export default function CountrySelect({ value, countries, onChange }) { }, [selectedCountry]); return ( -
+
{ const value = event.target.value; - if (!value) { setSelectedCountry(null); return; }; + if (!value) { + setSelectedCountry(null); + return; + } if (!selectedCountry?.code && typeof value === 'string') { const query = value.trim().toLowerCase(); - const maybeCountry = countriesLookup.find((country) => compareByName(country, query)); + const maybeCountry = countriesLookup.find((country) => + compareByName(country, query) + ); setSelectedCountry(maybeCountry); } }} diff --git a/components/Form/components/DateSelect.js b/components/Form/components/DateSelect.js index 39967ce..81f514e 100644 --- a/components/Form/components/DateSelect.js +++ b/components/Form/components/DateSelect.js @@ -1,26 +1,26 @@ import { Calendar } from 'primereact/calendar'; export default function DateSelect({ - firstDate, - setDate, - selectedDate, - disabled = true, + firstDate, + setDate, + selectedDate, + disabled = true, }) { - return ( -
- - setDate(e.value)} - view='month' - minDate={new Date(`${firstDate[0]}-${firstDate[1]}-15`)} - maxDate={new Date()} - dateFormat='mm/yy' - tooltipOptions={{ position: 'mouse' }} - tooltip="Since when do you have that income?" - /> -
- ); + return ( +
+ + setDate(e.value)} + view='month' + minDate={new Date(`${firstDate[0]}-${firstDate[1]}-15`)} + maxDate={new Date()} + dateFormat='mm/yy' + tooltipOptions={{ position: 'mouse' }} + tooltip='Since when do you have that income?' + /> +
+ ); } diff --git a/components/Form/components/SalaryInput.js b/components/Form/components/SalaryInput.js index 7d36e8e..78f6a60 100644 --- a/components/Form/components/SalaryInput.js +++ b/components/Form/components/SalaryInput.js @@ -1,23 +1,19 @@ import { InputNumber } from 'primereact/inputnumber'; -export default function SalaryInput({ - salary, - setSalary, - selectedCountry, -}) { - return ( -
- - setSalary(e.value)} - mode="currency" - currency={selectedCountry?.currencyCode || 'USD'} - disabled={!selectedCountry} - tooltipOptions={{ position: 'bottom', appendTo: 'self' }} - tooltip="What's your monthly income, in the selected country currency?" - /> -
- ); +export default function SalaryInput({ salary, setSalary, selectedCountry }) { + return ( +
+ + setSalary(e.value)} + mode='currency' + currency={selectedCountry?.currencyCode || 'USD'} + disabled={!selectedCountry} + tooltipOptions={{ position: 'bottom', appendTo: 'self' }} + tooltip="What's your monthly income, in the selected country currency?" + /> +
+ ); } diff --git a/components/Form/index.js b/components/Form/index.js index 743fd33..2525b1a 100644 --- a/components/Form/index.js +++ b/components/Form/index.js @@ -8,8 +8,16 @@ import DateSelect from './components/DateSelect.js'; import SalaryInput from './components/SalaryInput.js'; export default function Form({ countries }) { - const { salary, setSalary, setCountry, setDate, firstDate, selectedCountry, selectedDate, showResults } = - useFormData(countries); + const { + salary, + setSalary, + setCountry, + setDate, + firstDate, + selectedCountry, + selectedDate, + showResults, + } = useFormData(countries); return (
@@ -36,10 +44,8 @@ export default function Form({ countries }) { disabled={!selectedCountry} />
- -
+ + ); } diff --git a/components/Form/useFormData.js b/components/Form/useFormData.js index c904ac9..f38f2b0 100644 --- a/components/Form/useFormData.js +++ b/components/Form/useFormData.js @@ -7,7 +7,10 @@ export default function useFormData(countries) { const query = useSearchParams(); const [selectedCountry, setSelectedCountry] = useState(null); - const [firstDate, setSelectedCountryFirstDate] = useState([new Date().getFullYear(), '01']); + const [firstDate, setSelectedCountryFirstDate] = useState([ + new Date().getFullYear(), + '01', + ]); const [selectedDate, setDate] = useState(null); const [salary, setSalary] = useState(null); const [loading, setLoading] = useState(false); @@ -31,15 +34,27 @@ export default function useFormData(countries) { const setCountry = (country) => { setSelectedCountry(country); - setSelectedCountryFirstDate(country ? country.first.split('-') : [new Date().getFullYear(), '01']); + setSelectedCountryFirstDate( + country ? country.first.split('-') : [new Date().getFullYear(), '01'] + ); }; const showResults = async (e) => { e.preventDefault(); - const [year, month] = [selectedDate.getFullYear(), selectedDate.getMonth() + 1]; + const [year, month] = [ + selectedDate.getFullYear(), + selectedDate.getMonth() + 1, + ]; const code = selectedCountry.code; setLoading(true); - router.push(`/results?${new URLSearchParams({ code, year, month, salary }).toString()}`); + router.push( + `/results?${new URLSearchParams({ + code, + year, + month, + salary, + }).toString()}` + ); }; return { diff --git a/components/ResultsSummary/components/BuyingPowerGraph.js b/components/ResultsSummary/components/BuyingPowerGraph.js index 1b4e59d..f2d5016 100644 --- a/components/ResultsSummary/components/BuyingPowerGraph.js +++ b/components/ResultsSummary/components/BuyingPowerGraph.js @@ -1,132 +1,128 @@ import React, { useEffect, useState } from 'react'; import { - Chart as ChartJS, - LinearScale, - CategoryScale, - BarElement, - PointElement, - LineElement, - Legend, - LineController, - Tooltip, - Filler, + Chart as ChartJS, + LinearScale, + CategoryScale, + BarElement, + PointElement, + LineElement, + Legend, + LineController, + Tooltip, + Filler, } from 'chart.js'; import { Chart } from 'primereact/chart'; ChartJS.register( - LinearScale, - CategoryScale, - BarElement, - PointElement, - LineController, - LineElement, - Legend, - Tooltip, - Filler + LinearScale, + CategoryScale, + BarElement, + PointElement, + LineController, + LineElement, + Legend, + Tooltip, + Filler ); - const options = { - plugins: { - tooltip: { position: 'nearest' }, - filler: { - propagate: false, - }, - title: { - display: true, - text: (ctx) => 'drawTime: ' + ctx.chart.options.plugins.filler.drawTime - } + plugins: { + tooltip: { position: 'nearest' }, + filler: { + propagate: false, + }, + title: { + display: true, + text: (ctx) => 'drawTime: ' + ctx.chart.options.plugins.filler.drawTime, }, + }, - scales: { - x: { - border: { - display: false - }, - grid: { - display: true, - drawOnChartArea: true, - drawTicks: true, - color: 'rgba(255, 255, 255, 0.25)', - } - }, - y: { - border: { - display: true - }, - grid: { - display: false - }, - } + scales: { + x: { + border: { + display: false, + }, + grid: { + display: true, + drawOnChartArea: true, + drawTicks: true, + color: 'rgba(255, 255, 255, 0.25)', + }, }, - animations: { - y: { - easing: 'easeInOutElastic', - from: (ctx) => { - if (ctx.type === 'data') { - if (ctx.mode === 'default' && !ctx.dropped) { - ctx.dropped = true; - return 0; - } - } - } - } + y: { + border: { + display: true, + }, + grid: { + display: false, + }, }, - interaction: { - intersect: false, - mode: 'index', + }, + animations: { + y: { + easing: 'easeInOutElastic', + from: (ctx) => { + if (ctx.type === 'data') { + if (ctx.mode === 'default' && !ctx.dropped) { + ctx.dropped = true; + return 0; + } + } + }, }, + }, + interaction: { + intersect: false, + mode: 'index', + }, }; -const buyingPowerAtAPoint = (initialSalary) => (point) => initialSalary / (1 + (point.acumulatedInflation / 100)); +const buyingPowerAtAPoint = (initialSalary) => (point) => + initialSalary / (1 + point.acumulatedInflation / 100); const generateDataset = (dataPoints, initialSalary) => { - const buyingPointRelativeToSalary = buyingPowerAtAPoint(initialSalary); - return { - labels: dataPoints.map((dataPoint) => dataPoint.date), - datasets: [ - { - label: 'Your Salary', - data: dataPoints.map(() => initialSalary), - borderColor: 'rgba(0, 255, 91, 1)', - animations: { - y: { - duration: 2000, - } - }, - radius: 0, - borderWidth: 3, - backgroundColor: 'rgba(255, 0, 0, 0.25)', - fill: 1, - tension: 0.5 - }, - { - label: 'Your Buying Power', - borderColor: 'rgba(238, 255, 0, 1)', - backgroundColor: 'rgba(0, 255, 91, 0.25)', - animations: { - y: { - duration: 2000, - delay: 1000 - } - }, - fill: true, - radius: 1, - data: [initialSalary, ...dataPoints.map(buyingPointRelativeToSalary)], - beginAtZero: true - - }, - ], - }; + const buyingPointRelativeToSalary = buyingPowerAtAPoint(initialSalary); + return { + labels: dataPoints.map((dataPoint) => dataPoint.date), + datasets: [ + { + label: 'Your Salary', + data: dataPoints.map(() => initialSalary), + borderColor: 'rgba(0, 255, 91, 1)', + animations: { + y: { + duration: 2000, + }, + }, + radius: 0, + borderWidth: 3, + backgroundColor: 'rgba(255, 0, 0, 0.25)', + fill: 1, + tension: 0.5, + }, + { + label: 'Your Buying Power', + borderColor: 'rgba(238, 255, 0, 1)', + backgroundColor: 'rgba(0, 255, 91, 0.25)', + animations: { + y: { + duration: 2000, + delay: 1000, + }, + }, + fill: true, + radius: 1, + data: [initialSalary, ...dataPoints.map(buyingPointRelativeToSalary)], + beginAtZero: true, + }, + ], + }; }; - - - export function BuyingPowerGraph({ data, initialSalary = 1000 }) { - const [chartData, setChartData] = useState(generateDataset([])); - useEffect(() => { - data.length && setChartData(generateDataset(data, initialSalary)); - }, [data, initialSalary]); + const [chartData, setChartData] = useState(generateDataset([])); + useEffect(() => { + data.length && setChartData(generateDataset(data, initialSalary)); + }, [data, initialSalary]); - return ; + return ; } diff --git a/components/ResultsSummary/index.js b/components/ResultsSummary/index.js index 518ea90..9c1b9e0 100644 --- a/components/ResultsSummary/index.js +++ b/components/ResultsSummary/index.js @@ -1,14 +1,15 @@ import { useSearchParams } from 'next/navigation'; import { BuyingPowerGraph } from './components/BuyingPowerGraph'; - export default function ResultSummary({ result }) { - const query = useSearchParams(); - - return ( - <> - - - - ); + const query = useSearchParams(); + + return ( + <> + + + ); } diff --git a/pages/api/country/[code].js b/pages/api/country/[code].js index 456674d..7166f45 100644 --- a/pages/api/country/[code].js +++ b/pages/api/country/[code].js @@ -4,8 +4,8 @@ import countries from './../../../countryData/data/allCountriesData.json'; /** * Get the country periods by provider. If no provider is requested, it will return the average - * @param {*} requestedProvider - * @param {*} country + * @param {*} requestedProvider + * @param {*} country * @returns {Object} { periods: [], providers: [] } */ function getCountryPeriodsByProvider(requestedProvider, country) { @@ -18,18 +18,24 @@ function getCountryPeriodsByProvider(requestedProvider, country) { const countryProvider = meta.find((p) => p.provider === requestedProvider); if (!countryProvider) { const countryProviders = meta.map(({ provider }) => provider); - throw new Error('Country provider not found, avaliable providers: ' + countryProviders.join(', ')); + throw new Error( + 'Country provider not found, avaliable providers: ' + + countryProviders.join(', ') + ); } - return { periods: inflation[countryProvider.provider], providers: [countryProvider] }; + return { + periods: inflation[countryProvider.provider], + providers: [countryProvider], + }; } /** * Get the country periods sliced by the fromYear and fromMonth to the end (now). * If no fromYear and fromMonth is provided, it will return all the periods - * @param {*} dateFilter { fromYear, fromMonth } + * @param {*} dateFilter { fromYear, fromMonth } * @param {*} periods The previously filtered by provider periods - * @returns + * @returns */ function getCountrySlicedPeriods({ fromYear, fromMonth }, periods) { let fromIndex = 0; @@ -49,44 +55,51 @@ function getCountrySlicedPeriods({ fromYear, fromMonth }, periods) { * Correct the last period, by the percentage of the month that the user is asking on. * That way, if we are at 80% of the month, we reduce the estimated change by 20%. * The last period is almost always estimated, because data is always old. - * @param {*} previousToLastPeriod - * @param {*} lastPeriod + * @param {*} previousToLastPeriod + * @param {*} lastPeriod */ function correctLastEstimatedPeriod(allPeriods, slicedPeriods) { const lastPeriod = allPeriods[allPeriods.length - 1]; const previousToLastPeriod = allPeriods[allPeriods.length - 2]; const percentage = percentageOfCurrentMonth(); const inflation = percentage * lastPeriod.inflation; - const cpi = previousToLastPeriod.cpi + (previousToLastPeriod.cpi * (inflation / 100)); - slicedPeriods[slicedPeriods.length - 1] = { ...lastPeriod, percentage, inflation, cpi }; + const cpi = + previousToLastPeriod.cpi + previousToLastPeriod.cpi * (inflation / 100); + slicedPeriods[slicedPeriods.length - 1] = { + ...lastPeriod, + percentage, + inflation, + cpi, + }; } - /** * Calculate the total inflation of the periods - * Uses the composite interest formula, to calculate the total inflation of the periods, - * because the inflation is compounded. + * Uses the composite interest formula, to calculate the total inflation of the periods, + * because the inflation is compounded. * And that method allows us to not need an extra CPI period to calculate the inflation. * @see https://ciecmza.files.wordpress.com/2020/09/como-se-calcula-la-inflacion.pdf - * @param {*} periods filtered by provider and sliced by date + * @param {*} periods filtered by provider and sliced by date */ const calculateTotalInflationOfPeriods = (periods) => { if (periods.length === 1) return periods[0].inflation; let acumulatedInflation = 1; for (let i = 0; i < periods.length; i++) { - acumulatedInflation *= (periods[i].inflation / 100 + 1); + acumulatedInflation *= periods[i].inflation / 100 + 1; periods[i].acumulatedInflation = (acumulatedInflation - 1) * 100; } }; - /** Main function to get the country inflation data */ function getCpi(code, provider, fromYear, fromMonth) { const country = countries.data[code]; if (!country) throw new Error('Country CPI not found'); const { periods, providers } = getCountryPeriodsByProvider(provider, country); - const slicedPeriods = getCountrySlicedPeriods({ fromYear, fromMonth }, periods); + const slicedPeriods = getCountrySlicedPeriods( + { fromYear, fromMonth }, + periods + ); correctLastEstimatedPeriod(periods, slicedPeriods); calculateTotalInflationOfPeriods(slicedPeriods); @@ -117,8 +130,9 @@ export default function handler(req, res) { try { const country = getCpiFromQuery(req.query); res.status(200).json(country); - } catch (error) { - return res.status(404).json({ error: 'Error getting CPI' + error.message, params: req.query }); + return res + .status(404) + .json({ error: 'Error getting CPI' + error.message, params: req.query }); } } diff --git a/pages/index.js b/pages/index.js index 960d583..90e14ec 100644 --- a/pages/index.js +++ b/pages/index.js @@ -4,10 +4,11 @@ import countryList from '../countryData/data/countryList.json'; import Form from '../components/Form/index.js'; -export async function getStaticProps() { return { props: { countryList } }; } +export async function getStaticProps() { + return { props: { countryList } }; +} export default function Home({ countryList }) { - return (
diff --git a/pages/results.js b/pages/results.js index 25a5421..7768adc 100644 --- a/pages/results.js +++ b/pages/results.js @@ -6,58 +6,51 @@ import Form from '../components/Form/index.js'; import ResultsSummary from '../components/ResultsSummary/index.js'; import { Accordion, AccordionTab } from 'primereact/accordion'; - export async function getServerSideProps(context) { - try { - const inflationData = getCpiFromQuery(context.query); - return { - props: { - countryList, - inflationData, - }, - }; - } catch (error) { - return { - redirect: { - destination: '/', - permanent: false, - }, - }; - } - - - + try { + const inflationData = getCpiFromQuery(context.query); + return { + props: { + countryList, + inflationData, + }, + }; + } catch (error) { + return { + redirect: { + destination: '/', + permanent: false, + }, + }; + } } export default function Results({ countryList, inflationData }) { - return ( -
- - Raise Calculator - - - + return ( +
+ + Raise Calculator + + + -
-

Results Page

- - -
- - - - - -
{JSON.stringify(inflationData, null, 2)}
-
- -
-
- ); +
+

Results Page

+ + + + + + + + +
{JSON.stringify(inflationData, null, 2)}
+
+
+
+
+ ); }