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')
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()
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))
def register(self): if self.m_valid: offer = Offer.create(self.m_offer) if offer != None: FileUpload.mark_used(self.m_file_id, self.m_user) return self.m_offer else: return None
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)
def offer(request): key = request.POST.get('key', 'offer') offers = Offer.fetch_by_match(key) offersdata = list(offers) data = {'status': 200, 'data': offersdata} print(data) return JsonResponse(data)
def search(request): pprint(request.POST) key = request.POST.get('key', 'offer') offers = Offer.get_match(key) offersdata = list(offers) data = {'status':200, 'data': offersdata} print(data) return JsonResponse(data)
def validate(self): super().validate() error = None start = self.model_value('start_at') end = self.model_value('expire_at') if start is None or start == '': error = ('start_at', '*Date value is missing') elif end is None or end == '': error = ('expire_at', '*Date value is missing') else: tz = timezone.get_current_timezone() start = tz.localize(datetime.strptime(start, "%Y/%m/%d")) if start < timezone.now(): error = ('start_at', '*Start date cannot be before today') end = tz.localize(datetime.strptime(end, "%Y/%m/%d")) if end < timezone.now(): error = ('expire_at', '*Expire date cannot be before today') if start > end: error = ('start_at', '*Start date cannot be before expire date') if error is None: self.add_model_value('start_at', start) self.add_model_value('expire_at', start) else: self.set_error(*error) files = self.m_values.get('files', '') if files != '': images = files.split(',') # FIXME :: fetch support for multiple images upload = FileUpload.fetch_file(images[0], self.request().user) if upload is not None: self.add_model_value('image', upload.file) else: self.set_error('fk_business', 'Image not uploaded') self.add_model_value('fk_user', self.request().user) business_id = self.model_value('fk_business') business = Business.fetch_by_id(business_id) if business is not None: self.add_model_value('fk_business', business) else: self.set_error('fk_business', 'Business does not exist') # compute the slug slug = self.model_value('name')+'-by-'+self.request().user.name slug = App_Slugify(slug) if Offer.fetch_by_slug(slug) is None: self.add_model_value('slug', slug) else: self.set_error('name', '*Offer with same name is already posted by you') return self.valid()
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()
def parseRequest(self, request): post = request.POST # files = request.FILES try: self.m_valid = False self.m_values = {} self.m_errors = {} self.m_file_id = None self.m_user = request.user self.m_offer = Offer() if request.is_ajax(): self.m_file_id = post.get('files') else: self.m_offer.product_image = request.FILES['product_image'] self.m_offer.product_name = post.get('product_name', '').strip(' \t\n\r') self.m_offer.discount = post.get('discount', '').strip(' \t\n\r') self.m_offer.start_date = post.get('start_date', '').strip(' \t\n\r') self.m_offer.expire_date = post.get('expire_date', '').strip(' \t\n\r') self.m_area = post.get('area', '').strip(' \t\n\r') # save values for session self.m_values['product_name'] = self.m_offer.product_name self.m_values['discount'] = self.m_offer.discount self.m_values['start_date'] = self.m_offer.start_date self.m_values['expire_date'] = self.m_offer.expire_date self.m_values['area'] = self.m_area return True except: self.m_errors['request'] = 'Failed to parse request' print('Failed to parse request') traceback.print_exc() return False
def home_backup_view(request): offers = Offer.get_all() data = {'title': 'Home Backup', 'offers_list': offers} return App_Render(request, 'home/home_backup_1.html', data)
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)
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)
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)
def offer_detail_view(request, slug): print('slug : '+slug) offer = Offer.fetch_by_slug(slug) data = {'title': 'View Offers', 'offer': offer} return App_Render(request, 'offer/offer_item_detail_1.html', data)
def offer_home_view(request): offers = Offer.fetch_all() data = {'title': 'Offers', 'offers_list': offers} return App_Render(request, 'offer/offer_home_1.html', data)
def home_page(request): offers = Offer.get_all() pprint(offers) data = {'title': 'home', 'offers_list': offers} file = device.get_template(request, 'home.html') return render(request, file, data)
def merchant_start_offer(request,template = "offer/merchant_offer_start.html"): user = request.user try: su = user.shoppleyuser if su.is_customer(): return HttpResponseRedirect(reverse("offer.views.offer_home")) except ShoppleyUser.DoesNotExist: return HttpResponseRedirect(reverse("home")) if request.method == 'POST': form = StartOfferForm(request.POST, request.FILES) if form.is_valid(): user = request.user merchant = user.shoppleyuser.merchant #offer_type = form.cleaned_data["offer_radio"] value = float(form.cleaned_data["value"]) description = form.cleaned_data["description"] title = form.cleaned_data["title"] if form.cleaned_data["now"]: d = datetime.now() d = d + timedelta(minutes=5) d = d.replace(second=0, microsecond=0) time_stamp = d else: d = form.cleaned_data["date"] t = form.cleaned_data["time"] time_stamp = datetime.combine(d,t) max_offers = form.cleaned_data["max_offers"] duration = form.cleaned_data["duration"] discount_obj = form.cleaned_data["discount"] discount_obj = discount_obj.split(':::') discount = float(discount_obj[0]) discount_type = discount_obj[1] dollar_off = 0 percentage = 0 discount_str = "None" if discount_type == '%': dollar_off = discount * value percentage = int(discount) elif discount_type == '$': dollar_off = discount if value ==0: percentage = 0 else: percentage = int(100.0*discount / value) if discount_type != 'custom': discount_str = ''.join(discount_obj) expiration = time_stamp + timedelta(minutes=duration) Offer(merchant = merchant, title = title, description = description, time_stamp = time_stamp, starting_time = time_stamp, duration = duration , max_offers = max_offers, expired_time =expiration , offer_value= value, dollar_off = dollar_off, percentage=percentage).save() #return HttpResponseRedirect(reverse("offer.views.offer_home")) t = TxtTemplates() templates = TxtTemplates.templates txt_preview =t.render(templates["CUSTOMER"]["INFO"], { "offercode": "xxxx", "description":title, "merchant": merchant, "expiration": expiration, }) return render_to_response("offer/offer_confirmation.html", {"offer": title, "business_name": merchant.business_name, "expiration": expiration, "address": merchant.print_address(), "value": value, "discount": discount_str, "starting_time": time_stamp, "max_offers": max_offers, "description" :description, "txt_preview": txt_preview, },context_instance=RequestContext(request)) else: ten_min_later = datetime.now() +timedelta( minutes=5) ten_min_later = ten_min_later.time().replace(second=0,microsecond=0) form = StartOfferForm(initial={"value": '0',"time": ten_min_later, "date": datetime.today()}) return render_to_response(template,{"form": form,}, context_instance=RequestContext(request))