99 lines
3.1 KiB
TypeScript
99 lines
3.1 KiB
TypeScript
import { FastifyInstance } from "fastify";
|
|
import {and, desc, eq} from "drizzle-orm";
|
|
import {authProfiles, devices, stafftimeevents} from "../../../db/schema";
|
|
|
|
export default async function devicesRFIDRoutes(server: FastifyInstance) {
|
|
server.post(
|
|
"/rfid/createevent/:terminal_id",
|
|
async (req, reply) => {
|
|
try {
|
|
|
|
const {rfid_id} = req.body as {rfid_id: string};
|
|
const {terminal_id} = req.params as {terminal_id: string};
|
|
|
|
if(!rfid_id ||!terminal_id) {
|
|
console.log(`Missing Params`);
|
|
return reply.code(400).send(`Missing Params`)
|
|
}
|
|
|
|
const device = await server.db
|
|
.select()
|
|
.from(devices)
|
|
.where(
|
|
eq(devices.externalId, terminal_id)
|
|
|
|
)
|
|
.limit(1)
|
|
.then(rows => rows[0]);
|
|
|
|
if(!device) {
|
|
console.log(`Device ${terminal_id} not found`);
|
|
return reply.code(400).send(`Device ${terminal_id} not found`)
|
|
|
|
}
|
|
|
|
const profile = await server.db
|
|
.select()
|
|
.from(authProfiles)
|
|
.where(
|
|
and(
|
|
eq(authProfiles.tenant_id, device.tenant),
|
|
eq(authProfiles.token_id, rfid_id)
|
|
)
|
|
)
|
|
.limit(1)
|
|
.then(rows => rows[0]);
|
|
|
|
if(!profile) {
|
|
console.log(`Profile for Token ${rfid_id} not found`);
|
|
return reply.code(400).send(`Profile for Token ${rfid_id} not found`)
|
|
|
|
}
|
|
|
|
const lastEvent = await server.db
|
|
.select()
|
|
.from(stafftimeevents)
|
|
.where(
|
|
eq(stafftimeevents.user_id, profile.user_id)
|
|
)
|
|
.orderBy(desc(stafftimeevents.eventtime)) // <-- Sortierung: Neuestes zuerst
|
|
.limit(1)
|
|
.then(rows => rows[0]);
|
|
|
|
console.log(lastEvent)
|
|
|
|
|
|
const dataToInsert = {
|
|
tenant_id: device.tenant,
|
|
user_id: profile.user_id,
|
|
actortype: "system",
|
|
eventtime: new Date(),
|
|
eventtype: lastEvent.eventtype === "work_start" ? "work_end" : "work_start",
|
|
source: "WEB"
|
|
}
|
|
|
|
console.log(dataToInsert)
|
|
|
|
const [created] = await server.db
|
|
.insert(stafftimeevents)
|
|
//@ts-ignore
|
|
.values(dataToInsert)
|
|
.returning()
|
|
|
|
return created
|
|
} catch (err: any) {
|
|
console.error(err)
|
|
return reply.code(400).send({ error: err.message })
|
|
}
|
|
|
|
|
|
|
|
console.log(req.body)
|
|
|
|
return
|
|
|
|
|
|
}
|
|
);
|
|
}
|