def test_save(self): main_cashbox = get_main_cashbox() sale = Sale( offer = self.offer, cashbox = main_cashbox, ) sale.save() self.assertEqual(3, sale.transactions.count())
def AddSale(request): form = SaleForm(request.POST or None) if form.is_valid(): CustomerName = form.cleaned_data["CustomerName"] Address = form.cleaned_data["Address"] pub_date = form.cleaned_data["pub_date"] Sale_Quantity = form.cleaned_data["Sale_Quantity"] Product_Sold = form.cleaned_data["Product_Sold"] sale = Sale() sale.CustomerName = CustomerName sale.Address = Address sale.pub_date = pub_date sale.Sale_Quantity = Sale_Quantity sale.Product_Sold = Product_Sold sale.save() product = Product.objects.filter(pk=sale.Product_Sold.id)[0] product.Quantity = product.Quantity - sale.Sale_Quantity product.save() return HttpResponseRedirect(reverse('ecom:sale')) else: return render(request, "SaleMaster.html", {"form": form})
def addSale(request): if request.method == 'GET': customers = database.users.find() departments = database.departments.find() products = database.products.find() return render(request, 'addSale.html', {'customers': customers, 'departments': departments, 'products': products}) elif request.method == 'POST': customer = database.getUserById(request.POST['userId']) department = database.getDepartmentById(request.POST['departmentId']) product = database.getProductById(request.POST['productId']) sale = Sale(customer, department, product, request.POST['saleType'], request.POST['saleDescription']) database.sales.insert(sale.mongify()) return redirect(reverse('index') + '?message=Added Sale')
def AddSale(request): form = SaleForm(request.POST or None) if form.is_valid(): CustomerName = form.cleaned_data["CustomerName"] Address = form.cleaned_data["Address"] pub_date = form.cleaned_data["pub_date"] Sale_Quantity = form.cleaned_data["Sale_Quantity"] Product_Sold = form.cleaned_data["Product_Sold"] sale=Sale() sale.CustomerName = CustomerName sale.Address = Address sale.pub_date = pub_date sale.Sale_Quantity = Sale_Quantity sale.Product_Sold = Product_Sold sale.save() product = Product.objects.filter(pk=sale.Product_Sold.id)[0] product.Quantity = product.Quantity - sale.Sale_Quantity product.save() return HttpResponseRedirect(reverse('ecom:sale')) else: return render(request,"SaleMaster.html",{"form":form})
def saleDrug(drugId): # 判断用户是否登录 user_id = session.get('user_id') if user_id: user = User.query.filter(User.id == user_id).first() if user: # 判断是否是POST if request.method == 'GET': count = 0 drug = Drug.query.filter(Drug.id == drugId).first() # 查找选购表 药品的选购数量 s = db.session.query(func.sum(Sale.saleCount).label('count')).\ filter(db.and_(Sale.userId == user_id, Sale.drugId == drug.id, Sale.accountId == None)).group_by(Sale.drugId).first() if s: count = s.count return render_template('saleDrug.html', drug=drug, count=int(drug.count) - count) else: nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) id = request.form.get('id') price = request.form.get('price') saleCount = request.form.get('saleCount') sale = Sale(time=nowTime, userId=user.id, saleCount=saleCount, saleMoney=int(saleCount) * float(price), drugId=id) db.session.add(sale) db.session.commit() return redirect(url_for('showSaleDrug')) return redirect(url_for('login'))
def editSale(request, id): if request.method == 'GET': customers = database.users.find() departments = database.departments.find() products = database.products.find() sale = database.sales.find_one({"_id": ObjectId(id)}) return render(request, 'editSale.html', {'customers': customers, 'departments': departments, 'products': products, 'sale': sale}) else: customer = database.getUserById(request.POST['userId']) department = database.getDepartmentById(request.POST['departmentId']) product = database.getProductById(request.POST['productId']) sale = Sale(customer, department, product, request.POST['saleType'], request.POST['saleDescription']) database.sales.update_one({"_id": ObjectId(id)}, {'$set': sale.mongify()}) return redirect(reverse('index') + '?message=Changed Sale')
def enter_deposits(self): d = Daemon() unpaid = Sale.get_unpaid(session) logger.debug(json.dumps({"action": "enter deposits"})) # get list of pending orders with amounts and addresses for order in unpaid: if order.payment_address is None: continue # get total out total = Decimal(str(order.price)) address = order.payment_address received = d.get_receivedbyaddress(address, MINCONF) logger.info( json.dumps({ "action": "check received", "expected": str(total), "received": received, "address": address })) if (received >= total): logger.info( json.dumps({ "action": "payment complete", "order_id": str(order.id) })) # do things when payment received - mark a bucket paid, send an email, etc. order.paid = True session.add(order) session.commit()
def transaction(self, request_body): print(request_body) venda = Sale() db.session.add(venda) db.session.flush() for produto in request_body['produtos']: if produto["categoria"] == "bebida": produto_query = Produto.query.filter_by(nome=produto["nome"]).first() if int(produto["qtd"]) <= produto_query.qtd: produto_query.qtd -= int(produto["qtd"]) db.session.add(produto_query) else: return produto["nome"], produto_query.qtd item = Item_Venda() item.id_venda = venda.id item.produto = produto["nome"] item.qtd_produto = produto["qtd"] item.preco_produto = produto["preco"] db.session.add(item) db.session.commit() db.session.close() return "OK"
def upload_v1(conn, fileitem): import csv import repositories from models import Merchant, Sale, Upload upload = Upload() upload = repositories.UploadRepository(conn).create(upload) for row in csv.DictReader(fileitem.file, delimiter="\t"): merchant = Merchant(name=row['merchant name'].decode('utf-8'), address=row['merchant address'].decode('utf-8')) merchant = repositories.MerchantRepository(conn).create(merchant) sale = Sale(upload=upload, merchant=merchant, purchaser_name=row['purchaser name'].decode('utf-8'), description=row['item description'].decode('utf-8'), unit_price=row['item price'], count=row['purchase count']) sale = repositories.SaleRepository(conn).create(sale) upload.add_sale(sale) repositories.UploadRepository(conn).save(upload) return upload
def delete_sale(self, sale_id): sale = Sale.get(sale_id) for payment in Payment.select().join(Sale).where(Sale.id==sale_id): payment.delete_instance() for order in Order.select().join(Sale).where(Sale.id==sale_id): order.delete_instance() sale.delete_instance() self.insert_into_daily_tree()
def saleDrug(drugNum): # 判断用户是否登录 user_id = session.get('user_id') if user_id: user = User.query.filter(User.id == user_id).first() if user: # 判断是否是POST if request.method == 'GET': count = 0 drug = {} # 查找药品编号 卖出价格 数量 drugsfromDb = db.session.query( Drug.num, Drug.name, Drug.stockPrice, func.count('*').label('count')).filter( db.and_(Drug.num == drugNum, Drug.isSale == False)).first() salesfromDb = db.session.query( func.count('*').label('count')).filter( db.and_(Sale.drugNum == drugNum, Sale.userId == user_id)).first() drug['name'] = drugsfromDb.name drug['num'] = drugsfromDb.num drug['stockPrice'] = drugsfromDb.stockPrice if drugsfromDb.count - salesfromDb.count >= 0: count = drugsfromDb.count - salesfromDb.count drug['count'] = count return render_template('saleDrug.html', drug=drug) else: num = request.form.get('num') saleCount = request.form.get('saleCount') for index in range(int(saleCount)): nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) sale = Sale(time=nowTime, userId=user.id, drugNum=num) sale.user = user db.session.add(sale) db.session.commit() return redirect(url_for('showSaleDrug')) return redirect(url_for('login'))
def get(self): self.response.headers['Content-Type'] = 'text/plain' qry = Sale.query(Sale.excel_log_status == False) results = qry.fetch() #result_set = query.filter("excel_log_status=",False) #gc = gspread.login('*****@*****.**', 'insta_mojo_test') self.response.write(qry.count())
def delete_credit(self): if self.credits_tree.focus(): response = messagebox.askyesno("Atención, atención!", f"Quieres eliminar este {self.title.rstrip('s')}?", parent=self.credits_frame) if response: sale_id = self.credits_tree.item(self.credits_tree.focus())['values'][0] sale = Sale.get(sale_id) sale.delete_instance() self.insert_into_credits_tree(self.get_filter_params())
def insert_into_daily_tree(self, query_date=None): # Update title if not query_date: day = self.query_date.get() else: day = query_date self.day_tree_label['text'] = "Ventas del {} {} {} - {}".format( get_weekday(datetime.strptime(day, DATE_FORMAT)), day.split('-')[2], get_month_name(day), day.split('-')[0]) # Delete Previus Rows. self.day_tree.delete(*self.day_tree.get_children()) # Date. day_date = datetime.strptime(self.query_date.get(), DATE_FORMAT) day_sales = Sale.select().where(Sale.date==day_date).order_by(-Sale.is_finished) for sale in day_sales: orders = (Order .select() .join(Sale) .where(Sale.id == sale)) sale_total_orders = 0 for order in orders: sale_total_orders += order.price payments = (Payment .select() .join(Sale) .where(Sale.id == sale)) sale_total_payments = get_summary_payments(payments)[2] total = abs(sale_total_orders - sale_total_payments) if sale.is_finished: state = "Finalizado" total = sale_total_orders elif (sale_total_orders > sale_total_payments): state = "Crédito" else: state = "Vale" self.day_tree.insert( "", index='end', value=( sale.id, state, sale.description, number_to_str(total))) self.insert_into_summary_day()
def get(self): # try: gc = gspread.login('*****@*****.**', 'insta_mojo_test') wks = gc.open("Test").sheet1 qry = Sale.query(Sale.excel_log_status == True) line_count = qry.count() qry = Sale.query(Sale.excel_log_status == False) results = qry.fetch() line_count=line_count+2 for sale_item in results: try: logging.info("logging to excel , payment id" + str(sale_item.payment_id)) wks.update_cell(line_count,1,sale_item.currency) wks.update_cell(line_count,2,sale_item.buyer_phone) wks.update_cell(line_count,3,sale_item.offer_slug) wks.update_cell(line_count,4,sale_item.offer_title) wks.update_cell(line_count,5,sale_item.custom_fields) wks.update_cell(line_count,6,sale_item.payment_id) wks.update_cell(line_count,7,sale_item.buyer_name) wks.update_cell(line_count,8,sale_item.status) wks.update_cell(line_count,9,sale_item.buyer) wks.update_cell(line_count,10,sale_item.mac) wks.update_cell(line_count,11,sale_item.unit_price) wks.update_cell(line_count,12,sale_item.quantity) wks.update_cell(line_count,13,sale_item.fees) wks.update_cell(line_count,14,sale_item.amount) line_count+=1 except Exception as e: logging.error(str(e)) # raise e continue sale_item.excel_log_status=True sale_item.put() logging.debug("logged") self.response.http_status_message(200) '''
def add_sales_item_html(form): name = form.name.data.strip() quantity = form.quantity.data price = form.price.data date = form.date.data item = Item.query.filter_by(name=name).first() sale = Sale(item_id=item.get_id(), quantity=quantity, price=price, date=date) item.quantity -= quantity db.session.add(sale) db.session.commit() return True
def add_sales_item_json(data): name = data['name'] quantity = int(data['quantity']) price = int(data['price']) date = data['date'] item = Item.query.filter_by(name=name).first() sale = Sale(item_id=item.get_id(), quantity=quantity, price=price, date=date) item.quantity -= quantity db.session.add(sale) db.session.commit() return jsonify(status="success")
def scrape_for_new_sales(self): print('checking for new sales') r = requests.get(url=self.configuration['frenzy_endpoint'], verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError: print('[error] bad status {} on scrape'.format(r.status_code)) return False try: j = r.json() except json.JSONDecodeError: print('[error] couldnt decode json') return False for idx, fs in enumerate(j['flashsales']): id_to_check = fs['id'] if not Sale.objects(shopify_id=id_to_check): print('!!! NEW SALE FOUND !!!') print('<<<') print('[{}] [{} ] [{}]'.format( str(fs['id']).ljust(10), fs['password'], fs['title'].ljust(30))) print('[count: {}] [pickup: {}] [{}]'.format( str(fs['products_count']).ljust(3), str(fs['pickup']).ljust(5), fs['shipping_message'])) print('[deal: {}]'.format(fs['deal_sale'])) for fs_prod in fs['product_details']: print( '-> [{}] $[{}]'.format(fs_prod['title'].ljust(30), fs_prod['price_range']['min'])) print('>>> {}\n'.format(idx)) try: im_url = fs['image_urls'][0] except IndexError: im_url = None # new_sale = Sale( shopify_id=fs['id'], handle=fs['password'], image_url=im_url, title=fs['title'], start_time=datetime.strptime( fs['started_at'].split('.')[0], '%Y-%m-%dT%H:%M:%S'), is_hidden=fs['hidden'], is_sold_out=fs['sold_out'], is_pickup=fs['pickup'], shipping_message=fs['shipping_message']).save() if not new_sale: print('[error] couldnt save new sale to database') return False self.fire_discord(new_sale, new=True) new_sale.has_sent_new_alert = True new_sale.save() return True
def get_initial_scrape(self): print('getting initial scrape') r = requests.get(url=self.configuration['frenzy_endpoint'], verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError: print('[error] bad status {} on initial scrape'.format( r.status_code)) return False try: j = r.json() except json.JSONDecodeError: print('[error] couldnt decode json') return False print('initially found {} flashsales'.format(len(j['flashsales']))) for idx, fs in enumerate(j['flashsales']): try: im_url = fs['image_urls'][0] except IndexError: im_url = None new_sale = Sale(shopify_id=fs['id'], handle=fs['password'], description=fs['description'], image_url=im_url, title=fs['title'], start_time=datetime.strptime( fs['started_at'].split('.')[0], '%Y-%m-%dT%H:%M:%S'), is_hidden=fs['hidden'], is_sold_out=fs['sold_out'], is_pickup=fs['pickup'], shipping_message=fs['shipping_message']).save() if not new_sale: print('[error] couldnt save new sale to database') return False return True
def enter_deposits(self): d = Daemon() unpaid = Sale.get_unpaid(session) logger.debug(json.dumps({"action": "enter deposits"})) # get list of pending orders with amounts and addresses for order in unpaid: if order.payment_address is None: continue # get total out total = Decimal(str(order.price)) address = order.payment_address received = d.get_receivedbyaddress(address, MINCONF) logger.info( json.dumps( {"action": "check received", "expected": str(total), "received": received, "address": address} ) ) if received >= total: logger.info(json.dumps({"action": "payment complete", "order_id": str(order.id)})) # do things when payment received - mark a bucket paid, send an email, etc. order.paid = True session.add(order) session.commit()
def post(self): try: logging.debug("logging sale") logging.debug("payment_id" + str(self.request.get('payment_id'))) sale_item = Sale() sale_item.currency = self.request.get('currency') sale_item.buyer_phone = self.request.get('buyer_phone') sale_item.offer_slug = self.request.get('offer_slug') sale_item.offer_title = self.request.get('offer_title') sale_item.custom_fields = self.request.get('custom_fields') sale_item.payment_id = self.request.get('payment_id') sale_item.buyer_name = self.request.get('buyer_name') sale_item.status = self.request.get('status') sale_item.buyer = self.request.get('buyer') sale_item.mac = self.request.get('mac') sale_item.unit_price = float(self.request.get('unit_price')) sale_item.quantity = int(self.request.get('quantity')) sale_item.fees = float(self.request.get('fees')) sale_item.amount = float(self.request.get('amount')) sale_item.excel_log_status = False sale_item.put() logging.debug("logged") self.response.http_status_message(200) except Exception as e: logging.error(str(e)) self.error(500)
def __init__(self, parent, sale_id, rate): try: self.sale_id = sale_id self.parent = parent self.rate = rate self.orders = Order.select().where(Order.sale_id == sale_id) self.sale = Sale.get(Sale.id == self.sale_id) if not self.sale.client: raise Exception('No se encontró el cliente') self.resume_window = tk.Toplevel(padx=30, pady=50) # Title. title = 'Crear nota de entrega' self.resume_window.title(title) title_label = tk.Label(self.resume_window, text=title, font=('calibri', 18, 'bold')) title_label.grid(row=0, column=0, pady=(0, 20), columnspan=2) # Currency. curr_label = tk.Label(self.resume_window, text="Moneda", font=('calibri', 15)) curr_label.grid(row=1, column=0, sticky=tk.W) self.currency = tk.StringVar() currency_choices = ('', 'Bolívares', 'Dólares') self.currency.set(currency_choices[1]) curr_option = ttk.OptionMenu(self.resume_window, self.currency, *currency_choices) curr_option.grid(row=1, column=1, sticky=tk.E) # Sale Option. option_label = tk.Label(self.resume_window, text="Condición", font=('calibri', 15)) option_label.grid(row=2, column=0, pady=(10, 0), sticky=tk.W) self.option = tk.StringVar() option_choices = ('', 'DE CONTADO', 'CRÉDITO') self.option.set(option_choices[1]) curr_option = ttk.OptionMenu(self.resume_window, self.option, *option_choices) curr_option.grid(row=2, column=1, pady=(10, 0), sticky=tk.E) # IVA. iva_label = tk.Label(self.resume_window, text="Imprimir IVA", font=('calibri', 15)) iva_label.grid(row=3, column=0, pady=(10, 0), sticky=tk.W) self.iva = tk.StringVar() iva_choices = ('', 'No', 'Sí') self.iva.set(iva_choices[1]) iva_options = ttk.OptionMenu(self.resume_window, self.iva, *iva_choices) iva_options.grid(row=3, column=1, pady=(10, 0), sticky=tk.E) # IVA. iva_label = tk.Label(self.resume_window, text="Descontar IVA", font=('calibri', 15)) iva_label.grid(row=4, column=0, pady=(10, 0), sticky=tk.W) self.withoutIva = tk.StringVar() without_iva_choices = ('', 'No', 'Sí') self.withoutIva.set(without_iva_choices[1]) without_iva_options = ttk.OptionMenu(self.resume_window, self.withoutIva, *without_iva_choices) without_iva_options.grid(row=4, column=1, pady=(10, 0), sticky=tk.E) # Rate # Amount rate_label = tk.Label(self.resume_window, text="Tasa", font=('calibri', 15)) rate_label.grid(row=5, pady=(10, 0), sticky=tk.W) self.rate_entry = ttk.Entry(self.resume_window, width=13, font=('calibri', 15), justify='right') self.rate_entry.insert(0, self.rate) self.rate_entry.grid(row=5, column=1, pady=(10, 0), sticky=tk.E) create_button = tk.Button(self.resume_window, text="Crear", font=('calibri', 18, 'bold'), bd=1, relief=tk.RIDGE, bg='#54bf54', command=self.create_xlsx) create_button.grid(row=7, pady=(20, 0), sticky=tk.W + tk.E, columnspan=2) except Exception as err: messagebox.showerror("Error!", err, parent=self.parent)
def get_debt_color(self, client): client_sales = (Sale.select().join(Client).where(Client.id == client)) debt_sales = (client_sales.select().where(Sale.is_finished == False)) if debt_sales.count() > 0: return 'red' return 'black'
Book(id=2, title='Книга 2 поставщика №1', id_publisher=1), Book(id=3, title='Книга 3 поставщика №1', id_publisher=1), Book(id=4, title='Книга 1 поставщика №2', id_publisher=2), Book(id=5, title='Книга 2 поставщика №2', id_publisher=2), Book(id=6, title='Книга 1 поставщика №3', id_publisher=3) ]) session.commit() session.add_all([ Shop(id=1, name='Магазин №1'), Shop(id=2, name='Магазин №2') ]) session.commit() session.add_all([ Stock(id=1, count=3, id_book=1, id_shop=1), Stock(id=2, count=2, id_book=1, id_shop=2), Stock(id=3, count=5, id_book=2, id_shop=2), Stock(id=4, count=0, id_book=3, id_shop=1), Stock(id=5, count=2, id_book=4, id_shop=1), Stock(id=6, count=3, id_book=4, id_shop=2), Stock(id=7, count=4, id_book=6, id_shop=1) ]) session.commit() session.add_all([ Sale(id=1, price=15, date_sale='11.02.2020', id_stock=1, count=3), Sale(id=2, price=10, date_sale='11.03.2020', id_stock=1, count=2), Sale(id=3, price=13, date_sale='10.02.2020', id_stock=2, count=1), Sale(id=4, price=30, date_sale='11.04.2020', id_stock=3, count=3), Sale(id=5, price=14, date_sale='11.04.2020', id_stock=4, count=2) ]) session.commit()
def insert_into_credits_tree(self, params): self.credits_tree.delete(*self.credits_tree.get_children()) credits = [] vales = [] unfinished_sales = (Sale.select().where(Sale.is_finished == False)) client_identity_card = params['pre_id'] + "-" + params['identity'] if params['identity']: unfinished_sales = (unfinished_sales .select() .join(Client) .where(Client.identity_card .contains(client_identity_card))) elif params['name']: unfinished_sales = (unfinished_sales .select() .join(Client) .where(Client.name .contains(params['name']))) for sale in unfinished_sales: sale_total_orders = 0 sale_total_payments = 0 orders = (Order .select() .join(Sale) .where(Sale.id == sale) ) for order in orders: sale_total_orders += order.price payments = (Payment .select() .join(Sale) .where(Sale.id == sale)) sale_total_payments = get_summary_payments(payments)[2] total = abs(sale_total_orders - sale_total_payments) if (sale_total_orders > sale_total_payments): credits.append([sale,total]) else: vales.append([sale,total]) total_credits = 0 total_vales = 0 if not self.vale: for credit in credits: sale = credit[0] if not sale.client: print(sale.id) total = credit[1] total_credits += total self.total_label['text'] = number_to_str(total_credits) + "$" self.credits_tree.insert( "", index='end', value=( sale.id, (date.today() - sale.date).days, sale.client.name, sale.client.identity_card, sale.description, number_to_str(total) ) ) else: for vale in vales: sale = vale[0] total = vale[1] total_vales += total self.total_label['text'] = number_to_str(total_vales) + "$" self.credits_tree.insert( "", index='end', value=( sale.id, (date.today() - sale.date).days, sale.client.name, sale.client.identity_card, sale.description, number_to_str(total) ) )
def addSale(self, name, sale): productOnSale = [] productOnSale.append(address) newProductOnSale = Sale(name, self.myAddress) self.session.add(newProductOnSale) self.session.commit()
def get_sales_history(): global con c = con.cursor() c.execute("""SELECT * FROM sales_history""") history = c.fetchall() return tuple(map(lambda sale: Sale(time=sale.time, _id=sale.id)))
from models import Production, Customer, Seller, Administrator, Orders, Sale # print (Production.order_production_data(2)) # print(Production.edit(26,"图书","喜为你疾,药石无医","31.4","20","wei.png","This is i like book","新品上架")) # print(Production.basket_production_data(2)) # print(Seller.add_new_production(1,28,"0.9","200-20")) # print(Seller.delete_production(2,25)) # print(Seller.query_seller_product(2)) # print(Production.all_query()) # print(Orders.add_from_basket(14)) # print(Production.query_by_type_type1("图书", "新品上架")) # print(Seller.search_id_by_name('john')) # print(Seller.change_production(2,25,'0.9','0')) # print(Production.basket_production_data(2)) print(Sale.get_price_full_sub(Production.basket_production_data(2)))
def upload(): file_types = [('sale', 'Sale Details'), ('cancel', 'Cancels'), ('clawback', 'Clawbacks'), ('agent', 'Agent List'),] if request.method=='POST': f = request.files['upload'] file_type = request.form['file_type'] data = _parse_file(f, file_type) if file_type == 'sale': for sale in data: try: s = Sale(sale_status='Unverified', **sale) except AgentNotFoundError: db_session.rollback() flash('Agent {} could not be found.'.format(sale['agent_name']), 'danger') else: db_session.add(s) try: db_session.commit() except IntegrityError: db_session.rollback() flash('NMI {} has already been imported.'.format(sale['nmi_mirn']), 'danger') else: ssh = SaleStatusHistory(sale=s, status='Unverified') db_session.add(ssh) db_session.commit() elif file_type == 'cancel': for sale in data: sales = Sale.query.filter(Sale.nmi_mirn == sale['nmi_mirn']) if sales.count(): s = sales.first() if s.sale_status != 'Cancelled': s.sale_status = 'Cancelled' ssh = SaleStatusHistory(sale=s, status='Cancelled') db_session.add(ssh) db_session.commit() else: flash('NMI {} is already cancelled or clawed back.'.format(sale['nmi_mirn']), 'danger') else: flash('NMI {} could not be found for cancellation.'.format(sale['nmi_mirn']), 'danger') elif file_type == 'clawback': for sale in data: sales = Sale.query.filter(Sale.nmi_mirn == sale['nmi_mirn'], Sale.clawback_value == None) if sales.count(): s = sales.first() s.sale_status = 'Clawback' s.clawback_value = sale['commission_value'] ssh = SaleStatusHistory(sale=s, status='Clawback') db_session.add(ssh) db_session.commit() else: flash('NMI {} could not be found or is already clawed back.'.format(sale['nmi_mirn']), 'danger') elif file_type == 'agent': for agent in data: a = Agent(**agent) db_session.add(a) try: db_session.commit() except IntegrityError: db_session.rollback() flash('SIDN {} has already been imported.'.format(agent['sidn']), 'danger') return redirect(url_for('upload')) context = {'file_types': file_types} return render_template('upload.html', **context)
def create_sale(self): try: def create_orders(sale): for order_index in self.order_tree.orders_tree.get_children(): order_values = self.order_tree.orders_tree.item(order_index)['values'] product_id = order_values[1] amount = order_values[3] price = get_dollars(order_values[5]) discount = int(order_values[7]) Order.create( product=product_id, sale=sale, amount=amount, date=datetime.strptime(self.new_sale_date_entry.get(), DATE_FORMAT), price=price, discount=discount ) def create_payments(sale): for payment_index in self.payment_handler.payments_tree.get_children(): payment_values = self.payment_handler.payments_tree.item(payment_index)['values'] Payment.create( sale=sale, date=datetime.strptime(payment_values[2], DATE_FORMAT), type=Payment.TYPES[payment_values[3]], amount=string_to_float(payment_values[4]), currency=Payment.CURRENCIES[payment_values[5]], method=Payment.METHODS[payment_values[6]], rate= string_to_float(payment_values[7]), account=Payment.ACCOUNTS[payment_values[8]] ) if not self.order_tree.orders_tree.get_children(): raise Exception("No puedes crear una venta sin productos.") total_sale = float(self.order_tree.total_orders_usd) total_payments = float(self.payment_handler.total_payments) if es_casi_igual(total_sale, total_payments): client = self.client_handler.client sale = Sale.create( client=client, date=datetime.strptime(self.new_sale_date_entry.get(), DATE_FORMAT), description=self.new_sale_desc_text.get(), is_finished=True, finished_date=datetime.now()) create_orders(sale) create_payments(sale) self.clear_new_sale_frame(creating=True) self.insert_into_daily_tree() self.insert_into_summary_day() else: title = "Pagos insuficientes!" message = "¿Desea crear esta venta como CRÉDITO?" if total_sale < total_payments: title = "Exceso de Pago!" message = "Desea crear esta venta como VALE?" response = messagebox.askyesno(title, message, parent=self.root) client = self.client_handler.client if response: if not client: message = message.split(" ")[-1].rstrip("?") raise Exception(f"No puedes crear un {message} sin cliente!") sale = Sale.create( client=client, date=datetime.strptime(self.new_sale_date_entry.get(), DATE_FORMAT), description=self.new_sale_desc_text.get()) create_orders(sale) create_payments(sale) self.clear_new_sale_frame(creating=True) self.insert_into_daily_tree() self.insert_into_summary_day() except Exception as err: messagebox.showerror("Error", err, parent=self.root)
def __init__(self, sale_id, query_date, rate, callbacks=[], params=None): self.params = params self.query_date = query_date self.rate = rate self.callbacks = callbacks self.sale = Sale.get(Sale.id == sale_id) finished = "" if self.sale.is_finished: finished = " - Finalizada." # New Window self.detail_sale_window = tk.Toplevel(width=700, height=700, padx=30, pady=30) self.detail_sale_window.title(f"Venta {sale_id}") # MENU menubar = tk.Menu(self.detail_sale_window) resume_menu = tk.Menu(menubar, tearoff=0, font=('arial', 15)) self.detail_sale_window.title(f"Venta {sale_id}") resume_menu.add_command( label="Crear", command=lambda: CreateResume(self.detail_sale_window, sale_id, self .rate)) resume_menu.add_command(label="Imprimir") menubar.add_cascade(label="Notas de entrega", menu=resume_menu) self.detail_sale_window.config(menu=menubar) # Title. filters_title = tk.Label(self.detail_sale_window, text=f"Venta {sale_id}" + finished, font=('calibri', 18, 'bold')) filters_title.grid(row=0, columnspan=2, pady=(10, 20)) # Frame frame = tk.Frame(self.detail_sale_window) frame.grid(row=1, column=0, columnspan=2) # Date date_label = tk.Label(frame, text="Fecha", font=('calibri', 15)) date_label.grid(row=0, column=0) self.sale_date_entry = ttk.Entry(frame, width=10, font=('calibri', 15)) self.sale_date_entry.insert(0, self.sale.date.strftime(DATE_FORMAT)) self.sale_date_entry.grid(row=0, column=1) # Description desc_label = tk.Label(frame, text="Descripción", font=('calibri', 15)) desc_label.grid(row=0, column=2, padx=(3, 0)) self.sale_desc_text = ttk.Entry(frame, width=52, font=('calibri', 15)) self.sale_desc_text.insert(0, self.sale.description) self.sale_desc_text.grid(row=0, column=3) # Client client_frame = tk.Frame(self.detail_sale_window) client_frame.grid(row=2, column=0, columnspan=2, pady=(20, 0), sticky=tk.W) self.client_handler = ClientHandler(client_frame, self.sale.client) if not self.client_handler.client: self.client_handler.display_client_checker() else: self.client_handler.display_client_detail(self.sale.client) # Total total_frame = tk.Frame(self.detail_sale_window) total_frame.grid(row=4, column=1, pady=(20, 0), sticky=tk.E) # Orders orders_frame = tk.Frame(self.detail_sale_window) orders_frame.grid(row=3, column=0, columnspan=2, sticky=tk.W) self.order_tree = OrderTree(orders_frame, total_frame=total_frame, sale=self.sale) # Payments payments_frame = tk.Frame(self.detail_sale_window) payments_frame.grid(row=4, column=0, pady=(10, 0), sticky=tk.W) self.payments_handler = PaymentHandler() self.payments_handler.display_total_payments(total_frame, True) self.payments_handler.display_payments_tree( payments_frame, True, # callbacks=[self.calculate_remaining] ) self.payments_handler.insert_into_payments_sale_tree(sale_id) # Buttons. add_product_button = tk.Button( orders_frame, text="Agregar", font=('calibri', 12), bd=1, relief=tk.RIDGE, bg='#54bf54', command=lambda: ProductsWin( self.rate, on_create=self.order_tree.insert_into_orders_tree, callbacks=[self.order_tree.calculate_total])) add_product_button.grid(row=2, column=0, sticky=tk.W) add_payment_button = tk.Button( payments_frame, text="+ Pago", font=('calibri', 15), bd=1, relief=tk.RIDGE, bg='#54bf54', command=lambda: self.payments_handler.add_payment_window( self.query_date, self.rate, False, True)) add_payment_button.grid(row=3, column=0, sticky=tk.W) add_return_button = tk.Button( payments_frame, text="+ Vuelto", font=('calibri', 15), bd=1, relief=tk.RIDGE, bg='#54bf54', command=lambda: self.payments_handler.add_payment_window( self.query_date, self.rate, True, True)) add_return_button.grid(row=3, column=0, sticky=tk.W, padx=(100, 0)) update_sale_button = tk.Button(self.detail_sale_window, text="Guardar Venta", font=('calibri', 18, 'bold'), bd=1, relief=tk.RIDGE, bg='#54bf54', command=self.update_sale) update_sale_button.grid(row=5, columnspan=2, pady=(35, 15))