@jayyuen66/dsh-dir-prep-organize 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +117 -0
- package/LICENSE +1 -1
- package/README.md +5 -5
- package/README.zh-CN.md +5 -5
- package/agents/academic/academic-statistician.md +143 -0
- package/agents/design/design-inclusive-visuals-specialist.md +4 -3
- package/agents/design/design-ui-designer.md +6 -3
- package/agents/design/design-ux-architect.md +20 -7
- package/agents/design/design-whimsy-injector.md +23 -1
- package/agents/engineering/engineering-autonomous-optimization-architect.md +31 -22
- package/agents/engineering/engineering-backend-architect.md +43 -54
- package/agents/engineering/engineering-data-engineer.md +21 -6
- package/agents/engineering/engineering-database-optimizer.md +22 -10
- package/agents/engineering/engineering-devops-automator.md +12 -3
- package/agents/engineering/engineering-email-intelligence-engineer.md +41 -4
- package/agents/engineering/engineering-embedded-firmware-engineer.md +27 -5
- package/agents/engineering/engineering-feishu-integration-developer.md +10 -2
- package/agents/engineering/engineering-frontend-developer.md +24 -18
- package/agents/engineering/engineering-git-workflow-master.md +16 -4
- package/agents/engineering/engineering-incident-response-commander.md +3 -3
- package/agents/engineering/engineering-prompt-engineer.md +7 -2
- package/agents/engineering/engineering-rapid-prototyper.md +7 -3
- package/agents/engineering/engineering-security-engineer.md +2 -0
- package/agents/engineering/engineering-solidity-smart-contract-engineer.md +1 -1
- package/agents/engineering/engineering-technical-writer.md +4 -4
- package/agents/engineering/engineering-threat-detection-engineer.md +2 -0
- package/agents/engineering/engineering-voice-ai-integration-engineer.md +39 -16
- package/agents/engineering/engineering-wechat-mini-program-developer.md +7 -2
- package/agents/game-development/blender/blender-addon-engineer.md +12 -3
- package/agents/game-development/economy-designer.md +155 -0
- package/agents/game-development/godot/godot-gameplay-scripter.md +4 -0
- package/agents/game-development/godot/godot-multiplayer-engineer.md +6 -2
- package/agents/game-development/godot/godot-shader-developer.md +4 -3
- package/agents/game-development/roblox-studio/roblox-experience-designer.md +7 -6
- package/agents/game-development/roblox-studio/roblox-systems-scripter.md +7 -0
- package/agents/game-development/technical-artist.md +4 -0
- package/agents/game-development/unity/unity-multiplayer-engineer.md +67 -0
- package/agents/game-development/unreal-engine/unreal-multiplayer-architect.md +82 -31
- package/agents/game-development/unreal-engine/unreal-systems-engineer.md +13 -1
- package/agents/marketing/marketing-agentic-search-optimizer.md +50 -87
- package/agents/marketing/marketing-carousel-growth-engine.md +49 -35
- package/agents/marketing/marketing-private-domain-operator.md +2 -2
- package/agents/marketing/marketing-seo-specialist.md +22 -0
- package/agents/product/product-behavioral-nudge-engine.md +3 -0
- package/agents/project-management/project-management-jira-workflow-steward.md +5 -2
- package/agents/security/security-appsec-engineer.md +75 -43
- package/agents/security/security-threat-detection-engineer.md +6 -0
- package/agents/security/security-threat-intelligence-analyst.md +32 -15
- package/agents/specialized/accounts-payable-agent.md +39 -45
- package/agents/specialized/grant-writer.md +2 -2
- package/agents/specialized/healthcare-aging-parent-care-companion.md +396 -0
- package/agents/specialized/identity-graph-operator.md +24 -3
- package/agents/specialized/lsp-index-engineer.md +17 -15
- package/agents/specialized/recruitment-specialist.md +17 -11
- package/agents/specialized/specialized-developer-advocate.md +4 -4
- package/agents/specialized/specialized-fedramp-rmf-compliance.md +379 -0
- package/agents/specialized/specialized-focus-music-architect.md +176 -0
- package/agents/specialized/specialized-french-consulting-market.md +17 -15
- package/agents/specialized/specialized-model-qa.md +78 -34
- package/agents/specialized/specialized-salesforce-architect.md +17 -15
- package/agents/specialized/specialized-workflow-architect.md +2 -2
- package/agents/supply-chain/supply-chain-strategist.md +12 -3
- package/agents/support/support-analytics-reporter.md +48 -30
- package/agents/support/support-finance-tracker.md +36 -18
- package/agents/support/support-infrastructure-maintainer.md +2 -2
- package/agents/support/support-support-responder.md +43 -26
- package/agents/testing/testing-api-tester.md +37 -27
- package/agents/testing/testing-performance-benchmarker.md +82 -47
- package/agents/testing/testing-test-results-analyzer.md +37 -18
- package/agents/testing/testing-tool-evaluator.md +30 -10
- package/client.js +118 -82
- package/cordis.patch.yml +4 -23
- package/host.js +49 -18
- package/package.json +44 -43
- package/templates.data.mjs +9 -10
- package/types/host.d.ts +9 -4
- package/types/src/host-messages.d.ts +2 -0
- package/types/src/remote.d.ts +7 -1
- package/types/src/ui-messages.d.ts +10 -2
|
@@ -87,10 +87,17 @@ class InventoryManager:
|
|
|
87
87
|
EOQ = sqrt(2 * D * S / H)
|
|
88
88
|
"""
|
|
89
89
|
d = self.params.annual_demand
|
|
90
|
+
if d <= 0:
|
|
91
|
+
raise ValueError("Discrete-unit EOQ requires positive annual demand")
|
|
90
92
|
s = self.params.order_cost
|
|
91
93
|
h = self.params.unit_price * self.params.holding_cost_rate
|
|
94
|
+
if not np.isfinite([d, s, h]).all() or s < 0 or h <= 0:
|
|
95
|
+
raise ValueError("EOQ needs finite demand/costs and positive holding cost")
|
|
92
96
|
eoq = np.sqrt(2 * d * s / h)
|
|
93
|
-
|
|
97
|
+
# 最小化实际的离散订货成本与持有成本之和,
|
|
98
|
+
# 不能简单四舍五入(相邻整数的分界点是 sqrt(n*(n+1)))。
|
|
99
|
+
candidates = {max(1, int(np.floor(eoq))), max(1, int(np.ceil(eoq)))}
|
|
100
|
+
return min(candidates, key=lambda q: (d * s / q + h * q / 2, q))
|
|
94
101
|
|
|
95
102
|
def calculate_safety_stock(self) -> float:
|
|
96
103
|
"""
|
|
@@ -154,7 +161,9 @@ class InventoryManager:
|
|
|
154
161
|
eoq = self.calculate_eoq()
|
|
155
162
|
safety_stock = self.calculate_safety_stock()
|
|
156
163
|
rop = self.calculate_reorder_point()
|
|
157
|
-
|
|
164
|
+
# 稳态 EOQ 模型用的是年订货频率,它可以是小数。
|
|
165
|
+
# 四舍五入会改变订货成本这一优化目标。
|
|
166
|
+
annual_orders = self.params.annual_demand / eoq
|
|
158
167
|
total_cost = (
|
|
159
168
|
self.params.annual_demand * self.params.unit_price + # 采购成本
|
|
160
169
|
annual_orders * self.params.order_cost + # 订货成本
|
|
@@ -166,7 +175,7 @@ class InventoryManager:
|
|
|
166
175
|
'eoq': eoq, # 经济订货量
|
|
167
176
|
'safety_stock': safety_stock, # 安全库存
|
|
168
177
|
'reorder_point': rop, # 再订货点
|
|
169
|
-
'annual_orders': annual_orders, #
|
|
178
|
+
'annual_orders': annual_orders, # 年均订货次数
|
|
170
179
|
'total_annual_cost': round(total_cost, 2), # 年度总成本
|
|
171
180
|
'avg_inventory': round(eoq / 2 + safety_stock), # 平均库存量
|
|
172
181
|
'inventory_turns': round(self.params.annual_demand / (eoq / 2 + safety_stock), 1) # 库存周转次数
|
|
@@ -61,16 +61,16 @@ WITH monthly_metrics AS (
|
|
|
61
61
|
SUM(revenue) as monthly_revenue,
|
|
62
62
|
COUNT(DISTINCT customer_id) as active_customers,
|
|
63
63
|
AVG(order_value) as avg_order_value,
|
|
64
|
-
SUM(revenue) / COUNT(DISTINCT customer_id) as revenue_per_customer
|
|
64
|
+
SUM(revenue) * 1.0 / NULLIF(COUNT(DISTINCT customer_id), 0) as revenue_per_customer
|
|
65
65
|
FROM transactions
|
|
66
|
-
WHERE date >=
|
|
66
|
+
WHERE date >= CURRENT_DATE - INTERVAL '12 months'
|
|
67
67
|
GROUP BY DATE_TRUNC('month', date)
|
|
68
68
|
),
|
|
69
69
|
growth_calculations AS (
|
|
70
70
|
SELECT *,
|
|
71
71
|
LAG(monthly_revenue, 1) OVER (ORDER BY month) as prev_month_revenue,
|
|
72
|
-
(monthly_revenue - LAG(monthly_revenue, 1) OVER (ORDER BY month)) /
|
|
73
|
-
LAG(monthly_revenue, 1) OVER (ORDER BY month)
|
|
72
|
+
(monthly_revenue - LAG(monthly_revenue, 1) OVER (ORDER BY month)) * 100.0 /
|
|
73
|
+
NULLIF(LAG(monthly_revenue, 1) OVER (ORDER BY month), 0) as revenue_growth_rate
|
|
74
74
|
FROM monthly_metrics
|
|
75
75
|
)
|
|
76
76
|
SELECT
|
|
@@ -81,6 +81,7 @@ SELECT
|
|
|
81
81
|
revenue_per_customer,
|
|
82
82
|
revenue_growth_rate,
|
|
83
83
|
CASE
|
|
84
|
+
WHEN revenue_growth_rate IS NULL THEN 'No Comparable Baseline'
|
|
84
85
|
WHEN revenue_growth_rate > 10 THEN 'High Growth'
|
|
85
86
|
WHEN revenue_growth_rate > 0 THEN 'Positive Growth'
|
|
86
87
|
ELSE 'Needs Attention'
|
|
@@ -90,6 +91,9 @@ ORDER BY month DESC;
|
|
|
90
91
|
```
|
|
91
92
|
|
|
92
93
|
### 客户细分分析
|
|
94
|
+
|
|
95
|
+
输入的行可能是单个订单明细。计算时对收入求和,计算购买频率时按客户统计不重复的订单 ID。
|
|
96
|
+
|
|
93
97
|
```python
|
|
94
98
|
import pandas as pd
|
|
95
99
|
import numpy as np
|
|
@@ -106,7 +110,7 @@ def customer_segmentation_analysis(df):
|
|
|
106
110
|
current_date = df['date'].max()
|
|
107
111
|
rfm = df.groupby('customer_id').agg({
|
|
108
112
|
'date': lambda x: (current_date - x.max()).days, # 最近一次消费(Recency)
|
|
109
|
-
'order_id': '
|
|
113
|
+
'order_id': 'nunique', # 消费频率(Frequency):不重复订单数
|
|
110
114
|
'revenue': 'sum' # 消费金额(Monetary)
|
|
111
115
|
}).rename(columns={
|
|
112
116
|
'date': 'recency',
|
|
@@ -114,10 +118,16 @@ def customer_segmentation_analysis(df):
|
|
|
114
118
|
'revenue': 'monetary'
|
|
115
119
|
})
|
|
116
120
|
|
|
117
|
-
#
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
+
# 百分位档位适用于小样本,并将相同值放在同一档。
|
|
122
|
+
# 这是当前客群内的相对评分,不是绝对价值阈值。
|
|
123
|
+
def score(values, higher_is_better=True):
|
|
124
|
+
percentile = values.rank(method='average', pct=True)
|
|
125
|
+
band = np.ceil(percentile * 5).clip(1, 5).astype(int)
|
|
126
|
+
return band if higher_is_better else 6 - band
|
|
127
|
+
|
|
128
|
+
rfm['r_score'] = score(rfm['recency'], higher_is_better=False)
|
|
129
|
+
rfm['f_score'] = score(rfm['frequency'])
|
|
130
|
+
rfm['m_score'] = score(rfm['monetary'])
|
|
121
131
|
|
|
122
132
|
# 客户分群
|
|
123
133
|
rfm['rfm_score'] = rfm['r_score'].astype(str) + rfm['f_score'].astype(str) + rfm['m_score'].astype(str)
|
|
@@ -131,10 +141,10 @@ def customer_segmentation_analysis(df):
|
|
|
131
141
|
return 'Potential Loyalists'
|
|
132
142
|
elif row['rfm_score'] in ['512', '511', '422', '421', '412', '411', '311']:
|
|
133
143
|
return 'New Customers'
|
|
134
|
-
elif row['
|
|
135
|
-
return 'At Risk'
|
|
136
|
-
elif row['rfm_score'] in ['155', '154', '144', '214', '215', '115', '114']:
|
|
144
|
+
elif row['r_score'] <= 2 and row['f_score'] == 5:
|
|
137
145
|
return 'Cannot Lose Them'
|
|
146
|
+
elif row['r_score'] <= 2 and row['f_score'] in (3, 4):
|
|
147
|
+
return 'At Risk'
|
|
138
148
|
else:
|
|
139
149
|
return 'Others'
|
|
140
150
|
|
|
@@ -158,30 +168,38 @@ def generate_customer_insights(rfm_df):
|
|
|
158
168
|
return insights
|
|
159
169
|
```
|
|
160
170
|
|
|
171
|
+
示例中的流失规则把"最近购买间隔大(R 为 1–2)、频率最高(F 为 5)"的流失客户,与其他高频流失客户(F 为 3–4)区分开,不考虑消费金额档位。原来两个分支的取值列表完全相同,导致 `Cannot Lose Them` 永远走不到。这里的阈值只是示例,不是通用的营销活动标准,需要结合你的客户生命周期验证。
|
|
172
|
+
|
|
161
173
|
### 营销效果仪表盘
|
|
162
174
|
```javascript
|
|
163
175
|
// 营销归因与 ROI 分析
|
|
164
176
|
const marketingDashboard = {
|
|
165
177
|
// 多触点归因模型
|
|
178
|
+
// conversion_id 和 touchpoint_id 分别是唯一 ID;每次转化单独归因。
|
|
179
|
+
// 恰好两个触点时各分配一半收入。
|
|
166
180
|
attributionAnalysis: `
|
|
167
181
|
WITH customer_touchpoints AS (
|
|
168
182
|
SELECT
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
183
|
+
c.conversion_id,
|
|
184
|
+
mt.customer_id,
|
|
185
|
+
mt.channel,
|
|
186
|
+
mt.campaign,
|
|
187
|
+
mt.touchpoint_date,
|
|
188
|
+
c.conversion_date,
|
|
189
|
+
c.revenue,
|
|
190
|
+
ROW_NUMBER() OVER (
|
|
191
|
+
PARTITION BY c.conversion_id ORDER BY mt.touchpoint_date, mt.touchpoint_id
|
|
192
|
+
) as touch_sequence,
|
|
193
|
+
COUNT(*) OVER (PARTITION BY c.conversion_id) as total_touches
|
|
177
194
|
FROM marketing_touchpoints mt
|
|
178
195
|
JOIN conversions c ON mt.customer_id = c.customer_id
|
|
179
|
-
WHERE touchpoint_date <= conversion_date
|
|
196
|
+
WHERE mt.touchpoint_date <= c.conversion_date
|
|
180
197
|
),
|
|
181
198
|
attribution_weights AS (
|
|
182
199
|
SELECT *,
|
|
183
200
|
CASE
|
|
184
|
-
WHEN
|
|
201
|
+
WHEN total_touches = 1 THEN 1.0 -- 单触点
|
|
202
|
+
WHEN total_touches = 2 THEN 0.5 -- 双触点
|
|
185
203
|
WHEN touch_sequence = 1 THEN 0.4 -- 首次触点
|
|
186
204
|
WHEN touch_sequence = total_touches THEN 0.4 -- 最后触点
|
|
187
205
|
ELSE 0.2 / (total_touches - 2) -- 中间触点
|
|
@@ -192,25 +210,25 @@ const marketingDashboard = {
|
|
|
192
210
|
channel,
|
|
193
211
|
campaign,
|
|
194
212
|
SUM(revenue * attribution_weight) as attributed_revenue,
|
|
195
|
-
COUNT(DISTINCT
|
|
196
|
-
SUM(revenue * attribution_weight) / COUNT(DISTINCT
|
|
213
|
+
COUNT(DISTINCT conversion_id) as attributed_conversions,
|
|
214
|
+
SUM(revenue * attribution_weight) / COUNT(DISTINCT conversion_id) as revenue_per_conversion
|
|
197
215
|
FROM attribution_weights
|
|
198
216
|
GROUP BY channel, campaign
|
|
199
217
|
ORDER BY attributed_revenue DESC;
|
|
200
218
|
`,
|
|
201
219
|
|
|
202
|
-
// 营销活动 ROI
|
|
220
|
+
// PostgreSQL 营销活动 ROI:conversions 为每行已统计的转化数
|
|
203
221
|
campaignROI: `
|
|
204
222
|
SELECT
|
|
205
223
|
campaign_name,
|
|
206
224
|
SUM(spend) as total_spend,
|
|
207
225
|
SUM(attributed_revenue) as total_revenue,
|
|
208
|
-
(SUM(attributed_revenue) - SUM(spend)) / SUM(spend)
|
|
209
|
-
SUM(attributed_revenue) / SUM(spend) as revenue_multiple,
|
|
210
|
-
|
|
211
|
-
SUM(spend) /
|
|
226
|
+
(SUM(attributed_revenue) - SUM(spend)) * 100.0 / SUM(spend) as roi_percentage,
|
|
227
|
+
SUM(attributed_revenue) * 1.0 / SUM(spend) as revenue_multiple,
|
|
228
|
+
SUM(conversions) as total_conversions,
|
|
229
|
+
SUM(spend) * 1.0 / NULLIF(SUM(conversions), 0) as cost_per_conversion
|
|
212
230
|
FROM campaign_performance
|
|
213
|
-
WHERE date >=
|
|
231
|
+
WHERE date >= CURRENT_DATE - INTERVAL '90 days'
|
|
214
232
|
GROUP BY campaign_name
|
|
215
233
|
HAVING SUM(spend) > 1000 -- 过滤有效投放
|
|
216
234
|
ORDER BY roi_percentage DESC;
|
|
@@ -69,9 +69,9 @@ WITH budget_actuals AS (
|
|
|
69
69
|
actual_amount,
|
|
70
70
|
DATE_TRUNC('quarter', date) as quarter,
|
|
71
71
|
budget_amount - actual_amount as variance,
|
|
72
|
-
(actual_amount - budget_amount) / budget_amount
|
|
72
|
+
(actual_amount - budget_amount) * 100.0 / NULLIF(budget_amount, 0) as variance_percentage
|
|
73
73
|
FROM financial_data
|
|
74
|
-
WHERE fiscal_year = YEAR
|
|
74
|
+
WHERE fiscal_year = EXTRACT(YEAR FROM CURRENT_DATE)
|
|
75
75
|
),
|
|
76
76
|
department_summary AS (
|
|
77
77
|
SELECT
|
|
@@ -80,7 +80,8 @@ department_summary AS (
|
|
|
80
80
|
SUM(budget_amount) as total_budget,
|
|
81
81
|
SUM(actual_amount) as total_actual,
|
|
82
82
|
SUM(variance) as total_variance,
|
|
83
|
-
|
|
83
|
+
(SUM(actual_amount) - SUM(budget_amount)) * 100.0 /
|
|
84
|
+
NULLIF(SUM(budget_amount), 0) as variance_pct
|
|
84
85
|
FROM budget_actuals
|
|
85
86
|
GROUP BY department, quarter
|
|
86
87
|
)
|
|
@@ -90,10 +91,11 @@ SELECT
|
|
|
90
91
|
total_budget,
|
|
91
92
|
total_actual,
|
|
92
93
|
total_variance,
|
|
93
|
-
|
|
94
|
+
variance_pct,
|
|
94
95
|
CASE
|
|
95
|
-
WHEN
|
|
96
|
-
WHEN
|
|
96
|
+
WHEN variance_pct IS NULL THEN 'No Budget Baseline'
|
|
97
|
+
WHEN ABS(variance_pct) <= 5 THEN 'On Track' -- 在轨
|
|
98
|
+
WHEN variance_pct > 5 THEN 'Over Budget' -- 超预算
|
|
97
99
|
ELSE 'Under Budget' -- 低于预算
|
|
98
100
|
END as budget_status,
|
|
99
101
|
total_budget - total_actual as remaining_budget -- 剩余预算
|
|
@@ -102,10 +104,13 @@ ORDER BY department, quarter;
|
|
|
102
104
|
```
|
|
103
105
|
|
|
104
106
|
### 现金流管理系统
|
|
107
|
+
|
|
108
|
+
下面的上下浮动 15% 仅为示例情景区间,不是统计置信区间。示例中的季节系数、增长系数与初始现金余额需要由业务实现提供;历史数据需覆盖要预测的月份。
|
|
109
|
+
|
|
105
110
|
```python
|
|
106
111
|
import pandas as pd
|
|
107
112
|
import numpy as np
|
|
108
|
-
from datetime import datetime
|
|
113
|
+
from datetime import datetime
|
|
109
114
|
import matplotlib.pyplot as plt
|
|
110
115
|
|
|
111
116
|
class CashFlowManager:
|
|
@@ -117,7 +122,9 @@ class CashFlowManager:
|
|
|
117
122
|
"""
|
|
118
123
|
生成 12 个月滚动现金流预测
|
|
119
124
|
"""
|
|
120
|
-
|
|
125
|
+
rows = []
|
|
126
|
+
cumulative_cash = self.current_cash
|
|
127
|
+
start_month = pd.Timestamp(datetime.now()).to_period('M')
|
|
121
128
|
|
|
122
129
|
# 历史模式分析
|
|
123
130
|
monthly_patterns = self.data.groupby('month').agg({
|
|
@@ -128,7 +135,7 @@ class CashFlowManager:
|
|
|
128
135
|
|
|
129
136
|
# 带季节性因子的预测
|
|
130
137
|
for i in range(periods):
|
|
131
|
-
forecast_date =
|
|
138
|
+
forecast_date = (start_month + i).to_timestamp()
|
|
132
139
|
month = forecast_date.month
|
|
133
140
|
|
|
134
141
|
# 计算季节性系数
|
|
@@ -141,17 +148,21 @@ class CashFlowManager:
|
|
|
141
148
|
|
|
142
149
|
net_flow = forecasted_receipts - forecasted_payments
|
|
143
150
|
|
|
144
|
-
|
|
151
|
+
cumulative_cash += net_flow
|
|
152
|
+
rows.append({
|
|
145
153
|
'date': forecast_date,
|
|
146
154
|
'forecasted_receipts': forecasted_receipts, # 预计收款
|
|
147
155
|
'forecasted_payments': forecasted_payments, # 预计付款
|
|
148
156
|
'net_cash_flow': net_flow, # 净现金流
|
|
149
|
-
'cumulative_cash':
|
|
150
|
-
'
|
|
151
|
-
'
|
|
152
|
-
}
|
|
157
|
+
'cumulative_cash': cumulative_cash, # 累计现金
|
|
158
|
+
'scenario_low': net_flow - abs(net_flow) * 0.15, # 情景下限,不是置信区间
|
|
159
|
+
'scenario_high': net_flow + abs(net_flow) * 0.15 # 情景上限,不是置信区间
|
|
160
|
+
})
|
|
153
161
|
|
|
154
|
-
return
|
|
162
|
+
return pd.DataFrame(rows, columns=[
|
|
163
|
+
'date', 'forecasted_receipts', 'forecasted_payments', 'net_cash_flow',
|
|
164
|
+
'cumulative_cash', 'scenario_low', 'scenario_high'
|
|
165
|
+
])
|
|
155
166
|
|
|
156
167
|
def identify_cash_flow_risks(self, forecast_df):
|
|
157
168
|
"""
|
|
@@ -220,14 +231,21 @@ class InvestmentAnalyzer:
|
|
|
220
231
|
计算内部收益率(IRR)
|
|
221
232
|
"""
|
|
222
233
|
from scipy.optimize import fsolve
|
|
234
|
+
import math
|
|
223
235
|
|
|
224
236
|
def npv_function(rate):
|
|
225
237
|
return sum([cf / ((1 + rate) ** (i + 1)) for i, cf in enumerate(cash_flows)]) - initial_investment
|
|
226
238
|
|
|
227
239
|
try:
|
|
228
|
-
|
|
240
|
+
roots, info, status, _ = fsolve(npv_function, 0.1, full_output=True)
|
|
241
|
+
irr = float(roots[0])
|
|
242
|
+
scale = max(1.0, abs(initial_investment), sum(abs(cf) for cf in cash_flows))
|
|
243
|
+
if (status != 1 or not math.isfinite(irr) or irr <= -1 or
|
|
244
|
+
not math.isfinite(float(info['fvec'][0])) or
|
|
245
|
+
abs(float(info['fvec'][0])) > 1e-7 * scale):
|
|
246
|
+
return None
|
|
229
247
|
return irr
|
|
230
|
-
except:
|
|
248
|
+
except (ValueError, TypeError, OverflowError, ZeroDivisionError):
|
|
231
249
|
return None
|
|
232
250
|
|
|
233
251
|
def payback_period(self, cash_flows, initial_investment):
|
|
@@ -257,7 +275,7 @@ class InvestmentAnalyzer:
|
|
|
257
275
|
'project_name': project_name,
|
|
258
276
|
'initial_investment': initial_investment,
|
|
259
277
|
'npv': npv,
|
|
260
|
-
'irr': irr * 100 if irr else None,
|
|
278
|
+
'irr': irr * 100 if irr is not None else None,
|
|
261
279
|
'payback_period': payback,
|
|
262
280
|
'roi_percentage': roi,
|
|
263
281
|
'risk_score': risk_score,
|
|
@@ -334,7 +334,7 @@ backup_database() {
|
|
|
334
334
|
fi
|
|
335
335
|
|
|
336
336
|
# 加密备份文件
|
|
337
|
-
if ! gpg --cipher-algo AES256 --compress-algo 1 --s2k-mode 3 \
|
|
337
|
+
if ! gpg --batch --cipher-algo AES256 --compress-algo 1 --s2k-mode 3 \
|
|
338
338
|
--s2k-digest-algo SHA512 --s2k-count 65536 --symmetric \
|
|
339
339
|
--passphrase-file "$ENCRYPTION_KEY" "$backup_file"; then
|
|
340
340
|
handle_error "数据库 $db_name 备份加密失败"
|
|
@@ -360,7 +360,7 @@ backup_files() {
|
|
|
360
360
|
|
|
361
361
|
# 压缩打包并加密
|
|
362
362
|
if ! tar -czf - -C "$source_dir" . | \
|
|
363
|
-
gpg --cipher-algo AES256 --compress-algo 0 --s2k-mode 3 \
|
|
363
|
+
gpg --batch --cipher-algo AES256 --compress-algo 0 --s2k-mode 3 \
|
|
364
364
|
--s2k-digest-algo SHA512 --s2k-count 65536 --symmetric \
|
|
365
365
|
--passphrase-file "$ENCRYPTION_KEY" \
|
|
366
366
|
--output "$backup_file"; then
|
|
@@ -159,7 +159,7 @@ class SupportAnalytics:
|
|
|
159
159
|
# 质量指标
|
|
160
160
|
self.metrics['first_contact_resolution_rate'] = (
|
|
161
161
|
len(self.data[self.data['contacts_to_resolution'] == 1]) /
|
|
162
|
-
len(self.data) * 100
|
|
162
|
+
len(self.data) * 100 if len(self.data) else None
|
|
163
163
|
)
|
|
164
164
|
|
|
165
165
|
self.metrics['customer_satisfaction_score'] = self.data['csat_score'].mean()
|
|
@@ -180,27 +180,41 @@ class SupportAnalytics:
|
|
|
180
180
|
return self.metrics
|
|
181
181
|
|
|
182
182
|
def identify_support_trends(self):
|
|
183
|
-
"""
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
trends['top_issues'] = issue_frequency.head(5).to_dict()
|
|
195
|
-
|
|
196
|
-
# 客户满意度趋势
|
|
197
|
-
monthly_csat = self.data.groupby(self.data['created_date'].dt.month)['csat_score'].mean()
|
|
198
|
-
trends['satisfaction_trend'] = 'improving' if monthly_csat.iloc[-1] > monthly_csat.iloc[-2] else 'declining'
|
|
199
|
-
|
|
200
|
-
# 响应时间趋势
|
|
201
|
-
weekly_response_time = self.data.groupby(self.data['created_date'].dt.week)['first_response_time'].mean()
|
|
202
|
-
trends['response_time_trend'] = 'improving' if weekly_response_time.iloc[-1] < weekly_response_time.iloc[-2] else 'declining'
|
|
183
|
+
"""按自然日历周期比较趋势,保留跨年边界与缺失证据。"""
|
|
184
|
+
dated = self.data.dropna(subset=['created_date']).set_index('created_date').sort_index()
|
|
185
|
+
|
|
186
|
+
def compare_recent_periods(values, lower_is_better=False):
|
|
187
|
+
if len(values) < 2 or values.iloc[-2:].isna().any():
|
|
188
|
+
return 'insufficient_data'
|
|
189
|
+
previous, current = values.iloc[-2], values.iloc[-1]
|
|
190
|
+
if current == previous:
|
|
191
|
+
return 'stable'
|
|
192
|
+
improving = current < previous if lower_is_better else current > previous
|
|
193
|
+
return 'improving' if improving else 'declining'
|
|
203
194
|
|
|
195
|
+
trends = {}
|
|
196
|
+
# 假设首末日期之间的每一天都在数据采集范围内。
|
|
197
|
+
# 纳入零工单的自然日,比较截至最新观测日期的连续两个七天窗口,
|
|
198
|
+
# 而不是只比较有工单的七个日期。
|
|
199
|
+
daily_volume = dated.resample('D').size()
|
|
200
|
+
trends['volume_trend'] = 'insufficient_data'
|
|
201
|
+
if len(daily_volume) >= 14:
|
|
202
|
+
previous = daily_volume.iloc[-14:-7].mean()
|
|
203
|
+
current = daily_volume.iloc[-7:].mean()
|
|
204
|
+
trends['volume_trend'] = (
|
|
205
|
+
'stable' if current == previous else
|
|
206
|
+
'increasing' if current > previous else 'decreasing'
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
trends['top_issues'] = self.data['issue_category'].value_counts().head(5).to_dict()
|
|
210
|
+
# 按日历重采样可正确处理十二月到一月的跨年顺序,
|
|
211
|
+
# 缺失月份或周保留为 NaN,不混合不同年份,也不猜测趋势。
|
|
212
|
+
monthly_csat = dated['csat_score'].resample('MS').mean()
|
|
213
|
+
trends['satisfaction_trend'] = compare_recent_periods(monthly_csat)
|
|
214
|
+
weekly_response_time = dated['first_response_time'].resample('W').mean()
|
|
215
|
+
trends['response_time_trend'] = compare_recent_periods(
|
|
216
|
+
weekly_response_time, lower_is_better=True
|
|
217
|
+
)
|
|
204
218
|
return trends
|
|
205
219
|
|
|
206
220
|
def generate_improvement_recommendations(self):
|
|
@@ -220,7 +234,8 @@ class SupportAnalytics:
|
|
|
220
234
|
})
|
|
221
235
|
|
|
222
236
|
# 首次联系解决率建议
|
|
223
|
-
if self.metrics['first_contact_resolution_rate']
|
|
237
|
+
if (self.metrics['first_contact_resolution_rate'] is not None and
|
|
238
|
+
self.metrics['first_contact_resolution_rate'] < 80):
|
|
224
239
|
recommendations.append({
|
|
225
240
|
'area': '解决效率',
|
|
226
241
|
'issue': f"首次联系解决率为 {self.metrics['first_contact_resolution_rate']:.1f}%",
|
|
@@ -245,9 +260,10 @@ class SupportAnalytics:
|
|
|
245
260
|
"""
|
|
246
261
|
识别需要主动支持外联的客户
|
|
247
262
|
"""
|
|
263
|
+
now = datetime.now(tz=self.data['created_date'].dt.tz)
|
|
248
264
|
# 近期有多个工单的客户
|
|
249
265
|
frequent_reporters = self.data[
|
|
250
|
-
self.data['created_date'] >=
|
|
266
|
+
self.data['created_date'] >= now - timedelta(days=30)
|
|
251
267
|
].groupby('customer_id').size()
|
|
252
268
|
|
|
253
269
|
high_volume_customers = frequent_reporters[frequent_reporters >= 3].index.tolist()
|
|
@@ -255,13 +271,14 @@ class SupportAnalytics:
|
|
|
255
271
|
# 满意度低的客户
|
|
256
272
|
low_satisfaction = self.data[
|
|
257
273
|
(self.data['csat_score'] <= 3) &
|
|
258
|
-
(self.data['created_date'] >=
|
|
274
|
+
(self.data['created_date'] >= now - timedelta(days=7))
|
|
259
275
|
]['customer_id'].unique()
|
|
260
276
|
|
|
261
|
-
#
|
|
277
|
+
# 状态已知为未解决、且已超过 SLA 的工单客户
|
|
262
278
|
overdue_tickets = self.data[
|
|
279
|
+
self.data['status'].notna() &
|
|
263
280
|
(self.data['status'] != 'resolved') &
|
|
264
|
-
(self.data['created_date'] <=
|
|
281
|
+
(self.data['created_date'] <= now - timedelta(hours=48))
|
|
265
282
|
]['customer_id'].unique()
|
|
266
283
|
|
|
267
284
|
return {
|
|
@@ -58,29 +58,36 @@ color: purple
|
|
|
58
58
|
|
|
59
59
|
### 全面的 API 测试套件示例
|
|
60
60
|
```javascript
|
|
61
|
-
//
|
|
61
|
+
// 保存为 tests/api.spec.ts。只能在获得授权的测试环境中运行。
|
|
62
|
+
// 包含安全与性能测试的高级 API 自动化测试
|
|
62
63
|
import { test, expect } from '@playwright/test';
|
|
63
64
|
import { performance } from 'perf_hooks';
|
|
64
65
|
|
|
65
|
-
describe('User API Comprehensive Testing', () => {
|
|
66
|
+
test.describe('User API Comprehensive Testing', () => {
|
|
66
67
|
let authToken: string;
|
|
67
|
-
|
|
68
|
+
const baseURL = process.env.API_BASE_URL;
|
|
69
|
+
if (!baseURL || !process.env.TEST_USER_PASSWORD) {
|
|
70
|
+
throw new Error('API_BASE_URL and TEST_USER_PASSWORD are required');
|
|
71
|
+
}
|
|
68
72
|
|
|
69
|
-
beforeAll(async () => {
|
|
73
|
+
test.beforeAll(async () => {
|
|
70
74
|
// 认证并获取 token
|
|
71
75
|
const response = await fetch(`${baseURL}/auth/login`, {
|
|
72
76
|
method: 'POST',
|
|
73
77
|
headers: { 'Content-Type': 'application/json' },
|
|
74
78
|
body: JSON.stringify({
|
|
75
79
|
email: 'test@example.com',
|
|
76
|
-
password:
|
|
80
|
+
password: process.env.TEST_USER_PASSWORD
|
|
77
81
|
})
|
|
78
82
|
});
|
|
83
|
+
expect(response.status).toBe(200);
|
|
79
84
|
const data = await response.json();
|
|
85
|
+
expect(typeof data.token).toBe('string');
|
|
86
|
+
expect(data.token.length).toBeGreaterThan(0);
|
|
80
87
|
authToken = data.token;
|
|
81
88
|
});
|
|
82
89
|
|
|
83
|
-
describe('Functional Testing', () => {
|
|
90
|
+
test.describe('Functional Testing', () => {
|
|
84
91
|
test('should create user with valid data', async () => {
|
|
85
92
|
const userData = {
|
|
86
93
|
name: 'Test User',
|
|
@@ -100,7 +107,7 @@ describe('User API Comprehensive Testing', () => {
|
|
|
100
107
|
expect(response.status).toBe(201);
|
|
101
108
|
const user = await response.json();
|
|
102
109
|
expect(user.email).toBe(userData.email);
|
|
103
|
-
expect(user.password).toBeUndefined(); //
|
|
110
|
+
expect(user.password).toBeUndefined(); // 不应返回密码
|
|
104
111
|
});
|
|
105
112
|
|
|
106
113
|
test('should handle invalid input gracefully', async () => {
|
|
@@ -126,7 +133,7 @@ describe('User API Comprehensive Testing', () => {
|
|
|
126
133
|
});
|
|
127
134
|
});
|
|
128
135
|
|
|
129
|
-
describe('Security Testing', () => {
|
|
136
|
+
test.describe('Security Testing', () => {
|
|
130
137
|
test('should reject requests without authentication', async () => {
|
|
131
138
|
const response = await fetch(`${baseURL}/users`, {
|
|
132
139
|
method: 'GET'
|
|
@@ -136,17 +143,20 @@ describe('User API Comprehensive Testing', () => {
|
|
|
136
143
|
|
|
137
144
|
test('should prevent SQL injection attempts', async () => {
|
|
138
145
|
const sqlInjection = "'; DROP TABLE users; --";
|
|
139
|
-
const response = await fetch(`${baseURL}/users?search=${sqlInjection}`, {
|
|
146
|
+
const response = await fetch(`${baseURL}/users?search=${encodeURIComponent(sqlInjection)}`, {
|
|
140
147
|
headers: { 'Authorization': `Bearer ${authToken}` }
|
|
141
148
|
});
|
|
142
149
|
expect(response.status).not.toBe(500);
|
|
143
|
-
// 应返回安全的结果或 400
|
|
150
|
+
// 应返回安全的结果或 400,而不是崩溃
|
|
144
151
|
});
|
|
145
152
|
|
|
146
153
|
test('should enforce rate limiting', async () => {
|
|
154
|
+
// 使用单独的账号/token:耗尽它的配额不能影响其他测试。
|
|
155
|
+
const rateLimitToken = process.env.RATE_LIMIT_TEST_TOKEN;
|
|
156
|
+
if (!rateLimitToken) throw new Error('RATE_LIMIT_TEST_TOKEN is required');
|
|
147
157
|
const requests = Array(100).fill(null).map(() =>
|
|
148
158
|
fetch(`${baseURL}/users`, {
|
|
149
|
-
headers: { 'Authorization': `Bearer ${
|
|
159
|
+
headers: { 'Authorization': `Bearer ${rateLimitToken}` }
|
|
150
160
|
})
|
|
151
161
|
);
|
|
152
162
|
|
|
@@ -156,7 +166,7 @@ describe('User API Comprehensive Testing', () => {
|
|
|
156
166
|
});
|
|
157
167
|
});
|
|
158
168
|
|
|
159
|
-
describe('Performance Testing', () => {
|
|
169
|
+
test.describe('Performance Testing', () => {
|
|
160
170
|
test('should respond within performance SLA', async () => {
|
|
161
171
|
const startTime = performance.now();
|
|
162
172
|
|
|
@@ -164,30 +174,30 @@ describe('User API Comprehensive Testing', () => {
|
|
|
164
174
|
headers: { 'Authorization': `Bearer ${authToken}` }
|
|
165
175
|
});
|
|
166
176
|
|
|
177
|
+
await response.arrayBuffer(); // 把响应体的传输时间也计入延迟
|
|
167
178
|
const endTime = performance.now();
|
|
168
179
|
const responseTime = endTime - startTime;
|
|
169
180
|
|
|
170
181
|
expect(response.status).toBe(200);
|
|
171
|
-
expect(responseTime).toBeLessThan(200); // 低于 200ms SLA
|
|
182
|
+
expect(responseTime).toBeLessThan(200); // 低于 200ms 的 SLA
|
|
172
183
|
});
|
|
173
184
|
|
|
174
185
|
test('should handle concurrent requests efficiently', async () => {
|
|
175
186
|
const concurrentRequests = 50;
|
|
176
|
-
const
|
|
177
|
-
|
|
187
|
+
const samples = await Promise.all(Array.from({ length: concurrentRequests }, async () => {
|
|
188
|
+
const start = performance.now();
|
|
189
|
+
const response = await fetch(`${baseURL}/users`, {
|
|
178
190
|
headers: { 'Authorization': `Bearer ${authToken}` }
|
|
179
|
-
})
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
expect(allSuccessful).toBe(true);
|
|
190
|
-
expect(avgResponseTime).toBeLessThan(500);
|
|
191
|
+
});
|
|
192
|
+
await response.arrayBuffer();
|
|
193
|
+
return { status: response.status, durationMs: performance.now() - start };
|
|
194
|
+
}));
|
|
195
|
+
|
|
196
|
+
expect(samples.every(sample => sample.status === 200)).toBe(true);
|
|
197
|
+
const averageLatency = samples.reduce((sum, sample) => sum + sample.durationMs, 0)
|
|
198
|
+
/ samples.length;
|
|
199
|
+
expect(averageLatency).toBeLessThan(500);
|
|
200
|
+
// 用整批耗时除以并发数衡量的是吞吐量,不是单个请求的延迟。
|
|
191
201
|
});
|
|
192
202
|
});
|
|
193
203
|
});
|