# Buggy code
def send_notif_to_attendees(order, purchaser_id):
    for holder in order.ticket_holders:
        if holder.id != purchaser_id:
            send_notification(
                user=holder,
                action=TICKET_PURCHASED_ATTENDEE,
                title=NOTIFS[TICKET_PURCHASED_ATTENDEE]["title"].format(
                    event_name=order.event.name
                ),
                message=NOTIFS[TICKET_PURCHASED_ATTENDEE]["message"].format(
                    pdf_url=holder.pdf_url
                ),
            )
        else:
            send_notification(
                user=holder,
                action=TICKET_PURCHASED,
                title=NOTIFS[TICKET_PURCHASED]["title"].format(
                    invoice_id=order.invoice_number
                ),
                message=NOTIFS[TICKET_PURCHASED]["message"].format(
                    pdf_url=holder.pdf_url
                ),
            )


# 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 send_notif_to_attendees(order, purchaser_id):
    for holder in order.ticket_holders:
        if holder.user:
            # send notification if the ticket holder is a registered user.
            if holder.user.id != purchaser_id:
                # The ticket holder is not the purchaser
                send_notification(
                    user=holder.user,
                    action=TICKET_PURCHASED_ATTENDEE,
                    title=NOTIFS[TICKET_PURCHASED_ATTENDEE]["title"].format(
                        event_name=order.event.name
                    ),
                    message=NOTIFS[TICKET_PURCHASED_ATTENDEE]["message"].format(
                        pdf_url=holder.pdf_url
                    ),
                )
            else:
                # The Ticket purchaser
                send_notification(
                    user=holder.user,
                    action=TICKET_PURCHASED,
                    title=NOTIFS[TICKET_PURCHASED]["title"].format(
                        invoice_id=order.invoice_number
                    ),
                    message=NOTIFS[TICKET_PURCHASED]["message"].format(
                        pdf_url=holder.pdf_url
                    ),
                )