def set_data_for(self, value=None): products = [(Product.get(id=rpt.product_id).name) for rpt in Report.select(fn.Distinct(Report.product))] if value: products = [(prod.name) for prod in Product.select().where(Product.name.contains(value)) .where(Product.name << products).order_by(Product.name.desc())] self.data = [(prd, "") for prd in products]
def save_report(self): ''' add operation ''' # entete de la facture self.table_out.changed_value() if not self.table_out.isvalid: return False date_out = str(self.date_out.text()) datetime_ = date_to_datetime(date_out) self.current_store = self.liste_store[self.box_store.currentIndex()] values_t = self.table_out.get_table_items() for qty, name in values_t: rep = Reports(type_=Reports.S, store=self.current_store, date=datetime_, product=Product.get(name=name), qty_use=int(qty)) try: rep.save() except: self.parent.Notify( u"Ce mouvement n'a pas pu être enrgistré dans les raports", "error") return False self.parent.change_context(GReportViewWidget) self.parent.Notify(u"La sortie des articles avec succès", "success")
def details(request, id): p = Product.get(id) if not p: raise Http404("Product cannot be found") return render_to_response('store/details.html', { 'p': p }, RequestContext(request))
def product_detail(request, values): product = Product.get(pk=values.get('id')) if product is None: raise NotFound() return render_template('product.html', {'product': product})
def set_data_for(self, value=None): products = [(Product.get(id=rpt.product_id).name) for rpt in Report.select(fn.Distinct(Report.product))] if value: products = [(prod.name) for prod in Product.select().where( Product.name.contains(value)).where( Product.name << products).order_by(Product.name.desc())] self.data = [(prd, "") for prd in products]
def product_delete(request, values): product = Product.get(pk=values.get('id')) if product is None: raise NotFound() product.delete() return redirect(product.shop.get_absolute_url())
def many_to_many_query(): categories = Category.select() for category in categories: print(">>" + str(category)) for product in category.products: print(product) producto = Product.get(Product.name == 'Jamon') for category in producto.categories: print(category.category.name)
def test_product_id(): """ Test that we get product data by product id when it's passed as a URL parameter """ product = Product.get() restApp = TestApp(webservice.app.wsgifunc(*[])) req = restApp.get("/product/{0}/".format(product.product_id)) product_data = json.loads(req.body) assert product.name == product_data['name']
def import_data(): session = Session() client = OpenFoodFactsApi() categories = client.get_categories() stores = client.get_stores() # product_schema = ProductSchema() # insert data to Category for store in stores: store1 = Store(name=store) session.add(store1) for cat in categories: category1 = Category(name=cat) print(category1) products = client.get_products(cat) # insert data to Product, Store, Brand for product in products: if product.get("product_name") != "": b = session.query(Brand).filter( Brand.name == product.get("brands")).first() if not b: brand = Brand(name=product.get("brands"), label=product.get("label")) session.add(brand) b = session.query(Brand).filter( Brand.name == product.get("brands")).first() product = Product( name=product.get("product_name"), nutriscore=product.get("nutrition_grades"), nova=product.get("nova_groups_tags"), brand=b, url=product.get("url"), barcode=product.get("code")) product.categories.append(category1) product.stores.append(store1) print(product) session.add(product) session.commit() # dump_data = product_schema.dump(product) # load_data = product_schema.load(dump_data, session=session) session.close()
def changed_value(self, refresh=False): """ Calcule les Resultat """ self.mtt_ht = 0 # self.button.setEnabled(False) for row_num in xrange(0, self.data.__len__()): product = Product.get( Product.name == unicode(self.item(row_num, 0).text())) last_report = product.last_report last_price = product.last_price() qtremaining = last_report.remaining selling_price = last_price invoice_date = unicode(self.parent.invoice_date.text()) qtsaisi = is_int(self.cellWidget(row_num, 1).text()) pusaisi = is_int(self.cellWidget(row_num, 2).text()) if check_is_empty(self.parent.num_invoice): return if check_is_empty(self.parent.name_client_field.lineEdit()): return # if check_field(self.parent.invoice_date, # "Le {} est Inférieure à la date de la dernière rapport (<b>{}</b>)".format(date_to_datetime(invoice_date), last_report.date), (last_report.date > date_to_datetime(invoice_date))): # return if (pusaisi and check_is_empty(self.cellWidget(row_num, 1))): return if (pusaisi and check_is_empty(self.cellWidget(row_num, 2))): return if check_field( self.cellWidget(row_num, 1), u"<b>{}</b> est supérieur à la quantité restante (<b>{}</b>)" .format(qtsaisi, qtremaining), qtremaining < qtsaisi): return if check_field( self.cellWidget(row_num, 2), u"<b>{}</b> est inférieure au prix minimum de vente<b> {} CFA</b>" .format(pusaisi, selling_price), pusaisi < selling_price): print("E") # return montant = (qtsaisi * pusaisi) self.mtt_ht += montant self.setItem(row_num, 3, TotalsWidget(formatted_number(montant))) self._update_data(row_num, [qtsaisi, pusaisi, self.mtt_ht]) self.setItem(row_num + 1, 3, TotalsWidget(formatted_number(self.mtt_ht))) typ = self.parent.liste_type_invoice[ self.parent.box_type_inv.currentIndex()] self.paid_amount_field.setText( str(self.mtt_ht) if typ == Invoice.TYPE_BON else "0") self.button.setEnabled(True)
def _update_products(self): counter = 0 updated_prices = 0 update_names = 0 created_products = 0 for key, value in self.df.iterrows(): if counter == 0: counter += 1 continue code = value[2] if str(code) != 'nan': brand = value[0] refence = value[1] price = format_float(value[5]) name = value[3].replace("Ð", "Ñ").replace("║", "|") try: product = Product.get(code=code) except Exception: Product.create(brand=brand, reference=refence, code=code, name=name, price=price) counter += 1 created_products += 1 continue if product.name != name: product.name = name product.save() update_names += 1 if es_casi_igual(product.price, price): pass else: # Actualizar precio. product.price = price product.save() updated_prices += 1 counter += 1 if updated_prices or update_names or created_products: messagebox.showinfo( "Precios Actualizados!", f"{updated_prices} precios actualizados, {update_names} nombre modificados, {created_products} productos nuevos." )
def changed_value(self, refresh=False): """ Calcule les Resultat """ self.mtt_ht = 0 # self.button.setEnabled(False) for row_num in xrange(0, self.data.__len__()): product = Product.get( Product.name == unicode(self.item(row_num, 0).text())) last_report = product.last_report last_price = product.last_price() qtremaining = last_report.remaining selling_price = last_price invoice_date = unicode(self.parent.invoice_date.text()) qtsaisi = is_int(self.cellWidget(row_num, 1).text()) pusaisi = is_int(self.cellWidget(row_num, 2).text()) if check_is_empty(self.parent.num_invoice): return if check_is_empty(self.parent.name_client_field.lineEdit()): return # if check_field(self.parent.invoice_date, # "Le {} est Inférieure à la date de la dernière rapport (<b>{}</b>)".format(date_to_datetime(invoice_date), last_report.date), (last_report.date > date_to_datetime(invoice_date))): # return if (pusaisi and check_is_empty(self.cellWidget(row_num, 1))): return if (pusaisi and check_is_empty(self.cellWidget(row_num, 2))): return if check_field(self.cellWidget(row_num, 1), u"<b>{}</b> est supérieur à la quantité restante (<b>{}</b>)".format( qtsaisi, qtremaining), qtremaining < qtsaisi): return if check_field(self.cellWidget(row_num, 2), u"<b>{}</b> est inférieure au prix minimum de vente<b> {} CFA</b>".format( pusaisi, selling_price), pusaisi < selling_price): print("E") # return montant = (qtsaisi * pusaisi) self.mtt_ht += montant self.setItem(row_num, 3, TotalsWidget(formatted_number(montant))) self._update_data(row_num, [qtsaisi, pusaisi, self.mtt_ht]) self.setItem( row_num + 1, 3, TotalsWidget(formatted_number(self.mtt_ht))) typ = self.parent.liste_type_invoice[ self.parent.box_type_inv.currentIndex()] self.paid_amount_field.setText( str(self.mtt_ht) if typ == Invoice.TYPE_BON else "0") self.button.setEnabled(True)
def edit(request, id): u = auth.get_current_user(request) if u.is_admin: p = Product.get(id) if not p: raise Http404("Product cannot be found") elif request.method == "POST": form = ProductForm(data=request.POST, instance=p) if form.is_valid(): form.save() else: form = ProductForm(instance=p) return render_to_response('store/edit.html', { 'form': form }, RequestContext(request)) return HttpResponseRedirect(reverse('store-index'))
def relacion2(): #Relacion Muchos a Muchos categories = Category.select() for category in categories: print(f'>> {category}') for product in category.products: print(product) print('*' * 50) jamon = Product.get(Product.name == 'Jamon') for category in jamon.categories: print(category) print('*' * 50) liquido = Category.get(Category.name == 'Liquidos') for product in liquido.products: print(product)
def section_choice_handler(text: str, current_section: str) -> Tuple[str, BytesIO] or bool: """ Обрабатывает запросы в конкретном разделе :param text: текст сообщения :param current_section: название раздела :return: текст отправляемого сообщения и файловый объект картинки, или False в случае некорректного запроса """ products = select(p.name for p in Product if p.section.name == current_section) for product in products: if product.lower() in text.lower(): product_obj = Product.get(name=product) image = open_image(product_obj.image) log.debug(f'Ответ: {product_obj.description}') return product_obj.description, image else: return False
def save_b(self): ''' add operation ''' # entete de la facture if not self.table_buy.isvalid: return False owner = Owner.get(Owner.islog == True) date = str(self.date.text()) values_t = self.table_buy.get_table_items() buy = Buy() # buy.date = datetime_ buy.provd_or_clt = \ ProviderOrClient.get_or_create( "Fournisseur", 000000, ProviderOrClient.FSEUR) buy.owner = owner try: buy.save() err = False except: raise raise_error("Erreur", u"Impossible d'enregistrer l'entête de la facture") return False for name, qty, cost_buying, selling_price in values_t: rep = Report() rep.buy = buy rep.type_ = Report.E rep.store = 1 rep.date = date_to_datetime(date) rep.product = Product.get(name=name) rep.qty = int(qty) rep.cost_buying = int(cost_buying) rep.selling_price = int(selling_price) try: rep.save() except Exception as e: print(e) err = True if err: buy.delete_instance() raise_error( "Erreur", u"Ce mouvement n'a pas pu etre " u"enregistré dans les rapports") return False else: self.parent.Notify(u"L'entrée des articles avec succès", "success") self.change_main_context(BuyShowViewWidget, buy=buy)
def save_b(self): ''' add operation ''' # entete de la facture if not self.table_buy.isvalid: return False owner = Owner.get(Owner.islog == True) date = str(self.date.text()) values_t = self.table_buy.get_table_items() buy = Buy() # buy.date = datetime_ buy.provd_or_clt = \ ProviderOrClient.get_or_create( "Fournisseur", 000000, ProviderOrClient.FSEUR) buy.owner = owner try: buy.save() err = False except: raise raise_error( "Erreur", u"Impossible d'enregistrer l'entête de la facture") return False for name, qty, cost_buying, selling_price in values_t: rep = Report() rep.buy = buy rep.type_ = Report.E rep.store = 1 rep.date = date_to_datetime(date) rep.product = Product.get(name=name) rep.qty = int(qty) rep.cost_buying = int(cost_buying) rep.selling_price = int(selling_price) try: rep.save() except Exception as e: print(e) err = True if err: buy.delete_instance() raise_error("Erreur", u"Ce mouvement n'a pas pu etre " u"enregistré dans les rapports") return False else: self.parent.Notify(u"L'entrée des articles avec succès", "success") self.change_main_context(BuyShowViewWidget, buy=buy)
def product_update(request, values): shop = Shop.get(slug=values.get('slug')) product = Product.get(pk=values.get('id')) product_categories = [category.id for category in product.get_categories()] if shop is None or product is None: categories = Category.all() return render_template( 'product-form.html', { 'categories': categories, 'shop': shop, 'product': product, 'product_categories': product_categories, }) name = request.form.get('name') price = request.form.get('price') description = request.form.get('description') categories = request.form.getlist('category') image = request.files.get('image') if image and image.filename != product.image: if allowed_image(image.filename): image_name = secure_filename(image.filename) image.save(os.path.join(MEDIA_ROOT, image_name)) if product.image != '': os.remove(os.path.join(MEDIA_ROOT, product.image)) else: image_name = '' else: image_name = '' product.update( name=name or product.name, price=price or product.price, description=description or product.description, image=image_name or product.image, ) # TODO: update categories return redirect(f'/shops/{shop.slug}/products/{product.id}')
def refresh_(self, idd): self.prod = Product.get(id=idd) rest_by_store = "" for store in Store.select(): remaining, nbr_parts = store.get_remaining_and_nb_parts(self.prod) if remaining < 10: color_style = 'color: DarkGreen' if remaining <= 5: color_style = 'color: LightCoral' if remaining <= 2: color_style = 'color: red; text-decoration: blink' if remaining >= 10: color_style = 'color: LimeGreen;' color_style = color_style + \ "; border:3px solid green; font-size: 15px" if Store.select().count() == 1: rest_by_store += """ <p><strong style='{color_style}'> {remaining} </strong><i>pièces</i></p> """.format(color_style=color_style, remaining=remaining) else: rest_by_store += """<li> {store}: <strong style='{color_style}'> {nbr_parts} </strong><i>pièces</i> <b>{remaining} </b><i>carton</i> </li>""".format(store=store.name, color_style=color_style, remaining=remaining, nbr_parts=nbr_parts * remaining) width = height = 50 if self.prod.image_link: self.image_btt.setText("Zoom") width = 200 height = 100 self.info_box.setText(u"""<h2>{name}</h2> <h4>Quantité restante:</h4> <ul>{remaining}</ul> """.format(name=self.prod.name, remaining=rest_by_store)) self.image.setText("""<img src="{image}" width='{width}' height='{height}'>""".format(image=self.prod.image_link, width=width, height=height))
def delete_product(request, product_code, *args, **kwargs): resp = { "status": 400, "success": False, "message": "", } try: product = Product.get(where={'code': product_code}) if not product: raise Exception('No product for the given code') Product.delete(where={'code': product_code}) resp["status"] = 200 resp["success"] = True resp["message"] = "Success" except Exception as e: resp['message'] = str(e) return resp
def refresh_(self, idd): self.prod = Product.get(id=idd) self.nameLabel.setText((u"<h4>Article:</h4>")) self.name.setText(u"<h6>{name}</h6>".format(name=self.prod.name.title())) rest_by_store = "" for store in Store.select(): remaining, nbr_parts = store.get_remaining_and_nb_parts(self.prod) if remaining < 10: color_style = 'color: DarkGreen' if remaining <= 5: color_style = 'color: LightCoral' if remaining <= 2: color_style = 'color: red; text-decoration: blink' if remaining >= 10: color_style = 'color: LimeGreen;' color_style = color_style + "; border:3px solid green; font-size: 15px" rest_by_store += u"<div> {store}: <strong style='{color_style}'>" \ u" {remaining} </strong> ({nbr_parts} pièces)"\ u"</div>".format(store=store.name, color_style=color_style, remaining=remaining, nbr_parts=nbr_parts) self.store.setText(u"<h4><u>Quantité restante</u>:</h4> \ {remaining}</ul>".format(remaining=rest_by_store)) self.imagelabel.setText(u"<b>Pas d'image<b>") self.image.setStyleSheet("") if self.prod.image_link: self.imagelabel.setText(u"<b><u>Image</u></b>") self.image.setStyleSheet("background: url({image})" " no-repeat scroll 20px 110px #CCCCCC;" "width: 55px".format(image=self.prod.image_link))
Category.create(name='Carnes', description='carnes') def insert_categories_product(): CategoriesProduct.create(category_id=1, product_id=5) CategoriesProduct.create(category_id=1, product_id=5) CategoriesProduct.create(category_id=1, product_id=5) CategoriesProduct.create(category_id=2, product_id=4) CategoriesProduct.create(category_id=3, product_id=3) CategoriesProduct.create(category_id=4, product_id=2) CategoriesProduct.create(category_id=4, product_id=2) CategoriesProduct.create(category_id=5, product_id=1) def create_schema(): create_table() insert_users() insert_stores() insert_products() insert_categories() insert_categories_product() if __name__ == '__main__': buze = Product.get(Product.name == 'Buzenits') buze.delete_instance(recursive=True)
def deleted_recursive(): jamon = Product.get(Product.name == 'Jamon') jamon.delete_instance(recursive=True)
def create_or_update_product(self, product_id=None, callback={}): title = "Nuevo Producto" if product_id: product = Product.get(Product.id == product_id) title = f"Producto - {product_id}" detail_product_window = tk.Toplevel(width=700, height=700, padx=30, pady=30) detail_product_window.title(title) # Title. title_label = tk.Label(detail_product_window, text=title, font=('calibri', 18, 'bold')) title_label.grid(row=0, columnspan=2, pady=(10, 20)) # Name. name_label = tk.Label(detail_product_window, text="Nombre", font=('calibri', 15, 'bold')) name_label.grid(row=1, column=0, pady=(0, 5)) name_entry = ttk.Entry(detail_product_window, width=25, font=('calibri', 15)) name_entry.grid(row=2, column=0, pady=(0, 15)) # Reference. reference_label = tk.Label(detail_product_window, text="Referencia", font=('calibri', 15, 'bold')) reference_label.grid(row=3, column=0, pady=(0, 5)) reference_entry = ttk.Entry(detail_product_window, width=25, font=('calibri', 15)) reference_entry.grid(row=4, column=0, pady=(0, 15)) # Brand. brand_label = tk.Label(detail_product_window, text="Marca", font=('calibri', 15, 'bold')) brand_label.grid(row=5, column=0, pady=(0, 5)) brand_entry = ttk.Entry(detail_product_window, width=25, font=('calibri', 15)) brand_entry.grid(row=6, column=0, pady=(0, 15)) # Code. code_label = tk.Label(detail_product_window, text="Código", font=('calibri', 15, 'bold')) code_label.grid(row=7, column=0, pady=(0, 5)) code_entry = ttk.Entry(detail_product_window, width=25, font=('calibri', 15)) code_entry.grid(row=8, column=0, pady=(0, 15)) # Price. price_label = tk.Label(detail_product_window, text="Precio $", font=('calibri', 15, 'bold')) price_label.grid(row=9, column=0, pady=(0, 5)) price_entry = ttk.Entry(detail_product_window, width=25, font=('calibri', 15)) price_entry.grid(row=10, column=0, pady=(0, 15)) # Stock. stock_label = tk.Label(detail_product_window, text="En inventario", font=('calibri', 15, 'bold')) stock_label.grid(row=11, column=0, pady=(0, 5)) stock_entry = ttk.Entry(detail_product_window, width=25, font=('calibri', 15)) stock_entry.insert(0, 0) stock_entry.grid(row=12, column=0, pady=(0, 15)) # Functions. def create_product(): try: Product.create(name=name_entry.get().upper(), reference=reference_entry.get().upper(), brand=brand_entry.get().upper(), code=code_entry.get(), price=float(price_entry.get()), stock=int(stock_entry.get())) detail_product_window.destroy() except Exception as err: messagebox.showerror("Error", err, parent=detail_product_window) def update_product(): try: product.name = name_entry.get().upper() product.reference = reference_entry.get().upper() product.brand = brand_entry.get().upper() product.code = code_entry.get() product.price = float(price_entry.get()) product.stock = int(stock_entry.get()) product.save() detail_product_window.destroy() except Exception as err: messagebox.showerror("Error", err, parent=detail_product_window) # Buttons. if not product_id: create_product_button = tk.Button(detail_product_window, text="Agregar", font=('calibri', 15, 'bold'), bd=1, relief=tk.RIDGE, bg='#54bf54', command=create_product) create_product_button.grid(row=13, column=0, sticky=tk.W + tk.E, padx=15, pady=15) else: update_product_button = tk.Button(detail_product_window, text="Guardar", font=('calibri', 15, 'bold'), bd=1, relief=tk.RIDGE, bg='#54bf54', command=update_product) update_product_button.grid(row=13, column=0, sticky=tk.W + tk.E, padx=15, pady=15) name_entry.insert(0, product.name) reference_entry.insert(0, product.reference) brand_entry.insert(0, product.brand) code_entry.insert(0, product.code) price_entry.insert(0, product.price) stock_entry.insert(0, product.stock)
def remove(name): product = Product.get(Product.name == name) product.delete_instance() return f'Product {product.name} removed!'
def delete(id): try: product = Product.get(Product.id == id) return product.delete_instance() except: return 'Product not found'
Category.new(name='Carnes', description='carnes') def insert_categories_products(): CategoriesProducts.new(categorie=1, product=2) CategoriesProducts.new(categorie=1, product=5) CategoriesProducts.new(categorie=1, product=7) CategoriesProducts.new(categorie=2, product=3) CategoriesProducts.new(categorie=3, product=6) CategoriesProducts.new(categorie=4, product=4) CategoriesProducts.new(categorie=4, product=8) CategoriesProducts.new(categorie=5, product=3) def create_schema(): create_tables() create_users() create_stores() create_products() insert_categories() insert_categories_products() if __name__ == "__main__": jamon = Product.get(Product.name == 'Jamon') jamon.delete_instance(recursive=True)
def purchase(request, id): return purchase_do(request, Product.get(id))
def remove_product(product_id): product = Product.get(UserProduct.product_id == product_id) product.delete_instance()
def save_b(self): ''' add operation ''' # entete de la facture print("save") if not self.is_valide(): return invoice_date = unicode(self.invoice_date.text()) num_invoice = int(self.num_invoice.text()) invoice_type = self.liste_type_invoice[ self.box_type_inv.currentIndex()] lis_error = [] invoice = Invoice() try: self.owner = Owner.get(Owner.islog == True) except: lis_error.append("Aucun utilisateur est connecté <br/>") paid_amount = int(self.table_invoice.paid_amount_field.text()) try: clt = ProviderOrClient.get_or_create( self.name_client, int(self.phone.replace(" ", "")), ProviderOrClient.CLT) except ValueError: field_error(self.name_client_field, "Nom, numéro de téléphone du client") invoice.number = num_invoice invoice.owner = self.owner invoice.client = clt invoice.location = "Bamako" invoice.type_ = invoice_type invoice.subject = "" invoice.paid_amount = paid_amount invoice.tax = False try: invoice.save() if int(paid_amount) != 0 or invoice_type == Invoice.TYPE_BON: Refund(type_=Refund.DT, owner=self.owner, amount=paid_amount, date=date_to_datetime(invoice_date), provider_client=clt, invoice=Invoice.get(number=num_invoice)).save() except Exception as e: invoice.deletes_data() lis_error.append( "Erreur sur l'enregistrement d'entête de facture<br/>") return False # Save invoiceitems invoice = Invoice.get(Invoice.number == num_invoice) for name, qty, price in self.table_invoice.get_table_items(): rep = Report() product = Product.get(Product.name == name) rep.store = 1 rep.product = product rep.invoice = invoice rep.type_ = Report.S rep.cost_buying = int(product.last_report.cost_buying) rep.date = date_to_datetime(invoice_date) rep.qty = int(qty) rep.selling_price = int(price) try: rep.save() except Exception as e: lis_error.append(e) if lis_error != []: invoice.delete_instance() self.parent.Notify(lis_error, "error") return False else: self.parent.Notify("Facture Enregistrée avec succès", "success") self.table_invoice._reset() try: self.parent.open_dialog(ShowInvoiceViewWidget, modal=True, opacity=100, table_p=self, invoice_num=invoice.number) except Exception as e: print(e)
def save_b(self): ''' add operation ''' # entete de la facture print("save") if not self.is_valide(): return invoice_date = unicode(self.invoice_date.text()) num_invoice = int(self.num_invoice.text()) invoice_type = self.liste_type_invoice[ self.box_type_inv.currentIndex()] lis_error = [] invoice = Invoice() try: self.owner = Owner.get(Owner.islog == True) except: lis_error.append("Aucun utilisateur est connecté <br/>") paid_amount = int(self.table_invoice.paid_amount_field.text()) try: clt = ProviderOrClient.get_or_create( self.name_client, int(self.phone.replace(" ", "")), ProviderOrClient.CLT) except ValueError: field_error( self.name_client_field, "Nom, numéro de téléphone du client") invoice.number = num_invoice invoice.owner = self.owner invoice.client = clt invoice.location = "Bamako" invoice.type_ = invoice_type invoice.subject = "" invoice.paid_amount = paid_amount invoice.tax = False try: invoice.save() if int(paid_amount) != 0 or invoice_type == Invoice.TYPE_BON: Refund(type_=Refund.DT, owner=self.owner, amount=paid_amount, date=date_to_datetime(invoice_date), provider_client=clt, invoice=Invoice.get(number=num_invoice)).save() except Exception as e: invoice.deletes_data() lis_error.append( "Erreur sur l'enregistrement d'entête de facture<br/>") return False # Save invoiceitems invoice = Invoice.get(Invoice.number == num_invoice) for name, qty, price in self.table_invoice.get_table_items(): rep = Report() product = Product.get(Product.name == name) rep.store = 1 rep.product = product rep.invoice = invoice rep.type_ = Report.S rep.cost_buying = int(product.last_report.cost_buying) rep.date = date_to_datetime(invoice_date) rep.qty = int(qty) rep.selling_price = int(price) try: rep.save() except Exception as e: lis_error.append(e) if lis_error != []: invoice.delete_instance() self.parent.Notify(lis_error, "error") return False else: self.parent.Notify("Facture Enregistrée avec succès", "success") self.change_main_context(ShowInvoiceViewWidget, invoice_num=invoice.number)
def fetch_existing_product(upc): try: product = Product.get(Product.upc == upc) return product except: return None
def set_data_for(self, main_date): reports = [] self.totals = 0 self.total_sum_d1 = 0 self.total_sum_d2 = 0 self.total_sum_d3 = 0 self.total_sum_d4 = 0 self.total_sum_d5 = 0 self.total_sum_d6 = 0 try: self.date_on, self.date_end = main_date.current.current except Exception as e: self.date_on, self.date_end = main_date.current products = [(Product.get(id=rpt.product_id).name) for rpt in Report.select(fn.Distinct(Report.product)).where( Report.date >= self.date_on, Report.date <= self.date_end, Report.type_ == Report.S)] products = [(prod.name) for prod in Product.select().where( Product.name << products).order_by(Product.name.desc())] for prod_name in products: on = date_on_or_end(self.date_on) end = date_on_or_end(self.date_end, on=False) dict_store = {} repts = Report.select().where(Report.type_ == Report.S, Report.product == Product.get( name=prod_name)) dict_store["product"] = prod_name dict_store["sum_week"] = repts.select( peewee.fn.SUM(Report.qty)).where(Report.date >= on, Report.date <= end).scalar() or 0 self.totals += (dict_store["sum_week"]) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d1"] = repts.select( peewee.fn.SUM(Report.qty)).where(Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d1 += dict_store["sum_d1"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d2"] = repts.select( peewee.fn.SUM(Report.qty)).where(Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d2 += dict_store["sum_d2"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d3"] = repts.select( peewee.fn.SUM(Report.qty)).where(Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d3 += dict_store["sum_d3"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d4"] = repts.select( peewee.fn.SUM(Report.qty)).where(Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d4 += dict_store["sum_d4"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d5"] = repts.select( peewee.fn.SUM(Report.qty)).where(Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d5 += dict_store["sum_d5"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d6"] = repts.select( peewee.fn.SUM(Report.qty)).where(Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d6 += dict_store["sum_d6"] reports.append(dict_store) self.data = [(rep.get('product'), rep.get('sum_d1'), rep.get('sum_d2'), rep.get('sum_d3'), rep.get('sum_d4'), rep.get('sum_d5'), rep.get('sum_d6'), rep.get('sum_week'), "") for rep in reports]
def set_data_for(self, main_date): reports = [] self.totals = 0 self.total_sum_d1 = 0 self.total_sum_d2 = 0 self.total_sum_d3 = 0 self.total_sum_d4 = 0 self.total_sum_d5 = 0 self.total_sum_d6 = 0 try: self.date_on, self.date_end = main_date.current.current except Exception as e: self.date_on, self.date_end = main_date.current products = [(Product.get(id=rpt.product_id).name) for rpt in Report.select(fn.Distinct(Report.product)).where( Report.date >= self.date_on, Report.date <= self.date_end, Report.type_ == Report.S)] products_ = [(prod.name) for prod in Product.select().where( Product.name << products).order_by(Product.name.desc())] for prod_name in products_: on = date_on_or_end(self.date_on) end = date_on_or_end(self.date_end, on=False) dict_store = {} repts = Report.select().where(Report.type_ == Report.S, Report.product == Product.get( name=prod_name)) dict_store["product"] = prod_name dict_store["sum_week"] = repts.select( peewee.fn.SUM(Report.qty)).where( Report.date >= on, Report.date <= end).scalar() or 0 self.totals += (dict_store["sum_week"]) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d1"] = repts.select( peewee.fn.SUM(Report.qty)).where( Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d1 += dict_store["sum_d1"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d2"] = repts.select( peewee.fn.SUM(Report.qty)).where( Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d2 += dict_store["sum_d2"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d3"] = repts.select( peewee.fn.SUM(Report.qty)).where( Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d3 += dict_store["sum_d3"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d4"] = repts.select( peewee.fn.SUM(Report.qty)).where( Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d4 += dict_store["sum_d4"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d5"] = repts.select( peewee.fn.SUM(Report.qty)).where( Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d5 += dict_store["sum_d5"] on += timedelta(1) end = on + timedelta(days=1, seconds=-1) dict_store["sum_d6"] = repts.select( peewee.fn.SUM(Report.qty)).where( Report.date >= on, Report.date <= end).scalar() or 0 self.total_sum_d6 += dict_store["sum_d6"] reports.append(dict_store) self.data = [( rep.get('product'), rep.get('sum_d1'), rep.get('sum_d2'), rep.get('sum_d3'), rep.get('sum_d4'), rep.get('sum_d5'), rep.get('sum_d6'), rep.get('sum_week')) for rep in reports]