2 """Main module to migrate loanapps data.""" 10 from ody_migr_config
import (INSERT,
20 LOANAPP_SCHEMAMASTER_LOANID_MAP_CSV_FILE,
21 LOANAPP_USER_USERID_MAP_CSV_FILE)
23 from ody_migr_transaction
import PgTransaction
24 from ody_migr_transaction
import pg_crsr_hndlr_decrtr
25 import ody_migr_db_handler
as pg_handler
26 from ody_migr_mmth_endpoint
import MammothMigration
27 from ody_migr_utils
import (get_valid_json,
32 LOGGER = logging.getLogger(__name__)
40 """Migrate loanapps data in a single transaction 43 loans_transaction: transaction to commit all insertions for loanapps 44 mmth_loanapp_dict: response dictionary from Mammoth for loanapps 45 verbose: verbosity flag 46 cucode: current credit union code 49 psycopg2.Error, psycopg2.Warning on db operation errors 51 mmth_loanapp_data = mmth_loanapp_dict[
"data"]
52 progress_dict = {
"completed": 0,
"total": 5}
56 mmth_lnappschemamaster_records = mmth_loanapp_data[
"lnappschemamaster"]
58 lnappschemamaster_loanid_map = {}
61 with open(LOANAPP_SCHEMAMASTER_LOANID_MAP_CSV_FILE.format(cucode.lower()),
62 'w', newline=
'')
as loanidmap_csvfile:
63 loanid_columns = [
"mammoth_lnappschemamaster_loanid",
64 "odyssey_lnappschemamaster_loanid"]
65 csvwriter_loanid = csv.writer(loanidmap_csvfile, delimiter=
",",
66 quotechar=
'|',quoting=csv.QUOTE_MINIMAL)
67 csvwriter_loanid.writerow(loanid_columns)
69 for lnappschemamaster_rec
in mmth_lnappschemamaster_records:
70 old_loanid = lnappschemamaster_rec[
"loanid"].strip()
72 del lnappschemamaster_rec[
"loanid"]
77 list(lnappschemamaster_rec.keys()),
78 list(lnappschemamaster_rec.values()),
79 returning_col=
"loanid" 81 new_loanid = loans_transaction.cur.fetchone()[0]
83 lnappschemamaster_loanid_map[old_loanid] = new_loanid
85 csvwriter_loanid.writerow([old_loanid, new_loanid])
87 progress_dict[
"completed"] += 1
88 log_progress(progress_dict)
91 lnappschemadetail_detailid_map = {}
92 mmth_lnappschemadetail_records = mmth_loanapp_data[
"lnappschemadetail"]
93 for lnappschemadetail_rec
in mmth_lnappschemadetail_records:
94 old_detailid = lnappschemadetail_rec[
"detailid"].strip()
96 del lnappschemadetail_rec[
"detailid"]
98 lnappschemadetail_rec[
"loanid"] = lnappschemamaster_loanid_map[
99 lnappschemadetail_rec[
"loanid"].strip()]
105 list(lnappschemadetail_rec.keys()),
106 list(lnappschemadetail_rec.values()),
107 returning_col=
"detailid" 109 new_detailid = loans_transaction.cur.fetchone()[0]
112 lnappschemadetail_detailid_map[old_detailid] = new_detailid
114 progress_dict[
"completed"] += 1
115 log_progress(progress_dict)
118 mmth_lnappuser_records = mmth_loanapp_data[
"lnappuser"]
120 lnappuser_userid_map = {}
121 mmth_userids_with_no_ody_banking_user_id = []
124 with open(LOANAPP_USER_USERID_MAP_CSV_FILE.format(cucode.lower()),
125 'w', newline=
'')
as useridmap_csvfile:
127 userid_columns = [
"mammoth_lnappuser_userid",
128 "odyssey_lnappuser_userid"]
129 csvwriter_userid = csv.writer(useridmap_csvfile, delimiter=
",",
130 quotechar=
'|',quoting=csv.QUOTE_MINIMAL)
131 csvwriter_userid.writerow(userid_columns)
133 for lnappuser_rec
in mmth_lnappuser_records:
134 old_userid = get_strip_value_dict(
"userid", lnappuser_rec)
136 del lnappuser_rec[
"userid"]
139 mmth_banking_user_name = lnappuser_rec[
"user_name"]
140 del lnappuser_rec[
"user_name"]
141 lnappuser_rec[
"session_account"] = mmth_banking_user_name
146 if mmth_banking_user_name
not in [
None,
""]:
147 ody_banking_user_id = loans_transaction(
149 "{}memberacct".format(cucode.lower()),
150 where_conditions={
"accountnumber": mmth_banking_user_name},
151 select_columns=[
"primary_user"]
153 if(len(ody_banking_user_id) > 0):
155 lnappuser_rec[
"banking_user_id"] = ody_banking_user_id[0][0]
157 mmth_userids_with_no_ody_banking_user_id.append(old_userid)
163 list(lnappuser_rec.keys()),
164 list(lnappuser_rec.values()),
165 returning_col=
"userid" 167 new_userid = loans_transaction.cur.fetchone()[0]
169 lnappuser_userid_map[old_userid] = new_userid
171 csvwriter_userid.writerow([old_userid, new_userid])
173 if len(mmth_userids_with_no_ody_banking_user_id) > 0:
174 LOGGER.warning(
"`{}` Loanapps user(s) (lnappuser.userids) in Mammoth" 175 " were found to have no associated Odyssey userid" 176 " (<cu>memberacct.primary_user)." 177 " Developers can refer to the mapping file to look" 178 " at the Odyssey lnappuser.userids if needed." 179 " Mammoth lnappuser.userids : [{}]".format(
180 len(mmth_userids_with_no_ody_banking_user_id),
181 ", ".join(mmth_userids_with_no_ody_banking_user_id)))
183 progress_dict[
"completed"] += 1
184 log_progress(progress_dict)
187 mmth_lnappuser_questselect_records = mmth_loanapp_data[
"lnappuser_questselect"]
188 for lnappuser_questselect_rec
in mmth_lnappuser_questselect_records:
189 lnappuser_questselect_rec[
"userid"] = lnappuser_userid_map[lnappuser_questselect_rec[
"userid"].strip()]
193 "lnappuser_questselect",
194 collection=mmth_lnappuser_questselect_records
197 progress_dict[
"completed"] += 1
198 log_progress(progress_dict)
201 mmth_lnappuserresponse_records = mmth_loanapp_data[
"lnappuserresponse"]
203 invalid_responses_indices = []
205 for ind, lnappuserresponse_rec
in enumerate(mmth_lnappuserresponse_records):
207 del lnappuserresponse_rec[
"respid"]
212 if lnappuserresponse_rec[
"userid"].strip()
not in lnappuser_userid_map:
213 invalid_responses_indices.append(ind)
217 lnappuserresponse_rec[
"userid"] = lnappuser_userid_map[lnappuserresponse_rec[
"userid"].strip()]
218 lnappuserresponse_rec[
"loanid"] = lnappschemamaster_loanid_map[lnappuserresponse_rec[
"loanid"].strip()]
221 if "resploandesc" in lnappuserresponse_rec:
222 del lnappuserresponse_rec[
"resploandesc"]
225 respapplication = json.loads(lnappuserresponse_rec[
"respapplication"])
231 if type(respapplication) == dict:
232 updated_respapplication = {}
233 for k_resp_formfield
in list(respapplication.keys()):
234 assert "formfield" in k_resp_formfield
235 ffield, resp_old_detailid = k_resp_formfield.strip().split(
"_")
237 new_k_resp_formfield =
"{}_{}".format(
239 lnappschemadetail_detailid_map[resp_old_detailid])
240 updated_respapplication[new_k_resp_formfield] = respapplication[k_resp_formfield]
242 lnappuserresponse_rec[
"respapplication"] = get_valid_json(updated_respapplication)
245 [mmth_lnappuserresponse_records.pop(i)
for i
in sorted(invalid_responses_indices, reverse=
True)]
250 collection=mmth_lnappuserresponse_records
253 progress_dict[
"completed"] += 1
254 log_progress(progress_dict)
258 @pg_crsr_hndlr_decrtr
260 """Cleanup loanapps content 262 If kwargs.get('commit_later') flag is True, we do not commit the 263 transaction here (and only cleanup database tables, not the branding 264 files), meaning that the the cleanup may have been executed before actual 265 migration and we do not want to commit the database delete just yet. 266 If commit_later flag is False, we commit the transaction here and proceed 267 with the file cleanup. 270 del_loans_transaction: instance of PgTransaction to which this 271 cleanup process is part of 272 cucode: current credit union code 273 **kwargs: Optional parameters: 274 commit_later: flag to commit transaction later 276 accountnumber: if we want to filter delete 277 based on account number 280 SystemExit: if IOError, NameError or PermissionError is caught 281 psycopg2.Error, psycopg2.Warning on db operation errors 283 commit_later = kwargs.get(
"commit_later",
False)
284 where_condition_cu = {
"cu": cucode}
287 lnappschemamaster_loanids = del_loans_transaction(
290 select_columns=[
"loanid"],
291 where_conditions=where_condition_cu
295 lnappuser_userids = del_loans_transaction(
298 select_columns=[
"userid"],
299 where_conditions=where_condition_cu
307 for tbl_del_loanid
in [
"lnappschemadetail",
"lnappuserresponse"]:
308 for lnappschemamaster_loanid
in lnappschemamaster_loanids:
309 del_loans_transaction(
312 where_conditions={
"loanid": lnappschemamaster_loanid[0]}
319 for tbl_del_userid
in [
"lnappuser_questselect",
"lnappuserresponse"]:
320 for lnappuser_userid
in lnappuser_userids:
321 del_loans_transaction(
324 where_conditions={
"userid": lnappuser_userid[0]}
331 for tbl
in [
"lnappschemamaster",
"lnappuser"]:
332 del_loans_transaction(
335 where_conditions=where_condition_cu
338 if os.path.exists(LOANAPP_SCHEMAMASTER_LOANID_MAP_CSV_FILE.format(cucode.lower())):
339 os.remove(LOANAPP_SCHEMAMASTER_LOANID_MAP_CSV_FILE.format(cucode.lower()))
341 if os.path.exists(LOANAPP_USER_USERID_MAP_CSV_FILE.format(cucode.lower())):
342 os.remove(LOANAPP_USER_USERID_MAP_CSV_FILE.format(cucode.lower()))
346 del_loans_transaction.commit()
347 del_loans_transaction(
354 @pg_crsr_hndlr_decrtr
356 """Entry point to the loanapps migration. 359 cu: current credit union code 360 server: Mammoth endpoint server 361 action: one of the migration options to be 362 performed on settings data category 363 user: Mammoth monitor username 364 passwd: Mammoth monitor password 365 verbose: level of verbosity 366 reset: flag to cleanup tables before migration 369 psycopg2.Error, psycopg2.Warning on db operation errors 372 with pg_handler.PGSession()
as conn:
373 with conn.cursor()
as cur:
377 do_not_exist_list) = tables_exist_transaction(
383 if not tables_exist_flag:
384 error_msg = (
"Stopping migration. Following table" 385 " schemas do not exist: {}").format(
386 get_valid_json(
", ".join(do_not_exist_list)))
387 LOGGER.error(error_msg)
388 raise SystemExit(error_msg)
391 "All required target tables exist! Continuing migration..")
394 if action == ACTION_OPT_MIGRATE:
397 with pg_handler.PGSession()
as conn:
398 with conn.cursor()
as cur:
410 loanapps_migration.run()
412 LOGGER.info(
"Initiating migrating response data to odyssey")
417 with pg_handler.PGSession()
as conn:
418 with conn.cursor()
as cur:
434 loanapps_migration.response,
438 loans_transaction.commit()
448 LOGGER.info(
"Loan apps migration completed!")
451 elif action == ACTION_OPT_CLEAN:
452 with pg_handler.PGSession()
as conn:
453 with conn.cursor()
as cur:
457 LOGGER.info(
"Loan apps records clean up completed!")
460 elif action == ACTION_OPT_SUMMARY:
461 with pg_handler.PGSession()
as conn:
462 with conn.cursor()
as cur:
def migrate_loanapps(cu, server, action, user, passwd, verbose, reset)
def cleanup_loanapps(del_loans_transaction, cucode, **kwargs)
def move_loanapps(loans_transaction, mmth_loanapp_dict, verbose, cucode)