ki-backend/ki/handlers/update_profile.py

70 lines
2.2 KiB
Python
Raw Normal View History

2021-06-27 11:55:08 +02:00
from flask import make_response, request
2021-06-27 13:07:54 +02:00
from ki.models import Address, Contact, ContactType, User, Profile
2021-06-27 11:55:08 +02:00
from app import db
2021-06-27 12:20:36 +02:00
def update_address(profile, address_data):
address = profile.address
if (address is None):
address = Address(profile=profile)
db.session.add(address)
address.name = address_data.get("name", "")
address.street = address_data.get("street", "")
address.house_number = address_data.get("house_number", "")
address.additional = address_data.get("additional", "")
address.postcode = address_data.get("postcode", "")
address.city = address_data.get("city", "")
address.country = address_data.get("country", "")
2021-06-27 13:07:54 +02:00
def update_contacts(profile, contacts_data):
contact_ids_to_be_deleted = list(map(lambda c: c.id, profile.contacts))
for contact_data in contacts_data:
contacttype = ContactType.query.filter(
ContactType.name == contact_data["contacttype"]["name"]).first()
if (contacttype is None):
contacttype = ContactType(name=contact_data["contacttype"]["name"])
db.session.add(contacttype)
if "id" in contact_data:
contact_id = int(contact_data["id"])
contact_ids_to_be_deleted.remove(contact_id)
contact = Contact.query.get(contact_id)
else:
contact = Contact(profile=profile, contacttype=contacttype)
db.session.add(contact)
contact.contacttype_id = contacttype.id
contact.content = contact_data["content"]
Contact.query.filter(Contact.id.in_(contact_ids_to_be_deleted)).delete()
def update_profile(user_id: int):
user = User.query.get(user_id)
2021-06-27 11:55:08 +02:00
if user is None:
return make_response({}, 404)
profile = user.profile
if (profile is None):
profile = Profile(user=user, nickname=user.auth_id)
db.session.add(profile)
profile.pronouns = request.json.get("pronouns", "")
profile.volunteerwork = request.json.get("volunteerwork", "")
profile.freetext = request.json.get("freetext", "")
2021-06-27 12:20:36 +02:00
update_address(profile, request.json.get("address", {}))
2021-06-27 13:07:54 +02:00
update_contacts(profile, request.json.get("contacts", {}))
2021-06-27 12:20:36 +02:00
2021-06-27 11:55:08 +02:00
db.session.commit()
return make_response({"profile": profile.to_dict()})