def create_user(request): try: if request.method == 'POST': data = request.POST user = data['mobile'] emailid = data['emailid'] passwd = data['passwd'] fname = data['fname'] lname = data['lname'] user_obj = User.objects.create_user(username=user, email=emailid, password=passwd) user_obj.first_name = fname user_obj.last_name = lname user_obj.is_active = 0 user_obj.save() status, otptranid = util.generateOTP(user) if status == 1: result = { "status": "success", "msg": "successfully created an user account", "otptranid": otptranid } else: result = { "status": "success", "msg": "successfully created an user account but error in triggering otp", "otptranid": otptranid } else: result = {"status": "failure", "msg": "Invalid request method"} except KeyError: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "Mandatory data missing"} except IntegrityError: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "User account already exists."} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "something went wrong"} return HttpResponse(json.dumps(result, default=json_default), content_type="application/json")
def getJobCardsList(dealerid, for_invoice=False): try: result = [] jc_objs = JCStatus.objects.filter(DealerID__iexact=dealerid) if jc_objs: for obj in jc_objs: try: if for_invoice or ((obj.CreatedTime[:10] < str( datetime.datetime.now())[:10] and obj.Status != "CLOSED") or obj.CreatedTime[:10] == str( datetime.datetime.now())[:10]): veh_obj = JCVehicleInfo.objects.get( JobCardID=obj.JobCardID, DealerID=dealerid) if veh_obj: temp_dict = {} temp_dict['jc_id'] = obj.JobCardID temp_dict['veh_no'] = veh_obj.VehicleNumber temp_dict[ 'model'] = veh_obj.Brand + " " + veh_obj.Model temp_dict['status'] = obj.Status temp_dict['service_type'] = "%s - %s" % ( global_constants.service_types[ obj.ServiceTypeId]['service_type'], global_constants.service_types[ obj.ServiceTypeId]['classification']) temp_dict['invoice'] = False temp_dict['mechanic_name'] = obj.MechanicName temp_dict['vehicle_images'] = obj.VehicleImages try: invoice_obj = JCInvoiceAndLabourCost.objects.get( JobCardID__iexact=obj.JobCardID) except JCInvoiceAndLabourCost.DoesNotExist: invoice_obj = None if invoice_obj and invoice_obj.InvoiceNumber != "": temp_dict['invoice'] = True temp_dict['mode'] = invoice_obj.PaymentMode result.append(temp_dict) except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) continue return result except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) return []
class LoadMaintenanceDueFile(View): def get(self, request, url): result = config.INVALID_REQUEST_METHOD_RESPONSE return HttpResponse(json.dumps(result, default=utils.json_default), content_type="application/json") def post(self, request, url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: apartmentid = request.POST.get('apartmentid') file_name = request.POST.get('file_name') SheetNo = request.POST.get('SheetNo') dueDataLoader = DueDataLoader() result = dueDataLoader.read_due_data(apartmentid, file_name, SheetNo) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE except KeyError: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = config.MANDATORY_DATA_MISSING_RESPONSE
class VerifyOTP(View): def get(self, request, url): result = config.INVALID_REQUEST_METHOD_RESPONSE return HttpResponse(json.dumps(result, default=utils.json_default), content_type="application/json") def post(self, request, url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: mobile_number = request.POST.get('mobile_number') apartment_id = request.POST.get('apartment_id') otp = request.POST.get('otp') apartmentUserObj = ApartUserUtil() result = apartmentUserObj.verifyOTP(apartment_id, mobile_number, otp) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE except KeyError: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = config.MANDATORY_DATA_MISSING_RESPONSE
def post(self, request, url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') block_name = request.POST.get('block_name') flat_number = request.POST.get('flat_number') mobile_number = request.POST.get('mobile_number') email_id = request.POST.get('email_id') type_occupancy = request.POST.get('type_occupancy') apartment_id = request.POST.get('apartment_id') apartmentUserObj = ApartUserUtil() result = apartmentUserObj.updatePreRegUser(first_name, last_name, block_name, flat_number, mobile_number, email_id, type_occupancy, apartment_id) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE
def post(self, request, url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: block_name = request.POST.get('block_name') flat_number = request.POST.get('flat_number') apartment_id = request.POST.get('apartment_id') type_occupancy = request.POST.get('type_occupancy') apartmentUserObj = ApartUserUtil() result['unmatch'] = apartmentUserObj.getunmatchreg( block_name, flat_number, apartment_id, type_occupancy) result['prereg'] = apartmentUserObj.getpreregistrations( block_name, flat_number, apartment_id, type_occupancy) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE
def updateStocks(request): try: if request.method == 'POST': if request.user.is_authenticated(): data = request.POST details = {} details['brand'] = data['brand'] details['model'] = data['model'] details['identifier'] = data['identifier'] details['description'] = data['description'] details['ndp'] = data['ndp'] details['mrp'] = data['mrp'] details['min_qty'] = data['min_qty'] details['avail_qty'] = data['avail_qty'] details['critical'] = data.get('critical', '0') details['alternate'] = data.get('alternate', '0') result = util.updateInventoryItem(details, request.user) else: result = {"status": "unauthorized", "msg": "Not authorized."} else: result = {"status": "failure", "msg": "Invalid request method"} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "something went wrong"} return HttpResponse(json.dumps(result, default=json_default), content_type="application/json")
def post(self, request, url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: AppartmentName = request.POST.get('AppartmentName') AppartmentEmail = request.POST.get('AppartmentEmail') AppartmentAddress = request.POST.get('AppartmentAddress') NoOfBlocks = request.POST.get('NoOfBlocks') NumberOfFlats = request.POST.get('NumberOfFlats') EmailAddress = request.POST.get('EmailAddress') MobileNumber = request.POST.get('MobileNumber') LandLine = request.POST.get('LandLine') Password = request.POST.get('Password') apartmentUserObj = ApartUserUtil() result = apartmentUserObj.createAccount( AppartmentName, AppartmentEmail, AppartmentAddress, NoOfBlocks, NumberOfFlats, EmailAddress, MobileNumber, LandLine, Password) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE
def updateInventoryItem(detail, dealerid): try: try: obj = Inventory.objects.get( DealerID__iexact=dealerid, PartIdentifier__iexact=detail['identifier']) obj.Brand = detail['brand'] obj.Model = detail['model'] obj.Description = detail['description'] obj.MinQty = detail['min_qty'] obj.AvailableQty = detail['avail_qty'] obj.NDP = detail['ndp'] obj.MRP = detail['mrp'] obj.IsCritical = detail['critical'] obj.AlternatePart = detail['alternate'] obj.save() result = {"status": "success", "msg": "updated successfully"} except ObjectDoesNotExist: result = { "status": "failure", "msg": "The item is not in inventory." } except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "Something went wrong."} return result
def get_inventory(request): try: view_logger = log_rotator.view_logger() view_logger.debug("INVENTORY details: %s :"%(request)) view_logger.debug("INVENTORY user: %s :"%(request.user)) if request.method == 'GET': view_logger.debug("DEALER VIEW : Get inventory request for %s through GET method"%request.user) if not request.user.is_authenticated(): view_logger.debug("DEALER VIEW : Redirected %s to login from get inventory"%request.user) return redirect('/dealer/login/') t = get_template('inventory.html') html = t.render({'user': request.user}) view_logger.debug("DEALER VIEW : Rendered Get Inventory page for : %s"%request.user) return HttpResponse(html) elif request.method == 'POST': view_logger.debug("DEALER VIEW : Get Inventory request for %s through POST method"%request.user) if not request.user.is_authenticated(): view_logger.debug("DEALER VIEW : Invalid session for %s"%request.user) result = {"status": "failure", "msg" : "Invalid session"} else: result = util.fetchInventoryData(request.user) view_logger.debug("DEALER VIEW : Get Inventory response for %s is %s"%(request.user, str(result))) return HttpResponse(json.dumps(result, default=json_default), content_type="application/json") else: result = {"status": "failure", "msg": "Invalid request method"} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "something went wrong"} return HttpResponse(json.dumps(result, default=json_default), content_type="application/json")
def generate_invoice(request): try: view_logger = log_rotator.view_logger() if request.method == 'POST': #data = request.body dealerid = request.user details = {} view_logger.debug("JOBCARD VIEW : Generate Invoice request - %s"%str(request)) try: data = json.loads(request.body.decode('utf-8'))['data'] #data = json.loads(data) #data = data['data'] except: data={} print("request.POST.keys() - %s" % request.POST.keys()) data['jc_id']=list(request.POST.keys())[0] data['pmt_mode']=list(request.POST.values())[0] view_logger.debug("JOBCARD VIEW : Generate Invoice request - %s"%str(data)) view_logger.debug("JOBCARD VIEW : Generate Invoice request - %s"%str(data)) jc_id = data['jc_id'] pmt_mode = data['pmt_mode'] result = util.generateInvoice(jc_id, pmt_mode, dealerid) else: result = {"status": "failure", "msg": "Invalid request method"} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "something went wrong"} view_logger.debug("JOBCARD VIEW : Generate Invoice response - %s"%str(result)) return HttpResponse(json.dumps(result, default=json_default), content_type="application/json")
def post(self,request,url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: AppartmentName = request.POST.get('AppartmentName') AppartmentEmail = request.POST.get('AppartmentEmail') AppartmentAddress = request.POST.get('AppartmentAddress') NoOfBlocks = request.POST.get('NoOfBlocks') NumberOfFlats = request.POST.get('NumberOfFlats') EmailAddress = request.POST.get('EmailAddress') MobileNumber = request.POST.get('MobileNumber') LandLine = request.POST.get('LandLine') Password = request.POST.get('Password') apartmentUserObj = ApartUserUtil() result = apartmentUserObj.createAccount(AppartmentName,AppartmentEmail,AppartmentAddress,NoOfBlocks, NumberOfFlats,EmailAddress,MobileNumber,LandLine,Password) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE
def post(self,request,url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') block_name = request.POST.get('block_name') flat_number = request.POST.get('flat_number') mobile_number = request.POST.get('mobile_number') email_id = request.POST.get('email_id') type_occupancy = request.POST.get('type_occupancy') apartment_id = request.POST.get('apartment_id') apartmentUserObj = ApartUserUtil() result = apartmentUserObj.updatePreRegUser(first_name, last_name, block_name, flat_number, mobile_number, email_id, type_occupancy, apartment_id) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE
def home(request): try: view_logger = log_rotator.view_logger() if request.method == 'GET': if not request.user.is_authenticated(): view_logger.debug("Home page request. Not logged in. Redirecting to home page.") return redirect('/dealer/login/') t = get_template('dashboard.html') user_agent = "all" user_agent=request.META.get("HTTP_USER_AGENT") view_logger.debug("USER AGENT : %s"%user_agent) if "Android" in user_agent: user_agent = "android" view_logger.debug("Home page request for : %s"%request.user) context_dictionary = util.getDashboardData(request.user) context_dictionary['user'] = request.user context_dictionary['user_agent'] = user_agent html = t.render(context_dictionary) view_logger.debug("Rendered home page for : %s"%request.user) return HttpResponse(html) else: result = {'status': 'error', 'msg': 'Invalid Request method.'} return HttpResponse(json.dumps(result, default=json_default), content_type="application/json") except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {'status': 'error', 'msg': 'Something went wrong.'} return HttpResponse(json.dumps(result, default=json_default), content_type="application/json")
def jobcard_new(request): try: view_logger = log_rotator.view_logger() if request.method == 'GET': view_logger.debug("DEALER VIEW : Create job card request for %s through GET method"%request.user) if not request.user.is_authenticated(): view_logger.debug("DEALER VIEW : Redirected %s to login from Create job card"%request.user) return redirect('/dealer/login/') t = get_template('createjobcard.html') user_agent = "all" user_agent=request.META.get("HTTP_USER_AGENT") view_logger.debug("USER AGENT : %s"%user_agent) if "Android" in user_agent: user_agent = "android" context_dictionary = util.getCarBrands() #print("context_dictionary - %s" % context_dictionary) context_dictionary['user'] = request.user context_dictionary['user_agent'] = user_agent context_dictionary['serviceTypes'] = global_constants.service_types_dropdown html = t.render(context_dictionary) view_logger.debug("DEALER VIEW : Rendered Create job card page for : %s"%request.user) return HttpResponse(html) else: result = {"status": "failure", "msg": "Invalid request method"} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "something went wrong"} return HttpResponse(json.dumps(result, default=json_default), content_type="application/json")
def fetchScheduledServices(brand, model, fuel_type, km_ticked): try: serid_obj = ScheduledServices.objects.get(Brand__iexact=brand, Model__iexact=model, FuelType__iexact=fuel_type, MaxKM__gte=km_ticked, MinKM__lte=km_ticked) if serid_obj: service_id = serid_obj.ServiceIdentifier else: raise ObjectDoesNotExist print(serid_obj) sch_obj = ScheduledServiceDetails.objects.filter( ServiceIdentifier=service_id) services = [] parts = [] for obj in sch_obj: temp_dict = {} parts_list = obj.Parts.split(',') temp_dict[obj.ServiceInfo] = parts_list if parts_list != [""]: parts.extend(parts_list) services.append(temp_dict) result = {"status": "success", "services": services, "parts": parts} except ObjectDoesNotExist: result = { "status": "failure", "msg": "No scheduled mainenance availble for this model." } except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "Something went wrong."} return result
def fetchServiceHistory(veh_num, c_num): try: history = [] if veh_num: objs = JCVehicleInfo.objects.filter(VehicleNumber__iexact=veh_num) elif c_num: objs = JCVehicleInfo.objects.filter(ChassisNumber__iexact=c_num) job_card_km_map = [] for obj in objs: temp_dict = {} temp_dict['km'] = obj.KilometersTicked temp_dict['jc_id'] = obj.JobCardID temp_dict['date'] = obj.CreatedTime[:10] job_card_km_map.append(temp_dict) for temp_dict in job_card_km_map: objs = JCServiceDetails.objects.filter( JobCardID__iexact=temp_dict['jc_id']) services = [] for obj in objs: temp_dict2 = {} temp_dict2['service_item'] = obj.ServiceItem temp_dict2['is_availed'] = obj.IsAvailed services.append(temp_dict2) temp_dict['services'] = services history.append(temp_dict) result = {"status": "success", "history": history} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "Something went wrong."} return result
def getDashboardData(dealerid): try: result = {} result['open_jc'] = JCStatus.objects.filter( DealerID__iexact=dealerid, Status__iexact="OPEN").count() open_old = JCStatus.objects.filter(DealerID__iexact=dealerid, Status__iexact="OPEN", CreatedTime__lte=str( datetime.date.today())).count() pending_old = JCStatus.objects.filter( DealerID__iexact=dealerid, Status__iexact="PENDING", CreatedTime__lte=str(datetime.date.today())).count() result['pending_jc'] = open_old + pending_old result['to_deliever_today'] = JCStatus.objects.filter( DealerID__iexact=dealerid, DeliveryTime__iexact=str(datetime.date.today())).count() objects = Inventory.objects.filter(DealerID__iexact=dealerid) result['min_order'] = 0 for obj in objects: if float(obj.AvailableQty) <= float(obj.MinQty): result['min_order'] = result['min_order'] + 1 except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "Something went wrong."} return result
def generateOTP(user): try: tranID = "OTP" + datetime.datetime.now().strftime( "%Y%m%d%H%M%S") + '_' + str(random.randint(111, 999)) otpValue = str(random.randint(111111, 999999)) time = str(datetime.datetime.now()) status = 0 # trigger SMS OTPTransactionInfo.objects.create(User=user, TranID=tranID, OTPValue=otpValue, DateTime=time, VerificationStatus=status) # deactivate user until verification user_obj = User.objects.get(username=user) user_obj.is_active = 0 user_obj.save() print("otpValue - %s" % otpValue) send_text_message(user, "EASE SERVICE OTP - %s" % otpValue) return 1, tranID except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) return 0, ""
def getEstimate(parts, dealerid): try: if isinstance(eval(parts), list): estimate = [] print(parts, dealerid) for part in eval(parts): try: inv_obj = Inventory.objects.get( PartIdentifier=part['identifier'], DealerID__iexact=dealerid) estimate_dict = {} estimate_dict['description'] = inv_obj.Description estimate_dict['unit_price'] = inv_obj.MRP estimate_dict['total_price'] = float(inv_obj.MRP) * float( part['qty']) estimate.append(estimate_dict) except ObjectDoesNotExist: pass result = {"status": "success", "estimate": estimate} else: raise except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "Something went wrong."} return result
class UpdateApartmentAccount(View): def get(self, request, url): result = config.INVALID_REQUEST_METHOD_RESPONSE return HttpResponse(json.dumps(result, default=utils.json_default), content_type="application/json") def post(self, request, url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: AppartmentEmail = request.POST.get('AppartmentEmail') AccountHolderName = request.POST.get('AccountHolderName') AccountNumber = request.POST.get('AccountNumber') IFSCCode = request.POST.get('IFSCCode') apartmentAccountObj = ApartmentAccountClass() result = apartmentAccountObj.UpdateBankDetails( AppartmentEmail, AccountHolderName, AccountNumber, IFSCCode) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE except KeyError: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = config.MANDATORY_DATA_MISSING_RESPONSE
def process_request(self, request): try: request_time = datetime.datetime.now() request.__setattr__('request_time', request_time) except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) pass
def data_for_jobs_auto_suggestion(request): try: view_logger = log_rotator.view_logger() if request.method == 'POST': result = util.getCompliantCodes() else: result = {"status": "failure", "msg": "Invalid request method"} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "something went wrong"} return HttpResponse(json.dumps(result, default=json_default), content_type="application/json")
def process_response(self, request, response): try: request_time = request.request_time if hasattr( request, 'request_time') else datetime.datetime.now() record_dict = self.get_log_record_response_str( response, request, request_time) record_str = '%(request_time)s | %(status)s | %(method)s | %(ip)s | %(url)s | %(process_time)s | %(browser)s | %(referrer)s | %(user)s | %(ios_version)s | %(android_version)s' % record_dict tracking_logger = log_rotator.tracking_logger() tracking_logger.debug(record_str) except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) return response
def getCarBrands(): try: brands = list(SupportedCarBrands.objects.all()) #brands = list(VehicleModels.objects.all()) data = [] if brands: for brand in brands: data.append(brand) result = {'brands': data} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {'brands': []} return result
def auto_suggest_inventory(request): try: if request.method == 'POST': if request.user.is_authenticated(): result = util.fetchInventoryData(request.user) else: result = {"status": "unauthorized", "msg": "Not authorized."} else: result = {"status": "failure", "msg": "Invalid request method"} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "something went wrong"} return HttpResponse(json.dumps(result, default=json_default), content_type="application/json")
def save_image(image_id, image): try: db = MySQLdb.connect("localhost", "root", settings.DATABASES['default']['PASSWORD'], "easedb") query = "INSERT INTO images values ('" + image_id + "', '" + image + "')" cursor = db.cursor() cursor.execute(query) db.commit() db.close() return True except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) return False
def get_image(): try: db = MySQLdb.connect("localhost", "root", settings.DATABASES['default']['PASSWORD'], "easedb") query = "SELECT image FROM images limit 1" cursor = db.cursor() cursor.execute(query) image = cursor.fetchall()[0] db.close() return image except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) return False
def register(request): register_form = forms.RegisterForm(request.data) if not register_form.is_valid(): return Response({ 'status': "failure", 'errors': register_form.errors }, status=status_code.HTTP_400_BAD_REQUEST) try: user_obj = User.objects.create_user( username=register_form.cleaned_data['mobile'], email=register_form.cleaned_data['email'], password=register_form.cleaned_data['password'], last_login=timezone.now()) customer_obj = models.Customer.objects.create( mobile=register_form.cleaned_data['mobile'], first_name=register_form.cleaned_data['first_name'], last_name=register_form.cleaned_data['last_name'], #address = {'address': [register_form.cleaned_data['address']]} #address = register_form.cleaned_data['address'] ) except IntegrityError: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) return Response( { 'status': "failure", 'msg': "User account already exists." }, status=status_code.HTTP_409_CONFLICT) status, otptranid = util.generateOTP(register_form.cleaned_data['mobile']) if status != 1: return Response({ 'status': "failure", 'msg': "OPT Failure" }, status=status_code.HTTP_500_INTERNAL_SERVER_ERROR) return Response({ 'status': "success", 'msg': "Account creation successful.", 'otptranid': otptranid })
def change_password(request): try: if request.method == 'POST': data = request.POST username = data.get('user', 'NA') passwd = data.get('passwd', 'NA') tranid = data.get('tran_id', 'NA') result = util.resetPassword(username, passwd, tranid) else: result = {"status": "failure", "msg": "Invalid request method"} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "something went wrong"} return HttpResponse(json.dumps(result, default=json_default), content_type="application/json")
def getCompliantCodes(): try: compliants = list(ComplaintCode.objects.all()) data = [] if compliants: for compliant in compliants: temp_dict = {} temp_dict['Code'] = compliant.Code temp_dict['Description'] = compliant.Description temp_dict['Aggregate'] = compliant.Aggregate data.append(temp_dict) result = {"status": "success", "compliants": data} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "Something went wrong."} return result
def generateInvoice(jc_id, pmt_mode, dealerid): try: status_obj = JCStatus.objects.get(JobCardID__iexact=jc_id, DealerID__iexact=dealerid) if status_obj.Status == "CLOSED": invoice_obj = JCInvoiceAndLabourCost.objects.get( JobCardID__iexact=jc_id, DealerID__iexact=dealerid) if invoice_obj.InvoiceNumber == "": spares_obj = JCStocksInfo.objects.filter( JobCardID__iexact=jc_id, DealerID__iexact=dealerid) try: other_parts_inv = other_parts = JCOtherStocksInfo.objects.get( JobCardID__iexact=jc_id) except JCOtherStocksInfo.DoesNotExist: other_parts_inv = None total_parts_cost = 0.00 if spares_obj: for obj in spares_obj: total_parts_cost += float(obj.TotalPrice) invoice_number = "INV" + datetime.datetime.now().strftime( "%Y%m%d%H%M%S") + '_' + str(random.randint(111, 999)) invoice_obj.InvoiceNumber = invoice_number invoice_obj.PaymentMode = pmt_mode invoice_obj.PartsTotalPrice = "%.2f" % total_parts_cost invoice_obj.VATPercentage = "%.2f" % config.TAX_PERCENTAGE invoice_obj.TaxPercentage = "%.2f" % config.SERVICE_TAX_PERCENTAGE invoice_obj.GeneratedTime = datetime.datetime.now().strftime( "%d-%m-%Y %H:%M") invoice_obj.save() result = { "status": "success", "msg": "Invoice generated successfully" } else: result = { "status": "failure", "msg": "Invoice already generated" } else: result = {"status": "failure", "msg": "Job card is not closed"} except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = {"status": "failure", "msg": "Something went wrong."} return result
def post(self,request,url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: apartmentid = request.POST.get('apartmentid') file_name = request.POST.get('file_name') SheetNo = request.POST.get('SheetNo') dueDataLoader = DueDataLoader() result = dueDataLoader.read_due_data(apartmentid, file_name, SheetNo) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE
def post(self,request,url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: mobile_number = request.POST.get('mobile_number') apartment_id = request.POST.get('apartment_id') otp = request.POST.get('otp') apartmentUserObj = ApartUserUtil() result = apartmentUserObj.verifyOTP(apartment_id, mobile_number, otp) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE
def post(self,request,url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: AppartmentEmail = request.POST.get('AppartmentEmail') AccountHolderName = request.POST.get('AccountHolderName') AccountNumber = request.POST.get('AccountNumber') IFSCCode = request.POST.get('IFSCCode') apartmentAccountObj = ApartmentAccountClass() result = apartmentAccountObj.UpdateBankDetails(AppartmentEmail,AccountHolderName, AccountNumber, IFSCCode) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE
def post(self,request,url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status. """ viewslogger = log_rotator.views_logger() result = {} try: block_name = request.POST.get('block_name') flat_number = request.POST.get('flat_number') apartment_id = request.POST.get('apartment_id') type_occupancy = request.POST.get('type_occupancy') apartmentUserObj = ApartUserUtil() result['unmatch'] = apartmentUserObj.getunmatchreg(block_name, flat_number, apartment_id,type_occupancy) result['prereg'] = apartmentUserObj.getpreregistrations(block_name, flat_number, apartment_id, type_occupancy) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE
SheetNo = request.POST.get('SheetNo') peopleDataLoader = PeopleDataLoader() result = peopleDataLoader.read_people_data(apartmentid, file_name, SheetNo) except urllib2.HTTPError, err: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) if err.code == 401: result = config.INVALID_CREDENTIALS_RESPONSE else: result = config.UNKNOWN_ERROR_RESPONSE except KeyError: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = config.MANDATORY_DATA_MISSING_RESPONSE except: error_logger = log_rotator.error_logger() error_logger.debug("Exception::", exc_info=True) result = config.UNKNOWN_ERROR_RESPONSE viewslogger.debug("Response : %s" % result) return HttpResponse(json.dumps(result, default=utils.json_default), content_type="application/json") class LoadMaintenanceDueFile(View): def get(self,request,url): result = config.INVALID_REQUEST_METHOD_RESPONSE return HttpResponse(json.dumps(result, default=utils.json_default), content_type="application/json") def post(self,request,url): """ @summary: View method to handle file load requests. @param request: file path @rtype: HttpResponse @return: HttpResponse containing load file status.