Compare commits

...

2 Commits

Author SHA1 Message Date
wuqi d4b94d335d feat(launch_confirm): 新增启动确认样本列表内部接口(供 pricebot distill 回读)
补齐「启动确认窗自进化闭环」里 app-server 这一侧的读路径:pricebot 的 launch_confirm
LLM 兜底成功样本会 server→server 落到 app-server 的 launch_confirm_sample 表;本提交
新增「样本列表查询」内部接口, 供 pricebot 的 scripts/distill_launch_confirm.py 回读这些
样本、按「宿主包 × 文案变体」聚合沉淀出候选规则。

- app/api/internal/launch_confirm.py: 新增样本列表内部接口(server→server, 不走用户 JWT)
- app/repositories/launch_confirm_sample.py: 样本列表查询
- app/schemas/launch_confirm_sample.py: 列表响应 schema

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 21:36:26 +08:00
xiebing 2ed62c789f feat(h5): 我的页改 H5(mine 页 + shared bridge/api) (#89)
- h5/mine/index.html: 个人中心「我的页」H5 实现
- h5/shared/bridge.js, api.js: H5↔客户端桥与 API 封装(mine 依赖)

Reviewed-on: #89
Co-authored-by: xiebing <xiebing@wonderable.ai>
Co-committed-by: xiebing <xiebing@wonderable.ai>
2026-06-28 14:16:32 +08:00
6 changed files with 8064 additions and 1 deletions
+33
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import hmac
import logging
from datetime import datetime, timedelta, timezone
from typing import Annotated
from fastapi import APIRouter, Header, HTTPException, status
@@ -21,6 +22,7 @@ from app.repositories import launch_confirm_sample as repo
from app.schemas.launch_confirm_sample import (
LaunchConfirmSampleIn,
LaunchConfirmSampleOut,
LaunchConfirmSampleRow,
)
logger = logging.getLogger("shagua.internal.launch_confirm")
@@ -61,3 +63,34 @@ def report_launch_confirm_sample(
payload.exec_success, payload.trace_id,
)
return LaunchConfirmSampleOut(id=sid)
@router.get(
"/launch-confirm-samples",
response_model=list[LaunchConfirmSampleRow],
summary="启动确认窗兜底样本列表(沉淀脚本 distill 读; server→server, 不走 JWT)",
)
def list_launch_confirm_samples(
db: DbSession,
x_internal_secret: Annotated[str | None, Header()] = None,
exec_success: bool | None = None,
host_package: str | None = None,
since_days: int | None = None,
limit: int = 1000,
) -> list[LaunchConfirmSampleRow]:
"""读样本供 pricebot 的 distill_launch_confirm.py 聚合沉淀回 PROFILES。
与上报端点同一把共享密钥;exec_success/host_package/since_days 均可选,limit 默认 1000。
"""
_check_secret(x_internal_secret)
since = None
if since_days and since_days > 0:
since = datetime.now(timezone.utc) - timedelta(days=since_days)
rows = repo.list_samples(
db,
exec_success=exec_success,
host_package=host_package,
since=since,
limit=limit,
)
return [LaunchConfirmSampleRow.model_validate(r) for r in rows]
+26
View File
@@ -2,8 +2,10 @@
from __future__ import annotations
import logging
from datetime import datetime
from typing import Optional
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.models.launch_confirm_sample import LaunchConfirmSample
@@ -33,3 +35,27 @@ def insert_sample(db: Session, payload: LaunchConfirmSampleIn) -> int:
db.commit()
db.refresh(row)
return row.id
def list_samples(
db: Session,
*,
exec_success: Optional[bool] = None,
host_package: Optional[str] = None,
since: Optional[datetime] = None,
limit: int = 1000,
) -> list[LaunchConfirmSample]:
"""按条件查样本(pricebot 的 distill_launch_confirm.py 沉淀工具读)。created_at 升序。
过滤项都可空:exec_success(只看放行成功的)/ host_package(只看某宿主包)/
since(>= created_at)。limit 兜底防一次拉爆全表。
"""
stmt = select(LaunchConfirmSample)
if exec_success is not None:
stmt = stmt.where(LaunchConfirmSample.exec_success == exec_success)
if host_package:
stmt = stmt.where(LaunchConfirmSample.host_package == host_package)
if since is not None:
stmt = stmt.where(LaunchConfirmSample.created_at >= since)
stmt = stmt.order_by(LaunchConfirmSample.created_at.asc()).limit(limit)
return list(db.execute(stmt).scalars().all())
+20 -1
View File
@@ -1,7 +1,9 @@
"""启动确认窗兜底样本的内部上报模型(pricebot → app-server)。"""
from __future__ import annotations
from pydantic import BaseModel
from datetime import datetime
from pydantic import BaseModel, ConfigDict
class LaunchConfirmSampleIn(BaseModel):
@@ -24,3 +26,20 @@ class LaunchConfirmSampleOut(BaseModel):
"""落库结果。"""
id: int
class LaunchConfirmSampleRow(BaseModel):
"""单条样本(列表读出;沉淀脚本 distill 用,payload 原样带出)。"""
model_config = ConfigDict(from_attributes=True)
id: int
created_at: datetime
trace_id: str | None = None
device_id: str | None = None
host_package: str | None = None
target_app: str | None = None
system_locale: str | None = None
exec_success: bool = False
dialog_title: str | None = None
payload: dict | None = None
+7771
View File
File diff suppressed because it is too large Load Diff
+52
View File
@@ -0,0 +1,52 @@
/**
* SGApi —— H5 调 app-server 后端的薄封装。
*
* 同源:H5 由 app-server 的 /media/h5/ 托管,后端在 /api/v1,同 host:port → 用相对路径、无 CORS。
* 鉴权:JWT Bearer。token 经 SGBridge.getToken() 从原生取(原生持登录态);浏览器调试走 bridge 的 mock token。
* 401:交原生拉登录(requestLogin)兜底,本次请求按失败 reject;正式的 refresh 重试策略阶段2 再补。
*
* 依赖 shared/bridge.js 先加载(取 token)。
*/
(function (global) {
'use strict';
var BASE = '/api/v1';
function authHeaders() {
var t = (global.SGBridge && global.SGBridge.getToken()) || '';
var h = { 'Content-Type': 'application/json' };
if (t) h['Authorization'] = 'Bearer ' + t;
return h;
}
function handle(res) {
if (res.status === 401) {
// 未授权:拉原生登录(异步),本次请求按失败处理,调用方自行决定是否重试
if (global.SGBridge) global.SGBridge.requestLogin();
return Promise.reject(new Error('unauthorized'));
}
if (!res.ok) {
return res.text().then(function (t) {
return Promise.reject(new Error('http ' + res.status + ' ' + t));
});
}
// 204 / 空体兜底
return res.text().then(function (t) { return t ? JSON.parse(t) : null; });
}
/** GET /api/v1<path>。path 以 / 开头,如 '/savings/battle'。 */
function apiGet(path) {
return fetch(BASE + path, { method: 'GET', headers: authHeaders() }).then(handle);
}
/** POST /api/v1<path>body 自动 JSON 序列化。 */
function apiPost(path, body) {
return fetch(BASE + path, {
method: 'POST',
headers: authHeaders(),
body: JSON.stringify(body || {}),
}).then(handle);
}
global.SGApi = { base: BASE, get: apiGet, post: apiPost };
})(window);
+162
View File
@@ -0,0 +1,162 @@
/**
* SGBridge —— 傻瓜比价 H5 ↔ Android 原生 的桥。
*
* 背景:四个主 tab(首页/福利/记录/我的)由原生 Compose 改造为 WebView 加载本工程 H5。
* H5 只负责"画 + 取后端数据";凡需要原生能力(登录态 / 跳转 / 跳外卖 App / 比价领券 /
* 权限 / 定位 / Toast / 激励视频),一律经本桥调用原生。
*
* 协议两个方向:
* ① H5 → 原生:Android 端 WebView.addJavascriptInterface(obj, "SGBridgeNative")。
* obj 方法都是【同步】:查询类返回 String(JSON 或纯串),动作类无返回。
* ② 原生 → H5:原生执行 evaluateJavascript("window.SGBridge._emit('<event>', '<json>')")。
* 事件:onAuthChange(登录态变) / onBalanceChange(余额变) / onSigninChange(签到态变) / onResume(回前台刷新)。
*
* 离线兜底:浏览器里(无 SGBridgeNative)走 MOCK,便于不装 App 直接在本地 server 调样式 / 渲染。
* 与原生实现对应:见 shaguabijia-app-android 的 SGBridge.kt(方法名逐个对齐本文件)。
*/
(function (global) {
'use strict';
var native = global.SGBridgeNative || null;
var hasNative = !!native;
// ---- 离线 MOCK(仅无原生时生效,便于浏览器调试渲染;真机一律走 native) ----
var MOCK = {
authState: { loggedIn: true, userId: 1, nickname: '冰', avatarUrl: '', phone: '188****8888' },
token: 'mock-token-for-browser-debug',
deviceId: 'browser-debug-device',
appVersion: '0.0.0-debug',
};
function safeParse(s, fallback) {
try { return s ? JSON.parse(s) : fallback; } catch (e) { return fallback; }
}
// ====== 查询类(同步返回) ======
/** 当前登录态 + 用户基本信息 → {loggedIn, userId, nickname, avatarUrl, phone}。 */
function getAuthState() {
if (hasNative && native.getAuthState) return safeParse(native.getAuthState(), { loggedIn: false });
return MOCK.authState;
}
/** 后端鉴权用的 access token(空串=未登录)。原生持登录态,H5 调后端前取它拼 Bearer。 */
function getToken() {
if (hasNative && native.getToken) return native.getToken() || '';
return MOCK.token;
}
/** 设备唯一标识(心跳 / 领券状态查询等用)。 */
function getDeviceId() {
if (hasNative && native.getDeviceId) return native.getDeviceId() || '';
return MOCK.deviceId;
}
/** App 版本号。 */
function getAppVersion() {
if (hasNative && native.getAppVersion) return native.getAppVersion() || '';
return MOCK.appVersion;
}
/** 已安装的目标电商/外卖 App 包名数组(原生 InstalledApps 探测)。H5 选平台弹窗据此判真实装机态。 */
function getInstalledApps() {
if (hasNative && native.getInstalledApps) return safeParse(native.getInstalledApps(), []);
// MOCK(浏览器无原生):给主流已装,便于本地预览选平台弹窗正常显示"有"。
return ['com.sankuai.meituan', 'com.taobao.taobao', 'com.jingdong.app.mall', 'me.ele'];
}
/** 今日是否已领券(置灰「去领取」→「去查看」)。原生读 CompareButtonState(SP 按天);无桥默认 false。 */
function getCouponClaimedToday() {
if (hasNative && native.getCouponClaimedToday) return !!native.getCouponClaimedToday();
return false;
}
// ====== 动作类(无返回;异步结果走事件) ======
/** 跳原生页。route 取值对齐安卓 Routes(invite / settings / feedback / withdrawal / compareRecords / reportFlow / guideVideo / compareResult / coinHistory / cashHistory / welfareRules ...)。 */
function navigate(route) {
if (hasNative && native.navigate) native.navigate(route);
else console.log('[SGBridge mock] navigate →', route);
}
/** 拉起极光一键登录。结果异步经 onAuthChange 事件回来(不在此函数返回)。 */
function requestLogin() {
if (hasNative && native.requestLogin) native.requestLogin();
else console.log('[SGBridge mock] requestLogin');
}
/** 原生居中 Toast。 */
function toast(msg) {
if (hasNative && native.toast) native.toast(String(msg));
else console.log('[SGBridge mock] toast →', msg);
}
/** 跳美团/外卖 App(deeplink 优先;空则原生按包名启动,未装可跳应用商店)。 */
function openMeituan(deeplink) {
if (hasNative && native.openMeituan) native.openMeituan(deeplink || '');
else console.log('[SGBridge mock] openMeituan →', deeplink);
}
/** 触发 agent 比价流程(原生起无障碍引擎)。 */
function startCompare() {
if (hasNative && native.startCompare) native.startCompare();
else console.log('[SGBridge mock] startCompare');
}
/** 触发一键领券(原生先校验悬浮窗/无障碍权限,再起前台服务)。platforms: string[]。 */
function startCouponClaim(platforms) {
var json = JSON.stringify(platforms || []);
if (hasNative && native.startCouponClaim) native.startCouponClaim(json);
else console.log('[SGBridge mock] startCouponClaim →', json);
}
/** 按候选包名拉起对应平台 App。照原生 HomePicker 点击跳转:原生在该平台一组候选包里取首个可
* getLaunchIntentForPackage 的拉起(NEW_TASK|CLEAR_TASK 冷启到平台首页)。packages: string[](一个平台一组候选包,任一可拉即拉)。 */
function launchApp(packages) {
var json = JSON.stringify(packages || []);
if (hasNative && native.launchApp) native.launchApp(json);
else console.log('[SGBridge mock] launchApp →', json);
}
// ====== 原生 → H5 事件总线 ======
var listeners = {}; // event → [fn]
/** 订阅原生事件。返回取消订阅函数。 */
function on(event, fn) {
(listeners[event] || (listeners[event] = [])).push(fn);
return function off() {
listeners[event] = (listeners[event] || []).filter(function (f) { return f !== fn; });
};
}
/** 供原生回调:window.SGBridge._emit('onAuthChange', '{...}')。payload 可为 JSON 串或对象。 */
function _emit(event, payload) {
var data = typeof payload === 'string' ? safeParse(payload, payload) : payload;
(listeners[event] || []).forEach(function (fn) {
try { fn(data); } catch (e) { console.error('[SGBridge] listener error', event, e); }
});
}
global.SGBridge = {
hasNative: hasNative,
// 查询
getAuthState: getAuthState,
getToken: getToken,
getDeviceId: getDeviceId,
getAppVersion: getAppVersion,
getInstalledApps: getInstalledApps,
getCouponClaimedToday: getCouponClaimedToday,
// 动作
navigate: navigate,
requestLogin: requestLogin,
toast: toast,
openMeituan: openMeituan,
startCompare: startCompare,
startCouponClaim: startCouponClaim,
launchApp: launchApp,
// 事件
on: on,
_emit: _emit,
};
})(window);