Compare commits
9 Commits
c2e6f81775
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ecf62faff | ||
|
|
06e146f1c4 | ||
|
|
5051abc440 | ||
|
|
f69fa8b563 | ||
|
|
4ff56ec06c | ||
|
|
3b6f544946 | ||
|
|
dadb094017 | ||
|
|
27ee5d59c3 | ||
|
|
c39384badf |
@@ -1,13 +1,15 @@
|
||||
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),
|
||||
@@ -19,6 +21,10 @@ STARTUP_TABLE_CREATION_QUERIES = {
|
||||
Capacity INT,
|
||||
reservedBy varchar(255)
|
||||
);""",
|
||||
"santa": """CREATE TABLE IF NOT EXISTS santa (
|
||||
Name varchar(255),
|
||||
Santa varchar(255)
|
||||
);""",
|
||||
}
|
||||
|
||||
INJECT_TABLE_CREATION_QUERIES = {
|
||||
@@ -55,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:
|
||||
@@ -78,6 +85,57 @@ class DBClient:
|
||||
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
|
||||
for attempt in range(max_retries):
|
||||
@@ -87,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -264,6 +264,15 @@ nav ul {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -6,10 +6,24 @@ 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);
|
||||
};
|
||||
@@ -35,6 +49,18 @@ function App() {
|
||||
<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>
|
||||
|
||||
@@ -47,6 +73,15 @@ function App() {
|
||||
<div id="program">
|
||||
<Program />
|
||||
</div>
|
||||
<div id="suggestions">
|
||||
<Suggestions />
|
||||
</div>
|
||||
<div id="santa">
|
||||
<SecretSanta />
|
||||
</div>
|
||||
<div id="attendance-table">
|
||||
<AttendanceTable />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,17 +1,51 @@
|
||||
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";
|
||||
|
||||
function Greeting() {
|
||||
const [cookie] = useCookies<string>(['userName'])
|
||||
const userName = cookie.userName;
|
||||
const { updateAttendance } = useFetchUser()
|
||||
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'])
|
||||
const userName = cookie.userName;
|
||||
|
||||
return (
|
||||
<>
|
||||
<CenteredContainer>
|
||||
@@ -24,11 +58,9 @@ function Greeting() {
|
||||
Приглашаем тебя отпраздновать предстоящий Новый Год <b>2025-2026</b> с нами в сосновой избе, в которой, ко всему прочему, будет праздноваться годовщина нашей жизни в ней!
|
||||
|
||||
Наши двери открыты с <b>30.12.2025</b>. Праздник обычно длится до <b>01.01.2025</b>, но если тебе или твоим спутникам будет безумно плохо, то можно остаться и до второго числа.
|
||||
<h3>Присоеденишься?</h3>
|
||||
<p>(Можно и потом ответить)</p>
|
||||
<button style={localStyles.buttonOk} onClick={() => handleUpdate(true)}>Да!</button>
|
||||
<button style={localStyles.buttonNok}onClick={() => handleUpdate(false)}>Не смогу в этот раз</button>
|
||||
|
||||
</p>
|
||||
<Attendance/>
|
||||
</CenteredContainer>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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";
|
||||
@@ -9,16 +9,16 @@ 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, unreserve } = 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 (name: string) => {
|
||||
try {
|
||||
@@ -50,68 +50,33 @@ const ReserveButton: React.FC<ReserveButtonProps> = (props) => {
|
||||
);
|
||||
};
|
||||
|
||||
interface CreateHostingFormProps {
|
||||
createHosting: (token: string, name: string, capacity: number) => void,
|
||||
}
|
||||
|
||||
const CreateHostingForm: React.FC<CreateHostingFormProps> = (props) => {
|
||||
const { createHosting } = props;
|
||||
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 () => {
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault(); // Prevent the default form submission
|
||||
|
||||
if (!name || !capacity) {
|
||||
notify('Надо заполнить все поля', 'error')
|
||||
return
|
||||
notify('Надо заполнить все поля', 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await createHosting(tokenCookie.apiToken, name, Number(capacity)); // Call the existing hook
|
||||
await createHosting(tokenCookie.apiToken, name, Number(capacity));
|
||||
|
||||
// Reset form fields
|
||||
setName('');
|
||||
setCapacity('');
|
||||
notify('Удалось создать!', 'success')
|
||||
notify('Удалось создать!', 'success');
|
||||
} catch (error) {
|
||||
notify(`Не удалось создать: ${error instanceof Error ? error.message : 'Unknown error'}`, 'error'); // Capture any error message
|
||||
notify(`Не удалось создать: ${error instanceof Error ? error.message : 'Unknown error'}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<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" onClick={() => handleSubmit()}>
|
||||
{'Создать размещение'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
const Hosting = () => {
|
||||
const { data, error, loading, update, unreserveHosting, createHosting } = useFetchHosting();
|
||||
return (
|
||||
<>
|
||||
<CenteredContainer>
|
||||
@@ -142,7 +107,7 @@ const Hosting = () => {
|
||||
<td>{item.name}</td>
|
||||
<td>{item.capacity}</td>
|
||||
<td>
|
||||
<ReserveButton update={update} reservedBy={item.reservedBy} id={item.id} unreserve={unreserveHosting} />
|
||||
<ReserveButton update={update} reservedBy={item.reservedBy} id={item.id} unreserve={unreserveHosting} notify={notify} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -152,7 +117,34 @@ const Hosting = () => {
|
||||
</div>
|
||||
)}
|
||||
Если вы хотите организовать себе свои спальные места и хотите, чтобы остальные это видели, вы можете добавить свое месо в таблицу.
|
||||
<CreateHostingForm createHosting={createHosting}/>
|
||||
<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 />
|
||||
</>
|
||||
|
||||
@@ -3,7 +3,6 @@ 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 = () => {
|
||||
@@ -13,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, isLoading } = 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) => {
|
||||
@@ -35,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]);
|
||||
@@ -66,16 +58,11 @@ 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) {
|
||||
return (
|
||||
<ApologyMessage/>
|
||||
)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
|
||||
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;
|
||||
@@ -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;
|
||||
10
frontend/src/types/index.d.ts
vendored
10
frontend/src/types/index.d.ts
vendored
@@ -10,3 +10,13 @@ export interface Furniture {
|
||||
export interface Hosting {
|
||||
furniture: Furniture[]; // Array of furniture items
|
||||
}
|
||||
|
||||
export interface User {
|
||||
attendance: boolean | null
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface SantaInfo {
|
||||
santa_to: string,
|
||||
wishlist: string
|
||||
}
|
||||
|
||||
@@ -71,7 +71,6 @@ const useFetchHosting = () => {
|
||||
};
|
||||
|
||||
const createHosting = async (token: string, name: string, capacity: number) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/hosting/create`, {
|
||||
@@ -84,13 +83,13 @@ const useFetchHosting = () => {
|
||||
|
||||
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 {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ 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)
|
||||
@@ -114,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 {
|
||||
@@ -140,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',
|
||||
@@ -155,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, isLoading };
|
||||
|
||||
return { userSet, passwordCreate, signUser, validToken, updateAttendance, updateWishlist, getAttendance, isLoading, getAttendanceAll, getSantaInfo };
|
||||
};
|
||||
|
||||
export default useFetchUser;
|
||||
|
||||
Reference in New Issue
Block a user