Estimate Builder

Polar Sponsor
爱发电 赞助
.NET 9.0

构建建筑项目估算,生成包含人工、材料、设备和管理费用的详细成本分解。

Project Builder – Business Case. problem – Problem – Expactive Results:: 复杂成本结构

功能概述

Project Builder – Business Case. problem – Problem – Expactive Results:: 复杂成本结构是一项面向实际任务的技能,主要用于多重成本类别.;Markup 计算.;

核心要点

  • Format 要求不同.;
  • Solution.。
  • 它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。

使用与执行

使用时应结合输入条件选择合适的执行方式,核对必要参数、依赖环境与输出内容,并按原始要求处理异常情况。从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。

结果检查与注意事项

执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。该技能适合用于一次性任务,也可以接入自动化工作流,与其他技能或上层代理配合完成更完整的业务链路;在组合使用时,应明确每一步的输入输出关系,并避免不同步骤之间出现参数冲突。

估价构建器

商业案例

问题陈述

估价编制面临的挑战:

  • 成本结构复杂
  • 成本类别繁多
  • 需进行加价(markup)计算
  • 格式要求因项目而异

解决方案

一款结构化的估价构建工具,可生成专业的建筑工程估价,支持合理的成本分类、加价计算及多种导出能力。

技术实现

import pandas as pd
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import date
from enum import Enum


class CostCategory(Enum):
    LABOR = "labor"
    MATERIAL = "material"
    EQUIPMENT = "equipment"
    SUBCONTRACTOR = "subcontractor"
    OTHER = "other"


@dataclass
class EstimateLineItem:
    line_number: int
    wbs_code: str
    description: str
    quantity: float
    unit: str
    unit_cost: float
    category: CostCategory
    notes: str = ""

    @property
    def total_cost(self) -> float:
        return round(self.quantity * self.unit_cost, 2)


@dataclass
class CostSummary:
    labor: float = 0
    material: float = 0
    equipment: float = 0
    subcontractor: float = 0
    other: float = 0

    @property
    def direct_cost(self) -> float:
        return self.labor + self.material + self.equipment + self.subcontractor + self.other


@dataclass
class Markup:
    name: str
    rate: float  # 以小数表示(例如 0.10 表示 10%)
    base: str = "direct"  # "direct" 或 "subtotal"


class EstimateBuilder:
    """构建建筑工程估价。"""

    def __init__(self, project_name: str, project_number: str = ""):
        self.project_name = project_name
        self.project_number = project_number
        self.estimate_date = date.today()
        self.items: List[EstimateLineItem] = []
        self.markups: List[Markup] = []
        self._next_line = 1

    def add_item(self,
                 wbs_code: str,
                 description: str,
                 quantity: float,
                 unit: str,
                 unit_cost: float,
                 category: CostCategory = CostCategory.OTHER,
                 notes: str = "") -> EstimateLineItem:
        """向估价中添加明细项。"""

        item = EstimateLineItem(
            line_number=self._next_line,
            wbs_code=wbs_code,
            description=description,
            quantity=quantity,
            unit=unit,
            unit_cost=unit_cost,
            category=category,
            notes=notes
        )
        self.items.append(item)
        self._next_line += 1
        return item

    def add_markup(self, name: str, rate: float, base: str = "direct"):
        """添加加价项(如管理费、利润、不可预见费等)。"""
        self.markups.append(Markup(name=name, rate=rate, base=base))

    def set_standard_markups(self,
                             overhead: float = 0.15,
                             profit: float = 0.10,
                             contingency: float = 0.05):
        """设置标准建筑工程加价率。"""

        self.markups = [
            Markup("General Conditions / Overhead", overhead, "direct"),
            Markup("Profit", profit, "subtotal"),
            Markup("Contingency", contingency, "subtotal")
        ]

    def get_cost_summary(self) -> CostSummary:
        """按成本类别获取汇总信息。"""

        summary = CostSummary()
        for item in self.items:
            cost = item.total_cost
            if item.category == CostCategory.LABOR:
                summary.labor += cost
            elif item.category == CostCategory.MATERIAL:
                summary.material += cost
            elif item.category == CostCategory.EQUIPMENT:
                summary.equipment += cost
            elif item.category == CostCategory.SUBCONTRACTOR:
                summary.subcontractor += cost
            else:
                summary.other += cost
        return summary

    def calculate_total(self) -> Dict[str, Any]:
        """计算含加价项的估价总额。"""

        summary = self.get_cost_summary()
        direct_cost = summary.direct_cost

        markups_detail = []
        subtotal = direct_cost

        for markup in self.markups:
            if markup.base == "direct":
                amount = direct_cost * markup.rate
            else:
                amount = subtotal * markup.rate

            markups_detail.append({
                'name': markup.name,
                'rate': f"{markup.rate * 100:.1f}%",
                'amount': round(amount, 2)
            })
            subtotal += amount

        return {
            'cost_summary': {
                'labor': round(summary.labor, 2),
                'material': round(summary.material, 2),
                'equipment': round(summary.equipment, 2),
                'subcontractor': round(summary.subcontractor, 2),
                'other': round(summary.other, 2),
                'direct_cost': round(direct_cost, 2)
            },
            'markups': markups_detail,
            'total_markups': round(subtotal - direct_cost, 2),
            'grand_total': round(subtotal, 2)
        }

    def get_items_by_wbs(self) -> Dict[str, List[EstimateLineItem]]:
        """按 WBS 编码前缀对明细项进行分组。"""

        by_wbs = {}
        for item in self.items:
            prefix = item.wbs_code.split('.')[0] if '.' in item.wbs_code else item.wbs_code
            if prefix not in by_wbs:
                by_wbs[prefix] = []
            by_wbs[prefix].append(item)
        return by_wbs

    def import_from_df(self, df: pd.DataFrame):
        """从 DataFrame 导入明细项。"""

        for _, row in df.iterrows():
            self.add_item(
                wbs_code=str(row.get('wbs_code', '')),
                description=row['description'],
                quantity=float(row['quantity']),
                unit=row['unit'],
                unit_cost=float(row['unit_cost']),
                category=CostCategory(row.get('category', 'other').lower()),
                notes=row.get('notes', '')
            )

    def export_to_df(self) -> pd.DataFrame:
        """将估价导出为 DataFrame。"""

        data = []
        for item in self.items:
            data.append({
                'Line': item.line_number,
                'WBS': item.wbs_code,
                'Description': item.description,
                'Qty': item.quantity,
                'Unit': item.unit,
                'Unit Cost': item.unit_cost,
                'Total': item.total_cost,
                'Category': item.category.value,
                'Notes': item.notes
            })
        return pd.DataFrame(data)

    def export_to_excel(self, output_path: str) -> str:
        """将估价导出为 Excel 文件。"""

        totals = self.calculate_total()

        with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
            # 封面页
            cover_df = pd.DataFrame([{
                'Project Name': self.project_name,
                'Project Number': self.project_number,
                'Estimate Date': self.estimate_date,
                'Total Items': len(self.items),
                'Direct Cost': totals['cost_summary']['direct_cost'],
                'Grand Total': totals['grand_total']
            }])
            cover_df.to_excel(writer, sheet_name='Summary', index=False)

            # 明细项表
            items_df = self.export_to_df()
            items_df.to_excel(writer, sheet_name='Line Items', index=False)

            # 成本分解表
            breakdown_df = pd.DataFrame([totals['cost_summary']])
            breakdown_df.to_excel(writer, sheet_name='Cost Breakdown', index=False)

            # 加价项表
            if totals['markups']:
                markups_df = pd.DataFrame(totals['markups'])
                markups_df.to_excel(writer, sheet_name='Markups', index=False)

        return output_path

    def validate(self) -> List[str]:
        """校验估价中常见的潜在问题。"""

        issues = []

        if not self.items:
            issues.append("估价中无明细项")

        for item in self.items:
            if item.quantity <= 0:
                issues.append(f"第 {item.line_number} 行:数量无效")
            if item.unit_cost < 0:
                issues.append(f"第 {item.line_number} 行:单价为负值")
            if not item.description:
                issues.append(f"第 {item.line_number} 行:缺少描述")

        if not self.markups:
            issues.append("未定义加价项(如管理费、利润等)")

        return issues

快速上手

# 创建估价实例
estimate = EstimateBuilder("Office Building A", "PRJ-2024-001")

# 添加明细项
estimate.add_item("01.01", "Site Preparation", 5000, "SF", 2.50, CostCategory.OTHER)
estimate.add_item("03.01", "Concrete Foundation", 200, "CY", 350, CostCategory.MATERIAL)
estimate.add_item("03.02", "Foundation Formwork", 1500, "SF", 8.50, CostCategory.LABOR)
estimate.add_item("05.01", "Structural Steel", 50, "TON", 4500, CostCategory.SUBCONTRACTOR)

# 设置加价项
estimate.set_standard_markups(overhead=0.15, profit=0.10, contingency=0.05)

# 计算总金额
result = estimate.calculate_total()
print(f"Direct Cost: ${result['cost_summary']['direct_cost']:,.2f}")
print(f"Grand Total: ${result['grand_total']:,.2f}")

常见使用场景

1. 按成本类别统计

summary = estimate.get_cost_summary()
print(f"Labor: ${summary.labor:,.2f}")
print(f"Material: ${summary.material:,.2f}")

2. 导出为 Excel

estimate.export_to_excel("estimate_output.xlsx")

3. 估价校验

issues = estimate.validate()
for issue in issues:
    print(f"Warning: {issue}")

参考资料

相关专题

更多
PHP 8.6依赖注入教程合集
PHP 8.6依赖注入教程合集

服务容器负责创建对象和装配依赖,能减少PHP项目中重复的初始化代码。本专题结合PHP 8.6与Symfony的实际用法,从依赖配置讲到服务生命周期,帮助理清对象何时创建、如何释放,以及配置改变后怎样生效。

2026.12.04

0

8

PHP 8.6命令行使用技巧
PHP 8.6命令行使用技巧

PHP除了运行网站,也能用来编写终端工具和批处理脚本。本专题围绕PHP 8.6命令行开发,介绍参数输入、交互操作和结果输出的组织方式,帮助把临时脚本做成便于使用和维护的命令。

2026.12.04

0

8

PHP 8.6字符串处理实例
PHP 8.6字符串处理实例

中文、Emoji和组合字符不能总按普通字节处理,截取与转码规则也会影响最终结果。本专题整理PHP 8.6常用文本处理技巧,说明怎样保留字符完整性,并根据实际用途选择编码、排序和规范化方式。

2026.12.04

0

8

PHP 8.6 JSON使用教程
PHP 8.6 JSON使用教程

JSON常用于接口传输和数据交换,处理时既要保证结构正确,也要留意数字精度和数据量带来的影响。本专题结合PHP 8.6的实际用法,介绍JSON读写与更新的处理思路,帮助理清数据类型、错误处理和大文件读取中的关键问题。

2026.12.04

0

8

PHP 8.6报错排查指南
PHP 8.6报错排查指南

错误处理和日志记录是PHP应用定位故障、追踪运行状态的重要手段。本专题结合PHP 8.6介绍从本地调试到线上日志管理的常用做法,说明怎样保留有用的错误信息,同时控制堆栈和敏感数据的暴露,便于在问题发生后找到排查线索。

2026.12.02

0

8

PHP 8.6日期计算教程
PHP 8.6日期计算教程

日期和时间既用于页面显示,也关系到统计结果与业务规则是否准确。本专题结合PHP 8.6介绍日期计算和时区转换的常用方法,讲清日期、时间点与显示格式的区别,遇到月末、跨年或夏令时等情况时,能按明确的规则处理。

2026.12.02

0

8

PHP 8.6 cURL用法详解
PHP 8.6 cURL用法详解

cURL可用于PHP项目调用外部接口和传输文件,连接方式与认证配置会直接影响请求结果。本专题整理PHP 8.6中常见的cURL用法,说明不同连接环境下的配置思路,帮助理解证书、身份认证和请求结果之间的关系,也为调用失败时的排查提供参考。

2026.12.02

0

8

Watermill消息发布订阅实战
Watermill消息发布订阅实战

本专题聚焦Watermill的消息发布与订阅,拆解Publisher接口、Topic指定、Ack/Nack确认与批量发送,说明元数据传递、载荷序列化、消费者组与幂等消费,并整理消息重复、乱序与丢失的排查路径。

2026.12.01

0

15

Watermill安装配置指南
Watermill安装配置指南

本专题围绕Watermill的安装与快速上手展开,讲清依赖拉取、Go channel本地总线与RabbitMQ最小示例,说明消息发布订阅的调用流程、Context传递与容器网络配置,并整理依赖冲突和连接超时的处理办法。

2026.12.01

0

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
phpStudy极速入门视频教程
phpStudy极速入门视频教程

共6课时 | 54.8万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时 | 134.6万人学习