# Buggy code
def calculate_update_amount(order):
    discount = None
    if order.discount_code_id:
        discount = order.discount
    # Access code part will be done ticket_holders API
    amount = 0
    total_discount = 0
    fees = TicketFees.query.filter_by(currency=order.event.payment_currency).first()

    for order_ticket in order.order_tickets:
        with db.session.no_autoflush:
            if order_ticket.ticket.is_fee_absorbed or not fees:
                ticket_amount = order_ticket.ticket.price * order_ticket.quantity
                amount += order_ticket.ticket.price * order_ticket.quantity
            else:
                order_fee = (
                    fees.service_fee
                    * (order_ticket.ticket.price * order_ticket.quantity)
                    / 100
                )
                if order_fee > fees.maximum_fee:
                    ticket_amount = (
                        order_ticket.ticket.price * order_ticket.quantity
                    ) + fees.maximum_fee
                    amount += (
                        order_ticket.ticket.price * order_ticket.quantity
                    ) + fees.maximum_fee
                else:
                    ticket_amount = (
                        order_ticket.ticket.price * order_ticket.quantity
                    ) + order_fee
                    amount += (
                        order_ticket.ticket.price * order_ticket.quantity
                    ) + order_fee

            if discount and str(order_ticket.ticket.id) in discount.tickets.split(","):
                if discount.type == "amount":
                    total_discount += discount.value * order_ticket.quantity
                else:
                    total_discount += discount.value * ticket_amount / 100

    if discount:
        if discount.type == "amount":
            order.amount = max(amount - total_discount, 0)
        elif discount.type == "percent":
            order.amount = amount - (discount.value * amount / 100.0)
    else:
        order.amount = amount
    save_to_db(order)
    return order


# Traceback (psycopg2.IntegrityError)
(psycopg2.IntegrityError) insert or update on table "notifications" violates foreign key constraint "notifications_user_id_fkey"
DETAIL:  Key (user_id)=(5) is not present in table "users".
[SQL: 'INSERT INTO notifications (user_id, title, message, action, received_at, is_read) VALUES (%(user_id)s, %(title)s, %(message)s, %(action)s, %(received_at)s, %(is_read)s) RETURNING notifications.id'] [parameters: {'user_id': 5, 'title': 'Your ticket for Main Event', 'message': "Your order has been processed successfully.<br><br><a href='http://127.0.0.1:5000/static/media/attendees/tickets/pdf/5566d5b7-bfb8-43f1-a834-a851ac45ede1/YXU5RWJWcT/c4438374-d5dd-46a5-bac2-c21695370d47.pdf' class='btn btn-info btn-sm'>View PDF</a>", 'action': 'Ticket Purchased to Attendee', 'received_at': datetime.datetime(2018, 6, 20, 11, 12, 16, 856225, tzinfo=<UTC>), 'is_read': False}]
Traceback (most recent call last):
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
psycopg2.IntegrityError: insert or update on table "notifications" violates foreign key constraint "notifications_user_id_fkey"
DETAIL:  Key (user_id)=(5) is not present in table "users".


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/app/api/helpers/db.py", line 24, in save_to_db
db.session.commit()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 921, in commit
self.transaction.commit()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 461, in commit
self._prepare_impl()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 441, in _prepare_impl
self.session.flush()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2192, in flush
self._flush(objects)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2312, in _flush
transaction.rollback(_capture_exception=True)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 187, in reraise
raise value
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2276, in _flush
flush_context.execute()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 389, in execute
rec.execute(self)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 548, in execute
uow
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 181, in save_obj
mapper, table, insert)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 835, in _emit_insert_statements
execute(statement, params)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
return meth(self, multiparams, params)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
context)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
exc_info
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 186, in reraise
raise value.with_traceback(tb)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) insert or update on table "notifications" violates foreign key constraint "notifications_user_id_fkey"
DETAIL:  Key (user_id)=(5) is not present in table "users".
[SQL: 'INSERT INTO notifications (user_id, title, message, action, received_at, is_read) VALUES (%(user_id)s, %(title)s, %(message)s, %(action)s, %(received_at)s, %(is_read)s) RETURNING notifications.id'] [parameters: {'user_id': 5, 'title': 'Your ticket for Main Event', 'message': "Your order has been processed successfully.<br><br><a href='http://127.0.0.1:5000/static/media/attendees/tickets/pdf/5566d5b7-bfb8-43f1-a834-a851ac45ede1/YXU5RWJWcT/c4438374-d5dd-46a5-bac2-c21695370d47.pdf' class='btn btn-info btn-sm'>View PDF</a>", 'action': 'Ticket Purchased to Attendee', 'received_at': datetime.datetime(2018, 6, 20, 11, 12, 16, 856225, tzinfo=<UTC>), 'is_read': False}]
ERROR:root:DB Exception! (psycopg2.IntegrityError) insert or update on table "notifications" violates foreign key constraint "notifications_user_id_fkey"
DETAIL:  Key (user_id)=(5) is not present in table "users".
[SQL: 'INSERT INTO notifications (user_id, title, message, action, received_at, is_read) VALUES (%(user_id)s, %(title)s, %(message)s, %(action)s, %(received_at)s, %(is_read)s) RETURNING notifications.id'] [parameters: {'user_id': 5, 'title': 'Your ticket for Main Event', 'message': "Your order has been processed successfully.<br><br><a href='http://127.0.0.1:5000/static/media/attendees/tickets/pdf/5566d5b7-bfb8-43f1-a834-a851ac45ede1/YXU5RWJWcT/c4438374-d5dd-46a5-bac2-c21695370d47.pdf' class='btn btn-info btn-sm'>View PDF</a>", 'action': 'Ticket Purchased to Attendee', 'received_at': datetime.datetime(2018, 6, 20, 11, 12, 16, 856225, tzinfo=<UTC>), 'is_read': False}]

# Fixed code
def calculate_update_amount(order):
    discount = None
    if order.discount_code_id:
        discount = order.discount_code
    # Access code part will be done ticket_holders API
    amount = 0
    total_discount = 0
    fees = TicketFees.query.filter_by(currency=order.event.payment_currency).first()

    for order_ticket in order.order_tickets:
        with db.session.no_autoflush:
            if order_ticket.ticket.is_fee_absorbed or not fees:
                ticket_amount = order_ticket.ticket.price * order_ticket.quantity
                amount += order_ticket.ticket.price * order_ticket.quantity
            else:
                order_fee = (
                    fees.service_fee
                    * (order_ticket.ticket.price * order_ticket.quantity)
                    / 100
                )
                if order_fee > fees.maximum_fee:
                    ticket_amount = (
                        order_ticket.ticket.price * order_ticket.quantity
                    ) + fees.maximum_fee
                    amount += (
                        order_ticket.ticket.price * order_ticket.quantity
                    ) + fees.maximum_fee
                else:
                    ticket_amount = (
                        order_ticket.ticket.price * order_ticket.quantity
                    ) + order_fee
                    amount += (
                        order_ticket.ticket.price * order_ticket.quantity
                    ) + order_fee

            if discount and str(order_ticket.ticket.id) in discount.tickets.split(","):
                if discount.type == "amount":
                    total_discount += discount.value * order_ticket.quantity
                else:
                    total_discount += discount.value * ticket_amount / 100

    if discount:
        if discount.type == "amount":
            order.amount = max(amount - total_discount, 0)
        elif discount.type == "percent":
            order.amount = amount - (discount.value * amount / 100.0)
    else:
        order.amount = amount
    save_to_db(order)
    return order