Beispiel #1
0
    def get(self):
        """Do a document search for the given product id,
    and display the retrieved document fields."""

        params = self.parseParams()

        pid = params['pid']
        if not pid:
            # we should not reach this
            msg = 'Error: do not have product id.'
            url = '/'
            linktext = 'Go to product search page.'
            self.render_template(
                'notification.html', {
                    'title': 'Error',
                    'msg': msg,
                    'goto_url': url,
                    'linktext': linktext
                })
            return
        doc = docs.Product.getDocFromPid(pid)
        if not doc:
            error_message = ('Document not found for pid %s.' % pid)
            return self.abort(404, error_message)
            logging.error(error_message)
        pdoc = docs.Product(doc)
        pname = pdoc.getName()
        app_url = wsgiref.util.application_uri(self.request.environ)
        rlink = '/reviews?' + urllib.urlencode({'pid': pid, 'pname': pname})
        template_values = {
            'app_url': app_url,
            'pid': pid,
            'pname': pname,
            'review_link': rlink,
            'comment': params['comment'],
            'rating': params['rating'],
            'category': pdoc.getCategory(),
            'prod_doc': doc,
            # for this demo, 'admin' status simply equates to being logged in
            'user_is_admin': users.get_current_user()
        }
        self.render_template('product.html', template_values)
Beispiel #2
0
    def doProductSearch(self, params):
        """Perform a product search and display the results."""

        # the defined product categories
        cat_info = models.Category.getCategoryInfo()
        # the product fields that we can sort on from the UI, and their mappings to
        # search.SortExpression parameters
        sort_info = docs.Product.getSortMenu()
        sort_dict = docs.Product.getSortDict()
        query = params.get('query', '')
        user_query = query
        doc_limit = self._getDocLimit()

        categoryq = params.get('category')
        if categoryq:
            # add specification of the category to the query
            # Because the category field is atomic, put the category string
            # in quotes for the search.
            query += ' %s:"%s"' % (docs.Product.CATEGORY, categoryq)

        sortq = params.get('sort')
        try:
            offsetval = int(params.get('offset', 0))
        except ValueError:
            offsetval = 0

        # Check to see if the query parameters include a ratings filter, and
        # add that to the final query string if so.  At the same time, generate
        # 'ratings bucket' counts and links-- based on the query prior to addition
        # of the ratings filter-- for sidebar display.
        query, rlinks = self._generateRatingsInfo(params, query, user_query,
                                                  sortq, categoryq)
        logging.debug('query: %s', query.strip())

        try:
            # build the query and perform the search
            search_query = self._buildQuery(query, sortq, sort_dict, doc_limit,
                                            offsetval)
            search_results = docs.Product.getIndex().search(search_query)
            returned_count = len(search_results.results)

        except search.Error:
            logging.exception("Search error:")  # log the exception stack trace
            msg = 'There was a search error (see logs).'
            url = '/'
            linktext = 'Go to product search page.'
            self.render_template(
                'notification.html', {
                    'title': 'Error',
                    'msg': msg,
                    'goto_url': url,
                    'linktext': linktext
                })
            return

        # cat_name = models.Category.getCategoryName(categoryq)
        psearch_response = []
        # For each document returned from the search
        for doc in search_results:
            # logging.info("doc: %s ", doc)
            pdoc = docs.Product(doc)
            # use the description field as the default description snippet, since
            # snippeting is not supported on the dev app server.
            description_snippet = pdoc.getDescription()
            price = pdoc.getPrice()
            # on the dev app server, the doc.expressions property won't be populated.
            for expr in doc.expressions:
                if expr.name == docs.Product.DESCRIPTION:
                    description_snippet = expr.value
                # uncomment to use 'adjusted price', which should be
                # defined in returned_expressions in _buildQuery() below, as the
                # displayed price.
                # elif expr.name == 'adjusted_price':
                # price = expr.value

            # get field information from the returned doc
            pid = pdoc.getPID()
            cat = catname = pdoc.getCategory()
            pname = pdoc.getName()
            avg_rating = pdoc.getAvgRating()
            # for this result, generate a result array of selected doc fields, to
            # pass to the template renderer
            psearch_response.append([
                doc,
                urllib.quote_plus(pid), cat, description_snippet, price, pname,
                catname, avg_rating
            ])
        if not query:
            print_query = 'All'
        else:
            print_query = query

        # Build the next/previous pagination links for the result set.
        (prev_link, next_link) = self._generatePaginationLinks(
            offsetval, returned_count, search_results.number_found, params)

        logging.debug('returned_count: %s', returned_count)
        # construct the template values
        template_values = {
            'base_pquery': user_query,
            'next_link': next_link,
            'prev_link': prev_link,
            'qtype': 'product',
            'query': query,
            'print_query': print_query,
            'pcategory': categoryq,
            'sort_order': sortq,
            'category_name': categoryq,
            'first_res': offsetval + 1,
            'last_res': offsetval + returned_count,
            'returned_count': returned_count,
            'number_found': search_results.number_found,
            'search_response': psearch_response,
            'cat_info': cat_info,
            'sort_info': sort_info,
            'ratings_links': rlinks
        }
        # render the result page.
        self.render_template('index.html', template_values)
Beispiel #3
0
    def get(self):
        """Do a document search for the given product id,
    and display the retrieved document fields."""

        params = self.parseParams()

        pid = params['pid']
        if not pid:
            # we should not reach this
            msg = 'Error: do not have product id.'
            url = '/'
            linktext = 'Go to product search page.'
            self.render_template(
                'notification.html',
                {'title': 'Error', 'msg': msg,
                 'goto_url': url, 'linktext': linktext})
            return
        doc = docs.Product.getDocFromPid(pid)
        logging.info(doc)
        if not doc:
            error_message = ('Document not found for pid %s.' % pid)
            return self.abort(404, error_message)
            logging.error(error_message)

        date_format = "%Y-%m-%d"
        pickupD = (datetime.strptime(self.request.get('pickupD'), date_format))
        returnD = (datetime.strptime(self.request.get('returnD'), date_format))
        logging.info("pickup: %s", pickupD)
        logging.info("return: %s", returnD)
        c = returnD - pickupD
        logging.info("c: %s", c)
        c = int(c.days)
        logging.info("days: %d", c)
        pdoc = docs.Product(doc)
        pname = pdoc.getName()
        price = pdoc.getPrice()
        ppacc = pdoc.getMerchant()
        amount_paid = float(price) * int(c)
        app_url = wsgiref.util.application_uri(self.request.environ)
        template_values = {
            'app_url': app_url,
            'pid': pid,
            'pname': pname,
            'price': price,
            'ppacc': ppacc,
            'pickupD': pickupD.date(),
            'returnD': returnD.date(),
            'amount_paid': amount_paid,
            'image_url': pdoc.getImageUrl(),
            'prod_doc': doc,
            # for this demo, 'admin' status simply equates to being logged in
            'user_is_admin': users.get_current_user()}
        logging.info("name: %s", pname)
        logging.info("name: %s", pickupD.date())
        logging.info("name: %s", returnD.date())
        logging.info("name: %s", amount_paid)
        user = users.get_current_user()
        userinfo = ndb.Key(models.UserInfo, pdoc.getUserId()).get()
        transaction = models.Transaction(
            t_id = uuid.uuid4().hex,  # auto-generate default UID
            rentee_id = user.user_id(),  # give id automatically to product
            renter_id = pdoc.getUserId(),
            amount_paid = amount_paid,
            pickupD = pickupD.date(),
            returnD = returnD.date(),
            meet_point = userinfo.meetPoint,
            doc_id = user.user_id(),
            product = pname,
            email = userinfo.email,
            #dateSent = '',
            #payment_status = ndb.StringProperty(),
            verified = False
        )
        transaction.put()
        logging.info('transaction saved')
        logging.info('template_values :')
        logging.info(template_values)
        self.render_template('order.html', template_values)
Beispiel #4
0
  def get(self):
    """Do a document search for the given product id,
    and display the retrieved document fields."""

    params = self.parseParams()

    pid = params['pid']
    if not pid:
      # we should not reach this
      msg = 'Error: do not have product id.'
      url = '/'
      linktext = 'Go to product search page.'
      self.render_template(
          'notification.html',
          {'title': 'Error', 'msg': msg,
           'goto_url': url, 'linktext': linktext})
      return
    doc = docs.Product.getDocFromPid(pid)
    logging.info(doc)
    if not doc:
      error_message = ('Document not found for pid %s.' % pid)
      return self.abort(404, error_message)
      logging.error(error_message)
    pdoc = docs.Product(doc)
    pname = pdoc.getName()
    price = pdoc.getPrice()
    ppacc = pdoc.getMerchant()
    app_url = wsgiref.util.application_uri(self.request.environ)
    rlink = '/reviews?' + urllib.urlencode({'pid': pid, 'pname': pname})
    olink = '/order?' + urllib.urlencode({'pid': pid, 'pname': pname})
    userinfo = ndb.Key(models.UserInfo, pdoc.getUserId()).get()
    meetPoint = "Montreal, Qc"
    if userinfo is not None:
        meetPoint = userinfo.meetPoint
        phoneNumber = userinfo.phoneNumber
        nickname = userinfo.nickname
    user = users.get_current_user()
    if user is not None:
        if user.user_id() == pdoc.getUserId():
            user_is_poster = True
        else:
            user_is_poster = None
    else:
        user_is_poster = None;
    template_values = {
        'app_url': app_url,
        'pid': pid,
        'pname': pname,
        'price': price,
        'ppacc': ppacc,
        'review_link': rlink,
        'order_link': olink,
        'comment': params['comment'],
        'rating': params['rating'],
        'category': pdoc.getCategory(),
        'image_url': pdoc.getImageUrl(),
        'user_id': pdoc.getUserId(),
        'prod_doc': doc,
        'user_is_admin': user_is_poster,
        'meetPoint': meetPoint,
        'phoneNumber': phoneNumber,
        'userName': nickname}
    logging.info('template_values :')
    logging.info(template_values)
    self.render_template('product.html', template_values)
Beispiel #5
0
  def doProductSearch(self, params):
    """Perform a product search and display the results."""

    # the defined product categories
    cat_info = models.Category.getCategoryInfo()
    # the product fields that we can sort on from the UI, and their mappings to
    # search.SortExpression parameters
    sort_info = docs.Product.getSortMenu()
    sort_dict = docs.Product.getSortDict()
    query = params.get('query', '')
    user_query = query
    doc_limit = self._getDocLimit()

    categoryq = params.get('category')
    if categoryq:
      # add specification of the category to the query
      # Because the category field is atomic, put the category string
      # in quotes for the search.
      query += ' %s:"%s"' % (docs.Product.CATEGORY, categoryq)

    sortq = params.get('sort')
    try:
      offsetval = int(params.get('offset', 0))
    except ValueError:
      offsetval = 0

    

    # cat_name = models.Category.getCategoryName(categoryq)
    psearch_response = []
    # For each document returned from the search
    for doc in search_results:
      # logging.info("doc: %s ", doc)
      pdoc = docs.Product(doc)
      # use the description field as the default description snippet, since
      # snippeting is not supported on the dev app server.
      description_snippet = pdoc.getDescription()
      price = pdoc.getPrice()
      # on the dev app server, the doc.expressions property won't be populated.
      for expr in doc.expressions:
        if expr.name == docs.Product.DESCRIPTION:
          description_snippet = expr.value
        # uncomment to use 'adjusted price', which should be
        # defined in returned_expressions in _buildQuery() below, as the
        # displayed price.
        # elif expr.name == 'adjusted_price':
          # price = expr.value

      # get field information from the returned doc
      pid = pdoc.getPID()
      cat = catname = pdoc.getCategory()
      pname = pdoc.getName()
      #avg_rating = pdoc.getAvgRating()
      # for this result, generate a result array of selected doc fields, to
      # pass to the template renderer
      psearch_response.append(
          [doc, urllib.quote_plus(pid), cat,
           description_snippet, price, pname, catname])
    if not query:
      print_query = 'All'
    else:
      print_query = query

    # Build the next/previous pagination links for the result set.
    (prev_link, next_link) = self._generatePaginationLinks(
        offsetval, returned_count,
        search_results.number_found, params)

    logging.debug('returned_count: %s', returned_count)
    # construct the template values
    template_values = {
        'base_pquery': user_query, 'next_link': next_link,
        'prev_link': prev_link, 'qtype': 'product',
        'query': query, 'print_query': print_query,
        'pcategory': categoryq, 'sort_order': sortq, 'category_name': categoryq,
        'first_res': offsetval + 1, 'last_res': offsetval + returned_count,
        'returned_count': returned_count,
        'number_found': search_results.number_found,
        'search_response': psearch_response,
        'cat_info': cat_info, 'sort_info': sort_info}
    # render the result page.
    self.render_template('index.html', template_values)