Пример #1
0
    def put(self, goods_id):
        accountinfo = self.current_user
        station = self.current_station
        stock = self.args["stock"]
        remarks = self.args.get("remarks", "").strip()
        if stock >= 2147483600:
            return self.send_fail("库存值过大")
        if stock < 0:
            return self.send_fail("库存不能为负数")
        if len(remarks) > constants.REMARKS_LEN:
            return self.send_fail("备注长度超过128位")
        goods = models.Goods.get_by_goods_id(self.session, goods_id)
        if not goods:
            return self.send_fail("此商品不存在")

        # 生成修改记录
        stock_operation_record = models.StockOperationRecord(
            operation_detail="库存修改({0}→{1})".format(
                check_float(goods.stock / 100), check_float(stock)),
            remarks=remarks,
            goods_id=goods_id,
            creator_id=accountinfo.id,
            station_id=station.id)
        # 更新库存成本
        goods.stock_cost += check_float(
            (stock * 100 - goods.stock) * goods.stock_average_price / 100)
        # 修改库存
        goods.stock = check_int(stock * 100)
        self.session.add(stock_operation_record)
        self.session.commit()
        return self.send_success()
Пример #2
0
    def with_goods_summary(self, staff):
        start_date = self.args["start_date"]
        end_date = self.args["end_date"]
        page = self.args["page"]
        limit = self.args["limit"]
        if limit > constants.PAGE_MAX_LIMIT:
            limit = constants.PAGE_SIZE
        goods_id_tuple = self.session.query(models.PurchaseOrderGoods.goods_id)\
            .filter(models.PurchaseOrderGoods.purchaser_id == staff.id,
                    models.PurchaseOrderGoods.firm_id >= 0,
                    models.PurchaseOrderGoods.status >= 0)\
            .distinct()\
            .offset(page * limit)\
            .limit(limit)\
            .all()
        goods_ids = [goods_id[0] for goods_id in goods_id_tuple] or [0]

        purchase_goods_objs = self.session.query(models.PurchaseOrderGoods)\
            .filter(models.PurchaseOrderGoods.goods_id.in_(goods_ids),
                    func.DATE(models.PurchaseOrderGoods.create_time) >= start_date,
                    func.DATE(models.PurchaseOrderGoods.create_time) < end_date,
                    models.PurchaseOrderGoods.purchaser_id == staff.id,
                    models.PurchaseOrderGoods.firm_id >= 0,
                    models.PurchaseOrderGoods.status >= 0)\
            .all()

        purchase_goods_dict = defaultdict(list)
        for purchase_goods in purchase_goods_objs:
            purchase_goods_dict[purchase_goods.goods_id].append(
                purchase_goods.to_dict())

        purchase_goods_data_list = list()
        for goods_id, purchase_goods_info in purchase_goods_dict.items():
            data = dict()
            data["goods_id"] = purchase_goods_info[0]["goods_id"]
            data["goods_name"] = purchase_goods_info[0]["goods_name"]
            # 采购次数
            data["purchase_count"] = len([
                purchase_goods["firm_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))
            # 供货商名称列表
            data["firm_name_list"] = list({
                purchase_goods["firm_name"]
                for purchase_goods in purchase_goods_info
            })
            purchase_goods_data_list.append(data)

        has_more = len(goods_ids) >= limit
        return self.send_success(
            purchase_goods_data_list=purchase_goods_data_list,
            has_more=has_more)
Пример #3
0
    def validate_goods_list(self, vouchers):
        """验证待结算单列表参数"""

        if not isinstance(vouchers, list):
            return False, "待结算单列表参数格式有误"

        for i in range(len(vouchers)):
            voucher = vouchers[i]
            if not isinstance(voucher, dict):
                return False, "待结算单列表参数项格式有误"

            if "id" not in voucher:
                return False, "参数缺失:id"
            if "amount" not in voucher:
                return False, "参数缺失:amount"
            if "price" not in voucher:
                return False, "参数缺失:price"
            if "total_money" not in voucher:
                return False, "参数缺失:total_money"

            amount = voucher["amount"]
            price = voucher["price"]
            total_money = voucher["total_money"]

            if check_float(amount * price) != total_money:
                return False, "第 {} 项应结金额计算有误,应为{}".format(i, check_float(amount * price))

        return True, ""
Пример #4
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()
Пример #5
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)
Пример #6
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)
Пример #7
0
 def get_all_goods_by_classify(self):
     """根据分类获取商品信息
     """
     session = self.session
     classify = self.args["classify"]
     if classify == 3:
         # 表示获取水果和蔬菜
         classify_list = [1, 2]
     else:
         classify_list = [classify]
     all_goods_list = []
     Goods = models.Goods
     ShopGoods = models.ShopGoods
     HireLink = models.HireLink
     current_user_id = self.current_user.id
     hire_link =session.query(HireLink)\
                         .filter_by(staff_id=current_user_id,\
                             active_recorder=1)\
                         .first()
     all_goods= session.query(Goods,ShopGoods)\
                         .join(ShopGoods,Goods.id==ShopGoods.goods_id)\
                         .filter(ShopGoods.status!=-1,\
                                 ShopGoods.shop_id==hire_link.shop_id,\
                                 Goods.classify.in_(classify_list))\
                         .order_by(Goods.goods_code)\
                         .all()
     for each_element in all_goods:
         each_goods = each_element[0]
         each_shop_goods = each_element[1]
         each_goods_dict = {
             "shop_goods_id":
             each_shop_goods.id,
             "goods_id":
             each_goods.id,
             "goods_name":
             each_goods.goods_name,
             "goods_code":
             each_goods.goods_code,
             "unit":
             each_goods.unit_text,
             "reserve_ratio":
             each_shop_goods.reserve_ratio,
             "reserve_cycle":
             each_shop_goods.reserve_cycle,
             "discount":
             each_shop_goods.discount,
             "today_purchase_price":
             check_float(each_shop_goods.today_purchase_price / 100),
             "today_sale_price":
             check_float(each_shop_goods.today_sale_price / 100)
         }
         all_goods_list.append(each_goods_dict)
     return self.send_success(all_goods=all_goods_list)
Пример #8
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)
Пример #9
0
    def firm_summary_detail(self, staff):
        firm_id = self.args["firm_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.firm_id == firm_id,
                    models.PurchaseOrderGoods.purchaser_id == staff.id,
                    models.PurchaseOrderGoods.firm_id >= 0,
                    models.PurchaseOrderGoods.status >= 0)\
            .all()

        purchase_goods_dict = defaultdict(list)
        for purchase_goods in purchase_goods_objs:
            purchase_goods_dict[purchase_goods.goods_id].append(
                purchase_goods.to_dict())

        purchase_goods_data_list = list()
        firm_summary_data = defaultdict(int)
        total_actual_amount = 0
        total_spending = 0
        for firm_name, purchase_goods_info in purchase_goods_dict.items():
            data = dict()
            data["goods_name"] = purchase_goods_info[0]["goods_name"]
            # 采购次数
            data["purchase_count"] = len([
                purchase_goods["firm_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))
            # 单价/元
            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"]
        # 按供货商汇总数据
        firm_summary_data["total_actual_amount"] += total_actual_amount
        firm_summary_data["total_spending"] += total_spending

        return self.send_success(
            purchase_goods_data_list=purchase_goods_data_list,
            firm_summay_data=firm_summary_data)
Пример #10
0
    def post(self):
        date = self.args["date"]
        fee_list = self.args["fee_list"]

        valid, message = self.validate_fee_list(fee_list)
        if not valid:
            return self.send_fail(message)

        for fee in fee_list:
            type = check_int(fee["type"])
            money = check_float(fee["money"])
            remarks = fee.get("remarks", "")

            new_fee = models.Fee(
                date=date,
                type=type,
                money=check_int(money * 100),
                remarks=remarks,
                station_id=self.current_station.id,
                creator_id=self.current_user.id,
            )
            self.session.add(new_fee)

        self.session.commit()
        return self.send_success()
Пример #11
0
    def validate_goods_list(self, goods_list):
        """验证商品列表参数"""

        if not isinstance(goods_list, list):
            return False, "商品列表参数格式有误"

        for goods in goods_list:
            if not isinstance(goods, dict):
                return False, "商品列表参数项格式有误"

            if "id" not in goods:
                return False, "参数缺失:id"
            if "allocated_amount" not in goods:
                return False, "参数缺失:allocated_amount"
            elif check_float(goods["allocated_amount"]) >= 2147483600:
                return False, "实配量过大:{}".format(goods["allocated_amount"])

        # 有没有无效的分车单货品 ID
        order_goods_ids = {check_int(goods["id"]) for goods in goods_list}
        valid_goods_list = models.AllocationOrderGoods.get_by_ids(
            self.session, order_goods_ids)
        valid_goods_ids = {goods.id for goods in valid_goods_list}
        if order_goods_ids != valid_goods_ids:
            return False, "存在无效的分车单货品"

        return True, ""
Пример #12
0
    def validate_goods_list(self, goods_list):
        """验证商品列表参数"""

        if not isinstance(goods_list, list):
            return False, "商品列表参数格式有误"

        for goods in goods_list:
            if not isinstance(goods, dict):
                return False, "商品列表参数项格式有误"

            if "goods_name" not in goods:
                return False, "参数缺失:goods_name"
            elif len(goods["goods_name"]) > 128:
                return False, "商品名过长:{}".format(goods["goods_name"])
            if "demand_amount" not in goods:
                return False, "参数缺失:demand_amount"
            elif check_float(goods["demand_amount"]) >= 2147483600:
                return False, "订货量过大:{}".format(goods["demand_amount"])
            if "demand_unit" not in goods:
                return False, "参数缺失:demand_unit"
            elif goods["demand_unit"] not in (0, 1, 2, 3, 4, 5, 6, 7):
                return False, "参数无效:demand_unit == {}".format(
                    goods["demand_unit"])

        return True, ""
Пример #13
0
    def month_summary_detail(self, staff):
        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.purchaser_id == staff.id,
                    models.PurchaseOrderGoods.firm_id >= 0,
                    models.PurchaseOrderGoods.status >= 0) \
            .all()

        purchase_goods_dict = defaultdict(list)
        for purchase_goods in purchase_goods_objs:
            purchase_goods_dict[purchase_goods.goods_id].append(
                purchase_goods.to_dict())

        purchase_goods_data_list = list()
        month_summary_data = defaultdict(int)
        total_actual_amount = 0
        total_spending = 0
        for goods_id, purchase_goods_info in purchase_goods_dict.items():
            data = dict()
            data["goods_name"] = purchase_goods_info[0]["goods_name"]
            # 采购件数
            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["firm_purchase_record"] = list()
            for purchase_goods in purchase_goods_info:
                data["firm_purchase_record"].append(purchase_goods)
            purchase_goods_data_list.append(data)
            # 月汇总数据
            total_actual_amount += data["goods_amount"]
            total_spending += data["goods_subtotal"]
        month_summary_data["total_actual_amount"] = check_float(
            total_actual_amount)
        month_summary_data["total_spending"] = check_float(total_spending)

        return self.send_success(
            purchase_goods_data_list=purchase_goods_data_list,
            month_summary_data=month_summary_data)
Пример #14
0
 def get(self, goods_id):
     station_id = self.current_station.id
     goods = models.Goods.get_by_goods_id(self.session,
                                          goods_id,
                                          station_id=station_id)
     if not goods:
         return self.send_fail("该商品不存在")
     goods_dict = {
         "name": goods.name,
         "code": goods.code,
         "length": check_float(goods.length / 100),
         "width": check_float(goods.width / 100),
         "height": check_float(goods.height / 100),
         "standards_volume": float(goods.standards_volume),
         "standards_weight": check_float(goods.standards_weight / 100)
     }
     return self.send_success(goods_dict=goods_dict)
Пример #15
0
 def get(self):
     goods_ids = set(self.args["goods_ids"].split("|")) - {0} - {"0"}
     goods_list = models.Goods.get_by_ids(self.session, goods_ids,
                                          self.current_station.id)
     goods_stock_dict = {
         goods.id: check_float(goods.stock / 100)
         for goods in goods_list
     }
     return self.send_success(stock_data=goods_stock_dict)
Пример #16
0
 def stockout_affirm(self, stock_outin_record):
     goods = stock_outin_record.goods
     # 减少库存量
     goods.stock -= stock_outin_record.amount
     # 减少库存成本(数据库中存储时 * 100,所以再做乘法处理时需要 / 100)
     goods.stock_cost -= check_float(goods.stock_average_price *
                                     stock_outin_record.amount / 100)
     stock_outin_record.operator_id = self.current_user.id
     stock_outin_record.status = 3
     self.session.commit()
     return self.send_success()
Пример #17
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)
Пример #18
0
    def update_goods_list(self, demand_order, goods_list):
        """更新订货单货品列表"""
        valid, message = self.validate_goods_list(goods_list)
        if not valid:
            self.send_fail(message)
            raise Finish()

        wish_order = models.WishOrder.get_by_id(self.session,
                                                demand_order.wish_order_id)
        if not wish_order:
            self.send_fail("没有找到对应的意向单")
            raise Finish()
        if wish_order.status >= 3:
            self.send_fail("意向单已截止订货")
            raise Finish()

        demand_order_goods_list = models.DemandOrderGoods.get_by_order_id(
            self.session, demand_order.id)
        demand_order_goods_dict = {
            goods.id: goods
            for goods in demand_order_goods_list
        }

        for goods in goods_list:
            demand_goods_id = check_int(goods["id"])
            current_storage = round(
                check_float(goods.get("current_storage", 0)) * 100)
            demand_amount = round(
                check_float(goods.get("demand_amount", 0)) * 100)
            demand_remarks = goods.get("demand_remarks", "")

            demand_order_goods = demand_order_goods_dict[demand_goods_id]

            demand_order_goods.current_storage = current_storage
            demand_order_goods.demand_amount = demand_amount
            demand_order_goods.remarks = demand_remarks

        # 初次提交
        if demand_order.status == 0:
            demand_order.status = 2
Пример #19
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)
Пример #20
0
 def save_draft(self, order_id):
     goods_today_price = self.args.get("goods_today_price")
     valid, message, goods_today_price = self.validate_goods_today_price(
         goods_today_price)
     if not valid:
         return self.send_fail(message)
     goods_ids = goods_today_price.keys()
     wish_goods_objects = self.session.query(models.WishOrderGoods) \
                                      .filter(models.WishOrderGoods.wish_order_id == order_id,
                                              models.WishOrderGoods.id.in_(goods_ids),
                                              models.WishOrderGoods.status != -1) \
                                      .all()
     for wish_goods in wish_goods_objects:
         wish_goods.today_price = check_float(
             goods_today_price.get(wish_goods.id, 0) * 100)
     self.session.commit()
     return self.send_success()
Пример #21
0
    def get(self, order_id):
        allocation_order = models.AllocationOrder.get_by_id(
            self.session, 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("对应的分车单还未被确认")

        allocated_amount = self.session.query(func.sum(models.AllocationOrderGoods.actual_allocated_amount)) \
            .filter(models.AllocationOrderGoods.order_id == allocation_order.id) \
            .first()
        allocated_amount = allocated_amount[0] or 0 if allocated_amount else 0

        # 采购分车记录
        if allocation_order.purchase_order_goods_id:
            purchase_goods = models.PurchaseOrderGoods.get_by_id(
                self.session, allocation_order.purchase_order_goods_id,
                self.current_station.id)
            if not purchase_goods:
                return self.send_fail("没有找到对应的采购单商品")

            goods_name = purchase_goods.goods.name
            firm_name = purchase_goods.firm.name
        # 仓库分车记录
        elif allocation_order.stock_out_record_id:
            stock_out_record = models.StockOutInGoods.get_by_id(
                self.session, allocation_order.stock_out_record_id,
                self.current_station, [3, 4])
            if not stock_out_record:
                return self.send_fail("没有找到对应的出库记录")
            goods_name = stock_out_record.goods.name
            firm_name = "仓库"
        else:
            return self.send_fail("分车单类型未知")

        data = {
            "id": allocation_order.id,
            "goods_name": goods_name,
            "firm_name": firm_name,
            "order_no": allocation_order.order_no,
            "amount": check_float(allocated_amount / 100),
        }
        return self.send_success(data=data)
Пример #22
0
    def stock_out_order(self, number_map):
        """ 出库单搜索 """
        record = self.session.query(models.StockOutInGoods) \
            .filter(models.StockOutInGoods.id == number_map.order_id,
                    models.StockOutInGoods.station_id == self.current_station.id,
                    models.StockOutInGoods.type == 0,
                    models.StockOutInGoods.status.in_([2, 3, 4])) \
            .first()
        if not record:
            return self.send_fail("没有找到对应的出库单")

        goods = record.goods
        data = {
            "order_type": number_map.order_type,
            "order_no": number_map.order_no,
            "id": record.id,
            "amount": check_float(record.amount / 100),
            "goods_id": goods.id,
            "goods_name": goods.name,
            "status": record.status,
        }
        return self.send_success(data=data)
Пример #23
0
    def validate_fee_list(self, fee_list):
        """验证费用列表参数"""

        if not isinstance(fee_list, list):
            return False, "费用列表参数格式有误"

        for fee in fee_list:
            if not isinstance(fee, dict):
                return False, "费用列表参数项格式有误"

            if "type" not in fee:
                return False, "参数缺失:type"
            elif check_int(fee["type"]) not in (1, 2):
                return False, "参数无效:type == {}".format(fee["type"])
            if "money" not in fee:
                return False, "参数缺失:money"
            elif check_float(fee["money"]) > 21474836:
                return False, "金额过大"
            if "remarks" in fee and len(fee["remarks"]) > 128:
                return False, "备注不能超过 128 个字符"

        return True, ""
Пример #24
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()
Пример #25
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()
Пример #26
0
def update_station_fee_statistics(session,
                                  statistics_session,
                                  specific_date=None,
                                  station_id=None,
                                  scope=0):
    # 先拿到所有的日期对象
    if station_id:
        if scope == 0:
            fee_dates = session.query(models.Fee.date) \
                .filter(models.Fee.station_id == station_id).order_by(models.Fee.date.desc())
            voucher_dates = session.query(func.DATE(models.FirmSettlementVoucher.create_time)) \
                .filter(models.FirmSettlementVoucher.station_id == station_id) \
                .order_by(models.FirmSettlementVoucher.create_time.desc())
            dates = fee_dates.union(voucher_dates).distinct().all()
        else:
            fee_dates = session.query(models.Fee.date) \
                .filter(models.Fee.station_id == station_id)
            voucher_dates = session.query(func.DATE(models.FirmSettlementVoucher.create_time)) \
                .filter(models.FirmSettlementVoucher.station_id == station_id)
            dates = fee_dates.union(voucher_dates).distinct().all()
    else:
        if scope == 0:
            fee_dates = session.query(models.Fee.date).order_by(
                models.Fee.date.desc())
            voucher_dates = session.query(func.DATE(models.FirmSettlementVoucher.create_time)) \
                .order_by(models.FirmSettlementVoucher.create_time.desc())
            dates = fee_dates.union(voucher_dates).distinct().all()
        else:
            fee_dates = session.query(models.Fee.date)
            voucher_dates = session.query(
                func.DATE(models.FirmSettlementVoucher.create_time))
            dates = fee_dates.union(voucher_dates).distinct().all()
    dates = [date[0] for date in dates]
    fee_statistics = statistics_session.query(models_statistics.StatisticsStationFee) \
        .filter_by(statistics_type=0)
    if station_id:
        fee_statistics = fee_statistics.filter_by(station_id=station_id)
    if specific_date:
        fee_statistics = fee_statistics.filter_by(
            statistics_date=specific_date)
    fee_statistics_list = fee_statistics.all()
    # 先拿到当前已有的全部统计表
    fee_sta_dict = {
        "{}:{}".format(s.statistics_date, s.station_id): s
        for s in fee_statistics_list
    }

    # 对费用统计表,需要取到三个值,分别是采购费用,运杂费,日常杂费
    # 对financial里实时更新的方法进行修改放到公共方法里
    fee_sums = session.query(
        models.Fee.date,
        func.sum(func.IF(models.Fee.type == 1, models.Fee.money,
                         0)).label("delivery"),
        func.sum(func.IF(models.Fee.type == 2, models.Fee.money,
                         0)).label("routine"), models.Fee.station_id)

    if station_id:
        fee_sums = fee_sums.filter(models.Fee.station_id == station_id)
    if specific_date:
        fee_sums = fee_sums.filter(models.Fee.date == specific_date)
    fee_sums = fee_sums.group_by(models.Fee.date).all()

    vouchers = session.query(models.FirmSettlementVoucher,
                             models.AllocationOrder,
                             models.PurchaseOrderGoods) \
        .join(models.AllocationOrder,
              models.AllocationOrder.id == models.FirmSettlementVoucher.allocation_order_id) \
        .join(models.PurchaseOrderGoods,
              models.PurchaseOrderGoods.id == models.AllocationOrder.purchase_order_goods_id)
    if station_id:
        vouchers = vouchers.filter(
            models.FirmSettlementVoucher.station_id == station_id)
    if specific_date:
        vouchers = vouchers.filter(
            func.DATE(models.FirmSettlementVoucher.create_time) ==
            specific_date)
    vouchers = vouchers.all()

    # 计算结算件数
    allocation_order_ids = {order.id for _, order, _ in vouchers}
    allocated_amount_sums = session.query(models.AllocationOrderGoods.order_id,
                                          func.sum(models.AllocationOrderGoods.allocated_amount)) \
        .filter(models.AllocationOrderGoods.order_id.in_(allocation_order_ids)) \
        .group_by(models.AllocationOrderGoods.order_id) \
        .all()
    allocated_amount_sum_dict = {
        data[0]: data[1]
        for data in allocated_amount_sums
    }

    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

    # 待结算单总金额
    voucher_sum_dict = defaultdict(int)
    voucher_station_dict = {}
    for voucher, allocation, purchase_goods in vouchers:
        amount = allocated_amount_sum_dict.get(allocation.id, 0)
        # 采购价,按件数比例计算,实配件数/采购件数*小计
        total_money = check_float(amount / purchase_goods.actual_amount *
                                  purchase_goods.subtotal)
        date = scoped_date(voucher.create_time)
        voucher_sum_dict[date] += total_money
        voucher_station_dict[date] = voucher.station_id
    # 按指定范围求和
    fee_summary_dict = {}
    for date, delivery, routine, station_id in fee_sums:
        date = scoped_date(date)
        if date not in fee_summary_dict:
            fee_summary_dict[date] = {
                "delivery_sum": 0,
                "routine_sum": 0,
                "station_id": station_id
            }
        fee_summary_dict[date]["delivery_sum"] += delivery or 0
        fee_summary_dict[date]["routine_sum"] += routine or 0
    result_dates = {scoped_date(date) for date in dates}
    for date in result_dates:
        voucher_sum = voucher_sum_dict.get(date, 0)
        fee_summary = fee_summary_dict.get(date)
        # 包含当日有采购和未采购但有其他费用的情况
        station_id = voucher_station_dict.get(
            date) or fee_summary["station_id"]
        delivery_sum = check_float(
            fee_summary["delivery_sum"]) if fee_summary else 0
        routine_sum = check_float(
            fee_summary["routine_sum"]) if fee_summary else 0
        key = "{}:{}".format(date, station_id)
        statistics = fee_sta_dict.get(key)
        if not statistics:
            new_fee_statistic = models_statistics.StatisticsStationFee(
                statistics_date=date,
                statistics_type=0,
                station_id=station_id,
                voucher_sum=voucher_sum,
                delivery_sum=delivery_sum,
                routine_sum=routine_sum)
            statistics_session.add(new_fee_statistic)
            statistics_session.flush()
            fee_sta_dict[key] = new_fee_statistic
        else:
            statistics.routine_sum = routine_sum
            statistics.delivery_sum = delivery_sum
            statistics.voucher_sum = voucher_sum_dict.get(date, 0)
    statistics_session.commit()
Пример #27
0
 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)
Пример #28
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)
Пример #29
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()
Пример #30
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)