Example #1
0
    def handle(self, *args, **options):

        if len(args) <= 0:
            raise CommandError('please specify file name')

        if not os.path.exists(args[0]):
            raise CommandError("file %s doesn't exist" % args[0])

        with open(args[0], 'r') as f:
            result = json.load(f)

        for i in result:
            try:
                place = Place.objects.get(vendor_id=i['id'])
                if place.data == json.dumps(i):
                    print "place id #%s already exist... skipping" % i["id"]
                else:
                    place.data = json.dumps(i)
                    place.save()
                    print "place id #%s was update" % i["id"]
            except Place.DoesNotExist:
                place = Place()
                place.vendor_id = i["id"]
                place.data = json.dumps(i)
                place.save()
                print "place id #%s added" % i["id"]
Example #2
0
def _create(request):
	if request.POST:
		m_place_name = request.POST.get('place_name')
		m_place_type_name = request.POST.get('place_type')
		m_latitude = request.POST.get('latitude')
		m_longitude = request.POST.get('longitude') 
		m_description = request.POST.get('description')
		m_creater_id = request.user.id
	else:
		return HttpResponseRedirect(reverse('index'))
		
	try:
		place = Place.objects.get(name = m_place_name,latitude = m_latitude, longitude = m_longitude,description = m_description)
	except Place.DoesNotExist:
		try:
			m_creater = User.objects.get(pk=m_creater_id)
		except User.DoesNotExist:
			return HttpResponseRedirect(reverse('index'))

		m_place_type = PlaceType.objects.get(name = m_place_type_name)
		place = Place(creater = m_creater, name = m_place_name,description = m_description, place_type = m_place_type,latitude = m_latitude, longitude = m_longitude,create_time = datetime.now())
		if request.user.is_superuser: 
			place.status = 2
		place.save()
		return HttpResponseRedirect(reverse('places:index'))
	
	return HttpResponseRedirect(reverse('index'))
Example #3
0
def add_places():
	"""
		Add the vendor features, categories, 
		then add the vendors
	"""
	# categories
	tapv= Category(name='tapvendors',description='TAP Vendors')
	db.session.add(tapv)
	# features
	avta_passes= Feature(name='avta_passes',description='AVTA Passes')
	ctc_coupons= Feature(name='ctc_coupons',description='CTC Coupons')
	ez_passes= Feature(name='ez_passes',description='EZ Passes')
	foothilltransit_passes= Feature(name='foothilltransit_passes',description='Foothill Transit Passes')
	ladot_passes= Feature(name='ladot_passes',description='LADOT Passes')
	longbeachtransit_passes= Feature(name='longbeachtransit_passes',description='Long Beach Transit Passes')
	metro_passes= Feature(name='metro_passes',description='Metro Passes')
	metrolink_passes= Feature(name='metrolink_passes',description='Metrolink Passes')
	montebello_passes= Feature(name='montebello_passes',description='Montebello Passes')
	rrtp_coupons= Feature(name='rrtp_coupons',description='Rider Relief Coupons')
	santaclaritatransit_passes= Feature(name='santaclaritatransit_passes',description='Santa Clarita Transit Passes')
	# add 'em to the db session
	db.session.add(avta_passes)
	db.session.add(ctc_coupons)
	db.session.add(ez_passes)
	db.session.add(foothilltransit_passes)
	db.session.add(ladot_passes)
	db.session.add(longbeachtransit_passes)
	db.session.add(metro_passes)
	db.session.add(metrolink_passes)
	db.session.add(montebello_passes)
	db.session.add(rrtp_coupons)
	db.session.add(santaclaritatransit_passes)
	# get the vendors from a csv
	tapvendors_csv = csv.reader(open("data/tapvendors.csv"), delimiter=",")
	# loop over 'em and add them to the db session
	for name,street,city,zipcode,phone,features,comments in tapvendors_csv:
		try:
			fl=features[1:-1].split(',')
			myfeatures = [eval(x) for x in fl]
			vndr=Place(name=name,
				address=street,
				city=city,
				zipcode=zipcode,
				phone=phone,
				features=myfeatures,
				categories=[tapv],
				comment=comments,
				)
			vndr._geocode(street,city,'CA',zipcode)
			print vndr.name
			db.session.add(vndr)
		except Exception as e:
			print "blargh! %s" %(e)
	# Now, COMMIT!
	db.session.commit()
Example #4
0
def create_dataset(request, name, description, in_places, user_id):
    try:
        # if the dataset already exists
        ds = Dataset.objects.get(name=name)
        messages.error(request, "שם המאגר קיים במערכת")
        return False
    except Dataset.DoesNotExist:
        pass
    ds = Dataset()
    ds.owner = User.objects.get(id=user_id)
    ds.name = name
    ds.description = description
    ds.save()

    for p in in_places:
        place = Place()

        try:
            place.vendor_id = p["id"]
        
            place.address = p["address"].strip()
            place.city = p["city"].strip()
            place.title = p["title"].strip()
        except KeyError, ex:
            print ex
            delete_dataset(ds)
            messages.error(request, "אחד השדות הדרושים חסר. וודא כי כל הרשומות מכילות את השדות: id, address, city, title")
            return False
        place.data = json.dumps(p)
        place.dataset = ds
        place.save()
Example #5
0
 def setUp(self):
     place = Place()
     place.name = 'Nome'
     place.address = 'Endereço'
     place.neighborhood = 'Bairro'
     place.time = 'Seg. a Sexta: 19h às 2'
     place.phone = '(41) 5555-5555'
     place.city = City.objects.get(name='Curitiba')
     place.save()
     self.place = place
Example #6
0
    def setUp(self):
        User.objects.create_user("segalle", email=None, password="******")
        User.objects.create_user("moshe", email=None, password="******")
        p = Place()
        p.vendor_id = 1000
        p.data = {
        "city": "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd", 
        "name": "\u05e9\u05d9\u05da \u05d2'\u05e8\u05d0\u05d7", 
        "district": "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd", 
        "phones": "02-5871923", 
        "notes": "", 
        "subdistrict": "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd", 
        "days": [
            "8:00-17:00", 
            "8:00-17:00", 
            "8:00-17:00", 
            "8:00-17:00", 
            "8:00-13:00", 
            "\u05e1\u05d2\u05d5\u05e8"
        ], 
        "address": "\u05de\u05e8\u05db\u05d6 \u05e8\u05e4\u05d5\u05d0\u05d9", 
        "owner": "\u05e2\u05d9\u05e8\u05d9\u05d9\u05ea \u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd", 
        "id": 1000
        }
        p.save()
        
        self.pm = Placemark()
        self.pm.place = p
        self.pm.city = "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd"
        self.pm.address = "\u05de\u05e8\u05db\u05d6 \u05e8\u05e4\u05d5\u05d0\u05d9"
        self.pm.lat = 31.15
        self.pm.lng = 32.16
        self.pm.save()

        self.pm1 = Placemark()
        self.pm1.place = p
        self.pm1.city = "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd"
        self.pm1.address = "\u05de\u05e8\u05db\u05d6 \u05e8\u05e4\u05d5\u05d0\u05d9"
        self.pm1.lat = 31.25
        self.pm1.lng = 32.26
        self.pm1.save()

        self.pm2 = Placemark()
        self.pm2.place = p
        self.pm2.city = "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd"
        self.pm2.address = "\u05de\u05e8\u05db\u05d6 \u05e8\u05e4\u05d5\u05d0\u05d9"
        self.pm2.lat = 31.35
        self.pm2.lng = 32.36
        self.pm2.save()
Example #7
0
 def save(self, request, place=None):
     cleaned_data = self.cleaned_data
     name = cleaned_data['name']
     street = cleaned_data['addr']
     city = cleaned_data['city']
     state = cleaned_data['state']
     zip = cleaned_data['zip']
     apt = cleaned_data['apt']
     location = "%s %s, %s %s" % (street, city, state, zip)
     from geopy import geocoders
     try:
         geocoder = geocoders.Google('ABQIAAAA4HDqD8t_GwFAvzzFapPlGRQ_R5Qiphk1phJft3u3QNxBad8fLRRA-q4ZSxjFfS9SK2wsDFMnz3jl7g')
         geocoding_results = None
         geocoding_results = list(geocoder.geocode(location, exactly_one=False))
     except:
         # no internet??
         # log failure for db update
         latitude = longitude = -1
     if geocoding_results:
         address, (latitude, longitude) = geocoding_results[0]
     try:
         if post_data['email']:
             username, password = create_account_from_email(post_data['email'])
             user = authenticate(username=username, password=password) 
             login(request, user)
     except:
         pass
     if place: #request.REQUEST['place'] == '-1':
         print 'place', place
         place.name = name
         place.zip = zip
         place.apt = apt
         place.street = street
         place.city = city
         place.latitude = latitude
         place.longitude = longitude
         # delete pics ? 
     else:
         place = Place(user=request.user, name=name, street=street, city=city, \
              state=state, zip=zip, apt=apt, latitude=latitude, longitude=longitude)
     place.save()
     place_pic_uploader(place, request.FILES)
     return place
Example #8
0
    def save(self, request):
        from places.models import Place, PlacePic, place_pic_uploader

        cleaned_data = self.cleaned_data
        name = cleaned_data["name"]
        street = cleaned_data["addr"]
        city = cleaned_data["city"]
        state = cleaned_data["state"]
        zip = cleaned_data["zip"]
        apt = cleaned_data["apt"]
        location = "%s %s, %s %s" % (street, city, state, zip)
        from geopy import geocoders

        geocoder = geocoders.Google(
            "ABQIAAAA4HDqD8t_GwFAvzzFapPlGRQ_R5Qiphk1phJft3u3QNxBad8fLRRA-q4ZSxjFfS9SK2wsDFMnz3jl7g"
        )
        geocoding_results = None
        geocoding_results = list(geocoder.geocode(location, exactly_one=False))
        if geocoding_results:
            place, (latitude, longitude) = geocoding_results[0]
        try:
            if post_data["email"]:
                username, password = create_account_from_email(post_data["email"])
                user = authenticate(username=username, password=password)
                login(request, user)
        except:
            pass
        place = Place(
            user=request.user,
            name=name,
            street=street,
            city=city,
            state=state,
            zip=zip,
            apt=apt,
            latitude=latitude,
            longitude=longitude,
        )
        place.save()
        place_pic_uploader(place, request.FILES)
        return place
Example #9
0
def add_stations():
	"""
		Add the station features, categories, 
		then add the stations
	"""
	rails= Category(name='railstations',description='Rail Stations')
	db.session.add(rails)
	locker_f= Feature(name='bikelockers',description='Bike Lockers')
	db.session.add(locker_f)
	stations=csv.DictReader(open('data/railstations.csv','rU'), delimiter=",")
	"""['stop_id',
		 'stop_code',
		 'stop_name',
		 'stop_desc',
		 'stop_lat',
		 'stop_lon',
		 'stop_url',
		 'location_type',
		 'parent_station',
		 'tpis_name']"""
	for row in stations:
		try:
			myfeatures = [locker_f]
			comment = "parent_station:%s" %(row['parent_station'])
			vndr=Place(name=row['stop_name'],
				lat=row['stop_lat'],
				lon=row['stop_lon'],
				features=myfeatures,
				categories=[rails],
				comment=comment,
				)
			vndr._reversegeocode(row['stop_lat'],row['stop_lon'])
			print vndr.name
			db.session.add(vndr)
		except Exception as e:
			print "blargh! %s" %(e)
	# Now, COMMIT!
	db.session.commit()
Example #10
0
def place_copy(request, place_id):
    source = get_object_or_404(Place, id=place_id)

    place = Place(user=request.user,
                  name=source.name,
                  pltype=source.pltype,
                  city=source.city,
                  locale=source.locale,
                  cuisine=source.cuisine,
                  dog_friendly=source.dog_friendly,
                  has_bar=source.has_bar,
                  outdoor=source.outdoor,
                  yelp=source.yelp,
                  )

    place.id = Place.next_id()
    place.save()
    ChangeLog.place_copy(place, request.user.username, place_id)
    m = 'User: {} copied place: {}'.format(request.user, place.name)
    logprint(m)
    log_to_slack(m)
    # because this is a new request it need a leading /
    return redirect('/places/edit/{}/'.format(place.id))
Example #11
0
def create_johnnys(user):
    p = Place.from_args(
        user=get_user(user),
        name="Johnny's",
        locale='Harbor',
        city='Santa Cruz',
        outdoor=False,
        rating=2,
        dog_friendly=False,
        visited=1,
        good_for='fancy dinner',
        pltype=Place.RESTAURANT,
        comment='good seafood')
    p.save()
    ChangeLog.create_place(p)
    return(p)
Example #12
0
    def send_notification(cls, place_id):
        total = cls.objects.for_place_today(place_id).count()
        try:
            place = Place.objects.get(pk=place_id)
        except Place.DoesNotExist:
            return

        notification = {
            'place_id': place_id,
            'total': total,
            'users': place.voters,
            'most_wanted': Place.most_wanted()
        }
        Group('votes').send({
            'text': json.dumps(notification),
        })
Example #13
0
def create_engfer(user):
    p = Place.from_args(
        user=get_user(user),
        name='Engfer Pizza',
        locale='Harbor',
        city='Santa Cruz',
        outdoor=True,
        rating=3,
        dog_friendly=True,
        visited=1,
        good_for='casual dinner',
        pltype=Place.RESTAURANT,
        comment='only open at dinner')
    p.save()
    ChangeLog.create_place(p)
    return(p)
Example #14
0
    def handle(self, *args, **options):

        if len(args) <= 0:
            raise CommandError('please specify file name')

        if not os.path.exists(args[0]):
            raise CommandError("file %s doesn't exist" % args[0])

        fullgeojson = {"type": "FeatureCollection", "features": []}
        fullgeojson["features"] = [Place.export_feature(p) for p in Place.objects.all() if Place.export_feature(p) != None]

        fullpath = os.path.join(args[0], 'full.geojson')
 
        with open(fullpath, 'w') as f:
            json.dump(fullgeojson, f, indent=4)

        print "Geojson was created successfuly"
Example #15
0
    def test_leading_placemark(self):
        c = Client()
        c.login(username="******", password="******")
        response = c.post('/vote/', {'id': str(self.pm.id), 'positive': 'True'})
        response = c.post('/vote/', {'id': str(self.pm1.id), 'positive': 'True'})
        response = c.post('/vote/', {'id': str(self.pm2.id), 'positive': 'false'})
        c.logout()
        
        c.login(username="******", password="******")
        response = c.post('/vote/', {'id': str(self.pm.id), 'positive': 'True'})
        response = c.post('/vote/', {'id': str(self.pm1.id), 'positive': 'false'})
        response = c.post('/vote/', {'id': str(self.pm2.id), 'positive': 'false'})
        c.logout()
        
        place = Place.objects.get(vendor_id=1000)

        leading = Place.get_leading_placemark(place)
        self.assertEqual(leading.id,1)
Example #16
0
    def setUp(self):
        """create some stuff"""
        self.m1 = Menu.objects.create(name="menu_test")

        self.mi_fanta = MenuItem.objects.create(name="fanta", price=2.5, menu=self.m1)
        self.mi_cola = MenuItem.objects.create(name="cola", price=1.85, menu=self.m1)

        self.speyker = Place(name="speyker", menu=self.m1)
        self.speyker.save()

        self.t1 = Table(place=self.speyker)
        self.t1.save()

        self.t2 = Table(place=self.speyker)
        self.t2.save()

        self.t3 = Table(place=self.speyker)
        self.t3.save()
Example #17
0
    def get_context_data(self, **kwargs):

        from places.models import Place

        context = super(DesktopView, self).get_context_data(**kwargs)

        if self.request.GET.get('srch'):
            from urllib import unquote
            srch = unquote(self.request.GET.get('srch'))
            p = Place.from_name(srch) 
            context['srch'] = srch
        else:
            lat = float(self.request.GET.get('lat', 40.7500))
            lon = float(self.request.GET.get('lon', -111.8833))
            p = Place(lat, lon)

        context['place'] = p

        return context
Example #18
0
 def test_export_feature(self):
     
     c = Client()
     c.login(username="******", password="******")
     response = c.post('/vote/', {'id': str(self.pm.id), 'positive': 'True'})
     response = c.post('/vote/', {'id': str(self.pm1.id), 'positive': 'True'})
     response = c.post('/vote/', {'id': str(self.pm2.id), 'positive': 'false'})
     c.logout()
     
     c.login(username="******", password="******")
     response = c.post('/vote/', {'id': str(self.pm.id), 'positive': 'True'})
     response = c.post('/vote/', {'id': str(self.pm1.id), 'positive': 'false'})
     response = c.post('/vote/', {'id': str(self.pm2.id), 'positive': 'false'})
     c.logout()
     
     place = Place.objects.get(vendor_id=1000)
     
     feature = Place.export_feature(place)
     print feature
     
     self.assertEqual(1,1)
Example #19
0
class MenuTest(TestCase):
    """ Simple tests on the MenuItem object, and there menus group """

    def setUp(self):
        """create some stuff"""
        self.m1 = Menu.objects.create(name="menu_test")

        self.mi_fanta = MenuItem.objects.create(name="fanta", price=2.5, menu=self.m1)
        self.mi_cola = MenuItem.objects.create(name="cola", price=1.85, menu=self.m1)

        self.speyker = Place(name="speyker", menu=self.m1)
        self.speyker.save()

        self.t1 = Table(place=self.speyker)
        self.t1.save()

        self.t2 = Table(place=self.speyker)
        self.t2.save()

        self.t3 = Table(place=self.speyker)
        self.t3.save()

    def test_filter_contains_a(self):
        # find stuff that contains an 'a' ( 2 )
        self.assertEquals(MenuItem.objects.filter(name__contains='a', menu=self.m1).count(),
                          2)

    def test_menu_item(self):
        # two items are created
        self.assertEquals(MenuItem.objects.filter(menu=self.m1).count(),
                          2)

    def test_find_cola(self):
        # find back cola
        self.assertIsNotNone(MenuItem.objects.get(name="cola", menu=self.m1))

    def test_no_more_fristi(self):
        # do not find fristi
        with self.assertRaises(MenuItem.DoesNotExist):
            MenuItem.objects.get(name="fristi", menu=self.m1)

    def test_find_menu(self):
        # try to find all the menu items for 1 menus
        menu = Menu.objects.get(name="menu_test")

        self.assertEquals(menu.menuitem_set.count(), 2)

    def test_find_a_menu_and_find_also_menu_items(self):
        """ Fetch a menus, and list the menus items  """

        # Menu
        menu = Menu.objects.create(name="some menu")

        # menu items
        MenuItem.objects.create(name="Duvel", price=3.8, menu=menu)
        MenuItem.objects.create(name="Vedet", price=2.5, menu=menu)

        found_menu_list = Menu.objects.filter(name="some menu")
        self.assertEquals(found_menu_list.count(), 1)

        found_menu = found_menu_list.first()

        self.assertEquals(found_menu.menuitem_set.count(), 2)

    def test_add_items_to_a_menu(self):
        # the setup-created menus
        m1 = Menu.objects.get(name="menu_test")

        self.assertEquals(m1.menuitem_set.get(name="fanta").price, Decimal('2.5'))
        self.assertEquals(m1.menuitem_set.get(name="cola").price, Decimal('1.85'))

        # start with 2 items
        self.assertEquals(len(m1.menuitem_set.all()), 2)

        # adding coffee
        MenuItem.objects.create(name="coffee", price=1.8, menu=m1)

        found_menu = Menu.objects.get(pk=m1.pk)

        self.assertEquals(len(found_menu.menuitem_set.all()), 3)

    def test_menu_can_not_have_twice_the_same_item(self):
        # trying to add fanta twice
        self.assertRaises(MenuItem.objects.create, name="fanta", price=2.5, menu=self.m1)

    def test_getting_all_orders_for_speyker(self):
        Order.objects.create(table=self.t2)

        orders = self.speyker.get_orders()

        self.assertEquals(len(orders), 1)
        self.assertEquals(orders[0].table, self.t2)


    def test_get_menu_items(self):
        """Testing the json response for menu items that"""

        # pks can not be stored, because in postgres the sequences are preserved in between tests

        json_menu_items = [
            {"pk": self.mi_fanta.pk, "model": "menus.menuitem", "fields":
                {"category": "", "menu": 2, "price": "2.5", "name": "fanta"}},
            {"pk": self.mi_cola.pk, "model": "menus.menuitem", "fields":
                {"category": "", "menu": 2, "price": "1.85", "name": "cola"}}]

        c = Client()
        r = c.get('/mi/' + self.t1.pk, follow=True)

        self.assertEqual(200, r.status_code)
        self.assertJSONEqual(r.content, json_menu_items)

    def test_add_items_to_order_by_id(self):
        """Testing that adding menu items by id has the correct effect on the price"""

        o = Order(table=self.t1)
        o.save()

        mi = self.m1.menuitem_set.all()[0]
        o.add_item_by_pk(mi.pk, 2)

        expected_price = mi.price * 2
        self.assertAlmostEqual(o.calculate_total_price(), expected_price)
        self.assertEqual(1, o.menuItems.count())

        mi2 = self.m1.menuitem_set.all()[0]
        o.add_item_by_pk(mi2.pk, 3)

        expected_price = mi.price * 2 + mi2.price * 3
        self.assertAlmostEqual(o.calculate_total_price(), expected_price)
        self.assertEqual(2, o.menuItems.count())

    def test_create_category(self):
        """can i create and find a category?"""

        c = Category(name='beer', place=self.speyker)
        c.save()

        found_c = Category.objects.filter(place=self.speyker)
        self.assertEqual(found_c.count(), 1)

        found_c = found_c.all()[0]

        self.assertEqual(found_c.name, 'beer')

    def test_category_has_to_be_unique(self):
        """I should not be able to add 2 categories with the same name and place"""

        self.assertEqual(Category.objects.all().count(), 0)

        Category.objects.create(name='beer', place=self.speyker)

        # Cannot add a second beer to this place
        #
        # the atomic() is needed because of the error we expect. If I did not do this,
        # later questions to this transaction would result in
        # "An error occurred in the current transaction. You can't execute queries until
        # the end of the 'atomic' block."
        # see https://docs.djangoproject.com/en/1.6/topics/db/transactions/#django.db.transaction.atomic
        with self.assertRaises(IntegrityError), transaction.atomic():
            Category.objects.create(name='beer', place=self.speyker)

        # But another Category is no problem
        Category.objects.create(name='ham&cheese', place=self.speyker)

        # Also, beer can be added to another place!
        p2 = Place.objects.create(name="bogus place")
        Category.objects.create(name='beer', place=p2)
Example #20
0
def places():
    return Place.place_choices()
Example #21
0
def create_sanjose():
    user = get_user(1)
    for s in sanjose_restaurants:
        p = Place.from_csv(user, s)
        ChangeLog.create_place(p)
Example #22
0
File: forms.py Project: biznixcn/WR
    def process_objects(self, circuit):
        results = OrderedDict()
        # multiple = true if creating a place and a CircuitStop
        results['multiple'] = False
        # conflict = CircuitStop with this place already exists
        results['conflict'] = False
        new_place = False

        place = None

        place_id = self.cleaned_data.get('place_id', None)
        print type(place_id)
        if place_id != '':
            try:
                place = Place.objects.get(place_id=place_id)
            except Place.DoesNotExist:
                place = None

        # Enter here if query did not returned a Place
        if place is None:
            # Mandatory fields
            place = Place()
            place.name = self.cleaned_data.get('name', '')
            place.coordinates = Point(
                self.cleaned_data.get('lat'),
                self.cleaned_data.get('lng')
            )
            if place_id is not None:
                place.place_id = place_id
            else:
                # TODO handle case when no place_id is passed
                pass
            # Optional fields
            if 'address' in self.cleaned_data:
                place.address = self.cleaned_data.get('address', '')
            if 'phone_number' in self.cleaned_data:
                place.phone_number = self.cleaned_data.get('phone_number', '')
            if 'website' in self.cleaned_data:
                place.website = self.cleaned_data.get('website', '')
            if 'crossStreet' in self.cleaned_data:
                place.crossStreet = self.cleaned_data.get('crossStreet', '')
            if 'twitter' in self.cleaned_data:
                place.twitter = self.cleaned_data.get('twitter', '')
            # get place_type from db or default
            try:
                place_type = PlaceType.objects.get(
                    place_type_id=self.cleaned_data.get('place_type_id')
                )
            except PlaceType.DoesNotExist:
                place_type = PlaceType.objects.get(
                    place_type_id=DEFAULT_PLACE_TYPE_ID
                )

            place = Place.new_place_save(place, place_type)

            # Sync new Place with MongoDB
            # check_mongo(place)
            # Setting the new place flag to True
            new_place = True

        # Check if the place object has not yet been included in
        # a circuit stop that is part of the circuit
        if circuit.circuit_stops.filter(place=place).exists():
            # There is a conflict with the current state of the
            # resource since there already exists a circuit stop
            # referring to that place
            results['conflict'] = True
            return results

        # Creating a circuit stop for the place
        circuit_stop = CircuitStop(
            circuit=circuit,
            place=place,
            description=self.clean_description(),
            picture=self.cleaned_data.get('picture')
        )

        circuit_stop.save()
        # Now we add it to the circuit
        circuit.circuit_stops.add(circuit_stop)
        circuit.save()
        # Create objects dictionary
        results['circuit_stop'] = circuit_stop
        if new_place:
            results['place'] = place
            results['multiple'] = True
        # Return results dictionary
        return results
Example #23
0
def place_translation(request, id, lang):
    trans = Place.c_get_translation(id, lang)
    return HttpResponse(json.dumps((linebreaksbr(trans[0],True),trans[1])), mimetype='application/json')
Example #24
0
def addPlace(request, ajax=False, id=None):
    template_name = "add_place_wizard.html" if ajax else "add_place.html"
    sayfa = Sayfa.al_anasayfa()
    lang = request.LANGUAGE_CODE
    user = request.user
    response = {}
    new_place = None
    loged_in = user.is_authenticated()
    photos = []
    profile = user.get_profile()
    ask_phone = not bool(profile.phone.strip()) if profile.phone else True
    if id:
        old_place = get_object_or_404(Place, pk=id)
        photos = list(old_place.photo_set.values_list('id',flat=True))
        if old_place.owner != request.user:
            return HttpResponseForbidden()
        old_place.invalidate_caches()
    else:
        old_place = Place()

    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        login_form = LoginForm(request.POST)
        form = addPlaceForm(request.POST, instance=old_place, req_phone=ask_phone)
        if form.is_valid():
            new_place=form.save(commit=False)
            new_place.translation_check()
#            if register_form.is_valid() or loged_in:
#                if not loged_in:
#                    user = register_form.save(commit=False)
#                    user.username = user.email
#                    user.set_password(register_form.cleaned_data['pass1'])
#                    user.save()
            phone = form.cleaned_data.get('phone')
            if phone:
                profile.phone = phone
                profile.save()
            new_place.owner = user
            new_place.lat = str(new_place.lat)
            new_place.lon = str(new_place.lon)
            new_place.lang = request.LANGUAGE_CODE
#            log.info('%s %s '% (new_place.lang, request.LANGUAGE_CODE))
            new_place.save()
            form.save_m2m()
            for tag in form.cleaned_data['tags']:
                new_place.tags.add(tag)
#            log.info(form.cleaned_data['tags'])

            new_place.save()
            d, new = Description.objects.get_or_create(place=new_place, lang=new_place.lang)
            d.text = new_place.description
            d.title = new_place.title
            d.save()
            tmp_photos = request.session.get('tmp_photos')
            if tmp_photos:
                Photo.objects.filter(id__in=tmp_photos).update(place=new_place)
                if tmp_photos[0]:
                    p=Photo.objects.filter(pk=tmp_photos[0])
                    if p: p[0].save()
                request.session['tmp_photos']=[]
            if not ajax:
                if not new_place.published:
                    messages.success(request, _('Your place succesfully saved but not published yet.'))
                    messages.info(request, _('You can publish this place by pressing the "Publish" button below.'))
                else:
                    messages.success(request, _('Your changes succesfully saved.'))
                return HttpResponseRedirect('%s#do_listPlaces,this'%reverse('dashboard'))
        else:
            for e in form.errors:
                messages.error(request, e)
        if ajax:
            response = {
                'user':getattr(user,'username'),
                'loged_in':loged_in,
#                'new_place':repr(new_place),
                'errors':form.errors,
                'new_place_id':getattr(new_place,'id',0),
            }
            return HttpResponse(json.dumps(response), mimetype='application/json')


    else:
        form = addPlaceForm(instance=old_place, req_phone=ask_phone)
        register_form = RegisterForm()
        login_form = LoginForm()
    str_fee =  _('%s Service Fee '% configuration('host_fee'))
    context = {'form':form, 'rform':register_form,'lform':login_form,'place':old_place,
               'host_fee':configuration('host_fee'), 'str_fee':str_fee, 'photos':photos,
               'tags':TagTranslation.objects.filter(lang=request.LANGUAGE_CODE),
               'existing_tags':[],

    }
    if id:
        context['existing_tags'] = old_place.tags.values_list('id',flat=True)
    return render_to_response(template_name, context, context_instance=RequestContext(request))
Example #25
0
def delete_dataset(ds):
    for place in ds.places.all():
        Place.delete(place)
    Dataset.delete(ds)
Example #26
0
class SimpleTest_orders(TestCase):
    def setUp(self):
        """create some stuff"""
        self.m1 = Menu.objects.create(name="menu_test")

        self.mi1 = MenuItem.objects.create(name="fanta", price=2.5, menu=self.m1)
        self.mi2 = MenuItem.objects.create(name="cola", price=1.85, menu=self.m1)

        self.speyker = Place(name="speyker", menu=self.m1)
        self.speyker.save()

        self.t1 = Table(place=self.speyker)
        self.t1.save()

        self.t2 = Table(place=self.speyker, table_nr="2")
        self.t2.save()

        self.t3 = Table(place=self.speyker)
        self.t3.save()

    def test_basic_addition(self):
        """
        Tests that 1 + 1 always equals 2.
        """
        self.assertEqual(1 + 1, 2)

    def test_create_an_order(self):
        cola = self.t1.get_menu().menuitem_set.get(name='cola')

        order = Order(table=self.t1)
        order.save()

        order.add_menuitem(cola, 2)

        # When comparing with equals, the decimals are converted into floats
        # i guess.
        self.assertEqual(order.calculate_total_price(), Decimal('3.7'))

    def test_more_elaborate_order(self):
        order = Order(table=self.t1)
        order.save()

        order.add_menuitem(self.m1.menuitem_set.get(name="cola"), 3)
        order.add_menuitem(self.m1.menuitem_set.get(name="fanta"), 1)

        self.assertEqual(order.calculate_total_price(), Decimal('8.05'))
        self.assertEquals(len(order.menuItems.all()), 2)

        # get the menu item count
        order_menu_item = OrderMenuItem.objects.get(menuItem=self.m1.menuitem_set.get(name="cola"),
                                                    order=order)
        self.assertEquals(order_menu_item.amount, 3)

    def test_order_statuses(self):
        order = Order(table=self.t1)

        # fist status is ordered ( default )
        self.assertEquals(order.get_status_display(), 'Ordered')

        order.proceed()
        # second status is done
        self.assertEquals(order.get_status_display(), 'Done')

        order.proceed()
        # last status is payed
        self.assertEquals(order.get_status_display(), 'Payed')

        # no next step, except an exception
        self.assertRaises(order.proceed)

    def test_place_order_price(self):
        order = {self.mi1.pk: 2, self.mi2.pk: 1}
        c = Client()
        c.post("/order/p/" + self.t1.pk + '/', order)

        o = Order.objects.get(table=self.t1)
        self.assertEqual(o.calculate_total_price(), Decimal('6.85'))

    def test_posting_an_order(self):
        table_pk = self.t1.pk
        c = Client()

        # a cola please
        response = c.post("/order/p/%s/" % table_pk, {'cola_amount': '3'})

        # find the orders in the database
        orders = Order.objects.filter(table__pk=table_pk).all()
        self.assertEquals(len(orders), 1)

    def test_ordered_status(self):
        import json

        order = Order.objects.create(table=self.t2)
        order.add_menuitem(self.mi1, 2)
        order.add_menuitem(self.mi2, 1)
        order.save()

        c = Client()
        response = c.get("/wait_status/" + str(order.pk) + "/", {}, False,
                         HTTP_ACCEPT="application/json",
                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        response = json.loads(response.content)
        self.assertEquals(Order.ORDERED, response['status'])
        self.assertTrue(response.get('next_check_timeout'))

        order.status = Order.DONE
        order.save()

        # response should contain
        response = c.get("/wait_status/" + str(order.pk) + "/", {}, False,
                         HTTP_ACCEPT="application/json",
                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        response = json.loads(response.content)
        self.assertEquals(Order.DONE, response['status'])

    def test_place_order_rest_call(self):
        self.assertEqual(Order.objects.filter(table=self.t1).count(), 0)

        c = Client()

        post_order = {self.mi1.pk: 2, self.mi2.pk: 6}

        r = c.post('/order/p/%s/' % self.t1.pk, post_order, follow=True)
        self.assertEqual(r.status_code, 200)

        self.assertEqual(Order.objects.filter(table=self.t1).count(), 1)

    def test_orders_open(self):
        order = Order.objects.create(table=self.t2)
        order.add_menuitem(self.mi1, 2)
        order.add_menuitem(self.mi2, 1)
        order.save()

        c = Client()
        r = c.get('/order/o/%d/' % self.speyker.pk, {}, False,
                  HTTP_ACCEPT="application/json",
                  HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        orders = json.loads(r.content)

        self.assertEqual(len(orders), 1)
        order = orders[0]
        self.assertEquals(len(order), 5)
        self.assertEquals(order['table_nr'], self.t2.table_nr)
        self.assertIsNotNone(order['pk'])
        self.assertEquals(order['seconds'], 1)

        item_amounts_ = order['item_amounts']
        self.assertEquals(len(item_amounts_), 2)

        item_amounts_1 = item_amounts_[0]
        self.assertEquals(item_amounts_1[0], 'fanta')
        self.assertEquals(item_amounts_1[1], 2)
        self.assertEquals(item_amounts_1[2], '5')

    def test_order_in_progress(self):
        order = Order.objects.create(table=self.t2)
        order.save()

        places_views.order_in_progress(None, order.pk)

        order_2 = Order.objects.get(pk=order.pk)
        self.assertEquals(order_2.status, Order.IN_PROGRESS)
Example #27
0
 def test_null_place(self):
     with self.assertRaises(IntegrityError):
         p = Place()
         p.save()
Example #28
0
def index(request):
    logprint('User: {} is on home page'.format(request.user))
    if request.user.username == 'admin':
        logout(request)
    return render(request, 'places/index.html', {'last': Place.last_added()})
Example #29
0
    def setUp(self):
        place = Place()
        place.name = 'Sirvo Jantar'
        place.address = 'Endereço'
        place.neighborhood = 'Bairro'
        place.time = 'Seg. a Sexta: 19h às 2'
        place.phone = '(41) 5555-5555'
        place.city = City.objects.get(name='Curitiba')
        place.save()
        jantar = Meal.objects.get(name='Jantar')
        place.meal.add(jantar)
        place.save()
        self.place = place


        place2 = Place()
        place2.name = u'Sirvo Almoço'
        place2.address = 'Endereço'
        place2.neighborhood = 'Bairro'
        place2.time = 'Seg. a Sexta: 19h às 2'
        place2.phone = '(41) 5555-5555'
        place2.city = City.objects.get(name='São Paulo')
        place2.save()
        almoco = Meal.objects.get(name='Almoço')
        place2.meal.add(almoco)
        place2.save()
        self.place2 = place2
Example #30
0
    def handle(self, *args, **options):
        #self.send_email('Start Search Places - %s' % time.strftime("%c"))
        error = False
        numrows = 10
        count_api = 0
        for keyword in keywords:
            grids = Grid.objects.filter(scanned=False, keyword=keyword)[:numrows]
            #print grids.count()
            #print keyword
            while grids.count() and not error > 0:
                for g in grids:
                    #print g.keyword,
                    places, status, err_message = nearby_search(str(g.lat), str(g.lng), '3000', g.keyword)
                    time.sleep(1)
                    #print status
                    if status == 'OVER_QUERY_LIMIT':
                        print '%s - OVER_QUERY_LIMIT - %s' % (time.strftime("%c"), err_message)
                        self.send_email('OVER_QUERY_LIMIT')
                        error = True
                        break
                    elif status == 'REQUEST_DENIED':
                        print '%s - REQUEST_DENIED - %s' % (time.strftime("%c"), err_message)
                        self.send_email('REQUEST_DENIED')
                        #error = True
                        #break
                    elif status == 'INVALID_REQUEST':
                        print '%s - INVALID_REQUEST- %s' % (time.strftime("%c"), err_message)
                        self.send_email('INVALID_REQUEST')
                        #error = True
                        #break
                    elif status == 'ZERO_RESULTS':
                        #print '%s - ZERO' % time.strftime("%c")
                        places = []
                    elif status == 'OK':
                        g.count_place = len(places)
                        #print places
                        #print len(places)
                        for place in places:
                            place_detail, status, err_message = get_detail(place['place_id'])
                            count_api += 1
                            pp = Place.objects.filter(lat=place_detail['geometry']['location']['lat'],
                                                      lng=place_detail['geometry']['location']['lng'],
                                                      grid__place_type=g.place_type)
                            if pp.count() == 0:
                                p = Place(name=place_detail['name'],
                                          lat=place_detail['geometry']['location']['lat'],
                                          lng=place_detail['geometry']['location']['lng'],
                                          address=place_detail['formatted_address'],
                                          grid=g,
                                          place_id=place_detail['place_id'],
                                          place_detail=json.dumps(place_detail))

                                if 'permanently_closed' in place_detail:
                                    p.permanently_closed = True
                                else:
                                    p.permanently_closed = False
                                p.save()
                    else:
                        print status + ' - ' + time.strftime("%c") + ' - ' + err_message
                        self.send_email(status)
                        #error = True
                        #break

                    if status == 'OK' or status =='ZERO_RESULTS':
                        #print g.keyword
                        kws = KeywordSummary.objects.get(keyword=g.keyword)
                        kws.grid_complete += 1
                        #print kws.grid_complete
                        g.scanned = True
                        kws.save()
                        g.save()
                grids = Grid.objects.filter(scanned=False, keyword=keyword)[:numrows]
            if error:
                    break
Example #31
0
def create_campbell():
    user = get_user(1)
    for s in campbell_restaurants:
        p = Place.from_csv(user, s)
        ChangeLog.create_place(p)
Example #32
0
django.setup()
from places.models import Place
import pandas as pd
import sys
from places.google_places_helper import fetch_details_for_place_id

fl = sys.argv[1]

df = pd.read_csv(fl)

for _, row in df.iterrows():
    place_id = row['place_id']
    try:
        p = Place.objects.get(place_id=place_id)
    except Place.DoesNotExist:
        p = Place(place_id=place_id)

        r, photo_url, photo_attrib = fetch_details_for_place_id(place_id)
        if not r.get('rating'):  # probably not meaningful place
            continue
        p.name = r['name']
        p.address = r['formatted_address']
        p.image_url = photo_url
        p.user_rating = r['rating']
        p.num_ratings = r['user_ratings_total']
        p.place_types = ','.join(r.get('types', []))
        p.place_url = r.get('website')
        lat, lng = r['geometry']['location']['lat'], r['geometry']['location']['lng']
        p.lat = lat or row['lat']
        p.lng = lng or row['lng']
        p.image_attribution = photo_attrib
Example #33
0
def place_add(request, pltype='rest'):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        if pltype == 'rest':
            form = RestaurantForm(request.POST)
        else:
            form = HotelForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            d = form.cleaned_data
            p = Place(user=request.user,
                      name=d['name'].strip(),
                      city=d['city'].strip(),
                      locale=d['locale'].strip(),
                      visited=d['visited'],
                      rating=d['rating'])
            p.id = Place.next_id()

            p.good_for = d['good_for']
            p.comment = d['comment']
            p.dog_friendly = d['dog_friendly']

            if pltype == 'rest':
                p.pltype = Place.RESTAURANT
                p.cuisine = d['cuisine']
                p.yelp = d['yelp']
                p.outdoor = d['outdoor']
            else:
                p.pltype = Place.HOTEL
                p.yelp = d['tripadvisor']
                p.has_bar = d['has_bar']

            p.save()
            m = 'User: {} added place: {} with id: {}'.format(p.user, p.name, p.id)
            logprint(m)
            ChangeLog.place_add(p, request.user.username)

            if not p.yelp and p.pltype == Place.RESTAURANT:
                try:
                    yelp_matches = get_yelp_matches(p.name, p.city)
                    if yelp_matches:
                        return select_yelp_match(request, p, yelp_matches)
                except:
                    pass
            return place_detail(request, p.id)
    else:
        # form = PlaceForm().as_table()
        if pltype == 'rest':
            form = RestaurantForm().as_table()
        else:
            form = HotelForm().as_table()

    if pltype == 'rest':
        pltypeS = 'Restaurant'
    else:
        pltypeS = 'Hotel'
    return render(request, 'places/place_add.html', {'form': form, 'pltype': pltype,
                                                     'pltypeS': pltypeS})