Skip to content

Commit

Permalink
Merge pull request #452 from Vizzuality/fix/wdpa-flow
Browse files Browse the repository at this point in the history
WDPA: read them from scenario instead of store in certain cases
  • Loading branch information
mbarrenechea authored Aug 16, 2021
2 parents aaf2ebc + 753c435 commit 9be9a4d
Show file tree
Hide file tree
Showing 23 changed files with 186 additions and 142 deletions.
1 change: 1 addition & 0 deletions app/hoc/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { QueryClient } from 'react-query';

import { getSession } from 'next-auth/client';
import { dehydrate } from 'react-query/hydration';

import PROJECTS from 'services/projects';

import { mergeDehydratedState } from './utils';
Expand Down
71 changes: 71 additions & 0 deletions app/hoc/scenarios.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { QueryClient } from 'react-query';

import { getSession } from 'next-auth/client';
import { dehydrate } from 'react-query/hydration';

import SCENARIOS from 'services/scenarios';

import { mergeDehydratedState } from './utils';

export function withScenario(getServerSidePropsFunc?: Function) {
return async (context: any) => {
const session = await getSession(context);

if (!session) {
if (getServerSidePropsFunc) {
const SSPF = await getServerSidePropsFunc(context) || {};

return {
props: {
...SSPF.props,
},
};
}

return {
props: {},
};
}

const { params } = context;

const { sid } = params;

const queryClient = new QueryClient();

await queryClient.prefetchQuery(['scenarios', sid], () => SCENARIOS.request({
method: 'GET',
url: `/${sid}`,
headers: {
Authorization: `Bearer ${session.accessToken}`,
},
}).then((response) => {
return response.data;
}));

if (getServerSidePropsFunc) {
const SSPF = await getServerSidePropsFunc(context) || {};

const { dehydratedState: prevDehydratedState } = SSPF.props;
const currentDehydratedState = JSON.parse(JSON.stringify(dehydrate(queryClient)));

const newDehydratedState = mergeDehydratedState(prevDehydratedState, currentDehydratedState);

return {
...SSPF,
props: {
session,
...SSPF.props,
dehydratedState: newDehydratedState,
},
};
}

return {
props: {
session,
dehydratedState: JSON.parse(JSON.stringify(dehydrate(queryClient))),
},
};
};
}
6 changes: 3 additions & 3 deletions app/hooks/gap-analysis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,13 @@ export function useGapAnalysis(sId, options: UseFeaturesOptionsProps = {}) {
return pageData.map((d):AllItemProps => {
const {
id,
alias,
featureClassName,
name,
} = d;

// TODO: use data from API
return {
id,
name: alias || featureClassName,
name,
current: {
percent: 0.5,
value: 400,
Expand Down
42 changes: 23 additions & 19 deletions app/hooks/map/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ export function usePUGridPreviewLayer({

// PUGrid
export function usePUGridLayer({
active, sid, type, subtype, runId, options = {}, cache,
active, sid, type, subtype, options = {}, cache,
}: UsePUGridLayer) {
const include = useMemo(() => {
if (type === 'protected-areas' || type === 'features') return 'protection';
Expand All @@ -259,6 +259,7 @@ export function usePUGridLayer({
wdpaThreshold = 0,
puIncludedValue,
puExcludedValue,
runId,
} = options;

return {
Expand Down Expand Up @@ -290,24 +291,28 @@ export function usePUGridLayer({
},

// PROTECTED AREAS
...(type === 'protected-areas' && subtype === 'protected-areas-percentage') || type === 'features' ? [
{
type: 'fill',
'source-layer': 'layer0',
paint: {
'fill-color': COLORS.wdpa,
'fill-opacity': [
'case',
['all',
['has', 'percentageProtected'],
['>=', ['get', 'percentageProtected'], (wdpaThreshold * 100)],
...(
type === 'protected-areas' && subtype === 'protected-areas-percentage')
|| type === 'features'
|| (type === 'analysis' && subtype === 'analysis-preview'
) ? [
{
type: 'fill',
'source-layer': 'layer0',
paint: {
'fill-color': COLORS.wdpa,
'fill-opacity': [
'case',
['all',
['has', 'percentageProtected'],
['>=', ['get', 'percentageProtected'], (wdpaThreshold)],
],
0.5,
0,
],
0.5,
0,
],
},
},
},
] : [],
] : [],

// ANALYSIS - GAP ANALYSIS
...type === 'analysis' && subtype === 'analysis-gap-analysis' ? [
Expand Down Expand Up @@ -419,11 +424,10 @@ export function usePUGridLayer({
},
},
] : [],

],
},
};
}, [cache, active, sid, type, subtype, runId, options, include]);
}, [cache, active, sid, type, subtype, options, include]);
}

// PUGrid
Expand Down
2 changes: 2 additions & 0 deletions app/hooks/map/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export interface UsePUGridLayer {
puAction?: string;
puIncludedValue?: string[];
puExcludedValue?: string[];
runId?: string;
};
}

Expand All @@ -75,5 +76,6 @@ export interface UseLegend {
puAction?: string;
puIncludedValue?: string[];
puExcludedValue?: string[];
runId?: string;
};
}
31 changes: 9 additions & 22 deletions app/hooks/solutions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export function useSolutions(sid, options: UseSolutionsOptionsProps = {}) {

return {
id,
run: runId,
runId,
score: scoreValue,
cost: costValue,
planningUnits,
Expand All @@ -94,7 +94,7 @@ export function useSolutions(sid, options: UseSolutionsOptionsProps = {}) {
export function useSolution(sid, solutionId) {
const [session] = useSession();

const query = useQuery(['scenarios', sid, solutionId], async () => SCENARIOS.request({
const query = useQuery(['solution-id', sid, solutionId], async () => SCENARIOS.request({
method: 'GET',
url: `/${sid}/marxan/solutions/${solutionId}`,
headers: {
Expand All @@ -116,36 +116,23 @@ export function useSolution(sid, solutionId) {
}, [query, data?.data]);
}

export function useMostDifferentSolutions(sid, options: UseSolutionsOptionsProps = {}) {
export function useMostDifferentSolutions(sid) {
const [session] = useSession();

const {
filters = {},
} = options;

const parsedFilters = Object.keys(filters)
.reduce((acc, k) => {
return {
...acc,
[`filter[${k}]`]: filters[k],
};
}, {});

const query = useQuery(['scenarios', sid], async () => SCENARIOS.request({
const query = useQuery(['solutions-different', sid], async () => SCENARIOS.request({
method: 'GET',
url: `/${sid}/marxan/solutions/most-different`,
headers: {
Authorization: `Bearer ${session.accessToken}`,
},
params: {
...parsedFilters,
},
}).then((response) => {
return response.data;
}));

const { data } = query;

return useMemo(() => {
const parsedData = Array.isArray(data.data.data) ? data.data.data.map((d) => {
const parsedData = Array.isArray(data?.data) ? data.data.map((d) => {
const {
id,
runId,
Expand All @@ -157,7 +144,7 @@ export function useMostDifferentSolutions(sid, options: UseSolutionsOptionsProps

return {
id,
run: runId,
runId,
score: scoreValue,
cost: costValue,
planningUnits,
Expand All @@ -175,7 +162,7 @@ export function useMostDifferentSolutions(sid, options: UseSolutionsOptionsProps
export function useBestSolution(sid) {
const [session] = useSession();

const query = useQuery(['scenarios', sid], async () => SCENARIOS.request({
const query = useQuery(['solutions-best', sid], async () => SCENARIOS.request({
method: 'GET',
url: `/${sid}/marxan/solutions/best`,
headers: {
Expand Down
6 changes: 3 additions & 3 deletions app/hooks/solutions/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,23 @@ import { Solution } from 'types/project-model';
const ITEMS: Solution[] = [
{
id: '1',
run: 1,
runId: 1,
score: 5,
cost: 100,
planningUnits: 10,
missingValues: 0,
},
{
id: '2',
run: 2,
runId: 2,
score: 10,
cost: 10,
planningUnits: 1,
missingValues: 30,
},
{
id: '3',
run: 3,
runId: 3,
score: 3,
cost: 13,
planningUnits: 3,
Expand Down
4 changes: 2 additions & 2 deletions app/layout/scenarios/edit/features/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useRouter } from 'next/router';
import { getScenarioEditSlice } from 'store/slices/scenarios/edit';

import { motion } from 'framer-motion';
import { mergeScenarioStatusMetaData, SCENARIO_EDITING_META_DATA_DEFAULT_VALUES } from 'utils/utils-scenarios';
import { mergeScenarioStatusMetaData } from 'utils/utils-scenarios';

import { useSelectedFeatures } from 'hooks/features';
import { useScenario, useSaveScenario } from 'hooks/scenarios';
Expand Down Expand Up @@ -56,7 +56,7 @@ export const ScenariosSidebarEditFeatures: React.FC<ScenariosSidebarEditFeatures
const { scenarioEditingMetadata } = metadata || {};
const {
subtab: metaSubtab,
} = scenarioEditingMetadata || SCENARIO_EDITING_META_DATA_DEFAULT_VALUES;
} = scenarioEditingMetadata;

const {
data: selectedFeaturesData,
Expand Down
14 changes: 10 additions & 4 deletions app/layout/scenarios/edit/map/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
useWDPAPreviewLayer, usePUGridLayer, useFeaturePreviewLayers, useLegend,
} from 'hooks/map';
import { useProject } from 'hooks/projects';
import { useScenario } from 'hooks/scenarios';

import ScenariosDrawingManager from 'layout/scenarios/edit/map/drawing-manager';

Expand Down Expand Up @@ -46,6 +47,10 @@ export const ScenariosEditMap: React.FC<ScenariosEditMapProps> = () => {
const { data = {} } = useProject(pid);
const { bbox } = data;

const {
data: scenarioData,
} = useScenario(sid);

const {
data: selectedFeaturesData,
} = useSelectedFeatures(sid, {});
Expand All @@ -59,6 +64,7 @@ export const ScenariosEditMap: React.FC<ScenariosEditMapProps> = () => {
tab,
subtab,
cache,

// WDPA
wdpaCategories,
wdpaThreshold,
Expand Down Expand Up @@ -101,8 +107,8 @@ export const ScenariosEditMap: React.FC<ScenariosEditMapProps> = () => {
type: tab,
subtype: subtab,
options: {
...wdpaCategories,
wdpaThreshold,
wdpaIucnCategories: tab === 'protected-areas' && subtab === 'protected-areas-preview' ? wdpaCategories.wdpaIucnCategories : scenarioData.wdpaIucnCategories,
wdpaThreshold: tab === 'protected-areas' && subtab === 'protected-areas-percentage' ? wdpaThreshold * 100 : scenarioData.wdpaThreshold,
puAction,
puIncludedValue: puTmpIncludedValue,
puExcludedValue: puTmpExcludedValue,
Expand All @@ -115,8 +121,8 @@ export const ScenariosEditMap: React.FC<ScenariosEditMapProps> = () => {
type: tab,
subtype: subtab,
options: {
...wdpaCategories,
wdpaThreshold,
wdpaIucnCategories: tab === 'protected-areas' && subtab === 'protected-areas-preview' ? wdpaCategories.wdpaIucnCategories : scenarioData.wdpaIucnCategories,
wdpaThreshold: tab === 'protected-areas' && subtab === 'protected-areas-percentage' ? wdpaThreshold : scenarioData.wdpaThreshold,
puAction,
puIncludedValue: puTmpIncludedValue,
puExcludedValue: puTmpExcludedValue,
Expand Down
3 changes: 1 addition & 2 deletions app/layout/scenarios/edit/run/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { useRouter } from 'next/router';

import cx from 'classnames';
import { usePlausible } from 'next-plausible';
import { SCENARIO_EDITING_META_DATA_DEFAULT_VALUES } from 'utils/utils-scenarios';

import { useMe } from 'hooks/me';
import { useProject } from 'hooks/projects';
Expand Down Expand Up @@ -44,7 +43,7 @@ export const ScenariosRun: React.FC<ScenariosRunProps> = () => {

const { data: scenarioData } = useScenario(sid);
const { metadata } = scenarioData || {};
const { scenarioEditingMetadata = SCENARIO_EDITING_META_DATA_DEFAULT_VALUES } = metadata || {};
const { scenarioEditingMetadata } = metadata || {};

const saveScenarioMutation = useSaveScenario({
requestConfig: {
Expand Down
Loading

0 comments on commit 9be9a4d

Please sign in to comment.