Esempio n. 1
0
def bank_update():
    try:
        userid = int(request.json['userid'])

        user_details = User.find_one({"userid": userid}, {"_id": 0})
        bank_details = []
        if user_details:
            User.update({"userid": userid},
                        {"$set": {
                            "paypal_id": request.json['paypal_id']
                        }})

            bank_details = User.find_one({"userid": userid}, {
                "_id": 0,
                "paypal_id": 1
            })

        return make_response(
            jsonify({
                "status": 402,
                "message": "User not Connected",
                "bank_details": bank_details
            }), 200)

    except Exception as e:
        return make_response(
            jsonify({
                "status": 500,
                "message": "Something went wrong, Please try again!"
            }), 500)
Esempio n. 2
0
def userlogin():
    try:
        email = request.json['email']
        password = request.json['password']

        if email is not None and password is not None:
            salt = ""
            userdata = User.find_one({
                "signupJSON.email": email,
                "isadmin": False,
                "active": True
            })
            print(userdata)
            # if userData.count == 0 :
            # 	userdata = user.find_one({"signupJSON.mobile":int(email),"isadmin":False,"active":True})
            if userdata is not None:
                salt = userdata['salt']
                password = hashlib.md5(password.strip()).hexdigest() + salt
                print(password)
                result = User.find_one({"email": email, "password": password})
                if result is not None:
                    fullname = result['firstname'] + "  " + result['lastname']
                    session['cookiesUserid'] = int(result['userid'])
                    session['userValid'] = result['salt']
                    session['cookiesToken'] = str(result['token'])
                    session['city'] = str(result['addressJSON']['city'])
                    session['userloginName'] = fullname
                    session['location'] = str(result['locationid'])
                    session.permanent = True
                    print(session)
                    picPath = URL + imagePath
                    print(request.cookies)
                    return jsonify({
                        'status': 200,
                        'message': 'success',
                        'userid': result['userid'],
                        'token': result['token'],
                        'city': result['addressJSON']['city'],
                        'location': result['locationid'],
                        "firstname": result['firstname'],
                        "lastname": result['lastname'],
                        "picurl": result['picurl'],
                        "picPath": picPath
                    })
                else:
                    return jsonify({
                        'status': 201,
                        'message': 'Invalid username and Password.'
                    })
            else:
                return jsonify({'status': 202, 'message': 'Invalid username.'})
        else:
            return jsonify({
                'status': 203,
                'message': "Email or Password not be null."
            })

    except Exception as e:
        return jsonify({"status": 500, "message": "error"})
Esempio n. 3
0
def verify_email():

    #Check authentications keys
    userid = int(request.json['userid'])
    token = request.json['token']

    email = request.json['email']
    findUser = User.find_one({"userid" : userid, "token": token, "email":request.json['email'], "active":True})
    if findUser is not None:
        emailhash = CommonUtils.getHashValue()
        result = User.update({	"userid" : userid, "token": token, "email":request.json['email']},{"$set":{
                                                                                                            "emailhash": emailhash
                                                                                                        }})
        # Send email verification
        reset_password_link = str(URL)+"emailverify/"+str(emailhash)

        subject = "Your SAVEonJOBS.comAccount Email Verification"
        msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[email])
        msg.html = render_template('/emailTemplates/email_verification_template.html', name= findUser['firstname'], resetLink= reset_password_link ,email=email)
        mail.send(msg)
        EmailTracks.insert({"emailtrackid":CommonUtils.generateRandomNo(EmailTracks,"emailtrackid"),"userid":userid , "email":request.json['email'] , "subject":subject ,"emailtext":msg.html ,"createdatetime":datetime.now(),"updatedatetime":datetime.now()})

        return jsonify({'status':200 , 'message' : 'Send Successfully.'})
    else:
        return jsonify({'status':201 , 'message' : "Email doesn't match."})

    #Check authentications keys
    userid = int(request.json['userid'])
    token = request.json['token']

    email = request.json['email']
    findUser = User.find_one({"userid" : userid, "token": token, "email":request.json['email'], "active":True})
    if findUser is not None:
        emailhash = CommonUtils.getHashValue()
        result = User.update({	"userid" : userid, "token": token, "email":request.json['email']},{"$set":{
                                                                                                            "emailhash": emailhash
                                                                                                        }})
        # Send email verification
        reset_password_link = str(URL)+"emailverify__"+str(emailhash)

        subject = "Your jobwork Account Email Verification"
        msg = Message(subject, sender=("Jobwork", "*****@*****.**"), recipients=[email])
        msg.html = render_template('/emailTemplates/email_verification_template.html', name= findUser['firstname'], resetLink= reset_password_link ,email=email)
        mail.send(msg)
        EmailTracks.insert({"emailtrackid":CommonUtils.generateRandomNo(EmailTracks,"emailtrackid"),"userid":userid , "email":request.json['email'] , "subject":subject ,"emailtext":msg.html ,"createdatetime":datetime.now(),"updatedatetime":datetime.now()})

        return jsonify({'status':200 , 'message' : 'Send Successfully.'})
    else:
        return jsonify({'status':201 , 'message' : "Email doesn't match."})
Esempio n. 4
0
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
        })
Esempio n. 5
0
def reportuser():
    userid = int(request.json['userid'])
    token = request.json['token']
    touserid = int(request.json['touserid'])

    userreportedJSON = []

    if (userid != None) and (token != None) and (touserid != None):
        userData = User.find_one({"userid": touserid}, {"_id": 0})
        if userData is not None:
            userreportedJSON = userreportedJSON + userData['reportedJSON']
            newReportedJSON = {
                "reportid": CommonUtils.generateRandomNo(Report, "reportid"),
                "byuserid": userid,
                "reportresolved": False,
                "reporteddatetime": datetime.now(),
                "reportresolveddatetime": -1,
                "active": True
            }
            userreportedJSON.append(newReportedJSON)
            User.update({"userid": touserid},
                        {"$set": {
                            "reportedJSON": userreportedJSON
                        }})

        return jsonify({
            "status": 200,
            "message": "Successfully Report Created."
        })
    else:
        return jsonify({"status": 400, "message": "No data Recevied"})
Esempio n. 6
0
def change_password():
    try:
        userid = int(request.json['userid'])
        token = request.json['token']
        password = request.json['password']

        userdata = User.find_one({
            "userid": userid,
            "active": True
        }, {"_id": 0})
        if userdata is not None:
            salt = userdata['salt']
            if request.json['password'].strip() != "":
                password = hashlib.md5(
                    request.json['password'].strip()).hexdigest() + salt

            User.update({"userid": userid}, {"$set": {"password": password}})

            return jsonify({
                "status": 200,
                "message": "Password Successfully changed."
            })
        else:
            return jsonify({"status": 202, "message": "No user is found."})
    except Exception as e:
        return jsonify({"status": 500, "message": e.message})
Esempio n. 7
0
def emailverifyhash(hashvalue):
    getuserdata = User.find_one({"emailhash" : hashvalue, "emailverified" :False}, {"_id" :0})
    if getuserdata is not None:
        User.update({"emailhash" : hashvalue} ,{"$set" :{"emailverified" :True, "updateddatetime" : datetime.now()}})
        return render_template("sample.html")
    else:
        return jsonify({"status" :200 ,"message" :"Email already Verified."})
Esempio n. 8
0
def delUser():
    email = request.json['email']

    result = User.find_one({"email": email})
    if result is not None:
        db.user.remove({"email": email})
        return jsonify({"status": 200, "msg": "account deleted!"})
    else:
        return jsonify({"status": 201, "msg": "not found!"})
Esempio n. 9
0
def verify_mobile_otp():
    userid = int(request.json['userid'])
    token = request.json['token']
    findUser = User.find_one({
        "userid": userid,
        "token": token,
        "mobile": str(request.json['mobile']),
        "mobileotp": int(request.json['mobileotp']),
        "isdcode": int(request.json['isdcode']),
        "mobileverified": False,
        "active": True
    })
    if findUser is not None:
        result = User.update(
            {
                "userid": userid,
                "token": token,
                "mobile": str(request.json['mobile'])
            },
            {"$set": {
                "mobileverified": True,
                "proJSON.mobileverified": True
            }})
        sendText = "Your Mobile Number is registered to SAVEonJOBS."
        full_mobile_number = "+" + str(request.json['isdcode']) + str(
            request.json['mobile'])
        message = msgclient.messages.create(body=sendText,
                                            to=full_mobile_number,
                                            from_=Constants.MSG_SEND_FROM)
        print(message.sid)
        MessageTracks.insert({
            "messagetrackid":
            CommonUtils.generateRandomNo(MessageTracks, "messagetrackid"),
            "userid":
            userid,
            "mobile":
            full_mobile_number,
            "messagetext":
            sendText,
            "messagesid":
            message.sid,
            "createdatetime":
            datetime.now(),
            "updatedatetime":
            datetime.now()
        })
        userdata = list(User.find({"userid": userid}, {"_id": 0}))
        return jsonify({
            'status': 200,
            'message': 'Verify Successfully.',
            "userdata": userdata
        })
    else:
        return jsonify({
            'status': 201,
            'message': "OTP and Mobile Number doesn't match."
        })
Esempio n. 10
0
def find_FCM_id(userid):
    try:
        result = User.find_one({"userid": int(userid)})
        if "device_token" in result:
            return result['device_token']
        else:
            return False
    except Exception as e:
        raise e
Esempio n. 11
0
 def decorated_function(*args, **kwargs):
     if request.json.get('userid', False) == False or request.json.get('token', False) == False:
         return make_response(jsonify({"status": 400, "message": "1 Authentication keys are missing."}), 400)
     userid = int(request.json['userid'])
     token = request.json['token']
     result = User.find_one({"userid": int(userid), "token": str(token)})
     if not result:
         return make_response(jsonify({"status": 401, "message": " No mach found.","error":True,"response":[]}), 401)
     else:
         return f(*args, **kwargs)
Esempio n. 12
0
def emailverifyhash(hashvalue):
    getuserdata = User.find_one(
        {
            "emailhash": hashvalue,
            "emailverified": False
        }, {"_id": 0})
    if getuserdata is not None:
        User.update({"emailhash": hashvalue}, {
            "$set": {
                "emailverified": True,
                "updateddatetime": datetime.now()
            }
        })
        # userid = getuserdata['userid']
        # token = getuserdata['token']
        return render_template("front_saveonjobs/email_verify.html")
    else:
        return jsonify({"status": 200, "message": "Email already Verified."})
Esempio n. 13
0
def user_forgotpassword_email():
    try:
        email = request.json['email']
        if email is not None:
            getuserdata = User.find_one({"email": email, "active": True}, {"_id": 0})

            # data = user.find_one({"$or" : {"email" : email},{"mobile" : mobile}})
            addforgotpasswordJSON = []
            if getuserdata is not None:
                oldJSON = getuserdata['forgotpasswordJSON']
                forgotpassworduseddatetime = -1
                forgopassworddatetime = datetime.now()
                forgotpasswordhash = CommonUtils.getHashValue()
                addforgotpasswordJSON = addforgotpasswordJSON + oldJSON
                addforgotpasswordJSON.append({"forgopassworddatetime": forgopassworddatetime,
                                              "forgotpasswordhash": forgotpasswordhash,
                                              "forgotpassworduseddatetime": forgotpassworduseddatetime
                                              })
                User.update({"email": email}, {"$set": {"forgotpasswordJSON": addforgotpasswordJSON}})

                reset_password_link = str(URL) + "forgotpassword__" + str(forgotpasswordhash)

                subject = "Your SAVEonJOBS Password"
                msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[email])
                msg.html = render_template('/emailTemplates/Reset_password_template.html',
                                           name=getuserdata['firstname'], resetLink=reset_password_link)

                mail.send(msg)
                EmailTracks.insert(
                    {"emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": getuserdata['userid'],
                     "email": email, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(),
                     "updatedatetime": datetime.now()})
                return jsonify({"status": 200, "message": "Successfully mail sent."})
            else:
                return jsonify({"status": 200, "message": "No data."})
        else:
            return jsonify({"status": 200, "message": "email not found."})

    except Exception as e:
        print(e)
        return jsonify({"status": 500, "message": "error"})
Esempio n. 14
0
def bank_fetch():
    try:
        userid = int(request.json['userid'])
        response = User.find_one({"userid": userid}, {
            "_id": 0,
            "paypal_id": 1
        })
        # response = User.find_one({"userid": userid}, {"_id": 0})
        return make_response(
            jsonify({
                "bank_details": response,
                "status": 200
            }), 200)

    except Exception as e:
        print(e)
        return make_response(
            jsonify({
                "status": 500,
                "message": "Something went wrong, Please try again!"
            }), 500)
Esempio n. 15
0
def get_or_create_user(user_data, user_type, facebook_token):
    email = user_data.get("email", "")
    if email:
        is_user_exists = User.count({"signupJSON.email": email})
        if is_user_exists == 0:
            mobile, mobileotp = "", ""
            # emailhash = send_email(email)
            emailhash = CommonUtils.getHashValue()

            firstname = user_data.get('first_name', "")
            lastname = user_data.get('last_name', "")
            usertype = user_type
            city, location, device_token = "", "", ""
            fullname = user_data.get("name", "")
            password = CommonUtils.generateRandomName()

            if fullname and usertype:

                salt = CommonUtils.generateRandomName()

                # random.randrange(1000, 9999)

                signupJSON = SignupUtils.get_signup_json(email, fbid=user_data.get("id", ""),
                                                         fbaccesstoken=facebook_token)

                addressJSON = SignupUtils.get_user_address_json(city)

                proJSON = SignupUtils.get_pro_json()

                paymentdetailsJSON = SignupUtils.get_payment_detail_json()

                if password:
                    password = CommonUtils.password_hash(password, salt)
                token = request.json.get('token', "")
                userid = request.json.get('userid', "")
                if not userid:
                    userid = CommonUtils.generateRandomNo(User, "userid")
                if not token:
                    token = CommonUtils.generateRandomName()

                User.insert({
                    "userid": userid,
                    "email": email,
                    "mobile": mobile,
                    "mobileotp": str(mobileotp),
                    "emailhash": emailhash,
                    "password": password,
                    "salt": salt,
                    "token": token,
                    "usertype": usertype,
                    "firstname": firstname,
                    "lastname": lastname,
                    "device_token": device_token,
                    "signupJSON": signupJSON,
                    "emailverified": False,
                    "mobileverified": False,
                    "isdcode": None,
                    "fbid": "",
                    "fbaccesstoken": "",
                    "isadmin": False,
                    "createddatetime": datetime.datetime.now(),
                    "updateddatetime": datetime.datetime.now(),
                    "addressJSON": addressJSON,
                    "paymentdetailsJSON": paymentdetailsJSON,
                    "skillsJSON": [],
                    "languagesJSON": [],
                    "educationCSV": [],
                    "workplaceCSV": [],
                    "certificateJSON": [],
                    "proJSON": proJSON,
                    "forgotpasswordJSON": [],
                    "gender": "",
                    "dob": "",
                    "locationid": location,
                    "aboutme": "",
                    "picurl": "user-no-image.jpg",
                    "reportedJSON": [],
                    "notificationJSON": [],
                    "socaillogin": False,
                    "facebookpicurl": "",
                    "active": True,
                    "paypal_id": ""
                })

                session['cookiesUserid'] = int(userid)
                session['userValid'] = str(salt)
                session['cookiesToken'] = str(token)
                session['city'] = str(city)
                session['userloginName'] = str(fullname)
                session['location'] = str(location)
                session.permanent = True

                # Onboard Push notification
                PushNotificationUtils.notify_onboard(userid, fullname, device_token)
                # Onboard Email
                EmailUtils.send_onboard_email(userid, email, emailhash, firstname)

                return {
                    'status': 200,
                    'message': 'Successfull Register',
                    'userid': userid,
                    'token': token,
                    'city': city,
                    'location': location,
                    "firstname": firstname,
                    "lastname": lastname,
                    "picurl": "user-no-image.jpg",
                    "picPath": Constants.PROFIL_PIC_STATIC_PATH
                }
            else:
                return {'status': 400, 'message': 'Data can not be null.'}
        else:
            user = User.find_one({"email": email},
                                 {"_id": 0, "userid": 1, "token": 1, "city": 1, "location": 1, "firstname": 1,
                                  "lastname": 1, "picurl": 1, "picPath": Constants.PROFIL_PIC_STATIC_PATH})
            return {
                'status': 200,
                'message': 'Successfull Register',
            }.update(user)
    else:
        return {'status': 202, 'message': 'Data can not be null.'}
Esempio n. 16
0
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"})
Esempio n. 17
0
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)})
Esempio n. 18
0
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"})
Esempio n. 19
0
def conversations_list():
    userid = int(request.json['userid'])
    token = request.json['token']
    allconversationListData = []
    URL = Constants.URL
    imagePath = Constants.IMAGE_PATH

    conversationData = list(
        Conversations.find(
            {
                "$or": [{
                    "userid1": userid
                }, {
                    "userid2": userid
                }],
                "active": True
            }, {
                "_id": 0
            }).sort("lastdatetime", -1))

    if len(conversationData) > 0:
        for conversationListData in conversationData:
            messageUnreadCount = Messages.find(
                {
                    "conversationid": conversationListData['conversationid'],
                    "isread": False
                }, {
                    "_id": 0
                }).count()
            conversationListData.update(
                {"messageUnreadCount": messageUnreadCount})
            # Users Detail
            userData1 = User.find_one(
                {"userid": int(conversationListData['userid1'])}, {"_id": 0})
            if userData1 is not None:
                fullname1 = userData1['firstname'] + " " + userData1['lastname']
                cityName1 = {}
                if userData1['picurl'] != "":
                    picurl1 = URL + imagePath + userData1['picurl']
                else:
                    picurl1 = URL + imagePath + "user-no-image.jpg"
                if userData1['addressJSON']['city'] != "":
                    cityName1 = CityCollections.find_one(
                        {"cityid": userData1['addressJSON']['city']}, {
                            "_id": 0,
                            "city": 1
                        })
                else:
                    cityName1['city'] = ""
                if conversationListData['userid1'] != userid:
                    lastMessageDetail = {
                        "lastuserfullname": fullname1,
                        "lastusercityname": cityName1['city'],
                        "lastuserpicurl": picurl1
                    }
                    conversationListData.update(lastMessageDetail)
                userDataCollection1 = {
                    "fullname1": fullname1,
                    "cityname1": cityName1['city'],
                    "picurl1": picurl1
                }
                conversationListData.update(userDataCollection1)

            userData2 = User.find_one(
                {"userid": int(conversationListData['userid2'])}, {"_id": 0})
            if userData2 is not None:
                fullname2 = userData2['firstname'] + " " + userData2['lastname']
                cityName2 = {}
                if userData2['picurl'] != "":
                    picurl2 = URL + imagePath + userData2['picurl']
                else:
                    picurl2 = URL + imagePath + "user-no-image.jpg"
                if userData2['addressJSON']['city'] != "":
                    cityName2 = CityCollections.find_one(
                        {"cityid": userData2['addressJSON']['city']}, {
                            "_id": 0,
                            "city": 1
                        })
                else:
                    cityName2['city'] = ""
                if conversationListData['userid2'] != userid:
                    lastMessageDetail = {
                        "lastuserfullname": fullname2,
                        "lastusercityname": cityName2['city'],
                        "lastuserpicurl": picurl2
                    }
                    conversationListData.update(lastMessageDetail)
                userDataCollection2 = {
                    "fullname2": fullname2,
                    "cityname2": cityName2['city'],
                    "picurl2": picurl2
                }
                conversationListData.update(userDataCollection2)

            allconversationListData.append(conversationListData)

        return jsonify({
            "status": 200,
            "message": "Conversation Data.",
            "conversationListData": allconversationListData
        })
    else:
        return jsonify({
            "status": 200,
            "message": "No Conversation data Found.",
            "conversationListData": []
        })
Esempio n. 20
0
def conversation_messages_list():
    #return jsonify({"ok": 1})
    URL = Constants.URL
    imagePath = Constants.IMAGE_PATH
    userid = int(request.json['userid'])
    allMessageData = []
    converstaionCollection = Conversations.find_one({
        "conversationid":
        int(request.json['conversationid']),
        "active":
        True
    })
    displayuserCollection = {
        "displayfullname": "",
        "displaycityname": "",
        "displaypicurl": "",
        "displayuserid": "",
        "conversationid": int(request.json['conversationid'])
    }

    userDisplayData = Conversations.find_one(
        {
            "conversationid": int(request.json['conversationid']),
            "active": True
        }, {
            "_id": 0,
            "userid1": 1,
            "userid2": 1
        })
    if userDisplayData is not None:
        # messages.update({"conversationid":request.json['conversationid']},{"$set":{"isread" : True}}, True, True)
        messageData = list(
            Messages.find(
                {
                    "conversationid": request.json['conversationid'],
                    "isread": False
                }, {"_id": 0}))
        if len(messageData) > 0:
            for messageCollection in messageData:
                Messages.update(
                    {
                        "createdatetimeinseconds":
                        messageCollection['createdatetimeinseconds']
                    }, {"$set": {
                        "isread": True
                    }})
        else:
            print("No unread Message.")
        if userDisplayData['userid1'] != userid:
            userData = User.find_one({"userid": userDisplayData['userid1']},
                                     {"_id": 0})
            if userData is not None:
                cityName = {}
                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'] != "":
                    cityName = CityCollections.find_one(
                        {"cityid": userData['addressJSON']['city']}, {
                            "_id": 0,
                            "city": 1
                        })
                else:
                    cityName['city'] = ""
                displayuserCollection = {
                    "displayfullname": fullname,
                    "displaycityname": cityName['city'],
                    "displaypicurl": picurl,
                    "displayuserid": userDisplayData['userid1'],
                    "conversationid": int(request.json['conversationid'])
                }

        if userDisplayData['userid2'] != userid:
            userData = User.find_one({"userid": userDisplayData['userid2']},
                                     {"_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"
                cityName = CityCollections.find_one(
                    {"cityid": userData['addressJSON']['city']}, {
                        "_id": 0,
                        "city": 1
                    })
                displayuserCollection = {
                    "displayfullname": fullname,
                    "displaycityname": cityName['city'],
                    "displaypicurl": picurl,
                    "displayuserid": userDisplayData['userid2'],
                    "conversationid": int(request.json['conversationid'])
                }
    else:
        return jsonify({"status": 402, "message": "No Data."})

    if converstaionCollection is not None:
        messageData = list(
            Messages.find(
                {
                    "conversationid": int(request.json['conversationid'])
                }, {
                    "_id": 0
                }).sort("createddatetime", 1))
        if len(messageData) > 0:
            for messageListData in messageData:
                userData = User.find_one(
                    {"userid": int(messageListData['userid'])}, {"_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"
                    cityName = CityCollections.find_one(
                        {"cityid": userData['addressJSON']['city']}, {
                            "_id": 0,
                            "city": 1
                        })
                    userDataCollection = {
                        "fullname": fullname,
                        "cityname": cityName['city'],
                        "picurl": picurl
                    }
                    messageListData.update(userDataCollection)
                allMessageData.append(messageListData)

            return jsonify({
                "status": 200,
                "message": "Message Data.",
                "messageListData": allMessageData,
                "displayuserCollection": displayuserCollection
            })
        else:
            return jsonify({
                "status": 200,
                "message": "No Message data Found.",
                "messageListData": [],
                "displayuserCollection": displayuserCollection
            })
    else:
        return jsonify({
            "status": 200,
            "message": "No Message data Found.",
            "messageListData": [],
            "displayuserCollection": displayuserCollection
        })
Esempio n. 21
0
def user_update_image():
    try:
        userid = int(request.form['userid'])
        token = request.form['token']

        secdatetime = datetime.utcnow() - timedelta(minutes=1)
        createdatetimeinseconds = calendar.timegm(secdatetime.utctimetuple())

        findUser = User.find_one({
            "userid": userid,
            "token": token,
            "active": True
        })
        certificateJSON = findUser['certificateJSON']

        if findUser is not None:
            print(request.form['type'])
            # Profile Pic Upload
            if request.form['type'] == "profileimage":
                file = request.files['myimage']
                fileNameContain = str(userid) + str(
                    findUser['salt']) + "profile_" + str(
                        createdatetimeinseconds)
                if file and allowed_file_image(file.filename):
                    print(file.filename)
                    filename = secure_filename(file.filename)
                    ext = file.filename.rsplit('.', 1)[1]
                    filename = fileNameContain + "." + ext
                    file.save(
                        os.path.join(jw_upload.config['UPLOAD_FOLDER_PROFILE'],
                                     filename))
                    User.update({
                        'userid': userid,
                        'token': token
                    }, {"$set": {
                        'picurl': filename
                    }})
                    profilePic = URL + imagePath + filename
                    message = {
                        'status': 200,
                        'message': 'Image successfully uploaded',
                        "profilePic": profilePic
                    }

            # Police Documents Upload
            if request.form['type'] == "police":
                file = request.files['myimage']
                fileNameContain = str(userid) + str(
                    findUser['salt']) + "police_" + str(
                        createdatetimeinseconds)
                if file and (allowed_file_image(file.filename)
                             or allowed_file_doc_pdf(file.filename)):
                    filename = secure_filename(file.filename)
                    ext = file.filename.rsplit('.', 1)[1]
                    filename = fileNameContain + "." + ext
                    file.save(
                        os.path.join(jw_upload.config['UPLOAD_FOLDER_DOC'],
                                     filename))
                    proDocuments = URL + Constants.DOC_PATH + filename
                    certificateJSONDATA = {
                        "type":
                        ext,
                        "certificateid":
                        CommonUtils.generateRandomNo(Certificate,
                                                     "certificateid"),
                        "certificateimageurl":
                        filename,
                        "certificatestatus":
                        "pending",
                        "certificatecaption":
                        request.form['certificatecaption'],
                        "ispoliceverification":
                        True
                    }
                    certificateJSON.append(certificateJSONDATA)
                    User.update({
                        'userid': userid,
                        'token': token
                    }, {"$set": {
                        'certificateJSON': certificateJSON
                    }})
                    message = {
                        'status': 200,
                        'message': 'Image successfully uploaded',
                        "certificateJSON": certificateJSON
                    }

            # Pro Documents Uploads
            if request.form['type'] == "certificateimage":
                file = request.files['myimage']
                fileNameContain = str(userid) + str(
                    findUser['salt']) + "pro_docs_" + str(
                        createdatetimeinseconds)
                if file and (allowed_file_image(file.filename)
                             or allowed_file_doc_pdf(file.filename)):
                    filename = secure_filename(file.filename)
                    ext = file.filename.rsplit('.', 1)[1]
                    filename = fileNameContain + "." + ext
                    file.save(
                        os.path.join(jw_upload.config['UPLOAD_FOLDER_DOC'],
                                     filename))
                    proDocuments = URL + Constants.DOC_PATH
                    certificateJSONDATA = {
                        "type":
                        ext,
                        "certificateid":
                        CommonUtils.generateRandomNo(Certificate,
                                                     "certificateid"),
                        "certificateimageurl":
                        filename,
                        "certificatestatus":
                        "pending",
                        "certificatecaption":
                        request.form['certificatecaption'],
                        "ispoliceverification":
                        False
                    }
                    certificateJSON.append(certificateJSONDATA)
                    User.update({
                        'userid': userid,
                        'token': token
                    }, {"$set": {
                        'certificateJSON': certificateJSON
                    }})
                    message = {
                        'status': 200,
                        'message': 'Image successfully uploaded',
                        "certificateJSON": certificateJSON
                    }

            # Portfolio Images Uploads
            if request.form['type'] == "portfolioimage":
                file = request.files['myimage']
                fileNameContain = str(userid) + str(
                    findUser['salt']) + "portfolio_" + str(
                        createdatetimeinseconds)
                if file and allowed_file_image(file.filename):
                    filename = secure_filename(file.filename)
                    ext = file.filename.rsplit('.', 1)[1]
                    filename = fileNameContain + "." + ext
                    file.save(
                        os.path.join(
                            jw_upload.config['UPLOAD_FOLDER_PORTFOLIO'],
                            filename))
                    portfolioDataPath = URL + Constants.PORTFOLIO_PATH
                    UserPortfolio.insert({
                        "portfolioid":
                        CommonUtils.generateRandomNo(UserPortfolio,
                                                     "portfolioid"),
                        "portfolioimage":
                        filename,
                        "userid":
                        userid,
                        "active":
                        True,
                        "createddatetime":
                        datetime.now(),
                        "updatedatetime":
                        datetime.now()
                    })
                    portfolioData = list(
                        UserPortfolio.find({
                            "userid": userid,
                            "active": True,
                        }, {"_id": 0}))
                    message = {
                        'status': 200,
                        'message': 'Image successfully uploaded',
                        "portfolioData": portfolioData,
                        "portfolioDataPath": portfolioDataPath
                    }

            User.update({
                "userid": userid,
                "token": token,
                "active": True
            }, {"$set": {
                "updateddatetime": datetime.now()
            }})

            return jsonify(message)
        else:
            return jsonify({"status": 402, "message": "No User found."})

    except Exception as e:
        return jsonify({"status": 500, "message": e.message})
Esempio n. 22
0
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": []
        })
Esempio n. 23
0
def user_update():
    try:
        userid = int(request.json['userid'])
        token = request.json['token']
        location = request.json['location']
        if location != "":
            location = int(location)

        find_user = User.find_one({"userid": userid, "active": True})

        if find_user is not None:
            skills = request.json['skills']

            print(skills)
            print(type(skills))

            if request.json['dob'] != "":
                birth = request.json['dob']
                print(birth)
                format = '%d-%m-%Y'
                dob = datetime.datetime.strptime(birth, format)
            else:
                dob = ""

            if request.json['city'] != "":
                citydetail = CityCollections.find_one(
                    {"cityid": int(request.json['city'])}, {"_id": 0})
                addressJSON = {
                    "address1": request.json['address1'],
                    "address2": request.json['address2'],
                    "city": int(request.json['city']),
                    "state": citydetail['stateid'],
                    "country": citydetail['countryid'],
                    "pincode": request.json['pincode']
                }
            else:
                addressJSON = {
                    "address1": request.json['address1'],
                    "address2": request.json['address2'],
                    "city": "",
                    "state": "",
                    "country": "",
                    "pincode": request.json['pincode']
                }

            if request.json['isdcode'] != "" and request.json[
                    'isdcode'] is not None:
                isdcode = int(request.json['isdcode'])
            else:
                isdcode = ""

            # locationData = location.find_one({"cityid" : int(request.json['city'])},{"_id":0,"locationid":1})

            # skillsJSON = []
            # for skillDataJSON in skills:
            # 	stringData = '.*'+skillDataJSON+'.*'
            # 	skillsData = skills.find_one({"skillname" : { "$regex" : skillDataJSON, "$options" : 'i' }},{"_id":0,"skillid":1,"skillname":1})
            # 	if skillsData is not None:
            # 		for skillsCollections in skillsData :
            # 			skillDict = {"skillid" : skillsCollections['skillid'],
            # 						"skillname" : skillsCollections['skillname']}
            # 			skillsJSON.append(skillDict)

            randomNameForFile = ""
            # if request.json['imageFlag']:
            # 	randomNameForFile = "image_"+str(int(time.time()))+".jpg"
            # 	fh = open("static/images/profile/"+randomNameForFile, "wb")
            # 	fh.write(request.json['picurl'].decode('base64'))
            # 	fh.close()

            # languagesJSON = request.json['languagesJSON']
            # educationCSV = request.json['educationCSV']
            # workplaceCSV = request.json['workplaceCSV']
            # certificateJSON = request.json['certificateJSON']
            # reportedJSON = list(report.find({ "userid" : userid, "token" : token }, {"_id":0}))
            if find_user['mobile'] != str(request.json['mobile']):
                User.update({"userid": userid}, {
                    "$set": {
                        "signupJSON.mobile": str(request.json['mobile']),
                        "mobile": str(request.json['mobile']),
                        "mobileverified": False,
                        "proJSON.mobileverified": False
                    }
                })
            if find_user['email'] != str(request.json['email']):
                User.update({"userid": userid}, {
                    "$set": {
                        "signupJSON.email": str(request.json['email']),
                        "email": str(request.json['email']),
                        "emailverified": False
                    }
                })

            result = User.update({"userid": userid}, {
                "$set": {
                    "firstname": request.json['firstname'],
                    "lastname": request.json['lastname'],
                    "aboutme": request.json['aboutme'],
                    "languagesJSON": [],
                    "educationCSV": [],
                    "workplaceCSV": [],
                    "updateddatetime": datetime.datetime.now(),
                    "isdcode": isdcode,
                    "addressJSON": addressJSON,
                    "skillsJSON": skills,
                    "gender": request.json['gender'],
                    "dob": dob,
                    "locationid": location
                }
            })

            userdata_array = list(
                User.find({
                    "userid": userid,
                    "active": True
                }, {"_id": 0}))

            resultArray = {}
            responseArr = []

            if len(userdata_array) > 0:
                for collectionInfo in userdata_array:
                    # cityname = citycollections.find_one({"cityid":collectionInfo['addressJSON']['city']},{"_id":0})
                    # 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']})

                    location_name = ""
                    if collectionInfo['addressJSON']['city'] != "":
                        citynamedata = CityCollections.find_one(
                            {"cityid": collectionInfo['addressJSON']['city']},
                            {"_id": 0})
                        city_name = citynamedata['city']
                        countrynamedata = CountryCollections.find_one(
                            {
                                "countryid":
                                collectionInfo['addressJSON']['country']
                            }, {"_id": 0})
                        country_name = countrynamedata['country']
                    else:
                        city_name = ""
                        country_name = ""

                    if collectionInfo['locationid'] != "":
                        location_name_data = Locations.find_one(
                            {"locationid": int(collectionInfo['locationid'])},
                            {
                                "_id": 0,
                                "locationname": 1,
                                "under": 1
                            })
                        if location_name_data is not None:
                            if location_name_data['under'] != "":
                                location_name = str(
                                    location_name_data['under']) + " - " + str(
                                        location_name_data['locationname'])
                            else:
                                location_name = str(
                                    location_name_data['locationname'])
                    else:
                        location_name = ""

                    skill_data = collectionInfo['skillsJSON']
                    skillNameData = []
                    if len(skill_data) > 0:
                        for skillDataCollections in skill_data:
                            skillNameData.append(
                                skillDataCollections['skillname'])

                    rating = 0  # Rating Initially 0
                    userReview = list(
                        JobReviews.find(
                            {
                                "touserid": 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
                    allCityData = list(
                        CityCollections.find({}, {
                            "_id": 0,
                            "cityid": 1,
                            "city": 1
                        }))
                    picurlPath = Constants.PROFIL_PIC_STATIC_PATH + collectionInfo[
                        'picurl']
                    portfolioData = list(
                        UserPortfolio.find({
                            "userid": userid,
                            "active": True,
                        }, {"_id": 0}))
                    documentsPath = Constants.URL + Constants.DOC_PATH
                    portfolioDataPath = Constants.URL + Constants.PORTFOLIO_PATH
                    updateJSON = {
                        "cityname": city_name,
                        "locationName": location_name,
                        "countryname": country_name,
                        "allcity": allCityData,
                        "skillName": skillNameData,
                        "portfolioData": portfolioData,
                        "picurlPath": picurlPath,
                        "userrating": tatalRating,
                        "documentsPath": documentsPath,
                        "portfolioDataPath": portfolioDataPath
                    }
                    collectionInfo.update(updateJSON)

                    responseArr.append(collectionInfo)
                resultArray['data'] = responseArr
            else:
                resultArray['data'] = responseArr

            return make_response(
                jsonify({
                    'status': 200,
                    'message': 'Successfull Updated',
                    'userid': userid,
                    'token': token,
                    'updateData': responseArr
                }), 200)
        else:
            return make_response(
                jsonify({
                    'status': 402,
                    'message': 'No User Found.',
                    'userid': userid,
                    'token': token,
                    'updateData': []
                }), 400)

    except Exception as e:
        CommonUtils.print_exception()
        return make_response(jsonify({"status": 500, "message": str(e)}), 500)
Esempio n. 24
0
def jobFilter():
    try:
        allDataCollections = []
        userid = (request.json['userid'])
        sortBy = int(request.json['sortBy'])
        budgetMin = int(request.json['budgetMin'])
        budgetMax = int(request.json['budgetMax'])
        city = request.json['city']
        location = request.json['location']
        jobtype = request.json['jobtype']
        radius = request.json['radius']
        page_offset = request.json['page_offset']
        searchString = request.json['search']

        PageLimit = 10

        if (jobtype == 0):
            jobTypKey = "$or"
            jobTypVal = [{"online": True}, {"online": False}]
        if (jobtype == 1):
            jobTypKey = "online"
            jobTypVal = True
        if (jobtype == 2):
            jobTypKey = "online"
            jobTypVal = False

        if location != "":
            location = int(request.json['location'])
            valLoc = location
        else:
            location = 0
            valLoc = {"$ne": location}

        if city != "":
            city = int(request.json['city'])
            valCity = city
            cityLocation = db.location.find_one({"cityid": int(city)}, {
                "_id": 0,
                "gpsJSON": 1
            })
            cityLat = cityLocation['gpsJSON']['lat']
            cityLng = cityLocation['gpsJSON']["lng"]
            print(cityLat, cityLng)
            origin = True
        else:
            if userid != "":
                userCity = db.user.find_one({"userid": int(userid)}, {
                    "_id": 0,
                    "addressJSON.city": 1
                })
                cityId = userCity['addressJSON']['city']
                valCity = cityId
                print(cityId)
                cityLocation = db.location.find_one({"cityid": int(cityId)}, {
                    "_id": 0,
                    "gpsJSON": 1
                })
                cityLat = cityLocation['gpsJSON']['lat']
                cityLng = cityLocation['gpsJSON']["lng"]
                origin = True
            else:
                city = 0
                valCity = {"$ne": city}
                print("no city no user")
                radius = ""
                origin = False

        locationList = []
        print("1")
        if radius != "" and origin:
            #locations=list(db.location.find({ "gpsJSON" : { "$near" : [cityLat,cityLng],"$maxDistance":int(request.json['radius'] ) } },{"locationid":1,"_id":0} ))
            locations = list(
                db.location.find({
                    "gpsJSON.lnglat": {
                        "$near": {
                            "$geometry": {
                                "type": "Point",
                                "coordinates": [cityLng, cityLat]
                            },
                            "$maxDistance": int(radius) * 1000
                        }
                    }
                }))
            print("2")
            for data in locations:
                locationList.append(data["locationid"])
        #return jsonify({"status": locationList})

        if (sortBy == 0):
            sortKey = "publisheddatetime"
            sortVal = -1
        if (sortBy == 1):
            sortKey = "budget"
            sortVal = 1
        if (sortBy == 2):
            sortKey = "budget"
            sortVal = -1
        if (sortBy == 3):
            sortKey = "distance"
            sortVal = -1
        # db.location.find({ gpsJSON : { $near : [43.8492143,-79.0241784],$maxDistance:1  } } )
        #cityList=db.location.find()
        #return jsonify({"status": budgetMin,"lt":budgetMax})
        listd = (jobTypKey, jobTypVal, valLoc, valCity, budgetMin, budgetMax)
        #return jsonify({"back":listd})
        if len(locationList) != 0:
            result = db.jobs.find(
                {
                    "description": {
                        "$regex": searchString
                    },
                    jobTypKey: jobTypVal,
                    "cityid": valCity,
                    "budget": {
                        "$gte": budgetMin,
                        "$lte": budgetMax
                    },
                    "locationid": {
                        "$in": locationList
                    }
                }, {
                    "_id": 0
                }).sort(sortKey, sortVal).skip(page_offset).limit(PageLimit)
            #return jsonify({"status": locationList,"result":list(result)})

        else:
            result = db.jobs.find(
                {
                    "description": {
                        "$regex": searchString
                    },
                    jobTypKey: jobTypVal,
                    "cityid": valCity,
                    "budget": {
                        "$gte": budgetMin,
                        "$lte": budgetMax
                    }
                }, {
                    "_id": 0
                }).sort(sortKey, sortVal).skip(page_offset).limit(PageLimit)

        count = db.jobs.count(
            {
                "description": {
                    "$regex": searchString
                },
                jobTypKey: jobTypVal,
                "locationid": valLoc,
                "cityid": valCity,
                "budget": {
                    "$gte": budgetMin,
                    "$lte": budgetMax
                },
                "locationid": {
                    "$in": locationList
                }
            }, )
        #return jsonify({"back": list(result)})
        print("3")
        response = dict()
        for data in result:
            #return jsonify({"location": data})
            map = dict()
            if (data['locationid'] != ""):
                location_data = db.location.find_one(
                    {"locationid": data['locationid']})
            if (data['addressJSON']['state'] != ""):
                state = db.state.find_one(
                    {"stateid": data['addressJSON']['state']})
            if (data['addressJSON']['country'] != ""):
                country = db.country.find_one(
                    {"countryid": data['addressJSON']['country']})
            if (data['cityid'] != ""):
                city = db.city.find_one({"cityid": data['cityid']})

            map.update({"city": city['city']})
            map.update({"state": state['state']})
            map.update({"country": country['country']})
            map.update({"lon": location_data['location_raw']['lon']})
            map.update({"lat": location_data['location_raw']['lat']})
            map.update({"locationname": location_data['locationname']})
            data.update({"map": map})
            bidcount = db.jobbids.count({"jobid": data['jobid']})
            data.update({"bidcount": bidcount})

            userId = User.find_one({"userid": data['creatinguserid']})
            try:
                fname = userId['firstname']
                space = " "
            except Exception as e:
                fname = ""
                space = ""
            try:
                lname = userId['lastname']
            except Exception as e:
                lname = ""
            username = fname + space + lname
            data.update({"username": username})

            try:
                data.update({"picurl": userId['picurl']})
            except Exception as e:
                data.update({"picurl": "no pic url field in db"})

            if (radius != ""):
                if (data["locationid"] in locationList):
                    #count = count + 1
                    allDataCollections.append(data)
            else:
                #count = count + 1
                allDataCollections.append(data)

        if count is 0:
            return jsonify({
                "status": 200,
                "message": "no data",
                "error": True,
                "response": {}
            })
        else:
            #return jsonify({"count": count})
            return jsonify({
                "response": allDataCollections,
                "status": 200,
                "error": False,
                "message": count
            })
    except Exception as e:
        return json.dumps(e, indent=4, default=json_util.default)
Esempio n. 25
0
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)
Esempio n. 26
0
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})
Esempio n. 27
0
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
        })
Esempio n. 28
0
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"
Esempio n. 29
0
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
        })
Esempio n. 30
0
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})