Skip to content

Commit

Permalink
Begin Uploading Draft Plants
Browse files Browse the repository at this point in the history
  • Loading branch information
max.tyson committed Jun 10, 2024
1 parent 088797a commit fa1ccc0
Show file tree
Hide file tree
Showing 7 changed files with 160 additions and 10 deletions.
33 changes: 33 additions & 0 deletions scripts/data/upload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Read the data from the JSON file
import json
import os
import requests

DATA = "out/sortnames.json"
API = "http://localhost:3000/api/plants/testplant"

def main():
data = json.load(open(DATA, "r", encoding="utf-8"))

sql = ""

for i in data:
english_name = "scientific"
maori_name = ""
latin_name = i["scientific"]
preferred_name = "Latin"

if len(i["english"]) > 0:
english_name = ','.join(i["english"]).title()
preferred_name = "English"

if len(i["moari"]) > 0:
maori_name = ','.join(i["moari"]).title()
preferred_name = "Maori"

# Make a request to the API posting the data
sql += f"INSERT INTO plants ( preferred_name, english_name, maori_name, latin_name, location_found, small_description, long_description, author, last_modified, display_image, plant_type, published) VALUES ( '{preferred_name}', '{english_name}', '{maori_name}', '{latin_name}', 'Forest', 'Not Published - Change This', 'Not Published - Change This', '2', FROM_UNIXTIME(1717988479818 / 1000.0), 'Deafult', 'Plant', 1) ;DROP TABLE IF EXISTS new_plant; CREATE TEMPORARY TABLE new_plant AS ( SELECT id FROM plants ORDER BY id DESC LIMIT 1 ); SELECT id FROM new_plant;



main()
2 changes: 1 addition & 1 deletion website/src/pages/api/plants/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export default async function handler(
}


query += ` ${selector} (english_name LIKE '${name}%' OR maori_name LIKE '${name}%' OR latin_name LIKE '${name}%')`;
query += ` ${selector} (english_name LIKE '${name}%' OR maori_name LIKE '${name}%' OR latin_name LIKE '${name}%') AND ${tables.published} = 1`;
selector = "AND";
}

Expand Down
108 changes: 108 additions & 0 deletions website/src/pages/api/plants/testplant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// noinspection SpellCheckingInspection

import {NextApiRequest, NextApiResponse} from 'next';
import {getClient, getTables, makeQuery} from "@/lib/databse";
import {USE_POSTGRES} from "@/lib/constants";
import {getServerSession} from "next-auth";
import {authOptions} from "@/pages/api/auth/[...nextauth]";
import {checkApiPermissions} from "@/lib/api_tools";
import { Logger } from 'next-axiom';

export default async function handler(
request: NextApiRequest,
response: NextApiResponse,
) {

// Get the logger
const logger = new Logger()

// If the request is not a POST request, return an error
if(request.method !== 'POST') {
return response.status(405).json({ error: 'Method not allowed, please use POST' });
}

// Get the client
const client = await getClient()


// Try uploading the data to the database
try {
let {
preferred_name,
english_name,
maori_name,
latin_name,

} = request.body;

// Check if the data is being downloaded from the Postgres database
const tables = getTables()

let insertQuery = "";
let insetQueryValues = "";
let getIDQuery = "(SELECT id FROM new_plant)";
const timeFunction = USE_POSTGRES ? "to_timestamp" : "FROM_UNIXTIME";

// Remove any ' from the strings
preferred_name = preferred_name.replace(/'/g, "");
english_name = english_name.replace(/'/g, "");
maori_name = maori_name.replace(/'/g, "");
latin_name = latin_name.replace(/'/g, "");

// Create the query
let query = ``;

// Add the information for the plant data
query += `INSERT INTO plants (${insertQuery} ${tables.preferred_name}, ${tables.english_name}, ${tables.maori_name}, ${tables.latin_name}, ${tables.location_found}, ${tables.small_description}, ${tables.long_description}, ${tables.author}, ${tables.last_modified}, ${tables.display_image}, ${tables.plant_type}, ${tables.published}) `;
query += `VALUES (${insetQueryValues} '${preferred_name}', '${english_name}', '${maori_name}', '${latin_name}', 'Forest', 'Not Published - Change This', 'Not Published - Change This', '2', ${timeFunction}(${Date.now()} / 1000.0), 'Deafult', 'Plant', 1) ${USE_POSTGRES ? "RETURNING id" : ""};`;

// Create a temporary table to hold the new plant id
query += `DROP TABLE IF EXISTS new_plant; CREATE TEMPORARY TABLE new_plant AS ( SELECT id FROM plants ORDER BY id DESC LIMIT 1 ); ${!USE_POSTGRES ? "SELECT id FROM new_plant;" : ""}`;


console.log(query);

// Run the query
const data = await makeQuery(query, client, true)

if(!data)
return response.status(500).json({ error: "No data returned" });

// Get the id of the new plant
// @ts-ignore (has to be like this data[0] is an object)
let id = undefined

if(USE_POSTGRES){
id = data[0].rows[0].id;
}else{

// Loop through the data
data.forEach((item: any) => {

// If there is an id, set it
if (item[0] && item[0].id) {
id = item[0].id;
}
});
}


// If there is no id, return an error
if(!id) {
return response.status(500).json({ error: "Error creating plant (id not returned)" });
}


// Log the upload
logger.info(`Plant ${id} created by ${session?.user?.email}`);

return response.status(200).json({ message: "Upload Successful", id: id });
} catch (error) {
return response.status(500).json({message: "ERROR IN SERVER", error: error });
} finally {

if(USE_POSTGRES)
await client.end();

}
}
4 changes: 2 additions & 2 deletions website/src/pages/api/plants/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ export default async function handler(
let query = ``;

// Add the information for the plant data
query += `INSERT INTO plants (${insertQuery} ${tables.preferred_name}, ${tables.english_name}, ${tables.maori_name}, ${tables.latin_name}, ${tables.location_found}, ${tables.small_description}, ${tables.long_description}, ${tables.author}, ${tables.last_modified}, ${tables.display_image}, ${tables.plant_type}) `;
query += `VALUES (${insetQueryValues} '${preferred_name}', '${english_name}', '${maori_name}', '${latin_name}', '${location_found}', '${small_description}', '${long_description}', '${author}', ${timeFunction}(${Date.now()} / 1000.0), '${display_image}', '${plant_type}') ${USE_POSTGRES ? "RETURNING id" : ""};`;
query += `INSERT INTO plants (${insertQuery} ${tables.preferred_name}, ${tables.english_name}, ${tables.maori_name}, ${tables.latin_name}, ${tables.location_found}, ${tables.small_description}, ${tables.long_description}, ${tables.author}, ${tables.last_modified}, ${tables.display_image}, ${tables.plant_type}, ${tables.published}) `;
query += `VALUES (${insetQueryValues} '${preferred_name}', '${english_name}', '${maori_name}', '${latin_name}', '${location_found}', '${small_description}', '${long_description}', '${author}', ${timeFunction}(${Date.now()} / 1000.0), '${display_image}', '${plant_type}', 0) ${USE_POSTGRES ? "RETURNING id" : ""};`;

// Create a temporary table to hold the new plant id
query += `DROP TABLE IF EXISTS new_plant; CREATE TEMPORARY TABLE new_plant AS ( SELECT id FROM plants ORDER BY id DESC LIMIT 1 ); ${!USE_POSTGRES ? "SELECT id FROM new_plant;" : ""}`;
Expand Down
8 changes: 5 additions & 3 deletions website/src/pages/plants/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ export default function Plants(){
<p className={styles.subtitle}> To search for a specific plant, use the search page or the plant
index page. </p>

<QueryClientProvider client={queryClient}>
<InfiniteLoading searchQuery={"/api/plants/search?mushrooms=exclude"} display={"PlantCardApi"}/>
</QueryClientProvider>
<div className={styles.mushroomContainer}>
<QueryClientProvider client={queryClient}>
<InfiniteLoading searchQuery={"/api/plants/search?mushrooms=exclude"} display={"PlantCardApi"}/>
</QueryClientProvider>
</div>
</Layout>
</>
)
Expand Down
10 changes: 6 additions & 4 deletions website/src/pages/plants/mushrooms.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ export default function Mushrooms(){
<h1 className={styles.title}>All Mushrooms</h1>
<p className={styles.subtitle}> To search for a specific mushroom, use the search page. </p>

<QueryClientProvider client={queryClient}>
<InfiniteLoading searchQuery={"/api/plants/search?mushrooms=only"} display={"PlantCardApi"}/>
</QueryClientProvider>
<div className={styles.mushroomContainer}>
<QueryClientProvider client={queryClient}>
<InfiniteLoading searchQuery={"/api/plants/search?mushrooms=only"} display={"PlantCardApi"}/>
</QueryClientProvider>
</div>
</Layout>
</>
)
)
}
5 changes: 5 additions & 0 deletions website/src/styles/components/infiniteloading.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
padding: 10px;
border-radius: 10px;
box-shadow: 0 4px 4px var(--shadow-less);

/* Span across 3 cols */
grid-column-start: 1;
grid-column-end: 4;

}

@media only screen and (max-width: 1400px) {
Expand Down

0 comments on commit fa1ccc0

Please sign in to comment.