Refactor contact handling across backend and frontend

Replaced usage of "ContactPerson" with "Contact" for consistency across the codebase. Updated related component props, state variables, API calls, and database queries to align with the new model. Also enhanced backend functionality with stricter validations and added support for handling active pgroups in contact management.
This commit is contained in:
GotthardG
2025-01-22 16:31:08 +01:00
parent 6cde57f783
commit 382b1eaba8
24 changed files with 627 additions and 373 deletions

View File

@ -8,7 +8,7 @@ def get_shipments(db: Session):
shipments = (
db.query(Shipment)
.options(
joinedload(Shipment.contact_person),
joinedload(Shipment.contact),
joinedload(Shipment.return_address),
joinedload(Shipment.proposal),
joinedload(Shipment.dewars),
@ -30,7 +30,7 @@ def get_shipment_by_id(db: Session, id: int):
shipment = (
db.query(Shipment)
.options(
joinedload(Shipment.contact_person),
joinedload(Shipment.contact),
joinedload(Shipment.return_address),
joinedload(Shipment.proposal),
joinedload(Shipment.dewars),

View File

@ -1,5 +1,5 @@
from app.models import (
ContactPerson,
Contact,
Address,
Dewar,
Proposal,
@ -34,71 +34,81 @@ serial_numbers = [
# Define contact persons
contacts = [
ContactPerson(
Contact(
id=1,
pgroups="p20000, p20001",
firstname="Frodo",
lastname="Baggins",
phone_number="123-456-7890",
email="frodo.baggins@lotr.com",
),
ContactPerson(
Contact(
id=2,
pgroups="p20000, p20002",
firstname="Samwise",
lastname="Gamgee",
phone_number="987-654-3210",
email="samwise.gamgee@lotr.com",
),
ContactPerson(
Contact(
id=3,
pgroups="p20001, p20002",
firstname="Aragorn",
lastname="Elessar",
phone_number="123-333-4444",
email="aragorn.elessar@lotr.com",
),
ContactPerson(
Contact(
id=4,
pgroups="p20003, p20004",
firstname="Legolas",
lastname="Greenleaf",
phone_number="555-666-7777",
email="legolas.greenleaf@lotr.com",
),
ContactPerson(
Contact(
id=5,
pgroups="p20002, p20003",
firstname="Gimli",
lastname="Son of Gloin",
phone_number="888-999-0000",
email="gimli.sonofgloin@lotr.com",
),
ContactPerson(
Contact(
id=6,
pgroups="p20001, p20002",
firstname="Gandalf",
lastname="The Grey",
phone_number="222-333-4444",
email="gandalf.thegrey@lotr.com",
),
ContactPerson(
Contact(
id=7,
pgroups="p20000, p20004",
firstname="Boromir",
lastname="Son of Denethor",
phone_number="111-222-3333",
email="boromir.sonofdenethor@lotr.com",
),
ContactPerson(
Contact(
id=8,
pgroups="p20001, p20002",
firstname="Galadriel",
lastname="Lady of Lothlórien",
phone_number="444-555-6666",
email="galadriel.lothlorien@lotr.com",
),
ContactPerson(
Contact(
id=9,
pgroups="p20001, p20004",
firstname="Elrond",
lastname="Half-elven",
phone_number="777-888-9999",
email="elrond.halfelven@lotr.com",
),
ContactPerson(
Contact(
id=10,
pgroups="p20004, p20006",
firstname="Eowyn",
lastname="Shieldmaiden of Rohan",
phone_number="000-111-2222",
@ -184,7 +194,7 @@ dewars = [
dewar_serial_number_id=2,
tracking_number="TRACK123",
return_address_id=1,
contact_person_id=1,
contact_id=1,
status="Ready for Shipping",
ready_date=datetime.strptime("2023-09-30", "%Y-%m-%d"),
shipping_date=None,
@ -199,7 +209,7 @@ dewars = [
dewar_serial_number_id=1,
tracking_number="TRACK124",
return_address_id=2,
contact_person_id=2,
contact_id=2,
status="In Preparation",
ready_date=None,
shipping_date=None,
@ -214,7 +224,7 @@ dewars = [
dewar_serial_number_id=3,
tracking_number="TRACK125",
return_address_id=1,
contact_person_id=3,
contact_id=3,
status="Not Shipped",
ready_date=datetime.strptime("2024-01-01", "%Y-%m-%d"),
shipping_date=None,
@ -229,7 +239,7 @@ dewars = [
dewar_serial_number_id=4,
tracking_number="",
return_address_id=1,
contact_person_id=3,
contact_id=3,
status="Delayed",
ready_date=datetime.strptime("2024-01-01", "%Y-%m-%d"),
shipping_date=datetime.strptime("2024-01-02", "%Y-%m-%d"),
@ -244,7 +254,7 @@ dewars = [
dewar_serial_number_id=1,
tracking_number="",
return_address_id=1,
contact_person_id=3,
contact_id=3,
status="Returned",
arrival_date=datetime.strptime("2024-01-03", "%Y-%m-%d"),
returning_date=datetime.strptime("2024-01-07", "%Y-%m-%d"),
@ -277,7 +287,7 @@ shipments = [
shipment_date=datetime.strptime("2024-10-10", "%Y-%m-%d"),
shipment_name="Shipment from Mordor",
shipment_status="Delivered",
contact_person_id=2,
contact_id=2,
proposal_id=3,
return_address_id=1,
comments="Handle with care",
@ -288,7 +298,7 @@ shipments = [
shipment_date=datetime.strptime("2024-10-24", "%Y-%m-%d"),
shipment_name="Shipment from Mordor",
shipment_status="In Transit",
contact_person_id=4,
contact_id=4,
proposal_id=4,
return_address_id=2,
comments="Contains the one ring",
@ -299,7 +309,7 @@ shipments = [
shipment_date=datetime.strptime("2024-10-28", "%Y-%m-%d"),
shipment_name="Shipment from Mordor",
shipment_status="In Transit",
contact_person_id=5,
contact_id=5,
proposal_id=5,
return_address_id=1,
comments="Contains the one ring",

View File

@ -80,7 +80,7 @@ def load_sample_data(session: Session):
)
# If any data exists, don't reseed
if session.query(models.ContactPerson).first():
if session.query(models.Contact).first():
return
session.add_all(

View File

@ -21,25 +21,27 @@ class Shipment(Base):
shipment_date = Column(Date)
shipment_status = Column(String(255))
comments = Column(String(200), nullable=True)
contact_person_id = Column(Integer, ForeignKey("contact_persons.id"))
contact_id = Column(Integer, ForeignKey("contacts.id"))
return_address_id = Column(Integer, ForeignKey("addresses.id"))
proposal_id = Column(Integer, ForeignKey("proposals.id"), nullable=True)
contact_person = relationship("ContactPerson", back_populates="shipments")
contact = relationship("Contact", back_populates="shipments")
return_address = relationship("Address", back_populates="shipments")
proposal = relationship("Proposal", back_populates="shipments")
dewars = relationship("Dewar", back_populates="shipment")
class ContactPerson(Base):
__tablename__ = "contact_persons"
class Contact(Base):
__tablename__ = "contacts"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
firstname = Column(String(255))
status = Column(String(255), default="active")
pgroups = Column(String(255), nullable=False)
firstname = Column(String(255), nullable=False)
lastname = Column(String(255))
phone_number = Column(String(255))
email = Column(String(255))
shipments = relationship("Shipment", back_populates="contact_person")
shipments = relationship("Shipment", back_populates="contact")
class Address(Base):
@ -91,11 +93,11 @@ class Dewar(Base):
unique_id = Column(String(255), unique=True, index=True, nullable=True)
shipment_id = Column(Integer, ForeignKey("shipments.id"))
return_address_id = Column(Integer, ForeignKey("addresses.id"))
contact_person_id = Column(Integer, ForeignKey("contact_persons.id"))
contact_id = Column(Integer, ForeignKey("contacts.id"))
shipment = relationship("Shipment", back_populates="dewars")
return_address = relationship("Address")
contact_person = relationship("ContactPerson")
contact = relationship("Contact")
pucks = relationship("Puck", back_populates="dewar")
dewar_type = relationship("DewarType")

View File

@ -1,5 +1,5 @@
from .address import protected_router as address_router
from .contact import router as contact_router
from .address import address_router
from .contact import contact_router
from .proposal import router as proposal_router
from .dewar import router as dewar_router
from .shipment import router as shipment_router

View File

@ -1,4 +1,4 @@
from fastapi import Depends, HTTPException, status, Query
from fastapi import Depends, HTTPException, status, Query, APIRouter
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import List
@ -12,10 +12,11 @@ from app.schemas import (
)
from app.models import Address as AddressModel
from app.dependencies import get_db
from app.routers.protected_router import protected_router
address_router = APIRouter()
@protected_router.get("/", response_model=List[AddressSchema])
@address_router.get("/", response_model=List[AddressSchema])
async def get_return_addresses(
active_pgroup: str = Query(...),
db: Session = Depends(get_db),
@ -36,7 +37,7 @@ async def get_return_addresses(
return user_addresses
@protected_router.get("/all", response_model=List[AddressSchema])
@address_router.get("/all", response_model=List[AddressSchema])
async def get_all_addresses(
db: Session = Depends(get_db),
current_user: loginData = Depends(get_current_user),
@ -52,7 +53,7 @@ async def get_all_addresses(
return user_addresses
@protected_router.post(
@address_router.post(
"/", response_model=AddressSchema, status_code=status.HTTP_201_CREATED
)
async def create_return_address(address: AddressCreate, db: Session = Depends(get_db)):
@ -81,7 +82,7 @@ async def create_return_address(address: AddressCreate, db: Session = Depends(ge
return db_address
@protected_router.put("/{address_id}", response_model=AddressSchema)
@address_router.put("/{address_id}", response_model=AddressSchema)
async def update_return_address(
address_id: int, address: AddressUpdate, db: Session = Depends(get_db)
):
@ -140,7 +141,7 @@ async def update_return_address(
return new_address
@protected_router.delete("/{address_id}", status_code=status.HTTP_204_NO_CONTENT)
@address_router.delete("/{address_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_return_address(address_id: int, db: Session = Depends(get_db)):
db_address = db.query(AddressModel).filter(AddressModel.id == address_id).first()
if not db_address:

View File

@ -1,36 +1,83 @@
from fastapi import APIRouter, HTTPException, status, Depends
from fastapi import APIRouter, HTTPException, status, Depends, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import List
from app.schemas import ContactPerson, ContactPersonCreate, ContactPersonUpdate
from app.models import ContactPerson as ContactPersonModel
from app.schemas import Contact, ContactCreate, ContactUpdate, loginData
from app.models import Contact as ContactModel
from app.dependencies import get_db
from app.routers.auth import get_current_user
router = APIRouter()
contact_router = APIRouter()
# Existing routes
@router.get("/", response_model=List[ContactPerson])
async def get_contacts(db: Session = Depends(get_db)):
return db.query(ContactPersonModel).all()
# GET /contacts: Retrieve active contacts from the active_pgroup
@contact_router.get("/", response_model=List[Contact])
async def get_contacts(
active_pgroup: str = Query(...),
db: Session = Depends(get_db),
current_user: loginData = Depends(get_current_user),
):
# Validate that the active_pgroup belongs to the user
if active_pgroup not in current_user.pgroups:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid pgroup provided.",
)
# Query for active contacts in the active_pgroup
contacts = (
db.query(ContactModel)
.filter(
ContactModel.pgroups.like(f"%{active_pgroup}%"),
ContactModel.status == "active",
)
.all()
)
return contacts
@router.post("/", response_model=ContactPerson, status_code=status.HTTP_201_CREATED)
async def create_contact(contact: ContactPersonCreate, db: Session = Depends(get_db)):
# GET /contacts/all: Retrieve all contacts from the user's pgroups
@contact_router.get("/all", response_model=List[Contact])
async def get_all_contacts(
db: Session = Depends(get_db),
current_user: loginData = Depends(get_current_user),
):
# Query for all contacts belonging to any of the user's pgroups
user_pgroups = current_user.pgroups
filters = [ContactModel.pgroups.like(f"%{pgroup}%") for pgroup in user_pgroups]
contacts = db.query(ContactModel).filter(or_(*filters)).all()
return contacts
@contact_router.post("/", response_model=Contact, status_code=status.HTTP_201_CREATED)
async def create_contact(
contact: ContactCreate, # Body parameter ONLY
db: Session = Depends(get_db), # Secondary dependency for database access
):
# Check if a contact with the same email already exists in this pgroup
if (
db.query(ContactPersonModel)
.filter(ContactPersonModel.email == contact.email)
db.query(ContactModel)
.filter(
ContactModel.email == contact.email,
ContactModel.pgroups.like(f"%{contact.pgroups}%"),
ContactModel.status == "active",
)
.first()
):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="This contact already exists.",
detail="This contact already exists in the provided pgroup.",
)
db_contact = ContactPersonModel(
# Create a new contact
db_contact = ContactModel(
firstname=contact.firstname,
lastname=contact.lastname,
phone_number=contact.phone_number,
email=contact.email,
pgroups=contact.pgroups, # Use the pgroups from the body
status="active", # Newly created contacts will be active
)
db.add(db_contact)
db.commit()
@ -38,34 +85,78 @@ async def create_contact(contact: ContactPersonCreate, db: Session = Depends(get
return db_contact
# New routes
@router.put("/{contact_id}", response_model=ContactPerson)
# PUT /contacts/{contact_id}: Update a contact
@contact_router.put("/{contact_id}", response_model=Contact)
async def update_contact(
contact_id: int, contact: ContactPersonUpdate, db: Session = Depends(get_db)
contact_id: int,
contact: ContactUpdate,
db: Session = Depends(get_db),
):
db_contact = (
db.query(ContactPersonModel).filter(ContactPersonModel.id == contact_id).first()
)
# Retrieve the existing contact
db_contact = db.query(ContactModel).filter(ContactModel.id == contact_id).first()
if not db_contact:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Contact not found."
status_code=status.HTTP_404_NOT_FOUND,
detail="Contact not found.",
)
for key, value in contact.dict(exclude_unset=True).items():
setattr(db_contact, key, value)
# Normalize existing and new pgroups (remove whitespace, handle case
# sensitivity if needed)
existing_pgroups = (
set(p.strip() for p in db_contact.pgroups.split(",") if p.strip())
if db_contact.pgroups
else set()
)
new_pgroups = (
set(p.strip() for p in contact.pgroups.split(",") if p.strip())
if contact.pgroups
else set()
)
# Check if any old pgroups are being removed (strict validation against removal)
if not new_pgroups.issuperset(existing_pgroups):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Modifying pgroups to remove existing ones is not allowed.",
)
combined_pgroups = existing_pgroups.union(new_pgroups)
# Mark the old contact as inactive
db_contact.status = "inactive"
db.commit()
db.refresh(db_contact)
return db_contact
@router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_contact(contact_id: int, db: Session = Depends(get_db)):
db_contact = (
db.query(ContactPersonModel).filter(ContactPersonModel.id == contact_id).first()
# Create a new contact with the updated data
new_contact = ContactModel(
firstname=contact.firstname or db_contact.firstname,
lastname=contact.lastname or db_contact.lastname,
phone_number=contact.phone_number or db_contact.phone_number,
email=contact.email or db_contact.email,
pgroups=",".join(combined_pgroups), # Use the active_pgroup
status="active", # Newly created contacts will be active
)
db.add(new_contact)
db.commit()
db.refresh(new_contact)
return new_contact
# DELETE /contacts/{contact_id}: Mark a contact as inactive
@contact_router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_contact(
contact_id: int,
db: Session = Depends(get_db),
):
# Retrieve the existing contact
db_contact = db.query(ContactModel).filter(ContactModel.id == contact_id).first()
if not db_contact:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Contact not found."
status_code=status.HTTP_404_NOT_FOUND,
detail="Contact not found.",
)
db.delete(db_contact)
# Mark the contact as inactive
db_contact.status = "inactive"
db.commit()
return

View File

@ -1,7 +1,12 @@
from fastapi import APIRouter, Depends
from app.routers.auth import get_current_user
from app.routers.address import address_router
from app.routers.contact import contact_router
protected_router = APIRouter(
dependencies=[Depends(get_current_user)] # Applies to all routes
)
protected_router.include_router(address_router, prefix="/addresses", tags=["addresses"])
protected_router.include_router(contact_router, prefix="/contacts", tags=["contacts"])

View File

@ -7,7 +7,7 @@ import json
from app.models import (
Shipment as ShipmentModel,
ContactPerson as ContactPersonModel,
Contact as ContactModel,
Address as AddressModel,
Proposal as ProposalModel,
Dewar as DewarModel,
@ -19,7 +19,7 @@ from app.schemas import (
ShipmentCreate,
UpdateShipmentComments,
Shipment as ShipmentSchema,
ContactPerson as ContactPersonSchema,
Contact as ContactSchema,
Sample as SampleSchema,
DewarSchema,
)
@ -71,10 +71,8 @@ async def get_dewars_by_shipment_id(shipment_id: int, db: Session = Depends(get_
@router.post("", response_model=ShipmentSchema, status_code=status.HTTP_201_CREATED)
async def create_shipment(shipment: ShipmentCreate, db: Session = Depends(get_db)):
contact_person = (
db.query(ContactPersonModel)
.filter(ContactPersonModel.id == shipment.contact_person_id)
.first()
contact = (
db.query(ContactModel).filter(ContactModel.id == shipment.contact_id).first()
)
return_address = (
db.query(AddressModel)
@ -85,7 +83,7 @@ async def create_shipment(shipment: ShipmentCreate, db: Session = Depends(get_db
db.query(ProposalModel).filter(ProposalModel.id == shipment.proposal_id).first()
)
if not (contact_person or return_address or proposal):
if not (contact or return_address or proposal):
raise HTTPException(status_code=404, detail="Associated entity not found")
db_shipment = ShipmentModel(
@ -93,7 +91,7 @@ async def create_shipment(shipment: ShipmentCreate, db: Session = Depends(get_db
shipment_date=shipment.shipment_date,
shipment_status=shipment.shipment_status,
comments=shipment.comments,
contact_person_id=contact_person.id,
contact_id=contact.id,
return_address_id=return_address.id,
proposal_id=proposal.id,
)
@ -189,8 +187,8 @@ async def update_shipment(
# Validate relationships by IDs
contact_person = (
db.query(ContactPersonModel)
.filter(ContactPersonModel.id == updated_shipment.contact_person_id)
db.query(ContactModel)
.filter(ContactModel.id == updated_shipment.contact_person_id)
.first()
)
return_address = (
@ -225,9 +223,7 @@ async def update_shipment(
for key, value in update_fields.items():
if key == "contact_person_id":
contact_person = (
db.query(ContactPersonModel)
.filter(ContactPersonModel.id == value)
.first()
db.query(ContactModel).filter(ContactModel.id == value).first()
)
if not contact_person:
raise HTTPException(
@ -342,9 +338,9 @@ async def remove_dewar_from_shipment(
return shipment
@router.get("/contact_persons", response_model=List[ContactPersonSchema])
@router.get("/contact_persons", response_model=List[ContactSchema])
async def get_shipment_contact_persons(db: Session = Depends(get_db)):
contact_persons = db.query(ContactPersonModel).all()
contact_persons = db.query(ContactModel).all()
return contact_persons

View File

@ -366,25 +366,24 @@ class Results(BaseModel):
pass
class ContactPersonBase(BaseModel):
class ContactCreate(BaseModel):
pgroups: str
firstname: str
lastname: str
phone_number: str
email: EmailStr
class ContactPersonCreate(ContactPersonBase):
pass
class ContactPerson(ContactPersonBase):
class Contact(ContactCreate):
id: int
status: str = "active"
class Config:
from_attributes = True
class ContactPersonUpdate(BaseModel):
class ContactUpdate(BaseModel):
pgroups: str
firstname: Optional[str] = None
lastname: Optional[str] = None
phone_number: Optional[str] = None
@ -510,7 +509,7 @@ class DewarBase(BaseModel):
shipping_date: Optional[date]
arrival_date: Optional[date]
returning_date: Optional[date]
contact_person_id: Optional[int]
contact_id: Optional[int]
return_address_id: Optional[int]
pucks: List[PuckCreate] = []
@ -525,7 +524,7 @@ class DewarCreate(DewarBase):
class Dewar(DewarBase):
id: int
shipment_id: Optional[int]
contact_person: Optional[ContactPerson]
contact: Optional[Contact]
return_address: Optional[Address]
pucks: List[Puck] = [] # List of pucks within this dewar
@ -544,7 +543,7 @@ class DewarUpdate(BaseModel):
shipping_date: Optional[date] = None
arrival_date: Optional[date] = None
returning_date: Optional[date] = None
contact_person_id: Optional[int] = None
contact_id: Optional[int] = None
address_id: Optional[int] = None
@ -553,7 +552,7 @@ class DewarSchema(BaseModel):
dewar_name: str
tracking_number: str
status: str
contact_person_id: int
contact_id: int
return_address_id: int
class Config:
@ -574,7 +573,7 @@ class Shipment(BaseModel):
shipment_date: date
shipment_status: str
comments: Optional[str]
contact_person: Optional[ContactPerson]
contact: Optional[Contact]
return_address: Optional[Address]
proposal: Optional[Proposal]
dewars: List[Dewar] = []
@ -588,7 +587,7 @@ class ShipmentCreate(BaseModel):
shipment_date: date
shipment_status: str
comments: Optional[constr(max_length=200)]
contact_person_id: int
contact_id: int
return_address_id: int
proposal_id: int
dewars: List[DewarCreate] = []
@ -621,7 +620,7 @@ class SlotSchema(BaseModel):
retrievedTimestamp: Optional[str]
beamlineLocation: Optional[str]
shipment_name: Optional[str]
contact_person: Optional[str]
contact: Optional[str]
local_contact: Optional[str]
class Config: