mirror of
https://github.com/Hestia-Homes/Model.git
synced 2026-06-08 11:17:27 +00:00
59 lines
2.1 KiB
Python
59 lines
2.1 KiB
Python
###
|
|
# This script contains methods for interacting with the property table in the database
|
|
###
|
|
import datetime
|
|
from sqlalchemy.orm import sessionmaker
|
|
from backend.app.db.models.portfolio import PropertyModel, PropertyCreationStatus, PortfolioStatus
|
|
from backend.app.db.connection import db_engine
|
|
from sqlalchemy.orm.exc import NoResultFound
|
|
|
|
|
|
def create_property(portfolio_id: int, address: str, postcode: str) -> (int, bool):
|
|
"""
|
|
This function will create a record for the property in the database if it does not exist.
|
|
If it does exist, it will just update the updated_at field.
|
|
:param portfolio_id: The ID of the portfolio the property belongs to
|
|
:param address: The address of the property
|
|
:param postcode: The postcode of the property
|
|
:return: The ID of the property and a boolean indicating whether it was created or not
|
|
"""
|
|
Session = sessionmaker(bind=db_engine)
|
|
with Session() as session:
|
|
|
|
now = datetime.datetime.now()
|
|
|
|
try:
|
|
# Attempt to fetch the existing property
|
|
existing_property = session.query(PropertyModel).filter_by(
|
|
address=address, postcode=postcode, portfolio_id=portfolio_id
|
|
).one()
|
|
|
|
# Update the 'updated_at' field
|
|
existing_property.updated_at = now
|
|
|
|
# Merge the updated property back into the session
|
|
session.merge(existing_property)
|
|
session.commit()
|
|
|
|
return existing_property.id, False
|
|
|
|
except NoResultFound:
|
|
# Property doesn't exist, create a new one
|
|
new_property = PropertyModel(
|
|
address=address,
|
|
postcode=postcode,
|
|
portfolio_id=portfolio_id,
|
|
created_at=now,
|
|
updated_at=now,
|
|
creation_status=PropertyCreationStatus.LOADING,
|
|
status=PortfolioStatus.ASSESSMENT.value,
|
|
has_pre_condition_report=False,
|
|
has_recommendations=False
|
|
)
|
|
|
|
# Add the new property to the session
|
|
session.add(new_property)
|
|
|
|
session.commit()
|
|
|
|
return new_property.id, True
|