Ejemplo n.º 1
0
def bids():
    data = []
    userid = int(request.json['userid'])
    type = int(request.json['type'])

    if (type == 0):
        typeKey = "$or"
        typeVal = [{"draft": True}, {"draft": False}]
    elif (type == 1):
        typeKey = "draft"
        typeVal = True
    elif (type == 2):
        typeKey = "draft"
        typeVal = False
    try:

        usersJob = list(JobBids.find({"userid": userid}, {"_id": 0}))
        count = 0
        for df in usersJob:
            #return jsonify({"count": d["jobid"]})
            #jobbids=list(JobBids.find({"jobid":d["jobid"]},{"_id":0}))
            jobdraftdata = list(
                Jobs.find({
                    "jobid": df["jobid"],
                    typeKey: typeVal
                }, {"_id": 0}))
            if (len(jobdraftdata) != 0):
                count = count + 1
                for con in jobdraftdata:
                    convertations = list(
                        Conversations.find(
                            {
                                "userid1": userid,
                                "userid2": con["creatinguserid"]
                            }, {"_id": 0}))
                    con.update({"conversations": convertations})
                data.append({"job": jobdraftdata})
            #data["job"].update({"bid":jobbids})

        return jsonify({
            "status": 200,
            "response": "ok",
            "message": count,
            "data": data,
            "error": False
        })
    except Exception as e:
        print(e)
        return jsonify({
            "error": True,
            "response": [],
            "message": "unknown error",
            "status": 400
        })
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 user_dashboard():
    URL = Constants.URL
    imagePath = Constants.IMAGE_PATH
    try:
        dashboardData = {}
        userid = int(request.json['userid'])
        userdata_array = User.find_one({
            "userid": userid,
            "active": True
        }, {"_id": 0})

        if userdata_array is not None:
            # Account Percentage

            if userdata_array['paymentdetailsJSON']['bankaccountname'] != "":
                overallAccountPercentage = 100
            else:
                overallAccountPercentage = 0

            verifyLen = len(userdata_array['proJSON']) - 1
            countVerificationPercentage = 0
            if userdata_array['proJSON']['facebookapproved'] == True:
                countVerificationPercentage = countVerificationPercentage + 1
            if userdata_array['proJSON']['policeverification'] == True:
                countVerificationPercentage = countVerificationPercentage + 1
            if userdata_array['proJSON'][
                    'professionalcertificationverified'] == True:
                countVerificationPercentage = countVerificationPercentage + 1
            if userdata_array['proJSON']['mobileverified'] == True:
                countVerificationPercentage = countVerificationPercentage + 1

            if countVerificationPercentage != 0:
                countVerificationPercentage = int(countVerificationPercentage *
                                                  100)
                overallVerificationPercentage = float(
                    countVerificationPercentage / verifyLen)
            else:
                overallVerificationPercentage = 0

            # Skills Verfication

            skillsLen = 5
            countSkillsPercentage = len(userdata_array['skillsJSON'])
            if countSkillsPercentage != 0:
                if countSkillsPercentage < skillsLen:
                    countSkillsPercentage = countSkillsPercentage * 100
                    overallSkillsPercentage = float(countSkillsPercentage /
                                                    skillsLen)
                else:
                    overallSkillsPercentage = 100
            else:
                overallSkillsPercentage = 0

            # Profile Verification

            profileLen = 13
            countProfilePercentage = 0
            if userdata_array['addressJSON']['city'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['addressJSON']['state'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['addressJSON']['country'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['addressJSON']['state'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['addressJSON']['country'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['addressJSON']['state'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['addressJSON']['country'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['firstname'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['lastname'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['locationid'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['email'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['mobile'] != "":
                countProfilePercentage = countProfilePercentage + 1
            if userdata_array['aboutme'] != "":
                countProfilePercentage = countProfilePercentage + 1

            if countProfilePercentage != 0:
                countProfilePercentage = countProfilePercentage * 100
                countProfilePercentage = float(countProfilePercentage /
                                               profileLen)
            else:
                countProfilePercentage = 0

            # Jobs Percentage

            jobs_posted = Jobs.find({"creatinguserid": int(userid)}).count()
            jobs_completed = JobBids.find({
                "userid": int(userid),
                "status": "completed"
            }).count()

            # Payment percentage
            total_received_amount = 0
            total_paid_refund = 0
            total_commission_refund = 0
            earned_amount = 0
            paid_amount = 0
            total_earning_amount = 0
            total_received_list = Ledgers.find(
                {
                    "userid": userid,
                    "type": "ESCROW"
                }, {"_id": 0})
            if total_received_list is not None:
                for total_received_dict in total_received_list:
                    total_received_amount += total_received_dict['amount']

            total_paid_refund_list = Ledgers.find(
                {
                    "userid": userid,
                    "type": "REFUND"
                }, {"_id": 0})
            if total_paid_refund_list is not None:
                for total_paid_refund_dict in total_paid_refund_list:
                    total_paid_refund += total_paid_refund_dict['amount']

            paid_amount = (total_received_amount - total_paid_refund) * (-1)

            total_earning_list = Ledgers.find(
                {
                    "userid": userid,
                    "type": "PAID OUT"
                }, {"_id": 0})
            if total_earning_list is not None:
                for total_earning_dict in total_earning_list:
                    total_earning_amount += total_earning_dict['amount']

            earned_amount = total_earning_amount

            # overall Percentage
            overallPercentage = float \
                (overallAccountPercentage + overallVerificationPercentage + overallSkillsPercentage + countProfilePercentage)
            overallPercentage = float(overallPercentage / 4)

            print(overallPercentage)

            fullname = userdata_array['firstname'] + ' ' + userdata_array[
                'lastname']
            picurl = URL + imagePath + userdata_array['picurl']
            dashboardData = {
                "picurl": picurl,
                "jobsPosted": jobs_posted,
                "jobsCompleted": jobs_completed,
                "earnedAmount": earned_amount,
                "paidAmount": paid_amount,
                "overallPercentage": overallPercentage,
                "accountPercentage": overallAccountPercentage,
                "verificationPercentage": overallVerificationPercentage,
                "skillsPercentage": overallSkillsPercentage,
                "profilePercentage": countProfilePercentage,
                "fullname": fullname
            }

            return jsonify({
                'status': 200,
                'message': 'Dashboard Data.',
                'dashboardData': dashboardData
            })
        else:
            return jsonify({
                'status': 402,
                'message': 'No data fouund',
                'dashboardData': dashboardData
            })

    except Exception as e:
        return jsonify({"status": 500, "message": "error"})
Ejemplo n.º 4
0
def job_all_list():
    try:
        allDataCollections = []

        sortDataAccording = request.json['sortDataAccording']
        city = request.json.get('city', "")
        location = request.json.get('location', "")
        radius = request.json.get('radius', "")
        jobType = request.json.get('jobType', "")
        budgetMin = request.json.get('budgetMin', "")
        budgetMax = request.json.get('budgetMax', '')
        searchstring = request.json.get('searchstring', '')
        page_offset = request.json.get('page_offset', 0)
        result = []
        lat = 0
        lng = 0
        job_location = []
        filterstring = {
            "active": True,
            "draft": False,
            "jobstatus": {
                "$in": ["pending", "reversebid"]
            }
        }
        sort_filter = []
        distance_filter_string = {
            "active": True,
            "draft": False,
            "jobstatus": {
                "$in": ["pending", "reversebid"]
            }
        }
        distance_job = []

        startCity = "252347228"

        if len(searchstring) != 0:
            stringData = '.*' + searchstring + '.*'

            getall = []  # for OR
            conditionOR = {
                '$options': 'i',
                '$regex': stringData
            }  # regex condition
            serchdatainarray = {'title': conditionOR}  # for title
            singleget = {"description": conditionOR}  # for description
            getall.append(serchdatainarray)
            getall.append(singleget)
            filterstring['$or'] = getall

        filterstring['expired'] = False
        distance_filter_string['expired'] = False
        mapCoordinate = {}
        cityResult = CityCollections.find_one({"cityid": int(startCity)},
                                              {"_id": 0})
        if cityResult is not None:
            lat = cityResult['gpsJSON']['lat']
            lng = cityResult['gpsJSON']['lng']
            mapCoordinate = {"lat": lat, "lng": lng}

        if radius != "":
            if location != "":
                location_result = Locations.find_one(
                    {"locationid": int(location)}, {"_id": 0})
                if location_result is not None:
                    lat = location_result['gpsJSON']['lat']
                    lng = location_result['gpsJSON']['lng']
                    mapCoordinate = {"lat": lat, "lng": lng}
                    print(mapCoordinate)
                location_gps_result = Locations.find({
                    "gpsJSON.lnglat": {
                        "$near": {
                            "$geometry": {
                                "type": "Point",
                                "coordinates": [lng, lat]
                            },
                            "$maxDistance": int(radius) * 1000
                        }
                    }
                })
                if location_gps_result is not None:
                    for location_gps in location_gps_result:
                        job_location.append(int(location_gps['locationid']))

            elif city != "":
                city_result = CityCollections.find_one({"cityid": int(city)},
                                                       {"_id": 0})
                if city_result is not None:
                    lat = city_result['gpsJSON']['lat']
                    lng = city_result['gpsJSON']['lng']
                    mapCoordinate = {"lat": lat, "lng": lng}
                    print(mapCoordinate)
                city_gps_result = Locations.find({
                    "gpsJSON.lnglat": {
                        "$near": {
                            "$geometry": {
                                "type": "Point",
                                "coordinates": [lng, lat]
                            },
                            "$maxDistance": int(radius) * 1000
                        }
                    }
                })
                if city_gps_result is not None:
                    for city_gps in city_gps_result:
                        job_location.append(int(city_gps['locationid']))
            elif mapCoordinate:
                city_gps_result = Locations.find({
                    "gpsJSON.lnglat": {
                        "$near": {
                            "$geometry": {
                                "type":
                                "Point",
                                "coordinates": [
                                    mapCoordinate.get("lng"),
                                    mapCoordinate.get("lat")
                                ]
                            },
                            "$maxDistance": int(radius) * 1000
                        }
                    }
                })
                if city_gps_result is not None:
                    for city_gps in city_gps_result:
                        job_location.append(int(city_gps['locationid']))
            print(job_location)

        if jobType != "allJobs":
            filterstring.update({"online": jobType})
            distance_filter_string.update({"online": jobType})

        if budgetMin or budgetMax:
            budget_filter = {"budget": {}}
            if budgetMin:
                budget_filter['budget']['$gte'] = int(budgetMin)
            if budgetMax:
                budget_filter['budget']['$lte'] = int(budgetMax)
            filterstring.update(budget_filter)
            distance_filter_string.update(budget_filter)

        if job_location:
            if city:
                filterstring.update({
                    "cityid": int(city),
                    "locationid": {
                        "$in": job_location
                    }
                })
            else:
                filterstring.update({
                    "cityid": int(startCity),
                    "locationid": {
                        "$in": job_location
                    }
                })
        else:
            if location:
                filterstring.update({"locationid": int(location)})
            if city:
                filterstring.update({"cityid": int(city)})
            else:
                filterstring.update({"cityid": int(startCity)})

        print(type(location))
        print(filterstring)

        if sortDataAccording == "" or sortDataAccording == "recent":
            sort_filter.append(("publisheddatetime", -1))
        elif sortDataAccording == "price_asc":
            sort_filter.append(("budget", 1))
        elif sortDataAccording == "distance":
            dist_centre = location if location else city if city else "252347228"
            dist_city_result = Locations.find_one(
                {"locationid": int(dist_centre)}, {"_id": 0})
            if dist_city_result:
                dist_lat = dist_city_result['gpsJSON']['lat']
                dist_lng = dist_city_result['gpsJSON']['lng']
                mapCoordinate = {"lat": dist_lat, "lng": dist_lng}
                print(mapCoordinate)
                radius = radius if radius else 50000
                distance_gps_result = Locations.aggregate([{
                    "$geoNear": {
                        "near": {
                            "type": "Point",
                            "coordinates": [dist_lng, dist_lat]
                        },
                        "maxDistance": radius * 1000,
                        "spherical": True,
                        "distanceField": "distance"
                    }
                }])
                if distance_gps_result is not None:
                    for distance_job_location in distance_gps_result:
                        distance_job.append({
                            "locationid":
                            distance_job_location['locationid'],
                            "distance":
                            distance_job_location['distance']
                        })
            distance_job = sorted(distance_job, key=lambda k: k['distance'])

            if city:
                distance_filter_string.update({
                    "cityid": int(city),
                    "locationid": int(dist_centre)
                })
                distance_result = Jobs.find(distance_filter_string, {
                    "_id": 0
                }).skip(page_offset).limit(Constants.PAGE_LIMIT)
                if distance_result:
                    for distance in distance_result:
                        result.append(distance)
            else:
                for distance in distance_job:
                    distance_filter_string.update({
                        "cityid":
                        int(dist_centre),
                        "locationid":
                        distance['locationid']
                    })
                    print(distance_filter_string)
                    distance_result = Jobs.find(distance_filter_string, {
                        "_id": 0
                    }).skip(page_offset).limit(Constants.PAGE_LIMIT)
                    if distance_result:
                        for dist in distance_result:
                            result.append(dist)

        else:
            sort_filter.append(("budget", -1))

        if sortDataAccording != "distance":
            result = Jobs.find(filterstring, {
                "_id": 0
            }).sort(sort_filter).skip(page_offset).limit(Constants.PAGE_LIMIT)
            print(result.count())

        if result:
            for resultData in result:
                # Job bidding Detail
                jobBids = list(
                    JobBids.find({"jobid": resultData['jobid']}, {"_id": 0}))
                if resultData.get('creatinguserid', None):
                    if resultData['creatinguserid']:
                        userData = User.find_one(
                            {"userid": int(resultData['creatinguserid'])},
                            {"_id": 0})
                        if userData:
                            fullname = userData['firstname'] + " " + userData[
                                'lastname']
                            if resultData['cityid']:
                                cityName = CityCollections.find_one(
                                    {"cityid": resultData['cityid']}, {
                                        "_id": 0,
                                        "city": 1
                                    })
                                cityName = cityName['city']
                            else:
                                cityName = ""
                            if userData.get('picurl', ""):
                                picurl = Constants.PROFIL_PIC_STATIC_PATH + userData[
                                    'picurl']
                            else:
                                picurl = Constants.PROFIL_PIC_STATIC_PATH + "user-no-image.jpg"

                            location_name = ""
                            if resultData['cityid'] and resultData[
                                    'locationid']:
                                jobMapResult = Locations.find_one(
                                    {
                                        "locationid": int(
                                            resultData['locationid'])
                                    }, {"_id": 0})
                                location_name = jobMapResult[
                                    'locationname'] + " - " + jobMapResult[
                                        'under']

                            else:
                                if not resultData['cityid']:
                                    jobMapCity = 252347228
                                else:
                                    jobMapCity = int(resultData['cityid'])
                                jobMapResult = CityCollections.find_one(
                                    {"cityid": jobMapCity}, {"_id": 0})

                            jobMapCoordinate = {}
                            if jobMapResult is not None:
                                lat = jobMapResult['gpsJSON']['lat']
                                lng = jobMapResult['gpsJSON']['lng']
                                jobMapCoordinate = {"lat": lat, "lng": lng}

                            MapResult = CityCollections.find_one(
                                {"cityid": int(resultData['cityid'])},
                                {"_id": 0})
                            if MapResult is not None:
                                city_lat = MapResult['gpsJSON']['lat']
                                city_lng = MapResult['gpsJSON']['lng']
                                mapCoordinate = {
                                    "lat": city_lat,
                                    "lng": city_lng
                                }

                            userDataCollection = {
                                "fullname": fullname,
                                "cityname": cityName,
                                "locationname": location_name,
                                "picurl": picurl,
                                "totalJobBids": len(jobBids),
                                "jobMapCoordinate": jobMapCoordinate,
                                "mapCoordinate": mapCoordinate
                            }
                            resultData.update(userDataCollection)
                            allDataCollections.append(resultData)

            return jsonify({
                "status": 200,
                "message": "Job List.",
                "allTask": allDataCollections,
                "countData": len(allDataCollections)
            })
        else:
            return jsonify({
                "status": 200,
                "message": "No data.",
                "allTask": result,
                "countData": len(allDataCollections)
            })
    except Exception as e:
        CommonUtils.print_exception()
        return jsonify({"status": 500, "message": str(e)})
Ejemplo n.º 5
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
        })