Ejemplo n.º 1
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."})
Ejemplo n.º 2
0
def jobset():
    resultd = Jobs.find({})

    if resultd is not None:
        for result in resultd:
            currentdata = datetime.now()
            if result['duedate'] < currentdata:
                jobUpdate = Jobs.update(
                    {
                        "jobid": result['jobid'],
                        "draft": False
                    }, {"$set": {
                        "expired": True
                    }})

    return 'success'
Ejemplo n.º 3
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)
Ejemplo n.º 4
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"
Ejemplo n.º 5
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"})
Ejemplo n.º 6
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})
Ejemplo n.º 7
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
        })