Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#27 and #34- store each suggestion with unique id and alter sentences table - Appolin Semegni Fotso #38

Merged
merged 12 commits into from
Oct 12, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 33 additions & 12 deletions client/src/components/PopUpAlert.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const Alert = React.forwardRef(function Alert(props, ref) {
return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});

export default function PopUpAlert({ text }) {
export default function PopUpAlert(props) {
const [open, setOpen] = React.useState(false);

const handleClick = () => {
Expand All @@ -24,15 +24,36 @@ export default function PopUpAlert({ text }) {
};

return (
<Stack spacing={1} sx={{ width: "100%" }}>
<Button color="success" variant="contained" onClick={handleClick}>
{text}
</Button>
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
<Alert onClose={handleClose} severity="success" sx={{ width: "100%" }}>
Suggestion saved successfully.
</Alert>
</Snackbar>
</Stack>
);
<Stack spacing={1} sx={{ width: "100%" }}>
<Button
color="success"
variant="contained"
onClick={() => {
props.submitButton();
handleClick();
}}
>
{props.text}
</Button>
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
{props.message === "Suggestions saved successfully" ? (
<Alert
onClose={handleClose}
severity="success"
sx={{ width: "100%" }}
>
Suggestions saved successfully
</Alert>
) : (
<Alert
onClose={handleClose}
severity="error"
sx={{ width: "100%" }}
>
Could not saved suggestion
</Alert>
)}
</Snackbar>
</Stack>
);
}
48 changes: 27 additions & 21 deletions client/src/pages/SubmitSuggestion.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,36 @@
import PopUpAlert from "../components/PopUpAlert";

import { useState } from "react";
const SubmitSuggestion = (props) => {
const [messageAfterPost, setMessageAfterPost] = useState("");
const submitButton = () => {
const jsonData = {
sentence: props.randomText,
suggestions: props.suggestionsText,
selectedSuggestion: props.selectedSuggestion,
};

fetch("/api/save-suggestions", {
method: "POST",
body: JSON.stringify(jsonData),
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
})
.then((res) => res.json())
.then((data) => {
setMessageAfterPost(data.message);
console.log(data.message);
});
let randomNumber = Math.random() * 1000;
props.setNextOriginalText(randomNumber);
};
return (
<div className="flex-end">
<PopUpAlert text={"Submit Suggestion"}
className="width submit"
onClick={() => {
const data = new URLSearchParams();
data.append("sentence", props.randomText);
data.append("suggestions", props.suggestionsText);
data.append("selectedSuggestion", props.selectedSuggestion);

fetch("/api/save-suggestions", {
method: "POST",
body: data,
headers: {
"Access-Control-Allow-Origin" : "*",
},
})
.then((res) => res.json())
.then((data) => {
console.log(data.message);
});
let randomNumber = Math.random() * 1000;
props.setNextOriginalText(randomNumber);
}}
submitButton={submitButton}
message = {messageAfterPost}
/>
</div>
);
Expand Down
41 changes: 20 additions & 21 deletions server/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,22 @@ const fs = require("fs/promises");

const router = Router();

router.get("/", (_, res) => {
router.get("/", async(_, res) => {
logger.debug("Welcoming everyone...");
const text = [
"Bhiodh iad a' dèanamh móran uisge-bheatha bho chionn fhada ro n a latha againn.",
"Tha iad ris an Gearrloch fhathast.",
"Well, chuala mi gun robh iad ris an Gearrloch a sin.",
"Bha iad a' faicinn bòcan shios ann an Arasaig.",
"agus 's e a'chiad rud a bha iad a' faicinn dhe'n rud colainn gun cheann a' falbh feadh siod.",
"agus bha bodach a' fuireach ann a' sabhall.",
"Chuir iad duine ann a' sabhall a dh' fhuireach oidhche.",
"agus chunnaic e am bòcan a bha seo agus an bòcan bhitheadh aige.",
"agus tha obair uamhasach aige mun d' fhuair e am bòcan a chumail bhuaidh.",
"agus bha coltas air gun deànadh am bòcan an gróthach air.",
"Cha robh buille a bhuaileadh e air nach robh e a' smaoineach' gur h- ann air póca cloìmh leis cho bog 's a bha a' bhuille is cha robh i a' dèanadh feum.",
];

const getRandomIndex = (length) => {
return Math.floor(Math.random() * length);
};
res.json(text[getRandomIndex(text.length)]);
// Select sentences from sentences table
const sentences = await db.query(
"SELECT sentence FROM sentences WHERE count >= 1"
sztupy marked this conversation as resolved.
Show resolved Hide resolved
);
const randomSentences = [];
for (let sentence of sentences.rows) {
randomSentences.push(sentence.sentence);
}
// const randomSentence = sentences.rows[getRandomIndex(sentences.rows.length)];
res.json(randomSentences[getRandomIndex(randomSentences.length)]);
});

router.post("/save-suggestions", async (req, res) => {
Expand All @@ -33,18 +30,20 @@ router.post("/save-suggestions", async (req, res) => {
try {
// Check if all data exist in req.body
if (sentence && suggestions && selectedSuggestion) {
// Insert the sentence into the sentences table
// Select id from sentences table
const sentenceResult = await db.query(
"INSERT INTO sentences (sentence) VALUES ($1) RETURNING id",
"SELECT id FROM sentences WHERE sentence = $1",
[sentence]
);
const sentenceId = sentenceResult.rows[0].id;

// Insert the suggestions into the suggestions table
await db.query(
"INSERT INTO suggestions (sentence_id, suggestion) VALUES ($1, $2)",
[sentenceId, suggestions]
);
for (const suggestion of suggestions) {
await db.query(
"INSERT INTO suggestions (sentence_id, suggestion) VALUES ($1, $2)",
[sentenceId, suggestion]
);
}
// for (const suggestion of suggestions) {
// }
// Insert selected suggestion to user_interactions table
Expand Down
42 changes: 42 additions & 0 deletions server/db-schema.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@

/* gla6-fp-team1 week 1 Investigate the database schema ticket*/

sentences {
id INT PK,
sentence TEXT,
source TEXT,
count INT

}

sentences--0NE ||--MANY{ suggesions : have}

suggesions {
id INT PK,
sentence_id INT REFERENCES sentences(id),
suggestion TEXT

}
suggesions --ONE || --ONE { sentence : correspond to}
user_interactions{
id SERIAL PRIMARY KEY,
sentence_id INTEGER REFERENCES sentences(id),
selected_suggestion TEXT,
user_provided_suggestion TEXT
}
user_interactions --ONE || ONE {sentence : correspond to}
CREATE TABLE sentences (
id SERIAL PRIMARY KEY,
sentence TEXT
);
CREATE TABLE suggestions (
id SERIAL PRIMARY KEY,
sentence_id INTEGER REFERENCES sentences(id),
suggestion TEXT
);
CREATE TABLE user_interactions (
id SERIAL PRIMARY KEY,
sentence_id INTEGER REFERENCES sentences(id),
selected_suggestion TEXT,
user_provided_suggestion TEXT
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whenever you update the schema it is also customary to provide update scripts - otherwise people will need to delete and re-create the database from scratch. This is not a problem right now, but could become an issue in the future once the project is live

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also we should provide some test data - a couple of INSERT INTOs of the existing sentence data for example to make sure we have enough data to start with. Something like

INSERT INTO sentences (sentence) VALUES ('Tha iad ris an Gearrloch fhathast.');