class vouchersServices(object): """ Class contains functions and attributes for authtentication Function: * getCampainge(sel) """ def __init__(self, user): self.lang = {} self.lang = getattr(language, config.DEFAULT_LANG) self.user = user self.model = Vouchers(user) self.logger = Logger() def getAllVouchers(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ if request_data == {}: request_data = {'page': 0, 'fromdate': '', 'todate': ''} else: pass print(request_data) self.logger.write_to_console("EVENT", "loading all vouchers for {0}".format(self.user['username'])) if request_data == {}: request_data = {'offset':0, 'records':10, 'fromdate':'', 'todate':'', 'status':''} else: request_data['offset'] = int(request_data['page'])*10 request_data['records'] = 10 if self.user.get('branch_code',"").lower()!='all': request_data['branch']=self.user.get('branch') customer_data = self.model.getAllVouchers(request_data) print(customer_data) branch_data = self.model.getBranches() for result in customer_data[0]: result["date_uploaded"] = result["date_uploaded"].strftime("%Y-%m-%d %H:%M:%S") # if result["status"] == 1: # result["status"] = self.lang["active"] # else: # result["status"] = self.lang["inactive"] pages = math.ceil(customer_data[1][0]['count']/12) print(pages) self.logger.write_to_console("EVENT", "Administrators gotten | Success.") return {"code":language.CODES['SUCCESS'], "msg":self.lang['data_retrived'], "data":customer_data[0], "pages": pages, "branches": branch_data} return customer_data def getAllvouchersExport(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ request_data['offset'] = 0 request_data['records'] = 1000000 print(request_data) self.logger.write_to_console("EVENT", "loading all bulkpay uploads for {0}".format(self.user['username'])) export_list = [['ACCOUNT', 'FIRST NAME', 'LAST NAME', 'MIDDLE NAME','GENDER','PHONE NUMBER', 'BRANCH', 'STATUS', 'DATE REGISTERED']] # if self.user['access_level_id'] == 4: merchant_data = self.model.getAllvouchers(request_data) # else: # merchant_data = self.model.getAllvouchersByBranch(request_data) print(merchant_data) for result in merchant_data[0]: result["join_date"] = result["join_date"].strftime("%Y-%m-%d %H:%M:%S") if result["status"] == 1: result["status"] = self.lang["active"] else: result["status"] = self.lang["inactive"] export_list.append([result['id'], result['first_name'], result['last_name'], result['middle_name'], result['gender'], result['status'], result['join_date']]) print(export_list) return export_list def addVoucher(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console("EVENT", "{0} Adding Customer {1}".format(self.user['username'], str(request_data))) request_data['requested_by'] = self.user['username'] request_data['branch'] = request_data['customer_account'][:3] print(request_data) result = self.model.addNewRegistrationRequest(request_data) result = self.model.addCustomerRequest({'requested_by': self.user['username'], 'request_type': '0', 'customer_msisdn': request_data['customer_msisdn'], 'customer_account': request_data['customer_account'], 'branch': self.user['branch_id'] }) self.logger.write_log("CUSTOMER", "Customer registration Request | {} | {} | {} | ".format(request_data['customer_msisdn'], request_data['customer_account'], self.user['username'])) # return customer_data return {'code': '00', 'msg': 'Customer registration request sent successfully'} def getVoucherDetials(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console("EVENT", "Getting voucher details: {}".format(request_data)) # print(request_data.get('msisdn')) request_keys = request_data.keys() validation_keys = ["mno","msisdn","apikey","serial_no"] for item in validation_keys: if item not in request_data: return {'code': '01', 'msg': 'Wrong parameters sent.', 'data':[]} if request_data['apikey'] != "500cdd1b531d83e00a5a4": return {'code': '01', 'msg': 'Unauthorised request.', 'data':[]} # if 'serial_no' not in request_data or 'sticker_no' not in request_data or 'msisdn' not in request_data or 'mno' not in request_data: # return {'code': '01', 'msg': 'Wrong parameters sent.', 'data':[]} # vhash = hashlib.sha256((request_data['serial_no'] +":"+ request_data['sticker_no']).encode()) vhash = hashlib.sha256((request_data['serial_no']).encode()) vhash = vhash.hexdigest() print(vhash) voucher_data = self.model.getVoucherByHash(vhash) for result in voucher_data: result["date_uploaded"] = result["date_uploaded"].strftime("%Y-%m-%d %H:%M:%S") if result["date_validated"] != None: result["date_validated"] = result["date_validated"].strftime("%Y-%m-%d %H:%M:%S") if voucher_data == []: return {'code': '01', 'msg': 'Serial number is invalid.', 'data':[]} else: return {'code': '00', 'msg': 'Serial number is valid.', 'data':[]} def getVoucherDetialsValidate(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console("EVENT", "Getting voucher details: {}".format(request_data)) if request_data['apikey'] != "500cdd1b531d83e00a5a4": return {'code': '01', 'msg': 'Unauthorised request.', 'data':[]} if 'serial_no' not in request_data or 'sticker_no' not in request_data or 'msisdn' not in request_data or 'mno' not in request_data: return {'code': '01', 'msg': 'Wrong parameters sent.', 'data':[]} vhash = hashlib.sha256((request_data['serial_no'] +":"+ request_data['sticker_no']).encode()) vhash = vhash.hexdigest() print(vhash) voucher_data = self.model.getVoucherByHash(vhash) for result in voucher_data: result["date_uploaded"] = result["date_uploaded"].strftime("%Y-%m-%d %H:%M:%S") if result["date_validated"] != None: result["date_validated"] = result["date_validated"].strftime("%Y-%m-%d %H:%M:%S") if voucher_data == []: use_data = { "user_msisdn": request_data['msisdn'], "serial_no": request_data['serial_no'], "sticker_no": request_data['sticker_no'], 'status': "NON-EXISTENT", 'status_details': "Sticker does not exist.", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) blacklist_res = self.report_user(use_data) return {'code': '02', 'msg': 'Voucher is invalid.', 'data':[], "blacklisted": blacklist_res} else: if voucher_data[0]['is_used'] == "USED": use_data = { "user_msisdn": request_data['msisdn'], "serial_no": request_data['serial_no'], "sticker_no": request_data['sticker_no'], 'status': "USED STICKER", 'status_details': "Sticker already used.", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) blacklist_res = self.report_user(use_data) return {'code': '01', 'msg': 'Voucher is used', 'data': voucher_data[0], "blacklisted": blacklist_res} elif voucher_data[0]['is_used'] == "UNUSED": use_data = { "user_msisdn": request_data['msisdn'], "serial_no": request_data['serial_no'], "sticker_no": request_data['sticker_no'], 'status': "VALID STICKER", 'status_details': "Sticker is valid.", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '00', 'msg': 'Voucher is not used', 'data':[]} else: use_data = { "user_msisdn": request_data['msisdn'], "serial_no": request_data['serial_no'], "sticker_no": request_data['sticker_no'], 'status': "NON-EXISTENT", 'status_details': "Sticker does not exist.", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) blacklist_res = self.report_user(use_data) return {'code': '02', 'msg': 'Voucher is invalid.', 'data':[], "blacklisted": blacklist_res} def getSerialDetialsValidate(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console("EVENT", "Getting voucher details: {}".format(request_data)) if request_data['apikey'] != "500cdd1b531d83e00a5a4": return {'code': '01', 'msg': 'Unauthorised request.', 'data':[]} if 'serial_no' not in request_data or 'msisdn' not in request_data or 'mno' not in request_data: return {'code': '01', 'msg': 'Wrong parameters sent.', 'data':[]} escaped_serial_no = re.sub("\ |\?|\.|\!|\/|\;|\:|\%|\@|\#|\*|\)|\(", '', request_data['serial_no']) vhash = hashlib.sha256((escaped_serial_no.encode())) vhash = vhash.hexdigest() print(vhash) voucher_data = self.model.getSerialByHash(vhash) validators = self.model.getValidatorByMsisdn(request_data['msisdn']) if voucher_data == []: if validators == []: use_data = { "user_msisdn": request_data['msisdn'], "user_type": "gen_public", "user_name": "unknown", "serial_no": request_data['serial_no'], 'status': "NON EXISTENT", 'status_details': "Serial does not exist", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) else: use_data = { "user_msisdn": request_data['msisdn'], "user_type": "validator", "user_name": validators[0]["first_name"], "user_branch": validators[0]["branch"], "serial_no": request_data['serial_no'], 'status': "FAILED", 'status_details': "Serial does not exist", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '02', 'msg': 'Your serial is invalid.', 'data':[]} else: #identify who is initiating the validation (a user or a validator) #validators = self.model.getValidatorByMsisdn(request_data['msisdn']) if validators == []: #if no validator data is found, then user is a public user if voucher_data[0]['serial_status'] == "NOT VALIDATED": use_data = { "user_msisdn": request_data['msisdn'], "user_type": "gen_public", "user_name": "unknown", "serial_no": request_data['serial_no'], 'status': "NOT VALIDATED", 'status_details': "Serial is not validated", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '01', 'msg': 'Your serial is not validated', 'data': []} elif voucher_data[0]['serial_status'] == "VALIDATED": voucher_data[0]["expiry_date"] = voucher_data[0]["expiry_date"].strftime("%Y-%m-%d") expiry_date = voucher_data[0]["expiry_date"] use_data = { "user_msisdn": request_data['msisdn'], "user_type": "gen_public", "user_name": "unknown", "serial_no": request_data['serial_no'], 'status': "VALIDATED", 'status_details': 'Serial is validated but expires on ' + voucher_data[0]["expiry_date"], 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '00', 'msg': 'Your serial is valid but expires on ' + voucher_data[0]["expiry_date"], 'data':[]} else: use_data = { "user_msisdn": request_data['msisdn'], "user_type": "gen_public", "user_name": "unknown", "serial_no": request_data['serial_no'], 'status': "NO ACTION", 'status_details': "No action performed", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '02', 'msg': 'No action to perform', 'data':[]} else: #ok now we know its a validator, lets proceed to validate a serial number if not validated yet if voucher_data[0]['serial_status'] == "NOT VALIDATED": #All serials must be assigned to branch before validation can be successful so check here if voucher_data[0]['branch_assigned'] == "None": use_data = { "user_msisdn": request_data['msisdn'], "user_type": "validator", "user_name": validators[0]["first_name"], "user_branch": validators[0]["branch"], "serial_no": request_data['serial_no'], 'status': "FAILED", 'status_details': "Serial not assigned to a branch", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '01', 'msg': 'Serial must be assigned to a branch', 'data': []} else: expiry_date = self.addDaysToDate(addDays = 90) update_params = { "serial_id": voucher_data[0]['serial_id'], "serial_status": "VALIDATED", "validator_msisdn": validators[0]["msisdn"], "date_validated": "NOW()", "expiry_date": expiry_date } update_response = self.model.updateSerial(update_params) if update_response == True: use_data = { "user_msisdn": request_data['msisdn'], "user_type": "validator", "user_name": validators[0]["first_name"], "user_branch": validators[0]["branch"], "serial_no": request_data['serial_no'], 'status': "SUCCESS", 'status_details': "Successful serial validation", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '00', 'msg': 'Serial successfully validated', 'data': []} else: use_data = { "user_msisdn": request_data['msisdn'], "user_type": "validator", "user_name": validators[0]["first_name"], "user_branch": validators[0]["branch"], "serial_no": request_data['serial_no'], 'status': "FAILED", 'status_details': "Failed to validate serial ", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '01', 'msg': 'Failed to validate Serial', 'data': []} elif voucher_data[0]['serial_status'] == "VALIDATED": use_data = { "user_msisdn": request_data['msisdn'], "user_type": "validator", "user_name": validators[0]["first_name"], "user_branch": validators[0]["branch"], "serial_no": request_data['serial_no'], 'status': "DUPLICATE", 'status_details': "Serial already validated", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '00', 'msg': 'Serial is already validated', 'data':[]} else: use_data = { "user_msisdn": request_data['msisdn'], "user_type": "validator", "user_name": validators[0]["first_name"], "user_branch": validators[0]["branch"], "serial_no": request_data['serial_no'], 'status': "NO ACTION", 'status_details': "No action performed", 'user_mno': request_data['mno'], } self.model.add_user_activity(use_data) return {'code': '02', 'msg': 'Nothing for admin to perform', 'data':[]} def report_user(self, use_data): today_start = str(datetime.datetime.today().date())+' 00:00:00' today_end = str(datetime.datetime.today().date())+' 23:59:59' request_data = {'offset':0, 'records':1000, 'fromdate': today_start, 'todate': today_end, 'status':'', 'user_msisdn': use_data["user_msisdn"]} act = Activities({}) vdata = act.getAllActivities(request_data) print(vdata) if len(vdata[0]) >=3: self.model.addBlacklist({"msisdn": use_data["user_msisdn"], "reason": "Too many wrong tries"}) return True else: return False def useVoucher(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console("EVENT", "Getting voucher details: {}".format(request_data)) if request_data['apikey'] != "500cdd1b531d83e00a5a4": return {'code': '01', 'msg': 'Unautorised request.', 'data':[]} if 'serial_no' not in request_data or 'sticker_no' not in request_data or 'msisdn' not in request_data or 'mno' not in request_data or 'car_no' not in request_data: return {'code': '01', 'msg': 'Wrong parameters sent.', 'data':[]} vhash = hashlib.sha256((request_data['serial_no'] +":"+ request_data['sticker_no']).encode()) vhash = vhash.hexdigest() print(vhash) voucher_data = self.model.getVoucherByHash(vhash) if voucher_data == []: return {'code': '01', 'msg': 'Voucher is invalid.', 'data':[]} else: if voucher_data[0]['is_used'] == "USED": return {'code': '01', 'msg': 'Voucher is already used', 'data': []} elif voucher_data[0]['is_used'] == "UNUSED": vcode = ''.join(random.SystemRandom().choice(string.digits) for _ in range(8)) sms_status = 'SENT' use_data = { "unique_id": voucher_data[0]['unique_id'], "is_used": "USED", "car_no": request_data['car_no'], 'user_msisdn': request_data['msisdn'], 'user_mno': request_data['mno'], 'serial_no': request_data['serial_no'], 'sticker_no': request_data['sticker_no'], 'sms_status': sms_status, 'verification_code': vcode, 'date_validated': 'NOW()' } print(use_data) result = self.model.updateVoucher(use_data) if result == True: return {'code': '00', 'msg': 'Voucher validation completed.', 'data':{"car_no": request_data['car_no'], 'use_msisdn': request_data['msisdn'],'serial_no': request_data['serial_no'], 'sticker_no': request_data['sticker_no'], 'verification_code': vcode }} else: return {'code': '01', 'msg': 'Failed: Kindly try again.', 'data':[]} else: return {'code': '01', 'msg': 'Voucher is invalid.', 'data':[]} def updateVoucher(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console("EVENT", "{0} Customer Reset Pin {1}".format(self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequests(request_data['id']) if request_data['msisdn'] != request_data['id']: if len(pending_requests) > 0: for reques in pending_requests: if reques['request_type'] == 2: return {'code': '01', 'msg': 'Change phone number request for customer is already pending.'} else: result = self.model.addCustomerRequest({'requested_by': self.user['username'], 'request_type': '2', 'customer_msisdn': request_data['id'], 'customer_account': request_data['id'], 'branch': self.user['branch_id'], 'change_from': request_data['id'], 'change_to': request_data['msisdn'] }) self.logger.write_log("CUSTOMER", "Change Customer Phone Number Request | {} | {} | {} ".format(request_data['customer_id'], request_data['id'], self.user['username'])) break result = self.model.updatevouchers({ 'id': request_data['id'], 'first_name': request_data['first_name'], 'middle_name': request_data['middle_name'], 'last_name': request_data['last_name'], 'gender': request_data['gender'] }) self.logger.write_log("CUSTOMER", "Update Customer Details | {} | {} ".format(request_data['id'], self.user['username'])) return {'code': '00', 'msg': 'Request sent.'} def searchvouchers(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ print(request_data) self.logger.write_to_console("EVENT", "Searching vouchers for {0}".format(request_data['search_param'])) customer_data = self.model.searchvouchers(request_data) for result in customer_data: result["join_date"] = result["join_date"].strftime("%Y-%m-%d %H:%M:%S") # if result["status"] == 1: # result["status"] = self.lang["active"] # else: # result["status"] = self.lang["inactive"] return customer_data def getAllUploadsRequests(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ if request_data == {}: request_data = {'page': 0, 'fromdate': '', 'todate': ''} else: pass print(request_data) self.logger.write_to_console("EVENT", "loading all uploads for {0}".format(self.user['username'])) if request_data == {}: request_data = {'offset':0, 'records':10, 'fromdate':'', 'todate':'', 'request_type':''} else: request_data['offset'] = int(request_data['page'])*10 request_data['records'] = 10 if self.user.get('branch_code',"").lower()!='all': request_data['branch']=self.user.get('branch_code') print("branch ##################{}".format(self.user)) customer_data = self.model.getAllUploads(request_data) print(customer_data) for result in customer_data[0]: result["upload_date"] = result["upload_date"].strftime("%Y-%m-%d %H:%M:%S") if result["processed_date"] != None: result["processed_date"] = result["processed_date"].strftime("%Y-%m-%d %H:%M:%S") if result["approved_date"] != None: result["approved_date"] = result["approved_date"].strftime("%Y-%m-%d %H:%M:%S") pages = math.ceil(customer_data[1][0]['count']/10) print(pages) self.logger.write_to_console("EVENT", "Administrators gotten | Success.") return {"code":language.CODES['SUCCESS'], "msg":self.lang['data_retrived'], "data":customer_data[0], "pages": pages} return customer_data def record_uploaded_file(self, file_obl): self.logger.write_to_console("EVENT", "Recording Uploaded file | {}".format(file_obl.filename)) file_extension = file_obl.filename.split(".") # filetype = file_extension[-1] if file_extension[-1] != "csv": return {"code":language.CODES['FAIL'], "msg":self.lang['wrong_file_format'], "data":[]} bulk_id = self.generate_id(self.user['branch_code']) # file_obl.save(secure_filename(file_obl.filename)) file_obl.save(os.path.join(config.UPLOAD_DIRECTORY, bulk_id+".csv")) # fileChecksum = self.md5Checksum(bulk_id+".csv") fileSize = os.stat(os.path.join(config.UPLOAD_DIRECTORY, bulk_id+".csv")).st_size fields = {"bulk_id":bulk_id, "filename": file_obl.filename, "filesize": fileSize, "fileType": file_extension[-1], # "file_checksum": fileChecksum, "branch": self.user['branch_code'], "uploaded_by": self.user['username'] } self.logger.write_to_console("EVENT", "Uploaded File Details | {}".format(fields)) result = self.model.insertBulkUpload(fields) print(result) if result == True: # self.logger.write_to_console("EVENT", "Starting processing Thread for | {}".format(file_obl.filename)) # processing_thread = Thread(target=self.process_csv, args=(os.path.join(config.UPLOAD_DIRECTORY, bulk_id+".csv"), file_obl.filename, self.user['username'])) # processing_thread.start() # self.logger.write_to_console("EVENT", "Thread started for | {}".format(file_obl.filename)) self.logger.write_log("UPLOAD", "Uploaded Bulk Serials | {} | {} ".format(fields['bulk_id'] + ".csv", self.user['username']) + " | Successful") return {"code":language.CODES['SUCCESS'], "msg":self.lang['file_recorded'], "data":[]} else: self.logger.write_log("UPLOAD", "Uploaded Bulk Serials | {} | {} ".format(fields['bulk_id']+ ".csv", self.user['username']) + " | Failed") return {"code":language.CODES['FAIL'], "msg":self.lang['wrong_file_format'], "data":[]} def approve_uploaded_file(self, request_data): self.logger.write_to_console("EVENT", "Recording Uploaded file | {}".format(request_data['bulk_id'])) #bulk_details = self.model.getBulkUploadDetails(request_data['bulk_id']) fields = {"bulk_id": request_data['bulk_id'], # "file_checksum": fileChecksum, "approval_status": "Approved", "processing_status": "Processing", "approved_by": self.user['username'], "approved_date": "NOW()" } self.logger.write_to_console("EVENT", "Uploaded File Details | {}".format(fields)) result = self.model.updateBulkUpload(fields) print(result) if result == True: bulk_details = self.model.getBulkUploadDetails(request_data['bulk_id']) self.logger.write_to_console("EVENT", "Starting processing Thread for | {}".format(request_data['bulk_id'])) processing_thread = Thread(target=self.process_csv_new, args=(os.path.join(config.UPLOAD_DIRECTORY, request_data['bulk_id']+".csv"), bulk_details[0]['approved_date'],self.user['username'],bulk_details[0]['branch'], request_data['bulk_id'])) processing_thread.start() self.logger.write_to_console("EVENT", "Thread started for | {}".format(request_data['bulk_id'])) self.logger.write_log("PROCESS_UPLOAD", "Approve Bulk Serials | {} | {} ".format(request_data['bulk_id']+ ".csv", self.user['username']) + " | Successful") return {"code":language.CODES['SUCCESS'], "msg": "File processing approved.", "data":[]} else: self.logger.write_log("PROCESS_UPLOAD", "Approve Bulk Serials | {} | {} ".format(request_data['bulk_id']+ ".csv", self.user['username']) + " | Failed") return {"code":language.CODES['FAIL'], "msg":self.lang['wrong_file_format'], "data":[]} def decline_uploaded_file(self, request_data): self.logger.write_to_console("EVENT", "Recording Uploaded file | {}".format(request_data['bulk_id'])) fields = {"bulk_id": request_data['bulk_id'], # "file_checksum": fileChecksum, "approval_status": "Declined", "processing_status": "Processing", "approved_by": self.user['username'], "approved_date": "NOW()" } self.logger.write_to_console("EVENT", "Uploaded File Details | {}".format(request_data['bulk_id'])) result = self.model.updateBulkUpload(fields) print(result) if result == True: self.logger.write_log("PROCESS_UPLOAD", "Decline Bulk Serials | {} | {} ".format(request_data['bulk_id']+ ".csv", self.user['username']) + " | Successful") return {"code":language.CODES['SUCCESS'], "msg": "File processing declined.", "data":[]} else: self.logger.write_log("PROCESS_UPLOAD", "Decline Bulk Serials | {} | {} ".format(request_data['bulk_id']+ ".csv", self.user['username']) + " | Failed") return {"code":language.CODES['FAIL'], "msg":self.lang['wrong_file_format'], "data":[]} def process_csv(self, filename, uploaded_by,approved_by,branch, bulk_id): try: res=[] unique_id = "" voucher_hash = "" print("processing csv") with open(filename, "rb") as f: reader= unicodecsv.DictReader(f) #file upload is being read in a group in a dictionary{} print(reader) res=[x for x in reader] # self.log.write_to_file(msg="In process_csv_reader {}".format(res),filename="event") # print(res) #reading the file in a format way for processing counter=1 for trans in res: try: #Converting the data in a dictionary form trans = dict(trans) self.logger.write_to_console("EVENT", "Processing: {}".format(trans)) print(trans) #Converting the header of the file in lowercase for processing in key-value pair for key, value in trans.items(): try: print(key) print(value) if key.lower() == "id": unique_id = bulk_id +"--"+ value if key.lower() == "serial": vhash = hashlib.sha256((value.encode())) vhash = vhash.hexdigest() voucher_hash = vhash except Exception as e: raise e print(e) error = str(e) return error #sending request to the tups_portal(etienee' portal) request_data = { "unique_id": unique_id, "voucher_hash": voucher_hash, "uploaded_by":uploaded_by, "approved_by":approved_by, "branch":branch } self.logger.write_to_console("EVENT", "Adding voucher | {}".format(request_data)) api_response = self.model.add_voucher_new(request_data) print(api_response) # api_response = {"code": "00", "msg": "Response"} self.logger.write_to_console("EVENT", "Adding serials response | {}".format(api_response)) #response from tups portal(etienne's portal) successfully save to tbl_bulk_transaction if api_response == True: self.logger.write_to_console("EVENT", "Serial Adding Successful | {}".format(request_data)) #api_response from tups portal(etienne's portal) failed to be processed which is save to tbl_bulk_transaction else: self.logger.write_to_console("EVENT", "Registration Failed | {}".format(request_data)) except Exception as e: raise e print(e) error = str(e) self.log.write_to_file(msg="In process_csv_error_exception {}".format(error),filename="error") return error data = {"processing_status": "Completed", "processed_date": "NOW()", "bulk_id": bulk_id} result = self.model.updateBulkUpload(data) ##### # Send Mail ##### except Exception as e: raise e error = "Processing of file failed" self.log.write_to_file(msg="In process_csv_exeception_raised_error {}".format(error),filename="error") return error def process_csv_new(self, filename, date_approved,approved_by,branch, bulk_id): try: res=[] unique_id = "" voucher_hash = "" print("processing csv") with open(filename, "rb") as f: reader= unicodecsv.DictReader(f) #file upload is being read in a group in a dictionary{} print(reader) res=[x for x in reader] # self.log.write_to_file(msg="In process_csv_reader {}".format(res),filename="event") # print(res) #reading the file in a format way for processing counter=1 for trans in res: try: #Converting the data in a dictionary form trans = dict(trans) self.logger.write_to_console("EVENT", "Processing: {}".format(trans)) print(trans) #Converting the header of the file in lowercase for processing in key-value pair for key, value in trans.items(): try: print(key) print(value) if key.lower() == "id": unique_id = bulk_id +"--"+ value if key.lower() == "serial": vhash = hashlib.sha256((value.encode())) vhash = vhash.hexdigest() voucher_hash = vhash except Exception as e: raise e print(e) error = str(e) return error #sending request to the tups_portal(etienee' portal) request_data = { "bulk_id": bulk_id, "hashed_serial_number": voucher_hash, "date_approved":date_approved, "approved_by":approved_by, "raw_serial_number":value, "serial_status": "NOT VALIDATED", "batch_id": counter } counter+=1 self.logger.write_to_console("EVENT", "Adding voucher | {}".format(request_data)) api_response = self.model.add_voucher_new(request_data) print(api_response) # api_response = {"code": "00", "msg": "Response"} self.logger.write_to_console("EVENT", "Adding serials response | {}".format(api_response)) #response from tups portal(etienne's portal) successfully save to tbl_bulk_transaction if api_response == True: self.logger.write_to_console("EVENT", "Serial Adding Successful | {}".format(request_data)) #api_response from tups portal(etienne's portal) failed to be processed which is save to tbl_bulk_transaction else: self.logger.write_to_console("EVENT", "Registration Failed | {}".format(request_data)) except Exception as e: raise e print(e) error = str(e) self.log.write_to_file(msg="In process_csv_error_exception {}".format(error),filename="error") return error data = {"processing_status": "Completed", "processed_date": "NOW()", "bulk_id": bulk_id} result = self.model.updateBulkUpload(data) ##### # Send Mail ##### except Exception as e: raise e error = "Processing of file failed" self.log.write_to_file(msg="In process_csv_exeception_raised_error {}".format(error),filename="error") return error def searchvouchersRequests(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ print(request_data) self.logger.write_to_console("EVENT", "Searching vouchers for {0}".format(request_data['search_param'])) customer_data = self.model.searchvouchersReq(request_data) for result in customer_data: result["request_date"] = result["request_date"].strftime("%Y-%m-%d %H:%M:%S") # if result["status"] == 1: # result["status"] = self.lang["active"] # else: # result["status"] = self.lang["inactive"] return customer_data def generate_id(self, preamb): """ Generate unique id Parameters: preamb => string to be used at the start of the id """ t_id = preamb + str(hash(str(uuid.uuid1())) % 100000000000) return t_id def md5Checksum(self, fileName): filePath = os.path.join(config.UPLOAD_DIRECTORY, fileName) with open(filePath, 'rb') as fh: m = hashlib.md5() while True: data = fh.read() if not data: break m.update(data) return m.hexdigest() def getVoucherByBulkId(self, bulk_id, request_data): if request_data == {}: request_data = {'offset':0, 'records':10} else: request_data['offset'] = int(request_data['page'])*10 request_data['records'] = 10 filter_data={} voucher_bulk_data = self.model.getVoucherByBulkId(bulk_id, request_data) filter_data['voucher_details'] = voucher_bulk_data[0] filter_data['pages'] = math.ceil(voucher_bulk_data[1][0]['count']/10) filter_data['branches'] = branch_data = self.model.getBranches() print(filter_data) return filter_data def updateBulkAssignSerialBranch(self, data): request_data = { "branch_assigned": data["branch_assigned"] } result = self.model.updateBulkAssignSerialBranch(request_data, data["bulk_id"], data["minRange"], data["maxRange"]) if result == True: return {"code":language.CODES['SUCCESS'], "msg":"Serials successfully assigned to branch", "data":[]} else: return {"code":language.CODES['FAIL'], "msg":"Failed to assign serials to branch", "data":[]} def addDaysToDate(self, dateFormat="%Y-%m-%d %H:%M:%S", addDays=0): timeNow = datetime.datetime.now() anotherTime = timeNow + datetime.timedelta(days=addDays) return anotherTime.strftime(dateFormat) def getVerificationHistory(self, request_data): filter_data = {} if request_data == {}: request_data = {'offset':0, 'records':10, 'user_type': 'gen_public'} else: request_data['offset'] = int(request_data['page'])*10 request_data['records'] = 10 request_data['user_type'] = 'gen_public' print(str(request_data)) all_data = self.model.getVerificationHistory(request_data) filter_data['history'] = all_data[0] filter_data['pages'] = math.ceil(all_data[1][0]['count']/10) return filter_data def searchVerifiedVouchers(self, request_data): self.logger.write_to_console("EVENT", "Searching vouchers for {0}".format(request_data['search_param'])) request_data['user_type'] = 'gen_public' voucher_data = self.model.searchVerifiedVouchers(request_data) print(voucher_data) return voucher_data
class DashboardServices(object): """ Class contains functions and attributes for authtentication Function: * getCampainge(sel) """ def __init__(self, user): self.lang = {} self.lang = getattr(language, config.DEFAULT_LANG) self.user = user self.model = Dashboard(user) self.logger = Logger() def getValidationInfo(self): self.logger.write_to_console( "EVENT", "{0} Getting Statistics {1}".format(self.user['username'], str(self.user['username']))) filter_data = {} validation_query = "SELECT COUNT(*) AS total, SUM(serial_status = 'VALIDATED') AS validated, SUM(serial_status = 'NOT VALIDATED') AS non_validated FROM tbl_serials" uploads_query = "SELECT COUNT(*) AS total, SUM(approval_status = 'Approved') AS approved, SUM(approval_status = 'Not Approved') AS pending, SUM(approval_status = 'Declined') AS declined FROM tbl_uploads" verification_query = "SELECT COUNT(*) AS total, SUM(status = 'VALIDATED') AS validated, SUM(status = 'NOT VALIDATED' OR status = 'NON EXISTENT') AS failed FROM tbl_activity_log WHERE user_type = 'gen_public'" filter_data['validation'] = self.model.getSerialsValidationInfo( validation_query) filter_data['uploads'] = self.model.getSerialsValidationInfo( uploads_query) filter_data['verification'] = self.model.getSerialsValidationInfo( verification_query) print(filter_data) return filter_data def generateSerialsReport(self, request_data): """ This function generates report to be used in the chart @Params : void """ start_date = datetime.datetime.now().strftime("%Y-%m-%d") #if no data is supplied, return weekly report if 'get_chart' in request_data: end_date = self.addDaysToDate(addDays=6) request_data = { 'filter_type': 'weekly', 'from_date': end_date, 'end_date': start_date, 'user_type': request_data['get_chart'] } else: #check filter and apply necessary date range if request_data['filter_type'] == "daily": request_data['from_date'] = start_date request_data['end_date'] = start_date elif request_data['filter_type'] == "weekly": request_data['from_date'] = self.addDaysToDate(addDays=6) request_data['end_date'] = start_date elif request_data['filter_type'] == "monthly": request_data['from_date'] = self.addDaysToDate(addDays=30) request_data['end_date'] = start_date else: return [] report_data = self.model.generateSerialsReport(request_data) #process weekly days in order if request_data['filter_type'] == "weekly": week_days = [ "Monday", "Tuesday", "Wednessday", "Thursday", "Friday", "Saturday", "Sunday" ] i = 0 for days in report_data: days["days"] = week_days[i] i += 1 #process monthly days in order elif request_data['filter_type'] == "monthly": days_list = self.getDaysList() #length = len(days_list) formatted_date = [ "1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th", "31st" ] for days in report_data: day = days["days"] total = days["total"] #if day is in list if day in days_list: index = days_list.index(day) tempDict = { "days": formatted_date[day - 1], "total": total } days_list[index] = tempDict return days_list return report_data def addDaysToDate(self, dateFormat="%Y-%m-%d", addDays=0): timeNow = datetime.datetime.now() anotherTime = timeNow - datetime.timedelta(days=addDays) return anotherTime.strftime(dateFormat) def getDaysList(self): cur_date = datetime.date.today() days_ago = cur_date - datetime.timedelta(31) #get 30days ago date_difference = cur_date - days_ago daysList = [] for i in range(date_difference.days + 1): tempDate = cur_date - datetime.timedelta(i) daysList.append(tempDate.day) return daysList
class validatorServices(object): """ Class contains functions and attributes for authtentication Function: * getCampainge(sel) """ def __init__(self, user): self.lang = {} self.lang = getattr(language, config.DEFAULT_LANG) self.user = user self.model = Validator(user) self.logger = Logger() def getAllValidators(self, request_data): filter_data = {} if request_data == {}: request_data = {'offset': 0, 'records': 10, 'branch': 'None'} else: request_data['offset'] = int(request_data['page']) * 10 request_data['records'] = 10 validator_data = self.model.getAllValidators(request_data) filter_data['validators'] = validator_data[0] filter_data['pages'] = math.ceil(validator_data[1][0]['count'] / 10) filter_data['branches'] = self.model.getBranches() print(filter_data) return filter_data def getValidatorsHistory(self, request_data): self.logger.write_to_console( "EVENT", "{0} Getting Validators History {1}".format( self.user['username'], str(request_data))) filter_data = {} if request_data == {}: request_data = { 'offset': 0, 'records': 10, 'user_type': 'validator' } else: request_data['offset'] = int(request_data['page']) * 10 request_data['records'] = 10 request_data['user_type'] = 'validator' print(str(request_data)) all_data = self.model.getValidatorsHistory(request_data) filter_data['history'] = all_data[0] filter_data['pages'] = math.ceil(all_data[1][0]['count'] / 10) return filter_data def addValidator(self, request_data): """ This function handles the adding of a new validator @Params : void """ self.logger.write_to_console( "EVENT", "{0} Adding Validator {1}".format(self.user['username'], str(request_data))) request_data['msisdn'] = "233" + request_data['msisdn'][-9:] request_data['email'] = request_data['email'].strip() admin_data = self.model.getValidatorByMsisdn(request_data['msisdn']) if admin_data == []: admin_data = self.model.getValidatorByEmail(request_data['email']) if admin_data == []: self.logger.write_to_console("EVENT", "Preparing data") res = self.model.addValidator(request_data) if res == True: #Utilites.send_mail(Utilites, "SSNIT PORTAL", "<p>Hi {0}</p><p>Welcome SSNIT, below are your login credentials.<br><br>Username: {1}<br>Password: {2}<br><br><br> Regards</p><p>FUSION PLATFORM</p>".format(request_data['first_name'], request_data['username'], raw_password), [request_data['email']]) return { "code": language.CODES['SUCCESS'], "msg": self.lang['validator_added'], "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['validator_add_fail'], "data": [] } else: self.logger.write_to_console( "EVENT", "Existing validator email " + request_data['email'] + " | Blocked User.") return { "code": language.CODES['FAIL'], "msg": "Email is already registered to another validator.", "data": [] } else: self.logger.write_to_console( "EVENT", "Existing validator phone " + request_data['msisdn'] + " | Blocked User.") return { "code": language.CODES['FAIL'], "msg": "Phone number is already registered to another validator.", "data": [] } def deleteValidator(self, request_data): self.logger.write_to_console( "EVENT", "{0} Deleting Validator {1}".format( self.user['username'], str(request_data['validator_id']))) res = self.model.deleteValidator(request_data['validator_id']) if res == True: return { "code": language.CODES['SUCCESS'], "msg": self.lang['validator_deleted'], "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['validator_delete_fail'], "data": [] } def getValidatorDetails(self, request_data): self.logger.write_to_console( "EVENT", "Getting Details for " + self.user['username']) validator_data = self.model.getValidatorByEmail(request_data['email']) if validator_data == []: self.logger.write_to_console( "EVENT", "Failed to get validator " + self.user['username'] + " | Non-Existing User.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": [] } else: self.logger.write_to_console( "EVENT", "Validator Data retreived successfully " + self.user['username'] + " | Success.") return { "code": language.CODES['SUCCESS'], "msg": self.lang['record_successful'], "data": validator_data[0] } def updateValidator(self, request_data): self.logger.write_to_console( "EVENT", "{0} Updating Validator {1}".format(self.user['username'], str(request_data))) request_data['msisdn'] = "233" + request_data['msisdn'][-9:] res = self.model.updateValidator(request_data) if res == True: return { "code": language.CODES['SUCCESS'], "msg": self.lang['validator_updated'], "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['validator_update_fail'], "data": [] } def searchValidatoinHistory(self, request_data): self.logger.write_to_console( "EVENT", "Searching vouchers for {0}".format(request_data['search_param'])) request_data['user_type'] = 'validator' voucher_data = self.model.searchValidatoinHistory(request_data) print(voucher_data) for result in voucher_data: result["date_created"] = result["date_created"].strftime( "%Y-%m-%d %H:%M:%S") return voucher_data
class adminServices(object): """ Class contains functions and attributes for authtentication Function: * getCampainge(sel) """ def __init__(self, user): self.lang = {} self.lang = getattr(language, config.DEFAULT_LANG) self.user = user self.model = Administrator(user) self.logger = Logger() def adminlogin(self, request_data, try_var): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "Login request for " + request_data['username']) admin_data = self.model.getAdminByUsernameLogin( request_data['username']) if admin_data == []: self.logger.write_log( "USER_ACCESS", "Login request | " + request_data['username'] + " | Failed | Non-Existing User.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": [] } else: print(try_var) if try_var != None and try_var >= 3: self.model.updateAdministrator({ "active": "2", "last_login": "******", "username": request_data['username'] }) if try_var == 3: return { "code": language.CODES['FAIL'], "msg": "Sorry your account has been blocked. Kindly contact your administrator.", "data": 2, "username": request_data['username'] } else: return { "code": language.CODES['FAIL'], "msg": "Sorry your account has been blocked. Kindly contact your administrator.", "data": [] } else: if admin_data[0]['active'] == 1: print(admin_data[0]) verify_pass = sha256_crypt.verify( request_data['password'], admin_data[0]['password']) self.logger.write_to_console( "EVENT", "varify Password | " + str(verify_pass)) if verify_pass == True: self.model.updateAdministrator({ "status": "1", "last_login": "******", "username": request_data['username'] }) self.logger.write_log( "USER_ACCESS", "Login request | " + request_data['username'] + " | Successful | Login Successful") return { "code": language.CODES['SUCCESS'], "msg": self.lang['login_successful'], "data": admin_data[0], "username": request_data['username'] } else: self.logger.write_to_console( "EVENT", "Login request failed for " + request_data['username'] + " | Failed | Wrong Password.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": 1, "username": request_data['username'] } else: self.logger.write_to_console( "EVENT", "Login request failed for " + request_data['username'] + " | Failed | Blocked User") return { "code": language.CODES['FAIL'], "msg": "Sorry your account has been blocked. Kindly contact your administrator.", "data": 2, "username": request_data['username'] } def adminLogout(self): result = self.model.updateAdministrator({ "status": "0", "username": self.user['username'] }) return result def getAllAdministrators(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ if request_data == {}: request_data = { 'offset': 0, 'records': 11, 'fromdate': '', 'user_right_id': '', "branch": '', 'active': '' } else: request_data['offset'] = int(request_data['page']) * 11 request_data['records'] = 11 self.logger.write_to_console( "EVENT", "Getting administrator list for {} -> {}".format( self.user['username'], request_data)) if self.user['branch_code'] == "All": administrators_data = self.model.getAllAdministrators(request_data) admin_groups_data = self.model.getAdminGroups() branches_data = self.model.getBranches({ 'offset': 0, 'records': 11 }) else: administrators_data = self.model.getAllAdministratorsByBranch( request_data) admin_groups_data = self.model.getAdminGroups() branches_data = self.model.getBranches({ 'offset': 0, 'records': 11 }) for result in administrators_data: result["created"] = result["created"].strftime("%Y-%m-%d %H:%M:%S") result["last_login"] = result["last_login"].strftime( "%Y-%m-%d %H:%M:%S") if "pass_date" in result: result["pass_date"] = result["pass_date"].strftime( "%Y-%m-%d %H:%M:%S") self.logger.write_to_console( "EVENT", "Administrators list gotten successfully for {}".format( self.user['username'])) return { "code": language.CODES['SUCCESS'], "msg": self.lang['data_retrived'], "data": administrators_data, 'admin_group': admin_groups_data, 'branches': branches_data } def getAllAdministratorsExport(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ request_data['offset'] = 0 request_data['records'] = 10000 self.logger.write_to_console( "EVENT", "Getting administrator list for {} -> {}".format( self.user['username'], request_data)) export_list = [[ 'USERNAME', 'FIRST NAME', 'LAST NAME', 'EMAIL', 'PHONE NUMBER', 'BRANCH', 'GROUP', 'STATUS', 'DATE CREATED' ]] if self.user['branch_code'] == "All": administrators_data = self.model.getAllAdministrators(request_data) admin_groups_data = self.model.getAdminGroups() branches_data = self.model.getBranches() else: administrators_data = self.model.getAllAdministratorsByBranch( request_data) admin_groups_data = self.model.getAdminGroups() branches_data = self.model.getBranches() for result in administrators_data: result["created"] = result["created"].strftime("%Y-%m-%d %H:%M:%S") result["last_login"] = result["last_login"].strftime( "%Y-%m-%d %H:%M:%S") if "pass_date" in result: result["pass_date"] = result["pass_date"].strftime( "%Y-%m-%d %H:%M:%S") if result["active"] == 1: result["active"] = self.lang["active"] else: result["active"] = self.lang["inactive"] export_list.append([ result['username'], result['first_name'], result['last_name'], result['email'], result['email'], result['branch_code'], result['name'], result['active'], result['created'] ]) self.logger.write_to_console( "EVENT", "Administrators Export list gotten successfully for {}".format( self.user['username'])) return export_list def addAdmin(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Adding Admin {1}".format(self.user['username'], str(request_data))) request_data['msisdn'] = "233" + request_data['msisdn'][-9:] request_data['email'] = request_data['email'].strip() admin_data = self.model.getAdminByUsername(request_data['username']) if admin_data == []: admin_data = self.model.getAdminByMsisdn(request_data['msisdn']) if admin_data == []: admin_data = self.model.getAdminByEmail(request_data['email']) if admin_data == []: self.logger.write_to_console("EVENT", "Preparing data") # raw_password = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8)) utl = Utilites() raw_password = utl.generate_password(10) password = sha256_crypt.encrypt(raw_password) self.logger.write_to_console( "EVENT", "Generated password: {0} \n Hashed Password: {1} \n". format(raw_password, password)) # request_data['msisdn'] = "233" + request_data['msisdn'][-9:] request_data['password'] = password request_data['last_login'] = "******" res = self.model.addAdministrator(request_data) if res == True: Utilites.send_mail( Utilites, "SSNIT PORTAL", "<p>Hi {0}</p><p>Welcome SSNIT, below are your login credentials.<br><br>Username: {1}<br>Password: {2}<br><br><br> Regards</p><p>FUSION PLATFORM</p>" .format(request_data['first_name'], request_data['username'], raw_password), [request_data['email']]) return { "code": language.CODES['SUCCESS'], "msg": self.lang['admin_added'], "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['admin_add_fail'], "data": [] } else: self.logger.write_to_console( "EVENT", "Existing Admin Username " + request_data['username'] + " | Blocked User.") return { "code": language.CODES['FAIL'], "msg": "Email is already registered to another administrator.", "data": [] } else: self.logger.write_to_console( "EVENT", "Existing Admin Username " + request_data['username'] + " | Blocked User.") return { "code": language.CODES['FAIL'], "msg": "Phone number is already registered to another administrator.", "data": [] } else: self.logger.write_to_console( "EVENT", "Existing Admin Username " + request_data['username'] + " | Blocked User.") return { "code": language.CODES['FAIL'], "msg": "Username is already registered to another administrator.", "data": [] } def addAdminGroup(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Adding Admin Group {1}".format(self.user['username'], str(request_data))) res = self.model.addAdministratorGroup(request_data) if res == True: return { "code": language.CODES['SUCCESS'], "msg": "New group added successfully.", "data": [] } else: return { "code": language.CODES['FAIL'], "msg": "Failed to add group.", "data": [] } def updateAdminGroup(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Updating Admin Group {1}".format(self.user['username'], str(request_data))) res = self.model.updateAdministratorGroup(request_data) if res == True: return { "code": language.CODES['SUCCESS'], "msg": "Group updated successfully.", "data": [] } else: return { "code": language.CODES['FAIL'], "msg": "Failed to update group.", "data": [] } def getAdmin(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "Login request for " + request_data['username']) admin_data = self.model.getAdminByUsername(request_data['username']) if admin_data == []: self.logger.write_to_console( "EVENT", "Failed to get admin " + request_data['username'] + " | Non-Existing User.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": [] } else: self.logger.write_to_console( "EVENT", "Administor Data retreived successfully " + request_data['username'] + " | Success.") return { "code": language.CODES['SUCCESS'], "msg": self.lang['login_successful'], "data": admin_data[0] } def getAdminInstDetails(self): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "Getting Details for " + self.user['username']) admin_data = self.model.getAdminByUsername(self.user['username']) if admin_data == []: self.logger.write_to_console( "EVENT", "Failed to get admin " + self.user['username'] + " | Non-Existing User.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": [] } else: self.logger.write_to_console( "EVENT", "Administor Data retreived successfully " + self.user['username'] + " | Success.") return { "code": language.CODES['SUCCESS'], "msg": self.lang['login_successful'], "data": admin_data[0] } def updateAdmin(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Updating Admin {1}".format(self.user['username'], str(request_data))) self.logger.write_to_console("EVENT", "Preparing data") request_data['msisdn'] = "233" + request_data['msisdn'][-9:] res = self.model.updateAdministrator(request_data) if res == True: return { "code": language.CODES['SUCCESS'], "msg": self.lang['admin_updated'], "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['admin_update_failed'], "data": [] } def changeAdminPassword(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} changing Admin password {1}".format(self.user['username'], str(request_data))) if request_data['newPassword'] == request_data['oldPassword']: return { "code": language.CODES['FAIL'], "msg": "New password can not be the same as the old password.", "data": [] } utl = Utilites() comple = utl.password_complexity_check(request_data['newPassword']) print(comple) if comple['strength'] < 10: self.logger.write_to_console( "EVENT", "password_weak_password" + self.user['username'] + " | Password change.") return { "code": language.CODES['FAIL'], "msg": "The password entered is weak. Kindly make sure the password length is 8 and above and contains a a least one digit symbol uppercase and lowercase", "data": [] } if request_data['newPassword'] == request_data['newPasswordRep']: admin_data = self.model.getAdminByUsername_chg( self.user['username']) if admin_data == []: self.logger.write_to_console( "EVENT", "User does not exit " + self.user['username'] + " | Non-Existing User.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": [] } else: verify_pass = sha256_crypt.verify(request_data['oldPassword'], admin_data[0]['password']) self.logger.write_to_console( "EVENT", "varify Password | " + str(verify_pass)) if verify_pass == True: password = sha256_crypt.encrypt( request_data['newPassword']) res = self.model.updateAdministrator({ "password": password, "username": self.user['username'], "pass_date": "NOW()" }) if res == True: admin_data = self.model.getAdminByUsernameLogin( self.user['username']) try: Utilites.send_mail( Utilites, "SSNIT PASSWORD CHANGE", "<p>Hi {0}</p><p>Your SSNIT password has been changed. If you are not aware of this change kindly send a mail to <a>[email protected]</a>.<br><br>Best Regards</p><p>FUSION PLATFORM</p>" .format(admin_data[0]['first_name']), [admin_data[0]['email']]) except Exception as e: pass return { "code": language.CODES['SUCCESS'], "msg": self.lang['admin_sucessful_pass_change'], "data": admin_data[0] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['admin_update_failed'], "data": [] } else: self.logger.write_to_console( "EVENT", "wrong previous password " + self.user['username'] + " | Password change.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_old_password'], "data": [] } else: self.logger.write_to_console( "EVENT", "password_mismatch " + self.user['username'] + " | Password change.") return { "code": language.CODES['FAIL'], "msg": self.lang['password_mismatch'], "data": [] } def resetAdminPassword(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} resting Admin password {1}".format(request_data['username'], str(request_data))) admin_data = self.model.getAdminByUsername(request_data['username']) if admin_data == []: self.logger.write_to_console( "EVENT", "Login request failed for " + request_data['username'] + " | Non-Existing User.") return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_username'], "data": [] } else: utl = Utilites() raw_password = utl.generate_password(10) # raw_password = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8)) password = sha256_crypt.encrypt(raw_password) self.logger.write_to_console( "EVENT", "Generated password: {0} \n Hashed Password: {1} \n".format( raw_password, password)) res = self.model.updateAdministrator({ "password": password, "username": request_data['username'] }) if res == True: Utilites.send_mail( Utilites, "SSNIT PASSWORD RESET", "<p>Hi {0}</p><p>Your SSNIT password has been changed to <strong>{1}</strong>.<br>Keeping your password safe is your responsibility.<br><br><br><br>Regards</p><p>FUSION PLATFORM</p>" .format(request_data['username'], raw_password), [admin_data[0]['email']]) return { "code": language.CODES['SUCCESS'], "msg": (self.lang['admin_pass_reset_successful'] + admin_data[0]['email']), "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['admin_pass_reset_failed'], "data": [] } def searchAdmins(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ print(request_data) self.logger.write_to_console( "EVENT", "Searching Transactions for {0}".format( request_data['search_param'])) admin_data = [] if self.user['branch_code'] == "All": admin_data = self.model.searchAdmins(request_data) else: admin_data = self.model.searchAdminsBranch(request_data) for result in admin_data: result["created"] = result["created"].strftime("%Y-%m-%d %H:%M:%S") result["last_login"] = result["last_login"].strftime( "%Y-%m-%d %H:%M:%S") if "pass_date" in result and result['pass_date'] is not None: result["pass_date"] = result["pass_date"].strftime( "%Y-%m-%d %H:%M:%S") if result["active"] == 1: result["active"] = self.lang["active"] else: result["active"] = self.lang["inactive"] return admin_data def getAllBranches(self, request_data): """ This function gets branches in the db @Params : void """ print("inside get branches route ", str(request_data)) if request_data == {}: request_data = {'offset': 0, 'records': 11} else: request_data['offset'] = int(request_data['page']) * 11 request_data['records'] = 11 #self.logger.write_to_console("EVENT", "Getting branches list for {0} -> {1}".format(self.user['username'], request_data)) branches_data = self.model.getBranches(request_data) print(branches_data) self.logger.write_to_console( "EVENT", "Branches list gotten successfully for {}".format( self.user['username'])) return branches_data def getAllBranchesFully(self): filter_data = {} filter_data['branches'] = self.model.dbconn.select_from_table( "tbl_branches") print(filter_data) return filter_data def getAllBranchesExport(self): """ This function handles all logic related to login on the platform @Params : void """ request_data = {} request_data['offset'] = 0 request_data['records'] = 10000 # inst_model = Institution(self.user) self.logger.write_to_console( "EVENT", "Getting administrator list for {} -> {}".format( self.user['username'], request_data)) export_list = [['BRANCH ID', 'ACRONYM', 'BRANCH NAME', 'BRANCH CODE']] branches_data = self.model.getBranches() for result in branches_data: export_list.append([ result['branch_id'], result['acronym'], result['branch_name'], result['branch_code'] ]) self.logger.write_to_console( "EVENT", "Branches Export list gotten successfully for {}".format( self.user['username'])) return export_list def searchBranches(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ print(request_data) self.logger.write_to_console( "EVENT", "Searching Transactions for {0}".format( request_data['search_param'])) admin_data = [] admin_data = self.model.searchBranches(request_data) return admin_data def addBranch(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Adding Branch {1}".format(self.user['username'], str(request_data))) branch_codes = self.model.getBranchByCode(request_data['branch_code']) if branch_codes == []: res = self.model.addAdminBranch(request_data) if res == True: self.logger.write_log( "ADMIN", "ADDED BRANCH | {} | SUCESSFUL | {}".format( str(request_data), self.user['username'])) return { "code": language.CODES['SUCCESS'], "msg": "New branch added successfully.", "data": [] } else: return { "code": language.CODES['FAIL'], "msg": "Failed to add branch.", "data": [] } else: return { "code": language.CODES['FAIL'], "msg": "Branch code already exist", "data": [] } def removeBranch(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Adding Branch {1}".format(self.user['username'], str(request_data))) res = self.model.removeAdminBranch(request_data) if res == True: self.logger.write_log( "ADMIN", "REMOVED BRANCH | {} | SUCESSFUL | {}".format( str(request_data), self.user['username'])) return { "code": language.CODES['SUCCESS'], "msg": "New branch removed successfully.", "data": [] } else: return { "code": language.CODES['FAIL'], "msg": "Failed to remove branch.", "data": [] }
class activitiesServices(object): """ Class contains functions and attributes for authtentication Function: * getCampainge(sel) """ def __init__(self, user): self.lang = {} self.lang = getattr(language, config.DEFAULT_LANG) self.user = user self.model = Activities(user) self.logger = Logger() def getAllactivities(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ request_data['page'] = int(request_data['page']) - 1 if request_data == {}: request_data = { 'offset': 0, 'records': 12, 'fromdate': '', 'todate': '', 'status': '', 'branch': '', 'destination': '', 'tag': '', 'type': '' } else: request_data['offset'] = int(request_data['page']) * 12 request_data['records'] = 12 print(request_data) self.logger.write_to_console( "EVENT", "loading all transactions for {0}".format(self.user['username'])) if request_data['fromdate'] != "": request_data['start_date'] = request_data['fromdate'] + " 00:00:00" if request_data['todate'] != "": request_data['end_date'] = request_data['todate'] + " 23:59:59" # transaction_data = api_calls.request_api_json(api_calls, request) # if self.user['name'] == "Administrator": transaction_data = self.model.getAllTransactions(request_data) # else: # transaction_data = self.model.getAllTransactionsByBranch(request_data) for transaction in transaction_data[0]: transaction['amount'] = str(transaction['amount']) transaction['request_time'] = str(transaction['request_time']) transaction['response_time'] = str(transaction['response_time']) transaction_data[1][0]['count'] = int( round(transaction_data[1][0]['count'] / 12)) return transaction_data def searchActivities(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ print(request_data) self.logger.write_to_console( "EVENT", "Searching Activities for {0}".format( request_data['search_param'])) transaction_data = self.model.searchTransactions(request_data) # print(transaction_data) for transaction in transaction_data: transaction['amount'] = str(transaction['amount']) transaction['request_time'] = str(transaction['request_time']) transaction['response_time'] = str(transaction['response_time']) return transaction_data def getAllActivitiesExport(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ if request_data == {}: request_data = { 'offset': 0, 'records': 12, 'fromdate': '', 'todate': '', 'status': '', 'branch': '', 'destination': '', 'tag': '', 'type': '' } else: request_data['offset'] = 0 request_data['records'] = 100000 print(request_data) self.logger.write_to_console( "EVENT", "Exporting transactions for {0}".format(self.user['username'])) if self.user['name'] == 'Administrator': transaction_data = self.model.getAllTransactions(request_data) else: transaction_data = self.model.getAllTransactions(request_data) export_list = [[ 'TRANSACTION ID', 'REFERENCE', 'SOURCE ACCOUNT', 'BRANCH', 'DESTINATION ACCOUNT', 'DESTINATION', 'MSISDN', 'AMOUNT', 'TYPE', 'TAG', 'STATUS', 'REQUEST DATE', 'RESPONSE DATE' ]] for result in transaction_data[0]: result["request_time"] = result["request_time"].strftime( "%Y-%m-%d %H:%M:%S") result["response_time"] = result["response_time"].strftime( "%Y-%m-%d %H:%M:%S") result["amount"] = str(result["amount"]) export_list.append([ result['xref'], result['reference'], result['account_number'], result['account_branch'], result['des_act'], result['destination'], result['msisdn'], result['amount'], result['type'], result['fusion_tag'], result['msg_stat'], result['request_time'], result['response_time'] ]) print(export_list) return export_list def getActivitiesfilter(self): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "loading all transaction filter options for {0}".format( self.user['username'])) # transaction_data = api_calls.request_api_json(api_calls, request) if self.user['branch_code'] == "All": filter_data = self.model.getAllTransactionsfilter() else: filter_data = self.model.getAllTransactionsfilter() return filter_data def getUploadDetails(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "Getting details for {0}".format(request_data['bulk_id'])) detailed_data = self.model.getBulkUploadDetailsByBulkId( request_data['bulk_id']) print(detailed_data) for result in detailed_data: result["date_processed"] = result["date_processed"].strftime( "%Y-%m-%d %H:%M:%S") result["date_upload"] = result["date_upload"].strftime( "%Y-%m-%d %H:%M:%S") if result["approval_status"] == 0: result["approval_status"] = self.lang["not_submitted"] elif result["approval_status"] == 1: result["approval_status"] = self.lang["submitted"] elif result["approval_status"] == 2: result["approval_status"] = self.lang["Declined"] elif result["approval_status"] == 3: result["approval_status"] = self.lang["approved"] elif result["approval_status"] == 4: result["approval_status"] = self.lang["corrupt_file"] else: result["processing_status"] = self.lang["unknown"] if result["processing_status"] == 0: result["processing_status"] = self.lang["not_processed"] elif result["processing_status"] == 1: result["processing_status"] = self.lang["initiated"] elif result["processing_status"] == 2: result["processing_status"] = self.lang["failed"] elif result["processing_status"] == 3: result["processing_status"] = self.lang["success"] else: result["processing_status"] = self.lang["unknown"] pass self.logger.write_to_console("EVENT", "BulkPay Uploads gotten | Success.") return { "code": language.CODES['SUCCESS'], "msg": self.lang['data_retrived'], "data": detailed_data } def record_uploaded_file(self, file_obl): self.logger.write_to_console( "EVENT", "BulkPay Recording Uploaded file | {}".format(file_obl.filename)) file_extension = file_obl.filename.split(".") # filetype = file_extension[-1] if file_extension[-1] != "csv": return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_file_format'], "data": [] } bulk_id = self.generate_id(self.user['institution_shortName']) # file_obl.save(secure_filename(file_obl.filename)) file_obl.save(os.path.join(config.UPLOAD_DIRECTORY, bulk_id + ".csv")) fileChecksum = self.md5Checksum(bulk_id + ".csv") fileSize = os.stat( os.path.join(config.UPLOAD_DIRECTORY, bulk_id + ".csv")).st_size fields = {"bulk_id":bulk_id, \ "filename": file_obl.filename, \ "filesize": fileSize, \ "fileType": file_extension[-1], \ "file_checksum": fileChecksum, \ "merchant_id": self.user['institution_data']['id'], \ "merchant_admin_id": self.user['id'], \ "approval_status": '1', \ "date_upload": "NOW()", \ } self.logger.write_to_console( "EVENT", "BulkPay File Details | {}".format(fields)) result = self.model.insertBulkUpload(fields) if result == True: result = self.model.insertBulkUploadXtraDetails( {"bulk_id": bulk_id}) if result == True: return { "code": language.CODES['SUCCESS'], "msg": self.lang['file_recorded'], "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_file_format'], "data": [] } def md5Checksum(self, fileName): filePath = os.path.join(config.UPLOAD_DIRECTORY, fileName) with open(filePath, 'rb') as fh: m = hashlib.md5() while True: data = fh.read() if not data: break m.update(data) return m.hexdigest() def generate_id(self, preamb): """ Generate unique id Parameters: preamb => string to be used at the start of the id """ t_id = preamb + str(hash(str(uuid.uuid1())) % 100000000000) return t_id
class activitiesServices(object): """ Class contains functions and attributes for authtentication Function: * getCampainge(sel) """ def __init__(self, user): self.lang = {} self.lang = getattr(language, config.DEFAULT_LANG) self.user = user self.model = Activities(user) self.logger = Logger() def getAllActivities(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ if request_data == {}: request_data = {'page': 0, 'fromdate': '', 'todate': ''} else: pass print(request_data) self.logger.write_to_console( "EVENT", "loading all bulkpay uploads for {0}".format( self.user['username'])) if request_data == {}: request_data = { 'offset': 0, 'records': 11, 'fromdate': '', 'todate': '', 'status': '' } else: request_data['offset'] = int(request_data['page']) * 11 request_data['records'] = 11 customer_data = self.model.getAllActivities(request_data) print(customer_data) branch_data = self.model.getBranches() for result in customer_data[0]: result["date_created"] = result["date_created"].strftime( "%Y-%m-%d %H:%M:%S") # if result["status"] == 1: # result["status"] = self.lang["active"] # else: # result["status"] = self.lang["inactive"] pages = math.ceil(customer_data[1][0]['count'] / 12) print(pages) self.logger.write_to_console("EVENT", "Administrators gotten | Success.") return { "code": language.CODES['SUCCESS'], "msg": self.lang['data_retrived'], "data": customer_data[0], "pages": pages, "branches": branch_data } return customer_data def getAllBlacklist(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ if request_data == {}: request_data = {'page': 0, 'fromdate': '', 'todate': ''} else: pass print(request_data) self.logger.write_to_console( "EVENT", "loading all customer request uploads for {0}".format( self.user['username'])) if request_data == {}: request_data = { 'offset': 0, 'records': 11, 'fromdate': '', 'todate': '', 'branch': '', 'request_type': '' } else: request_data['offset'] = int(request_data['page']) * 11 request_data['records'] = 11 customer_data = self.model.getAllBlack(request_data) print(customer_data) for result in customer_data[0]: result["date_blacklisted"] = result["date_blacklisted"].strftime( "%Y-%m-%d %H:%M:%S") # if result["status"] == 1: # result["status"] = self.lang["active"] # else: # result["status"] = self.lang["inactive"] pages = math.ceil(customer_data[1][0]['count'] / 12) print(pages) self.logger.write_to_console("EVENT", "Administrators gotten | Success.") return { "code": language.CODES['SUCCESS'], "msg": self.lang['data_retrived'], "data": customer_data[0], "pages": pages } return customer_data def getAllvouchersExport(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ request_data['offset'] = 0 request_data['records'] = 1000000 print(request_data) self.logger.write_to_console( "EVENT", "loading all bulkpay uploads for {0}".format( self.user['username'])) export_list = [[ 'ACCOUNT', 'FIRST NAME', 'LAST NAME', 'MIDDLE NAME', 'GENDER', 'PHONE NUMBER', 'BRANCH', 'STATUS', 'DATE REGISTERED' ]] # if self.user['access_level_id'] == 4: merchant_data = self.model.getAllvouchers(request_data) # else: # merchant_data = self.model.getAllvouchersByBranch(request_data) print(merchant_data) for result in merchant_data[0]: result["join_date"] = result["join_date"].strftime( "%Y-%m-%d %H:%M:%S") if result["status"] == 1: result["status"] = self.lang["active"] else: result["status"] = self.lang["inactive"] export_list.append([ result['id'], result['first_name'], result['last_name'], result['middle_name'], result['gender'], result['status'], result['join_date'] ]) print(export_list) return export_list def addCustomer(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Adding Customer {1}".format(self.user['username'], str(request_data))) request_data['requested_by'] = self.user['username'] request_data['branch'] = request_data['customer_account'][:3] print(request_data) result = self.model.addNewRegistrationRequest(request_data) result = self.model.addCustomerRequest({ 'requested_by': self.user['username'], 'request_type': '0', 'customer_msisdn': request_data['customer_msisdn'], 'customer_account': request_data['customer_account'], 'branch': self.user['branch_id'] }) self.logger.write_log( "CUSTOMER", "Customer registration Request | {} | {} | {} | ".format( request_data['customer_msisdn'], request_data['customer_account'], self.user['username'])) # return customer_data return { 'code': '00', 'msg': 'Customer registration request sent successfully' } def getUserActivities(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "Getting customer request: {}".format(request_data)) customer_data = self.model.getCustomerActivities(request_data) # self.logger.write_to_console("EVENT", "Get customer reponse: {}".format(customer_data)) return customer_data def getCustomerDetials(self, customer_id): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "Getting customer request: {}".format(customer_id)) customer_data = self.model.getCustomer(customer_id) cust_accs_data = self.model.getCustomerAccounts(customer_id) cust_transactions_data = [] for account in cust_accs_data: cust_transactions_data = cust_transactions_data + self.model.getCustomerTransactions( account['account_number']) cust_requests_data = self.model.getCustomerRequests(customer_id) cust_branches = self.model.getBranches() return { "code": language.CODES['SUCCESS'], "msg": self.lang['data_retrived'], "data": customer_data, "accounts": cust_accs_data, "transactions": cust_transactions_data, "requests": cust_requests_data, "branches": cust_branches } def getCustomerReqDetails(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "Getting customer request: {}".format(request_data)) customer_data = self.model.getCustomerRequestsByRequestId( request_data['request_id']) request_details = self.model.getNewCustomerRegistration( customer_data[0]) # self.logger.write_to_console("EVENT", "Get customer reponse: {}".format(customer_data)) for result in request_details: result["dob"] = result["dob"].strftime("%Y-%m-%d %H:%M:%S") result["request_date"] = result["request_date"].strftime( "%Y-%m-%d %H:%M:%S") return request_details[0] def blockCustomerRequest(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Block Customer {1}".format(self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequests( request_data['customer_id']) if len(pending_requests) > 0: for reques in pending_requests: if reques['request_type'] == 7: return { 'code': '01', 'msg': 'Block request for user is already pending.' } result = self.model.addCustomerRequest({ 'requested_by': self.user['username'], 'request_type': '7', 'customer_msisdn': request_data['customer_id'], 'customer_account': request_data['customer_id'], 'branch': self.user['branch_id'] }) self.logger.write_log( "CUSTOMER", "Block Customer Request | {} | {} ".format( request_data['customer_id'], self.user['username'])) return {'code': '00', 'msg': 'Request sent.'} def enableCustomerRequest(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Activate user Customer {1}".format(self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequests( request_data['customer_id']) if len(pending_requests) > 0: for reques in pending_requests: if reques['request_type'] == 8: return { 'code': '01', 'msg': 'Unblock user request for user is already pending.' } result = self.model.addCustomerRequest({ 'requested_by': self.user['username'], 'request_type': '8', 'customer_msisdn': request_data['customer_id'], 'customer_account': request_data['customer_id'], 'branch': self.user['branch_id'] }) self.logger.write_log( "CUSTOMER", "Unblock Customer Request | {} | {} ".format( request_data['customer_id'], self.user['username'])) return {'code': '00', 'msg': 'Request sent.'} def resetPinRequest(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Customer Reset Pin {1}".format(self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequests( request_data['customer_id']) if len(pending_requests) > 0: for reques in pending_requests: if reques['request_type'] == 1: return { 'code': '01', 'msg': 'Reset pin request for customer is already pending.' } result = self.model.addCustomerRequest({ 'requested_by': self.user['username'], 'request_type': '1', 'customer_msisdn': request_data['customer_id'], 'customer_account': request_data['customer_id'], 'branch': self.user['branch_id'] }) self.logger.write_log( "CUSTOMER", "Reset Pin Request | {} | {} ".format(request_data['customer_id'], self.user['username'])) return {'code': '00', 'msg': 'Request sent.'} def deactivateCustomerAccountRequest(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Deactivate Customer Account {1}".format( self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequests( request_data['customer_id']) if len(pending_requests) > 0: for reques in pending_requests: if reques['request_type'] == 4: return { 'code': '01', 'msg': 'Account Deactivation request for user is already pending.' } result = self.model.addCustomerRequest({ 'requested_by': self.user['username'], 'request_type': '4', 'customer_msisdn': request_data['customer_id'], 'customer_account': request_data['customer_id'], 'change_to': request_data['account_req'], 'branch': self.user['branch_id'] }) self.logger.write_log( "CUSTOMER", "Deactivate Customer Account Request | {} | {} | {} ".format( request_data['customer_id'], request_data['account_req'], self.user['username'])) return {'code': '00', 'msg': 'Request sent.'} def activateCustomerAccountRequest(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Activate Customer Account {1}".format(self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequests( request_data['customer_id']) if len(pending_requests) > 0: for reques in pending_requests: if reques['request_type'] == 5: return { 'code': '01', 'msg': 'Account Deactivation request for user is already pending.' } result = self.model.addCustomerRequest({ 'requested_by': self.user['username'], 'request_type': '5', 'customer_msisdn': request_data['customer_id'], 'customer_account': request_data['customer_id'], 'change_to': request_data['account_req'], 'branch': self.user['branch_id'] }) self.logger.write_log( "CUSTOMER", "Activate Customer Account Request | {} | {} | {} ".format( request_data['customer_id'], request_data['account_req'], self.user['username'])) return {'code': '00', 'msg': 'Request sent.'} def addCustomerAccountRequest(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Add Customer Account {1}".format(self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequests( request_data['customer_id']) if len(pending_requests) > 0: for reques in pending_requests: if reques['request_type'] == 6 and reques[ 'change_to'] == request_data['new_account']: return { 'code': '01', 'msg': 'Add account request for user is already pending.' } result = self.model.addCustomerRequest({ 'requested_by': self.user['username'], 'request_type': '6', 'customer_msisdn': request_data['customer_id'], 'customer_account': request_data['customer_id'], 'change_to': request_data['new_account'], 'branch': self.user['branch_id'] }) self.logger.write_log( "CUSTOMER", "Add Customer Account Request | {} | {} | {} ".format( request_data['customer_id'], request_data['new_account'], self.user['username'])) return {'code': '00', 'msg': 'Request sent.'} def updateCustomer(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Customer Reset Pin {1}".format(self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequests(request_data['id']) if request_data['msisdn'] != request_data['id']: if len(pending_requests) > 0: for reques in pending_requests: if reques['request_type'] == 2: return { 'code': '01', 'msg': 'Change phone number request for customer is already pending.' } else: result = self.model.addCustomerRequest({ 'requested_by': self.user['username'], 'request_type': '2', 'customer_msisdn': request_data['id'], 'customer_account': request_data['id'], 'branch': self.user['branch_id'], 'change_from': request_data['id'], 'change_to': request_data['msisdn'] }) self.logger.write_log( "CUSTOMER", "Change Customer Phone Number Request | {} | {} | {} " .format(request_data['customer_id'], request_data['id'], self.user['username'])) break result = self.model.updatevouchers({ 'id': request_data['id'], 'first_name': request_data['first_name'], 'middle_name': request_data['middle_name'], 'last_name': request_data['last_name'], 'gender': request_data['gender'] }) self.logger.write_log( "CUSTOMER", "Update Customer Details | {} | {} ".format( request_data['id'], self.user['username'])) return {'code': '00', 'msg': 'Request sent.'} def searchvouchers(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ print(request_data) self.logger.write_to_console( "EVENT", "Searching vouchers for {0}".format(request_data['search_param'])) customer_data = self.model.searchvouchers(request_data) for result in customer_data: result["join_date"] = result["join_date"].strftime( "%Y-%m-%d %H:%M:%S") # if result["status"] == 1: # result["status"] = self.lang["active"] # else: # result["status"] = self.lang["inactive"] return customer_data def declineCustomerRequest(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Add Customer Account {1}".format(self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequestsByRequestId( request_data['request_id']) print(pending_requests) if len(pending_requests) > 0: if pending_requests[0]['request_type'] == 0: #Remove from tbl_customer self.model.deleteCustomerNewCustomer( pending_requests[0]['customer_account'], pending_requests[0]['customer_msisdn']) #Remove from tbl_user_requests self.model.deleteCustomerRequest(request_data['request_id']) self.logger.write_log( "CUSTOMER", "Customer Registration Declined | {} | {} | {} ".format( pending_requests[0]['customer_msisdn'], pending_requests[0]['customer_account'], self.user['username'])) return { 'code': '00', 'msg': 'Registration request declined successfully.' } else: #Remove from tbl_user_requests self.model.deleteCustomerRequest(request_data['request_id']) return {'code': '00', 'msg': 'Request declined successfully.'} else: self.model.deleteCustomerRequest(request_data['request_id']) return {'code': '01', 'msg': 'No request for found.'} def approveCustomerRequest(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ self.logger.write_to_console( "EVENT", "{0} Add Customer Account {1}".format(self.user['username'], str(request_data))) pending_requests = self.model.getCustomerRequestsByRequestId( request_data['request_id']) print(pending_requests) if len(pending_requests) > 0: if pending_requests[0]['request_type'] == 0: return self.registerNewUser(pending_requests[0]) elif pending_requests[0]['request_type'] == 1: return self.changeUserPin(pending_requests[0]) elif pending_requests[0]['request_type'] == 2: return self.changeUserPhoneNumber(pending_requests[0]) elif pending_requests[0]['request_type'] == 3: return self.changeUserAccountNumber(pending_requests[0]) elif pending_requests[0]['request_type'] == 4: return self.deactivateUserAccountNumber(pending_requests[0]) elif pending_requests[0]['request_type'] == 5: return self.activateUserAccountNumber(pending_requests[0]) elif pending_requests[0]['request_type'] == 6: return self.addUserAccountNumber(pending_requests[0]) elif pending_requests[0]['request_type'] == 7: return self.deactivateUser(pending_requests[0]) elif pending_requests[0]['request_type'] == 8: return self.activateUser(pending_requests[0]) else: self.model.deleteCustomerRequest(request_data['request_id']) return {'code': '01', 'msg': 'No request for found.'} else: self.model.deleteCustomerRequest(request_data['request_id']) return {'code': '01', 'msg': 'No request for found.'} def registerNewUser(self, request_data): # GET User data customer_data = self.model.getNewCustomerRegistration(request_data) print(customer_data) # Send to Dari API to register result = self.model.sic_register_customer(customer_data[0]) if result['code'] == '00': self.model.deleteCustomerNewCustomer( customer_data[0]['customer_account'], customer_data[0]['customer_msisdn']) self.model.deleteCustomerRequest(request_data['id']) self.logger.write_log( "CUSTOMER", "Customer Registration Approved | {} | {} | {} ".format( customer_data[0]['customer_msisdn'], customer_data[0]['customer_account'], self.user['username'])) return {'code': '00', 'msg': "Customer registration approved"} else: return {'code': '01', 'msg': result['msg']} def changeUserPin(self, request_data): # GET User data customer_data = self.model.getCustomer( request_data['customer_account']) print(customer_data) # Send to Dari API to register result = self.model.sic_reset_customer_pin(customer_data[0]) if result['code'] == '00': self.model.deleteCustomerRequest(request_data['id']) self.logger.write_log( "CUSTOMER", "Approved Change Pin | {} | {} ".format( customer_data[0]['id'], self.user['username'])) return {'code': '00', 'msg': "Customer pin reset sucessful."} else: return {'code': '01', 'msg': result['msg']} def changeUserPhoneNumber(self, request_data): # GET User data res = False customer_data = self.model.getCustomer( request_data['customer_account']) customer_accs = self.model.getCustomerAccounts( request_data['customer_account']) print(customer_data) print(customer_accs) for account in customer_accs: # Send to Dari API to register result = self.model.fusion_deactivate_customer({ 'msisdn': customer_data[0]['msisdn'], 'uniqueID': customer_data[0]['account'] }) print(result) if result['code'] == '00': reg_result = self.model.fusion_register_customer({ 'msisdn': request_data['change_to'], 'uniqueID': customer_data[0]['account'] }) print(reg_result) if reg_result['code'] == '00': res = True else: pass if res == True: self.model.updatevouchers({ 'id': customer_data['id'], 'msisdn': request_data['change_to'] }) self.model.deleteCustomerRequest(request_data['id']) self.logger.write_log( "CUSTOMER", "Approved Change Phone Number | {} | from: {} | to: {} | {} ". format(customer_data[0]['msisdn'], customer_data[0]['msisdn'], request_data['change_to'], self.user['username'])) return { 'code': '00', 'msg': "Customer phone number change sucessful." } else: self.model.deleteCustomerRequest(request_data['id']) return { 'code': '01', 'msg': "Customer phone number change failed." } def changeUserAccountNumber(self, request_data): # GET User data customer_data = self.model.getCustomer( request_data['customer_account']) print(customer_data) # Send to Dari API to register # result = self.model.sic_reset_customer_pin(customer_data[0]) # if result['code'] == '00': self.model.deleteCustomerRequest(request_data['id']) return {'code': '00', 'msg': "Customer account changed successfully."} # else: # return {'code': '01', 'msg': result['msg']} def deactivateUserAccountNumber(self, request_data): # GET User data # customer_data = self.model.getCustomer(request_data['customer_account']) # customer_accs = self.model.getCustomerAccounts(request_data['customer_account']) # print(customer_data) # print(customer_accs) # result = None # acc_id = None # # Send to Dari API to register # for account in customer_accs: # if account['account_number'] == request_data['change_to']: # acc_id = account['id'] # result = self.model.fusion_deactivate_customer({'msisdn': request_data['change_to'], 'uniqueID': customer_data[0]['account']}) # break # if result['code'] == '00': # self.model.updateCustomerAccount({'id': acc_id, 'status': 'INACTIVE'}) # self.model.deleteCustomerRequest(request_data['id']) # return {'code': '00', 'msg':"Customer deactivation successful."} # else: # return {'code': '01', 'msg': result['msg']} # GET User data customer_data = self.model.getCustomer( request_data['customer_account']) print(customer_data) # Send to Dari API to register result = self.model.sic_change_customer_account_status( request_data, "INACTIVE") if result['code'] == '00': self.model.deleteCustomerRequest(request_data['id']) self.logger.write_log( "CUSTOMER", "Approved Change Pin | {} | {} ".format( customer_data[0]['id'], self.user['username'])) return {'code': '00', 'msg': "Customer account has been blocked."} else: return {'code': '01', 'msg': result['msg']} def activateUserAccountNumber(self, request_data): # GET User data # customer_data = self.model.getCustomer(request_data['customer_account']) # customer_accs = self.model.getCustomerAccounts(request_data['customer_account']) # print(customer_data) # print(customer_accs) # result = None # acc_id = None # Send to Dari API to register # for account in customer_accs: # if account['account_number'] == request_data['change_to']: # acc_id = account['id'] # result = self.model.fusion_activate_customer({'msisdn': request_data['change_to'], 'uniqueID': customer_data[0]['account']}) # break # if result['code'] == '00': # self.model.updateCustomerAccount({'id': acc_id, 'status': 'ACTIVE'}) # self.model.deleteCustomerRequest(request_data['id']) # return {'code': '00', 'msg':"Customer account activation successful."} # else: # return {'code': '01', 'msg': result['msg']} customer_data = self.model.getCustomer( request_data['customer_account']) print(customer_data) # Send to Dari API to register result = self.model.sic_change_customer_account_status( request_data, "ACTIVE") if result['code'] == '00': self.model.deleteCustomerRequest(request_data['id']) self.logger.write_log( "CUSTOMER", "Approved Account Activation | {} | {} | {} ".format( customer_data[0]['id'], request_data['change_to'], self.user['username'])) return {'code': '00', 'msg': "Customer account has been blocked."} else: return {'code': '01', 'msg': result['msg']} def addUserAccountNumber(self, request_data): # GET User data customer_data = self.model.getCustomer( request_data['customer_account']) print(customer_data) # Send to Dari API to register result = self.model.fusion_register_customer({ 'msisdn': customer_data[0]['msisdn'], 'uniqueID': request_data[0]['change_to'] }) if result['code'] == '00': self.model.deleteCustomerRequest(request_data['id']) self.logger.write_log( "CUSTOMER", "Approved Account Activation | {} | {} | {} ".format( customer_data[0]['id'], request_data['change_to'], self.user['username'])) return {'code': '00', 'msg': "Customer account added sucessfully."} else: return {'code': '01', 'msg': result['msg']} def deactivateUser(self, request_data): # GET User data customer_data = self.model.getCustomer( request_data['customer_account']) print(customer_data) # Send to Dari API to register result = self.model.sic_change_customer_status(customer_data[0], "INACTIVE") if result['code'] == '00': self.model.deleteCustomerRequest(request_data['id']) self.logger.write_log( "CUSTOMER", "Approved Account Deactivation | {} | {} | {} ".format( customer_data[0]['id'], request_data['change_to'], self.user['username'])) return {'code': '00', 'msg': "Customer account has been blocked."} else: return {'code': '01', 'msg': result['msg']} def activateUser(self, request_data): # GET User data customer_data = self.model.getCustomer( request_data['customer_account']) print(customer_data) # Send to Dari API to register result = self.model.sic_change_customer_status(customer_data[0], "ACTIVE") if result['code'] == '00': self.model.deleteCustomerRequest(request_data['id']) return { 'code': '00', 'msg': "Customer account has been unblocked." } else: return {'code': '01', 'msg': result['msg']} def getAllUploadsRequests(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ if request_data == {}: request_data = {'page': 0, 'fromdate': '', 'todate': ''} else: pass print(request_data) self.logger.write_to_console( "EVENT", "loading all uploads for {0}".format(self.user['username'])) if request_data == {}: request_data = { 'offset': 0, 'records': 11, 'fromdate': '', 'todate': '', 'request_type': '' } else: request_data['offset'] = int(request_data['page']) * 11 request_data['records'] = 11 customer_data = self.model.getAllUploads(request_data) print(customer_data) for result in customer_data[0]: result["upload_date"] = result["upload_date"].strftime( "%Y-%m-%d %H:%M:%S") if result["processed_date"] != None: result["processed_date"] = result["processed_date"].strftime( "%Y-%m-%d %H:%M:%S") if result["approved_date"] != None: result["approved_date"] = result["approved_date"].strftime( "%Y-%m-%d %H:%M:%S") pages = math.ceil(customer_data[1][0]['count'] / 12) print(pages) self.logger.write_to_console("EVENT", "Administrators gotten | Success.") return { "code": language.CODES['SUCCESS'], "msg": self.lang['data_retrived'], "data": customer_data[0], "pages": pages } return customer_data def record_uploaded_file(self, file_obl): self.logger.write_to_console( "EVENT", "Recording Uploaded file | {}".format(file_obl.filename)) file_extension = file_obl.filename.split(".") # filetype = file_extension[-1] if file_extension[-1] != "csv": return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_file_format'], "data": [] } bulk_id = self.generate_id(self.user['branch_code']) # file_obl.save(secure_filename(file_obl.filename)) file_obl.save(os.path.join(config.UPLOAD_DIRECTORY, bulk_id + ".csv")) # fileChecksum = self.md5Checksum(bulk_id+".csv") fileSize = os.stat( os.path.join(config.UPLOAD_DIRECTORY, bulk_id + ".csv")).st_size fields = { "bulk_id": bulk_id, "filename": file_obl.filename, "filesize": fileSize, "fileType": file_extension[-1], # "file_checksum": fileChecksum, "branch": self.user['branch_code'], "uploaded_by": self.user['username'] } self.logger.write_to_console( "EVENT", "Uploaded File Details | {}".format(fields)) result = self.model.insertBulkUpload(fields) print(result) if result == True: # self.logger.write_to_console("EVENT", "Starting processing Thread for | {}".format(file_obl.filename)) # processing_thread = Thread(target=self.process_csv, args=(os.path.join(config.UPLOAD_DIRECTORY, bulk_id+".csv"), file_obl.filename, self.user['username'])) # processing_thread.start() # self.logger.write_to_console("EVENT", "Thread started for | {}".format(file_obl.filename)) self.logger.write_log( "CUSTOMER", "Uploaded Bulk Registration | {} | {} ".format( fields['bulk_id'], self.user['username'])) return { "code": language.CODES['SUCCESS'], "msg": self.lang['file_recorded'], "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_file_format'], "data": [] } def approve_uploaded_file(self, request_data): self.logger.write_to_console( "EVENT", "Recording Uploaded file | {}".format(request_data['bulk_id'])) bulk_details = self.model.getBulkUploadDetails(request_data['bulk_id']) fields = { "bulk_id": request_data['bulk_id'], # "file_checksum": fileChecksum, "approval_status": "Approved", "processing_status": "Processing", "approved_by": self.user['username'], "approved_date": "NOW()" } self.logger.write_to_console( "EVENT", "Uploaded File Details | {}".format(fields)) result = self.model.updateBulkUpload(fields) print(result) if result == True: self.logger.write_to_console( "EVENT", "Starting processing Thread for | {}".format( request_data['bulk_id'])) processing_thread = Thread( target=self.process_csv, args=(os.path.join(config.UPLOAD_DIRECTORY, request_data['bulk_id'] + ".csv"), request_data['bulk_id'], self.user['username'], bulk_details[0]['uploaded_by'], request_data['bulk_id'])) processing_thread.start() self.logger.write_to_console( "EVENT", "Thread started for | {}".format(request_data['bulk_id'])) self.logger.write_log( "CUSTOMER", "Approved Bulk Registration | {} | {} ".format( request_data['bulk_id'], self.user['username'])) return { "code": language.CODES['SUCCESS'], "msg": "File processing approved.", "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_file_format'], "data": [] } def decline_uploaded_file(self, request_data): self.logger.write_to_console( "EVENT", "Recording Uploaded file | {}".format(request_data['bulk_id'])) fields = { "bulk_id": request_data['bulk_id'], # "file_checksum": fileChecksum, "approval_status": "Declined", "processing_status": "Processing", "approved_by": self.user['username'], "approved_date": "NOW()" } self.logger.write_to_console( "EVENT", "Uploaded File Details | {}".format(request_data['bulk_id'])) result = self.model.updateBulkUpload(fields) print(result) if result == True: self.logger.write_log( "CUSTOMER", "Decline Bulk Registration | {} | {} ".format( request_data['bulk_id'], self.user['username'])) return { "code": language.CODES['SUCCESS'], "msg": "File processing declined.", "data": [] } else: return { "code": language.CODES['FAIL'], "msg": self.lang['wrong_file_format'], "data": [] } def process_csv(self, upload_id, filename, username, uploaded_by, bulk_id): try: res = [] first_name = "" last_name = "" middle_name = "" dob = "" gender = "" region = "" city = "" msisdn = "" uniqueid = "" registered_by = username print("processing csv") with open(upload_id, "rb") as f: reader = unicodecsv.DictReader(f) #file upload is being read in a group in a dictionary{} print(reader) res = [x for x in reader] # self.log.write_to_file(msg="In process_csv_reader {}".format(res),filename="event") # print(res) #reading the file in a format way for processing for trans in res: try: #Converting the data in a dictionary form trans = dict(trans) self.logger.write_to_console( "EVENT", "Processing: {}".format(trans)) print(trans) #Converting the header of the file in lowercase for processing in key-value pair for key, value in trans.items(): try: print(key) print(value) if key.lower() == "first_name": first_name = value if key.lower() == "last_name": last_name = value if key.lower() == "middle_name": middle_name = value if key.lower() == "dob": dob = value if key.lower() == "gender": gender = value if key.lower() == "region": region = value if key.lower() == "city": city = value if key.lower() == "msisdn": msisdn = value if key.lower() == "uniqueid": uniqueid = value except Exception as e: raise e print(e) error = str(e) return error #sending request to the tups_portal(etienee' portal) request_data = { "action": "register", "uniqueid": uniqueid, "msisdn": msisdn, "firstname": first_name, "lastname": last_name, "middlename": middle_name, "dob": dob, "gender": gender, "region": region, "city": city, "requestedBy": uploaded_by, "requestBranch": uniqueid[:3] } self.logger.write_to_console( "EVENT", "Sending registrations request | {}".format( request_data)) api_response = self.model.sic_bulk_register_customer( request_data) print(api_response) # api_response = {"code": "00", "msg": "Response"} self.logger.write_to_console( "EVENT", "Registration response | {}".format(api_response)) #response from tups portal(etienne's portal) successfully save to tbl_bulk_transaction if api_response["code"] == "00": self.logger.write_to_console( "EVENT", "Registration Successful | {}".format( request_data)) #api_response from tups portal(etienne's portal) failed to be processed which is save to tbl_bulk_transaction else: self.logger.write_to_console( "EVENT", "Registration Failed | {}".format(request_data)) except Exception as e: raise e print(e) error = str(e) self.log.write_to_file( msg="In process_csv_error_exception {}".format(error), filename="error") return error data = { "processing_status": "Completed", "processed_date": "NOW()", "bulk_id": bulk_id } result = self.model.updateBulkUpload(data) ##### # Send Mail ##### except Exception as e: raise e error = "Processing of file failed" self.log.write_to_file( msg="In process_csv_exeception_raised_error {}".format(error), filename="error") return error def searchvouchersRequests(self, request_data): """ This function handles all logic related to login on the platform @Params : void """ print(request_data) self.logger.write_to_console( "EVENT", "Searching vouchers for {0}".format(request_data['search_param'])) customer_data = self.model.searchvouchersReq(request_data) for result in customer_data: result["request_date"] = result["request_date"].strftime( "%Y-%m-%d %H:%M:%S") # if result["status"] == 1: # result["status"] = self.lang["active"] # else: # result["status"] = self.lang["inactive"] return customer_data def generate_id(self, preamb): """ Generate unique id Parameters: preamb => string to be used at the start of the id """ t_id = preamb + str(hash(str(uuid.uuid1())) % 100000000000) return t_id def md5Checksum(self, fileName): filePath = os.path.join(config.UPLOAD_DIRECTORY, fileName) with open(filePath, 'rb') as fh: m = hashlib.md5() while True: data = fh.read() if not data: break m.update(data) return m.hexdigest()