示例#1
0
def add_product(request):
    if request.method == 'POST':
        str_brand = request.POST.get('strBrand')
        str_model = request.POST.get('strModel')
        str_ram = request.POST.get('strRam')
        str_memory = request.POST.get('strMemory')
        str_camera = request.POST.get('strCamera')
        str_battery = request.POST.get('strBattery')
        str_processor = request.POST.get('strProcessor')
        int_price = int(request.POST.get('strPrice'))
        img_image = request.FILES.get('imgImage')

        ins_product = Product(str_brand=str_brand,
                              str_model=str_model,
                              str_ram=str_ram,
                              str_memory=str_memory,
                              str_camera=str_camera,
                              str_battery=str_battery,
                              str_processor=str_processor,
                              int_price=int_price,
                              img_image=img_image)
        ins_product.save()

        int_offer_price = int_price
        int_discount = (100 - (int_offer_price // int_price) * 100)
        ins_offer = Offer(fk_product=ins_product,
                          int_offer_price=int_price,
                          int_offer_percent=int_discount)
        ins_offer.save()
        return redirect('home')
    else:
        return render(request, 'add_product.html')
示例#2
0
	def iphone_review(self):

		us, created = Country.objects.get_or_create(name="United States", code="US")
		region, created = Region.objects.get_or_create(name="Hawaii", code="HI", country=us)
		city, created = City.objects.get_or_create(name="Huna", region=region)
		zipcode1, created = ZipCode.objects.get_or_create(code="96727", city=city)

		# create users
		u, created = User.objects.get_or_create(username="******")
		u.email="*****@*****.**"
		u.set_password("hello")
		u.save()
		
		num = parse_phone_number("6176829602")
		if not Customer.objects.filter(user=u).exists():
			c, created = Customer.objects.get_or_create(user=u, address_1="", address_2="", zipcode=zipcode1, balance=1000)
			p, pcreated = CustomerPhone.objects.get_or_create(customer = c, number = num)
			c.active = True
			c.verified = True
			c.save()
			c.set_location_from_address()
	
		u, created = User.objects.get_or_create(username="******")
		u.email="*****@*****.**"
		u.set_password("hello")
		u.save()
		
		#617-453-8665 Meng's googlevoice number
		num = parse_phone_number("6174538665")
		if not Merchant.objects.filter(user=u).exists():
			m, created = Merchant.objects.get_or_create(user=u, address_1="", address_2="", zipcode=zipcode1, phone=num, balance=10000, business_name="Dunkin Donuts", admin="Jake Sullivan", url="http://www.shoppley.com")
			p, pcreated =MerchantPhone.objects.get_or_create(merchant = m, number = num)
			m.active = True
			m.verified = True
			m.save()
			m.set_location_from_address()

		shop_user = Customer.objects.get(user__email="*****@*****.**")
		shop_merch = Merchant.objects.get(user__email="*****@*****.**")
		shop_user.merchant_likes.add(shop_merch)

		offers = ["$5 off shoes brands, Nike, Reebok",
				"10% off Abercrombie flip flops",
								"Save $15 on your purchase of dress shoes",
								"Buy dress shoes today & get free socks"]

		m = Merchant.objects.get(user__email="*****@*****.**")	
		for o in offers:
			# start offers 30 minutes ago
			input_time = datetime.now()-timedelta(minutes=30)
			offer = Offer(merchant=m, title=o[:40], description=o, time_stamp=input_time, duration=40320, starting_time=input_time) 
			offer.save()

		self.distributor.handle_noargs()
示例#3
0
    def test_4(self):
        """
	Создать офферы на основе 
	    1 чеков - человек
		найти по строке из чека, стоимости, магазину - подходящие продукты
		выбрать продукты для клоторых обновится оффер, так как это разовое событие то оно не может меняться а только меняться с временем
		    карточек продуктов может быть найдно много(так как пользователи могут создавать разные карточки)
			Обойти это можно создав супер карточку которую пользователи немогут менять но ккоторой могут привязывать свою
			    и эти супер карточки будут в отдельном дереве
			обновлять оыыер у 3 из 1000 карточек которые выбрал польователь.
	    2 ресурсов - человек
		найти на основе ресурса - подходящие продукты
		    что бы сделать оффер нужна цена, а у ресурса ее нет, так что не походит
		    но возможно стоит ввести отдельную сущность приоретения где фиксируются ресурсы и стоимости их приобретения.
	    3 ресурса основанного на чеке
		найти на основе ресурса и связанного с ним чека - продукты
	    4 импорта с сайтов - робот
		кадый робот знает как карточка продукта связана с элементом витрины к которой он подключен, для получения оффера
		    елемент витрины для сайта это может быть страница товара
			а иакже есть другме роботы которые обновляют информацию по карточек если на витрине она меняется - полу ручной режим
	"""
        print 'test 4'

        #1
        #ChequeElement.objects.filter(
        list_buy_milk = self.__list_buy_milk()
        elements = []
        for i in list_buy_milk:
            for j in i['items']:
                elements.append({
                    'title': j['name'],
                    'price': j['price'],
                    'datetime_buy': i['dateTime'],
                    'showcase': i['retailPlaceAddress']
                })

        #TODO тут идет ручной выбор карточек к которым надо создать оффер
        for e in elements:
            for product_card in ProductCard.find_by_text(e['title']):
                offer = Offer(product_card=product_card,
                              price=e['price'],
                              datetime=e['datetime_buy'],
                              showcase=e['showcase'])
                offer.save()

        #for o in Offer.objects.all():
        #    print o

        product_cards = ProductCard.objects.all()
        self.assertEqual(4, len(product_cards))

        offers = Offer.objects.filter(product_card__in=product_cards)
        #TODO результат наверно не верный так как продуктов похожих может быть больше
        self.assertEqual(24, len(offers))
示例#4
0
def new_offer(request):
    args = custom_proc(request)

    if request.user.is_authenticated() and request.user.is_staff:
        offer = Offer()
        offer.save()

        args['offer'] = offer
        str_offer = unicode(offer.pk)
        url = u'/lk/offer_detail/' + str_offer + u'/'
        return redirect(url, "offer/offer_detail.html", args)
    else:
        # Отображение страницы с ошибкой
        args['login_errors'] = 'Пользователь не найден!'
        args['username'] = auth.get_user(request).username

        return redirect('%s?next=%s' % ('/lk/login/', request.path), args)
示例#5
0
    def save_jobs(self, jobs: list) -> None:
        for job in jobs:
            if not 'company' in job.keys():
                company = None
            else:
                company = job['company']

            offer = Offer(owner=self.tracker,
                          foreign_identity=job['id'],
                          title=job['title'],
                          location=job['location'],
                          snippet=job['snippet'],
                          salary=job['salary'],
                          source=job['source'],
                          job_type=job['type'],
                          link=job['link'],
                          company=company,
                          updated=parser.parse(job['updated']))
            offer.save()
示例#6
0
	def create_test_offers(self):
		"""
			Generate several offers by multiple merchants that targets two different users in two different
			zip codes
		"""
	
		offers = ["$5 off shoes brands, Nike, Reebok",
				"10% off Abercrombie flip flops",
								"Save $15 on your purchase of dress shoes",
								"Buy dress shoes today & get free socks"]

		m = Merchant.objects.get(user__email="*****@*****.**")	
		for o in offers:
			# start offers 30 minutes ago
			input_time = datetime.now()-timedelta(minutes=30)
			offer = Offer(merchant=m, title=o[:40], description=o, time_stamp=input_time, duration=40320, starting_time=input_time) 
			offer.save()
			#print offer.distribute()
			

		if not settings.SMS_DEBUG:
			self.assertGreaterEqual(offer.offercode_set.all().count(), 0)

		offers = ["$1 off Chicken Sandwiches",
				"Free drink when you order $10 or more",
								"Half priced cookies"]

		m = Merchant.objects.get(user__email="*****@*****.**")	
		for o in offers:
			# start offers 30 minutes ago
			input_time = datetime.now()-timedelta(minutes=30)
			offer = Offer(merchant=m, title=o[:40], description=o, time_stamp=input_time, duration=40320, starting_time=input_time) 
			offer.save()
			#offer.distribute()

		if not settings.SMS_DEBUG:
			self.assertGreaterEqual(offer.offercode_set.all().count(), 0)

		offers = ["$1 off Oil Change",
						"20% off car wash",
						"$30 snow tire exchange"]

		m = Merchant.objects.get(user__email="*****@*****.**")	
		for o in offers:
			# start offers 30 minutes ago
			input_time = datetime.now()-timedelta(minutes=30)
			offer = Offer(merchant=m, title=o[:40], description=o, time_stamp=input_time, duration=40320, starting_time=input_time) 
			offer.save()
			#offer.distribute()

		self.distributor.handle_noargs()
    
		self.redeem_offer()

		if not settings.SMS_DEBUG:
			self.assertGreaterEqual(offer.offercode_set.all().count(), 0)
示例#7
0
	def create_spam_offers(self):
		"""
			Generate several offers by multiple merchants that targets two different users in two different
			zip codes
		"""
	
		offers = ["$5 off shit ass brands, Nike, Reebok",
				"10% off American Eagle flip flops",
								"Save $15 on your mother f** of dress shoes",
								"Buy dress dope pal & get free socks"]

		m = Merchant.objects.get(user__email="*****@*****.**")	
		for o in offers:
			# start offers 30 minutes ago
			input_time = datetime.now()-timedelta(minutes=30)
			offer = Offer(merchant=m, title=o[:40], description=o, time_stamp=input_time, duration=40320, starting_time=input_time) 
			offer.save()
			#print offer.distribute()
			

		if not settings.SMS_DEBUG:
			self.assertGreaterEqual(offer.offercode_set.all().count(), 0)

		offers = ["$1 off Chicken Fart",
				"Free orange juice when you order $10 or more",
								"Half priced cum cookies"]

		m = Merchant.objects.get(user__email="*****@*****.**")	
		for o in offers:
			# start offers 30 minutes ago
			input_time = datetime.now()-timedelta(minutes=30)
			offer = Offer(merchant=m, title=o[:40], description=o, time_stamp=input_time, duration=40320, starting_time=input_time) 
			offer.save()
			#offer.distribute()

		if not settings.SMS_DEBUG:
			self.assertGreaterEqual(offer.offercode_set.all().count(), 0)

		offers = ["$1 off Wet Oil Change",
						"20% off car ass",
						"$30 Summer tire exchange"]

		m = Merchant.objects.get(user__email="*****@*****.**")	
		for o in offers:
			# start offers 30 minutes ago
			input_time = datetime.now()-timedelta(minutes=30)
			offer = Offer(merchant=m, title=o[:40], description=o, time_stamp=input_time, duration=40320, starting_time=input_time) 
			offer.save()
			#offer.distribute()

		self.distributor.handle_noargs()

		if not settings.SMS_DEBUG:
			self.assertGreaterEqual(offer.offercode_set.all().count(), 0)
示例#8
0
def offer_start(request):
	"""
		Offer parameters are defined and offer is started

		'title':'$10 off on entree',
		'description': 'Come taste some great greek food next 30 minutes',
		'now': False,
		'date': '2011-05-18',
		'time': '06:00:00 PM',
		'duration': 30,
		'units': 1,
		'amount': 10,
		'lat': 42.32342,
		'lon': -23.2342
		
		(optional) 'start_unixtime' instead of date & time

	"""

	data = {}

	# check if the necessary parameters are provided
	title = request.POST.get('title', None)
	description = request.POST.get('description', None)
	duration = int(request.POST.get('duration', 90))
	amount = int(request.POST.get('amount', 0))
	unit = int(request.POST.get('units', 0))
	lat = float(request.POST.get('lat', 0))
	lon = float(request.POST.get('lon', 0))
	
	if (title is None or title == "") and (description is None or description == ""):
	    data["result"] = -1
	    data["result_msg"] = "Please provide title and description."
	    return JSONHttpResponse(data)

	if title is None:
		title = description[:128]
	now = request.POST.get('now', False)
	start_unixtime = request.POST.get('start_unixtime', None)
	if now:
		start_time = datetime.now()
	elif start_unixtime is not None:
		start_time = datetime.fromtimestamp(float(start_unixtime))
	else:
		date = request.POST.get('date', None)
		time = request.POST.get('time', None)
		if (time is None) or (date is None):
			data["result"] = -1
			data["result_msg"] = "Please provide start date & time."
			return JSONHttpResponse(data)

		start_time = datetime.strptime("%s %s"%(date, time), "%Y-%m-%d %I:%M:%S %p")

	u = request.user
	if u.shoppleyuser.is_merchant():
		merchant = u.shoppleyuser.merchant

		if unit == 0:
			# percent 
			offer = Offer(merchant=merchant, title=title,
					description=description, percentage=amount,
					duration=duration,
					time_stamp=datetime.now(),
					starting_time=start_time)
		else:
			# dollar
			offer = Offer(merchant=merchant, title=title,
					description=description, dollar_off=amount,
					duration=duration,
					time_stamp=datetime.now(),
					starting_time=start_time)
		offer.expired_time = offer.starting_time + timedelta(minutes=offer.duration)
		offer.save()

        # save location where the offer was generated to track merchant location
		if (lat is not 0) and (lon is not 0):
			offer.set_location_from_latlon(lat,lon)

		num_reached = 0
		receipt_msg = _("Offer has been submitted.  We are actively looking for customers.  Check back in a few minutes for status update.")
		data["offer"] = offer.offer_detail()
		data["result"] = num_reached 
		data["result_msg"] = receipt_msg 
	else:
		data["result"] = -1
		data["result_msg"] = "Not a valid merchant user."

	return JSONHttpResponse(data)