Beispiel #1
0
def generate_offers_xls():
    import urlparse, StringIO
    from modules.catalog.models import Offer
    from xlwt import Workbook

    wb = Workbook()
    ws = wb.add_sheet('Offers')
    url_root = request.url_root

    for line, offer in enumerate(Offer.objects()):
        ws.write(line, 0, offer.name)
        ws.write(
            line, 1,
            urlparse.urljoin(url_root,
                             url_for('site.dispatcher', path=offer.path)))

    output = StringIO.StringIO()
    wb.save(output)

    response = Response()
    response.status_code = 200
    response.data = output.getvalue()

    response.content_type = u'application/vnd.ms-excel'
    response.headers["Content-Disposition"] = "attachment; filename=offers.xls"

    return response
Beispiel #2
0
def order_upsale(order_id):
    if request_wants_json():
        order = Order.objects(id=order_id).first()

        if order and request.method == 'GET':
            offers = order.get_relevant_offers(3)

            if not offers.count():
                return None

            favorites = session.get('favorites', [])
            offers = [
                dict(id=str(offer.id),
                     name=offer.name,
                     url=url_for('site.dispatcher', path=offer.path),
                     favorited=str(offer.id) in favorites,
                     category=dict(name=offer.parent.name,
                                   url=url_for('site.dispatcher',
                                               path=offer.parent.path)),
                     price=offer.get_price(),
                     oldprice=offer.get_oldprice,
                     timer=offer.get_timer,
                     picture=offer.get_picture()) for offer in offers
            ]

            return jsonify(offers=offers)

        if order and request.method == 'POST':
            offer_id = request.form.get('offer_id', None)
            if not offer_id:
                return jsonify(error=True)

            offer = Offer.objects(id=offer_id).first()
            if not offer:
                return jsonify(error=True)

            quantity = request.form.get('quantity', 1)
            variant_id = request.form.get('variant_id', None)
            variant = offer.get_variant(variant_id)

            sale = send_upsale(order, offer, quantity, variant)

            order.add_offer(offer, quantity, variant)

            # item = {
            #     'picture': offer.get_picture(),
            #     'name': offer.name,
            #     'price': offer.get_price(),
            #     'quantity': quantity,
            #     'total': offer.get_price() * quantity,
            #     'url': url_for('site.dispatcher', path=offer.path),
            # }

            return jsonify(error=False)

    return abort(404)
Beispiel #3
0
def get_offer_articul():
    if request_wants_json():
        oid = request.form.get('offer_id', None)
        if not oid:
            return jsonify(error=True)

        offer = Offer.objects(id=oid).only('articul').first()
        if not offer:
            return jsonify(error=True)

        return jsonify(articul=offer.articul)

    return abort(404)
Beispiel #4
0
def related_cart():
    if request_wants_json():
        cart = Cart.get_or_create()
        ids_in_cart = cart.get_offer_ids()

        filters = {
            'available': True,
            'id__nin': ids_in_cart,
        }

        founded_ids = Offer.objects(**filters).distinct('id')

        try:
            max_items = 4
            random_ids = random.sample(founded_ids, max_items)
        except ValueError:
            random_ids = random.sample(founded_ids, len(founded_ids))

        offers = Offer.objects(id__in=random_ids)
        favorites = session.get('favorites', [])
        if offers.count():
            offers = [
                dict(id=str(offer.id),
                     name=offer.name,
                     url=url_for('site.dispatcher', path=offer.path),
                     favorited=str(offer.id) in favorites,
                     category=dict(name=offer.parent.name,
                                   url=url_for('site.dispatcher',
                                               path=offer.parent.path)),
                     price=offer.get_price(),
                     oldprice=offer.get_oldprice,
                     timer=offer.get_timer,
                     picture=offer.get_picture()) for offer in offers
            ]

        return jsonify(offers=offers)

    return abort(404)
Beispiel #5
0
def cart_api(offer_id=None):

    if offer_id:
        variants = []
        offer = Offer.objects(id=offer_id).first()
        if offer:
            variants = [
                dict(name=variant.name,
                     count=variant.store_count,
                     id=variant.aid) for variant in offer.variants
            ]

        return json.dumps(dict(variants=variants))
    else:
        cart = Cart.get_or_create()
        form = request.form

        offer_id = form.get('offer_id', None)
        if offer_id:
            remove = True if form.get('remove') == 'true' else False
            variant_id = form.get('variant_id')
            if remove:
                cart.remove_offer(offer_id, variant_id)
            else:
                cart.add_offer(offer_id, form.get('quantity', 1), variant_id)

            cart.reload()

        offers = []
        for offer in cart.offers:
            cart_offer = dict(id=offer.offer.id,
                              quantity=offer.quantity,
                              name=offer.offer.name,
                              url=url_for('site.dispatcher',
                                          path=offer.offer.path),
                              image=offer.offer.get_picture('small'),
                              price=offer.offer.get_price(),
                              oldprice=offer.offer.get_oldprice)
            if offer.variant:
                cart_offer['variant'] = dict(id=offer.variant,
                                             name=offer.offer.get_variant(
                                                 offer.variant).name)
            offers.append(cart_offer)

        data = dict(offers=offers, userinfo=session.get('userinfo', None))

        return json.dumps(data)
Beispiel #6
0
 def dispatch(self):
     o = Offer.objects.get_or_404(path=self.path)
     o.set_visit()
     if session.get('userinfo', None):
         region_id = session['userinfo']['region'].get('id', None) \
             if session['userinfo'].get('region', None) else None
     else:
         region_id = None
     return 'offer.html', {
         'region_id': region_id,
         'offer': o,
         'category': o.parent,
         'has_active': True,
         'breadcrumbs': o.get_breadcrumbs(),
         'reviews': o.get_reviews(),
         'related_offers': o.get_related(),
         'popular_offers': Offer.get_popular().filter(id__ne=o.id)[:12],
         'banners': Banner.get_banners('wide')
     }
Beispiel #7
0
    def dispatch(self):
        c = Category.objects.get_or_404(path=self.path)
        tree = c.get_tree_from()

        page = request.args.get('page', 1)

        typ = request.args.get('sort', None)
        if not typ:
            typ = session.get('category_sort', None)
        else:
            session['category_sort'] = typ

        sort = get_ordering(typ)

        ordering_form = ProductsOrderForm(data={'sort': sort[0]})

        try:
            page = int(page)
        except ValueError:
            return 'redirect', {'location': request.path, 'code': 301}

        per_page = 18
        if not c.parent:
            per_page = 1000

        category_root_url = c.get_category_root_url()

        os = Offer.objects(parent__in=c.get_childs())\
                  .order_by('-available', sort[2])\
                  .paginate(per_page=per_page, page=page)

        return 'category.html', {
            'category': c,
            'category_root_url': category_root_url,
            'offers': os,
            'tree': tree,
            'has_active': True,
            'breadcrumbs': c.get_breadcrumbs(),
            'ordering_form': ordering_form
        }
Beispiel #8
0
def reviews():
    form = request.form
    offer_id = form.get('offer_id', None)
    offer = Offer.objects(id=offer_id).first()

    if offer:
        fullname = Markup(form.get('fullname')).striptags()
        email = Markup(form.get('email')).striptags()
        text = clear_tags_and_make_lines(form.get('review'))
        rating = Markup(form.get('rating')).striptags()

        try:
            rating = int(rating)
        except (TypeError, ValueError):
            rating = 0

        review = Review(offer=offer,
                        fullname=fullname,
                        email=email,
                        text=text,
                        rating=rating)

        if current_user.is_authenticated and current_user.has_role('admin'):
            review.is_moderated = True

        review.save()

        userinfo = session.get('userinfo', None)
        if userinfo:
            if not userinfo.get('fullname', None):
                userinfo['fullname'] = fullname
            if not userinfo.get('email', None):
                userinfo['email'] = email
        else:
            userinfo = dict(fullname=fullname, email=email)

        session['userinfo'] = userinfo

    return json.dumps(dict(hello='world'))
Beispiel #9
0
def favorites():
    favorites = session.get('favorites', [])

    for fav in favorites:
        try:
            int(fav)
        except ValueError:
            favorites.remove(fav)
            session['favorites'] = favorites

    if request.method == 'POST':
        offer_id = request.form.get('offer_id', None)

        if request_wants_json():
            if offer_id and offer_id in favorites:
                favorites.remove(offer_id)

            elif offer_id and offer_id not in favorites:
                favorites.append(offer_id)

            session['favorites'] = favorites

            return jsonify(favorites=favorites)

        return

    offers = Offer.objects(id__in=favorites)
    ids = offers.distinct('id')

    # Проверяем, совпадает ли количество найденых товаров
    # Если нет, то популяризируем favorites
    if len(ids) != len(favorites):
        favorites = [str(id) for id in ids]
        session['favorites'] = favorites

    return render_template('favorites.html', offers=offers)
Beispiel #10
0
def get_delivery_for_each_region(config, regions=None):
    from modules.apishop import api_connect
    aids = Offer.objects(available=True).distinct('aid')

    if not len(aids):
        return

    d_methods = {
        str(d.id): {
            'id': d.id,
            'method': d.name
        }
        for d in DeliveryMethod.objects()
    }
    conn = api_connect(config)

    def request(region):
        aid = random.choice(aids)
        methods = []
        cart_string = '-'.join([str(aid), str(1)])
        result = conn.get_cart_delivery(cart_string, 0, region.id)
        methods = region.get_delivery_prices(result, aid)

        return methods

    if regions:
        regions = [regions]
    else:
        regions = Region.objects

    for region in regions:
        result = request(region)

        if len(result):
            region.update(set__deliveries=result)
    return
Beispiel #11
0
    def get_context(self, category_id, offer_id):
        context = {}
        categories = Category.get_tree()

        page = int(request.args.get('page', 1))

        if not offer_id:
            if not category_id:
                category = Category()
                offers = Offer.objects()
            else:
                category = Category.objects.get_or_404(id=category_id)
                offers = Offer.objects(parent__in=category.get_childs())

            if request.method == 'POST':
                form = self.category_form(request.form, initial=category._data)
            else:
                form = self.category_form(request.form, obj=category)

            if category.id and request.path == url_for(
                    'admin.catalog.category.edit', category_id=category.id):
                context['edit'] = True
                self.template = 'admin/catalog_category_edit.html'

            context['category'] = category
            context['category_form'] = form
            context['add_category_form'] = self.add_category_form(
                request.form, initial=category._data)
            context['categories'] = categories
            context['offers'] = offers.paginate(page=page, per_page=18)
        else:
            offer = Offer.objects.get(id=offer_id)
            context['offer'] = offer

            if request.path == url_for('admin.catalog.offer.upload',
                                       offer_id=offer.id):
                context['upload'] = True

            if request.path == url_for('admin.catalog.offer.pic_remove',
                                       offer_id=offer.id):
                context['pic_remove'] = True

            if request.path == url_for('admin.catalog.offer.edit',
                                       offer_id=offer.id):
                context['edit'] = True
                self.template = 'admin/catalog_offer_edit.html'

                if request.method == 'POST':
                    form = self.offer_form(request.form, initial=offer._data)
                else:
                    form = self.offer_form(request.form, obj=offer)

                context['offer_form'] = form

            if request.path == url_for('admin.catalog.offer.edit.special',
                                       offer_id=offer.id):
                context['edit_special'] = True
                special = offer.get_special
                self.template = 'admin/catalog_offer_edit_special.html'

                if request.method == 'POST':
                    if special:
                        form = self.special_form(request.form,
                                                 initial=special._data)
                    else:
                        form = self.special_form(request.form)
                else:
                    if special:
                        form = self.special_form(request.form, obj=special)
                    else:
                        form = self.special_form(request.form)

                context['special'] = special
                context['special_form'] = form

        return context
Beispiel #12
0
def index():
    return render_template('index.html',
                           popular_offers=Offer.get_popular()[:8],
                           special_offers=Offer.get_special_offers()[:12],
                           banners=Banner.get_banners())
Beispiel #13
0
def quick_cart(offer_id=None):

    if request.method == 'POST' and request_wants_json():
        offer_id = request.form.get('offer_id', None)
        offer = Offer.objects(id=offer_id).first()

        if offer:
            quantity = request.form.get('count', 1)
            variant_id = request.form.get('variant', None)

            if variant_id:
                variant = offer.get_variant(variant_id)
                variant = str(variant.aid)
            else:
                variant = None

            cart_offer = dict(articul=offer.articul,
                              aid=offer.aid,
                              quantity=quantity,
                              variant=variant,
                              price=offer.get_price())

            form = dict(phone=request.form.get('phone'))

            order_id = send_order([cart_offer], form)

            return jsonify(
                order=dict(order_id=order_id,
                           url=url_for('site.order', order_id=order_id)))

        return jsonify(errors=True)

    if offer_id and request_wants_json():
        offer = Offer.objects(id=offer_id).first()
        if offer:
            offer = dict(name=offer.name,
                         url=url_for('site.dispatcher', path=offer.path),
                         category=dict(
                             name=offer.parent.name,
                             url=url_for('site.dispatcher',
                                         path=offer.parent.path),
                         ),
                         price=offer.get_price(),
                         oldprice=offer.get_oldprice,
                         timer=offer.get_timer,
                         variants=[
                             dict(name=variant.name,
                                  count=variant.store_count,
                                  id=variant.aid) for variant in offer.variants
                         ],
                         picture=offer.get_picture('medium'))

            user = session.get('userinfo', None)
            if user:
                name = user.get('fullname', '')
                phone = user.get('phone', '')

                offer['user'] = dict(name=name, phone=phone)

            return jsonify(offer=offer)

        return jsonify(offer={})

    return abort(404)
Beispiel #14
0
def upto1000():
    offers = Offer.objects(price__ru__lt=1000.00,
                           available=True).order_by('-stats.populatiry')
    return render_template('upto1000.html', offers=offers)
Beispiel #15
0
def specials():
    offers = Offer.objects(special__ne=None).order_by('price.ru')
    return render_template('specials.html', offers=offers)
Beispiel #16
0
 def dispatch(self):
     vendor = Vendor.objects.get_or_404(path=self.path)
     os = Offer.objects(vendor=vendor)
     return 'base.html', {'vendor': vendor, 'offers': os}