コード例 #1
0
ファイル: tickets.py プロジェクト: mainframed/Concord
def purchase_tickets():
    tickets = app.config['TICKETS']
    form = forms.PurchaseForm()
    if form.validate_on_submit():
        purchase = Purchase()
        purchase.date = datetime.now()
        form.populate_obj(purchase)

        # First thing that we need to do is check to make sure that the email
        # actually is a .edu address.  If not, tell the user they f****d up and
        # set it back to attendee.
        if purchase.ticket_type == 'student' and purchase.email[-3:] != 'edu':
            flash('Not a student, defaulting to Attendee')
            # The student was a lie!  Reset it to attendee.
            purchase.ticket_type = 'attendee'
            purchase.price = tickets[purchase.ticket_type]['price']

        # Next we need to match up the ticket types to make sure that no one
        # was mucking about with the ticket types.  If everything matches, then
        # go ahead and trust what the form is telling us and apply the price.
        if (purchase.ticket_type in tickets
                and tickets[purchase.ticket_type]['visible'] and
            (tickets[purchase.ticket_type]['expiration'] is None
             or date.today() < tickets[purchase.ticket_type]['expiration'])):
            purchase.price = tickets[purchase.ticket_type]['price']
        else:
            flash('Invalid Ticket Type...resetting to Attendee')
            # If it looks like someone was actually sending odd form values,
            # then we wont trust the ticket type and override it with a regular
            # attendee ticket type.
            purchase.ticket_type = 'attendee'
            purchase.price = tickets[purchase.ticket_type]['price']
        if form.discountcode.data != '':
            # Lets check to see if the discount code is valid.  If it is, then
            # we will be overriding the price and the ticket type associated
            # with this purchase.
            code = DiscountCode.query.filter_by(
                code=form.discountcode.data).first()
            if code is None or code.uses < 1:
                flash('Invalid or Expired Discount Code')
            else:
                purchase.price = code.price
                purchase.ticket_type = code.t_type

        # Add the purchase to the database and then return the confirmation page.
        db.session.add(purchase)
        db.session.commit()
        return render_template('ticketing/confirm.html',
                               purchase=purchase,
                               title='Purchase Confirmation',
                               stripe_key=app.config['STRIPE_PKEY'])
    return render_template('ticketing/purchase.html',
                           form=form,
                           title='Ticket Purchasing')
コード例 #2
0
ファイル: purchases.py プロジェクト: lettemax/zipnodes
def seed_purchases():

    pur1 = Purchase(node_id=1, project_id=1, num_shares=10)

    pur2 = Purchase(node_id=1, project_id=2, num_shares=100)

    pur3 = Purchase(node_id=6, project_id=1, num_shares=500)

    db.session.add(pur1)
    db.session.add(pur2)
    db.session.add(pur3)

    db.session.commit()
コード例 #3
0
ファイル: tickets.py プロジェクト: Healwhans/Concord
def purchase_tickets():
    tickets = app.config['TICKETS']
    form = forms.PurchaseForm()
    if form.validate_on_submit():
        purchase = Purchase()
        purchase.date = datetime.now()
        form.populate_obj(purchase)

        # First thing that we need to do is check to make sure that the email
        # actually is a .edu address.  If not, tell the user they f****d up and
        # set it back to attendee. 
        if purchase.ticket_type == 'student' and purchase.email[-3:] != 'edu':
            flash('Not a student, defaulting to Attendee')
            # The student was a lie!  Reset it to attendee.
            purchase.ticket_type = 'attendee'
            purchase.price = tickets[purchase.ticket_type]['price']
        
        # Next we need to match up the ticket types to make sure that no one
        # was mucking about with the ticket types.  If everything matches, then
        # go ahead and trust what the form is telling us and apply the price.
        if (purchase.ticket_type in tickets 
            and tickets[purchase.ticket_type]['visible']
            and (tickets[purchase.ticket_type]['expiration'] is None
                or date.today() < tickets[purchase.ticket_type]['expiration'])):
            purchase.price = tickets[purchase.ticket_type]['price']
        else:
            flash('Invalid Ticket Type...resetting to Attendee')
            # If it looks like someone was actually sending odd form values,
            # then we wont trust the ticket type and override it with a regular
            # attendee ticket type.
            purchase.ticket_type = 'attendee'
            purchase.price = tickets[purchase.ticket_type]['price']
        if form.discountcode.data != '':
            # Lets check to see if the discount code is valid.  If it is, then
            # we will be overriding the price and the ticket type associated
            # with this purchase.
            code = DiscountCode.query.filter_by(code=form.discountcode.data).first()
            if code is None or code.uses < 1:
                flash('Invalid or Expired Discount Code')
            else:
                purchase.price = code.price
                purchase.ticket_type = code.t_type

        # Add the purchase to the database and then return the confirmation page.
        db.session.add(purchase)
        db.session.commit()
        return render_template('ticketing/confirm.html', 
            purchase=purchase, 
            title='Purchase Confirmation',
            stripe_key=app.config['STRIPE_PKEY'])
    return render_template('ticketing/purchase.html', 
            form=form,
            title='Ticket Purchasing')
コード例 #4
0
def add():
    form = PurchaseForm()
    for field in form.item_quantity:
        field.item_id.choices = [
            (i.id, i.name) for i in Inventory.query.filter_by(
                company_id=current_user.id).order_by('name')
        ]
        field.unit_id.choices = [(u.id, u.name) for u in Unit.query.filter_by(
            company_id=current_user.id).order_by('name')]
    if form.validate_on_submit():
        d = lambda f: f.data  # d = Data and f = field
        purchase = Purchase(party_name=d(form.name),
                            current_date=d(form.current_date),
                            suplier_date=d(form.suplier_date),
                            invoice=d(form.invoice),
                            company_id=current_user.id)
        for item in form.item_quantity.data:
            qpp = QuantityPerPurchase(inventory_id=item['item_id'],
                                      unit_id=item['unit_id'],
                                      quantity=item['quantity'],
                                      price=item['price'])
            db.session.add(qpp)
            purchase.items.append(qpp)
        db.session.add(purchase)
        db.session.commit()
        return redirect(url_for('pur.home'))
    return render_template('purcadd.html', form=form)
コード例 #5
0
ファイル: routes.py プロジェクト: NoamGit/HouseFinance
def index():
    form = PurchaseForm()
    if form.validate_on_submit():
        purchase = Purchase(
            business_name=form.business_name.data,
            date=form.date.data  # .strftime('%Y-%m-%d')
            ,
            price=form.price.data,
            payment_price=form.payment_price.data,
            buyer=current_user)
        db.session.add(purchase)
        db.session.commit()
        flash('Purchase was commited!')
        return redirect(url_for('main.index'))

    page = request.args.get('page', 1, type=int)
    purchases = Purchase.query.filter_by(buyer=current_user).order_by(
        Purchase.date.desc()).paginate(
            page, current_app.config['PURCHASES_PER_PAGE'], False)
    next_url = url_for('main.index',
                       page=purchases.next_num) if purchases.has_next else None
    prev_url = url_for('main.index',
                       page=purchases.prev_num) if purchases.prev_num else None
    return render_template('index.html',
                           title='Home',
                           form=form,
                           purchases=purchases.items,
                           next_url=next_url,
                           prev_url=prev_url)
コード例 #6
0
ファイル: cart_routes.py プロジェクト: olivianicole/plantMe
def checkout():
    form = PurchaseForm()
    print(request.get_json())
    # Get the csrf_token from the request cookie and put it into the
    # form manually to validate_on_submit can be used
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        purchase = Purchase(
            user_id=form.user_id.data,
            listing_id=form.listing_id.data,
            quantity=form.quantity.data,
        )
    db.session.add(purchase)
    db.session.commit()
    return {'item': purchase.to_dict()}
    return {'errors': validation_errors_to_error_messages(form.errors)}, 401
コード例 #7
0
ファイル: tests.py プロジェクト: BEricDavis/quilt_pos
    def test_purchase(self):
        print('In test_purchase')
        customer = Customer.query.filter_by(
            email='*****@*****.**').first()
        c2 = Customer.query.filter_by(email='*****@*****.**').all()
        print('c2: {}'.format(c2))
        item1 = Item.query.filter_by(sku='123456789A').first()
        print('item1: {}'.format(item1))
        item2 = Item.query.filter_by(sku='abc-def-123').first()
        print('item2: {}'.format(item2))
        subtotal = item1.price + item2.price
        tax = float(subtotal) * .075
        total = float(subtotal) + tax

        p = Purchase(customer_id=customer,
                     items=[item1, item2],
                     total_items=2,
                     tax=tax,
                     subtotal=subtotal,
                     total=total)
        print('purchase: {}'.format(p))
        db.session.add(p)
        db.session.commit()
        p1 = Purchase.query.filter_by(id=1)
        print('purhcase: {}'.format(p1))
コード例 #8
0
ファイル: purchase_routes.py プロジェクト: lettemax/zipnodes
def create_purchase():
    """
    Creates a purchase.
    """
    form = PurchaseForm()
    print(request.get_json())
    # Get the csrf_token from the request cookie and put it into the
    # form manually to validate_on_submit can be used
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        purchase = Purchase(node_id=form.data['node_id'],
                            project_id=form.data['project_id'],
                            num_shares=form.data['num_shares'])
        db.session.add(purchase)
        db.session.commit()
        return purchase.to_dict()
    return 'invalid form'
コード例 #9
0
def purchase_form_handler(form):
    purchase_data = Purchase(rstnumber=form.rst_number.data,
                             weight=form.weight.data,
                             moisture=form.moisture.data,
                             rate=form.rate.data,
                             variety_id=form.variety.data,
                             agent_id=form.agent.data,
                             timestamp=form.date.data,
                             amount=form.amount.data)
    return write_to_db(purchase_data)
コード例 #10
0
ファイル: views.py プロジェクト: waffle-iron/ludolatin
def profile_pictures(picture_id):
    product = Product.query.filter_by(name="Profile picture").first()
    if product.available:
        try:
            Purchase(
                product=product,
                price=product.total_price,
                user_id=current_user.id,
            ).save()
            current_user.profile_picture = picture_id
            current_user.total_score -= product.total_price
        except:
            abort(400)
    return jsonify(current_user.to_dict()), 200
コード例 #11
0
ファイル: controllers.py プロジェクト: lzhua/shop
def addStock():

    # If sign in form is submitted
    form = AddStock(request.form)

    # Verify the purchse form
    if form.validate_on_submit():
        # filter_by(name='')
        if Stock.query.filter_by(name=request.form['name']).first():

            updates = Stock.query.filter_by(name=request.form['name']).first()
            quantty = int(updates.quantity)
            qtty = int(request.form['quantity'])
            #update name
            updates.quantity = quantty + qtty

            #add to the purchase table
            pur_record = Purchase(request.form['name'],
                                  request.form['quantity'])
            db.session.add(pur_record)
            db.session.commit()
            flash('product was successfully updated ')
            return redirect(url_for('stock.viewItem', item_id=updates.id))
        else:
            product = Stock(request.form['name'], request.form['price'],
                            request.form['quantity'])
            #add to the purchase table
            pur_record = Purchase(request.form['name'],
                                  request.form['quantity'])
            db.session.add(product)
            db.session.add(pur_record)
            db.session.commit()
            flash('product was successfully added ')
            return redirect(url_for('stock.viewItem', item_id=product.id))

    return render_template("add/add.html", form=form)
コード例 #12
0
ファイル: routes.py プロジェクト: NoamGit/HouseFinance
def search():
    if not g.search_form.validate():
        return redirect(url_for('main.index'))
    page = request.args.get('page', 1, type=int)
    purchases, total = Purchase.search(
        g.search_form.q.data, page, current_app.config['PURCHASES_PER_PAGE'])
    next_url = url_for('main.search', q=g.search_form.q.data, page=page + 1) \
        if total > page * current_app.config['PURCHASES_PER_PAGE'] else None
    prev_url = url_for('main.search', q=g.search_form.q.data, page=page - 1) \
        if page > 1 else None
    return render_template('search.html',
                           title='Search',
                           purchases=purchases,
                           next_url=next_url,
                           prev_url=prev_url)
コード例 #13
0
ファイル: views.py プロジェクト: waffle-iron/ludolatin
def recover_streak():
    try:
        product = Product.query.filter_by(name="Streak recovery").first()
        if product.available:
            current_user.total_score -= product.total_price

            Purchase(
                product=product,
                price=product.total_price,
                user_id=current_user.id,
            ).save()

            Score(user_id=current_user.id,
                  created_at=datetime.datetime.utcnow(),
                  score=0).save()
    except:
        abort(400)
    return jsonify(current_user.to_dict()), 200
コード例 #14
0
def index():
    form = PurchaseForm()
    form.purchaser.choices = [(current_user.id, current_user.username)] + [
        (u.id, u.username)
        for u in User.get_user_list().filter(User.id != current_user.id).all()
    ]
    if form.validate_on_submit():
        language = guess_language(form.subject.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        shopname = form.shopname.data
        shop = Shop.query.filter_by(shopname=shopname).first()
        if shop is None:
            shop = Shop(shopname=shopname)
            db.session.add(shop)
        purchaser = User.query.get(form.purchaser.data)
        if purchaser is None:
            purchaser = current_user
        purchase = Purchase(purchase_date=form.purchase_date.data,
                            value=form.value.data,
                            seller=shop,
                            subject=form.subject.data,
                            author=current_user,
                            language=language)
        purchaser.add_purchase(purchase)
        db.session.add(purchase)
        db.session.commit()
        flash(_l("Your purchase is traced now!"))
        return redirect(url_for('main.index'))
    else:
        page = request.args.get('page', 1, type=int)
        purchases = current_user.followed_purchases().paginate(
            page, current_app.config['ELEMENTS_PER_PAGE'], False)
        next_url = url_for('main.index', page=purchases.next_num) \
            if purchases.has_next else None
        prev_url = url_for('main.index', page=purchases.prev_num) \
            if purchases.has_prev else None
        return render_template('index.html',
                               title=_l("Home Page"),
                               form=form,
                               purchases=purchases.items,
                               next_url=next_url,
                               prev_url=prev_url)
コード例 #15
0
def increasePurchaseOrder():
    form=increasePurchaseOrders()
    if form.validate_on_submit():
        data = form.data
        good_names=goods.query.filter_by(goods_id=data['goods_name']).first()
        ywy=User.query.filter_by(user_id=data['ywy']).first()
        gys=supplier.query.filter_by(supplier_id=data['gys']).first()
        names = Purchase(
            purchase_goods=good_names.goods_name,
            purchase_count=data['num'],
            purchase_supplier=gys.supplier_name,
            purchase_user_name=ywy.user_name,
            purchase_price=float(data['num'])*float(good_names.goods_price),
            purchase_num=on_created()
        )
        db.session.add(names)
        db.session.commit()
        time.sleep(2)

    return render_template("admin/increasePurchaseOrder.html",form=form)
コード例 #16
0
    def post(self):
        data = request.get_json(force=True)['purchase']
        if 'description' not in data or 'amount' not in data or 'date' not in data or 'category_id' not in data:
            return make_error("Please fill out all fields")
        purchase = Purchase()
        purchase.from_dict(data)

        date_arr = data['date'].split('-')
        purchase.date = datetime.date(int(date_arr[0]), int(date_arr[1]),
                                      int(date_arr[2]))

        cat = Category.query.get_or_404(purchase.category_id)
        cat.purchases.append(purchase)
        db.session.commit()

        return purchase.to_dict(), 201
コード例 #17
0
ファイル: views.py プロジェクト: leogout/gunter
def homepage(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = PurchaseForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            data = form.cleaned_data

            purchase = Purchase()

            purchase.category = data['category']
            purchase.price = data['price']

            purchase.save()

    form = PurchaseForm()
    categories = Category.objects.all()
    today = datetime.date.today()

    month = request.GET.get('month', today.month)
    year = request.GET.get('year', today.year)

    purchases = Purchase.objects.filter(date__year=year, date__month=month).order_by('-date')
    x = [category.name for category in categories]
    y = [category.total_in_month(month, year) for category in categories]
    limits = [category.limit for category in categories]
    colors = [category.color for category in categories]

    return render(
        request,
        'homepage.html',
        {
            'form': form,
            'today': today,
            'categories': categories,
            'purchases': purchases,
            'plot': {
                'x': x,
                'y': y,
                'colors': colors,
                'limits': limits,
                'total_limits': sum(limits),
                'xyc': zip(x, y, colors)
            }
        }
    )
コード例 #18
0
ファイル: views.py プロジェクト: waffle-iron/ludolatin
def triple_or_nothing():
    product = Product.query.filter_by(name="Triple or nothing").first()
    result = ""
    if product.available:
        try:
            Purchase(
                product=product,
                price=product.total_price,
                user_id=current_user.id,
            ).save()

            if randint(0, 2) == 0:
                current_user.total_score += (int(
                    current_user.total_score / 4)) * 2
                result = "success"
            else:
                current_user.total_score -= int(current_user.total_score / 4)
                result = "failure"
        except:
            abort(400)
    return jsonify({
        'user': current_user.to_dict(),
        'result': result,
    }), 200
コード例 #19
0
ファイル: testdata.py プロジェクト: NoamGit/HouseFinance
    df_abroad_purchase.rename(columns=new_abroad_colname, inplace=True)

    existing_users = db.session.query(User.username).all()
    sqlalchemy_to_str = lambda x: str(list(x)[0])
    if user_name not in [sqlalchemy_to_str(x) for x in existing_users]:
        u = User(username=user_name)
        db.session.add(u)
        db.session.commit()
    else:
        u = User.query.filter_by(username=user_name).all()[0]

    # for Israeli purchases
    for k, row in df_israel_purchase.iterrows():
        p = Purchase(business_name=row['business_name'],
                     date=datetime.strptime(row['purchase_date'],
                                            "%d/%m/%Y").date(),
                     price=float(row['price']),
                     payment_price=float(row['payment_price']),
                     buyer=u)
        db.session.merge(p)
        db.session.commit()

    # for purchases from the US
    for k, row in df_abroad_purchase.iterrows():
        p = Purchase(business_name=row['business_name'],
                     date=datetime.strptime(row['purchase_date'],
                                            "%d/%m/%Y").date(),
                     price=float(row['price']) * USD2ILS,
                     payment_price=float(row['payment_price']) * USD2ILS,
                     buyer=u)
        db.session.merge(p)
        db.session.commit()
コード例 #20
0
def importcsv():
    try:
        if request.files['import_filename']:
            # format csv file :
            log.info('Import from : {}'.format(
                request.files['import_filename']))
            assets_file = unicodecsv.DictReader(
                request.files['import_filename'], delimiter=';')
            commissioning_key_present = True if 'Indienststelling' in assets_file.fieldnames else False
            photo_key_present = True if 'Foto' in assets_file.fieldnames else False
            manual_key_present = True if 'Handleiding' in assets_file.fieldnames else False
            nbr_assets = 0
            nbr_devices = 0
            nbr_purchases = 0
            for a in assets_file:
                #check if supplier already exists
                supplier = Supplier.query.filter(
                    Supplier.name == 'ONBEKEND').first()
                if not supplier:
                    #add a new supplier
                    supplier = Supplier(name='ONBEKEND')
                    db.session.add(supplier)
                    log.info('add: {}'.format(supplier.log()))
                #check if device already exists
                device = Device.query.filter(
                    Device.brand == a['Merk'],
                    Device.type == a['Typenummer']).first()
                if device:
                    purchase = Purchase.query.filter(
                        Purchase.device == device).first()
                else:
                    #add a new device
                    try:
                        power = int(a['Vermogen'])
                    except:
                        power = 0

                    photo_file = a['Foto'].split(
                        '\\')[-1] if photo_key_present else ''
                    manual_file = a['Handleiding'].split(
                        '\\')[-1] if manual_key_present else ''
                    device = Device(brand=a['Merk'],
                                    category=a['Categorie'],
                                    type=a['Typenummer'],
                                    photo=photo_file,
                                    manual=manual_file,
                                    power=power,
                                    ce=True if a['CE'] == 'ok' else False)
                    db.session.add(device)
                    nbr_devices += 1
                    #Create a new purchase
                    purchase = Purchase.query.filter(
                        Purchase.since == '1999/1/1').order_by('-id').first()
                    commissioning_file = a['Indienststelling'].split(
                        '\\')[-1] if commissioning_key_present else ''
                    if purchase:
                        #create a new purchase with a value +1
                        purchase = Purchase(since=purchase.since,
                                            value=int(purchase.value) + 1,
                                            device=device,
                                            supplier=supplier,
                                            commissioning=commissioning_file)
                    else:
                        #add a new purchase
                        purchase = Purchase(since='1999/1/1',
                                            value='0',
                                            device=device,
                                            supplier=supplier,
                                            commissioning=commissioning_file)
                    db.session.add(purchase)
                    nbr_purchases += 1
                # #add the asset
                asset = Asset(name=a['Toestel'],
                              status=a['Status'],
                              serial=a['Serienummer'],
                              location=a['Lokaal'],
                              purchase=purchase)
                db.session.add(asset)
                nbr_assets += 1

            db.session.commit()
            log.info(
                'import: added {} assets, {} purchases and {} devices'.format(
                    nbr_assets, nbr_purchases, nbr_devices))

    except Exception as e:
        flash('Kan bestand niet importeren')
    return redirect(url_for('management.admin.show'))