@jayyuen66/dsh-dir-prep-organize 0.1.5 → 0.1.7

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.
Files changed (86) hide show
  1. package/CHANGELOG.md +146 -0
  2. package/LICENSE +1 -1
  3. package/README.md +25 -21
  4. package/README.zh-CN.md +25 -21
  5. package/THIRD_PARTY_NOTICES.md +3 -1
  6. package/agents/academic/academic-statistician.md +143 -0
  7. package/agents/design/design-inclusive-visuals-specialist.md +4 -3
  8. package/agents/design/design-ui-designer.md +6 -3
  9. package/agents/design/design-ux-architect.md +20 -7
  10. package/agents/design/design-whimsy-injector.md +23 -1
  11. package/agents/engineering/engineering-autonomous-optimization-architect.md +31 -22
  12. package/agents/engineering/engineering-backend-architect.md +43 -54
  13. package/agents/engineering/engineering-data-engineer.md +21 -6
  14. package/agents/engineering/engineering-database-optimizer.md +22 -10
  15. package/agents/engineering/engineering-devops-automator.md +12 -3
  16. package/agents/engineering/engineering-email-intelligence-engineer.md +41 -4
  17. package/agents/engineering/engineering-embedded-firmware-engineer.md +27 -5
  18. package/agents/engineering/engineering-feishu-integration-developer.md +10 -2
  19. package/agents/engineering/engineering-frontend-developer.md +24 -18
  20. package/agents/engineering/engineering-git-workflow-master.md +16 -4
  21. package/agents/engineering/engineering-incident-response-commander.md +3 -3
  22. package/agents/engineering/engineering-prompt-engineer.md +7 -2
  23. package/agents/engineering/engineering-rapid-prototyper.md +7 -3
  24. package/agents/engineering/engineering-security-engineer.md +2 -0
  25. package/agents/engineering/engineering-solidity-smart-contract-engineer.md +1 -1
  26. package/agents/engineering/engineering-technical-writer.md +4 -4
  27. package/agents/engineering/engineering-threat-detection-engineer.md +2 -0
  28. package/agents/engineering/engineering-voice-ai-integration-engineer.md +39 -16
  29. package/agents/engineering/engineering-wechat-mini-program-developer.md +7 -2
  30. package/agents/game-development/blender/blender-addon-engineer.md +12 -3
  31. package/agents/game-development/economy-designer.md +155 -0
  32. package/agents/game-development/godot/godot-gameplay-scripter.md +4 -0
  33. package/agents/game-development/godot/godot-multiplayer-engineer.md +6 -2
  34. package/agents/game-development/godot/godot-shader-developer.md +4 -3
  35. package/agents/game-development/roblox-studio/roblox-experience-designer.md +7 -6
  36. package/agents/game-development/roblox-studio/roblox-systems-scripter.md +7 -0
  37. package/agents/game-development/technical-artist.md +4 -0
  38. package/agents/game-development/unity/unity-multiplayer-engineer.md +67 -0
  39. package/agents/game-development/unreal-engine/unreal-multiplayer-architect.md +82 -31
  40. package/agents/game-development/unreal-engine/unreal-systems-engineer.md +13 -1
  41. package/agents/marketing/marketing-agentic-search-optimizer.md +50 -87
  42. package/agents/marketing/marketing-carousel-growth-engine.md +49 -35
  43. package/agents/marketing/marketing-private-domain-operator.md +2 -2
  44. package/agents/marketing/marketing-seo-specialist.md +22 -0
  45. package/agents/product/product-behavioral-nudge-engine.md +3 -0
  46. package/agents/project-management/project-management-jira-workflow-steward.md +5 -2
  47. package/agents/security/security-appsec-engineer.md +75 -43
  48. package/agents/security/security-threat-detection-engineer.md +6 -0
  49. package/agents/security/security-threat-intelligence-analyst.md +32 -15
  50. package/agents/specialized/accounts-payable-agent.md +39 -45
  51. package/agents/specialized/grant-writer.md +2 -2
  52. package/agents/specialized/healthcare-aging-parent-care-companion.md +396 -0
  53. package/agents/specialized/identity-graph-operator.md +24 -3
  54. package/agents/specialized/lsp-index-engineer.md +17 -15
  55. package/agents/specialized/recruitment-specialist.md +17 -11
  56. package/agents/specialized/specialized-developer-advocate.md +4 -4
  57. package/agents/specialized/specialized-fedramp-rmf-compliance.md +379 -0
  58. package/agents/specialized/specialized-focus-music-architect.md +176 -0
  59. package/agents/specialized/specialized-french-consulting-market.md +17 -15
  60. package/agents/specialized/specialized-model-qa.md +78 -34
  61. package/agents/specialized/specialized-salesforce-architect.md +17 -15
  62. package/agents/specialized/specialized-workflow-architect.md +2 -2
  63. package/agents/supply-chain/supply-chain-strategist.md +12 -3
  64. package/agents/support/support-analytics-reporter.md +48 -30
  65. package/agents/support/support-finance-tracker.md +36 -18
  66. package/agents/support/support-infrastructure-maintainer.md +2 -2
  67. package/agents/support/support-support-responder.md +43 -26
  68. package/agents/testing/testing-api-tester.md +37 -27
  69. package/agents/testing/testing-performance-benchmarker.md +82 -47
  70. package/agents/testing/testing-test-results-analyzer.md +37 -18
  71. package/agents/testing/testing-tool-evaluator.md +30 -10
  72. package/client.js +470 -287
  73. package/cordis.patch.yml +4 -23
  74. package/docs/DETAIL.md +26 -0
  75. package/docs/DETAIL.zh.md +26 -0
  76. package/host.js +84 -25
  77. package/locale/en.json +7 -0
  78. package/locale/zh.json +7 -0
  79. package/package.json +61 -52
  80. package/templates.data.mjs +9 -10
  81. package/types/host.d.ts +36 -4
  82. package/types/src/client-entry.d.ts +2 -3
  83. package/types/src/host-messages.d.ts +2 -0
  84. package/types/src/input-writeback.d.ts +32 -0
  85. package/types/src/remote.d.ts +7 -1
  86. package/types/src/ui-messages.d.ts +19 -6
@@ -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 >= DATE_SUB(CURRENT_DATE(), INTERVAL 12 MONTH)
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) * 100 as revenue_growth_rate
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': 'count', # 消费频率(Frequency)
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
- # 创建 RFM 评分
118
- rfm['r_score'] = pd.qcut(rfm['recency'], 5, labels=[5,4,3,2,1])
119
- rfm['f_score'] = pd.qcut(rfm['frequency'].rank(method='first'), 5, labels=[1,2,3,4,5])
120
- rfm['m_score'] = pd.qcut(rfm['monetary'], 5, labels=[1,2,3,4,5])
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['rfm_score'] in ['155', '154', '144', '214', '215', '115', '114']:
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
- customer_id,
170
- channel,
171
- campaign,
172
- touchpoint_date,
173
- conversion_date,
174
- revenue,
175
- ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY touchpoint_date) as touch_sequence,
176
- COUNT(*) OVER (PARTITION BY customer_id) as total_touches
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 touch_sequence = 1 AND total_touches = 1 THEN 1.0 -- 单触点
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 customer_id) as attributed_conversions,
196
- SUM(revenue * attribution_weight) / COUNT(DISTINCT customer_id) as revenue_per_conversion
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) * 100 as roi_percentage,
209
- SUM(attributed_revenue) / SUM(spend) as revenue_multiple,
210
- COUNT(conversions) as total_conversions,
211
- SUM(spend) / COUNT(conversions) as cost_per_conversion
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 >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
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 * 100 as variance_percentage
72
+ (actual_amount - budget_amount) * 100.0 / NULLIF(budget_amount, 0) as variance_percentage
73
73
  FROM financial_data
74
- WHERE fiscal_year = YEAR(CURRENT_DATE())
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
- AVG(variance_percentage) as avg_variance_pct
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
- avg_variance_pct,
94
+ variance_pct,
94
95
  CASE
95
- WHEN ABS(avg_variance_pct) <= 5 THEN 'On Track' -- 在轨
96
- WHEN avg_variance_pct > 5 THEN 'Over Budget' -- 超预算
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, timedelta
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
- forecast = pd.DataFrame()
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 = datetime.now() + timedelta(days=30*i)
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
- forecast = forecast.append({
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': self.current_cash + forecast['net_cash_flow'].sum() if len(forecast) > 0 else self.current_cash + net_flow, # 累计现金
150
- 'confidence_interval_low': net_flow * 0.85, # 置信区间下限
151
- 'confidence_interval_high': net_flow * 1.15 # 置信区间上限
152
- }, ignore_index=True)
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 forecast
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
- irr = fsolve(npv_function, 0.1)[0]
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
- trends = {}
187
-
188
- # 工单量趋势
189
- daily_volume = self.data.groupby(self.data['created_date'].dt.date).size()
190
- trends['volume_trend'] = 'increasing' if daily_volume.iloc[-7:].mean() > daily_volume.iloc[-14:-7].mean() else 'decreasing'
191
-
192
- # 常见问题分类
193
- issue_frequency = self.data['issue_category'].value_counts()
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'] < 80:
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'] >= datetime.now() - timedelta(days=30)
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'] >= datetime.now() - timedelta(days=7))
274
+ (self.data['created_date'] >= now - timedelta(days=7))
259
275
  ]['customer_id'].unique()
260
276
 
261
- # 超过 SLA 的未解决工单客户
277
+ # 状态已知为未解决、且已超过 SLA 的工单客户
262
278
  overdue_tickets = self.data[
279
+ self.data['status'].notna() &
263
280
  (self.data['status'] != 'resolved') &
264
- (self.data['created_date'] <= datetime.now() - timedelta(hours=48))
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
- // 包含安全和性能的高级 API 测试自动化
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
- let baseURL = process.env.API_BASE_URL;
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: 'secure_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 ${authToken}` }
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 requests = Array(concurrentRequests).fill(null).map(() =>
177
- fetch(`${baseURL}/users`, {
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
- const startTime = performance.now();
183
- const responses = await Promise.all(requests);
184
- const endTime = performance.now();
185
-
186
- const allSuccessful = responses.every(r => r.status === 200);
187
- const avgResponseTime = (endTime - startTime) / concurrentRequests;
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
  });