def get_orders_of_sales(sales_id): status = request.args.get('status') if status: return Order.find_all_in_status_by_sales(sales_id, status) else: return Order.find_all_by_sales(sales_id)
def postOrder(restaurantId): order = json.loads(request.data) order['price'] = 0 returnableItemList = [] savedOrder = Order(restaurantId, order['name'], order['address'], order['phone'], order['price']) db.session().add(savedOrder) for item in order['items']: # Use actual db prices and items to calculate the price and give descriptions, rather than accepting whatever's posted by user itemInDb = MenuItem.query.filter_by(id=item['id']).first() savedOrder.price = round((savedOrder.price + itemInDb.price), 2) returnableItemList.append({ "id": itemInDb.id, "name": itemInDb.name, "description": itemInDb.description, "price": itemInDb.price }) # Create OrderMenuItem table items db.session().add(OrderMenuItem(savedOrder.id, itemInDb.id)) db.session().commit() return jsonify({ "orderId": savedOrder.id, "restaurantName": Restaurant.query.get(restaurantId).name, "name": savedOrder.name, "address": savedOrder.address, "phone": savedOrder.phone, "price": savedOrder.price, "items": returnableItemList })
def morning_call(): current_user = g.user store_id = get_or_set_store_id() today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) orders_stats = dict() orders_stats['yesterday_orders_count'] = Order.count_orders_by_date_and_store(yesterday, store_id) orders_stats['current_month_orders_count'] = Order.count_orders_from_date_and_store( datetime.date.today().replace(day=1), store_id) current_month_ta = TaSetting.find_active_monthly_ta(today.year, today.month, store_id) orders_stats['current_month_target'] = current_month_ta.value if current_month_ta else 'N/A' sales_stats = User.get_all_sales_by_store_from_cache(long(store_id)) yesterday_receptions = Reception.find_all_by_date_in_store(yesterday, store_id) today_appointments = Appointment.find_all_by_date_in_store(datetime.date.today(), store_id) rx_stats = dict() rx_stats['yesterday_incomplete_count'] = len( [x for x in yesterday_receptions if x._last_status_changer == 'system']) total_counts, sales_counts = calc_reception_counts(yesterday_receptions, sales_stats) for sale in sales_stats: sale.rx_count = sales_counts.get(sale.id, {'total': 0, 'new': 0, 'appt_new': 0, 'appt': 0, 'other': 0}) populate_appt_count_agg_by_sale_and_type(today_appointments, sale) sales_stats.sort(key=lambda sale: sale.rx_count, reverse=True) appts_count = generate_appt_count_agg_by_type(today_appointments) recent_campaigns = Campaign.find_all_by_store_in_recent_days(store_id, 15) current_endpoint = 'user.morning_call' now = datetime.datetime.now() yesterday_datetime = now - datetime.timedelta(days=1) rx_base_url, rx_url_params = get_filter_link('receptions.receptions', yesterday_datetime, yesterday_datetime, current_endpoint) rx_incomplete_params = rx_url_params.copy() rx_incomplete_params['incomplete'] = 'y' appt_base_url, appt_url_params = get_filter_link('appointments.appts', now, now, current_endpoint) order_base_url, order_url_params = get_filter_link('orders.orders', yesterday_datetime, yesterday_datetime, current_endpoint) monthly_order_url_params = order_url_params.copy() monthly_order_url_params['start_date'] = datetime.date.today().replace(day=1).strftime(DATE_FORMAT) monthly_order_url_params['end_date'] = now.strftime(DATE_FORMAT) return render_template('user/salesmanager/morningcall.html', selected_menu=USER_MORNING_CALL, orders_stats=orders_stats, sales_stats=sales_stats, appts_count=appts_count, total_rx_count=total_counts, recent_campaigns=recent_campaigns, recent_campaigns_count=len(recent_campaigns), current_month_ta=current_month_ta, rx_base_url=rx_base_url, rx_url_params=rx_url_params, appt_base_url=appt_base_url, appt_url_params=appt_url_params, rx_incomplete_params=rx_incomplete_params, order_base_url=order_base_url, order_url_params=order_url_params, monthly_order_url_params=monthly_order_url_params, rx_stats=rx_stats, back_endpoint=request.args.get('back_endpoint', None))
def order_get(order_id): order = Order.get_or_none(Order.id == order_id) if order is None: raise ApiException(Errors.NOT_FOUND, "order") order_dict = model_to_dict(Order.get_by_id(order_id)) order_dict["product"] = { "id": order.product.product.id, "quantity": order.product.quantity } return jsonify(order_dict)
def cancel_customer(cid): replaced_by_customer_id = request.json.get('by_customer_id') customer = get_customer(cid) customer.status = 'cancelled' customer.save_and_flush() replaced_by_customer = get_customer(replaced_by_customer_id) Appointment.reset_customer_id(customer, replaced_by_customer) Reception.reset_customer_id(customer, replaced_by_customer) Order.reset_customer_id(customer, replaced_by_customer) return replaced_by_customer
def count_rr_orders(start, end, store_id): result = [] refered_customers_order_ids = Order.count_all_refered_between_dates_in_store( start, end, store_id) if len(refered_customers_order_ids) > 0: result.extend(refered_customers_order_ids) reorder_customers_order_ids = Order.count_all_reorder_between_dates_in_store( start, end, store_id) if len(reorder_customers_order_ids) > 0: result.extend(reorder_customers_order_ids) return len(set(result))
def create_order_from_req(req, product): new_product_order = ProductOrder(product=product, quantity=req['product']['quantity']) new_product_order.save() total_price = req['product']['quantity'] * product.price order = Order(product=new_product_order, total_price=total_price, shipping_price=total_price + (5 if product.weight <= 500 else 10 if product.weight <= 2000 else 25)) order.save() return order
def get_order(uid): result = Order.find(uid) if result is None: return abort(404, description=gettext(u'Order with id %(id)s is not found', id=uid)) return result
def create_order(): data = request.json if data is None: abort(400, description=gettext('invalid json request')) validate_amounts_fields_in_orders(data) order = Order(**data) order.generate_order_no() order.save_and_flush() customer = Customer.find(order.customer_id) customer.status = 'ordered' Appointment.cancel_all_for_sales_customer( order.sales_id, order.customer_id, 'Order: ' + str(order.id) + ' is created') Reception.complete_all_for_sales_customer( order.sales_id, order.customer_id, 'Order: ' + str(order.id) + ' is created') return Order.find(order.id), 201, add_location_header( dict(), url_for('api.get_order', uid=order.id))
def add_client_info_from_req(req, order): new_shipping_info = dict_to_model(ShippingInformation, req['shipping_information']) order = Order.get_by_id(order.id) order.email = req['email'] order.shipping_information = new_shipping_info new_shipping_info.save() order.save()
def confirm_order(oid): order = Order.find(oid) if order is None: return abort(404, description=gettext(u'Order with id %(id)s is not found', id=oid)) order.is_confirmed = True return order
def save_order(cls, code_id, address, city, price): order = Order() order.code = cls.create_purchase_code(code_id) order.status = OrderStatus.PENDING order.address = address order.city = city order.total_price = price db.session.add(order) db.session.commit() return order
def order_put(order_id): order = Order.get_or_none(Order.id == order_id) if order is None: raise ApiException(Errors.NOT_FOUND, "order") req = request.json if 'order' not in request.json else request.json['order'] req["product"] = None if 'shipping_information' in req and 'email' in req and 'credit_card' in req: raise ApiException(Errors.PAYMENT_REQUEST_NOT_UNIQUE, "order") is_client_info_missing_from_req = not field_exists( req, ["email"]) or not field_exists( req["shipping_information"], ["country", "address", "postal_code", "city", "province"]) client_info_missing_from_model = order.email is None or order.shipping_information is None if client_info_missing_from_model and 'credit_card' in req: raise ApiException( Errors.MISSING_FIELD, 'order/credit_card', "Les informations du client sont nécessaire avant d'appliquer une carte de crédit" ) if client_info_missing_from_model and is_client_info_missing_from_req: raise ApiException(Errors.MISSING_FIELD, "order") if "credit_card" in req and not field_exists( req['credit_card'], ['name', 'number', 'expiration_year', 'cvv', 'expiration_month']): raise ApiException(Errors.MISSING_FIELD, "order/credit_card") if 'shipping_information' in req: OrderService.add_client_info_from_req(req, order) return order_get(order_id) if order.paid: raise ApiException(Errors.ALREADY_PAID, 'order/credit_card') payment_api_response = PaymentService.request_payment_to_api( req['credit_card'], order.shipping_price) if 'success' in payment_api_response and not payment_api_response[ 'success']: raise ApiException(Errors.CARD_DECLINED, 'order/payment') OrderService.add_payment_from_res(payment_api_response, order) return order_get(order_id)
def update_order(oid): result = Order.find(oid) if result is None: return abort(404, description=gettext(u'Order with id %(id)s is not found', id=id)) if result.status in ('delivered', 'cancelled'): return abort( 400, description=gettext(u'Cannot update delivered or cancelled order')) data = request.json new_status = data.get('status', 'new') result.status = new_status if result.status.lower() == 'cancelled': result.customer.reset_status() else: # FIXME use flask inputs to do validation validate_amounts_fields_in_orders(data) # update order data for key in Order.attributes_names(Order.excludes_attrs()): if data.get(key, None): setattr(result, key, data.get(key)) # FIXME: disable delivered followup temporarily # if result.status.lower() == 'delivered': # today = datetime.date.today() # delivered_date = parse_date(result.delivered_date) # if delivered_date >= today: # # make two appointments # Appointment.auto_make_delivered_followup_appointments(result) return result
def view_details(cid): current_user = g.user store_id = get_or_set_store_id() customer = Customer.find_by_id_and_store(cid, store_id) if not customer: abort(404) orders = Order.find_all_by_customer_sales(customer.id) appts = Appointment.find_all_by_customer_sales(customer.id) receptions = Reception.find_all_by_customer_sales(customer.id) calllogs = Calllog.find_all_by_customer_id(customer.id) form = CustomerReassignForm() form.saleses_list.choices = get_sales_selection(store_id) if current_user.is_receptionist() or ( current_user.is_sales() and current_user.is_role_in_store_id(store_id, 'manager') == False and customer.sales_id != current_user.id): abort(401) if request.method == 'GET': form.saleses_list.data = customer.sales_id if request.method == 'POST' and ( form.saleses_list.data not in ('None', customer.sales_id) and current_user.is_role_in_store_id(store_id, 'manager')): customer.reassign(int(form.saleses_list.data)) customer.save_and_flush() flash_success(u'重新分配成功') return redirect(url_for('customers.view_details', cid=cid, back_url=back_url( url_for('customers.customers'))), code=303) return render_template('customers/detail.html', selected_menu=CUSTOMER_MGMT, customer=customer, orders=orders, appts=appts, receptions=receptions, calllogs=calllogs, form=form, back_url=back_url(url_for('customers.customers')))
def reset_status(self): from application.models.appointment import Appointment if self.status == 'defeated': return elif len(Order.find_all_by_customer_sales(self.id, self.sales_id)): self.status = 'ordered' return elif Appointment.exist_opened_of_sales_customer(self.sales_id, self.id): self.status = 'enlist' return elif self.has_required_fields_filled(): self.status = 'formal' return else: self.status = 'draft' return
def validate(self, appt_data): now_time = datetime.now() appt_type = appt_data.get('type', None) appt_time = parse(appt_data.get('appt_datetime')) store_id = appt_data.get('store_id') if appt_type and appt_type == 'followup': customer = appt_data.get('customer', None) if customer and customer.is_active(): # 1. 未成交客户, 预约回访时间不得晚于当前时间+10天 general_time_limit = now_time + timedelta(days=10) if appt_time > general_time_limit: abort( 400, description=gettext( 'appt_datetime can not be later than %(days)s days', days=10)) # 2. 如果客户是首次客户, 首次预约回访时间不得晚于到店第二天晚上24时 receptions = Reception.find_all_by_customer_sales(customer.id) if receptions and len(receptions) == 1: last_rx_date = receptions[0].rx_date rx_limit = last_rx_date + timedelta(days=1) if not Appointment.exist_followup_between_dates_by_customer(parse_date(now_time), parse_date( rx_limit), customer.id, store_id) and parse_date(now_time) <= parse_date(rx_limit) \ < parse_date(appt_time): abort( 400, description=gettext( 'appt_datetime can not be later than 1 days for new customer' )) elif customer.status == 'ordered': # 3. 如果客户是交车客户, 预约交车时间不得晚于交车第二天晚上24时 order = Order.find_latest_delivered_order_by_customer( customer.id) if order: delivered_date = order.delivered_date order_limit = delivered_date + timedelta(days=1) if not Appointment.exist_followup_between_dates_by_customer(parse_date(now_time), parse_date( order_limit), customer.id, store_id) and parse_date(now_time) <= parse_date(order_limit) < \ parse_date(appt_time): abort( 400, description=gettext( 'appt_datetime can not be later than 1 days for delivered customer' ))
def orders(): store_id = request.args.get('store_id', None) if not store_id: store_id = get_or_set_store_id() from application.forms.order import OrderSearchForm search_form = OrderSearchForm(request.args) search_form.ordered_car_ids_filter.choices = get_intent_car_ids_selection( store_id) search_form.sales_filter.choices = get_sales_selection(store_id) search_form.status_filter.choices = get_status_selection() # build query query = dict() if search_form.start_date.data and search_form.start_date.data != '': query['start_date'] = search_form.start_date.data if search_form.end_date.data and search_form.end_date.data != '': query['end_date'] = search_form.end_date.data if search_form.ordered_car_ids_filter.data not in ('None', 'all'): query['ordered_car_ids'] = search_form.ordered_car_ids_filter.data if search_form.sales_filter.data not in ('None', 'all'): query['sales_id'] = search_form.sales_filter.data if search_form.status_filter.data not in ('None', 'all'): query['status'] = search_form.status_filter.data if search_form.keywords.data: query['keywords'] = search_form.keywords.data if search_form.history.data: query['history'] = search_form.history.data sort_params = SortMixin.get_order_query(search_form) if sort_params: query.update(sort_params) query.update(get_page_info(request)) cancel_form = OrderCancelForm() orders_list = Order.find_all_by_query_params_in_store(store_id, **query) return render_template('orders/orders.html', selected_menu=ORDERS_MGMT, form=search_form, orders=orders_list, cancel_form=cancel_form, back_endpoint=request.args.get( 'back_endpoint', None))
def merge_stores(from_store_id, to_store_id): passcode = request.args.get('passcode', None) if not passcode or not valid_passcode(passcode): abort(401) result = dict() result['receptions'] = Reception.migrate_store(from_store_id, to_store_id) result['customers'] = Customer.migrate_store(from_store_id, to_store_id) result['appointments'] = Appointment.migrate_store(from_store_id, to_store_id) from application.models.order import Order result['orders'] = Order.migrate_store(from_store_id, to_store_id) from application.models.calllog import Calllog result['calllogs'] = Calllog.migrate_store(from_store_id, to_store_id) from application.models.campaign import Campaign result['campaigns'] = Campaign.migrate_store(from_store_id, to_store_id) from application.models.driverecord import DriveRecord result['driverecords'] = DriveRecord.migrate_store(from_store_id, to_store_id) return result
def cancel_order(): current_user = g.user store_id = get_or_set_store_id() form = OrderCancelForm() if form.order_id.data is None or int(form.order_id.data) < 1: flash_error(u'订单信息错误,请选择需要取消的订单') else: order = Order.find_by_id_and_store(form.order_id.data, store_id) if not order: abort(404) if order and order.status not in ('delivered', 'cancelled'): order.status = 'cancelled' order.save_and_flush() flash_success(u'订单已取消') elif order: flash_error(u'订单已交车或已取消') else: flash_error(u'找不到需要取消的订单') return redirect(url_for('orders.orders'))
def dashboard(): current_user = g.user now = datetime.datetime.now() store_id = get_or_set_store_id() orders_stats = dict() orders_stats['today_orders_count'] = Order.count_orders_by_date_and_store(datetime.date.today(), store_id) orders_with_status = Order.find_orders_status_from_date_and_store(datetime.date.today().replace(day=1), store_id) orders_stats['current_month_new_count'] = len( [x for x in orders_with_status if x.status == 'new']) orders_stats['current_month_delivered_count'] = Order.count_delivered_orders_between_date_and_store(store_id, get_first_day_of_month( now).date(), now.date()) customer_stats = dict() today_receptions = Reception.find_all_of_today_in_store(store_id) completed_reception = filter(lambda rx: rx.status == 'completed', today_receptions) customer_stats['total'] = len(today_receptions) if today_receptions else 0 customer_stats['complete'] = len(completed_reception) if completed_reception else 0 customer_stats['instore'] = customer_stats['total'] - customer_stats['complete'] customer_stats['new'] = len([x for x in today_receptions if x.rx_type == 'new']) customer_stats['appt_new'] = len([x for x in today_receptions if x.rx_type == 'appt_new']) customer_stats['appt'] = len([x for x in today_receptions if x.rx_type == 'appt']) customer_stats['other'] = len([x for x in today_receptions if x.rx_type == 'other']) today_appointments = Appointment.find_all_by_date_in_store(datetime.date.today(), store_id) appt_stats = dict() appt_stats['instore'] = len([x for x in today_appointments if x.status != 'cancelled' and x.type == 'instore']) appt_stats['open_instore'] = len([x for x in today_appointments if x.status == 'opened' and x.type == 'instore']) appt_stats['followup'] = len([x for x in today_appointments if x.type == 'followup']) appt_stats['open_followup'] = len([x for x in today_appointments if x.status == 'opened' and x.type == 'followup']) sales = User.get_all_sales_by_store_from_cache(long(store_id)) # make sure the status is correct SalesStatus.reset_all_sales_status(store_id) sales_status = SalesStatus.get_all_sales_status(store_id) total_counts, reception_counts = calc_reception_counts(today_receptions, sales) for sale in sales: sale.status = sales_status.get(str(sale.id), 'free') set_status_label_and_style(sale) sale.rx_count = reception_counts.get(sale.id, {'total': 0, 'new': 0, 'appt_new': 0, 'appt': 0, 'other': 0}) # receptions_per_sale = filter(lambda rx: rx.sales_id == sale.id, today_receptions) # sale.rx_count = len(receptions_per_sale) if receptions_per_sale else 0 # total_rx_count += sale.rx_count sales.sort(key=lambda sale: sale.status) today_orders = Order.find_all_created_today_by_store(store_id) today_orders_count = len(today_orders) if today_orders else 0 current_endpoint = 'user.dashboard' rx_base_url, rx_url_params = get_filter_link('receptions.receptions', now, now, current_endpoint) order_base_url, order_url_params = get_filter_link('orders.orders', now, now, current_endpoint) monthly_order_url_params = order_url_params.copy() monthly_order_url_params.update({'start_date': datetime.date.today().replace(day=1).strftime(DATE_FORMAT)}) monthly_delivered_order_url_params = monthly_order_url_params.copy() monthly_delivered_order_url_params['status_filter'] = 'delivered' monthly_delivered_order_url_params['history'] = 'y' appt_base_url, appt_url_params = get_filter_link('appointments.appts', now, now, current_endpoint) # tbc_orders = Order.find_all_in_status_by_store(store_id, confirmed=0, status='new') return render_template('user/salesmanager/dashboard.html', selected_menu=USER_RT_DATA, orders_stats=orders_stats, appt_stats=appt_stats, customer_stats=customer_stats, sales=sales, today_orders=today_orders, total_count=total_counts, today_orders_count=today_orders_count, sales_receptions=reception_counts, rx_base_url=rx_base_url, rx_url_params=rx_url_params, order_base_url=order_base_url, order_url_params=order_url_params, monthly_order_url_params=monthly_order_url_params, monthly_delivered_order_url_params=monthly_delivered_order_url_params, appt_base_url=appt_base_url, appt_url_params=appt_url_params)
def stats_summary(): now = datetime.datetime.now() today = datetime.date.today() first_day_of_currrent_month = datetime.date.today().replace(day=1) store_id = get_or_set_store_id() current_endpoint = 'mmgmt.stats_summary' orders_stats = dict() orders_stats['today_orders_count'] = Order.count_orders_by_date_and_store( today, store_id) orders_stats[ 'today_delivered_count'] = Order.count_delivered_orders_between_date_and_store( store_id, today, today) orders_stats[ 'current_month_delivered_count'] = Order.count_delivered_orders_between_date_and_store( store_id, first_day_of_currrent_month, today) orders_stats['undelivered_count'] = Order.count_all_new_orders_by_store( store_id) # inv_status = dict() # inv_status['total_inv'] = ? rx_stats = dict() from application.models.reception import Reception today_receptions = Reception.find_all_of_today_in_store(store_id) rx_stats['rx_new'] = len( [rx for rx in today_receptions if rx.rx_type == 'new']) rx_stats['rx_appt_new'] = len( [rx for rx in today_receptions if rx.rx_type == 'appt_new']) rx_stats['rx_appt'] = len( [rx for rx in today_receptions if rx.rx_type == 'appt']) rx_stats['rx_other'] = len( [rx for rx in today_receptions if rx.rx_type == 'other']) rx_stats['rx_total'] = len(today_receptions) rx_stats['rx_instore'] = len( [rx for rx in today_receptions if rx.status != 'completed']) rx_base_url, rx_url_params = get_filter_link('receptions.receptions', now, now, current_endpoint) order_base_url, order_url_params = get_filter_link('orders.orders', now, now, current_endpoint) monthly_delivered_order_url_params = order_url_params.copy() monthly_delivered_order_url_params.update({ 'start_date': datetime.date.today().replace(day=1).strftime(DATE_FORMAT) }) monthly_delivered_order_url_params['status_filter'] = 'delivered' monthly_delivered_order_url_params['history'] = 'y' all_new_order_url_params = order_url_params.copy() all_new_order_url_params['start_date'] = '' all_new_order_url_params['end_date'] = '' all_new_order_url_params['status_filter'] = 'new' return render_template( 'mmgmt/summary.html', today_str=format_date_zh(datetime.date.today()), orders_stats=orders_stats, rx_stats=rx_stats, rx_base_url=rx_base_url, rx_url_params=rx_url_params, order_base_url=order_base_url, order_url_params=order_url_params, monthly_delivered_order_url_params=monthly_delivered_order_url_params, all_new_order_url_params=all_new_order_url_params)
def get_all_customer_orders(customer_id): sales_id = request.args.get("sales_id", None) return Order.find_all_by_customer_sales(customer_id, sales_id)
def get_store_orders(sid): status = request.args.get('status') confirmed = request.args.get('confirmed') return Order.find_all_in_status_by_store(sid, status, confirmed, **get_page_info(request))
def convert_from_reception(cls, reception): hc = cls.find_by_reception_id(reception.id) if not hc: hc = cls() hc.reception_id = reception.id hc.customer_id = reception.customer_id hc.store_id = reception.store_id hc.uuid = str(uuid.uuid4()) customer = reception.customer from application.models.hwaccount import HwjdAccount hwjd_account = HwjdAccount.find_by_store_id(hc.store_id) hc.company_code = hwjd_account.org_code if hwjd_account else '' hc.created_date = reception.rx_date hc.intent_car_code, hc.intent_car_model, hc.intent_car_name = convert_car_code( hc.store_id, customer.intent_car_ids) hc.visit_type = convert_visit_type(reception.rx_type) hc.rx_start = reception.created_on.strftime(TIME_FORMAT_WO_SEC) hc.rx_end = (reception.created_on + timedelta( seconds=reception.rx_duration)).strftime(TIME_FORMAT_WO_SEC) hc.rx_duration = reception.rx_duration hc.rx_type = convert_rx_type(reception.rx_type) hc.channel = u'其他' hc.sales = reception.sales.username hc.intent_car_color = customer.intent_car_colors.split( ',')[0] if customer.intent_car_colors and len( customer.intent_car_colors) > 0 else '' hc.intent_order_date = None hc.budget = customer.budget hc.payment = customer.payment hc.purchase_type = convert_purchase_type(customer) hc.intent_level = LookupValue.get_vendor_code_by_code( customer.intent_level, hc.store_id, 'intent-level') hc.on_file = convert_boolean(customer.mobile and len(customer.mobile) >= 11) hc.has_trail = convert_boolean( customer.test_drive_car_ids and customer.test_drive_car_ids != 'none' and len(customer.test_drive_car_ids) > 0) hc.name = customer.respect_name hc.age_group = LookupValue.get_vendor_code_by_code( customer.channel, hc.store_id, 'age-group') hc.gender = customer.gender_str hc.mobile = customer.mobile if customer.mobile and customer.mobile != '000' else '' hc.has_order = convert_boolean( Order.has_valid_orders_by_customer(hc.customer_id)) hc.discount = '' hc.price = '' hc.gadgets_gift = u'否' hc.gadgets_purchase = u'否' hc.competing_car_brand = u'未定' hc.competing_car_name = u'未定' hc.used_car_model = u'无' hc.remark = customer.remark from application.models.customer import CustomerAddlInfo addl_info = CustomerAddlInfo.find_by_customer_id(reception.customer_id) if addl_info: hc.purpose = addl_info.purpose hc.industry = addl_info.industry hc.district = addl_info.district hc.dealership = addl_info.dealership hc.used_car_value = addl_info.used_car_value hc.has_used_car_assess = addl_info.has_used_car_assessed return hc
def order_get_all(): return jsonify(list(Order.select().dicts()))
def evening_call(): current_user = g.user store_id = get_or_set_store_id() today = datetime.date.today() orders_stats = dict() orders_stats['today_orders_count'] = Order.count_orders_by_date_and_store(datetime.date.today(), store_id) orders_stats['current_month_orders_count'] = Order.count_orders_from_date_and_store( datetime.date.today().replace(day=1), store_id) current_month_ta = TaSetting.find_active_monthly_ta(today.year, today.month, store_id) orders_stats['current_month_target'] = current_month_ta.value if current_month_ta else 'N/A' sales_stats = User.get_all_sales_by_store_from_cache(long(store_id)) today_receptions = Reception.find_all_of_today_in_store(store_id) today_appointments = Appointment.find_all_by_date_in_store(datetime.date.today(), store_id) tomorrow_appointments = Appointment.find_all_by_date_in_store(datetime.date.today() + datetime.timedelta(days=1), store_id) total_counts, sales_counts = calc_reception_counts(today_receptions, sales_stats) for sale in sales_stats: populate_appt_count_agg_by_sale_and_type(today_appointments, sale, include_closed=True) populate_appt_count_agg_by_sale_and_type(tomorrow_appointments, sale, attr_prefix='tomorrow_') sale.rx_count = sales_counts.get(sale.id, {'total': 0, 'new': 0, 'appt_new': 0, 'appt': 0, 'other': 0}) appts_count = generate_appt_count_agg_by_type(today_appointments, include_closed=True) tomorrow_appts_count = generate_appt_count_agg_by_type(tomorrow_appointments) sales_stats.sort(key=lambda sale: sale.rx_count, reverse=True) rx_stats = {'today_incomplete_count': len([x for x in today_receptions if x.status != 'completed'])} appt_stats = dict() appt_stats['instore'] = len([x for x in today_appointments if x.status != 'cancelled' and x.type == 'instore']) appt_stats['open_instore'] = len([x for x in today_appointments if x.status == 'opened' and x.type == 'instore']) appt_stats['followup'] = len([x for x in today_appointments if x.type == 'followup']) appt_stats['open_followup'] = len([x for x in today_appointments if x.status == 'opened' and x.type == 'followup']) now = datetime.datetime.now() tomorrow_datetime = now + datetime.timedelta(days=1) current_endpoint = 'user.evening_call' rx_base_url, rx_url_params = get_filter_link('receptions.receptions', now, now, current_endpoint) rx_incomplete_params = rx_url_params.copy() rx_incomplete_params['status_filter'] = 'in-store' appt_base_url, appt_url_params = get_filter_link('appointments.appts', now, now, current_endpoint) tomorrow_appt_base_url, tomorrow_appt_url_params = get_filter_link('appointments.appts', tomorrow_datetime, tomorrow_datetime, current_endpoint) recent_campaigns = Campaign.find_all_by_store_in_recent_days(store_id, 15) order_base_url, order_url_params = get_filter_link('orders.orders', now, now, current_endpoint) monthly_order_url_params = order_url_params.copy() monthly_order_url_params['start_date'] = datetime.date.today().replace(day=1).strftime(DATE_FORMAT) monthly_order_url_params['end_date'] = now.strftime(DATE_FORMAT) return render_template('user/salesmanager/eveningcall.html', selected_menu=USER_EVENING_CALL, rx_stats=rx_stats, orders_stats=orders_stats, today_receptions_count=len(today_receptions), rx_incomplete_params=rx_incomplete_params, sales_stats=sales_stats, appts_count=appts_count, total_rx_count=total_counts, tomorrow_appts_count=tomorrow_appts_count, recent_campaigns=recent_campaigns, recent_campaigns_count=len(recent_campaigns), rx_base_url=rx_base_url, rx_url_params=rx_url_params, order_base_url=order_base_url, tomorrow_appt_base_url=tomorrow_appt_base_url, tomorrow_appt_url_params=tomorrow_appt_url_params, order_url_params=order_url_params, appt_stats=appt_stats, appt_base_url=appt_base_url, appt_url_params=appt_url_params, monthly_order_url_params=monthly_order_url_params, back_endpoint=request.args.get('back_endpoint', None))
def get_orders_count_by_car_models(start, end, store_id): orders_by_car = Order.count_all_by_car_models_bwteeen_dates_in_store( start, end, store_id) return {o[1]: o[0] for o in orders_by_car}