Пример #1
0
def user_update():
    try:
        userid = int(request.json['userid'])
        token = request.json['token']
        location = request.json['location']
        if location != "":
            location = int(location)

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

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

            print(skills)
            print(type(skills))

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

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

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

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

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

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

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

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

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

            resultArray = {}
            responseArr = []

            if len(userdata_array) > 0:
                for collectionInfo in userdata_array:
                    # cityname = citycollections.find_one({"cityid":collectionInfo['addressJSON']['city']},{"_id":0})
                    # allCityData = list(CityCollections.find({}, {"_id": 0, "cityid": 1, "city": 1}))
                    # allcity = []
                    # if len(allCityData) > 0:
                    # 	for getAllCityData in allCityData:
                    # 		allcity.append({"cityid" : getAllCityData['cityid'], "city" : getAllCityData['city']})

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

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

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

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

                            tatalRating = int(rating / totalUserReview)
                    else:
                        tatalRating = 0
                    allCityData = list(
                        CityCollections.find({}, {
                            "_id": 0,
                            "cityid": 1,
                            "city": 1
                        }))
                    picurlPath = Constants.PROFIL_PIC_STATIC_PATH + collectionInfo[
                        'picurl']
                    portfolioData = list(
                        UserPortfolio.find({
                            "userid": userid,
                            "active": True,
                        }, {"_id": 0}))
                    documentsPath = Constants.URL + Constants.DOC_PATH
                    portfolioDataPath = Constants.URL + Constants.PORTFOLIO_PATH
                    updateJSON = {
                        "cityname": city_name,
                        "locationName": location_name,
                        "countryname": country_name,
                        "allcity": allCityData,
                        "skillName": skillNameData,
                        "portfolioData": portfolioData,
                        "picurlPath": picurlPath,
                        "userrating": tatalRating,
                        "documentsPath": documentsPath,
                        "portfolioDataPath": portfolioDataPath
                    }
                    collectionInfo.update(updateJSON)

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

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

    except Exception as e:
        CommonUtils.print_exception()
        return make_response(jsonify({"status": 500, "message": str(e)}), 500)
Пример #2
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)})