Example #1
0
 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)
Example #2
0
 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
Example #3
0
    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)
Example #4
0
    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)
Example #5
0
    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)
Example #6
0
    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()
Example #7
0
    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)
Example #8
0
    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
Example #9
0
    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)
Example #10
0
    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)
Example #11
0
    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)
Example #12
0
    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)
Example #13
0
 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)
Example #14
0
 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)
Example #15
0
    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)
Example #16
0
    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)
Example #17
0
    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)
Example #18
0
    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)
Example #19
0
    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()
Example #20
0
    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)
Example #21
0
    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)
Example #22
0
    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)
Example #23
0
    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()
Example #24
0
    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)
Example #25
0
    def post(self):
        allocation_order_id = self.args["allocation_order_id"]
        remarks = self.args.get("remarks", "")

        allocation_order = models.AllocationOrder.get_by_id(self.session, allocation_order_id, self.current_station.id)
        if not allocation_order:
            return self.send_fail("没有找到对应的分车单")
        elif not allocation_order.purchase_order_goods_id:
            return self.send_fail("没有找到有效的供货商分车单")
        elif allocation_order.status != 1:
            return self.send_fail("对应的分车单还未被确认")

        # 已配置的打印机
        config = models.Config.get_by_station_id(self.session, self.current_station.id)
        printer_id = config.settlement_printer_id
        printer = models.Printer.get_by_id(self.session, printer_id, self.current_station.id)
        if not printer:
            return self.send_fail("待结算单打印机设置无效,请在中转站设置中配置")

        # 除入库外已分车量
        allocated_amount = self.session.query(func.sum(models.AllocationOrderGoods.actual_allocated_amount)) \
            .filter(models.AllocationOrderGoods.order_id == allocation_order.id,
                    models.AllocationOrderGoods.destination != 1) \
            .first()
        allocated_amount = allocated_amount[0] or 0 if allocated_amount else 0

        # 分车入库记录
        stock_in_record = self.session.query(models.StockOutInGoods) \
            .filter(models.StockOutInGoods.allocation_order_id == allocation_order.id,
                    models.StockOutInGoods.type == 1,
                    models.StockOutInGoods.status == 1) \
            .first()
        allocated_amount += stock_in_record.amount if stock_in_record else 0

        purchase_goods = models.PurchaseOrderGoods.get_by_id(self.session, allocation_order.purchase_order_goods_id)
        if not purchase_goods:
            return self.send_fail("没有找到对应的采购单商品")
        elif not purchase_goods.firm_id:
            return self.send_fail("没有可结算的供货商")

        # 已有的待结算单
        settlement_voucher = self.session.query(models.FirmSettlementVoucher) \
            .filter(models.FirmSettlementVoucher.station_id == self.current_station.id,
                    models.FirmSettlementVoucher.allocation_order_id == allocation_order.id) \
            .first()
        if not settlement_voucher:
            # 生成待结算单号
            number_map = models.SerialNumberMap.generate(self.session, 4, allocation_order.id, self.current_station.id)
            # 创建新的待结算单
            settlement_voucher = models.FirmSettlementVoucher(
                station_id=self.current_station.id,
                creator_id=self.current_user.id,
                allocation_order_id=allocation_order_id,
                firm_id=purchase_goods.firm_id,
                order_no=number_map.order_no,
                remarks=remarks,
            )
            self.session.add(settlement_voucher)
            self.session.flush()

        # 打印待结算单
        receipt_printer = ReceiptPrinter(printer.wireless_print_num, printer.wireless_print_key)
        order = purchase_goods.order
        receipt_types = config.get_settlement_receipt_types()
        receipt_content = ""
        # 打印会计联
        if receipt_types["print_accountant_receipt"]:
            receipt_content += receipt_printer.firm_settlement_voucher_template(
                receipt_type=0,
                goods_name=purchase_goods.goods.name,
                firm_name=purchase_goods.firm.name,
                order_no=settlement_voucher.order_no,
                amount=check_float(allocated_amount / 100),
                remarks=settlement_voucher.remarks,
                operator_name=self.current_user.username,
                create_time=TimeFunc.time_to_str(datetime.datetime.now()),
                should_cut=receipt_types["print_customer_receipt"],  # XXX ugly workaround,需要打印客户联时才切纸
            )
        # 打印客户联
        if receipt_types["print_customer_receipt"]:
            receipt_content += receipt_printer.firm_settlement_voucher_template(
                receipt_type=1,
                goods_name=purchase_goods.goods.name,
                firm_name=purchase_goods.firm.name,
                order_no=settlement_voucher.order_no,
                amount=check_float(allocated_amount / 100),
                remarks=settlement_voucher.remarks,
                operator_name=self.current_user.username,
                create_time=TimeFunc.time_to_str(datetime.datetime.now()),
            )
        if receipt_content:
            success, error_msg = receipt_printer.print(receipt_content)
            if not success:
                return self.send_fail(error_msg)

        self.session.commit()
        return self.send_success()
Example #26
0
    def get(self):
        order_id = self.args.get("order_id")
        keyword = self.args.get("keyword")
        status = self.args.get("status")
        order_by = self.args.get("order_by")
        asc = self.args.get("asc", False)
        from_date = self.args.get("from_date")
        before_date = self.args.get("before_date")
        date = self.args.get("date")
        settled_from_date = self.args.get("settled_from_date")
        settled_before_date = self.args.get("settled_before_date")
        settled_date = self.args.get("settled_date")
        page = self.args.get("page", 0)
        limit = self.args.get("limit", 20)

        vouchers = self.session.query(models.FirmSettlementVoucher,
                                      models.FirmSettlementOrder,
                                      models.AllocationOrder,
                                      models.PurchaseOrderGoods,
                                      models.WishOrderGoods,
                                      models.Firm,
                                      models.Staff,
                                      models.AccountInfo) \
            .join(models.AllocationOrder, models.AllocationOrder.id == models.FirmSettlementVoucher.allocation_order_id) \
            .outerjoin(models.FirmSettlementOrder, models.FirmSettlementOrder.id == models.FirmSettlementVoucher.settlement_order_id) \
            .join(models.PurchaseOrderGoods, models.PurchaseOrderGoods.id == models.AllocationOrder.purchase_order_goods_id) \
            .join(models.WishOrderGoods, and_(models.WishOrderGoods.goods_id == models.PurchaseOrderGoods.goods_id,
                                              models.WishOrderGoods.wish_order_id == models.AllocationOrder.wish_order_id)) \
            .join(models.Firm, models.Firm.id == models.FirmSettlementVoucher.firm_id) \
            .outerjoin(models.Staff, models.Staff.id == models.PurchaseOrderGoods.purchaser_id) \
            .outerjoin(models.AccountInfo, models.AccountInfo.id == models.Staff.account_id) \
            .filter(models.FirmSettlementVoucher.station_id == self.current_station.id,
                    models.WishOrderGoods.status >= 0)

        if order_id:
            vouchers = vouchers.filter(models.FirmSettlementVoucher.settlement_order_id == order_id)

        if keyword:
            vouchers = vouchers.filter(or_(models.WishOrderGoods.goods_name.like("%{}%".format(keyword)),
                                       models.Firm.name.like("%{}%".format(keyword))))
        if status is not None:
            vouchers = vouchers.filter(models.FirmSettlementVoucher.status == status)

        # 结算时间过滤
        if settled_from_date or settled_before_date or settled_date:
            if settled_from_date:
                vouchers = vouchers.filter(func.DATE(models.FirmSettlementOrder.create_time) >= settled_from_date)
            if settled_before_date:
                vouchers = vouchers.filter(func.DATE(models.FirmSettlementOrder.create_time) < settled_before_date)
            if settled_date:
                vouchers = vouchers.filter(func.DATE(models.FirmSettlementOrder.create_time) == settled_date)

        # 开票时间过滤
        if from_date:
            vouchers = vouchers.filter(func.DATE(models.FirmSettlementVoucher.create_time) >= from_date)
        if before_date:
            vouchers = vouchers.filter(func.DATE(models.FirmSettlementVoucher.create_time) < before_date)
        if date:
            vouchers = vouchers.filter(func.DATE(models.FirmSettlementVoucher.create_time) == date)

        if order_by == "date":
            if asc:
                vouchers = vouchers.order_by(models.FirmSettlementVoucher.create_time.asc())
            else:
                vouchers = vouchers.order_by(models.FirmSettlementVoucher.create_time.desc())
        elif order_by == "goods_name":
            if asc:
                vouchers = vouchers.order_by(models.WishOrderGoods.name_acronym.asc())
            else:
                vouchers = vouchers.order_by(models.WishOrderGoods.name_acronym.desc())
        elif order_by == "firm_name":
            if asc:
                vouchers = vouchers.order_by(models.Firm.name_acronym.asc())
            else:
                vouchers = vouchers.order_by(models.Firm.name_acronym.desc())

        data_count = vouchers.count()
        vouchers = vouchers.offset(page * limit).limit(limit).all()

        # 计算结算件数(不含分车入库部分)
        allocation_order_ids = {order.id for _, _, order, _, _, _, _, _ in vouchers}
        allocated_amount_sums = self.session.query(models.AllocationOrderGoods.order_id,
                                                   func.sum(models.AllocationOrderGoods.actual_allocated_amount)) \
            .filter(models.AllocationOrderGoods.order_id.in_(allocation_order_ids),
                    models.AllocationOrderGoods.destination != 1) \
            .group_by(models.AllocationOrderGoods.order_id) \
            .all()
        allocated_amount_sum_dict = {data[0]: data[1] for data in allocated_amount_sums}

        # 分车入库记录(用于计算实际入库件数)
        stock_in_records = self.session.query(models.StockOutInGoods.allocation_order_id,
                                              models.StockOutInGoods.amount) \
            .filter(models.StockOutInGoods.allocation_order_id.in_(allocation_order_ids),
                    models.StockOutInGoods.type == 1,
                    models.StockOutInGoods.status == 1) \
            .all()
        stock_in_amount_dict = {record[0]: record[1] for record in stock_in_records}

        order_list = []
        for voucher, settlement_order, allocation, purchase_goods, wish_goods, firm, purchaser, purchaser_account in vouchers:
            amount = check_float(allocated_amount_sum_dict.get(allocation.id, 0) / 100)
            stock_in_amount = check_float(stock_in_amount_dict.get(allocation.id, 0) / 100)
            # 应结量 = 非入库部分分车量 + 实际入库量
            amount += stock_in_amount

            # 应结金额,按件数比例计算,实配件数/采购件数*小计
            total_money = check_float(amount / purchase_goods.actual_amount * purchase_goods.subtotal)
            # 采购价
            price = check_float(total_money / amount)

            order_list.append({
                "id": voucher.id,
                "order_no": voucher.order_no,
                "settlement_order_id": voucher.settlement_order_id,
                "amount": amount,
                "price": price,
                "total_money": total_money,
                "settled_amount": check_float((voucher.settled_amount or 0) / 100),
                "settled_price": check_float((voucher.settled_price or 0) / 100),
                "settled_time": TimeFunc.time_to_str(settlement_order.create_time) if settlement_order else "",
                "date": TimeFunc.time_to_str(voucher.create_time, "date"),
                "create_time": TimeFunc.time_to_str(voucher.create_time),
                "creator_name": voucher.creator.username,
                "goods_id": wish_goods.goods_id,
                "goods_name": wish_goods.goods_name,
                "firm_id": firm.id,
                "firm_name": firm.name,
                "remarks": voucher.remarks,
                "purchaser_name": (purchaser.remarks or purchaser_account.username) if purchaser and purchaser_account else "",
                "status": voucher.status,
            })

        has_more = len(order_list) >= limit
        return self.send_success(order_list=order_list, data_count=data_count, has_more=has_more)
Example #27
0
    def get(self, order_id):
        order = self.session.query(models.FirmSettlementOrder) \
            .filter(models.FirmSettlementOrder.id == order_id,
                    models.FirmSettlementOrder.station_id == self.current_station.id) \
            .first()
        if not order:
            return self.send_fail("没有找到该结算单")

        # 结算账号信息
        payment_account = order.payment_account
        if payment_account:
            parent_bank = None
            if payment_account.account_type in [2, 3]:
                parent_bank = self.session.query(models.LcParentBank) \
                    .filter(models.LcParentBank.parent_bank_no == payment_account.branch_bank_no) \
                    .first()
            payment_firm = payment_account.firm
            payment_account_info = {
                "id": payment_account.id,
                "account_type": payment_account.account_type,
                "account_name": payment_account.account_name,
                "account_num": payment_account.account_num,
                "bank_name": parent_bank.parent_bank_name if parent_bank else "",
                "firm_id": payment_firm.id,
                "firm_name": payment_firm.name,
                "status": payment_account.status,
            }
        else:
            payment_account_info = {}

        # 供货商信息
        firms = self.session.query(models.Firm.id,
                                   models.Firm.name,
                                   func.sum(models.FirmSettlementVoucher.settled_amount
                                            * models.FirmSettlementVoucher.settled_price).label("settled_money")) \
            .join(models.FirmSettlementVoucher, models.FirmSettlementVoucher.firm_id == models.Firm.id) \
            .filter(models.FirmSettlementVoucher.settlement_order_id == order_id,
                    models.FirmSettlementVoucher.status == 1) \
            .group_by(models.FirmSettlementVoucher.firm_id) \
            .all()
        firms = [{
            "id": firm.id,
            "name": firm.name,
            "settled_money": check_float(firm.settled_money / 10000),
        } for firm in firms]

        creator = order.creator
        order_info = {
            "id": order.id,
            "agent_name": order.agent_name,
            "agent_phone": order.agent_phone,
            "payment": order.payment,
            "total_money": check_float(order.total_money / 100),
            "remarks": order.remarks,
            "create_time": TimeFunc.time_to_str(order.create_time),
            "creator_id": creator.id,
            "creator_name": creator.username,
            "payment_account": payment_account_info,
            "firms": firms,
        }

        return self.send_success(order_info=order_info)
Example #28
0
    def post(self):
        vouchers = self.args["vouchers"]
        agent_name = self.args["agent_name"]
        agent_phone = self.args["agent_phone"]
        total_money_sum = self.args["total_money_sum"]
        payment_account_id = self.args["payment_account_id"] or None
        remarks = self.args.get("remarks", "")
        send_sms = self.args.get("send_sms", False)

        valid, message = self.validate_goods_list(vouchers)
        if not valid:
            return self.send_fail(message)

        voucher_ids = {check_int(voucher["id"]) for voucher in vouchers}
        valid_vouchers = self.session.query(models.FirmSettlementVoucher) \
            .filter(models.FirmSettlementVoucher.id.in_(voucher_ids),
                    models.FirmSettlementVoucher.status == 0) \
            .all()
        if {voucher.id for voucher in valid_vouchers} != voucher_ids:
            return self.send_fail("提交了无效的或已结算过的记录")
        valid_vouchers_dict = {voucher.id: voucher for voucher in valid_vouchers}

        payment = 0
        if payment_account_id:
            payment_account = models.FirmPaymentAccount.get_by_id(self.session, payment_account_id, self.current_station.id)
            if not payment_account:
                return self.send_fail("没有找到指定的供货商收款账号")
            payment = 2 if payment_account.account_type == 1 else 1

        settlement_order = models.FirmSettlementOrder(
            agent_name=agent_name,
            agent_phone=agent_phone,
            payment=payment,
            payment_account_id=payment_account_id,
            total_money=check_int(total_money_sum * 100),
            remarks=remarks,
            station_id=self.current_station.id,
            creator_id=self.current_user.id
        )
        self.session.add(settlement_order)
        self.session.flush()

        voucher_money_sum = 0
        for voucher_arg in vouchers:
            voucher_id = check_int(voucher_arg["id"])
            amount = check_float(voucher_arg["amount"])
            price = check_float(voucher_arg["price"])
            total_money = check_float(voucher_arg["total_money"])
            voucher = valid_vouchers_dict[voucher_id]

            voucher.settlement_order_id = settlement_order.id
            voucher.settled_amount = check_int(amount * 100)
            voucher.settled_price = check_int(price * 100)
            voucher.status = 1

            voucher_money_sum += total_money

        if total_money_sum != voucher_money_sum:
            return self.send_fail("结算总金额计算有误,应为 {}".format(voucher_money_sum))

        self.session.commit()

        if send_sms:
            from libs import yunpian
            yunpian.send_firm_settlement(agent_phone,
                                         TimeFunc.time_to_str(datetime.datetime.now()),
                                         self.current_station.name,
                                         total_money_sum)

        return self.send_success()
Example #29
0
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()
Example #30
0
    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()