Compare commits
14 Commits
327ab8592a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ecf62faff | ||
|
|
06e146f1c4 | ||
|
|
5051abc440 | ||
|
|
f69fa8b563 | ||
|
|
4ff56ec06c | ||
|
|
3b6f544946 | ||
|
|
dadb094017 | ||
|
|
27ee5d59c3 | ||
|
|
c39384badf | ||
|
|
c2e6f81775 | ||
|
|
d1eeea0800 | ||
|
|
cf9b0d53c1 | ||
|
|
98e5ef06c0 | ||
|
|
0edcae1a24 |
@@ -1,18 +1,46 @@
|
||||
from enum import Enum
|
||||
import mysql.connector
|
||||
import os
|
||||
import random
|
||||
from mysql.connector import pooling
|
||||
|
||||
STARTUP_TABLE_CREATION_QUERIES = {
|
||||
"users": """CREATE TABLE IF NOT EXISTS users (
|
||||
Name varchar(255),
|
||||
Attendance bool,
|
||||
Password VARCHAR(2048)
|
||||
Password VARCHAR(2048),
|
||||
WishListUrl VARCHAR(2048)
|
||||
);""",
|
||||
"sessions": """CREATE TABLE IF NOT EXISTS sessions (
|
||||
Token VARCHAR(2048),
|
||||
Name varchar(255)
|
||||
);""",
|
||||
"hosting": """CREATE TABLE IF NOT EXISTS hosting (
|
||||
id SERIAL,
|
||||
Name varchar(255),
|
||||
Capacity INT,
|
||||
reservedBy varchar(255)
|
||||
);""",
|
||||
"santa": """CREATE TABLE IF NOT EXISTS santa (
|
||||
Name varchar(255),
|
||||
Santa varchar(255)
|
||||
);""",
|
||||
}
|
||||
|
||||
INJECT_TABLE_CREATION_QUERIES = {
|
||||
"hosting": """
|
||||
INSERT INTO hosting (Name, Capacity, reservedBy)
|
||||
SELECT name, capacity, reservedBy FROM (
|
||||
SELECT 'Матрац 160см' AS name, 2 AS capacity, '' AS reservedBy
|
||||
UNION ALL
|
||||
SELECT 'Кровать 120см', 2, ''
|
||||
UNION ALL
|
||||
SELECT 'Матрац 90см', 1, ''
|
||||
UNION ALL
|
||||
SELECT 'Диван', 1, ''
|
||||
) AS temp
|
||||
WHERE NOT EXISTS (SELECT 1 FROM hosting WHERE Name = temp.name);
|
||||
""",
|
||||
}
|
||||
|
||||
class Severity(Enum):
|
||||
@@ -33,6 +61,7 @@ class DBClient:
|
||||
self.pool = self.create_pool() # Create a connection pool
|
||||
|
||||
self.initialize_database()
|
||||
self.initialize_secret_santa() # Initialize Secret Santa
|
||||
|
||||
def validate_env_variables(self):
|
||||
if not self.db_server or not self.db_port or not self.password or not self.database:
|
||||
@@ -53,6 +82,59 @@ class DBClient:
|
||||
def initialize_database(self):
|
||||
self.query(STARTUP_TABLE_CREATION_QUERIES['users'])
|
||||
self.query(STARTUP_TABLE_CREATION_QUERIES['sessions'])
|
||||
self.query(STARTUP_TABLE_CREATION_QUERIES['hosting'])
|
||||
self.query(INJECT_TABLE_CREATION_QUERIES['hosting'])
|
||||
|
||||
def initialize_secret_santa(self):
|
||||
table_exists = self.query("SHOW TABLES LIKE 'santa';")
|
||||
|
||||
if not table_exists:
|
||||
self.query(STARTUP_TABLE_CREATION_QUERIES['santa'])
|
||||
|
||||
count_query = self.query('SELECT COUNT(*) FROM santa;')
|
||||
if count_query[0][0] > 0:
|
||||
self.app.logger.warning('The santa table is not empty. No assignments will be made.')
|
||||
return
|
||||
|
||||
attendees = self.query('SELECT Name FROM users WHERE Attendance = 1;')
|
||||
|
||||
if not attendees:
|
||||
return
|
||||
|
||||
attendees = [user[0] for user in attendees]
|
||||
couples = [("Тюлень", "Тюлениха"), ("Медведь", "Ксения")]
|
||||
|
||||
max_attempts = 1000
|
||||
|
||||
for attempt in range(max_attempts):
|
||||
shuffled_attendees = attendees.copy()
|
||||
random.shuffle(shuffled_attendees)
|
||||
|
||||
santa_assignments = {}
|
||||
valid = True
|
||||
|
||||
for index, user in enumerate(shuffled_attendees):
|
||||
prev_user = shuffled_attendees[index - 1]
|
||||
next_user = shuffled_attendees[(index + 1) % len(shuffled_attendees)]
|
||||
|
||||
if any(user in couple and (prev_user in couple or next_user in couple) for couple in couples):
|
||||
valid = False
|
||||
break
|
||||
|
||||
santa_assignments[user] = prev_user
|
||||
|
||||
if valid:
|
||||
break
|
||||
|
||||
else:
|
||||
self.app.logger.warning('Could not find valid Santa assignments after multiple attempts.')
|
||||
return
|
||||
|
||||
self.app.logger.info(f'Santa assignments: {santa_assignments}')
|
||||
|
||||
for user, santa in santa_assignments.items():
|
||||
self.query('INSERT INTO santa (Name, Santa) VALUES (%s, %s);', (user, santa))
|
||||
|
||||
|
||||
def query(self, query_str, params=None):
|
||||
max_retries = 3
|
||||
@@ -63,7 +145,7 @@ class DBClient:
|
||||
connection = self.pool.get_connection()
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(query_str, params)
|
||||
if 'SELECT' in query_str:
|
||||
if 'SELECT' in query_str or 'SHOW' in query_str:
|
||||
results = cursor.fetchall()
|
||||
self.app.logger.info(f'Query results: {results}')
|
||||
return results
|
||||
|
||||
146
backend/src/hosting.py
Normal file
146
backend/src/hosting.py
Normal file
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python
|
||||
# encoding: utf-8
|
||||
|
||||
'''
|
||||
hosting.py is a source for all hosting endpoints.
|
||||
'''
|
||||
|
||||
from flask import request, jsonify
|
||||
import mysql.connector
|
||||
|
||||
def registerHostingEndpoints(app, database):
|
||||
|
||||
@app.route('/hosting', methods=['GET'])
|
||||
def get_hosting():
|
||||
try:
|
||||
app.logger.info('Fetching hosting data')
|
||||
query = "SELECT id, Name AS name, Capacity AS capacity, reservedBy FROM hosting"
|
||||
result = database.query(query) # Adjust this depending on your database implementation
|
||||
|
||||
# Transform the result into the required structure
|
||||
furniture_list = [
|
||||
{
|
||||
"id": row[0],
|
||||
"name": row[1],
|
||||
"capacity": row[2],
|
||||
"reservedBy": row[3]
|
||||
} for row in result
|
||||
]
|
||||
|
||||
hosting_data = {
|
||||
"furniture": furniture_list
|
||||
}
|
||||
|
||||
app.logger.info(f'Fetched data: {hosting_data}')
|
||||
return jsonify(hosting_data), 200
|
||||
except mysql.connector.Error as err:
|
||||
app.logger.error(f"Database error: {err}")
|
||||
return jsonify({"error": "Database error occurred"}), 500
|
||||
except Exception as e:
|
||||
app.logger.error(f"Unexpected error: {e}")
|
||||
return jsonify({"error": "Internal server error"}), 500
|
||||
|
||||
|
||||
@app.route('/hosting/<int:id>', methods=['POST'])
|
||||
def update_hosting(id):
|
||||
data = request.get_json()
|
||||
reserved_by = data.get('reservedBy')
|
||||
|
||||
if not reserved_by:
|
||||
return jsonify({"error": "reservedBy field is required"}), 400
|
||||
|
||||
try:
|
||||
app.logger.info(f'Updating hosting with ID {id} to reserved by {reserved_by}')
|
||||
query = "UPDATE hosting SET reservedBy=%s WHERE id=%s"
|
||||
params = (reserved_by, id)
|
||||
database.query(query, params) # Adjust this depending on your database implementation
|
||||
app.logger.info(f'Successfully updated hosting ID {id}')
|
||||
return jsonify({"message": "Successfully updated"}), 200
|
||||
except mysql.connector.Error as err:
|
||||
app.logger.error(f"Database error: {err}")
|
||||
return jsonify({"error": "Database error occurred"}), 500
|
||||
except Exception as e:
|
||||
app.logger.error(f"Unexpected error: {e}")
|
||||
return jsonify({"error": "Internal server error"}), 500
|
||||
|
||||
@app.route('/hosting/<int:id>/unreserve', methods=['POST'])
|
||||
def unreserve_item(id):
|
||||
token = request.json.get('token')
|
||||
|
||||
if not token:
|
||||
return jsonify(success=False, message="Token is required"), 400
|
||||
|
||||
query_session = "SELECT * FROM sessions WHERE Token=%s"
|
||||
|
||||
try:
|
||||
result = database.query(query_session, params=(token,))
|
||||
if not result:
|
||||
return jsonify(success=False, message="Token is invalid or expired"), 401
|
||||
|
||||
user_name = result[0][1] # Assuming user name is in the second column of session result
|
||||
|
||||
# Check if the item is reserved by the user
|
||||
reservation_check_query = """
|
||||
SELECT * FROM hosting WHERE id = %s AND reservedBy = %s
|
||||
"""
|
||||
reservation_check_result = database.query(reservation_check_query, params=(id, user_name))
|
||||
|
||||
if not reservation_check_result:
|
||||
return jsonify(success=False, message="Item is not reserved by you or does not exist"), 404
|
||||
|
||||
# Proceed to unreserve the item
|
||||
unreserve_query = """
|
||||
UPDATE hosting SET reservedBy = '' WHERE id = %s
|
||||
"""
|
||||
database.query(unreserve_query, params=(id,))
|
||||
|
||||
return jsonify(success=True, message="Item unreserved successfully"), 200
|
||||
|
||||
except Exception as e:
|
||||
return jsonify(success=False, message=str(e)), 500
|
||||
|
||||
@app.route('/hosting/create', methods=['POST'])
|
||||
def create_and_reserve_item():
|
||||
token = request.json.get('token')
|
||||
name = request.json.get('name') # Name of the item to create
|
||||
capacity = request.json.get('capacity') # Capacity of the item
|
||||
|
||||
if not token:
|
||||
return jsonify(success=False, message="Token is required"), 400
|
||||
if not name:
|
||||
return jsonify(success=False, message="Забыл имя"), 400
|
||||
if capacity is None:
|
||||
return jsonify(success=False, message="Забыл количество мест"), 400
|
||||
|
||||
query_session = "SELECT * FROM sessions WHERE Token=%s"
|
||||
|
||||
try:
|
||||
# Verify user by token
|
||||
result = database.query(query_session, params=(token,))
|
||||
if not result:
|
||||
return jsonify(success=False, message="Token is invalid or expired"), 401
|
||||
|
||||
user_name = result[0][1] # Assuming user name is in the second column of session result
|
||||
|
||||
# Check if the item already exists
|
||||
item_check_query = "SELECT * FROM hosting WHERE Name = %s"
|
||||
item_check_result = database.query(item_check_query, params=(name,))
|
||||
|
||||
if item_check_result: # If an item with the same name already exists
|
||||
return jsonify(success=False, message="Уже существует"), 400
|
||||
|
||||
# Insert the new item and reserve it for the user
|
||||
insert_query = """
|
||||
INSERT INTO hosting (Name, Capacity, reservedBy)
|
||||
VALUES (%s, %s, %s)
|
||||
"""
|
||||
params = (name, capacity, user_name) # Reserve the item to the user
|
||||
database.query(insert_query, params=params)
|
||||
|
||||
return jsonify(success=True, message="Создано"), 201
|
||||
|
||||
except Exception as e:
|
||||
return jsonify(success=False, message=str(e)), 500
|
||||
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from flask_cors import CORS
|
||||
from dotenv import load_dotenv
|
||||
from db_client import DBClient
|
||||
from user import registerUserEndpoints
|
||||
from hosting import registerHostingEndpoints
|
||||
import logging
|
||||
|
||||
load_dotenv()
|
||||
@@ -23,6 +24,7 @@ allowed_origins = [
|
||||
CORS(app, resources={r"*": {"origins": allowed_origins}}) # Only allow example.com
|
||||
database = DBClient(app)
|
||||
registerUserEndpoints(app=app, database=database)
|
||||
registerHostingEndpoints(app=app, database=database)
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True)
|
||||
@@ -133,11 +133,96 @@ def registerUserEndpoints(app, database):
|
||||
|
||||
attendance_status = attendance_result[0][0]
|
||||
|
||||
return jsonify(success=True, attendance=bool(attendance_status)), 200
|
||||
return jsonify(success=True, attendance=attendance_status), 200
|
||||
|
||||
except Exception as e:
|
||||
return jsonify(success=False, message=str(e)), 500
|
||||
|
||||
@app.route('/users/attendance/all', methods=['GET'])
|
||||
def get_attendance_all():
|
||||
token = request.args.get('token')
|
||||
|
||||
if not token:
|
||||
return jsonify(success=False, message="Token is required"), 400
|
||||
|
||||
query_session = "SELECT * FROM sessions WHERE Token=%s"
|
||||
|
||||
try:
|
||||
result = database.query(query_session, params=(token,))
|
||||
if not result:
|
||||
return jsonify(success=False, message="Token is invalid or expired"), 401
|
||||
|
||||
attendance_query = "SELECT Name, Attendance FROM users"
|
||||
attendance_result = database.query(attendance_query)
|
||||
|
||||
if not attendance_result:
|
||||
return jsonify(success=False, message="No users found"), 404
|
||||
|
||||
attendance_list = [{"name": row[0], "attendance": row[1]} for row in attendance_result]
|
||||
|
||||
return jsonify(success=True, attendance_list=attendance_list), 200
|
||||
|
||||
except Exception as e:
|
||||
return jsonify(success=False, message=str(e)), 500
|
||||
|
||||
|
||||
@app.route('/users/wishlist', methods=['PUT'])
|
||||
def update_wishlist():
|
||||
data = request.json
|
||||
token = data.get('token')
|
||||
wishlist_url = data.get('wishlist')
|
||||
|
||||
if wishlist_url is None:
|
||||
return jsonify(success=False, message="Wishlist URL is required"), 400
|
||||
|
||||
query_session = "SELECT * FROM sessions WHERE Token=%s"
|
||||
try:
|
||||
result = database.query(query_session, params=(token,))
|
||||
if not result:
|
||||
return jsonify(success=False, message="Token is invalid or expired"), 401
|
||||
|
||||
user_name = result[0][1]
|
||||
wishlist_query = "UPDATE users SET WishListUrl = %s WHERE Name = %s"
|
||||
update_result = database.query(wishlist_query, params=(wishlist_url, user_name))
|
||||
|
||||
return jsonify(success=True, message="WishListUrl updated successfully"), 200
|
||||
|
||||
except Exception as e:
|
||||
return jsonify(success=False, message=str(e)), 500
|
||||
|
||||
@app.route('/users/santa', methods=['GET'])
|
||||
def get_santainfo():
|
||||
token = request.args.get('token')
|
||||
|
||||
if not token:
|
||||
return jsonify(success=False, message="Token is required"), 400
|
||||
|
||||
query_session = "SELECT * FROM sessions WHERE Token=%s"
|
||||
|
||||
try:
|
||||
result = database.query(query_session, params=(token,))
|
||||
if not result:
|
||||
return jsonify(success=False, message="Token is invalid or expired"), 401
|
||||
|
||||
user_name = result[0][1]
|
||||
|
||||
santa_query = "SELECT Name FROM santa WHERE Santa = %s"
|
||||
santa_result = database.query(santa_query, params=(user_name,))
|
||||
|
||||
if not santa_result:
|
||||
return jsonify(success=False, message=f"User's {user_name} Santa info not found"), 404
|
||||
|
||||
santa_to = santa_result[0][0]
|
||||
|
||||
wishlist_query = "SELECT WishListUrl FROM users WHERE Name = %s"
|
||||
wishlist_result = database.query(wishlist_query, params=(santa_to,))
|
||||
|
||||
santa_info = {
|
||||
"santa_to": santa_to,
|
||||
"wishlist": wishlist_result[0][0]
|
||||
}
|
||||
|
||||
return jsonify(success=True, santa_info=santa_info), 200
|
||||
|
||||
except Exception as e:
|
||||
return jsonify(success=False, message=str(e)), 500
|
||||
|
||||
18
frontend/package-lock.json
generated
18
frontend/package-lock.json
generated
@@ -3149,14 +3149,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.14",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.4.4",
|
||||
"picomatch": "^4.0.2"
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
@@ -3324,9 +3324,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.3.tgz",
|
||||
"integrity": "sha512-OOUi5zjkDxYrKhTV3V7iKsoS37VUM7v40+HuwEmcrsf11Cdx9y3DIr2Px6liIcZFwt3XSRpQvFpL3WVy7ApkGw==",
|
||||
"version": "7.1.12",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.12.tgz",
|
||||
"integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -3335,7 +3335,7 @@
|
||||
"picomatch": "^4.0.3",
|
||||
"postcss": "^8.5.6",
|
||||
"rollup": "^4.43.0",
|
||||
"tinyglobby": "^0.2.14"
|
||||
"tinyglobby": "^0.2.15"
|
||||
},
|
||||
"bin": {
|
||||
"vite": "bin/vite.js"
|
||||
|
||||
@@ -1,42 +1,62 @@
|
||||
/* fonts.css */
|
||||
@font-face {
|
||||
font-family: 'Plovdiv'; /* Font family name */
|
||||
src: url('./assets/fonts/Plovdiv/PlovdivDisplay-Bold.otf') format('opentype'); /* Regular style */
|
||||
font-weight: bold; /* Standard weight */
|
||||
font-style: normal; /* Standard style */
|
||||
font-family: 'Plovdiv';
|
||||
/* Font family name */
|
||||
src: url('./assets/fonts/Plovdiv/PlovdivDisplay-Bold.otf') format('opentype');
|
||||
/* Regular style */
|
||||
font-weight: bold;
|
||||
/* Standard weight */
|
||||
font-style: normal;
|
||||
/* Standard style */
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'Plovdiv'; /* Same font family name */
|
||||
src: url('./assets/fonts/Plovdiv/PlovdivDisplay-Regular.otf') format('opentype'); /* Bold style */
|
||||
font-weight: normal; /* Bold weight */
|
||||
font-style: normal; /* Standard style */
|
||||
font-family: 'Plovdiv';
|
||||
/* Same font family name */
|
||||
src: url('./assets/fonts/Plovdiv/PlovdivDisplay-Regular.otf') format('opentype');
|
||||
/* Bold style */
|
||||
font-weight: normal;
|
||||
/* Bold weight */
|
||||
font-style: normal;
|
||||
/* Standard style */
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'Pomelo'; /* Name of the font */
|
||||
src: url('./assets/fonts/Pomelo/PomeloRegular.ttf') format('truetype'); /* Path to the TTF file */
|
||||
font-weight: normal; /* Standard weight */
|
||||
font-style: normal; /* Standard style */
|
||||
font-family: 'Pomelo';
|
||||
/* Name of the font */
|
||||
src: url('./assets/fonts/Pomelo/PomeloRegular.ttf') format('truetype');
|
||||
/* Path to the TTF file */
|
||||
font-weight: normal;
|
||||
/* Standard weight */
|
||||
font-style: normal;
|
||||
/* Standard style */
|
||||
}
|
||||
|
||||
#root {
|
||||
width: 100%;
|
||||
text-align: center; /* Centered text alignment */
|
||||
text-align: center;
|
||||
/* Centered text alignment */
|
||||
}
|
||||
|
||||
/* Overall Body Style */
|
||||
body {
|
||||
background-color: #ffffff; /* Light background for contrast */
|
||||
background-image: url('./assets/snowflakes.png'); /* Background image */
|
||||
background-size: cover; /* Cover the entire screen */
|
||||
background-position: center; /* Center the image */
|
||||
background-repeat: no-repeat; /* Prevent repeating */
|
||||
color: #ffffff; /* Darker red brown for readability */
|
||||
background-color: #ffffff;
|
||||
/* Light background for contrast */
|
||||
background-image: url('./assets/snowflakes.png');
|
||||
/* Background image */
|
||||
background-size: cover;
|
||||
/* Cover the entire screen */
|
||||
background-position: center;
|
||||
/* Center the image */
|
||||
background-repeat: no-repeat;
|
||||
/* Prevent repeating */
|
||||
color: #ffffff;
|
||||
/* Darker red brown for readability */
|
||||
font-family: 'Plovdiv', sans-serif;
|
||||
font-size: 1.5em;
|
||||
margin: 0;
|
||||
text-align: center; /* Centered text alignment */
|
||||
text-align: center;
|
||||
/* Centered text alignment */
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
@@ -62,10 +82,12 @@ body {
|
||||
|
||||
/* Header Style */
|
||||
header {
|
||||
background-color: #a41e34; /* Christmas red */
|
||||
background-color: #a41e34;
|
||||
/* Christmas red */
|
||||
color: white;
|
||||
padding: 20px 0;
|
||||
border-bottom: 5px solid #b7c9b5; /* Light green border */
|
||||
border-bottom: 5px solid #b7c9b5;
|
||||
/* Light green border */
|
||||
}
|
||||
|
||||
header h1 {
|
||||
@@ -76,9 +98,15 @@ h1 {
|
||||
font-family: 'Pomelo', sans-serif;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
|
||||
/* Section Style */
|
||||
section {
|
||||
background-color: #e4f7e0; /* Light green background */
|
||||
background-color: #e4f7e0;
|
||||
/* Light green background */
|
||||
padding: 20px;
|
||||
border-radius: 10px;
|
||||
margin: 15px 0;
|
||||
@@ -86,103 +114,206 @@ section {
|
||||
|
||||
/* Festive Buttons */
|
||||
button {
|
||||
background-color: #b77de5; /* Purple with a slight festive flair */
|
||||
background-color: #b77de5;
|
||||
/* Purple with a slight festive flair */
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
font-size: 1.1em;
|
||||
display: inline-block; /* Centers button in the container */
|
||||
display: inline-block;
|
||||
/* Centers button in the container */
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: #9b6bb5; /* Darker purple on hover */
|
||||
background-color: #9b6bb5;
|
||||
/* Darker purple on hover */
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
background-color: #d3d3d3; /* Light gray for disabled button */
|
||||
color: #a9a9a9; /* Darker gray for text */
|
||||
cursor: not-allowed; /* Show not-allowed cursor */
|
||||
background-color: #d3d3d3;
|
||||
/* Light gray for disabled button */
|
||||
color: #a9a9a9;
|
||||
/* Darker gray for text */
|
||||
cursor: not-allowed;
|
||||
/* Show not-allowed cursor */
|
||||
}
|
||||
|
||||
/* Footer Style */
|
||||
footer {
|
||||
text-align: center; /* Centered */
|
||||
text-align: center;
|
||||
/* Centered */
|
||||
padding: 20px;
|
||||
background-color: #a41e34; /* Same red as header */
|
||||
background-color: #a41e34;
|
||||
/* Same red as header */
|
||||
color: white;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
|
||||
.table-wrapper {
|
||||
width: 100%; /* Full width of the viewport */
|
||||
text-align: center; /* Center the text (optional for non-text elements) */
|
||||
overflow-x: auto; /* Enables horizontal scrolling if necessary */
|
||||
width: 100%;
|
||||
/* Full width of the viewport */
|
||||
text-align: center;
|
||||
/* Center the text (optional for non-text elements) */
|
||||
overflow-x: auto;
|
||||
/* Enables horizontal scrolling if necessary */
|
||||
}
|
||||
|
||||
/* General table styles */
|
||||
table {
|
||||
width: 100%; /* Set table width to 80% to create space on sides */
|
||||
max-width: 100%; /* Prevents exceeding the parent's width */
|
||||
width: 100%;
|
||||
/* Set table width to 80% to create space on sides */
|
||||
max-width: 100%;
|
||||
/* Prevents exceeding the parent's width */
|
||||
color: black;
|
||||
border-collapse: collapse;
|
||||
text-align: center; /* Centered text in table */
|
||||
margin: 0 auto; /* Center the table within the wrapper */
|
||||
text-align: center;
|
||||
/* Centered text in table */
|
||||
margin: 0 auto;
|
||||
/* Center the table within the wrapper */
|
||||
}
|
||||
|
||||
|
||||
/* Table header styles */
|
||||
th {
|
||||
background-color: #060698; /* Christmas red */
|
||||
background-color: #060698;
|
||||
/* Christmas red */
|
||||
color: white;
|
||||
padding: 10px 15px;
|
||||
border-bottom: 3px solid #e0e9f7; /* Light green border for header */
|
||||
border-bottom: 3px solid #e0e9f7;
|
||||
/* Light green border for header */
|
||||
}
|
||||
|
||||
/* Table cell styles */
|
||||
td {
|
||||
border: 1px solid #ddd;
|
||||
padding: 10px 15px; /* Added padding for better spacing */
|
||||
background-color: #e0e9f7; /* Light green background for cells */
|
||||
padding: 10px 15px;
|
||||
/* Added padding for better spacing */
|
||||
background-color: #e0e9f7;
|
||||
/* Light green background for cells */
|
||||
}
|
||||
|
||||
/* Zebra striping for table rows */
|
||||
tr:nth-child(even) {
|
||||
background-color: #f9f9f9; /* Light gray for even rows */
|
||||
background-color: #f9f9f9;
|
||||
/* Light gray for even rows */
|
||||
}
|
||||
|
||||
/* Hover effect for rows */
|
||||
tr:hover {
|
||||
background-color: #c28f8f; /* Softer red when hovering */
|
||||
background-color: #c28f8f;
|
||||
/* Softer red when hovering */
|
||||
}
|
||||
|
||||
/* Additional table styling for Christmas theme */
|
||||
table {
|
||||
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); /* Shadow for depth */
|
||||
border-radius: 8px; /* Rounded corners */
|
||||
overflow: hidden; /* Ensures border radius works */
|
||||
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
|
||||
/* Shadow for depth */
|
||||
border-radius: 8px;
|
||||
/* Rounded corners */
|
||||
overflow: hidden;
|
||||
/* Ensures border radius works */
|
||||
}
|
||||
|
||||
/* Add some festive decorations */
|
||||
th::after {
|
||||
content: '🎄'; /* Small Christmas tree icon in the header */
|
||||
content: '🎄';
|
||||
/* Small Christmas tree icon in the header */
|
||||
margin-left: 10px;
|
||||
font-size: 1.2em; /* Slightly larger */
|
||||
font-size: 1.2em;
|
||||
/* Slightly larger */
|
||||
}
|
||||
|
||||
td {
|
||||
position: relative; /* For potential decorations */
|
||||
position: relative;
|
||||
/* For potential decorations */
|
||||
}
|
||||
|
||||
td::before {
|
||||
content: ''; /* Placeholder for decoration */
|
||||
content: '';
|
||||
/* Placeholder for decoration */
|
||||
position: absolute;
|
||||
background-image: url('path/to/snowflake-icon.png'); /* Snowflake icon */
|
||||
width: 16px; /* Adjust as necessary */
|
||||
background-image: url('path/to/snowflake-icon.png');
|
||||
/* Snowflake icon */
|
||||
width: 16px;
|
||||
/* Adjust as necessary */
|
||||
height: 16px;
|
||||
opacity: 0.1; /* Very subtle */
|
||||
top: 5px; /* Position it nicely */
|
||||
opacity: 0.1;
|
||||
/* Very subtle */
|
||||
top: 5px;
|
||||
/* Position it nicely */
|
||||
left: 5px;
|
||||
pointer-events: none; /* Ignore mouse events */
|
||||
pointer-events: none;
|
||||
/* Ignore mouse events */
|
||||
}
|
||||
|
||||
nav {
|
||||
top: 0; /* Align it to the top */
|
||||
background-color: rgba(0, 42, 255, 0.6);; /* Background color */
|
||||
border-radius: 20px;
|
||||
z-index: 1000; /* Make sure it stays above other content */
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
nav ul {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: flex; /* Use flex to align items */
|
||||
justify-content: space-around; /* Space the items evenly */
|
||||
}
|
||||
|
||||
nav ul li p {
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
nav ul li p:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
nav li {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
nav a {
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
nav a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.nav-toggle {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.nav-toggle {
|
||||
display: block;
|
||||
background-color: rgba(0, 42, 255, 0.6); /* Button color */
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
cursor: pointer;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
nav {
|
||||
display: none; /* Hide by default for mobile */
|
||||
flex-direction: column; /* Stack vertically */
|
||||
}
|
||||
|
||||
nav.open {
|
||||
display: flex; /* Show when open */
|
||||
}
|
||||
|
||||
nav ul {
|
||||
flex-direction: column; /* Stack menu items */
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
nav li {
|
||||
margin: 10px 0; /* Space between items */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,89 @@
|
||||
import './App.css'
|
||||
import Greeting from './components/Greeting'
|
||||
import Hosting from './components/Hosting'
|
||||
import InitialSetup from './components/InitialSetup'
|
||||
import Program from './components/Program'
|
||||
import Snowflakes from './components/Snowflakes'
|
||||
import { useState } from 'react';
|
||||
import './App.css';
|
||||
import Greeting from './components/Greeting';
|
||||
import Hosting from './components/Hosting';
|
||||
import InitialSetup from './components/InitialSetup';
|
||||
import Program from './components/Program';
|
||||
import Snowflakes from './components/Snowflakes';
|
||||
import { FullScreenLoading } from './components/Loading';
|
||||
import SecretSanta from './components/SecretSanta';
|
||||
import Suggestions from './components/Suggestions';
|
||||
import AttendanceTable from './components/AttendnaceTable';
|
||||
|
||||
function App() {
|
||||
const [isNavOpen, setIsNavOpen] = useState(false);
|
||||
|
||||
const handleLogout = () => {
|
||||
const cookies = document.cookie.split(";");
|
||||
|
||||
for (let cookie of cookies) {
|
||||
const cookieName = cookie.split("=")[0].trim();
|
||||
// Set the cookie's expiration date to the past to delete it
|
||||
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;`;
|
||||
}
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
const toggleNav = () => {
|
||||
setIsNavOpen(!isNavOpen);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<FullScreenLoading />
|
||||
<Snowflakes />
|
||||
<InitialSetup/>
|
||||
<Greeting/>
|
||||
<br/>
|
||||
<Hosting/>
|
||||
<Program/>
|
||||
<InitialSetup />
|
||||
|
||||
<button onClick={toggleNav} className="nav-toggle">
|
||||
{isNavOpen ? '❌' : 'Меню 📂'}
|
||||
</button>
|
||||
|
||||
<nav className={isNavOpen ? 'open' : ''}>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="#greeting">Приглашение</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#hosting">Поселение</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#program">Программа</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#suggestions">Пожелания</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#santa">Secret Santa</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#attendance-table">Кто празднует?</a>
|
||||
</li>
|
||||
<li>
|
||||
<button onClick={() => handleLogout()}>Выйти</button>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<div id="greeting">
|
||||
<Greeting />
|
||||
</div>
|
||||
<div id="hosting">
|
||||
<Hosting />
|
||||
</div>
|
||||
<div id="program">
|
||||
<Program />
|
||||
</div>
|
||||
<div id="suggestions">
|
||||
<Suggestions />
|
||||
</div>
|
||||
<div id="santa">
|
||||
<SecretSanta />
|
||||
</div>
|
||||
<div id="attendance-table">
|
||||
<AttendanceTable />
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export default App
|
||||
export default App;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import React, { createContext, useContext, useState } from 'react';
|
||||
|
||||
type NotificationType = 'success' | 'error';
|
||||
export type NotificationType = 'success' | 'error';
|
||||
|
||||
interface NotificationContextType {
|
||||
notify: (message: string, type: NotificationType) => void;
|
||||
|
||||
63
frontend/src/components/AttendnaceTable.tsx
Normal file
63
frontend/src/components/AttendnaceTable.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import useFetchUser from "../utils/fetchUser";
|
||||
import CenteredContainer from "./ChildrenContainer";
|
||||
import type { User } from "../types";
|
||||
|
||||
const processAttendance = (attendance: boolean | null): string => {
|
||||
if (attendance == null) {
|
||||
return "Пока не ответил"
|
||||
}
|
||||
return (attendance == true) ? "Да!" : "Не в этот раз"
|
||||
}
|
||||
|
||||
function AttendanceTable() {
|
||||
|
||||
const {getAttendanceAll} = useFetchUser()
|
||||
const [userAttendanceData, setUserAttendnaceData] = useState<User[]>([])
|
||||
|
||||
const fetchUserData = async () => {
|
||||
const userData = await getAttendanceAll()
|
||||
setUserAttendnaceData(userData)
|
||||
}
|
||||
|
||||
const handleRefresh = () => {
|
||||
fetchUserData()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchUserData()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<>
|
||||
<CenteredContainer>
|
||||
<h2>Кто празднует?</h2>
|
||||
{userAttendanceData && (
|
||||
<div className="table-wrapper">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Пятка</th>
|
||||
<th>Празднует с нами?</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{userAttendanceData && userAttendanceData.map((item) => (
|
||||
<tr>
|
||||
<td>{item.name}</td>
|
||||
<td>{processAttendance(item.attendance)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="scroll-instruction">Таблицу можно скроллить</p>
|
||||
</div>
|
||||
)}
|
||||
<br/>
|
||||
<button onClick={handleRefresh}>Обновить</button>
|
||||
</CenteredContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default AttendanceTable;
|
||||
@@ -1,5 +1,46 @@
|
||||
import { useCookies } from "react-cookie";
|
||||
import CenteredContainer from "./ChildrenContainer";
|
||||
import useFetchUser from "../utils/fetchUser";
|
||||
import type React from "react";
|
||||
import ApologyMessage from "./Attendance";
|
||||
import { useState } from "react";
|
||||
|
||||
const Attendance: React.FC = () => {
|
||||
const { updateAttendance, getAttendance } = useFetchUser()
|
||||
const [attendance, setAttendance] = useState<boolean | null>(null)
|
||||
const fetchAttendance = async () => {
|
||||
const is = await getAttendance()
|
||||
setAttendance(is)
|
||||
}
|
||||
fetchAttendance()
|
||||
|
||||
const handleUpdate = async (status: boolean) => {
|
||||
await updateAttendance(status)
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
if (attendance == false) {
|
||||
return (<ApologyMessage/>)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{attendance == null && (
|
||||
<>
|
||||
<h3>Присоеденишься?</h3>
|
||||
<p>(Можно и потом ответить)</p>
|
||||
<button style={localStyles.buttonOk} onClick={() => handleUpdate(true)}>Да!</button>
|
||||
<button style={localStyles.buttonNok} onClick={() => handleUpdate(false)}>Не смогу в этот раз</button>
|
||||
</>
|
||||
)}
|
||||
{attendance == true && (
|
||||
<>
|
||||
<h3>Круто! Ты с нами!</h3>
|
||||
<p>Если все же по разным обстоятельствам ты не сможешь/не захочешь, то всегда можно передумать</p>
|
||||
<button style={localStyles.buttonNok} onClick={() => handleUpdate(false)}>Все же никак</button>
|
||||
</>)}
|
||||
</>)
|
||||
}
|
||||
|
||||
function Greeting() {
|
||||
const [cookie] = useCookies<string>(['userName'])
|
||||
@@ -17,10 +58,25 @@ function Greeting() {
|
||||
Приглашаем тебя отпраздновать предстоящий Новый Год <b>2025-2026</b> с нами в сосновой избе, в которой, ко всему прочему, будет праздноваться годовщина нашей жизни в ней!
|
||||
|
||||
Наши двери открыты с <b>30.12.2025</b>. Праздник обычно длится до <b>01.01.2025</b>, но если тебе или твоим спутникам будет безумно плохо, то можно остаться и до второго числа.
|
||||
|
||||
</p>
|
||||
<Attendance/>
|
||||
</CenteredContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const localStyles = {
|
||||
buttonOk: {
|
||||
margin: '0.5em',
|
||||
padding: '0.3em',
|
||||
backgroundColor: 'green'
|
||||
},
|
||||
buttonNok: {
|
||||
margin: '0.5em',
|
||||
padding: '0.3em',
|
||||
backgroundColor: 'red'
|
||||
}
|
||||
}
|
||||
|
||||
export default Greeting;
|
||||
@@ -1,43 +1,82 @@
|
||||
import useFetchHosting from "../utils/fetchHosting";
|
||||
import { useNotification } from "../NotificationContext";
|
||||
import { useNotification, type NotificationType } from "../NotificationContext";
|
||||
import { useCookies } from "react-cookie";
|
||||
import CenteredContainer from "./ChildrenContainer";
|
||||
import { useState } from "react";
|
||||
|
||||
|
||||
interface ReserveButtonProps {
|
||||
update: (name: string, id: number) => void,
|
||||
unreserve: (token: string, id: number) => void,
|
||||
reservedBy: string,
|
||||
notify: (message: string, type: NotificationType) => void,
|
||||
id: number,
|
||||
}
|
||||
|
||||
const ReserveButton: React.FC<ReserveButtonProps> = (props) => {
|
||||
const { reservedBy, update, id } = props;
|
||||
const { reservedBy, update, id, unreserve, notify } = props;
|
||||
const [cookie] = useCookies<string>(['userName'])
|
||||
const [tokenCookie] = useCookies<string>(['apiToken'])
|
||||
const userName = cookie.userName;
|
||||
const isReserved = reservedBy !== '';
|
||||
const notify = useNotification();
|
||||
|
||||
const handleReserve = async () => {
|
||||
const handleReserve = async (name: string) => {
|
||||
try {
|
||||
await update(userName, id);
|
||||
notify(`Успешно забронировано для ${userName}`, 'success');
|
||||
await update(name, id);
|
||||
notify(`Успешно забронировано для ${name}`, 'success');
|
||||
} catch (error) {
|
||||
notify(`Не удалось забронировать: ${error instanceof Error ? error.message : 'Unknown error'}`, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleUnreserve = async () => {
|
||||
try {
|
||||
await unreserve(tokenCookie.apiToken, id);
|
||||
notify(`Удалось разбронировать ${name}`, 'success');
|
||||
} catch (error) {
|
||||
notify(`Не удалось разбронировать: ${error instanceof Error ? error.message : 'Unknown error'}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={handleReserve} disabled={isReserved}>
|
||||
<button onClick={() => handleReserve(userName)} disabled={isReserved}>
|
||||
{isReserved ? `${reservedBy}` : 'Занять'}
|
||||
</button>
|
||||
{(reservedBy == userName) && (
|
||||
<button onClick={() => handleUnreserve()} disabled={false}>❌</button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
function Hosting() {
|
||||
|
||||
const { data, error, loading, update } = useFetchHosting();
|
||||
const Hosting = () => {
|
||||
const { data, error, loading, update, unreserveHosting, createHosting } = useFetchHosting();
|
||||
const [name, setName] = useState('');
|
||||
const [capacity, setCapacity] = useState('');
|
||||
const [tokenCookie] = useCookies<string>(['apiToken'])
|
||||
const notify = useNotification();
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault(); // Prevent the default form submission
|
||||
|
||||
if (!name || !capacity) {
|
||||
notify('Надо заполнить все поля', 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await createHosting(tokenCookie.apiToken, name, Number(capacity));
|
||||
|
||||
// Reset form fields
|
||||
setName('');
|
||||
setCapacity('');
|
||||
notify('Удалось создать!', 'success');
|
||||
} catch (error) {
|
||||
notify(`Не удалось создать: ${error instanceof Error ? error.message : 'Unknown error'}`, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<CenteredContainer>
|
||||
@@ -63,11 +102,13 @@ function Hosting() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{Object.entries(data).map(([id, item]) => (
|
||||
<tr key={id}>
|
||||
{data.furniture && data.furniture.map((item) => (
|
||||
<tr key={item.id}>
|
||||
<td>{item.name}</td>
|
||||
<td>{item.capacity}</td>
|
||||
<td>{<ReserveButton update={update} reservedBy={item.reservedBy} id={Number(id)} />}</td>
|
||||
<td>
|
||||
<ReserveButton update={update} reservedBy={item.reservedBy} id={item.id} unreserve={unreserveHosting} notify={notify} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@@ -75,10 +116,39 @@ function Hosting() {
|
||||
<p className="scroll-instruction">Таблицу можно скроллить</p>
|
||||
</div>
|
||||
)}
|
||||
Если вы хотите организовать себе свои спальные места и хотите, чтобы остальные это видели, вы можете добавить свое месо в таблицу.
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div>
|
||||
<label>
|
||||
Размещение:
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label>
|
||||
Спальных мест:
|
||||
<input
|
||||
type="number"
|
||||
value={capacity}
|
||||
onChange={(e) => setCapacity(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<button type="submit">
|
||||
{'Создать размещение'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
</CenteredContainer>
|
||||
<br />
|
||||
</>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export default Hosting;
|
||||
@@ -3,7 +3,7 @@ import { useCookies } from 'react-cookie';
|
||||
import { GUESTS } from '../constants/constants';
|
||||
import useFetchUser from '../utils/fetchUser'; // Import your custom hook
|
||||
import { useNotification } from '../NotificationContext';
|
||||
import ApologyMessage from './Attendance';
|
||||
import {Loading} from './Loading';
|
||||
|
||||
const InitialSetup = () => {
|
||||
const [cookie, setCookie] = useCookies();
|
||||
@@ -12,9 +12,8 @@ const InitialSetup = () => {
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
const [password, setPassword] = useState('');
|
||||
const [isPasswordSet, setIsPasswordSet] = useState(false); // To track if password is set
|
||||
const [userAttendance, setUserAttendance] = useState<boolean | null>(null);
|
||||
|
||||
const { userSet, passwordCreate, signUser, validToken, getAttendance } = useFetchUser(); // Destructure functions from the hook
|
||||
const { userSet, passwordCreate, signUser, validToken, isLoading } = useFetchUser(); // Destructure functions from the hook
|
||||
const notify = useNotification();
|
||||
|
||||
const checkUserPassword = async (name: string) => {
|
||||
@@ -34,14 +33,8 @@ const InitialSetup = () => {
|
||||
setIsSubmitted(isTokenValid);
|
||||
};
|
||||
|
||||
const getUserAttendance = async () => {
|
||||
const attendance = await getAttendance()
|
||||
setUserAttendance(attendance)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (cookie.apiToken !== undefined) {
|
||||
getUserAttendance()
|
||||
validateToken();
|
||||
}
|
||||
}, [cookie.apiToken]);
|
||||
@@ -65,14 +58,17 @@ const InitialSetup = () => {
|
||||
validateToken()
|
||||
};
|
||||
|
||||
if (isSubmitted && userAttendance !== false) {
|
||||
if (isSubmitted) {
|
||||
console.log('Selected', selectedName);
|
||||
return null; // or you can redirect to another component or page
|
||||
}
|
||||
|
||||
if (userAttendance == false) {
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<ApologyMessage/>
|
||||
<div style={styles.container}>
|
||||
<Loading/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
29
frontend/src/components/Loading.css
Normal file
29
frontend/src/components/Loading.css
Normal file
@@ -0,0 +1,29 @@
|
||||
.spinner {
|
||||
font-size: 100px; /* Adjust size as needed */
|
||||
animation: spin 2s linear infinite; /* Spin animation */
|
||||
position: fixed; /* Keep the snowflake in a fixed position */
|
||||
top: 50%; /* Adjust vertical position */
|
||||
left: 50%; /* Center horizontally */
|
||||
transform: translateX(-50%); /* Center the snowflake */
|
||||
z-index: 10000; /* Ensure it's above the full-screen loading */
|
||||
}
|
||||
|
||||
/* Keyframes for spinning */
|
||||
@keyframes spin {
|
||||
0% { transform: translateX(-50%) rotate(0deg); }
|
||||
100% { transform: translateX(-50%) rotate(360deg); }
|
||||
}
|
||||
|
||||
|
||||
.full-screen {
|
||||
display: flex; /* Use flexbox for centering */
|
||||
align-items: center; /* Center vertically */
|
||||
justify-content: center; /* Center horizontally */
|
||||
height: 100vh; /* Full viewport height */
|
||||
width: 100vw; /* Full viewport width */
|
||||
background-color: rgba(4, 0, 0); /* Semi-transparent background */
|
||||
position: fixed; /* Fix it in the viewport */
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 9999; /* Ensure it's above other content */
|
||||
}
|
||||
34
frontend/src/components/Loading.tsx
Normal file
34
frontend/src/components/Loading.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import './Loading.css'; // Import CSS for styling
|
||||
|
||||
export const Loading: React.FC = () => {
|
||||
return (
|
||||
<div className="spinner">
|
||||
🎅🏻
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const FullScreenLoading: React.FC = () => {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
// Set a timeout to change the loading state
|
||||
const timer = setTimeout(() => {
|
||||
setIsLoading(false);
|
||||
}, 1000); // 1000 ms = 1 second
|
||||
|
||||
// Cleanup function to clear the timeout if the component unmounts
|
||||
return () => clearTimeout(timer);
|
||||
}, []); // Empty dependency array means it runs once on mount
|
||||
|
||||
if (!isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="full-screen">
|
||||
<Loading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
73
frontend/src/components/SecretSanta.tsx
Normal file
73
frontend/src/components/SecretSanta.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import CenteredContainer from "./ChildrenContainer";
|
||||
import useFetchUser from "../utils/fetchUser.tsx"
|
||||
import type { SantaInfo } from "../types/index";
|
||||
import { useState } from "react";
|
||||
import { useNotification } from "../NotificationContext.tsx";
|
||||
|
||||
function SecretSanta() {
|
||||
|
||||
const { updateWishlist, getSantaInfo } = useFetchUser()
|
||||
const [santaInfo, setSantaInfo] = useState<SantaInfo | null>(null)
|
||||
const [wishListUrl, setWishListUrl] = useState('')
|
||||
|
||||
const notify = useNotification();
|
||||
|
||||
const fetchSecretSanta = async () => {
|
||||
const santaInfoData = await getSantaInfo()
|
||||
setSantaInfo(santaInfoData)
|
||||
}
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
const updated = await updateWishlist(wishListUrl)
|
||||
|
||||
if (updated) {
|
||||
notify('Вишлсит обновлен', 'success')
|
||||
} else {
|
||||
notify('Не удалось обновить вишлист, все вопросы к админу', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<CenteredContainer>
|
||||
<h2>Secret Santa</h2>
|
||||
<p className="mainText">
|
||||
{santaInfo ? (
|
||||
<>
|
||||
<p>Вы санта для Пятки: <b>{santaInfo.santa_to}</b></p>
|
||||
{santaInfo.wishlist ? (
|
||||
<h4>Пятка оставила вам <a href={santaInfo.wishlist}>вишлист</a></h4>
|
||||
) : (
|
||||
<h4>Пятка не оставила вам вишлист, используйте свое воображение. Либо ждите, пока добавит...</h4>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<button type="submit" onClick={fetchSecretSanta}>Показать чей я Санта!</button>
|
||||
)}
|
||||
<hr style={{ color: 'white'}}/>
|
||||
<b>Добавить свой вишлист</b>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div>
|
||||
<label>
|
||||
Ссылка на вишлист:
|
||||
<input
|
||||
type="url"
|
||||
value={wishListUrl}
|
||||
onChange={(e) => setWishListUrl(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" style={{ margin: '20px 0.5em' }}>
|
||||
{'Отправить'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
</p>
|
||||
</CenteredContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default SecretSanta;
|
||||
@@ -6,7 +6,7 @@
|
||||
height: 100%;
|
||||
pointer-events: none; /* Make snowflakes non-interactive */
|
||||
overflow: hidden; /* Hide overflow */
|
||||
z-index: 1000; /* Ensure snowflakes are above other content */
|
||||
z-index: 998; /* Ensure snowflakes are above other content */
|
||||
}
|
||||
|
||||
.snowflake {
|
||||
@@ -14,7 +14,7 @@
|
||||
top: -10%; /* Start above the top of the screen */
|
||||
color: white; /* Snowflake color */
|
||||
font-size: 1em; /* Size of the snowflake; adjust as needed */
|
||||
opacity: 0.8; /* Transparency */
|
||||
opacity: 0.5; /* Transparency */
|
||||
animation: fall linear infinite; /* Apply the fall animation */
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ const Snowflakes: React.FC = () => {
|
||||
className="snowflake"
|
||||
style={{
|
||||
left: `${Math.random() * 100}vw`, // Random position across the full width
|
||||
animationDuration: `${Math.random() * 3 + 2}s`, // Random fall duration between 2s and 5s
|
||||
animationDuration: `${Math.random() * 20 + 10}s`, // Random fall duration between 2s and 5s
|
||||
}}
|
||||
>
|
||||
❄️
|
||||
|
||||
19
frontend/src/components/Suggestions.tsx
Normal file
19
frontend/src/components/Suggestions.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import CenteredContainer from "./ChildrenContainer";
|
||||
|
||||
function Sugegstions() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<CenteredContainer>
|
||||
<h2>Ваши предложения и пожелания</h2>
|
||||
<p className="mainText">
|
||||
Тут вы можете оставить ваши пожелания/предпочтения для чего-либо. Хотите ли вы купить ракеты, поехат в какой-то из дней куда-то, какое основное блюдо вы бы хотели тд и тп...
|
||||
<br/><br/>
|
||||
Таблица в производстве... Ожидайте к <b>середине-концу ноября</b>
|
||||
</p>
|
||||
</CenteredContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Sugegstions;
|
||||
19
frontend/src/types/index.d.ts
vendored
19
frontend/src/types/index.d.ts
vendored
@@ -1,11 +1,22 @@
|
||||
// src/types/index.d.ts
|
||||
|
||||
export interface Furniture {
|
||||
reservedBy: string;
|
||||
name: string;
|
||||
capacity: number;
|
||||
id: number; // Unique identifier for the furniture
|
||||
name: string; // Name of the furniture
|
||||
capacity: number; // Capacity of the furniture
|
||||
reservedBy: string; // Name of the person who reserved the furniture
|
||||
}
|
||||
|
||||
export interface Hosting {
|
||||
[key: number]: Furniture;
|
||||
furniture: Furniture[]; // Array of furniture items
|
||||
}
|
||||
|
||||
export interface User {
|
||||
attendance: boolean | null
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface SantaInfo {
|
||||
santa_to: string,
|
||||
wishlist: string
|
||||
}
|
||||
|
||||
@@ -2,31 +2,8 @@ import { useState, useEffect } from 'react';
|
||||
import type { Hosting } from '../types';
|
||||
import { API_URL } from '../constants/constants';
|
||||
|
||||
const mockData: Hosting = {
|
||||
1: {
|
||||
reservedBy: "",
|
||||
name: "Матрац 160см",
|
||||
capacity: 2
|
||||
},
|
||||
2: {
|
||||
reservedBy: "Vasya",
|
||||
name: "Кровать 120см",
|
||||
capacity: 2
|
||||
},
|
||||
3: {
|
||||
reservedBy: "",
|
||||
name: "Матрац 90см",
|
||||
capacity: 1
|
||||
},
|
||||
4: {
|
||||
reservedBy: "",
|
||||
name: "Диван",
|
||||
capacity: 1
|
||||
},
|
||||
};
|
||||
|
||||
const useFetchHosting = () => {
|
||||
const [data, setData] = useState(mockData);
|
||||
const [data, setData] = useState<Hosting|null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
@@ -69,12 +46,59 @@ const useFetchHosting = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const unreserveHosting = async (token: string, id: number) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/hosting/${id}/unreserve`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ token })
|
||||
});
|
||||
|
||||
if (!response.ok) { // Check for non-200 responses
|
||||
const errorText = await response.text(); // Capture the response text for further insights
|
||||
throw new Error(`Error ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
// Optional: Fetch the updated data after reservation
|
||||
await fetchData();
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const createHosting = async (token: string, name: string, capacity: number) => {
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/hosting/create`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ token, name, capacity })
|
||||
});
|
||||
|
||||
if (!response.ok) { // Check for non-200 responses
|
||||
const errorText = await response.text(); // Capture the response text for further insights
|
||||
console.log(`Error ${response.status}: ${errorText}`)
|
||||
throw new Error(`Error ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
// Optional: Fetch the updated data after reservation
|
||||
await fetchData();
|
||||
} finally {
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
//fetchData(); // Initial fetch on mount
|
||||
fetchData(); // Initial fetch on mount
|
||||
}, []);
|
||||
|
||||
return { data, error, loading, refetch: fetchData, update: updateData };
|
||||
return { data, error, loading, refetch: fetchData, update: updateData, unreserveHosting, createHosting};
|
||||
};
|
||||
|
||||
export default useFetchHosting;
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
import { useCookies } from 'react-cookie';
|
||||
import { API_URL } from '../constants/constants';
|
||||
import { hashPassword } from './hashPassword';
|
||||
import { useState } from 'react';
|
||||
import type { User, SantaInfo } from '../types';
|
||||
|
||||
const useFetchUser = () => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [apiCookie, setApiCookie] = useCookies(['apiToken']);
|
||||
const [, setUserNameCookie] = useCookies(['userName'])
|
||||
|
||||
const userSet = async (userName: string): Promise<boolean> => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
const response = await fetch(`${API_URL}/users/isSet?userName=${encodeURIComponent(userName)}`);
|
||||
setIsLoading(false)
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const data = await response.json();
|
||||
return data; // Assuming the server returns true/false
|
||||
@@ -84,6 +89,7 @@ const useFetchUser = () => {
|
||||
|
||||
const validToken = async (token: string | undefined): Promise<boolean> => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
const response = await fetch(`${API_URL}/login/validateToken`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -93,6 +99,7 @@ const useFetchUser = () => {
|
||||
token
|
||||
}),
|
||||
});
|
||||
setIsLoading(false)
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const data = await response.json();
|
||||
@@ -108,6 +115,76 @@ const useFetchUser = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const getAttendance = async (): Promise<boolean | null> => {
|
||||
const token = apiCookie.apiToken
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/users/attendance?token=${encodeURIComponent(token)}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.success) throw new Error(data.message);
|
||||
|
||||
return data.attendance
|
||||
} catch (error) {
|
||||
console.error('Error retrieving attendance:', error);
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const updateWishlist = async (wishlistUrl: string): Promise<boolean> => {
|
||||
const token = apiCookie.apiToken
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/users/wishlist`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
token,
|
||||
wishlist: wishlistUrl,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.success) throw new Error(data.message);
|
||||
|
||||
return true; // Attendance updated successfully
|
||||
} catch (error) {
|
||||
console.error('Error updating wishlist:', error);
|
||||
return false; // Attendance update failed
|
||||
}
|
||||
}
|
||||
|
||||
const getSantaInfo = async (): Promise<SantaInfo | null> => {
|
||||
const token = apiCookie.apiToken
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/users/santa?token=${encodeURIComponent(token)}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.success) throw new Error(data.message);
|
||||
|
||||
return data.santa_info
|
||||
} catch (error) {
|
||||
console.error('Error retrieving attendance:', error);
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const updateAttendance = async (attendanceStatus: boolean): Promise<boolean> => {
|
||||
const token = apiCookie.apiToken
|
||||
try {
|
||||
@@ -134,10 +211,10 @@ const useFetchUser = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const getAttendance = async (): Promise<boolean | null> => {
|
||||
const getAttendanceAll = async (): Promise<User[]> => {
|
||||
const token = apiCookie.apiToken
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/users/attendance?token=${encodeURIComponent(token)}`, {
|
||||
const response = await fetch(`${API_URL}/users/attendance/all?token=${encodeURIComponent(token)}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -149,14 +226,15 @@ const useFetchUser = () => {
|
||||
|
||||
if (!data.success) throw new Error(data.message);
|
||||
|
||||
return data.attendance; // Returns attendance status (true/false)
|
||||
return data.attendance_list
|
||||
} catch (error) {
|
||||
console.error('Error retrieving attendance:', error);
|
||||
return null; // In case of error or if attendance status is not found
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
return { userSet, passwordCreate, signUser, validToken, updateAttendance, getAttendance };
|
||||
|
||||
return { userSet, passwordCreate, signUser, validToken, updateAttendance, updateWishlist, getAttendance, isLoading, getAttendanceAll, getSantaInfo };
|
||||
};
|
||||
|
||||
export default useFetchUser;
|
||||
|
||||
Reference in New Issue
Block a user