前端(uni-app · Vue3)
- 设计系统:uni.scss 品牌令牌(花红 #E8604C / 蜜橙 #F5A65B / 暖米白 #FFF9F5),
App.vue 全局原子类(卡片/按钮/胶囊/单元格/空态/进度)
- 页面:登录、首页(聚合)、周期(花瓣日历+当日记录+预测+概览)、情绪(记录+趋势+日记+疗愈)、
我的(资料/会员/隐私/提醒)、健康报告、会员套餐、内容详情
- 组件:hq-tabbar(自定义底栏)、bloom-calendar(阶段日历)
- 基础层:utils/{config,request,store,api,date}.js(统一 token、401 处理、接口集中定义)
后端(FastAdmin / ThinkPHP 5.0)
- 新增 api 控制器:Home / Cycle / Mood / Content / Member / Setting,User 增补 detail、updateprofile
- 新增服务层:CycleService(四阶段计算、预测、月历、汇总)、MemberService(权益判定)
- 新增表:fa_cycle / fa_cycle_log / fa_symptom_tag / fa_mood_log / fa_content /
fa_content_category / fa_member_plan / fa_member_order / fa_user_setting
- 初始化数据:20 个症状标签、28 条内容(心语/科普/知识/食谱/运动/睡眠/痛经/冥想)、3 档会员
验证(全部通过)
- 接口全链路 48 项断言(登录→周期→首页→情绪→内容→会员→设置→资料)
- 前后端契约静态校验 24 个接口 0 偏差
- Vue SFC 编译 11/11、SCSS 编译 10/10
- 验证脚本见 scripts/verify/,报告见 docs/04-前端设计系统与联调验证.md
170 行
7.1 KiB
Python
170 行
7.1 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""花期 APP · 前后端契约静态校验(无需打包即可发现接口/路由/事件类错误)"""
|
||
import os
|
||
import re
|
||
import sys
|
||
import json
|
||
|
||
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))
|
||
SERVER_API = os.path.join(ROOT, 'server/application/api/controller')
|
||
|
||
issues = []
|
||
notes = []
|
||
|
||
|
||
def add(msg):
|
||
issues.append(msg)
|
||
|
||
|
||
# ---------------- 1. 解析前端 api.js ----------------
|
||
api_src = open(os.path.join(ROOT, 'utils/api.js'), encoding='utf-8').read()
|
||
pattern = re.compile(r"(\w+):\s*(?:\([^)]*\))?\s*=>\s*request\('(/api/[\w/]+)'(?:\s*,\s*(\{[^}]*\}))?")
|
||
endpoints = []
|
||
for m in pattern.finditer(api_src):
|
||
name, path, opts = m.group(1), m.group(2), m.group(3) or ''
|
||
method = 'POST' if "'POST'" in opts.replace('"', "'") else 'GET'
|
||
endpoints.append({'name': name, 'path': path, 'method': method})
|
||
|
||
print(f"[1] 前端 api.js 定义 {len(endpoints)} 个接口")
|
||
|
||
# ---------------- 2. 校验后端控制器方法存在 ----------------
|
||
php_cache = {}
|
||
for ep in endpoints:
|
||
parts = ep['path'].strip('/').split('/') # api / controller / action
|
||
controller, action = parts[1].capitalize(), parts[2]
|
||
f = os.path.join(SERVER_API, controller + '.php')
|
||
if f not in php_cache:
|
||
php_cache[f] = open(f, encoding='utf-8').read() if os.path.exists(f) else None
|
||
src = php_cache[f]
|
||
if src is None:
|
||
add(f"接口 {ep['name']} -> {ep['path']}:后端缺少控制器 {controller}.php")
|
||
continue
|
||
if not re.search(r'function\s+' + action + r'\s*\(', src):
|
||
add(f"接口 {ep['name']} -> {ep['path']}:{controller}.php 缺少方法 {action}()")
|
||
|
||
print(f"[2] 后端控制器映射校验完成(检查 {len(php_cache)} 个控制器文件)")
|
||
|
||
# ---------------- 3. 页面里调用的 api.xxx 是否都已定义 ----------------
|
||
defined = {ep['name'] for ep in endpoints}
|
||
vue_files = []
|
||
for dirpath, _, files in os.walk(ROOT):
|
||
if 'node_modules' in dirpath or '/server' in dirpath or '/.git' in dirpath:
|
||
continue
|
||
for fn in files:
|
||
if fn.endswith('.vue'):
|
||
vue_files.append(os.path.join(dirpath, fn))
|
||
|
||
used = {}
|
||
for f in vue_files:
|
||
src = open(f, encoding='utf-8').read()
|
||
for m in re.finditer(r'\bapi\.(\w+)\s*\(', src):
|
||
used.setdefault(m.group(1), set()).add(os.path.relpath(f, ROOT))
|
||
|
||
for name, files in sorted(used.items()):
|
||
if name not in defined:
|
||
add(f"前端调用了未定义的接口 api.{name}()(使用位置:{', '.join(sorted(files))})")
|
||
|
||
print(f"[3] 页面接口调用校验完成({len(used)} 个被调用接口,覆盖 {len(vue_files)} 个 .vue)")
|
||
|
||
# ---------------- 4. pages.json 路由与文件存在性 ----------------
|
||
pages_cfg = json.load(open(os.path.join(ROOT, 'pages.json'), encoding='utf-8'))
|
||
for page in pages_cfg.get('pages', []):
|
||
p = os.path.join(ROOT, page['path'] + '.vue')
|
||
if not os.path.exists(p):
|
||
add(f"pages.json 声明的页面不存在:{page['path']}.vue")
|
||
print(f"[4] 路由校验完成({len(pages_cfg.get('pages', []))} 个页面)")
|
||
|
||
# ---------------- 5. 页面跳转目标是否在 pages.json 中 ----------------
|
||
declared = {'/' + page['path'] for page in pages_cfg.get('pages', [])}
|
||
for f in vue_files:
|
||
src = open(f, encoding='utf-8').read()
|
||
for m in re.finditer(r"url:\s*'(/pages/[\w/]+)(?:\?[^']*)?'", src):
|
||
target = m.group(1)
|
||
if target not in declared:
|
||
add(f"{os.path.relpath(f, ROOT)}:跳转到未注册页面 {target}")
|
||
|
||
# ---------------- 6. 组件引用与文件存在性 ----------------
|
||
for f in vue_files:
|
||
src = open(f, encoding='utf-8').read()
|
||
for m in re.finditer(r"from '(@/[\w\-/]+\.vue)'", src):
|
||
rel = m.group(1).replace('@/', '')
|
||
if not os.path.exists(os.path.join(ROOT, rel)):
|
||
add(f"{os.path.relpath(f, ROOT)}:组件文件不存在 {rel}")
|
||
# 模板中使用的组件是否已注册
|
||
script = src.split('</template>')[0]
|
||
regs = set(re.findall(r'components:\s*\{([^}]*)\}', src))
|
||
registered = set()
|
||
for block in regs:
|
||
registered |= set(re.findall(r'(\w+)\s*:', block))
|
||
# 支持 ES6 简写注册 components: { hqTabbar }
|
||
registered |= {t.strip() for t in block.split(',') if re.fullmatch(r'\s*\w+\s*', t)}
|
||
def camelize(name):
|
||
parts = name.split('-')
|
||
return parts[0] + ''.join(p.capitalize() for p in parts[1:])
|
||
|
||
registered_camel = {camelize(r) for r in registered}
|
||
for tag in set(re.findall(r'<(hq-[a-z\-]+|bloom-calendar)', script)):
|
||
if camelize(tag) not in registered_camel:
|
||
add(f"{os.path.relpath(f, ROOT)}:模板使用 <{tag}> 但未在 components 中注册")
|
||
|
||
# ---------------- 7. 模板事件处理函数是否在 methods 中定义 ----------------
|
||
HANDLER_RE = re.compile(r'@(?:tap|change|confirm|select|input|submit)="(\w+)"')
|
||
for f in vue_files:
|
||
src = open(f, encoding='utf-8').read()
|
||
if '<script>' not in src:
|
||
continue
|
||
template = src.split('<template>', 1)[-1].split('</template>', 1)[0]
|
||
script = src.split('<script>', 1)[-1].split('</script>', 1)[0]
|
||
for h in set(HANDLER_RE.findall(template)):
|
||
if not re.search(r'\b' + h + r'\s*\(', script):
|
||
add(f"{os.path.relpath(f, ROOT)}:模板绑定的处理函数 {h}() 未定义")
|
||
|
||
# ---------------- 8. SFC 结构完整性 ----------------
|
||
for f in vue_files:
|
||
src = open(f, encoding='utf-8').read()
|
||
blocks = ('template', 'script')
|
||
for block in blocks:
|
||
c_open = src.count('<' + block + '>')
|
||
c_close = src.count('</' + block + '>')
|
||
# App.vue 允许没有 template(uni-app 全局样式/生命周期文件)
|
||
if os.path.basename(f) == 'App.vue' and block == 'template':
|
||
if c_open != c_close:
|
||
add(f"{os.path.relpath(f, ROOT)}:<template> 块异常({c_open}/{c_close})")
|
||
continue
|
||
if c_open != 1 or c_close != 1:
|
||
add(f"{os.path.relpath(f, ROOT)}:<{block}> 块异常({c_open}/{c_close})")
|
||
# 标签配对(忽略自闭合与 void 标签)
|
||
stack = []
|
||
void_tags = {'input', 'image', 'img', 'switch', 'br', 'hr'}
|
||
for m in re.finditer(r'<(/?)([a-zA-Z][\w\-]*)([^>]*?)(/?)>', src):
|
||
closing, tag, _, selfclose = m.group(1), m.group(2), m.group(3), m.group(4)
|
||
if tag in ('template', 'script', 'style'):
|
||
continue
|
||
if selfclose or tag in void_tags:
|
||
continue
|
||
if closing:
|
||
if stack and stack[-1] == tag:
|
||
stack.pop()
|
||
elif tag in stack:
|
||
while stack and stack.pop() != tag:
|
||
pass
|
||
add(f"{os.path.relpath(f, ROOT)}:标签闭合顺序异常 </{tag}>")
|
||
else:
|
||
add(f"{os.path.relpath(f, ROOT)}:多余的闭合标签 </{tag}>")
|
||
else:
|
||
stack.append(tag)
|
||
if stack:
|
||
add(f"{os.path.relpath(f, ROOT)}:未闭合标签 {stack[-5:]}")
|
||
|
||
print(f"[5] 跳转/组件/事件/SFC 结构校验完成")
|
||
|
||
# ---------------- 输出 ----------------
|
||
print("=" * 66)
|
||
if issues:
|
||
print(f"发现 {len(issues)} 个问题:")
|
||
for i in issues:
|
||
print(" ❌ " + i)
|
||
sys.exit(1)
|
||
print("✅ 前后端契约静态校验全部通过")
|