在2024年的技术落地场景中,档案管理系统的收费模式已从单一的“买断制”转向“SaaS订阅+存储弹性计费+功能模块授权”的混合模式。作为技术人员,我们需要构建一套能够精准计算费用的底层引擎。本指南将基于Python和MySQL,从零搭建一套符合2024年行业标准的计费系统,涵盖阶梯定价算法、数据库设计及前端交互实现。
为了应对市场价格的频繁波动,硬编码价格是绝对禁止的。我们将采用JSON格式定义2024年的主流收费标准。该配置包含基础版本价格、用户席位费、存储阶梯单价以及高级功能模块的授权费。
请在项目根目录下创建pricing_config.json文件,并填入以下完整的配置数据。该数据模拟了当前市场主流的中小企业版收费标准:
{
"base_fee": 5000,
"currency": "CNY",
"billing_cycle": "yearly",
"user_seat": {
"included": 10,
"unit_price": 200
},
"storage_tiers": [
{
"max_gb": 100,
"price_per_gb": 1.5
},
{
"max_gb": 500,
"price_per_gb": 1.2
},
{
"max_gb": null,
"price_per_gb": 0.8
}
],
"modules": {
"ocr_recognition": 3000,
"full_text_search": 1500,
"workflow_engine": 2500,
"audit_log": 800
}
}
配置说明:上述配置定义了年费5000元起,包含10个用户席位。超出部分每人每年200元。存储采用阶梯定价:100GB以内1.5元/GB,100-500GB之间1.2元/GB,超过500GB部分0.8元/GB。
接下来编写核心的计费逻辑。我们需要处理阶梯存储计算和模块叠加。为了确保金额计算的精确性,严禁使用浮点数,必须使用Python的Decimal模块。
创建billing_engine.py,代码如下:
import json
from decimal import Decimal
class ArchivePricingEngine:
def __init__(self, config_path='pricing_config.json'):
with open(config_path, 'r', encoding='utf-8') as f:
self.config = json.load(f)
def calculate_storage_fee(self, total_gb):
"""
根据存储量计算阶梯费用
"""
if total_gb <= 0:
return Decimal('0')
remaining_gb = Decimal(str(total_gb))
total_fee = Decimal('0')
按照配置的阶梯顺序计算
for tier in self.config['storage_tiers']:
tier_max = Decimal(str(tier['max_gb'])) if tier['max_gb'] else remaining_gb
tier_price = Decimal(str(tier['price_per_gb']))
计算当前阶梯的用量
if remaining_gb <= 0:
break
current_tier_usage = min(remaining_gb, tier_max)
total_fee += current_tier_usage tier_price
remaining_gb -= current_tier_usage
return total_fee
def calculate_total(self, user_count, storage_gb, enabled_modules):
"""
计算总费用
:param user_count: 用户总数
:param storage_gb: 存储总量(GB)
:param enabled_modules: 启用的模块列表
:return: dict
"""
1. 基础费用
base_fee = Decimal(str(self.config['base_fee']))
2. 用户席位费用
included_users = self.config['user_seat']['included']
user_unit_price = Decimal(str(self.config['user_seat']['unit_price']))
extra_users = max(0, user_count - included_users)
user_fee = extra_users user_unit_price
3. 存储费用
storage_fee = self.calculate_storage_fee(storage_gb)
4. 模块费用
module_fee = Decimal('0')
valid_modules = []
for mod in enabled_modules:
if mod in self.config['modules']:
module_fee += Decimal(str(self.config['modules'][mod]))
valid_modules.append(mod)
total_amount = base_fee + user_fee + storage_fee + module_fee
return {
"base_fee": str(base_fee),
"user_fee": str(user_fee),
"storage_fee": str(storage_fee.quantize(Decimal('0.00'))),
"module_fee": str(module_fee),
"total_amount": str(total_amount.quantize(Decimal('0.00'))),
"currency": self.config['currency']
}
测试入口
if __name__ == "__main__":
engine = ArchivePricingEngine()
模拟场景:50个用户,250GB存储,开启OCR和全文检索
result = engine.calculate_total(
user_count=50,
storage_gb=250,
enabled_modules=['ocr_recognition', 'full_text_search']
)
print(json.dumps(result, indent=2, ensure_ascii=False))
操作步骤:直接在终端运行python billing_engine.py。如果环境未安装Python,请先执行sudo apt-get install python3(Ubuntu)或访问Python官网下载安装包。运行后,你将看到包含各分项费用及总价的JSON输出,验证阶梯计算逻辑是否正确。
为了支持订单持久化和历史价格追溯,我们需要设计两张核心表:pricing_rules(用于存储不同版本的价格配置,方便后续回滚)和customer_orders(存储客户订单详情)。
请在MySQL客户端执行以下SQL语句:
CREATE DATABASE IF NOT EXISTS archive_billing_system CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE archive_billing_system;
-- 价格规则表
CREATE TABLE pricing_rules (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
rule_name VARCHAR(100) NOT NULL COMMENT '规则名称,如2024_Standard_V1',
config_json JSON NOT NULL COMMENT '完整的定价配置JSON',
effective_date DATETIME NOT NULL COMMENT '生效时间',
is_active TINYINT(1) DEFAULT 0 COMMENT '是否激活',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- 客户订单表
CREATE TABLE customer_orders (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
customer_id VARCHAR(50) NOT NULL,
rule_id BIGINT NOT NULL COMMENT '关联的定价规则ID',
user_count INT NOT NULL,
storage_gb DECIMAL(10, 2) NOT NULL,
enabled_modules JSON COMMENT '启用的模块列表',
total_amount DECIMAL(12, 2) NOT NULL,
billing_cycle_start DATE NOT NULL,
billing_cycle_end DATE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (rule_id) REFERENCES pricing_rules(id)
) ENGINE=InnoDB;
-- 插入当前默认配置
INSERT INTO pricing_rules (rule_name, config_json, effective_date, is_active)
VALUES (
'2024_Standard_V1',
'{"base_fee": 5000, "currency": "CNY", "user_seat": {"included": 10, "unit_price": 200}, "storage_tiers": [{"max_gb": 100, "price_per_gb": 1.5}, {"max_gb": 500, "price_per_gb": 1.2}, {"max_gb": null, "price_per_gb": 0.8}], "modules": {"ocr_recognition": 3000, "full_text_search": 1500}}',
NOW(),
1
);
技术细节:使用JSON数据类型存储模块列表和配置,极大地增强了扩展性。外键约束确保了订单必须关联到一个有效的定价规则版本,防止价格计算混乱。
为了让销售或客户能自主估算费用,我们需要一个纯静态的前端页面。该页面将复用后端的JSON配置逻辑,在浏览器端完成计算,无需请求服务器。

创建calculator.html文件,内容如下:
2024档案管理系统费用计算器
2024档案管理系统费用估算
基础年费:5000元 (含10用户)
额外用户费:0元
存储费:0元
模块费:0元
总计预估费用:5000 元/年
使用方法:直接双击打开calculator.html。页面加载时会自动执行calculate()函数。当你调整用户数或存储量时,oninput事件会触发重算,即时反馈总价。
我们需要将Python后端与前端进行打通。虽然前端可以做估算,但正式下单必须调用后端接口以生成数据库记录。我们可以使用Flask快速搭建一个API服务。
安装Flask:pip install flask mysql-connector-python
创建app.py:
from flask import Flask, request, jsonify
from billing_engine import ArchivePricingEngine
import mysql.connector
app = Flask(__name__)
engine = ArchivePricingEngine()
数据库连接配置
db_config = {
'user': 'root',
'password': 'your_password', 请修改为实际密码
'host': 'localhost',
'database': 'archive_billing_system'
}
@app.route('/api/calculate', methods=['POST'])
def api_calculate():
data = request.json
try:
result = engine.calculate_total(
user_count=int(data['user_count']),
storage_gb=float(data['storage_gb']),
enabled_modules=data.get('enabled_modules', [])
)
这里可以添加写入数据库的逻辑
conn = mysql.connector.connect(db_config)
cursor = conn.cursor()
... 执行INSERT INTO customer_orders ...
conn.close()
return jsonify({"code": 200, "data": result})
except Exception as e:
return jsonify({"code": 500, "error": str(e)})
if __name__ == '__main__':
app.run(port=5000, debug=True)
最终验证:运行python app.py启动服务。使用Postman或curl发送POST请求到http://localhost:5000/api/calculate,Body中传入JSON数据:{"user_count": 20, "storage_gb": 150, "enabled_modules": ["ocr_recognition"]}。若返回正确的价格 breakdown,则整个计费系统搭建完成。