Пример #1
0
def get_user_lists(userid=None):
    reponse_obj = Base()
    try:
        if userid is not None:

            usersCollection = db['users']

            user = usersCollection.find_one({"_id": ObjectId(userid)})

            reponse_obj.Data = jsonpickle.decode(
                dumps({
                    'shortlist': user['shortlist'],
                    'applylist': user['applylist']
                }))
            BaseUtils.SetOKDTO(reponse_obj)

    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponse_obj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    json_obj = jsonpickle.encode(reponse_obj, unpicklable=False)
    response = Response(json_obj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
Пример #2
0
def create_user():
    reponse_obj = Base()
    try:
        user_first_name = request.form['firstName']
        user_last_name = request.form['lastName']
        user_email = request.form['email']
        user_phone = request.form['phone']
        user_auth0_user_id = request.form['auth0UserId']
        user_shortlist_list = jsonpickle.decode(request.form['shortlist'])

        users_collection = db['users']
        listings_collection = db['listings']

        #validate existing user
        user = users_collection.find_one({'email': user_email})
        print "user" , user

        return_user_id = None
        # TODO: fix this, the idea is not wo overwrite the shortlist. This is suposed to be done in front end, further auth0 info is required.
        if user is None:

            user_shortlist_list_object_id = []
            for user_shortlist_list_element in user_shortlist_list:
                user_shortlist_list_object_id.append(ObjectId(user_shortlist_list_element))



            shortlist_listings_cursors = listings_collection.find({"_id" : {"$in" : user_shortlist_list_object_id}})
            shortlist_listings_list = list(shortlist_listings_cursors)

            user_obj = {
                'firstname': user_first_name,
                'lastname': user_last_name,
                'email': user_email,
                'phone': user_phone,
                'auth0userid': user_auth0_user_id,
                'comments': [],
                'shortlist': shortlist_listings_list,
                'applylist': []
            }

            return_user_id = users_collection.insert(user_obj)
        else:
            return_user_id = user['_id']

        reponse_obj.Data = jsonpickle.decode(dumps({'UserId': return_user_id}))

        BaseUtils.SetOKDTO(reponse_obj)
        
    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponse_obj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    json_obj = jsonpickle.encode(reponse_obj, unpicklable=False)
    response = Response(json_obj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
Пример #3
0
def getListingById(listingid=None):

    reponseObj = Base()

    try:
        if listingid is not None:
            ## select mondodb collection
            listingsCollection = db['listings']
            ## retrieve listing from db
            listingsObject = listingsCollection.find_one(
                {'_id': ObjectId(listingid)})
            ## serialize listing
            reponseObj.Data = jsonpickle.decode(dumps(listingsObject))
            BaseUtils.SetOKDTO(reponseObj)
    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponseObj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    jsonObj = jsonpickle.encode(reponseObj, unpicklable=False)
    response = Response(jsonObj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
def get_listings_details_by_id_list_method():

    reponse_obj = Base()

    try:
        listings_id_list = jsonpickle.decode(request.form['listings_id_list'])
        print "listings_id_list", listings_id_list
        ## select mondodb collection
        listingsCollection = db['listings']

        listings_object_id_list = MongoUtils.to_object_id(listings_id_list)
        result_listings_cursors = listingsCollection.find(
            {'_id': {
                '$in': listings_object_id_list
            }})
        result_listings_list = list(result_listings_cursors)

        reponse_obj.Data = jsonpickle.decode(dumps(result_listings_list))
        BaseUtils.SetOKDTO(reponse_obj)
        # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponse_obj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    json_obj = jsonpickle.encode(reponse_obj, unpicklable=False)
    response = Response(json_obj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
def getUserPreferences(userPreferencesId=None):
    reponseObj = Base()
    # {"apartmentType":"1 Bedroom" , "personType":"student","hoodType":"classic", "budget":5000, "moveIn":20143101}

    try:
        if (userPreferencesId != None):
            preferencesCollection = db['preferences']
            pref_obj = preferencesCollection.find_one(
                {"_id": ObjectId(userPreferencesId)})
            print pref_obj
            filtersObj = dict()
            if "filters" in pref_obj.keys():
                filtersObj = pref_obj['filters']
            reponseObj.Data = Preference(
                jsonpickle.decode(dumps(pref_obj['_id'])), filtersObj)
            print "reponseObj.Data", reponseObj.Data
            BaseUtils.SetOKDTO(reponseObj)

    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponseObj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    jsonObj = jsonpickle.encode(reponseObj, unpicklable=False)
    response = Response(jsonObj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
Пример #6
0
def validate_user(userauth0id=None):
    reponse_obj = Base()
    print "userauth0id: ", userauth0id
    try:
        if userauth0id is not None:

            usersCollection = db['users']

            user = usersCollection.find_one({"auth0userid": userauth0id})

            user_id = None
            if user is not None:
                user_id = user['_id']

            reponse_obj.Data = jsonpickle.decode(dumps({'UserId': user_id}))
            BaseUtils.SetOKDTO(reponse_obj)

    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponse_obj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    print "reponse_obj", reponse_obj
    json_obj = jsonpickle.encode(reponse_obj, unpicklable=False)
    response = Response(json_obj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
def add_trotter_comment():
    reponse_obj = Base()
    try:

        json_object = request.form.keys()
        requestObj = json.loads(json_object[0])

        request_user = requestObj['userid']
        request_trotter = requestObj['trotterid']
        request_comment = requestObj['comment']

        usersCollection = db['users']
        trottersCollection = db['trotters']

        user = usersCollection.find_one({"_id" : ObjectId(request_user)})
        trotter = trottersCollection.find_one({"_id" : ObjectId(request_trotter)})

        comments = user['comments']
        comment = dict()
        comment['commenter'] = trotter['fullname']
        comment_date = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
        comment['timestamp'] = time.time()
        comment['date'] = comment_date
        comment['text'] = request_comment
        comment['type'] = 'trotter'
        comments.append(comment)

        # for entry in shortlist:
        #     if entry['_id'] == ObjectId(request_listing):
        #         if 'comments' not in entry.keys():
        #             entry['comments'] = []
        #         entry['comments'].append(comment)
        #         result_bool = True

        usersCollection.update({'_id':user['_id']}, {'$set':{'comments':comments}})

        reponse_obj.Data = jsonpickle.decode(dumps({'comments': comments}))
        BaseUtils.SetOKDTO(reponse_obj)

        
    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponse_obj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    json_obj = jsonpickle.encode(reponse_obj, unpicklable=False)
    response = Response(json_obj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
Пример #8
0
def add_bulk_shortlist():
    reponse_obj = Base()
    try:
        request_listings = request.form['listingids']
        request_user = request.form['userid']

        request_listings_split = request_listings.split(',')

        bulklistings = []
        for r_listing in request_listings_split:
            bulklistings.append(ObjectId(r_listing))

        print bulklistings

        listingsCollection = db['listings']
        usersCollection = db['users']

        user = usersCollection.find_one({"_id": ObjectId(request_user)})
        listings_result = listingsCollection.find(
            {"_id": {
                "$in": bulklistings
            }})

        listings = list(listings_result)

        print listings

        shortlist = user['shortlist']
        for listing in listings:
            shortlist.append(listing)

        usersCollection.update({'_id': user['_id']},
                               {'$set': {
                                   'shortlist': shortlist
                               }})

        reponse_obj.Data = jsonpickle.decode(dumps({'_id': user['_id']}))
        BaseUtils.SetOKDTO(reponse_obj)

    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponse_obj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    json_obj = jsonpickle.encode(reponse_obj, unpicklable=False)
    response = Response(json_obj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
Пример #9
0
def change_status():
    reponse_obj = Base()
    try:
        request_listing = request.form['listingId']
        request_user = request.form['userId']
        request_status = request.form['status']

        usersCollection = db['users']

        user = usersCollection.find_one({"_id": ObjectId(request_user)})

        shortlist = user['shortlist']
        result_bool = False

        for entry in shortlist:
            if entry['_id'] == ObjectId(request_listing):
                entry['status'] = request_status
                print entry['status']
                result_bool = True

        usersCollection.update({'_id': user['_id']},
                               {'$set': {
                                   'shortlist': shortlist
                               }})

        reponse_obj.Data = jsonpickle.decode(dumps({'result': result_bool}))
        BaseUtils.SetOKDTO(reponse_obj)

    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponse_obj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    json_obj = jsonpickle.encode(reponse_obj, unpicklable=False)
    response = Response(json_obj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
Пример #10
0
def getListingById(listingid= None):
	
	reponseObj = Base()
	
	try:
		if listingid is not None:
			## select mondodb collection
			listingsCollection = db['listings']
			## retrieve listing from db
			listingsObject = listingsCollection.find_one({'_id': ObjectId(listingid)})
			## serialize listing
			reponseObj.Data = jsonpickle.decode(dumps(listingsObject))
			BaseUtils.SetOKDTO(reponseObj)	
	# TODO: IMPLEMENT APROPIATE ERROR HANDLING
   	except Exception as e:
   		BaseUtils.SetUnexpectedErrorDTO(reponseObj)
	       	print "There was an unexpected error: " , str(e)
	       	print traceback.format_exc()
		
	jsonObj = jsonpickle.encode(reponseObj, unpicklable=False)
	response = Response(jsonObj)	
	response.headers.add('Access-Control-Allow-Origin', '*')
	response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')  	
	return response
def saveUserPreferences(email):
    reponseObj = Base()

    try:
        filtersObj = {}

        ## identify filters
        f = request.form
        if 'filters' in f:
            print "request.form['filters']", request.form['filters']
            filtersObj = jsonpickle.decode(request.form['filters'])
            print "type(filtersObj)", type(filtersObj)
            print "filtersObj", filtersObj

        hood_must_have = dict()
        hood_must_have["keywords"] = []
        hood_delighter = dict()
        hood_delighter["keywords"] = []
        unit_must_have = dict()
        unit_must_have["keywords"] = []
        unit_delighter = dict()
        unit_delighter["keywords"] = []
        information = dict()
        db_dict = dict()
        unit_count_m = 1
        hood_count_m = 1
        unit_count_d = 1
        hood_count_d = 1
        apt_type_count = 1
        unit_must_have["rooms"] = []

        for field in request.form:
            print field
            preferencesStr = request.form[field]
            if preferencesStr:
                if field in [
                        "Locales_good", "Parks", "Walkable", "Family",
                        "Student_vibe", "Young_pro", "Quiet", "Classic",
                        "Modern"
                ]:
                    hood_delighter["keywords"].append(field)

                elif field in [
                        "Near_action", "Safe", "Easy_transport", "Parking"
                ]:
                    hood_must_have["keywords"].append(field)

                elif field in [
                        "hardwood", "laundry", "lighting", "deck_balcony",
                        "cieling", "kitchen", "spacing", "ameneties", "view",
                        "modern", "classic", "loft"
                ]:
                    unit_delighter["keywords"].append(field)

                elif field in ["pet", "spacing", "lighting", "parking"]:
                    unit_must_have["keywords"].append(field)

                elif field == "sublet_roomate":
                    unit_must_have["rooms"].extend((1, 2, 3, 4, 5))
                    unit_must_have["keywords"].append("sublet_roomate")
                elif field == "studio":
                    unit_must_have["rooms"].extend((0, 1, 2))
                    unit_must_have["keywords"].append("studio")
                elif field == "1bed":
                    unit_must_have["rooms"].append(1)
                elif field == "2bed":
                    unit_must_have["rooms"].append(2)

                elif field in [
                        "firstname", "lastname", "email", "gender",
                        "move_reason", "location", "transportation",
                        "profession", "importance", "movein"
                ]:
                    information[field] = preferencesStr

                elif field in [
                        "budget", "walking_time", "bike_time", "driving_time",
                        "transit_time"
                ]:
                    information[field] = int(preferencesStr)

        if 'budget' not in information.keys():
            information['budget'] = 5000

        db_dict["information"] = information
        db_dict["filters"] = filtersObj
        db_dict["unit_must_have"] = unit_must_have
        db_dict["unit_delighter"] = unit_delighter
        db_dict["hood_must_have"] = hood_must_have
        db_dict["hood_delighter"] = hood_delighter

        preferencesCollection = db['preferences']
        pref_id = preferencesCollection.insert(db_dict)
        print "pref_id", pref_id
        reponseObj.Data = Preference(jsonpickle.decode(dumps(pref_id)),
                                     filtersObj)
        #reponseObj.Data = {"preferenceId" : pref_id}

        # fromadd = "*****@*****.**"
        # toadd = information["email"]
        # msg = MIMEMultipart()
        # msg['From'] = fromadd
        # msg['To'] = toadd
        # msg['Subject'] = "Socrex - Concierge reply"
        # body = "Thank you for using our service, to view your personalized listings please follow this url:\n \nhttp://frontend-socrex-stage.herokuapp.com/#/listings/filter/"+str(pref_id)
        # msg.attach(MIMEText(body, 'plain'))

        # # Send the message via our own SMTP server, but don't include the
        # # envelope header.
        # s = smtplib.SMTP('smtp.gmail.com:587')
        # s.ehlo()
        # s.starttls()
        # s.ehlo()
        # s.login(fromadd, "monaco123")
        # text = msg.as_string()
        # s.sendmail(fromadd, toadd, text)
        # s.quit()

        BaseUtils.SetOKDTO(reponseObj)
    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponseObj)
        print "There was an unexpected error: ", str(e)
        print traceback.format_exc()

    jsonObj = jsonpickle.encode(reponseObj, unpicklable=False)
    response = Response(jsonObj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
Пример #12
0
def filterListings():
    reponseObj = Base()
    try:

        requestId = request.form['id']

        if "currentPage" in request.form.keys():
            requestPage = request.form['currentPage']
            requestPage = int(requestPage)
        else:
            requestPage = 1
        if "itemsOnPage" in request.form.keys():
            requestItems = request.form['itemsOnPage']
            requestItems = int(requestItems)
        else:
            requestItems = 100

        limitNumber = (requestPage-1) * requestItems
        skipNumber = requestPage * requestItems

        preferencesCollection = db['preferences']
        listingsCollection = db['listings']
        hoodsCollection = db['hoods']

        print "requestId" , requestId
        entry = preferencesCollection.find_one({"_id" : ObjectId(requestId)})

        information = entry["information"]
        unit_delighter = entry["unit_delighter"]
        unit_must_have = entry["unit_must_have"]
        hood_delighter = entry["hood_delighter"]
        hood_must_have = entry["hood_must_have"]

        delimiters = []

        if "rooms" in unit_must_have.keys():
            bed_range = unit_must_have["rooms"]

        if len(bed_range) == 0:
            bed_range = range(0,4)

        udelighters = []
        if "keywords" in unit_delighter.keys():
            udelighters = unit_delighter["keywords"]

        umust_haves = []
        if "keywords" in unit_must_have.keys():
            umust_haves = unit_must_have["keywords"]

        hmust_haves = []
        if "keywords" in hood_must_have.keys():
            hmust_haves = hood_must_have["keywords"]

        hdelighters = []
        if "keywords" in hood_delighter.keys():
            hdelighters = hood_delighter["keywords"]

        unit_query = {
                    "price": {"$in": range(300,information["budget"])}
                    , "bedroom": {"$in": bed_range}
                    , "isDeleted": 0
                }
        if "studio" in umust_haves:
            unit_query["studio"] = 1
        if "sublet_roomate" in umust_haves:
            unit_query["sublet_roomate"] = 1
        else:
            unit_query["sublet_roomate"] = 0

        filteredListingsCursors = listingsCollection.find(unit_query)
        filteredListingsList = list(filteredListingsCursors)

        final_filter = []
        score_list = []
        price_list = []

        for listing in filteredListingsList:

            ldatetime=""
            idatetime=""

            if "neighborhood" in listing.keys():
                listing_hood = listing["neighborhood"]
                hood = listing_hood
                ldatetime = datetime.datetime.strptime(listing["move_in"], '%Y%d%m')
                idatetime = datetime.datetime.strptime(information["movein"], '%Y%m%d')
                negative_score = 0

                for must_have in hmust_haves:
                    if hood[must_have] != 1:
                        negative_score += 20

            else :

                passed_musthaves = False

            for must_have in umust_haves:
                if listing.has_key(must_have):
                    if listing[must_have] != 1 and must_have not in ["sublet_roomate", "studio"]:
                        negative_score += 20


            passed_musthaves = True
            if ldatetime >= idatetime:
                passed_musthaves = False

            if 0 not in bed_range:
                if listing["studio"] == 1:
                    passed_musthaves = False


            if passed_musthaves:
                listing["score"] = 0
                for key in listing.keys():
                    if key in udelighters:
                        if listing[key] == 1:
                            listing["score"] += 30
                    elif listing[key] == 1 and key in ['laundry', 'hardwood', 'lighting', 'kitchen', 'deck_balcony', 'ameneties', 'cieling'] :
                        listing["score"] +=10
                for key in hood.keys():
                    if key in hdelighters:
                        if hood[key] == 1:
                            listing["score"] += 30
                    elif hood[key] == 1 and key in ['Safe', 'Locales_good', 'Parks']:
                        listing["score"] += 10


                price = float(information["budget"] - listing["price"]) / float(information["budget"])
                price_list.append(listing["price"])
                price_score = price * 100.00
                listing["score"] += int(price_score)
                listing["score"] = listing["score"] - negative_score
                score_list.append(listing["score"])
                listing["relevance"] = (float(listing["score"]) * 20.00) / 200.00
                if listing["relevance"] > 20:
                    listing["relevance"] = 20
                final_filter.append(listing)

        sorted_list = sorted(final_filter, key=itemgetter('score'), reverse=True)

        final_list = []
        if len(score_list) >0:
            arr_score = numpy.array([score_list])
            mean_score =  int(numpy.mean(arr_score))
            standard_dev_score =  int(numpy.std(arr_score))
            lower_score = mean_score-(standard_dev_score*2)
            upper_score = mean_score+(standard_dev_score*2)

            arr_price = numpy.array([price_list])
            mean_price =  int(numpy.mean(arr_price))
            standard_dev_price =  int(numpy.std(arr_price))
            lower_price = mean_price-(int(standard_dev_price*1))
            upper_price = mean_price+(int(standard_dev_price*2))

            for element in sorted_list:
                if element["score"] in range(lower_score, upper_score) and element["price"] in range(lower_price, upper_price):
                    final_list.append(element)
        else:
            final_list = sorted_list

        complete_length = len(final_list)
        if skipNumber < complete_length:
            final_list = final_list[limitNumber:skipNumber]
        else:
            final_list = final_list[limitNumber:]


        pages = int(math.ceil(float(complete_length) / float(requestItems)))

        user_email = ""
        if "email" in information.keys():
            user_email = information["email"]

        # returns the list of data objects

        reponseObj.Data = ListingList(4,jsonpickle.decode(dumps(final_list)),complete_length, user_email, pages)
        BaseUtils.SetOKDTO(reponseObj)



    # TODO: IMPLEMENT APROPIATE ERROR HANDLING
    except Exception as e:
        BaseUtils.SetUnexpectedErrorDTO(reponseObj)
        print "There was an unexpected error: " , str(e)
        print traceback.format_exc()

    jsonObj = jsonpickle.encode(reponseObj, unpicklable=False)
    response = Response(jsonObj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
    return response
Пример #13
0
def filterListings():	
	reponseObj = Base()
	try:

		requestId = request.form['id']

		if "currentPage" in request.form.keys():
			requestPage = request.form['currentPage']
			requestPage = int(requestPage)
		else: 
			requestPage = 1
		if "itemsOnPage" in request.form.keys():
			requestItems = request.form['itemsOnPage']
			requestItems = int(requestItems)
		else:
			requestItems = 100

		limitNumber = (requestPage-1) * requestItems
		skipNumber = requestPage * requestItems

		# {"id":26,"currentPage":2,"itemsOnPage":10}

		#filtersDic = jsonpickle.decode(filtersStr)

		preferencesCollection = db['preferences']
		listingsCollection = db['listings']
		hoodsCollection = db['hoods']


		entry = preferencesCollection.find_one({"_id" : ObjectId(requestId)})

		information = entry["information"]
		unit_delighter = entry["unit_delighter"]
		unit_must_have = entry["unit_must_have"]
		hood_delighter = entry["hood_delighter"]
		hood_must_have = entry["hood_must_have"]

		delimiters = []

		if "rooms" in unit_must_have.keys():
			bed_range = unit_must_have["rooms"]

		if len(bed_range) == 0:
			bed_range = range(0,4)

		udelighters = []
		if "keywords" in unit_delighter.keys():
			udelighters = unit_delighter["keywords"]

		umust_haves = []
		if "keywords" in unit_must_have.keys():
			umust_haves = unit_must_have["keywords"]

		hmust_haves = []
		if "keywords" in hood_must_have.keys():
			hmust_haves = hood_must_have["keywords"]

		hdelighters = []
		if "keywords" in hood_delighter.keys():
			hdelighters = hood_delighter["keywords"]

		unit_query = {
					"price": {"$in": range(300,information["budget"])}
					, "bedroom": {"$in": bed_range}
				}
		if "studio" in umust_haves:
			unit_query["studio"] = 1
		if "sublet_roomate" in umust_haves:
			unit_query["sublet_roomate"] = 1
		else:
			unit_query["sublet_roomate"] = 0

		filteredListingsCursors = listingsCollection.find(unit_query)
		filteredListingsList = list(filteredListingsCursors)

		final_filter = []
		score_list = []
		price_list = []

		for listing in filteredListingsList:

			ldatetime=""
			idatetime=""

			if "neighborhood" in listing.keys():
				listing_hood = listing["neighborhood"]
				hood_query = {'_id': ObjectId(listing_hood["_id"])}
				hood = hoodsCollection.find_one(hood_query)
				ldatetime = datetime.datetime.strptime(listing["move_in"], '%Y%d%m')
				idatetime = datetime.datetime.strptime(information["movein"], '%Y%m%d')
				negative_score = 0

				for must_have in hmust_haves:
					if hood[must_have] != 1:
						negative_score += 20 

			else :

				passed_musthaves = False

			for must_have in umust_haves:
				if listing.has_key(must_have):
					if listing[must_have] != 1 and must_have not in ["sublet_roomate", "studio"]:
						negative_score += 20


			passed_musthaves = True
			if ldatetime >= idatetime:
				passed_musthaves = False

			if 0 not in bed_range:
				if listing["studio"] == 1:
					passed_musthaves = False



			# if listing["bedroom"] in [0,1]:
			# 	if "Top85_1bed" in hood.keys():
			# 		if listing["studio"] == 1:
			# 			if int(listing["price"]) < int(hood["Top85_studio"]):
			# 				passed_musthaves = False
			# 		else:
			# 			if listing["price"] < hood["Top85_1bed"]:
			# 				passed_musthaves = False 


			# if listing["bedroom"] == 2:
			# 	if "Top85_2bed" in hood.keys():
			# 		if int(listing["price"]) < int(hood["Top85_2bed"]):
			# 			passed_musthaves = False


			if passed_musthaves:
				listing["score"] = 0
				for key in listing.keys():
					if key in udelighters:
						if listing[key] == 1:
							listing["score"] += 30
					elif listing[key] == 1 and key in ['laundry', 'hardwood', 'lighting', 'kitchen', 'deck_balcony', 'ameneties', 'cieling'] :
						listing["score"] +=10
				for key in hood.keys():
					if key in hdelighters:
						if hood[key] == 1:
							listing["score"] += 30
					elif hood[key] == 1 and key in ['Safe', 'Locales_good', 'Parks']:
						listing["score"] += 10


				price = float(information["budget"] - listing["price"]) / float(information["budget"])
				price_list.append(listing["price"])
	 			price_score = price * 100.00
 				listing["score"] += int(price_score)
 				listing["score"] = listing["score"] - negative_score
 				score_list.append(listing["score"])
 				listing["relevance"] = (float(listing["score"]) * 20.00) / 200.00
 				if listing["relevance"] > 20:
 					listing["relevance"] = 20
 				final_filter.append(listing)

		sorted_list = sorted(final_filter, key=itemgetter('score'), reverse=True)

		final_list = []		
		if len(score_list) >0:
			arr_score = numpy.array([score_list])
			mean_score =  int(numpy.mean(arr_score))
			standard_dev_score =  int(numpy.std(arr_score))
			lower_score = mean_score-(standard_dev_score*2)
			upper_score = mean_score+(standard_dev_score*2)

			arr_price = numpy.array([price_list])
			mean_price =  int(numpy.mean(arr_price))
			standard_dev_price =  int(numpy.std(arr_price))
			lower_price = mean_price-(int(standard_dev_price*1))
			upper_price = mean_price+(int(standard_dev_price*2))		

			for element in sorted_list:
				if element["score"] in range(lower_score, upper_score) and element["price"] in range(lower_price, upper_price):
					final_list.append(element)
		else:
			final_list = sorted_list

		complete_length = len(final_list)
		if skipNumber < complete_length:
			final_list = final_list[limitNumber:skipNumber]
		else:
			final_list = final_list[limitNumber:]


		pages = int(math.ceil(float(complete_length) / float(requestItems)))

		user_email = ""
		if "email" in information.keys():
			user_email = information["email"]

		# returns the list of data objects
	
		reponseObj.Data = ListingList(4,jsonpickle.decode(dumps(final_list)),complete_length, user_email, pages)
		BaseUtils.SetOKDTO(reponseObj)	



	# TODO: IMPLEMENT APROPIATE ERROR HANDLING
	except Exception as e:
   		BaseUtils.SetUnexpectedErrorDTO(reponseObj)
	       	print "There was an unexpected error: " , str(e)
	       	print traceback.format_exc()
	
	jsonObj = jsonpickle.encode(reponseObj, unpicklable=False)
	response = Response(jsonObj)
	response.headers.add('Access-Control-Allow-Origin', '*')
	response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')  
	return response
Пример #14
0
def saveUserPreferences():	
	reponseObj = Base()
	try:
		hood_must_have = dict()
		hood_must_have["keywords"] = []
		hood_delighter = dict()
		hood_delighter["keywords"] = []
		unit_must_have = dict()
		unit_must_have["keywords"] = []
		unit_delighter = dict()
		unit_delighter["keywords"] = []
		information = dict()
		db_dict = dict()
		unit_count_m = 1
		hood_count_m = 1
		unit_count_d = 1
		hood_count_d = 1
		apt_type_count = 1
		unit_must_have["rooms"]=[]

		for field in request.form:
			preferencesStr = request.form[field]
			if preferencesStr:
				if field in ["Locales_good", "Parks", "Walkable", "Family", "Student_vibe", "Young_pro", "Quiet", "Classic", "Modern"]:
					hood_delighter["keywords"].append(field)

				elif field in ["Near_action", "Safe", "Easy_transport", "Parking"]:
					hood_must_have["keywords"].append(field)

				elif field in ["hardwood", "laundry", "lighting", "deck_balcony", "cieling", "kitchen", "spacing", "ameneties", "view", "modern", "classic", "loft"]:
					unit_delighter["keywords"].append(field)

				elif field in ["pet", "spacing", "lighting", "parking"]:
					unit_must_have["keywords"].append(field)

				elif field == "sublet_roomate":
					unit_must_have["rooms"].extend((1,2,3,4,5))
					unit_must_have["keywords"].append("sublet_roomate")
				elif field == "studio":
					unit_must_have["rooms"].extend((0,1,2))
					unit_must_have["keywords"].append("studio")
				elif field == "1bed":
					unit_must_have["rooms"].append(1)
				elif field == "2bed":
					unit_must_have["rooms"].append(2)

				elif field in ["firstname", "lastname", "email", "gender", "move_reason", "location", "transportation", "profession", "importance", "movein"]:
					information[field] = preferencesStr

				elif field in ["budget", "walking_time", "bike_time", "driving_time", "transit_time"]:
					information[field] = int(preferencesStr)

		if 'budget' not in information.keys():
			information['budget'] = 5000

		db_dict["information"] = information
		db_dict["unit_must_have"] = unit_must_have
		db_dict["unit_delighter"] = unit_delighter
		db_dict["hood_must_have"] = hood_must_have
		db_dict["hood_delighter"] = hood_delighter

		preferencesCollection = db['preferences']
		pref_id = preferencesCollection.insert(db_dict)
		print "pref_id" , pref_id
		reponseObj.Data = Preference(jsonpickle.decode(dumps(pref_id)))
		#reponseObj.Data = {"preferenceId" : pref_id}
		print "reponseObj.Data" , reponseObj.Data
		# fromadd = "*****@*****.**"
		# toadd = information["email"]
		# msg = MIMEMultipart()
		# msg['From'] = fromadd
		# msg['To'] = toadd
		# msg['Subject'] = "Socrex - Concierge reply"
		# body = "Thank you for using our service, to view your personalized listings please follow this url:\n \nhttp://frontend-socrex-stage.herokuapp.com/#/listings/filter/"+str(pref_id)
		# msg.attach(MIMEText(body, 'plain'))

		# # Send the message via our own SMTP server, but don't include the
		# # envelope header.
		# s = smtplib.SMTP('smtp.gmail.com:587')
		# s.ehlo()
		# s.starttls()
		# s.ehlo()
		# s.login(fromadd, "monaco123")
		# text = msg.as_string()
		# s.sendmail(fromadd, toadd, text)
		# s.quit()

	
		BaseUtils.SetOKDTO(reponseObj)	
	# TODO: IMPLEMENT APROPIATE ERROR HANDLING
	except Exception as e:
   		BaseUtils.SetUnexpectedErrorDTO(reponseObj)
	       	print "There was an unexpected error: " , str(e)
	       	print traceback.format_exc()
	
	jsonObj = jsonpickle.encode(reponseObj, unpicklable=False)
	response = Response(jsonObj)
	response.headers.add('Access-Control-Allow-Origin', '*')
	response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')  
	return response