def reportjob(): userid = int(request.json['userid']) token = request.json['token'] jobid = request.json['jobid'] reporteddatetime = datetime.now() reportresolveddatetime = datetime.now() if (userid != None) and (jobid != None): reportedJSON = { "reportid": CommonUtils.generateRandomNo(Report, "reportid"), "byuserid": userid, "reportresolved": False, "reporteddatetime": reporteddatetime, "reportresolveddatetime": reportresolveddatetime, "active": True } temp = [] temp.append(reportedJSON) Jobs.update({"jobid": jobid}, {"$set": {"reportedJSON": temp}}) return jsonify({ "status": 200, "message": "Successfully Report Created." }) else: return jsonify({"status": 400, "message": "No Data Recevied."})
def job_comment_list(): # Check authentications keys response = [] jobid = int(request.json['jobid']) jobCommentsList = db.jobcomments.find({ "jobid": jobid, "active": True }, {"_id": 0}) job = Jobs.find_one({"jobid": jobid}) jobowner = job['creatinguserid'] for data in jobCommentsList: userId = User.find_one({"userid": data['userid']}) username = userId['firstname'] + " " + userId['lastname'] data.update({"username": username}) if (data['userid'] == jobowner): data.update({"jobowner": True}) else: data.update({"jobowner": False}) response.append(data) if len(response) != 0: return jsonify({ "status": 200, "message": "Job Comments List.", "jobCommentsList": response, "error": False }) else: return jsonify({ "status": 200, "message": "Job Comments List empty", "jobCommentsList": [], "error": True })
def jobset(): resultd = Jobs.find({}) if resultd is not None: for result in resultd: currentdata = datetime.now() if result['duedate'] < currentdata: jobUpdate = Jobs.update( { "jobid": result['jobid'], "draft": False }, {"$set": { "expired": True }}) return 'success'
def jobDetails(): jobid = request.json['jobid'] job = list(Jobs.find_one({"jobid": jobid}, {"_id": 0})) if job is not None: return jsonify({"detail": job}) else: return jsonify({"message": "no job found with this id"})
def bids(): data = [] userid = int(request.json['userid']) type = int(request.json['type']) if (type == 0): typeKey = "$or" typeVal = [{"draft": True}, {"draft": False}] elif (type == 1): typeKey = "draft" typeVal = True elif (type == 2): typeKey = "draft" typeVal = False try: usersJob = list(JobBids.find({"userid": userid}, {"_id": 0})) count = 0 for df in usersJob: #return jsonify({"count": d["jobid"]}) #jobbids=list(JobBids.find({"jobid":d["jobid"]},{"_id":0})) jobdraftdata = list( Jobs.find({ "jobid": df["jobid"], typeKey: typeVal }, {"_id": 0})) if (len(jobdraftdata) != 0): count = count + 1 for con in jobdraftdata: convertations = list( Conversations.find( { "userid1": userid, "userid2": con["creatinguserid"] }, {"_id": 0})) con.update({"conversations": convertations}) data.append({"job": jobdraftdata}) #data["job"].update({"bid":jobbids}) return jsonify({ "status": 200, "response": "ok", "message": count, "data": data, "error": False }) except Exception as e: print(e) return jsonify({ "error": True, "response": [], "message": "unknown error", "status": 400 })
def paypal_payment(): try: userid = int(request.json['userid']) pay_id = request.json['payid'] print(pay_id) payment = Payment.find(pay_id) print(payment) transactions = [] transaction_amount = {} # credit_card = {} sales_id = 0 soj_transaction_id = 0 transactionstatus = "" # for card_details in payment.payer.funding_instruments: # if card_details.has_key('credit_card_token'): # credit_card = {"expire_year":card_details.credit_card_token.expire_year, # "type":card_details.credit_card_token.type,"number":card_details.credit_card_token.number, # "expire_month":card_details.credit_card_token.expire_month} # elif card_details.has_key('credit_card'): # credit_card = {"expire_year":card_details.credit_card.expire_year, # "type":card_details.credit_card.type,"number":card_details.credit_card.number, # "expire_month":card_details.credit_card.expire_month} # transactions.append(credit_card) for transaction_details in payment.transactions: transaction_amount = {"currency": transaction_details.amount.currency, "total": transaction_details.amount.total} sales_link = transaction_details['related_resources'][0]['sale']['links'][0]['href'] sales_list = sales_link.split('sale')[1] sales_id = sales_list.split('/')[1] soj_transaction_id = int(transaction_details.description) transactionstatus = int(request.json['transactionid']) transactions.append(transaction_amount) payment_details = {"payment": payment.id, "sales_id": sales_id, "paymenttype": payment.payer.payment_method, "state": payment.state, "transaction_details": transactions} if payment.state == "approved": print(soj_transaction_id) TransactionTrack.update({ "transactionid": soj_transaction_id }, { "$set": { "transactionstatus": transactionstatus, "transactionresponse": payment_details, "responsedatetime": datetime.datetime.now() } }) transactions_details_from_database = TransactionTrack.find_one({"transactionid": soj_transaction_id}, {"_id": 0}) print(transactions_details_from_database) bidid = transactions_details_from_database['jobbid'] jobid = transactions_details_from_database['jobid'] final_bid = JobBids.find_one({"bidid": int(bidid)}, {"_id": 0}) completionremarks = "" # completionstatus = "" bidcanceldatetime = "" bidcancellationreason = "" # bidselected = False jobberfullname = "" # jobberEmail = None # jobberMobile = None bidderfullname = "" bidder_email = None # bidderMobile = None person_selected = 0 if final_bid is not None: job_collection = Jobs.find_one({"jobid": final_bid['jobid']}, {"_id": 0}) if job_collection: try: person_selected = int(job_collection['personsselected']) except ValueError: pass user_jobber_collection = User.find_one({"userid": job_collection['creatinguserid']}, {"_id": 0}) if user_jobber_collection is not None: jobberfullname = user_jobber_collection['firstname'] + " " + user_jobber_collection['lastname'] # jobberEmail = user_jobber_collection['email'] # jobberMobile = user_jobber_collection['mobile'] user_bidder_collection = User.find_one({"userid": final_bid['userid']}, {"_id": 0}) if user_bidder_collection is not None: bidderfullname = user_bidder_collection['firstname'] + " " + user_bidder_collection['lastname'] bidder_email = user_bidder_collection['email'] # bidderMobile = user_bidder_collection['mobile'] else: print("No jobs") if request.json['status'] == "selectedbyjobber": if final_bid['status'] == "pending": print(transaction_amount) JobBids.update({ "bidid": int(bidid) }, { "$set": { "selected": True, "final_bidamount": int(float(transaction_amount['total'])), "bidcanceldatetime": bidcanceldatetime, "bidcancellationreason": bidcancellationreason, "status": "selectedbyjobber", "completionstatus": "pending", "completionremarks": completionremarks } }) if job_collection['personsrequired'] > person_selected: if job_collection['personsrequired'] == person_selected + 1: Jobs.update({"jobid": int(jobid)}, {"$set": { "personsselected": int(person_selected + 1), "jobstatus": "allotted" }}) else: Jobs.update({"jobid": int(jobid)}, {"$set": { "personsselected": int(person_selected + 1) }}) # Ledger Entries Ledgers.bid_selection_entries(userid, jobid, bidid, final_bid, payment_details) # Push Notification Bid Accepted PushNotificationUtils.notify_bid_accepted(userid, jobid, bidid, job_collection, jobberfullname, final_bid) # Bid Accepted Email EmailUtils.send_bid_accpeted_mail(final_bid['userid'], bidder_email, job_collection['title'], bidderfullname, jobberfullname, transaction_amount['total']) elif request.json['status'] == "reversebid": job_bid_detail = JobBids.find_one({"bidid": int(bidid)}, {"_id": 0}) if job_bid_detail is not None: if job_bid_detail['status'] == 'pending': total_bid_amount = int(float(transaction_amount['total'])) # updating bidamount array and reverse bid array reverse_bid_data = {"reversebidamount": int(float(transaction_amount['total'])), "reversebiddatetime": datetime.datetime.now()} JobBids.update({"bidid": int(bidid)}, {"$set": {"status": "reversebid", "reversebid": reverse_bid_data, "final_bidamount": total_bid_amount }}) # Bid Reverse Entried Ledgers.bid_reverse_entries(userid, jobid, bidid, final_bid, payment_details) # Bid Reverse Push Notification PushNotificationUtils.notify_bid_reverse(userid, jobid, bidid, job_collection, bidderfullname, job_bid_detail) # Bid Reverse Email EmailUtils.send_reverse_bid_mail(final_bid['userid'], bidder_email, job_collection['title'], bidderfullname, jobberfullname, transaction_amount['total']) return make_response(jsonify({"status": 200, "message": "Payment Successful"}), 200) except ResourceNotFound as e: print("Payment Not Found") print(str(e)) return make_response(jsonify({"status": 500, "message": "Something went wrong, Please try again!"}), 500) except Exception as e: print(str(e)) return make_response(jsonify({"status": 500, "message": "Something went wrong, Please try again!"}), 500)
def job_comment_create(): # Check authentications keys if request.json.has_key('userid') == False or request.json.has_key( 'token') == False: return jsonify({ "status": 401, "message": "Authentication keys are missing." }) userid = int(request.json['userid']) token = request.json['token'] # Authenticate credentials if authentication(userid, token) == False: return jsonify({"status": 400, "message": "Authentication Failed."}) jobData = Jobs.find_one({"jobid": int(request.json['jobid'])}, {"_id": 0}) if jobData is not None: userCollection = User.find_one({"userid": userid}, {"_id": 0}) if userCollection is not None: fullname = userCollection['firstname'] + " " + userCollection[ 'lastname'] if userCollection['picurl'] != "": picurl = URL + imagePath + userCollection['picurl'] else: picurl = URL + imagePath + "user-no-image.jpg" else: fullname = "" commentid = CommonUtils.generateRandomNo(JobComments, "commentid") JobComments.insert({ "commentid": commentid, "jobid": int(request.json['jobid']), "userid": userid, "comment": request.json['comment'], "reportedJSON": [], "createdatetime": datetime.now(), "updatedatetime": datetime.now(), "active": True, "picurl": picurl }) commentData = list( JobComments.find({"jobid": int(request.json['jobid'])}, { "_id": 0, "userid": 1 })) if len(commentData) > 0: userArray = [] for commentCollection in commentData: if commentCollection['userid'] != jobData[ 'creatinguserid'] and commentCollection[ 'userid'] != userid: userArray.append(commentCollection['userid']) userArrayList = list(set(userArray)) if jobData['creatinguserid'] != userid: notificationtext = fullname + " commented on your job - title " + jobData[ 'title'] registration_id = find_FCM_id(jobData['creatinguserid']) if (registration_id): data_message = { "body": notificationtext, } result = push_service.notify_single_device( registration_id=registration_id, message_title="New comment", message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY") Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Comment", "notificationtouserid": int(jobData['creatinguserid']), "notificationfromuserid": userid, "jobid": jobData['jobid'], "bidid": -1, "commentid": commentid, "createddatetime": datetime.now(), "updatedatetime": datetime.now(), "isread": False }) else: print("job created userid and userid is same.") for userArrayListData in userArrayList: notificationtext = fullname + " commented on your job - title " + jobData[ 'title'] registration_id = find_FCM_id(userArrayListData) if (registration_id): data_message = { "body": notificationtext, } result = push_service.notify_single_device( registration_id=registration_id, message_title="New Comment", message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY") Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Comment", "notificationtouserid": int(userArrayListData), "notificationfromuserid": userid, "jobid": jobData['jobid'], "bidid": -1, "commentid": commentid, "createddatetime": datetime.now(), "updatedatetime": datetime.now(), "isread": False }) else: print("No comment data.") print(commentid) getNewJobComment = list( JobComments.find({"commentid": commentid}, {"_id": 0})) print(getNewJobComment) return jsonify({ "status": 200, "message": "Comments created.", "getNewJobComment": getNewJobComment }) else: return jsonify({ "status": 200, "message": "No Job Found.", "getNewJobComment": [] })
def conversation_create(): userid = int(request.json['userid']) token = request.json['token'] check_status = JobBids.find({ "jobid": int(request.json['jobid']), "userid": userid, "active": True, "status": { "$in": ["selectedbyjobber", "approvedbybidder"] } }).count() if check_status == 1: secdatetime = datetime.utcnow() - timedelta(minutes=1) jobData = Jobs.find_one( { "jobid": int(request.json['jobid']), "active": True, "jobstatus": { "$ne": "completed" }, "expired": False }, {"_id": 0}) if jobData is not None: if jobData['creatinguserid'] != userid: conversationData = Conversations.find_one( { "userid1": jobData['creatinguserid'], "userid2": userid, "jobid": jobData['jobid'] }, {"_id": 0}) if conversationData is None: conversationid = CommonUtils.generateRandomNo( Conversations, "conversationid") Conversations.insert({ "userid1": jobData['creatinguserid'], "userid2": userid, "lastdatetime": datetime.now(), "lastmessages": None, "lastmessagesuserid": None, "conversationid": conversationid, "jobid": jobData['jobid'], "createddatetime": datetime.now(), "createdatetimeinseconds": calendar.timegm(secdatetime.utctimetuple()), "updatedatetime": datetime.now(), "jobexpired": False, "active": True }) conversationList = list( Conversations.find({ "conversationid": conversationid }, { "_id": 0 }).sort("createddatetime", -1)) return jsonify({ "status": 200, "message": "Conversation Created.", "conversationList": conversationList }) else: return jsonify({ "status": 402, "message": "Conversation already Exist.", "conversationData": conversationData['conversationid'] }) else: return jsonify({ "status": 402, "message": "Conversation not on same user.", "conversationData": [] }) else: return jsonify({ "status": 402, "message": "No job data Found.", "conversationList": [] }) else: return jsonify({ "status": 402, "message": "status not correct", "conversationList": [] })
def user_profile_fetch(): URL = Constants.URL imagePath = Constants.IMAGE_PATH try: # Check Authentication Key. userid = int(request.json['userid']) token = request.json['token'] otherUserId = int(request.json['messageUserid']) userdata_array = list( User.find({ "userid": otherUserId, "active": True }, {"_id": 0})) resultArray = {} responseArr = [] temp = [] reportStatus = False if len(userdata_array) > 0: for collectionInfo in userdata_array: reportedJSONdata = collectionInfo['reportedJSON'] if len(reportedJSONdata) > 0: for reportStatusData in reportedJSONdata: # print reportStatusData['byuserid'] if reportStatusData['byuserid'] == userid: reportStatus = True else: reportStatus = False reviewsDataList = list \ (JobReviews.find({"touserid" :otherUserId, "adminaction" :True, "active" : True} ,{"_id" :0})) reviewsData = [] if len(reviewsDataList) > 0: for collectionInfoReview in reviewsDataList: userdata = User.find_one( { "userid": collectionInfoReview['userid'], "active": True }, {"_id": 0}) if userdata is not None: fullname = userdata['firstname'] + ' ' + userdata[ 'lastname'] if userdata['picurl'] != "": picurl = URL + imagePath + userdata['picurl'] else: picurl = URL + imagePath + "user-no-image.jpg" if collectionInfoReview.has_key('jobid'): jobData = Jobs.find_one( { "jobid": collectionInfoReview['jobid'], "active": True }, {"_id": 0}) if jobData is not None: title = jobData['title'] else: title = "" editionData = { "fullname": fullname, "jobtitle": title, "picurl": picurl } collectionInfoReview.update(editionData) reviewsData.append(collectionInfoReview) else: reviewsData = [] locationName = "" cityName = "" if collectionInfo['addressJSON']['city'] != "": citynamedata = CityCollections.find_one( {"cityid": int(collectionInfo['addressJSON']['city'])}, {"_id": 0}) cityName = citynamedata['city'] countrynamedata = CityCollections.find_one( {"countryid": int(citynamedata['countryid'])}, {"_id": 0}) print(countrynamedata) #return jsonify({"ok": 1}) countryName = countrynamedata['countryid'] else: cityName = "" countryName = "" if collectionInfo['locationid'] != "": locationNameData = Locations.find_one( {"locationid": int(collectionInfo['locationid'])}, { "_id": 0, "locationname": 1, "under": 1 }) if locationNameData is not None: if locationNameData['under'] != "": locationName = str(locationNameData['under'] ) +" - " +str \ (locationNameData['locationname']) else: locationName = str( locationNameData['locationname']) else: locationName = "" allCityData = list( CityCollections.find({}, { "_id": 0, "cityid": 1, "city": 1 })) # allcity = [] # if len(allCityData) > 0: # for getAllCityData in allCityData: # allcity.append({"cityid" : getAllCityData['cityid'], "city" : getAllCityData['city']}) skillData = collectionInfo['skillsJSON'] skillNameData = [] if len(skillData) > 0: for skillDataCollections in skillData: skillNameData.append(skillDataCollections['skillname']) rating = 0 # Rating Initially 0 userReview = list( JobReviews.find( { "touserid": int(collectionInfo['userid']), "active": True }, { "_id": 0, "rating": 1 })) if len(userReview) > 0: totalUserReview = len(userReview) if userReview is not None: for userRating in userReview: rating = rating + userRating['rating'] tatalRating = int(rating / totalUserReview) else: tatalRating = 0 portfolioData = list( UserPortfolio.find( { "userid": otherUserId, "active": True, }, {"_id": 0})) picurlPath = URL + imagePath + collectionInfo['picurl'] documentsPath = URL + Constants.DOC_PATH portfolioDataPath = URL + Constants.PORTFOLIO_PATH updateJSON = { "cityname": cityName, "locationName": locationName, "countryname": countryName, "allcity": allCityData, "skillName": skillNameData, "reviewsData": reviewsData, "portfolioData": portfolioData, "reportStatus": reportStatus, "picurlPath": picurlPath, "userrating": tatalRating, "documentsPath": documentsPath, "portfolioDataPath": portfolioDataPath } collectionInfo.update(updateJSON) responseArr.append(collectionInfo) resultArray['data'] = responseArr resultArray['status'] = "200" resultArray['message'] = "Userdata List." else: resultArray['data'] = responseArr resultArray['status'] = "400" resultArray['message'] = "No data in List." return jsonify(resultArray) except Exception as e: print(e) return jsonify({"status": 500})
def jobadd(): if request.method == 'POST': try: #return "ok" # Check authentications keys ''' if request.form['userid'] == "" or request.form['token'] =="": return jsonify({"status": 401, "message": "Authentication keys are missing."}) ''' userid = request.form['userid'] #return userid token = request.form['token'] # Authenticate credentials userInfo = User.find_one({"userid": int(userid)}, {"_id": 0}) if userInfo is not None: if userInfo['emailverified'] is False: return jsonify({ "status": 202, "message": "Email not verified. Please verify your email to enable this feature" }) jobid = request.form['jobid'] originaljobid = None if (jobid != ""): originaljobid = jobid draft = request.form['draft'] title = request.form['title'] description = request.form['description'] duedate = request.form['duedate'] #return jsonify({"ok": 1}) jobOnline = request.form['jobonline'] #return "ok" print("1") city = int(request.form['city']) print("2") location = int(request.form['location']) print("3") if duedate == "today": duedate = "" duedate = datetime.now() if duedate == "week": duedate = "" duedate = datetime.now() + timedelta(days=7) if duedate == "certain_day": duedate = "" format = '%d-%m-%Y %H:%M:%S' certaindatetime = request.form['certaindatetime'] duedate = datetime.strptime(certaindatetime, format) citydetail = CityCollections.find_one({"cityid": city}, {"_id": 0}) statedetail = StateCollections.find_one( {"stateid": citydetail['stateid']}, {"_id": 0}) countrydetail = CountryCollections.find_one( {"countryid": citydetail['countryid']}, {"_id": 0}) addressJSON = { "address1": "", "address2": "", "city": city, "state": citydetail['stateid'], "country": countrydetail['countryid'], "pincode": "" } person = request.form['person'] print("5") budgettype = request.form['budgettype'] print("6") budget = float(request.form['budget']) print("7") if budgettype == "hourly": totalhours = int(request.form['hours']) totalbudget = int(budget * totalhours) else: totalhours = -1 totalbudget = budget print("8") if draft == False: publisheddatetime = datetime.now() else: publisheddatetime = None target = os.path.join(Constants.APP_ROOT, 'static/jobdocument/') index = 0 filelist = [] thumblist = [] print("9") jobidno = CommonUtils.generateRandomNo(Jobs, "jobid") for file in request.files.getlist("file"): index = index + 1 try: filename = str(jobidno) + "_" + str(index) + ".jpg" destination = "original/".join([target, filename]) file.save(destination) im = Image.open(file) size = 45, 45 im.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste(im, (int((size[0] - im.size[0]) / 2), int((size[1] - im.size[1]) / 2))) tname = target + "/thumbnail/" + str(jobidno) + "_" + str( index) + ".png" background.save(tname) thumblist.append(tname) except Exception as e: fname = str(jobidno) + "_" + str(index) + file.filename destination = "original/".join([target, fname]) file.save(destination) tname = target + "/thumbnail/pdf.png" thumblist.append(tname) #thumblist.append(tpath) filelist.append(destination) #return jsonify({"t":thumblist,"l":filelist}) print("10") jobdocs = {} jobdocs.update({"thumbnails": thumblist}) jobdocs.update({"doc": filelist}) print("11") if (request.form['draft_data'] == "false"): jobid = jobidno result = Jobs.insert({ "jobid": jobid, "title": title, "description": description, "creatinguserid": userid, "duedate": duedate, "budget": budget, "budgettype": budgettype, "totalbudget": totalbudget, "totalhours": totalhours, "jobstatus": "pending", "draft": draft, "publisheddatetime": publisheddatetime, "personsrequired": int(person), "reportedJSON": [], "active": True, "cancellationreason": None, "cityid": city, "online": jobOnline, "addressJSON": addressJSON, "locationid": location, "personsselected": 0, "originaljobid": originaljobid, "adminapprovalforcancellation": None, "skillid": None, "tags": None, "jobdocs": jobdocs, "updatedatetime": datetime.now(), "createdatetime": datetime.now(), "expired": False }) return jsonify({ 'status': 200, 'message': 'Job Created.', 'jobid': jobid }) else: Jobs.update({"jobid": jobid}, { "$set": { "title": title, "description": description, "creatinguserid": userid, "duedate": duedate, "budget": budget, "budgettype": budgettype, "totalbudget": totalbudget, "totalhours": totalhours, "jobstatus": "pending", "draft": draft, "publisheddatetime": publisheddatetime, "personsrequired": int(person), "reportedJSON": [], "active": True, "cancellationreason": None, "cityid": city, "online": jobOnline, "addressJSON": addressJSON, "locationid": location, "personsselected": 0, "originaljobid": originaljobid, "adminapprovalforcancellation": None, "skillid": None, "tags": None, "jobdocs": jobdocs, "updatedatetime": datetime.now(), "expired": False } }) return jsonify({ 'status': 200, 'message': 'Job Updated.', 'jobid': jobid }) except Exception as e: print(e) return "error"
def user_job_review(): # Check authentications keys userid = int(request.json['userid']) token = request.json['token'] if request.json['bidderJobStatus'] == "verify": check_status = JobBids.find \ ({"jobid" :int(request.json['jobid']) ,"userid" :int(request.json['touserid']) ,"active" :True ,"status" : "completed"}).count() elif request.json['bidderJobStatus'] == "completed": check_status = JobBids.find({ "jobid": int(request.json['jobid']), "userid": userid, "active": True, "status": { "$in": ["selectedbyjobber", "approvedbybidder"] } }).count() print(check_status) if check_status == 1: if request.json['bidderJobStatus'] == "verify": bidid = 0 jobbids_info = JobBids.find_one \ ({"userid" :int(request.json['touserid']) ,"jobid" :int(request.json['jobid'])} ,{"_id" :0}) if jobbids_info is not None: bidid = jobbids_info['bidid'] jobReviewsDataCount = JobReviews.find({ "userid": userid, "jobid": int(request.json['jobid']) }).count() jobCollection = list(Jobs.find({"jobid": int(request.json['jobid'])})) # print jobBidsData['bidid'] if jobReviewsDataCount == 0: jobreviewData = JobReviews.insert({ "userid": userid, "reviewid": CommonUtils.generateRandomNo(JobReviews, "reviewid"), "jobid": int(request.json['jobid']), "rating": int(request.json['rating']), "comment": request.json['comment'], "touserid": int(request.json['touserid']), "adminaction": False, "active": True, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) if request.json['bidderJobStatus'] == "verify": jobCollection = Jobs.find_one( {"jobid": int(request.json['jobid'])}, {"_id": 0}) if jobCollection is not None: total_paid_task = JobBids.find({ "jobid": int(request.json['jobid']), "completionstatus": { "$in": ["accepted", "rejectedaccepted"] } }).count() if total_paid_task != 0: if (total_paid_task >= jobCollection['personsrequired']): Jobs.update({"jobid": int(request.json['jobid'])}, {"$set": { "jobstatus": "paid" }}) jobBidsData = JobBids.find_one \ ({"userid" : int(request.json['touserid']) ,"jobid" : int(request.json['jobid'])} ,{"_id" :0}) JobBids.update({"bidid": int(jobBidsData['bidid'])}, { "$set": { "status": "verify", "completionstatus": "accepted" } }) jobCollection = Jobs.find_one( {"jobid": int(request.json['jobid'])}, {"_id": 0}) if jobCollection is not None: userJobberCollection = user.find_one( {"userid": jobCollection['creatinguserid']}, {"_id": 0}) if userJobberCollection is not None: jobberfullname = userJobberCollection[ 'firstname'] + " " + userJobberCollection[ 'lastname'] jobberEmail = userJobberCollection['email'] jobberMobile = userJobberCollection['mobile'] else: jobberfullname = "" jobberEmail = None jobberMobile = None userbidderCollection = User.find_one( {"userid": int(request.json['touserid'])}, {"_id": 0}) if userbidderCollection is not None: bidderfullname = userbidderCollection[ 'firstname'] + " " + userbidderCollection[ 'lastname'] bidderEmail = userbidderCollection['email'] bidderMobile = userbidderCollection['mobile'] else: bidderfullname = "" bidderEmail = None bidderMobile = None else: print("No jobs") if bidderEmail is not None: subject = "Payment released." msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[bidderEmail]) msg.html = render_template( '/emailTemplates/Payment-released.html', name=bidderfullname, title=str(jobCollection['title']), jobber=jobberfullname) Mail.send(msg) EmailTracks.insert({ "emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": int(request.json['touserid']), "email": bidderEmail, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) else: print("No email of jobber.") else: jobBidsData = JobBids.find_one( { "userid": userid, "jobid": int(request.json['jobid']) }, {"_id": 0}) JobBids.update({"bidid": int(jobBidsData['bidid'])}, {"$set": { "status": "completed" }}) jobCollection = Jobs.find_one( {"jobid": int(request.json['jobid'])}, {"_id": 0}) if jobCollection is not None: total_completed_task = JobBids.find({ "jobid": int(request.json['jobid']), "status": "completed" }).count() print total_completed_task if total_completed_task != 0: if (total_completed_task >= jobCollection['personsrequired']): Jobs.update({"jobid": int(request.json['jobid'])}, {"$set": { "jobstatus": "completed" }}) updateJobBids = list( JobBids.find({"bidid": int(jobBidsData['bidid'])}, {"_id": 0})) return jsonify({ "status": 200, "message": "Review Created.", "updateJobBids": updateJobBids }) else: updateJobBids = list( JobBids.find( { "jobid": int(request.json['jobid']), "userid": userid, "active": True }, {"_id": 0})) return jsonify({ "status": 200, "message": "Review Data.", "updateJobBids": updateJobBids }) else: updateJobBids = list( JobBids.find( { "jobid": int(request.json['jobid']), "userid": userid, "active": True }, {"_id": 0})) return jsonify({ "status": 200, "message": "this bid is not present", "updateJobBids": updateJobBids })
def job_all_list(): try: allDataCollections = [] sortDataAccording = request.json['sortDataAccording'] city = request.json.get('city', "") location = request.json.get('location', "") radius = request.json.get('radius', "") jobType = request.json.get('jobType', "") budgetMin = request.json.get('budgetMin', "") budgetMax = request.json.get('budgetMax', '') searchstring = request.json.get('searchstring', '') page_offset = request.json.get('page_offset', 0) result = [] lat = 0 lng = 0 job_location = [] filterstring = { "active": True, "draft": False, "jobstatus": { "$in": ["pending", "reversebid"] } } sort_filter = [] distance_filter_string = { "active": True, "draft": False, "jobstatus": { "$in": ["pending", "reversebid"] } } distance_job = [] startCity = "252347228" if len(searchstring) != 0: stringData = '.*' + searchstring + '.*' getall = [] # for OR conditionOR = { '$options': 'i', '$regex': stringData } # regex condition serchdatainarray = {'title': conditionOR} # for title singleget = {"description": conditionOR} # for description getall.append(serchdatainarray) getall.append(singleget) filterstring['$or'] = getall filterstring['expired'] = False distance_filter_string['expired'] = False mapCoordinate = {} cityResult = CityCollections.find_one({"cityid": int(startCity)}, {"_id": 0}) if cityResult is not None: lat = cityResult['gpsJSON']['lat'] lng = cityResult['gpsJSON']['lng'] mapCoordinate = {"lat": lat, "lng": lng} if radius != "": if location != "": location_result = Locations.find_one( {"locationid": int(location)}, {"_id": 0}) if location_result is not None: lat = location_result['gpsJSON']['lat'] lng = location_result['gpsJSON']['lng'] mapCoordinate = {"lat": lat, "lng": lng} print(mapCoordinate) location_gps_result = Locations.find({ "gpsJSON.lnglat": { "$near": { "$geometry": { "type": "Point", "coordinates": [lng, lat] }, "$maxDistance": int(radius) * 1000 } } }) if location_gps_result is not None: for location_gps in location_gps_result: job_location.append(int(location_gps['locationid'])) elif city != "": city_result = CityCollections.find_one({"cityid": int(city)}, {"_id": 0}) if city_result is not None: lat = city_result['gpsJSON']['lat'] lng = city_result['gpsJSON']['lng'] mapCoordinate = {"lat": lat, "lng": lng} print(mapCoordinate) city_gps_result = Locations.find({ "gpsJSON.lnglat": { "$near": { "$geometry": { "type": "Point", "coordinates": [lng, lat] }, "$maxDistance": int(radius) * 1000 } } }) if city_gps_result is not None: for city_gps in city_gps_result: job_location.append(int(city_gps['locationid'])) elif mapCoordinate: city_gps_result = Locations.find({ "gpsJSON.lnglat": { "$near": { "$geometry": { "type": "Point", "coordinates": [ mapCoordinate.get("lng"), mapCoordinate.get("lat") ] }, "$maxDistance": int(radius) * 1000 } } }) if city_gps_result is not None: for city_gps in city_gps_result: job_location.append(int(city_gps['locationid'])) print(job_location) if jobType != "allJobs": filterstring.update({"online": jobType}) distance_filter_string.update({"online": jobType}) if budgetMin or budgetMax: budget_filter = {"budget": {}} if budgetMin: budget_filter['budget']['$gte'] = int(budgetMin) if budgetMax: budget_filter['budget']['$lte'] = int(budgetMax) filterstring.update(budget_filter) distance_filter_string.update(budget_filter) if job_location: if city: filterstring.update({ "cityid": int(city), "locationid": { "$in": job_location } }) else: filterstring.update({ "cityid": int(startCity), "locationid": { "$in": job_location } }) else: if location: filterstring.update({"locationid": int(location)}) if city: filterstring.update({"cityid": int(city)}) else: filterstring.update({"cityid": int(startCity)}) print(type(location)) print(filterstring) if sortDataAccording == "" or sortDataAccording == "recent": sort_filter.append(("publisheddatetime", -1)) elif sortDataAccording == "price_asc": sort_filter.append(("budget", 1)) elif sortDataAccording == "distance": dist_centre = location if location else city if city else "252347228" dist_city_result = Locations.find_one( {"locationid": int(dist_centre)}, {"_id": 0}) if dist_city_result: dist_lat = dist_city_result['gpsJSON']['lat'] dist_lng = dist_city_result['gpsJSON']['lng'] mapCoordinate = {"lat": dist_lat, "lng": dist_lng} print(mapCoordinate) radius = radius if radius else 50000 distance_gps_result = Locations.aggregate([{ "$geoNear": { "near": { "type": "Point", "coordinates": [dist_lng, dist_lat] }, "maxDistance": radius * 1000, "spherical": True, "distanceField": "distance" } }]) if distance_gps_result is not None: for distance_job_location in distance_gps_result: distance_job.append({ "locationid": distance_job_location['locationid'], "distance": distance_job_location['distance'] }) distance_job = sorted(distance_job, key=lambda k: k['distance']) if city: distance_filter_string.update({ "cityid": int(city), "locationid": int(dist_centre) }) distance_result = Jobs.find(distance_filter_string, { "_id": 0 }).skip(page_offset).limit(Constants.PAGE_LIMIT) if distance_result: for distance in distance_result: result.append(distance) else: for distance in distance_job: distance_filter_string.update({ "cityid": int(dist_centre), "locationid": distance['locationid'] }) print(distance_filter_string) distance_result = Jobs.find(distance_filter_string, { "_id": 0 }).skip(page_offset).limit(Constants.PAGE_LIMIT) if distance_result: for dist in distance_result: result.append(dist) else: sort_filter.append(("budget", -1)) if sortDataAccording != "distance": result = Jobs.find(filterstring, { "_id": 0 }).sort(sort_filter).skip(page_offset).limit(Constants.PAGE_LIMIT) print(result.count()) if result: for resultData in result: # Job bidding Detail jobBids = list( JobBids.find({"jobid": resultData['jobid']}, {"_id": 0})) if resultData.get('creatinguserid', None): if resultData['creatinguserid']: userData = User.find_one( {"userid": int(resultData['creatinguserid'])}, {"_id": 0}) if userData: fullname = userData['firstname'] + " " + userData[ 'lastname'] if resultData['cityid']: cityName = CityCollections.find_one( {"cityid": resultData['cityid']}, { "_id": 0, "city": 1 }) cityName = cityName['city'] else: cityName = "" if userData.get('picurl', ""): picurl = Constants.PROFIL_PIC_STATIC_PATH + userData[ 'picurl'] else: picurl = Constants.PROFIL_PIC_STATIC_PATH + "user-no-image.jpg" location_name = "" if resultData['cityid'] and resultData[ 'locationid']: jobMapResult = Locations.find_one( { "locationid": int( resultData['locationid']) }, {"_id": 0}) location_name = jobMapResult[ 'locationname'] + " - " + jobMapResult[ 'under'] else: if not resultData['cityid']: jobMapCity = 252347228 else: jobMapCity = int(resultData['cityid']) jobMapResult = CityCollections.find_one( {"cityid": jobMapCity}, {"_id": 0}) jobMapCoordinate = {} if jobMapResult is not None: lat = jobMapResult['gpsJSON']['lat'] lng = jobMapResult['gpsJSON']['lng'] jobMapCoordinate = {"lat": lat, "lng": lng} MapResult = CityCollections.find_one( {"cityid": int(resultData['cityid'])}, {"_id": 0}) if MapResult is not None: city_lat = MapResult['gpsJSON']['lat'] city_lng = MapResult['gpsJSON']['lng'] mapCoordinate = { "lat": city_lat, "lng": city_lng } userDataCollection = { "fullname": fullname, "cityname": cityName, "locationname": location_name, "picurl": picurl, "totalJobBids": len(jobBids), "jobMapCoordinate": jobMapCoordinate, "mapCoordinate": mapCoordinate } resultData.update(userDataCollection) allDataCollections.append(resultData) return jsonify({ "status": 200, "message": "Job List.", "allTask": allDataCollections, "countData": len(allDataCollections) }) else: return jsonify({ "status": 200, "message": "No data.", "allTask": result, "countData": len(allDataCollections) }) except Exception as e: CommonUtils.print_exception() return jsonify({"status": 500, "message": str(e)})
def createJob(): try: userid = int(request.json['userid']) token = request.json['token'] userInfo = User.find_one({"userid": int(userid)}, {"_id": 0}) if userInfo is not None: if userInfo['emailverified'] is False: return jsonify({ "status": 202, "message": "Email not verified. Please verify your email to enable this feature" }) jobid = request.json['jobid'] originaljobid = None if (jobid != ""): originaljobid = jobid draft = request.json['draft'] title = request.json['title'] description = request.json['description'] duedate = request.json['duedate'] jobOnline = request.json['jobOnline'] city = int(request.json['city']) location = int(request.json['location']) if duedate == "today": duedate = "" duedate = datetime.now() if duedate == "week": duedate = "" duedate = datetime.now() + timedelta(days=7) if duedate == "certain_day": duedate = "" format = '%d-%m-%Y %H:%M:%S' certaindatetime = request.json['certaindatetime'] duedate = datetime.strptime(certaindatetime, format) citydetail = CityCollections.find_one({"cityid": city}, {"_id": 0}) statedetail = StateCollections.find_one( {"stateid": citydetail['stateid']}, {"_id": 0}) countrydetail = CountryCollections.find_one( {"countryid": citydetail['countryid']}, {"_id": 0}) addressJSON = { "address1": "", "address2": "", "city": city, "state": citydetail['stateid'], "country": countrydetail['countryid'], "pincode": "" } person = request.json['person'] budgettype = request.json['budgettype'] budget = float(request.json['budget']) if budgettype == "hourly": totalhours = int(request.json['hours']) totalbudget = int(budget * totalhours) else: totalhours = -1 totalbudget = budget if draft == False: publisheddatetime = datetime.now() else: publisheddatetime = None if (request.json['draft_data'] == False): jobid = CommonUtils.generateRandomNo(Jobs, "jobid") result = Jobs.insert({ "jobid": jobid, "title": title, "description": description, "creatinguserid": userid, "duedate": duedate, "budget": budget, "budgettype": budgettype, "totalbudget": totalbudget, "totalhours": totalhours, "jobstatus": "pending", "draft": draft, "publisheddatetime": publisheddatetime, "personsrequired": int(person), "reportedJSON": [], "active": True, "cancellationreason": None, "cityid": city, "online": jobOnline, "addressJSON": addressJSON, "locationid": location, "personsselected": 0, "originaljobid": originaljobid, "adminapprovalforcancellation": None, "skillid": None, "tags": None, "updatedatetime": datetime.now(), "createdatetime": datetime.now(), "expired": False }) return jsonify({ 'status': 200, 'message': 'Job Created.', 'jobid': jobid }) else: Jobs.update({"jobid": jobid}, { "$set": { "title": title, "description": description, "creatinguserid": userid, "duedate": duedate, "budget": budget, "budgettype": budgettype, "totalbudget": totalbudget, "totalhours": totalhours, "jobstatus": "pending", "draft": draft, "publisheddatetime": publisheddatetime, "personsrequired": int(person), "reportedJSON": [], "active": True, "cancellationreason": None, "cityid": city, "online": jobOnline, "addressJSON": addressJSON, "locationid": location, "personsselected": 0, "originaljobid": originaljobid, "adminapprovalforcancellation": None, "skillid": None, "tags": None, "updatedatetime": datetime.now(), "expired": False } }) return jsonify({ 'status': 200, 'message': 'Job Updated.', 'jobid': jobid }) except Exception as e: return jsonify({'status': 500, 'message': "error"})
def job_paypal_payment(): try : if request.json.has_key('userid') == False or request.json.has_key('token') == False: return jsonify({ "status" :401 ,"message" :"Authentication keys are missing." }) userid = int(request.json['userid']) token = request.json['token'] # Authenticate credentials if authentication(userid ,token) == False: return jsonify({"status" :400 ,"message" :"Authentication Failed."}) pay_id = request.json['payid'] print (pay_id) payment = Payment.find(pay_id) print (payment) transactions = [] transaction_amount = {} credit_card = {} sales_id = 0 soj_transaction_id = 0 transactionstatus = "" for transaction_details in payment.transactions: transaction_amount = {"currency" :transaction_details.amount.currency ,"total" :transaction_details.amount.total} sales_link = transaction_details['related_resources'][0]['sale']['links'][0]['href'] sales_list = sales_link.split('sale')[1] sales_id = sales_list.split('/')[1] soj_transaction_id = int(transaction_details.custom) transactionstatus = transaction_details.state transactions.append(transaction_amount) payment_details = {"payment" :payment.id ,"sales_id" :sales_id ,"paymenttype" :payment.payer.payment_method ,"state" :payment.state ,"transaction_details" :transactions} if (payment.state == "approved"): print (soj_transaction_id) TransactionTrack.update({ "transactionid" : soj_transaction_id} ,{"$set" :{ "transactionstatus" : transactionstatus, "transactionresponse" : payment_details, "responsedatetime" : datetime.now()}}) transactions_details_from_database = TransactionTrack.find_one({"transactionid" :soj_transaction_id} ,{"_id" :0}) print (transactions_details_from_database) bidid = transactions_details_from_database['jobbid'] jobid = transactions_details_from_database['jobid'] finalBid = JobBids.find_one({"bidid" : int(bidid)} ,{"_id" :0}) completionremarks = "" completionstatus = "" bidcanceldatetime = "" bidcancellationreason = "" bidselected = False if finalBid is not None: jobCollection = Jobs.find_one({"jobid" :finalBid['jobid']} ,{"_id" :0}) if jobCollection is not None: person_selected = jobCollection['personsselected'] if person_selected is None : person_selected = 0 else: person_selected = int(person_selected) userJobberCollection = User.find_one({"userid" :jobCollection['creatinguserid']} ,{"_id" :0}) if userJobberCollection is not None: jobberfullname = userJobberCollection['firstname' ] +" " +userJobberCollection['lastname'] jobberEmail = userJobberCollection['email'] jobberMobile = userJobberCollection['mobile'] else: jobberfullname = "" jobberEmail = None jobberMobile = None userbidderCollection = User.find_one({"userid" :finalBid['userid']} ,{"_id" :0}) if userbidderCollection is not None: bidderfullname = userbidderCollection['firstname' ] +" " +userbidderCollection['lastname'] bidderEmail = userbidderCollection['email'] bidderMobile = userbidderCollection['mobile'] else: bidderfullname = "" bidderEmail = None bidderMobile = None else: print ("No jobs") if request.json['status'] == "selectedbyjobber" : if finalBid['status'] == "pending": print (transaction_amount) JobBids.update({"bidid" :int(bidid)} ,{ "$set" : { "selected" : True, "finalbidamount" : int(float(transaction_amount['total'])), "bidcanceldatetime" : bidcanceldatetime, "bidcancellationreason" : bidcancellationreason, "status" : "selectedbyjobber", "completionstatus" : "pending", "completionremarks" : completionremarks }}) if (jobCollection['personsrequired'] > person_selected ): if (jobCollection['personsrequired'] == person_selected +1 ): Jobs.update({"jobid" :int(jobid)} ,{"$set" :{ "personsselected" : int(person_selected +1), "jobstatus" : "allotted" }}) else: Jobs.update({"jobid" :int(jobid)} ,{"$set" :{ "personsselected" : int(person_selected +1) }}) Totalbidamount = float(finalBid['bidamount']) commission = float(Totalbidamount * 0.1) finalbidamount = float(Totalbidamount - commission) Ledgers.insert({"userid" : userid, "ledgerid" : CommonUtils.generateRandomNo(Ledgers ,"ledgerid"), "amount" : float(Totalbidamount ) *(-1), "datetime" : datetime.now(), "type" : "ESCROW", "jobid" : int(jobid), "jobbidid" : int(bidid), "paymentdetailsJSON" : payment_details, "refunddetailsJSON" : "", "refundcompletiondatetime" : "", "payingdatetime": "", "remark" : "", "active" : True}) Ledgers.insert({"userid" : userid, "ledgerid" : CommonUtils.generateRandomNo(Ledgers ,"ledgerid"), "amount" : float(commission), "datetime" : datetime.now(), "type" : "COMMISSION", "jobid" : int(jobid), "jobbidid" : int(bidid), "paymentdetailsJSON" : "", "refunddetailsJSON" : "", "refundcompletiondatetime" : "", "payingdatetime": "", "remark" : "", "active" : True}) Ledgers.insert({"userid" : finalBid['userid'], "ledgerid" : CommonUtils.generateRandomNo(Ledgers ,"ledgerid"), "amount" : float(finalbidamount), "datetime" : datetime.now(), "type" : "PAID", "jobid" : int(jobid), "jobbidid" : int(bidid), "paymentdetailsJSON" : "", "refunddetailsJSON" : "", "refundcompletiondatetime" : "", "payingdatetime": "", "remark" : "", "active" : True}) notificationtext = "Your Bid on job title ' " +jobCollection['title' ] +"' is accepted by Jobber : " +jobberfullname registration_id = find_FCM_id(finalBid['userid']) if(registration_id): data_message = { "body" : notificationtext, } result = push_service.notify_single_device(registration_id=registration_id, message_title="Bid Accepted" ,message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY") Notifications.insert({"notificationid" :CommonUtils.generateRandomNo(Notifications ,"notificationid"), "notificationtext" :notificationtext, "notificationtype" :"Bid", "notificationtouserid" :int(finalBid['userid']), "notificationfromuserid" :userid, "jobid" : int(jobid), "jobbidid" : int(bidid), "commentid" :-1, "createddatetime" :datetime.now(), "updatedatetime" :datetime.now(), "isread" :False }) if bidderEmail is not None: subject = "Bid Accepted." msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[bidderEmail]) msg.html = render_template('/emailTemplates/Accept-bid.html', name= bidderfullname, title= jobCollection['title'] ,jobber=jobberfullname, amount=int(float(transaction_amount['total']))) Mail.send(msg) EmailTracks.insert({"emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": finalBid['userid'], "email": bidderEmail, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now()}) else: print "No email of bidder." elif request.json['status'] == "reversebid": job_bid_detail = JobBids.find_one({"bidid": int(bidid)}, {"_id": 0}) if job_bid_detail is not None: if job_bid_detail['status'] == 'pending': Totalbidamount = int(float(transaction_amount['total'])) # updating bidamount array and reverse bid array reverseBidData = {"reversebidamount": int(float(transaction_amount['total'])), "reversebiddatetime": datetime.now()} JobBids.update({"bidid": int(bidid)}, {"$set": {"status": "reversebid", "reversebid": reverseBidData, "finalbidamount": Totalbidamount }}) commission = float(Totalbidamount * 0.1) finalbidamount = float(Totalbidamount - commission) Ledgers.insert({"userid": userid, "ledgerid": CommonUtils.generateRandomNo(Ledgers, "ledgerid"), "amount": float(Totalbidamount) * (-1), "datetime": datetime.now(), "type": "ESCROW", "jobid": int(jobid), "jobbidid": int(bidid), "paymentdetailsJSON": payment_details, "refunddetailsJSON": "", "refundcompletiondatetime": "", "payingdatetime": "", "remark": "", "active": True}) Ledgers.insert({"userid": userid, "ledgerid": CommonUtils.generateRandomNo(Ledgers, "ledgerid"), "amount": float(commission), "datetime": datetime.now(), "type": "COMMISSION", "jobid": int(jobid), "jobbidid": int(bidid), "paymentdetailsJSON": "", "refunddetailsJSON": "", "refundcompletiondatetime": "", "payingdatetime": "", "remark": "", "active": True}) Ledgers.insert({"userid": finalBid['userid'], "ledgerid": CommonUtils.generateRandomNo(Ledgers, "ledgerid"), "amount": float(finalbidamount), "datetime": datetime.now(), "type": "PAID", "jobid": int(jobid), "jobbidid": int(bidid), "paymentdetailsJSON": "", "refunddetailsJSON": "", "refundcompletiondatetime": "", "payingdatetime": "", "remark": "", "active": True}) notificationtext = "You reverse bid on the job title " + jobCollection[ 'title'] + " for bidder : " + str(bidderfullname) registration_id = find_FCM_id(job_bid_detail['userid']) if (registration_id): data_message = { "body": notificationtext, } result = push_service.notify_single_device(registration_id=registration_id, message_title="Reverse Bid", message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY") Notifications.insert({"notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Bid", "notificationtouserid": int(job_bid_detail['userid']), "notificationfromuserid": userid, "jobid": int(jobid), "jobbidid": int(bidid), "commentid": -1, "createddatetime": datetime.now(), "updatedatetime": datetime.now(), "isread": False }) if bidderEmail is not None: subject = "Reverse Bid on Job." msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[bidderEmail]) msg.html = render_template('/emailTemplates/reverse-bid.html', name=bidderfullname, title=jobCollection['title'], jobber=jobberfullname, amount=int(float(transaction_amount['total']))) Mail.send(msg) EmailTracks.insert({"emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": finalBid['userid'], "email": bidderEmail, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now()}) else: print("No email of bidder.") return jsonify({"status": 200, "message": "Payment Successful"}) except ResourceNotFound as e: # It will through ResourceNotFound exception if the payment not found print("Payment Not Found") print(e.message) return jsonify({"status": 500, "message": e.message})
def invoice_list(): userid = int(request.json['userid']) token = request.json['token'] invoiceid = request.json['invoiceid'] if invoiceid == 1: invoiceData = list( Invoice.find({"invoiceid": int(request.json['invoiceid'])}, {"_id": 0})) else: invoiceData = list(Invoice.find({"userid": userid}, {"_id": 0})) invoiceAllData = {} invoiceArray = [] if len(invoiceData) > 0: for invoiceDataArray in invoiceData: # jobsDetail Data jobsDetail = Jobs.find_one( { "jobid": int(invoiceDataArray['jobid']), "active": True }, {"_id": 0}) # Job Created By User createdUserDetail = User.find_one( { "userid": jobsDetail['creatinguserid'], "active": True }, {"_id": 0}) # For job Bid and Comments (How many user bid on this job.) job_biding_count = JobBids.find( { "jobid": invoiceDataArray['jobid'] }, { "_id": 0 }).count() job_comment_count = JobComments.find( { "jobid": invoiceDataArray['jobid'] }, { "_id": 0 }).count() # For User who post this job (How many jobs bid by this user.) if createdUserDetail is not None: user_biding_count = JobBids.find( { "userid": createdUserDetail['userid'] }, { "_id": 0 }).count() user_comment_count = JobComments.find( { "userid": createdUserDetail['userid'] }, { "_id": 0 }).count() # Address Detail for created User citydetail = CityCollections.find_one( {"cityid": createdUserDetail['addressJSON']['city']}, {"_id": 0}) statedetail = StateCollections.find_one( {"stateid": citydetail['stateid']}, {"_id": 0}) countrydetail = CountryCollections.find_one( {"countryid": citydetail['countryid']}, {"_id": 0}) address2 = createdUserDetail['addressJSON']['address2'] address1 = createdUserDetail['addressJSON']['address1'] if address2 == "": fullAddress = address1 + "," else: fullAddress = address1 + ", " + address2 + "," else: fullAddress = "" user_biding_count = 0 user_comment_count = 0 # Billing to User billingUserDetail = User.find_one( { "userid": invoiceDataArray['userid'], "active": True }, {"_id": 0}) # Address Detail for created User billingcitydetail = CountryCollections.find_one( {"cityid": billingUserDetail['addressJSON']['city']}, {"_id": 0}) billingstatedetail = StateCollections.find_one( {"stateid": billingcitydetail['stateid']}, {"_id": 0}) billingcountrydetail = CountryCollections.find_one( {"countryid": billingcitydetail['countryid']}, {"_id": 0}) billingaddress2 = billingUserDetail['addressJSON']['address2'] billingaddress1 = billingUserDetail['addressJSON']['address1'] if billingaddress2 == "": billingfullAddress = billingaddress1 + "," else: billingfullAddress = billingaddress1 + ", " + billingaddress2 + "," createdInfoCollection = { "createdByuserid": createdUserDetail['userid'], "createdByaddressJSON": createdUserDetail['addressJSON'], "createdByemail": createdUserDetail['email'], "createdByfirstname": createdUserDetail['firstname'], "createdBylastname": createdUserDetail['lastname'], "createdBymobile": createdUserDetail['mobile'], "createdByaddress": fullAddress, "createdBycity": citydetail['city'], "createdBystate": statedetail['state'], "createdBycountry": countrydetail['country'], "createdBypincode": createdUserDetail['addressJSON']['pincode'], "createdByactive": createdUserDetail['active'], "createdByuser_biding_count": user_biding_count, "createdByuser_comment_count": user_comment_count, "job_biding_count": job_biding_count, "user_comment_count": user_comment_count, "jobsDetail": jobsDetail, "billinguserid": billingUserDetail['userid'], "billingaddressJSON": billingUserDetail['addressJSON'], "billingemail": billingUserDetail['email'], "billingfirstname": billingUserDetail['firstname'], "billinglastname": billingUserDetail['lastname'], "billingmobile": billingUserDetail['mobile'], "billingaddress": billingfullAddress, "billingcity": billingcitydetail['city'], "billingstate": billingstatedetail['state'], "billingcountry": billingcountrydetail['country'], "billingpincode": billingUserDetail['addressJSON']['pincode'], "billingactive": billingUserDetail['active'], } invoiceDataArray.update(createdInfoCollection) invoiceArray.append(invoiceDataArray) return jsonify({ "status": 200, "message": "Invoice List.", "invoiceAllData": invoiceArray }) else: return jsonify({ "status": 200, "message": "No Data.", "invoiceAllData": invoiceArray })
def job_bid_create(): userid = request.json['userid'] userInfo = User.find_one({"userid": int(userid)}, {"_id": 0}) if userInfo is not None: if userInfo['emailverified'] is False: return jsonify({ "status": 202, "message": "Email not verified. Please verify your email to bid" }) jobCollection = Jobs.find_one( { "jobid": int(request.json['jobid']), "active": True }, {"_id": 0}) #if jobCollection['personsselected'] >= jobCollection['personsrequired']: # return jsonify({"status": 203, "message": "Jobber's requirement has already been fulfilled"}) jobberUser = User.find_one({"userid": jobCollection['creatinguserid']}, {"_id": 0}) userCollection = User.find_one({"userid": userid}, {"_id": 0}) if userCollection is not None: fullname = userCollection['firstname'] + " " + userCollection[ 'lastname'] bidderEmail = userCollection['email'] else: fullname = "" bidderEmail = None if jobberUser is not None: jobberfullname = jobberUser['firstname'] + " " + jobberUser['lastname'] jobberEmail = jobberUser['email'] else: jobberfullname = None jobberEmail = None if jobCollection is not None: if request.json['bidid'] == "": check_status = JobBids.find( { "jobid": int(request.json['jobid']), "userid": userid, "active": True }, {"_id": 0}) if check_status.count() == 0: reverseBidData = { "reversebidamount": None, "reversebiddatetime": None } bidid = CommonUtils.generateRandomNo(JobBids, "bidid") JobBids.insert({ "jobid": int(request.json['jobid']), "bidid": bidid, "userid": userid, "selected": False, "bidamount": float(request.json['bidamount']), "finalbidamount": None, "bidcomment": request.json['bidcomment'], "createdatetime": datetime.now(), "bidcanceldatetime": "", "bidcancellationreason": "", "status": "pending", "reversebid": reverseBidData, "completionstatus": "pending", "completionremarks": "", "active": True }) notificationtext = "Your job title " + jobCollection[ 'title'] + " is bid by : " + fullname '''registration_id = find_FCM_id(jobCollection['creatinguserid']) if (registration_id): data_message = { "body": notificationtext, } result = push_service.notify_single_device(registration_id=registration_id, message_title="New Bid", message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY")''' Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Bid", "notificationtouserid": int(jobCollection['creatinguserid']), "notificationfromuserid": userid, "jobid": jobCollection['jobid'], "bidid": bidid, "commentid": -1, "createddatetime": datetime.now(), "updatedatetime": datetime.now(), "isread": False }) ''' # Sending Email if jobberEmail is not None: subject = "Bid Created." msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[jobberEmail]) msg.html = render_template('/emailTemplates/bid-receive.html', name=jobberfullname, title=str(jobCollection['title']), bidder=fullname, amount=int(request.json['bidamount'])) mail.send(msg) emailtracks.insert({"emailtrackid": generateRandomNo(emailtracks, "emailtrackid"), "userid": int(jobCollection['creatinguserid']), "email": jobberEmail, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now()}) else: print "No email of jobber." ''' new_bid = list(JobBids.find({"bidid": bidid}, {"_id": 0})) return jsonify({ "status": 200, "message": "Successfully created.", "response": new_bid, "error": False }) else: new_bid = list( JobBids.find({"bidid": check_status['bidid']}, {"_id": 0})) return jsonify({ "status": 200, "message": "bid status intercepted.", "bidUpdate": new_bid }) else: job_bid_detail = JobBids.find_one( {"bidid": int(request.json['bidid'])}, {"_id": 0}) if job_bid_detail is not None: if job_bid_detail['status'] == 'pending': finalbidamount = float(request.json['reversebid']) # updating bidamount array and reverse bid array reverseBidData = { "reversebidamount": request.json['reversebid'], "reversebiddatetime": datetime.now() } JobBids.update({"bidid": int(request.json['bidid'])}, { "$set": { "status": "reversebid", "bidcomment": request.json['bidcomment'], "reversebid": reverseBidData, "finalbidamount": finalbidamount } }) commission = float(finalbidamount * 0.1) finalbidamount = float(finalbidamount - commission) Ledgers.insert({ "userid": userid, "ledgerid": CommonUtils.generateRandomNo(Ledgers, "ledgerid"), "amount": float(finalbidamount), "datetime": datetime.now(), "type": "escrow", "jobid": int(jobCollection['jobid']), "paymentdetailsJSON": "", "refundinitateddatetime": "", "refunddetailsJSON": "", "refundcompletiondatetime": "", "payingdatetime": "", "remark": "", "active": True }) Ledgers.insert({ "userid": userid, "ledgerid": CommonUtils.generateRandomNo(Ledgers, "ledgerid"), "amount": float(commission), "datetime": datetime.now(), "type": "commission", "jobid": int(jobCollection['jobid']), "paymentdetailsJSON": datetime.now(), "refundinitateddatetime": "", "refunddetailsJSON": "", "refundcompletiondatetime": "", "active": True }) notificationtext = "Jobber reverse bid on the job title " + jobCollection[ 'title'] + " for bidder : " + fullname '''registration_id = find_FCM_id(job_bid_detail['userid']) if (registration_id): data_message = { "body": notificationtext, } result = push_service.notify_single_device(registration_id=registration_id, message_title="Reverse Bid", message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY")''' Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Bid", "notificationtouserid": int(job_bid_detail['userid']), "notificationfromuserid": userid, "jobid": jobCollection['jobid'], "bidid": int(request.json['bidid']), "commentid": -1, "createddatetime": datetime.now(), "updatedatetime": datetime.now(), "isread": False }) ''' if bidderEmail is not None: subject = "Reverse Bid on Job." msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[bidderEmail]) msg.html = render_template('/emailTemplates/reverse-bid.html', name=bidderfullname, title=jobCollection['title'], jobber=jobberfullname, amount=int(request.form['payment'])) mail.send(msg) emailtracks.insert({"emailtrackid": generateRandomNo(emailtracks, "emailtrackid"), "userid": finalBid['userid'], "email": bidderEmail, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now()}) else: print "No email of bidder." ''' update_bid = list( JobBids.find({"bidid": int(request.json['bidid'])}, {"_id": 0})) return jsonify({ "status": 200, "message": "Bid Successfully set.", "response": update_bid, "error": False }) else: update_bid = list( JobBids.find({"bidid": int(request.json['bidid'])}, {"_id": 0})) return jsonify({ "status": 200, "message": "bid update", "Response": update_bid, "error": False }) else: return jsonify({ "status": 200, "message": "Bid not found.", "response": [], "error": True }) else: return jsonify({ "status": 402, "message": "Job Not Found.", "response": [], "error": True })
def notification_list(): URL = Constants.URL imagePath = Constants.IMAGE_PATH userid = int(request.json['userid']) token = request.json['token'] notificationArray = [] notificationData = list( Notifications.find({ "notificationtouserid": userid }, { "_id": 0 }).sort("createddatetime", -1)) notificationUnread = list( Notifications.find({ "notificationtouserid": userid, "isread": False }, {"_id": 0})) print(notificationData) if len(notificationData) > 0: for collections in notificationData: jobber = {} if collections['notificationfromuserid'] != -1: jobber = Jobs.find_one({"jobid": int(collections['jobid'])}, { "_id": 0, "creatinguserid": 1 }) userData = User.find_one( {"userid": int(collections['notificationfromuserid'])}, {"_id": 0}) if userData is not None: fullname = userData['firstname'] + " " + userData[ 'lastname'] if userData['picurl'] != "": picurl = URL + imagePath + userData['picurl'] else: picurl = URL + imagePath + "user-no-image.jpg" if userData['addressJSON']['city'] != "": cityNamedata = CityCollections.find_one( {"cityid": userData['addressJSON']['city']}, { "_id": 0, "city": 1 }) cityName = cityNamedata['city'] else: cityName = "" else: fullname = "" picurl = URL + imagePath + "user-no-image.jpg" cityName = "" else: fullname = "SAVEonJOBS" picurl = URL + "static/front_end/images/logo1.png" cityName = "" userDataCollection = { "fullname": fullname, "cityname": cityName, "picurl": picurl, "jobber": jobber } collections.update(userDataCollection) notificationArray.append(collections) return jsonify({ "status": 200, "message": "Notification Data.", "notificationArray": notificationArray, "notificationUnread": len(notificationUnread) }) else: return jsonify({ "status": 200, "message": "No Notification data Found.", "notificationArray": [], "notificationUnread": notificationUnread })
def user_dashboard(): URL = Constants.URL imagePath = Constants.IMAGE_PATH try: dashboardData = {} userid = int(request.json['userid']) userdata_array = User.find_one({ "userid": userid, "active": True }, {"_id": 0}) if userdata_array is not None: # Account Percentage if userdata_array['paymentdetailsJSON']['bankaccountname'] != "": overallAccountPercentage = 100 else: overallAccountPercentage = 0 verifyLen = len(userdata_array['proJSON']) - 1 countVerificationPercentage = 0 if userdata_array['proJSON']['facebookapproved'] == True: countVerificationPercentage = countVerificationPercentage + 1 if userdata_array['proJSON']['policeverification'] == True: countVerificationPercentage = countVerificationPercentage + 1 if userdata_array['proJSON'][ 'professionalcertificationverified'] == True: countVerificationPercentage = countVerificationPercentage + 1 if userdata_array['proJSON']['mobileverified'] == True: countVerificationPercentage = countVerificationPercentage + 1 if countVerificationPercentage != 0: countVerificationPercentage = int(countVerificationPercentage * 100) overallVerificationPercentage = float( countVerificationPercentage / verifyLen) else: overallVerificationPercentage = 0 # Skills Verfication skillsLen = 5 countSkillsPercentage = len(userdata_array['skillsJSON']) if countSkillsPercentage != 0: if countSkillsPercentage < skillsLen: countSkillsPercentage = countSkillsPercentage * 100 overallSkillsPercentage = float(countSkillsPercentage / skillsLen) else: overallSkillsPercentage = 100 else: overallSkillsPercentage = 0 # Profile Verification profileLen = 13 countProfilePercentage = 0 if userdata_array['addressJSON']['city'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['addressJSON']['state'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['addressJSON']['country'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['addressJSON']['state'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['addressJSON']['country'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['addressJSON']['state'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['addressJSON']['country'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['firstname'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['lastname'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['locationid'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['email'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['mobile'] != "": countProfilePercentage = countProfilePercentage + 1 if userdata_array['aboutme'] != "": countProfilePercentage = countProfilePercentage + 1 if countProfilePercentage != 0: countProfilePercentage = countProfilePercentage * 100 countProfilePercentage = float(countProfilePercentage / profileLen) else: countProfilePercentage = 0 # Jobs Percentage jobs_posted = Jobs.find({"creatinguserid": int(userid)}).count() jobs_completed = JobBids.find({ "userid": int(userid), "status": "completed" }).count() # Payment percentage total_received_amount = 0 total_paid_refund = 0 total_commission_refund = 0 earned_amount = 0 paid_amount = 0 total_earning_amount = 0 total_received_list = Ledgers.find( { "userid": userid, "type": "ESCROW" }, {"_id": 0}) if total_received_list is not None: for total_received_dict in total_received_list: total_received_amount += total_received_dict['amount'] total_paid_refund_list = Ledgers.find( { "userid": userid, "type": "REFUND" }, {"_id": 0}) if total_paid_refund_list is not None: for total_paid_refund_dict in total_paid_refund_list: total_paid_refund += total_paid_refund_dict['amount'] paid_amount = (total_received_amount - total_paid_refund) * (-1) total_earning_list = Ledgers.find( { "userid": userid, "type": "PAID OUT" }, {"_id": 0}) if total_earning_list is not None: for total_earning_dict in total_earning_list: total_earning_amount += total_earning_dict['amount'] earned_amount = total_earning_amount # overall Percentage overallPercentage = float \ (overallAccountPercentage + overallVerificationPercentage + overallSkillsPercentage + countProfilePercentage) overallPercentage = float(overallPercentage / 4) print(overallPercentage) fullname = userdata_array['firstname'] + ' ' + userdata_array[ 'lastname'] picurl = URL + imagePath + userdata_array['picurl'] dashboardData = { "picurl": picurl, "jobsPosted": jobs_posted, "jobsCompleted": jobs_completed, "earnedAmount": earned_amount, "paidAmount": paid_amount, "overallPercentage": overallPercentage, "accountPercentage": overallAccountPercentage, "verificationPercentage": overallVerificationPercentage, "skillsPercentage": overallSkillsPercentage, "profilePercentage": countProfilePercentage, "fullname": fullname } return jsonify({ 'status': 200, 'message': 'Dashboard Data.', 'dashboardData': dashboardData }) else: return jsonify({ 'status': 402, 'message': 'No data fouund', 'dashboardData': dashboardData }) except Exception as e: return jsonify({"status": 500, "message": "error"})