Beispiel #1
0
def job_comment_list():
    # Check authentications keys
    response = []
    jobid = int(request.json['jobid'])
    jobCommentsList = db.jobcomments.find({
        "jobid": jobid,
        "active": True
    }, {"_id": 0})
    job = Jobs.find_one({"jobid": jobid})
    jobowner = job['creatinguserid']
    for data in jobCommentsList:

        userId = User.find_one({"userid": data['userid']})
        username = userId['firstname'] + " " + userId['lastname']
        data.update({"username": username})
        if (data['userid'] == jobowner):
            data.update({"jobowner": True})
        else:
            data.update({"jobowner": False})
        response.append(data)
    if len(response) != 0:
        return jsonify({
            "status": 200,
            "message": "Job Comments List.",
            "jobCommentsList": response,
            "error": False
        })
    else:
        return jsonify({
            "status": 200,
            "message": "Job Comments List empty",
            "jobCommentsList": [],
            "error": True
        })
Beispiel #2
0
def jobDetails():
    jobid = request.json['jobid']
    job = list(Jobs.find_one({"jobid": jobid}, {"_id": 0}))
    if job is not None:
        return jsonify({"detail": job})
    else:
        return jsonify({"message": "no job found with this id"})
Beispiel #3
0
def notification_list():
    URL = Constants.URL
    imagePath = Constants.IMAGE_PATH
    userid = int(request.json['userid'])
    token = request.json['token']
    notificationArray = []

    notificationData = list(
        Notifications.find({
            "notificationtouserid": userid
        }, {
            "_id": 0
        }).sort("createddatetime", -1))
    notificationUnread = list(
        Notifications.find({
            "notificationtouserid": userid,
            "isread": False
        }, {"_id": 0}))

    print(notificationData)
    if len(notificationData) > 0:
        for collections in notificationData:
            jobber = {}
            if collections['notificationfromuserid'] != -1:
                jobber = Jobs.find_one({"jobid": int(collections['jobid'])}, {
                    "_id": 0,
                    "creatinguserid": 1
                })
                userData = User.find_one(
                    {"userid": int(collections['notificationfromuserid'])},
                    {"_id": 0})
                if userData is not None:
                    fullname = userData['firstname'] + " " + userData[
                        'lastname']
                    if userData['picurl'] != "":
                        picurl = URL + imagePath + userData['picurl']
                    else:
                        picurl = URL + imagePath + "user-no-image.jpg"
                    if userData['addressJSON']['city'] != "":
                        cityNamedata = CityCollections.find_one(
                            {"cityid": userData['addressJSON']['city']}, {
                                "_id": 0,
                                "city": 1
                            })
                        cityName = cityNamedata['city']
                    else:
                        cityName = ""
                else:
                    fullname = ""
                    picurl = URL + imagePath + "user-no-image.jpg"
                    cityName = ""
            else:
                fullname = "SAVEonJOBS"
                picurl = URL + "static/front_end/images/logo1.png"
                cityName = ""

            userDataCollection = {
                "fullname": fullname,
                "cityname": cityName,
                "picurl": picurl,
                "jobber": jobber
            }
            collections.update(userDataCollection)
            notificationArray.append(collections)
        return jsonify({
            "status": 200,
            "message": "Notification Data.",
            "notificationArray": notificationArray,
            "notificationUnread": len(notificationUnread)
        })
    else:
        return jsonify({
            "status": 200,
            "message": "No Notification data Found.",
            "notificationArray": [],
            "notificationUnread": notificationUnread
        })
Beispiel #4
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
        })
Beispiel #5
0
def paypal_payment():
    try:
        userid = int(request.json['userid'])
        pay_id = request.json['payid']
        print(pay_id)
        payment = Payment.find(pay_id)
        print(payment)
        transactions = []
        transaction_amount = {}
        # credit_card = {}
        sales_id = 0
        soj_transaction_id = 0
        transactionstatus = ""
        # for card_details in payment.payer.funding_instruments:
        # 	if card_details.has_key('credit_card_token'):
        # 		credit_card = {"expire_year":card_details.credit_card_token.expire_year,
        # "type":card_details.credit_card_token.type,"number":card_details.credit_card_token.number,
        # "expire_month":card_details.credit_card_token.expire_month}
        # 	elif card_details.has_key('credit_card'):
        # 		credit_card = {"expire_year":card_details.credit_card.expire_year,
        # "type":card_details.credit_card.type,"number":card_details.credit_card.number,
        # "expire_month":card_details.credit_card.expire_month}
        # transactions.append(credit_card)
        for transaction_details in payment.transactions:
            transaction_amount = {"currency": transaction_details.amount.currency,
                                  "total": transaction_details.amount.total}
            sales_link = transaction_details['related_resources'][0]['sale']['links'][0]['href']
            sales_list = sales_link.split('sale')[1]
            sales_id = sales_list.split('/')[1]
            soj_transaction_id = int(transaction_details.description)
            transactionstatus = int(request.json['transactionid'])
        transactions.append(transaction_amount)
        payment_details = {"payment": payment.id, "sales_id": sales_id, "paymenttype": payment.payer.payment_method,
                           "state": payment.state, "transaction_details": transactions}
        if payment.state == "approved":

            print(soj_transaction_id)
            TransactionTrack.update({
                "transactionid": soj_transaction_id
            }, {
                "$set": {
                    "transactionstatus": transactionstatus,
                    "transactionresponse": payment_details,
                    "responsedatetime": datetime.datetime.now()
                }
            })

            transactions_details_from_database = TransactionTrack.find_one({"transactionid": soj_transaction_id},
                                                                           {"_id": 0})
            print(transactions_details_from_database)

            bidid = transactions_details_from_database['jobbid']
            jobid = transactions_details_from_database['jobid']

            final_bid = JobBids.find_one({"bidid": int(bidid)}, {"_id": 0})

            completionremarks = ""
            # completionstatus = ""
            bidcanceldatetime = ""
            bidcancellationreason = ""
            # bidselected = False
            jobberfullname = ""
            # jobberEmail = None
            # jobberMobile = None
            bidderfullname = ""
            bidder_email = None
            # bidderMobile = None
            person_selected = 0

            if final_bid is not None:

                job_collection = Jobs.find_one({"jobid": final_bid['jobid']}, {"_id": 0})
                if job_collection:
                    try:
                        person_selected = int(job_collection['personsselected'])
                    except ValueError:
                        pass

                    user_jobber_collection = User.find_one({"userid": job_collection['creatinguserid']}, {"_id": 0})
                    if user_jobber_collection is not None:
                        jobberfullname = user_jobber_collection['firstname'] + " " + user_jobber_collection['lastname']
                        # jobberEmail = user_jobber_collection['email']
                        # jobberMobile = user_jobber_collection['mobile']

                    user_bidder_collection = User.find_one({"userid": final_bid['userid']}, {"_id": 0})
                    if user_bidder_collection is not None:
                        bidderfullname = user_bidder_collection['firstname'] + " " + user_bidder_collection['lastname']
                        bidder_email = user_bidder_collection['email']
                        # bidderMobile = user_bidder_collection['mobile']
                else:
                    print("No jobs")
                if request.json['status'] == "selectedbyjobber":
                    if final_bid['status'] == "pending":
                        print(transaction_amount)
                        JobBids.update({
                            "bidid": int(bidid)
                        }, {
                            "$set": {
                                "selected": True,
                                "final_bidamount": int(float(transaction_amount['total'])),
                                "bidcanceldatetime": bidcanceldatetime,
                                "bidcancellationreason": bidcancellationreason,
                                "status": "selectedbyjobber",
                                "completionstatus": "pending",
                                "completionremarks": completionremarks
                            }
                        })

                        if job_collection['personsrequired'] > person_selected:
                            if job_collection['personsrequired'] == person_selected + 1:
                                Jobs.update({"jobid": int(jobid)}, {"$set": {
                                    "personsselected": int(person_selected + 1),
                                    "jobstatus": "allotted"
                                }})
                            else:
                                Jobs.update({"jobid": int(jobid)}, {"$set": {
                                    "personsselected": int(person_selected + 1)
                                }})
                        # Ledger Entries
                        Ledgers.bid_selection_entries(userid, jobid, bidid, final_bid, payment_details)

                        # Push Notification Bid Accepted
                        PushNotificationUtils.notify_bid_accepted(userid, jobid, bidid, job_collection, jobberfullname,
                                                                  final_bid)
                        # Bid Accepted Email
                        EmailUtils.send_bid_accpeted_mail(final_bid['userid'], bidder_email, job_collection['title'],
                                                          bidderfullname, jobberfullname, transaction_amount['total'])

                elif request.json['status'] == "reversebid":
                    job_bid_detail = JobBids.find_one({"bidid": int(bidid)}, {"_id": 0})
                    if job_bid_detail is not None:

                        if job_bid_detail['status'] == 'pending':
                            total_bid_amount = int(float(transaction_amount['total']))
                            # updating bidamount array and reverse bid array
                            reverse_bid_data = {"reversebidamount": int(float(transaction_amount['total'])),
                                                "reversebiddatetime": datetime.datetime.now()}
                            JobBids.update({"bidid": int(bidid)}, {"$set": {"status": "reversebid",
                                                                            "reversebid": reverse_bid_data,
                                                                            "final_bidamount": total_bid_amount
                                                                            }})
                            # Bid Reverse Entried
                            Ledgers.bid_reverse_entries(userid, jobid, bidid, final_bid, payment_details)
                            # Bid Reverse Push Notification
                            PushNotificationUtils.notify_bid_reverse(userid, jobid, bidid, job_collection,
                                                                     bidderfullname, job_bid_detail)
                            # Bid Reverse Email
                            EmailUtils.send_reverse_bid_mail(final_bid['userid'], bidder_email, job_collection['title'],
                                                             bidderfullname, jobberfullname,
                                                             transaction_amount['total'])
        return make_response(jsonify({"status": 200, "message": "Payment Successful"}), 200)
    except ResourceNotFound as e:
        print("Payment Not Found")
        print(str(e))
        return make_response(jsonify({"status": 500, "message": "Something went wrong, Please try again!"}), 500)
    except Exception as e:
        print(str(e))
        return make_response(jsonify({"status": 500, "message": "Something went wrong, Please try again!"}), 500)
Beispiel #6
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": []
        })
Beispiel #7
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": []
        })
Beispiel #8
0
def user_profile_fetch():
    URL = Constants.URL
    imagePath = Constants.IMAGE_PATH

    try:
        # Check Authentication Key.
        userid = int(request.json['userid'])
        token = request.json['token']
        otherUserId = int(request.json['messageUserid'])

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

        resultArray = {}
        responseArr = []
        temp = []

        reportStatus = False

        if len(userdata_array) > 0:
            for collectionInfo in userdata_array:
                reportedJSONdata = collectionInfo['reportedJSON']
                if len(reportedJSONdata) > 0:
                    for reportStatusData in reportedJSONdata:
                        # print reportStatusData['byuserid']
                        if reportStatusData['byuserid'] == userid:
                            reportStatus = True
                else:
                    reportStatus = False

                reviewsDataList = list \
                    (JobReviews.find({"touserid" :otherUserId, "adminaction" :True, "active" : True} ,{"_id" :0}))
                reviewsData = []
                if len(reviewsDataList) > 0:
                    for collectionInfoReview in reviewsDataList:
                        userdata = User.find_one(
                            {
                                "userid": collectionInfoReview['userid'],
                                "active": True
                            }, {"_id": 0})
                        if userdata is not None:
                            fullname = userdata['firstname'] + ' ' + userdata[
                                'lastname']
                            if userdata['picurl'] != "":
                                picurl = URL + imagePath + userdata['picurl']
                            else:
                                picurl = URL + imagePath + "user-no-image.jpg"
                        if collectionInfoReview.has_key('jobid'):
                            jobData = Jobs.find_one(
                                {
                                    "jobid": collectionInfoReview['jobid'],
                                    "active": True
                                }, {"_id": 0})
                            if jobData is not None:
                                title = jobData['title']
                            else:
                                title = ""
                        editionData = {
                            "fullname": fullname,
                            "jobtitle": title,
                            "picurl": picurl
                        }
                        collectionInfoReview.update(editionData)
                        reviewsData.append(collectionInfoReview)
                else:
                    reviewsData = []

                locationName = ""
                cityName = ""

                if collectionInfo['addressJSON']['city'] != "":
                    citynamedata = CityCollections.find_one(
                        {"cityid": int(collectionInfo['addressJSON']['city'])},
                        {"_id": 0})
                    cityName = citynamedata['city']
                    countrynamedata = CityCollections.find_one(
                        {"countryid": int(citynamedata['countryid'])},
                        {"_id": 0})
                    print(countrynamedata)
                    #return jsonify({"ok": 1})
                    countryName = countrynamedata['countryid']

                else:
                    cityName = ""
                    countryName = ""

                if collectionInfo['locationid'] != "":
                    locationNameData = Locations.find_one(
                        {"locationid": int(collectionInfo['locationid'])}, {
                            "_id": 0,
                            "locationname": 1,
                            "under": 1
                        })
                    if locationNameData is not None:
                        if locationNameData['under'] != "":
                            locationName = str(locationNameData['under'] ) +" -  " +str \
                                (locationNameData['locationname'])
                        else:
                            locationName = str(
                                locationNameData['locationname'])
                else:
                    locationName = ""
                allCityData = list(
                    CityCollections.find({}, {
                        "_id": 0,
                        "cityid": 1,
                        "city": 1
                    }))
                # allcity = []
                # if len(allCityData) > 0:
                # 	for getAllCityData in allCityData:
                # 		allcity.append({"cityid" : getAllCityData['cityid'], "city" : getAllCityData['city']})
                skillData = collectionInfo['skillsJSON']
                skillNameData = []
                if len(skillData) > 0:
                    for skillDataCollections in skillData:
                        skillNameData.append(skillDataCollections['skillname'])

                rating = 0  # Rating Initially 0

                userReview = list(
                    JobReviews.find(
                        {
                            "touserid": int(collectionInfo['userid']),
                            "active": True
                        }, {
                            "_id": 0,
                            "rating": 1
                        }))
                if len(userReview) > 0:
                    totalUserReview = len(userReview)
                    if userReview is not None:
                        for userRating in userReview:
                            rating = rating + userRating['rating']

                    tatalRating = int(rating / totalUserReview)
                else:
                    tatalRating = 0

                portfolioData = list(
                    UserPortfolio.find(
                        {
                            "userid": otherUserId,
                            "active": True,
                        }, {"_id": 0}))
                picurlPath = URL + imagePath + collectionInfo['picurl']
                documentsPath = URL + Constants.DOC_PATH

                portfolioDataPath = URL + Constants.PORTFOLIO_PATH
                updateJSON = {
                    "cityname": cityName,
                    "locationName": locationName,
                    "countryname": countryName,
                    "allcity": allCityData,
                    "skillName": skillNameData,
                    "reviewsData": reviewsData,
                    "portfolioData": portfolioData,
                    "reportStatus": reportStatus,
                    "picurlPath": picurlPath,
                    "userrating": tatalRating,
                    "documentsPath": documentsPath,
                    "portfolioDataPath": portfolioDataPath
                }
                collectionInfo.update(updateJSON)
                responseArr.append(collectionInfo)
            resultArray['data'] = responseArr
            resultArray['status'] = "200"
            resultArray['message'] = "Userdata List."
        else:
            resultArray['data'] = responseArr
            resultArray['status'] = "400"
            resultArray['message'] = "No data in List."

        return jsonify(resultArray)

    except Exception as e:
        print(e)
        return jsonify({"status": 500})
Beispiel #9
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})
Beispiel #10
0
def invoice_list():
    userid = int(request.json['userid'])
    token = request.json['token']
    invoiceid = request.json['invoiceid']
    if invoiceid == 1:
        invoiceData = list(
            Invoice.find({"invoiceid": int(request.json['invoiceid'])},
                         {"_id": 0}))
    else:
        invoiceData = list(Invoice.find({"userid": userid}, {"_id": 0}))

    invoiceAllData = {}
    invoiceArray = []

    if len(invoiceData) > 0:
        for invoiceDataArray in invoiceData:
            # jobsDetail Data
            jobsDetail = Jobs.find_one(
                {
                    "jobid": int(invoiceDataArray['jobid']),
                    "active": True
                }, {"_id": 0})
            # Job Created By User
            createdUserDetail = User.find_one(
                {
                    "userid": jobsDetail['creatinguserid'],
                    "active": True
                }, {"_id": 0})
            # For job Bid and Comments (How many user bid on this job.)
            job_biding_count = JobBids.find(
                {
                    "jobid": invoiceDataArray['jobid']
                }, {
                    "_id": 0
                }).count()
            job_comment_count = JobComments.find(
                {
                    "jobid": invoiceDataArray['jobid']
                }, {
                    "_id": 0
                }).count()
            # For User who post this job (How many jobs bid by this user.)
            if createdUserDetail is not None:
                user_biding_count = JobBids.find(
                    {
                        "userid": createdUserDetail['userid']
                    }, {
                        "_id": 0
                    }).count()
                user_comment_count = JobComments.find(
                    {
                        "userid": createdUserDetail['userid']
                    }, {
                        "_id": 0
                    }).count()
                # Address Detail for created User
                citydetail = CityCollections.find_one(
                    {"cityid": createdUserDetail['addressJSON']['city']},
                    {"_id": 0})
                statedetail = StateCollections.find_one(
                    {"stateid": citydetail['stateid']}, {"_id": 0})
                countrydetail = CountryCollections.find_one(
                    {"countryid": citydetail['countryid']}, {"_id": 0})
                address2 = createdUserDetail['addressJSON']['address2']
                address1 = createdUserDetail['addressJSON']['address1']
                if address2 == "":
                    fullAddress = address1 + ","
                else:
                    fullAddress = address1 + ", " + address2 + ","
            else:
                fullAddress = ""
                user_biding_count = 0
                user_comment_count = 0

            # Billing to User
            billingUserDetail = User.find_one(
                {
                    "userid": invoiceDataArray['userid'],
                    "active": True
                }, {"_id": 0})
            # Address Detail for created User
            billingcitydetail = CountryCollections.find_one(
                {"cityid": billingUserDetail['addressJSON']['city']},
                {"_id": 0})
            billingstatedetail = StateCollections.find_one(
                {"stateid": billingcitydetail['stateid']}, {"_id": 0})
            billingcountrydetail = CountryCollections.find_one(
                {"countryid": billingcitydetail['countryid']}, {"_id": 0})
            billingaddress2 = billingUserDetail['addressJSON']['address2']
            billingaddress1 = billingUserDetail['addressJSON']['address1']
            if billingaddress2 == "":
                billingfullAddress = billingaddress1 + ","
            else:
                billingfullAddress = billingaddress1 + ", " + billingaddress2 + ","

            createdInfoCollection = {
                "createdByuserid": createdUserDetail['userid'],
                "createdByaddressJSON": createdUserDetail['addressJSON'],
                "createdByemail": createdUserDetail['email'],
                "createdByfirstname": createdUserDetail['firstname'],
                "createdBylastname": createdUserDetail['lastname'],
                "createdBymobile": createdUserDetail['mobile'],
                "createdByaddress": fullAddress,
                "createdBycity": citydetail['city'],
                "createdBystate": statedetail['state'],
                "createdBycountry": countrydetail['country'],
                "createdBypincode":
                createdUserDetail['addressJSON']['pincode'],
                "createdByactive": createdUserDetail['active'],
                "createdByuser_biding_count": user_biding_count,
                "createdByuser_comment_count": user_comment_count,
                "job_biding_count": job_biding_count,
                "user_comment_count": user_comment_count,
                "jobsDetail": jobsDetail,
                "billinguserid": billingUserDetail['userid'],
                "billingaddressJSON": billingUserDetail['addressJSON'],
                "billingemail": billingUserDetail['email'],
                "billingfirstname": billingUserDetail['firstname'],
                "billinglastname": billingUserDetail['lastname'],
                "billingmobile": billingUserDetail['mobile'],
                "billingaddress": billingfullAddress,
                "billingcity": billingcitydetail['city'],
                "billingstate": billingstatedetail['state'],
                "billingcountry": billingcountrydetail['country'],
                "billingpincode": billingUserDetail['addressJSON']['pincode'],
                "billingactive": billingUserDetail['active'],
            }
            invoiceDataArray.update(createdInfoCollection)
            invoiceArray.append(invoiceDataArray)
        return jsonify({
            "status": 200,
            "message": "Invoice List.",
            "invoiceAllData": invoiceArray
        })
    else:
        return jsonify({
            "status": 200,
            "message": "No Data.",
            "invoiceAllData": invoiceArray
        })
Beispiel #11
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
        })