Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 0 additions & 36 deletions migrations/versions/0a05674586cf_add_buy_table.py

This file was deleted.

24 changes: 0 additions & 24 deletions migrations/versions/3987bfa63fb9_fusion_de_cabeceras.py

This file was deleted.

45 changes: 0 additions & 45 deletions migrations/versions/a89ed922689b_.py

This file was deleted.

84 changes: 84 additions & 0 deletions migrations/versions/c9722b8d62f1_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""initial

Revision ID: c9722b8d62f1
Revises:
Create Date: 2026-06-26 17:02:33.249944

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'c9722b8d62f1'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('company',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('nombre_legal', sa.String(length=150), nullable=False),
sa.Column('cif_nif', sa.String(length=20), nullable=False),
sa.Column('email', sa.String(length=120), nullable=False),
sa.Column('name', sa.String(length=120), nullable=True),
sa.Column('password', sa.String(), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('cif_nif'),
sa.UniqueConstraint('email')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(length=120), nullable=False),
sa.Column('name', sa.String(length=120), nullable=True),
sa.Column('password', sa.String(), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
op.create_table('event',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=120), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('date', sa.DateTime(), nullable=False),
sa.Column('location', sa.String(length=250), nullable=False),
sa.Column('price', sa.Float(), nullable=False),
sa.Column('capacity', sa.Integer(), nullable=False),
sa.Column('category', sa.String(length=80), nullable=False),
sa.Column('image_url', sa.String(length=500), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('company_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['company_id'], ['company.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('buy',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False),
sa.Column('purchase_date', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['event_id'], ['event.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user_event_follow',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['event_id'], ['event.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('user_event_follow')
op.drop_table('buy')
op.drop_table('event')
op.drop_table('user')
op.drop_table('company')
# ### end Alembic commands ###
25 changes: 22 additions & 3 deletions src/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,23 @@ def handle_login():
user = User.query.filter_by(email=body.get("email")).first()
if user and bcrypt.check_password_hash(user.password, body.get("password")):
token = create_access_token(identity=str(user.id))
return jsonify({"access_token": token, "user": user.serialize()}), 200
return jsonify({"msg": "Email o contraseña incorrectos"}), 401
return jsonify({"access_token": token,
"accountType": "user",
"user": user.serialize()}), 200


company = Company.query.filter_by(email=body.get("email")).first()

if company and bcrypt.check_password_hash(company.password, body.get("password")):
token = create_access_token(identity=str(company.id))

return jsonify({
"access_token": token,
"accountType": "company",
"company": company.serialize()
}), 200

return jsonify({"msg": "Invalid email or password"}), 401


@api.route('/registro-empresa', methods=['POST'])
Expand All @@ -67,7 +82,8 @@ def create_event():
body['date'].replace("Z", "+00:00"))
new_event = Event(title=body['title'], description=body['description'], date=event_date,
location=body['location'], price=body['price'], capacity=body['capacity'],
category=body['category'], company_id=body['company_id'])
category=body['category'], image_url=body['image_url'],
company_id=body['company_id'])
db.session.add(new_event)
db.session.commit()
return jsonify({"msg": "Evento creado", "event": new_event.serialize()}), 201
Expand Down Expand Up @@ -125,3 +141,6 @@ def get_followed_events():
user_id = int(get_jwt_identity())
follows = UserEventFollow.query.filter_by(user_id=user_id).all()
return jsonify([follow.event.serialize() for follow in follows]), 200



76 changes: 47 additions & 29 deletions src/front/components/CompanyRegisterForm.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import React, { useState, useContext } from "react";
// Dependiendo de cómo se llame el archivo de Contexto en esta nueva plantilla,
// la importación será algo parecido a esto. A veces está en Layout.jsx o un AppContext.jsx
// import { Context } from "../Layout";
import React, { useState } from "react";
import { BASE_BACK_URL } from "../core/constantsUrl";
import { useNavigate } from "react-router-dom";


export const CompanyRegisterForm = () => {
// Descomenta y ajusta la importación del Contexto cuando confirmes el nombre
// const { store, dispatch } = useContext(Context);
const [message, setMessage] = useState("");
const [success, setSuccess] = useState(false);
const navigate = useNavigate();


const [formData, setFormData] = useState({
companyName: "",
Expand All @@ -21,39 +23,55 @@ export const CompanyRegisterForm = () => {
const handleSubmit = async (e) => {
e.preventDefault();

try {
console.log("Iniciando simulación de fetch al backend para EMPRESA...");

// Aquí irá tu fetch real cuando el backend esté listo:
/*
const response = await fetch(import.meta.env.VITE_BACKEND_URL + "/api/companies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData)
});

if (!response.ok) throw new Error("Error en el registro de la empresa");
const data = await response.json();
*/
setMessage("");

console.log("¡Datos de empresa enviados con éxito!", formData);
try {
const response = await fetch(`${BASE_BACK_URL}api/registro-empresa`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
nombre_legal: formData.companyName,
cif_nif: formData.cif,
email: formData.email,
password: formData.password
})
});

// Si el registro va bien, podemos enviar un mensaje al store global
// dispatch({ type: 'set_hello', payload: '¡Empresa registrada correctamente!' });
const data = await response.json();

alert("¡Empresa registrada con éxito!");
if (response.ok) {
setMessage("Company registered successfully");
setSuccess(true);
navigate("/login");

// Aquí añadiremos el navigate('/login') de react-router-dom más adelante
setFormData({
companyName: "",
cif: "",
email: "",
password: ""
});

} catch (error) {
console.error("Hubo un error:", error);
alert("Error al registrar la empresa.");
} else {
setMessage(data.msg || "Error registering company");
setSuccess(false);
}
};

} catch (error) {
console.error(error);
setMessage("Server error");
setSuccess(false);
}
};
return (
<div className="card p-4 shadow-sm border-primary">
<h3 className="text-center mb-3">Crear cuenta de Empresa</h3>
{message && (
<div className={`alert ${success ? "alert-success" : "alert-danger"}`}>
{message}
</div>
)}
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label className="form-label">Razón Social (Nombre de la empresa)</label>
Expand Down
Loading