basic profile
This commit is contained in:
3
.env
3
.env
@@ -1,11 +1,12 @@
|
||||
# ============== POSTGRES ==============
|
||||
POSTGRES_SERVER=db
|
||||
POSTGRES_DB=mydatabase
|
||||
POSTGRES_USER=myuser
|
||||
POSTGRES_PASSWORD=mysecretpassword
|
||||
|
||||
# URL del database per SQLAlchemy e Alembic
|
||||
# La porta 5432 è quella interna di Docker. 'db' è il nome del servizio in docker-compose.
|
||||
DATABASE_URL=postgresql://myuser:mysecretpassword@db:5432/mydatabase
|
||||
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_SERVER}/${POSTGRES_DB}
|
||||
|
||||
# ============== FRONTEND ==============
|
||||
# L'URL a cui il frontend contatterà il backend (attraverso il proxy)
|
||||
|
||||
148
ackages/frontend/src/components/CelebrityProfile.jsx
Normal file
148
ackages/frontend/src/components/CelebrityProfile.jsx
Normal file
@@ -0,0 +1,148 @@
|
||||
// packages/frontend/src/components/CelebrityProfile.jsx
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useParams, useNavigate, Link } from 'react-router-dom';
|
||||
import { getCelebrityById, updateCelebrity, deleteCelebrity } from '../services/api';
|
||||
import EditableField from './EditableField';
|
||||
import './CelebrityProfile.css'; // Importa il nuovo CSS
|
||||
|
||||
function CelebrityProfile() {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [celebrity, setCelebrity] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Ignoriamo la modalità "new", questa pagina è solo per visualizzare/modificare
|
||||
if (id) {
|
||||
setLoading(true);
|
||||
getCelebrityById(id)
|
||||
.then((data) => {
|
||||
// Formatta la data per l'input type="date"
|
||||
if (data.birth_date) {
|
||||
data.birth_date = data.birth_date.split('T')[0];
|
||||
}
|
||||
setCelebrity(data);
|
||||
})
|
||||
.catch((err) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
} else {
|
||||
navigate('/'); // Se non c'è id, torna alla home
|
||||
}
|
||||
}, [id, navigate]);
|
||||
|
||||
const handleFieldSave = async (fieldName, newValue) => {
|
||||
// Converte stringa vuota a null per il backend
|
||||
const valueToSend = newValue === '' ? null : newValue;
|
||||
const payload = { [fieldName]: valueToSend };
|
||||
|
||||
try {
|
||||
const updatedCelebrity = await updateCelebrity(id, payload);
|
||||
// Aggiorna lo stato locale per un feedback immediato
|
||||
setCelebrity((prev) => ({ ...prev, [fieldName]: newValue }));
|
||||
console.log('Salvataggio riuscito:', updatedCelebrity);
|
||||
} catch (err) {
|
||||
setError(`Errore durante il salvataggio del campo ${fieldName}: ${err.message}`);
|
||||
// Potresti voler ripristinare il valore precedente in caso di errore
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (window.confirm(`Sei sicuro di voler eliminare ${celebrity.name}? L'azione è irreversibile.`)) {
|
||||
try {
|
||||
await deleteCelebrity(id);
|
||||
alert(`${celebrity.name} è stato eliminato con successo.`);
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
setError(`Errore durante l'eliminazione: ${err.message}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <p>Caricamento profilo...</p>;
|
||||
if (error) return <p className="error-message">Errore: {error}</p>;
|
||||
if (!celebrity) return <p>Nessuna celebrità trovata.</p>;
|
||||
|
||||
// Opzioni per i campi <select>
|
||||
const genderOptions = [
|
||||
{ value: 'female', label: 'Female' }, { value: 'male', label: 'Male' }, { value: 'other', label: 'Other' },
|
||||
];
|
||||
const braSystemOptions = [
|
||||
{ value: 'US', label: 'US' }, { value: 'UK', label: 'UK' }, { value: 'EU', label: 'EU' },
|
||||
{ value: 'FR', label: 'FR' }, { value: 'AU', label: 'AU' }, { value: 'IT', label: 'IT' }, { value: 'JP', label: 'JP' },
|
||||
];
|
||||
const booleanOptions = [
|
||||
{ value: 'true', label: 'Sì' }, { value: 'false', label: 'No' },
|
||||
];
|
||||
|
||||
|
||||
return (
|
||||
<div className="profile-container">
|
||||
<div className="profile-sidebar">
|
||||
{/* Immagine del profilo (placeholder) */}
|
||||
<img src={`https://i.pravatar.cc/300?u=${id}`} alt={celebrity.name} className="profile-main-image" />
|
||||
<div className="thumbnails">
|
||||
{/* Placeholder per le miniature */}
|
||||
<div className="thumbnail"><img src={`https://i.pravatar.cc/150?u=${id}a`} alt="thumbnail" /></div>
|
||||
<div className="thumbnail"><img src={`https://i.pravatar.cc/150?u=${id}b`} alt="thumbnail" /></div>
|
||||
<div className="thumbnail"><img src={`https://i.pravatar.cc/150?u=${id}c`} alt="thumbnail" /></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="profile-content">
|
||||
<div className="profile-header">
|
||||
<h1>{celebrity.name}</h1>
|
||||
<EditableField label="Nome completo / Alias" name="name" value={celebrity.name} onSave={handleFieldSave} />
|
||||
</div>
|
||||
|
||||
<section className="profile-section">
|
||||
<h2>Dati Personali</h2>
|
||||
<div className="profile-grid">
|
||||
<EditableField label="Data di nascita" name="birth_date" value={celebrity.birth_date} type="date" onSave={handleFieldSave} />
|
||||
<EditableField label="Luogo di nascita" name="birth_place" value={celebrity.birth_place} onSave={handleFieldSave} />
|
||||
<EditableField label="Nazionalità" name="nationality" value={celebrity.nationality} onSave={handleFieldSave} />
|
||||
<EditableField label="Etnia" name="ethnicity" value={celebrity.ethnicity} onSave={handleFieldSave} />
|
||||
<EditableField label="Genere" name="gender" value={celebrity.gender} type="select" options={genderOptions} onSave={handleFieldSave} />
|
||||
<EditableField label="Sessualità" name="sexuality" value={celebrity.sexuality} onSave={handleFieldSave} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="profile-section">
|
||||
<h2>Aspetto Fisico</h2>
|
||||
<div className="profile-grid">
|
||||
<EditableField label="Colore Capelli" name="hair_color" value={celebrity.hair_color} onSave={handleFieldSave} />
|
||||
<EditableField label="Colore Occhi" name="eye_color" value={celebrity.eye_color} onSave={handleFieldSave} />
|
||||
<EditableField label="Altezza (cm)" name="height_cm" value={celebrity.height_cm} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Peso (kg)" name="weight_kg" value={celebrity.weight_kg} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Seno (cm)" name="bust_cm" value={celebrity.bust_cm} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Vita (cm)" name="waist_cm" value={celebrity.waist_cm} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Fianchi (cm)" name="hips_cm" value={celebrity.hips_cm} type="number" onSave={handleFieldSave} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="profile-section">
|
||||
<h2>Reggiseno</h2>
|
||||
<div className="profile-grid">
|
||||
<EditableField label="Misura Fascia" name="bra_band_size" value={celebrity.bra_band_size} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Coppa" name="bra_cup_size" value={celebrity.bra_cup_size} onSave={handleFieldSave} />
|
||||
<EditableField label="Sistema" name="bra_size_system" value={celebrity.bra_size_system} type="select" options={braSystemOptions} onSave={handleFieldSave} />
|
||||
<EditableField label="Seno Naturale?" name="boobs_are_natural" value={String(celebrity.boobs_are_natural)} type="select" options={booleanOptions} onSave={handleFieldSave} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="profile-section">
|
||||
<h2>Biografia</h2>
|
||||
<EditableField label="Note biografiche" name="biography" value={celebrity.biography} type="textarea" onSave={handleFieldSave} />
|
||||
</section>
|
||||
|
||||
<div className="profile-actions">
|
||||
<Link to="/" className="button-back">Torna alla Lista</Link>
|
||||
<button onClick={handleDelete} className="button-delete">Elimina Profilo</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CelebrityProfile;
|
||||
13
packages/backend/.env
Normal file
13
packages/backend/.env
Normal file
@@ -0,0 +1,13 @@
|
||||
# ============== POSTGRES ==============
|
||||
POSTGRES_SERVER=db
|
||||
POSTGRES_DB=mydatabase
|
||||
POSTGRES_USER=myuser
|
||||
POSTGRES_PASSWORD=mysecretpassword
|
||||
|
||||
# URL del database per SQLAlchemy e Alembic
|
||||
# La porta 5432 è quella interna di Docker. 'db' è il nome del servizio in docker-compose.
|
||||
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_SERVER}/${POSTGRES_DB}
|
||||
|
||||
# ============== FRONTEND ==============
|
||||
# L'URL a cui il frontend contatterà il backend (attraverso il proxy)
|
||||
VITE_API_URL=http://localhost:8080/api
|
||||
@@ -1,10 +1,147 @@
|
||||
# ... altre configurazioni ...
|
||||
[alembic]
|
||||
# ...
|
||||
script_location = alembic
|
||||
# ...
|
||||
# A generic, single database configuration.
|
||||
|
||||
# Aggiungi questa riga per leggere l'URL dal file .env
|
||||
[alembic]
|
||||
# path to migration scripts.
|
||||
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||
# format, relative to the token %(here)s which refers to the location of this
|
||||
# ini file
|
||||
script_location = %(here)s/alembic
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory. for multiple paths, the path separator
|
||||
# is defined by "path_separator" below.
|
||||
prepend_sys_path = .
|
||||
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
|
||||
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
|
||||
# string value is passed to ZoneInfo()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to <script_location>/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "path_separator"
|
||||
# below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||
|
||||
# path_separator; This indicates what character is used to split lists of file
|
||||
# paths, including version_locations and prepend_sys_path within configparser
|
||||
# files such as alembic.ini.
|
||||
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||
# to provide os-dependent path splitting.
|
||||
#
|
||||
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||
# take place if path_separator is not present in alembic.ini. If this
|
||||
# option is omitted entirely, fallback logic is as follows:
|
||||
#
|
||||
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||
# behavior of splitting on spaces and/or commas.
|
||||
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||
# behavior of splitting on spaces, commas, or colons.
|
||||
#
|
||||
# Valid values for path_separator are:
|
||||
#
|
||||
# path_separator = :
|
||||
# path_separator = ;
|
||||
# path_separator = space
|
||||
# path_separator = newline
|
||||
#
|
||||
# Use os.pathsep. Default configuration used for new projects.
|
||||
path_separator = os
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# database URL. This is consumed by the user-maintained env.py script only.
|
||||
# other means of configuring database URLs may be customized within the env.py
|
||||
# file.
|
||||
sqlalchemy.url = ${DATABASE_URL}
|
||||
|
||||
# ... altre configurazioni ...
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||
# hooks = ruff
|
||||
# ruff.type = module
|
||||
# ruff.module = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration. This is also consumed by the user-maintained
|
||||
# env.py script only.
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
|
||||
1
packages/backend/alembic/README
Normal file
1
packages/backend/alembic/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
BIN
packages/backend/alembic/__pycache__/env.cpython-311.pyc
Normal file
BIN
packages/backend/alembic/__pycache__/env.cpython-311.pyc
Normal file
Binary file not shown.
45
packages/backend/alembic/env.py
Normal file
45
packages/backend/alembic/env.py
Normal file
@@ -0,0 +1,45 @@
|
||||
# packages/backend/alembic/env.py
|
||||
|
||||
import os
|
||||
import sys
|
||||
from logging.config import fileConfig
|
||||
|
||||
from dotenv import load_dotenv # <--- 1. AGGIUNGI QUESTO IMPORT
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
# Aggiungi la root del progetto (/app) al percorso di ricerca di Python
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||
|
||||
# Aggiungi l'import del tuo modello specifico sotto l'import di Base
|
||||
from app.models import Base, Celebrity
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# === 2. AGGIUNGI QUESTA SEZIONE PER CARICARE LA VARIABILE D'AMBIENTE ===
|
||||
# Carica il file .env che si trova nella root del progetto (/app)
|
||||
# Dato che lo script è in /app/alembic, dobbiamo risalire di un livello
|
||||
dotenv_path = os.path.join(os.path.dirname(__file__), '..', '.env')
|
||||
load_dotenv(dotenv_path=dotenv_path)
|
||||
|
||||
# Imposta programmaticamente l'URL del database nell'oggetto di configurazione di Alembic
|
||||
config.set_main_option('sqlalchemy.url', os.getenv('DATABASE_URL'))
|
||||
# === FINE DELLA SEZIONE DA AGGIUNGERE ===
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# ... il resto del file rimane invariato ...
|
||||
28
packages/backend/alembic/script.py.mako
Normal file
28
packages/backend/alembic/script.py.mako
Normal file
@@ -0,0 +1,28 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Initial migration with celebrities table
|
||||
|
||||
Revision ID: 23353f53a7cf
|
||||
Revises:
|
||||
Create Date: 2025-10-10 17:00:56.622311
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '23353f53a7cf'
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
pass
|
||||
Binary file not shown.
BIN
packages/backend/app/__pycache__/crud.cpython-311.pyc
Normal file
BIN
packages/backend/app/__pycache__/crud.cpython-311.pyc
Normal file
Binary file not shown.
BIN
packages/backend/app/__pycache__/database.cpython-311.pyc
Normal file
BIN
packages/backend/app/__pycache__/database.cpython-311.pyc
Normal file
Binary file not shown.
Binary file not shown.
BIN
packages/backend/app/__pycache__/models.cpython-311.pyc
Normal file
BIN
packages/backend/app/__pycache__/models.cpython-311.pyc
Normal file
Binary file not shown.
BIN
packages/backend/app/__pycache__/schemas.cpython-311.pyc
Normal file
BIN
packages/backend/app/__pycache__/schemas.cpython-311.pyc
Normal file
Binary file not shown.
37
packages/backend/app/crud.py
Normal file
37
packages/backend/app/crud.py
Normal file
@@ -0,0 +1,37 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from . import models, schemas
|
||||
|
||||
def get_celebrity(db: Session, celebrity_id: int):
|
||||
return db.query(models.Celebrity).filter(models.Celebrity.id == celebrity_id).first()
|
||||
|
||||
def get_celebrities(db: Session, skip: int = 0, limit: int = 100):
|
||||
return db.query(models.Celebrity).offset(skip).limit(limit).all()
|
||||
|
||||
def create_celebrity(db: Session, celebrity: schemas.CelebrityCreate):
|
||||
db_celebrity = models.Celebrity(**celebrity.model_dump())
|
||||
db.add(db_celebrity)
|
||||
db.commit()
|
||||
db.refresh(db_celebrity)
|
||||
return db_celebrity
|
||||
|
||||
def update_celebrity(db: Session, celebrity_id: int, celebrity_update: schemas.CelebrityUpdate):
|
||||
db_celebrity = get_celebrity(db, celebrity_id)
|
||||
if not db_celebrity:
|
||||
return None
|
||||
|
||||
update_data = celebrity_update.model_dump(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(db_celebrity, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_celebrity)
|
||||
return db_celebrity
|
||||
|
||||
def delete_celebrity(db: Session, celebrity_id: int):
|
||||
db_celebrity = get_celebrity(db, celebrity_id)
|
||||
if not db_celebrity:
|
||||
return None
|
||||
|
||||
db.delete(db_celebrity)
|
||||
db.commit()
|
||||
return db_celebrity
|
||||
25
packages/backend/app/database.py
Normal file
25
packages/backend/app/database.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import os
|
||||
from sqlalchemy import create_engine
|
||||
# MODIFICA: La best practice moderna è usare DeclarativeBase
|
||||
from sqlalchemy.orm import sessionmaker, DeclarativeBase
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
DATABASE_URL = os.getenv("DATABASE_URL")
|
||||
|
||||
engine = create_engine(DATABASE_URL)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Assicurati che Base sia definito così
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
# Dependency per ottenere una sessione DB per ogni richiesta
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -1,7 +1,11 @@
|
||||
from fastapi import FastAPI
|
||||
from .routers import celebrities # Importa il nuovo router
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# Includi il router delle celebrities nell'app principale
|
||||
app.include_router(celebrities.router)
|
||||
|
||||
@app.get("/api")
|
||||
def read_root():
|
||||
return {"message": "Ciao dal backend FastAPI!"}
|
||||
|
||||
91
packages/backend/app/models.py
Normal file
91
packages/backend/app/models.py
Normal file
@@ -0,0 +1,91 @@
|
||||
import enum
|
||||
from sqlalchemy import (Column, Integer, String, Date, Enum, Boolean,
|
||||
DECIMAL, Text, TIMESTAMP, ForeignKey)
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy.orm import relationship # Aggiungi questo import
|
||||
|
||||
from .database import Base
|
||||
|
||||
# Definiamo gli Enum Python corrispondenti ai tipi custom di PostgreSQL
|
||||
class GenderType(str, enum.Enum):
|
||||
male = "male"
|
||||
female = "female"
|
||||
other = "other"
|
||||
|
||||
class ShoeSystemType(str, enum.Enum):
|
||||
EU = "EU"
|
||||
US = "US"
|
||||
UK = "UK"
|
||||
|
||||
class BraSystemType(str, enum.Enum):
|
||||
US = "US"
|
||||
UK = "UK"
|
||||
EU = "EU"
|
||||
FR = "FR"
|
||||
AU = "AU"
|
||||
IT = "IT"
|
||||
JP = "JP"
|
||||
|
||||
class Image(Base):
|
||||
__tablename__ = "images"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
celebrity_id = Column(Integer, ForeignKey("celebrities.id"), nullable=False)
|
||||
file_path = Column(String, nullable=False)
|
||||
caption = Column(Text, nullable=True)
|
||||
uploaded_at = Column(TIMESTAMP(timezone=True), server_default=func.now())
|
||||
|
||||
# Relazione inversa: "questa immagine appartiene a UNA celebrità".
|
||||
# Specifichiamo che deve usare la colonna `celebrity_id` di QUESTA tabella.
|
||||
celebrity = relationship("Celebrity", back_populates="images", foreign_keys=[celebrity_id])
|
||||
|
||||
|
||||
class Celebrity(Base):
|
||||
__tablename__ = "celebrities"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, unique=True, nullable=False, index=True)
|
||||
gender = Column(Enum(GenderType), nullable=False)
|
||||
birth_date = Column(Date, nullable=True)
|
||||
birth_place = Column(String, nullable=True)
|
||||
nationality = Column(String, nullable=True)
|
||||
ethnicity = Column(String, nullable=True)
|
||||
sexuality = Column(String, nullable=True)
|
||||
|
||||
hair_color = Column(String, nullable=True)
|
||||
eye_color = Column(String, nullable=True)
|
||||
height_cm = Column(Integer, nullable=True)
|
||||
weight_kg = Column(Integer, nullable=True)
|
||||
body_type = Column(String, nullable=True)
|
||||
|
||||
bust_cm = Column(Integer, nullable=True)
|
||||
waist_cm = Column(Integer, nullable=True)
|
||||
hips_cm = Column(Integer, nullable=True)
|
||||
|
||||
chest_circumference_cm = Column(Integer, nullable=True)
|
||||
|
||||
bra_band_size = Column(Integer, nullable=True)
|
||||
bra_cup_size = Column(String, nullable=True)
|
||||
bra_size_system = Column(Enum(BraSystemType), nullable=True)
|
||||
|
||||
boobs_are_natural = Column(Boolean, nullable=True)
|
||||
shoe_size = Column(DECIMAL(4, 1), nullable=True)
|
||||
shoe_size_system = Column(Enum(ShoeSystemType), nullable=True)
|
||||
|
||||
biography = Column(Text, nullable=True)
|
||||
official_website = Column(String, nullable=True)
|
||||
# 1. Relazione "una celebrità ha MOLTE immagini".
|
||||
# SQLAlchemy deve usare la FK che si trova nella tabella Image.
|
||||
images = relationship("Image", back_populates="celebrity", foreign_keys="[Image.celebrity_id]")
|
||||
# Chiave esterna per l'immagine del profilo
|
||||
profile_image_id = Column(Integer, ForeignKey("images.id", ondelete="SET NULL"), nullable=True)
|
||||
# 2. Relazione "una celebrità ha UNA immagine del profilo".
|
||||
# SQLAlchemy deve usare la FK che si trova in QUESTA tabella (celebrities).
|
||||
profile_image = relationship("Image", foreign_keys=[profile_image_id])
|
||||
|
||||
created_at = Column(TIMESTAMP(timezone=True), server_default=func.now())
|
||||
updated_at = Column(TIMESTAMP(timezone=True), default=func.now(), onupdate=func.now())
|
||||
|
||||
# Nota: le altre tabelle (images, tattoos, etc.) andrebbero modellate qui
|
||||
# se si volessero gestire le relazioni in modo completo con SQLAlchemy.
|
||||
# Per questo esempio, ci concentriamo solo sulla tabella `celebrities`.
|
||||
Binary file not shown.
43
packages/backend/app/routers/celebrities.py
Normal file
43
packages/backend/app/routers/celebrities.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
|
||||
from .. import crud, models, schemas
|
||||
from ..database import get_db
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/celebrities",
|
||||
tags=["celebrities"],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
@router.post("/", response_model=schemas.Celebrity, status_code=201)
|
||||
def create_celebrity(celebrity: schemas.CelebrityCreate, db: Session = Depends(get_db)):
|
||||
# Qui potresti aggiungere un check per vedere se una celebrità con lo stesso nome esiste già
|
||||
return crud.create_celebrity(db=db, celebrity=celebrity)
|
||||
|
||||
@router.get("/", response_model=List[schemas.Celebrity])
|
||||
def read_celebrities(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||
celebrities = crud.get_celebrities(db, skip=skip, limit=limit)
|
||||
return celebrities
|
||||
|
||||
@router.get("/{celebrity_id}", response_model=schemas.Celebrity)
|
||||
def read_celebrity(celebrity_id: int, db: Session = Depends(get_db)):
|
||||
db_celebrity = crud.get_celebrity(db, celebrity_id=celebrity_id)
|
||||
if db_celebrity is None:
|
||||
raise HTTPException(status_code=404, detail="Celebrity not found")
|
||||
return db_celebrity
|
||||
|
||||
@router.put("/{celebrity_id}", response_model=schemas.Celebrity)
|
||||
def update_celebrity(celebrity_id: int, celebrity: schemas.CelebrityUpdate, db: Session = Depends(get_db)):
|
||||
db_celebrity = crud.update_celebrity(db, celebrity_id=celebrity_id, celebrity_update=celebrity)
|
||||
if db_celebrity is None:
|
||||
raise HTTPException(status_code=404, detail="Celebrity not found")
|
||||
return db_celebrity
|
||||
|
||||
@router.delete("/{celebrity_id}", response_model=schemas.Celebrity)
|
||||
def delete_celebrity(celebrity_id: int, db: Session = Depends(get_db)):
|
||||
db_celebrity = crud.delete_celebrity(db, celebrity_id=celebrity_id)
|
||||
if db_celebrity is None:
|
||||
raise HTTPException(status_code=404, detail="Celebrity not found")
|
||||
return db_celebrity
|
||||
73
packages/backend/app/schemas.py
Normal file
73
packages/backend/app/schemas.py
Normal file
@@ -0,0 +1,73 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import date, datetime
|
||||
from .models import GenderType, ShoeSystemType, BraSystemType
|
||||
|
||||
# Schema di base con i campi comuni
|
||||
class CelebrityBase(BaseModel):
|
||||
name: str
|
||||
gender: GenderType
|
||||
birth_date: Optional[date] = None
|
||||
birth_place: Optional[str] = None
|
||||
nationality: Optional[str] = None
|
||||
ethnicity: Optional[str] = None
|
||||
sexuality: Optional[str] = None
|
||||
hair_color: Optional[str] = None
|
||||
eye_color: Optional[str] = None
|
||||
height_cm: Optional[int] = None
|
||||
weight_kg: Optional[int] = None
|
||||
body_type: Optional[str] = None
|
||||
bust_cm: Optional[int] = None
|
||||
waist_cm: Optional[int] = None
|
||||
hips_cm: Optional[int] = None
|
||||
chest_circumference_cm: Optional[int] = None
|
||||
bra_band_size: Optional[int] = None
|
||||
bra_cup_size: Optional[str] = None
|
||||
bra_size_system: Optional[BraSystemType] = None
|
||||
boobs_are_natural: Optional[bool] = None
|
||||
shoe_size: Optional[float] = None
|
||||
shoe_size_system: Optional[ShoeSystemType] = None
|
||||
biography: Optional[str] = None
|
||||
official_website: Optional[str] = None
|
||||
profile_image_id: Optional[int] = None
|
||||
|
||||
# Schema per la creazione di una nuova celebrità (eredita da Base)
|
||||
class CelebrityCreate(CelebrityBase):
|
||||
pass
|
||||
|
||||
# Schema per l'aggiornamento (tutti i campi sono opzionali)
|
||||
class CelebrityUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
gender: Optional[GenderType] = None
|
||||
birth_date: Optional[date] = None
|
||||
birth_place: Optional[str] = None
|
||||
nationality: Optional[str] = None
|
||||
ethnicity: Optional[str] = None
|
||||
sexuality: Optional[str] = None
|
||||
hair_color: Optional[str] = None
|
||||
eye_color: Optional[str] = None
|
||||
height_cm: Optional[int] = None
|
||||
weight_kg: Optional[int] = None
|
||||
body_type: Optional[str] = None
|
||||
bust_cm: Optional[int] = None
|
||||
waist_cm: Optional[int] = None
|
||||
hips_cm: Optional[int] = None
|
||||
chest_circumference_cm: Optional[int] = None
|
||||
bra_band_size: Optional[int] = None
|
||||
bra_cup_size: Optional[str] = None
|
||||
bra_size_system: Optional[BraSystemType] = None
|
||||
boobs_are_natural: Optional[bool] = None
|
||||
shoe_size: Optional[float] = None
|
||||
shoe_size_system: Optional[ShoeSystemType] = None
|
||||
biography: Optional[str] = None
|
||||
official_website: Optional[str] = None
|
||||
profile_image_id: Optional[int] = None
|
||||
|
||||
# Schema per la lettura dei dati (include campi generati dal DB)
|
||||
class Celebrity(CelebrityBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True # Permette a Pydantic di leggere dati da un modello ORM
|
||||
@@ -2,6 +2,10 @@
|
||||
fastapi
|
||||
uvicorn[standard]
|
||||
|
||||
# Pydantic per la validazione e le impostazioni
|
||||
pydantic
|
||||
pydantic-settings
|
||||
|
||||
# Database
|
||||
sqlalchemy
|
||||
psycopg2-binary
|
||||
|
||||
56
packages/frontend/package-lock.json
generated
56
packages/frontend/package-lock.json
generated
@@ -9,7 +9,8 @@
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1"
|
||||
"react-dom": "^19.1.1",
|
||||
"react-router-dom": "^7.9.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
@@ -1628,6 +1629,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cookie": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz",
|
||||
"integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
@@ -2503,6 +2513,44 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "7.9.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.9.4.tgz",
|
||||
"integrity": "sha512-SD3G8HKviFHg9xj7dNODUKDFgpG4xqD5nhyd0mYoB5iISepuZAvzSr8ywxgxKJ52yRzf/HWtVHc9AWwoTbljvA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cookie": "^1.0.1",
|
||||
"set-cookie-parser": "^2.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18",
|
||||
"react-dom": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-router-dom": {
|
||||
"version": "7.9.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.9.4.tgz",
|
||||
"integrity": "sha512-f30P6bIkmYvnHHa5Gcu65deIXoA2+r3Eb6PJIAddvsT9aGlchMatJ51GgpU470aSqRRbFX22T70yQNUGuW3DfA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"react-router": "7.9.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18",
|
||||
"react-dom": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/resolve-from": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
|
||||
@@ -2571,6 +2619,12 @@
|
||||
"semver": "bin/semver.js"
|
||||
}
|
||||
},
|
||||
"node_modules/set-cookie-parser": {
|
||||
"version": "2.7.1",
|
||||
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz",
|
||||
"integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/shebang-command": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1"
|
||||
"react-dom": "^19.1.1",
|
||||
"react-router-dom": "^7.9.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
|
||||
@@ -1,24 +1,20 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
// packages/frontend/src/App.jsx
|
||||
|
||||
import { Routes, Route } from 'react-router-dom';
|
||||
import CelebrityList from './components/CelebrityList';
|
||||
import CelebrityProfile from './components/CelebrityProfile';
|
||||
import CelebrityCreate from './components/CelebrityCreate'; // <-- 1. Importa il nuovo componente
|
||||
import './App.css';
|
||||
|
||||
function App() {
|
||||
const [message, setMessage] = useState('Caricamento...');
|
||||
|
||||
useEffect(() => {
|
||||
// Vite espone le variabili d'ambiente prefixate con VITE_
|
||||
// sull'oggetto import.meta.env
|
||||
const apiUrl = import.meta.env.VITE_API_URL || '/api';
|
||||
|
||||
fetch(apiUrl)
|
||||
.then((res) => res.json())
|
||||
.then((data) => setMessage(data.message))
|
||||
.catch((err) => setMessage(`Errore: ${err.message}`));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="App">
|
||||
<h1>Monorepo React + FastAPI</h1>
|
||||
<p>Messaggio dal backend: <strong>{message}</strong></p>
|
||||
<div className="container">
|
||||
<Routes>
|
||||
<Route path="/" element={<CelebrityList />} />
|
||||
{/* 2. Riattiva questa rotta e puntala al nuovo componente */}
|
||||
<Route path="/celebrity/new" element={<CelebrityCreate />} />
|
||||
<Route path="/celebrity/:id" element={<CelebrityProfile />} />
|
||||
</Routes>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
110
packages/frontend/src/components/CelebrityCreate.css
Normal file
110
packages/frontend/src/components/CelebrityCreate.css
Normal file
@@ -0,0 +1,110 @@
|
||||
/* packages/frontend/src/components/CelebrityCreate.css */
|
||||
|
||||
.create-form-container {
|
||||
width: 100%;
|
||||
max-width: 900px;
|
||||
margin: 2rem auto;
|
||||
padding: 2rem;
|
||||
background-color: #2c2c2c;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #444;
|
||||
}
|
||||
|
||||
.create-form-container h2 {
|
||||
margin-top: 0;
|
||||
color: #d4b996;
|
||||
}
|
||||
|
||||
.form-section {
|
||||
margin-bottom: 2rem;
|
||||
border-top: 1px solid #444;
|
||||
padding-top: 1.5rem;
|
||||
}
|
||||
|
||||
.form-section h3 {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: 0.9rem;
|
||||
color: #ccc;
|
||||
}
|
||||
|
||||
.form-group input,
|
||||
.form-group select,
|
||||
.form-group textarea {
|
||||
padding: 0.75rem;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #555;
|
||||
background-color: #1e1e1e;
|
||||
color: #f0f0f0;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
outline: none;
|
||||
border-color: #646cff;
|
||||
box-shadow: 0 0 0 2px rgba(100, 108, 255, 0.5);
|
||||
}
|
||||
|
||||
.form-group-checkbox {
|
||||
margin-top: 1rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.form-group-checkbox input {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 1rem;
|
||||
margin-top: 2rem;
|
||||
border-top: 1px solid #444;
|
||||
padding-top: 1.5rem;
|
||||
}
|
||||
|
||||
.button-save {
|
||||
background-color: #28a745;
|
||||
}
|
||||
.button-save:hover {
|
||||
background-color: #218838;
|
||||
border-color: #1e7e34;
|
||||
}
|
||||
.button-save:disabled {
|
||||
background-color: #555;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.button-cancel {
|
||||
background-color: #6c757d;
|
||||
padding: 0.6em 1.2em; /* Emula lo stile del bottone */
|
||||
border-radius: 8px;
|
||||
font-weight: 500;
|
||||
text-decoration: none;
|
||||
color: white;
|
||||
display: inline-block;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.button-cancel:hover {
|
||||
background-color: #5a6268;
|
||||
border-color: #545b62;
|
||||
}
|
||||
177
packages/frontend/src/components/CelebrityCreate.jsx
Normal file
177
packages/frontend/src/components/CelebrityCreate.jsx
Normal file
@@ -0,0 +1,177 @@
|
||||
// packages/frontend/src/components/CelebrityCreate.jsx
|
||||
|
||||
import React, { useState } from 'react'; // <-- ECCO LA CORREZIONE
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { createCelebrity } from '../services/api';
|
||||
import './CelebrityCreate.css'; // Stile dedicato per questo form
|
||||
|
||||
// Stato iniziale pulito per il form
|
||||
const initialFormState = {
|
||||
name: '',
|
||||
gender: 'female',
|
||||
birth_date: '',
|
||||
height_cm: '',
|
||||
weight_kg: '',
|
||||
bust_cm: '',
|
||||
waist_cm: '',
|
||||
hips_cm: '',
|
||||
bra_band_size: '',
|
||||
bra_cup_size: '',
|
||||
bra_size_system: 'US',
|
||||
boobs_are_natural: true,
|
||||
birth_place: '',
|
||||
nationality: '',
|
||||
ethnicity: '',
|
||||
sexuality: '',
|
||||
hair_color: '',
|
||||
eye_color: '',
|
||||
biography: '',
|
||||
};
|
||||
|
||||
function CelebrityCreate() {
|
||||
const navigate = useNavigate();
|
||||
const [formData, setFormData] = useState(initialFormState);
|
||||
const [error, setError] = useState(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const handleChange = (e) => {
|
||||
const { name, value, type, checked } = e.target;
|
||||
setFormData({
|
||||
...formData,
|
||||
[name]: type === 'checkbox' ? checked : value,
|
||||
});
|
||||
};
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setIsSubmitting(true);
|
||||
|
||||
// "Pulisce" i dati: converte le stringhe vuote dei campi numerici in `null`
|
||||
// per evitare errori di validazione nel backend.
|
||||
const payload = { ...formData };
|
||||
Object.keys(payload).forEach(key => {
|
||||
if (payload[key] === '') {
|
||||
payload[key] = null;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
await createCelebrity(payload);
|
||||
alert('Celebrità creata con successo!');
|
||||
navigate('/'); // Torna alla lista dopo la creazione
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="create-form-container">
|
||||
<h2>Aggiungi Nuova Celebrità</h2>
|
||||
<p>Compila i campi sottostanti per aggiungere un nuovo profilo al catalogo.</p>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-section">
|
||||
<h3>Anagrafica</h3>
|
||||
<div className="form-grid">
|
||||
<div className="form-group">
|
||||
<label>Nome *</label>
|
||||
<input type="text" name="name" value={formData.name} onChange={handleChange} required />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Genere</label>
|
||||
<select name="gender" value={formData.gender} onChange={handleChange}>
|
||||
<option value="female">Female</option>
|
||||
<option value="male">Male</option>
|
||||
<option value="other">Other</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Data di Nascita</label>
|
||||
<input type="date" name="birth_date" value={formData.birth_date} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Luogo di Nascita</label>
|
||||
<input type="text" name="birth_place" value={formData.birth_place} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Nazionalità</label>
|
||||
<input type="text" name="nationality" value={formData.nationality} onChange={handleChange} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-section">
|
||||
<h3>Misure e Aspetto</h3>
|
||||
<div className="form-grid">
|
||||
<div className="form-group">
|
||||
<label>Altezza (cm)</label>
|
||||
<input type="number" name="height_cm" value={formData.height_cm} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Peso (kg)</label>
|
||||
<input type="number" name="weight_kg" value={formData.weight_kg} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Seno (cm)</label>
|
||||
<input type="number" name="bust_cm" value={formData.bust_cm} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Vita (cm)</label>
|
||||
<input type="number" name="waist_cm" value={formData.waist_cm} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Fianchi (cm)</label>
|
||||
<input type="number" name="hips_cm" value={formData.hips_cm} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Colore Capelli</label>
|
||||
<input type="text" name="hair_color" value={formData.hair_color} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Colore Occhi</label>
|
||||
<input type="text" name="eye_color" value={formData.eye_color} onChange={handleChange} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-section">
|
||||
<h3>Reggiseno</h3>
|
||||
<div className="form-grid">
|
||||
<div className="form-group">
|
||||
<label>Misura Fascia</label>
|
||||
<input type="number" name="bra_band_size" value={formData.bra_band_size} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Coppa</label>
|
||||
<input type="text" name="bra_cup_size" value={formData.bra_cup_size} onChange={handleChange} />
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Sistema</label>
|
||||
<select name="bra_size_system" value={formData.bra_size_system} onChange={handleChange}>
|
||||
<option value="US">US</option> <option value="UK">UK</option> <option value="EU">EU</option> <option value="FR">FR</option>
|
||||
<option value="AU">AU</option> <option value="IT">IT</option> <option value="JP">JP</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-group-checkbox">
|
||||
<label>Seno Naturale?</label>
|
||||
<input type="checkbox" name="boobs_are_natural" checked={formData.boobs_are_natural} onChange={handleChange} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <p className="error-message">Errore: {error}</p>}
|
||||
|
||||
<div className="form-actions">
|
||||
<Link to="/" className="button-cancel">Annulla</Link>
|
||||
<button type="submit" className="button-save" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Salvataggio...' : 'Salva Profilo'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CelebrityCreate;
|
||||
85
packages/frontend/src/components/CelebrityList.jsx
Normal file
85
packages/frontend/src/components/CelebrityList.jsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { getCelebrities, deleteCelebrity } from '../services/api';
|
||||
|
||||
function CelebrityList() {
|
||||
const [celebrities, setCelebrities] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchCelebrities();
|
||||
}, []);
|
||||
|
||||
const fetchCelebrities = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await getCelebrities();
|
||||
setCelebrities(data);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (window.confirm('Sei sicuro di voler eliminare questa celebrità?')) {
|
||||
try {
|
||||
await deleteCelebrity(id);
|
||||
// Rimuovi la celebrità dalla lista senza ricaricare i dati
|
||||
setCelebrities(celebrities.filter((c) => c.id !== id));
|
||||
} catch (err) {
|
||||
alert(`Errore: ${err.message}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <p>Caricamento in corso...</p>;
|
||||
if (error) return <p>Errore: {error}</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>Catalogo Celebrità</h1>
|
||||
<Link to="/celebrity/new" className="button-new">
|
||||
+ Aggiungi Nuova Celebrità
|
||||
</Link>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nome</th>
|
||||
<th>Seno (cm)</th>
|
||||
<th>Vita (cm)</th>
|
||||
<th>Fianchi (cm)</th>
|
||||
<th>Taglia Reggiseno</th>
|
||||
<th>Naturali?</th>
|
||||
<th>Azioni</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{celebrities.map((celeb) => (
|
||||
<tr key={celeb.id}>
|
||||
<td>{celeb.name}</td>
|
||||
<td>{celeb.bust_cm || 'N/A'}</td>
|
||||
<td>{celeb.waist_cm || 'N/A'}</td>
|
||||
<td>{celeb.hips_cm || 'N/A'}</td>
|
||||
<td>
|
||||
{celeb.bra_band_size && celeb.bra_cup_size
|
||||
? `${celeb.bra_band_size}${celeb.bra_cup_size} (${celeb.bra_size_system})`
|
||||
: 'N/A'}
|
||||
</td>
|
||||
<td>{celeb.boobs_are_natural === null ? 'N/A' : celeb.boobs_are_natural ? 'Sì' : 'No'}</td>
|
||||
<td>
|
||||
<Link to={`/celebrity/${celeb.id}`} className="button-edit">Modifica</Link>
|
||||
<button onClick={() => handleDelete(celeb.id)} className="button-delete">Elimina</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CelebrityList;
|
||||
138
packages/frontend/src/components/CelebrityProfile.css
Normal file
138
packages/frontend/src/components/CelebrityProfile.css
Normal file
@@ -0,0 +1,138 @@
|
||||
/* packages/frontend/src/components/CelebrityProfile.css */
|
||||
|
||||
.profile-container {
|
||||
display: flex;
|
||||
gap: 2rem;
|
||||
width: 100%;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.profile-sidebar {
|
||||
flex: 0 0 300px; /* Larghezza fissa per la colonna sinistra */
|
||||
}
|
||||
|
||||
.profile-main-image {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 1rem;
|
||||
border: 1px solid #444;
|
||||
}
|
||||
|
||||
.thumbnails {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.thumbnail img {
|
||||
width: 100%;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #444;
|
||||
}
|
||||
|
||||
.profile-content {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.profile-header {
|
||||
border-bottom: 1px solid #555;
|
||||
padding-bottom: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.profile-header h1 {
|
||||
margin: 0;
|
||||
font-size: 2.5rem;
|
||||
color: #f0e6d2;
|
||||
}
|
||||
|
||||
.profile-header .editable-field {
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.profile-section {
|
||||
background-color: #2c2c2c;
|
||||
border-radius: 8px;
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
border: 1px solid #444;
|
||||
}
|
||||
|
||||
.profile-section h2 {
|
||||
margin-top: 0;
|
||||
border-bottom: 1px solid #555;
|
||||
padding-bottom: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
color: #d4b996;
|
||||
}
|
||||
|
||||
.profile-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
/* Stile per i campi editabili */
|
||||
.editable-field {
|
||||
padding: 8px;
|
||||
border-radius: 4px;
|
||||
transition: background-color 0.2s ease-in-out;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.editable-field:hover {
|
||||
background-color: #3a3a3a;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
display: block;
|
||||
font-size: 0.8rem;
|
||||
color: #aaa;
|
||||
margin-bottom: 4px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.field-value {
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.editable-field input,
|
||||
.editable-field select,
|
||||
.editable-field textarea {
|
||||
width: 100%;
|
||||
padding: 6px;
|
||||
font-size: 1rem;
|
||||
border: 1px solid #646cff;
|
||||
border-radius: 4px;
|
||||
background-color: #1a1a1a;
|
||||
color: #fff;
|
||||
box-sizing: border-box; /* Assicura che padding non alteri la larghezza */
|
||||
}
|
||||
|
||||
.profile-actions {
|
||||
margin-top: 2rem;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.button-delete {
|
||||
background-color: #b22222;
|
||||
color: white;
|
||||
}
|
||||
.button-delete:hover {
|
||||
background-color: #dc143c;
|
||||
border-color: #dc143c;
|
||||
}
|
||||
|
||||
.button-back {
|
||||
background-color: #444;
|
||||
}
|
||||
.button-back:hover {
|
||||
background-color: #555;
|
||||
border-color: #666;
|
||||
}
|
||||
148
packages/frontend/src/components/CelebrityProfile.jsx
Normal file
148
packages/frontend/src/components/CelebrityProfile.jsx
Normal file
@@ -0,0 +1,148 @@
|
||||
// packages/frontend/src/components/CelebrityProfile.jsx
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useParams, useNavigate, Link } from 'react-router-dom';
|
||||
import { getCelebrityById, updateCelebrity, deleteCelebrity } from '../services/api';
|
||||
import EditableField from './EditableField';
|
||||
import './CelebrityProfile.css'; // Importa il nuovo CSS
|
||||
|
||||
function CelebrityProfile() {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [celebrity, setCelebrity] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Ignoriamo la modalità "new", questa pagina è solo per visualizzare/modificare
|
||||
if (id) {
|
||||
setLoading(true);
|
||||
getCelebrityById(id)
|
||||
.then((data) => {
|
||||
// Formatta la data per l'input type="date"
|
||||
if (data.birth_date) {
|
||||
data.birth_date = data.birth_date.split('T')[0];
|
||||
}
|
||||
setCelebrity(data);
|
||||
})
|
||||
.catch((err) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
} else {
|
||||
navigate('/'); // Se non c'è id, torna alla home
|
||||
}
|
||||
}, [id, navigate]);
|
||||
|
||||
const handleFieldSave = async (fieldName, newValue) => {
|
||||
// Converte stringa vuota a null per il backend
|
||||
const valueToSend = newValue === '' ? null : newValue;
|
||||
const payload = { [fieldName]: valueToSend };
|
||||
|
||||
try {
|
||||
const updatedCelebrity = await updateCelebrity(id, payload);
|
||||
// Aggiorna lo stato locale per un feedback immediato
|
||||
setCelebrity((prev) => ({ ...prev, [fieldName]: newValue }));
|
||||
console.log('Salvataggio riuscito:', updatedCelebrity);
|
||||
} catch (err) {
|
||||
setError(`Errore durante il salvataggio del campo ${fieldName}: ${err.message}`);
|
||||
// Potresti voler ripristinare il valore precedente in caso di errore
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (window.confirm(`Sei sicuro di voler eliminare ${celebrity.name}? L'azione è irreversibile.`)) {
|
||||
try {
|
||||
await deleteCelebrity(id);
|
||||
alert(`${celebrity.name} è stato eliminato con successo.`);
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
setError(`Errore durante l'eliminazione: ${err.message}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <p>Caricamento profilo...</p>;
|
||||
if (error) return <p className="error-message">Errore: {error}</p>;
|
||||
if (!celebrity) return <p>Nessuna celebrità trovata.</p>;
|
||||
|
||||
// Opzioni per i campi <select>
|
||||
const genderOptions = [
|
||||
{ value: 'female', label: 'Female' }, { value: 'male', label: 'Male' }, { value: 'other', label: 'Other' },
|
||||
];
|
||||
const braSystemOptions = [
|
||||
{ value: 'US', label: 'US' }, { value: 'UK', label: 'UK' }, { value: 'EU', label: 'EU' },
|
||||
{ value: 'FR', label: 'FR' }, { value: 'AU', label: 'AU' }, { value: 'IT', label: 'IT' }, { value: 'JP', label: 'JP' },
|
||||
];
|
||||
const booleanOptions = [
|
||||
{ value: 'true', label: 'Sì' }, { value: 'false', label: 'No' },
|
||||
];
|
||||
|
||||
|
||||
return (
|
||||
<div className="profile-container">
|
||||
<div className="profile-sidebar">
|
||||
{/* Immagine del profilo (placeholder) */}
|
||||
<img src={`https://i.pravatar.cc/300?u=${id}`} alt={celebrity.name} className="profile-main-image" />
|
||||
<div className="thumbnails">
|
||||
{/* Placeholder per le miniature */}
|
||||
<div className="thumbnail"><img src={`https://i.pravatar.cc/150?u=${id}a`} alt="thumbnail" /></div>
|
||||
<div className="thumbnail"><img src={`https://i.pravatar.cc/150?u=${id}b`} alt="thumbnail" /></div>
|
||||
<div className="thumbnail"><img src={`https://i.pravatar.cc/150?u=${id}c`} alt="thumbnail" /></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="profile-content">
|
||||
<div className="profile-header">
|
||||
<h1>{celebrity.name}</h1>
|
||||
<EditableField label="Nome completo / Alias" name="name" value={celebrity.name} onSave={handleFieldSave} />
|
||||
</div>
|
||||
|
||||
<section className="profile-section">
|
||||
<h2>Dati Personali</h2>
|
||||
<div className="profile-grid">
|
||||
<EditableField label="Data di nascita" name="birth_date" value={celebrity.birth_date} type="date" onSave={handleFieldSave} />
|
||||
<EditableField label="Luogo di nascita" name="birth_place" value={celebrity.birth_place} onSave={handleFieldSave} />
|
||||
<EditableField label="Nazionalità" name="nationality" value={celebrity.nationality} onSave={handleFieldSave} />
|
||||
<EditableField label="Etnia" name="ethnicity" value={celebrity.ethnicity} onSave={handleFieldSave} />
|
||||
<EditableField label="Genere" name="gender" value={celebrity.gender} type="select" options={genderOptions} onSave={handleFieldSave} />
|
||||
<EditableField label="Sessualità" name="sexuality" value={celebrity.sexuality} onSave={handleFieldSave} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="profile-section">
|
||||
<h2>Aspetto Fisico</h2>
|
||||
<div className="profile-grid">
|
||||
<EditableField label="Colore Capelli" name="hair_color" value={celebrity.hair_color} onSave={handleFieldSave} />
|
||||
<EditableField label="Colore Occhi" name="eye_color" value={celebrity.eye_color} onSave={handleFieldSave} />
|
||||
<EditableField label="Altezza (cm)" name="height_cm" value={celebrity.height_cm} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Peso (kg)" name="weight_kg" value={celebrity.weight_kg} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Seno (cm)" name="bust_cm" value={celebrity.bust_cm} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Vita (cm)" name="waist_cm" value={celebrity.waist_cm} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Fianchi (cm)" name="hips_cm" value={celebrity.hips_cm} type="number" onSave={handleFieldSave} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="profile-section">
|
||||
<h2>Reggiseno</h2>
|
||||
<div className="profile-grid">
|
||||
<EditableField label="Misura Fascia" name="bra_band_size" value={celebrity.bra_band_size} type="number" onSave={handleFieldSave} />
|
||||
<EditableField label="Coppa" name="bra_cup_size" value={celebrity.bra_cup_size} onSave={handleFieldSave} />
|
||||
<EditableField label="Sistema" name="bra_size_system" value={celebrity.bra_size_system} type="select" options={braSystemOptions} onSave={handleFieldSave} />
|
||||
<EditableField label="Seno Naturale?" name="boobs_are_natural" value={String(celebrity.boobs_are_natural)} type="select" options={booleanOptions} onSave={handleFieldSave} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="profile-section">
|
||||
<h2>Biografia</h2>
|
||||
<EditableField label="Note biografiche" name="biography" value={celebrity.biography} type="textarea" onSave={handleFieldSave} />
|
||||
</section>
|
||||
|
||||
<div className="profile-actions">
|
||||
<Link to="/" className="button-back">Torna alla Lista</Link>
|
||||
<button onClick={handleDelete} className="button-delete">Elimina Profilo</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CelebrityProfile;
|
||||
82
packages/frontend/src/components/EditableField.jsx
Normal file
82
packages/frontend/src/components/EditableField.jsx
Normal file
@@ -0,0 +1,82 @@
|
||||
// packages/frontend/src/components/EditableField.jsx
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
|
||||
function EditableField({
|
||||
label,
|
||||
name,
|
||||
value,
|
||||
onSave,
|
||||
type = 'text',
|
||||
options = [], // Per i campi <select>
|
||||
}) {
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
// Usiamo un valore interno per non scatenare re-render del genitore ad ogni tasto premuto
|
||||
const [currentValue, setCurrentValue] = useState(value);
|
||||
|
||||
// Aggiorna il valore interno se il prop 'value' cambia dall'esterno
|
||||
useEffect(() => {
|
||||
setCurrentValue(value);
|
||||
}, [value]);
|
||||
|
||||
const handleSave = () => {
|
||||
// Salva solo se il valore è cambiato
|
||||
if (currentValue !== value) {
|
||||
onSave(name, currentValue);
|
||||
}
|
||||
setIsEditing(false);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleSave();
|
||||
} else if (e.key === 'Escape') {
|
||||
// Annulla le modifiche e chiudi
|
||||
setCurrentValue(value);
|
||||
setIsEditing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const renderInputField = () => {
|
||||
const commonProps = {
|
||||
name,
|
||||
value: currentValue || '',
|
||||
onChange: (e) => setCurrentValue(e.target.value),
|
||||
onBlur: handleSave,
|
||||
onKeyDown: handleKeyDown,
|
||||
autoFocus: true,
|
||||
};
|
||||
|
||||
if (type === 'select') {
|
||||
return (
|
||||
<select {...commonProps}>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === 'textarea') {
|
||||
return <textarea {...commonProps} rows="5" />;
|
||||
}
|
||||
|
||||
// Default per 'text', 'number', 'date', etc.
|
||||
return <input type={type} {...commonProps} />;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="editable-field" onClick={() => !isEditing && setIsEditing(true)}>
|
||||
<span className="field-label">{label}</span>
|
||||
{isEditing ? (
|
||||
renderInputField()
|
||||
) : (
|
||||
<span className="field-value">{value || 'N/A'}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditableField;
|
||||
@@ -1,10 +1,13 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.jsx'
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom'; // <-- Importa
|
||||
import './index.css';
|
||||
import App from './App.jsx';
|
||||
|
||||
createRoot(document.getElementById('root')).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
<BrowserRouter> {/* <-- Avvolgi l'App con il Router */}
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>
|
||||
);
|
||||
48
packages/frontend/src/services/api.js
Normal file
48
packages/frontend/src/services/api.js
Normal file
@@ -0,0 +1,48 @@
|
||||
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api';
|
||||
|
||||
const handleResponse = async (response) => {
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.detail || 'Si è verificato un errore');
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const getCelebrities = async () => {
|
||||
const response = await fetch(`${API_BASE_URL}/celebrities/`);
|
||||
return handleResponse(response);
|
||||
};
|
||||
|
||||
export const getCelebrityById = async (id) => {
|
||||
const response = await fetch(`${API_BASE_URL}/celebrities/${id}`);
|
||||
return handleResponse(response);
|
||||
};
|
||||
|
||||
export const createCelebrity = async (celebrityData) => {
|
||||
const response = await fetch(`${API_BASE_URL}/celebrities/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(celebrityData),
|
||||
});
|
||||
return handleResponse(response);
|
||||
};
|
||||
|
||||
export const updateCelebrity = async (id, celebrityData) => {
|
||||
const response = await fetch(`${API_BASE_URL}/celebrities/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(celebrityData),
|
||||
});
|
||||
return handleResponse(response);
|
||||
};
|
||||
|
||||
export const deleteCelebrity = async (id) => {
|
||||
const response = await fetch(`${API_BASE_URL}/celebrities/${id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.detail || 'Errore durante l\'eliminazione');
|
||||
}
|
||||
return response.json(); // O un messaggio di successo
|
||||
};
|
||||
Reference in New Issue
Block a user