def postProductPurchase(ObjectList, Credential): feed_remark = FeedLogWithRemark(len(ObjectList.ProductPurchaseData), feed_type='Purchase Feed', action='Received', status=True) product_purchase_list = [] for product in ObjectList.ProductPurchaseData: try: product_purchase_list.append({ 'vin': product.CHASSIS, 'sap_customer_id': product.CUSTOMER_ID, 'customer_phone_number': utils.mobile_format(product.CUST_MOBILE), 'customer_name': product.CUSTOMER_NAME, 'city': product.CITY, 'state': product.STATE, 'pin_no': product.PIN_NO, 'product_purchase_date': product.VEH_SL_DT, 'engine': product.ENGINE, 'veh_reg_no': product.VEH_REG_NO }) except Exception as ex: ex = "ProductPurchaseService: {0} Error on Validating {1}".format(product, ex) feed_remark.fail_remarks(ex) logger.error(ex) feed_remark = save_to_db( feed_type='purchase', data_source=product_purchase_list, feed_remark=feed_remark) feed_remark.save_to_feed_log() return get_response(feed_remark)
def save_sa_registration(request, groups): data = request.POST existing_sa = False data_source = [] phone_number = utils.mobile_format(str(data['phone-number'])) if data['sa-id']: service_advisor_id = data['sa-id'] existing_sa = True else: service_advisor_id = TEMP_SA_ID_PREFIX + str(random.randint(10**5, 10**6)) data_source.append(utils.create_sa_feed_data(data, request.user.username, service_advisor_id)) logger.info('[Temporary_sa_registration]:: Initiating dealer-sa feed for ID' + service_advisor_id) if Roles.ASCS in groups: feed_type='asc_sa' else: feed_type='dealer' feed_remark = FeedLogWithRemark(len(data_source), feed_type='Dealer Feed', action='Received', status=True) sap_obj = SAPFeed() feed_response = sap_obj.import_to_db(feed_type=feed_type, data_source=data_source, feed_remark=feed_remark) if feed_response.failed_feeds > 0: failure_msg = list(feed_response.remarks.elements())[0] logger.info('[Temporary_sa_registration]:: dealer-sa feed fialed ' + failure_msg) return json.dumps({"message": failure_msg}) logger.info('[Temporary_sa_registration]:: dealer-sa feed completed') if existing_sa: return json.dumps({'message': SA_UPDATE_SUCCESS}) return json.dumps({'message': SA_REGISTER_SUCCESS})
def postDistributor(ObjectList, Credential): distributor_list = [] feed_remark = FeedLogWithRemark( len(ObjectList.DistributorData), feed_type="Distributor Feed", action="Received", status=True ) for distributor in ObjectList.DistributorData: try: distributor_list.append( { "id": distributor.DISTRIBUTOR_ID.upper(), "name": distributor.NAME.upper(), "email": distributor.EMAIL, "mobile": utils.mobile_format(distributor.PHONE_NUMBER), "city": distributor.CITY.upper(), "asm_id": distributor.ASM_ID, } ) except Exception as ex: ex = "DistributorService: {0} Error on Validating {1}".format(distributor, ex) feed_remark.fail_remarks(ex) logger.error(ex) feed_remark = save_to_db(feed_type="distributor", data_source=distributor_list, feed_remark=feed_remark) feed_remark.save_to_feed_log() return get_response(feed_remark)
def postDealer(ObjectList, Credential): dealer_list = [] feed_remark = FeedLogWithRemark(len(ObjectList.DealerData), feed_type='Dealer Feed', action='Received', status=True) for dealer in ObjectList.DealerData: try: dealer_list.append({ 'id': dealer.KUNNR, 'address': dealer.ADDRESS, 'service_advisor_id': dealer.SER_ADV_ID, 'name': dealer.SER_ADV_NAME, 'phone_number': utils.mobile_format(dealer.SER_ADV_MOBILE), 'status': dealer.ACTIVE_FLAG, 'cdms_flag':dealer.CDMS_FLAG }) except Exception as ex: ex = "DealerService: {0} Error on Validating {1}".format(dealer, ex) feed_remark.fail_remarks(ex) logger.error(ex) feed_remark = save_to_db(feed_type='dealer', data_source=dealer_list, feed_remark=feed_remark) feed_remark.save_to_feed_log() return get_response(feed_remark)
def postNSM(ObjectList, Credential): nsm_list = [] feed_remark = FeedLogWithRemark(len(ObjectList.NSMData), feed_type="NSM Feed", action="Received", status=True) for nsm in ObjectList.NSMData: try: nsm_list.append( { "name": nsm.NAME, "email": nsm.EMAIL, "phone_number": utils.mobile_format(nsm.PHONE_NUMBER), "territory": nsm.TERRITORY, } ) except Exception as ex: ex = "NSMService: {0} Error on Validating {1}".format(nsm, ex) feed_remark.fail_remarks(ex) logger.error(ex) feed_remark = save_to_db(feed_type="nsm", data_source=nsm_list, feed_remark=feed_remark) feed_remark.save_to_feed_log() return get_response(feed_remark)
def postASC(ObjectList, Credential): asc_list = [] feed_remark = FeedLogWithRemark(len(ObjectList.ASCData), feed_type='ASC Feed', action='Received', status=True) for asc_element in ObjectList.ASCData: try: asc_list.append({ 'asc_id': asc_element.ASC_ID, 'name': asc_element.ASC_NAME, 'phone_number': utils.mobile_format(asc_element.ASC_MOBILE), 'address': asc_element.ASC_ADDRESS, 'email': asc_element.ASC_EMAIL, 'dealer_id': asc_element.KUNNAR }) except Exception as ex: ex = "ASCService: {0} Error on Validating {1}".format(asc_element, ex) feed_remark.fail_remarks(ex) logger.error(ex) feed_remark = save_to_db(feed_type='ASC', data_source=asc_list, feed_remark=feed_remark) feed_remark.save_to_feed_log() return get_response(feed_remark)
def save_model(self, request, obj, form, change): obj.phone_number = utils.mobile_format(obj.phone_number) super(ASMAdmin, self).save_model(request, obj, form, change)
def upload_mech_data(self): """Upload data of the mechanic""" print "Started uploading mech data..." file_list = ["MECHANIC_DATA.csv"] mech_list = [] retailer = get_model("Retailer", APP) dist = get_model("Distributor", APP) user_profile = get_model("UserProfile", APP) mech = get_model("Member", APP) State = get_model("State", APP) for i in range(0, 1): with open(settings.PROJECT_DIR + "/upload_data/" + file_list[i], "r") as csvfile: spamreader = csv.reader(csvfile, delimiter=",") next(spamreader) for row_list in spamreader: temp = {} temp["form_no"] = self.empty_to_none(row_list[0].strip()) temp["first_name"] = row_list[1].strip() temp["last_name"] = row_list[3].strip() dob = row_list[4].strip() if dob: temp["dob"] = datetime.datetime.strptime(dob, "%d/%m/%Y") else: temp["dob"] = None temp["shop_name"] = row_list[5].strip() temp["shop_no"] = row_list[6].strip() temp["shop_address"] = row_list[7].strip() temp["locality"] = row_list[8].strip() temp["tehsil"] = row_list[9].strip() temp["district"] = (row_list[11].strip()).upper() temp["state"] = row_list[12].strip() temp["pincode"] = row_list[13].strip() temp["dist_id"] = row_list[14].strip() temp["wall_len"] = self.empty_to_none(row_list[16].strip()) temp["wall_width"] = self.empty_to_none(row_list[17].strip()) temp["mobile"] = row_list[18].strip() temp["two_stroke"] = self.empty_to_none(row_list[19].strip()) temp["four_stroke"] = self.empty_to_none(row_list[20].strip()) temp["cng_lpg"] = self.empty_to_none(row_list[21].strip()) temp["diesel"] = self.empty_to_none(row_list[22].strip()) temp["spare_month"] = self.empty_to_none(row_list[23].strip()) temp["genuine"] = self.empty_to_none(row_list[24].strip()) temp["ret_name"] = row_list[26].strip() temp["ret_town"] = row_list[27].strip() reg = row_list[29].strip() if reg: temp["reg_date"] = datetime.datetime.strptime(reg, "%d/%m/%Y") else: temp["reg_date"] = None temp["complete"] = row_list[31].strip() temp["mech_id"] = row_list[32].strip() mech_list.append(temp) for mechanic in mech_list: mobile = mobile_format(mechanic["mobile"]) mech_object = mech.objects.filter(phone_number=mobile).using(APP) if not mech_object: if not mechanic["mech_id"]: mech_id = generate_temp_id("TME") else: mech_id = mechanic["mech_id"] if mechanic["dist_id"]: dist_object = dist.objects.using(APP).get(distributor_id=mechanic["dist_id"]) else: dist_object = None ret_obj = retailer.objects.filter(retailer_name=mechanic["ret_name"]).using(APP) if not ret_obj: ret_obj = retailer(retailer_name=mechanic["ret_name"], retailer_town=mechanic["ret_town"]) ret_obj.save(using=APP) else: ret_obj = ret_obj[0] state = State.objects.using(APP).get(state_name=mechanic["state"]) mech_object = mech( registered_by_distributor=dist_object, preferred_retailer=ret_obj, mechanic_id=mech_id, first_name=mechanic["first_name"], last_name=mechanic["last_name"], date_of_birth=mechanic["dob"], phone_number=mobile, form_number=mechanic["form_no"], registered_date=mechanic["reg_date"], shop_number=mechanic["shop_no"], shop_name=mechanic["shop_name"], shop_address=mechanic["shop_address"], locality=mechanic["locality"], tehsil=mechanic["tehsil"], district=mechanic["district"], state=state, pincode=mechanic["pincode"], shop_wall_length=mechanic["wall_len"], shop_wall_width=mechanic["wall_width"], serviced_2S=mechanic["two_stroke"], serviced_4S=mechanic["four_stroke"], serviced_CNG_LPG=mechanic["cng_lpg"], serviced_diesel=mechanic["diesel"], spare_per_month=mechanic["spare_month"], genuine_parts_used=mechanic["genuine"], form_status=mechanic["complete"], ) mech_object.save(using=APP)
def redeem_point(self, sms_dict, phone_number): '''redeem points with given upc for Member''' product_codes = sms_dict['product_id'].upper().split() try: retailer = get_model('Retailer').objects.using(settings.BRAND).filter(mobile=utils.mobile_format(phone_number)) if retailer: message = self.redeem_point_retailer(product_codes, phone_number, sms_dict,retailer) return {'status': True, 'message': message} mechanic = get_model('Member').objects.using(settings.BRAND).filter(phone_number=utils.mobile_format(phone_number)) if not mechanic: message=get_template('UNREGISTERED_USER') raise ValueError('Unregistered user') elif mechanic and mechanic[0].form_status=='Incomplete': message=get_template('INCOMPLETE_FORM') raise ValueError('Incomplete user details') elif mechanic and (mechanic[0].mechanic_id!=sms_dict['member_id'] and mechanic[0].permanent_id!=sms_dict['member_id']): message=get_template('INVALID_MEMBER_ID').format(mechanic_name=mechanic[0].first_name) raise ValueError('Invalid user-ID') products=get_model('ProductCatalog').objects.using(settings.BRAND).filter(product_id__in=product_codes) redeem_points=0 if len(products)==len(product_codes): for product in products: redeem_points=redeem_points+product.points left_points=mechanic[0].total_points-redeem_points if left_points>=0: total_points=self.update_points(mechanic[0], redeem=redeem_points) transaction_ids = self.register_redemption_request(mechanic, products) message=get_template('SEND_REDEEM_POINT').format( mechanic_name=mechanic[0].first_name, transaction_id=transaction_ids, total_points=total_points) else: if len(products)==1: message=get_template('SEND_INSUFFICIENT_POINT_SINGLE').format( mechanic_name=mechanic[0].first_name, total_points=mechanic[0].total_points, shortage_points=abs(left_points)) else: message=get_template('SEND_INSUFFICIENT_POINT_MULTIPLE').format( mechanic_name=mechanic[0].first_name, shortage_points=abs(left_points)) else: message=get_template('INVALID_PRODUCT_ID') except Exception as ex: LOG.error('[redeem_point]:{0}:: {1}'.format(phone_number, ex)) finally: phone_number = utils.get_phone_number_format(phone_number) sms_log(settings.BRAND, receiver=phone_number, action=AUDIT_ACTION, message=message) self.queue_service(send_point, {'phone_number': phone_number, 'message': message, "sms_client": settings.SMS_CLIENT}) return {'status': True, 'message': message}
def accumulate_point(self, sms_dict, phone_number): '''accumulate points with given upc''' unique_product_codes = set((sms_dict['upc'].upper()).split()) valid_upc=[] valid_product_number=[] invalid_upcs_message='' try: if len(unique_product_codes)>constants.MAX_UPC_ALLOWED: message=get_template('MAX_ALLOWED_UPC').format( max_limit=constants.MAX_UPC_ALLOWED) raise ValueError('Maximum allowed upc exceeded') retailer = get_model('Retailer').objects.using(settings.BRAND).filter(mobile=utils.mobile_format(phone_number)) if retailer: message = self.accumulate_point_retailer(retailer, phone_number, unique_product_codes) return {'status': True, 'message': message} mechanic = get_model('Member').objects.using(settings.BRAND).filter(phone_number=utils.mobile_format(phone_number)) if not mechanic: message=get_template('UNREGISTERED_USER') raise ValueError('Unregistered user') elif mechanic and mechanic[0].form_status=='Incomplete': message=get_template('INCOMPLETE_FORM') raise ValueError('Incomplete user details') state_code= mechanic[0].state.state_code spares = get_model('SparePartUPC').objects.get_spare_parts(unique_product_codes) if not spares: message=get_template('SEND_UPC_IS_USED') raise ValueError('Requested UPC is already used.') added_points=0 spare_upc_part_map={} total_points=mechanic[0].total_points if spares: for spare in spares: valid_product_number.append(spare.part_number) if not spare_upc_part_map.has_key(spare.part_number): spare_upc_part_map[spare.part_number]=[] spare_upc_part_map[spare.part_number].append(spare.unique_part_code.upper()) spare_points = get_model('SparePartPoint').objects.get_part_number(valid_product_number, state_code) if spare_points: accumulation_log=get_model('AccumulationRequest')(member=mechanic[0], points=0,total_points=0) accumulation_log.save(using=settings.BRAND) for spare_point in spare_points: if spare_point.valid_from and spare_point.valid_till: if self.check_date_validity(spare_point.valid_from,spare_point.valid_till): added_points=added_points+(len(spare_upc_part_map[spare_point.part_number]) * spare_point.points) valid_upc.extend(spare_upc_part_map[spare_point.part_number]) else: added_points=added_points+(len(spare_upc_part_map[spare_point.part_number]) * spare_point.points) valid_upc.extend(spare_upc_part_map[spare_point.part_number]) total_points=self.update_points(mechanic[0], accumulate=added_points) valid_spares = get_model('SparePartUPC').objects.get_spare_parts(valid_upc) for spare in valid_spares: accumulation_log.upcs.add(spare) accumulation_log.points=added_points accumulation_log.total_points=total_points accumulation_log.save(using=settings.BRAND) valid_spares.using(settings.BRAND).update(is_used=True) invalid_upcs = list(set(unique_product_codes).difference(valid_upc)) if invalid_upcs: invalid_upcs_message=' Invalid Entry... {0} does not exist in our records.'.format( (', '.join(invalid_upcs))) used_upcs = get_model('SparePartUPC').objects.get_spare_parts(invalid_upcs, is_used=True) if used_upcs: accumulation_requests = get_model('AccumulationRequest').objects.using(settings.BRAND).filter(upcs__in=used_upcs).prefetch_related('upcs').select_related('upcs') accumulation_dict = {} try: for accumulation_request in accumulation_requests: for upcs in accumulation_request.upcs.values(): accumulation_dict[upcs['unique_part_code']] = accumulation_request for used_upc in used_upcs: discrepant_accumulation_log = get_model('DiscrepantAccumulation')(new_member=mechanic[0], upc = used_upc, accumulation_request=accumulation_dict[used_upc]) discrepant_accumulation_log.save(using=settings.BRAND) except Exception as ex: LOG.error('[accumulate_point]:{0}:: {1}'.format(phone_number, ex)) if len(unique_product_codes)==1 and invalid_upcs: message=get_template('SEND_INVALID_UPC') else: message=get_template('SEND_ACCUMULATED_POINT').format( mechanic_name=mechanic[0].first_name, added_points=added_points, total_points=total_points, invalid_upcs=invalid_upcs_message) except Exception as ex: LOG.error('[accumulate_point]:{0}:: {1}'.format(phone_number, ex)) finally: phone_number = utils.get_phone_number_format(phone_number) sms_log(settings.BRAND, receiver=phone_number, action=AUDIT_ACTION, message=message) self.queue_service(send_point, {'phone_number': phone_number, 'message': message, "sms_client": settings.SMS_CLIENT}) return {'status': True, 'message': message}
def check_point_balance(self, sms_dict, phone_number): '''send balance point of the user''' try: mechanic = get_model('Member').objects.using(settings.BRAND).filter(phone_number=utils.mobile_format(phone_number)) if not mechanic: message=get_template('UNREGISTERED_USER') raise ValueError('Unregistered user') elif mechanic and mechanic[0].form_status=='Incomplete': message=get_template('INCOMPLETE_FORM') raise ValueError('Incomplete user details') total_points=mechanic[0].total_points today = datetime.now().strftime('%d/%m/%Y') message=get_template('SEND_BALANCE_POINT').format( mechanic_name=mechanic[0].first_name, total_points=total_points, today=today) except Exception as ex: LOG.error('[check_point_balance]:{0}:: {1}'.format( phone_number, ex)) finally: phone_number = utils.get_phone_number_format(phone_number) sms_log(settings.BRAND, receiver=phone_number, action=AUDIT_ACTION, message=message) self.queue_service(send_point, {'phone_number': phone_number, 'message': message, "sms_client": settings.SMS_CLIENT}) return {'status': True, 'message': message}