Skip to content

Commit

Permalink
Checkpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
lublagg committed Sep 15, 2023
1 parent 4f69f8e commit a24f45a
Show file tree
Hide file tree
Showing 7 changed files with 195 additions and 26 deletions.
27 changes: 22 additions & 5 deletions src/components/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,22 @@ import classnames from "classnames";
import { Information } from "./information";
import { categories, defaultSelectedOptions } from "./constants";
import { IStateOptions } from "./types";
import { createQueryFromSelections } from "../scripts/api";
import { connect } from "../scripts/connect";


import css from "./app.scss";
import { runTestQuery } from "../scripts/api";

function App() {
const [showInfo, setShowInfo] = useState<boolean>(false);
const [selectedOptions, setSelectedOptions] = useState<IStateOptions>(defaultSelectedOptions);

useEffect(() => {
runTestQuery();
}, [])
const init = async () => {
await connect.initialize();
};
init();
}, []);

const handleSetSelectedOptions = (option: string, value: string | string[]) => {
const newSelectedOptions = {...selectedOptions, [option]: value};
Expand All @@ -25,6 +30,18 @@ function App() {
setShowInfo(true);
};

const handleGetData = () => {
createQueryFromSelections(selectedOptions);

const makeDataSetAndTable = async () => {
const dS = await connect.guaranteeDataset(selectedOptions.geographicLevel);
if (dS.success) {
await connect.makeCaseTableAppear();
}
};
makeDataSetAndTable();
};

return (
<div className={css.pluginContent}>
{ showInfo &&
Expand Down Expand Up @@ -52,12 +69,12 @@ function App() {
handleSetSelectedOptions={handleSetSelectedOptions}
selectedOptions={selectedOptions}
/>
)
);
})}
</div>
<div className={css.summary}>
<span className={css.statusGraphic}></span>
<button className={css.getDataButton}>Get Data</button>
<button className={css.getDataButton} onClick={handleGetData}>Get Data</button>
</div>
</div>

Expand Down
11 changes: 6 additions & 5 deletions src/components/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const stateOptions: IAttrOptions = {
key: "states",
instructions: "Choose states to include in your dataset from the list below",
options: [
"All States",
"Alabama",
"Alaska",
"Arizona",
Expand Down Expand Up @@ -110,21 +111,21 @@ export const yearsOptions: IAttrOptions = {
label: "Years",
options: yearsArray,
instructions: null
}
};

export const categories = [
{header: "Place", options: placeOptions, altText: ""},
{header: "Attributes", options: attributeOptions, altText: ""},
{header: "Years", options: yearsOptions, altText: ""}
]
];

export const defaultSelectedOptions: IStateOptions = {
"geographicLevel": "",
"states": [],
"geographicLevel": "State",
"states": ["All States"],
"farmerDemographics": [],
"farmDemographics": [],
"economicsAndWages": [],
"cropUnits": "",
"crops": [],
"years": []
};
};
2 changes: 1 addition & 1 deletion src/components/dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const Dropdown: React.FC<IProps> = (props) => {
const renderOptions = () => {
return category === "Place" ? <PlaceOptions {...commonProps}/> :
category === "Attributes" ? <AttributeOptions {...commonProps}/> :
<YearsOptions {...commonProps}/>
<YearsOptions {...commonProps}/>;
};

return (
Expand Down
10 changes: 5 additions & 5 deletions src/components/summary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,17 @@ export const Summary: React.FC<IProps> = ({category, selectedOptions}) => {
return null;
}
})
.filter((item) => item !== null)
.filter((item) => item !== null);
const finalString = resultString.join(", ");
return finalString;
} else if (category === "Years") {
return selectedOptions.years.join(", ")
return selectedOptions.years.join(", ");
}
}
};

return (
<div>
{getSummaryText()}
</div>
)
}
);
};
6 changes: 3 additions & 3 deletions src/components/years-options.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ export const YearsOptions: React.FC<IProps> = (props) => {
console.log({selectedYears});

Check warning on line 39 in src/components/years-options.tsx

View workflow job for this annotation

GitHub Actions / Build and Run Jest Tests

Unexpected console statement

Check warning on line 39 in src/components/years-options.tsx

View workflow job for this annotation

GitHub Actions / S3 Deploy

Unexpected console statement
// do something if years are not valid
}
})
});
}
})
});
}
}
};

return (
<div className={css.checkOptions}>
Expand Down
83 changes: 77 additions & 6 deletions src/scripts/api.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,94 @@
import fetchJsonp from "fetch-jsonp";
import { queryData } from "./query-headers";
import { IStateOptions } from "../components/types";
import { connect } from "./connect";

Check warning on line 4 in src/scripts/api.ts

View workflow job for this annotation

GitHub Actions / Build and Run Jest Tests

'connect' is defined but never used

Check warning on line 4 in src/scripts/api.ts

View workflow job for this annotation

GitHub Actions / S3 Deploy

'connect' is defined but never used

const baseURL = `https://quickstats.nass.usda.gov/api/api_GET/?key=9ED0BFB8-8DDD-3609-9940-A2341ED6A9E3`;

export const createRequest = (attribute: string, geoLevel: string, location: string, year: string) => {
const queryParams = queryData.find((d) => d.plugInAttribute === attribute);
const {sector, group, commodity, category, domains, dataItem} = queryParams!;

Check warning on line 10 in src/scripts/api.ts

View workflow job for this annotation

GitHub Actions / Build and Run Jest Tests

Forbidden non-null assertion

Check warning on line 10 in src/scripts/api.ts

View workflow job for this annotation

GitHub Actions / S3 Deploy

Forbidden non-null assertion
const req = `${baseURL}&sect_desc=${sector}&group_desc=${group}&commodity_desc=${commodity}&statisticcat_desc=${category}&domain_desc=${domains}&short_desc=${dataItem}&agg_level_desc=${geoLevel}&state_name=${location}&year=${year}`;
return req;

const baseReq = `${baseURL}&sect_desc=${sector}&group_desc=${group}&commodity_desc=${commodity}&statisticcat_desc=${category}&domain_desc=${domains}&agg_level_desc=${geoLevel}&state_name=${location}&year=${year}`;

Check warning on line 12 in src/scripts/api.ts

View workflow job for this annotation

GitHub Actions / Build and Run Jest Tests

This line has a length of 215. Maximum allowed is 120

Check warning on line 12 in src/scripts/api.ts

View workflow job for this annotation

GitHub Actions / S3 Deploy

This line has a length of 215. Maximum allowed is 120

const reqs = [];

if (Array.isArray(dataItem)) {
dataItem.forEach(item => {
reqs.push(`${baseReq}&short_desc=${item}`);
});
} else {
reqs.push(`${baseReq}&short_desc=${dataItem}`);
}

return reqs;
};

export const createQueryFromSelections = (selectedOptions: IStateOptions) => {
const {geographicLevel, states, years, ...subOptions} = selectedOptions;
const multipleStatesSelected = states.length > 1 || states[0] === "All States";
const multipleYearsSelected = years.length > 1;

if (multipleStatesSelected) {
states.forEach((state) => {
if (multipleYearsSelected) {
years.forEach(year => {
// do something
console.log("multiple years and mulitple states selected");

Check warning on line 37 in src/scripts/api.ts

View workflow job for this annotation

GitHub Actions / Build and Run Jest Tests

Unexpected console statement

Check warning on line 37 in src/scripts/api.ts

View workflow job for this annotation

GitHub Actions / S3 Deploy

Unexpected console statement
});
} else {
console.log("multiple states selected with one year");
}
});
} else {
for (const key in subOptions) {
const value = subOptions[key as keyof typeof subOptions];
console.log("current value", value);
if (value && Array.isArray(value) && value.length > 1) {
console.log("you selected more than one value from a sub-category");
} else if (value && Array.isArray(value) && value.length === 1) {
console.log("you selected only one value from a sub-category and it is this value", value);
const reqArray = createRequest(value[0], geographicLevel, states[0], years[0]);
console.log("REQUEST", reqArray[0]);
getDataAndCreateCodapTable(reqArray);
}
}
}
};

export const runTestQuery = () => {
const request = createRequest("Total Farmers", "STATE", "CALIFORNIA", "2017");
fetchJsonp(request)
export const getDataAndCreateCodapTable = (reqs: string[]) => {
reqs.forEach((req) => {
fetchJsonp(req)
.then(function(response) {
return response.json();
}).then(function(json) {
console.log("parsed json", json);
const formattedData = formatDataForCODAP(json);
}).catch(function(ex) {
console.log("parsing failed", ex);
})
});
});
};

const formatDataForCODAP = (res: any) => {
console.log({res});
return res;
};

// export const runTestQuery = () => {
// const request1 = createRequest("Total Farmers", "STATE", "CALIFORNIA", "2017")[0];
// const request2 = createRequest("Total Farmers", "STATE", "ARKANSAS", "2017")[0];
// const request3 = createRequest("Total Farmers", "STATE", "ALABAMA", "2017")[0];
// const request4 = createRequest("Total Farmers", "STATE", "MONTANA", "2017")[0];
// const requests = [request1, request2, request3, request4];
// requests.forEach((req) => {
// fetchJsonp(req)
// .then(function(response) {
// return response.json();
// }).then(function(json) {
// console.log("parsed json", json);
// }).catch(function(ex) {
// console.log("parsing failed", ex);
// })
// })
// };
82 changes: 81 additions & 1 deletion src/scripts/connect.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,90 @@
import { codapInterface } from "./codapInterface";

const dataSetName = "NASS Quickstats Data";
const dataSetTitle = "NASS Quickstats Data";

export const connect = {
initialize: async function () {
return await codapInterface.init(this.iFrameDescriptor, null);
},

makeCODAPAttributeDef: function (attr) {
return {
name: attr.title,
title: attr.title,
description: attr.description,
type: attr.format,
formula: attr.formula
}
},

createNewDataset: async function (geoLevel) {
const geoLabel = geoLevel === "State" ? "States" : "Counties";
return codapInterface.sendRequest({
action: 'create',
resource: 'dataContext',
values: {
name: dataSetName,
title: dataSetTitle,
collections: [{
name: geoLabel,
attrs: [
{
name: geoLevel,
title: geoLevel,
description: `Selected ${geoLabel}`
},
{
name: "Boundaries",
title: "Boundaries",
formula: 'lookupBoundary(US_state_boundaries, State)',
formulaDependents: 'State'
}
]
}, {
name: "Data",
parent: geoLabel,
attrs: [ // note how this is an array of objects.
{name: "Year", title: "Year"}
]
}]
}
});
},


guaranteeDataset: async function (geoLevel) {
let datasetResource = 'dataContext[' + dataSetName +
']';
await this.createNewDataset(geoLevel);
const response = await codapInterface.sendRequest({
action: 'get',
resource: datasetResource});
return response;
},

makeCaseTableAppear : async function() {
const theMessage = {
action : "create",
resource : "component",
values : {
type : 'caseTable',
dataContext : dataSetName,
name : dataSetName,
title: dataSetName,
cannotClose : true
}
};

const makeCaseTableResult = await codapInterface.sendRequest(theMessage);
if (makeCaseTableResult.success) {
console.log("Success creating case table: " + theMessage.title);
} else {
console.log("FAILED to create case table: " + theMessage.title);
}
return makeCaseTableResult.success && makeCaseTableResult.values.id;
},

createNewCollection: async function(dSName, collName) {
const message = {
"action": "create",
Expand Down Expand Up @@ -33,6 +113,6 @@ export const connect = {
iFrameDescriptor: {
version: '0.0.1',
name: 'nass-plugin',
title: 'MultiData'
title: 'NASS Quickstats Data'
},
}

0 comments on commit a24f45a

Please sign in to comment.