Beispiel #1
0
 def post(self):
     '''
     HTTP POST Method Handler
     Parameters: None
     '''
     if not users.is_current_user_admin():
         self.abort(404)
     self.load_http_params({
         'name': (str, True),
         'adm': (lambda s: ndb.Key(urlsafe=s), True),
         'lat': (float, True),
         'lon': (float, True)
     })
     b = Business(
         name=self.params['name'],
         lat=self.params['lat'],
         lon=self.params['lon'],
         admins=[self.params['adm']]
     )
     b.put()
     qry = User.query(projection=[User.email]).order(User.email)
     self.render(
         user_iter=qry.iter(),
         statusClass='success',
         status='Succesfully created business "<a href="/business/{}/">{}</a>"'.format(b.key.id(), b.name)
     )
Beispiel #2
0
    def test_reports_yelp_business_detail(self):
        """Test that calling business detail on a business that has reports
           written about it includes details about that business.

           # TODO: MOCK out actual yelp API call."""

        u1 = User.register(email='*****@*****.**',
                           username='******', password='******')
        Business.create(
            name='Cuisine of Nepal', longitude=-122.42318,
            latitude=37.74097, id='iUockw0CUssKZLyoGJYEXA',
            city='San Francisco', state='CA', country='US')

        db.session.commit()

        Report.create(user_id=u1.id, text='Good fud.',
                      business_id='iUockw0CUssKZLyoGJYEXA')

        db.session.commit()

        with self.client as c:
            resp = c.get(
                '/v1/business_detail/iUockw0CUssKZLyoGJYEXA?name=Cuisine+of+Nepal&latlng=37.74097,-122.42318')  # noqa e501
            data = resp.get_json()

        self.assertEqual(resp.status_code, 200)
        self.assertIn('reports', data)
        self.assertEqual(data['reports'][0]['text'], 'Good fud.')
Beispiel #3
0
    def get(self):
        '''
        Returns business URI's, filtered by optional parameters
        Parameters:
            name - Name of the business
            lat,lon - Location of the business
        '''
        params = self.load_http_params({
            'lat': (float, False),
            'lon': (float, False),
            'name': (str, False)
        })

        if 'lat' in params and 'lon' in params:
            query = Business.query_location(
                lat=self.params['lat'],
                lon=self.params['lon']
            )
        else:
            query = Business.query()

        if 'name' in params and params['name']:
            query = query.filter(Business.name == params['name'])

        self.response.status = '200 OK'
        flag = False
        for key in query.iter(keys_only=True):
            if flag:
                self.response.write('\n')
            else:
                flag = True
            self.response.write(str(key.id()))
Beispiel #4
0
 def form_to_dao_business(self, **update):
     business = Business()
     business.name = update['name']
     #Create an automatic alias for the business
     business.alias = utils.slugify(update['name'])
     business.description = update['description']
     business = self.form_to_dao_contact_info_import(business, **update)
     return business
Beispiel #5
0
def business_details(business_id):
    response = jsonify({})
    business = {}
    businesses_list = Business.get_businesses()
    for bus in businesses_list:
        if bus.id == int(business_id):
            business = Business.get_business_details(bus)
    response = jsonify(business)
    response.status_code = 200
    return response
Beispiel #6
0
def delete_business(business_id):
    response = jsonify({})
    businesses = Business.get_businesses()
    for bus in businesses:
        if bus.id == int(business_id):
            businesses.remove(bus)
    businesses_list = []
    for bus in businesses:
        businesses_list.append(Business.get_business_details(bus))
    response = jsonify(businesses_list)
    response.status_code = 200

    return response
Beispiel #7
0
 def form_to_dao(self, business_id):
     business = None
     if business_id is not None and len(business_id) > 1:
         business = self.businessDao.get_record(long(business_id))
         logger.debug('business ' + str(business))
     else:
         business = Business()
     logger.debug('business 2 ' + str(business))
     business.name = self.form.name.data
     #Create an automatic alias for the business
     business.alias = utils.slugify(self.form.name.data)
     business.description = self.form.description.data
     return cms_utils.form_to_dao_contact_info(self.form, business)
Beispiel #8
0
    def setUp(self):

        self.user = User.register(email="*****@*****.**",
                                  username="******",
                                  password="******")

        self.mission = Mission.create(editor=self.user.id,
                                      name="test mission",
                                      city="Albany",
                                      state="NY",
                                      country='US')

        self.business = Business.create(name='Cuisine of Nepal',
                                        longitude=-122.42318,
                                        latitude=37.74097,
                                        id='iUockw0CUssKZLyoGJYEXA',
                                        city='San Francisco',
                                        state='CA',
                                        country='US')

        self.mission.businesses.append(self.business)

        self.report = Report.create(user_id=self.user.id,
                                    business_id='iUockw0CUssKZLyoGJYEXA',
                                    text='Best nepalese food I ever had!')

        db.session.commit()

        self.report2 = Report.create(user_id=self.user.id,
                                     mission_id=self.mission.id,
                                     text='The curry was devine!')

        db.session.commit()
    def setUp(self):
        self.predictor = TrendPredictor()

        self.X_train, self.X_test, self.y_train, self.y_test = \
            Business.train_test_set(DataReader().sample_businesses())

        self.predictor.fit(self.X_train, self.y_train)
Beispiel #10
0
    def post(self):
        '''
        Creates a new busines model from posted data
        Returns corresponding URI
        Parameters:
            name - Name of the business
            lat - Lattitude of the business
            lon - Longitude of the business
        '''
        params = self.load_json_params({
            'lat': (float, True),
            'lon': (float, True),
            'name': (str, True),
            'admins': (list, False)
        }, use_default=True)

        authenticate()
        admin_keys = [ndb.Key('User', adm_id) for adm_id in params['admins']]
        if not len(ndb.get_multi(admin_keys)) == len(admin_keys):
            self.abort(400)

        key = Business.new(
            lat=params['lat'],
            lon=params['lon'],
            name=params['name'],
            admins=admin_keys
        ).put()
        uri = '/api/business/{}'.format(key.id())
        self.response.status = '200 OK'
        self.response.write(uri)
 def add_bus_from_resp(self):
     if not Business.query.filter(Business.yelp_id==self.yelp_id).first():
         business = Business(yelp_id=self.yelp_id,name=self.name)
         db.session.add(business)
         db.session.commit()
         return self
     return self
Beispiel #12
0
def update_company():
    user = Users.query.filter_by(email=current_user.email).first()
    business = Business.query.filter_by(owner_id=user.id).first()

    name = request.form.get('business_name')
    address = request.form.get('business_address')
    phone_number = request.form.get('phone_number')
    email = request.form.get('business_email')
    sector = request.form.get('business_sector')
    description = request.form.get('business_description')

    if business is not None:
        business.name = name
        business.address = address
        business.phone_number = phone_number
        business.business_email = email
        business.sector = sector
        business.description = description

        db.session.commit()
    else:
        new_business = Business(owner_id=user.id,
                                name=name,
                                address=address,
                                phone_number=phone_number,
                                sector=sector,
                                business_email=email,
                                description=description)
        db.session.add(new_business)
        db.session.commit()

    return redirect(url_for('main.profile'))
Beispiel #13
0
	def post(self):
		request_text = request.get_json(force=True)
		business_json = json.loads(json.dumps(request_text))

		if('city' in business_json and 'review_count' in business_json and 'name' in business_json and 'business_id' in business_json
			and 'longitude' in business_json and 'hours' in business_json and 'state' in business_json
			and 'postal_code' in business_json and 'stars' in business_json and 'address' in business_json and 'latitude' in business_json
			and 'is_open' in business_json and 'attributes' in business_json and 'categories' in business_json and 'deleted' in business_json):
			new_business = Business(
				address = business_json['address'],
				business_attributes = business_json['attributes'],
				business_id = business_json['business_id'],
				categories = business_json['categories'],
				city = business_json['city'],
				deleted = business_json['deleted'],
				hours = business_json['hours'],
				is_open = business_json['is_open'],
				latitude = business_json['latitude'],
				longitude = business_json['longitude'],
				business_name = business_json['name'],
				postal_code = business_json['postal_code'],
				review_count = business_json['review_count'],
				stars = business_json['stars'],
				business_state = business_json['state']
			)
			postgres.session.add(new_business)
			postgres.session.commit()
			return "Success"
		return "Invalid fields"
Beispiel #14
0
def add_favorite(business_id):
    """Add favorite business to the current user"""
    if not g.user:
        flash("Please log in first.", "danger")
        return redirect('/signin')

    # get business's name
    url = API_BASE_URL + '/businesses/' + business_id
    req = requests.get(url, headers=headers)
    business = json.loads(req.text)
    business_name = business.get('name', None)

    # check if the item is on the Business models
    # if Business.query.all() == [] or not Business.query.filter(Business.business_id == business_id).first():
    # get id for user's favorite businesses
    fav_business_ids = []
    for each_fav_business in g.user.favorite_business:
        fav_business_ids.append(each_fav_business.business_id)

    # check if current id is in favourite businesses already
    if business_id not in fav_business_ids:
        new_business = Business(business_id=business_id,
                                business_name=business_name)
        g.user.favorite_business.append(new_business)
        db.session.commit()

    return redirect('/users/' + g.user.username)
Beispiel #15
0
 def post(self):
     r = request.get_json(force=True)
     businessBatch = r[10:len(r) - 6].strip().replace("\n",
                                                      "").split('},   {')
     for singleBusiness in businessBatch:
         json_data = json.loads('{' + singleBusiness + '}')
         try:
             business = Business(
                 city=json_data['city'],
                 review_count=json_data['review_count'],
                 business_name=json_data['name'],
                 business_id=json_data['business_id'],
                 longitude=json_data['longitude'],
                 hours=json_data['hours'],
                 business_state=json_data['state'],
                 postal_code=json_data['postal_code'],
                 stars=json_data['stars'],
                 address=json_data['address'],
                 latitude=json_data['latitude'],
                 is_open=json_data['is_open'],
                 business_attributes=json_data['attributes'],
                 categories=json_data['categories'],
                 deleted=json_data['deleted'])
         except Exception as e:
             return (str(e))
         postgres.session.add(business)
     postgres.session.commit()
     return {}
Beispiel #16
0
    def add_business(payload):
        body = request.get_json()
        if not request.get_json():
            abort(400)

        name = body['name']
        description = body['description']
        date_added = datetime.today()

        business = Business(name=name,
                            description=description,
                            date_added=date_added)

        Business.insert(business)

        return jsonify({'success': True, 'new_business': business.format()})
Beispiel #17
0
def signup():
    """
    signup route
    :return:
    """
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        print('validate', request.form)
        username = form.name.data.title()
        email = form.email.data.capitalize()
        business = form.business.data.title()
        language = form.language.data.title()
        password = generate_password_hash(form.password.data, method='sha256')
        check_valid = User.query.filter_by(name=username).first()
        if check_valid is None:
            check_valid = User.query.filter_by(email=email).first()
        if check_valid is not None:
            return render_template('signup.html', error='Username, Email or address already taken', form=form)
        
        new_user = User(name=username, email=email, password=password,
                       language=language, verified=True)
        
        db.session.add(new_user)
        db.session.commit()
        
        new_bus = Business(name=business, user_id=new_user.id)
        db.session.add(new_bus)
        db.session.commit()
        return redirect(url_for('login'))
    else:
        print(form.errors)
    return render_template('signup.html', form=form, error='')
Beispiel #18
0
def add_to_mission(mission_id):
    """Add business to mission endpoint."""

    if not g.user:
        return Unauthorized()

    mission = Mission.query.get_or_404(mission_id)

    data = request.json

    business = Business.query.get(data['id'])

    if business:
        if business in mission.businesses:
            return jsonify({'success': 'Already Added.', 'color': 'warning'})
    else:
        # Index page adds new businesses to DB.
        business = Business.create(
            id=data['id'], name=data['name'], city=data['city'],
            state=data['state'], country=data['country'],
            longitude=float(data['longitude'] or 0),
            latitude=float(data['latitude'] or 0))

    mission.businesses.append(business)

    try:
        db.session.commit()
    except Exception as e:
        H.error_logging(e)
        return jsonify({'error': 'Error!'})

    return jsonify({'success': 'Added!', 'color': 'green'})
Beispiel #19
0
def add_business():
    """Add business to database if it is not present."""

    data = request.json

    business = Business.query.get(data['id'])

    if business:
        return jsonify({'success': 'business already in database'})

    business = Business.create(id=data['id'],
                               name=data['name'],
                               city=data['city'],
                               state=data['state'],
                               country=data['country'],
                               longitude=float(data['longitude'] or 0),
                               latitude=float(data['latitude'] or 0))

    try:
        db.session.commit()
    except Exception as e:
        H.error_logging(e)
        return jsonify({'error': 'Error!'})

    return jsonify({'success': 'Added!'})
Beispiel #20
0
    def test_remove_business_from_mission(self):
        """Test removing business from mission endpoint."""

        business = Business.create(**self.business_data)
        self.mission.businesses.append(business)
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess['user_id'] = self.user2.id

            db.session.add(self.mission)  # ????

            data = {'business_id': self.business_data['id']}

            # test removing mission
            resp = c.post(f'/v1/mission/remove_business/{self.mission.id}',
                          json=data)

            self.assertEqual(resp.json['success'],
                             'Business Removed from Mission!')
            self.assertNotIn(business, self.mission.businesses)

            # test repeat removing does nothing
            resp = c.post(f'/v1/mission/remove_business/{self.mission.id}',
                          json=data)

            self.assertEqual(resp.json['success'], 'Business not in mission.')
            self.assertNotIn(business, self.mission.businesses)
Beispiel #21
0
 def search(self, value, key='name', status='all'):
     logger.info('NdbBusinessDao:: DBHIT: search for %s, %s ' % key % value)
     search_query = Business.query(Business._properties[key] == value)
     if status != 'all':
         status_value = STATUS_DICT.get(status)
         search_query = search_query.filter(status == status_value)
     search_query = search_query.order(Business.updated_on)
     return search_query.fetch()
Beispiel #22
0
    def create_business_profile():
        if request.method == 'GET':
            return render_template('new_business_form.html',
                                   userinfo=session['business_profile'])

        body = request.get_json()
        try:
            name = body.get('name')
            email = body.get('email')
            zip_code = body.get('zip_code')
            goals = body.get('goals')
            website = body.get('website')
            address = body.get('address')
            description = body.get('description')
            skills = body.get('skills'),
            auth_id = body.get('auth_id')

            business = Business(name=name,
                                email=email,
                                zip_code=zip_code,
                                goals=goals,
                                website=website,
                                address=address,
                                description=description,
                                skills=skills,
                                auth_id=auth_id)

            if not business:
                abort(404)

            business.insert()

            return jsonify({
                'success': True,
                'name': business.name,
                'email': business.email,
                'zip_code': business.zip_code,
                'goals': business.goals,
                'website': business.website,
                'address': business.address,
                'description': business.description,
                'skills': business.skills,
                'auth_id': business.auth_id
            }), 200
        except:
            abort(422)
Beispiel #23
0
    def post_business(payload):
        body = request.get_json()
        id = body.get('id', None)
        name = body.get('name', None)
        address = body.get('address', None)
        phone = body.get('phone', None)
        cif = body.get('cif', None)
        email = body.get('email', None)

        try:
            if id is None:
                business = Business(name=name,
                                    address=address,
                                    phone=phone,
                                    cif=cif,
                                    email=email)
            else:
                business = Business(id=id,
                                    name=name,
                                    address=address,
                                    phone=phone,
                                    cif=cif,
                                    email=email)
            business.insert()
        except:
            abort(422)

        return jsonify({
            'success': True,
            'business': business.long(),
            'status': 200
        }), 200
Beispiel #24
0
 def get(self):
     if not users.is_current_user_admin():
         self.abort(404)
     for b in Business.query().iter():
         b.key.delete()
     for c in Coupon.query().iter():
         c.key.delete()
     self.init()
     self.response.write('success')
Beispiel #25
0
def is_admin(uid=None, bid=None):
    if users.is_current_user_admin():
        return True
    cur_user = users.get_current_user().user_id()
    if uid == cur_user:
        return True
    if bid:
        user_key = ndb.Key('User', cur_user)
        admins = Business.get_by_id(bid).admins
        return user_key in admins
    return False
Beispiel #26
0
 def register(self, request, **cleaned_data):
     new_user = super(BusinessRegistrationView, self).register(request, **cleaned_data)
     group = Group.objects.get(name="Business Users")
     new_user.groups.add(group)
     permission = Permission.objects.get(name="account_up-to-date")
     new_user.user_permissions.add(permission)
     new_user.first_name = cleaned_data["first_name"]
     new_user.save()
     new_profile = Business(
         user=new_user,
         street=cleaned_data["street"],
         area=cleaned_data["area"],
         city=cleaned_data["city"],
         region=cleaned_data["region"],
         country=cleaned_data["country"],
         telephone=cleaned_data["telephone"],
         min_age=cleaned_data["min_age"],
         mailing_list=cleaned_data["mailing_list"],
     )
     new_profile.save()
     return new_user
Beispiel #27
0
 def query_by_owner(self, user, status='all'):
     logger.info('NdbBusinessDao:: DBHIT: query_by_owner for %s ' %
                 user.email)
     business_query = Business.query(
         ndb.OR(Business.owners == user.key,
                Business.created_by == user.key,
                Business.updated_by == user.key))
     if status != 'all':
         status_value = STATUS_DICT.get(status)
         business_query = business_query.filter(status == status_value)
     business_query = business_query.order(Business.updated_on)
     return business_query.fetch()
Beispiel #28
0
	def post(self, user_id):
		#try:
			biz_id = self.request.get('biz')
			business_gql = Business.gql('where y_business_id = :1', biz_id)
  			if business_gql.count() == 0:
  				business = Business(y_business_id=biz_id)
  				business.put()
  				#self.error(404)
  				#self.response.out.write("biz not found")
  				return
  			else:
  				for biz in business_gql:
  					business = biz
  					break

  			user_gql = User.gql('where name = :1', user_id)
  			if user_gql.count() == 0:
  				#user = User(name=user_id, subscriptions=[])
  				#user.put()
  				self.error(404)
  				self.response.out.write("user not found")
  				return
  			else:
  				for u in user_gql:
  					user = u
  					if not business.key() in user.subscriptions:
  						user.subscriptions.append(business.key())
  						user.put()
  					break

  			businesses = self.list_all_subscriptions(user_id)
  			result = {'businesses': businesses}
  			result = json.dumps(result)
  			self.response.out.write(result)
Beispiel #29
0
    def setUp(self):

        self.user = User.register(email="*****@*****.**",
                                  username="******",
                                  password="******")

        self.mission = Mission.create(editor=self.user.id,
                                      name="test mission",
                                      city="Albany",
                                      state="NY",
                                      country='US')
        self.mission.share()

        self.mission2 = Mission.create(editor=self.user.id,
                                       name="test mission 2",
                                       city="Ithica",
                                       state="NY",
                                       country='US')
        self.mission2.share()

        self.business = Business.create(name='Cuisine of Nepal',
                                        longitude=-122.42318,
                                        latitude=37.74097,
                                        id='iUockw0CUssKZLyoGJYEXA',
                                        city='San Francisco',
                                        state='CA',
                                        country='US')

        self.business2 = Business.create(name='Little Nepal',
                                         longitude=-122.41361,
                                         latitude=37.7391,
                                         id='Kx1WExNj5ogaFe0cyg9L6A',
                                         city='San Francisco',
                                         state='CA',
                                         country='US')

        self.mission.businesses.append(self.business)
        self.mission2.businesses.append(self.business2)

        db.session.commit()
Beispiel #30
0
    def create_or_update_business(self, alias_name, import_data):
        business = self.businessDao.query_by_alias(alias_name)

        if business is not None:
            business_key = business.key
            import_data.business_id = business_key
            logger.info('Business Already Exist with Key %s' %
                        str(business_key))
        else:
            try:
                business = Business()
                business.name = import_data.name
                business.description = import_data.description
                business.alias = import_data.alias
                business.contact_info = import_data.contact_info
                business_key = self.businessDao.persist(
                    business, self.user_info)
                import_data.business_id = business_key
                logger.info('New Business Created for %s with key %s' %
                            (alias_name, str(business_key)))
            except StandardError as e:
                #Skip the error and continue
                logger.error('Error occured, %s, for %s' %
                             (str(e), alias_name))
                raise
        return business_key
Beispiel #31
0
def displayBusinessForm():
    if request.method == 'GET':
        return render_template('business-registration-form.html')

    elif request.method == 'POST':
        bname = request.form.get('bname')
        num_interns = request.form.get('num_interns')
        duration = request.form.get('duration')
        credits = request.form.get('credits')
        stipend = request.form.get('stipend')
        lang = request.form.get('lang')
        design = request.form.get('design')
        dbms = request.form.get('dbms')
        soft_skills = request.form.get('soft_skills')

        business = Business.query.filter_by(bname=bname).first()

        if business is None:
            new_business = Business(bname=bname,
                                    num_interns=num_interns,
                                    duration=duration,
                                    stipend=stipend,
                                    credits=credits,
                                    language=lang,
                                    design=design,
                                    dbms=dbms,
                                    soft_skills=soft_skills)

            db.session.add(new_business)
            db.session.commit()

            proj_name = request.form.get('proj_name')
            proj_descript = request.form.get('proj_descript')
            activities = request.form.get('activities')
            internship = Internship.query.filter_by(
                proj_name=proj_name).first()

            if internship is None:
                new_internship = Internship(
                    proj_name=proj_name,
                    proj_descript=proj_descript,
                    activities=activities,
                    business_ID=new_business.businessID)
            try:
                db.session.add(new_internship)
                db.session.commit()
                #return render_template('business-homepage.html')
                return redirect(url_for('displayBusinessForm'))
            except IntegrityError:
                return 'Application does not exist', render_template(
                    "business-registration.html"), 400
    return
Beispiel #32
0
    def get(self):
        '''
        Lists coupons, filtered by optional parameters
        Parameters:
            name - Name of the business
            lat,lon - Location of the business
        '''
        try:
            lat = float(urllib.unquote(self.request.get('lat')))
            lon = float(urllib.unquote(self.request.get('lon')))
        except ValueError:
            query = Business.query()
        else:
            query = Business.query_location(lat=lat, lon=lon)

        name = urllib.unquote(self.request.get('name'))
        if name:
            query = query.filter(Business.name == name)
        coupons = [c for business in query.map(lambda x: Coupon.get_by_business(x.key.id()))
                   for c in business]

        coupons = sorted(coupons, lambda x, y: cmp(x.end, y.end))
        now = datetime.datetime.now()
        i = 0
        expired_index = None
        for i in range(len(coupons)):
            if expired_index is None and now < coupons[i].end:
                expired_index = i
            if now < coupons[i].start:
                break
        expired = coupons[0:expired_index]
        active = coupons[expired_index:i]
        inactive = coupons[i:]

        self.response.status = '200 OK'
        self.response.write(self.template.render(
            coupons=active+inactive+expired
        ))
Beispiel #33
0
def signup_business():
    request_body = request.get_json()
    print(request_body)

    business1 = Business(
        business_name=request_body["business_name"],
        address=request_body["address"],
        phone_number=request_body["phone_number"],
        email=request_body["email"],
        password=request_body["password"],
    )
    db.session.add(business1)
    db.session.commit()
    return jsonify(request_body), 200
Beispiel #34
0
    def test_business_details(self):
        with app.test_client() as client:
            client.get('/')
            # Create a user with info shown below
            b1 = Business(business_id = 'OSZ6bFeCcv4PvUmvuiMEJw', business_name = 'Little Sweet')
            db.session.add(b1)
            db.session.commit()

            res = client.get("foodies/details/OSZ6bFeCcv4PvUmvuiMEJw")
            html = res.get_data(as_text = True)

            self.assertEqual(res.status_code, 200)
            self.assertIn('<i class="fab fa-yelp" style="color: #c41200;"></i> More Reviews', html)
            # this item has not been added to user's favourite
            self.assertIn('style="display: inline-block; margin-right: 0.1rem" style="display: inline-block; margin-right: 0.1rem">Add it to Favorite?</a>', html)
 def create_or_update_business(self, trainingcentre):
   if trainingcentre.business_id is not None:
     business = self.businessDao.get_record(long(trainingcentre.business_id.id()))
   else:
     business = Business()
   business.name = trainingcentre.name
   business.description = trainingcentre.description
   business.alias = trainingcentre.alias
   business.contact_info = trainingcentre.contact_info
   return business
Beispiel #36
0
 def create_or_update_business(self, event):
   if event.business_id is not None:
     business = self.businessDao.get_record(long(event.business_id.id()))
   else:
     business = Business()
   business.name = event.name
   business.description = event.description
   business.alias = event.alias
   business.contact_info = event.contact_info
   return business
Beispiel #37
0
 def create_or_update_business(self, playground):
   if playground.business_id is not None:
     business = self.businessDao.get_record(long(playground.business_id.id()))
   else:
     business = Business()
   business.name = playground.name
   business.description = playground.description
   business.alias = playground.alias
   business.contact_info = playground.contact_info
   return business
Beispiel #38
0
    def add_new_business(cls, business_id, data):
        """Add new business logic for add report."""

        model = Business.create(id=business_id,
                                name=data['name'],
                                city=data['city'],
                                state=data['state'],
                                country=data['country'],
                                longitude=float(data['lng'] or 0),
                                latitude=float(data['lat'] or 0))
        try:
            db.session.commit()
        except Exception as e:
            cls.error_logging(e)
            return False

        return model
Beispiel #39
0
 def test_unicode_pk(self):
     # Primary key may be unicode string
     bus = Business(name=u'jaźń')
     bus.save()
Beispiel #40
0
    def test_custom_pk(self):
        dan = Employee(employee_code=123, first_name='Dan', last_name='Jones')
        dan.save()
        self.assertQuerysetEqual(Employee.objects.all(),
                                 ['<Employee: Dan Jones>'])

        fran = Employee(employee_code=456, first_name='Fran', last_name='Bones')
        fran.save()
        self.assertQuerysetEqual(Employee.objects.all(),
                                 ['<Employee: Fran Bones>', '<Employee: Dan Jones>'])

        self.assertEqual(repr(Employee.objects.get(pk=123)),
                         '<Employee: Dan Jones>')
        self.assertEqual(repr(Employee.objects.get(pk=456)),
                         '<Employee: Fran Bones>')

        self.assertRaises(Employee.DoesNotExist,
                          Employee.objects.get, pk=42)

        # Use the name of the primary key, rather than pk.
        self.assertEqual(repr(Employee.objects.get(employee_code__exact=123)),
                         '<Employee: Dan Jones>')

        # pk can be used as a substitute for the primary key.
        self.assertQuerysetEqual(Employee.objects.filter(pk__in=[123, 456]),
                                 ['<Employee: Fran Bones>', '<Employee: Dan Jones>'])

        # The primary key can be accessed via the pk property on the model.
        e = Employee.objects.get(pk=123)
        self.assertEqual(e.pk, 123)

        # Or we can use the real attribute name for the primary key:
        self.assertEqual(e.employee_code, 123)

        # Fran got married and changed her last name.
        fran = Employee.objects.get(pk=456)
        fran.last_name = 'Jones'
        fran.save()

        self.assertQuerysetEqual(Employee.objects.filter(last_name__exact='Jones') ,
                                 ['<Employee: Dan Jones>', '<Employee: Fran Jones>'])

        emps = Employee.objects.in_bulk([123, 456])
        self.assertEqual(repr(emps[123]),
                         '<Employee: Dan Jones>')


        b = Business(name='Sears')
        b.save()
        b.employees.add(dan, fran)
        self.assertQuerysetEqual(b.employees.all(),
                                 ['<Employee: Dan Jones>', '<Employee: Fran Jones>'])
        self.assertQuerysetEqual(fran.business_set.all(),
                                 ['<Business: Sears>'])
        self.assertEqual(repr(Business.objects.in_bulk(['Sears'])),
                         "{u'Sears': <Business: Sears>}")

        self.assertQuerysetEqual(Business.objects.filter(name__exact='Sears'),
                                 ['<Business: Sears>'])
        self.assertQuerysetEqual(Business.objects.filter(pk='Sears'),
                                 ['<Business: Sears>'])

        # Queries across tables, involving primary key
        self.assertQuerysetEqual(Employee.objects.filter(business__name__exact='Sears'),
                                 ['<Employee: Dan Jones>', '<Employee: Fran Jones>'])
        self.assertQuerysetEqual(Employee.objects.filter(business__pk='Sears'),
                                 ['<Employee: Dan Jones>', '<Employee: Fran Jones>'])

        self.assertQuerysetEqual(Business.objects.filter(employees__employee_code__exact=123),
                                 ['<Business: Sears>'])
        self.assertQuerysetEqual(Business.objects.filter(employees__pk=123),
                                 ['<Business: Sears>'])
        self.assertQuerysetEqual(Business.objects.filter(employees__first_name__startswith='Fran'),
                                 ['<Business: Sears>'])
Beispiel #41
0
def _add_to_businesses(params):
    """adds dictionary of attributes to businesses db"""
    print params
    if not Business.query.filter_by(yelp_id=params['yelp_id']).first():
        business = Business()
        cat_list = []
        for key in params:
            # adds elements in category lists to category table if they don't already exist
            if key == "categories":
                for cat in params[key]:
                    cat_list.append(cat)
                    if not Category.query.filter_by(category_name=cat).first():
                        category = Category(category_name=cat)
                        db.session.add(category)
                # THROUGH LINE 40 REPLACED BY 30-34
                # for group in params[key]:
                #     print type(group)
                #     for subtype in group:
                #         print type(subtype)
                #         if not Category.query.filter_by(category_name=subtype).first():
                #             category = Category(category_name=subtype)
                #             db.session.add(category)
                #         cat_list.append(subtype)
                #         print cat_list
            elif key == "yelp_id":
                business.yelp_id = params[key]
            elif key == "name":
                business.name = params[key]
            elif key == "address_line_1":
                business.address_line_1 = params[key]
            elif key == "address_line_2":
                business.address_line_2 = params[key]
            elif key == "city":
                business.city = params[key]
            elif key == "state":
                business.state = params[key]
            elif key == "zipcode":
                business.zipcode = params[key]
            elif key == "phone":
                business.phone = params[key]
            elif key == "latitude":
                business.latitude = params[key]
            elif key == "longitude":
                business.longitude = params[key]
        try:
            db.session.add(business)
            db.session.commit()
        except:
            db.session.rollback()
            print business.name, "has insufficient information, skipping."
            return None
    # creates rows in reference table
        for cat in cat_list:
            # creates row in reference table
            business = Business.query.filter_by(yelp_id=params['yelp_id']).first()
            catbus = BusinessCategory()
            print business.business_id
            catbus.business_id = business.business_id
            cat_object = Category.query.filter_by(category_name=cat).first()
            print cat_object.category_name
            catbus.category_id = cat_object.category_id

            if not BusinessCategory.query.filter_by(business_id=catbus.business_id,
                                                     category_id=catbus.category_id).first():
                db.session.add(catbus)
        db.session.commit()

        print "added " + business.name + " to db"

    else:
        print "Already in Dictionary"
        return None
Beispiel #42
0
def validate_db(yelp_object, haven_model=None):
    """takes the result of a yelp query by businesses id and compares it to the database entry. If any information
     on the local db is out of date, it is updated accordingly. Will also create new db if the haven_model is none"""
    print "yelp object in validate_db:", yelp_object
    print "haven_model in validate_db", haven_model
    new = False

    if haven_model is None:
        haven_model = Business()
        haven_model.yelp_id = yelp_object['id']
        new = True

    haven_model.name = yelp_object['name']

    if yelp_object['location'].get('address'):
        if len(yelp_object['location']['address']) > 1:
            haven_model.address_line_2 = yelp_object['location']['address'][1]

        haven_model.address_line_1 = yelp_object['location']['address'][0]

    # nothing in local db should not have a city and state code but if for some reason yelp wiped them, it prevents it
    # from being cleared, protecting db integrity
    if yelp_object['location'].get('city'):
        haven_model.city = yelp_object['location']['city']

    if yelp_object['location'].get('state_code'):
        haven_model.state = yelp_object['location']['state_code']

    if yelp_object['location'].get('postal_code'):
        haven_model.zipcode = yelp_object['location']['postal_code']

    if yelp_object.get('phone'):
        haven_model.phone = yelp_object['phone']

    if yelp_object['location'].get('coordinate'):
        haven_model.latitude = yelp_object['location']['coordinate']['latitude']
        haven_model.longitude = yelp_object['location']['coordinate']['longitude']
    try:
        if new:
            db.session.add(haven_model)
            print "successfully added"
        db.session.commit()
        print 'successfully committed'
        print "committed business:", haven_model

    except:
        print 'ut-oh'
Beispiel #43
0
    def post(self):
        user_name = self.request.get("user_name", default_value=None)
        biz = self.request.get("biz", default_value=None)
        time = self.request.get("time", default_value=None)

        if user_name is None:
            self.error(404)
            self.response.out.write("user_name required")
            return

        if biz is None:
            self.error(404)
            self.response.out.write("biz required")
            return

        if time is None:
            self.error(404)
            self.response.out.write("time required")
            return

        biz_name = None
        biz_rating = None
        biz_address = None
        try:
            biz_info = get_biz_info(biz)
            if biz_info:
                biz_name = biz_info["name"]
                biz_rating = int(biz_info["rating"])
                biz_address = biz_info["location"]["display_address"]
            else:
                self.error(404)
                self.response.out.write("Invalid biz ID or Yelp API error")
                return
        except:
            self.error(404)
            self.response.out.write("Invalid biz ID or Yelp API error")
            return

        try:
            business = None
            business_gql = Business.gql("where y_business_id = :1", biz)
            if business_gql.count() == 0:
                business = Business(y_business_id=biz, name=biz_name, rating=biz_rating, address=biz_address)
                business.put()
            else:
                for biz in business_gql:
                    business = biz
                    break

            train = None
            departure_time = datetime.datetime.fromtimestamp(float(time))
            train_gql = Train.gql("where business = :1 and departure_time = :2", business, departure_time)
            if train_gql.count() == 0:
                train = Train(destination=business, departure_time=departure_time)
                train.put()
            else:
                for t in train_gql:
                    train = t
                    break

            user = get_user_by_name(user_name)
            if user is None:
                user = User(name=user_name, train=train, subscriptions=[])

            user.train = train
            user.put()

            result = []
            if train:
                result.append(train.get_train_info())
                self.response.out.write(json.dumps(result))

        except:
            self.error(404)
Beispiel #44
0
def build_db(city, state):

    # categories = ['active', 'arts', 'auto', 'beautysvc', 'education', 'eventservices', 'financialservices', 'food',
    #               'health', 'homeservices', 'hotelstravel', 'localflavor', 'localservices', 'massmedia', 'nightlife',
    #               'pets', 'professional', 'publicservicesgovt', 'realestate', 'religiousorgs', 'restaurants',
    #               'shopping']
    city_state= city + ", " + state
    # for category in categories:

        # result_count = yelp_api.search_query(location=city_state, category_filter=category)['total']
    result_count = yelp_api.search_query(location=city_state)['total']

    offset = 0
    added = 0
    skipped = 0
    print result_count
    # max offset is 1000
    # try:
    while offset < result_count:
        while offset < 1000:
            # print category
            # results = yelp_api.search_query(location=city_state, category_filter=category, offset=offset)
            results = yelp_api.search_query(location=city_state, offset=offset)
            for result in results['businesses']:
                try:
                    business = Business()

                    # id
                    business.yelp_id = result['id']
                    # name
                    business.name= result['name']

                    # address lines 1 and 2
                    if result['location'].get('address'):
                        business.address_line_1 = result['location']['address'][0]
                        if len(result['location']['address']) > 1:
                            business.address_line_2 = result['location']['address'][1]

                    # city
                    business.city = result['location']['city']
                    # state code
                    business.state = result['location']['state_code']
                    # zip code
                    business.zipcode = result['location']['postal_code']

                    # phone
                    if result.get('phone'):
                        business.phone = result['phone']

                    # latitude and longitude
                    if result['location'].get('coordinate'):
                        business.latitude = result['location']['coordinate']['latitude']
                        business.longitude = result['location']['coordinate']['longitude']

                    # list of categories
                    if result.get('categories'):
                        cat_list = []
                        for group in result['categories']:
                            for subtype in group:
                                if not Category.query.filter_by(category_name=subtype).first():
                                    category = Category(category_name=subtype)
                                    db.session.add(category)

                                cat_list.append(subtype)

                    # if not Business.query.filter_by(yelp_id=business.yelp_id).first():
                    #     db.session.add(business)
                    db.session.add(business)
                    db.session.commit()
                    bus_id = business.business_id

                    for cat in cat_list:
                        # creates row in reference table
                        catbus = BusinessCategory()

                        catbus.business_id = bus_id

                        cat_object = Category.query.filter_by(category_name=cat).first()
                        catbus.category_id = cat_object.category_id

                        db.session.add(catbus)
                    db.session.commit()
                    added += 1
                    print "added" + str(added)
                    print business.name
                except:
                    print "already added:" + business.name
                    print 'skipped' + str(skipped)
                    skipped += 1
                    print "added so far: " + str(added)

                db.session.commit()
                offset += 20
Beispiel #45
0
def save_businesses():
    for bdata in iterate_file("business", shortcircuit=False):
        business = Business()
        business.business_id = bdata['business_id']
        business.name = bdata['name']
        business.full_address = bdata['full_address']
        business.city = bdata['city']
        business.state = bdata['state']
        business.latitude = bdata['latitude']
        business.longitude = bdata['longitude']
        business.stars = decimal.Decimal(bdata.get('stars', 0))
        business.review_count = int(bdata['review_count'])
        business.is_open = True if bdata['open'] == "True" else False
        try:
            business.save()
        except InternalError:
            print "i dont care"
            pass

        save_categories(bdata['business_id'], bdata['categories'])
        save_neighborhoods(bdata['business_id'], bdata['neighborhoods'])
Beispiel #46
0
def upload(request):
    """
        Uploads the receipt
        
        :url: /shoebox/upload/
        :param POST['email']: email identifying user
        :param POST['business_name']: i.e. McDonalds (blank)
        :param POST['address']: business address (blank)
        :param POST['location']: i.e. JFK International (blank)
        :param POST['phone']: phone number (blank)
        :param POST['city']: city (blank)
        :param POST['state']: state (blank)
        :param POST['purchase_date']: purchase date in NeatReceipts format
        :param POST['tax']: tax (blank)
        :param POST['tip']: tip (blank)
        :param POST['amount']: total amount
        :param POST['payment_method']: Visa, Master, Cash etc
        :param POST['category']: NeatReceipts category
        :param FILES['img']: Receipts image

        :rtype: JSON
        
        ::
        
            #: if success in posting returns id of created or update object in string format
            {'result': 'id'}
            #: if failed
            {'result': '-1'}
            #: if request was not POST
            {'result': '0'}
    """
    if request.method == 'POST':
        form = ReceiptUploadForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            # assign to the current user uploading data
            instance.user, created = OTNUserTemp.objects.get_or_create(email=request.POST['email']) 
            instance.save()
            
            receipt = DetailReceipt(basic=instance)
            if 'business_name' in request.POST:
                b = Business(name=request.POST['business_name'])
                if 'location' in request.POST:
                    b.location = request.POST['location']
                if 'phone' in request.POST:
                    b.phone = request.POST['phone']
                if 'address' in request.POST:
                    b.address = request.POST['address']
                if 'city' in request.POST:
                    c = City(name=request.POST['city'], state=request.POST['state'])
                    c.save()
                    b.city = c
                b.save()
                receipt.business = b
        
            if 'category' in request.POST:
                cat, created = Category.objects.get_or_create(name=request.POST['category'])
                receipt.category = cat
            if 'tax' in request.POST: 
                receipt.tax = request.POST['tax']
            if 'tip' in request.POST:
                receipt.tip = request.POST['tip']
            if 'payment_method' in request.POST:
                pmethod = request.POST['payment_method'].lower()
                if pmethod.find('cash') != -1:
                    receipt.payment_method = receipt.CASH
                elif pmethod.find('amex') != -1:
                    receipt.payment_method = receipt.AMEX
                elif pmethod.find('visa') != -1:
                    receipt.payment_method = receipt.VISA
                elif pmethod.find('master') != -1:
                    receipt.payment_method = receipt.MASTER
                elif pmethod.find('discover') != -1:
                    receipt.payment_method = receipt.DISCOVER
                else:
                    receipt.payment_method = receipt.CASH

            receipt.save()
            return JSONHttpResponse({'result':str(receipt.id)})
        else:
            return JSONHttpResponse({'result':'-1', 'form_errors':str(form.errors)})
    else:
        return JSONHttpResponse({'result':'0'})