def put(self, sale_id): '''Close a sale)''' sale = Sale.get_by_id(sale_id) if sale is None: return {"error": 404, "message": "sale not found"} logged_user = User.get_by_id(id=get_jwt_identity())['username'] if logged_user == sale.created_by or User.isAdmin( user_id=get_jwt_identity()): sale = Sale.get_by_id(sale_id) sale_json = sale.json_dump() sale_json["products"] = SaleStock.get_sale_stocks(sale_id=sale.id) if not sale_json["products"]: return { "Error": 400, "message": "You can't close a sale with no products" }, 400 if sale.status == "submitted": return { "Error": 400, "message": "The sale is already closed" }, 400 sale.submit() sale = Sale.get_by_id(sale_id) sale_json = sale.json_dump() sale_json["products"] = SaleStock.get_sale_stocks(sale_id=sale.id) return { "message": "successfuly closed the sale", "data": sale_json }, 200 return { "message": "Unauthorized,only an admin or sale owner can close a sale" }, 403
def get(pk=None): if pk: Sale = model_to_dict( Sale.select().where(Sale.id == pk).get()) return json.dumps(Sale) prodcuts = list(Sale.select()) return json.dumps([model_to_dict(item.get()) for item in prodcuts])
def edit_stock(request, pk): data = json.loads(request.data) stock = data.get("stock") if stock is None: raise BadRequest("Stock is required") Sale = Sale.update(stock=stock).where(Sale.id == pk).execute() return 200, json.dumps(model_to_dict(Sale.select().where(Sale.id == pk).get()))
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()
def post(self, request): user_profile = UserProfile.objects.get(badge=request.POST.get('badge')) user = user_profile.user item = Item.objects.get(code=request.POST.get('code')) sale = Sale(user=user) sale.save() sl = SaleLine(quantity=1, item=item, sale=sale) sl.save() t = Transaction(user=user, amount=-sale.total) t.save() return HttpResponse()
def create_sale(): data = request.get_json() or {} if 'event_id' not in data or 'user_id' not in data or 'date' not in data: return bad_request('Must include event_id, user_id, and date fields.') sale = Sale() sale.from_dict(data) db.session.add(sale) db.session.commit() response = jsonify(sale.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_sale', id=sale.id) return response
def get(self): '''Get all sales ever created.Admin only''' user_logged_in = get_jwt_identity() if not User.isAdmin(user_id=user_logged_in): return {"error": 401, "message": "Not authorized.Admin only."} if "search" in request.args: sales_found = Sale.search_closed_sales( self, username=request.args['search']) if sales_found: return {"message": "Sales found", "data": sales_found}, 200 return {"message": "No sales found"}, 404 all_sales = Sale.get_all() return {"message": "Ok", "data": all_sales}, 200
def post(self, id_receipt, id_product, quantity): receipt = Receipt.query.filter_by(id=id_receipt).one() product = Product.query.filter_by(id=id_product).one() # проверяем наличие товара в чеке если он есть просто увеличиваем количество in_receipt = Sale.query.filter_by(product_id=id_product, receipt_id=id_receipt).first() if in_receipt: in_receipt.quantity += quantity db.session.add(in_receipt) else: new_sale = Sale(quantity=quantity, price=product.price) new_sale.product = product receipt.sale.append(new_sale) db.session.add(receipt) db.session.commit() return '', 204
def sell(): '''Goes through all the necessary interactions that must happen when a sale request is made.''' if len(current_user.cards) == 0: flash('You do not have any cards to sell!', 'danger') return redirect(url_for('user.cards')) if 'card' in request.form.keys() and 'price' in request.form.keys(): num = 0 for card in current_user.cards: if int(card.id) == int(request.form['card']): num += 1 if (len( Sale.query.filter_by(user_id=current_user.id, card_id=request.form['card']).all()) >= num): flash( 'All of your copies of ' + str( Card.query.filter_by(id=request.form['card']).first().name) + ' are already on sale!', 'danger') return render_template('sales.html') flash('Your sale has been posted!', 'success') from app import app with app.app_context(): Card.query.filter_by( id=request.form['card']).first().num_sales += 1 sale = Sale(request.form['card'], request.form['price'], 0, current_user.id, None) db.session.add(sale) db.session.commit() return redirect(url_for('user.mysales')) return render_template('sales.html')
def buy(oid): user = User.query.filter_by(UserAccountId=current_user.get_id()).first() dataset = Dataset.query.filter_by(OfferingId=oid).first() sale = Sale(SaleDate=datetime.datetime.now(), SellerId=dataset.owner.UserAccountId, BuyerId=user.UserAccountId, \ SalePrice=dataset.Price, dataset=dataset) customer = stripe.Customer.create(email=request.form['stripeEmail'], source=request.form['stripeToken']) charge = stripe.Charge.create(customer=customer.id, amount=int(dataset.Price * 100), currency='usd') db.session.add(sale) db.session.commit() new_row = [ dataset.OfferingName, dataset.owner.UserName, dataset.Category, dataset.Region, dataset.OfferingType, dataset.UpdateFrequency, dataset.Description, dataset.Price ] train_file = os.path.join(app.root_path, 'train.csv') with open(train_file, 'a') as fd: writer = csv.writer(fd, lineterminator='\n') writer.writerow(new_row) return redirect( url_for('show_dataset_details', oid=oid, dn=dataset.OfferingName.replace(' ', '-').lower()))
def get(self): '''Get all closed sales for a user''' if 'user' in request.args: try: user_to_search = User.get_by_id( request.args['user'])['username'] except: return { "error": 404, "message": "No user found with that id" }, 404 logged_user = User.get_by_id(id=get_jwt_identity())['username'] if user_to_search == logged_user or User.isAdmin( user_id=get_jwt_identity()): user_sales = Sale.get_all_user_closed_sales( username=user_to_search) if user_sales: return {"message": "Success", "data": user_sales}, 200 return { "error": 404, "message": "The user has no closed sales yet" } return { "message": "Unauthorized.Only admin or sale owner can access" }, 401
def test_date_is_updated_when_data_changes(self): company_id = self.get_id_from_POST(data1) for metric in self.KPI: for data in kpis[metric]: self.KPI[metric]( company_id=company_id, value=data, ).save() updated_time = Sale.get_last_updated(company_id).updated_at Sale.get_last_updated(company_id).value = 234 db.session.commit() new_updated_time = Sale.get_last_updated(company_id).updated_at self.assertNotEqual(updated_time, new_updated_time)
def get(self): '''Get all closed sales''' user_logged_in = get_jwt_identity() if not User.isAdmin(user_id=user_logged_in): return {"error": 401, "message": "Not authorized.Admin only."} all_sales = Sale.get_all_closed_sales() return {"message": "Ok", "data": all_sales}, 200
def get_user_event_sales(user_id, event_id): page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 20, type=int), 100) data = Sale.to_collection_dict(Sale.query.filter( Sale.user_id == user_id).filter(Sale.event_id == event_id), page, per_page, 'api.get_user_event_sales', user_id=user_id, event_id=event_id) return jsonify(data)
def add_employee_sales(): if not current_user.is_authenticated: return redirect(url_for('login')) # add employee sales to database # declare the Sale Form form = SaleForm(request.form) msg = None # check if both http method is POST and form is valid on submit if form.validate_on_submit(): # assign form data to variables quantity = request.form.get('quantity', 0, type=int) request_id = request.form.get('request_item', 0, type=int) # request_id = int(form.request_item.value) # print (request_id) sale = Sale(current_user.id, request_id, quantity) sale.save() flash('Sale entry successfully created!') else: flash('I am sorry but the details you entered cannot be saved :(') return redirect(f'/psalm2vs8/employee-requests/sales/{request_id}')
def buyback_car(id): car = Car.query.filter_by(id=id, onsale=False).first() if car: car.onsale = True sale = Sale(car=id, dealer=car.vendor_id, price=car.price, onsale=True) db.session.add(sale) db.session.commit() return make_response(jsonify({'result': 'Car is Back on Sale'}), 200) else: return make_response( jsonify({'error': 'Car Not Found or Already on sale'}), 404)
def reprice_car(id, new_price): car = Car.query.filter_by(id=id, onsale=True).first() if car: car.price = new_price sale = Sale(car=id, dealer=car.vendor_id, price=new_price) db.session.add(sale) db.session.commit() return make_response(jsonify({'result': 'Price changed successfully'}), 200) else: return make_response( jsonify({'error': 'Car Not Found or Not on Sale'}), 404)
def saleFormHandler(form): sale = Sale(party_name=form.party_name.data, party_address=form.party_address.data, gst_number=form.gst_number.data, vehicle_number=form.vehicle_number.data, no_of_bags=form.no_of_bags.data, variety_id=form.variety.data, agent_id=form.agent.data, quintol=form.quintol.data, rate=form.rate.data, timestamp=form.date.data, amount=form.amount.data) return write_to_db(sale)
def move_car(car_id, dealer_id): car = Car.query.filter_by(id=car_id).first() dealer = Dealer.query.filter_by(id=dealer_id).first() if car and dealer: car.vendor_id = dealer_id sale = Sale(car=car_id, dealer=dealer_id, price=car.price) db.session.add(sale) db.session.commit() return make_response(jsonify({'result': 'Car moved successfully'}), 200) elif not car: return make_response(jsonify({'error': 'Car Not Found'}), 404) else: return make_response(jsonify({'error': 'Dealer Not Found'}), 404)
def post(self): '''Create a sale''' parser = reqparse.RequestParser() parser.add_argument('buyer_name', help='The product field cannot be blank', required=True, type=str) data = parser.parse_args() logged_in_user = User.get_by_id(get_jwt_identity())['username'] sale = Sale(id=None, buyer_name=data['buyer_name'], status='open', created_by=logged_in_user, date_created=str(datetime.now()), date_modified=str(datetime.now())) sale.save() posted_sale = dict(buyer_name=data['buyer_name'], status='open', created_by=User.get_by_id(id=get_jwt_identity()), date_created=str(datetime.now()), date_modified=str(datetime.now())) return {"message": "Sale created", "data": posted_sale}
def post(self, sale_id): '''Add products to a sale''' parser = reqparse.RequestParser() parser.add_argument('product', help='The product field cannot be blank', required=True, type=int) parser.add_argument('quantity', help='The quantity field cannot be blank', required=True, type=int) data = parser.parse_args() sale = Sale.get_by_id(sale_id) if sale is None: return {"error": 404, "message": "sale not found"}, 404 if sale.status == "submitted": return {"message": "Forbidden.Sale is already submitted"}, 403 sale_json = sale.json_dump() product = Product.get_by_id(id=data["product"]) if product is None: return {"error": 404, "message": "product not found"}, 404 stocks = product.get_available_stocks() if len(stocks) == 0: return {"error": 404, "message": "product out of stock"}, 404 sale_product = SaleStock(id=None, sale_id=sale_id, stock_id=stocks[0].id, quantity=data["quantity"]) sale_product.save() sale = Sale.get_by_id(sale_id) sale_json = sale.json_dump() sale_json["products"] = SoldStock.get_sale_products(sale_id=sale.id) return {"message": "success", "data": sale_json}, 201
def get(self, sale_id): '''Get a sale by id''' sale = Sale.get_by_id(sale_id) if sale is None: return {"error": 404, "message": "sale not found"}, 404 logged_user = User.get_by_id(id=get_jwt_identity())['username'] if logged_user == sale.created_by or User.isAdmin( user_id=get_jwt_identity()): sale_json = sale.json_dump() sale_json["products"] = SaleStock.get_sale_stocks(sale_id=sale_id) return {"message": "Ok", "data": sale_json}, 200 return { "message": "You are not authorised.Only admin or sale owner can get the sale" }, 401
def add(request, dispatcher): data = json.loads(request.data) user_id = data.get("user_id") quantity = data.get("quantity") product_id = data.get("product_id") if user_id is None or quantity is None or product_id is None: raise BadRequest("Sale Id, User Id and are Quantity required") sale = Sale.create(Sale_name=Sale_name, stock=stock) payload = { "stock": (stock - quantity), "product_id": product_id } dispatcher("update_stock", payload) return 200, json.dumps(model_to_dict(Sale))
def sale_form_handler(form): quintol = form.quintol.data rate = form.rate.data gst = 5 amt = (quintol * rate) + (quintol * rate * gst / 100) sale_data = Sale(party_name=form.party_name.data, party_address=form.party_address.data, gst_number=form.gst_number.data, vehicle_number=form.vehicle_number.data, no_of_bags=form.no_of_bags.data, variety_id=form.variety.data, agent_id=form.agent.data, quintol=form.quintol.data, rate=form.rate.data, timestamp=form.date.data, amount=amt) return write_to_db(sale_data)
def buyCards(): '''Goes through all the necessary interactions that must happen when a card is bought.''' card = Card.query.filter_by(id=request.form['card']).first() anysale = Sale.query.filter_by(card_id=card.id, status=0).first() lowestsale = Sale.query.filter_by(card_id=card.id, status=0).filter( Sale.user_id != current_user.id).order_by(Sale.cost).first() if anysale == None: flash('This card is no longer on sale', 'danger') return redirect(url_for('user.cards')) elif lowestsale == None: flash('You cannot buy your own card', 'danger') return redirect(url_for('user.cards')) owner = User.query.filter_by(id=lowestsale.user_id).first() if (float(lowestsale.cost) <= float( current_user.balance)): #if the user has enough money to buy it current_user.balance -= lowestsale.cost owner.balance += lowestsale.cost current_user.cards.append(card) if lowestsale.user_id != 4: lowestsale.buyer = current_user owner.cards.remove(card) lowestsale.status = 1 print(card not in owner.cards) if (card not in owner.cards): trades = Trade.query.filter_by(status=0, user_id=lowestsale.user_id, given_card_id=card.id).all() print(trades) if trades != None: for trade in trades: db.session.delete(trade) else: sale = Sale(lowestsale.card_id, lowestsale.cost, 1, 4, current_user.id) db.session.add(sale) db.session.commit() flash('You have bought ' + get_card_id(int(request.form['card'])).name, 'success') else: flash('You do not enough money to buy ' + request.form['card'], 'danger') db.session.commit() return redirect(url_for('user.cards'))
def get(self): self.response.headers['Content-Type'] = 'text/plain' sale_ids = [] brands = defaultdict(dict) content = helper.fetch('http://m.gilt.com/pagegen_service/sale/mobile_sale_set') if content: sale_groups = json.loads(content).get('data').get('mobile_sale_set').get('sale_groups') active_sales = [sale_group.get('sales') for sale_group in sale_groups if sale_group.get('title') == 'Active Sales'][0] for sale_data in active_sales: sale_id = sale_data.get('id') sale_name = sale_data.get('name') sale_data['stores'] = [str(store.lower()) for store in sale_data['stores']] sale = Sale.create(sale_data) if sale: new_sale_msg = "Created sale %s - %s.\nhttp://%s/tasks/fetch/sale/%d\n\n" % \ (sale_id, sale_name, self.request.host, sale_id) else: new_sale_msg = "Sale %s - %s already exists.\n\n" % (sale_id, sale_name) self.response.out.write(new_sale_msg) sale_ids.append(sale_id) for brand in sale_data.get('brands') or []: Brand.create(brand_id=brand.get('id'), name=brand.get('name')) for sale_id in sale_ids: task_name = TASK_NAME_FETCH_SALE % (TASK_QUEUE_FETCH_SALE, sale_id, datetime.now().microsecond) task = taskqueue.Task(url='/tasks/fetch/sale/%s' % (sale_id), \ params={'brands': brands[sale_id]}, name=task_name, method='GET') try: task.add(TASK_QUEUE_FETCH_SALE) task_msg = "Added task '%s' to task queue '%s'.\n" except TaskAlreadyExistsError: task_msg = "Task '%s' already exists in task queue '%s'.\n" except TombstonedTaskError: task_msg = "Task '%s' is tombstoned in task queue '%s'.\n" self.response.out.write("%s\n%s" % (task.url, task_msg % (task.name, TASK_QUEUE_FETCH_SALE)))
def delete(self, sale_id): '''Delete a sale record''' sale = Sale.get_by_id(sale_id) if sale is None: return {"error": 404, "message": "sale not found"}, 404 logged_user = User.get_by_id(id=get_jwt_identity())['username'] if logged_user == sale.created_by or User.isAdmin( user_id=get_jwt_identity()): if sale.status == "deleted": return { "error": 400, "message": "The sale record has already been deleted" }, 400 sale.cancel() return {"response": 204, "message": "successfully deleted"}, 204 return { "message": "You are not authorised.Only admin or sale owner can delete a sale" }, 401
def charts_load(request): context = {'segment': 'charts_from_load'} html_template = loader.get_template('charts-from-load.html') # ----------------------------------------------- # Extract data from Sale table # ----------------------------------------------- sales, labels = Sale.get_sales_report() data = [{ 'y': year, 'a': '{:.2f}'.format(sales[year].get('A')), 'b': '{:.2f}'.format(sales[year].get('B')), 'c': '{:.2f}'.format(sales[year].get('C')) } for year in sales] context['chart_data'] = json.dumps({ 'element': 'morris-bar-chart', 'data': data, 'xkey': 'y', 'barSizeRatio': 0.70, 'barGap': 3, 'resize': True, 'responsive': True, 'ykeys': ['a', 'b', 'c'], # it can be custom 'labels': labels, 'barColors': ['0-#1de9b6-#1dc4e9', '0-#899FD4-#A389D4', '#04a9f5'] # it can be custom }) return HttpResponse(html_template.render(context, request))
def add_car(): if (not request.json or not 'brand' in request.json or not 'model' in request.json or not 'dealer' in request.json or not 'price' in request.json or not 'color' in request.json): return make_response(jsonify({'error': 'Incorrect Request'}), 400) else: new_car = Car(brand=request.json['brand'], model=request.json['model'], price=int(request.json['price']), vendor_id=int(request.json['dealer']), color=request.json['color']) if 'year_built' in request.json: new_car.year_built = int(request.json['year_built']) if 'mileage' in request.json: new_car.mileage = int(request.json['mileage']) db.session.add(new_car) db.session.commit() sale = Sale(car=new_car.id, dealer=new_car.vendor_id, price=new_car.price) db.session.add(sale) db.session.commit() return make_response(jsonify({'result': 'Created Successfully'}), 201)
def add_sale(): add_sale = True form = SaleForm() if form.validate_on_submit(): sale = Sale(broker=form.broker.data, description=form.description.data) try: # add product to the database db.session.add(sale) db.session.commit() except: # in case product name already exists flash('Error: product name already exists.') # redirect to products page return redirect(url_for('sales.list_sales')) # load product template return render_template('sales/sale.html', action="Add", add_sale=add_sale, form=form, title="Add Sale")
def get_sales(): page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 10, type=int), 100) data = Sale.to_collection_dict(Sale.query, page, per_page, 'api.get_sales') return jsonify(data)
def get(self, sale_id): self.response.headers['Content-Type'] = 'text/plain' sale_id = int(sale_id) sale = Sale.lookup(sale_id) if not sale: self.response.out.write('Sale id %d not found.\n' % (sale_id)) else: url = "%s/sale/mobile_sale_listing?sale_id=%d" % (API_SVC, sale_id) content = helper.fetch(url) products_data = json.loads(content)['data']['products'] if products_data and len(products_data): brand_entities = [Brand.get_by_key_name(str(product['brand_id'])) for product in products_data.values()] brands = dict([(int(brand.id), brand) for brand in brand_entities if brand]) for product_id, product_data in products_data.items(): brand_id = product_data['brand_id'] brand = Brand.lookup(brand_id) product_id = int(product_id) product_data['name'] = mod_product_string(product_data['name']) product_data['description'] = mod_product_string(product_data['description'], '\n') product_data['categories'] = list(itertools.chain(*([k.split('_') for k in product_data['category_keys']]))) product = Product.create(product_id, product_data, sale, brands.get(brand_id) or Brand.create(brand_id)) if not product: self.response.out.write("Did not create product %d - %s.\n" % (product_id, product_data['name'])) else: self.response.out.write("Created product %d - %s.\n" % (product_id, product_data['name'])) prices = [] sizes = [] looks = product_data['looks'] if looks: for look_data in looks: look_id = look_data['look_id'] look = Look.create(look_id, look_data, product) if not look: self.response.out.write('\tDid not create Look for look id %d.\n' % look_id) else: self.response.out.write('\tCreated look id %d for product %d %s.\n' % (look_id, product_id, product.name)) prices.extend([look_data.get(price_key) for price_key in PRICE_KEYS]) skus = look_data.get('skus') or [] for sku_data in skus: size = sku_data.get('size') if size: if size[0].isdigit(): sizes.extend(size.split('/')) else: sizes.append(size) sku_id = sku_data['sku_id'] sku = SKU.create(sku_id, sku_data, look or Look.get_by_key_name("%s" % look_id)) if sku: self.response.out.write('\t\t- Created SKU %d.\n' % sku_id) prices.extend([sku_data.get(price_key) for price_key in PRICE_KEYS]) else: self.response.out.write('\t\t- Did not create SKU %d.\n' % sku_id) prices = list(frozenset(filter(lambda price: price and price > 0, prices))) if prices: product.lowest_price = min(prices) product.highest_price = max(prices) if sizes: product.sizes = list(frozenset(sizes)) product.put() self.response.out.write("\n\n")