def get(self): staff = self.current_staff data = {} if staff: data = { "id": staff.id, "station_id": staff.station_id, "account_id": staff.account_id, "super_admin_status": staff.super_admin_status, "admin_status": staff.admin_status, "purchaser_status": staff.purchaser_status, "admin_permissions": staff.admin_permission_list, "purchaser_permissions": staff.purchaser_permission_list, "remarks": staff.remarks, "position": staff.position, "date_onboarding": TimeFunc.time_to_str(staff.date_onboarding, "date"), "birthday": TimeFunc.time_to_str(staff.birthday, "date"), "status": staff.status, } return self.send_success(data=data)
def scoped_date(date_param): if scope == 0: str_result = TimeFunc.time_to_str(date_param, "date") elif scope == 1: str_result = TimeFunc.time_to_str(date_param, "year") else: str_result = TimeFunc.time_to_str(date_param, "year_only") return str_result
def get(self): page = self.args.get("page", 0) limit = self.args.get("limit", 20) wish_orders = self.session.query(models.WishOrder) \ .filter(models.WishOrder.station_id == self.current_station.id) \ .order_by(models.WishOrder.wish_date.desc()) \ .offset(page * limit) \ .limit(limit) \ .all() # 门店数 shop_count = self.session.query(models.Shop.id) \ .filter(models.Shop.status == 0, models.Shop.station_id == self.current_station.id) \ .count() wish_order_ids = {order.id for order in wish_orders} demand_order_count_list = self.session.query(models.DemandOrder.wish_order_id, func.count(models.DemandOrder.id)) \ .filter(models.DemandOrder.status >= 1, models.DemandOrder.wish_order_id.in_(wish_order_ids)) \ .group_by(models.DemandOrder.wish_order_id) \ .all() demand_order_count_dict = { wish_order_id: count for wish_order_id, count in demand_order_count_list } order_list = [] for order in wish_orders: order_list.append({ "id": order.id, "station_id": order.station_id, "create_time": TimeFunc.time_to_str(order.create_time), "creator_id": order.creator_id, "demand_order_count": demand_order_count_dict.get(order.id, 0), "shop_count": shop_count, "wish_date": TimeFunc.time_to_str(order.wish_date, "date"), "status": order.status, }) has_more = len(wish_orders) >= limit return self.send_success(order_list=order_list, has_more=has_more)
def get(self): fee_types = self.args.get("types") date = self.args.get("date") from_date = self.args.get("from_date") before_date = self.args.get("before_date") page = self.args.get("page", 0) limit = self.args.get("limit", 20) fees = self.session.query(models.Fee) \ .filter(models.Fee.station_id == self.current_station.id) if fee_types is not None: fees = fees.filter(models.Fee.type.in_(fee_types)) if date is not None: fees = fees.filter(models.Fee.date == date) if from_date is not None: fees = fees.filter(models.Fee.date >= from_date) if before_date is not None: fees = fees.filter(models.Fee.date < before_date) fee_sum = fees.with_entities(func.sum(models.Fee.money)).scalar() or 0 fee_sum = check_float(fee_sum / 100) fees = fees.order_by(models.Fee.date.desc()).offset( page * limit).limit(limit).all() fee_list = [] for fee in fees: creator = fee.creator fee_list.append({ "id": fee.id, "date": TimeFunc.time_to_str(fee.date, "date"), "type": fee.type, "money": check_float(fee.money / 100), "remarks": fee.remarks, "creator_id": creator.id, "creator_name": creator.username, "create_time": TimeFunc.time_to_str(fee.create_time), }) has_more = len(fee_list) >= limit return self.send_success(fee_sum=fee_sum, fees=fee_list, has_more=has_more)
def get(self): page = self.args.get("page", 0) limit = self.args.get("limit", 20) orders = self.session.query(models.ExternalDemandOrder, models.ExternalDemandOrder.id, func.count(models.ExternalDemandOrderGoods.id)) \ .join(models.ExternalDemandOrderGoods, models.ExternalDemandOrderGoods.order_id == models.ExternalDemandOrder.id) \ .filter(models.ExternalDemandOrder.creator_id == self.current_user.id) \ .group_by(models.ExternalDemandOrder.id) \ .order_by(models.ExternalDemandOrder.id.desc()) \ .offset(page * limit) \ .limit(limit) \ .all() data_list = [] for order, order_id, goods_count in orders: data_list.append({ "id": order.id, "demand_date": TimeFunc.time_to_str(order.demand_date, "date"), "shop_name": order.object_name, "goods_count": goods_count or 0, "status": order.status, }) has_more = len(data_list) >= limit return self.send_success(data_list=data_list, has_more=has_more)
def send_pf_demand_order(self, phone, shop_id, order_id, demand_date, demand_list): """ 向批发系统发起订货请求 """ shop_id = PfSimpleEncrypt.encrypt(shop_id) url = "{}/oauth/caigou/demand/{}".format(PF_ROOT_HOST_NAME, shop_id) phone = PfSimpleEncrypt.encrypt(phone) parameters = { 'passport_id': self.encrypted_passport_id, 'auth_token': self.auth_token, 'phone': phone, 'external_demand_id': order_id, 'expect_receive_date': TimeFunc.time_to_str(demand_date, "date"), 'demand_list': demand_list, } result = requests.post(url, json=parameters, verify=False) ret_dict = {} err_dict = {"success": False, "msg": "批发系统接口异常"} res_dict = result.json() if result else err_dict ret_dict["success"] = res_dict.get('success', False) ret_dict["msg"] = res_dict.get('msg', '') return ret_dict
def get(self, station_id): station = models.TransferStation.get_by_id(self.session, station_id) if not station: return self.send_fail("没有找到该中转站") staff = self.session.query(models.Staff) \ .filter(models.Staff.account_id == self.current_user.id, models.Staff.station_id == station.id, models.Staff.status == 0) \ .first() if not staff: return self.send_fail("您不是该中转站的员工") if staff.admin_status != 1 and staff.super_admin_status != 1: return self.send_fail("您无权查看该中转站的信息") station_data = { "id": station.id, "name": station.name, "creator_id": station.creator_id, "province": station.province, "city": station.city, "address": station.address, "create_time": TimeFunc.time_to_str(station.create_time), "status": station.status, } return self.send_success(station=station_data)
def post(self): allocation_order_id = self.args["allocation_order_id"] order = models.AllocationOrder.get_by_id(self.session, allocation_order_id, self.current_station.id) config = models.Config.get_by_station_id(self.session, self.current_station.id) printer_id = config.allocation_printer_id copies = config.allocation_print_copies printer = models.Printer.get_by_id(self.session, printer_id, self.current_station.id) if not printer: return self.send_fail("分车单打印机设置无效,请在中转站设置中配置") goods = order.goods purchase_order_goods = order.purchase_order_goods goods_list = order.goods_list total_amount = 0 allocation_list = [] for order_goods in goods_list: total_amount += order_goods.actual_allocated_amount if order_goods.destination == 0: shop = order_goods.shop shop_name = shop.abbreviation if shop else "未知店铺" elif order_goods.destination == 1: shop_name = "仓库" elif order_goods.destination == 2: shop_name = "其他" else: shop_name = "" allocation_list.append({ "shop_name": shop_name, "allocating_amount": check_float(order_goods.actual_allocated_amount / 100) }) # 打印分车单据 receipt_printer = ReceiptPrinter(printer.wireless_print_num, printer.wireless_print_key) receipt_content = receipt_printer.allocation_order_template( goods_name=goods.name, firm_name=purchase_order_goods.firm.name if purchase_order_goods else "仓库", order_no=order.order_no, total_amount=check_float(total_amount / 100), allocation_list=allocation_list, operator_name=self.current_user.username, create_time=TimeFunc.time_to_str(datetime.datetime.now()), ) for i in range(copies): success, error_msg = receipt_printer.print(receipt_content) if not success: return self.send_fail(error_msg) return self.send_success()
def time_summary(self): firm_id = self.args["firm_id"] size = self.args["size"] # 日期范围内的汇总粒度 0-每天的汇总 1-每月的汇总 from_date = self.args["from_date"] before_date = self.args["before_date"] # 更新一下统计表相关信息 update_firm_payment_statistics(self.session, self.statistic_session, station_id=self.current_station.id) statics_date = self.statistic_session.query(models_statistics.StatisticsFirmPayment) \ .filter(models_statistics.StatisticsFirmPayment.firm_id == firm_id, func.DATE(models_statistics.StatisticsFirmPayment.statistics_date) >= from_date, func.DATE(models_statistics.StatisticsFirmPayment.statistics_date) <= before_date) \ .group_by(func.DATE(models_statistics.StatisticsFirmPayment.statistics_date)).all() # 汇总计算 summary_dict = {} for data in statics_date: order_count = data.settle_times voucher_count = data.settle_nums total_money = data.settle_money settlement_date = data.statistics_date if size == 1: date = TimeFunc.time_to_str(settlement_date, "year") elif size == 0: date = TimeFunc.time_to_str(settlement_date, "date") else: date = TimeFunc.time_to_str(settlement_date, "date") if date not in summary_dict: summary_dict[date] = { "order_count": 0, "voucher_count": 0, "total_money": 0, } summary_dict[date]["order_count"] += order_count summary_dict[date]["voucher_count"] += voucher_count summary_dict[date]["total_money"] += total_money summarys = sorted([{ "date": key, "order_count": value["order_count"], "voucher_count": value["voucher_count"], "total_money": check_float(value["total_money"] / 10000), } for key, value in summary_dict.items()], key=lambda i: i["date"], reverse=True) return self.send_success(summarys=summarys)
def get(self): shop_id = self.args["shop_id"] from_date = self.args.get("from_date") to_date = self.args.get("to_date") before_date = self.args.get("before_date") order_by = self.args.get("order_by") asc = self.args.get("asc", False) page = self.args.get("page", 0) limit = self.args.get("limit", 20) payouts = self.session.query(models.ShopPayout, models.AccountInfo) \ .join(models.AccountInfo) \ .filter(models.ShopPayout.station_id == self.current_station.id, models.ShopPayout.shop_id == shop_id) if from_date: payouts = payouts.filter(models.ShopPayout.date >= from_date) if to_date: payouts = payouts.filter(models.ShopPayout.date <= to_date) if before_date: payouts = payouts.filter(models.ShopPayout.date < before_date) payout_sum = payouts.with_entities(func.sum( models.ShopPayout.money)).first() if order_by == "money": if asc: payouts = payouts.order_by(models.ShopPayout.money.asc()) else: payouts = payouts.order_by(models.ShopPayout.money.desc()) payouts = payouts.offset(page * limit).limit(limit).all() data_list = [] for payout, creator in payouts: data_list.append({ "id": payout.id, "creator": creator.username, "create_time": TimeFunc.time_to_str(payout.create_time), "type": payout.type, "money": check_float(payout.money / 100), "remarks": payout.remarks, }) sum_data = { "money": check_float( (payout_sum[0] or 0) / 100) if payout_sum else 0, } has_more = len(data_list) >= limit return self.send_success(data_list=data_list, sum_data=sum_data, has_more=has_more)
def goods_summary_detail(self, staff): goods_id = self.args["goods_id"] start_date = self.args["start_date"] end_date = self.args["end_date"] purchase_goods_objs = self.session.query(models.PurchaseOrderGoods)\ .filter(func.DATE(models.PurchaseOrderGoods.create_time) >= start_date, func.DATE(models.PurchaseOrderGoods.create_time) < end_date, models.PurchaseOrderGoods.goods_id == goods_id, models.PurchaseOrderGoods.purchaser_id == staff.id, models.PurchaseOrderGoods.firm_id >= 0, models.PurchaseOrderGoods.status >= 0)\ .all() day_purchase_dict = defaultdict(list) for purchase_goods in purchase_goods_objs: purchase_date = TimeFunc.time_to_str(purchase_goods.create_time, _type="date") day_purchase_dict[purchase_date].append(purchase_goods.to_dict()) purchase_goods_data_list = list() goods_summary_data = defaultdict(int) total_actual_amount = 0 total_spending = 0 for date, purchase_goods_info in day_purchase_dict.items(): data = dict() data["date"] = date # 供货商列表 data["firm_name_list"] = list({ purchase_goods["firm_name"] for purchase_goods in purchase_goods_info }) # 总件数 data["goods_amount"] = check_float( sum(purchase_goods["actual_amount"] for purchase_goods in purchase_goods_info)) # 总支出 data["goods_subtotal"] = check_float( sum(purchase_goods["subtotal"] for purchase_goods in purchase_goods_info)) # 单价/元 data["price"] = check_float(data["goods_subtotal"] / data["goods_amount"]) purchase_goods_data_list.append(data) total_actual_amount += data["goods_amount"] total_spending += data["goods_subtotal"] # 按商品汇总数据 goods_summary_data["total_actual_amount"] += check_float( total_actual_amount) goods_summary_data["total_spending"] += check_float(total_spending) # 排序 purchase_goods_data_list = sorted(purchase_goods_data_list, key=lambda x: x["date"], reverse=True) return self.send_success( purchase_goods_data_list=purchase_goods_data_list, goods_summary_data=goods_summary_data)
def get(self): page = self.args.get("page", 0) limit = self.args.get("limit", 20) shops = self.session.query(models.Shop) \ .filter(models.Shop.station_id == self.current_station.id, models.Shop.status == 0) \ .offset(page * limit) \ .limit(limit) \ .all() shop_ids = [shop.id for shop in shops] contacts = models.ShopContact.get_by_shop_ids(self.session, shop_ids) contacts_dict = defaultdict(list) [contacts_dict[contact.shop_id].append(contact) for contact in contacts] # 店铺订货人对应的用户信息 contact_account_ids = {contact.account_id for contact in contacts} accounts = models.AccountInfo.get_by_ids(self.session, contact_account_ids) account_dict = {account.id: account for account in accounts} shop_list = [] for shop in shops: contacts = contacts_dict.get(shop.id, []) contacts_data = [] for contact in contacts: account = account_dict.get(contact.account_id) contacts_data.append({ "id": contact.id, "account_id": contact.account_id, "shop_id": contact.shop_id, "name": contact.name, "phone": contact.phone, "avatar": account.headimgurl if account else "", "status": contact.status, }) shop_data = { "id": shop.id, "serial_number": shop.serial_number, "name": shop.name, "station_id": shop.station_id, "creator_id": shop.creator_id, "create_time": TimeFunc.time_to_str(shop.create_time), "abbreviation": shop.abbreviation, "address": shop.address, "status": shop.status, "contacts": contacts_data, } shop_list.append(shop_data) has_more = len(shops) >= limit return self.send_success(shop_list=shop_list, has_more=has_more)
def get(self): wish_date = self.args["wish_date"] order = self.session.query(models.WishOrder) \ .filter(models.WishOrder.wish_date == wish_date, models.WishOrder.station_id == self.current_station.id) \ .first() if not order: return self.send_fail("{} 没有意向单".format( TimeFunc.time_to_str(wish_date, "date"))) return self.send_success(order_id=order.id)
def get(self): shop = self.current_shop data = {} if shop: data = { "id": shop.id, "name": shop.name, "abbreviation": shop.abbreviation, "address": shop.address, "create_time": TimeFunc.time_to_str(shop.create_time), "status": shop.status, "station_name": shop.station.name } return self.send_success(data=data)
def get(self, order_id): order = models.WishOrder.get_by_id(self.session, order_id, self.current_station.id) if not order: self.write("没有找到该意向单") raise Finish() goods_list = models.WishOrderGoods.get_by_order_id(self.session, order_id) # 默认采购员信息 goods_ids = {goods.goods_id for goods in goods_list} default_purchasers = self.session.query(models.StaffGoods, models.Staff, models.AccountInfo) \ .join(models.Staff, models.Staff.id == models.StaffGoods.staff_id) \ .join(models.AccountInfo, models.AccountInfo.id == models.Staff.account_id) \ .filter(models.StaffGoods.goods_id.in_(goods_ids)) \ .all() default_purchaser_dict = {item[0].goods_id: item for item in default_purchasers} workbook = Workbook() worksheet = workbook.active worksheet.title = "意向单" # 表头 worksheet.cell(column=1, row=1, value="嘿嘛{}月{}日各店剩货及意向单".format(order.wish_date.month, order.wish_date.day)) worksheet.merge_cells("A1:G1") worksheet.cell(column=1, row=2, value="序号") worksheet.cell(column=2, row=2, value="条码") worksheet.cell(column=3, row=2, value="商品名称") worksheet.cell(column=4, row=2, value="负责人") worksheet.cell(column=5, row=2, value="剩货数量") worksheet.cell(column=6, row=2, value="意向数量") worksheet.cell(column=7, row=2, value="说明") # 意向单商品列表 for idx, wish_goods in enumerate(goods_list): row = 3 + idx goods = wish_goods.goods purchaser = default_purchaser_dict.get(goods.id) purchaser_name = purchaser[1].remarks or purchaser[2].username if purchaser else "" worksheet.cell(column=1, row=row, value=idx + 1) worksheet.cell(column=2, row=row, value=goods.code or "") worksheet.cell(column=3, row=row, value=wish_goods.goods_name or goods.name) worksheet.cell(column=4, row=row, value=purchaser_name) worksheet.cell(column=5, row=row, value="") worksheet.cell(column=6, row=row, value="") worksheet.cell(column=7, row=row, value=wish_goods.remarks) file_name = "{}各店意向单".format(TimeFunc.time_to_str(order.wish_date, "date")) return self.export_xlsx(workbook, file_name)
def get(self): station = self.current_station data = {} if station: data = { "id": station.id, "name": station.name, "province": station.province, "city": station.city, "address": station.address, "create_time": TimeFunc.time_to_str(station.create_time), "status": station.status, } return self.send_success(data=data)
def get(self): user = self.current_user if not user: return self.send_success() user_data = { "id": user.id, "phone": user.phone, "avatar": user.headimgurl, "sex": user.sex, "birthday": TimeFunc.time_to_str(user.birthday, "date"), "wx_unionid": user.wx_unionid, "realname": user.realname, "nickname": user.nickname, } return self.send_success(user=user_data)
def get(self): role = self.args.get("role", "").strip() # 当前用户作为管理员和采购员的所有中转站 station_query_set = self.session.query(models.TransferStation)\ .join(models.Staff, models.Staff.station_id == models.TransferStation.id)\ .filter(models.TransferStation.status == 0, models.Staff.status == 0, models.Staff.account_id == self.current_user.id) if role == "admin": stations = station_query_set.filter(or_(models.Staff.super_admin_status == 1, models.Staff.admin_status == 1))\ .all() elif role == "purchaser": stations = station_query_set.filter(models.Staff.purchaser_status == 1)\ .all() else: # 默认拿管理员的中转站列表 stations = station_query_set.filter(or_(models.Staff.super_admin_status == 1, models.Staff.admin_status == 1)) \ .all() station_list = [] for station in stations: station_list.append({ "id": station.id, "name": station.name, "creator_id": station.creator_id, "province": station.province, "city": station.city, "address": station.address, "create_time": TimeFunc.time_to_str(station.create_time), "status": station.status, }) return self.send_success(station_list=station_list)
def post(self): printer_id = self.args["printer_id"] printer = models.Printer.get_by_id(self.session, printer_id, self.current_station.id) if not printer: return self.send_fail("选择了无效的打印机") receipt_printer = ReceiptPrinter(printer.wireless_print_num, printer.wireless_print_key) receipt_content = receipt_printer.test_order_template( printer_remarks=printer.remarks, printer_num=printer.wireless_print_num, printer_key=printer.wireless_print_key, operator_name=self.current_user.username, create_time=TimeFunc.time_to_str(datetime.datetime.now()), ) success, error_msg = receipt_printer.print(receipt_content) if not success: return self.send_fail(error_msg) return self.send_success()
def month_summary_record(self, staff): # TODO 月年的因为数据量不会多于 20 条,暂时不分页 purchase_goods_objs = self.session.query(models.PurchaseOrderGoods)\ .filter(models.PurchaseOrderGoods.purchaser_id == staff.id, models.PurchaseOrderGoods.firm_id >= 0, models.PurchaseOrderGoods.status >= 0)\ .all() month_purchase_dict = defaultdict(list) for purchase_goods in purchase_goods_objs: purchase_date = TimeFunc.time_to_str(purchase_goods.create_time, _type="year") month_purchase_dict[purchase_date].append(purchase_goods.to_dict()) purchase_goods_data_list = list() for year, purchase_goods_info in month_purchase_dict.items(): data = dict() data["year"] = year # 货品数(区分日期) data["goods_num"] = 0 data["goods_num"] += len({ purchase_goods["goods_id"] for purchase_goods in purchase_goods_info }) # 总件数 data["goods_amount"] = check_float( sum(purchase_goods["actual_amount"] for purchase_goods in purchase_goods_info)) # 总支出 data["goods_subtotal"] = check_float( sum(purchase_goods["subtotal"] for purchase_goods in purchase_goods_info)) purchase_goods_data_list.append(data) # 排序 purchase_goods_data_list = sorted(purchase_goods_data_list, key=lambda x: x["year"], reverse=True) return self.send_success( purchase_goods_data_list=purchase_goods_data_list)
def get(self, order_id): order = models.WishOrder.get_by_id(self.session, order_id) if not order: return self.send_fail("没有找到指定的意向单") wish_order_id = order_id # 统计已提交及汇总的订货单 demand_orders = self.session.query(models.DemandOrder, models.AccountInfo) \ .join(models.AccountInfo, models.DemandOrder.creator_id == models.AccountInfo.id) \ .filter(models.DemandOrder.wish_order_id == wish_order_id, models.DemandOrder.status != 0).all() shop_id_list = [u.shop_id for u, _ in demand_orders] shop_contact_list = self.session.query(models.ShopContact) \ .filter(models.ShopContact.shop_id.in_(shop_id_list)).all() shop_contact_dict = {} for shop_contact in shop_contact_list: shop_contact_dict[shop_contact.phone] = shop_contact.name shops = self.session.query(models.Shop).filter( models.Shop.id.in_(shop_id_list)) shop_name_dict = {} for shop in shops: shop_name_dict[shop.id] = shop.abbreviation demand_order_data = [] for demand_order, account_info in demand_orders: demand_order_data.append({ "creator": shop_contact_dict.get(account_info.phone, "") or account_info.username, "creator_id": account_info.id, "shop_id": demand_order.shop_id, "shop": shop_name_dict[demand_order.shop_id], "create_time": TimeFunc.time_to_str(demand_order.create_time), "headimgurl": account_info.headimgurl }) return self.send_success(demand_order_data=demand_order_data)
def get(self, shop_id): shop = models.Shop.get_by_id(self.session, shop_id, self.current_station.id) if not shop: return self.send_fail("没有找到此店铺") contacts = models.ShopContact.get_by_shop_id(self.session, shop.id) # 店铺订货人对应的用户信息 contact_account_ids = {contact.account_id for contact in contacts} accounts = models.AccountInfo.get_by_ids(self.session, contact_account_ids) account_dict = {account.id: account for account in accounts} contacts_data = [] for contact in contacts: account = account_dict.get(contact.account_id) contacts_data.append({ "id": contact.id, "account_id": contact.account_id, "shop_id": contact.shop_id, "phone": contact.phone, "name": contact.name, "avatar": account.headimgurl if account else "", "status": contact.status, }) shop_data = { "id": shop.id, "name": shop.name, "station_id": shop.station_id, "creator_id": shop.creator_id, "create_time": TimeFunc.time_to_str(shop.create_time), "abbreviation": shop.abbreviation, "address": shop.address, "status": shop.status, "contacts": contacts_data, } return self.send_success(shop=shop_data)
def post(self): record_id = self.args["record_id"] printer_id = self.args["printer_id"] record = models.StockOutInGoods.get_by_id(self.session, record_id, self.current_station.id, status_list=[2, 3, 4]) if not record: return self.send_fail("没有找到指定的出库单") printer = models.Printer.get_by_id(self.session, printer_id, self.current_station.id) if not printer: return self.send_fail("选择了无效的打印机") number_map = self.session.query(models.SerialNumberMap) \ .filter(models.SerialNumberMap.order_type == 2, models.SerialNumberMap.order_id == record.id) \ .first() if not number_map: return self.send_fail("该出库单没有有效的出库单号") receipt_printer = ReceiptPrinter(printer.wireless_print_num, printer.wireless_print_key) receipt_content = receipt_printer.stock_out_order_template( goods_name=record.goods.name, order_no=number_map.order_no, amount=check_float(record.amount / 100), operator_name=record.operator.username, create_time=TimeFunc.time_to_str(record.create_time), ) success, error_msg = receipt_printer.print(receipt_content) if not success: return self.send_fail(error_msg) return self.send_success()
def get_goods_demand_by_week(self): """ 按周获取订货信息,查询最近三周的统计数据 """ goods_id = self.args.get("goods_id", 0) today = datetime.date.today() this_week_start_date, _ = TimeFunc.get_week_start_end(today) last_week_start_date = this_week_start_date + datetime.timedelta( days=-7) last_week_end_date = last_week_start_date + datetime.timedelta(days=6) pre_week_start_date = this_week_start_date + datetime.timedelta( days=-14) pre_week_end_date = pre_week_start_date + datetime.timedelta(days=6) # 查询这周,上周,上上周的记录 data_list = [] this_week = this_week_start_date.strftime( "%m-%d") + "~" + today.strftime("%m-%d") this_week_dict = self.get_goods_demand_base(goods_id, this_week_start_date, 2) this_week_dict["date_text"] = this_week data_list.append(this_week_dict) last_week = last_week_start_date.strftime( "%m-%d") + "~" + last_week_end_date.strftime("%m-%d") last_week_dict = self.get_goods_demand_base(goods_id, last_week_start_date, 2) last_week_dict["date_text"] = last_week data_list.append(last_week_dict) pre_week = pre_week_start_date.strftime( "%m-%d") + "~" + pre_week_end_date.strftime("%m-%d") pre_week_dict = self.get_goods_demand_base(goods_id, pre_week_start_date, 2) pre_week_dict["date_text"] = pre_week data_list.append(pre_week_dict) return self.send_success(data_list=data_list)
def get(self): today = datetime.date.today() from_date = self.args.get("from_date", today - datetime.timedelta(days=30)) to_date = self.args.get("to_date", today) firm_ids = self.args.get("firm_ids") firm_ids = set(map(lambda i: check_int(i), firm_ids.split("|"))) if firm_ids else None page = self.args.get("page", 0) limit = self.args.get("limit", 20) # 预先对结算单分页 order_ids_base = self.session.query(models.FirmSettlementOrder.id) \ .join(models.FirmSettlementVoucher, models.FirmSettlementVoucher.settlement_order_id == models.FirmSettlementOrder.id) \ .filter(models.FirmSettlementOrder.station_id == self.current_station.id, func.DATE(models.FirmSettlementOrder.create_time) >= from_date, func.DATE(models.FirmSettlementOrder.create_time) <= to_date) \ .order_by(models.FirmSettlementOrder.create_time.desc()) # 未筛选的所有结算单 unfiltered_order_ids = order_ids_base.all() unfiltered_order_ids = [o.id for o in unfiltered_order_ids] if firm_ids is not None: order_ids_base = order_ids_base.filter(models.FirmSettlementVoucher.firm_id.in_(firm_ids)) order_ids = order_ids_base.distinct() \ .offset(page * limit).limit(limit).all() # 本页所有结算单 order_ids = {o.id for o in order_ids} orders = self.session.query(models.FirmSettlementOrder) \ .filter(models.FirmSettlementOrder.id.in_(order_ids)) \ .order_by(models.FirmSettlementOrder.create_time.desc()) \ .all() # 对应的所有待结算单 vouchers_firms = self.session.query(models.FirmSettlementVoucher, models.Firm) \ .join(models.Firm, models.Firm.id == models.FirmSettlementVoucher.firm_id) \ .filter(models.FirmSettlementVoucher.settlement_order_id.in_(order_ids)) \ .all() firms_dict = defaultdict(set) [firms_dict[voucher.settlement_order_id].add(firm) for voucher, firm in vouchers_firms] firm_account_ids = {order.payment_account_id for order in orders} accounts = self.session.query(models.FirmPaymentAccount) \ .filter(models.FirmPaymentAccount.id.in_(firm_account_ids)) \ .all() account_dict = {account.id: account for account in accounts} order_list = [] for order in orders: creator = order.creator settlement_account = account_dict.get(order.payment_account_id) firms = firms_dict.get(order.id, []) firms = [{ "id": firm.id, "name": firm.name, } for firm in firms] order_list.append({ "id": order.id, "creator_id": creator.id, "creator_name": creator.username, "create_time": TimeFunc.time_to_str(order.create_time), "agent_name": order.agent_name, "agent_phone": order.agent_phone, "payment": order.payment, "firms": firms, "settlement_account_id": settlement_account.id if settlement_account else 0, "settlement_account_num": settlement_account.account_num if settlement_account else "现金", "total_money": check_float(order.total_money / 100), "remarks": order.remarks, }) all_firms = self.session.query(models.Firm) \ .join(models.FirmSettlementVoucher, models.FirmSettlementVoucher.firm_id == models.Firm.id) \ .filter(models.FirmSettlementVoucher.settlement_order_id.in_(unfiltered_order_ids)) \ .distinct() \ .all() all_firms = [{ "id": firm.id, "name": firm.name, } for firm in all_firms] has_more = len(orders) >= limit return self.send_success(orders=order_list, all_firms=all_firms, has_more=has_more)
def firm_summary(self): """各供货商的结算汇总""" scope = self.args["scope"] summary_date = self.args["summary_date"] firm_ids = self.args.get("firm_ids") firm_ids = set(map(lambda i: check_int(i), firm_ids.split("|"))) if firm_ids else None page = self.args.get("page", 0) limit = self.args.get("limit", 20) # 更新一下统计表相关信息 update_firm_payment_statistics(self.session, self.statistic_session, station_id=self.current_station.id) # 汇总日期范围 if scope == 0: date_start = summary_date date_end = summary_date + datetime.timedelta(days=1) elif scope == 1: date_start = datetime.date(summary_date.year, summary_date.month, 1) # 当月最后一天 date_end = TimeFunc.add_months(date_start, 1) - datetime.timedelta(days=1) elif scope == 2: date_start = datetime.date(summary_date.year, 1, 1) date_end = datetime.date(summary_date.year + 1, 1, 1) else: return self.send_fail("不支持的汇总范围") statistics = self.statistic_session.query(models_statistics.StatisticsFirmPayment) \ .filter(models_statistics.StatisticsFirmPayment.station_id == self.current_station.id, models_statistics.StatisticsFirmPayment.statistics_type == 0, func.DATE(models_statistics.StatisticsFirmPayment.statistics_date) >= date_start, func.DATE(models_statistics.StatisticsFirmPayment.statistics_date) < date_end) # 待筛选的所有供货商 ID all_firm_ids = statistics.with_entities(models_statistics.StatisticsFirmPayment.firm_id).all() all_firm_ids = {i.firm_id for i in all_firm_ids} # 累计数据 total_sum = \ statistics.with_entities(func.count(models_statistics.StatisticsFirmPayment.settle_times), func.count(models_statistics.StatisticsFirmPayment.settle_nums), func.sum(models_statistics.StatisticsFirmPayment.settle_money)) \ .first() if firm_ids: statistics = statistics.filter(models_statistics.StatisticsFirmPayment.firm_id.in_(firm_ids)) statistics = statistics.all() all_firms = self.session.query(models.Firm) \ .filter(models.Firm.id.in_(all_firm_ids)).all() firm_dict = {firm.id: firm for firm in all_firms} # 待筛选的所有供货商 firms = [{"id": firm.id, "name": firm.name} for firm in all_firms] summary_dict = {} for statics in statistics: if statics.firm_id not in summary_dict: summary_dict[statics.firm_id] = { "settle_times": 0, # 结算次数 "settle_nums": 0, # 结算票数 "settle_money": 0, # 结算总金额 } summary_dict[statics.firm_id]["settle_times"] += statics.settle_times summary_dict[statics.firm_id]["settle_nums"] += statics.settle_nums summary_dict[statics.firm_id]["settle_money"] += statics.settle_money # 累计数据 settle_times = total_sum[0] or 0 if total_sum else 0 settle_nums = total_sum[1] or 0 if total_sum else 0 total_money = check_float(total_sum[2] or 0 / 10000) if total_sum else 0 sum_data = { "times": settle_times, "voucher_count": settle_nums, "total_money": total_money, "firms": firms } # 汇总列表 summarys = [] for firm_id, summary in summary_dict.items(): firm = firm_dict.get(firm_id) summarys.append({ "firm_id": firm.id if firm else 0, "firm_name": firm.name if firm else "", "times": summary["settle_times"], "voucher_count": summary["settle_nums"], "total_money": check_float(summary["settle_money"] / 10000), }) # 暂时不分页 nomore = True return self.send_success(sum_data=sum_data, summarys=summarys, nomore=nomore)
def update_firm_payment_statistics(session, statistics_session, specific_date=None, station_id=None, scope=0): # specific_date应该为一个Date对象 firm_statistics = statistics_session.query(models_statistics.StatisticsFirmPayment) \ .filter_by(statistics_type=0) if station_id: firm_statistics = firm_statistics.filter_by(station_id=station_id) if specific_date: firm_statistics = firm_statistics.filter_by( statistics_date=specific_date) firm_statistics_list = firm_statistics.all() firm_sta_dict = { "{}:{}:{}".format(s.statistics_date, s.station_id, s.firm_id): s for s in firm_statistics_list } # 更新数据 vouchers = session.query(models.FirmSettlementVoucher, models.FirmSettlementOrder) \ .join(models.FirmSettlementOrder, models.FirmSettlementOrder.id == models.FirmSettlementVoucher.settlement_order_id) \ .filter(models.FirmSettlementVoucher.status == 1) if specific_date: vouchers = vouchers.filter( models.FirmSettlementOrder.statistics_date == specific_date) if station_id: vouchers = vouchers.filter_by(station_id=station_id) # 待筛选的所有供货商 ID all_firm_ids = vouchers.with_entities( models.FirmSettlementVoucher.firm_id).all() all_firm_ids = {i.firm_id for i in all_firm_ids} vouchers = vouchers.all() all_firms = session.query(models.Firm) \ .filter(models.Firm.id.in_(all_firm_ids)) \ .all() firm_dict = {firm.id: firm for firm in all_firms} summary_dict = {} # 改走统计表的形式,依据统计表的数据结构,需要保证firm_id与date的组合为唯一 for voucher, voucher_order in vouchers: key_date = TimeFunc.time_to_str(voucher_order.create_time, "date") if voucher.firm_id not in summary_dict: summary_dict[voucher.firm_id] = {} summary_dict[voucher.firm_id][key_date] = { "order_ids": set(), "voucher_count": 0, # 结算次数 "total_money": 0, # 总价钱 } elif not summary_dict.get(voucher.firm_id, {}).get(key_date): summary_dict[voucher.firm_id][key_date] = { "order_ids": set(), "voucher_count": 0, # 结算次数 "total_money": 0, # 总价钱 } summary_dict[voucher.firm_id][key_date]["order_ids"].add( voucher.settlement_order_id) summary_dict[voucher.firm_id][key_date]["voucher_count"] += 1 summary_dict[voucher.firm_id][key_date][ "total_money"] += voucher.settled_price * voucher.settled_amount summary_dict[voucher.firm_id][key_date]["date"] = func.DATE( voucher_order.create_time) summary_dict[ voucher.firm_id][key_date]["station_id"] = voucher_order.station_id for firm_id, date_summary_dict in summary_dict.items(): firm = firm_dict.get(firm_id) for key_date, summary in date_summary_dict.items(): date = summary["date"] station_id = summary["station_id"] firm_id = firm.id if firm else 0 key = "{}:{}:{}".format(key_date, station_id, firm_id) settle_times = len(summary["order_ids"]) settle_nums = summary["voucher_count"] settle_money = summary["total_money"] firm_sta = firm_sta_dict.get(key) if not firm_sta: new_statistics_firm_payment = \ models_statistics.StatisticsFirmPayment(statistics_date=date, statistics_type=0, station_id=station_id, firm_id=firm_id, settle_times=settle_times, settle_nums=settle_nums, settle_money=settle_money) statistics_session.add(new_statistics_firm_payment) statistics_session.flush() else: firm_sta.settle_times = settle_times firm_sta.settle_nums = settle_nums firm.settle_money = settle_money statistics_session.commit()
def demand_statistic(cls, session, statistic_session): """统计所有的要货请求,用于后续数据统计使用 """ #首先按天统计要货情况 StatisticsDemand = models_statistic.StatisticsDemand Demand = models.Demand old_statistic_demand=statistic_session.query(StatisticsDemand)\ .filter_by(statistic_type=1)\ .order_by(StatisticsDemand.statistic_datetime.desc())\ .first() start_datetime = None if not old_statistic_demand: # 如果一条记录都没有,说明此前还没有更新数据,则统计demand的开始时间就是所有demand的最小时间 early_demand=session.query(Demand)\ .order_by(Demand.create_date)\ .first() start_datetime = early_demand.create_date else: # 这里注意要增加1秒 免得会重复统计已经统计过的,那么为啥不在query语句中使用大于呢,这是为了满足在old_statistic_demand=None的时候 start_datetime = old_statistic_demand.statistic_datetime + datetime.timedelta( seconds=1) cls.update_by_day(session, statistic_session, start_datetime) statistic_session.flush() #其次统计按周的要货情况 old_statistic_demand=statistic_session.query(StatisticsDemand)\ .filter_by(statistic_type=2)\ .order_by(StatisticsDemand.statistic_datetime.desc())\ .first() start_datetime = None if not old_statistic_demand: # 如果一条记录都没有,说明此前还没有按周的更新数据,则统计的开始时间就是所有按天统计的最小时间 early_demand=statistic_session.query(StatisticsDemand)\ .filter_by(statistic_type=1)\ .order_by(StatisticsDemand.statistic_datetime)\ .first() # 还没有任何按天统计的要货记录 if not early_demand: return True start_datetime = early_demand.statistic_datetime else: start_datetime = old_statistic_demand.statistic_datetime week_start_datetime, week_end_datetime = TimeFunc.get_week_start_end( start_datetime) cls.update_by_week_and_month(statistic_session, week_start_datetime, 2) statistic_session.flush() #最后统计按月的要货情况 old_statistic_demand=statistic_session.query(StatisticsDemand)\ .filter_by(statistic_type=3)\ .order_by(StatisticsDemand.statistic_date.desc())\ .first() start_datetime = None if not old_statistic_demand: # 如果一条记录都没有,说明此前还没有按月的更新数据,则统计的开始时间就是所有按周统计的最小时间 early_demand=statistic_session.query(StatisticsDemand)\ .filter_by(statistic_type=2)\ .order_by(StatisticsDemand.statistic_date)\ .first() # 还没有任何按周统计的要货记录 if not early_demand: return True start_datetime = early_demand.statistic_date else: start_datetime = old_statistic_demand.statistic_date month_start_datetime, month_end_datetime = TimeFunc.get_month_start_end( start_datetime) cls.update_by_week_and_month(statistic_session, month_start_datetime, 3) statistic_session.commit() return True
def update_by_week_and_month(cls, statistic_session, start_datetime, statistic_type): """按周或者月更新统计数据 statistic_type 2: 按月 3:按周 """ StatisticsDemand = models_statistic.StatisticsDemand Demand = models.Demand start_date = datetime.date(start_datetime.year, start_datetime.month, start_datetime.day) group_type = None if statistic_type == 2: group_type = StatisticsDemand.statistic_week elif statistic_type == 3: group_type = StatisticsDemand.statistic_month day_statistic_demands=statistic_session.query(StatisticsDemand.shop_id, StatisticsDemand.goods_id,\ func.sum(StatisticsDemand.total_order_amount),\ func.sum(StatisticsDemand.total_wasted),\ func.sum(StatisticsDemand.total_sale),func.sum(StatisticsDemand.total_arrival),\ func.sum(StatisticsDemand.average_purchase_price),func.sum(StatisticsDemand.average_price),\ func.sum(StatisticsDemand.total_current_stock),func.count(StatisticsDemand.id),\ func.max(StatisticsDemand.statistic_datetime),StatisticsDemand.statistic_year,\ StatisticsDemand.statistic_month,StatisticsDemand.statistic_week)\ .order_by(StatisticsDemand.statistic_year,group_type)\ .filter(StatisticsDemand.statistic_date>=start_date)\ .filter_by(statistic_type=statistic_type-1)\ .group_by(StatisticsDemand.shop_id,\ StatisticsDemand.goods_id,\ StatisticsDemand.statistic_year,\ group_type)\ .all() if not day_statistic_demands: return True for each_demand in day_statistic_demands: average_purchase_price = 0 average_price = 0 demand_count = each_demand[9] if demand_count: average_purchase_price = each_demand[6] / demand_count average_price = each_demand[7] / demand_count new_statistic_demand = None if_new = False # 统计按周的数据 if statistic_type == 2: if each_demand[11] == int( start_date.strftime("%Y")) and each_demand[13] == int( start_date.strftime("%W")): exist_statistic_demand=statistic_session.query(StatisticsDemand)\ .filter_by(statistic_year=each_demand[11],\ statistic_week=each_demand[13],\ statistic_type=statistic_type,\ shop_id=each_demand.shop_id,\ goods_id=each_demand.goods_id)\ .first() if exist_statistic_demand: new_statistic_demand = exist_statistic_demand else: if_new = True else: if_new = True # 统计按月的数据 elif statistic_type == 3: if each_demand[11] == int( start_date.strftime("%Y")) and each_demand[12] == int( start_date.strftime("%m")): exist_statistic_demand=statistic_session.query(StatisticsDemand)\ .filter_by(statistic_year=each_demand[11],\ statistic_month=each_demand[12],\ statistic_type=statistic_type,\ shop_id=each_demand.shop_id,\ goods_id=each_demand.goods_id)\ .first() if exist_statistic_demand: new_statistic_demand = exist_statistic_demand else: if_new = True else: if_new = True if if_new: new_statistic_demand=StatisticsDemand(statistic_type=statistic_type,\ shop_id=each_demand[0],\ goods_id=each_demand[1],\ statistic_year=each_demand[11],\ statistic_month=each_demand[12],\ statistic_week=each_demand[13]) statistic_session.add(new_statistic_demand) statistic_session.flush() new_statistic_demand.total_order_amount = each_demand[2] # 重要点,因为数据录入的时候,昨日损耗和昨日销量是保存在今天这条录入记录的, # 所以,在进行按周和按月统计的时候,统计的时间需要错开,也就是说损耗统计和 # 销量统计需要减去统计周期(按周/按月)的起始天的,并加上下个周期起始天的数据 # 首先重新计算统计日期 if statistic_type == 2: new_start_datetime, new_end_datetime = TimeFunc.get_week_start_end( each_demand[10]) elif statistic_type == 3: new_start_datetime, new_end_datetime = TimeFunc.get_month_start_end( each_demand[10]) # 统计起始天昨日消耗和昨日销量 day_statistic_demand_base=statistic_session.query(StatisticsDemand.total_wasted,\ StatisticsDemand.total_sale)\ .filter_by(shop_id=each_demand[0],\ goods_id=each_demand[1]) start_date_statistic_demand =day_statistic_demand_base.filter_by(statistic_date=new_start_datetime.strftime("%Y-%m-%d"))\ .first() next_start_date_statistic_demand=day_statistic_demand_base.filter_by(statistic_date=new_end_datetime.strftime("%Y-%m-%d"))\ .first() decrease_wasted = 0 decrease_sale = 0 increase_wasted = 0 increase_sale = 0 if start_date_statistic_demand: decrease_wasted = start_date_statistic_demand[0] decrease_sale = start_date_statistic_demand[1] if next_start_date_statistic_demand: increase_wasted = next_start_date_statistic_demand[0] increase_sale = next_start_date_statistic_demand[1] # 累计损耗和销量数据修正 new_statistic_demand.total_wasted = each_demand[ 3] - decrease_wasted + increase_wasted new_statistic_demand.total_sale = each_demand[ 4] - decrease_sale + increase_sale new_statistic_demand.total_arrival = each_demand[5] new_statistic_demand.average_purchase_price = average_purchase_price new_statistic_demand.average_price = average_price new_statistic_demand.total_current_stock = each_demand[8] new_statistic_demand.demand_count = demand_count new_statistic_demand.statistic_datetime = each_demand[10] new_statistic_demand.statistic_date = each_demand[10].strftime( "%Y-%m-%d") statistic_session.flush() return True
def post(self): wish_order_id = self.args["wish_order_id"] shop_id = self.args["shop_id"] printer_id = self.args["printer_id"] wish_order = models.WishOrder.get_by_id(self.session, wish_order_id, self.current_station.id) if not wish_order: return self.send_fail("对应的意向单无效") shop = models.Shop.get_by_id(self.session, shop_id, self.current_station.id) if not shop: return self.send_fail("没有找到对应的店铺") printer = models.Printer.get_by_id(self.session, printer_id, self.current_station.id) if not printer: return self.send_fail("选择了无效的打印机") allocation_goods_list = self.session.query(models.AllocationOrderGoods, models.AllocationOrder) \ .join(models.AllocationOrder, models.AllocationOrder.id == models.AllocationOrderGoods.order_id) \ .filter(models.AllocationOrderGoods.shop_id == shop_id, models.AllocationOrder.wish_order_id == wish_order_id, models.AllocationOrder.station_id == self.current_station.id, models.AllocationOrder.status == 1) \ .all() goods_ids = [] # 各商品的总实配量 allocation_dict = defaultdict(int) for allocation_goods, allocation_order in allocation_goods_list: allocation_dict[ allocation_order. goods_id] += allocation_goods.actual_allocated_amount goods_ids.append(allocation_order.goods_id) goods_ids = set(goods_ids) wish_goods_list = self.session.query(models.WishOrderGoods) \ .filter(models.WishOrderGoods.status >= 0, models.WishOrderGoods.wish_order_id == wish_order_id, models.WishOrderGoods.goods_id.in_(goods_ids)) \ .all() wish_goods_dict = {goods.goods_id: goods for goods in wish_goods_list} demand_goods_list = self.session.query(models.DemandOrderGoods) \ .join(models.DemandOrder, models.DemandOrder.id == models.DemandOrderGoods.demand_order_id) \ .filter(models.DemandOrder.shop_id == shop_id, models.DemandOrder.wish_order_id == wish_order_id, models.DemandOrderGoods.goods_id.in_(goods_ids)) \ .all() demand_goods_dict = { goods.goods_id: goods for goods in demand_goods_list } goods_list = self.session.query(models.Goods) \ .filter(models.Goods.station_id == self.current_station.id, models.Goods.id.in_(goods_ids)) \ .all() goods_dict = {goods.id: goods for goods in goods_list} packing_list = [] for goods_id in goods_ids: goods = goods_dict.get(goods_id) wish_goods = wish_goods_dict.get(goods_id) demand_goods = demand_goods_dict.get(goods_id) allocated_amount = allocation_dict.get(goods_id, 0) packing_list.append({ "goods_name": wish_goods.goods_name if wish_goods else goods.name if goods else "", "demand_amount": check_float(demand_goods.demand_amount / 100) if demand_goods else 0, "allocated_amount": check_float(allocated_amount / 100), }) printer = models.Printer.get_by_id(self.session, printer_id, self.current_station.id) if not printer: return self.send_fail("选择了无效的打印机") number_map = models.SerialNumberMap.generate(self.session, 3, 0, self.current_station.id) receipt_printer = ReceiptPrinter(printer.wireless_print_num, printer.wireless_print_key) receipt_content = receipt_printer.packing_order_template( shop_name=shop.name, order_no=number_map.order_no, goods_list=packing_list, operator_name=self.current_user.username, create_time=TimeFunc.time_to_str(datetime.datetime.now()), ) success, error_msg = receipt_printer.print(receipt_content) if not success: return self.send_fail(error_msg) return self.send_success()