Skip to content

Commit

Permalink
PH-1046 make editMandate request transactional
Browse files Browse the repository at this point in the history
  • Loading branch information
Artjom Aralov committed Jan 10, 2024
1 parent 98acf32 commit f4fcb11
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 33 deletions.
50 changes: 31 additions & 19 deletions api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_swagger_ui import get_swaggerui_blueprint
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker

from api.enums import is_valid_action
from api.exceptions import (CompanyCodeInvalid,
Expand Down Expand Up @@ -164,27 +167,36 @@ def delete_mandate(representee_id, delegate_id, mandate_id):
raise ActionInvalid("Action invalid", error_config)

db_uri = app.config['SQLALCHEMY_DATABASE_URI']
engine = create_engine(db_uri)
Session = sessionmaker(bind=engine)
session = Session()
try:
data_rows_deleted_subdelegated_mandates = delete_subdelegated_mandates_pg(db_uri, mandate_id)
data_row_deleted_mandate = delete_mandate_pg(
db_uri,
representee_id,
delegate_id,
mandate_id
)
except psycopg2.errors.RaiseException as e:
app.logger.exception(str(e))
with session.begin():
conn = session.connection().connection
data_rows_deleted_subdelegated_mandates = delete_subdelegated_mandates_pg(conn, mandate_id)
data_row_deleted_mandate = delete_mandate_pg(
conn,
representee_id,
delegate_id,
mandate_id
)

if data_row_deleted_mandate:
data_rows_mandates = get_mandates(db) # because the changes related to mandates are not persisted yet (running in session, we have to search from active mandates)
response_data = serialize_deleted_subdelegated_mandates(
data_rows_deleted_subdelegated_mandates,
data_rows_mandates,
app.config['SETTINGS']
)
return make_success_response(response_data, 200)
except Exception as custom_exception:
session.rollback()
app.logger.exception(str(custom_exception))
error_config = app.config['SETTINGS']['errors']['unprocessable_request']
raise UnprocessableRequestError('Unprocessable request while deleting mandate. Something went wrong.',
error_config)
if data_row_deleted_mandate:
data_rows_deleted_mandates = get_deleted_mandates(db)
response_data = serialize_deleted_subdelegated_mandates(
data_rows_deleted_subdelegated_mandates,
data_rows_deleted_mandates,
app.config['SETTINGS']
)
return make_success_response(response_data, 200)
raise UnprocessableRequestError(str(custom_exception), error_config)
finally:
session.close()

error_config = app.config['SETTINGS']['errors']['mandate_not_found']
raise MandateNotFound('Mandate to delete was not found', error_config)

Expand Down
8 changes: 4 additions & 4 deletions api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ def serialize_mandate(representee, delegate, mandate, settings):

validity_period = {}
if mandate['validity_period_from']:
validity_period['from'] = mandate['validity_period_from'].strftime('%Y-%m-%d')
validity_period['from'] = mandate['validity_period_from'].strftime('%Y-%m-%d') if mandate['validity_period_from'] is not None else None,
if mandate['validity_period_through']:
validity_period['through'] = mandate['validity_period_through'].strftime('%Y-%m-%d')
validity_period['through'] = mandate['validity_period_through'].strftime('%Y-%m-%d') if mandate['validity_period_through'] is not None else None

mandate_data = {
'links': links,
Expand All @@ -103,8 +103,8 @@ def serialize_deleted_subdelegated_mandates(subdelegated_deleted_mandates, delet
deleted_sub_delegated_mandates = []
for item in data_rows:
validity_period = {
'from': item['validity_period_from'].strftime('%Y-%m-%d'),
'through': item['validity_period_through'].strftime('%Y-%m-%d')
'from': item['validity_period_from'].strftime('%Y-%m-%d') if item['validity_period_from'] is not None else None,
'through': item['validity_period_through'].strftime('%Y-%m-%d') if item['validity_period_through'] is not None else None
}
validity_period = {k: v for k, v in validity_period.items() if v is not None}

Expand Down
14 changes: 4 additions & 10 deletions api/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,14 +270,12 @@ def create_mandate_pg(uri, data):
data['data_can_display_document_to_delegate']
]
)

cur.close()
conn.close()


def delete_mandate_pg(uri, representee_id, delegate_id, mandate_id):
conn = psycopg2.connect(uri)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

def delete_mandate_pg(conn, representee_id, delegate_id, mandate_id):
cur = conn.cursor()
cur.callproc(
'paasuke_delete_mandate', [
Expand All @@ -287,15 +285,12 @@ def delete_mandate_pg(uri, representee_id, delegate_id, mandate_id):
]
)
result = cur.fetchone()[0]

cur.close()
conn.close()
return result


def delete_subdelegated_mandates_pg(uri, mandate_id):
conn = psycopg2.connect(uri)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

def delete_subdelegated_mandates_pg(conn, mandate_id):
cur = conn.cursor()
cur.callproc(
'paasuke_delete_subdelegated_mandates', [mandate_id]
Expand All @@ -308,7 +303,6 @@ def delete_subdelegated_mandates_pg(uri, mandate_id):
]

cur.close()
conn.close()
return result


Expand Down
1 change: 1 addition & 0 deletions tests/pg_data/02a_view_mandates_view.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
CREATE OR REPLACE VIEW paasuke_mandates_view AS
SELECT
mandate.id,
mandate.role,
mandate.validity_period_from::DATE,
mandate.validity_period_through::DATE,
Expand Down

0 comments on commit f4fcb11

Please sign in to comment.