Compare commits
No commits in common. "c2e6f81775a573c756516dd1015bbc6b002476d3" and "cf9b0d53c15396c76e3dff1e4cd692e6a6bd5427" have entirely different histories.
c2e6f81775
...
cf9b0d53c1
@ -13,28 +13,6 @@ STARTUP_TABLE_CREATION_QUERIES = {
|
|||||||
Token VARCHAR(2048),
|
Token VARCHAR(2048),
|
||||||
Name varchar(255)
|
Name varchar(255)
|
||||||
);""",
|
);""",
|
||||||
"hosting": """CREATE TABLE IF NOT EXISTS hosting (
|
|
||||||
id SERIAL,
|
|
||||||
Name varchar(255),
|
|
||||||
Capacity INT,
|
|
||||||
reservedBy 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):
|
class Severity(Enum):
|
||||||
@ -75,8 +53,6 @@ class DBClient:
|
|||||||
def initialize_database(self):
|
def initialize_database(self):
|
||||||
self.query(STARTUP_TABLE_CREATION_QUERIES['users'])
|
self.query(STARTUP_TABLE_CREATION_QUERIES['users'])
|
||||||
self.query(STARTUP_TABLE_CREATION_QUERIES['sessions'])
|
self.query(STARTUP_TABLE_CREATION_QUERIES['sessions'])
|
||||||
self.query(STARTUP_TABLE_CREATION_QUERIES['hosting'])
|
|
||||||
self.query(INJECT_TABLE_CREATION_QUERIES['hosting'])
|
|
||||||
|
|
||||||
def query(self, query_str, params=None):
|
def query(self, query_str, params=None):
|
||||||
max_retries = 3
|
max_retries = 3
|
||||||
|
|||||||
@ -1,146 +0,0 @@
|
|||||||
#!/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,7 +10,6 @@ from flask_cors import CORS
|
|||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from db_client import DBClient
|
from db_client import DBClient
|
||||||
from user import registerUserEndpoints
|
from user import registerUserEndpoints
|
||||||
from hosting import registerHostingEndpoints
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
@ -24,7 +23,6 @@ allowed_origins = [
|
|||||||
CORS(app, resources={r"*": {"origins": allowed_origins}}) # Only allow example.com
|
CORS(app, resources={r"*": {"origins": allowed_origins}}) # Only allow example.com
|
||||||
database = DBClient(app)
|
database = DBClient(app)
|
||||||
registerUserEndpoints(app=app, database=database)
|
registerUserEndpoints(app=app, database=database)
|
||||||
registerHostingEndpoints(app=app, database=database)
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
app.run(debug=True)
|
app.run(debug=True)
|
||||||
@ -1,4 +1,4 @@
|
|||||||
import { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import './App.css';
|
import './App.css';
|
||||||
import Greeting from './components/Greeting';
|
import Greeting from './components/Greeting';
|
||||||
import Hosting from './components/Hosting';
|
import Hosting from './components/Hosting';
|
||||||
|
|||||||
@ -2,116 +2,42 @@ import useFetchHosting from "../utils/fetchHosting";
|
|||||||
import { useNotification } from "../NotificationContext";
|
import { useNotification } from "../NotificationContext";
|
||||||
import { useCookies } from "react-cookie";
|
import { useCookies } from "react-cookie";
|
||||||
import CenteredContainer from "./ChildrenContainer";
|
import CenteredContainer from "./ChildrenContainer";
|
||||||
import { useState } from "react";
|
|
||||||
|
|
||||||
|
|
||||||
interface ReserveButtonProps {
|
interface ReserveButtonProps {
|
||||||
update: (name: string, id: number) => void,
|
update: (name: string, id: number) => void,
|
||||||
unreserve: (token: string, id: number) => void,
|
|
||||||
reservedBy: string,
|
reservedBy: string,
|
||||||
id: number,
|
id: number,
|
||||||
}
|
}
|
||||||
|
|
||||||
const ReserveButton: React.FC<ReserveButtonProps> = (props) => {
|
const ReserveButton: React.FC<ReserveButtonProps> = (props) => {
|
||||||
const { reservedBy, update, id, unreserve } = props;
|
const { reservedBy, update, id } = props;
|
||||||
const [cookie] = useCookies<string>(['userName'])
|
const [cookie] = useCookies<string>(['userName'])
|
||||||
const [tokenCookie] = useCookies<string>(['apiToken'])
|
|
||||||
const userName = cookie.userName;
|
const userName = cookie.userName;
|
||||||
const isReserved = reservedBy !== '';
|
const isReserved = reservedBy !== '';
|
||||||
const notify = useNotification();
|
const notify = useNotification();
|
||||||
|
|
||||||
const handleReserve = async (name: string) => {
|
const handleReserve = async () => {
|
||||||
try {
|
try {
|
||||||
await update(name, id);
|
await update(userName, id);
|
||||||
notify(`Успешно забронировано для ${name}`, 'success');
|
notify(`Успешно забронировано для ${userName}`, 'success');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
notify(`Не удалось забронировать: ${error instanceof Error ? error.message : 'Unknown error'}`, '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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<button onClick={() => handleReserve(userName)} disabled={isReserved}>
|
<button onClick={handleReserve} disabled={isReserved}>
|
||||||
{isReserved ? `${reservedBy}` : 'Занять'}
|
{isReserved ? `${reservedBy}` : 'Занять'}
|
||||||
</button>
|
</button>
|
||||||
{(reservedBy == userName) && (
|
|
||||||
<button onClick={() => handleUnreserve()} disabled={false}>❌</button>
|
|
||||||
)}
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
interface CreateHostingFormProps {
|
function Hosting() {
|
||||||
createHosting: (token: string, name: string, capacity: number) => void,
|
|
||||||
}
|
|
||||||
|
|
||||||
const CreateHostingForm: React.FC<CreateHostingFormProps> = (props) => {
|
const { data, error, loading, update } = useFetchHosting();
|
||||||
const { createHosting } = props;
|
|
||||||
const [name, setName] = useState('');
|
|
||||||
const [capacity, setCapacity] = useState('');
|
|
||||||
const [tokenCookie] = useCookies<string>(['apiToken'])
|
|
||||||
const notify = useNotification();
|
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
|
||||||
if (!name || !capacity) {
|
|
||||||
notify('Надо заполнить все поля', 'error')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await createHosting(tokenCookie.apiToken, name, Number(capacity)); // Call the existing hook
|
|
||||||
|
|
||||||
// Reset form fields
|
|
||||||
setName('');
|
|
||||||
setCapacity('');
|
|
||||||
notify('Удалось создать!', 'success')
|
|
||||||
} catch (error) {
|
|
||||||
notify(`Не удалось создать: ${error instanceof Error ? error.message : 'Unknown error'}`, 'error'); // Capture any error message
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<CenteredContainer>
|
<CenteredContainer>
|
||||||
@ -137,13 +63,11 @@ const Hosting = () => {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{data.furniture && data.furniture.map((item) => (
|
{Object.entries(data).map(([id, item]) => (
|
||||||
<tr key={item.id}>
|
<tr key={id}>
|
||||||
<td>{item.name}</td>
|
<td>{item.name}</td>
|
||||||
<td>{item.capacity}</td>
|
<td>{item.capacity}</td>
|
||||||
<td>
|
<td>{<ReserveButton update={update} reservedBy={item.reservedBy} id={Number(id)} />}</td>
|
||||||
<ReserveButton update={update} reservedBy={item.reservedBy} id={item.id} unreserve={unreserveHosting} />
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
@ -151,12 +75,10 @@ const Hosting = () => {
|
|||||||
<p className="scroll-instruction">Таблицу можно скроллить</p>
|
<p className="scroll-instruction">Таблицу можно скроллить</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
Если вы хотите организовать себе свои спальные места и хотите, чтобы остальные это видели, вы можете добавить свое месо в таблицу.
|
|
||||||
<CreateHostingForm createHosting={createHosting}/>
|
|
||||||
</CenteredContainer>
|
</CenteredContainer>
|
||||||
<br />
|
<br />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
}
|
||||||
|
|
||||||
export default Hosting;
|
export default Hosting;
|
||||||
9
frontend/src/types/index.d.ts
vendored
9
frontend/src/types/index.d.ts
vendored
@ -1,12 +1,11 @@
|
|||||||
// src/types/index.d.ts
|
// src/types/index.d.ts
|
||||||
|
|
||||||
export interface Furniture {
|
export interface Furniture {
|
||||||
id: number; // Unique identifier for the furniture
|
reservedBy: string;
|
||||||
name: string; // Name of the furniture
|
name: string;
|
||||||
capacity: number; // Capacity of the furniture
|
capacity: number;
|
||||||
reservedBy: string; // Name of the person who reserved the furniture
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Hosting {
|
export interface Hosting {
|
||||||
furniture: Furniture[]; // Array of furniture items
|
[key: number]: Furniture;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,8 +2,31 @@ import { useState, useEffect } from 'react';
|
|||||||
import type { Hosting } from '../types';
|
import type { Hosting } from '../types';
|
||||||
import { API_URL } from '../constants/constants';
|
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 useFetchHosting = () => {
|
||||||
const [data, setData] = useState<Hosting|null>(null);
|
const [data, setData] = useState(mockData);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
@ -46,60 +69,12 @@ 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) => {
|
|
||||||
setLoading(true);
|
|
||||||
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
|
|
||||||
throw new Error(`Error ${response.status}: ${errorText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Optional: Fetch the updated data after reservation
|
|
||||||
await fetchData();
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchData(); // Initial fetch on mount
|
//fetchData(); // Initial fetch on mount
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return { data, error, loading, refetch: fetchData, update: updateData, unreserveHosting, createHosting};
|
return { data, error, loading, refetch: fetchData, update: updateData };
|
||||||
};
|
};
|
||||||
|
|
||||||
export default useFetchHosting;
|
export default useFetchHosting;
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user