CHANGE: updated to correct sql database

This commit is contained in:
2024-09-10 22:29:26 +02:00
parent 6cb8bd5afd
commit 0fac697cda
8 changed files with 82 additions and 278 deletions

25
.vscode/settings.json vendored
View File

@@ -1,14 +1,15 @@
{ {
"sqltools.connections": [ "sqltools.connections": [
{ {
"previewLimit": 50, "previewLimit": 50,
"server": "localhost", "server": "localhost",
"port": 5432, "port": 5432,
"askForPassword": true, "askForPassword": true,
"driver": "PostgreSQL", "driver": "PostgreSQL",
"name": "arbeitszeiten", "name": "arbeitszeiten",
"database": "arbeitszeitmessung", "database": "arbeitszeitmessung",
"username": "arbeit_zeit" "username": "arbeit_zeit"
} }
] ],
"makefile.configureOnOpen": false
} }

View File

@@ -17,7 +17,7 @@ func OpenDatabase() (*sql.DB, error) {
} }
func GetBookingsByCardID(db *sql.DB, card_id string) ([]models.Booking, error) { func GetBookingsByCardID(db *sql.DB, card_id string) ([]models.Booking, error) {
qStr, err := db.Prepare((`SELECT * FROM zeiten WHERE card_id = $1`)) qStr, err := db.Prepare((`SELECT * FROM anwesenheit WHERE card_id = $1`))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -32,7 +32,7 @@ func GetBookingsByCardID(db *sql.DB, card_id string) ([]models.Booking, error) {
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
var booking models.Booking var booking models.Booking
if err := rows.Scan(&booking.Id, &booking.LoggedTime, &booking.CardID, &booking.ReaderID, &booking.BookingType); err != nil { if err := rows.Scan(&booking.CounterId, &booking.Timestamp, &booking.CardUID, &booking.GeraetID, &booking.CheckInOut); err != nil {
return bookings, err return bookings, err
} }
bookings = append(bookings, booking) bookings = append(bookings, booking)

View File

@@ -24,7 +24,7 @@ func main() {
http.HandleFunc("/time/new", timeCreateHandler) http.HandleFunc("/time/new", timeCreateHandler)
http.HandleFunc("/time", timeHandler) http.HandleFunc("/time", timeHandler)
fmt.Printf("Server is running at http://localhost:8080 exposed to port %s\n", getEnv("EXPOSED_PORT", "8000")) fmt.Printf("Server is running at http://localhost:8000 exposed to port %s\n", getEnv("EXPOSED_PORT", "8000"))
log.Fatal(http.ListenAndServe(":8000", nil)) log.Fatal(http.ListenAndServe(":8000", nil))
} }
@@ -76,7 +76,7 @@ func createBooking(w http.ResponseWriter, r *http.Request) {
} }
func getBookings(w http.ResponseWriter, r *http.Request) { func getBookings(w http.ResponseWriter, r *http.Request) {
card_id := r.URL.Query().Get("cardID") card_id := r.URL.Query().Get("card_uid")
if card_id == "" { if card_id == "" {
http.Error(w, "Missing cardID query parameter", http.StatusBadRequest) http.Error(w, "Missing cardID query parameter", http.StatusBadRequest)
return return
@@ -92,7 +92,7 @@ func getBookings(w http.ResponseWriter, r *http.Request) {
} }
func updateBooking(w http.ResponseWriter, r *http.Request) { func updateBooking(w http.ResponseWriter, r *http.Request) {
_booking_id := r.URL.Query().Get("bookingID") _booking_id := r.URL.Query().Get("counter_id")
if _booking_id == "" { if _booking_id == "" {
http.Error(w, "Missing bookingID query parameter", http.StatusBadRequest) http.Error(w, "Missing bookingID query parameter", http.StatusBadRequest)
return return
@@ -117,7 +117,7 @@ func updateBooking(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return return
} }
if booking.Id != 0 && booking.Id != _booking.Id { if booking.CounterId != 0 && booking.CounterId != _booking.CounterId {
log.Println("Booking Ids do not match") log.Println("Booking Ids do not match")
http.Error(w, "Booking Ids do not match", http.StatusBadRequest) http.Error(w, "Booking Ids do not match", http.StatusBadRequest)
return return

View File

@@ -16,36 +16,37 @@ func (e SameBookingError) Error() string {
} }
type Booking struct { type Booking struct {
CardID string `json:"cardID"` CardUID string `json:"card_uid"`
ReaderID string `json:"readerID"` GeraetID int16 `json:"geraet_id"`
BookingType int `json:"bookingType"` CheckInOut int16 `json:"check_in_out"`
LoggedTime time.Time `json:"loggedTime"` Timestamp time.Time `json:"timestamp"`
Id int `json:"id"` CounterId int `json:"counter_id"`
} }
var DB *sql.DB var DB *sql.DB
func (b Booking) New(card_id string, reader_id string, booking_type int) Booking { func (b Booking) New(card_id string, geraet_id int16, check_in_out int16) Booking {
return Booking{ return Booking{
CardID: card_id, CardUID: card_id,
ReaderID: reader_id, GeraetID: geraet_id,
BookingType: booking_type, CheckInOut: check_in_out,
} }
} }
func (b *Booking) FromUrlParams(params url.Values) Booking { func (b *Booking) FromUrlParams(params url.Values) Booking {
bookingType, err := strconv.Atoi(params.Get("bookingType")) var booking Booking
if err != nil { if _check_in_out, err := strconv.Atoi(params.Get("check_in_out")); err == nil {
log.Println("Error parsing bookingType: ", err) booking.CheckInOut = int16(_check_in_out)
return b.New("", "", 0)
} }
cardID := params.Get("cardID") if _geraet_id, err := strconv.Atoi(params.Get("geraet_id")); err == nil {
readerID := params.Get("readerID") booking.GeraetID = int16(_geraet_id)
return Booking{BookingType: bookingType, CardID: cardID, ReaderID: readerID} }
booking.CardUID = params.Get("card_uid")
return booking
} }
func (b Booking) Verify() bool { func (b Booking) Verify() bool {
if b.CardID == "" || b.ReaderID == "" || b.BookingType == 0 { if b.CardUID == "" || b.GeraetID == 0 || b.CheckInOut == 0 {
return false return false
} }
return true return true
@@ -55,11 +56,11 @@ func (b *Booking) Insert() error {
if !checkLastBooking(*b) { if !checkLastBooking(*b) {
return SameBookingError{} return SameBookingError{}
} }
stmt, err := DB.Prepare((`INSERT INTO zeiten (card_id, reader_id, booking_type) VALUES ($1, $2, $3) RETURNING id, logged_time`)) stmt, err := DB.Prepare((`INSERT INTO anwesenheit (card_uid, geraet_id, check_in_out) VALUES ($1, $2, $3) RETURNING counter_id, timestamp`))
if err != nil { if err != nil {
return err return err
} }
err = stmt.QueryRow(b.CardID, b.ReaderID, b.BookingType).Scan(&b.Id, &b.LoggedTime) err = stmt.QueryRow(b.CardUID, b.GeraetID, b.CheckInOut).Scan(&b.CounterId, &b.Timestamp)
if err != nil { if err != nil {
return err return err
} }
@@ -68,11 +69,11 @@ func (b *Booking) Insert() error {
func (b *Booking) GetBookingById(booking_id int) (Booking, error) { func (b *Booking) GetBookingById(booking_id int) (Booking, error) {
var booking Booking var booking Booking
qStr, err := DB.Prepare((`SELECT id, logged_time, card_id, reader_id, booking_type FROM zeiten WHERE id = $1`)) qStr, err := DB.Prepare((`SELECT counter_id, timestamp, card_uid, geraet_id, check_in_out FROM anwesenheit WHERE counter_id = $1`))
if err != nil { if err != nil {
return booking, err return booking, err
} }
err = qStr.QueryRow(booking_id).Scan(&booking.Id, &booking.LoggedTime, &booking.CardID, &booking.ReaderID, &booking.BookingType) err = qStr.QueryRow(booking_id).Scan(&booking.CounterId, &booking.Timestamp, &booking.CardUID, &booking.GeraetID, &booking.CheckInOut)
if err != nil { if err != nil {
return booking, err return booking, err
} }
@@ -84,7 +85,7 @@ func (b *Booking) GetBookingById(booking_id int) (Booking, error) {
} }
func (b *Booking) GetBookingsByCardID(card_id string) ([]Booking, error) { func (b *Booking) GetBookingsByCardID(card_id string) ([]Booking, error) {
qStr, err := DB.Prepare((`SELECT id, logged_time, card_id, reader_id, booking_type FROM zeiten WHERE card_id = $1`)) qStr, err := DB.Prepare((`SELECT counter_id, timestamp, card_uid, geraet_id, check_in_out FROM anwesenheit WHERE card_uid = $1`))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -99,7 +100,7 @@ func (b *Booking) GetBookingsByCardID(card_id string) ([]Booking, error) {
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
var booking Booking var booking Booking
if err := rows.Scan(&booking.Id, &booking.LoggedTime, &booking.CardID, &booking.ReaderID, &booking.BookingType); err != nil { if err := rows.Scan(&booking.CounterId, &booking.Timestamp, &booking.CardUID, &booking.GeraetID, &booking.CheckInOut); err != nil {
return bookings, err return bookings, err
} }
bookings = append(bookings, booking) bookings = append(bookings, booking)
@@ -111,12 +112,12 @@ func (b *Booking) GetBookingsByCardID(card_id string) ([]Booking, error) {
} }
func (b Booking) Save() { func (b Booking) Save() {
qStr, err := DB.Prepare((`UPDATE "zeiten" SET "id" = $1, "card_id" = $2, "reader_id" = $3, "booking_type" = $4 WHERE "id" = $1;`)) qStr, err := DB.Prepare((`UPDATE "anwesenheit" SET "id" = $1, "card_uid" = $2, "reader_id" = $3, "booking_type" = $4 WHERE "id" = $1;`))
if err != nil { if err != nil {
log.Fatalf("Error preparing query: %v", err) log.Fatalf("Error preparing query: %v", err)
return return
} }
_, err = qStr.Query(b.Id, b.CardID, b.ReaderID, b.BookingType) _, err = qStr.Query(b.CounterId, b.CardUID, b.GeraetID, b.CheckInOut)
if err != nil { if err != nil {
log.Fatalf("Error executing query: %v", err) log.Fatalf("Error executing query: %v", err)
return return
@@ -124,25 +125,25 @@ func (b Booking) Save() {
} }
func (b *Booking) Update(nb Booking) { func (b *Booking) Update(nb Booking) {
if b.BookingType != nb.BookingType && nb.BookingType != 0 { if b.CheckInOut != nb.CheckInOut && nb.CheckInOut != 0 {
b.BookingType = nb.BookingType b.CheckInOut = nb.CheckInOut
} }
if b.CardID != nb.CardID && nb.CardID != "" { if b.CardUID != nb.CardUID && nb.CardUID != "" {
b.CardID = nb.CardID b.CardUID = nb.CardUID
} }
if b.ReaderID != nb.ReaderID && nb.ReaderID != "" { if b.GeraetID != nb.GeraetID && nb.GeraetID != 0 {
b.ReaderID = nb.ReaderID b.GeraetID = nb.GeraetID
} }
} }
func checkLastBooking(b Booking) bool { func checkLastBooking(b Booking) bool {
var booking_type int var check_in_out int
stmt, err := DB.Prepare((`SELECT booking_type FROM "zeiten" WHERE "card_id" = $1 ORDER BY "logged_time" DESC LIMIT 1;`)) stmt, err := DB.Prepare((`SELECT check_in_out FROM "anwesenheit" WHERE "card_uid" = $1 ORDER BY "timestamp" DESC LIMIT 1;`))
if err != nil { if err != nil {
log.Fatalf("Error preparing query: %v", err) log.Fatalf("Error preparing query: %v", err)
return false return false
} }
err = stmt.QueryRow(b.CardID).Scan(&booking_type) err = stmt.QueryRow(b.CardUID).Scan(&check_in_out)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return true return true
} }
@@ -150,7 +151,7 @@ func checkLastBooking(b Booking) bool {
log.Println("Error checking last booking: ", err) log.Println("Error checking last booking: ", err)
return false return false
} }
if booking_type == b.BookingType { if int16(check_in_out) == b.CheckInOut {
return false return false
} }
return true return true

View File

@@ -1,5 +1,5 @@
POSTGRES_USER=arbeit_zeit POSTGRES_USER=arbeit_zeit
POSTGRES_PASSWORD=password POSTGRES_PASSWORD=password
POSTGRES_PATH=./database POSTGRES_PATH=../Backend/database
POSTGRES_DB=arbeitszeitmessung POSTGRES_DB=arbeitszeitmessung
EXPOSED_PORT=8000 EXPOSED_PORT=8000

View File

@@ -1,210 +0,0 @@
{
"openapi": "3.0.3",
"info": {
"title": "Arbeitszeitmessung - OpenAPI 3.0",
"description": "This demos the API for the Arbeitszeitmessung Project ",
"version": "0.1.0"
},
"externalDocs": {
"description": "Git-Repository",
"url": "https://git.letsstein.de/tom/arbeitszeitmessung"
},
"servers": [
{
"url": "http://localhost:8000"
}
],
"tags": [
{
"name": "booking",
"description": "all Bookings"
}
],
"paths": {
"/time": {
"put": {
"tags": [
"booking"
],
"summary": "Update a existing booking",
"description": "Update an existing booking by Id",
"operationId": "updateBooking",
"parameters": [
{
"name": "bookingID",
"in": "query",
"description": "Booking ID to update",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"description": "Update an existent booking in the db. Not all values have to be updated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Booking"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "Booking Updated",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Booking"
}
}
}
},
"400": {
"description": "Invalid ID supplied"
},
"500": {
"description": "Server Error"
}
}
},
"get": {
"tags": [
"booking"
],
"summary": "Gets all the bookings limited",
"description": "Returns all the bookings optionally filtered with cardID",
"parameters": [
{
"name": "cardID",
"in": "query",
"description": "CardID to filter for",
"required": false,
"schema": {
"type": "string"
}
}
],
"operationId": "addPet",
"responses": {
"200": {
"description": "Successful operation",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Booking"
}
}
}
}
},
"400": {
"description": "Invalid cardID"
}
}
}
},
"/time/new": {
"put": {
"tags": [
"booking"
],
"summary": "Create new Booking",
"description": "Creates a new booking with the supplied parameters",
"operationId": "createBooking",
"parameters": [
{
"name": "cardID",
"in": "query",
"description": "id of the RFID card scanned",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "readerID",
"in": "query",
"description": "id of the RFID reader scanning the card",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "bookingType",
"in": "query",
"description": "booking Type",
"required": true,
"schema": {
"type": "integer",
"enum": [
1,
2,
255
]
}
}
],
"responses": {
"200": {
"description": "successfully created booking",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Booking"
}
}
}
},
"409": {
"description": "Same booking type as last booking"
}
}
}
}
},
"components": {
"schemas": {
"Booking": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64",
"example": 100
},
"cardID": {
"type": "string",
"example": "test_card"
},
"readerID": {
"type": "string",
"example": "test_reader"
},
"bookingType": {
"type": "integer",
"example": 1,
"enum": [
1,
2,
255
]
},
"loggedTime": {
"type": "string",
"format": "date-time",
"example": "2024-09-05T08:51:12.670Z"
}
},
"xml": {
"name": "booking"
}
}
}
}
}

View File

@@ -2,7 +2,7 @@ openapi: 3.0.3
info: info:
title: Arbeitszeitmessung - OpenAPI 3.0 title: Arbeitszeitmessung - OpenAPI 3.0
description: |- description: |-
This demos the API for the Arbeitszeitmessung Project This demos the API for the Arbeitszeitmessung Project
version: 0.1.0 version: 0.1.0
externalDocs: externalDocs:
description: Git-Repository description: Git-Repository
@@ -21,7 +21,7 @@ paths:
description: Update an existing booking by Id description: Update an existing booking by Id
operationId: updateBooking operationId: updateBooking
parameters: parameters:
- name: bookingID - name: counterID
in: query in: query
description: Booking ID to update description: Booking ID to update
required: true required: true
@@ -40,7 +40,7 @@ paths:
content: content:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Booking' $ref: '#/components/schemas/Booking'
'400': '400':
description: Invalid ID supplied description: Invalid ID supplied
'500': '500':
@@ -66,7 +66,7 @@ paths:
schema: schema:
type: array type: array
items: items:
$ref: '#/components/schemas/Booking' $ref: '#/components/schemas/Booking'
'400': '400':
description: Invalid cardID description: Invalid cardID
/time/new: /time/new:
@@ -83,13 +83,13 @@ paths:
required: true required: true
schema: schema:
type: string type: string
- name: readerID - name: geraetID
in: query in: query
description: id of the RFID reader scanning the card description: id of the RFID reader scanning the card
required: true required: true
schema: schema:
type: string type: string
- name: bookingType - name: checkInOut
in: query in: query
description: booking Type description: booking Type
required: true required: true
@@ -105,7 +105,7 @@ paths:
content: content:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/Booking' $ref: '#/components/schemas/Booking'
'409': '409':
description: Same booking type as last booking description: Same booking type as last booking
components: components:
@@ -113,26 +113,26 @@ components:
Booking: Booking:
type: object type: object
properties: properties:
id: counterID:
type: integer type: integer
format: int64 format: int64
example: 100 example: 100
cardID: cardID:
type: string type: string
example: test_card example: test_card
readerID: geraetID:
type: string type: string
example: test_reader example: test_reader
bookingType: checkInOut:
type: integer type: integer
example: 1 example: 1
enum: enum:
- 1 - 1
- 2 - 2
- 255 - 255
loggedTime: timestamp:
type: string type: string
format: date-time format: date-time
example: 2024-09-05T08:51:12.670827Z example: 2024-09-05T08:51:12.670827Z
xml: xml:
name: booking name: booking

16
db.sql
View File

@@ -9,10 +9,11 @@ CREATE TABLE zeiten (
-- @block insert data -- @block insert data
INSERT INTO zeiten (card_id, reader_id, booking_type) INSERT INTO zeiten (card_id, reader_id, booking_type)
VALUES ('test_card', 'test_reader', '2') VALUES ('test_card', 'test_reader', '2')
RETURNING id, logged_time; RETURNING id,
logged_time;
-- @block select -- @block select
SELECT * SELECT *
FROM zeiten; FROM anwesenheit;
-- @block select last entry from card id -- @block select last entry from card id
SELECT * SELECT *
FROM "zeiten" FROM "zeiten"
@@ -22,3 +23,14 @@ ORDER BY "logged_time" DESC
LIMIT 1; LIMIT 1;
-- @block delete table -- @block delete table
DROP TABLE IF EXISTS zeiten; DROP TABLE IF EXISTS zeiten;
-- @block create table anwesenheit
DROP TABLE IF EXISTS "public"."anwesenheit";
CREATE TABLE "public"."anwesenheit" (
"counter_id" SERIAL PRIMARY KEY,
"timestamp" timestamp(6) DEFAULT CURRENT_TIMESTAMP,
"card_uid" varchar(255) COLLATE "pg_catalog"."default",
"check_in_out" int2,
"geraet_id" int2
);
COMMENT ON COLUMN "public"."anwesenheit"."check_in_out" IS '1=Check In 2=Check Out 255=Automatic Check Out';
COMMENT ON COLUMN "public"."anwesenheit"."geraet_id" IS 'ID des Lesegerätes';