calculate new points

This commit is contained in:
2024-09-14 16:01:51 +02:00
parent 7abc593186
commit 466981457d
3 changed files with 72 additions and 8 deletions

View File

@ -2,8 +2,9 @@ import express from "express";
import ejs from "ejs";
import multer from "multer";
import { db } from "./database/db";
import { eq, sql, sum } from "drizzle-orm";
import { eq, sql } from "drizzle-orm";
import { personTable, pointsTable } from "./database/schema";
import calculateNewPoints from "./gambleMath";
const app = express();
const port = 8080;
@ -15,8 +16,7 @@ app.use(express.static('www'));
app.get("/", async (req, res) => {
const people = await db.select({
personId: personTable.personId,
name: personTable.name,
pointsTotal: sql`coalesce(sum(${pointsTable.points}), 0)`
name: personTable.name
}).from(personTable)
.leftJoin(pointsTable, eq(personTable.personId, pointsTable.personId))
.groupBy(personTable.personId)
@ -103,9 +103,16 @@ app.post("/gamble/:id", upload.none(), async (req, res) => {
return;
}
let person = await db.query.personTable.findFirst({
where: eq(personTable.personId, id)
})
let person = (await db.select({
personId: personTable.personId,
name: personTable.name,
secret: personTable.secret,
gambleTime: personTable.gambleTime,
pointsTotal: sql<string>`coalesce(sum(${pointsTable.points}), 0)`
}).from(personTable)
.leftJoin(pointsTable, eq(personTable.personId, pointsTable.personId))
.where(eq(personTable.personId, id))
.groupBy(personTable.personId))[0];
if (!person) {
res.status(404).send("Invalid person id");
@ -122,6 +129,10 @@ app.post("/gamble/:id", upload.none(), async (req, res) => {
return;
}
let currentPoints = parseInt(person.pointsTotal);
let newTotalPoints = calculateNewPoints(currentPoints);
let pointsDiff = newTotalPoints - currentPoints;
await db.update(personTable)
.set({
gambleTime: sql`NOW()`
@ -130,7 +141,7 @@ app.post("/gamble/:id", upload.none(), async (req, res) => {
await db.insert(pointsTable).values({
personId: id,
points: req.body['points']
points: pointsDiff
})
res.redirect('/person/' + id);