def test_delete_order(self): # create customer, item and order and insert into<br> # database pending deletion request customer = Customer(name=self.new_customer['name'], email=self.new_customer['email']) customer.insert() item = Item(name=self.new_item['name'], brand=self.new_item['brand'], price=self.new_item['price']) item.insert() order = Orders(customer_id=customer.id, item_id=item.id, quantity=10) order.insert() # assign order id to variable prior to deletion for testing purposes order_id = order.id # delete order that was currently created res = self.client().delete('/delete_order/{}'.format(order.id), headers=manager_jwt) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['success']) # verify that deleted order id matched id included in request self.assertEqual(data['deleted_order_id'], order_id) self.assertEqual(data['current_orders'], (data['previous_orders'] - 1)) # delete customer and item customer.delete() item.delete()
def submit_order(): # get request JSON data data = request.get_json() # verify that data contains the correct info if (data.get('customer_id') is None or data.get('item_id') is None or data.get('quantity') is None): abort(404) # select item to be added to order item = Item.query.filter_by(id=data['item_id']).one_or_none() if item is None: abort(404) # verify that item is available if item.available is False: abort(422, 'item not available') # get todays date today = date.today() # calculate total price of order based upon item price<br> # and quantity of order total_price = item.price * data['quantity'] # create orders object order = Orders(order_date=today, customer_id=data['customer_id'], item_id=data['item_id'], quantity=data['quantity'], amount_due=total_price) # attempt to insert order into database with .insert() (see models.py) try: order.insert() except Exception as exc: db.session.rollback() print('Exception:', exc) abort(422) return ({'success': True, 'status_code': 200, 'order_id': order.id})
def order(self): order_string = "" for order_text in self.data_parsed[1:]: order_string += order_text + " " order = Orders(id=self.user_id, user_name=self.user_name, order=order_string) response = order.put() return 'Order Submitted/Updated'
def post(self): data = json.loads(self.request.body) name = data['name'] phone = data['phone'] email = data['email'] orders = data['orders'] Orders.set_order(name, phone, email, orders) self.response.write(json.dumps({ "done": True }))
def api_orders(*, page='1'): page_index = get_page_index(page) num = yield from Orders.findNumber('count(id)') p = Page(num, page_index) if num == 0: return dict(page=p, orders=()) orders = yield from Orders.findAll(limit=(p.offset, p.limit)) return dict(page=p, orders=orders)
def post_order() -> Tuple[str, int]: """Запрос на вывод и создание заказа.""" if request.method == 'GET': order_id = request.args.get('orderId') order = session.query(Orders).filter(Orders.id == order_id).first() json_return = {'id': order.id, 'address_from': order.address_from, 'address_to': order.address_to, 'client_id': order.client_id, 'driver_id': order.driver_id, 'date_created': order.date_created, 'status': order.status} return jsonify(json_return) if request.method == 'POST': response_post = request.json address_from = response_post['address_from'] address_to = response_post['address_to'] client_id = response_post['client_id'] driver_id = response_post['driver_id'] date_created = datetime.now() status = response_post['status'] posted_order = Orders(address_from, address_to, client_id, driver_id, date_created, status) session.add(posted_order) session.commit() session.close() return '', 200 assert False
def api_create_order(request, *, contract_no, streaming_no, product_id,product_name,service_name,service_id,order_type,province,city, enterprise_id,customer_name,mobile,creator,project_no,contract_url,sale_name,sale_mobile,create_time,opening_time): #check_admin(request) if not opening_time or not opening_time.strip(): raise APIValueError('opening_time', 'opening_time cannot be empty.') if not create_time or not create_time.strip(): raise APIValueError('create_time', 'create_time cannot be empty.') if not sale_mobile or not sale_mobile.strip(): raise APIValueError('sale_mobile', 'sale_mobile cannot be empty.') if not sale_name or not sale_name.strip(): raise APIValueError('sale_name', 'sale_name cannot be empty.') if not contract_url or not contract_url.strip(): raise APIValueError('contract_url', 'contract_url cannot be empty.') if not project_no or not project_no.strip(): raise APIValueError('project_no', 'project_no cannot be empty.') if not creator or not creator.strip(): raise APIValueError('creator', 'creator cannot be empty.') if not mobile or not mobile.strip(): raise APIValueError('mobile', 'mobile cannot be empty.') if not customer_name or not customer_name.strip(): raise APIValueError('customer_name', 'customer_name cannot be empty.') if not enterprise_id or not enterprise_id.strip(): raise APIValueError('enterprise_id', 'enterprise_id cannot be empty.') if not city or not city.strip(): raise APIValueError('city', 'city cannot be empty.') if not province or not province.strip(): raise APIValueError('province', 'province cannot be empty.') if not contract_no or not contract_no.strip(): raise APIValueError('contract_no', 'contract_no cannot be empty.') if not order_type or not order_type.strip(): raise APIValueError('order_type', 'order_type cannot be empty.') if not service_id or not service_id.strip(): raise APIValueError('service_id', 'service_id cannot be empty.') if not streaming_no or not streaming_no.strip(): raise APIValueError('streaming_no', 'streaming_no cannot be empty.') if not product_id or not product_id.strip(): raise APIValueError('product_id', 'product_id cannot be empty.') if not product_name or not product_name.strip(): raise APIValueError('product_name', 'product_name cannot be empty.') if not service_name or not service_name.strip(): raise APIValueError('service_name', 'service_name cannot be empty.') order = Orders(id=5002,contract_no=contract_no.strip(), streaming_no=streaming_no.strip(), product_id=product_id.strip(),product_name=product_name.strip(),service_name=service_name.strip(),service_id=service_id.strip(),order_type=order_type.strip(),province=province.strip(),city=city.strip(), enterprise_id=enterprise_id.strip(),customer_name=customer_name.strip(),mobile=mobile.strip(),creator=creator.strip(),project_no=project_no.strip(),contract_url=contract_url.strip(),sale_name=sale_name.strip(),sale_mobile=sale_mobile.strip(),create_time=create_time.strip(),opening_time=opening_time.strip()) yield from order.save() return order
def post(self): data = json.loads(self.request.body) phone = data['phone'] try: phone = int(phone) except: self.response.write(json.dumps({'data': False})) orders = Orders.get_order(phone).orders self.response.write(json.dumps({'data': orders}))
def post(self): data = json.loads(self.request.body) phone = data['phone'] orders = Orders.get_order(phone) print(orders) if orders is None: self.response.write(json.dumps({ 'orders': None })) else: self.response.write(json.dumps(orders.to_dict()))
def delete_order(): #deleting from first page form = TabletDeleteForm(request.form) if request.method == 'POST' and form.validate(): order = Orders() delete_details(order, form) return redirect('/') return render_template('delete_order.html', form=form)
def orders(): orderByUser = cart.query.filter( cart.user_id == session['user']['id']).all() user_order = Orders(user_id=session['user']['id']) db.session.add(user_order) db.session.commit() ord = Orders.query.all() for newOrder in orderByUser: amounts = newOrder.qty * newOrder.priceItem delete = cart.query.filter( cart.user_id == session['user']['id']).first() db.session.delete(delete) for i in ord: k = orderItems(product=newOrder.product_id, qty=newOrder.qty, price=newOrder.priceItem, amount=amounts, order_id=i.id) db.session.add(k) db.session.commit() mail_user = users.query.filter(users.id == session['user']['id']).all() with mail.connect() as conn: for us in mail_user: order_id = orderItems.query.filter( Orders.id == orderItems.order_id).order_by( Orders.id.desc()).first() orderByus = Orders.query.filter( db.and_(Orders.id == orderItems.order_id, Orders.user_id == session['user']['id'])).all() prodName = Product.query.filter( Product.id == orderItems.product).first() for byUs in orderByus: orderItemsByUser = orderItems.query.filter( db.and_(Orders.id == orderItems.order_id, Orders.user_id == session['user']['id'])).all() for itemsByuser in orderItemsByUser: message = 'This is your purchase' + '<br>' + 'name: ' + str(byUs.id) + '<br>' \ 'qty:' + str( itemsByuser.qty) + '<br>' \ 'price:' + str(itemsByuser.price) + '$' + '<br>' \ 'Amount:' + str( itemsByuser.amount) + '$' + '<br>' subject = "Your Purchase %s" % us.username msg = Message(recipients=[us.email], html=message, subject=subject) conn.send(msg) return redirect(url_for('shopping_cart'))
def customorOrders (enterprise_id): orders = yield from Orders.findAll('enterprise_id=?',enterprise_id) for order in (orders): order.services = order.service_name.split(';') order.openingTime = time.localtime(order.opening_time) order.openingTime = time.strftime('%Y%m%d',order.openingTime) return { '__template__':'customorOrders.html', 'orders': orders }
def take(self): query = Orders.query() return_string = "You need to get:```" for x in query: return_string += "{} for {} \n".format(x.order, x.user_name) x.key.delete() args = {"response_type": "in_channel", "text": "{} has agreed to go and get your orders! :smile:".format(self.user_name)} request = urllib2.Request(self.url_to_return) request.add_header('content-type', 'application/json') resp = urllib2.urlopen(request, json.dumps(args)) return return_string + "```"
def test_404_delete_nonexistent_order(self): ''' create and insert customer and item to be included in mock order. insert mock order, assign mock order's id to variable<br> and then delete mock order prior to the test to ensure<br> that order pending delete does not exist ''' customer = Customer(name='test_name', email='test_email') item = Item(name='test_name', brand='test_brand', price=1) customer.insert() item.insert() mock_order = Orders(customer_id=customer.id, item_id=item.id, quantity=1) mock_order.insert() nonexistent_order_id = mock_order.id mock_order.delete() # after mock order is deleted delete customer and item too customer.delete() item.delete() # attempt to delete nonexistent order res = self.client().delete( '/delete_order/{}'.format(nonexistent_order_id), headers=manager_jwt) data = json.loads(res.data) self.assertEqual(res.status_code, 404) self.assertFalse(data['success'])
def addOrder(**kwargs): """Add an order to the database""" db.session.close() item = ModOrders() data = item.add(**kwargs) if infoOrder(data['ord_num']): error = 'error' return error a = Orders(**data) db.session.add(a) db.session.commit() ord_id = Orders.query.filter_by(ord_num=data['ord_num']).first() return ord_id
def get(self): self.response.headers['Content-Type'] = 'application/csv' self.response.headers['Content-Disposition'] = 'attachment; filename=summary.csv' orders = Orders.get_all() writer = csv.writer(self.response.out) writer.writerow(['Name', 'Email', 'Phone', 'Orders', "Total"]) for i in orders: items = "" total = 0 for j in i.orders: value1 = 0 if j['qty'] is None else j['qty'] total += (value1 * j['price']) items += "%s %s ; " % (j['name'], value1) row = i.name, i.email, i.phone, items, total writer.writerow(row)
def goods_order(): order_item = Orders() order_item.order_str_id = "OID" + datetime.datetime.now().strftime("%Y%m%d%H%M%S") order_item.member = session["uid"] order_item.order_date = func.now() db_session.add(order_item) db_session.commit() baskets = db_session.query(Basket).filter(Basket.member == session["uid"]) for basket_item in baskets: detail_item = OrdersItem() detail_item.goods = basket_item.goods detail_item.goods_price = basket_item.goods_item.price detail_item.goods_cnt = basket_item.goods_cnt db_session.add(detail_item) db_session.delete(basket_item) flash("주문이 완료되었습니다") db_session.commit() return redirect("/basket")
def create_orders(order: OrdersBase, db: Session): arsene = Response_SM(status=False, result='...') logger.info(f'status {order.status_id}') try: orders_data = Orders(table_id=order.table_id, status_id=order.status_id, creation=order.creation) db.add(orders_data) db.commit() db.refresh(orders_data) arsene.status = True if orders_data.id else False arsene.result = 'success' if orders_data else 'order cant create' except Exception as e: arsene.result = f'error {e}' logger.error(f'error {e}') return arsene
def get_order_id(_): # An order ID has a maximum size of 14. unique_id = generate_unique_id(Orders, Orders.order_id, 14) if unique_id == "": return exceptions.InternalServerError() current_order = Orders(order_id=unique_id) db.session.add(current_order) db.session.commit() return { "exemptionID": "YOO", "exemptionTEXT": "Everything is free! You get a photo, you get a photo, and you get a photo.", "available": 1, "orderID": unique_id, }
def post(self): orders = Orders.get_all() ret = [] dd = defaultdict(int) for i in orders: ret.append(i.to_dict()) for j in i.orders: value1 = 0 if j['qty'] is None else j['qty'] dd[j['name']] += value1 agg = [] for key, value in dd.items(): agg.append({ 'name': key, 'qty': value }) if len(ret) > 0: self.response.write(json.dumps({ 'ret': ret, 'agg': agg })) else: self.response.write(json.dumps(None))
def create_orders_ocd(order: OrderCreateOrders, db: Session): arsene = Response_SM_ID(status=False, result='...', id_rs=0) logger.info(f'status {order.status_id}') try: orders_data = Orders(table_id=order.table_id, status_id=order.status_id, creation=order.creation) db.add(orders_data) db.commit() db.refresh(orders_data) arsene.status = True if orders_data.id else False arsene.result = 'success' if orders_data else 'order cant create' if arsene.status: arsene.id_rs = orders_data.id create_detail_cn(arsene.id_rs, order.orders_detail, db) except Exception as e: arsene.result = f'error {e}' logger.error(f'error {e}') return arsene
def cart_view(): form = OrderForm() foods = Food.query.filter(Food.id.in_(session['cart'])) if request.method == 'POST' and form.validate_on_submit( ) and current_user.is_authenticated: if not foods: flash('Вы ничего не выбрали') return render_template('delivery/cart.html', form=form) orders = Orders(amount=sum(sub.price for sub in foods), status='good', phone=form.phone.data, address=form.address.data, user=User.query.get(current_user.get_id())) db.session.add(orders) for food in foods: orders.food.append(food) db.session.commit() session.pop('cart', None) return redirect(url_for('ordered_view')) return render_template('delivery/cart.html', form=form)
def handle_orders(): """ Create orders and retrieve all orders """ # ******************* POST REQUEST ******************* if request.method == 'POST': body = request.get_json() if body is None: raise APIException( "You need to specify the request body as a json object", status_code=400) if 'client_email' not in body: raise APIException('You need to specify client_email', status_code=400) # if 'total' not in body: # raise APIException('You need to specify the total', status_code=400) # if 'order_number' not in body: # raise APIException('You need to specify the order number', status_code=400) # if 'date_created' not in body: # raise APIException('You need to specify the date created', status_code=400) # if 'assigned_consultant' not in body: # raise APIException('You need to specify the assigned_consultant', status_code=400) items = body['items'] for item in items: order1 = Orders(client_email=item.client_email, total=item.price) db.session.add(order1) db.session.commit() return "ok", 200 # ******************* GET REQUEST ******************* if request.method == 'GET': all_orders = Orders.query.all() all_orders = list(map(lambda x: x.serialize(), all_orders)) return jsonify(all_orders), 200 return "Invalid Method", 404
def save_order(tablet, form): #from add it is called to add details into order table """ Save the changes to the database """ # Get data from form and assign it to the correct attributes # of the SQLAlchemy table object orderid = int(random.randint(1000, 2000)) orders = Orders() orders.quantity = int(form.quantity.data) orders.orderId = orderid orders.productId = tablet.tabletId orders.productname = tablet.tabletname orders.ordercost = tablet.tabletcost * orders.quantity tablet.tabletquantity = tablet.tabletquantity - orders.quantity db_session.add(orders) # commit the data to the database db_session.commit() return orderid
def order(request,communityId,goodsId): params = request.POST; gd = Goods.objects.select_related('community','groupProfile').filter(id=goodsId)[0] if gd.status == 1 : return HttpResponseRedirect(redirect_to=reverse("mm:detailGoods",args=[goodsId])) group = UserGroupProfile.objects.select_related('community').filter(user=request.user,community=gd.community)[0] order = Orders() order.groupProfile=group order.goods=Goods(id=goodsId) order.number=int(params["number"]) order.save() gdCategorys = GoodsCategory.objects.select_related('category').filter(product=order.goods) for gdc in gdCategorys: oc = OrderCategory(); oc.order=order oc.categoryValue = CategoryValue(id=int(params["ct"+str(gdc.category.id)])) oc.save() return HttpResponseRedirect(redirect_to=reverse("mm:detailGoods",args=[goodsId]))
def huntparse(): s = addpath('originals_bin/pdf/hunt/') t = addpath('processing/pdf_bin/hunt/') u = addpath('originals_processed/pdf') for file in os.listdir(s): if fnmatch.fnmatch(file, '*.pdf'): shutil.copy(s + file, u) shutil.move(s + file, t + file) data = addpath('processing/pdf_bin/hunt') done = addpath('processing/pdforder/') viewloc = addpath('tmp/data/vorders/') #Using new format here the left item is what we are looking for (keyword) and right side is the Label hitems = ['Total Rate:Amount', 'Commodity:commodity'] # These items we look to see if there are load and delivery points to add to database vadditems = ['Pickup', 'Shipper', 'Consignee', 'Delivery'] today = datetime.datetime.today() todaydate = today.date() todaynow = today.time() todaystr = datetime.datetime.today().strftime('%Y-%m-%d') year = str(today.year) day = str(today.day) month = str(today.month) #print(month,day,year) datestr = 'label:' + month + '/' + day + '/' + year pyr = year[2] + year[3] date_p1 = re.compile( r'(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|January|February|March|April|June|July|August|September|October|November|December)\s?\d{1,2},?\s?\d{4}' ) date_y2 = re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{2}') date_y4 = re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{4}') date_p3 = re.compile( r'\d{1,2}\s?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s?\d{4}' ) date_p4 = re.compile(r'\s' + pyr + '(?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])') time_p24 = re.compile( r'(?:[1-9]|0[0-9]|1[0-9]|2[01234])[:](?:0[0-9]|[12345][0-9])') container_p = re.compile(r'[A-Z,a-z]{4}\s?[Ool0123456789]{7}') amount_p = re.compile( r'\$(?:[0-9]|[0-9]{2}|[0-9]{3}|[1-9],[0-9]{3})\.[0-9]{2}') fcount = 0 for file2 in os.listdir(addpath('processing/pdf_bin/hunt')): if fnmatch.fnmatch(file2, '*.pdf'): fcount = fcount + 1 base = os.path.splitext(file2)[0] #print(base) load = base.replace('Tender_', '') print('Load=', load) if not load: load = '000000' #print(file2,base,load) print('Running file: ', file2) print( subprocess.check_output([ 'pdf2txt.py', '-o', done + load + '.txt', addpath('processing/pdf_bin/hunt/' + file2) ])) #See if the order exists already: o = Orders.query.filter(Orders.Original == file2).first() if o is None: jtype = 'T' nextjo = newjo(jtype, todaystr) #add some default values here for database: input = Orders(Status='A0', Jo=nextjo, Load=load, Order=load, Company=None, Location=None, Booking=None, BOL=None, Container=None, Date=None, Driver=None, Company2=None, Time=None, Date2=None, Time2=None, Seal=None, Pickup=None, Delivery=None, Amount=None, Path=None, Original=file2, Description='Load Broker Line Haul', Chassis=None, Detention='0', Storage='0', Release=0, Shipper='JB Hunt', Type=None, Time3=None, Bid=0, Lid=0, Did=0, Label=None, Dropblock1=None, Dropblock2=None, Commodity=None, Packing=None, Links=None, Hstat=-1, Istat=-1, Proof=None, Invoice=None, Gate=None, Package=None, Manifest=None, Scache=0, Pcache=0, Icache=0, Mcache=0, Pkcache=0, QBi=0, InvoTotal=None) db.session.add(input) db.session.commit() o = Orders.query.filter(Orders.Jo == nextjo).first() # Find and add load and delivery points to database for j, item in enumerate(vadditems): with open(done + load + '.txt') as openfile: for line in openfile: if len(line) > 3: linelist = line.split() word1 = linelist[0] if item == word1: line1 = line line2 = next(openfile) line3 = next(openfile) line4 = next(openfile) line5 = next(openfile) if j == 0: pickupdate = line2 print('pickupdate', pickupdate) linelist2 = line2.split() print('DATE', linelist2[0], flush=True) try: date1 = datetime.datetime.strptime( linelist2[0], '%Y-%m-%d') except: print('Could not convert:', date1, flush=True) date1 = todaydate try: time1 = datetime.datetime.strptime( linelist2[1], '%H:%M').time() except: time1 = todaynow o.Date = date1 o.Time = time1 db.session.commit() if j == 1: shipperlines = line2 + line3 + line4 + line5 print('shipperlines: ', shipperlines) o.Dropblock1 = shipperlines company = dropupdate(shipperlines) addr1 = line3.strip() cdat = Drops.query.filter( (Drops.Entity == company) & (Drops.Addr1 == addr1)).first() if cdat is not None: lid = cdat.id else: lid = 0 o.Company = company o.Lid = lid db.session.commit() if j == 2: consigneelines = line2 + line3 + line4 + line5 print('consigneelines: ', consigneelines) o.Dropblock2 = consigneelines company2 = dropupdate(consigneelines) addr1 = line3.strip() cdat = Drops.query.filter( (Drops.Entity == company2) & (Drops.Addr1 == addr1)).first() if cdat is not None: did = cdat.id else: did = 0 o.Company2 = company2 o.Did = did db.session.commit() if j == 3: deliverydate = line2 print('deliverydate', deliverydate) linelist2 = line2.split() #print('DATE',linelist2[0]) date2 = datetime.datetime.strptime( linelist2[0], '%Y-%m-%d') print(date1) time2 = datetime.datetime.strptime( linelist2[1], '%H:%M').time() o.Date2 = date2 o.Time2 = time2 db.session.commit() for item in hitems: list = [] label = item.split(':', 1)[1] item = item.split(':', 1)[0] with open(done + load + '.txt') as openfile: for line in openfile: if item.lower() in line.lower(): rest = line.lower().split(item.lower(), 1)[1] rest = line[-len(rest):] if ':' in rest: rest = rest.split(':', 1)[1] elif '#' in rest: rest = rest.split('#', 1)[1] elif 'NUMBER' in rest: rest = rest.split('NUMBER', 1)[1] rest = rest.replace('#', '') rest = rest.replace(':', '') rest = rest.replace('-', '') rest = rest.strip() #Could have multiple space inside words which we do not want to store in database: pieces = rest.split() phrase = '' for piece in pieces: piece = piece.strip() phrase = phrase + ' ' + piece rest = phrase.strip() #print('item=',item,'rest=',rest,'line=',line) lofrest = len(rest) if lofrest > 0: numbers = sum(c.isdigit() for c in rest) keyratio = float(numbers) / float(lofrest) else: keyratio = 0.0 if keyratio > .4: list.append(rest) if len(list) > 0: best = max(list, key=list.count) else: best = None if label == 'Amount': o.Amount = best db.session.commit() if label == 'commodity': o.Location = best db.session.commit() pdat = People.query.filter(People.Company == 'JB Hunt').first() if pdat is not None: bid = pdat.id else: bid = 0 book = 'JBHunt ' + load o.Booking = book o.Bid = bid o.Type = '53 Dry Van' db.session.commit() os.rename( addpath('processing/pdf_bin/hunt/') + file2, viewloc + file2) print('File ', fcount) return
if first_order is not None: print "customer %d already has orders" % (cust_index+1) continue customer_store = random.choice(stores) shipping_locs = session.query(ShippingLocation).filter_by(loyalty_number=customer.loyalty_number).all() print "\tGenerating first order" first_order_store = None if random.uniform(0,1) > .5: first_order_store = website else: first_order_store = customer_store first_order = Orders(order_date=customer.join_date, store_id=first_order_store.id, loyalty_number=customer.loyalty_number, payment_type=random.choice(payment_types)) if first_order_store.name == 'Website': first_order.shipping_loc = random.choice(shipping_locs).id first_order.shipping_cost = round(random.uniform(5, 20), 2) session.add(first_order) session.flush() generate_order_products(first_order, products) num_orders = random.randint(0, 50) last_order_date = customer.join_date for i in range(num_orders): print "\tGenerating order %d of %d" % (i+1, num_orders) # choose the order for the store
Base.metadata.create_all(engine) # Access data via a session Session = sessionmaker(bind=engine) session = Session() # Insert data iteratively, begin by filling out the dimension tables for status_ in list(new_data['STATUS'].unique()): status = Status(status=status_) session.add(status) session.commit() for country_ in list(new_data['COUNTRY'].unique()): country = Country(country=country_) session.add(country) session.commit() for order_ in new_data.to_dict(orient='records'): status = session.query(Status).filter( Status.status == order_['STATUS']).first() country = session.query(Country).filter( Country.country == order_['COUNTRY']).first() order = Orders(order_number=order_['ORDERNUMBER'], order_line_number=order_['ORDERLINENUMBER'], quantity_ordered=order_['QUANTITYORDERED'], price_each=order_['PRICEEACH'], sales=order_['SALES'], status=status, country=country) session.add(order) session.commit()
def api_delete_order(request, *, id): #check_admin(request) order = yield from Orders.find(id) yield from order.remove() return dict(id=id)
def api_get_order(*, id): order = yield from Orders.find(id) return order
def view(self): query = Orders.query() return_string = "```" for x in query: return_string += "{} ordered {} \n".format(x.user_name, x.order) return return_string + "```"
def new_order(): #check if fields are there if not request.is_json: return jsonify({'msg': 'JSON Requerido'}), 400 user = request.json.get('user') if not user: return {"msg": "user input is required"} restaurant = request.json.get('restaurant') if not restaurant: return {"msg": "restaurant input is required"} product = request.json.get('product') if not product: return {"msg": "product input is required"} total = request.json.get('total') if not product: return {"msg": "total input is required"} usuario = User.query.filter_by(id=user).first() if not usuario: return {"msg": "usuario inexistente"} comment = request.json.get('comment') #get the restaurant #add fields to sqlalchemy order = Orders() order.total = total order.id_restaurant = restaurant order.id_user = user order.comment = comment db.session.add(order) #actualize restaurant with new order number restaurant = Restaurantuser.query.filter_by(id=order.id_restaurant).first() restaurant.number_of_orders = restaurant.number_of_orders + 1 order.order_number = restaurant.number_of_orders db.session.commit() #add each detail for x in product: detail = Orders_details() detail.amount = x["amount"] detail.id_product = x["id_product"] detail.product_name = x["name_product"] detail.product_price = x["price"] detail.id_order = order.id_order db.session.add(detail) db.session.commit() #small function to add the id_order and serialize def allofthem(elem): diccionario = elem.serialize() diccionario["id_order"] = order.id_order return diccionario #return everything in an orderly fashion details = Orders_details.query.filter_by(id_order=order.id_order).all() details = list(map(allofthem, details)) #email here!! user = User.query.filter_by(id=order.id_user).first() if not user: return jsonify({"msg": "This user is not registered"}), 404 subject = "Reservation" try: sendMailNew("Order sent", user.email) except: print("there is no such mail as " + user.email) if not restaurant: return jsonify({"msg": "This restaurant is not registered"}), 404 subject = "Reservation" try: sendMailNew("New Order", restaurant.email) except: print( "there is no such mail as ", restaurant.email, ) return jsonify({"order": order.serialize()}), 200
from flask import Flask, jsonify, request from models import Orders app = Flask(__name__) order_obj = Orders() @app.route("/order") def order(): data = order_obj.all_orders() return jsonify(data) @app.route("/create_order", methods=["POST"]) def create_order(): order_payload = request.json order_obj.set_order(order_payload=order_payload) return jsonify({ "order_id": order_payload["order_id"], "stock_id": order_payload["stock_id"], "count": order_payload["count"], "price": order_payload["price"] }) @app.route("/delete_order", methods=["DELETE"]) def delete_order(): order_payload = request.json try: order_obj.delete_order(order_id=order_payload["order_id"])
products = [product] available = [] description = [] price = [] rating = [] types = [] type_id = [] ids = [] for i in products: ids.append(str(i.ProductID)) available.append(str(i.Available)) description.append(str(i.Description)) price.append(str(i.Price)) rating.append(str(i.Rating)) types.append(str(i.Type)) type_id.append(str(i.TypeID)) k = Orders.query.order_by(Orders.OrderID).all() next_cid = [0] for i in k: next_cid.append(int(str(i.OrderID).replace('O', ''))) next_cid.sort() my_id = "O" + str(next_cid[-1] + 1) today = date.today() order = Orders(OrderID=my_id, Price=price[0], Quantity=1, Time=(date.today()), ProductID=prodid, CustomerID=cid) db.session.add(order) db.session.commit()
input = Orders( Status='A0', Jo=nextjo, Load=load, Order=order, Company='Global Business Link', Location=None, Booking=b, BOL=None, Container='TBD', Date=book[1], Driver=None, Company2='Baltimore Seagirt', Time=None, Date2=book[2], Time2=None, Seal=None, Pickup=None, Delivery=None, Amount='275.00', Path=None, Original=None, Description=None, Chassis=None, Detention='0', Storage='0', Release=0, Shipper='Global Business Link', Type=None, Time3=None, Bid=bid, Lid=lid, Did=did, Label=None, Dropblock1= 'Global Business Link\n4000 Coolidge Ave K\nBaltimore, MD 21229', Dropblock2= 'Baltimore Seagirt\n2600 Broening Hwy\nBaltimore, MD 21224', Commodity='Auto', Packing='Each', Links=None, Hstat=-1, Istat=-1, Proof=None, Invoice=None, Gate=None, Package=None, Manifest=None, Scache=0, Pcache=0, Icache=0, Mcache=0, Pkcache=0, QBi=0, InvoTotal='275.00')
def add_order(request): #TODO: do a create order if request.method == 'POST': if 'payment_type' in request.POST: if request.POST['payment_type'] == 'card': summ = request.POST['total'] template = loader.get_template("add_order.html") context = RequestContext(request, {'summary': summ}) return HttpResponse(template.render(context)) elif 'order' in request.POST: baskets = Basket.objects.filter( basket_id=request.session.session_key) order = Orders() if request.user.is_authenticated(): order.owner = request.user order.order_id = baskets[0].order_number order.total_cost = float(request.POST['total']) order.address = request.POST['address'] order.comments = request.POST['comments'] order.billing_card = request.POST['billing_card'] order.billing_number = request.POST['billing_number'] order.billing_name = request.POST['billing_name'] order.billing_date_mm = request.POST['billing_date_mm'] order.billing_date_yy = request.POST['billing_date_yy'] order.billing_cvv = request.POST['billing_cvv'] order.save() for basket in baskets: orderitems = OrderItem() orderitems.order_id_id = order.order_id orderitems.order_sess = basket.basket_id orderitems.goods = basket.item orderitems.quantity = basket.quantity orderitems.total_price_per_goods = basket.sum_total orderitems.partnumber = basket.partnumber order.orderitem_set.add(orderitems) orderitems.save() order.save() template = loader.get_template("order_success.html") context = RequestContext(request, {'order_id': order.pk}) return HttpResponse(template.render(context))
def add_order(request): #TODO: do a create order if request.method == 'POST': if 'payment_type' in request.POST: if request.POST['payment_type'] == 'card': summ = request.POST['total'] template = loader.get_template("add_order.html") context = RequestContext(request, {'summary': summ}) return HttpResponse(template.render(context)) elif 'order' in request.POST: baskets = Basket.objects.filter(basket_id=request.session.session_key) order = Orders() if request.user.is_authenticated(): order.owner = request.user order.order_id = baskets[0].order_number order.total_cost = float(request.POST['total']) order.address = request.POST['address'] order.comments = request.POST['comments'] order.billing_card = request.POST['billing_card'] order.billing_number = request.POST['billing_number'] order.billing_name = request.POST['billing_name'] order.billing_date_mm = request.POST['billing_date_mm'] order.billing_date_yy = request.POST['billing_date_yy'] order.billing_cvv = request.POST['billing_cvv'] order.save() for basket in baskets: orderitems = OrderItem() orderitems.order_id_id = order.order_id orderitems.order_sess = basket.basket_id orderitems.goods = basket.item orderitems.quantity = basket.quantity orderitems.total_price_per_goods = basket.sum_total orderitems.partnumber = basket.partnumber order.orderitem_set.add(orderitems) orderitems.save() order.save() template = loader.get_template("order_success.html") context = RequestContext(request, {'order_id': order.pk}) return HttpResponse(template.render(context))
def knight_parse(): #Move all files in the originals_bin/pdf to the processing/pdf_bin #We have to move and preserve the original file to rename it based on order and load s=addpath('originals_bin/pdf/knight/') t=addpath('processing/pdf_bin/knight/') u=addpath('originals_processed/pdf') for file in os.listdir(s): if fnmatch.fnmatch(file, '*.pdf'): shutil.copy(s+file,u) shutil.move(s+file,t+file) data=addpath('processing/pdf_bin/knight') done=addpath('processing/pdforder/') viewloc=addpath(f'tmp/{scac}/data/vorders/') #Using new format here the left item is what we are looking for (keyword) and right side is the Label hitems=['Order:Order', 'BOL:BOL', 'Booking:Booking', 'Pick Up:Pickup', 'Delivery:Delivery'] # These items we look to see if there are load and delivery points to add to database vadditems=['Load At:Load at', 'Deliver To:Deliver to'] today = datetime.datetime.today() year= str(today.year) day=str(today.day) month=str(today.month) #print(month,day,year) datestr='label:'+month+'/'+day+'/'+year pyr=year[2]+year[3] date_p1=re.compile(r'(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|January|February|March|April|June|July|August|September|October|November|December)\s?\d{1,2},?\s?\d{4}') date_y2=re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{2}') date_y4=re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{4}') date_p3=re.compile(r'\d{1,2}\s?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s?\d{4}') date_p4=re.compile(r'\s'+pyr+'(?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])') time_p24=re.compile(r'(?:[1-9]|0[0-9]|1[0-9]|2[01234])[:](?:0[0-9]|[12345][0-9])') container_p = re.compile(r'[A-Z,a-z]{4}\s?[Ool0123456789]{7}') amount_p = re.compile(r'\$(?:[0-9]|[0-9]{2}|[0-9]{3}|[1-9],[0-9]{3})\.[0-9]{2}') orderdata = [] fcount=0 for file2 in os.listdir(addpath('processing/pdf_bin/knight')): if fnmatch.fnmatch(file2, '*.pdf'): fcount=fcount+1 base=os.path.splitext(file2)[0] #print(base) load=re.findall('\d+', base)[0] #print('Load=',load) if not load: load='000000' mysetlist={'Load':load} #print(file2,base,load) print ('Running file: ',file2) print (subprocess.check_output(['pdf2txt.py', '-o', done+load+'.txt', addpath('processing/pdf_bin/knight/'+file2)])) #add some default values here for database: mysetlist.update({'Status':'A0'}) mysetlist.update({'Description':'Load Broker Line Haul'}) mysetlist.update({'Chassis': 'NFO'}) mysetlist.update({'Detention': 0}) mysetlist.update({'Storage': 0}) mysetlist.update({'Release': 0}) mysetlist.update({'Container': 'NFO'}) mysetlist.update({'BOL': 'NFO'}) mysetlist.update({'Driver': 'NFO'}) mysetlist.update({'Company2': 'NFO'}) mysetlist.update({'Seal': 'NFO'}) mysetlist.update({'Shipper': 'Knight Logistics LLC'}) mysetlist.update({'Type': 'NFO'}) mysetlist.update({'Order': '000000'}) companyfound='' locationfound='' # Find and add load and delivery points to database for item in vadditems: subitem = item.split(':',1)[1] item = item.split(':',1)[0] label=item with open(done+load+'.txt') as openfile: for line in openfile: if re.search(item, line, re.IGNORECASE) or re.search(subitem, line, re.IGNORECASE): if re.search(item, line, re.IGNORECASE): test=item else: test=subitem rest=line.lower().split(test.lower(),1)[0] line1=line line2=next(openfile) line3=next(openfile) line4=next(openfile) l1=len(rest) st=max(0,l1-15) en=st+40 capture1=line2[st:en] capture2=line3[st:en] capture3=line4[st:en] capture1=capture1.strip() capture2=capture2.strip() capture3=capture3.strip() capture4=capture3.split(' ',1)[0] capture4=capture4.replace(',','') capture4=capture4.strip() #print(capture1) #print(capture2) #print(capture3) #print(capture4) if 'load' in line1.lower(): type='Load' if 'deliver' in line1.lower(): type='Deliver' #print(type) # Update Database company1=dropupdate(capture1+'\n'+capture2+'\n'+capture3+'\n'+capture4) if 'load' in line1.lower(): mysetlist.update({'Company' : company1}) if 'deliver' in line1.lower(): mysetlist.update({'Company2' : company1}) date=None date2=None time=None time2=None time3=None with open(done+load+'.txt') as openfile: for line in openfile: if 'earliest' in line.lower() and not date: datep=date_y2.findall(line) if datep: date=datetime.datetime.strptime(datep[0], '%m/%d/%y').strftime('%Y/%m/%d') datep=date_y4.findall(line) if datep: date=datetime.datetime.strptime(datep[0], '%m/%d/%Y').strftime('%Y/%m/%d') time=time_p24.findall(line) if time: time=time[0] else: time=None #print(line) #print(date) #print(time) mysetlist.update({'Date' : date}) mysetlist.update({'Time' : time}) date_p2=re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}') if 'earliest' in line.lower() and not date2: datep=date_y2.findall(line) if datep: date2=datetime.datetime.strptime(datep[0], '%m/%d/%y').strftime('%Y/%m/%d') datep=date_y4.findall(line) if datep: date2=datetime.datetime.strptime(datep[0], '%m/%d/%Y').strftime('%Y/%m/%d') time2=time_p24.findall(line) if time2: time2=time2[0] else: time2=None mysetlist.update({'Date2' : date2}) mysetlist.update({'Time2' : time2}) mysetlist.update({'Time3' : time3}) container=container_p.findall(line) if container: mysetlist.update({'Container' : container[0]}) for item in hitems: list=[] label = item.split(':',1)[1] item = item.split(':',1)[0] with open(done+load+'.txt') as openfile: for line in openfile: if item.lower() in line.lower(): rest=line.lower().split(item.lower(),1)[1] rest=line[-len(rest):] if ':' in rest: rest=rest.split(':',1)[1] elif '#' in rest: rest=rest.split('#',1)[1] elif 'NUMBER' in rest: rest=rest.split('NUMBER',1)[1] rest=rest.replace('#', '') rest=rest.replace(':', '') rest=rest.replace('-', '') rest=rest.strip() #Could have multiple space inside words which we do not want to store in database: pieces=rest.split() phrase='' for piece in pieces: piece=piece.strip() phrase=phrase + ' ' + piece rest=phrase.strip() #print('item=',item,'rest=',rest,'line=',line) lofrest=len(rest) if lofrest > 0: numbers = sum(c.isdigit() for c in rest) keyratio = float(numbers)/float(lofrest) else: keyratio = 0.0 if keyratio > .4: list.append(rest) if len(list)>0: best=max(list,key=list.count) else: best=None mysetlist.update({label : best}) print('This is what I got on each iteration', list) #Looking for amount in whole file: longs = open(done+load+'.txt').read() amount=amount_p.findall(longs) if amount: amount = [w.replace('$','') for w in amount] amount = [w.replace(',','') for w in amount] amt=[float(i) for i in amount] newamount="{:.2f}".format(max(amt)) mysetlist.update({'Amount': newamount}) #Little cheat, the future name of the document after signing #Need it here to save in database order=mysetlist["Order"] print(mysetlist) print(load) print(order) forig='load'+load+'_order' + order + '.pdf' try: os.remove(viewloc+forig) except: print('File does not yet exist: '+viewloc+forig) os.rename(addpath('processing/pdf_bin/knight/'+file2),viewloc+forig) mysetlist.update({'Original': forig}) # fsig='load'+load+'_order' + mysetlist["Order"] + '_sig.pdf' # mysetlist.update({'Orders_Signed': fsig}) orderdata.append(mysetlist) print('File ',fcount,flush=True) print(mysetlist) if 1==1: # Get the next Job Order number print('Now entering the parsed data into database...',flush=True) lv=JO.query.get(1) nextid=lv.nextid eval=str(nextid%100).zfill(2) day2="{0:0=2d}".format(int(day)) if month=='10': month='X' if month=='11': month='Y' if month=='12': month='Z' # The type and company can be changed depending on who is calling jtype='T' jcompany='F' nextjo=jcompany+jtype+month+day2+year[3]+eval #print(nextjo, today) for index in range(len(orderdata)): obj=orderdata[index] Order=obj.get("Order") Order=Order.strip() tDate=obj.get("Date") #print('tDate=',tDate) if tDate is not None and tDate != '': Date=datetime.datetime.strptime(tDate, '%Y/%m/%d') else: Date=today tDate=obj.get("Date2") if tDate is not None and tDate != '': Date2=datetime.datetime.strptime(tDate, '%Y/%m/%d') else: Date2=today loadcompany=obj.get("Company") pdata=People.query.filter(People.Company==loadcompany).first() if pdata is None: lid=None else: lid=pdata.id delivercompany=obj.get("Company2") pdata=People.query.filter(People.Company==delivercompany).first() if pdata is None: did=None else: did=pdata.id # Check to see if this order file is in database already: odata = Orders.query.filter(Orders.Order == Order).first() if odata is None: input = Orders(Status=obj.get("Status"), Jo=nextjo, Load=obj.get("Load"),Order=obj.get("Order"), Company=obj.get("Company"), Location=obj.get("Location"),Booking=obj.get("Booking"), BOL=obj.get("BOL"),Container=obj.get("Container"), Date=Date,Driver=obj.get("Driver"),Company2=obj.get("Company2"), Time=obj.get("Time"), Date2=Date2, Time2=obj.get("Time2"), Seal=obj.get("Seal"), Pickup=obj.get("Pickup"), Delivery=obj.get("Delivery"), Amount=obj.get('Amount'), Path=None, Original=obj.get('Original'), Description=obj.get("Description"), Chassis=obj.get('Chassis'), Detention=obj.get('Detention'), Storage=obj.get('Storage'), Release=obj.get('Release'), Shipper=obj.get('Shipper'), Type=obj.get('Type'), Time3=None, Bid=None, Lid=lid, Did=did, Label='', Dropblock1='',Dropblock2='', Commodity=None, Packing=None, Links=None, Hstat=-1, Istat=-1, Proof=None, Invoice=None, Gate=None, Package=None, Manifest=None, Scache=0, Pcache=0, Icache=0, Mcache=0, Pkcache=0, QBi=0, InvoTotal=obj.get('Amount')) print ('Data part ', index+1, ' of ', len(orderdata), 'is being added to database: Orders') db.session.add(input) input2 = JO(jo=nextjo, nextid=0, date=today, status=1) db.session.add(input2) nextid=nextid+1 lv.nextid=nextid eval=str(nextid%100).zfill(2) nextjo=jcompany+jtype+month+day2+year[3]+eval else: # The order already exists so we merge the new with the old if have no values print ('The data for dataset ', index+1, ' of ', len(orderdata), 'is already in the database: table Orders has been updated') odata.Date=Date odata.Time=obj.get("Time") odata.Date2=Date2 odata.Time2=obj.get("Time2") odata.Original=obj.get('Original') if odata.Pickup=='NFO' or odata.Pickup=='None' or odata.Pickup is None: odata.Pickup=obj.get("Pickup") if odata.Location=='NFO': odata.Location=Location if odata.Company=='NFO': odata.Company=obj.get("Company") if odata.Driver=='NFO': odata.Driver=obj.get("Driver") if odata.Booking=='NFO' or odata.Booking=='None' or odata.Booking is None: odata.Booking=obj.get("Booking") if odata.BOL=='NFO': odata.BOL=obj.get("BOL") if odata.Container=='NFO' or odata.Container=='None' or odata.Container is None: odata.Container=obj.get("Container") if odata.Delivery=='NFO': odata.Delivery=obj.get("Delivery") odata.Amount=obj.get('Amount') if odata.Company2=='NFO': odata.Company2=obj.get('Company2') if odata.Seal=='NFO': odata.Seal=obj.get('Seal') if odata.Shipper=='NFO': odata.Shipper=obj.get('Shipper') if odata.Type=='NFO': odata.Type=obj.get('Type') db.session.commit() print('Total # pdf files found: ', fcount)
async def get_orders(request_user_id: str = Header(None)): return await Order_Pydantic.from_queryset( Orders.filter(created_by=request_user_id))