Skip to content

Commit

Permalink
Merge pull request #28 from rice-apps/data-storage
Browse files Browse the repository at this point in the history
Data storage
  • Loading branch information
KataTech authored Mar 30, 2024
2 parents c5b97b5 + d5ef67f commit b835560
Show file tree
Hide file tree
Showing 7 changed files with 229 additions and 23 deletions.
9 changes: 8 additions & 1 deletion public/data.json
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
{"stability":0.4,"development":0.66,"healthcare":0.2,"escape":0,"basicNeeds":0,"totalPeople":0}
{
"stability": 0.3,
"development": 0.5,
"healthcare": 0.2,
"escape": 0.1,
"basicNeeds": 0.1,
"totalPeople": 0.4
}
73 changes: 65 additions & 8 deletions src/app/admin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,36 @@

import React, { useState } from "react"

interface FormData {
type dataFields =
| "stability"
| "development"
| "healthcare"
| "escape"
| "basicNeeds"
| "totalPeople"

const data_fields: dataFields[] = [
"stability",
"development",
"healthcare",
"escape",
"basicNeeds",
"totalPeople",
]

type FormData = {
pinNumber: string
}
} & Record<dataFields, number>

function AdminLogin() {
const [formData, setFormData] = useState<FormData>({
pinNumber: "",
stability: 0,
development: 0,
healthcare: 0,
escape: 0,
basicNeeds: 0,
totalPeople: 0,
})

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
Expand All @@ -22,14 +45,24 @@ function AdminLogin() {

const handleFormSubmit = (e: { preventDefault: () => void }) => {
e.preventDefault()
const verifyPIN = async (pin: string) => {
const updateProportions = async (fd: FormData) => {
try {
const res = await fetch(`/api/verify/`, {
const res = await fetch(`/api/update/`, {
method: "Post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ pin: pin }),
body: JSON.stringify({
pin: fd.pinNumber,
data: {
stability: fd.stability,
development: fd.development,
healthcare: fd.healthcare,
escape: fd.escape,
basicNeeds: fd.basicNeeds,
totalPeople: fd.totalPeople,
},
}),
})
if (!res.ok) {
throw new Error(res.statusText)
Expand All @@ -42,7 +75,7 @@ function AdminLogin() {
console.error("Error verifying PIN:", error)
}
}
verifyPIN(formData.pinNumber)
updateProportions(formData)
}

const [password, setPassword] = useState("")
Expand Down Expand Up @@ -112,9 +145,33 @@ function AdminLogin() {
</button>
</div>
</div>
<hr />

<div className="grid grid-cols-3">
{data_fields.map((field) => (
<div className="m-2" key={field}>
<label htmlFor={field}>{field}</label>
<input
type="number"
id={field}
name={field}
value={formData[field]}
onChange={handleInputChange}
placeholder={`Enter ${field}`}
className="input mb-2 input-bordered bg-white w-full mt-3 text-black rounded-3xl font-normal"
min={0}
max={1}
step={0.01}
/>
</div>
))}
</div>

<button className="btn btn-outline self-center w-6/12 m-5 text-black bg-yellow hover:bg-orange rounded-3xl">
Sign in
<button
className="btn btn-outline self-center w-6/12 m-5 text-black bg-yellow hover:bg-orange rounded-3xl"
type="submit"
>
Update Data
</button>
</div>
</form>
Expand Down
14 changes: 2 additions & 12 deletions src/app/api/data/route.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
import { NextResponse } from "next/server"
import * as data from "../../../../public/data.json"

export async function GET(request: Request) {
// the json format:
return NextResponse.json(
{
stability: 0.3,
development: 0.5,
healthcare: 0.2,
escape: 0.1,
basicNeeds: 0.1,
totalPeople: 0.4,
},
{ status: 200 },
)
return NextResponse.json(data, { status: 200 })
}

// { "dollarsRaised": 500000,
Expand Down
143 changes: 143 additions & 0 deletions src/app/api/update/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { Proportions } from "@/app/types"
import { NextResponse } from "next/server"

export async function POST(req: Request) {
const j = await req.json()
console.log(j)

// get the user pin
const userPin = j.pin
// get the password from the env file
const actualPin = process.env.PRIVATE_KEY
const token = process.env.GITHUB_TOKEN

// check if the pin is null
if (userPin === null) {
return NextResponse.json({ response: "No Pin" }, { status: 400 })
}

console.log("pin success")

if (token === null) {
return NextResponse.json({ response: "No Token" }, { status: 500 })
}

console.log("token success")

// compare the
if (actualPin !== userPin) {
return NextResponse.json({ response: "Incorrect Pin" }, { status: 200 })
}

console.log("pin correct")

// get the new data
const json: Proportions = j.data

// check that all the data can be converted to numbers
if (
isNaN(json.stability) ||
isNaN(json.development) ||
isNaN(json.healthcare) ||
isNaN(json.escape) ||
isNaN(json.basicNeeds) ||
isNaN(json.totalPeople)
) {
return NextResponse.json(
{ response: "Invalid data, must be a number" },
{ status: 200 },
)
} else {
json.stability = Number(json.stability)
json.development = Number(json.development)
json.healthcare = Number(json.healthcare)
json.escape = Number(json.escape)
json.basicNeeds = Number(json.basicNeeds)
json.totalPeople = Number(json.totalPeople)
}

console.log("data success")

// check that the data is valid, all numbers between 0 and 1
if (
json.stability < 0 ||
json.stability > 1 ||
json.development < 0 ||
json.development > 1 ||
json.healthcare < 0 ||
json.healthcare > 1 ||
json.escape < 0 ||
json.escape > 1 ||
json.basicNeeds < 0 ||
json.basicNeeds > 1
) {
return NextResponse.json(
{ response: "Invalid data, must be between 0 and 1" },
{ status: 200 },
)
}

console.log("data valid")

const content = Buffer.from(JSON.stringify(json)).toString("base64")

console.log("content success")

// get the sha of the file
const responseSha = await fetch(
"https://api.github.com/repos/rice-apps/united-way/contents/public/data.json",
{
method: "GET",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${token}`,
"X-GitHub-Api-Version": "2022-11-28",
},
},
)

if (!responseSha.ok) {
console.log("error")
console.log(responseSha)
return NextResponse.error()
}

const sha = (await responseSha.json()).sha

console.log("sha success: " + sha)

// send a commit to github
const response = await fetch(
"https://api.github.com/repos/rice-apps/united-way/contents/public/data.json",
{
method: "PUT",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${token}`,
"X-GitHub-Api-Version": "2022-11-28",
},
body: JSON.stringify({
message: "Update proportions",
committer: {
name: "United Way RiceApps",
email: "united-way-bot",
},
sha: sha,
content: content,
}),
},
)

if (!response.ok) {
console.log("error")
console.log(response)
return NextResponse.error()
} else {
console.log("response success")
console.log(response)
return NextResponse.json(
{ response: "Updated proportions" },
{ status: 200 },
)
}
}
3 changes: 2 additions & 1 deletion src/app/donations/Donation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import ImpactCarousel from "./ImpactCarousel"
import { useEffect, useState } from "react"
import { Downloads } from "./Downloads"
import { Proportions } from "../types"

type DonationInputs = {
companyName: string | null
Expand All @@ -19,7 +20,7 @@ function Donation({ companyName, dollarsRaised }: DonationInputs) {
}

// get the proportions
const [proportionsMap, setProportionsMap] = useState(null)
const [proportionsMap, setProportionsMap] = useState<null | Proportions>(null)

useEffect(() => {
GetData()
Expand Down
8 changes: 8 additions & 0 deletions src/app/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export type Proportions = {
stability: number
development: number
healthcare: number
escape: number
basicNeeds: number
totalPeople: number
}
2 changes: 1 addition & 1 deletion tailwind.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const config: Config = {
translate: {
"30": "7.5rem",
},
// can add or overridee styles here
// can add or override styles here
colors: {
blue: "#015191",
purple: "#804B67",
Expand Down

0 comments on commit b835560

Please sign in to comment.