Пример #1
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."})
Пример #2
0
    def notify_onboard(cls, userid, fullname, device_token):
        if device_token:
            notificationtext = "Hello " + str(fullname) + "  SaveOnJobs welcomes you !!"
            data_message = {
                "body": notificationtext,
            }

            push_service.notify_single_device(registration_id=device_token,
                                              message_title="Welcome!",
                                              message_body=notificationtext,
                                              data_message=data_message,
                                              click_action="FCM_PLUGIN_ACTIVITY")

            from jobwork.models.notification import Notifications
            Notifications.insert({
                "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"),
                "notificationtext": notificationtext,
                "notificationtype": "welcome",
                "notificationtouserid": int(userid),
                "notificationfromuserid": -1,
                "jobid": -1,
                "bidid": -1,
                "commentid": -1,
                "createddatetime": datetime.datetime.now(),
                "updatedatetime": datetime.datetime.now(),
                "isread": False
            })
Пример #3
0
 def notify_bid_accepted(cls, userid, jobid, bidid, job_collection, jobberfullname, final_bid):
     notificationtext = "Your Bid on job title '" + job_collection[
         'title'] + "' is accepted by Jobber : " + jobberfullname
     from jobwork.models.user import User
     registration_id = User.find_FCM_id(final_bid['userid'])
     if registration_id:
         data_message = {
             "body": notificationtext,
         }
         push_service.notify_single_device(registration_id=registration_id, message_title="Bid Accepted",
                                           message_body=notificationtext, data_message=data_message)
     # Notification entry
     from jobwork.models.notification import Notifications
     Notifications.insert({
         "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"),
         "notificationtext": notificationtext,
         "notificationtype": "Bid",
         "notificationtouserid": int(final_bid['userid']),
         "notificationfromuserid": userid,
         "jobid": int(jobid),
         "jobbidid": int(bidid),
         "commentid": -1,
         "createddatetime": datetime.datetime.now(),
         "updatedatetime": datetime.datetime.now(),
         "isread": False
     })
Пример #4
0
    def notify_bid_reverse(cls, userid, jobid, bidid, job_collection, bidderfullname, job_bid_detail):
        notificationtext = "You reverse bid on the job title " + job_collection[
            'title'] + " for bidder : " + str(bidderfullname)

        from jobwork.models.user import User
        registration_id = User.find_FCM_id(job_bid_detail['userid'])
        if registration_id:
            data_message = {
                "body": notificationtext,
            }

            push_service.notify_single_device(registration_id=registration_id,
                                              message_title="Reverse Bid",
                                              message_body=notificationtext,
                                              data_message=data_message)

        from jobwork.models.notification import Notifications
        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.datetime.now(),
            "updatedatetime": datetime.datetime.now(),
            "isread": False
        })
Пример #5
0
    def send_reverse_bid_mail(cls, userid, bidder_email, job_title,
                              bidder_name, jobber_name, txn_amount):
        if bidder_email:
            subject = "Reverse Bid on Job."
            sender = ("SAVEonJOBS", "*****@*****.**")
            recipients = [bidder_email]
            template = render_template(Constants.BID_REVERSE_EMAIL_TEMPLATE,
                                       name=bidder_name,
                                       title=job_title,
                                       jobber=jobber_name,
                                       amount=int(float(txn_amount)))
            cls.send_mail(subject, sender, recipients, template)

            from jobwork.models.emailtrack import EmailTracks
            EmailTracks.insert({
                "emailtrackid":
                CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"),
                "userid":
                userid,
                "email":
                bidder_email,
                "subject":
                subject,
                "emailtext":
                template,
                "createdatetime":
                datetime.datetime.now(),
                "updatedatetime":
                datetime.datetime.now()
            })
        else:
            print("No email of bidder.")
        return
Пример #6
0
def addCity():
    CityCollections.insert({"city" :"Vancouver" ,"countryid" : 647010771 ,"stateid" : 719887913
                            ,"cityid" : CommonUtils.generateRandomNo(CityCollections ,"cityid"), "active" : True
                            ,"createddatetime" : datetime.now(), "updateddatetime" : datetime.now()
                            ,"gpsJSON" : {"lat" : 49.246292 ,"lng" : -123.116226 ,"lnglat" : [-123.116226 ,49.246292]
                                        ,"radius" : ""}})
    return "success"
Пример #7
0
    def send_onboard_email(cls, userid, email, email_hash, firstname):
        subject = "Your SAVEonJOBS.comAccount Email Verification"
        sender = ("SAVEonJOBS", "*****@*****.**")
        recipients = [email]
        reset_password_link = str(
            Constants.URL) + "/user/emailverify__" + str(email_hash)

        template = render_template(Constants.ONBOARD_EMAIL_TEMPLATE,
                                   name=firstname,
                                   resetLink=reset_password_link,
                                   email=email)
        cls.send_mail(subject, sender, recipients, template)
        from jobwork.models.emailtrack import EmailTracks
        EmailTracks.insert({
            "emailtrackid":
            CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"),
            "userid":
            userid,
            "email":
            email,
            "subject":
            subject,
            "emailtext":
            template,
            "createdatetime":
            datetime.datetime.now(),
            "updatedatetime":
            datetime.datetime.now()
        })
Пример #8
0
def reportjob():
    userid = int(request.json['userid'])
    token = request.json['token']
    jobid = request.json['jobid']
    reporteddatetime = datetime.now()
    reportresolveddatetime = datetime.now()

    if (userid != None) and (jobid != None):
        reportedJSON = {
            "reportid": CommonUtils.generateRandomNo(Report, "reportid"),
            "byuserid": userid,
            "reportresolved": False,
            "reporteddatetime": reporteddatetime,
            "reportresolveddatetime": reportresolveddatetime,
            "active": True
        }

        temp = []
        temp.append(reportedJSON)
        Jobs.update({"jobid": jobid}, {"$set": {"reportedJSON": temp}})

        return jsonify({
            "status": 200,
            "message": "Successfully Report Created."
        })
    else:
        return jsonify({"status": 400, "message": "No Data Recevied."})
Пример #9
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"})
Пример #10
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."
        })
Пример #11
0
def invoice_year_invoicenumber():
    InvoiceNumbers.insert({
        "invoicenumberid":
        CommonUtils.generateRandomNo(InvoiceNumbers, "invoicenumberid"),
        "invoicenumber":
        0,
        "financialyear":
        "2016 - 2017",
        "startyear":
        2016,
        "endyear":
        2017,
        "createdatetime":
        datetime.now(),
        "updatedatetime":
        datetime.now()
    })
    return jsonify({"status": "ok"})
Пример #12
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"})
Пример #13
0
def temp_transaction():
    try:
        userid = int(request.json['userid'])

        result_transaction = TransactionTrack.find_one(
            {"userid": userid, "jobid": int(request.json['jobid']), "jobbid": int(request.json['jobbid'])})


        if result_transaction:

            created_transactionid = CommonUtils.generateRandomNo(TransactionTrack, "transactionid")
            TransactionTrack.insert({
                "transactionid": created_transactionid,
                "requestdatetime": datetime.datetime.now(),
                "amount": request.json['amount'],
                "transactionstatus": request.json['transactionstatus'],
                "transactionresponse": "",
                "userid": userid,
                "jobid": int(request.json['jobid']),
                "jobbid": int(request.json['jobbid']),
                "responsedatetime": "",
                "type": "manual"
            })

        else:

            created_transactionid = result_transaction['transactionid']

            TransactionTrack.update({
                "transactionid": created_transactionid
            }, {
                "$set": {
                    "requestdatetime": datetime.datetime.now()
                }
            })
        return make_response(jsonify({"status": 200, "transactionid": created_transactionid}), 200)
    except Exception as e:
        print(e)
        return make_response(jsonify({"status": 500, "message": "Something went wrong, Please try again!"}), 500)
Пример #14
0
def reportcomment():
    userid = int(request.json['userid'])
    token = request.json['token']
    commentid = request.json['commentid']
    reporteddatetime = datetime.now()
    reportresolveddatetime = datetime.now()

    if (userid != None) and (token != None) and (commentid != None):
        reportedJSON = {
            "reportid": CommonUtils.generateRandomNo(Report, "reportid"),
            "byuserid": userid,
            "reportresolved": False,
            "reporteddatetime": reporteddatetime,
            "reportresolveddatetime": reportresolveddatetime,
            "active": True
        }

        commentsreportedJSON = []

        commentsreportedJSON = JobComments.find({"commentid": commentid}, {
            "_id": 0,
            "reportedJSON": 1
        })
        reportData = commentsreportedJSON['reportedJSON']
        temp = []
        temp.append(reportData)
        temp.append(reportedJSON)

        JobComments.update({"commentid": commentid},
                           {"$set": {
                               "reportedJSON": temp
                           }})

        return jsonify({
            "status": 200,
            "message": "Successfully Report Created."
        })
    else:
        return jsonify({"status": 400, "message": "No Data Recevied."})
Пример #15
0
 def send_onboard_sms(cls, userid, mobileotp, mobile):
     sendText = "Mobile Verify OTP is " + str(mobileotp)
     message = msgclient.messages.create(body=sendText,
                                         to=mobile,
                                         from_=sendFrom)
     print(message.sid)
     from jobwork.models.messagetrack import MessageTracks
     MessageTracks.insert({
         "messagetrackid":
         CommonUtils.generateRandomNo(MessageTracks, "messagetrackid"),
         "userid":
         userid,
         "mobile":
         mobile,
         "messagetext":
         sendText,
         "messagesid":
         message.sid,
         "createdatetime":
         datetime.datetime.now(),
         "updatedatetime":
         datetime.datetime.now()
     })
Пример #16
0
def register():

    try:
        firstname = request.json['fname']
        lastname = request.json['lname']
        email = request.json['email']
        regtype = int(request.json['regtype'])
        mobile = request.json['mobile']
        cityid = request.json['city']
        skill = request.json['skill']
        stateid = request.json['state']
        countryid = request.json['country']
        picurl = request.json['picurl']
        gender = request.json['gender']
        locationid = request.json['locationid']

        if locationid != "":
            locationid = int(locationid)

        if picurl == '':
            picurl = "default-image.jpg"
        '''
        if city!="":
            citylist=db.city.find_one({"city":city},{"_id":0,"cityid":1})
            cityid=citylist['cityid']
        else:
            cityid=""

        if state!="":
            statelist=db.state.find_one({"state":state},{"_id":0,"stateid":1})
            stateid=statelist['stateid']
        else:
            stateid=""

        if country!="":
            countrylist=db.country.find_one({"country":country},{"_id":0,"countryid":1})
            countryid=countrylist['countryid']
        else:
            countryid=""
'''
        addressJSON = {
            "address1": request.json['address1'],
            "address2": request.json['address2'],
            "city": cityid,
            "state": stateid,
            "country": countryid,
            "pincode": request.json['pincode']
        }
        salt = CommonUtils.generateRandomName()
        emailhash = CommonUtils.getHashValue()
        token = CommonUtils.generateRandomName()

        if regtype == 0:
            password = request.json['password']
            password = CommonUtils.password_hash(password, salt)
            sociallogin = False
            emailverified = False
            fbid = ""
            fbaccesstoken = ""
            registeredfrom = "jobwork"

        else:
            password = ""
            sociallogin = True
            emailverified = True
            fbid = request.json['fbid']
            fbaccesstoken = request.json['fbaccesstoken']
            if regtype == 1:
                registeredfrom = "facebook"
            elif regtype == 2:
                registeredfrom = "gmail"
        #return jsonify({"ok":1})
        userdata = list(User.find({"email": email}, {"_id": 0}))

        if User.count({"email": email}) == 0:
            userid = CommonUtils.generateRandomNo(User, "userid")
            User.insert({
                "userid": userid,
                "signupJSON": "",
                "email": email,
                "emailverified": emailverified,
                "emailhash": emailhash,
                "mobile": mobile,
                "mobileverified": False,
                "mobileotp": "",
                "isdcode": None,
                "fbid": fbid,
                "fbaccesstoken": fbaccesstoken,
                "password": password,
                "salt": salt,
                "token": token,
                "firstname": firstname,
                "lastname": lastname,
                "isadmin": False,
                "createddatetime": datetime.now(),
                "updateddatetime": datetime.now(),
                "addressJSON": addressJSON,
                "paymentdetailsJSON": [],
                "skillsJSON": skill,
                "languagesJSON": [],
                "educationCSV": [],
                "workplaceCSV": [],
                "certificateJSON": [],
                "proJSON": [],
                "forgotpasswordJSON": [],
                "gender": gender,
                "dob": "",
                "locationid": locationid,
                "aboutme": "",
                "picurl": picurl,
                "reportedJSON": [],
                "notificationJSON": [],
                "socaillogin": sociallogin,
                "facebookpicurl": "",
                "active": True,
                "paypal_id": "",
                "registeredfrom": registeredfrom
            })
            if regtype != 0:
                response = userDataResponse(email)
                # user = list(User.find({"email": email}, {"_id": 0}))
                return jsonify({
                    "status": 200,
                    "response": response,
                    "message": "",
                    "error": False,
                    "registedfrom": registeredfrom
                })
            else:
                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.io Account Email Verification"
                msg = Message(subject,
                              sender=("JobWork", "*****@*****.**"),
                              recipients=[email])
                msg.html = render_template(
                    '/emailTemplates/email_verification_template.html',
                    name=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,
                "response": {},
                "message": "verification mail sent",
                "error": True,
                "registedfrom": registeredfrom
            })

        elif userdata[0]['emailverified'] == False:
            emailhash = CommonUtils.getHashValue()
            userid = CommonUtils.generateRandomNo(User, "userid")
            db.user.remove({"email": email})
            User.insert({
                "userid": userid,
                "signupJSON": "",
                "email": email,
                "emailverified": emailverified,
                "emailhash": emailhash,
                "mobile": mobile,
                "mobileverified": False,
                "mobileotp": "",
                "isdcode": None,
                "fbid": fbid,
                "fbaccesstoken": fbaccesstoken,
                "password": password,
                "salt": salt,
                "token": token,
                "firstname": firstname,
                "lastname": lastname,
                "isadmin": False,
                "createddatetime": datetime.now(),
                "updateddatetime": datetime.now(),
                "addressJSON": addressJSON,
                "paymentdetailsJSON": [],
                "skillsJSON": skill,
                "languagesJSON": [],
                "educationCSV": [],
                "workplaceCSV": [],
                "certificateJSON": [],
                "proJSON": [],
                "forgotpasswordJSON": [],
                "gender": gender,
                "dob": "",
                "locationid": locationid,
                "aboutme": "",
                "picurl": picurl,
                "reportedJSON": [],
                "notificationJSON": [],
                "socaillogin": sociallogin,
                "facebookpicurl": "",
                "active": True,
                "paypal_id": "",
                "registeredfrom": registeredfrom
            })
            if regtype != 0:
                response = userDataResponse(email)
                return jsonify({
                    "status": 200,
                    "response": response,
                    "message": "existed now updated",
                    "error": False,
                    "registedfrom": registeredfrom
                })
            else:
                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.io Account Email Verification"
                msg = Message(subject,
                              sender=("JobWork", "*****@*****.**"),
                              recipients=[email])
                msg.html = render_template(
                    '/emailTemplates/email_verification_template.html',
                    name=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,
                "response": {},
                "message":
                "mail id exist but not verified yet verification mail sent",
                "error": True,
                "registedfrom": registeredfrom
            })

        elif regtype != 0:
            verify = False

            user = list(User.find({"email": email}, {"_id": 0}))

            if regtype == 1 and user[0]['registeredfrom'] == "facebook":
                verify = True

            elif regtype == 2 and user[0]['registeredfrom'] == "gmail":
                verify = True

            else:
                message = "account already registered from " + user[0][
                    'registeredfrom']
                return jsonify({
                    "status": 200,
                    "messsage": message,
                    "registedfrom": user[0]['registeredfrom'],
                    "response": {},
                    "error": True
                })
                #user = list(User.find({"email": email}, {"_id": 0}))
            if verify == True:

                #print(userdata[0]['cityname'][0])
                response = userDataResponse(email)
                print((response))
                return jsonify({
                    "status": 200,
                    "response": response,
                    "message": "",
                    "error": False,
                    "registedfrom": user[0]['registeredfrom']
                })
        else:
            return jsonify({
                "status": 200,
                "messsage": "email id already used",
                "response": {},
                "error": True,
                "registedfrom": userdata[0]['registeredfrom']
            })
    except Exception as e:
        return json.dumps(e, indent=4, default=json_util.default)
Пример #17
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.'}
Пример #18
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
        })
Пример #19
0
from jobwork.utils.common_utils import CommonUtils
from jobwork.utils.register_utils import userDataResponse
from jobwork.constants import Constants
from jobwork.models.messagetrack import MessageTracks
from twilio.rest import Client
from datetime import datetime
from bson import json_util, ObjectId
import json
from jobwork.db_connection import db
from flask_mail import Mail, Message
from jobwork.models.emailtrack import EmailTracks

user_register_all = Blueprint('user_register_all', __name__, url_prefix='')

msgclient = Client(Constants.MSG_ACCOUNT_SID, Constants.MSG_AUTH_TOKEN)
msgtrckid = CommonUtils.generateRandomNo(MessageTracks, "messagetrackid")

URL = Constants.URL
app = Flask(__name__)
mail = Mail()
app.config["MAIL_SERVER"] = "jobwork.io"
app.config["MAIL_PORT"] = 25
app.config["MAIL_DEBUG"] = True
app.config["MAIL_USERNAME"] = '******'  ## CHANGE THIS
app.config["MAIL_PASSWORD"] = '******'
app.config["MAIL_DEFAULT_SENDER"] = ("SAVEonJOBS", "*****@*****.**")

mail.init_app(app)
mail = Mail(app)

Пример #20
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": []
        })
Пример #21
0
def user_job_review():
    # Check authentications keys
    userid = int(request.json['userid'])
    token = request.json['token']

    if request.json['bidderJobStatus'] == "verify":
        check_status = JobBids.find \
            ({"jobid" :int(request.json['jobid']) ,"userid" :int(request.json['touserid']) ,"active" :True
             ,"status" : "completed"}).count()
    elif request.json['bidderJobStatus'] == "completed":
        check_status = JobBids.find({
            "jobid": int(request.json['jobid']),
            "userid": userid,
            "active": True,
            "status": {
                "$in": ["selectedbyjobber", "approvedbybidder"]
            }
        }).count()

    print(check_status)
    if check_status == 1:

        if request.json['bidderJobStatus'] == "verify":
            bidid = 0
            jobbids_info = JobBids.find_one \
                ({"userid" :int(request.json['touserid']) ,"jobid" :int(request.json['jobid'])} ,{"_id" :0})
            if jobbids_info is not None:
                bidid = jobbids_info['bidid']

        jobReviewsDataCount = JobReviews.find({
            "userid":
            userid,
            "jobid":
            int(request.json['jobid'])
        }).count()
        jobCollection = list(Jobs.find({"jobid": int(request.json['jobid'])}))

        # print jobBidsData['bidid']
        if jobReviewsDataCount == 0:
            jobreviewData = JobReviews.insert({
                "userid":
                userid,
                "reviewid":
                CommonUtils.generateRandomNo(JobReviews, "reviewid"),
                "jobid":
                int(request.json['jobid']),
                "rating":
                int(request.json['rating']),
                "comment":
                request.json['comment'],
                "touserid":
                int(request.json['touserid']),
                "adminaction":
                False,
                "active":
                True,
                "createdatetime":
                datetime.now(),
                "updatedatetime":
                datetime.now()
            })

            if request.json['bidderJobStatus'] == "verify":

                jobCollection = Jobs.find_one(
                    {"jobid": int(request.json['jobid'])}, {"_id": 0})
                if jobCollection is not None:
                    total_paid_task = JobBids.find({
                        "jobid":
                        int(request.json['jobid']),
                        "completionstatus": {
                            "$in": ["accepted", "rejectedaccepted"]
                        }
                    }).count()
                    if total_paid_task != 0:
                        if (total_paid_task >=
                                jobCollection['personsrequired']):
                            Jobs.update({"jobid": int(request.json['jobid'])},
                                        {"$set": {
                                            "jobstatus": "paid"
                                        }})

                jobBidsData = JobBids.find_one \
                    ({"userid" : int(request.json['touserid']) ,"jobid" : int(request.json['jobid'])} ,{"_id" :0})
                JobBids.update({"bidid": int(jobBidsData['bidid'])}, {
                    "$set": {
                        "status": "verify",
                        "completionstatus": "accepted"
                    }
                })

                jobCollection = Jobs.find_one(
                    {"jobid": int(request.json['jobid'])}, {"_id": 0})
                if jobCollection is not None:
                    userJobberCollection = user.find_one(
                        {"userid": jobCollection['creatinguserid']},
                        {"_id": 0})
                    if userJobberCollection is not None:
                        jobberfullname = userJobberCollection[
                            'firstname'] + "  " + userJobberCollection[
                                'lastname']
                        jobberEmail = userJobberCollection['email']
                        jobberMobile = userJobberCollection['mobile']
                    else:
                        jobberfullname = ""
                        jobberEmail = None
                        jobberMobile = None
                    userbidderCollection = User.find_one(
                        {"userid": int(request.json['touserid'])}, {"_id": 0})
                    if userbidderCollection is not None:
                        bidderfullname = userbidderCollection[
                            'firstname'] + "  " + userbidderCollection[
                                'lastname']
                        bidderEmail = userbidderCollection['email']
                        bidderMobile = userbidderCollection['mobile']
                    else:
                        bidderfullname = ""
                        bidderEmail = None
                        bidderMobile = None
                else:
                    print("No jobs")

                if bidderEmail is not None:

                    subject = "Payment released."
                    msg = Message(subject,
                                  sender=("SAVEonJOBS",
                                          "*****@*****.**"),
                                  recipients=[bidderEmail])
                    msg.html = render_template(
                        '/emailTemplates/Payment-released.html',
                        name=bidderfullname,
                        title=str(jobCollection['title']),
                        jobber=jobberfullname)
                    Mail.send(msg)
                    EmailTracks.insert({
                        "emailtrackid":
                        CommonUtils.generateRandomNo(EmailTracks,
                                                     "emailtrackid"),
                        "userid":
                        int(request.json['touserid']),
                        "email":
                        bidderEmail,
                        "subject":
                        subject,
                        "emailtext":
                        msg.html,
                        "createdatetime":
                        datetime.now(),
                        "updatedatetime":
                        datetime.now()
                    })

                else:
                    print("No email of jobber.")

            else:
                jobBidsData = JobBids.find_one(
                    {
                        "userid": userid,
                        "jobid": int(request.json['jobid'])
                    }, {"_id": 0})
                JobBids.update({"bidid": int(jobBidsData['bidid'])},
                               {"$set": {
                                   "status": "completed"
                               }})
                jobCollection = Jobs.find_one(
                    {"jobid": int(request.json['jobid'])}, {"_id": 0})
                if jobCollection is not None:
                    total_completed_task = JobBids.find({
                        "jobid":
                        int(request.json['jobid']),
                        "status":
                        "completed"
                    }).count()
                    print
                    total_completed_task
                    if total_completed_task != 0:
                        if (total_completed_task >=
                                jobCollection['personsrequired']):
                            Jobs.update({"jobid": int(request.json['jobid'])},
                                        {"$set": {
                                            "jobstatus": "completed"
                                        }})

            updateJobBids = list(
                JobBids.find({"bidid": int(jobBidsData['bidid'])}, {"_id": 0}))
            return jsonify({
                "status": 200,
                "message": "Review Created.",
                "updateJobBids": updateJobBids
            })
        else:
            updateJobBids = list(
                JobBids.find(
                    {
                        "jobid": int(request.json['jobid']),
                        "userid": userid,
                        "active": True
                    }, {"_id": 0}))
            return jsonify({
                "status": 200,
                "message": "Review Data.",
                "updateJobBids": updateJobBids
            })

    else:
        updateJobBids = list(
            JobBids.find(
                {
                    "jobid": int(request.json['jobid']),
                    "userid": userid,
                    "active": True
                }, {"_id": 0}))
        return jsonify({
            "status": 200,
            "message": "this bid is not present",
            "updateJobBids": updateJobBids
        })
Пример #22
0
def register():
    try:

        firstname = request.json['fname']
        lastname = request.json['lname']
        email = request.json['email']
        regtype = int(request.json['regtype'])
        mobile = request.json['mobile']
        city = request.json['city']
        skill = request.json['skill']
        state = request.json['state']
        country = request.json['country']
        picurl = request.json['picurl']
        gender = request.json['gender']

        if picurl == '':
            picurl = "default-image.jpg"

        if city != "":
            citylist = db.city.find_one({"city": city}, {"_id": 0, "cityid": 1})
            cityid = citylist['cityid']
        else:
            cityid = ""

        if state != "":
            statelist = db.state.find_one({"state": state}, {"_id": 0, "stateid": 1})
            stateid = statelist['stateid']
        else:
            stateid = ""

        if country != "":
            countrylist = db.country.find_one({"country": country}, {"_id": 0, "countryid": 1})
            countryid = countrylist['countryid']
        else:
            countryid = ""

        addressJSON = {
            "address1": request.json['address1'],
            "address2": request.json['address2'],
            "city": cityid,
            "state": stateid,
            "country": countryid,
            "pincode": request.json['pincode']
        }
        salt = CommonUtils.generateRandomName()
        emailhash = CommonUtils.getHashValue()
        token = CommonUtils.generateRandomName()

        password = request.json['password']
        password = CommonUtils.password_hash(password, salt)
        sociallogin = False
        emailverified = False
        fbid = ""
        fbaccesstoken = ""
        registeredfrom = "jobwork"

        # return jsonify({"ok":1})
        userdata = list(User.find({"email": email}, {"_id": 0}))
        #userdata=list(User.find_one({"email":email},{"id":0,"emailverified":1}))
        #return jsonify({"ok": len(userdata)})
        #print(userdata[0]['emailverified'])

        if len(userdata)==0:
            print("do resigtration")
            userid = CommonUtils.generateRandomNo(User, "userid")
            User.insert({"userid": userid,
                         "signupJSON": "",
                         "email": email,
                         "emailverified": emailverified,
                         "emailhash": emailhash,
                         "mobile": mobile,
                         "mobileverified": False,
                         "mobileotp": "",
                         "isdcode": None,
                         "fbid": fbid,
                         "fbaccesstoken": fbaccesstoken,
                         "password": password,
                         "salt": salt,
                         "token": token,
                         "firstname": firstname,
                         "lastname": lastname,
                         "isadmin": False,
                         "createddatetime": datetime.now(),
                         "updateddatetime": datetime.now(),
                         "addressJSON": addressJSON,
                         "paymentdetailsJSON": [],
                         "skillsJSON": skill,
                         "languagesJSON": [],
                         "educationCSV": [],
                         "workplaceCSV": [],
                         "certificateJSON": [],
                         "proJSON": [],
                         "forgotpasswordJSON": [],
                         "gender": gender,
                         "dob": "",
                         "aboutme": "",
                         "picurl": picurl,
                         "reportedJSON": [],
                         "notificationJSON": [],
                         "socaillogin": sociallogin,
                         "facebookpicurl": "",
                         "active": True,
                         "paypal_id": "",
                         "registeredfrom": registeredfrom
                         })
            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('sample.html', name=firstname,
                                       resetLink=reset_password_link, email=email)
            mail.send(msg)
            #return jsonify({"ok": 1})

            EmailTracks.insert({"emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": userid, "email": email,
                 "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(),
                 "updatedatetime": datetime.now()})
            return jsonify({"Status":200,"message":"verification mail sent"})

        elif userdata[0]['emailverified']==False:
                emailhash=CommonUtils.getHashValue()
                userid = CommonUtils.generateRandomNo(User, "userid")
                db.user.remove({"email":email})
                User.insert({"userid": userid,
                             "signupJSON": "",
                             "email": email,
                             "emailverified": emailverified,
                             "emailhash": emailhash,
                             "mobile": mobile,
                             "mobileverified": False,
                             "mobileotp": "",
                             "isdcode": None,
                             "fbid": fbid,
                             "fbaccesstoken": fbaccesstoken,
                             "password": password,
                             "salt": salt,
                             "token": token,
                             "firstname": firstname,
                             "lastname": lastname,
                             "isadmin": False,
                             "createddatetime": datetime.now(),
                             "updateddatetime": datetime.now(),
                             "addressJSON": addressJSON,
                             "paymentdetailsJSON": [],
                             "skillsJSON": skill,
                             "languagesJSON": [],
                             "educationCSV": [],
                             "workplaceCSV": [],
                             "certificateJSON": [],
                             "proJSON": [],
                             "forgotpasswordJSON": [],
                             "gender": gender,
                             "dob": "",
                             "aboutme": "",
                             "picurl": picurl,
                             "reportedJSON": [],
                             "notificationJSON": [],
                             "socaillogin": sociallogin,
                             "facebookpicurl": "",
                             "active": True,
                             "paypal_id": "",
                             "registeredfrom": registeredfrom
                             })
                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=firstname,
                                           resetLink=reset_password_link, email=email)
                mail.send(msg)
                EmailTracks.insert(
                    {"emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": userid,
                     "email": email,
                     "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(),
                     "updatedatetime": datetime.now()})

                return jsonify({"Status": 200, "message": "verification mail sent"})
        else:
            return jsonify({"status":202,"message":"email already exist"})





    except Exception as e:
        print(e)
Пример #23
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})
Пример #24
0
def conversation_create():
    userid = int(request.json['userid'])
    token = request.json['token']

    check_status = JobBids.find({
        "jobid": int(request.json['jobid']),
        "userid": userid,
        "active": True,
        "status": {
            "$in": ["selectedbyjobber", "approvedbybidder"]
        }
    }).count()

    if check_status == 1:

        secdatetime = datetime.utcnow() - timedelta(minutes=1)
        jobData = Jobs.find_one(
            {
                "jobid": int(request.json['jobid']),
                "active": True,
                "jobstatus": {
                    "$ne": "completed"
                },
                "expired": False
            }, {"_id": 0})

        if jobData is not None:
            if jobData['creatinguserid'] != userid:
                conversationData = Conversations.find_one(
                    {
                        "userid1": jobData['creatinguserid'],
                        "userid2": userid,
                        "jobid": jobData['jobid']
                    }, {"_id": 0})
                if conversationData is None:
                    conversationid = CommonUtils.generateRandomNo(
                        Conversations, "conversationid")
                    Conversations.insert({
                        "userid1":
                        jobData['creatinguserid'],
                        "userid2":
                        userid,
                        "lastdatetime":
                        datetime.now(),
                        "lastmessages":
                        None,
                        "lastmessagesuserid":
                        None,
                        "conversationid":
                        conversationid,
                        "jobid":
                        jobData['jobid'],
                        "createddatetime":
                        datetime.now(),
                        "createdatetimeinseconds":
                        calendar.timegm(secdatetime.utctimetuple()),
                        "updatedatetime":
                        datetime.now(),
                        "jobexpired":
                        False,
                        "active":
                        True
                    })

                    conversationList = list(
                        Conversations.find({
                            "conversationid": conversationid
                        }, {
                            "_id": 0
                        }).sort("createddatetime", -1))

                    return jsonify({
                        "status": 200,
                        "message": "Conversation Created.",
                        "conversationList": conversationList
                    })
                else:
                    return jsonify({
                        "status":
                        402,
                        "message":
                        "Conversation already Exist.",
                        "conversationData":
                        conversationData['conversationid']
                    })
            else:
                return jsonify({
                    "status": 402,
                    "message": "Conversation not on same user.",
                    "conversationData": []
                })
        else:
            return jsonify({
                "status": 402,
                "message": "No job data Found.",
                "conversationList": []
            })
    else:
        return jsonify({
            "status": 402,
            "message": "status not correct",
            "conversationList": []
        })
Пример #25
0
def user_forgotpassword_set():
    try:
        email = request.json['email']
        if request.json is not None:
            if request.json['hashData'] != "" and request.json[
                    'email'] != "" and request.json['password'] != "":
                getuserdata = User.find_one \
                    ({"forgotpasswordJSON.forgotpasswordhash" : request.json['hashData'] ,"email" :request.json['email']}, {"_id" :0})
                if getuserdata is not None:
                    salt = getuserdata['salt']
                    if request.json['password'].strip() != "":
                        password = hashlib.md5(request.json['password'].strip(
                        )).hexdigest() + salt
                        User.update(
                            {
                                "userid": getuserdata['userid'],
                                "email": request.json['email']
                            }, {"$set": {
                                "password": password
                            }})

                        subject = "Your SAVEonJOBS password has changed"
                        msg = Message(subject,
                                      sender=("SAVEonJOBS",
                                              "*****@*****.**"),
                                      recipients=[email])
                        msg.html = render_template(
                            '/emailTemplates/password_changed.html',
                            name=getuserdata['firstname'] + "  " +
                            getuserdata['lastname'])
                        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":
                            "Password Successfully changed."
                        })
                else:
                    return jsonify({
                        "status": 402,
                        "message": "No user is found."
                    })
            else:
                return jsonify({"status": 402, "message": "Data is empty."})
        else:
            return jsonify({"status": 402, "message": "No Data."})
    except Exception as e:
        return jsonify({"status": 500, "message": e.message})
Пример #26
0
    def bid_selection_entries(cls, userid, jobid, bidid, final_bid,
                              payment_details):
        total_bid_amount = float(final_bid['bidamount'])
        commission = float(total_bid_amount * 0.1)
        final_bidamount = float(total_bid_amount - commission)

        cls.insert({
            "userid":
            userid,
            "ledgerid":
            CommonUtils.generateRandomNo(Ledgers, "ledgerid"),
            "amount":
            float(total_bid_amount) * (-1),
            "datetime":
            datetime.datetime.now(),
            "type":
            "ESCROW",
            "jobid":
            int(jobid),
            "jobbidid":
            int(bidid),
            "paymentdetailsJSON":
            payment_details,
            "refunddetailsJSON":
            "",
            "refundcompletiondatetime":
            "",
            "payingdatetime":
            "",
            "remark":
            "",
            "active":
            True
        })

        cls.insert({
            "userid":
            userid,
            "ledgerid":
            CommonUtils.generateRandomNo(Ledgers, "ledgerid"),
            "amount":
            float(commission),
            "datetime":
            datetime.datetime.now(),
            "type":
            "COMMISSION",
            "jobid":
            int(jobid),
            "jobbidid":
            int(bidid),
            "paymentdetailsJSON":
            "",
            "refunddetailsJSON":
            "",
            "refundcompletiondatetime":
            "",
            "payingdatetime":
            "",
            "remark":
            "",
            "active":
            True
        })

        cls.insert({
            "userid":
            final_bid["userid"],
            "ledgerid":
            CommonUtils.generateRandomNo(Ledgers, "ledgerid"),
            "amount":
            float(final_bidamount),
            "datetime":
            datetime.datetime.now(),
            "type":
            "PAID",
            "jobid":
            int(jobid),
            "jobbidid":
            int(bidid),
            "paymentdetailsJSON":
            "",
            "refunddetailsJSON":
            "",
            "refundcompletiondatetime":
            "",
            "payingdatetime":
            "",
            "remark":
            "",
            "active":
            True
        })
Пример #27
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})
Пример #28
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"})
Пример #29
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"
Пример #30
0
def user_register():
    email = request.json['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 = request.json['firstname']
            lastname = request.json['lastname']
            usertype = request.json['usertype']
            city = int(request.json['city'])
            location = int(request.json['location'])
            device_token = request.json.get('device_token', "")
            fullname = firstname + " " + lastname
            password = request.json['password'].strip()

            if firstname and lastname and usertype and city:

                salt = CommonUtils.generateRandomName()

                # random.randrange(1000, 9999)

                signupJSON = SignupUtils.get_signup_json(email)

                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 make_response(
                    jsonify({
                        'status': 200,
                        'message': 'Successfull Register',
                        'userid': userid,
                        'token': token,
                        'city': city,
                        'location': location,
                        "firstname": firstname,
                        "lastname": lastname,
                        "picurl": "user-no-image.jpg",
                        "picPath": picPath
                    }), 200)
            else:
                return make_response(
                    jsonify({
                        'status': 202,
                        'message': 'Data can not be null.'
                    }), 400)
        else:
            return make_response(
                jsonify({
                    'status': 201,
                    'message': 'Email already exits.'
                }), 400)
    else:
        return make_response(
            jsonify({
                'status': 202,
                'message': 'Data can not be null.'
            }), 400)