def test_exception_when_stock_less_zero( self): # sempre iniciar o metodo com teste product = Product() with self.assertRaises(ValueError) as exception: product.stock = 10 product.decrement(11) self.assertEquals('Sem estoque disponível', str(exception.exception))
def new(self, barcode=""): if len(barcode) == 0: barcode = self.scan() if self.getProduct(barcode) == None: name = raw_input("Entrez le nom du produit: ") price = float(raw_input("Entrez le prix: ")) quantity = int(raw_input("Entrez la quantité: ")) minQuantity = int(raw_input("Entrez la quantité minimale")) p = Product(barcode=barcode, name=name, price=price, minQuantity = minQuantity, quantity=quantity) p.save() else: p = Product.objects.get(barcode=barcode) name = raw_input("Entrez le nouveau nom du produit [] : ") price = raw_input("Entrez le nouveau prix: ") quantity = raw_input("Entrez la quantité supplémentaire: ") minQuantity = raw_input("Entrez la quantité minimale: ") if len(name)>0: p.name = name if len(price) > 0: try: p.price = float(price) except ValueError: print("Un chiffre pls :'(") if len(minQuantity) > 0: try: p.minQuantity = int(minQuantity) except ValueError: print("Un chiffre pls :'(") if len(quantity) > 0: try: p.quantity = int(quantity) except ValueError: print("Un chiffre pls :'(") p.save()
def setUp(self): stock = make_product_type('Stock', 'stock') stationery = make_product_category('Stationery', 'stationery', stock) # products self.pack_pencils = Product.create_product( 'pack_pencil', 'Pack pencils', Decimal('2.00'), stationery, ) self.pen = Product.create_product( 'pen', 'Pen', Decimal('2.00'), stationery, ) self.pencil = Product.create_product( 'pencil', 'Pencil', Decimal('1.32'), stationery, )
def handle(self, *args, **kwargs): # Get the queryset product_qs = Product.objects.values('id', 'weight', 'volume', 'pallet_size', 'product_type') category_objects = list( ProductCategory.objects.values_list('id', flat=True)) # Convert qs to dataframe product_df = read_frame(product_qs) # Generate missing data for selected columns df_length = product_df.shape[0] product_df['weight'] = np.random.randint(100, 1000, df_length) product_df['volume'] = np.random.randint(10, 100, df_length) product_df['profit_margin'] = np.random.randint(1, 10, df_length) product_df['pallet_size'] = np.random.randint(10, 50, df_length) product_df['unit_size'] = (product_df['pallet_size'] // 10) + 1 product_df['product_type'] = np.random.choice(['Food', 'Non Food'], df_length, p=[0.6, 0.4]) product_df['category_id'] = np.random.choice(category_objects, df_length) self.stdout.write('Updating database...') # Bulk update classification in database product_objects = [ Product( id=row['id'], weight=row['weight'], volume=row['volume'], profit_margin=row['profit_margin'], unit_size=row['unit_size'], pallet_size=row['pallet_size'], product_type=row['product_type'], category_id=row['category_id'], ) for i, row in product_df.iterrows() ] Product.objects.bulk_update(product_objects, [ 'weight', 'volume', 'profit_margin', 'unit_size', 'pallet_size', 'product_type', 'category_id' ]) # Output success message self.stdout.write(self.style.SUCCESS('Products have been updated'))
def get_product_dropdown(dropdown_id, div_checklist_id, checklist_select_all_id): div = html.Div([ dbc.Label('Select products'), dcc.Dropdown( id=dropdown_id, placeholder="Select products", options=list(Product.get_products()), # value=list(Product.get_products().values_list('value', flat=True)), multi=True), html.Div( id=div_checklist_id, children=dcc.Checklist( id=checklist_select_all_id, options=[{ "label": "Select All", "value": "All" }], value=["All"], ), ), ]) return div
def update_stock_db(self, db): """Update database stock with the stock uploaded.""" self.is_safe_to_save() with db.atomic() as transaction: Product().truncate_table() try: reader = DictReader(StringIO(self.file.read().decode("utf-8"))) for row in reader: product = Product() product.manufacturer = row['manufacturer'] product.model = row['model'] product.color = row['color'] product.carrier_plan_type = row['carrier_plan_type'] product.quantity = row['quantity'] product.price = row['price'] product.save() # except peewee.IntegrityError as e: except peewee.IntegrityError: # print(str(e)) transaction.rollback() self.errors.append('Could not update the database.') self.errors.append('There is an error on given stock file!') return False except Exception: # @FIXME: Correctly catch database errors # http://docs.peewee-orm.com/en/latest/peewee/database.html transaction.rollback() self.errors.append('Could not update the database.') self.errors.append( 'The error is unknown, please contact support.') return False return True
def handle(self, *args, **kwargs): def _abc_segmentation(perc): ''' Creates the 3 classes A, B, and C based on quantity percentages (A-80%, B-15%, C-5%) ''' if perc > 0 and perc < 0.8: return 'A' elif perc >= 0.8 and perc < 0.95: return 'B' elif perc >= 0.95: return 'C' def _fmr_segmentation(perc): ''' Creates the 3 classes F, M, and R based on quantity percentages (F-80%, M-15%, R-5%) ''' if perc > 0 and perc < 0.8: return 'F' elif perc >= 0.8 and perc < 0.95: return 'M' elif perc >= 0.95: return 'R' # Date range to consider for calculation (last delta years) _delta_years = 2 start_date = datetime.today() - timedelta(days=_delta_years * 365) # Get the queryset qs = DeliveryDetail.objects.filter( delivery__delivered_at__gte=start_date) qs = qs.values('product__id', 'delivered_quantity', 'unit_price') # Convert qs to dataframe df = read_frame(qs) # Format df = df.astype({'delivered_quantity': float, 'unit_price': float}) # Add delivery count of each product (sum(1 for each product delivered)) df['delivery_freq'] = 1 # Group by product and aggregate df = df.groupby(['product__id']).agg({ 'delivered_quantity': 'sum', 'unit_price': 'mean', 'delivery_freq': 'sum', }).reset_index() # Create the column of the additive cost per product df['cost_product'] = df['unit_price'] * df['delivered_quantity'] # Order by cumulative cost and create ABC segmentation df = df.sort_values(by=['cost_product'], ascending=False) df['cost_product_cum'] = df['cost_product'].cumsum() df['cost_product_sum'] = df['cost_product'].sum() df['cost_perc'] = df['cost_product_cum'] / df['cost_product_sum'] df['abc_segmentation'] = df['cost_perc'].apply(_abc_segmentation) # Order by cumulative cost and create FMR segmentation df = df.sort_values(by=['delivery_freq'], ascending=False) df['delivery_freq_cum'] = df['delivery_freq'].cumsum() df['delivery_freq_sum'] = df['delivery_freq'].sum() df['delivery_freq_perc'] = df['delivery_freq_cum'] / df[ 'delivery_freq_sum'] df['fmr_segmentation'] = df['delivery_freq_perc'].apply( _fmr_segmentation) self.stdout.write('Updating database...') # Bulk update classification in database products = [ Product( id=row['product__id'], abc_segmentation=row['abc_segmentation'], fmr_segmentation=row['fmr_segmentation'], ) for i, row in df.iterrows() ] Product.objects.bulk_update(products, ['abc_segmentation', 'fmr_segmentation']) # Output success message self.stdout.write( self.style.SUCCESS('ABC & FMR segmentations have been updated'))
def test_update_stock_db_with_invalid_stock(self): self.test_is_valid_file_with_invalid_stock_file() assert Product().select().count() == 0 assert self.bulk_stock.update_stock_db(self.db) is False assert Product().select().count() == 0
def test_product_has_timestampable(self): product = Product() self.assertIsInstance(product, TimestampableMixin)
def test_value_initial_stock_field(self): product = Product() self.assertEquals(0, product.stock)
def test_value_initial_stock_field( self): # sempre iniciar o metodo com teste product = Product() self.assertEquals(0, product.stock)
def test_product_has_timestampable( self): # sempre iniciar o metodo com teste product = Product() self.assertIsInstance(product, TimestampableMixin)