Skip to content

Commit

Permalink
fix: separation of spatial_coverage feature into Prod and Staging
Browse files Browse the repository at this point in the history
  • Loading branch information
AldemirLucas committed Nov 6, 2024
1 parent 897fcff commit 675e29f
Show file tree
Hide file tree
Showing 9 changed files with 130 additions and 84 deletions.
83 changes: 55 additions & 28 deletions next/components/organisms/DatasetResource.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ import ChevronIcon from "../../public/img/icons/chevronIcon";
export default function DatasetResource({
dataset
}) {
const { t } = useTranslation('dataset');
const router = useRouter()
const { query, locale } = router
const [tables, setTables] = useState([])
const [rawDataSources, setRawDataSources] = useState([])
const [informationRequests, setInformationRequests] = useState([])
const { t } = useTranslation('dataset');
const displayScreen = useBreakpointValue({ base: "mobile", lg: "desktop" })

const pushQuery = (key, value) => {
Expand All @@ -55,7 +55,6 @@ export default function DatasetResource({
}

useEffect(() => {

let dataset_tables = dataset?.tables?.edges.map((elm) => elm.node)
.filter((elm) => elm?.status?.slug !== "under_review")
.filter((elm) => elm?.slug !== "dicionario")
Expand Down Expand Up @@ -194,10 +193,24 @@ export default function DatasetResource({
)
}

function SelectResource() {
const [widthScreen, setWidthScreen] = useState(0)
function SelectResource ({ selectedResource }) {
const { t } = useTranslation('dataset');
const [widthScreen, setWidthScreen] = useState(0);
const [value, setValue] = useState("")
const {table, raw_data_source, information_request} = selectedResource;

const findResourceName = (source, id) => {
const resource = source.find(item => item._id === id);
return resource ? resource[`name${capitalize(locale)}`] || resource.name : "";
};

useEffect(() => {
setValue(
table ? findResourceName(tables, table) :
raw_data_source ? findResourceName(rawDataSources, raw_data_source) :
information_request ? findResourceName(informationRequests, information_request) : ""
);

const updateWidthScreen = () => {
setWidthScreen(window.innerWidth - 48)
}
Expand All @@ -209,35 +222,49 @@ export default function DatasetResource({
return () => {
window.removeEventListener('resize', updateWidthScreen)
}
}, [])
}, [table, raw_data_source, information_request]);

return (
<Menu>
<MenuButton
width="100%"
maxWidth="360px"
borderRadius="8px"
padding="14px 20px"
<Text
as="label"
display="flex"
flexDirection="column"
gap="8px"
fontFamily="Roboto"
fontWeight="400"
fontSize="14px"
lineHeight="20px"
backgroundColor="#EEEEEE"
color="#464A51"
textAlign="start"
fontWeight="500"
fontSize="16px"
lineHeight="24px"
color="#252A32"
>
<Text
display="flex"
justifyContent="space-between"
alignItems="center"
{t('selectResource')}

<MenuButton
width="100%"
maxWidth="360px"
borderRadius="8px"
padding="14px 20px"
fontFamily="Roboto"
fontWeight="400"
fontSize="14px"
lineHeight="20px"
backgroundColor="#EEEEEE"
color="#464A51"
textAlign="start"
>
Selecione uma tabela ou fonte original
<ChevronIcon
marginLeft="auto"
transform="rotate(90deg)"
/>
</Text>
</MenuButton>
<Text
display="flex"
justifyContent="space-between"
alignItems="center"
>
{value}
<ChevronIcon
marginLeft="auto"
transform="rotate(90deg)"
/>
</Text>
</MenuButton>
</Text>

<MenuList
minWidth={widthScreen}
Expand Down Expand Up @@ -415,7 +442,7 @@ export default function DatasetResource({
/>
</Stack>
:
<SelectResource />
<SelectResource selectedResource={query}/>
}

<SwitchResource route={query}/>
Expand Down
7 changes: 6 additions & 1 deletion next/components/organisms/DatasetSearchCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ export default function Dataset({
const { t } = useTranslation('dataset');
const [spatialCoverageNames, setSpatialCoverageNames] = useState([]);

const allowedURLs = ["https://basedosdados.org", "https://staging.basedosdados.org"]


useEffect(() => {
if(allowedURLs.includes(process.env.NEXT_PUBLIC_BASE_URL_FRONTEND)) return

const fetchAreaNames = async () => {
if (!spatialCoverage) return;

Expand Down Expand Up @@ -299,7 +304,7 @@ export default function Dataset({
</Text>
</Stack>

{process.env.NEXT_PUBLIC_BASE_URL_FRONTEND !== "https://basedosdados.org" &&
{!allowedURLs.includes(process.env.NEXT_PUBLIC_BASE_URL_FRONTEND) &&
<Stack
direction={{ base: "column", lg: "row" }}
spacing={1}
Expand Down
45 changes: 25 additions & 20 deletions next/components/organisms/TablePage.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,35 +38,40 @@ export default function TablePage({ id }) {
const [isError, setIsError] = useState(false)
const [spatialCoverageNames, setSpatialCoverageNames] = useState([]);

const allowedURLs = ["https://basedosdados.org", "https://staging.basedosdados.org"]

useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(`/api/tables/getTable?id=${id}&locale=${locale}`, { method: "GET" })
const result = await response.json()

if (result.success) {
let areaNames = [];

if (result.resource?.spatialCoverage) {
const coverageArray = Array.isArray(result.resource.spatialCoverage)
? result.resource.spatialCoverage
: typeof result.resource.spatialCoverage === 'string'
? result.resource.spatialCoverage.split(',').map(item => item.trim())
: Object.values(result.resource.spatialCoverage);

const promises = coverageArray.map(slug =>
axios.get(`/api/areas/getArea?slug=${slug}&locale=${locale}`)
);

const responses = await Promise.all(promises);
areaNames = responses
.map(res => res.data.resource[0]?.node[`name${capitalize(locale)}`] || res.data.resource[0]?.node.name)
.filter(Boolean)
.sort((a, b) => a.localeCompare(b, locale));
if(!allowedURLs.includes(process.env.NEXT_PUBLIC_BASE_URL_FRONTEND)) {
let areaNames = [];

if (result.resource?.spatialCoverage) {
const coverageArray = Array.isArray(result.resource.spatialCoverage)
? result.resource.spatialCoverage
: typeof result.resource.spatialCoverage === 'string'
? result.resource.spatialCoverage.split(',').map(item => item.trim())
: Object.values(result.resource.spatialCoverage);

const promises = coverageArray.map(slug =>
axios.get(`/api/areas/getArea?slug=${slug}&locale=${locale}`)
);

const responses = await Promise.all(promises);
areaNames = responses
.map(res => res.data.resource[0]?.node[`name${capitalize(locale)}`] || res.data.resource[0]?.node.name)
.filter(Boolean)
.sort((a, b) => a.localeCompare(b, locale));
}

setSpatialCoverageNames(areaNames);
}

setResource(result.resource);
setSpatialCoverageNames(areaNames);
setIsError(false);
} else {
console.error(result.error)
Expand Down Expand Up @@ -346,7 +351,7 @@ export default function TablePage({ id }) {
</StackSkeleton>
</Stack>

{process.env.NEXT_PUBLIC_BASE_URL_FRONTEND !== "https://basedosdados.org" &&
{!allowedURLs.includes(process.env.NEXT_PUBLIC_BASE_URL_FRONTEND) &&
<Stack spacing="12px" marginBottom="40px !important">
<StackSkeleton width="300px" height="20px">
<Text
Expand Down
4 changes: 0 additions & 4 deletions next/pages/api/areas/getCountries.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@ async function getAreas(locale = 'pt') {

export default async function handler(req, res) {
const { locale } = req.query;
console.log('API URL:', API_URL);
console.log('Locale:', locale);

const result = await getAreas(locale);
console.log('Result:', result);

if(result.errors) return res.status(500).json({error: result.errors, success: false})
if(result === "err") return res.status(500).json({error: "err", success: false})
Expand Down
68 changes: 38 additions & 30 deletions next/pages/dataset/[dataset].js
Original file line number Diff line number Diff line change
Expand Up @@ -37,45 +37,50 @@ export async function getStaticProps(context) {
const { locale, params } = context;
let dataset = null;
let spatialCoverageNames = [];
const allowedURLs = ["https://basedosdados.org", "https://staging.basedosdados.org"]

try {
dataset = await getDataset(params.dataset, locale || 'pt');

if (dataset?.spatialCoverage) {
const coverageArray = Array.isArray(dataset.spatialCoverage)
? dataset.spatialCoverage
: typeof dataset.spatialCoverage === 'string'
? dataset.spatialCoverage.split(',').map(item => item.trim())
: Object.values(dataset.spatialCoverage);

const promises = coverageArray.map(slug => {
const url = `${process.env.NEXT_PUBLIC_BASE_URL_FRONTEND}/api/areas/getArea?slug=${slug}&locale=${locale}`;
return axios.get(url).catch(error => {
console.error(`Error fetching ${url}:`, error.message);
return null;
if(!allowedURLs.includes(process.env.NEXT_PUBLIC_BASE_URL_FRONTEND)) {
if (dataset?.spatialCoverage) {
const coverageArray = Array.isArray(dataset.spatialCoverage)
? dataset.spatialCoverage
: typeof dataset.spatialCoverage === 'string'
? dataset.spatialCoverage.split(',').map(item => item.trim())
: Object.values(dataset.spatialCoverage);

const promises = coverageArray.map(slug => {
const url = `${process.env.NEXT_PUBLIC_BASE_URL_FRONTEND}/api/areas/getArea?slug=${slug}&locale=${locale}`;
return axios.get(url).catch(error => {
console.error(`Error fetching ${url}:`, error.message);
return null;
});
});
});

const responses = await Promise.all(promises);
spatialCoverageNames = responses
.filter(res => res !== null)
.map(res => {
const name = res.data.resource[0]?.node[`name${capitalize(locale)}`] || res.data.resource[0]?.node.name;
return name;
})
.filter(Boolean)
.sort((a, b) => a.localeCompare(b, locale));
const responses = await Promise.all(promises);
spatialCoverageNames = responses
.filter(res => res !== null)
.map(res => {
const name = res.data.resource[0]?.node[`name${capitalize(locale)}`] || res.data.resource[0]?.node.name;
return name;
})
.filter(Boolean)
.sort((a, b) => a.localeCompare(b, locale));
}
}
} catch (error) {
console.error("Fetch error:", error.message);
}

const props = {
...(await serverSideTranslations(locale, ['dataset', 'common', 'menu', 'prices'])),
dataset,
...(allowedURLs.includes(process.env.NEXT_PUBLIC_BASE_URL_FRONTEND) ? {} : { spatialCoverageNames }),
};

return {
props: {
...(await serverSideTranslations(locale, ['dataset', 'common', 'menu', 'prices'])),
dataset,
spatialCoverageNames,
},
props,
revalidate: 30,
};
}
Expand All @@ -91,13 +96,16 @@ export async function getStaticPaths(context) {
}
}

export default function DatasetPage ({ dataset, spatialCoverageNames }) {
export default function DatasetPage ({ dataset, spatialCoverageNames = [] }) {
const { t } = useTranslation('dataset', 'common');
const router = useRouter()
const { locale } = router
const { query } = router
const [tabIndex, setTabIndex] = useState(0)

const allowedURLs = ["https://basedosdados.org", "https://staging.basedosdados.org"]


const isDatasetEmpty = dataset === null || Object.keys(dataset).length === 0

if(isDatasetEmpty) return <MainPageTemplate userTemplate><FourOFour/></MainPageTemplate>
Expand Down Expand Up @@ -236,7 +244,7 @@ export default function DatasetPage ({ dataset, spatialCoverageNames }) {
</Text>
</GridItem>

{process.env.NEXT_PUBLIC_BASE_URL_FRONTEND !== "https://basedosdados.org" &&
{!allowedURLs.includes(process.env.NEXT_PUBLIC_BASE_URL_FRONTEND) &&
<GridItem colSpan={{ base: 5, lg: 3 }} marginBottom="8px">
<Text
fontFamily="Roboto"
Expand Down
4 changes: 3 additions & 1 deletion next/pages/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ export default function SearchDatasetPage() {
const [pageInfo, setPageInfo] = useState({page: 0, count: 0})
const [isLoading, setIsLoading] = useState(true)

const allowedURLs = ["https://basedosdados.org", "https://staging.basedosdados.org"]

async function getDatasets({q, filters, page}) {
const res = await getSearchDatasets({q, filter: filters, page, locale: locale || 'pt'})
if(res === undefined) return router.push({pathname:"500"})
Expand Down Expand Up @@ -664,7 +666,7 @@ export default function SearchDatasetPage() {

<Divider marginY="16px !important" borderColor="#DEDFE0"/>

{process.env.NEXT_PUBLIC_BASE_URL_FRONTEND !== "https://basedosdados.org" ?
{!allowedURLs.includes(process.env.NEXT_PUBLIC_BASE_URL_FRONTEND) ?
<>
<CheckboxFilterAccordion
canSearch={true}
Expand Down
1 change: 1 addition & 0 deletions next/public/locales/en/dataset.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"clearFilters": "Clear filters",
"previous": "Previous",
"next": "Next",
"selectResource": "Select a table or original source",
"datasetCard": {
"table": "table",
"tables": "tables",
Expand Down
1 change: 1 addition & 0 deletions next/public/locales/es/dataset.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"clearFilters": "Limpiar filtros",
"previous": "Anterior",
"next": "Siguiente",
"selectResource": "Seleccione una tabla o fuente original",
"datasetCard": {
"table": "tabla",
"tables": "tablas",
Expand Down
1 change: 1 addition & 0 deletions next/public/locales/pt/dataset.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"clearFilters": "Limpar filtros",
"previous": "Anterior",
"next": "Próxima",
"selectResource": "Selecione uma tabela ou fonte original",
"datasetCard": {
"table": "tabela tratada",
"tables": "tabelas tratadas",
Expand Down

0 comments on commit 675e29f

Please sign in to comment.