Пример #1
0
def test_users():
    db.create_all()
    lucas = User(name='lucas',
                 email='*****@*****.**',
                 active=False,
                 password='******')
    lucas2 = User(name='admin',
                  email='*****@*****.**',
                  active=False,
                  password='******')
    of1 = Offer(price=10)
    of2 = Offer(price=20)
    of3 = Offer(price=30)
    of4 = Offer(price=40)

    lucas.offers = [of1, of2]
    db.session.add(lucas)
    db.session.add(of1)
    db.session.add(of2)
    db.session.commit()

    lucas2.offers = [of2, of3]
    db.session.add(lucas2)
    db.session.add(of3)
    db.session.commit()
    print('created')
    users = User.query.all()
    offers = Offer.query.all()
    for u in users:
        db.session.delete(u)
    for o in offers:
        db.session.delete(o)
    db.session.commit()
    print('deleted')
Пример #2
0
    def test_offer(self):
        u = User(email='*****@*****.**')
        c1 = Category(name='matematyka')
        c2 = Category(name='fizyka')
        db.session.add(u)
        db.session.add(c1)
        db.session.add(c2)
        db.session.commit()
        o1 = Offer(name='Analiza matematycza 1.0',
                   price=24.0,
                   count=20,
                   body='to jest przykladowy opis ksiazki',
                   timestamp=datetime.utcnow(),
                   author=u,
                   category=c1)
        o2 = Offer(name='Analiza matematycza 1.0',
                   price=20.0,
                   count=1,
                   body='to jest inny przykladowy opis ksiazki',
                   timestamp=datetime.utcnow(),
                   author=u,
                   category=c1)
        db.session.add(o1)
        db.session.add(o2)
        db.session.commit()

        assert len(Category.query.all()) == 2
Пример #3
0
 def setup_class(cls):
     cls.offer1 = Offer(1, 'Shop 1', 1000.5, 'https://url1')
     cls.offer2 = Offer(2, 'Shop 2', 500.0, 'https://url2')
     cls.offer3 = Offer(3, 'Shop 3', 700.0, 'https://url3')
     cls.product = Product(1, 2, 'Product', 'Description',
                           ['https://image1', 'https://image2'],
                           [cls.offer1, cls.offer2, cls.offer3])
Пример #4
0
 def _create_offers_with_new_sku(self, offer_list, sku):
     for offer in offer_list:
         r = requests.post(
             url=Config.DEVICE_PRICES,
             data={"processSegmentationCode": offer.segmentation,
                   "deviceStockCode": sku.stock_code,
                   "offerNSICode": offer.offer_code,
                   "tariffPlanCode": offer.tariff_plan_code,
                   "contractConditionCode": offer.contract_condition_code}
         )
         self.request_counter += 1
         if r.json()["devicesPrices"]:
             new_offer = Offer(
                 segmentation=offer.segmentation,
                 market=offer.market,
                 contract_condition_code=offer.contract_condition_code,
                 sku=sku,
                 tariff_plan_code=offer.tariff_plan_code,
                 offer_code=offer.offer_code
             )
             new_offer.priority = offer.priority
             new_offer.set_prices(offer.price)
             new_offer.abo_price = offer.abo_price
             db.session.add(new_offer)
     db.session.commit()
Пример #5
0
def populate_db():
    if not request.json:
        abort(400)
    jsonObj = json.loads(request.data)
    fake = Faker()
    fake.add_provider(MyProvider)
    if jsonObj['append'] == "False":
        try:
            db.session.query(Product).delete()
            db.session.query(Offer).delete()
            db.session.commit()
        except Exception as ex:
            template = "An exception of type {0} occurred. Arguments:\n{1!r}"
            message = {"message": template.format(type(ex).__name__, ex.args)}
    for i in range(jsonObj['ProdCount']):
        Product.seed(fake, i + 1)
    for j in range(jsonObj['OfferCount']):
        Offer.seed(fake, j + 1)
    orows = db.session.query(Offer).count()
    prows = db.session.query(Product).count()
    message = {
        "message":
        "Product table has {0} records and Offer table has {1} records".format(
            prows, orows)
    }
    return jsonify(message)
Пример #6
0
def create_request_offer(request):
    # todo there is no validation here

    if request.POST:
        if request.is_ajax():

            offer_id = request.POST.get('offer_id')

            # OFFER
            if offer_id:
                offer_project = Request.objects.get(pk=offer_id)
                offer_instance = Offer(project=offer_project, offer_by=request.user)
                offer_instance.save()

                # reputation change for offering
                offered_by_profile = UserProfile.objects.get(user=request.user)
                if offered_by_profile:
                    offered_by_profile.reputation += OFFERING_REPUTATION_POINT
                    offered_by_profile.save()

                notification = Notification(for_user=offer_project.created_by, extra=offer_instance, type=200,
                                            action_url="/projects/" + str(offer_project.slug),
                                            message="You have received an offer ", )
                notification.save()

            # REQUEST
            return project_create(request)

        else:
            return HttpResponseRedirect("/dashboard/")


    else:
        return HttpResponseRedirect("/dashboard/")
Пример #7
0
def offer(request, slug):
    project = get_object_or_404(Request, slug=slug)
    offered_by = request.user

    # todo validations
    # can't offer my own project
    if (offered_by == project.created_by):
        # messages.add_message(request, messages.INFO, 'Hmmm this is your project!')
        return HttpResponseRedirect("/projects/" + str(slug) + "/")

    # todo check if this user has already sent offer request ...
    sent_request = Offer.objects.filter(project=project, offer_by=offered_by)
    if sent_request:
        messages.add_message(request, messages.INFO, 'Your have already sent offer request for this project!')
        return HttpResponseRedirect("/projects/" + str(slug) + "/")




    # reputation change for offering
    offered_by_profile = UserProfile.objects.get(user=offered_by)
    if offered_by_profile:
        offered_by_profile.reputation += OFFERING_REPUTATION_POINT
        offered_by_profile.save()

    offer = Offer(project=project, offer_by=offered_by)
    offer.save()
    notification = Notification(for_user=project.created_by, extra=offer, type=200, action_url="/projects/" + str(slug),
                                message="You have received an offer ", )
    notification.save()
    # todo show offer processed message and redirect
    messages.add_message(request, messages.SUCCESS, 'Your Offer has been sent!')
    return HttpResponseRedirect("/projects/" + str(slug) + "/")
Пример #8
0
def offer(id):
    form = OfferForm()
    if id == 0:
        offer = Offer()
        offer.user = current_user
        offer.product_id = 1
        offer.created = datetime.utcnow()
    else:
        offer = Offer.query.get(id)
        if not offer:
            abort(404, _('Angebot nicht gefunden'))
        if offer.user.id != current_user.id and not current_user.has_role(
                'admin'):
            abort(403, _('Das darfst du leider nicht'))

    products = Product.query.filter(Product.active == True).all()
    form.product.choices = [(p.id, p.description) for p in products]
    if form.validate_on_submit():
        offer.active = form.active.data
        offer.price = form.price.data
        offer.stock = form.stock.data
        offer.product_id = form.product.data
        if not offer.id:
            db.session.add(offer)
        db.session.commit()
        flash(_('Gespeichert'))
        return redirect(url_for('main.offers'))
    if offer.product:
        form.product.data = offer.product.id
    form.active.data = offer.active
    form.price.data = offer.price
    form.stock.data = offer.stock
    form.supplier.data = offer.user.username
    return render_template('offer.html', form=form)
Пример #9
0
    def insert_offers(self, offer_map: Dict[int, List[Dict[str,
                                                           int]]]) -> None:
        for product_id, offers in offer_map.items():
            for offer in offers:
                offer_row = Offer.query.filter(
                    Offer.ms_id == offer['id']).first()
                if offer_row is None:
                    offer_row = Offer(product_id=product_id, ms_id=offer['id'])

                offer_row.price = offer['price']
                offer_row.items_in_stock = offer['items_in_stock']
                self.db.session.add(offer_row)
                self.db.session.commit()
Пример #10
0
    def test_init(self):
        offer = Offer(1, 'Shop Name', 30.5, 'https://shopurl')

        assert offer.id == 1
        assert offer.shop_name == 'Shop Name'
        assert offer.price == 30.5
        assert offer.url == 'https://shopurl'
Пример #11
0
    def patch(self, id):
        """
        Patch Offer
        """
        data = request.json
        o = Offer.objects.get_or_404(id=id)

        if o.facilitator.id != g.client.id:
            abort(400, error='Not authorized')

        if len(data) == 0:
            abort(400, error='No data')

        if data.get('name'):
            os = Offer.objects(name=data['name']).first()

            if os is not None and os.id != o.id:
                abort(400, error='Name already exist')

            o.name = data['name']

        if data.get('tags'):
            o.tags = data['tags']

        if data.get('price'):
            o.price = data['price']

        if data.get('description'):
            o.description = data['description']

        o.save()

        return 'Offer successfully patched', 204
Пример #12
0
def move_commence(game_privacy, duration):
    auth = auth_auth('commence')
    if auth['success']:
        app.logger.info(auth)
        player_id = auth['user_id']
    else:
        app.logger.info('player guest')
        player_id = auth_guest()
    try:
        app.logger.info('trying')
        if game_privacy == 'public':
            app.logger.info('we are game privacy')
            offer = Offer.query.filter_by(public=True).filter_by(
                time_limit=duration).first()
            if offer:
                app.logger.info('we are offer')
                new_game = Game(player_one=offer.player_one,
                                player_two=player_id,
                                time_limit=duration,
                                offer_id=offer.id)
                Game.insert(new_game)
                game = new_game.id
                offer.delete()
                current_state = State(game_id=new_game.id,
                                      move_number=1,
                                      move='white',
                                      position=calculate_moves(),
                                      time_limit=duration,
                                      white_timer=duration,
                                      black_timer=duration)
                State.insert(current_state)
                db.session.close()
                return json.dumps({'status': 'redirect', 'id': game})
        app.logger.info('we are here')
        offer = Offer(player_one=player_id, time_limit=duration)
        Offer.insert(offer)
        offer_id = offer.id
        db.session.close()
        return json.dumps({'status': 'waiting', 'offerId': offer_id})
    except:
        app.logger.info(sys.exc_info())
        error = True
        db.session.rollback()
    finally:
        db.session.close()
    if error:
        return json.dumps({'status': 'error'})
Пример #13
0
 def test_new_found_sku_has_abo_price_and_device_price(self):
     product = Product(manufacturer="LG", model_name="G2 Mini",
                       product_type="PHONE")
     sku = SKU(base_product=product, stock_code="lg-g2-mini-lte-black")
     offer = Offer(
         segmentation="IND.NEW.POSTPAID.ACQ",
         sku=sku, market="IND", offer_code="NSZAS24A",
         tariff_plan_code="5F20A", contract_condition_code="24A"
     )
     offer.abo_price = 100.00
     offer.price = 90.00
     db.session.add_all([product, sku, offer])
     db.session.commit()
     self.crawler.save_new_found_skus()
     new_sku = SKU.query.filter_by(stock_code="lg-g2-mini-lte-white").first()
     new_offer = Offer.query.filter_by(sku=new_sku).first()
     self.assertEqual(new_offer.abo_price, 100.00)
     self.assertEqual(new_offer.price, 90.00)
Пример #14
0
 def test_offer_valid(self):
     u = User(email='*****@*****.**')
     c1 = Category(name = 'matematyka')
     c2 = Category(name = 'fizyka')
     db.session.add(u)
     db.session.add(c1)
     db.session.add(c2)
     db.session.commit()
     o1 = Offer(name = 'Analiza matematycza 1.0', price = 24.0, count = 20,
               body = 'to jest przykladowy opis ksiazki', timestamp = datetime.utcnow(),
               author = u, category = c1
         )
     o2 = Offer(name = 'Analiza matematycza 1.0', price = 20.0, count = 0,
               body = 'to jest inny przykladowy opis ksiazki', timestamp = datetime.utcnow(),
               author = u, category = c1
         )
    
     assert o1.is_valid() == True
     assert o2.is_valid() == False
Пример #15
0
    def save_or_update_device(self, device_info, offer_info):
        # =================== Product ======================= #
        product = Product.query.filter_by(
            manufacturer=device_info["brand"],
            model_name=device_info["modelName"]
        ).first()
        if not product:
            product = Product(
                manufacturer=device_info["brand"],
                model_name=device_info["modelName"],
                product_type=device_info["productType"]
            )

        # =================== SKU ======================= #
        sku = SKU.query.filter_by(stock_code=device_info["sku"]).first()
        if not sku:
            sku = SKU(base_product=product, stock_code=device_info["sku"])
        sku.availability = device_info["available"]
        # =================== Photo ======================= #
        for photo in device_info["imagesOnDetails"]:
            device_photo = Photo.query.filter_by(
                url=photo["normalImage"]).first()
            if device_photo is not None:
                device_photo.default = photo["defaultImage"]
            else:
                device_photo = Photo(sku=sku, url=photo["normalImage"],
                                     default=photo["defaultImage"])
            db.session.add(device_photo)

        # =================== Offer ======================= #
        offer = Offer.query.filter_by(
            segmentation=self.segment,
            offer_code=offer_info["offerNSICode"],
            sku=sku,
            tariff_plan_code=offer_info["tariffPlanCode"],
            contract_condition_code=offer_info["contractConditionCode"]
        ).first()
        if not offer:
            offer = Offer(
                segmentation=self.segment,
                market=self.segment.split(".")[0],
                sku=sku,
                offer_code=offer_info["offerNSICode"],
                tariff_plan_code=offer_info["tariffPlanCode"],
                contract_condition_code=offer_info["contractConditionCode"]
            )
        offer.set_prices(
            float(device_info["prices"]["grossPrice"].replace(",", "."))
        )
        offer.abo_price = float(offer_info["monthlyFeeGross"].replace(",", "."))
        offer.priority = device_info["devicePriority"]

        # =================== Saving ======================= #
        db.session.add(product)
        db.session.add(sku)
        offer.ping(self.scrapping_time)
        db.session.commit()
Пример #16
0
def new_offer():
    form = OfferForm()
    if form.validate_on_submit():
        offer = Offer(offer_name=form.offer_name.data, brand=form.brand.data,
                      description=form.description.data, exp_date=form.exp_date.data,
                      price=form.price.data, percentage_discount=form.percentage_discount.data,
                      seller=current_user)
        db.session.add(offer)
        db.session.commit()
        flash('Offer created!')
        return redirect(url_for('foodsellerPage'))
    return render_template('create_offer.html', title='New Offer', form=form, legend='New Offer')
Пример #17
0
    def test_offer_valid(self):
        u = User(email='*****@*****.**')
        c1 = Category(name='matematyka')
        c2 = Category(name='fizyka')
        db.session.add(u)
        db.session.add(c1)
        db.session.add(c2)
        db.session.commit()
        o1 = Offer(name='Analiza matematycza 1.0',
                   price=24.0,
                   count=20,
                   body='to jest przykladowy opis ksiazki',
                   timestamp=datetime.utcnow(),
                   author=u,
                   category=c1)
        o2 = Offer(name='Analiza matematycza 1.0',
                   price=20.0,
                   count=0,
                   body='to jest inny przykladowy opis ksiazki',
                   timestamp=datetime.utcnow(),
                   author=u,
                   category=c1)

        assert o1.is_valid() == True
        assert o2.is_valid() == False
Пример #18
0
    def post(self):
        """
        Add Offer
        """
        data = request.json

        if g.client.type != 'facilitator':
            abort(400, error='You must be facilitator')

        f = Facilitator.objects.get_or_404(id=g.client.id)

        if Offer.objects(name=data['name']).count() > 0:
            abort(400, error='Name already exist')

        o = Offer(facilitator=f,
                  name=data['name'],
                  tags=data.get('tags'),
                  price=data['price'],
                  description=data.get('description'))

        o.save()

        return o
Пример #19
0
    def test_category(self):
        u = User(email='*****@*****.**')
        c = Category(name='matematyka')
        db.session.add(u)
        db.session.add(c)
        db.session.commit()

        o = Offer(name='Analiza matematycza 1.0',
                  price=24.0,
                  count=20,
                  body='to jest przykladowy opis ksiazki',
                  timestamp=datetime.utcnow(),
                  author=u,
                  category=c)
        db.session.add(o)
        db.session.commit()
Пример #20
0
def create_offer():
    message = {"message": ""}
    if not request.json:
        abort(400)
    jsonObjs = json.loads(request.data)
    for jsonObj in jsonObjs:
        db.session.add(
            Offer(offer_code=jsonObj['offer_code'],
                  offer_desc=jsonObj['offer_desc'],
                  offer_start=datetime.strptime(jsonObj['offer_start'],
                                                '%Y-%m-%d'),
                  offer_end=datetime.strptime(jsonObj['offer_end'],
                                              '%Y-%m-%d')))
    try:
        db.session.commit()
        message = {"message": "Records added"}
    except Exception as ex:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = {"message": template.format(type(ex).__name__, ex.args)}
    return jsonify(message)
Пример #21
0
    def _fetch_product_details(
            self,
            product_id: int,
            offset: int = 0,
            limit: int = DEFAULT_LIMIT) -> (str, List[str], List[Offer]):
        """
        Fetch product offers from the cache/API
        From the response extract also product description and product images
        :param product_id: ID of the product to fetch
        :param offset: offset for paginating the requests
        :param limit: limit: maximum number of the offers to fetch
        :return: Product description, list of product images urls, List of :class:`Offer` objects
        """
        offers = []

        product_description = ''

        product_image_urls = []

        cached_response, response_data = self._get(
            PRODUCT_OFFERS_URI.format(product_id=product_id,
                                      offset=offset,
                                      limit=limit))
        for item in response_data:
            if item['description'] and len(
                    item['description']) > len(product_description):
                product_description = item['description']

            if item['img_url']:
                product_image_urls.append(item['img_url'])

            shop_name = shop_name_from_url(item['url'])

            offers.append(
                Offer(offer_id=item['offerId'],
                      shop_name=shop_name,
                      price=item['price'],
                      url=item['url']))

        return product_description, product_image_urls, offers
Пример #22
0
def add_offer(request_id):
    import pdb
    pdb.set_trace()
    requestobj = Request.query.filter_by(id=request_id).first()

    request_for_help = Offer()
    request_for_help.request = requestobj   

    if 'lmessage_at' in request.json:
        request_for_help.lmessage_at = request.json['lmessage_at']
    if 'offer' in request.json:
        request_for_help.offer = request.json['offer']
    if 'offer_status' in request.json:
        request_for_help.offer_status = request.json['offer_status']
    if 'helpuser_id' in request.json:
        request_for_help.id = request.json['helpuser_id']
    if 'request_id' in request.json:
        request_for_help.request_id = request.json['request_id']

    db.session.add(request_for_help)
    db.session.commit()

    return request_for_help.to_json()
Пример #23
0
def build_offer():
  try:
    owner_id = request.json.get('ownerId')
    offeree_id = request.json.get('offereeId')
    game_id = request.json.get('gameId')
    offer_buy = bool(request.json.get('offerBuy'))
    offer_trade = bool(request.json.get('offerTrade'))
    offer_borrow = bool(request.json.get('offerBorrow'))
    offer = Offer(
      owner_id=owner_id,
      offeree_id=offeree_id,
      game_id=game_id,
      new_offer=True,
      pending_offer=True,
      offer_buy=offer_buy,
      offer_trade=offer_trade,
      offer_borrow=offer_borrow
    )
    db.session.add(offer)
    db.session.commit()
    return {"Message": "Offer successfully added."}, 200
  except:
    return {"Message": sqlalchemy.exc.DataError}, 500
Пример #24
0
def update_or_create_offer(network, offer):
    """
    :param network: Network object model
    :param offer: dict of importing offer data
    :return:
    """
    from app.models import Offer, OfferEvent
    from app import db

    db_offer = Offer.query.filter_by(network_id=network.id, remote_id=offer['id']).first()

    if db_offer:
        """update"""
        db_offer.name = offer['name'][:128]
        db_offer.preview_url = offer['preview_url'][:512]
        db_offer.payout = float(offer['payout'])
        db_offer.status = Offer.STATUS_ACTIVE

        return db_offer, True
    else:
        """insert"""
        db_offer = Offer()
        db_offer.remote_id = offer['id']
        db_offer.name = offer['name'][:128]
        db_offer.preview_url = offer['preview_url'][:512]
        db_offer.payout = offer['payout']
        db_offer.status = Offer.STATUS_ACTIVE
        db_offer.network = network

        db.session.add(db_offer)

        """create event"""
        offer_event = OfferEvent()
        offer_event.name = OfferEvent.TYPE_NEW
        offer_event.offer = db_offer

        db.session.add(offer_event)

        return db_offer, False
Пример #25
0
def main():

    amazon_api = get_amazon_api()

    todays_date = date.today()

    if DEBUG:
        logger.info('loading items from local file')
        wishlist_items = get_items_from_local_file()
    else:
        # scan the wishlist on Amazon's site
        logger.info('loading items from amazon')
        wishlist_items = get_items_from_wishlist(WISHLIST_ID)

    # if we didn't get anything back, refresh the prices for what we do have
    if len(wishlist_items) == 0:
        wishlist_items = get_current_wishlist_items()
        logger.info('Nothing returned from the last wishlist check - using old data.')
    else:
        # add all of the wishlist items to the database
        add_wishlist_items_to_db(wishlist_items=wishlist_items)

    # we're using a live_data flag to indicate which are live on the site and which aren't
    # everything we're updating won't have a live data flag until the end, where we delete
    # everything with the live_data flag and then update the new stuff

    # now that all of the base items are in the wishlist, get all of the parent items

    all_items = Item.query.filter(Item.live_data == False) \
                          .filter(or_(Item.date_last_checked == None, Item.date_last_checked != todays_date)) \
                          .all()

    # if DEBUG:
    #     all_items = all_items[:5]
    #     logger.info('in DEBUG, limiting all_items to 5')

    for i in all_items:
        logger.info('getting parent for {0}'.format(i.ASIN))
        item_parent_ASIN = get_parent_ASIN(ASIN=i.ASIN, amazon_api=amazon_api)
        logger.info('   got parent')
        # if this parent doesn't exist, create it
        parent = ParentItem.query.filter_by(parent_ASIN=item_parent_ASIN, live_data=False).first()
        if parent is None:
            logger.info("parent doesn't exist, creating")
            parent = ParentItem(parent_ASIN=item_parent_ASIN)
            db.session.add(parent)
            db.session.commit()
        # add the parent to the item
        i.parent_item = parent
        db.session.add(i)
        db.session.commit()

    # from that list of parents, get all variations
    all_parents = ParentItem.query.filter(Item.live_data==False) \
                                  .filter(or_(Item.date_last_checked == None, Item.date_last_checked != todays_date)) \
                                  .all()
    for p in all_parents:
        # get a list of all ASINS under that parent
        logger.info('getting variations for {0}'.format(p.parent_ASIN))
        variations = get_variations(parent_ASIN=p.parent_ASIN, amazon_api=amazon_api)
        logger.info('Found {0} variations for {1}'.format(len(variations), p.parent_ASIN))
        for v in variations:
            logger.info('   Checking for existence of variation {0}'.format(v))
            var = Item.query.filter_by(ASIN=v).all()
            if len(var) == 0:
                logger.info("       Don't have this one, adding.")
                # if we don't have these variations already, add them to the database
                # with the correct parent
                new_variation = Item(ASIN=v, parent_item=p)
                db.session.add(new_variation)
                db.session.commit()
            else:
                logger.info("       Have it.")

    ## Next step is to get the item data for everything in the database

    # get attributes (name, price, URL, etc) for all items
    # all all offers for each item
    all_items = Item.query.filter(Item.live_data==False) \
                          .filter(or_(Item.date_last_checked == None, Item.date_last_checked != todays_date)) \
                          .all()

    for i in all_items:
        logger.info('in the item refresh')
        refresh_item_data(item=i, amazon_api=amazon_api)
        # cant' get info on some - looks like maybe weapons?
        if i.name is not None:
            # get all of the available offers
            # first remove existing offers from database
            item_offers = i.offers.all()
            for x in item_offers:
                logger.info('   trying to remove old offers')
                db.session.delete(x)
                db.session.commit()
            # can't get offers for Kindle Books
            if i.product_group == 'eBooks':
                logger.info("   can't get offers for Kindle books")
            else:
                logger.info('   getting offers for {0}'.format(i.ASIN))
                offers = get_offers(item=i, amazon_api=amazon_api)
                for o in offers:
                    new_offer = Offer()
                    new_offer.condition = str(o['condition'])
                    new_offer.offer_source = str(o['offer_source'])
                    new_offer.offer_price_amount = int(o['offer_price_amount'])
                    new_offer.offer_price_formatted = str(o['offer_price_formatted'])
                    new_offer.prime_eligible = o['prime_eligible']
                    new_offer.availability = str(o['availability'])
                    new_offer.item_id = o['item_id']
                    new_offer.item = i
                    db.session.add(new_offer)
                    db.session.commit()

    # now let's see what the best deals are!
    find_best_offer_per_wishlist_item()

    update_last_refreshed()

    remove_old_data()

    set_live_data_flag()

    logger.info('Finished run at {0}'.format(datetime.now().strftime('%H:%M %Y-%m-%d')))

    send_completion_message()
Пример #26
0

@app.route('/offers')
def show_all_offers():
    all_offer_product = []
    offers = Offer.query.all()
    for offer in offers:
        offer_product = {}
        offer_product['offer_code'] = offer.offer_code
        offer_product['product_code'] = []
        for product in offer.products:
            offer_product['product_code'].append(product.product_code)
        all_offer_product.append(offer_product)
    print(all_offer_product)
    # return render_template('show_all_offers.html', offers=Offer.query.all())
    return jsonify(all_offer_product)


if __name__ == '__main__':
    db.drop_all()
    db.create_all()
    db.session.add(Product(product_code='PROD001'))
    db.session.add(Product(product_code='PROD002'))
    db.session.add(Product(product_code='PROD003'))
    db.session.add(Product(product_code='PROD004'))
    db.session.add(Product(product_code='PROD005'))
    db.session.add(Offer(offer_code='OFFER001'))
    db.session.add(Offer(offer_code='OFFER002'))
    db.session.add(Offer(offer_code='OFFER003'))
    db.session.commit()
    app.run(debug=True)
Пример #27
0
def merchant(action):
    """
    Manage merchants endpoint.

    action = any(list-all, new, save, delete, note, delete-note)
    """

    data = request.get_json()
    if action == 'list-all':
        merchants, count = Merchant.admin_list_all(data.get('offset', 0),
                                                   data.get('limit', 25),
                                                   data.get('search', ''))
        return jsonify({'merchants': merchants, 'count': count})
    elif action == 'new':
        return jsonify({'merchant': Merchant.new().as_dict()})
    elif action == 'save':
        Merchant.save(data.get('merchant'))
        return jsonify({'success': True})
    elif action == 'delete':
        Merchant.delete(data.get('merchant'))
        return jsonify({'success': True})
    elif action == 'note':
        if data.get('merchant_id') is not None:
            note = MerchantNote(note=data.get('note'),
                                merchant_id=data['merchant_id'])
            db.session.add(note)
            db.session.commit()
            return jsonify({'note': note.as_dict()})
    elif action == 'delete-note':
        if data.get('note') is not None and data['note'].get('id') is not None:
            note = MerchantNote.query.get(data['note']['id'])
            db.session.delete(note)
            db.session.commit()
            return jsonify({'success': True})
    elif action == 'location-note':
        if data.get('location_id') is not None:
            note = LocationNote(note=data.get('note'),
                                location_id=data['location_id'])
            db.session.add(note)
            db.session.commit()
            return jsonify({'note': note.as_dict()})
    elif action == 'location-delete-note':
        if data.get('note') is not None and data['note'].get('id') is not None:
            note = LocationNote.query.get(data['note']['id'])
            db.session.delete(note)
            db.session.commit()
            return jsonify({'success': True})
    elif action == 'offer-new':
        offer = Offer.new(data.get('merchant_id'))
        if offer is not None:
            return jsonify({'offer': offer.as_dict()})
    elif action == 'offer-save':
        offer = Offer.save(data.get('offer'))
        if offer is not None:
            return jsonify({'offer': offer.as_dict()})
    elif action == 'offer-delete':
        offer_id = data.get('offer', {}).get('id')
        if offer_id is not None:
            offer = Offer.query.get(offer_id)
            db.session.delete(offer)
            db.session.commit()
            return jsonify({'success': True})
    elif action == 'location-new':
        location = Location.new(data.get('merchant_id'))
        if location is not None:
            return jsonify({'location': location.as_dict()})
    elif action == 'location-save':
        location = Location.save(data.get('location'))
        if location is not None:
            return jsonify({'location': location.as_dict()})
    elif action == 'location-delete':
        location_id = data.get('location', {}).get('id')
        if location_id is not None:
            location = Location.query.get(location_id)
            db.session.delete(location)
            db.session.commit()
            return jsonify({'success': True})
    elif action == 'contact-new':
        contact = MerchantContact.new(data.get('merchant_id'))
        if contact is not None:
            return jsonify({'contact': contact.as_dict()})
    elif action == 'contact-save':
        contact = MerchantContact.save(data.get('contact'))
        if contact is not None:
            return jsonify({'contact': contact.as_dict()})
    elif action == 'contact-delete':
        contact_id = data.get('contact', {}).get('id')
        if contact_id is not None:
            contact = MerchantContact.query.get(contact_id)
            db.session.delete(contact)
            db.session.commit()
            return jsonify({'success': True})
    return jsonify({}), 400
Пример #28
0
def create_offer(offercode):
    offer = Offer(offer_code=offercode)
    db.session.add(offer)
    db.session.commit()
    flash('Record Added')
    return jsonify({'message': 'Offer code ' + offercode + ' Added'})