Browse Source

fix(recipe): 去掉生成兜底,失败时显式报错便于定位

产品决策:不再静默降级产出营养餐/营养汤假菜单,生成失败直接提示用户。

- 后端 generateRecommendation:AI 空结果/结构不完整 → IllegalArgumentException
  (Controller 已映射 Result.badRequest,message 传前端)
- 前端 generateRecipe catch:显示后端 message 而非固定『生成失败』
- 契约测试 RecipeNoFallback.contract.spec.js:主链路无 buildFallbackMenu、
  明确 throw、前端显示 message
Xiaogang Liao 58 minutes ago
parent
commit
05ded77a1e

+ 5 - 12
cfc-backend/src/main/java/com/etotem/cfc/service/DietRecommendationService.java

@@ -234,24 +234,17 @@ public class DietRecommendationService {
             menuJson = aiGateway.generateMenu(selectedFoodsJson, participantsJson, dateStr, dishCount);
         }
 
-        // 4. AI 失败 / 熔断 / 超时 → 规则降级(同菜数规则造 D(N)+1 道)
+        // 4. 不再做规则兜底:AI 失败/空结果/非法结构一律显式报错,便于定位问题。
+        //    (产品决策 2026-11-28:宁可生成失败提示给用户,也不静默产出"营养餐/营养汤"假菜单)
         List<String> ingredientNames = availableIngredientNames(familyId, date);
         if (menuJson == null || menuJson.trim().isEmpty() || "{}".equals(menuJson.trim())) {
-            menuJson = buildFallbackMenu(familyId, date, participantCount, ingredientNames, personalFoodNames, variationSeed);
+            throw new IllegalArgumentException("食谱生成失败:AI 未返回菜单(服务不可用或超时),请稍后重试");
         }
 
-        // 5. 归一化(唯一硬保证点)+ 聚合营养
+        // 5. 归一化 + 结构校验(不再降级)
         Map<String, Object> normalized = normalizeMenu(menuJson, participantCount, ingredientNames);
-        // CR-3 / AC-24·26·27:LangGraph 在 LLM 无 JSON / 异常时返回 HTTP 200 的 {"meals": []},
-        // 非法 JSON 也会被 normalizeMenu 的异常兜底吞掉,二者都产出空菜单;
-        // 步骤 4 只判 null / 空串 / "{}" 会漏掉这两种形态。
-        // 归一化后再校验一次结构可用性,不足则复用规则降级(绝不重新调用 aiGateway,禁止整份重试 AI)。
-        // 于是 AI 正常 / 熔断降级 / 空·非法输出 三条路径最终落库均为 D(N) 菜 + 1 汤;
-        // regenerate 复用本方法(L283),同样受保护。
         if (!hasUsableLunchDinner(normalized)) {
-            normalized = normalizeMenu(
-                    buildFallbackMenu(familyId, date, participantCount, ingredientNames, personalFoodNames, variationSeed),
-                    participantCount, ingredientNames);
+            throw new IllegalArgumentException("食谱生成失败:AI 返回的菜单结构不完整(午餐/晚餐缺菜),请稍后重试");
         }
         String normalizedMenuJson = safeWrite(normalized);
         Map<String, Object> nutritionSummary = aggregateNutrition(normalized);

+ 32 - 0
cfc-frontend/__tests__/RecipeNoFallback.contract.spec.js

@@ -0,0 +1,32 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:recipe.noFallback(生成失败必须明确报错,不再静默降级为规则兜底菜单)
+const SVC = resolve(__dirname, '../../../cfc-backend/src/main/java/com/etotem/cfc/service/DietRecommendationService.java')
+const VUE = resolve(__dirname, '../../pages/diet/recommendation.vue')
+const svc = readFileSync(SVC, 'utf8')
+const vue = readFileSync(VUE, 'utf8')
+
+describe('食谱生成失败显式报错(无兜底)', () => {
+  test('生成主链路不再调用 buildFallbackMenu', () => {
+    // 主链路(generateRecommendation 方法体内)不得出现兜底调用
+    const start = svc.indexOf('public Map<String, Object> generateRecommendation')
+    const end = svc.indexOf('public Map<String, Object> regenerateRecommendation')
+    expect(start).toBeGreaterThan(-1)
+    expect(end).toBeGreaterThan(start)
+    const body = svc.slice(start, end)
+    expect(body).not.toMatch(/buildFallbackMenu/)
+  })
+
+  test('AI 空结果 / 结构不完整时抛出明确错误', () => {
+    expect(svc).toMatch(/throw new IllegalArgumentException\([^\n]*生成失败/)
+    expect(svc).toMatch(/throw new IllegalArgumentException\([^\n]*AI/)
+  })
+
+  test('前端生成失败 toast 显示后端原因而非固定文案', () => {
+    const i = vue.indexOf('generateRecipe: function')
+    expect(i).toBeGreaterThan(-1)
+    const body = vue.slice(i, i + 1600)
+    expect(body).toMatch(/var reason[^\n]*message/)
+  })
+})

+ 4 - 2
cfc-frontend/pages/diet/recommendation.vue

@@ -688,10 +688,12 @@ export default {
         } else {
           uni.showToast({ title: (res && res.message) || '生成失败', icon: 'none' })
         }
-      }).catch(function() {
+      }).catch(function(err) {
         self.loading = false
         uni.hideLoading()
-        uni.showToast({ title: '生成失败', icon: 'none' })
+        // 展示后端明确原因(request 封装在 code!=200 时 reject(res.data)),便于定位生成失败
+        var reason = (err && err.message) || ''
+        uni.showToast({ title: reason ? ('生成失败:' + reason) : '生成失败', icon: 'none' })
       })
     },
     // 打开共餐人多选弹层(默认勾选全部家庭成员)