예제 #1
0
def main():
    # стартуем с этой даты
    now_date = date(2016, 1, 1)
    # крутим цикл по количеству дней
    while(now_date < date(2017, 6, 1)):
        # получаем дату текущего дня, datetime закрытия и открытия
        now_date += timedelta(days=1)
        now_end = datetime.combine(now_date, close_time)
        # счетчик который будет расти до конца дня и потом начинатся сначала дня, в данном месте будет всегда равен началу дня
        now = datetime.combine(now_date, open_time)
        # открываем кассовую смену на начало дня
        cashbox = Cashbox(now)
        cashbox_summ = 0
        # количество созданных товаров
        products_count = Product.query.count()
        # цикл  для чеков
        while now < now_end:
            # текущее время для продажи
            now += timedelta(minutes = genTime(now_date, now))
            # создаем новый чек и записываем время как время пробития
            receipt = Receipt(time = now)
            receipt_summ = 0
            # для генератора случайных id продуктов которые не повторяются
            products=[]
            product_id = 0
            # генерем количество позиций для продажи в чеке от1 до 3х позиций
            for sale in range(random.randint(1, 3)):
                while(True):
                    # верхней границей является id последнего товра в списке,
                    # при учете что товары не удалялись и нет разрывов в очередности
                    product_id = random.randint(1, products_count)
                    if not(product_id in products):
                        products.append(product_id)
                        break
                # получаем товар
                new_product = Product.query.filter_by(id=product_id).first()
                # добавляем в продажи
                rand_quantity = random.randint(1, 3)
                new_sale = Sale(quantity = rand_quantity, price = new_product.price)
                new_sale.product = new_product
                # добавляем продажу в чек
                receipt.sale.append(new_sale)
                # добавляем сумму в общую для кассы при учете что в чеке количество уникального товара = 1
                cashbox_summ += new_product.price*rand_quantity
                receipt_summ += new_product.price*rand_quantity

            receipt.status = 0
            receipt.cash = receipt_summ
            # добавляем чеки в кассовую смену
            cashbox.receipts.append(receipt)
        cashbox.status = 0
        cashbox.cash = cashbox_summ
        cashbox.close = now_end
        db.session.add(cashbox)
        db.session.commit()
예제 #2
0
def charge_coins(user_id, receipt):
    # 신뢰성 있는 영수증인지 확인한다.
    purchase = check_purchase(receipt)
    if purchase is None:
        # wrong receipt
        raise WrongReceiptError()
    # 구글 결제 테스트 시에는 order_id 가 할당되지 않는다.
    # 타당한 receipt이지만 order_id가 없을 수도 있다.
    if receipt.order_id is not None and receipt.order_id.strip():
        saved_receipt = Receipt.query.filter(
            Receipt.order_id == receipt.order_id).first()
        if saved_receipt is not None:
            # already handled
            raise ElementAlreadyExists()
        handled_receipt = Receipt()
        handled_receipt.user_id = user_id
        handled_receipt.order_id = receipt.order_id
        handled_receipt.package_name = receipt.package_name
        handled_receipt.product_id = receipt.product_id
        handled_receipt.purchase_time = receipt.purchase_time
        handled_receipt.purchase_state = receipt.purchase_state
        handled_receipt.purchase_token = receipt.purchase_token
        db.session.add(handled_receipt)
    try:
        coin = 0
        if receipt.product_id == 'android.test.purchased':
            coin = 100
        else:
            # product_id가 com.river_auction.coin.3 와 같은 형태로
            # 마지막 끝이 coin 갯수가 된다.
            coin = int(receipt.product_id.split('.')[-1])
        add_coins(user_id, coin, TransactionType.CHARGING)
    except:
        raise InvalidArgumentError(extra_message='product id is wrong')
    db.session.commit()
예제 #3
0
def upload_receipt(request):
    if request.method == 'POST':
        form = UploadReceiptForm(request.POST, request.FILES)
        if form.is_valid():
            registration_no = form.cleaned_data['registration_no']
            receipt = request.FILES['receipt']
            insert_receipt = Receipt(registration_no=registration_no,
                                     receipt=receipt)
            insert_receipt.save()
            messages.success(request, 'Receipt uploaded successfully!')
            return redirect('check_uploaded_receipt')
    else:
        form = UploadReceiptForm()
    return render(request, 'receipt/upload_receipt.html', {'form': form})
예제 #4
0
파일: views.py 프로젝트: AlexPutrya/csf
    def get(self):
        products = []
        number = 0
        receipt_summ = 0
        if 'id_cashbox' in session:
            # если в сессионной переменной нет id чека то мы создаем новый чек
            if not ('id_receipt' in session):
                receipt = Receipt(time=datetime.utcnow(),
                                  cashbox_id=session['id_cashbox'])
                db.session.add(receipt)
                db.session.commit()
                session['id_receipt'] = receipt.id
            cashbox = Cashbox.query.filter_by(id=session['id_cashbox']).one()
            if cashbox.status == 1:
                sales = Sale.query.filter_by(receipt_id=session['id_receipt'])
                for sale in sales:
                    number += 1
                    receipt_summ += sale.price * sale.quantity
                    products.append({
                        'number': number,
                        'name': sale.product.name,
                        'product_id': sale.product.id,
                        'quantity': sale.quantity,
                        'price': sale.price,
                        'summa': sale.price * sale.quantity
                    })
                return {
                    'cashbox_status': cashbox.status,
                    'receipt_products': products,
                    'receipt_summ': receipt_summ,
                    'cash': cashbox.cash,
                    'id_receipt': session['id_receipt']
                }

        return {'cashbox_status': 0}
예제 #5
0
파일: bills.py 프로젝트: ekkazit/bartender
def bill_checkout():
	result = 0
	f = request.get_json()
	if f is None:
		f = request.form

	frm = f['bill']
	frm_items = frm['bill_items']
	result = bill_prepare_save(frm, frm_items)

	checkforms = f['checkout']
	if result and checkforms:
		# delete old receipts
		Receipt.query.filter_by(bill_id=result).delete()
		# create new receipts
		receipt = Receipt(site_id=g.sid, branch_id=g.bid, bill_id=result)
		receipt.line_no = 1
		receipt.receipt_no = 'R' + frm['bill_no']
		receipt.method = 'cash'
		receipt.total_amount = checkforms.get('total_amount') or 0
		receipt.total_charge = checkforms.get('total_charge') or 0
		receipt.total_return = checkforms.get('total_return') or 0
		db.session.add(receipt)
		db.session.commit()
		# update bill status
		status = Status.query.filter_by(name='paid', module='bill').first()
		bill = Bill.query.get(result)
		if bill:
			bill.status_id = status.id
			db.session.merge(bill)
			db.session.commit()
	return jsonify({ 'result': result })
예제 #6
0
파일: views.py 프로젝트: AlexPutrya/csf
 def post(self):
     cashbox = Cashbox(datetime.utcnow())
     receipt = Receipt(time=datetime.utcnow())
     cashbox.receipts.append(receipt)
     db.session.add(cashbox)
     db.session.commit()
     session['id_cashbox'] = cashbox.id
     session['id_receipt'] = receipt.id
     return '', 204
예제 #7
0
def index():
    form = ReceiptForm()
    receipts = Receipt.query.filter_by(user_id=current_user.id).all()

    if form.validate_on_submit():
        if Usage.query.filter_by(name=form.usage.data).first():
            usage = Usage.query.filter_by(name=form.usage.data).first()
            receipt = Receipt(description=form.description.data, amount=form.amount.data, user_id=current_user.id, usage_id=usage.id)
            db.session.add(receipt)
            db.session.commit()
            flash("New Receipt Added")
        else:
            usage = Usage(name=form.usage.data)
            db.session.add(usage)
            db.session.commit()
            receipt = Receipt(description=form.description.data, amount=form.amount.data, user_id=current_user.id, usage_id=usage.id)
            db.session.add(receipt)
            db.session.commit()
            flash("New Receipt Added")
        return redirect('/index')

    return render_template('index.html', form=form, receipts=receipts)
예제 #8
0
def add_receipt(items):
    try:
        r = Receipt()
        db.session.add(r)
        db.session.commit()

        for item in items:
            d = ReceiptDetail()
            d.quantity = item["quantity"]
            d.unit_price = item["price"]
            d.receipt_id = r.id
            d.product_id = item["id"]
            db.session.add(d)
        db.session.commit()
        return True
    except Exception as ex:
        print(ex)
        return False
예제 #9
0
def add_receipt(cart):
    if cart:
        receipt = Receipt(customer_id=1)
        db.session.add(receipt)

        for r in list(cart.values()):
            detail = ReceiptDetail(receipt=receipt,
                                   room_id=int(r["id"]),
                                   quantity=r["quantity"],
                                   price=r["price"])
            db.session.add(detail)

        try:
            db.session.commit()
            return True
        except Exception as ex:
            print(ex)

    return False
예제 #10
0
파일: routes.py 프로젝트: oolawo09/receipt
def index():
    form = ReceiptForm()
    lif = LineItemForm()

    if form.validate_on_submit():
        add_receipt_to_session(form)

        receipt = Receipt(sender=form.sender.data,
                          recipient=form.recipient.data,
                          notes=form.notes.data, items=form.items.data)
        db.session.add(receipt)

        if current_user.is_authenticated:
            user = User.query.get(current_user.id) 
            user.receipts.append(receipt)
            db.session.add(user)
        
        db.session.commit()

        return redirect(url_for('preview'), code=302)
    return render_template('receipt.html',
                           form=form, lif=lif)
예제 #11
0
def checkout_action():

    # get submit bill info
    cardname = request.form.get('cardname')
    cardnumber = request.form.get('cardnumber')

    # gather selected checkout items
    product_in_cart = Cart.query.filter_by(user_id=current_user.id).join(
        Product, Cart.product_id == Product.product_id).add_columns(
            Product.name, Product.price, Product.image,
            Product.product_id).all()

    # create a checkout submit record and put it to the db
    checkout = Checkout(user_id=current_user.id)
    db.session.add(checkout)
    db.session.commit()
    for product in product_in_cart:
        receipt = Receipt(checkout_id=checkout.checkout_id,
                          product_id=product.product_id)
        db.session.add(receipt)
        db.session.commit()
    # remove selected checkout items
    for product in product_in_cart:
        empty_cart = Cart.query.filter_by(
            user_id=current_user.id, product_id=product.product_id).first()
        db.session.delete(empty_cart)
        db.session.commit()

    #Display receipt
    final_receipt = Receipt.query.filter_by(
        checkout_id=checkout.checkout_id).join(
            Product, Receipt.product_id == Product.product_id).add_columns(
                Product.name, Product.price).all()

    print("checkout_action:" + cardname + cardnumber)
    return render_template("checkout_action.html", final_receipt=final_receipt)
예제 #12
0
파일: views.py 프로젝트: AlexPutrya/csf
    def put(self):
        receipt_summ = 0

        #проверяем не пытается ли пользователь пробить пустой чек
        count_sales = Sale.query.filter_by(
            receipt_id=session['id_receipt']).count()
        if count_sales == 0:
            return '', 404
        sales = Sale.query.filter_by(receipt_id=session['id_receipt'])
        # определяем сумму чека
        for sale in sales:
            receipt_summ += sale.price * sale.quantity
        # закрываем чек и добавляем сумму чека к сумме кассы
        cashbox = Cashbox.query.filter_by(id=session['id_cashbox']).one()
        receipt = Receipt.query.filter_by(id=session['id_receipt']).one()
        receipt.status = 0
        receipt.cash = receipt_summ
        cashbox.cash += receipt_summ
        new_receipt = Receipt(time=datetime.utcnow(),
                              cashbox_id=session['id_cashbox'])
        db.session.add(new_receipt)
        db.session.commit()
        session['id_receipt'] = new_receipt.id
        return '', 204
예제 #13
0
def store_walmart_data(receipt_json, user_id):
    receipt_data = json.loads(receipt_json)

    date = receipt_data['receipts'][0]['dateTime'].split()[0]
    store = receipt_data['receipts'][0]['store']['displayName']
    sales_tax = receipt_data['receipts'][0]['total']['taxTotal']
    subtotal = receipt_data['receipts'][0]['total']['subtotal']

    queried_receipt = Receipt.query.filter_by(date=date,
                                              store=store,
                                              sales_tax=sales_tax,
                                              subtotal=subtotal,
                                              user_id=user_id).first()
    receipt = Receipt(date=date,
                      store=store,
                      sales_tax=sales_tax,
                      subtotal=subtotal,
                      user_id=user_id)

    #ERROR: SAME RECEIPT
    if queried_receipt == None or queried_receipt != receipt:
        db.session.add(receipt)
        db.session.commit()

        items = receipt_data['receipts'][0]['items']

        item_list = []
        with futures.ThreadPoolExecutor() as executor:
            futures_list = {}
            category_list = {}
            for item in items:
                name = item['description']
                price = item['price']
                upc = item['upc']
                image_url = item['imageUrl']

                i = Item(name=name,
                         price=price,
                         upc=upc,
                         receipt_id=receipt.id)
                item_list.append(i)

                category_list[executor.submit(get_walmart_categories,
                                              i)] = name
                futures_list[executor.submit(add_image_to_folder, image_url,
                                             upc)] = name

            for future in futures.as_completed(category_list):
                item_name = category_list[future]
                for item in item_list:
                    if item.name == item_name:
                        categoryList = future.result()
                        item.category1 = categoryList[0]
                        item.category2 = categoryList[1]
                        item.category3 = categoryList[2]

            for future in futures.as_completed(futures_list):
                item_name = futures_list[future]
                for item in item_list:
                    if item.name == item_name:
                        item.image_id = future.result()
                        db.session.add(item)
                        db.session.commit()
    else:
        #Do more with "same reciept" error
        print('Same Receipt')
예제 #14
0
파일: bills.py 프로젝트: ekkazit/bartender
def bill_form_save():
	f = request.get_json()
	if f is None:
		f = request.form

	forms = {
		'branch_id': g.bid,
		'site_id': g.sid,
		'user_id': g.uid,
		'bill_no': f.get('bill_no') or '',
		'currency': f.get('currency'),
		'cust_id': f.get('cust_id') or None,
		'no': f.get('no'),
		'receipt_no': f.get('receipt_no') or None,
		'remark': f.get('remark') or '',
		'status_id': f.get('status_id') or None,
		'table_id': f.get('table_id') or None,
		'tax_rate': f.get('tax_rate') or 0,
		'discount_rate': get_num(f.get('discount_rate')),
		'total_amount': get_num(f.get('total_amount')),
		'total_discount': get_num(f.get('total_discount')),
		'total_price': get_num(f.get('total_price')),
		'total_tax': get_num(f.get('total_tax')),
		'total_qty': get_num(f.get('total_qty')),
	}

	# update bill
	bill = None
	id = f.get('id') or None
	if id:
		bill = Bill.query.get(id)
		for k, v in forms.iteritems():
			setattr(bill, k, v)
		db.session.merge(bill)
	else:
		bill = Bill()
		for k, v in forms.iteritems():
			setattr(bill, k, v)
		db.session.add(bill)
	db.session.commit()

	# update bill items
	bill_items = json.loads(f.get('bill_items'))
	if bill.id:
		result = bill.id
		BillItem.query.filter_by(bill_id=bill.id).delete()
		for elem in bill_items:
			bill_item = BillItem()
			for k, v in elem.iteritems():
				try:
					if k == 'id': continue
					setattr(bill_item, k, v)
				except: pass
			bill_item.bill_id = bill.id
			db.session.add(bill_item)
		db.session.commit()

	# update receipt info
	rcv = f.get('receipt_no') or None
	if bill.id and rcv:
		Receipt.query.filter_by(site_id=g.sid, branch_id=g.bid, bill_id=result).delete()
		receipt = Receipt(site_id=g.sid, branch_id=g.bid, bill_id=result)
		receipt.line_no = 1
		receipt.receipt_no = f.get('receipt_no') or ''
		receipt.method = f.get('method') or ''
		receipt.total_amount = get_num(f.get('total_amount'))
		receipt.total_charge = get_num(f.get('total_rcv_charge'))
		receipt.total_return = get_num(f.get('total_rcv_return'))
		db.session.add(receipt)
		db.session.commit()
	return jsonify({'result': bill.id})