26 Commits
Author SHA1 Message Date
Timi 9ccdbe593a v1.6.0 2026-11-20 13:18:12 +08:00
Timi aed42057da feat(core): ready to native bridge 2026-11-20 13:14:15 +08:00
Timi effc4d93cf fix(product): better layout on tablet 2026-11-19 17:56:23 +08:00
Timi 2ad5066b5d fix(product): single column layout on phone 2026-11-19 17:25:29 +08:00
Timi d22e80241e fix(product): hide save to system media for not apk env 2026-11-19 17:25:10 +08:00
Timi 7b68e7642f feat(product): detail popup for product stock calendar 2026-11-19 17:13:42 +08:00
Timi 69c80f4129 chore(order): better layout in tablet 2026-11-19 17:03:39 +08:00
Timi 65de3785dc chore(package): detail slot for add package config on tablet 2026-11-19 16:48:16 +08:00
Timi e54f1af252 chore(consumption): master-detail-page on tablet 2026-11-19 16:40:26 +08:00
Timi b92046448a style(setting): remove title 2026-11-19 16:24:19 +08:00
Timi b570a6b269 feat(recycle): update order recycle page 2026-11-19 16:11:46 +08:00
Timi f667655e92 fix(UI): submit wrap overflow pane 2026-11-18 17:39:22 +08:00
Timi f25574eb20 feat(event): customer photo for event record calendar 2026-11-18 17:34:59 +08:00
Timi 6e3801f441 style(system): app setting 2026-11-18 17:23:20 +08:00
Timi c70b35bb89 fix(UI): better message offset top 2026-11-18 17:18:53 +08:00
Timi aa48ebf4ad style(point): use time label component 2026-11-18 16:48:12 +08:00
Timi 754e61eb5d feat(point): point redemption in product stock list and detail 2026-11-18 16:41:23 +08:00
Timi e88374c377 fix(notify): update read status for tablet 2026-11-18 16:15:51 +08:00
Timi 052cd28318 style(UI): clip customer name for order list 2026-11-18 16:11:17 +08:00
Timi 6aa33e2eb1 chore(UI): better layout for fund record 2026-11-18 16:07:09 +08:00
Timi 60cadff951 feat(system): write to system media for tack photo 2026-11-18 14:08:47 +08:00
Timi 635192eae1 fix(system): photo rotate and reduce on browser-image-compression 2026-11-18 14:08:15 +08:00
Timi aeeb44d710 build: remove TWA 2026-11-18 11:39:22 +08:00
Timi 9ee957419f build: android:apk build prod release 2026-11-18 11:26:45 +08:00
Timi 43a64acc12 chore(system): unlimit update note 2026-11-18 10:51:48 +08:00
Timi 3ccb586015 ci(release): publish 失败不再静默
- curl 加 -f,4xx/5xx 直接中断,不再无条件打印 OK
- 再校验响应体的 fail/success,业务层异常同样中断
- 避免出现 tag 已创建、包却没上线的假成功
2026-11-18 00:39:15 +08:00
130 changed files with 9632 additions and 3588 deletions
+16 -2
View File
@@ -281,8 +281,22 @@ jobs:
API_TOKEN: ${{ secrets.TIMI_API_TOKEN }} API_TOKEN: ${{ secrets.TIMI_API_TOKEN }}
RELEASE_ID: ${{ steps.create.outputs.release_id }} RELEASE_ID: ${{ steps.create.outputs.release_id }}
run: | run: |
curl -sS -X POST "$API_BASE_URL/app/release/publish?releaseId=$RELEASE_ID&channelCode=stable" \ if [ -z "$RELEASE_ID" ]; then
-H "Token: $API_TOKEN" echo "FAIL: 缺少发布记录 ID"
exit 1
fi
# -f 让 4xx/5xx 直接失败;否则下面那句 OK 会照打,tag 也会照建
response=$(curl -sS -f -X POST "$API_BASE_URL/app/release/publish?releaseId=$RELEASE_ID&channelCode=stable" \
-H "Token: $API_TOKEN") || {
echo "FAIL: 发布接口调用失败"
exit 1
}
echo "响应:$response"
# 业务层异常仍可能是 200 + fail:true,这里再兜一层
if printf '%s' "$response" | grep -qE '"fail"[[:space:]]*:[[:space:]]*true|"success"[[:space:]]*:[[:space:]]*false'; then
echo "FAIL: 发布未生效,请检查后端日志"
exit 1
fi
echo "OK: 已发布到 stable" echo "OK: 已发布到 stable"
# 打 tag 的时机是「上线成功」而不是「PR 合并」:草稿发布和失败发布都不该留下版本标记。 # 打 tag 的时机是「上线成功」而不是「PR 合并」:草稿发布和失败发布都不该留下版本标记。
+1
View File
@@ -154,3 +154,4 @@ release-note.txt
# Android Studio 本地配置及发布构建产物 # Android Studio 本地配置及发布构建产物
/android/.idea/ /android/.idea/
/android/app/release/ /android/app/release/
/android/keystore.properties
+24
View File
@@ -19,6 +19,30 @@ CI 规则(.gitea/workflows/release.yml):
需要更正请发补丁版本 需要更正请发补丁版本
--> -->
## v1.6.0
### 新增
- App 端支持拍照、录视频时写入系统相册
- 积分兑换的库存流水可以跳转对应积分兑换单
- 登记事件记录日历显示客户照片
- 新增和优化回收物流水、订单回收物、客户回收物页面
- 库存日历的当日流水支持直接弹出查看详情
### 调整
- 更多页面适配平板横屏模式:积分、消费、套餐
- 现在积分兑换凭证会同步兑换产品出库记录
- 积分兑换的库存流水现在显示客户姓名而不是操作用户名
- 顶部弹出消息不再遮挡导航栏
### 修复
- 拍照照片压缩后可能出现只有 1/4 大小,其余留白,并且发生旋转
- 平板横屏下阅读站内通知时列表没有刷新已读状态
- App 端顶部弹出消息偏移不足,导致和状态栏重合
- 部分页面样式
## v1.5.0 ## v1.5.0
### 调整 ### 调整
+617
View File
@@ -0,0 +1,617 @@
# 原生能力预埋清单
> 适用范围:gao-customer-h5 的 Android 原生壳(Capacitor 8)
> 关联文档:`NATIVE_UPGRADE.md`(发壳流程)、`capacitor.config.ts`(插件配置)
## 这份文档解决什么
Capacitor 的原生能力集是**编译期固定**的:壳里没有的插件,热更包调不到。每加一个插件、每加一个权限,都必须重新发一次 APK。
本次升级(versionCode 3 → 4)的核心目的不是上线新功能,而是**把未来一到两年可能用到的原生能力一次性装进壳里**,此后业务迭代全部走热更。
因此有一条硬约束:
> **本次发壳后,Web 侧不得调用任何新能力**,直到业务真正需要。
> 在 `APP_MIN_VERSION_CODE` 抬到 4 之前,老壳用户必须能正常收到热更。
---
## 一、能力清单
全部能力收在单个插件 `NativeKit` 下,避免注册表膨胀。前端只需 `registerPlugin("NativeKit")`。
| 分组 | 方法 | 说明 |
|---|---|---|
| 协商 | `getInfo()` | 返回壳版本、WebView 内核、能力名数组 |
| 扫码 | `scan()` | 原生整页取景,QR / CODE_128 / CODE_39 / EAN_13 / EAN_8 |
| 相机 | `capture()` | 单张或连拍,前后切换、闪光灯,返回原图 |
| 下载 | `download()` | DownloadManager,落 `Downloads/GaoCustomer` |
| 分享 | `share()` | 系统分享面板,发微信 / 企微 |
| 打印 | `print()` | 系统打印框架,图片与 PDF |
| 通知 | `scheduleNotification()` / `cancelNotification()` / `cancelAllNotifications()` / `listScheduledNotifications()` | 定时与每日/每周/每年重复,点击带路由,可按归属清理 |
| 通知 | `getNotificationPermission()` / `requestNotificationPermission()` | Android 13+ 运行时权限 |
| 通知 | `canScheduleExactAlarms()` / `openExactAlarmSettings()` | Android 12+ 精确闹钟授权 |
| 语音 | `voiceAvailable()` / `voiceStart()` / `voiceStop()` / `voiceCancel()` | 系统识别双通道,含 partial 回调 |
| 安全 | `biometricAvailable()` / `biometricUnlock()` | 指纹 / 面容解锁 |
| 安全 | `saveSession()` / `readSession()` / `clearSession()` | Keystore 加密的登录态存储 |
| 打印 | `listPrinters()` / `printRaw()` | 蓝牙 SPP + ESC/POS 原始字节 |
| 文件 | `pickFile()` / `saveFile()` | SAF 选择与另存 |
| 日历 | `calendarAvailable()` / `addCalendarEvent()` / `removeCalendarEvent()` | 写入系统日历,静默或拉起日历界面 |
| 状态 | `appStateChange` / `networkStatusChange` 事件、`getAppState()` / `getNetworkStatus()` | 前后台与网络变化感知 |
| 权限 | `getPermissionStates()` + 四个设置跳转 + `isIgnoringBatteryOptimizations()` | 授权状态查询与被拒后的补救入口 |
| 设备 | `getDeviceId()` / `getRingerMode()` / `setKeepAwake()` / `setOrientation()` / `restartApp()` / `clearWebCache()` | 设备标识、响铃模式、常亮、方向、重启、清缓存 |
| 通讯录 | `contactsAvailable()` / `addContact()` / `syncContacts()` / `clearContacts()` | 批量写入系统通讯录,供语音助手与来电识别使用 |
| 杂项 | `vibrate()` / `copy()` / `getDeviceInfo()` | 震动、剪贴板、设备信息 |
### 明确不做的
| 项 | 原因 |
|---|---|
| 离线语音模型(Vosk / sherpa-onnx) | 体积 42MB 起,业务短句识别率未必优于系统引擎 |
| 厂商推送 SDK | 需企业资质与逐厂商接入,侧载 APK 到达率差 |
| 水印合成 | 样式必然反复调整,放 Web 侧 canvas 叠加 |
| 图表、虚拟列表、图片压缩 | Web 层已够用,搬进原生只增加维护面 |
| 扫描枪适配 | USB / 蓝牙 HID 即键盘输入,隐藏 input 即可 |
---
## 二、接口契约
所有方法失败时 `reject(message, code)`,`code` 取值见各节。成功时 `resolve` 的对象结构如下。
### 2.1 `getInfo()`
```ts
{
versionCode: number; // 壳 versionCode
versionName: string; // 壳 versionName
packageName: string;
sdkInt: number;
webViewVersion: string;
capabilities: string[]; // 能力名数组,见下表
}
```
能力名与方法的对应关系:
```
scan, capture, download, share, print,
notify.schedule, notify.list, notify.permission, notify.exact,
voice, biometric, session,
btPrint, saf, calendar,
app.state, app.network, app.permission, app.device,
contacts, misc
```
**前端必须以此数组判断能力是否存在**,不要用 `try/catch` 或猜测。
### 2.2 `scan(options?)`
```ts
options: {
formats?: string[]; // 默认 ["QR_CODE","CODE_128","CODE_39","EAN_13","EAN_8"]
torch?: boolean; // 初始手电筒状态
continuous?: boolean; // 连续扫码,识别成功不关闭页面
}
=> { text: string, format: string }
```
- 整页原生取景,UI 只有返回、手电筒、相册、取景框,**不放业务文案**
- `continuous` 为真时每次识别通过 `scanResult` 事件回传,页面不关闭,点返回时 resolve 最后一次结果
- 相册识别走系统图片选择,单张解码
### 2.3 `capture(options?)`
```ts
options: {
multiple?: boolean; // 默认 false
maxCount?: number; // 多张时的上限,默认 9
facing?: "back" | "front";
flash?: boolean;
}
=> { files: Array<{ path: string, name: string, size: number, mimeType: string }> }
```
- `path` 是 `file://` 形式的 cache 路径,Web 侧需经 `Capacitor.convertFileSrc()` 使用
- **不压缩、不加水印**,压缩交给现有 `src/utils/imageCompression.ts`
### 2.4 `download(options)`
```ts
options: {
url: string;
fileName: string;
subDir?: string; // 默认 GaoCustomer
notify?: boolean; // 默认 true,通知栏显示进度
}
=> { uri: string, path: string, name: string, size: number }
```
- 落 `Environment.DIRECTORY_DOWNLOADS/<subDir>/`,Android 10+ 免存储权限
- `uri` 为 `content://`;`path` 是下载完成后复制到 cache 的 `file://` 地址,分享与打印用它
(Downloads 里的文件不在 FileProvider 放行范围内)
- 下载是异步的,Promise 在下载完成后 resolve;10 分钟未完成按超时 reject
### 2.5 `share(options)`
```ts
options: { path: string, mimeType?: string, title?: string, text?: string }
=> void
```
### 2.6 `print(options)`
```ts
options: { paths: string[], jobName?: string }
=> void
```
- 图片按 A4 等比缩放,一张一页
- PDF 直接交给打印框架
- **无法静默打印**,始终弹系统打印面板(系统限制)
### 2.7 `scheduleNotification(options)`
```ts
options: {
id?: number; // 不传则自增
title: string;
body: string;
at: number; // epoch 毫秒,必须大于当前时间
repeat?: "none" | "daily" | "weekly" | "yearly";
route?: string; // 点击后跳转的路径,如 "/product/order-fulfillments?status=PENDING"
channel?: "reminder" | "alert";
owner?: string; // 归属标识,通常是登录用户 ID,用于共用设备隔离
}
=> { id: number, at: number }
cancelNotification({ id }) => { id }
cancelAllNotifications({ owner? }) => void // 传 owner 只清该归属的任务
listScheduledNotifications({ owner? }) => {
items: Array<{
id: number, title: string, body: string,
at: number, repeat: string,
route: string | null, owner: string | null,
channel: "reminder" | "alert"
}>
}
```
- `reminder` 渠道为默认重要性,`alert` 为高重要性(响铃 + 震动)
- 重复任务由接收器在触发时重新排程,不依赖 `setRepeating`
- 设备重启后由 `BOOT_COMPLETED` 恢复全部未过期任务
- 点击通知:冷启动与热启动都会把 `route` 交给 Web,见 2.8
- **`listScheduledNotifications` 返回的是「原生记录过的任务」,不是 AlarmManager 的真实状态**:
系统强停、省电策略清理闹钟后,这里仍然会列出任务。它用于诊断和账号隔离,
不能当作「闹钟一定还在」的依据 —— 可靠做法是冷启动无条件全量重排(同 id 覆盖,天然幂等)
### 2.8 通知路由的两种消费方式
```ts
// 冷启动:Web 起来后主动拉一次,取走即清除
getLaunchRoute() => { route: string | null }
// 运行中:原生派发 window 事件
window.addEventListener("nativekit:route", e => { ... }) // e.detail.route
```
原生侧同时写 SharedPreferences 并 `triggerJSEvent`,两条路都能拿到。
### 2.9 语音
```ts
voiceAvailable() => { channel: "recognizer" | "intent" | "none", engine?: string }
voiceStart(options?: {
lang?: string; // 默认 zh-CN
partial?: boolean; // 默认 true,回调中间结果
preferOffline?: boolean;
}) => { text: string, confidence?: number }
voiceStop() => void // 停止录音;最终结果仍由 voiceStart 的 Promise 返回
voiceCancel() => void // 放弃本次识别,voiceStart 立即以 cancelled 拒绝
```
事件:
```
voicePartial { text: string }
voiceState { state: "listening" | "processing" | "idle" }
```
- 通道 A `SpeechRecognizer`:需要 `RECORD_AUDIO`,支持 partial
- 通道 B `ACTION_RECOGNIZE_SPEECH`:不需要权限,覆盖无识别服务的 ROM,拿不到 partial
- 两条通道都会在识别期间**置位内部导航标记**,避免被误判为「从后台回到前台」
### 2.10 生物识别与会话
```ts
biometricAvailable() => { available: boolean, type: string } // type: fingerprint | face | iris | none
biometricUnlock(options?: { title?: string, subtitle?: string, cancelText?: string }) => { ok: boolean }
saveSession(options: { json: string }) => void
readSession() => { json: string | null }
clearSession() => void
```
- 会话由 Android Keystore 的 AES/GCM 密钥加密后存 SharedPreferences,密钥不出 TEE
- `readSession()` 不校验指纹,**指纹闸门由前端控制**:先 `biometricUnlock()` 成功再 `readSession()`
- 若要更强约束,后续可加「会话读取必须带一次生物识别」的开关,接口预留
### 2.11 蓝牙打印
```ts
listPrinters() => { printers: Array<{ name: string, address: string, bonded: boolean }> }
printRaw(options: {
address: string;
data: string; // base64 编码的 ESC/POS 字节流
}) => { bytes: number }
```
- `data` 由前端拼装,小票模板、中文位图渲染全部在前端完成
- 原生只负责:连接 SPP、写入字节、关闭
- 需要 `BLUETOOTH_CONNECT`(Android 12+ 运行时权限)
- 已配对设备优先;未配对的设备需用户先在系统设置里配对
### 2.12 SAF
```ts
pickFile(options?: { mimeTypes?: string[], multiple?: boolean })
=> { files: Array<{ path: string, name: string, size: number, mimeType: string }> }
saveFile(options: { fileName: string, mimeType?: string, data: string }) // data 为 base64
=> { path: string, name: string }
```
- `pickFile` 选中后把内容拷到 `cacheDir/nativekit-pick/`,返回 `file://`
原因:`content://` 在 WebView 的 `fetch()` 里不可读
- `saveFile` 走 `ACTION_CREATE_DOCUMENT`,由用户选择落点
### 2.13 系统日历
```ts
calendarAvailable() => {
canInsert: boolean; // 设备上有能接收 INSERT 的日历应用
canWriteSilent: boolean; // 已授权且有可写日历,可静默写入
calendars: Array<{ id: string, name: string, accountName: string, accountType: string, primary: boolean }>
}
addCalendarEvent(options: {
title: string;
beginAt: number; // epoch 毫秒
endAt?: number; // 不传默认 beginAt + 30 分钟
description?: string;
location?: string;
allDay?: boolean;
reminderMinutes?: number[]; // 提前多少分钟提醒,默认 [0] 即事件开始时
calendarId?: string; // 不传按「主日历 > 本地日历 > 第一个」选
mode?: "auto" | "silent" | "intent";
}) => { mode: "silent" | "intent", eventId: string | null }
removeCalendarEvent(options: { eventId: string }) => { deleted: boolean }
```
- **提醒事项做不到**:各家的备忘录/待办是私有数据库,没有标准 ContentProvider,也没有统一 Intent
- `silent`:需要 `READ_CALENDAR` / `WRITE_CALENDAR`,且存在可写日历,返回 `eventId`
- `intent`:不需要任何权限,拉起系统日历新建页,由用户确认,**拿不到 `eventId`,后续无法删除**
- `auto`:先试静默,没权限或没有可写日历时自动降级到 intent
- 全天事件:`allDay: true` 时 `beginAt` / `endAt` 必须是 **UTC 午夜**的毫秒值,否则整体偏移一天
- 写入后提醒由系统日历应用负责,与 `scheduleNotification` 是两套互补机制
### 2.14 前后台与网络
```ts
getAppState() => { isActive: boolean }
getNetworkStatus() => { connected: boolean, type: "wifi" | "cellular" | "ethernet" | "vpn" | "other" | "none" }
// 事件
appStateChange { isActive: boolean }
networkStatusChange { connected: boolean, type: string }
```
- 前台判定用**进程内 Activity 计数**,不是 `onResume/onPause`:打开扫码页、语音页、SAF 选择器都会让 MainActivity pause,用后者会被误判成切到后台
- 计数归零时用进程 importance 兜底:`restartApp` 重建后新插件实例注册回调晚于新 Activity 的 onStart,只靠计数会一直误报后台
- `networkStatusChange` 只在真正变化时派发,网络抖动不会刷屏
- 冷启动时事件可能早于 Web 就绪,前端应先用 `getAppState()` / `getNetworkStatus()` 拉一次基线
### 2.15 权限状态与系统设置
```ts
getPermissionStates() => {
camera: "granted" | "denied" | "prompt" | "prompt-with-rationale",
microphone: 同上,
calendar: 同上,
contacts: 同上,
bluetooth: 同上, // Android 12 以下恒为 granted
notifications: "granted" | "denied" // Android 13 以下取系统开关状态
}
openAppSettings() => void // 应用详情页,权限被「拒绝且不再询问」后唯一的补救入口
openNotificationSettings() => void
openBatteryOptimizationSettings() => void // 直接把本应用加入电池白名单;ROM 不认时退回列表页
isIgnoringBatteryOptimizations() => { ignoring: boolean }
```
- `prompt` 表示还没问过、可以再弹;`denied` 表示已经拒绝,再调权限 API 不会弹窗,只能引导去设置
- 本地通知能否可靠触发,前提是 `isIgnoringBatteryOptimizations()` 为真
### 2.16 设备控制
```ts
getDeviceId() => { androidId: string } // Android 8+ 按签名隔离,清数据/重装不变
getRingerMode() => { mode: "silent" | "vibrate" | "normal" }
setKeepAwake({ enabled: boolean }) => { enabled: boolean }
setOrientation({ orientation: "portrait" | "landscape" | "auto" }) => { orientation: string }
restartApp() => void // 清空任务栈重建 Activity,进程不换
clearWebCache({ storage?: boolean }) => void
```
- `setKeepAwake` 只作用于当前 Activity,离开页面必须关掉,否则一直亮屏耗电
- `restartApp` **不是杀进程**:Android 10 起禁止后台启动 Activity,靠 `AlarmManager` 把进程拉回来的做法实测会被系统拦掉,杀了就再也起不来。这里改成清空任务栈重建 MainActivity,进程不变但 WebView 重新加载、Bridge 重建,对「切账号彻底重置」够用
- `clearWebCache` 的 `storage: true` 会连 localStorage 和 Cookie 一起清,**登录态、主题、热更记录都会没**,只用于排查白屏或切账号彻底重置
### 2.17 通讯录
```ts
contactsAvailable() => { canWrite: boolean, hasPermission: boolean, total: number }
addContact({ name, phone, note?, businessId?, groupTag? }) => { rawContactId: number }
syncContacts({
items: Array<{ id: string, name: string, phone: string, note?: string }>,
groupTag?: string // 默认 GaoCustomer,用于区分批次
}) => { inserted: number, updated: number, deleted: number, total: number }
clearContacts({ groupTag? }) => { deleted: number }
```
- `syncContacts` 是**批量幂等**的:以 `id` 为准做差集,缺的插入、变了的更新、多出来的删除。同一个 `groupTag` 下不会残留脏号码
- 业务 ID 存在自定义 MIMETYPE 的 Data 行里,**通讯录界面不会显示**,也不占姓名/备注/昵称任何可见字段
- 不会自动加任何姓名后缀,显示名完全由前端传
- 每批 100 条执行一次 `applyBatch`,500 个客户约 1–2 秒
- 写入后系统语音助手("打电话给张三")和来电识别才能命中;业务数据助手仍然读不到
### 2.18 杂项
```ts
vibrate(options?: { ms?: number }) => void
copy(options: { text: string }) => void
getDeviceInfo() => {
brand: string, model: string, manufacturer: string,
sdkInt: number, webViewVersion: string,
packageName: string, versionCode: number, versionName: string
}
```
---
## 三、权限与清单变更
`AndroidManifest.xml` 一次性声明,**后续加权限必然要重新发壳**。
| 权限 | 用途 | 授予方式 |
|---|---|---|
| `CAMERA` | 扫码、拍照 | 已在,运行时 |
| `RECORD_AUDIO` | 语音输入通道 A | 新增,运行时 |
| `POST_NOTIFICATIONS` | 本地通知(33+) | 新增,运行时 |
| `READ_MEDIA_IMAGES` / `READ_MEDIA_VIDEO` | 相册识别、选图(33+) | 新增,运行时 |
| `READ_EXTERNAL_STORAGE` | 同上,`maxSdkVersion=32` | 新增,运行时 |
| `BLUETOOTH_CONNECT` | 蓝牙打印(31+) | 新增,运行时 |
| `BLUETOOTH_SCAN` | 扫描未配对打印机(31+) | 新增,运行时,`usesPermissionFlags="neverForLocation"` |
| `BLUETOOTH` / `BLUETOOTH_ADMIN` | 同上,`maxSdkVersion=30` | 新增 |
| `READ_CALENDAR` / `WRITE_CALENDAR` | 写入系统日历日程 | 新增,运行时 |
| `READ_CONTACTS` / `WRITE_CONTACTS` | 批量写入客户通讯录 | 新增,运行时 |
| `FOREGROUND_SERVICE` | 预留常驻能力 | 新增 |
| `WAKE_LOCK` | 定时通知唤醒 | 新增 |
| `RECEIVE_BOOT_COMPLETED` | 重启恢复定时任务 | 新增 |
| `SCHEDULE_EXACT_ALARM` | 精确闹钟(32+) | 新增,用户手动授予 |
| `VIBRATE` | 震动反馈 | 新增 |
| `ACCESS_NETWORK_STATE` | DownloadManager | 新增 |
| `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` | 引导加入后台白名单 | 新增,需引导页 |
| `REQUEST_INSTALL_PACKAGES` | 壳自升级 | 已有 |
| `INTERNET` | 网络 | 已有 |
`file_paths.xml` 同步收窄:原先的 `external-path path="."` 把整个外部存储暴露给 FileProvider,改为只放行 cache 与 app 私有目录。`ShellUpdater` 使用 `cacheDir/shell-updates`,不受影响。
---
## 四、依赖与体积
| 依赖 | 版本 | 用途 | 体积 |
|---|---|---|---|
| `androidx.camera:camera-core/camera2/lifecycle/view` | 1.4.2 | 预览、分析、拍照 | ~1.5MB |
| `com.google.zxing:core` | 3.5.3 | 条码解码 | ~0.5MB |
| `androidx.biometric:biometric` | 1.1.0 | 指纹 / 面容 | ~0.3MB |
不引入 `zxing-android-embedded`(自带一套 UI,与自定义取景冲突)。
不引入 `androidx.security:security-crypto`(长期 alpha 且部分机型 MasterKey 创建失败),改为直接用 Android Keystore + AES/GCM 自实现,约 80 行。
`minifyEnabled` 本次仍保持 `false`。R8 会混淆 `@CapacitorPlugin` 注解类,预埋阶段先保证能跑通,等能力验证完再单独开一次。
---
## 五、前端约定
### 5.1 能力协商必须集中
新增 `src/utils/nativeCapabilities.ts`,**唯一入口**:
```ts
const capabilities = ref<Set<string>>(new Set());
export async function loadCapabilities(): Promise<void>; // 启动时调一次
export function hasCapability(name: string): boolean;
export function requireCapability(name: string): void; // 缺失时抛明确错误
```
禁止在页面里散落 `Capacitor.isPluginAvailable()`。老壳上所有新能力都应「按钮不出现」,而不是「点了没反应」。
### 5.2 自测入口
设置页连点 5 次开启(复用 `createVConsoleClickHandler`),页面列出全部能力,逐项可手动触发。
**这一步不能省**:预埋的代码从不执行等于没测过,等半年后真要用时才发现问题,还是得开壳。
自测页是纯 Web,热更可改,不增加壳的维护面。
### 5.3 新能力上线的三段式
```
1. 发壳(code 4)→ 通道切回 BUNDLE
2. 推装机,确认设备都升到 4
3. Gitea 改 APP_MIN_VERSION_CODE = 4
4. 发首个使用新能力的热更包
```
第 3 步不可逆:做了之后 `versionCode < 4` 的设备永久停在当前 BUNDLE,收不到任何后续修复。
---
## 六、实施步骤
| 阶段 | 内容 | 验收 |
|---|---|---|
| 一 | 依赖、权限、Manifest、`file_paths` 收窄、versionCode 4 | `assembleDebug` 通过,装上不崩 |
| 二 | `NativeKit` 主类 + `getInfo()` + 全部方法骨架 | 能力表可读,未实现方法返回明确错误 |
| 三 | 相机管线(扫码 + 拍照) | 真机扫码 8 个调用点场景可用,弱光与远景优于 JS 版 |
| 四 | 下载、分享、打印、SAF | 导出 ZIP 落 Downloads,能分享到微信,能打二维码 |
| 五 | 通知、语音 | 定时通知准点触发,重启后仍有效;语音在无 GMS 设备上自动降级 |
| 六 | 生物识别、蓝牙打印、杂项 | 指纹解锁可用,58mm 小票机能出字 |
| 七 | 自测页(Web 侧) | 全部能力逐项通过 |
每阶段单独打包装机验证,不要攒到最后一起验。
---
## 七、风险清单
| 风险 | 影响 | 处置 |
|---|---|---|
| 国产 ROM 无 `RecognitionService` | 语音不可用 | 双通道 + `voiceAvailable()` 探测,页面按结果渲染 |
| Android 15 前台服务 `dataSync` 每日 6 小时上限 | 常驻失效 | 本次不做常驻;定时任务走 AlarmManager + BOOT_COMPLETED |
| 精确闹钟未授权 | 提醒延迟 | `canScheduleExactAlarms()` 检查,未授权时降级 `setAndAllowWhileIdle` 并提供设置入口 |
| 蓝牙 MAC 在无权限时不可读 | 打印机选不中 | `listPrinters()` 在申请 `BLUETOOTH_CONNECT` 后再调用 |
| 国产 ROM 没有本地日历账户 | 静默写入无日历可选 | `auto` 模式降级到 `ACTION_INSERT`;前端先看 `calendarAvailable().canWriteSilent` |
| 廉价热敏机无中文字库 | 小票乱码 | 前端优先试 GBK 直发,失败走位图点阵(384 点宽) |
| WebView 内核过旧(Android 10 设备) | CameraX 无关,但 `:has()` 等 CSS 退化 | 原生扫码正好绕开 WebView 差异 |
| 抬基线过早 | 未升级设备断流 | 严格按 5.3 顺序,第 3 步留缓冲期 |
| 能力表与实现漂移 | 前端判存在但实际不可用 | `getInfo()` 的能力数组由代码常量生成,不手写 |
---
## 八、与壳升级流程的衔接
本次属于「新增插件 + 新增权限 + 新增 Activity」的完整原生变更,必须走 `NATIVE_UPGRADE.md` 全套流程:
1. `versionCode` 改成 4,`versionName` 改成 1.2.0
2. `pnpm run android:sync:prod`
3. `pnpm run android:apk`
4. 核对 versionCode、`apksigner` 证书指纹(`3E:9C:CC:8A:…`)、包内不含内网地址
5. 发 `kind = NATIVE` 发布记录
6. **把通道切回最新 BUNDLE 记录**(不切则新壳 `check` 返回 null,热更断流)
7. 装机确认后再抬 `APP_MIN_VERSION_CODE`
---
## 九、真机验证记录(2026-11-20)
设备:华为 SEA-AL10,Android 10(SDK 29),WebView 114.0.5735.196,无 GMS。
### 已验证通过
| 能力 | 验证方式与结果 |
|---|---|
| `getInfo` | 16 项能力全部返回,versionCode 4 / 1.2.0 |
| `getDeviceInfo` | 机型、SDK、WebView 版本、包版本均正确 |
| 通知排程 | 6 秒后精确触发,通知栏出现(自定义 `ic_notification` 图标、标题正文正确) |
| 通知路由 | `am start --es nativekit_route` 等价路径,`getLaunchRoute` 首次取值、二次为 null |
| 重复任务 | daily 任务触发后自动重排,间隔精确 86400000ms |
| 任务列表 | `listScheduledNotifications` 返回 id/title/at/repeat/route/owner/channel,按 owner 过滤生效 |
| 日历探测 | 华为本地日历 `com.android.huawei.phone` 可写,`canWriteSilent: true` |
| 日历写入 | 静默写入成功,`content query` 核对到 `hasAlarm=1`,Reminders `minutes=0 / method=1` |
| 日历删除 | `removeCalendarEvent` 后数据库记录消失 |
| 语音 | `channel: "recognizer"`,华为系统识别引擎可用 |
| 生物识别 | 硬件存在、未录指纹时正确返回 `none_enrolled` |
| 会话加密 | Keystore AES/GCM 写入→读取一致,清除后为 null |
| 下载器 | DownloadManager 落 Downloads,复制到 cache,`path` 可读 |
| 扫码页 | CameraX 预览正常、取景框/手电筒/相册按钮齐全,无黑屏 |
| 相册识别 | 选中 PNG 后正确解出 `GAO-NATIVE-TEST-2026` / `QR_CODE`,页面自动关闭 |
| 拍照 | 预览正常、计数递增、多张模式可继续、返回 9MB 原图 |
| 分享 | 系统面板弹出,缩略图正常,微信/邮件/文件管理可点 |
| 打印 | A4 预览、二维码居中清晰、1/1 页 |
| SAF 另存 | 写入 `content://`,`cat` 校验内容为 `hello native` |
| 震动 / 剪贴板 | 均返回成功 |
### 未覆盖(受设备条件限制)
| 项 | 原因 |
|---|---|
| 实时摄像头扫码解码 | 需要实物二维码对准镜头,无法自动化;YUV 旋转分支是唯一未跑到的代码路径 |
| 蓝牙 ESC/POS 打印 | 无配对打印机,`listPrinters` 只验证了空列表分支 |
| 生物识别解锁 | 设备未录入指纹 |
| 通知点击的真实 UI 点击 | 用 `am start` 模拟了同一 Intent 路径,PendingIntent 本身未点 |
### 真机测出并已修复的两个问题
| 问题 | 现象 | 修复 |
|---|---|---|
| `route` 脏值 | `optString` 对 JSON null 返回字符串 `"null"`,重排时又原样写回,点通知会跳到 `/null` | 读取判 `isNull` + `cleanText` 清洗空串与 `"null"`;写入前也归一 |
| 分区存储 | Android 10 上按绝对路径读 Downloads 里的文件失败,`path` 恒为空 | 改用 `DownloadManager.openDownloadedFile()` 拿 fd 复制 |
两个都是编译期看不出来、只能装机才暴露的问题。
## 十、第二批能力实测(2026-11-20)
同一台华为 SEA-AL10 / Android 10。
| 能力 | 结果 |
|---|---|
| `getPermissionStates` | 6 项权限状态全部正确返回 |
| `getNetworkStatus` | `wifi` / 关闭 WiFi 后 `none` → `cellular` → 恢复 `wifi` |
| `appStateChange` | 按 HOME 收到 `{isActive:false}`,回前台收到 `{isActive:true}` |
| `networkStatusChange` | 关开 WiFi 的两次变化都收到,无重复派发 |
| `getDeviceId` | 返回稳定 `ANDROID_ID` |
| `getRingerMode` | 设备静音时返回 `silent` |
| `isIgnoringBatteryOptimizations` | 未加白名单时 `false` |
| `setKeepAwake` / `setOrientation` | 横屏锁定后 `mCurrentRotation=ROTATION_90`,恢复 `auto` 正常 |
| `openAppSettings` | 跳到 `com.android.settings/.applications.InstalledAppDetails` |
| `clearWebCache` | 只清 HTTP 缓存时返回 ok |
| `syncContacts` 首次 | `inserted=3`,系统 `content query` 核对到姓名与号码 |
| `syncContacts` 二次 | 改 1、删 1、加 1,返回 `inserted=1 / updated=2 / deleted=1`,数据库核对无残留 |
| `clearContacts` | `deleted=3`,之后 `No result found` |
| `restartApp` | 进程 PID 不变,Activity 重建,21 项能力与 WebView 均恢复 |
### 本轮测出并修复的三个问题
| 问题 | 现象 | 修复 |
|---|---|---|
| `restartApp` 起不来 | 杀进程后 `AlarmManager` 的 PendingIntent 被 Android 10 的后台启动限制拦掉,7 秒后仍停在桌面 | 改为清空任务栈重建 Activity,不杀进程 |
| 重建后 `isActive` 恒为 false | 新插件实例注册回调晚于新 Activity 的 onStart,且旧 Activity 的 stop 被新实例接收 | 初始计数记 1 + 首次 started 只做对齐 + 归零时用进程 importance 兜底 |
| RawContact 插入不稳 | 不写 `ACCOUNT_TYPE` / `ACCOUNT_NAME` 时部分 ROM 行为不一致 | 显式写 null,明确落到本地联系人 |
## 十一、登录态联调(2026-11-20)
后端 `http://192.168.11.7:18091`,账号 `Admin`,WebView 114,设备同前。
### 接入时踩到的两个接口约定
| 接口 | 约束 | 踩坑表现 |
|---|---|---|
| `GET /captcha` | 必须带 `width` 与 `height` | 不带参数返回 `50000 not found width or less than 64` |
| `POST /gao/customer/follow-up-reminder/create` | `remindAt` 必须是整分钟(秒、毫秒为 0) | 否则返回 `提醒时间必须精确到分钟`,需要用 `Math.ceil(ts / 60000) * 60000` 处理 |
### 真实数据下的端到端验证
| 环节 | 结果 |
|---|---|
| 登录 | `POST /user/login` 返回 token 与 user,写入 `gao-customer-h5:user` 后重载进入 `/customers` |
| 客户列表 | 354 条,前 50 条中 33 条有 `telephone` |
| 批量写通讯录 | 取前 10 条真实客户,`inserted=10`,系统 `content query` 核对姓名与号码一致 |
| 创建跟进提醒 | `remindAt` 取整分钟后创建成功,回读 id 与时间正确 |
| 映射到原生 | 提醒 id 哈希成通知 id,`owner` 用登录用户 id,`route` 拼客户详情,排程成功 |
| 通知触发 | 15 秒后弹出,`id / title / channel=nativekit_alert` 全部正确 |
| 写日历 | 静默写入成功,`_id=262`、`title=跟进 陈小花`、`hasAlarm=1` |
| 清理 | 删除提醒、取消通知、删除日历、`clearContacts` 删除 10 条;两处 `content query` 均返回 `No result found` |
**结论:从业务数据到原生通知与日历的完整链路可用**,前端接入时只需要决定同步策略与 id 映射算法。
+11 -4
View File
@@ -40,15 +40,22 @@ grep versionCode android/app/build.gradle
- 增删插件后执行 `pnpm exec cap sync android` - 增删插件后执行 `pnpm exec cap sync android`
- 确认 `capacitor.config.ts` 无遗漏 - 确认 `capacitor.config.ts` 无遗漏
- **`minSdkVersion` 已是 29(Android 10+)**:下一次发壳,Android 9 及以下的机器装不上,
会永久停在旧版本。发之前先确认设备分布,别把一个还在用老系统的门店锁死
- **打壳前先 `pnpm run android:sync:prod` 重建资源**:它用 `.env.production` 构建并会清掉 - **打壳前先 `pnpm run android:sync:prod` 重建资源**:它用 `.env.production` 构建并会清掉
残留的 `VITE_API_BASE_URL`。真机调试用的 `android:sync:dev`(或 `android:open`)会把局域网地址 残留的 `VITE_API_BASE_URL`。真机调试用的 `android:sync:dev`(或 `android:open`)会把局域网地址
写进 `dist` 和 `android/app/src/main/assets/public`,直接拿去打包就会打出一个连内网的正式包 写进 `dist` 和 `android/app/src/main/assets/public`,直接拿去打包就会打出一个连内网的正式包
- 打完核对:`aapt2 dump badging` 的 versionCode、`apksigner verify --print-certs` 的证书, - 打完核对:`aapt2 dump badging` 的 versionCode、`apksigner verify --print-certs` 的证书,
以及解包 grep 接口地址(内网地址必须为 0 次) 以及解包 grep 接口地址(内网地址必须为 0 次)
- 用 Android Studio 打包,**签名必须与线上包一致**:线上 1.0.0 用的是 - **一条命令出正式包**:`pnpm run android:apk`
`twa/android.keystore`(alias `gao-customer`,证书 `CN=yeyu` / SHA-256 `3E:9C:CC:8A:…`)。 = `android:sync:prod` + `assembleRelease` + 用根目录 `android.keystore` 签名 + 复制到
签名不一致时系统会拒绝覆盖安装,老用户只能卸载重装 `android/app/release/app-release.apk`(已 gitignore),末尾会打印 versionCode、大小、
- `pnpm run android:apk` 走的是 `assembleDebug`,签的是本机 debug key,**不能用于发版** sha256 和证书指纹
- 签名凭证放在 `android/keystore.properties`(已 gitignore),格式见同目录
`keystore.properties.example`;缺密码时脚本会直接拦住,不会产出 debug 包
- 只重新打包、不重建 web:`pnpm run android:apk -- -SkipSync`
- 仍然可以用 Android Studio 打包,但**签名必须是根目录 `android.keystore`**
(alias `gao-customer`,`CN=yeyu` / SHA-256 `3E:9C:CC:8A:…`),否则系统拒绝覆盖安装
### 3. 提高 CI 的兼容基线 ### 3. 提高 CI 的兼容基线
+39 -2
View File
@@ -1,5 +1,13 @@
apply plugin: 'com.android.application' apply plugin: 'com.android.application'
// 发版签名凭证放在 android/keystore.properties(已 gitignore),不进版本库。
// 缺失时 assembleRelease 会产出未签名包,脚本会拦住并提示补全。
def keystorePropertiesFile = rootProject.file("keystore.properties")
def keystoreProperties = new Properties()
if (keystorePropertiesFile.exists()) {
keystorePropertiesFile.withInputStream { keystoreProperties.load(it) }
}
android { android {
namespace = "com.imyeyu.gao.customer" namespace = "com.imyeyu.gao.customer"
compileSdk = rootProject.ext.compileSdkVersion compileSdk = rootProject.ext.compileSdkVersion
@@ -7,8 +15,8 @@ android {
applicationId "com.imyeyu.gao.customer" applicationId "com.imyeyu.gao.customer"
minSdkVersion rootProject.ext.minSdkVersion minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 3 versionCode 4
versionName "1.1.0" versionName "1.2.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions { aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
@@ -16,12 +24,30 @@ android {
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~' ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
} }
} }
signingConfigs {
release {
if (keystorePropertiesFile.exists()) {
storeFile rootProject.file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
}
}
}
buildTypes { buildTypes {
release { release {
minifyEnabled false minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
if (keystorePropertiesFile.exists()) {
signingConfig signingConfigs.release
}
} }
} }
// 与 capacitor-android 保持一致,避免 JVM target 不一致的编译告警
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
} }
repositories { repositories {
@@ -36,6 +62,17 @@ dependencies {
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android') implementation project(':capacitor-android')
// 相机管线:扫码与拍照共用,避免 WebView getImageCapture 的差异与掉帧
implementation "androidx.camera:camera-core:$androidxCameraVersion"
implementation "androidx.camera:camera-camera2:$androidxCameraVersion"
implementation "androidx.camera:camera-lifecycle:$androidxCameraVersion"
implementation "androidx.camera:camera-view:$androidxCameraVersion"
// 纯 JVM 解码库,不依赖 Google Play 服务
implementation "com.google.zxing:core:$zxingVersion"
// 指纹 / 面容解锁
implementation "androidx.biometric:biometric:$androidxBiometricVersion"
testImplementation "junit:junit:$junitVersion" testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
+82
View File
@@ -24,6 +24,30 @@
</activity> </activity>
<!-- 扫码与拍照共用的相机页,不接受外部调用 -->
<activity
android:name=".nativekit.CameraKitActivity"
android:exported="false"
android:theme="@style/AppTheme.CameraKit"
android:launchMode="singleTop"
android:configChanges="orientation|screenSize|keyboardHidden|screenLayout|smallestScreenSize|uiMode" />
<!-- 定时通知触发;由 AlarmManager 发出,不对外 -->
<receiver
android:name=".nativekit.NotificationAlarmReceiver"
android:exported="false" />
<!-- 重启与覆盖安装后恢复未过期的定时通知 -->
<receiver
android:name=".nativekit.BootReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<provider <provider
android:name="androidx.core.content.FileProvider" android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider" android:authorities="${applicationId}.fileprovider"
@@ -35,10 +59,68 @@
</provider> </provider>
</application> </application>
<!--
Android 11 起受包可见性限制,不声明 queries 时 resolveActivity 与
SpeechRecognizer.isRecognitionAvailable 都会误判为「无可用识别服务」。
日历那条用于判断设备上是否存在能接收 INSERT 的日历应用。
-->
<queries>
<intent>
<action android:name="android.speech.RecognitionService" />
</intent>
<intent>
<action android:name="android.speech.action.RECOGNIZE_SPEECH" />
</intent>
<intent>
<action android:name="android.intent.action.INSERT" />
<data android:mimeType="vnd.android.cursor.dir/event" />
</intent>
</queries>
<!-- Permissions --> <!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" /> <uses-feature android:name="android.hardware.camera" android:required="false" />
<!-- 语音输入:仅识别器通道需要,Intent 通道不需要 -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- 本地通知与定时调度 -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- 相册选择与条码图片识别 -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<!-- 写入系统日历:跟进提醒同步为日程事件 -->
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<!-- 写入通讯录:让系统语音助手与来电识别能拿到客户姓名号码 -->
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<!-- 蓝牙小票与标签打印 -->
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission
android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation" />
</manifest> </manifest>
@@ -1,9 +1,11 @@
package com.imyeyu.gao.customer; package com.imyeyu.gao.customer;
import android.content.Intent;
import android.content.pm.ApplicationInfo; import android.content.pm.ApplicationInfo;
import android.graphics.Color; import android.graphics.Color;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.SystemClock;
import android.view.View; import android.view.View;
import android.view.Window; import android.view.Window;
import android.view.WindowManager; import android.view.WindowManager;
@@ -13,15 +15,42 @@ import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat; import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat; import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat; import androidx.core.view.WindowInsetsCompat;
import com.getcapacitor.Bridge;
import com.getcapacitor.BridgeActivity; import com.getcapacitor.BridgeActivity;
import com.imyeyu.gao.customer.mediasaver.MediaSaverPlugin;
import com.imyeyu.gao.customer.nativekit.NativeKitPlugin;
import com.imyeyu.gao.customer.nativekit.NotificationScheduler;
import com.imyeyu.gao.customer.shellupdater.ShellUpdaterPlugin; import com.imyeyu.gao.customer.shellupdater.ShellUpdaterPlugin;
import org.json.JSONObject;
import java.util.Locale; import java.util.Locale;
public class MainActivity extends BridgeActivity { public class MainActivity extends BridgeActivity {
/**
* 内部导航标记。
*
* 语音 Intent 通道会压一层 Activity,返回时触发 onResume;将来接入 appStateChange 后
* 需要用它把「从系统语音页返回」和「真正的回到前台」区分开,否则会误触发数据刷新。
*/
private static long internalNavigationAt = 0L;
public static void markInternalNavigation() {
internalNavigationAt = SystemClock.elapsedRealtime();
}
public static boolean consumeInternalNavigation() {
boolean recent = 0L < internalNavigationAt
&& SystemClock.elapsedRealtime() - internalNavigationAt < 8000L;
internalNavigationAt = 0L;
return recent;
}
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
registerPlugin(ShellUpdaterPlugin.class); registerPlugin(ShellUpdaterPlugin.class);
registerPlugin(MediaSaverPlugin.class);
registerPlugin(NativeKitPlugin.class);
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
applyEdgeToEdge(); applyEdgeToEdge();
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@@ -41,6 +70,53 @@ public class MainActivity extends BridgeActivity {
} }
} }
/**
* 通知点击与外部跳转的统一入口。
*
* Capacitor 的 BridgeActivity 在 load() 里会调一次 onNewIntent(getIntent()),
* 所以冷启动与热启动都会走到这里,不需要在 onCreate 里重复处理。
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleNotificationRoute(intent);
}
/**
* 把通知带来的路由交给 Web。
*
* 两条路都走:写 SharedPreferences 供冷启动后主动拉取,同时派发 window 事件供运行中响应。
* 只派发事件的话,WebView 还没加载完时点通知会丢;只写存储的话,前台时点通知没反应。
*/
private void handleNotificationRoute(Intent intent) {
if (intent == null) {
return;
}
String route = intent.getStringExtra(NotificationScheduler.EXTRA_ROUTE);
if (route == null || route.isEmpty()) {
return;
}
intent.removeExtra(NotificationScheduler.EXTRA_ROUTE);
getSharedPreferences(NativeKitPlugin.PREFS, MODE_PRIVATE)
.edit()
.putString(NativeKitPlugin.KEY_LAUNCH_ROUTE, route)
.apply();
Bridge bridge = getBridge();
if (bridge == null) {
return;
}
JSONObject detail = new JSONObject();
try {
detail.put("route", route);
} catch (Exception ignored) {
return;
}
bridge.triggerWindowJSEvent("nativekit:route", detail.toString());
}
/** /**
* 让窗口真正 edge-to-edge,安全区由 Web 侧按 --tui-safe-* 补齐。 * 让窗口真正 edge-to-edge,安全区由 Web 侧按 --tui-safe-* 补齐。
* *
@@ -0,0 +1,187 @@
package com.imyeyu.gao.customer.mediasaver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/// 把网页里拍到的照片/视频写进系统相册
///
/// 走 MediaStore 的 IS_PENDING 流程,Android 10 起不需要任何存储权限。
/// 分块接收是为了避免大视频在 JS 与原生之间一次性复制导致内存翻倍。
@CapacitorPlugin(name = "MediaSaver")
public class MediaSaverPlugin extends Plugin {
/// 单个文件上限,防止异常调用把手机存储写满
private static final long MAX_BYTES = 512L * 1024 * 1024;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final Map<String, Session> sessions = new ConcurrentHashMap<>();
private static class Session {
final File temp;
final String fileName;
final String mimeType;
final boolean video;
long size;
Session(File temp, String fileName, String mimeType, boolean video) {
this.temp = temp;
this.fileName = fileName;
this.mimeType = mimeType;
this.video = video;
}
}
/// 开始一次写入,返回后续分块要用的 id
@PluginMethod
public void begin(PluginCall call) {
String fileName = call.getString("fileName");
String mimeType = call.getString("mimeType");
String mediaType = call.getString("mediaType", "image");
if (fileName == null || !fileName.matches("[\\w.\\-]{1,120}")) {
call.reject("文件名不合法");
return;
}
if (mimeType == null || !mimeType.matches("(image|video)/[\\w.+-]+")) {
call.reject("媒体类型不合法");
return;
}
File directory = new File(getContext().getCacheDir(), "media-save");
if (!directory.exists() && !directory.mkdirs()) {
call.reject("无法创建缓存目录");
return;
}
String id = UUID.randomUUID().toString();
Session session = new Session(new File(directory, id + ".part"), fileName, mimeType, "video".equals(mediaType));
sessions.put(id, session);
JSObject result = new JSObject();
result.put("id", id);
call.resolve(result);
}
/// 追加一块 base64 数据
@PluginMethod
public void append(PluginCall call) {
String id = call.getString("id");
String data = call.getString("data");
Session session = id == null ? null : sessions.get(id);
if (session == null) {
call.reject("会话不存在");
return;
}
if (data == null) {
call.reject("数据为空");
return;
}
executor.execute(() -> {
try {
byte[] bytes = Base64.decode(data, Base64.DEFAULT);
if (MAX_BYTES < session.size + bytes.length) {
throw new IllegalStateException("文件超过大小上限");
}
try (FileOutputStream output = new FileOutputStream(session.temp, true)) {
output.write(bytes);
}
session.size += bytes.length;
call.resolve();
} catch (Exception e) {
sessions.remove(id);
session.temp.delete();
call.reject("写入失败", e);
}
});
}
/// 收尾:把临时文件搬进相册,成功后清理临时文件
@PluginMethod
public void finish(PluginCall call) {
String id = call.getString("id");
Session session = id == null ? null : sessions.remove(id);
if (session == null) {
call.reject("会话不存在");
return;
}
executor.execute(() -> {
Uri uri = null;
try {
ContentResolver resolver = getContext().getContentResolver();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, session.fileName);
values.put(MediaStore.MediaColumns.MIME_TYPE, session.mimeType);
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/GaoCustomer");
values.put(MediaStore.MediaColumns.IS_PENDING, 1);
Uri collection = session.video
? MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
: MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
uri = resolver.insert(collection, values);
if (uri == null) {
throw new IllegalStateException("无法创建相册条目");
}
try (InputStream input = new FileInputStream(session.temp); OutputStream output = resolver.openOutputStream(uri)) {
if (output == null) {
throw new IllegalStateException("无法写入相册");
}
byte[] buffer = new byte[32768];
int size;
while ((size = input.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
}
// 清掉 PENDING,相册 App 才会看到这个文件
ContentValues done = new ContentValues();
done.put(MediaStore.MediaColumns.IS_PENDING, 0);
resolver.update(uri, done, null, null);
session.temp.delete();
call.resolve();
} catch (Exception e) {
if (uri != null) {
try {
getContext().getContentResolver().delete(uri, null, null);
} catch (Exception ignored) {
// 清理失败不影响主流程
}
}
session.temp.delete();
call.reject("保存到相册失败", e);
}
});
}
/// 放弃本次写入
@PluginMethod
public void cancel(PluginCall call) {
String id = call.getString("id");
Session session = id == null ? null : sessions.remove(id);
if (session != null) {
session.temp.delete();
}
call.resolve();
}
@Override
protected void handleOnDestroy() {
executor.shutdown();
for (Session session : sessions.values()) {
session.temp.delete();
}
sessions.clear();
}
}
@@ -0,0 +1,122 @@
package com.imyeyu.gao.customer.nativekit;
import android.content.pm.PackageManager;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.getcapacitor.JSObject;
import com.getcapacitor.PluginCall;
/**
* 指纹 / 面容解锁。
*
* <p>只做「闸门」:解锁成功后由前端调 {@code readSession()} 取登录态。
* 是否要求「每次读会话都必须过生物识别」由前端控制,原生不强制 —— 业务上存在
* 「解锁一次、当天免密」的需求。
*/
final class BiometricHelper {
private BiometricHelper() {
}
static void available(FragmentActivity activity, PluginCall call) {
JSObject result = new JSObject();
int status;
try {
status = BiometricManager.from(activity)
.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK);
} catch (Exception error) {
result.put("available", false);
result.put("type", "none");
call.resolve(result);
return;
}
result.put("available", status == BiometricManager.BIOMETRIC_SUCCESS);
result.put("type", detectType(activity));
if (status != BiometricManager.BIOMETRIC_SUCCESS) {
result.put("reason", statusName(status));
}
call.resolve(result);
}
static void unlock(FragmentActivity activity, PluginCall call) {
int status = BiometricManager.from(activity)
.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK);
if (status != BiometricManager.BIOMETRIC_SUCCESS) {
call.reject("设备不支持生物识别:" + statusName(status), "unavailable");
return;
}
String title = call.getString("title", "验证身份");
String subtitle = call.getString("subtitle", "使用指纹或面容继续");
String cancelText = call.getString("cancelText", "改用密码");
BiometricPrompt.PromptInfo info = new BiometricPrompt.PromptInfo.Builder()
.setTitle(title)
.setSubtitle(subtitle)
.setNegativeButtonText(cancelText)
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_WEAK)
.setConfirmationRequired(false)
.build();
BiometricPrompt prompt = new BiometricPrompt(
activity,
ContextCompat.getMainExecutor(activity),
new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
JSObject payload = new JSObject();
payload.put("ok", true);
call.resolve(payload);
}
@Override
public void onAuthenticationError(int errorCode, CharSequence errString) {
call.reject(errString == null ? "验证失败" : errString.toString(), "auth_error:" + errorCode);
}
}
);
try {
prompt.authenticate(info);
} catch (Exception error) {
call.reject("无法启动生物识别", "prompt_failed");
}
}
private static String detectType(FragmentActivity activity) {
PackageManager manager = activity.getPackageManager();
if (manager.hasSystemFeature(PackageManager.FEATURE_FACE)) {
return "face";
}
if (manager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
return "fingerprint";
}
if (manager.hasSystemFeature(PackageManager.FEATURE_IRIS)) {
return "iris";
}
return "none";
}
/** 用字面量而不是常量引用,避免不同 androidx.biometric 版本之间的常量差异 */
private static String statusName(int status) {
switch (status) {
case 12:
return "no_hardware";
case 1:
return "hw_unavailable";
case 11:
return "none_enrolled";
case 15:
return "security_update_required";
case -2:
return "unsupported";
default:
return "unknown";
}
}
}
@@ -0,0 +1,20 @@
package com.imyeyu.gao.customer.nativekit;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* 重启与覆盖安装后的恢复。
*
* <p>Android 在重启时会清空所有 AlarmManager 闹钟,不做恢复的话,用户在重启手机之后
* 就再也收不到任何本地提醒 —— 这是这类功能最常见的静默失效原因。
*/
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationScheduler.ensureChannels(context);
NotificationScheduler.restore(context);
}
}
@@ -0,0 +1,135 @@
package com.imyeyu.gao.customer.nativekit;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Base64;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import com.getcapacitor.PluginCall;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 蓝牙 ESC/POS 打印。
*
* <p>原生只负责「连上、写字节、断开」,小票模板、字段顺序、中文位图渲染全部由前端完成。
* 这样以后改排版不需要开壳。
*
* <p>走 SPP(串口协议),UUID 是蓝牙打印机的通用服务号,不需要第三方 SDK。
*/
final class BtPrinterHelper {
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
private BtPrinterHelper() {
}
/** 列出已配对设备;未配对的打印机需要用户先在系统设置里配对 */
static void list(Context context, PluginCall call) {
BluetoothAdapter adapter = adapterOf(context);
if (adapter == null) {
call.reject("蓝牙不可用", "service_unavailable");
return;
}
if (!adapter.isEnabled()) {
call.reject("蓝牙未开启", "disabled");
return;
}
JSArray printers = new JSArray();
try {
Set<BluetoothDevice> bonded = adapter.getBondedDevices();
for (BluetoothDevice device : bonded) {
JSObject item = new JSObject();
item.put("name", device.getName() == null ? "" : device.getName());
item.put("address", device.getAddress());
item.put("bonded", true);
printers.put(item);
}
} catch (SecurityException error) {
call.reject("未授予蓝牙权限", "permission_denied");
return;
}
JSObject result = new JSObject();
result.put("printers", printers);
call.resolve(result);
}
static void printRaw(Context context, PluginCall call) {
String address = call.getString("address");
String data = call.getString("data");
if (address == null || !address.matches("([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}")) {
call.reject("打印机地址不合法", "invalid_argument");
return;
}
if (data == null || data.isEmpty()) {
call.reject("缺少打印数据", "invalid_argument");
return;
}
byte[] bytes;
try {
bytes = Base64.decode(data, Base64.DEFAULT);
} catch (Exception error) {
call.reject("打印数据不是合法的 base64", "invalid_argument");
return;
}
BluetoothAdapter adapter = adapterOf(context);
if (adapter == null) {
call.reject("蓝牙不可用", "service_unavailable");
return;
}
if (!adapter.isEnabled()) {
call.reject("蓝牙未开启", "disabled");
return;
}
EXECUTOR.execute(() -> {
BluetoothSocket socket = null;
try {
BluetoothDevice device = adapter.getRemoteDevice(address);
adapter.cancelDiscovery();
socket = device.createRfcommSocketToServiceRecord(SPP_UUID);
socket.connect();
OutputStream output = socket.getOutputStream();
output.write(bytes);
output.flush();
// 给打印机留出出纸时间,立刻 close 会截断最后一行
Thread.sleep(200);
JSObject result = new JSObject();
result.put("bytes", bytes.length);
call.resolve(result);
} catch (SecurityException error) {
call.reject("未授予蓝牙权限", "permission_denied");
} catch (Exception error) {
call.reject("打印失败:" + error.getMessage(), "bt_failed");
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception ignored) {
// 关闭失败不影响结果
}
}
}
});
}
private static BluetoothAdapter adapterOf(Context context) {
BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
return manager == null ? null : manager.getAdapter();
}
}
@@ -0,0 +1,365 @@
package com.imyeyu.gao.customer.nativekit;
import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract;
import androidx.core.content.ContextCompat;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import com.getcapacitor.PluginCall;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
/**
* 写入系统日历。
*
* <p>这是 Android 唯一跨厂商的「日程 / 提醒事项」入口:各家的备忘录、待办应用都是私有数据库,
* 没有标准 ContentProvider,也没有统一的 Intent 契约,做不了。日历走 {@link CalendarContract},
* 小米 / 华为 / OPPO 的日历都是 AOSP Calendar 改的,基本都响应。
*
* <p>两条写入路径:
* <ul>
* <li>静默写入:需要 READ_CALENDAR / WRITE_CALENDAR,且设备上存在可写日历,成功后返回 eventId</li>
* <li>拉起界面:不需要任何权限,弹系统日历新建页由用户确认,拿不到 eventId</li>
* </ul>
*
* <p>国产 ROM 常见的坑是「没有任何本地日历账户」,此时 Calendars 表为空,静默写入无日历可选,
* 只能降级到拉起界面。所以 auto 模式默认先试静默、失败再开界面。
*/
final class CalendarHelper {
private static final String EVENT_MIME_TYPE = "vnd.android.cursor.dir/event";
private static final long DEFAULT_DURATION = 30 * 60 * 1000L;
private static final int DEFAULT_REMINDER_MINUTES = 0;
private CalendarHelper() {
}
// ---------- 探测 ----------
static void available(Context context, PluginCall call) {
boolean hasPermission = hasWritePermission(context);
List<CalendarEntry> calendars = hasPermission ? queryWritable(context) : new ArrayList<>();
JSArray items = new JSArray();
for (CalendarEntry entry : calendars) {
JSObject item = new JSObject();
item.put("id", String.valueOf(entry.id));
item.put("name", entry.name);
item.put("accountName", entry.accountName);
item.put("accountType", entry.accountType);
item.put("primary", entry.primary);
items.put(item);
}
JSObject result = new JSObject();
result.put("canInsert", hasCalendarApp(context));
result.put("canWriteSilent", hasPermission && !calendars.isEmpty());
result.put("calendars", items);
call.resolve(result);
}
// ---------- 写入 ----------
static void add(Activity activity, PluginCall call) {
Payload payload = Payload.from(call);
if (payload == null) {
call.reject("缺少标题或开始时间", "invalid_argument");
return;
}
String mode = call.getString("mode", "auto");
boolean writable = hasWritePermission(activity);
long calendarId = writable ? resolveCalendarId(activity, call.getString("calendarId")) : -1;
if ("silent".equals(mode)) {
if (!writable) {
call.reject("未授予日历写入权限", "permission_denied");
return;
}
if (calendarId <= 0) {
call.reject("设备上没有可写的日历账户", "no_writable_calendar");
return;
}
insert(activity, call, payload, calendarId);
return;
}
if (!"intent".equals(mode) && 0 < calendarId) {
insert(activity, call, payload, calendarId);
return;
}
openIntent(activity, call, payload);
}
private static void insert(Activity activity, PluginCall call, Payload payload, long calendarId) {
ContentResolver resolver = activity.getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
values.put(CalendarContract.Events.TITLE, payload.title);
values.put(CalendarContract.Events.DTSTART, payload.beginAt);
values.put(CalendarContract.Events.DTEND, payload.endAt);
values.put(CalendarContract.Events.HAS_ALARM, 1);
values.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);
if (payload.description != null) {
values.put(CalendarContract.Events.DESCRIPTION, payload.description);
}
if (payload.location != null) {
values.put(CalendarContract.Events.EVENT_LOCATION, payload.location);
}
if (payload.allDay) {
// 全天事件的起止必须是 UTC 午夜,时区固定 UTC,否则会整体偏移一天
values.put(CalendarContract.Events.ALL_DAY, 1);
values.put(CalendarContract.Events.EVENT_TIMEZONE, "UTC");
} else {
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
}
Uri uri;
try {
uri = resolver.insert(CalendarContract.Events.CONTENT_URI, values);
} catch (Exception error) {
call.reject("写入日历失败:" + error.getMessage(), "insert_failed");
return;
}
if (uri == null) {
call.reject("写入日历失败", "insert_failed");
return;
}
long eventId = ContentUris.parseId(uri);
for (int minutes : payload.reminderMinutes) {
try {
ContentValues reminder = new ContentValues();
reminder.put(CalendarContract.Reminders.EVENT_ID, eventId);
reminder.put(CalendarContract.Reminders.MINUTES, minutes);
reminder.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
resolver.insert(CalendarContract.Reminders.CONTENT_URI, reminder);
} catch (Exception ignored) {
// 提醒建不上不影响事件本身,日历 App 会用自己的默认提醒策略
}
}
JSObject result = new JSObject();
result.put("mode", "silent");
result.put("eventId", String.valueOf(eventId));
call.resolve(result);
}
private static void openIntent(Activity activity, PluginCall call, Payload payload) {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setDataAndType(CalendarContract.Events.CONTENT_URI, EVENT_MIME_TYPE);
intent.putExtra(CalendarContract.Events.TITLE, payload.title);
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, payload.beginAt);
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, payload.endAt);
intent.putExtra(CalendarContract.Events.ALL_DAY, payload.allDay);
intent.putExtra(CalendarContract.Events.HAS_ALARM, 1);
intent.putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);
if (payload.description != null) {
intent.putExtra(CalendarContract.Events.DESCRIPTION, payload.description);
}
if (payload.location != null) {
intent.putExtra(CalendarContract.Events.EVENT_LOCATION, payload.location);
}
// 这个 extra 不是所有日历 App 都认,认不了就用应用自己的默认提醒
if (!payload.reminderMinutes.isEmpty()) {
intent.putExtra(CalendarContract.Reminders.MINUTES, payload.reminderMinutes.get(0));
}
try {
activity.startActivity(intent);
JSObject result = new JSObject();
result.put("mode", "intent");
result.put("eventId", JSObject.NULL);
call.resolve(result);
} catch (ActivityNotFoundException error) {
call.reject("设备上没有可用的日历应用", "no_calendar_app");
} catch (Exception error) {
call.reject("无法打开日历:" + error.getMessage(), "activity_not_found");
}
}
// ---------- 删除 ----------
static void remove(Context context, PluginCall call) {
String eventId = call.getString("eventId");
if (eventId == null || eventId.isEmpty()) {
call.reject("缺少 eventId", "invalid_argument");
return;
}
long id;
try {
id = Long.parseLong(eventId);
} catch (NumberFormatException error) {
call.reject("eventId 不合法", "invalid_argument");
return;
}
try {
Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id);
int deleted = context.getContentResolver().delete(uri, null, null);
JSObject result = new JSObject();
result.put("deleted", 0 < deleted);
call.resolve(result);
} catch (Exception error) {
call.reject("删除日程失败:" + error.getMessage(), "delete_failed");
}
}
// ---------- 内部 ----------
private static boolean hasWritePermission(Context context) {
return ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR)
== PackageManager.PERMISSION_GRANTED;
}
private static boolean hasCalendarApp(Context context) {
try {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setDataAndType(CalendarContract.Events.CONTENT_URI, EVENT_MIME_TYPE);
List<ResolveInfo> list = context.getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list != null && !list.isEmpty();
} catch (Exception error) {
return false;
}
}
private static List<CalendarEntry> queryWritable(Context context) {
List<CalendarEntry> result = new ArrayList<>();
String[] projection = {
CalendarContract.Calendars._ID,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.ACCOUNT_NAME,
CalendarContract.Calendars.ACCOUNT_TYPE,
CalendarContract.Calendars.IS_PRIMARY
};
String selection = CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL + ">=?";
String[] args = { String.valueOf(CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR) };
try (Cursor cursor = context.getContentResolver().query(
CalendarContract.Calendars.CONTENT_URI,
projection,
selection,
args,
null
)) {
if (cursor == null) {
return result;
}
while (cursor.moveToNext()) {
CalendarEntry entry = new CalendarEntry();
entry.id = cursor.getLong(0);
entry.name = cursor.getString(1) == null ? "" : cursor.getString(1);
entry.accountName = cursor.getString(2) == null ? "" : cursor.getString(2);
entry.accountType = cursor.getString(3) == null ? "" : cursor.getString(3);
entry.primary = 0 < cursor.getInt(4);
result.add(entry);
}
} catch (Exception ignored) {
// 部分 ROM 的 provider 会抛异常,按「没有可写日历」处理,由上层降级到 Intent
}
return result;
}
/** 选日历:指定 id > 主日历 > 本地日历 > 第一个 */
private static long resolveCalendarId(Context context, String preferred) {
List<CalendarEntry> list = queryWritable(context);
if (list.isEmpty()) {
return -1;
}
if (preferred != null && !preferred.isEmpty()) {
for (CalendarEntry entry : list) {
if (preferred.equals(String.valueOf(entry.id))) {
return entry.id;
}
}
}
for (CalendarEntry entry : list) {
if (entry.primary) {
return entry.id;
}
}
for (CalendarEntry entry : list) {
if ("LOCAL".equals(entry.accountType)) {
return entry.id;
}
}
return list.get(0).id;
}
private static final class CalendarEntry {
long id;
String name;
String accountName;
String accountType;
boolean primary;
}
/** 入参解析一次,避免在多个分支里重复取值 */
private static final class Payload {
String title;
String description;
String location;
long beginAt;
long endAt;
boolean allDay;
List<Integer> reminderMinutes = new ArrayList<>();
static Payload from(PluginCall call) {
String title = call.getString("title");
Long beginAt = call.getLong("beginAt");
if (title == null || title.isEmpty() || beginAt == null) {
return null;
}
Payload payload = new Payload();
payload.title = title;
payload.description = call.getString("description");
payload.location = call.getString("location");
payload.beginAt = beginAt;
payload.allDay = Boolean.TRUE.equals(call.getBoolean("allDay", false));
Long endAt = call.getLong("endAt");
payload.endAt = endAt == null || endAt <= beginAt ? beginAt + DEFAULT_DURATION : endAt;
if (payload.allDay && payload.endAt <= payload.beginAt) {
payload.endAt = payload.beginAt + 24 * 60 * 60 * 1000L;
}
JSArray minutes = call.getArray("reminderMinutes");
if (minutes != null) {
for (int index = 0; index < minutes.length(); index++) {
Object item = minutes.opt(index);
if (item instanceof Number) {
payload.reminderMinutes.add(((Number) item).intValue());
}
}
}
if (payload.reminderMinutes.isEmpty()) {
payload.reminderMinutes.add(DEFAULT_REMINDER_MINUTES);
}
return payload;
}
}
}
@@ -0,0 +1,805 @@
package com.imyeyu.gao.customer.nativekit;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Size;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.io.File;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* 扫码与拍照共用的相机页。
*
* <p>两条模式共用同一条 CameraX 管线:扫码绑 Preview + ImageAnalysis,拍照绑 Preview + ImageCapture。
* UI 只做取景、手电筒、相册、快门,不放任何业务文案 —— 文案一进原生,改一个字都要发壳。
*
* <p>解码用 zxing 的纯 JVM 实现,不依赖 Google Play 服务,国产 ROM 上同样可用。
*/
public class CameraKitActivity extends AppCompatActivity {
public static final String EXTRA_MODE = "mode";
public static final String MODE_SCAN = "scan";
public static final String MODE_CAPTURE = "capture";
public static final String EXTRA_FORMATS = "formats";
public static final String EXTRA_TORCH = "torch";
public static final String EXTRA_CONTINUOUS = "continuous";
public static final String EXTRA_MULTIPLE = "multiple";
public static final String EXTRA_MAX_COUNT = "maxCount";
public static final String EXTRA_FACING = "facing";
public static final String EXTRA_FLASH = "flash";
public static final String FACING_BACK = "back";
public static final String FACING_FRONT = "front";
public static final String RESULT_TEXT = "text";
public static final String RESULT_FORMAT = "format";
public static final String RESULT_FILES = "files";
private static final int REQUEST_GALLERY = 0x9001;
private static final String[] DEFAULT_FORMATS = {
"QR_CODE", "CODE_128", "CODE_39", "EAN_13", "EAN_8"
};
private final ExecutorService decodeExecutor = Executors.newSingleThreadExecutor();
private final AtomicBoolean decoding = new AtomicBoolean(false);
private final List<String> capturedPaths = new ArrayList<>();
private final MultiFormatReader reader = new MultiFormatReader();
private Map<DecodeHintType, Object> hints;
private PreviewView previewView;
private TextView torchButton;
private TextView counterView;
private TextView hintView;
private View shutterButton;
private View galleryButton;
private ProcessCameraProvider cameraProvider;
private Camera camera;
private ImageCapture imageCapture;
private String mode = MODE_SCAN;
private boolean continuous;
private boolean multiple;
private int maxCount = 9;
private boolean facingFront;
private boolean flashOn;
private boolean torchOn;
private boolean capturing;
private String lastText;
private String lastFormat;
private File outputDir;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mode = getIntent().getStringExtra(EXTRA_MODE);
if (MODE_CAPTURE.equals(mode)) {
mode = MODE_CAPTURE;
} else {
mode = MODE_SCAN;
}
continuous = getIntent().getBooleanExtra(EXTRA_CONTINUOUS, false);
multiple = getIntent().getBooleanExtra(EXTRA_MULTIPLE, false);
maxCount = Math.max(1, getIntent().getIntExtra(EXTRA_MAX_COUNT, 9));
facingFront = FACING_FRONT.equals(getIntent().getStringExtra(EXTRA_FACING));
flashOn = getIntent().getBooleanExtra(EXTRA_FLASH, false);
torchOn = getIntent().getBooleanExtra(EXTRA_TORCH, false);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
setResult(RESULT_CANCELED);
finish();
return;
}
outputDir = new File(getCacheDir(), "camera-kit");
if (!outputDir.exists()) {
outputDir.mkdirs();
}
hints = buildHints();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
buildUi();
startCamera();
registerBackHandler();
}
// ---------- UI ----------
private void buildUi() {
FrameLayout root = new FrameLayout(this);
root.setBackgroundColor(Color.BLACK);
previewView = new PreviewView(this);
previewView.setScaleType(PreviewView.ScaleType.FILL_CENTER);
root.addView(previewView, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
if (MODE_SCAN.equals(mode)) {
root.addView(new FrameOverlay(this), new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
}
// 顶部栏:返回、标题、手电筒
LinearLayout topBar = new LinearLayout(this);
topBar.setOrientation(LinearLayout.HORIZONTAL);
topBar.setGravity(Gravity.CENTER_VERTICAL);
topBar.setPadding(dp(8), dp(8), dp(8), dp(8));
TextView closeButton = actionText("✕");
closeButton.setOnClickListener(view -> handleClose());
topBar.addView(closeButton, new LinearLayout.LayoutParams(dp(48), dp(48)));
TextView titleView = new TextView(this);
titleView.setText(MODE_SCAN.equals(mode) ? "扫码" : "拍照");
titleView.setTextColor(Color.WHITE);
titleView.setTextSize(16f);
LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(
0,
ViewGroup.LayoutParams.WRAP_CONTENT,
1f
);
topBar.addView(titleView, titleParams);
torchButton = actionText("手电筒");
torchButton.setOnClickListener(view -> toggleTorch());
topBar.addView(torchButton, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp(48)
));
updateTorchLabel();
FrameLayout.LayoutParams topParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.TOP
);
root.addView(topBar, topParams);
ViewCompat.setOnApplyWindowInsetsListener(root, (view, insets) -> {
androidx.core.graphics.Insets bars = insets.getInsets(
WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout()
);
topBar.setPadding(dp(8), dp(8) + bars.top, dp(8), dp(8));
return insets;
});
// 底部栏
LinearLayout bottomBar = new LinearLayout(this);
bottomBar.setOrientation(LinearLayout.VERTICAL);
bottomBar.setGravity(Gravity.CENTER_HORIZONTAL);
bottomBar.setPadding(dp(16), dp(16), dp(16), dp(24));
hintView = new TextView(this);
hintView.setTextColor(Color.WHITE);
hintView.setTextSize(13f);
hintView.setGravity(Gravity.CENTER);
hintView.setText(MODE_SCAN.equals(mode) ? "将二维码移入取景框" : "点击拍摄");
bottomBar.addView(hintView, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
counterView = new TextView(this);
counterView.setTextColor(Color.WHITE);
counterView.setTextSize(13f);
counterView.setGravity(Gravity.CENTER);
counterView.setVisibility(multiple ? View.VISIBLE : View.GONE);
bottomBar.addView(counterView, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
FrameLayout actionRow = new FrameLayout(this);
actionRow.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
dp(96)
));
if (MODE_SCAN.equals(mode)) {
galleryButton = pillText("相册");
galleryButton.setOnClickListener(view -> pickFromGallery());
FrameLayout.LayoutParams galleryParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp(40),
Gravity.CENTER_VERTICAL | Gravity.START
);
actionRow.addView(galleryButton, galleryParams);
} else {
shutterButton = new View(this);
android.graphics.drawable.GradientDrawable circle = new android.graphics.drawable.GradientDrawable();
circle.setShape(android.graphics.drawable.GradientDrawable.OVAL);
circle.setColor(Color.WHITE);
circle.setStroke(dp(4), 0x66FFFFFF);
shutterButton.setBackground(circle);
shutterButton.setOnClickListener(view -> takePicture());
FrameLayout.LayoutParams shutterParams = new FrameLayout.LayoutParams(dp(72), dp(72), Gravity.CENTER);
actionRow.addView(shutterButton, shutterParams);
if (multiple) {
TextView doneButton = pillText("完成");
doneButton.setOnClickListener(view -> {
if (capturedPaths.isEmpty()) {
setResult(RESULT_CANCELED);
finish();
return;
}
finishWithFiles();
});
actionRow.addView(doneButton, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp(40),
Gravity.CENTER_VERTICAL | Gravity.END
));
}
}
bottomBar.addView(actionRow, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
dp(96)
));
FrameLayout.LayoutParams bottomParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
);
root.addView(bottomBar, bottomParams);
setContentView(root);
updateCounter();
}
private TextView actionText(String text) {
TextView view = new TextView(this);
view.setText(text);
view.setTextColor(Color.WHITE);
view.setTextSize(14f);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(0x33000000);
return view;
}
private TextView pillText(String text) {
TextView view = new TextView(this);
view.setText(text);
view.setTextColor(Color.WHITE);
view.setTextSize(14f);
view.setGravity(Gravity.CENTER);
view.setPadding(dp(16), 0, dp(16), 0);
android.graphics.drawable.GradientDrawable background = new android.graphics.drawable.GradientDrawable();
background.setShape(android.graphics.drawable.GradientDrawable.RECTANGLE);
background.setCornerRadius(dp(20));
background.setColor(0x66000000);
view.setBackground(background);
return view;
}
// ---------- 相机 ----------
private void startCamera() {
ListenableFuture<ProcessCameraProvider> future = ProcessCameraProvider.getInstance(this);
future.addListener(() -> {
try {
cameraProvider = future.get();
bindUseCases();
} catch (Exception error) {
finishWithMessage("相机初始化失败");
}
}, ContextCompat.getMainExecutor(this));
}
private void bindUseCases() {
if (cameraProvider == null) {
return;
}
CameraSelector selector = facingFront
? CameraSelector.DEFAULT_FRONT_CAMERA
: CameraSelector.DEFAULT_BACK_CAMERA;
try {
if (!cameraProvider.hasCamera(selector)) {
selector = CameraSelector.DEFAULT_BACK_CAMERA;
facingFront = false;
}
} catch (Exception error) {
// 查询相机信息失败时退回后置,不能直接崩
selector = CameraSelector.DEFAULT_BACK_CAMERA;
facingFront = false;
}
Preview preview = new Preview.Builder().build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
cameraProvider.unbindAll();
if (MODE_SCAN.equals(mode)) {
ImageAnalysis analysis = new ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
.setTargetResolution(new Size(1280, 720))
.build();
analysis.setAnalyzer(decodeExecutor, this::analyze);
camera = cameraProvider.bindToLifecycle(this, selector, preview, analysis);
} else {
imageCapture = new ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.setFlashMode(flashOn ? ImageCapture.FLASH_MODE_ON : ImageCapture.FLASH_MODE_OFF)
.build();
camera = cameraProvider.bindToLifecycle(this, selector, preview, imageCapture);
}
if (torchOn) {
applyTorch(true);
}
}
// ---------- 扫码 ----------
private void analyze(ImageProxy imageProxy) {
if (!decoding.compareAndSet(false, true)) {
imageProxy.close();
return;
}
try {
int width = imageProxy.getWidth();
int height = imageProxy.getHeight();
byte[] data = yuvToLuminance(imageProxy, width, height);
if (data == null) {
return;
}
int rotation = imageProxy.getImageInfo().getRotationDegrees();
if (90 == rotation || 270 == rotation) {
data = rotate90(data, width, height, 270 == rotation);
int swap = width;
width = height;
height = swap;
} else if (180 == rotation) {
data = rotate180(data, width, height);
}
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(
data,
width,
height,
0,
0,
width,
height,
false
);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap, hints);
if (result != null && result.getText() != null && !result.getText().isEmpty()) {
runOnUiThread(() -> onDecoded(result.getText(), result.getBarcodeFormat()));
}
} catch (NotFoundException ignored) {
// 大多数帧都不会命中,这是正常路径
} catch (Exception ignored) {
// 单帧解码失败不影响后续帧
} finally {
decoding.set(false);
imageProxy.close();
}
}
private void onDecoded(String text, BarcodeFormat format) {
vibrate();
lastText = text;
lastFormat = format == null ? "" : format.name();
if (continuous) {
hintView.setText("已识别:" + text);
return;
}
finishWithScan();
}
private void finishWithScan() {
Intent data = new Intent();
data.putExtra(RESULT_TEXT, lastText == null ? "" : lastText);
data.putExtra(RESULT_FORMAT, lastFormat == null ? "" : lastFormat);
setResult(RESULT_OK, data);
finish();
}
private void pickFromGallery() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(intent, REQUEST_GALLERY);
} catch (Exception error) {
hintView.setText("无法打开相册");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_GALLERY != requestCode || RESULT_OK != resultCode || data == null) {
return;
}
Uri uri = data.getData();
if (uri == null) {
return;
}
decodeFromUri(uri);
}
private void decodeFromUri(Uri uri) {
decodeExecutor.execute(() -> {
Bitmap bitmap = null;
try (InputStream input = getContentResolver().openInputStream(uri)) {
bitmap = BitmapFactory.decodeStream(input);
if (bitmap == null) {
showHint("图片读取失败");
return;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
Result result = reader.decode(new BinaryBitmap(new HybridBinarizer(source)), hints);
if (result != null && result.getText() != null && !result.getText().isEmpty()) {
runOnUiThread(() -> onDecoded(result.getText(), result.getBarcodeFormat()));
return;
}
showHint("图片里没有识别到条码");
} catch (Exception error) {
showHint("图片识别失败");
} finally {
if (bitmap != null) {
bitmap.recycle();
}
}
});
}
// ---------- 拍照 ----------
private void takePicture() {
if (imageCapture == null || capturing) {
return;
}
capturing = true;
String name = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.US).format(System.currentTimeMillis()) + ".jpg";
File file = new File(outputDir, name);
ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(file).build();
imageCapture.takePicture(options, ContextCompat.getMainExecutor(this), new ImageCapture.OnImageSavedCallback() {
@Override
public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
capturing = false;
capturedPaths.add(file.getAbsolutePath());
vibrate();
updateCounter();
if (!multiple || maxCount <= capturedPaths.size()) {
finishWithFiles();
}
}
@Override
public void onError(@NonNull ImageCaptureException exception) {
capturing = false;
hintView.setText("拍照失败:" + exception.getMessage());
}
});
}
private void finishWithFiles() {
Intent data = new Intent();
data.putStringArrayListExtra(RESULT_FILES, new ArrayList<>(capturedPaths));
setResult(RESULT_OK, data);
finish();
}
private void updateCounter() {
if (counterView == null) {
return;
}
if (!multiple) {
counterView.setVisibility(View.GONE);
return;
}
counterView.setVisibility(View.VISIBLE);
counterView.setText(String.format(Locale.US, "已拍 %d / %d", capturedPaths.size(), maxCount));
}
// ---------- 手电筒 ----------
private void toggleTorch() {
applyTorch(!torchOn);
}
private void applyTorch(boolean enabled) {
if (camera == null) {
return;
}
try {
camera.getCameraControl().enableTorch(enabled);
torchOn = enabled;
updateTorchLabel();
} catch (Exception error) {
hintView.setText("手电筒不可用");
}
}
private void updateTorchLabel() {
if (torchButton != null) {
torchButton.setText(torchOn ? "关灯" : "手电筒");
}
}
// ---------- 生命周期 ----------
private void registerBackHandler() {
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
handleClose();
}
});
}
private void handleClose() {
if (MODE_SCAN.equals(mode) && continuous && lastText != null) {
finishWithScan();
return;
}
setResult(RESULT_CANCELED);
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
decoding.set(true);
decodeExecutor.shutdownNow();
if (cameraProvider != null) {
cameraProvider.unbindAll();
}
}
// ---------- 工具 ----------
private void finishWithMessage(String message) {
hintView.setText(message);
setResult(RESULT_CANCELED);
finish();
}
private void showHint(String message) {
runOnUiThread(() -> {
if (hintView != null) {
hintView.setText(message);
}
});
}
private void vibrate() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (vibrator != null && vibrator.hasVibrator()) {
vibrator.vibrate(VibrationEffect.createOneShot(40, VibrationEffect.DEFAULT_AMPLITUDE));
}
}
private int dp(float value) {
return Math.round(value * getResources().getDisplayMetrics().density);
}
private Map<DecodeHintType, Object> buildHints() {
List<BarcodeFormat> formats = new ArrayList<>();
ArrayList<String> requested = getIntent().getStringArrayListExtra(EXTRA_FORMATS);
if (requested == null || requested.isEmpty()) {
requested = new ArrayList<>(java.util.Arrays.asList(DEFAULT_FORMATS));
}
for (String name : requested) {
BarcodeFormat format = toFormat(name);
if (format != null) {
formats.add(format);
}
}
if (formats.isEmpty()) {
formats.add(BarcodeFormat.QR_CODE);
}
Map<DecodeHintType, Object> result = new EnumMap<>(DecodeHintType.class);
result.put(DecodeHintType.POSSIBLE_FORMATS, formats);
result.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
return result;
}
private static BarcodeFormat toFormat(String name) {
if (name == null) {
return null;
}
switch (name) {
case "QR_CODE":
return BarcodeFormat.QR_CODE;
case "CODE_128":
return BarcodeFormat.CODE_128;
case "CODE_39":
return BarcodeFormat.CODE_39;
case "EAN_13":
return BarcodeFormat.EAN_13;
case "EAN_8":
return BarcodeFormat.EAN_8;
case "UPC_A":
return BarcodeFormat.UPC_A;
case "ITF":
return BarcodeFormat.ITF;
case "DATA_MATRIX":
return BarcodeFormat.DATA_MATRIX;
case "PDF_417":
return BarcodeFormat.PDF_417;
default:
return null;
}
}
/** 只取 Y plane,按 rowStride 逐行拷贝,交给 zxing 当灰度图 */
private static byte[] yuvToLuminance(ImageProxy imageProxy, int width, int height) {
ImageProxy.PlaneProxy plane = imageProxy.getPlanes()[0];
ByteBuffer buffer = plane.getBuffer();
int rowStride = plane.getRowStride();
int pixelStride = plane.getPixelStride();
byte[] data = new byte[width * height];
if (1 == pixelStride && rowStride == width) {
buffer.get(data, 0, data.length);
return data;
}
int offset = 0;
for (int row = 0; row < height; row++) {
int position = row * rowStride;
if (buffer.limit() < position + width) {
break;
}
buffer.position(position);
buffer.get(data, offset, width);
offset += width;
}
return data;
}
private static byte[] rotate90(byte[] data, int width, int height, boolean counterClockwise) {
byte[] rotated = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (counterClockwise) {
rotated[(width - 1 - x) * height + y] = data[y * width + x];
} else {
rotated[x * height + (height - 1 - y)] = data[y * width + x];
}
}
}
return rotated;
}
private static byte[] rotate180(byte[] data, int width, int height) {
byte[] rotated = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
rotated[(height - 1 - y) * width + (width - 1 - x)] = data[y * width + x];
}
}
return rotated;
}
/** 扫码取景框:半透明遮罩 + 四角高亮 */
private static final class FrameOverlay extends View {
private final Paint dimPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint cornerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final RectF frame = new RectF();
private final float density;
FrameOverlay(android.content.Context context) {
super(context);
density = context.getResources().getDisplayMetrics().density;
dimPaint.setColor(0x66000000);
cornerPaint.setColor(0xFF22C55E);
cornerPaint.setStyle(Paint.Style.STROKE);
cornerPaint.setStrokeWidth(3 * density);
cornerPaint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float size = Math.min(getWidth(), getHeight()) * 0.72f;
float left = (getWidth() - size) / 2f;
float top = (getHeight() - size) / 2f;
frame.set(left, top, left + size, top + size);
// 四周压暗,中间保持透明
canvas.drawRect(0, 0, getWidth(), frame.top, dimPaint);
canvas.drawRect(0, frame.bottom, getWidth(), getHeight(), dimPaint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom, dimPaint);
canvas.drawRect(frame.right, frame.top, getWidth(), frame.bottom, dimPaint);
float length = size * 0.14f;
// 左上
canvas.drawLine(frame.left, frame.top, frame.left + length, frame.top, cornerPaint);
canvas.drawLine(frame.left, frame.top, frame.left, frame.top + length, cornerPaint);
// 右上
canvas.drawLine(frame.right - length, frame.top, frame.right, frame.top, cornerPaint);
canvas.drawLine(frame.right, frame.top, frame.right, frame.top + length, cornerPaint);
// 左下
canvas.drawLine(frame.left, frame.bottom - length, frame.left, frame.bottom, cornerPaint);
canvas.drawLine(frame.left, frame.bottom, frame.left + length, frame.bottom, cornerPaint);
// 右下
canvas.drawLine(frame.right - length, frame.bottom, frame.right, frame.bottom, cornerPaint);
canvas.drawLine(frame.right, frame.bottom - length, frame.right, frame.bottom, cornerPaint);
}
}
}
@@ -0,0 +1,83 @@
package com.imyeyu.gao.customer.nativekit;
/**
* 能力名常量。
*
* <p>前端通过 {@code getInfo().capabilities} 判断某项能力是否存在,不要靠猜测或 try-catch。
* 这里的常量与 {@link NativeKitPlugin#getInfo} 的返回值必须保持一致,新增能力只改这一处。
*/
public final class Capabilities {
/** 原生扫码 */
public static final String SCAN = "scan";
/** 原生拍照 */
public static final String CAPTURE = "capture";
/** 通用下载器 */
public static final String DOWNLOAD = "download";
/** 系统分享 */
public static final String SHARE = "share";
/** 系统打印 */
public static final String PRINT = "print";
/** 本地通知调度 */
public static final String NOTIFY_SCHEDULE = "notify.schedule";
/** 已排程任务查询与按归属清理 */
public static final String NOTIFY_LIST = "notify.list";
/** 通知权限查询与申请 */
public static final String NOTIFY_PERMISSION = "notify.permission";
/** 精确闹钟授权状态 */
public static final String NOTIFY_EXACT = "notify.exact";
/** 语音输入 */
public static final String VOICE = "voice";
/** 生物识别 */
public static final String BIOMETRIC = "biometric";
/** 加密会话存储 */
public static final String SESSION = "session";
/** 蓝牙 ESC/POS 打印 */
public static final String BT_PRINT = "btPrint";
/** SAF 文件选择与另存 */
public static final String SAF = "saf";
/** 系统日历日程写入 */
public static final String CALENDAR = "calendar";
/** 前台/后台状态事件 */
public static final String APP_STATE = "app.state";
/** 网络状态查询与事件 */
public static final String APP_NETWORK = "app.network";
/** 权限状态查询与系统设置跳转 */
public static final String APP_PERMISSION = "app.permission";
/** 设备标识、响铃模式、常亮、方向、重启、清缓存 */
public static final String APP_DEVICE = "app.device";
/** 通讯录批量写入 */
public static final String CONTACTS = "contacts";
/** 震动、剪贴板、设备信息 */
public static final String MISC = "misc";
private Capabilities() {
}
/** 当前壳支持的全部能力 */
public static String[] all() {
return new String[] {
SCAN,
CAPTURE,
DOWNLOAD,
SHARE,
PRINT,
NOTIFY_SCHEDULE,
NOTIFY_LIST,
NOTIFY_PERMISSION,
NOTIFY_EXACT,
VOICE,
BIOMETRIC,
SESSION,
BT_PRINT,
SAF,
CALENDAR,
APP_STATE,
APP_NETWORK,
APP_PERMISSION,
APP_DEVICE,
CONTACTS,
MISC
};
}
}
@@ -0,0 +1,388 @@
package com.imyeyu.gao.customer.nativekit;
import android.Manifest;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import androidx.core.content.ContextCompat;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import com.getcapacitor.PluginCall;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 通讯录批量写入。
*
* <p>存在的意义只有一个:让系统语音助手和来电识别能拿到客户姓名与号码。
* 业务数据永远在 App 里,助手读不到。
*
* <p>业务 ID 存在自定义 MIMETYPE 的 Data 行里,不占姓名、备注、昵称任何可见字段,
* 通讯录界面不会显示这一行。靠它做增量更新与删除,而不是靠姓名匹配 —— 改名就失效。
*/
final class ContactsHelper {
/** 自定义 mimetype,通讯录 App 不认识,因此不会渲染 */
private static final String PROFILE_MIMETYPE = "vnd.android.cursor.item/com.imyeyu.gao.customer.profile";
private static final String DEFAULT_GROUP = "GaoCustomer";
private static final int BATCH_SIZE = 100;
private static final String SAFE_PHONE = "[+\\d][\\d\\-\\s]{4,24}";
private ContactsHelper() {
}
// ---------- 探测 ----------
static void available(Context context, PluginCall call) {
JSObject result = new JSObject();
boolean granted = hasPermission(context);
result.put("hasPermission", granted);
result.put("canWrite", granted);
result.put("total", granted ? countOwned(context, null) : 0);
call.resolve(result);
}
// ---------- 单条 ----------
static void add(Context context, PluginCall call) {
String name = call.getString("name");
String phone = call.getString("phone");
if (name == null || name.trim().isEmpty() || phone == null || !phone.matches(SAFE_PHONE)) {
call.reject("姓名或手机号不合法", "invalid_argument");
return;
}
String businessId = call.getString("businessId", "");
String group = normalizeGroup(call.getString("groupTag"));
String note = call.getString("note");
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
int rawIndex = operations.size();
operations.add(newRawContactOperation());
operations.add(buildNameOperation(rawIndex, name.trim()));
operations.add(buildPhoneOperation(rawIndex, phone.trim()));
operations.add(buildProfileOperation(rawIndex, businessId, group));
if (note != null && !note.isEmpty()) {
operations.add(buildNoteOperation(rawIndex, note));
}
try {
android.content.ContentProviderResult[] results = context
.getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, operations);
long rawContactId = results[0].uri == null ? 0 : ContentUris.parseId(results[0].uri);
JSObject result = new JSObject();
result.put("rawContactId", rawContactId);
call.resolve(result);
} catch (Exception error) {
call.reject("写入通讯录失败:" + error.getMessage(), "insert_failed");
}
}
// ---------- 批量同步 ----------
/**
* 批量幂等同步。
*
* <p>以 businessId 为准做差集:没有的插入、变了且更新、多出来的删除。
* 同一个 groupTag 下的历史数据会被完整对齐,不会残留脏号码。
*/
static void sync(Context context, PluginCall call) {
JSArray items = call.getArray("items");
if (items == null) {
call.reject("缺少 items", "invalid_argument");
return;
}
String group = normalizeGroup(call.getString("groupTag"));
Map<String, Long> existing = queryOwned(context, group);
List<Item> toInsert = new ArrayList<>();
List<Item> toUpdate = new ArrayList<>();
Set<String> incoming = new HashSet<>();
for (int index = 0; index < items.length(); index++) {
org.json.JSONObject raw = items.optJSONObject(index);
if (raw == null) {
continue;
}
String name = raw.optString("name", null);
String phone = raw.optString("phone", null);
String businessId = raw.optString("id", null);
if (businessId == null || businessId.isEmpty() || name == null || name.trim().isEmpty()) {
continue;
}
if (phone == null || !phone.matches(SAFE_PHONE)) {
continue;
}
incoming.add(businessId);
Item item = new Item();
item.businessId = businessId;
item.name = name.trim();
item.phone = phone.trim();
item.note = raw.optString("note", null);
Long rawContactId = existing.get(businessId);
if (rawContactId == null) {
toInsert.add(item);
} else {
item.rawContactId = rawContactId;
toUpdate.add(item);
}
}
List<Long> toDelete = new ArrayList<>();
for (Map.Entry<String, Long> entry : existing.entrySet()) {
if (!incoming.contains(entry.getKey())) {
toDelete.add(entry.getValue());
}
}
int inserted = 0;
int updated = 0;
int deleted = 0;
try {
ContentResolver resolver = context.getContentResolver();
deleted = deleteRawContacts(resolver, toDelete);
updated = updateContacts(context, toUpdate);
inserted = insertContacts(context, toInsert, group);
} catch (Exception error) {
call.reject("同步通讯录失败:" + error.getMessage(), "sync_failed");
return;
}
JSObject result = new JSObject();
result.put("inserted", inserted);
result.put("updated", updated);
result.put("deleted", deleted);
result.put("total", countOwned(context, group));
call.resolve(result);
}
static void clear(Context context, PluginCall call) {
String group = call.getString("groupTag") == null ? null : normalizeGroup(call.getString("groupTag"));
Map<String, Long> existing = queryOwned(context, group);
try {
int deleted = deleteRawContacts(context.getContentResolver(), new ArrayList<>(existing.values()));
JSObject result = new JSObject();
result.put("deleted", deleted);
call.resolve(result);
} catch (Exception error) {
call.reject("清除通讯录失败:" + error.getMessage(), "delete_failed");
}
}
// ---------- 内部 ----------
private static int insertContacts(Context context, List<Item> items, String group) throws Exception {
if (items.isEmpty()) {
return 0;
}
ContentResolver resolver = context.getContentResolver();
int inserted = 0;
for (int offset = 0; offset < items.size(); offset += BATCH_SIZE) {
List<Item> slice = items.subList(offset, Math.min(offset + BATCH_SIZE, items.size()));
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
for (Item item : slice) {
int rawIndex = operations.size();
operations.add(newRawContactOperation());
operations.add(buildNameOperation(rawIndex, item.name));
operations.add(buildPhoneOperation(rawIndex, item.phone));
operations.add(buildProfileOperation(rawIndex, item.businessId, group));
if (item.note != null && !item.note.isEmpty()) {
operations.add(buildNoteOperation(rawIndex, item.note));
}
}
resolver.applyBatch(ContactsContract.AUTHORITY, operations);
inserted += slice.size();
}
return inserted;
}
private static int updateContacts(Context context, List<Item> items) throws Exception {
if (items.isEmpty()) {
return 0;
}
ContentResolver resolver = context.getContentResolver();
int updated = 0;
for (int offset = 0; offset < items.size(); offset += BATCH_SIZE) {
List<Item> slice = items.subList(offset, Math.min(offset + BATCH_SIZE, items.size()));
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
for (Item item : slice) {
String rawId = String.valueOf(item.rawContactId);
operations.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] { rawId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }
)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, item.name)
.build());
operations.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] { rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }
)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, item.phone)
.build());
}
resolver.applyBatch(ContactsContract.AUTHORITY, operations);
updated += slice.size();
}
return updated;
}
private static int deleteRawContacts(ContentResolver resolver, List<Long> rawContactIds) throws Exception {
if (rawContactIds.isEmpty()) {
return 0;
}
int deleted = 0;
for (int offset = 0; offset < rawContactIds.size(); offset += BATCH_SIZE) {
List<Long> slice = rawContactIds.subList(offset, Math.min(offset + BATCH_SIZE, rawContactIds.size()));
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
for (Long rawContactId : slice) {
operations.add(ContentProviderOperation.newDelete(
ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId)
).build());
}
resolver.applyBatch(ContactsContract.AUTHORITY, operations);
deleted += slice.size();
}
return deleted;
}
/**
* 新建 RawContact。
*
* <p>ACCOUNT_TYPE / ACCOUNT_NAME 必须显式写 null:不写和写 null 在 AOSP 上等价,
* 但部分 ROM 的 ContactsProvider 会因此拒绝插入或归到奇怪的账户下。
*/
private static ContentProviderOperation newRawContactOperation() {
return ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build();
}
private static ContentProviderOperation buildNameOperation(int rawIndex, String name) {
return ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawIndex)
.withValue(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
.build();
}
private static ContentProviderOperation buildPhoneOperation(int rawIndex, String phone) {
return ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
.build();
}
private static ContentProviderOperation buildProfileOperation(int rawIndex, String businessId, String group) {
return ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawIndex)
.withValue(ContactsContract.Data.MIMETYPE, PROFILE_MIMETYPE)
.withValue(ContactsContract.Data.DATA1, businessId)
.withValue(ContactsContract.Data.DATA2, group)
.build();
}
private static ContentProviderOperation buildNoteOperation(int rawIndex, String note) {
return ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, note)
.build();
}
/** 查出本 App 写入的联系人:businessId -> rawContactId */
private static Map<String, Long> queryOwned(Context context, String group) {
Map<String, Long> result = new HashMap<>();
String[] projection = {
ContactsContract.Data.RAW_CONTACT_ID,
ContactsContract.Data.DATA1
};
String selection = ContactsContract.Data.MIMETYPE + "=?";
List<String> args = new ArrayList<>();
args.add(PROFILE_MIMETYPE);
if (group != null) {
selection += " AND " + ContactsContract.Data.DATA2 + "=?";
args.add(group);
}
try (Cursor cursor = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
projection,
selection,
args.toArray(new String[0]),
null
)) {
if (cursor == null) {
return result;
}
while (cursor.moveToNext()) {
String businessId = cursor.getString(1);
if (businessId != null && !businessId.isEmpty()) {
result.put(businessId, cursor.getLong(0));
}
}
} catch (Exception ignored) {
// 读取失败按空处理,下次同步会重来
}
return result;
}
private static int countOwned(Context context, String group) {
return queryOwned(context, group).size();
}
private static boolean hasPermission(Context context) {
return ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
== PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS)
== PackageManager.PERMISSION_GRANTED;
}
private static String normalizeGroup(String group) {
if (group == null || group.trim().isEmpty()) {
return DEFAULT_GROUP;
}
// DATA2 只用来分组,限制长度避免异常输入撑爆字段
String trimmed = group.trim();
return 40 < trimmed.length() ? trimmed.substring(0, 40) : trimmed;
}
private static final class Item {
String businessId;
String name;
String phone;
String note;
long rawContactId;
}
}
@@ -0,0 +1,217 @@
package com.imyeyu.gao.customer.nativekit;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import androidx.core.content.ContextCompat;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 通用下载器。
*
* <p>WebView 里的 {@code a[download]} 对跨域地址无效,数据导出的 ZIP 在 App 内要么跳到系统浏览器
* 要么静默失败。这里走系统 DownloadManager:断点续传、通知栏进度、断电重连都由系统负责。
*
* <p>下载完成后额外复制一份到 cache,返回 {@code file://} 路径 —— Downloads 里的文件不在
* FileProvider 放行范围内,直接分享或打印会失败。
*/
final class DownloadHelper {
private static final long TIMEOUT_MS = 10 * 60 * 1000L;
private static final String CACHE_DIR = "nativekit-download";
private static final String DEFAULT_SUB_DIR = "GaoCustomer";
private static final String SAFE_NAME = "[\\w.\\-]{1,120}";
private DownloadHelper() {
}
static void download(Plugin plugin, PluginCall call) {
Context context = plugin.getContext();
String url = call.getString("url");
String fileName = call.getString("fileName");
String subDir = call.getString("subDir", DEFAULT_SUB_DIR);
boolean showNotification = !Boolean.FALSE.equals(call.getBoolean("notify", true));
if (url == null || !(url.startsWith("https://") || url.startsWith("http://"))) {
call.reject("下载地址必须是 http 或 https", "invalid_argument");
return;
}
if (fileName == null || !fileName.matches(SAFE_NAME)) {
call.reject("文件名不合法", "invalid_argument");
return;
}
if (subDir == null || !subDir.matches(SAFE_NAME)) {
call.reject("子目录名不合法", "invalid_argument");
return;
}
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
if (manager == null) {
call.reject("下载服务不可用", "service_unavailable");
return;
}
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(fileName);
request.setDescription(subDir);
request.setAllowedOverMetered(true);
request.setAllowedOverRoaming(false);
request.setNotificationVisibility(
showNotification
? DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
: DownloadManager.Request.VISIBILITY_HIDDEN
);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
subDir + "/" + fileName
);
long downloadId;
try {
downloadId = manager.enqueue(request);
} catch (Exception error) {
call.reject("无法发起下载:" + error.getMessage(), "enqueue_failed");
return;
}
Handler handler = new Handler(Looper.getMainLooper());
final BroadcastReceiver[] holder = new BroadcastReceiver[1];
final boolean[] settled = new boolean[1];
Runnable timeout = () -> {
if (settled[0]) {
return;
}
settled[0] = true;
unregister(context, holder[0]);
call.reject("下载超时", "timeout");
};
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context receiverContext, Intent intent) {
if (intent == null) {
return;
}
long completed = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (completed != downloadId || settled[0]) {
return;
}
settled[0] = true;
handler.removeCallbacks(timeout);
unregister(receiverContext, holder[0]);
resolveResult(call, manager, downloadId, fileName, context);
}
};
holder[0] = receiver;
ContextCompat.registerReceiver(
context,
receiver,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE),
ContextCompat.RECEIVER_EXPORTED
);
handler.postDelayed(timeout, TIMEOUT_MS);
}
private static void resolveResult(
PluginCall call,
DownloadManager manager,
long downloadId,
String fileName,
Context context
) {
DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
long size = 0;
int status = DownloadManager.STATUS_FAILED;
String reason = "";
try (Cursor cursor = manager.query(query)) {
if (cursor != null && cursor.moveToFirst()) {
status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
size = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
reason = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON));
}
} catch (Exception error) {
call.reject("无法读取下载结果", "query_failed");
return;
}
if (status != DownloadManager.STATUS_SUCCESSFUL) {
call.reject("下载失败,状态 " + status + ",原因 " + reason, "download_failed");
return;
}
File cached = copyToCache(context, manager, downloadId, fileName);
JSObject result = new JSObject();
result.put("name", fileName);
result.put("size", 0 < size ? size : (cached == null ? 0 : cached.length()));
result.put("path", cached == null ? "" : "file://" + cached.getAbsolutePath());
result.put("uri", String.valueOf(manager.getUriForDownloadedFile(downloadId)));
call.resolve(result);
}
/**
* 复制到 cache。
*
* <p>不能用 {@code Environment.getExternalStoragePublicDirectory()} 拼绝对路径去读:
* Android 10 起 Downloads 属于分区存储,直接 {@code FileInputStream} 会失败。
* {@code openDownloadedFile} 拿 ParcelFileDescriptor 是官方通道,各版本都通。
*/
private static File copyToCache(Context context, DownloadManager manager, long downloadId, String fileName) {
File directory = new File(context.getCacheDir(), CACHE_DIR);
if (!directory.exists() && !directory.mkdirs()) {
return null;
}
File target = new File(directory, fileName);
try (ParcelFileDescriptor descriptor = manager.openDownloadedFile(downloadId)) {
if (descriptor == null) {
return null;
}
try (InputStream input = new FileInputStream(descriptor.getFileDescriptor());
OutputStream output = new FileOutputStream(target)) {
byte[] buffer = new byte[32768];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
return target;
}
} catch (Exception error) {
// 复制失败不算致命,前端还能拿 content:// 走系统分享
target.delete();
return null;
}
}
private static void unregister(Context context, BroadcastReceiver receiver) {
if (receiver == null) {
return;
}
try {
context.unregisterReceiver(receiver);
} catch (Exception ignored) {
// 已注销或进程重建,忽略
}
}
}
@@ -0,0 +1,84 @@
package com.imyeyu.gao.customer.nativekit;
import android.content.Context;
import android.webkit.MimeTypeMap;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import java.io.File;
import java.util.List;
import java.util.Locale;
/**
* 相机、SAF 等能力共用的文件信息结构。
*
* <p>返回给 Web 的路径统一是 {@code file://} 形式,前端需经 {@code Capacitor.convertFileSrc()}
* 才能放进 img/fetch 使用。
*/
final class MediaInfo {
private MediaInfo() {
}
/** 把绝对路径列表组装成 { files: [...] } */
static JSObject buildFiles(Context context, List<String> paths) {
JSArray files = new JSArray();
if (paths != null) {
for (String path : paths) {
if (path == null || path.isEmpty()) {
continue;
}
File file = new File(stripScheme(path));
if (!file.exists()) {
continue;
}
JSObject item = new JSObject();
item.put("path", "file://" + file.getAbsolutePath());
item.put("name", file.getName());
item.put("size", file.length());
item.put("mimeType", guessMimeType(file.getName()));
files.put(item);
}
}
JSObject result = new JSObject();
result.put("files", files);
return result;
}
/** 单个文件的描述 */
static JSObject buildFile(String path) {
File file = new File(stripScheme(path));
JSObject item = new JSObject();
item.put("path", "file://" + file.getAbsolutePath());
item.put("name", file.getName());
item.put("size", file.length());
item.put("mimeType", guessMimeType(file.getName()));
return item;
}
static String stripScheme(String path) {
if (path.startsWith("file://")) {
return path.substring("file://".length());
}
return path;
}
static String guessMimeType(String fileName) {
int dot = fileName.lastIndexOf('.');
if (0 < dot) {
String extension = fileName.substring(dot + 1).toLowerCase(Locale.ROOT);
String guess = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (guess != null) {
return guess;
}
if ("jpg".equals(extension) || "jpeg".equals(extension)) {
return "image/jpeg";
}
if ("pdf".equals(extension)) {
return "application/pdf";
}
}
return "application/octet-stream";
}
}
@@ -0,0 +1,929 @@
package com.imyeyu.gao.customer.nativekit;
import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.VibratorManager;
import android.provider.Settings;
import android.webkit.WebSettings;
import androidx.activity.result.ActivityResult;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import com.getcapacitor.PermissionState;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.ActivityCallback;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.annotation.Permission;
import com.getcapacitor.annotation.PermissionCallback;
import com.imyeyu.gao.customer.MainActivity;
import java.util.ArrayList;
import java.util.List;
/**
* 原生能力网关。
*
* <p>所有能力收在一个插件下,避免为每个小功能单独注册插件。前端通过 {@link #getInfo()}
* 拿能力表做降级判断,不要靠 try-catch 猜。
*
* <p>约定:方法失败时 {@code reject(message, code)},成功时 {@code resolve(JSObject)}。
*/
@CapacitorPlugin(
name = "NativeKit",
permissions = {
@Permission(alias = "camera", strings = { Manifest.permission.CAMERA }),
@Permission(alias = "microphone", strings = { Manifest.permission.RECORD_AUDIO }),
@Permission(alias = "notifications", strings = { Manifest.permission.POST_NOTIFICATIONS }),
@Permission(
alias = "calendar",
strings = { Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR }
),
@Permission(
alias = "contacts",
strings = { Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS }
),
@Permission(
alias = "bluetooth",
strings = { Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN }
)
}
)
public class NativeKitPlugin extends Plugin {
/** 通知点击后待消费的路由,键名与 MainActivity 共用 */
public static final String PREFS = "nativekit";
public static final String KEY_LAUNCH_ROUTE = "launch_route";
private NotificationScheduler notificationScheduler;
private VoiceInput voiceInput;
private SystemHelper systemHelper;
@Override
public void load() {
notificationScheduler = new NotificationScheduler(getContext());
voiceInput = new VoiceInput(this);
systemHelper = new SystemHelper(this);
systemHelper.start();
NotificationScheduler.ensureChannels(getContext());
}
@Override
protected void handleOnDestroy() {
if (voiceInput != null) {
voiceInput.release();
}
if (systemHelper != null) {
systemHelper.stop();
}
}
/** 供内部 helper 派发事件,notifyListeners 是 protected */
void emit(String event, JSObject payload) {
notifyListeners(event, payload);
}
// ---------- 能力协商 ----------
@PluginMethod
public void getInfo(PluginCall call) {
call.resolve(buildInfo(getContext()));
}
/** 供插件与 MainActivity 共用,避免两处各写一份 */
public static JSObject buildInfo(Context context) {
JSObject info = new JSObject();
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
info.put("versionCode", Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
? packageInfo.getLongVersionCode()
: packageInfo.versionCode);
info.put("versionName", packageInfo.versionName == null ? "" : packageInfo.versionName);
} catch (Exception error) {
info.put("versionCode", 0);
info.put("versionName", "");
}
info.put("packageName", context.getPackageName());
info.put("sdkInt", Build.VERSION.SDK_INT);
info.put("webViewVersion", resolveWebViewVersion(context));
info.put("capabilities", JSArray.from(Capabilities.all()));
return info;
}
/**
* 冷启动时取走通知带来的路由。
*
* <p>取走即清除,避免下次冷启动重复跳转。
*/
@PluginMethod
public void getLaunchRoute(PluginCall call) {
SharedPreferences preferences = getContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
String route = preferences.getString(KEY_LAUNCH_ROUTE, null);
if (route != null) {
preferences.edit().remove(KEY_LAUNCH_ROUTE).apply();
}
JSObject result = new JSObject();
result.put("route", route == null ? JSObject.NULL : route);
call.resolve(result);
}
// ---------- 扫码 ----------
@PluginMethod
public void scan(PluginCall call) {
if (getPermissionState("camera") != PermissionState.GRANTED) {
requestPermissionForAlias("camera", call, "scanWithPermission");
return;
}
startScan(call);
}
@PermissionCallback
private void scanWithPermission(PluginCall call) {
if (getPermissionState("camera") != PermissionState.GRANTED) {
call.reject("未授予相机权限", "permission_denied");
return;
}
startScan(call);
}
private void startScan(PluginCall call) {
Intent intent = new Intent(getContext(), CameraKitActivity.class);
intent.putExtra(CameraKitActivity.EXTRA_MODE, CameraKitActivity.MODE_SCAN);
intent.putExtra(CameraKitActivity.EXTRA_TORCH, Boolean.TRUE.equals(call.getBoolean("torch", false)));
intent.putExtra(
CameraKitActivity.EXTRA_CONTINUOUS,
Boolean.TRUE.equals(call.getBoolean("continuous", false))
);
JSArray formats = call.getArray("formats");
if (formats != null && formats.length() != 0) {
intent.putStringArrayListExtra(
CameraKitActivity.EXTRA_FORMATS,
new ArrayList<>(toStringList(formats))
);
}
startActivityForResult(call, intent, "scanResult");
}
@ActivityCallback
private void scanResult(PluginCall call, ActivityResult result) {
if (call == null) {
return;
}
if (result.getResultCode() != android.app.Activity.RESULT_OK) {
call.reject("已取消扫码", "cancelled");
return;
}
Intent data = result.getData();
JSObject payload = new JSObject();
payload.put("text", data == null ? "" : safeString(data.getStringExtra(CameraKitActivity.RESULT_TEXT)));
payload.put("format", data == null ? "" : safeString(data.getStringExtra(CameraKitActivity.RESULT_FORMAT)));
call.resolve(payload);
}
// ---------- 拍照 ----------
@PluginMethod
public void capture(PluginCall call) {
if (getPermissionState("camera") != PermissionState.GRANTED) {
requestPermissionForAlias("camera", call, "captureWithPermission");
return;
}
startCapture(call);
}
@PermissionCallback
private void captureWithPermission(PluginCall call) {
if (getPermissionState("camera") != PermissionState.GRANTED) {
call.reject("未授予相机权限", "permission_denied");
return;
}
startCapture(call);
}
private void startCapture(PluginCall call) {
Intent intent = new Intent(getContext(), CameraKitActivity.class);
intent.putExtra(CameraKitActivity.EXTRA_MODE, CameraKitActivity.MODE_CAPTURE);
intent.putExtra(
CameraKitActivity.EXTRA_MULTIPLE,
Boolean.TRUE.equals(call.getBoolean("multiple", false))
);
intent.putExtra(CameraKitActivity.EXTRA_MAX_COUNT, toInt(call.getInt("maxCount"), 9));
intent.putExtra(
CameraKitActivity.EXTRA_FACING,
"front".equals(call.getString("facing")) ? CameraKitActivity.FACING_FRONT : CameraKitActivity.FACING_BACK
);
intent.putExtra(CameraKitActivity.EXTRA_FLASH, Boolean.TRUE.equals(call.getBoolean("flash", false)));
startActivityForResult(call, intent, "captureResult");
}
@ActivityCallback
private void captureResult(PluginCall call, ActivityResult result) {
if (call == null) {
return;
}
if (result.getResultCode() != android.app.Activity.RESULT_OK) {
call.reject("已取消拍照", "cancelled");
return;
}
Intent data = result.getData();
ArrayList<String> paths = data == null
? new ArrayList<>()
: data.getStringArrayListExtra(CameraKitActivity.RESULT_FILES);
call.resolve(MediaInfo.buildFiles(getContext(), paths));
}
// ---------- 下载 ----------
@PluginMethod
public void download(PluginCall call) {
DownloadHelper.download(this, call);
}
// ---------- 分享 ----------
@PluginMethod
public void share(PluginCall call) {
String path = call.getString("path");
if (path == null || path.isEmpty()) {
call.reject("缺少文件路径", "invalid_argument");
return;
}
ShareHelper.share(getActivity(), call, path);
}
// ---------- 打印 ----------
@PluginMethod
public void print(PluginCall call) {
JSArray paths = call.getArray("paths");
if (paths == null || paths.length() == 0) {
call.reject("缺少待打印文件", "invalid_argument");
return;
}
PrintHelper.print(getActivity(), call, toStringList(paths), call.getString("jobName", "打印"));
}
// ---------- 本地通知 ----------
@PluginMethod
public void scheduleNotification(PluginCall call) {
notificationScheduler.schedule(call);
}
@PluginMethod
public void cancelNotification(PluginCall call) {
Integer id = call.getInt("id");
if (id == null) {
call.reject("缺少通知 id", "invalid_argument");
return;
}
notificationScheduler.cancel(id);
JSObject result = new JSObject();
result.put("id", id);
call.resolve(result);
}
@PluginMethod
public void cancelAllNotifications(PluginCall call) {
notificationScheduler.cancelAll(call.getString("owner"));
call.resolve();
}
/** 列出已排程的通知任务,用于诊断与共用设备上的账号隔离 */
@PluginMethod
public void listScheduledNotifications(PluginCall call) {
notificationScheduler.list(call);
}
@PluginMethod
public void getNotificationPermission(PluginCall call) {
JSObject result = new JSObject();
result.put("granted", NotificationScheduler.hasNotificationPermission(getContext()));
call.resolve(result);
}
/**
* 申请通知权限。
*
* <p>POST_NOTIFICATIONS 是 API 33 才引入的,低版本直接视为已授予,
* 不能走 @Permission 注解,否则在 Android 12 上会永远返回拒绝。
*/
@PluginMethod
public void requestNotificationPermission(PluginCall call) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
JSObject result = new JSObject();
result.put("granted", true);
call.resolve(result);
return;
}
if (NotificationScheduler.hasNotificationPermission(getContext())) {
JSObject result = new JSObject();
result.put("granted", true);
call.resolve(result);
return;
}
requestPermissionForAlias("notifications", call, "notificationPermissionResult");
}
@PermissionCallback
private void notificationPermissionResult(PluginCall call) {
JSObject result = new JSObject();
result.put("granted", NotificationScheduler.hasNotificationPermission(getContext()));
call.resolve(result);
}
@PluginMethod
public void canScheduleExactAlarms(PluginCall call) {
JSObject result = new JSObject();
result.put("granted", NotificationScheduler.canScheduleExactAlarms(getContext()));
call.resolve(result);
}
@PluginMethod
public void openExactAlarmSettings(PluginCall call) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
call.resolve();
return;
}
try {
Intent intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
intent.setData(Uri.parse("package:" + getContext().getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
call.resolve();
} catch (Exception error) {
call.reject("无法打开精确闹钟设置", "activity_not_found");
}
}
// ---------- 语音 ----------
@PluginMethod
public void voiceAvailable(PluginCall call) {
voiceInput.available(call);
}
@PluginMethod
public void voiceStart(PluginCall call) {
voiceInput.start(call);
}
@PluginMethod
public void voiceStop(PluginCall call) {
voiceInput.stop(call);
}
@PluginMethod
public void voiceCancel(PluginCall call) {
voiceInput.cancel(call);
}
/** 语音 Intent 通道的启动入口,VoiceInput 不持有 Activity 能力 */
void startVoiceIntent(PluginCall call, Intent intent) {
startActivityForResult(call, intent, "voiceIntentResult");
}
@PermissionCallback
private void voicePermissionResult(PluginCall call) {
voiceInput.onPermissionResult(call);
}
@ActivityCallback
private void voiceIntentResult(PluginCall call, ActivityResult result) {
voiceInput.onIntentResult(call, result);
}
/** 由 VoiceInput 回调,交给能力协商与权限流程使用 */
boolean hasMicrophonePermission() {
return getPermissionState("microphone") == PermissionState.GRANTED;
}
void requestMicrophonePermission(PluginCall call, String callbackName) {
requestPermissionForAlias("microphone", call, callbackName);
}
/** 语音 Intent 通道返回时压了一层 Activity,用它标记内部导航 */
void markInternalNavigation() {
MainActivity.markInternalNavigation();
}
void emitVoicePartial(String text) {
JSObject payload = new JSObject();
payload.put("text", text);
notifyListeners("voicePartial", payload);
}
void emitVoiceState(String state) {
JSObject payload = new JSObject();
payload.put("state", state);
notifyListeners("voiceState", payload);
}
// ---------- 生物识别与会话 ----------
@PluginMethod
public void biometricAvailable(PluginCall call) {
// BiometricPrompt 内部要操作 FragmentManager,必须在主线程
getActivity().runOnUiThread(() -> BiometricHelper.available(getActivity(), call));
}
@PluginMethod
public void biometricUnlock(PluginCall call) {
getActivity().runOnUiThread(() -> BiometricHelper.unlock(getActivity(), call));
}
@PluginMethod
public void saveSession(PluginCall call) {
String json = call.getString("json");
if (json == null) {
call.reject("缺少会话内容", "invalid_argument");
return;
}
SecureStore.saveSession(getContext(), json);
call.resolve();
}
@PluginMethod
public void readSession(PluginCall call) {
String json = SecureStore.readSession(getContext());
JSObject result = new JSObject();
result.put("json", json == null ? JSObject.NULL : json);
call.resolve(result);
}
@PluginMethod
public void clearSession(PluginCall call) {
SecureStore.clearSession(getContext());
call.resolve();
}
// ---------- 蓝牙打印 ----------
@PluginMethod
public void listPrinters(PluginCall call) {
if (!hasBluetoothPermission()) {
requestPermissionForAlias("bluetooth", call, "listPrintersWithPermission");
return;
}
BtPrinterHelper.list(getContext(), call);
}
@PermissionCallback
private void listPrintersWithPermission(PluginCall call) {
if (!hasBluetoothPermission()) {
call.reject("未授予蓝牙权限", "permission_denied");
return;
}
BtPrinterHelper.list(getContext(), call);
}
@PluginMethod
public void printRaw(PluginCall call) {
if (!hasBluetoothPermission()) {
requestPermissionForAlias("bluetooth", call, "printRawWithPermission");
return;
}
BtPrinterHelper.printRaw(getContext(), call);
}
@PermissionCallback
private void printRawWithPermission(PluginCall call) {
if (!hasBluetoothPermission()) {
call.reject("未授予蓝牙权限", "permission_denied");
return;
}
BtPrinterHelper.printRaw(getContext(), call);
}
/**
* BLUETOOTH_CONNECT / BLUETOOTH_SCAN 是 Android 12 才引入的运行时权限。
* 低版本直接视为已授予,否则 getPermissionState 会永远返回 DENIED,蓝牙打印彻底不可用。
*/
private boolean hasBluetoothPermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
return true;
}
return getPermissionState("bluetooth") == PermissionState.GRANTED;
}
// ---------- 系统日历 ----------
@PluginMethod
public void calendarAvailable(PluginCall call) {
CalendarHelper.available(getContext(), call);
}
@PluginMethod
public void addCalendarEvent(PluginCall call) {
// intent 模式不需要任何权限,直接拉起系统日历新建页
if ("intent".equals(call.getString("mode", "auto"))) {
CalendarHelper.add(getActivity(), call);
return;
}
if (getPermissionState("calendar") != PermissionState.GRANTED) {
requestPermissionForAlias("calendar", call, "addCalendarWithPermission");
return;
}
CalendarHelper.add(getActivity(), call);
}
@PermissionCallback
private void addCalendarWithPermission(PluginCall call) {
// auto 模式即使被拒绝也继续走,由 CalendarHelper 内部降级到 Intent 通道
if (getPermissionState("calendar") != PermissionState.GRANTED
&& !"auto".equals(call.getString("mode", "auto"))) {
call.reject("未授予日历权限", "permission_denied");
return;
}
CalendarHelper.add(getActivity(), call);
}
@PluginMethod
public void removeCalendarEvent(PluginCall call) {
if (getPermissionState("calendar") != PermissionState.GRANTED) {
requestPermissionForAlias("calendar", call, "removeCalendarWithPermission");
return;
}
CalendarHelper.remove(getContext(), call);
}
@PermissionCallback
private void removeCalendarWithPermission(PluginCall call) {
if (getPermissionState("calendar") != PermissionState.GRANTED) {
call.reject("未授予日历权限", "permission_denied");
return;
}
CalendarHelper.remove(getContext(), call);
}
// ---------- SAF ----------
@PluginMethod
public void pickFile(PluginCall call) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
JSArray mimeTypes = call.getArray("mimeTypes");
if (mimeTypes != null && mimeTypes.length() != 0) {
List<String> types = toStringList(mimeTypes);
intent.putExtra(Intent.EXTRA_MIME_TYPES, types.toArray(new String[0]));
if (types.size() == 1) {
intent.setType(types.get(0));
}
}
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, Boolean.TRUE.equals(call.getBoolean("multiple", false)));
startActivityForResult(call, intent, "pickFileResult");
}
@ActivityCallback
private void pickFileResult(PluginCall call, ActivityResult result) {
if (call == null) {
return;
}
if (result.getResultCode() != android.app.Activity.RESULT_OK) {
call.reject("已取消选择", "cancelled");
return;
}
Intent data = result.getData();
List<Uri> uris = new ArrayList<>();
if (data != null) {
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int index = 0; index < clipData.getItemCount(); index++) {
Uri uri = clipData.getItemAt(index).getUri();
if (uri != null) {
uris.add(uri);
}
}
} else if (data.getData() != null) {
uris.add(data.getData());
}
}
if (uris.isEmpty()) {
call.reject("没有选中文件", "cancelled");
return;
}
SafHelper.copyToCache(getContext(), call, uris);
}
@PluginMethod
public void saveFile(PluginCall call) {
String fileName = call.getString("fileName");
String data = call.getString("data");
if (fileName == null || fileName.isEmpty() || data == null) {
call.reject("缺少文件名或内容", "invalid_argument");
return;
}
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(call.getString("mimeType", "application/octet-stream"));
intent.putExtra(Intent.EXTRA_TITLE, fileName);
startActivityForResult(call, intent, "saveFileResult");
}
@ActivityCallback
private void saveFileResult(PluginCall call, ActivityResult result) {
if (call == null) {
return;
}
if (result.getResultCode() != android.app.Activity.RESULT_OK) {
call.reject("已取消保存", "cancelled");
return;
}
Intent data = result.getData();
Uri uri = data == null ? null : data.getData();
if (uri == null) {
call.reject("没有选择保存位置", "cancelled");
return;
}
SafHelper.writeToUri(getContext(), call, uri);
}
// ---------- 前台状态与网络 ----------
@PluginMethod
public void getAppState(PluginCall call) {
JSObject result = new JSObject();
result.put("isActive", systemHelper.isActive());
call.resolve(result);
}
@PluginMethod
public void getNetworkStatus(PluginCall call) {
systemHelper.getNetworkStatus(call);
}
// ---------- 权限状态与设置跳转 ----------
@PluginMethod
public void getPermissionStates(PluginCall call) {
JSObject result = new JSObject();
result.put("camera", getPermissionState("camera").toString());
result.put("microphone", getPermissionState("microphone").toString());
result.put("calendar", getPermissionState("calendar").toString());
result.put("contacts", getPermissionState("contacts").toString());
// 蓝牙在 Android 12 以下没有运行时权限,直接算已授予
result.put(
"bluetooth",
hasBluetoothPermission() ? "granted" : getPermissionState("bluetooth").toString()
);
// 通知在 Android 13 以下没有运行时权限,用系统开关状态代替
result.put(
"notifications",
NotificationScheduler.hasNotificationPermission(getContext()) ? "granted" : "denied"
);
call.resolve(result);
}
@PluginMethod
public void openAppSettings(PluginCall call) {
systemHelper.openAppSettings(call);
}
@PluginMethod
public void openNotificationSettings(PluginCall call) {
systemHelper.openNotificationSettings(call);
}
@PluginMethod
public void openBatteryOptimizationSettings(PluginCall call) {
systemHelper.openBatteryOptimizationSettings(call);
}
@PluginMethod
public void isIgnoringBatteryOptimizations(PluginCall call) {
JSObject result = new JSObject();
result.put("ignoring", systemHelper.isIgnoringBatteryOptimizations());
call.resolve(result);
}
// ---------- 设备控制 ----------
@PluginMethod
public void getDeviceId(PluginCall call) {
JSObject result = new JSObject();
result.put("androidId", systemHelper.getAndroidId());
call.resolve(result);
}
@PluginMethod
public void getRingerMode(PluginCall call) {
JSObject result = new JSObject();
result.put("mode", systemHelper.getRingerMode());
call.resolve(result);
}
@PluginMethod
public void setKeepAwake(PluginCall call) {
if (!ensureActivity(call)) {
return;
}
boolean enabled = Boolean.TRUE.equals(call.getBoolean("enabled", true));
getActivity().runOnUiThread(() -> {
systemHelper.setKeepAwake(getActivity(), enabled);
JSObject result = new JSObject();
result.put("enabled", enabled);
call.resolve(result);
});
}
@PluginMethod
public void setOrientation(PluginCall call) {
if (!ensureActivity(call)) {
return;
}
String orientation = call.getString("orientation", "auto");
getActivity().runOnUiThread(() -> {
systemHelper.setOrientation(getActivity(), orientation);
JSObject result = new JSObject();
result.put("orientation", orientation);
call.resolve(result);
});
}
@PluginMethod
public void restartApp(PluginCall call) {
if (!ensureActivity(call)) {
return;
}
// 先 resolve,重建后这个 PluginCall 就没地方回了
call.resolve();
getActivity().runOnUiThread(() -> systemHelper.restartApp(getActivity()));
}
@PluginMethod
public void clearWebCache(PluginCall call) {
if (!ensureActivity(call)) {
return;
}
boolean storage = Boolean.TRUE.equals(call.getBoolean("storage", false));
android.webkit.WebView webView = getBridge() == null ? null : getBridge().getWebView();
getActivity().runOnUiThread(() -> {
systemHelper.clearWebCache(webView, storage);
call.resolve();
});
}
private boolean ensureActivity(PluginCall call) {
if (getActivity() == null) {
call.reject("页面已销毁,无法执行", "no_activity");
return false;
}
return true;
}
// ---------- 通讯录 ----------
@PluginMethod
public void contactsAvailable(PluginCall call) {
ContactsHelper.available(getContext(), call);
}
@PluginMethod
public void addContact(PluginCall call) {
if (getPermissionState("contacts") != PermissionState.GRANTED) {
requestPermissionForAlias("contacts", call, "addContactWithPermission");
return;
}
ContactsHelper.add(getContext(), call);
}
@PermissionCallback
private void addContactWithPermission(PluginCall call) {
if (getPermissionState("contacts") != PermissionState.GRANTED) {
call.reject("未授予通讯录权限", "permission_denied");
return;
}
ContactsHelper.add(getContext(), call);
}
@PluginMethod
public void syncContacts(PluginCall call) {
if (getPermissionState("contacts") != PermissionState.GRANTED) {
requestPermissionForAlias("contacts", call, "syncContactsWithPermission");
return;
}
ContactsHelper.sync(getContext(), call);
}
@PermissionCallback
private void syncContactsWithPermission(PluginCall call) {
if (getPermissionState("contacts") != PermissionState.GRANTED) {
call.reject("未授予通讯录权限", "permission_denied");
return;
}
ContactsHelper.sync(getContext(), call);
}
@PluginMethod
public void clearContacts(PluginCall call) {
if (getPermissionState("contacts") != PermissionState.GRANTED) {
requestPermissionForAlias("contacts", call, "clearContactsWithPermission");
return;
}
ContactsHelper.clear(getContext(), call);
}
@PermissionCallback
private void clearContactsWithPermission(PluginCall call) {
if (getPermissionState("contacts") != PermissionState.GRANTED) {
call.reject("未授予通讯录权限", "permission_denied");
return;
}
ContactsHelper.clear(getContext(), call);
}
// ---------- 杂项 ----------
@PluginMethod
public void vibrate(PluginCall call) {
int duration = toInt(call.getInt("ms"), 30);
Vibrator vibrator;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
VibratorManager manager = (VibratorManager) getContext().getSystemService(Context.VIBRATOR_MANAGER_SERVICE);
vibrator = manager == null ? null : manager.getDefaultVibrator();
} else {
vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
}
if (vibrator != null && vibrator.hasVibrator()) {
vibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE));
}
call.resolve();
}
@PluginMethod
public void copy(PluginCall call) {
String text = call.getString("text");
if (text == null) {
call.reject("缺少文本", "invalid_argument");
return;
}
ClipboardManager manager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
if (manager == null) {
call.reject("剪贴板不可用", "service_unavailable");
return;
}
manager.setPrimaryClip(ClipData.newPlainText("NativeKit", text));
call.resolve();
}
@PluginMethod
public void getDeviceInfo(PluginCall call) {
JSObject result = new JSObject();
result.put("brand", Build.BRAND);
result.put("model", Build.MODEL);
result.put("manufacturer", Build.MANUFACTURER);
result.put("sdkInt", Build.VERSION.SDK_INT);
result.put("webViewVersion", resolveWebViewVersion(getContext()));
result.put("packageName", getContext().getPackageName());
JSObject info = buildInfo(getContext());
result.put("versionCode", info.optLong("versionCode"));
result.put("versionName", info.optString("versionName"));
call.resolve(result);
}
// ---------- 内部工具 ----------
private static String safeString(String value) {
return value == null ? "" : value;
}
private static int toInt(Integer value, int fallback) {
return value == null ? fallback : value;
}
private static List<String> toStringList(JSArray array) {
List<String> result = new ArrayList<>();
for (int index = 0; index < array.length(); index++) {
Object item = array.opt(index);
if (item != null) {
result.add(String.valueOf(item));
}
}
return result;
}
private static String resolveWebViewVersion(Context context) {
try {
String userAgent = WebSettings.getDefaultUserAgent(context);
java.util.regex.Matcher matcher = java.util.regex.Pattern
.compile("Chrome/([\\d.]+)")
.matcher(userAgent);
return matcher.find() ? matcher.group(1) : userAgent;
} catch (Exception error) {
return "";
}
}
}
@@ -0,0 +1,25 @@
package com.imyeyu.gao.customer.nativekit;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* 定时通知的触发入口。
*
* <p>只做转发:真正的发通知与重排逻辑在 {@link NotificationScheduler#handleFire}。
*/
public class NotificationAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null) {
return;
}
int id = intent.getIntExtra(NotificationScheduler.EXTRA_ID, -1);
if (id < 0) {
return;
}
NotificationScheduler.handleFire(context, id);
}
}
@@ -0,0 +1,468 @@
package com.imyeyu.gao.customer.nativekit;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import com.getcapacitor.PluginCall;
import com.imyeyu.gao.customer.MainActivity;
import com.imyeyu.gao.customer.R;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;
/**
* 本地通知的调度与恢复。
*
* <p>不用 {@code setRepeating}:它在 Doze 下会被打成批量窗口,误差可达几十分钟。
* 这里用一次性精确闹钟,触发后自行计算下一次并重排,配合 BOOT_COMPLETED 恢复,
* 设备重启、应用覆盖安装都不会丢任务。
*/
public final class NotificationScheduler {
public static final String EXTRA_ROUTE = "nativekit_route";
public static final String EXTRA_ID = "nativekit_notify_id";
static final String CHANNEL_REMINDER = "nativekit_reminder";
static final String CHANNEL_ALERT = "nativekit_alert";
private static final String PREFS = "nativekit_notifications";
private static final String KEY_TASKS = "tasks";
private static final String KEY_NEXT_ID = "next_id";
private static final int BASE_ID = 1000;
private static final Object LOCK = new Object();
private final Context context;
NotificationScheduler(Context context) {
this.context = context.getApplicationContext();
}
// ---------- 渠道 ----------
/** 渠道只需创建一次,重复调用无副作用 */
public static void ensureChannels(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return;
}
NotificationManager manager = context.getSystemService(NotificationManager.class);
if (manager == null) {
return;
}
NotificationChannel reminder = new NotificationChannel(
CHANNEL_REMINDER,
"业务提醒",
NotificationManager.IMPORTANCE_DEFAULT
);
reminder.setDescription("跟进提醒、生日提醒、履约到期");
reminder.enableVibration(true);
NotificationChannel alert = new NotificationChannel(
CHANNEL_ALERT,
"业务告警",
NotificationManager.IMPORTANCE_HIGH
);
alert.setDescription("待核销、库存告警等需要立即处理的消息");
alert.enableVibration(true);
manager.createNotificationChannels(java.util.Arrays.asList(reminder, alert));
}
// ---------- 调度 ----------
void schedule(PluginCall call) {
String title = call.getString("title");
String body = call.getString("body");
Long at = call.getLong("at");
if (title == null || title.isEmpty() || body == null || at == null) {
call.reject("缺少标题、内容或触发时间", "invalid_argument");
return;
}
if (at <= System.currentTimeMillis()) {
call.reject("触发时间必须晚于当前时间", "invalid_argument");
return;
}
Integer requestedId = call.getInt("id");
int id;
synchronized (LOCK) {
id = requestedId == null ? nextId(context) : requestedId;
// 同 id 视为覆盖:先撤销旧闹钟与旧通知
cancelInternal(id);
}
Task task = new Task();
task.id = id;
task.title = title;
task.body = body;
task.at = at;
task.repeat = normalizeRepeat(call.getString("repeat"));
task.route = cleanText(call.getString("route"));
task.owner = cleanText(call.getString("owner"));
task.channel = CHANNEL_ALERT.equals(toChannelId(call.getString("channel")))
? CHANNEL_ALERT
: CHANNEL_REMINDER;
synchronized (LOCK) {
List<Task> tasks = readTasks(context);
tasks.removeIf(item -> item.id == task.id);
tasks.add(task);
writeTasks(context, tasks);
scheduleAlarm(context, task);
}
JSObject result = new JSObject();
result.put("id", id);
result.put("at", at);
call.resolve(result);
}
void cancel(int id) {
synchronized (LOCK) {
cancelInternal(id);
List<Task> tasks = readTasks(context);
tasks.removeIf(item -> item.id == id);
writeTasks(context, tasks);
}
}
/**
* 清空任务。
*
* @param owner 非空时只清该归属的任务,用于共用设备上的账号切换
*/
void cancelAll(String owner) {
synchronized (LOCK) {
List<Task> tasks = readTasks(context);
List<Task> remain = new ArrayList<>();
for (Task task : tasks) {
if (owner == null || owner.isEmpty() || owner.equals(task.owner)) {
cancelInternal(task.id);
} else {
remain.add(task);
}
}
writeTasks(context, remain);
}
}
/** 列出已排程的任务,按触发时间升序;owner 非空时只返回该归属的 */
void list(PluginCall call) {
String owner = call.getString("owner");
synchronized (LOCK) {
List<Task> tasks = readTasks(context);
tasks.sort(Comparator.comparingLong(task -> task.at));
JSArray items = new JSArray();
for (Task task : tasks) {
if (owner != null && !owner.isEmpty() && !owner.equals(task.owner)) {
continue;
}
JSObject item = new JSObject();
item.put("id", task.id);
item.put("title", task.title);
item.put("body", task.body);
item.put("at", task.at);
item.put("repeat", task.repeat);
item.put("route", task.route == null ? JSObject.NULL : task.route);
item.put("owner", task.owner == null ? JSObject.NULL : task.owner);
item.put("channel", CHANNEL_ALERT.equals(task.channel) ? "alert" : "reminder");
items.put(item);
}
JSObject result = new JSObject();
result.put("items", items);
call.resolve(result);
}
}
/** 重启或覆盖安装后恢复未过期任务,过期的重复任务顺延到下一次 */
public static void restore(Context context) {
synchronized (LOCK) {
List<Task> tasks = readTasks(context);
List<Task> alive = new ArrayList<>();
long now = System.currentTimeMillis();
for (Task task : tasks) {
if (task.at <= now) {
if ("none".equals(task.repeat)) {
continue;
}
task.at = nextOccurrence(task.at, task.repeat, now);
}
alive.add(task);
scheduleAlarm(context, task);
}
writeTasks(context, alive);
}
}
/** 闹钟触发:发通知,重复任务顺延 */
public static void handleFire(Context context, int id) {
synchronized (LOCK) {
List<Task> tasks = readTasks(context);
Task target = null;
for (Task task : tasks) {
if (task.id == id) {
target = task;
break;
}
}
if (target == null) {
return;
}
post(context, target);
if ("none".equals(target.repeat)) {
tasks.removeIf(item -> item.id == id);
writeTasks(context, tasks);
return;
}
target.at = nextOccurrence(target.at, target.repeat, System.currentTimeMillis());
writeTasks(context, tasks);
scheduleAlarm(context, target);
}
}
// ---------- 权限 ----------
static boolean hasNotificationPermission(Context context) {
if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) {
return false;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
return true;
}
return ContextCompat.checkSelfPermission(context, android.Manifest.permission.POST_NOTIFICATIONS)
== PackageManager.PERMISSION_GRANTED;
}
static boolean canScheduleExactAlarms(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
return true;
}
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
return manager != null && manager.canScheduleExactAlarms();
}
// ---------- 内部实现 ----------
private static void scheduleAlarm(Context context, Task task) {
if (context == null) {
return;
}
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (manager == null) {
return;
}
Intent intent = new Intent(context, NotificationAlarmReceiver.class);
// data 参与 PendingIntent 去重,避免同 requestCode 的旧闹钟被覆盖
intent.setData(Uri.parse("nativekit://notify/" + task.id));
intent.putExtra(EXTRA_ID, task.id);
int flags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
PendingIntent pending = PendingIntent.getBroadcast(context, task.id, intent, flags);
try {
if (canScheduleExactAlarms(context)) {
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, task.at, pending);
} else {
// 未授权精确闹钟时降级,误差可接受,但不能直接失败
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, task.at, pending);
}
} catch (SecurityException error) {
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, task.at, pending);
}
}
private static void post(Context context, Task task) {
if (!hasNotificationPermission(context)) {
// 没权限也必须让重复任务继续走下去,否则一次拒绝就永久失效
return;
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, task.channel)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(task.title)
.setContentText(task.body)
.setStyle(new NotificationCompat.BigTextStyle().bigText(task.body))
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setPriority(
CHANNEL_ALERT.equals(task.channel)
? NotificationCompat.PRIORITY_HIGH
: NotificationCompat.PRIORITY_DEFAULT
);
if (task.route != null && !task.route.isEmpty()) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(EXTRA_ROUTE, task.route);
PendingIntent contentIntent = PendingIntent.getActivity(
context,
task.id,
intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
builder.setContentIntent(contentIntent);
}
Notification notification = builder.build();
NotificationManagerCompat.from(context).notify(task.id, notification);
}
private void cancelInternal(int id) {
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (manager != null) {
Intent intent = new Intent(context, NotificationAlarmReceiver.class);
intent.setData(Uri.parse("nativekit://notify/" + id));
PendingIntent pending = PendingIntent.getBroadcast(
context,
id,
intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
manager.cancel(pending);
}
NotificationManagerCompat.from(context).cancel(id);
}
/** 空串与字符串 "null" 都归一成 null,避免脏值被当成真实路由 */
private static String cleanText(String value) {
if (value == null || value.isEmpty() || "null".equals(value)) {
return null;
}
return value;
}
private static String normalizeRepeat(String repeat) { if ("daily".equals(repeat) || "weekly".equals(repeat) || "yearly".equals(repeat)) {
return repeat;
}
return "none";
}
private static String toChannelId(String channel) {
return "alert".equals(channel) ? CHANNEL_ALERT : CHANNEL_REMINDER;
}
/** 从 at 起找到第一个晚于 now 的时刻,按本地时区计算 */
private static long nextOccurrence(long at, String repeat, long now) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(at);
if ("yearly".equals(repeat)) {
do {
calendar.add(Calendar.YEAR, 1);
} while (calendar.getTimeInMillis() <= now);
return calendar.getTimeInMillis();
}
int step = "weekly".equals(repeat) ? 7 : 1;
do {
calendar.add(Calendar.DAY_OF_MONTH, step);
} while (calendar.getTimeInMillis() <= now);
return calendar.getTimeInMillis();
}
private static int nextId(Context context) {
SharedPreferences preferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
int id = preferences.getInt(KEY_NEXT_ID, BASE_ID);
preferences.edit().putInt(KEY_NEXT_ID, id + 1).apply();
return id;
}
private static List<Task> readTasks(Context context) {
SharedPreferences preferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
String raw = preferences.getString(KEY_TASKS, null);
List<Task> tasks = new ArrayList<>();
if (raw == null || raw.isEmpty()) {
return tasks;
}
try {
JSONArray array = new JSONArray(raw);
for (int index = 0; index < array.length(); index++) {
JSONObject object = array.optJSONObject(index);
if (object == null) {
continue;
}
Task task = new Task();
task.id = object.optInt("id");
task.title = object.optString("title");
task.body = object.optString("body");
task.at = object.optLong("at");
task.repeat = normalizeRepeat(object.optString("repeat"));
// optString 遇到 JSON null 会返回字符串 "null";早期版本还会把它原样写回存储,
// 所以这里两种形态都当没有处理,避免通知点击跳到 "/null"
task.route = cleanText(object.isNull("route") ? null : object.optString("route", null));
task.owner = cleanText(object.isNull("owner") ? null : object.optString("owner", null));
task.channel = toChannelId(object.optString("channel"));
if (0 < task.id && 0 < task.at) {
tasks.add(task);
}
}
} catch (Exception ignored) {
// 内容损坏时按空列表处理,避免整个提醒体系卡死
}
return tasks;
}
private static void writeTasks(Context context, List<Task> tasks) {
JSONArray array = new JSONArray();
for (Task task : tasks) {
JSONObject object = new JSONObject();
try {
object.put("id", task.id);
object.put("title", task.title);
object.put("body", task.body);
object.put("at", task.at);
object.put("repeat", task.repeat);
object.put("route", task.route == null ? JSONObject.NULL : task.route);
object.put("owner", task.owner == null ? JSONObject.NULL : task.owner);
object.put("channel", CHANNEL_ALERT.equals(task.channel) ? "alert" : "reminder");
array.put(object);
} catch (Exception ignored) {
// 单条序列化失败不影响其余任务
}
}
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.edit()
.putString(KEY_TASKS, array.toString())
.apply();
}
/** 任务模型,字段与前端 options 一一对应 */
static final class Task {
int id;
String title;
String body;
long at;
String repeat;
String route;
/** 归属标识,通常是登录用户 ID,用于共用设备上的隔离 */
String owner;
String channel;
}
}
@@ -0,0 +1,233 @@
package com.imyeyu.gao.customer.nativekit;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;
import android.print.PrintManager;
import android.print.pdf.PrintedPdfDocument;
import com.getcapacitor.PluginCall;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Locale;
/**
* 系统打印。
*
* <p>替代 Web 侧的 {@code window.open} 打印:那个做法在 Capacitor 里会把整页外抛到浏览器,
* 回来之后 App 状态全丢。
*
* <p>系统打印框架无法静默打印,一定会弹面板 —— 这是 Android 的限制,要静默只能走
* IPP/CUPS 直连或厂商 SDK。
*/
final class PrintHelper {
private PrintHelper() {
}
static void print(Activity activity, PluginCall call, List<String> paths, String jobName) {
if (paths.isEmpty()) {
call.reject("没有待打印文件", "invalid_argument");
return;
}
File first = new File(MediaInfo.stripScheme(paths.get(0)));
if (!first.isFile()) {
call.reject("文件不存在:" + paths.get(0), "file_not_found");
return;
}
PrintManager manager = (PrintManager) activity.getSystemService(Context.PRINT_SERVICE);
if (manager == null) {
call.reject("打印服务不可用", "service_unavailable");
return;
}
PrintAttributes attributes = new PrintAttributes.Builder()
.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
.build();
String safeJobName = jobName == null || jobName.isEmpty() ? "GaoCustomer" : jobName;
manager.print(safeJobName, new FilesPrintAdapter(activity, paths), attributes);
call.resolve();
}
/**
* 单文件 PDF 直接流式拷贝;图片则逐页绘制到同一个 PDF。
*
* <p>二维码批量打印是主路径:一页一张 2480×3508 的 PNG,必须先按页面尺寸采样解码,
* 否则一次解码多张直接 OOM。
*/
private static final class FilesPrintAdapter extends PrintDocumentAdapter {
private final Context context;
private final List<String> paths;
private PrintAttributes attributes;
private int pageCount;
FilesPrintAdapter(Context context, List<String> paths) {
this.context = context;
this.paths = paths;
}
@Override
public void onLayout(
PrintAttributes oldAttributes,
PrintAttributes newAttributes,
CancellationSignal cancellationSignal,
LayoutResultCallback callback,
Bundle extras
) {
attributes = newAttributes;
boolean pdf = paths.size() == 1 && isPdf(paths.get(0));
pageCount = pdf ? 1 : paths.size();
PrintDocumentInfo info = new PrintDocumentInfo.Builder("gao-customer-print")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(pageCount)
.build();
if (isCancelled(cancellationSignal)) {
callback.onLayoutCancelled();
return;
}
callback.onLayoutFinished(info, !newAttributes.equals(oldAttributes));
}
@Override
public void onWrite(
PageRange[] pages,
ParcelFileDescriptor destination,
CancellationSignal cancellationSignal,
WriteResultCallback callback
) {
try {
if (paths.size() == 1 && isPdf(paths.get(0))) {
copyFile(new File(MediaInfo.stripScheme(paths.get(0))), destination);
} else {
writeImages(destination, cancellationSignal);
}
callback.onWriteFinished(new PageRange[] { PageRange.ALL_PAGES });
} catch (Exception error) {
callback.onWriteFailed(error.getMessage());
}
}
private void writeImages(ParcelFileDescriptor destination, CancellationSignal cancellationSignal)
throws Exception {
PrintedPdfDocument document = new PrintedPdfDocument(context, attributes);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setFilterBitmap(true);
try {
int pageNumber = 1;
for (String path : paths) {
if (isCancelled(cancellationSignal)) {
return;
}
File file = new File(MediaInfo.stripScheme(path));
Bitmap bitmap = decode(file);
if (bitmap == null) {
continue;
}
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
document.getPageWidth(),
document.getPageHeight(),
pageNumber
).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
canvas.drawColor(Color.WHITE);
RectF target = fitCenter(bitmap, document.getPageWidth(), document.getPageHeight());
canvas.drawBitmap(bitmap, null, target, paint);
document.finishPage(page);
bitmap.recycle();
pageNumber++;
}
if (1 < pageNumber) {
try (OutputStream output = new FileOutputStream(destination.getFileDescriptor())) {
document.writeTo(output);
}
}
} finally {
document.close();
}
}
private static RectF fitCenter(Bitmap bitmap, int width, int height) {
float scale = Math.min(
(float) width / bitmap.getWidth(),
(float) height / bitmap.getHeight()
);
float drawWidth = bitmap.getWidth() * scale;
float drawHeight = bitmap.getHeight() * scale;
float left = (width - drawWidth) / 2f;
float top = (height - drawHeight) / 2f;
return new RectF(left, top, left + drawWidth, top + drawHeight);
}
/** 按页面最长边采样,避免一张 A4 大图直接吃掉几百 MB */
private static Bitmap decode(File file) {
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), bounds);
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
return null;
}
int longest = Math.max(bounds.outWidth, bounds.outHeight);
int sample = 1;
while (2480 < longest / sample) {
sample *= 2;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sample;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
}
private static void copyFile(File file, ParcelFileDescriptor destination) throws Exception {
try (InputStream input = new FileInputStream(file);
OutputStream output = new FileOutputStream(destination.getFileDescriptor())) {
byte[] buffer = new byte[32768];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
}
}
private static boolean isPdf(String path) {
return MediaInfo.stripScheme(path).toLowerCase(Locale.ROOT).endsWith(".pdf");
}
private static boolean isCancelled(CancellationSignal signal) {
return signal != null && signal.isCanceled();
}
}
}
@@ -0,0 +1,125 @@
package com.imyeyu.gao.customer.nativekit;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.util.Base64;
import com.getcapacitor.PluginCall;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* SAF 文件选择与另存。
*
* <p>选中的 {@code content://} 在 WebView 的 fetch 里读不到,必须先拷到 cache 再以
* {@code file://} 交给前端。这一步不能省,否则接口看着通、实际用不了。
*/
final class SafHelper {
private static final String CACHE_DIR = "nativekit-pick";
private static final String UNSAFE = "[^\\w.\\-\\u4e00-\\u9fa5]";
private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
private SafHelper() {
}
/** 把选中的 URI 复制到 cache,异步回调 */
static void copyToCache(Context context, PluginCall call, List<Uri> uris) {
EXECUTOR.execute(() -> {
File directory = new File(context.getCacheDir(), CACHE_DIR);
if (!directory.exists() && !directory.mkdirs()) {
call.reject("无法创建缓存目录", "io_error");
return;
}
List<String> paths = new ArrayList<>();
for (Uri uri : uris) {
String name = sanitize(queryName(context, uri));
File target = new File(directory, System.currentTimeMillis() + "-" + name);
try (InputStream input = context.getContentResolver().openInputStream(uri);
OutputStream output = new FileOutputStream(target)) {
if (input == null) {
continue;
}
byte[] buffer = new byte[32768];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
paths.add(target.getAbsolutePath());
} catch (Exception error) {
target.delete();
}
}
if (paths.isEmpty()) {
call.reject("读取文件失败", "io_error");
return;
}
call.resolve(MediaInfo.buildFiles(context, paths));
});
}
/** 把 base64 内容写进用户选定的 URI */
static void writeToUri(Context context, PluginCall call, Uri uri) {
String data = call.getString("data");
if (data == null) {
call.reject("缺少文件内容", "invalid_argument");
return;
}
EXECUTOR.execute(() -> {
try (OutputStream output = context.getContentResolver().openOutputStream(uri)) {
if (output == null) {
call.reject("无法写入所选位置", "io_error");
return;
}
output.write(Base64.decode(data, Base64.DEFAULT));
output.flush();
} catch (Exception error) {
call.reject("保存失败:" + error.getMessage(), "io_error");
return;
}
com.getcapacitor.JSObject result = new com.getcapacitor.JSObject();
result.put("path", uri.toString());
result.put("name", queryName(context, uri));
call.resolve(result);
});
}
private static String queryName(Context context, Uri uri) {
try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (0 <= index) {
String name = cursor.getString(index);
if (name != null && !name.isEmpty()) {
return name;
}
}
}
} catch (Exception ignored) {
// 查询失败时退回路径末段
}
String fallback = uri.getLastPathSegment();
return fallback == null || fallback.isEmpty() ? "file" : fallback;
}
private static String sanitize(String name) {
String cleaned = name.replaceAll(UNSAFE, "_");
if (120 < cleaned.length()) {
cleaned = cleaned.substring(cleaned.length() - 120);
}
return cleaned.isEmpty() ? "file" : cleaned;
}
}
@@ -0,0 +1,128 @@
package com.imyeyu.gao.customer.nativekit;
import android.content.Context;
import android.content.SharedPreferences;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
/**
* 登录态的加密存储。
*
* <p>密钥由 Android Keystore 生成并保存在 TEE,无法导出;密文落在独立的 SharedPreferences。
* 不使用 androidx.security:security-crypto —— 它在部分机型上创建 MasterKey 失败,且长期停留在 alpha。
*
* <p>存储格式为 Base64(IV[12] + 密文 + GCM tag),密钥被系统清除(恢复出厂、锁屏密码重置)时
* 解密会失败,此时按「无会话」处理,让用户重新登录,不抛异常。
*/
public final class SecureStore {
private static final String KEY_STORE = "AndroidKeyStore";
private static final String KEY_ALIAS = "nativekit_session_key";
private static final String PREFS_NAME = "nativekit_secure";
private static final String FIELD_SESSION = "session";
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final int IV_BYTES = 12;
private static final int TAG_BITS = 128;
private static final int KEY_BITS = 256;
private SecureStore() {
}
/** 写入加密会话;传空字符串等价于清除 */
public static void saveSession(Context context, String json) {
if (json == null || json.isEmpty()) {
clearSession(context);
return;
}
try {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey());
byte[] encrypted = cipher.doFinal(json.getBytes(StandardCharsets.UTF_8));
byte[] iv = cipher.getIV();
byte[] payload = new byte[iv.length + encrypted.length];
System.arraycopy(iv, 0, payload, 0, iv.length);
System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length);
preferences(context).edit()
.putString(FIELD_SESSION, Base64.encodeToString(payload, Base64.NO_WRAP))
.apply();
} catch (Exception error) {
// 密钥不可用时不保留任何明文,直接清空,交给上层重新登录
clearSession(context);
}
}
/** 读取并解密会话;不存在或解密失败返回 null */
public static String readSession(Context context) {
String stored = preferences(context).getString(FIELD_SESSION, null);
if (stored == null || stored.isEmpty()) {
return null;
}
try {
byte[] payload = Base64.decode(stored, Base64.NO_WRAP);
if (payload.length <= IV_BYTES) {
return null;
}
byte[] iv = new byte[IV_BYTES];
System.arraycopy(payload, 0, iv, 0, IV_BYTES);
byte[] encrypted = new byte[payload.length - IV_BYTES];
System.arraycopy(payload, IV_BYTES, encrypted, 0, encrypted.length);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), new GCMParameterSpec(TAG_BITS, iv));
return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
} catch (Exception error) {
return null;
}
}
/** 清除会话,同时丢弃密钥,避免残留可用密文 */
public static void clearSession(Context context) {
preferences(context).edit().remove(FIELD_SESSION).apply();
try {
KeyStore keyStore = KeyStore.getInstance(KEY_STORE);
keyStore.load(null);
if (keyStore.containsAlias(KEY_ALIAS)) {
keyStore.deleteEntry(KEY_ALIAS);
}
} catch (Exception ignored) {
// 密钥清理失败不影响业务流程
}
}
private static SharedPreferences preferences(Context context) {
return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
private static SecretKey getOrCreateKey() throws Exception {
KeyStore keyStore = KeyStore.getInstance(KEY_STORE);
keyStore.load(null);
if (keyStore.containsAlias(KEY_ALIAS)) {
return (SecretKey) keyStore.getKey(KEY_ALIAS, null);
}
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEY_STORE);
generator.init(
new KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(KEY_BITS)
.build()
);
return generator.generateKey();
}
}
@@ -0,0 +1,64 @@
package com.imyeyu.gao.customer.nativekit;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import androidx.core.content.FileProvider;
import com.getcapacitor.PluginCall;
import java.io.File;
/**
* 系统分享。
*
* <p>FileProvider 只放行 cache / files / external-files 三个目录,外部存储的路径会抛异常,
* 调用方需要先把文件落到应用私有目录(下载器就是这么做的)。
*/
final class ShareHelper {
private ShareHelper() {
}
static void share(Activity activity, PluginCall call, String path) {
File file = new File(MediaInfo.stripScheme(path));
if (!file.isFile()) {
call.reject("文件不存在:" + path, "file_not_found");
return;
}
Uri uri;
try {
uri = FileProvider.getUriForFile(
activity,
activity.getPackageName() + ".fileprovider",
file
);
} catch (Exception error) {
call.reject("文件不在可分享目录内,请先下载到应用缓存", "file_not_shareable");
return;
}
String mimeType = call.getString("mimeType", MediaInfo.guessMimeType(file.getName()));
String title = call.getString("title", "分享");
String text = call.getString("text");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (text != null && !text.isEmpty()) {
intent.putExtra(Intent.EXTRA_TEXT, text);
}
Intent chooser = Intent.createChooser(intent, title);
chooser.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
activity.startActivity(chooser);
call.resolve();
} catch (Exception error) {
call.reject("无法打开分享面板", "activity_not_found");
}
}
}
@@ -0,0 +1,437 @@
package com.imyeyu.gao.customer.nativekit;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.WebStorage;
import android.webkit.WebView;
import com.getcapacitor.JSObject;
/**
* 环境感知与设备控制。
*
* <p>这些能力单看都不起眼,但缺了它们,前端就没法回答三个基本问题:
* 「用户还在用 App 吗」「网断了吗」「权限被拒了还能不能救」。
*
* <p>前台判定没有用 Activity 的 onResume/onPause —— 打开扫码页、语音页都会让
* MainActivity pause,会被误判成切到后台。这里改用 Activity 计数:只要有任意一个
* 自己的 Activity 处于 started 状态,就算前台。
*/
final class SystemHelper implements Application.ActivityLifecycleCallbacks {
private final NativeKitPlugin plugin;
private final Context context;
/**
* 插件加载时必然处在前台(Bridge 只在 Activity 创建时构建),先记 1。
*
* <p>重建 Activity(restartApp)时更明显:新插件实例注册回调晚于新 Activity 的
* onStart,如果从 0 开始计,就再也收不到那次 started,会一直报「后台」。
* 所以第一次 onActivityStarted 只用来对齐这个初始值,不重复计数。
*/
private int startedCount = 1;
private boolean primed = false;
private ConnectivityManager.NetworkCallback networkCallback;
private boolean lastConnected = true;
private String lastType = "none";
SystemHelper(NativeKitPlugin plugin) {
this.plugin = plugin;
this.context = plugin.getContext().getApplicationContext();
}
void start() {
try {
Application application = (Application) context;
application.registerActivityLifecycleCallbacks(this);
} catch (Exception ignored) {
// 非 Application 上下文时跳过,不影响其他能力
}
registerNetwork();
}
void stop() {
try {
Application application = (Application) context;
application.unregisterActivityLifecycleCallbacks(this);
} catch (Exception ignored) {
// 未注册成功时忽略
}
unregisterNetwork();
}
// ---------- 前台状态 ----------
/**
* 是否在前台。
*
* <p>优先用 Activity 计数(事件由它驱动,时序准确);计数归零时再用进程 importance 兜底。
* 重建场景下新插件实例注册回调晚于新 Activity 的 onStart,计数会落不到 1,
* 只靠计数会一直误报后台。
*/
boolean isActive() {
if (0 < startedCount) {
return true;
}
return isProcessForeground();
}
private boolean isProcessForeground() {
try {
android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE
);
if (manager == null) {
return false;
}
java.util.List<android.app.ActivityManager.RunningAppProcessInfo> processes =
manager.getRunningAppProcesses();
if (processes == null) {
return false;
}
for (android.app.ActivityManager.RunningAppProcessInfo info : processes) {
if (context.getPackageName().equals(info.processName)) {
return info.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
}
}
} catch (Exception ignored) {
// 查询被 ROM 限制时按后台处理
}
return false;
}
@Override
public void onActivityStarted(Activity activity) {
if (!primed) {
primed = true;
return;
}
startedCount++;
if (1 == startedCount) {
emitAppState(true);
}
}
@Override
public void onActivityStopped(Activity activity) {
// 还没对齐初始值,这次 stop 来自被 restartApp 替换掉的旧 Activity,不能计数
if (!primed) {
return;
}
startedCount--;
if (startedCount <= 0) {
startedCount = 0;
emitAppState(false);
}
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
private void emitAppState(boolean active) {
JSObject payload = new JSObject();
payload.put("isActive", active);
plugin.emit("appStateChange", payload);
}
// ---------- 网络 ----------
void getNetworkStatus(com.getcapacitor.PluginCall call) {
call.resolve(buildNetworkStatus());
}
private JSObject buildNetworkStatus() {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
JSObject result = new JSObject();
if (manager == null) {
result.put("connected", false);
result.put("type", "none");
return result;
}
try {
Network network = manager.getActiveNetwork();
NetworkCapabilities capabilities = manager.getNetworkCapabilities(network);
boolean connected = capabilities != null
&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
result.put("connected", connected);
result.put("type", networkType(capabilities));
} catch (Exception error) {
result.put("connected", false);
result.put("type", "none");
}
return result;
}
private void registerNetwork() {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null) {
return;
}
JSObject current = buildNetworkStatus();
lastConnected = current.optBoolean("connected", false);
lastType = current.getString("type", "none");
networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
publishNetwork();
}
@Override
public void onLost(Network network) {
publishNetwork();
}
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
publishNetwork();
}
};
try {
manager.registerDefaultNetworkCallback(networkCallback);
} catch (Exception error) {
networkCallback = null;
}
}
private void unregisterNetwork() {
if (networkCallback == null) {
return;
}
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
if (manager != null) {
manager.unregisterNetworkCallback(networkCallback);
}
} catch (Exception ignored) {
// 已注销时忽略
}
networkCallback = null;
}
/** 只在状态真正变化时派发,避免每个网络抖动都打一次桥接 */
private void publishNetwork() {
JSObject status = buildNetworkStatus();
boolean connected = status.optBoolean("connected", false);
String type = status.getString("type", "none");
if (connected == lastConnected && type.equals(lastType)) {
return;
}
lastConnected = connected;
lastType = type;
plugin.emit("networkStatusChange", status);
}
private static String networkType(NetworkCapabilities capabilities) {
if (capabilities == null) {
return "none";
}
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return "wifi";
}
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return "cellular";
}
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
return "ethernet";
}
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
return "vpn";
}
return "other";
}
// ---------- 系统设置跳转 ----------
void openAppSettings(com.getcapacitor.PluginCall call) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
launch(call, intent, "无法打开应用设置");
}
void openNotificationSettings(com.getcapacitor.PluginCall call) {
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
} else {
intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
}
launch(call, intent, "无法打开通知设置");
}
void openBatteryOptimizationSettings(com.getcapacitor.PluginCall call) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
call.resolve();
return;
} catch (Exception ignored) {
// 部分 ROM 不认这个 action,退回到电池优化列表页
}
Intent fallback = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
launch(call, fallback, "无法打开电池优化设置");
}
boolean isIgnoringBatteryOptimizations() {
PowerManager manager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
return manager != null && manager.isIgnoringBatteryOptimizations(context.getPackageName());
}
private void launch(com.getcapacitor.PluginCall call, Intent intent, String message) {
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
call.resolve();
} catch (Exception error) {
call.reject(message, "activity_not_found");
}
}
// ---------- 设备 ----------
/**
* ANDROID_ID。
*
* <p>Android 8 起按「签名 + 用户」隔离,同一台设备重装、清数据都不变,
* 恢复出厂或换签名才会变,是当前唯一稳定可用的设备标识。
*/
String getAndroidId() {
try {
String id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
return id == null ? "" : id;
} catch (Exception error) {
return "";
}
}
String getRingerMode() {
AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (manager == null) {
return "normal";
}
switch (manager.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
return "silent";
case AudioManager.RINGER_MODE_VIBRATE:
return "vibrate";
default:
return "normal";
}
}
/** 只在当前 Activity 上生效,离开页面要关掉,否则一直亮屏耗电 */
void setKeepAwake(Activity activity, boolean enabled) {
if (activity == null) {
return;
}
if (enabled) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
void setOrientation(Activity activity, String orientation) {
if (activity == null) {
return;
}
int requested;
if ("portrait".equals(orientation)) {
requested = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
} else if ("landscape".equals(orientation)) {
requested = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else {
requested = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
}
activity.setRequestedOrientation(requested);
}
/**
* 重启应用界面。
*
* <p>不是杀进程。Android 10 起禁止后台启动 Activity,靠 AlarmManager 的
* PendingIntent 把进程拉回来的做法会被系统拦掉,实测杀了就再也起不来。
* 这里改成清空任务栈重建 MainActivity:进程不换,但 WebView 会重新加载、
* Bridge 会重建,对「切账号彻底重置」已经够用。
*/
void restartApp(Activity activity) {
if (activity == null) {
return;
}
try {
Intent intent = new Intent(activity, activity.getClass());
intent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK
);
activity.startActivity(intent);
activity.finishAffinity();
} catch (Exception error) {
activity.recreate();
}
}
/**
* 清 WebView 缓存。
*
* <p>{@code storage} 为真时会连 localStorage / Cookie 一起清 —— 登录态、主题、
* 热更记录都会没,只在排查白屏或切账号彻底重置时用。
*/
void clearWebCache(WebView webView, boolean storage) {
if (webView != null) {
webView.clearCache(true);
webView.clearFormData();
}
if (!storage) {
return;
}
try {
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
WebStorage.getInstance().deleteAllData();
android.webkit.WebViewDatabase.getInstance(context).clearHttpAuthUsernamePassword();
} catch (Exception ignored) {
// 单项清理失败不影响其余
}
}
}
@@ -0,0 +1,395 @@
package com.imyeyu.gao.customer.nativekit;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import androidx.activity.result.ActivityResult;
import com.getcapacitor.PluginCall;
import java.util.ArrayList;
/**
* 语音输入。
*
* <p>Web Speech API 在 Android WebView 里没有实现(Chromium 把 SpeechRecognition 编译排除在外),
* 只能走原生。两条通道:
*
* <ul>
* <li>A:{@link SpeechRecognizer} —— 可控,能拿 partial 结果(边说边上屏),但需要 RECORD_AUDIO</li>
* <li>B:{@link RecognizerIntent#ACTION_RECOGNIZE_SPEECH} —— 不需要权限,覆盖面更广,
* 但拿不到中间结果,且会压一层 Activity</li>
* </ul>
*
* <p>国产 ROM 上 A 的 {@code isRecognitionAvailable()} 常为 false,但系统语音助手能响应 B,
* 所以不能只判 A。
*/
final class VoiceInput implements RecognitionListener {
private static final String DEFAULT_LANG = "zh-CN";
private static final int ERROR_LANGUAGE_NOT_SUPPORTED = 12;
private static final int ERROR_LANGUAGE_UNAVAILABLE = 13;
private final NativeKitPlugin plugin;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private SpeechRecognizer recognizer;
/** 跨线程读写:start 在桥接线程,onResults 在主线程 */
private volatile PluginCall activeCall;
private String language;
private boolean wantPartial;
private boolean preferOffline;
private boolean offlineRetried;
private volatile boolean listening;
VoiceInput(NativeKitPlugin plugin) {
this.plugin = plugin;
}
// ---------- 探测 ----------
void available(PluginCall call) {
Context context = plugin.getContext();
com.getcapacitor.JSObject result = new com.getcapacitor.JSObject();
boolean recognizerReady = SpeechRecognizer.isRecognitionAvailable(context);
boolean intentReady = canHandleIntent(context);
String channel = recognizerReady ? "recognizer" : (intentReady ? "intent" : "none");
result.put("channel", channel);
result.put("engine", recognizerReady ? "system" : "");
call.resolve(result);
}
private static boolean canHandleIntent(Context context) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Android 11 起受包可见性限制,没有 queries 声明时这里永远返回 null
return intent.resolveActivity(context.getPackageManager()) != null;
}
// ---------- 开始 ----------
void start(PluginCall call) {
if (activeCall != null) {
call.reject("上一次识别尚未结束", "busy");
return;
}
Context context = plugin.getContext();
activeCall = call;
language = call.getString("lang", DEFAULT_LANG);
wantPartial = !Boolean.FALSE.equals(call.getBoolean("partial", true));
preferOffline = Boolean.TRUE.equals(call.getBoolean("preferOffline", false));
offlineRetried = false;
if (SpeechRecognizer.isRecognitionAvailable(context)) {
if (!plugin.hasMicrophonePermission()) {
plugin.requestMicrophonePermission(call, "voicePermissionResult");
return;
}
startRecognizer();
return;
}
if (!canHandleIntent(context)) {
finish();
call.reject("当前设备没有可用的语音识别服务", "unavailable");
return;
}
startIntent();
}
/** 权限回调后继续;由 NativeKitPlugin 的 @PermissionCallback 转发 */
void onPermissionResult(PluginCall call) {
if (!plugin.hasMicrophonePermission()) {
finish();
call.reject("未授予麦克风权限", "permission_denied");
return;
}
startRecognizer();
}
private void startRecognizer() {
if (activeCall == null) {
return;
}
plugin.emitVoiceState("listening");
mainHandler.post(() -> {
try {
destroyRecognizer();
recognizer = SpeechRecognizer.createSpeechRecognizer(plugin.getContext());
recognizer.setRecognitionListener(this);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, wantPartial);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
if (preferOffline) {
intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true);
}
listening = true;
recognizer.startListening(intent);
} catch (Exception error) {
fail("start_failed", "无法启动语音识别:" + error.getMessage());
}
});
}
private void startIntent() {
if (activeCall == null) {
return;
}
plugin.markInternalNavigation();
plugin.emitVoiceState("listening");
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请说出要输入的内容");
plugin.startVoiceIntent(activeCall, intent);
}
/** Intent 通道返回,由 NativeKitPlugin 的 @ActivityCallback 转发 */
void onIntentResult(PluginCall call, ActivityResult result) {
plugin.emitVoiceState("idle");
if (call == null) {
finish();
return;
}
if (result.getResultCode() != android.app.Activity.RESULT_OK || result.getData() == null) {
finish();
call.reject("已取消语音输入", "cancelled");
return;
}
ArrayList<String> texts = result
.getData()
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String text = texts == null || texts.isEmpty() ? "" : texts.get(0);
if (text == null) {
text = "";
}
if (text.trim().isEmpty()) {
finish();
call.reject("没有识别到内容", "no_match");
return;
}
com.getcapacitor.JSObject payload = new com.getcapacitor.JSObject();
payload.put("text", text.trim());
finish();
call.resolve(payload);
}
// ---------- 停止与取消 ----------
void stop(PluginCall call) {
mainHandler.post(() -> {
if (recognizer != null && listening) {
try {
recognizer.stopListening();
} catch (Exception ignored) {
// 已经结束的识别再 stop 会抛异常,忽略
}
}
});
call.resolve();
}
void cancel(PluginCall call) {
PluginCall pending = activeCall;
mainHandler.post(this::destroyRecognizer);
plugin.emitVoiceState("idle");
activeCall = null;
if (pending != null) {
pending.reject("已取消语音输入", "cancelled");
}
call.resolve();
}
void release() {
mainHandler.post(this::destroyRecognizer);
activeCall = null;
}
// ---------- RecognitionListener ----------
@Override
public void onReadyForSpeech(Bundle params) {
plugin.emitVoiceState("listening");
}
@Override
public void onBeginningOfSpeech() {
plugin.emitVoiceState("listening");
}
@Override
public void onRmsChanged(float rmsdB) {
// 波形由前端根据 voiceState 自己画,这里不做转发,避免桥接被高频回调打满
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
plugin.emitVoiceState("processing");
}
@Override
public void onError(int error) {
listening = false;
// 指定离线但引擎不支持时,退回联网模式再试一次
if (preferOffline && !offlineRetried
&& (error == ERROR_LANGUAGE_NOT_SUPPORTED || error == ERROR_LANGUAGE_UNAVAILABLE || error == SpeechRecognizer.ERROR_CLIENT)) {
offlineRetried = true;
preferOffline = false;
mainHandler.postDelayed(() -> {
if (activeCall != null) {
startRecognizer();
}
}, 120);
return;
}
// 引擎忙:销毁重建后再给一次机会
if (error == SpeechRecognizer.ERROR_RECOGNIZER_BUSY && !offlineRetried) {
offlineRetried = true;
mainHandler.postDelayed(() -> {
if (activeCall != null) {
startRecognizer();
}
}, 250);
return;
}
fail(errorName(error), "语音识别失败:" + errorName(error));
}
@Override
public void onResults(Bundle results) {
listening = false;
String text = firstResult(results);
if (text.isEmpty()) {
fail("no_match", "没有识别到内容");
return;
}
float[] scores = results == null
? null
: results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES);
com.getcapacitor.JSObject payload = new com.getcapacitor.JSObject();
payload.put("text", text);
if (scores != null && 0 < scores.length) {
payload.put("confidence", scores[0]);
}
PluginCall pending = activeCall;
finish();
plugin.emitVoiceState("idle");
if (pending != null) {
pending.resolve(payload);
}
}
@Override
public void onPartialResults(Bundle partialResults) {
if (!wantPartial) {
return;
}
String text = firstResult(partialResults);
if (!text.isEmpty()) {
plugin.emitVoicePartial(text);
}
}
@Override
public void onEvent(int eventType, Bundle params) {
}
// ---------- 内部 ----------
private static String firstResult(Bundle bundle) {
if (bundle == null) {
return "";
}
ArrayList<String> texts = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (texts == null || texts.isEmpty()) {
return "";
}
String text = texts.get(0);
return text == null ? "" : text.trim();
}
private void fail(String code, String message) {
PluginCall pending = activeCall;
finish();
plugin.emitVoiceState("idle");
if (pending != null) {
pending.reject(message, code);
}
}
private void finish() {
listening = false;
activeCall = null;
mainHandler.post(this::destroyRecognizer);
}
private void destroyRecognizer() {
if (recognizer == null) {
return;
}
try {
recognizer.cancel();
recognizer.destroy();
} catch (Exception ignored) {
// 已经销毁时 destroy 会抛异常,忽略
}
recognizer = null;
}
private static String errorName(int code) {
switch (code) {
case SpeechRecognizer.ERROR_AUDIO:
return "audio";
case SpeechRecognizer.ERROR_CLIENT:
return "client";
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
return "permission_denied";
case SpeechRecognizer.ERROR_NETWORK:
return "network";
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
return "network_timeout";
case SpeechRecognizer.ERROR_NO_MATCH:
return "no_match";
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
return "busy";
case SpeechRecognizer.ERROR_SERVER:
return "server";
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
return "speech_timeout";
case ERROR_LANGUAGE_NOT_SUPPORTED:
return "language_not_supported";
case ERROR_LANGUAGE_UNAVAILABLE:
return "language_unavailable";
default:
return "unknown";
}
}
}
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 通知栏小图标必须是纯白单色,彩色资源会被系统渲染成灰块 -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.9,2 2,2zM18,16v-5c0,-3.07 -1.63,-5.64 -4.5,-6.32V4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.64,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z" />
</vector>
@@ -19,4 +19,17 @@
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen"> <style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item> <item name="android:background">@drawable/splash</item>
</style> </style>
<!--
相机页:全屏黑底,系统栏透明。
不能用 AppTheme.NoActionBar,它的 android:background=@null 会让取景前的瞬间透出桌面。
-->
<style name="AppTheme.CameraKit" parent="Theme.AppCompat.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowBackground">#000000</item>
<item name="android:statusBarColor">#000000</item>
<item name="android:navigationBarColor">#000000</item>
<item name="android:windowLightStatusBar">false</item>
</style>
</resources> </resources>
+10 -3
View File
@@ -1,5 +1,12 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!--
FileProvider 只放行应用自己的目录。
原先的 external-path path="." 会把整个外部存储暴露给任何拿到 URI 的调用方,
分享与打印都不需要这个范围。ShellUpdater 使用 cacheDir/shell-updates,由 cache-path 覆盖。
-->
<paths xmlns:android="http://schemas.android.com/apk/res/android"> <paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." /> <cache-path name="nativekit_cache" path="." />
<cache-path name="my_cache_images" path="." /> <files-path name="nativekit_files" path="." />
</paths> <external-files-path name="nativekit_external_files" path="." />
</paths>
+6
View File
@@ -0,0 +1,6 @@
# 发版签名凭证(复制为 android/keystore.properties 后填写,该文件已 gitignore)
# storeFile 相对于 android/ 目录
storeFile=../android.keystore
keyAlias=gao-customer
storePassword=
keyPassword=
+6 -2
View File
@@ -1,5 +1,5 @@
ext { ext {
minSdkVersion = 24 minSdkVersion = 29
compileSdkVersion = 36 compileSdkVersion = 36
targetSdkVersion = 36 targetSdkVersion = 36
androidxActivityVersion = '1.11.0' androidxActivityVersion = '1.11.0'
@@ -9,8 +9,12 @@ ext {
androidxFragmentVersion = '1.8.9' androidxFragmentVersion = '1.8.9'
coreSplashScreenVersion = '1.2.0' coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.14.0' androidxWebkitVersion = '1.14.0'
// 原生能力预埋:相机、条码解码、生物识别
androidxCameraVersion = '1.4.2'
zxingVersion = '3.5.3'
androidxBiometricVersion = '1.1.0'
junitVersion = '4.13.2' junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0' androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0' androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1' cordovaAndroidVersion = '14.0.1'
} }
-2
View File
@@ -6,9 +6,7 @@
// biome-ignore lint: disable // biome-ignore lint: disable
export {} export {}
declare global { declare global {
const DialogPlugin: typeof import('tdesign-mobile-vue')['DialogPlugin']
const EffectScope: typeof import('vue')['EffectScope'] const EffectScope: typeof import('vue')['EffectScope']
const THUMBNAIL_WIDTH_PARAM: typeof import('tdesign-mobile-vue')['HUMBNAIL_WIDTH_PARAM']
const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate'] const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
const computed: typeof import('vue')['computed'] const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp'] const createApp: typeof import('vue')['createApp']
+3 -7
View File
@@ -1,15 +1,12 @@
{ {
"name": "gao-customer-h5", "name": "gao-customer-h5",
"private": true, "private": true,
"version": "1.5.0", "version": "1.6.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite --host", "dev": "vite --host",
"build": "pnpm run type-check:publish && vite build", "build": "pnpm run type-check:publish && vite build",
"build:zip": "pnpm run build && powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-zip.ps1", "build:zip": "pnpm run build && powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-zip.ps1",
"twa:build": "cd twa && pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 build --manifest=./twa-manifest.json",
"twa:update": "cd twa && pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 update --skipVersionUpgrade --manifest=./twa-manifest.json",
"twa:validate": "pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 validate --url=https://gao.imyeyu.com/",
"preview": "vite preview", "preview": "vite preview",
"lint": "eslint . --ext .ts,.vue", "lint": "eslint . --ext .ts,.vue",
"type-check": "vue-tsc -p tsconfig.app.json --noEmit", "type-check": "vue-tsc -p tsconfig.app.json --noEmit",
@@ -18,7 +15,7 @@
"android:sync:prod": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-sync.ps1 -Mode prod", "android:sync:prod": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-sync.ps1 -Mode prod",
"android:sync": "pnpm run android:sync:prod", "android:sync": "pnpm run android:sync:prod",
"android:open": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-open.ps1", "android:open": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-open.ps1",
"android:apk": "pnpm run android:sync:prod && cd android && gradlew.bat assembleDebug" "android:apk": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-apk.ps1"
}, },
"dependencies": { "dependencies": {
"@capacitor/android": "^8", "@capacitor/android": "^8",
@@ -26,13 +23,12 @@
"@capgo/capacitor-updater": "^8", "@capgo/capacitor-updater": "^8",
"@zxing/browser": "^0.1.5", "@zxing/browser": "^0.1.5",
"@zxing/library": "^0.21.3", "@zxing/library": "^0.21.3",
"browser-image-compression": "^2.0.2",
"echarts": "^6.0.0", "echarts": "^6.0.0",
"echarts-wordcloud": "^2.1.0", "echarts-wordcloud": "^2.1.0",
"less": "^4.3.0", "less": "^4.3.0",
"pinia": "^3.0.2", "pinia": "^3.0.2",
"tdesign-mobile-vue": "^1.17.1", "tdesign-mobile-vue": "^1.17.1",
"timi-tdesign-mobile": "^1.3.1", "timi-tdesign-mobile": "^1.5.0",
"timi-ts": "^1.0.0", "timi-ts": "^1.0.0",
"timi-web": "^1.0.2", "timi-web": "^1.0.2",
"timi-web-api": "^1.0.2", "timi-web-api": "^1.0.2",
+5 -20
View File
@@ -28,9 +28,6 @@ importers:
'@zxing/library': '@zxing/library':
specifier: ^0.21.3 specifier: ^0.21.3
version: 0.21.3 version: 0.21.3
browser-image-compression:
specifier: ^2.0.2
version: 2.0.2
echarts: echarts:
specifier: ^6.0.0 specifier: ^6.0.0
version: 6.1.0 version: 6.1.0
@@ -47,8 +44,8 @@ importers:
specifier: ^1.17.1 specifier: ^1.17.1
version: 1.17.1(patch_hash=c98db305008fbfd00046666ca890e1c6cb88257c0619418694689cddf8cd78c3)(vue@3.5.40(typescript@5.8.3)) version: 1.17.1(patch_hash=c98db305008fbfd00046666ca890e1c6cb88257c0619418694689cddf8cd78c3)(vue@3.5.40(typescript@5.8.3))
timi-tdesign-mobile: timi-tdesign-mobile:
specifier: ^1.3.1 specifier: ^1.5.0
version: 1.3.1(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue-router@4.5.1(vue@3.5.40(typescript@5.8.3)))(vue@3.5.40(typescript@5.8.3)) version: 1.5.0(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue-router@4.5.1(vue@3.5.40(typescript@5.8.3)))(vue@3.5.40(typescript@5.8.3))
timi-ts: timi-ts:
specifier: ^1.0.0 specifier: ^1.0.0
version: 1.0.0 version: 1.0.0
@@ -1424,9 +1421,6 @@ packages:
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
engines: {node: '>=8'} engines: {node: '>=8'}
browser-image-compression@2.0.2:
resolution: {integrity: sha512-pBLlQyUf6yB8SmmngrcOw3EoS4RpQ1BcylI3T9Yqn7+4nrQTXJD4sJDe5ODnJdrvNMaio5OicFo75rDyJD2Ucw==}
buffer-crc32@0.2.13: buffer-crc32@0.2.13:
resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==} resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==}
@@ -2748,8 +2742,8 @@ packages:
through2@4.0.2: through2@4.0.2:
resolution: {integrity: sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==} resolution: {integrity: sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==}
timi-tdesign-mobile@1.3.1: timi-tdesign-mobile@1.5.0:
resolution: {integrity: sha512-6hz7MSqseCUyyJzRiyQjymMDfSZ3kJrFP6J5DxHpE1pJ8xeByCzKgELS4CnO4187mqPEx46TtF03qB9XS4Mpuw==} resolution: {integrity: sha512-zp5yGlZaiJsf4QuREbBK7qjqQNteAB7PtWWG98rwGPzEwou6Q/45nEc1CJq47BFsuxjCq+7XIhCFl3eX7GgN6w==}
engines: {node: '>=20.0.0'} engines: {node: '>=20.0.0'}
peerDependencies: peerDependencies:
vue: ^3.5.0 vue: ^3.5.0
@@ -2904,9 +2898,6 @@ packages:
util-deprecate@1.0.2: util-deprecate@1.0.2:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
uzip@0.20201231.0:
resolution: {integrity: sha512-OZeJfZP+R0z9D6TmBgLq2LHzSSptGMGDGigGiEe0pr8UBe/7fdflgHlHBNDASTXB5jnFuxHpNaJywSg8YFeGng==}
v8-compile-cache-lib@3.0.1: v8-compile-cache-lib@3.0.1:
resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==} resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==}
@@ -4412,10 +4403,6 @@ snapshots:
dependencies: dependencies:
fill-range: 7.1.1 fill-range: 7.1.1
browser-image-compression@2.0.2:
dependencies:
uzip: 0.20201231.0
buffer-crc32@0.2.13: {} buffer-crc32@0.2.13: {}
buffer-from@1.1.2: {} buffer-from@1.1.2: {}
@@ -5849,7 +5836,7 @@ snapshots:
dependencies: dependencies:
readable-stream: 3.6.2 readable-stream: 3.6.2
timi-tdesign-mobile@1.3.1(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue-router@4.5.1(vue@3.5.40(typescript@5.8.3)))(vue@3.5.40(typescript@5.8.3)): timi-tdesign-mobile@1.5.0(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue-router@4.5.1(vue@3.5.40(typescript@5.8.3)))(vue@3.5.40(typescript@5.8.3)):
dependencies: dependencies:
tdesign-mobile-vue: 1.17.1(patch_hash=c98db305008fbfd00046666ca890e1c6cb88257c0619418694689cddf8cd78c3)(vue@3.5.40(typescript@5.8.3)) tdesign-mobile-vue: 1.17.1(patch_hash=c98db305008fbfd00046666ca890e1c6cb88257c0619418694689cddf8cd78c3)(vue@3.5.40(typescript@5.8.3))
timi-web: 1.0.2(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue@3.5.40(typescript@5.8.3)) timi-web: 1.0.2(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue@3.5.40(typescript@5.8.3))
@@ -6052,8 +6039,6 @@ snapshots:
util-deprecate@1.0.2: {} util-deprecate@1.0.2: {}
uzip@0.20201231.0: {}
v8-compile-cache-lib@3.0.1: {} v8-compile-cache-lib@3.0.1: {}
validator@13.15.35: {} validator@13.15.35: {}
-15
View File
@@ -1,15 +0,0 @@
[
{
"relation": [
"delegate_permission/common.handle_all_urls",
"delegate_permission/common.use_as_origin"
],
"target": {
"namespace": "android_app",
"package_name": "com.imyeyu.gao.customer",
"sha256_cert_fingerprints": [
"3E:9C:CC:8A:29:71:18:74:BB:56:AA:88:AD:62:E1:F3:AC:F2:70:07:C4:67:D9:32:B8:A2:4B:B7:E7:8E:06:34"
]
}
}
]
+89
View File
@@ -0,0 +1,89 @@
param(
[switch]$SkipSync
)
$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot
$propertiesPath = Join-Path $root "android\keystore.properties"
if (-not (Test-Path $propertiesPath)) {
Write-Host "缺少 android\keystore.properties:发版包必须用根目录 android.keystore 签名" -ForegroundColor Red
Write-Host "照着同目录的 keystore.properties.example 补全后重试"
exit 1
}
$properties = @{}
Get-Content $propertiesPath | ForEach-Object {
$line = $_.Trim()
if ($line -and -not $line.StartsWith("#")) {
$index = $line.IndexOf("=")
if (0 -lt $index) {
$properties[$line.Substring(0, $index).Trim()] = $line.Substring($index + 1).Trim()
}
}
}
if (-not $properties["storePassword"] -or -not $properties["keyPassword"]) {
Write-Host "android\keystore.properties 里的 storePassword / keyPassword 还没填" -ForegroundColor Red
exit 1
}
$storeFile = [System.IO.Path]::GetFullPath((Join-Path (Join-Path $root "android") $properties["storeFile"]))
if (-not (Test-Path $storeFile)) {
Write-Host "找不到签名文件:$storeFile" -ForegroundColor Red
exit 1
}
if (-not $SkipSync) {
& pnpm run android:sync:prod
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}
Push-Location (Join-Path $root "android")
try {
& .\gradlew.bat :app:assembleRelease --console=plain
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} finally {
Pop-Location
}
$outputDir = Join-Path $root "android\app\build\outputs\apk\release"
$apk = Get-ChildItem $outputDir -Filter "app-release*.apk" -ErrorAction SilentlyContinue |
Where-Object { -not $_.Name.Contains("unsigned") } |
Select-Object -First 1
if (-not $apk) {
Write-Host "没有产出已签名的 release 包,检查 android\app\build.gradle 的 signingConfigs" -ForegroundColor Red
exit 1
}
$targetDir = Join-Path $root "android\app\release"
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
$target = Join-Path $targetDir "app-release.apk"
Copy-Item $apk.FullName $target -Force
$gradle = Get-Content (Join-Path $root "android\app\build.gradle") -Raw
$versionCode = [regex]::Match($gradle, 'versionCode\s+(\d+)').Groups[1].Value
$versionName = [regex]::Match($gradle, 'versionName\s+"([^"]+)"').Groups[1].Value
$file = Get-Item $target
Write-Host ""
Write-Host "APK android\app\release\app-release.apk"
Write-Host "version $versionName ($versionCode)"
Write-Host "size $($file.Length)"
Write-Host "sha256 $((Get-FileHash $target -Algorithm SHA256).Hash.ToLower())"
# 顺手把签名证书打出来,对不上 3E:9C:CC:8A 就说明钥匙用错了
$sdk = $env:ANDROID_HOME
if (-not $sdk) { $sdk = $env:ANDROID_SDK_ROOT }
if (-not $sdk) { $sdk = Join-Path $env:LOCALAPPDATA "Android\Sdk" }
$buildTools = Join-Path $sdk "build-tools"
if (Test-Path $buildTools) {
$latest = Get-ChildItem $buildTools -Directory | Sort-Object Name | Select-Object -Last 1
$signer = Join-Path $latest.FullName "apksigner.bat"
if (Test-Path $signer) {
& $signer verify --print-certs $target | Select-String "SHA-256 digest" | ForEach-Object {
Write-Host "cert $($_.Line.Trim())"
}
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ if ($Mode -eq "dev") {
$env:VITE_API_BASE_URL = if ($env:ANDROID_API_BASE_URL) { $env:VITE_API_BASE_URL = if ($env:ANDROID_API_BASE_URL) {
$env:ANDROID_API_BASE_URL $env:ANDROID_API_BASE_URL
} else { } else {
"http://192.168.11.14:18091" "http://192.168.11.18:18091"
} }
Write-Host "接口地址(开发):$env:VITE_API_BASE_URL" Write-Host "接口地址(开发):$env:VITE_API_BASE_URL"
} else { } else {
+12
View File
@@ -76,6 +76,17 @@ async function listLedger(page: PointLedgerPage, options?: ListOptions): Promise
return await axios.post(`${BASE_URI}/ledger/list`, withCurrentStoreId(page)); return await axios.post(`${BASE_URI}/ledger/list`, withCurrentStoreId(page));
} }
/**
* 按流水 ID 查询积分流水。
*
* 不传 storeId:服务端按当前登录人的门店范围解析,非全局管理员天然只能查本店。
*/
async function ledgerDetail(id: string): Promise<PointLedger> {
return await axios.post(`${BASE_URI}/ledger/detail`, undefined, {
params: { id }
});
}
/** 人工调整积分,后端使用 adjustRequestId 保证幂等。 */ /** 人工调整积分,后端使用 adjustRequestId 保证幂等。 */
async function adjust(request: PointAdjustRequest): Promise<void> { async function adjust(request: PointAdjustRequest): Promise<void> {
await axios.post(`${BASE_URI}/adjust`, withCurrentStoreId(request)); await axios.post(`${BASE_URI}/adjust`, withCurrentStoreId(request));
@@ -177,6 +188,7 @@ export default {
detailByCustomerId, detailByCustomerId,
detail, detail,
listLedger, listLedger,
ledgerDetail,
adjust, adjust,
ruleList, ruleList,
ruleDetail, ruleDetail,
+31 -9
View File
@@ -26,6 +26,7 @@ import { getCurrentStoreId, withCurrentStoreId } from "@/utils/store";
const CONFIG_URI = "/gao/recycle/config"; const CONFIG_URI = "/gao/recycle/config";
const EXCHANGE_URI = "/gao/recycle/exchange"; const EXCHANGE_URI = "/gao/recycle/exchange";
const ACCOUNT_URI = "/gao/recycle/account"; const ACCOUNT_URI = "/gao/recycle/account";
const LEDGER_URI = "/gao/recycle/ledger";
const PAYMENT_URI = "/gao/recycle/payment"; const PAYMENT_URI = "/gao/recycle/payment";
const STAT_URI = "/gao/recycle/stat"; const STAT_URI = "/gao/recycle/stat";
@@ -119,9 +120,11 @@ async function accountList(customerId: string): Promise<RecycleAccount[]> {
} }
/** 按客户分页查询有余额的回收物及全门店汇总。 */ /** 按客户分页查询有余额的回收物及全门店汇总。 */
async function accountCustomers(offset: number, limit: number, recycleItemId?: string, keyword?: string, customerIds?: string[]): Promise<RecycleCustomerAccountPage> { async function accountCustomers(index: number, size: number, recycleItemId?: string, keyword?: string, customerIds?: string[]): Promise<RecycleCustomerAccountPage> {
return await axios.post(`${ACCOUNT_URI}/customers`, undefined, { return await axios.post(`${ACCOUNT_URI}/customers`, {
params: { storeId: getCurrentStoreId() || undefined, offset, limit, recycleItemId: recycleItemId || undefined, keyword: keyword || undefined, customerIds: customerIds?.length ? customerIds.join(",") : undefined } storeId: getCurrentStoreId() || undefined, index, size,
recycleItemId: recycleItemId || undefined, keyword: keyword || undefined,
customerIds: customerIds?.length ? customerIds : undefined
}); });
} }
@@ -130,11 +133,27 @@ async function accountItems(): Promise<RecycleItem[]> {
return await axios.post(`${ACCOUNT_URI}/items`, undefined, { params: { storeId: getCurrentStoreId() || undefined } }); return await axios.post(`${ACCOUNT_URI}/items`, undefined, { params: { storeId: getCurrentStoreId() || undefined } });
} }
/** 额度流水,服务端当前最多返回 100 条。 */ /** 分页查询回收物额度流水。 */
async function accountLedger(customerId: string): Promise<RecycleLedger[]> { async function ledgerList(page: {
return await axios.post(`${ACCOUNT_URI}/ledger`, undefined, { index: number; size: number; customerId?: string; recycleItemId?: string; keyword?: string;
params: { storeId: getCurrentStoreId() || undefined, customerId } bizType?: string; beginAt?: number; endAt?: number;
}); }): Promise<RecyclePageResult<RecycleLedger>> {
return await axios.post(`${LEDGER_URI}/list`, { ...page, storeId: getCurrentStoreId() || undefined });
}
/** 查询回收物额度流水详情。 */
async function ledgerDetail(id: string): Promise<RecycleLedger> {
return await axios.post(`${LEDGER_URI}/detail`, undefined, { params: { id } });
}
/** 查询回收物支付详情。 */
async function paymentDetail(id: string): Promise<RecyclePayment> {
return await axios.post(`${PAYMENT_URI}/detail`, undefined, { params: { id } });
}
/** 按客户分页查询额度流水。 */
async function accountLedger(customerId: string, index: number, size: number): Promise<RecyclePageResult<RecycleLedger>> {
return await ledgerList({ customerId, index, size });
} }
/** /**
@@ -143,7 +162,7 @@ async function accountLedger(customerId: string): Promise<RecycleLedger[]> {
* 减少不能超过可用额度;调整只动账面,不代表门店收到实物。 * 减少不能超过可用额度;调整只动账面,不代表门店收到实物。
*/ */
async function accountAdjust(request: RecycleAccountAdjustRequest): Promise<void> { async function accountAdjust(request: RecycleAccountAdjustRequest): Promise<void> {
await axios.post(`${ACCOUNT_URI}/adjust`, withCurrentStoreId(request)); await axios.post(`${LEDGER_URI}/adjust`, withCurrentStoreId(request));
} }
/** 某 SKU 的回收物产出配置。 */ /** 某 SKU 的回收物产出配置。 */
@@ -260,6 +279,9 @@ export default {
accountCustomers, accountCustomers,
accountItems, accountItems,
accountLedger, accountLedger,
ledgerList,
ledgerDetail,
paymentDetail,
accountAdjust, accountAdjust,
yieldList, yieldList,
yieldProductList, yieldProductList,
+37 -1
View File
@@ -64,6 +64,39 @@ html.theme-dark body {
box-sizing: border-box; box-sizing: border-box;
} }
// 消息提示避开顶部安全区和导航栏。
.t-message {
margin-top: calc(var(--tui-safe-top, 0px) + 48px);
&.message-enter-active {
animation: message-slide-in .5s;
}
&.message-leave-active {
animation: message-slide-out .45s;
}
}
@keyframes message-slide-in {
from {
transform: translateY(calc(-100% - var(--tui-safe-top, 0px) - 58px));
}
to {
transform: translateY(0);
}
}
@keyframes message-slide-out {
from {
transform: translateY(0);
}
to {
transform: translateY(calc(-100% - var(--tui-safe-top, 0px) - 58px));
}
}
/** /**
* 页面骨架(tui-page-layout / tui-page-content / tui-navbar / tui-tabbar)由 * 页面骨架(tui-page-layout / tui-page-content / tui-navbar / tui-tabbar)由
* timi-tdesign-mobile 的 page-layout.less 提供,这里只保留业务侧约定。 * timi-tdesign-mobile 的 page-layout.less 提供,这里只保留业务侧约定。
@@ -78,7 +111,7 @@ html.theme-dark body {
--td-search-square-radius: 1rem; --td-search-square-radius: 1rem;
top: -1rem; top: -1rem;
margin: -1rem 0 1rem 0; margin: -1rem 0 0 0;
padding: 1rem 1rem 0 1rem; padding: 1rem 1rem 0 1rem;
z-index: 10; z-index: 10;
position: sticky; position: sticky;
@@ -123,8 +156,11 @@ html.theme-dark body {
-webkit-overflow-scrolling: touch; -webkit-overflow-scrolling: touch;
.t-pull-down-refresh__track { .t-pull-down-refresh__track {
gap: 1rem;
height: auto; height: auto;
display: flex;
min-height: 100%; min-height: 100%;
flex-direction: column;
} }
&.has-dropdown-menu-navbar { &.has-dropdown-menu-navbar {
+53 -4
View File
@@ -40,11 +40,16 @@
:key="item.id" :key="item.id"
:title="getRecordEventName(item)" :title="getRecordEventName(item)"
:description="getRecordCustomerName(item)" :description="getRecordCustomerName(item)"
:note="`${formatRecordTime(item.registeredAt)}`" :note="formatRecordTime(item.registeredAt)"
arrow arrow
hover hover
@click="toRecordDetail(item)" @click="toRecordDetail(item)"
/> >
<template #left-icon>
<t-image v-if="getRecordPhotoURL(item)" :src="getRecordPhotoURL(item)" :alt="getRecordCustomerName(item)" fit="cover" class="avatar" />
<div v-else class="avatar fallback" v-text="getRecordCustomerName(item).slice(0, 1)" />
</template>
</t-cell>
</t-cell-group> </t-cell-group>
<center-tips v-else>该日暂无登记事件记录</center-tips> <center-tips v-else>该日暂无登记事件记录</center-tips>
</div> </div>
@@ -72,6 +77,7 @@
<script setup lang="ts"> <script setup lang="ts">
import StoreAPI from "@/api/StoreAPI"; import StoreAPI from "@/api/StoreAPI";
import EventRecordAPI from "@/api/EventRecordAPI";
import EventSelector from "@/components/EventSelector.vue"; import EventSelector from "@/components/EventSelector.vue";
import MonthCalendar from "@/components/monthCalendar/MonthCalendar.vue"; import MonthCalendar from "@/components/monthCalendar/MonthCalendar.vue";
import { buildMonthCalendarDays, type MonthCalendarDay } from "@/components/monthCalendar/monthCalendar"; import { buildMonthCalendarDays, type MonthCalendarDay } from "@/components/monthCalendar/monthCalendar";
@@ -79,6 +85,7 @@ import type {EventItem} from "@/types/EventItem";
import type {EventRecord} from "@/types/EventRecord"; import type {EventRecord} from "@/types/EventRecord";
import type {StoreBusinessDay} from "@/types/Store"; import type {StoreBusinessDay} from "@/types/Store";
import {getCurrentStoreId} from "@/utils/store"; import {getCurrentStoreId} from "@/utils/store";
import {getCustomerPhotoURL} from "@/utils/customer";
import {Time} from "timi-web"; import {Time} from "timi-web";
interface CalendarDay extends MonthCalendarDay { interface CalendarDay extends MonthCalendarDay {
@@ -126,6 +133,7 @@ const selectedDayTitle = ref("");
const selectedDayRecords = ref<EventRecord[]>([]); const selectedDayRecords = ref<EventRecord[]>([]);
const businessDayList = ref<StoreBusinessDay[]>([]); const businessDayList = ref<StoreBusinessDay[]>([]);
let businessDayRequestId = 0; let businessDayRequestId = 0;
let dayRecordRequestId = 0;
const selectedEventIdListProxy = computed({ const selectedEventIdListProxy = computed({
get: () => props.selectedEventIdList, get: () => props.selectedEventIdList,
@@ -199,7 +207,7 @@ function getDayRecords(dateText: string): EventRecord[] {
return filteredRecords.value.filter(item => getRecordDateText(item) === dateText); return filteredRecords.value.filter(item => getRecordDateText(item) === dateText);
} }
function openDayRecords(day: MonthCalendarDay): void { async function openDayRecords(day: MonthCalendarDay): Promise<void> {
const records = getDayRecords(day.dateText); const records = getDayRecords(day.dateText);
if (!records.length) { if (!records.length) {
return; return;
@@ -208,6 +216,31 @@ function openDayRecords(day: MonthCalendarDay): void {
selectedDayTitle.value = `${day.dateText} 登记事件记录`; selectedDayTitle.value = `${day.dateText} 登记事件记录`;
selectedDayRecords.value = [...records].sort((left, right) => (right.registeredAt || 0) - (left.registeredAt || 0)); selectedDayRecords.value = [...records].sort((left, right) => (right.registeredAt || 0) - (left.registeredAt || 0));
dayRecordVisible.value = true; dayRecordVisible.value = true;
const requestId = ++dayRecordRequestId;
const [year, month, date] = day.dateText.split("-").map(Number);
const begin = new Date(year, month - 1, date);
const end = new Date(year, month - 1, date, 23, 59, 59, 999);
const customerIds = [...new Set(records.map(item => item.customerId).filter((id): id is string => Boolean(id)))];
const eventIds = [...new Set(records.map(item => item.eventId).filter((id): id is string => Boolean(id)))];
try {
const result = await EventRecordAPI.list({
index: 0,
size: records.length,
storeId: resolvedStoreId.value,
customerId: customerIds.length === 1 ? customerIds[0] : undefined,
eventIdList: eventIds,
beginAt: Time.toTimestamp(begin),
endAt: Time.toTimestamp(end)
});
if (requestId !== dayRecordRequestId) return;
const customers = new Map((result.list || []).map(item => [item.id, item.customer]));
selectedDayRecords.value = selectedDayRecords.value.map(item => ({
...item,
customer: customers.get(item.id) || item.customer
}));
} catch {
// 记录资料不可用时保留姓名占位。
}
} }
function openRecordList(): void { function openRecordList(): void {
@@ -243,6 +276,10 @@ function getRecordCustomerName(record: EventRecord): string {
return record.customer?.name || props.customerName || record.customerId || "未知客户"; return record.customer?.name || props.customerName || record.customerId || "未知客户";
} }
function getRecordPhotoURL(record: EventRecord): string {
return getCustomerPhotoURL(record.customer, 64);
}
function formatRecordTime(value?: number): string { function formatRecordTime(value?: number): string {
if (!value) { if (!value) {
return "-"; return "-";
@@ -252,7 +289,7 @@ function formatRecordTime(value?: number): string {
if (!date) { if (!date) {
return "-"; return "-";
} }
return Time.toDateTime(date); return Time.toTime(date);
} }
function getRecordDateText(record: EventRecord): string { function getRecordDateText(record: EventRecord): string {
@@ -341,6 +378,18 @@ function toDateValue(date: Date): number {
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;
} }
.avatar {
width: 3.5rem;
height: 3.5rem;
}
.fallback {
display: flex;
background: var(--td-bg-color-secondarycontainer);
align-items: center;
justify-content: center;
}
} }
.filter-popup { .filter-popup {
@@ -53,7 +53,8 @@ import type {
import type { PhotoItem } from "@/types/Photo.ts"; import type { PhotoItem } from "@/types/Photo.ts";
import { getAttachmentReadURL } from "@/utils/attachment.ts"; import { getAttachmentReadURL } from "@/utils/attachment.ts";
import { Message } from "@/utils/message.ts"; import { Message } from "@/utils/message.ts";
import { saveCapturedFilesFromInput } from "@/utils/twaBridge"; import { saveToAlbum } from "@/utils/mediaSaver";
import { useSettingStore } from "@/store/settingStore";
defineOptions({ defineOptions({
inheritAttrs: false inheritAttrs: false
@@ -77,6 +78,8 @@ const props = withDefaults(defineProps<Props>(), {
required: false required: false
}); });
const settingStore = useSettingStore();
const emit = defineEmits<{ const emit = defineEmits<{
"update:items": [items: PhotoItem[]]; "update:items": [items: PhotoItem[]];
select: [selection: AttachmentSelectorSelection]; select: [selection: AttachmentSelectorSelection];
@@ -89,7 +92,13 @@ const isBusy = computed(() => props.busy || isUploading.value);
const attachmentItems = computed(() => props.items.map(toAttachmentSelectorItem)); const attachmentItems = computed(() => props.items.map(toAttachmentSelectorItem));
async function handleSelect(selection: AttachmentSelectorSelection): Promise<void> { async function handleSelect(selection: AttachmentSelectorSelection): Promise<void> {
saveCapturedFilesFromInput(selection.input, selection.files); // 直接拍摄的媒体额外存一份到系统相册,可在「应用设置」里关掉;失败不阻塞上传
if (settingStore.albumSave && selection.input.capture && selection.files.length) {
const mediaType: "image" | "video" = selection.input.accept.toLowerCase().includes("video") ? "video" : "image";
for (const file of selection.files) {
void saveToAlbum(file, mediaType).catch(() => Message.warning("保存到系统相册失败"));
}
}
if (!props.upload) { if (!props.upload) {
emit("select", selection); emit("select", selection);
return; return;
-3
View File
@@ -12,7 +12,6 @@ import { VCan, VRole } from "timi-web-api/utils/directives/Access";
import type { ApiResponse } from "timi-web-api"; import type { ApiResponse } from "timi-web-api";
import { Message } from "@/utils/message"; import { Message } from "@/utils/message";
import { runAutoUpdate } from "@/composables/useAppUpdate"; import { runAutoUpdate } from "@/composables/useAppUpdate";
import { initializeTwaBridge } from "@/utils/twaBridge";
import { VEntranceTransition } from "timi-tdesign-mobile"; import { VEntranceTransition } from "timi-tdesign-mobile";
import timiWebStyle from "timi-web/src/assets/style/timi-web.less?inline"; import timiWebStyle from "timi-web/src/assets/style/timi-web.less?inline";
import tdesignCustomStyle from "timi-tdesign-mobile/src/assets/style/tdesign-custom.less?inline"; import tdesignCustomStyle from "timi-tdesign-mobile/src/assets/style/tdesign-custom.less?inline";
@@ -29,8 +28,6 @@ export const pinia = createPinia();
const apiBaseURL = import.meta.env.VITE_API_BASE_URL as string | undefined; const apiBaseURL = import.meta.env.VITE_API_BASE_URL as string | undefined;
const libraryOverrideStyleId = "library-override-style"; const libraryOverrideStyleId = "library-override-style";
initializeTwaBridge();
function mountLibraryOverrideStyle(): void { function mountLibraryOverrideStyle(): void {
const oldStyle = document.getElementById(libraryOverrideStyleId); const oldStyle = document.getElementById(libraryOverrideStyleId);
oldStyle?.remove(); oldStyle?.remove();
+105 -45
View File
@@ -1,58 +1,105 @@
<template> <template>
<div class="tui-page-layout tui-navbar customer-recycle-list"> <div class="tui-page-layout tui-navbar customer-recycle-list">
<t-navbar fixed :z-index="20" title="客户回收物" left-arrow @left-click="$router.back()" /> <t-navbar
<main v-can="permissionCodes.recycleAccount.read" class="tui-page-content scroll column"> fixed
<t-pull-down-refresh v-model="refreshing" class="pull-refresh" :refresh-timeout="30000" @refresh="reload" :z-index="20"
@scrolltolower="loadMore"> title="客户回收物"
left-arrow
@left-click="$router.back()"
/>
<master-detail-page
v-can="permissionCodes.recycleAccount.read"
class="list"
:split="isWide"
:selected="!!selectedCustomerId"
:direction="paneDirection"
>
<template #master>
<t-pull-down-refresh
v-model="refreshing"
class="pull-refresh"
:refresh-timeout="30000"
@refresh="reload"
@scrolltolower="loadMore"
>
<div class="filters glass"> <div class="filters glass">
<t-input v-model.trim="keyword" type="search" borderless clearable placeholder="搜索客户姓名、拼音、编码"> <t-input v-model.trim="keyword" type="search" borderless clearable placeholder="搜索客户姓名、拼音、编码">
<template #suffix-icon> <template #suffix-icon>
<t-button size="extra-small" theme="primary" variant="outline" :content="customerIds.length ? `已选 ${customerIds.length} 人` : '选择客户'" @click.stop="customerVisible = true" /> <t-button
size="extra-small"
theme="primary"
variant="outline"
:content="customerIds.length ? `已选 ${customerIds.length} 人` : '选择客户'"
@click.stop="customerVisible = true"
/>
</template> </template>
</t-input> </t-input>
<t-dropdown-menu ref="filterMenuRef" class="menus"> <t-dropdown-menu ref="filterMenuRef" class="menus">
<t-dropdown-item :label="selectedName" :options="[]" @open="openItemPicker" /> <t-dropdown-item :label="selectedName" :options="[]" @open="openItemPicker" />
</t-dropdown-menu> </t-dropdown-menu>
</div> </div>
<t-cell-group theme="card"> <div class="list-wrap">
<t-cell title="汇总"> <t-cell-group theme="card">
<template v-if="selectedId" #note> <t-cell title="汇总">
<t-button size="extra-small" variant="outline" content="清除" @click="clearItem" /> <template #note>
</template> <t-button v-if="selectedId" size="extra-small" variant="outline" content="清除" @click="clearItem" />
<template #description> <div class="tags">
<div class="tags"> <t-tag
<t-tag v-for="item in displayedTotals" :key="item.recycleItemId" theme="primary" v-for="item in displayedTotals" :key="item.recycleItemId" theme="primary"
variant="light" variant="light"
:content="accountText(item)" /> :content="accountText(item)"
<span v-if="!displayedTotals.length" v-text="loading ? '正在加载' : '暂无回收物'" /> />
</div> <span v-if="!displayedTotals.length" v-text="loading ? '正在加载' : '暂无回收物'" />
</template> </div>
</t-cell> </template>
</t-cell-group> </t-cell>
<t-cell-group v-if="items.length" theme="card" class="fix-last-cell-line"> </t-cell-group>
<customer-cell v-for="row in items" :key="row.customer.id" :customer="row.customer" arrow hover <t-cell-group v-if="items.length" theme="card" class="fix-last-cell-line">
@click="openCustomer(row.customer)"> <customer-cell
<template #description> v-for="row in items"
<div class="tags"> :key="row.customer.id"
<t-tag v-for="account in row.accounts" :key="account.recycleItemId" theme="primary" :customer="row.customer"
variant="light" arrow
:content="accountText(account)" /> hover
</div> @click="openCustomer(row.customer)"
</template> >
</customer-cell> <template #description>
</t-cell-group> <div class="tags">
<center-tips v-else :content="loading ? '正在加载客户回收物' : '暂无客户回收物'" /> <t-tag
<center-tips v-if="items.length" v-for="account in row.accounts"
:content="loading ? '正在加载' : noMore ? `共 ${total} 位客户` : '上拉加载更多'" /> :key="account.recycleItemId" theme="primary"
size="small"
variant="light"
:content="accountText(account)"
/>
</div>
</template>
</customer-cell>
</t-cell-group>
<center-tips
v-else
:content="loading ? '正在加载客户回收物' : '暂无客户回收物'"
/>
<center-tips
v-if="items.length"
:content="loading ? '正在加载' : noMore ? `共 ${total} 位客户` : '上拉加载更多'"
/>
</div>
</t-pull-down-refresh> </t-pull-down-refresh>
</main> </template>
<template #detail>
<recycle-account-page :key="selectedCustomerId" :initial-customer-id="selectedCustomerId" />
</template>
</master-detail-page>
<customer-selector v-model="customerIds" v-model:visible="customerVisible" :initial-keyword="keyword" selection-mode="multiple" /> <customer-selector v-model="customerIds" v-model:visible="customerVisible" :initial-keyword="keyword" selection-mode="multiple" />
<recycle-item-picker-popup v-model:visible="filterVisible" :selected-id="selectedId" account-items @select="selectItem" /> <recycle-item-picker-popup v-model:visible="filterVisible" :selected-id="selectedId" account-items @select="selectItem" />
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile";
import RecycleAPI from "@/api/RecycleAPI"; import RecycleAPI from "@/api/RecycleAPI";
import RecycleAccountPage from "@/pages/recycle/RecycleAccount.vue";
import RecycleItemPickerPopup from "@/pages/recycle/components/RecycleItemPickerPopup.vue"; import RecycleItemPickerPopup from "@/pages/recycle/components/RecycleItemPickerPopup.vue";
import CustomerSelector from "@/components/CustomerSelector.vue"; import CustomerSelector from "@/components/CustomerSelector.vue";
import type { Customer } from "@/types/Customer"; import type { Customer } from "@/types/Customer";
@@ -63,7 +110,11 @@ import { permissionCodes } from "@/utils/permission";
import { getRecycleQuantityText } from "@/utils/recycle"; import { getRecycleQuantityText } from "@/utils/recycle";
defineOptions({ name: "CustomerRecycleList" }); defineOptions({ name: "CustomerRecycleList" });
const router = useRouter(); const route = useRoute();
const { selectedId: selectedCustomerId, isWide, paneDirection, openDetail } = useMasterDetailPane({
path: "/management/customer-recycle-accounts",
detail: id => `/management/recycle-accounts?customerId=${encodeURIComponent(id)}&transitionDepth=${Number(route.meta.depth ?? 0) + 1}`
});
const items = ref<RecycleCustomerAccountPage["list"]>([]); const items = ref<RecycleCustomerAccountPage["list"]>([]);
const totals = ref<RecycleAccount[]>([]); const totals = ref<RecycleAccount[]>([]);
const selectedId = ref(""); const selectedId = ref("");
@@ -79,6 +130,7 @@ const refreshing = ref(false);
const noMore = ref(false); const noMore = ref(false);
const total = ref(0); const total = ref(0);
let version = 0; let version = 0;
let pageIndex = 0;
const selectedName = computed(() => selectedItem.value?.name || "全部回收物"); const selectedName = computed(() => selectedItem.value?.name || "全部回收物");
const displayedTotals = computed(() => selectedId.value ? totals.value.filter(item => item.recycleItemId === selectedId.value) : totals.value); const displayedTotals = computed(() => selectedId.value ? totals.value.filter(item => item.recycleItemId === selectedId.value) : totals.value);
@@ -89,15 +141,16 @@ function accountText(account: RecycleAccount): string {
async function fetchPage(reset: boolean): Promise<void> { async function fetchPage(reset: boolean): Promise<void> {
if (!reset && (loading.value || noMore.value)) return; if (!reset && (loading.value || noMore.value)) return;
const token = reset ? ++version : version; const token = reset ? ++version : version;
const offset = reset ? 0 : items.value.length; const index = reset ? 0 : pageIndex;
if (reset) { if (reset) {
items.value = []; items.value = [];
noMore.value = false; noMore.value = false;
} }
loading.value = true; loading.value = true;
try { try {
const result = await RecycleAPI.accountCustomers(offset, 20, selectedId.value, keyword.value, customerIds.value); const result = await RecycleAPI.accountCustomers(index, 20, selectedId.value, keyword.value, customerIds.value);
if (token !== version) return; if (token !== version) return;
pageIndex = index + 1;
items.value = reset ? result.list : [...items.value, ...result.list]; items.value = reset ? result.list : [...items.value, ...result.list];
totals.value = result.totals; totals.value = result.totals;
total.value = result.total; total.value = result.total;
@@ -159,8 +212,8 @@ onUnmounted(() => {
if (searchTimer) clearTimeout(searchTimer); if (searchTimer) clearTimeout(searchTimer);
}); });
async function openCustomer(customer: Customer): Promise<void> { function openCustomer(customer: Customer): void {
if (customer.id) await router.push({ name: "RecycleAccount", query: { customerId: customer.id } }); if (customer.id) openDetail(customer.id);
} }
let wasDeactivated = false; let wasDeactivated = false;
@@ -175,11 +228,18 @@ onActivated(async () => {
<style scoped lang="less"> <style scoped lang="less">
.customer-recycle-list { .customer-recycle-list {
.tags {
gap: .375rem; .list-wrap {
gap: 1rem;
display: flex; display: flex;
padding: .25rem 0; flex-direction: column;
flex-wrap: wrap;
.tags {
gap: .375rem;
display: flex;
padding: .25rem 0;
flex-wrap: wrap;
}
} }
} }
</style> </style>
+4
View File
@@ -57,6 +57,9 @@ const props = withDefaults(defineProps<{
}>(), { }>(), {
notifyId: "" notifyId: ""
}); });
const emit = defineEmits<{
read: [];
}>();
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
@@ -171,6 +174,7 @@ async function markRead(item: NotifyDetail, requestToken: number): Promise<void>
} }
try { try {
await NotifyAPI.markInternalRead(item.id); await NotifyAPI.markInternalRead(item.id);
emit("read");
if (requestToken === loadToken && detail.value) { if (requestToken === loadToken && detail.value) {
detail.value = { detail.value = {
...detail.value, ...detail.value,
+11
View File
@@ -94,6 +94,7 @@
<user-notify-detail <user-notify-detail
:key="`detail-${selectedId}`" :key="`detail-${selectedId}`"
:notify-id="selectedId" :notify-id="selectedId"
@read="handleDetailRead"
/> />
</template> </template>
</master-detail-page> </master-detail-page>
@@ -233,6 +234,16 @@ async function refresh(): Promise<void> {
} }
} }
async function handleDetailRead(): Promise<void> {
try {
await reloadList();
await loadUnreadCount();
} catch (error) {
console.warn("已读通知刷新失败", error);
Message.error("通知列表刷新失败");
}
}
// ---------- 操作 ---------- // ---------- 操作 ----------
const isMarkingAllRead = ref(false); const isMarkingAllRead = ref(false);
+7
View File
@@ -169,11 +169,16 @@ const props = withDefaults(defineProps<{
configId: "" configId: ""
}); });
const emit = defineEmits<{ saved: [] }>();
const route = useRoute(); const route = useRoute();
/** 内联渲染时 id 来自 prop,整页渲染时来自路由参数 */ /** 内联渲染时 id 来自 prop,整页渲染时来自路由参数 */
const currentId = computed(() => props.configId || String(route.params.id || "")); const currentId = computed(() => props.configId || String(route.params.id || ""));
const routeNavBarTitle = computed(() => { const routeNavBarTitle = computed(() => {
if (pane && !currentId.value) {
return "新增套餐配置";
}
// 内联时路由停在列表页,标题只能看当前是新增还是编辑 // 内联时路由停在列表页,标题只能看当前是新增还是编辑
if (props.configId) { if (props.configId) {
return "编辑套餐配置"; return "编辑套餐配置";
@@ -452,6 +457,7 @@ async function save(): Promise<void> {
const id = await PackageAPI.configCreate(payload); const id = await PackageAPI.configCreate(payload);
Message.success("套餐配置已创建"); Message.success("套餐配置已创建");
if (pane) { if (pane) {
emit("saved");
pane.close(true); pane.close(true);
return; return;
} }
@@ -461,6 +467,7 @@ async function save(): Promise<void> {
await PackageAPI.configUpdate(payload); await PackageAPI.configUpdate(payload);
Message.success("套餐配置已保存"); Message.success("套餐配置已保存");
if (pane) { if (pane) {
emit("saved");
pane.close(true); pane.close(true);
return; return;
} }
+8 -2
View File
@@ -103,7 +103,8 @@
</t-pull-down-refresh> </t-pull-down-refresh>
</template> </template>
<template #detail> <template #detail>
<package-config-edit v-if="editing" :key="`edit-${selectedId}`" :config-id="selectedId" /> <package-config-edit v-if="selectedId === createPaneId" :key="createPaneId" @saved="reload" />
<package-config-edit v-else-if="editing" :key="`edit-${selectedId}`" :config-id="selectedId" @saved="reload" />
<package-config-detail <package-config-detail
v-else v-else
:key="`detail-${selectedId}-${detailVersion}`" :key="`detail-${selectedId}-${detailVersion}`"
@@ -137,10 +138,11 @@ const router = useRouter();
const userStore = useUserStore(); const userStore = useUserStore();
// 选中项、编辑态、切换方向、关闭逻辑、转屏、query 同步都在这里 // 选中项、编辑态、切换方向、关闭逻辑、转屏、query 同步都在这里
const createPaneId = "__create__";
const { selectedId, editing, detailVersion, paneDirection, isWide, openDetail, openEdit } = const { selectedId, editing, detailVersion, paneDirection, isWide, openDetail, openEdit } =
useMasterDetailPane({ useMasterDetailPane({
path: "/product/package-configs", path: "/product/package-configs",
detail: id => `/product/package-configs/${id}`, detail: id => id === createPaneId ? "/product/package-configs/create" : `/product/package-configs/${id}`,
edit: id => `/product/package-configs/${id}/edit` edit: id => `/product/package-configs/${id}/edit`
}); });
@@ -216,6 +218,10 @@ watch(keyword, () => {
}); });
async function toCreate(): Promise<void> { async function toCreate(): Promise<void> {
if (isWide.value && userStore.hasPermissions(permissionCodes.packageConfig.read)) {
openDetail(createPaneId);
return;
}
await router.push("/product/package-configs/create"); await router.push("/product/package-configs/create");
} }
+19 -4
View File
@@ -5,7 +5,7 @@
:z-index="20" :z-index="20"
:title="routeNavBarTitle" :title="routeNavBarTitle"
left-arrow left-arrow
@left-click="$router.back()" @left-click="exit"
> >
<template #right> <template #right>
<t-button <t-button
@@ -335,7 +335,7 @@
import DateTimeNowPicker from "@/components/DateTimeNowPicker.vue"; import DateTimeNowPicker from "@/components/DateTimeNowPicker.vue";
import { Time } from "timi-web"; import { Time } from "timi-web";
import { useUserStore } from "timi-web-api"; import { useUserStore } from "timi-web-api";
import { BottomPopup } from "timi-tdesign-mobile"; import { BottomPopup, usePane } from "timi-tdesign-mobile";
import { DialogPlugin } from "tdesign-mobile-vue"; import { DialogPlugin } from "tdesign-mobile-vue";
import CustomerAPI from "@/api/CustomerAPI"; import CustomerAPI from "@/api/CustomerAPI";
import PackageAPI from "@/api/PackageAPI"; import PackageAPI from "@/api/PackageAPI";
@@ -381,9 +381,13 @@ defineOptions({
name: "PackagePurchase" name: "PackagePurchase"
}); });
const props = defineProps<{ createOrder?: boolean }>();
const emit = defineEmits<{ created: [orderId: string] }>();
const pane = usePane();
const route = useRoute(); const route = useRoute();
const routeNavBarTitle = computed(() => { const routeNavBarTitle = computed(() => {
if (props.createOrder) return "创建客户套餐";
switch (route.name) { switch (route.name) {
case "PackagePurchase": case "PackagePurchase":
return "购买套餐"; return "购买套餐";
@@ -394,13 +398,20 @@ const routeNavBarTitle = computed(() => {
} }
}); });
const router = useRouter(); const router = useRouter();
function exit(): void {
if (pane) {
pane.close();
return;
}
void router.back();
}
const settingStore = useSettingStore(); const settingStore = useSettingStore();
const userStore = useUserStore(); const userStore = useUserStore();
// ---------- 套餐配置 ---------- // ---------- 套餐配置 ----------
const configId = computed(() => String(route.params.id || "")); const configId = computed(() => props.createOrder ? "" : String(route.params.id || ""));
const isCustomerPackageCreate = computed(() => route.name === "CustomerPackageCreate"); const isCustomerPackageCreate = computed(() => !!props.createOrder || route.name === "CustomerPackageCreate");
const config = ref<GaoPackageConfig>(); const config = ref<GaoPackageConfig>();
const configList = ref<GaoPackageConfig[]>([]); const configList = ref<GaoPackageConfig[]>([]);
const configSelectorVisible = ref(false); const configSelectorVisible = ref(false);
@@ -914,6 +925,10 @@ async function purchasePackage(): Promise<void> {
emitListDataChanged(listDataEventKeys.productStockChanged); emitListDataChanged(listDataEventKeys.productStockChanged);
await settingStore.playRegisterSuccessSound(); await settingStore.playRegisterSuccessSound();
Message.success(fulfillAll.value ? "套餐、收款及履约已完成" : paymentVerified.value ? "套餐及已核销收款已完成" : receiveFullPayment.value ? "套餐及全额收款已完成" : "套餐购买已提交"); Message.success(fulfillAll.value ? "套餐、收款及履约已完成" : paymentVerified.value ? "套餐及已核销收款已完成" : receiveFullPayment.value ? "套餐及全额收款已完成" : "套餐购买已提交");
if (pane && props.createOrder) {
emit("created", result.salesOrderId);
return;
}
await router.replace({ await router.replace({
name: "SalesOrderDetail", name: "SalesOrderDetail",
params: { id: result.salesOrderId }, params: { id: result.salesOrderId },
+96 -45
View File
@@ -5,7 +5,7 @@
:z-index="20" :z-index="20"
title="积分流水详情" title="积分流水详情"
left-arrow left-arrow
@left-click="$router.back()" @left-click="goBack"
/> />
<main class="tui-page-content scroll column"> <main class="tui-page-content scroll column">
<div v-if="customer" v-can="permissionCodes.point.ledgerRead" class="point-ledger-detail"> <div v-if="customer" v-can="permissionCodes.point.ledgerRead" class="point-ledger-detail">
@@ -83,7 +83,7 @@
<center-tips v-else :content="getRuleEmptyText()" /> <center-tips v-else :content="getRuleEmptyText()" />
</t-cell-group> </t-cell-group>
</template> </template>
<t-empty v-else :description="isLoading ? '正在加载积分流水' : '积分流水快照不存在,请从积分流水列表进入'" /> <t-empty v-else :description="isLoading ? '正在加载积分流水' : '积分流水不存在或无权查看'" />
</div> </div>
</main> </main>
</div> </div>
@@ -92,11 +92,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { TimeLabel, Text } from "timi-web"; import { TimeLabel, Text } from "timi-web";
import { useUserStore } from "timi-web-api"; import { useUserStore } from "timi-web-api";
import { useExpandToMaster, usePane } from "timi-tdesign-mobile";
import CustomerAPI from "@/api/CustomerAPI"; import CustomerAPI from "@/api/CustomerAPI";
import EventAPI from "@/api/EventAPI"; import EventAPI from "@/api/EventAPI";
import EventRecordAPI from "@/api/EventRecordAPI"; import EventRecordAPI from "@/api/EventRecordAPI";
import PointAPI from "@/api/PointAPI"; import PointAPI from "@/api/PointAPI";
import CustomerProfileCard from "@/components/CustomerProfileCard.vue"; import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
import { buildLedgerSubPane } from "@/pages/point/component/ledgerPane";
import type { Customer } from "@/types/Customer"; import type { Customer } from "@/types/Customer";
import type { EventItem } from "@/types/EventItem"; import type { EventItem } from "@/types/EventItem";
import type { EventRecord } from "@/types/EventRecord"; import type { EventRecord } from "@/types/EventRecord";
@@ -109,10 +111,48 @@ defineOptions({
name: "PointLedgerDetail" name: "PointLedgerDetail"
}); });
const props = withDefaults(defineProps<{
/** 指定流水 ID 时忽略路由参数,用于平板主从分栏的内联渲染。 */
ledgerId?: string;
}>(), {
ledgerId: ""
});
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const userStore = useUserStore(); const userStore = useUserStore();
function resolveId(): string {
return props.ledgerId || String(route.params.id || "");
}
// 竖屏整页进来后转成横屏:回到列表页并恢复右栏选中,而不是继续停在整页详情
useExpandToMaster({
path: "/management/points/ledger",
id: () => resolveId()
});
/** 非空说明当前被内联在主从分栏的右栏里 */
const pane = usePane();
/**
* 尝试在右栏压入一层子页(分栏的第三层)。
*
* 接不住时有三种情况:整页打开详情、窄屏、宿主列表没声明子页槽,
* 此时返回 false,调用方退回整页跳转。
*/
function openSub(view: string): boolean {
return pane?.openSub(view) ?? false;
}
function goBack(): void {
if (pane) {
pane.close();
return;
}
void router.back();
}
// ---------- 权限 ---------- // ---------- 权限 ----------
const canReadCustomer = computed(() => userStore.hasPermissions(permissionCodes.customer.read)); const canReadCustomer = computed(() => userStore.hasPermissions(permissionCodes.customer.read));
@@ -139,32 +179,6 @@ function isDeletedEventRevokeLedger(value?: PointLedger): boolean {
return value?.changeType === "REVOKE" && value?.triggerSourceType === "EVENT_RECORD" && !value.triggerSourceId; return value?.changeType === "REVOKE" && value?.triggerSourceType === "EVENT_RECORD" && !value.triggerSourceId;
} }
function getQueryText(key: string): string {
const value = route.query[key];
return Array.isArray(value) ? String(value[0] || "") : String(value || "");
}
function parseLedgerSnapshot(): PointLedger | undefined {
const snapshotText = getQueryText("snapshot");
if (!snapshotText) {
return undefined;
}
try {
const snapshot = JSON.parse(snapshotText) as PointLedger;
if (!snapshot || typeof snapshot !== "object") {
return undefined;
}
return {
...snapshot,
id: String(route.params.id || snapshot.id || "")
};
} catch (error) {
console.warn("积分流水快照解析失败", error);
return undefined;
}
}
async function loadOptional<T>(loader: () => Promise<T>, message: string): Promise<T | undefined> { async function loadOptional<T>(loader: () => Promise<T>, message: string): Promise<T | undefined> {
try { try {
return await loader(); return await loader();
@@ -175,17 +189,24 @@ async function loadOptional<T>(loader: () => Promise<T>, message: string): Promi
} }
async function loadPageData(): Promise<void> { async function loadPageData(): Promise<void> {
ledger.value = parseLedgerSnapshot(); ledger.value = undefined;
customer.value = undefined; customer.value = undefined;
triggerEvent.value = undefined; triggerEvent.value = undefined;
eventRecord.value = undefined; eventRecord.value = undefined;
hitRule.value = undefined; hitRule.value = undefined;
if (!ledger.value) { const id = resolveId();
if (!id) {
return; return;
} }
isLoading.value = true; isLoading.value = true;
try { try {
// 流水只追加不修改,缺字段的旧链接一律以服务端这条为准
ledger.value = await PointAPI.ledgerDetail(id);
if (!ledger.value) {
return;
}
if (ledger.value.triggerSourceType === "EVENT_RECORD" && ledger.value.triggerSourceId && canReadEventRecord.value && !isDeletedEventRevoke.value) { if (ledger.value.triggerSourceType === "EVENT_RECORD" && ledger.value.triggerSourceId && canReadEventRecord.value && !isDeletedEventRevoke.value) {
eventRecord.value = await loadOptional(() => EventRecordAPI.detail(ledger.value!.triggerSourceId!), "积分流水关联事件记录加载失败"); eventRecord.value = await loadOptional(() => EventRecordAPI.detail(ledger.value!.triggerSourceId!), "积分流水关联事件记录加载失败");
} }
@@ -200,14 +221,20 @@ async function loadPageData(): Promise<void> {
const ruleResult = ledger.value.ruleId && canReadRule.value const ruleResult = ledger.value.ruleId && canReadRule.value
? loadOptional(() => PointAPI.ruleDetail(ledger.value!.ruleId!), "积分流水命中规则加载失败") ? loadOptional(() => PointAPI.ruleDetail(ledger.value!.ruleId!), "积分流水命中规则加载失败")
: Promise.resolve(undefined); : Promise.resolve(undefined);
const customerResult = !eventRecord.value?.customer && ledger.value.customerId && canReadCustomer.value // 详情接口已经把客户资料带回来了,只有缺失时才单独补一次
? loadOptional(() => CustomerAPI.detail(ledger.value!.customerId!), "积分流水客户加载失败") const customerResult = ledger.value.customer
: Promise.resolve(undefined); ? Promise.resolve(ledger.value.customer)
: !eventRecord.value?.customer && ledger.value.customerId && canReadCustomer.value
? loadOptional(() => CustomerAPI.detail(ledger.value!.customerId!), "积分流水客户加载失败")
: Promise.resolve(undefined);
[triggerEvent.value, hitRule.value, customer.value] = await Promise.all([eventResult, ruleResult, customerResult]); [triggerEvent.value, hitRule.value, customer.value] = await Promise.all([eventResult, ruleResult, customerResult]);
if (eventRecord.value?.customer) { if (eventRecord.value?.customer) {
customer.value = eventRecord.value.customer; customer.value = eventRecord.value.customer;
} }
} catch (error) {
console.warn("积分流水加载失败", error);
ledger.value = undefined;
} finally { } finally {
isLoading.value = false; isLoading.value = false;
} }
@@ -312,43 +339,54 @@ function getRuleEmptyText(): string {
// ---------- 导航 ---------- // ---------- 导航 ----------
async function toCustomerDetail(): Promise<void> { async function toCustomerDetail(): Promise<void> {
if (customer.value?.id) { const id = customer.value?.id;
await router.push(`/management/customers/${customer.value.id}`); if (!id || openSub(buildLedgerSubPane("customer", id))) {
return;
} }
await router.push(`/management/customers/${id}`);
} }
async function toPointAccount(): Promise<void> { async function toPointAccount(): Promise<void> {
if (!canReadPointAccount.value || !ledger.value?.accountId) { const accountId = ledger.value?.accountId;
if (!canReadPointAccount.value || !accountId) {
return;
}
if (openSub(buildLedgerSubPane("account", accountId, ledger.value?.storeId || ""))) {
return; return;
} }
await router.push({ await router.push({
name: "PointAccountDetail", name: "PointAccountDetail",
params: { id: ledger.value.accountId }, params: { id: accountId },
query: { query: {
storeId: ledger.value.storeId || "", storeId: ledger.value?.storeId || "",
transitionDepth: String(Number(route.meta.depth ?? 0) + 1) transitionDepth: String(Number(route.meta.depth ?? 0) + 1)
} }
}); });
} }
async function toEventDetail(): Promise<void> { async function toEventDetail(): Promise<void> {
if (!canReadEvent.value || !triggerEvent.value?.id) { const id = triggerEvent.value?.id;
if (!canReadEvent.value || !id) {
return;
}
if (openSub(buildLedgerSubPane("event", id))) {
return; return;
} }
await router.push({ await router.push({
name: "EventDetail", name: "EventDetail",
params: { id: triggerEvent.value.id }, params: { id },
query: { transitionDepth: String(Number(route.meta.depth ?? 0) + 1) } query: { transitionDepth: String(Number(route.meta.depth ?? 0) + 1) }
}); });
} }
async function toEventRecordDetail(): Promise<void> { async function toEventRecordDetail(): Promise<void> {
if (!eventRecord.value?.id) { const id = eventRecord.value?.id;
if (!id || openSub(buildLedgerSubPane("event-record", id))) {
return; return;
} }
await router.push({ await router.push({
name: "EventRecordDetail", name: "EventRecordDetail",
params: { id: eventRecord.value.id }, params: { id },
query: { query: {
transitionDepth: String(Number(route.meta.depth ?? 0) + 1), transitionDepth: String(Number(route.meta.depth ?? 0) + 1),
changeType: ledger.value?.changeType changeType: ledger.value?.changeType
@@ -357,17 +395,30 @@ async function toEventRecordDetail(): Promise<void> {
} }
async function toPointRuleDetail(): Promise<void> { async function toPointRuleDetail(): Promise<void> {
if (!canReadRule.value || !hitRule.value?.id) { const id = hitRule.value?.id;
if (!canReadRule.value || !id) {
return;
}
if (openSub(buildLedgerSubPane("rule", id))) {
return; return;
} }
await router.push({ await router.push({
name: "PointRuleDetail", name: "PointRuleDetail",
params: { id: hitRule.value.id }, params: { id },
query: { transitionDepth: String(Number(route.meta.depth ?? 0) + 1) } query: { transitionDepth: String(Number(route.meta.depth ?? 0) + 1) }
}); });
} }
watch(() => [route.params.id, route.query.snapshot], async () => { /**
* 重载判据:两个来源拼成一个字符串再 watch。
*
* 不能直接 watch `[props.ledgerId, route.params.id]`:读 `route.params.id` 会依赖
* 整个 `params` 对象,分栏里改个 query(进子页、返回)也会被连带触发,
* `loadPageData` 一进来就把 ledger 置空重拉,看起来就是详情页自己刷新了一遍。
*/
const reloadKey = computed(() => `${props.ledgerId}|${String(route.params.id || "")}`);
watch(reloadKey, async () => {
await loadPageData(); await loadPageData();
}, { immediate: true }); }, { immediate: true });
</script> </script>
+149 -135
View File
@@ -7,117 +7,136 @@
left-arrow left-arrow
@left-click="$router.back()" @left-click="$router.back()"
/> />
<main v-can="permissionCodes.point.ledgerRead" class="tui-page-content scroll column list"> <master-detail-page
<t-pull-down-refresh v-can="permissionCodes.point.ledgerRead"
class="pull-refresh" class="list"
v-model="isRefreshing" :split="isWide"
:refresh-timeout="30000" :selected="!!selectedId"
@refresh="reload" :direction="paneDirection"
@scrolltolower="load" :sub="!!subView"
> >
<div class="filters glass"> <template #master>
<t-input <t-pull-down-refresh
v-model="customerKeyword" class="pull-refresh"
class="customer" v-model="isRefreshing"
type="search" :refresh-timeout="30000"
borderless @refresh="reload"
placeholder="输入客户编码或姓名" @scrolltolower="load"
@clear="searchCustomer" >
@enter="searchCustomer" <div class="filters glass">
@input="searchCustomer" <t-input
> v-model="customerKeyword"
<template #suffix-icon> class="customer"
<t-button type="search"
size="extra-small" borderless
theme="primary" placeholder="输入客户编码或姓名"
variant="outline" @clear="searchCustomer"
content="选择客户" @enter="searchCustomer"
@click.stop="selectorVisible = true" @input="searchCustomer"
/>
</template>
</t-input>
<t-dropdown-menu class="menus">
<t-dropdown-item
v-model="changeTypeFilter"
label="流水类型"
:options="changeTypeOptions"
@change="selectChangeType"
/>
<t-dropdown-item
v-model="dateFilter"
:label="dateFilterLabel"
:options="dateFilterOptions"
@change="selectDateFilter"
/>
</t-dropdown-menu>
</div>
<div class="list-wrap">
<card-container v-if="customer" class="customer">
<customer-profile-card :customer="customer" />
</card-container>
<t-cell-group class="summary" theme="card">
<t-cell
title="开始时间"
:note="dateRange[0] || '-'"
arrow
@click="openStartDate"
/>
<t-cell
title="结束时间"
:note="dateRange[1] || '-'"
arrow
@click="openEndDate"
/>
</t-cell-group>
<t-cell-group v-if="pageResult.list.length" class="list" theme="card">
<t-cell
v-entrance-transition="{ step: 30 }"
v-for="item in pageResult.list"
:key="item.id"
class="item"
:arrow="!!item.id"
:hover="!!item.id"
@click="toDetail(item)"
> >
<template #leftIcon> <template #suffix-icon>
<t-image <t-button
v-if="getCustomerPhotoURL(item.customer!, 64)" size="extra-small"
:src="getCustomerPhotoURL(item.customer!, 64)" theme="primary"
fit="cover" variant="outline"
class="avatar" content="选择客户"
@click.stop="selectorVisible = true"
/> />
<div v-else class="avatar fallback" v-text="(item.customer?.name || item.customer?.code || '客').slice(0, 1)" />
</template> </template>
<template #title> </t-input>
<div class="title"> <t-dropdown-menu class="menus">
<t-tag <t-dropdown-item
class="type-icon" v-model="changeTypeFilter"
:theme="item.pointDelta && 0 < item.pointDelta ? 'success' : 'danger'" label="流水类型"
:content="getLedgerShortType(item)" :options="changeTypeOptions"
variant="outline" @change="selectChangeType"
/>
<t-dropdown-item
v-model="dateFilter"
:label="dateFilterLabel"
:options="dateFilterOptions"
@change="selectDateFilter"
/>
</t-dropdown-menu>
</div>
<div class="list-wrap">
<card-container v-if="customer" class="customer">
<customer-profile-card :customer="customer" />
</card-container>
<t-cell-group class="summary" theme="card">
<t-cell
title="开始时间"
:note="dateRange[0] || '-'"
arrow
@click="openStartDate"
/>
<t-cell
title="结束时间"
:note="dateRange[1] || '-'"
arrow
@click="openEndDate"
/>
</t-cell-group>
<t-cell-group v-if="pageResult.list.length" class="list" theme="card">
<t-cell
v-entrance-transition="{ step: 30 }"
v-for="item in pageResult.list"
:key="item.id"
class="item"
:arrow="!!item.id"
:hover="!!item.id"
@click="toDetail(item)"
>
<template #leftIcon>
<t-image
v-if="getCustomerPhotoURL(item.customer!, 64)"
:src="getCustomerPhotoURL(item.customer!, 64)"
fit="cover"
class="avatar"
/> />
<div class="name" v-text="item.customer?.name" /> <div v-else class="avatar fallback" v-text="(item.customer?.name || item.customer?.code || '客').slice(0, 1)" />
</div> </template>
</template> <template #title>
<template #description> <div class="title">
<div class="description"> <t-tag
<div> class="type-icon"
<span>时间:</span> :theme="item.pointDelta && 0 < item.pointDelta ? 'success' : 'danger'"
<time-label :timestamp="item.occurredAt" underline /> :content="getLedgerShortType(item)"
variant="outline"
/>
<div class="name" v-text="item.customer?.name" />
</div> </div>
<div v-text="`余额:${formatPointValue(item.balanceBefore)} → ${formatPointValue(item.balanceAfter)}`" /> </template>
<div v-text="item.remark" /> <template #description>
</div> <div class="description">
</template> <div>
<template #note> <span>时间:</span>
<div class="delta keep-text" :class="getLedgerTheme(item)" v-text="getLedgerDelta(item)" /> <time-label :timestamp="item.occurredAt" underline />
</template> </div>
</t-cell> <div v-text="`余额:${formatPointValue(item.balanceBefore)} → ${formatPointValue(item.balanceAfter)}`" />
</t-cell-group> <div v-text="item.remark" />
<center-tips :content="loadStateText" /> </div>
</div> </template>
</t-pull-down-refresh> <template #note>
</main> <div class="delta keep-text" :class="getLedgerTheme(item)" v-text="getLedgerDelta(item)" />
</template>
</t-cell>
</t-cell-group>
<center-tips :content="loadStateText" />
</div>
</t-pull-down-refresh>
</template>
<template #detail>
<point-ledger-detail :key="`detail-${selectedId}`" :ledger-id="selectedId" />
</template>
<!--
第三层:详情点进子页(客户 / 积分账户 / 事件 / 事件记录 / 积分规则)时,
列表整列滑出、详情退到主栏,右栏换成那个子页。
-->
<template #sub>
<ledger-sub-view :key="subView" :view="subView" />
</template>
</master-detail-page>
<customer-selector <customer-selector
v-model="selectedCustomerId" v-model="selectedCustomerId"
v-model:visible="selectorVisible" v-model:visible="selectorVisible"
@@ -152,11 +171,15 @@
<script setup lang="ts"> <script setup lang="ts">
import type { DropdownValue } from "tdesign-mobile-vue"; import type { DropdownValue } from "tdesign-mobile-vue";
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile";
import { TimeLabel, Toolkit } from "timi-web"; import { TimeLabel, Toolkit } from "timi-web";
import { type PageResult, useUserStore } from "timi-web-api"; import { type PageResult, useUserStore } from "timi-web-api";
import CustomerAPI from "@/api/CustomerAPI"; import CustomerAPI from "@/api/CustomerAPI";
import PointAPI from "@/api/PointAPI"; import PointAPI from "@/api/PointAPI";
import CustomerSelector from "@/components/CustomerSelector.vue"; import CustomerSelector from "@/components/CustomerSelector.vue";
import PointLedgerDetail from "@/pages/point/PointLedgerDetail.vue";
import LedgerSubView from "@/pages/point/component/LedgerSubView.vue";
import { getLedgerSubRoute, parseLedgerSubPane } from "@/pages/point/component/ledgerPane";
import { useCurrentStoreStore } from "@/store/currentStoreStore"; import { useCurrentStoreStore } from "@/store/currentStoreStore";
import type { Customer } from "@/types/Customer"; import type { Customer } from "@/types/Customer";
import type { PointLedger, PointLedgerChangeType, PointLedgerPage } from "@/types/Point"; import type { PointLedger, PointLedgerChangeType, PointLedgerPage } from "@/types/Point";
@@ -172,10 +195,27 @@ defineOptions({
}); });
const route = useRoute(); const route = useRoute();
const router = useRouter();
const userStore = useUserStore(); const userStore = useUserStore();
const currentStoreStore = useCurrentStoreStore(); const currentStoreStore = useCurrentStoreStore();
// ---------- 分栏导航 ----------
// 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里;积分流水没有内联编辑视图
const { selectedId, subView, paneDirection, isWide, openDetail } = useMasterDetailPane({
path: "/management/points/ledger",
detail: detailRoute
});
/**
* 转屏变窄时右栏不再渲染,按右栏当前那一层落到整页路由。
*
* 子页落到各自模块的整页,详情落到流水自己的详情页。
*/
function detailRoute(id: string): string {
const sub = parseLedgerSubPane(subView.value || "");
return sub ? getLedgerSubRoute(sub) : `/management/points/ledger/${id}`;
}
// ---------- 筛选 ---------- // ---------- 筛选 ----------
const isGlobalManager = computed(() => userStore.hasRoles(gaoRoleCodes.globalManager)); const isGlobalManager = computed(() => userStore.hasRoles(gaoRoleCodes.globalManager));
@@ -410,38 +450,12 @@ function getLedgerTheme(item: PointLedger): string {
return item.pointDelta && 0 < item.pointDelta ? "increase" : "decrease"; return item.pointDelta && 0 < item.pointDelta ? "increase" : "decrease";
} }
async function toDetail(item: PointLedger): Promise<void> { function toDetail(item: PointLedger): void {
if (!item.id) { if (!item.id) {
return; return;
} }
const snapshot: PointLedger = { openDetail(item.id);
id: item.id,
accountId: item.accountId,
storeId: item.storeId,
customerId: item.customerId,
changeType: item.changeType,
direction: item.direction,
pointDelta: item.pointDelta,
balanceBefore: item.balanceBefore,
balanceAfter: item.balanceAfter,
ruleId: item.ruleId,
triggerSourceType: item.triggerSourceType,
triggerSourceId: item.triggerSourceId,
salesOrderId: item.salesOrderId,
groovyScriptVersionId: item.groovyScriptVersionId,
ruleSnapshot: item.ruleSnapshot,
sourcePayload: item.sourcePayload,
idempotencyKey: item.idempotencyKey,
remark: item.remark,
operatorUserId: item.operatorUserId,
occurredAt: item.occurredAt
};
await router.push({
name: "PointLedgerDetail",
params: { id: item.id },
query: { snapshot: JSON.stringify(snapshot) }
});
} }
function buildUnixRange(): [number, number] { function buildUnixRange(): [number, number] {
+12 -7
View File
@@ -21,7 +21,11 @@
<t-cell title="兑换数量" :note="`${quantityText(item.quantity)} ${item.unitSnapshot || ''}`" /> <t-cell title="兑换数量" :note="`${quantityText(item.quantity)} ${item.unitSnapshot || ''}`" />
<t-cell title="积分" :note="`${formatPoint(item.actualPointCost)}${item.actualPointCost !== item.defaultPointCost ? '(已减免)' : ''}`" /> <t-cell title="积分" :note="`${formatPoint(item.actualPointCost)}${item.actualPointCost !== item.defaultPointCost ? '(已减免)' : ''}`" />
<t-cell title="状态" :note="statusText(item.status)" /> <t-cell title="状态" :note="statusText(item.status)" />
<t-cell title="兑换时间" :note="timeText(item.redeemedAt)" /> <t-cell title="兑换时间">
<template #note>
<time-label :timestamp="item.redeemedAt" underline />
</template>
</t-cell>
<t-cell v-if="item.remark" title="备注" :note="item.remark" /> <t-cell v-if="item.remark" title="备注" :note="item.remark" />
<div class="photo-wrap bg-white"> <div class="photo-wrap bg-white">
<attachment-selector :items="redemptionPhotoItems" title="兑换凭证" readonly /> <attachment-selector :items="redemptionPhotoItems" title="兑换凭证" readonly />
@@ -32,8 +36,12 @@
v-for="record in returnList" v-for="record in returnList"
:key="record.id" :key="record.id"
:title="`退货 ${quantityText(record.quantity)} ${item?.unitSnapshot || ''}`" :title="`退货 ${quantityText(record.quantity)} ${item?.unitSnapshot || ''}`"
:note="`${formatPoint(record.pointCost)} · ${timeText(record.returnedAt)}`" :note="formatPoint(record.pointCost)"
/> >
<template #description>
<time-label :timestamp="record.returnedAt" underline />
</template>
</t-cell>
</t-cell-group> </t-cell-group>
<t-empty v-if="!item" :description="loading ? '正在加载兑换单' : '兑换单不存在'" /> <t-empty v-if="!item" :description="loading ? '正在加载兑换单' : '兑换单不存在'" />
<t-button <t-button
@@ -96,6 +104,7 @@ import { formatWanInteger } from "@/utils/money";
import { comparePackageQuantity, getPackageQuantityText, normalizePackageQuantity } from "@/utils/package"; import { comparePackageQuantity, getPackageQuantityText, normalizePackageQuantity } from "@/utils/package";
import { uploadPhotoList } from "@/utils/photo"; import { uploadPhotoList } from "@/utils/photo";
import { permissionCodes } from "@/utils/permission"; import { permissionCodes } from "@/utils/permission";
import { TimeLabel } from "timi-web";
defineOptions({ name: "PointRedemptionDetail" }); defineOptions({ name: "PointRedemptionDetail" });
@@ -248,10 +257,6 @@ function statusText(value?: PointRedemptionStatus): string {
} as Record<string, string>)[value || ""] || "未知"; } as Record<string, string>)[value || ""] || "未知";
} }
function timeText(value?: number): string {
return value ? new Date(value).toLocaleString("zh-CN", { hour12: false }) : "-";
}
onMounted(load); onMounted(load);
watch(() => [props.redemptionId, route.params.id], load); watch(() => [props.redemptionId, route.params.id], load);
</script> </script>
+9 -4
View File
@@ -191,8 +191,11 @@ defineOptions({
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
/** 指定积分规则 ID 时忽略路由参数,用于平板主从分栏的内联渲染。 */ /** 指定积分规则 ID 时忽略路由参数,用于平板主从分栏的内联渲染。 */
ruleId?: string; ruleId?: string;
/** 在分栏中新增积分规则。 */
create?: boolean;
}>(), { }>(), {
ruleId: "" ruleId: "",
create: false
}); });
const route = useRoute(); const route = useRoute();
@@ -200,6 +203,9 @@ const currentId = computed(() => props.ruleId || String(route.params.id || ""));
const routeNavBarTitle = computed(() => { const routeNavBarTitle = computed(() => {
// 内联时路由停在列表页,标题不能只看 route.name // 内联时路由停在列表页,标题不能只看 route.name
if (props.create) {
return "新增积分规则";
}
if (props.ruleId) { if (props.ruleId) {
return "编辑积分规则"; return "编辑积分规则";
} }
@@ -215,11 +221,10 @@ const routeNavBarTitle = computed(() => {
const router = useRouter(); const router = useRouter();
// 竖屏整页编辑转横屏:回到分栏,并用 view=edit 让列表页把右栏还原成编辑。 // 竖屏整页编辑转横屏:回到分栏,并用 view=edit 让列表页把右栏还原成编辑。
// 新增(Create)返回空 id,不触发——右栏没有可依附的选中项
useExpandToMaster({ useExpandToMaster({
path: "/management/points/rules", path: "/management/points/rules",
id: () => (route.name === "PointRuleCreate" ? "" : currentId.value), id: () => (route.name === "PointRuleCreate" ? "__create__" : currentId.value),
query: { view: "edit" } query: route.name === "PointRuleCreate" ? {} : { view: "edit" }
}); });
/** 非空说明当前被内联在主从分栏的右栏里 */ /** 非空说明当前被内联在主从分栏的右栏里 */
const pane = usePane(); const pane = usePane();
+14 -2
View File
@@ -86,7 +86,8 @@
</t-pull-down-refresh> </t-pull-down-refresh>
</template> </template>
<template #detail> <template #detail>
<point-rule-edit v-if="editing" :key="`edit-${selectedId}`" :rule-id="selectedId" /> <point-rule-edit v-if="selectedId === createPaneId" key="create" create />
<point-rule-edit v-else-if="editing" :key="`edit-${selectedId}`" :rule-id="selectedId" />
<point-rule-detail <point-rule-detail
v-else v-else
:key="`detail-${selectedId}-${detailVersion}`" :key="`detail-${selectedId}-${detailVersion}`"
@@ -121,12 +122,13 @@ defineOptions({
}); });
const router = useRouter(); const router = useRouter();
const createPaneId = "__create__";
// 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里 // 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里
const { selectedId, editing, detailVersion, paneDirection, isWide, openDetail, openEdit } = const { selectedId, editing, detailVersion, paneDirection, isWide, openDetail, openEdit } =
useMasterDetailPane({ useMasterDetailPane({
path: "/management/points/rules", path: "/management/points/rules",
detail: id => `/management/points/rules/${id}`, detail: id => id === createPaneId ? "/management/points/rules/create" : `/management/points/rules/${id}`,
edit: id => `/management/points/rules/${id}/edit` edit: id => `/management/points/rules/${id}/edit`
}); });
const userStore = useUserStore(); const userStore = useUserStore();
@@ -279,6 +281,12 @@ watch(keyword, () => {
reloadByKeyword(); reloadByKeyword();
}); });
watch(selectedId, async (id, previousId) => {
if (previousId === createPaneId && id !== createPaneId) {
await reload();
}
});
// ---------- 事件名称 ---------- // ---------- 事件名称 ----------
const eventList = ref<EventItem[]>([]); const eventList = ref<EventItem[]>([]);
@@ -340,6 +348,10 @@ function getStatusTheme(status?: PointRuleStatus): "default" | "success" | "warn
} }
async function toCreate(): Promise<void> { async function toCreate(): Promise<void> {
if (isWide.value) {
openDetail(createPaneId);
return;
}
await router.push({ name: "PointRuleCreate" }); await router.push({ name: "PointRuleCreate" });
} }
@@ -0,0 +1,46 @@
<template>
<customer-detail
v-if="kind === 'customer'"
:customer-id="arg"
/>
<point-account-detail
v-else-if="kind === 'account'"
:account-id="arg"
:store-id="extra"
/>
<event-detail
v-else-if="kind === 'event'"
:event-id="arg"
/>
<event-record-detail
v-else-if="kind === 'event-record'"
:record-id="arg"
/>
<point-rule-detail
v-else-if="kind === 'rule'"
:rule-id="arg"
/>
</template>
<script setup lang="ts">
import CustomerDetail from "@/pages/customer/CustomerDetail.vue";
import EventDetail from "@/pages/event/EventDetail.vue";
import EventRecordDetail from "@/pages/event/EventRecordDetail.vue";
import PointAccountDetail from "@/pages/point/PointAccountDetail.vue";
import PointRuleDetail from "@/pages/point/PointRuleDetail.vue";
import { parseLedgerSubPane } from "@/pages/point/component/ledgerPane";
defineOptions({ name: "LedgerSubView" });
const props = withDefaults(defineProps<{
/** 子页标识,形如 `customer:698f`、`account:698f:12`。 */
view?: string;
}>(), {
view: ""
});
const pane = computed(() => parseLedgerSubPane(props.view));
const kind = computed(() => pane.value?.kind || "");
const arg = computed(() => pane.value?.arg || "");
const extra = computed(() => pane.value?.extra || "");
</script>
+56
View File
@@ -0,0 +1,56 @@
/**
* 积分流水详情在右栏压入子页时的标识约定:`<kind>[:<arg>[:<extra>]]`。
*
* 这些子页都属于别的模块,宿主(积分流水列表页)按标识直接渲染对应页面,
* 与交易订单的 `orderPane` 是同一套思路,只是这里的上一级固定是当前流水。
*/
export type LedgerSubKind = "customer" | "account" | "event" | "event-record" | "rule";
export type LedgerSubPane = {
kind: LedgerSubKind;
/** 主参数:目标对象的 id。 */
arg: string;
/** 附加参数:目前只有积分账户详情需要带上门店 id。 */
extra: string;
};
const LEDGER_SUB_KINDS: LedgerSubKind[] = ["customer", "account", "event", "event-record", "rule"];
function isLedgerSubKind(value: string): value is LedgerSubKind {
return LEDGER_SUB_KINDS.includes(value as LedgerSubKind);
}
/** 拼接子页标识,调用方通常是流水详情里的跳转函数。 */
export function buildLedgerSubPane(kind: LedgerSubKind, arg: string, extra = ""): string {
return extra ? `${kind}:${arg}:${extra}` : `${kind}:${arg}`;
}
/** 解析子页标识;不认识的标识返回 null,调用方应改走整页路由。 */
export function parseLedgerSubPane(value: string): LedgerSubPane | null {
if (!value) {
return null;
}
const [kind, arg = "", extra = ""] = value.split(":");
if (!isLedgerSubKind(kind) || !arg) {
return null;
}
return { kind, arg, extra };
}
/**
* 子页对应的整页路由。
*
* 转屏变窄后右栏不再渲染,靠它把用户留在正在看的那一层;
* 也用于 `openSub()` 没接住时的兜底。
*/
export function getLedgerSubRoute(pane: LedgerSubPane): string {
const { kind, arg, extra } = pane;
switch (kind) {
case "customer": return `/management/customers/${arg}`;
case "account": return `/management/points/account/${arg}${extra ? `?storeId=${encodeURIComponent(extra)}` : ""}`;
case "event": return `/management/registration-events/${arg}`;
case "event-record": return `/management/registration-event-records/${arg}`;
case "rule": return `/management/points/rules/${arg}`;
default: return "/management/points/ledger";
}
}
+7 -452
View File
@@ -1,479 +1,34 @@
<template> <template>
<div class="tui-page-layout tui-navbar"> <div class="tui-page-layout tui-navbar">
<t-navbar <t-navbar fixed :z-index="20" title="库存流水详情" left-arrow @left-click="goBack" />
fixed
:z-index="20"
title="库存流水详情"
left-arrow
@left-click="goBack"
/>
<main class="tui-page-content scroll column"> <main class="tui-page-content scroll column">
<div v-can="permissionCodes.productStock.read" class="product-stock-record-detail"> <product-stock-record-content :record-id="resolveId()" />
<t-loading v-if="isLoading" class="loading" size="32px" />
<template v-else-if="record">
<section class="snapshot-head" v-entrance-transition>
<div class="eyebrow">库存 SKU 快照</div>
<h2 v-text="record.productNameSnapshot || '未命名产品'" />
<product-sku-tags
class="sku"
:product-name="record.productNameSnapshot"
:snapshot="record.skuSpecSnapshot"
:fallback="record.specSummarySnapshot || record.skuNameSnapshot || '默认 SKU'"
:unit="record.unitSnapshot"
/>
<div class="meta">
<span v-text="record.skuCodeSnapshot || '无 SKU 编码'" />
<t-tag size="small" variant="light-outline" :theme="getOperationTheme(record.onHandDelta)" :content="getStockOperationText(record.operationType)" />
</div>
</section>
<card-container description="库存变动信息" v-entrance-transition>
<div class="data">
<div class="card">
<span class="label">业务数量</span>
<strong :class="getDeltaClass(record.quantity)" v-text="getQuantityText(record)" />
</div>
<div class="card">
<span class="label">基础单位数量</span>
<strong :class="getDeltaClass(record.baseQuantity)" v-text="getSignedQuantityText(record.baseQuantity)" />
</div>
<div class="card">
<span class="label">实际库存变动</span>
<strong :class="getDeltaClass(record.onHandDelta)" v-text="getDeltaText(record.onHandDelta)" />
</div>
<div class="card">
<span class="label">预占库存变动</span>
<strong :class="getDeltaClass(record.reservedDelta)" v-text="getDeltaText(record.reservedDelta)" />
</div>
</div>
</card-container>
<t-cell-group title="库存快照" theme="card" v-entrance-transition>
<t-cell title="实际库存">
<template #note>
<span class="balance">
<span v-text="getProductQuantityText(record.onHandBefore)" />
<t-icon name="arrow-right" />
<span :class="getDeltaClass(record.onHandDelta)" v-text="getProductQuantityText(record.onHandAfter)" />
<span class="unit" v-text="baseUnitName || '基础单位'" />
</span>
</template>
</t-cell>
<t-cell title="预占库存">
<template #note>
<span class="balance">
<span v-text="getProductQuantityText(record.reservedBefore)" />
<t-icon name="arrow-right" />
<span :class="getDeltaClass(record.reservedDelta)" v-text="getProductQuantityText(record.reservedAfter)" />
<span class="unit" v-text="baseUnitName || '基础单位'" />
</span>
</template>
</t-cell>
</t-cell-group>
<t-cell-group title="库存流水" theme="card" v-entrance-transition>
<t-cell title="操作类型" :note="getStockOperationText(record.operationType)" />
<t-cell title="业务类型" :note="getBizTypeText(record.bizType)" />
<t-cell
v-if="relatedFulfillmentId && canReadFulfillment"
title="关联履约单"
note="查看履约详情"
arrow
@click="toFulfillment"
/>
<t-cell title="发生时间">
<template #note>
<time-label :timestamp="record.occurredAt" underline />
</template>
</t-cell>
<t-cell title="操作人" :note="record.operator?.nick || record.operator?.name || record.operatorUserId || '未知操作人'" />
<t-cell v-if="record.sourceRecordId" title="原库存流水" :note="record.sourceRecordId" arrow @click="openRelatedRecord(record.sourceRecordId)" />
<t-cell v-if="record.revokeRecordId" title="冲正流水" :note="record.revokeRecordId" arrow @click="openRelatedRecord(record.revokeRecordId)" />
<t-cell v-if="record.remark" title="备注" :note="record.remark" />
<t-cell class="empty-cell-title-margin">
<template #title>
<span></span>
</template>
<template #description>
<attachment-selector :items="photoItemList" title="操作照片" readonly />
</template>
</t-cell>
</t-cell-group>
<t-button
v-if="canManualRevoke"
class="cell-button"
theme="danger"
@click="openManualRevoke"
v-entrance-transition
content="手工流水冲正"
/>
</template>
<t-empty v-else :description="isLoading ? '正在加载库存流水' : '库存流水不存在'" />
<bottom-popup
v-model="revokeVisible"
title="手工流水冲正"
left-button-text="取消"
:right-button-text="isOperating ? '提交中' : '提交'"
@left-button-click="revokeVisible = false"
@right-button-click="submitManualRevoke"
>
<div class="revoke-popup">
<p class="tip">将新增一条反向库存流水,原流水不会被修改或删除。</p>
<t-form>
<t-form-item label="冲正备注" required-mark>
<t-textarea v-model="revokeRemark" borderless autosize maxlength="500" placeholder="请输入冲正备注" />
</t-form-item>
</t-form>
<attachment-selector
v-model:items="revokePhotoItems"
:upload="uploadPhotoList"
required
title="冲正凭证照片"
/>
</div>
</bottom-popup>
</div>
</main> </main>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { BottomPopup, useExpandToMaster, usePane } from "timi-tdesign-mobile"; import { useExpandToMaster, usePane } from "timi-tdesign-mobile";
import { TimeLabel } from "timi-web"; import ProductStockRecordContent from "@/pages/product/component/ProductStockRecordContent.vue";
import { useUserStore, type Attachment } from "timi-web-api";
import ProductAPI from "@/api/ProductAPI";
import AttachmentSelector from "@/components/attachmentSelector/AttachmentSelector.vue";
import ProductSkuTags from "@/components/ProductSkuTags.vue";
import type { StockBizType, StockRecord } from "@/types/Product";
import { getAttachmentReadURL } from "@/utils/attachment";
import { getErrorMessage } from "@/utils/error";
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
import { createProductRequestNo, getProductQuantityText, getStockOperationText } from "@/utils/product";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { uploadPhotoList } from "@/utils/photo";
import type { PhotoItem } from "@/types/Photo";
defineOptions({ name: "ProductStockRecordDetail" }); defineOptions({ name: "ProductStockRecordDetail" });
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{ recordId?: string }>(), { recordId: "" });
/** 指定库存流水 ID 时忽略路由参数,用于平板主从分栏的内联渲染。 */
recordId?: string;
}>(), {
recordId: ""
});
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const pane = usePane();
/** 内联渲染时 id 来自 prop,整页渲染时来自路由参数 */
function resolveId(): string { function resolveId(): string {
return props.recordId || String(route.params.id || ""); return props.recordId || String(route.params.id || "");
} }
// 竖屏整页进来后转成横屏:回到列表页并恢复右栏选中,而不是继续停在整页详情 useExpandToMaster({ path: "/product/product-stock-records", id: () => resolveId() });
useExpandToMaster({
path: "/product/product-stock-records",
id: () => resolveId()
});
/** 非空说明当前被内联在主从分栏的右栏里 */
const pane = usePane();
function goBack(): void { function goBack(): void {
if (pane) { if (pane) {
pane.close(); pane.close();
return; return;
} }
void router.back(); void router.back();
} }
const userStore = useUserStore();
const record = ref<StockRecord>();
const baseUnitName = ref("");
const isLoading = ref(false);
const isOperating = ref(false);
const revokeVisible = ref(false);
const revokeRemark = ref("");
const revokeRequestNo = ref("");
const revokePhotoItems = ref<PhotoItem[]>([]);
const canManualRevoke = computed(() => {
const operationType = record.value?.operationType;
return (operationType === "MANUAL_IN" || operationType === "MANUAL_OUT")
&& !record.value?.sourceRecordId
&& !record.value?.revokeRecordId
&& userStore.hasPermissions(permissionCodes.productStock.manualRevoke);
});
const canReadFulfillment = computed(() => userStore.hasPermissions(permissionCodes.orderFulfillment.read));
const relatedFulfillmentId = computed(() => record.value?.bizType === "ORDER_FULFILLMENT" ? record.value.bizId : "");
const photoItemList = computed<PhotoItem[]>(() => (record.value?.attachmentList || [])
.filter(item => !!item.id)
.map(item => ({
attachment: item,
attachType: item.attachType || "PHOTO",
previewUrl: getAttachmentReadURL(item.id || ""),
url: getAttachmentReadURL(item.id || "", 128)
})));
function getOperationTheme(value?: number | string): "success" | "danger" | "default" {
const amount = Number(value || 0);
return 0 < amount ? "success" : amount < 0 ? "danger" : "default";
}
function getDeltaText(value?: number | string): string {
return getSignedQuantityText(value);
}
function getSignedQuantityText(value?: number | string): string {
const amount = Number(value || 0);
const text = getProductQuantityText(String(value || "0").replace(/^-/, ""));
return `${0 < amount ? "+" : amount < 0 ? "-" : ""}${text}`;
}
function getDeltaClass(value?: number | string): string {
const amount = Number(value || 0);
return 0 < amount ? "positive" : amount < 0 ? "negative" : "gray";
}
function getQuantityText(item: StockRecord): string {
return `${getSignedQuantityText(item.quantity)} ${item.unitSnapshot || "业务单位"}`;
}
function getBizTypeText(type?: StockBizType): string {
return ({ PRODUCT_STOCK: "产品库存", ORDER_FULFILLMENT: "订单履约", POINT_REDEMPTION: "积分兑换" } as Record<string, string>)[type || ""] || "未知";
}
function buildAttachments(): Partial<Attachment>[] {
return revokePhotoItems.value.flatMap(item => item.tempFileId ? [{ tempFileId: item.tempFileId, attachType: "PHOTO" }] : []);
}
function openManualRevoke(): void {
if (!canManualRevoke.value) {
return;
}
revokeRemark.value = "";
revokeRequestNo.value = "";
revokePhotoItems.value = [];
revokeVisible.value = true;
}
async function openRelatedRecord(id?: string): Promise<void> {
if (id) {
await router.push({
name: "ProductStockRecordDetail",
params: { id },
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
}
async function toFulfillment(): Promise<void> {
if (!relatedFulfillmentId.value || !canReadFulfillment.value) {
return;
}
await router.push({
path: `/product/order-fulfillments/${relatedFulfillmentId.value}`,
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
function getCurrentRouteDepth(): number {
const transitionDepth = Array.isArray(route.query.transitionDepth)
? route.query.transitionDepth[0]
: route.query.transitionDepth;
const depth = Number(transitionDepth);
if (transitionDepth && Number.isInteger(depth) && 0 <= depth && depth <= 20) {
return depth;
}
return Number(route.meta.depth ?? 0);
}
async function submitManualRevoke(): Promise<void> {
if (!canManualRevoke.value || !record.value?.id || isOperating.value) {
return;
}
if (!revokeRemark.value.trim()) {
Message.warning("冲正备注不能为空");
return;
}
if (!revokePhotoItems.value.some(item => !!item.tempFileId)) {
Message.warning("库存流水冲正必须上传至少一张照片");
return;
}
isOperating.value = true;
try {
if (!revokeRequestNo.value) {
revokeRequestNo.value = createProductRequestNo();
}
await ProductAPI.manualRevoke({
requestNo: revokeRequestNo.value,
sourceRecordId: record.value.id,
remark: revokeRemark.value.trim(),
attachmentList: buildAttachments()
});
revokeVisible.value = false;
emitListDataChanged(listDataEventKeys.productStockChanged, record.value.id);
Message.success("手工库存流水已冲正");
await loadData();
} catch (error) {
Message.error(getErrorMessage(error, "库存流水冲正失败,重试会复用同一请求号"));
} finally {
isOperating.value = false;
}
}
async function loadData(): Promise<void> {
const id = resolveId();
if (!id) {
return;
}
isLoading.value = true;
try {
const result = await ProductAPI.recordDetail(id);
record.value = result;
baseUnitName.value = "";
if (result.skuId) {
try {
const sku = await ProductAPI.skuDetail(result.skuId);
baseUnitName.value = sku.unitList?.find(unit => unit.isBase)?.name || sku.unitList?.[0]?.name || "";
} catch {
baseUnitName.value = "";
}
}
} catch (error) {
Message.error(getErrorMessage(error, "库存流水加载失败"));
} finally {
isLoading.value = false;
}
}
onMounted(async () => {
await loadData();
});
watch(resolveId, async (id, previousId) => {
if (id && id !== previousId) {
await loadData();
}
});
</script> </script>
<style scoped lang="less">
.product-stock-record-detail {
gap: 1rem;
display: flex;
padding: 0 0 2rem;
flex-direction: column;
.loading {
margin: 3rem auto;
}
.snapshot-head {
margin: 0 1rem;
padding: 1rem;
background: var(--td-bg-color-container);
box-shadow: var(--td-shadow-1);
border-radius: 1rem;
.eyebrow {
color: var(--td-brand-color);
font-size: .75rem;
font-weight: 700;
}
h2 {
margin: .5rem 0 .25rem;
font-size: 1.25rem;
}
.sku {
color: var(--td-text-color-secondary);
}
.meta {
gap: .5rem;
display: flex;
margin-top: .75rem;
align-items: center;
justify-content: space-between;
span {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
}
}
.positive {
color: var(--td-success-color);
}
.negative {
color: var(--td-error-color);
}
.balance {
gap: .25rem;
display: inline-flex;
align-items: center;
.arrow,
.unit {
color: var(--td-text-color-secondary);
}
}
.data {
gap: .75rem;
display: grid;
padding: .75rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
.card {
gap: .25rem;
min-width: 0;
padding: .5rem .75rem;
display: flex;
background: var(--td-bg-color-secondarycontainer);
border-radius: .75rem;
flex-direction: column;
.label {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
strong {
overflow: hidden;
font-size: 1.25rem;
word-break: break-all;
text-align: center;
line-height: 1.4;
}
}
}
.actions {
padding: 0 1rem;
}
}
:global(html.theme-dark) {
.product-stock-record-detail {
.data .card {
background: rgba(15, 23, 42, .72);
border-color: rgba(148, 163, 184, .16);
}
}
}
.revoke-popup {
padding: .5rem 1rem calc(1rem + var(--tui-safe-bottom, 0px));
.tip {
margin: 0 0 .75rem;
color: var(--td-text-color-secondary);
font-size: .875rem;
}
}
</style>
+150 -147
View File
@@ -40,7 +40,6 @@
</div> </div>
</template> </template>
</dropdown-menu-navbar> </dropdown-menu-navbar>
<div class="list-wrap">
<t-cell-group v-if="isCustomDate || filteredSku" class="summary" theme="card"> <t-cell-group v-if="isCustomDate || filteredSku" class="summary" theme="card">
<template v-if="isCustomDate"> <template v-if="isCustomDate">
<t-cell <t-cell
@@ -116,7 +115,7 @@
class="avatar" class="avatar"
/> />
<div <div
v-else-if="record.customer" v-else-if="record.customer || record.operationType === 'POINT_REDEMPTION_OUT'"
class="avatar fallback" class="avatar fallback"
v-text="getCustomerText(record).slice(0, 1)" v-text="getCustomerText(record).slice(0, 1)"
/> />
@@ -133,7 +132,7 @@
</template> </template>
<template #title> <template #title>
<div class="title"> <div class="title">
<span v-if="record.customer" class="actor" v-text="getCustomerText(record)" /> <span v-if="record.customer || record.operationType === 'POINT_REDEMPTION_OUT'" class="actor" v-text="getCustomerText(record)" />
<span v-else-if="record.operator" class="actor" v-text="getOperatorText(record)" /> <span v-else-if="record.operator" class="actor" v-text="getOperatorText(record)" />
<strong class="operation" :class="getOperationClass(record.operationType)" v-text="getStockOperationText(record.operationType)" /> <strong class="operation" :class="getOperationClass(record.operationType)" v-text="getStockOperationText(record.operationType)" />
<strong class="product-name clip-text" v-text="record.productNameSnapshot || '未命名产品'" /> <strong class="product-name clip-text" v-text="record.productNameSnapshot || '未命名产品'" />
@@ -166,7 +165,6 @@
</t-cell-group> </t-cell-group>
<center-tips v-else :content="emptyText" /> <center-tips v-else :content="emptyText" />
<center-tips v-if="recordList.length" :content="loadStateText" /> <center-tips v-if="recordList.length" :content="loadStateText" />
</div>
</t-pull-down-refresh> </t-pull-down-refresh>
</template> </template>
<template #detail> <template #detail>
@@ -211,7 +209,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { type DropdownValue } from "tdesign-mobile-vue"; import { type DropdownValue } from "tdesign-mobile-vue";
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile"; import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile";
import { TimeLabel, Time } from "timi-web"; import { Time, TimeLabel } from "timi-web";
import { UserAPI } from "timi-web-api"; import { UserAPI } from "timi-web-api";
import { onBeforeRouteLeave } from "vue-router"; import { onBeforeRouteLeave } from "vue-router";
import ProductAPI from "@/api/ProductAPI"; import ProductAPI from "@/api/ProductAPI";
@@ -222,13 +220,27 @@ import type { ProductSkuSelectionValue } from "@/types/ProductSkuSelection";
import { buildPresetDateRange, parseDateFilterType, parseDateTime } from "@/utils/date"; import { buildPresetDateRange, parseDateFilterType, parseDateTime } from "@/utils/date";
import { DATE_FILTER_OPTIONS as dateOptions, type DateFilterType } from "@/utils/dateFilter"; import { DATE_FILTER_OPTIONS as dateOptions, type DateFilterType } from "@/utils/dateFilter";
import { getErrorMessage } from "@/utils/error"; import { getErrorMessage } from "@/utils/error";
import { getProductBaseUnitName, getProductPhotoURL, getProductQuantityText, getProductSkuSpecEntries, getProductTypeText, getStockOperationText } from "@/utils/product"; import {
getProductBaseUnitName,
getProductPhotoURL,
getProductQuantityText,
getProductSkuSpecEntries,
getProductTypeText,
getStockOperationText
} from "@/utils/product";
import { Message } from "@/utils/message"; import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission"; import { permissionCodes } from "@/utils/permission";
import { getCustomerPhotoURL } from "@/utils/customer"; import { getCustomerPhotoURL } from "@/utils/customer";
import { buildFallbackAvatar } from "@/utils/avatar"; import { buildFallbackAvatar } from "@/utils/avatar";
import type { Product, ProductSelection, ProductSku, StockOperationType, StockRecord, StockRecordDirection } from "@/types/Product"; import type {
Product,
ProductSelection,
ProductSku,
StockOperationType,
StockRecord,
StockRecordDirection
} from "@/types/Product";
defineOptions({ name: "ProductStockRecordList" }); defineOptions({ name: "ProductStockRecordList" });
@@ -676,162 +688,153 @@ onUnmounted(() => {
<style scoped lang="less"> <style scoped lang="less">
.product-stock-record-list { .product-stock-record-list {
display: flex;
padding: var(--tui-nav-height) 0 1rem;
flex-direction: column;
.list-wrap { .summary {
gap: 1rem;
display: flex;
flex-direction: column;
.summary { :deep(.t-cell__title) {
flex: 0 0 4.5rem;
:deep(.t-cell__title) {
flex: 0 0 4.5rem;
}
:deep(.t-cell__note) {
flex: 1 1 0;
min-width: 0;
overflow: hidden;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
} }
.sku { :deep(.t-cell__note) {
--td-tag-square-border-radius: .5rem; flex: 1 1 0;
min-width: 0;
overflow: hidden;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.sku {
--td-tag-square-border-radius: .5rem;
padding: 10px;
:deep(.t-cell__title) {
display: flex;
align-items: center;
}
.avatar {
width: 2rem;
height: 2rem;
border-radius: .5rem !important;
}
.title {
gap: .5rem;
display: flex;
min-width: 0;
align-items: center;
}
}
.list {
margin: 0;
.item {
padding: 10px; padding: 10px;
min-width: 0;
:deep(.t-cell__title) {
display: flex;
align-items: center;
}
.avatar { .avatar {
width: 2rem; width: 3.5rem;
height: 2rem; height: 3.5rem;
border-radius: .5rem !important; }
.icon {
width: 2.25rem;
height: 2.25rem;
display: inline-flex;
background: var(--td-bg-color-secondarycontainer);
align-items: center;
border-radius: 50%;
justify-content: center;
} }
.title { .title {
gap: .25rem;
min-width: 0;
max-width: 100%;
flex: 1;
display: flex;
font-size: .75rem;
align-items: center;
white-space: nowrap;
.actor {
flex: 0 0 auto;
color: var(--td-text-color-brand);
}
.operation {
flex: 0 0 auto;
color: var(--operation-color, var(--td-text-color-secondary));
font-weight: 700;
&.initial-in {
--operation-color: #2563eb;
}
&.manual-in {
--operation-color: #15803d;
}
&.manual-out {
--operation-color: #c2410c;
}
&.manual-revoke {
--operation-color: #be123c;
}
&.order-reserve {
--operation-color: #7c3aed;
}
&.order-release {
--operation-color: #0891b2;
}
&.order-out {
--operation-color: #dc2626;
}
&.order-revoke {
--operation-color: #4f46e5;
}
&.stocktake-gain {
--operation-color: #0f766e;
}
&.stocktake-loss {
--operation-color: #a16207;
}
}
.product-name {
flex: 0 1 auto;
color: var(--td-text-color-primary);
}
.quantity {
color: var(--td-text-color-secondary);
flex: 0 0 auto;
font-weight: 400;
}
}
.description {
gap: .5rem; gap: .5rem;
display: flex; display: flex;
min-width: 0; font-size: .75rem;
align-items: center; align-items: center;
} justify-content: space-between;
}
.list { .delta {
margin: 0;
.item { .value {
padding: 10px; font-size: 1.25rem;
min-width: 0;
.avatar {
width: 3.5rem;
height: 3.5rem;
}
.icon {
width: 2.25rem;
height: 2.25rem;
display: inline-flex;
background: var(--td-bg-color-secondarycontainer);
align-items: center;
border-radius: 50%;
justify-content: center;
}
.title {
gap: .25rem;
min-width: 0;
max-width: 100%;
flex: 1;
display: flex;
font-size: .75rem;
align-items: center;
white-space: nowrap;
.actor {
flex: 0 0 auto;
color: var(--td-text-color-brand);
}
.operation {
flex: 0 0 auto;
color: var(--operation-color, var(--td-text-color-secondary));
font-weight: 700;
&.initial-in {
--operation-color: #2563eb;
}
&.manual-in {
--operation-color: #15803d;
}
&.manual-out {
--operation-color: #c2410c;
}
&.manual-revoke {
--operation-color: #be123c;
}
&.order-reserve {
--operation-color: #7c3aed;
}
&.order-release {
--operation-color: #0891b2;
}
&.order-out {
--operation-color: #dc2626;
}
&.order-revoke {
--operation-color: #4f46e5;
}
&.stocktake-gain {
--operation-color: #0f766e;
}
&.stocktake-loss {
--operation-color: #a16207;
}
}
.product-name {
flex: 0 1 auto;
color: var(--td-text-color-primary);
}
.quantity {
color: var(--td-text-color-secondary);
flex: 0 0 auto;
font-weight: 400;
}
}
.description {
gap: .5rem;
display: flex;
font-size: .75rem;
align-items: center;
justify-content: space-between;
.delta {
.value {
font-size: 1.25rem;
}
} }
} }
} }
@@ -318,6 +318,10 @@ defineExpose({
gap: 1rem; gap: 1rem;
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));
@media (max-width: 42rem) {
grid-template-columns: minmax(0, 1fr);
}
} }
// 分栏窄容器:双列图表一律改单列 // 分栏窄容器:双列图表一律改单列
@@ -27,7 +27,7 @@
<t-segmented :value="direction" :options="directionOptions" @change="changeDirection" /> <t-segmented :value="direction" :options="directionOptions" @change="changeDirection" />
</div> </div>
<t-cell-group v-if="records.length" class="list empty-cell-title-margin" theme="card"> <t-cell-group v-if="records.length" class="list empty-cell-title-margin" theme="card">
<t-cell v-for="record in records" :key="record.id" class="item"> <t-cell v-for="record in records" :key="record.id" class="item" arrow @click="openRecord(record)">
<template #leftIcon> <template #leftIcon>
<t-image <t-image
v-if="getCustomerPhotoURL(record.customer, 64)" v-if="getCustomerPhotoURL(record.customer, 64)"
@@ -103,6 +103,18 @@
</div> </div>
<t-empty v-else description="暂无库存流水查看权限" /> <t-empty v-else description="暂无库存流水查看权限" />
</bottom-popup> </bottom-popup>
<bottom-popup
v-model="detailVisible"
title="库存流水详情"
height="75vh"
left-button-text="关闭"
right-button-text=""
@left-button-click="detailVisible = false"
>
<div class="detail-scroll">
<product-stock-record-content v-if="detailVisible" :record-id="selectedRecordId" />
</div>
</bottom-popup>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -110,6 +122,7 @@ import { BottomPopup } from "timi-tdesign-mobile";
import { TimeLabel } from "timi-web"; import { TimeLabel } from "timi-web";
import { UserAPI, useUserStore } from "timi-web-api"; import { UserAPI, useUserStore } from "timi-web-api";
import ProductAPI from "@/api/ProductAPI"; import ProductAPI from "@/api/ProductAPI";
import ProductStockRecordContent from "@/pages/product/component/ProductStockRecordContent.vue";
import type { MonthCalendarDay } from "@/components/monthCalendar/monthCalendar"; import type { MonthCalendarDay } from "@/components/monthCalendar/monthCalendar";
import type { GaoProductStockMovementDailyStatView } from "@/types/GaoChart"; import type { GaoProductStockMovementDailyStatView } from "@/types/GaoChart";
import type { ProductSelection, StockRecord, StockRecordDirection } from "@/types/Product"; import type { ProductSelection, StockRecord, StockRecordDirection } from "@/types/Product";
@@ -180,6 +193,15 @@ function getDeltaText(value?: number | string): string {
return `${0 < amount ? "+" : amount < 0 ? "-" : ""}${text}`; return `${0 < amount ? "+" : amount < 0 ? "-" : ""}${text}`;
} }
const detailVisible = ref(false);
const selectedRecordId = ref("");
function openRecord(record: StockRecord): void {
if (!record.id) return;
selectedRecordId.value = record.id;
detailVisible.value = true;
}
const visible = ref(false); const visible = ref(false);
const selectedDate = ref(""); const selectedDate = ref("");
const selectedStart = ref(0); const selectedStart = ref(0);
@@ -247,6 +269,7 @@ async function loadRecords(): Promise<void> {
watch([() => props.storeId, skuId], () => { watch([() => props.storeId, skuId], () => {
visible.value = false; visible.value = false;
detailVisible.value = false;
recordToken++; recordToken++;
}); });
@@ -254,6 +277,11 @@ defineExpose({ openDay });
</script> </script>
<style scoped lang="less"> <style scoped lang="less">
.detail-scroll {
height: 100%;
overflow-y: auto;
}
.records { .records {
height: 100%; height: 100%;
overflow-y: auto; overflow-y: auto;
@@ -0,0 +1,463 @@
<template>
<div v-can="permissionCodes.productStock.read" class="product-stock-record-detail">
<t-loading v-if="isLoading" class="loading" size="32px" />
<template v-else-if="record">
<section class="snapshot-head" v-entrance-transition>
<div class="eyebrow">库存 SKU 快照</div>
<h2 v-text="record.productNameSnapshot || '未命名产品'" />
<product-sku-tags
class="sku"
:product-name="record.productNameSnapshot"
:snapshot="record.skuSpecSnapshot"
:fallback="record.specSummarySnapshot || record.skuNameSnapshot || '默认 SKU'"
:unit="record.unitSnapshot"
/>
<div class="meta">
<span v-text="record.skuCodeSnapshot || '无 SKU 编码'" />
<t-tag size="small" variant="light-outline" :theme="getOperationTheme(record.onHandDelta)" :content="getStockOperationText(record.operationType)" />
</div>
</section>
<card-container description="库存变动信息" v-entrance-transition>
<div class="data">
<div class="card">
<span class="label">业务数量</span>
<strong :class="getDeltaClass(record.quantity)" v-text="getQuantityText(record)" />
</div>
<div class="card">
<span class="label">基础单位数量</span>
<strong :class="getDeltaClass(record.baseQuantity)" v-text="getSignedQuantityText(record.baseQuantity)" />
</div>
<div class="card">
<span class="label">实际库存变动</span>
<strong :class="getDeltaClass(record.onHandDelta)" v-text="getDeltaText(record.onHandDelta)" />
</div>
<div class="card">
<span class="label">预占库存变动</span>
<strong :class="getDeltaClass(record.reservedDelta)" v-text="getDeltaText(record.reservedDelta)" />
</div>
</div>
</card-container>
<t-cell-group title="库存快照" theme="card" v-entrance-transition>
<t-cell title="实际库存">
<template #note>
<span class="balance">
<span v-text="getProductQuantityText(record.onHandBefore)" />
<t-icon name="arrow-right" />
<span :class="getDeltaClass(record.onHandDelta)" v-text="getProductQuantityText(record.onHandAfter)" />
<span class="unit" v-text="baseUnitName || '基础单位'" />
</span>
</template>
</t-cell>
<t-cell title="预占库存">
<template #note>
<span class="balance">
<span v-text="getProductQuantityText(record.reservedBefore)" />
<t-icon name="arrow-right" />
<span :class="getDeltaClass(record.reservedDelta)" v-text="getProductQuantityText(record.reservedAfter)" />
<span class="unit" v-text="baseUnitName || '基础单位'" />
</span>
</template>
</t-cell>
</t-cell-group>
<t-cell-group title="库存流水" theme="card" v-entrance-transition>
<t-cell title="操作类型" :note="getStockOperationText(record.operationType)" />
<t-cell title="业务类型" :note="getBizTypeText(record.bizType)" />
<t-cell
v-if="relatedRedemptionId && canReadRedemption"
title="关联积分兑换单"
note="查看兑换详情"
arrow
@click="toRedemption"
/>
<t-cell
v-if="relatedFulfillmentId && canReadFulfillment"
title="关联履约单"
note="查看履约详情"
arrow
@click="toFulfillment"
/>
<t-cell title="发生时间">
<template #note>
<time-label :timestamp="record.occurredAt" underline />
</template>
</t-cell>
<t-cell title="操作人" :note="record.operator?.nick || record.operator?.name || record.operatorUserId || '未知操作人'" />
<t-cell v-if="record.sourceRecordId" title="原库存流水" :note="record.sourceRecordId" arrow @click="openRelatedRecord(record.sourceRecordId)" />
<t-cell v-if="record.revokeRecordId" title="冲正流水" :note="record.revokeRecordId" arrow @click="openRelatedRecord(record.revokeRecordId)" />
<t-cell v-if="record.remark" title="备注" :note="record.remark" />
<t-cell class="empty-cell-title-margin">
<template #title>
<span></span>
</template>
<template #description>
<attachment-selector :items="photoItemList" title="操作照片" readonly />
</template>
</t-cell>
</t-cell-group>
<t-button
v-if="canManualRevoke"
class="cell-button"
theme="danger"
@click="openManualRevoke"
v-entrance-transition
content="手工流水冲正"
/>
</template>
<t-empty v-else :description="isLoading ? '正在加载库存流水' : '库存流水不存在'" />
<bottom-popup
v-model="revokeVisible"
title="手工流水冲正"
left-button-text="取消"
:right-button-text="isOperating ? '提交中' : '提交'"
@left-button-click="revokeVisible = false"
@right-button-click="submitManualRevoke"
>
<div class="revoke-popup">
<p class="tip">将新增一条反向库存流水,原流水不会被修改或删除。</p>
<t-form>
<t-form-item label="冲正备注" required-mark>
<t-textarea v-model="revokeRemark" borderless autosize maxlength="500" placeholder="请输入冲正备注" />
</t-form-item>
</t-form>
<attachment-selector
v-model:items="revokePhotoItems"
:upload="uploadPhotoList"
required
title="冲正凭证照片"
/>
</div>
</bottom-popup>
</div>
</template>
<script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile";
import { TimeLabel } from "timi-web";
import { useUserStore, type Attachment } from "timi-web-api";
import ProductAPI from "@/api/ProductAPI";
import AttachmentSelector from "@/components/attachmentSelector/AttachmentSelector.vue";
import ProductSkuTags from "@/components/ProductSkuTags.vue";
import type { StockBizType, StockRecord } from "@/types/Product";
import { getAttachmentReadURL } from "@/utils/attachment";
import { getErrorMessage } from "@/utils/error";
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
import { createProductRequestNo, getProductQuantityText, getStockOperationText } from "@/utils/product";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { uploadPhotoList } from "@/utils/photo";
import type { PhotoItem } from "@/types/Photo";
const props = defineProps<{ recordId: string }>();
const route = useRoute();
const router = useRouter();
function resolveId(): string {
return props.recordId;
}
const userStore = useUserStore();
const record = ref<StockRecord>();
const baseUnitName = ref("");
const isLoading = ref(false);
const isOperating = ref(false);
const revokeVisible = ref(false);
const revokeRemark = ref("");
const revokeRequestNo = ref("");
const revokePhotoItems = ref<PhotoItem[]>([]);
const canManualRevoke = computed(() => {
const operationType = record.value?.operationType;
return (operationType === "MANUAL_IN" || operationType === "MANUAL_OUT")
&& !record.value?.sourceRecordId
&& !record.value?.revokeRecordId
&& userStore.hasPermissions(permissionCodes.productStock.manualRevoke);
});
const canReadRedemption = computed(() => userStore.hasPermissions(permissionCodes.pointRedemption.create));
const relatedRedemptionId = computed(() => record.value?.operationType === "POINT_REDEMPTION_OUT"
&& record.value.bizType === "POINT_REDEMPTION" ? record.value.bizId : "");
const canReadFulfillment = computed(() => userStore.hasPermissions(permissionCodes.orderFulfillment.read));
const relatedFulfillmentId = computed(() => record.value?.bizType === "ORDER_FULFILLMENT" ? record.value.bizId : "");
const photoItemList = computed<PhotoItem[]>(() => (record.value?.attachmentList || [])
.filter(item => !!item.id)
.map(item => ({
attachment: item,
attachType: item.attachType || "PHOTO",
previewUrl: getAttachmentReadURL(item.id || ""),
url: getAttachmentReadURL(item.id || "", 128)
})));
function getOperationTheme(value?: number | string): "success" | "danger" | "default" {
const amount = Number(value || 0);
return 0 < amount ? "success" : amount < 0 ? "danger" : "default";
}
function getDeltaText(value?: number | string): string {
return getSignedQuantityText(value);
}
function getSignedQuantityText(value?: number | string): string {
const amount = Number(value || 0);
const text = getProductQuantityText(String(value || "0").replace(/^-/, ""));
return `${0 < amount ? "+" : amount < 0 ? "-" : ""}${text}`;
}
function getDeltaClass(value?: number | string): string {
const amount = Number(value || 0);
return 0 < amount ? "positive" : amount < 0 ? "negative" : "gray";
}
function getQuantityText(item: StockRecord): string {
return `${getSignedQuantityText(item.quantity)} ${item.unitSnapshot || "业务单位"}`;
}
function getBizTypeText(type?: StockBizType): string {
return ({ PRODUCT_STOCK: "产品库存", ORDER_FULFILLMENT: "订单履约", POINT_REDEMPTION: "积分兑换" } as Record<string, string>)[type || ""] || "未知";
}
function buildAttachments(): Partial<Attachment>[] {
return revokePhotoItems.value.flatMap(item => item.tempFileId ? [{ tempFileId: item.tempFileId, attachType: "PHOTO" }] : []);
}
function openManualRevoke(): void {
if (!canManualRevoke.value) {
return;
}
revokeRemark.value = "";
revokeRequestNo.value = "";
revokePhotoItems.value = [];
revokeVisible.value = true;
}
async function openRelatedRecord(id?: string): Promise<void> {
if (id) {
await router.push({
name: "ProductStockRecordDetail",
params: { id },
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
}
async function toRedemption(): Promise<void> {
if (!relatedRedemptionId.value || !canReadRedemption.value) {
return;
}
await router.push({
name: "PointRedemptionDetail",
params: { id: relatedRedemptionId.value },
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
async function toFulfillment(): Promise<void> {
if (!relatedFulfillmentId.value || !canReadFulfillment.value) {
return;
}
await router.push({
path: `/product/order-fulfillments/${relatedFulfillmentId.value}`,
query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
});
}
function getCurrentRouteDepth(): number {
const transitionDepth = Array.isArray(route.query.transitionDepth)
? route.query.transitionDepth[0]
: route.query.transitionDepth;
const depth = Number(transitionDepth);
if (transitionDepth && Number.isInteger(depth) && 0 <= depth && depth <= 20) {
return depth;
}
return Number(route.meta.depth ?? 0);
}
async function submitManualRevoke(): Promise<void> {
if (!canManualRevoke.value || !record.value?.id || isOperating.value) {
return;
}
if (!revokeRemark.value.trim()) {
Message.warning("冲正备注不能为空");
return;
}
if (!revokePhotoItems.value.some(item => !!item.tempFileId)) {
Message.warning("库存流水冲正必须上传至少一张照片");
return;
}
isOperating.value = true;
try {
if (!revokeRequestNo.value) {
revokeRequestNo.value = createProductRequestNo();
}
await ProductAPI.manualRevoke({
requestNo: revokeRequestNo.value,
sourceRecordId: record.value.id,
remark: revokeRemark.value.trim(),
attachmentList: buildAttachments()
});
revokeVisible.value = false;
emitListDataChanged(listDataEventKeys.productStockChanged, record.value.id);
Message.success("手工库存流水已冲正");
await loadData();
} catch (error) {
Message.error(getErrorMessage(error, "库存流水冲正失败,重试会复用同一请求号"));
} finally {
isOperating.value = false;
}
}
async function loadData(): Promise<void> {
const id = resolveId();
if (!id) {
return;
}
isLoading.value = true;
try {
const result = await ProductAPI.recordDetail(id);
record.value = result;
baseUnitName.value = "";
if (result.skuId) {
try {
const sku = await ProductAPI.skuDetail(result.skuId);
baseUnitName.value = sku.unitList?.find(unit => unit.isBase)?.name || sku.unitList?.[0]?.name || "";
} catch {
baseUnitName.value = "";
}
}
} catch (error) {
Message.error(getErrorMessage(error, "库存流水加载失败"));
} finally {
isLoading.value = false;
}
}
onMounted(async () => {
await loadData();
});
watch(resolveId, async (id, previousId) => {
if (id && id !== previousId) {
await loadData();
}
});
</script>
<style scoped lang="less">
.product-stock-record-detail {
gap: 1rem;
display: flex;
padding: 0 0 2rem;
flex-direction: column;
.loading {
margin: 3rem auto;
}
.snapshot-head {
margin: 0 1rem;
padding: 1rem;
background: var(--td-bg-color-container);
box-shadow: var(--td-shadow-1);
border-radius: 1rem;
.eyebrow {
color: var(--td-brand-color);
font-size: .75rem;
font-weight: 700;
}
h2 {
margin: .5rem 0 .25rem;
font-size: 1.25rem;
}
.sku {
color: var(--td-text-color-secondary);
}
.meta {
gap: .5rem;
display: flex;
margin-top: .75rem;
align-items: center;
justify-content: space-between;
span {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
}
}
.positive {
color: var(--td-success-color);
}
.negative {
color: var(--td-error-color);
}
.balance {
gap: .25rem;
display: inline-flex;
align-items: center;
.arrow,
.unit {
color: var(--td-text-color-secondary);
}
}
.data {
gap: .75rem;
display: grid;
padding: .75rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
.card {
gap: .25rem;
min-width: 0;
padding: .5rem .75rem;
display: flex;
background: var(--td-bg-color-secondarycontainer);
border-radius: .75rem;
flex-direction: column;
.label {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
strong {
overflow: hidden;
font-size: 1.25rem;
word-break: break-all;
text-align: center;
line-height: 1.4;
}
}
}
.actions {
padding: 0 1rem;
}
}
:global(html.theme-dark) {
.product-stock-record-detail {
.data .card {
background: rgba(15, 23, 42, .72);
border-color: rgba(148, 163, 184, .16);
}
}
}
.revoke-popup {
padding: .5rem 1rem calc(1rem + var(--tui-safe-bottom, 0px));
.tip {
margin: 0 0 .75rem;
color: var(--td-text-color-secondary);
font-size: .875rem;
}
}
</style>
+3 -2
View File
@@ -5,6 +5,7 @@
<customer-profile-card <customer-profile-card
class="customer" class="customer"
:customer="customer" :customer="customer"
v-entrance-transition
/> />
<template v-if="customerId"> <template v-if="customerId">
<t-cell-group title="额度账户" theme="card" v-entrance-transition> <t-cell-group title="额度账户" theme="card" v-entrance-transition>
@@ -30,7 +31,7 @@
</t-cell> </t-cell>
<t-cell v-if="!accountList.length" title="暂无额度" :note="accountLoading ? '正在加载' : '该客户还没有回收物额度'" /> <t-cell v-if="!accountList.length" title="暂无额度" :note="accountLoading ? '正在加载' : '该客户还没有回收物额度'" />
</t-cell-group> </t-cell-group>
<t-cell-group theme="card"> <t-cell-group theme="card" v-entrance-transition>
<t-cell v-if="canAdjust" title="调整额度" arrow @click="adjustPopup?.open()" /> <t-cell v-if="canAdjust" title="调整额度" arrow @click="adjustPopup?.open()" />
<t-cell title="回收流水" arrow @click="openPayments" /> <t-cell title="回收流水" arrow @click="openPayments" />
</t-cell-group> </t-cell-group>
@@ -127,7 +128,7 @@ async function openPayments(): Promise<void> {
const queryDepth = Number(Array.isArray(route.query.transitionDepth) ? route.query.transitionDepth[0] : route.query.transitionDepth); const queryDepth = Number(Array.isArray(route.query.transitionDepth) ? route.query.transitionDepth[0] : route.query.transitionDepth);
const currentDepth = route.query.transitionDepth && Number.isInteger(queryDepth) && 0 <= queryDepth && !(20 < queryDepth) const currentDepth = route.query.transitionDepth && Number.isInteger(queryDepth) && 0 <= queryDepth && !(20 < queryDepth)
? queryDepth : Number(route.meta.depth ?? 0); ? queryDepth : Number(route.meta.depth ?? 0);
await router.push({ name: "RecyclePaymentAll", query: { customerId: customerId.value, transitionDepth: String(currentDepth + 1) } }); await router.push({ name: "RecycleLedgerList", query: { customerId: customerId.value, transitionDepth: String(currentDepth + 1) } });
} }
function goBack(): void { function goBack(): void {
+243
View File
@@ -0,0 +1,243 @@
<template>
<div class="tui-page-layout tui-navbar recycle-ledger-detail">
<t-navbar
fixed
:z-index="20"
title="回收物流水详情"
left-arrow
@left-click="goBack"
/>
<main
v-can="permissionCodes.recycleAccount.read"
class="tui-page-content scroll column"
>
<t-loading v-if="loading" class="loading" size="32px" />
<template v-else-if="record">
<section class="head" v-entrance-transition>
<div class="eyebrow">客户回收物</div>
<h2 v-text="record.recycleName || '回收物'" />
<div class="meta">
<span v-text="record.customerName || record.customerCode || '未知客户'" />
<t-tag variant="light-outline" :content="getRecycleLedgerTypeText(record.bizType)" />
</div>
</section>
<card-container description="额度变动信息" v-entrance-transition>
<div class="data">
<div class="card">
<span>余额变动</span>
<strong
:class="deltaClass(record.balanceDelta)"
v-text="deltaText(record.balanceDelta)"
/>
</div>
<div class="card">
<span>预占变动</span>
<strong
:class="deltaClass(record.reservedDelta)"
v-text="deltaText(record.reservedDelta)"
/>
</div>
</div>
</card-container>
<t-cell-group title="额度快照" theme="card" v-entrance-transition>
<t-cell title="余额" :note="snapshot(record.balanceAfter, record.balanceDelta)" />
<t-cell title="预占" :note="snapshot(record.reservedAfter, record.reservedDelta)" />
</t-cell-group>
<t-cell-group title="流水信息" theme="card" v-entrance-transition>
<t-cell title="业务类型" :note="getRecycleLedgerTypeText(record.bizType)" />
<t-cell
v-if="record.customerId"
title="客户回收物账户"
note="查看账户"
arrow
@click="openAccount"
/>
<t-cell v-if="orderId" title="关联回收兑换单" note="查看订单详情" arrow @click="openOrder" />
<t-cell title="发生时间">
<template #note>
<time-label :timestamp="record.createdAt" underline />
</template>
</t-cell>
<t-cell
title="操作人"
:note="record.operator?.nick || record.operator?.name || '未知操作人'"
/>
<t-cell v-if="record.reason" title="备注" :note="record.reason" />
</t-cell-group>
</template>
<t-empty v-else description="回收物流水不存在或加载失败" />
</main>
</div>
</template>
<script setup lang="ts">
import { useExpandToMaster, usePane } from "timi-tdesign-mobile";
import { TimeLabel } from "timi-web";
import { useUserStore } from "timi-web-api";
import RecycleAPI from "@/api/RecycleAPI";
import { buildOrderPaneView } from "@/pages/salesOrder/component/orderPane";
import type { RecycleLedger } from "@/types/Recycle";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { getRecycleLedgerTypeText, getRecycleQuantityText } from "@/utils/recycle";
defineOptions({ name: "RecycleLedgerDetail" });
const props = withDefaults(defineProps<{ recordId?: string }>(), { recordId: "" });
const route = useRoute();
const router = useRouter();
const pane = usePane();
const resolveId = (): string => props.recordId || String(route.params.id || "");
useExpandToMaster({
path: "/product/recycle-payments",
id: resolveId,
query: {
...(typeof route.query.customerId === "string" ? { customerId: route.query.customerId } : {}),
...(typeof route.query.transitionDepth === "string" ? { transitionDepth: String(Math.max(0, Number(route.query.transitionDepth) - 1)) } : {})
}
});
function goBack(): void {
if (pane) pane.close();
else void router.back();
}
const userStore = useUserStore();
const record = ref<RecycleLedger>();
const orderId = ref("");
const loading = ref(false);
function deltaClass(value?: number | string): string {
const amount = Number(value || 0);
return 0 < amount ? "positive" : amount < 0 ? "negative" : "";
}
function deltaText(value?: number | string): string {
return `${0 < Number(value || 0) ? "+" : ""}${getRecycleQuantityText(value ?? 0, record.value?.recycleUnit)}`;
}
function snapshot(after?: number | string, delta?: number | string): string {
if ((after === null || after === undefined) || (delta === null || delta === undefined)) return "-";
const before = (Number(after) - Number(delta)).toFixed(3);
return `${getRecycleQuantityText(before, record.value?.recycleUnit)} → ${getRecycleQuantityText(after, record.value?.recycleUnit)}`;
}
async function openAccount(): Promise<void> {
if (!record.value?.customerId) return;
if (pane?.openSub(`recycle-account:${record.value.customerId}`)) return;
const depth = Number(route.query.transitionDepth || route.meta.depth || 0);
await router.push({
name: "RecycleAccount",
query: { customerId: record.value.customerId, transitionDepth: String(depth + 1) }
});
}
async function openOrder(): Promise<void> {
if (!orderId.value) return;
if (pane?.openSub(buildOrderPaneView(orderId.value))) return;
const depth = Number(route.query.transitionDepth || route.meta.depth || 0);
await router.push({
name: "SalesOrderDetail",
params: { id: orderId.value },
query: { transitionDepth: String(depth + 1) }
});
}
async function loadData(): Promise<void> {
loading.value = true;
record.value = undefined;
orderId.value = "";
try {
const result = await RecycleAPI.ledgerDetail(resolveId());
record.value = result;
if (result.bizType?.startsWith("PAYMENT_") && result.bizId
&& userStore.hasPermissions(permissionCodes.fundRecord.read) && userStore.hasPermissions(permissionCodes.salesOrder.read)) {
try {
const payment = await RecycleAPI.paymentDetail(result.bizId);
orderId.value = payment.orderId || "";
} catch (error) {
Message.error(getErrorMessage(error, "关联订单加载失败"));
}
}
} catch (error) {
Message.error(getErrorMessage(error, "回收物流水加载失败"));
} finally {
loading.value = false;
}
}
onMounted(async () => await loadData());
watch(resolveId, async (id, previousId) => {
if (id && id !== previousId) await loadData();
});
</script>
<style scoped lang="less">
.recycle-ledger-detail {
.loading {
margin: 3rem auto;
}
.head {
margin: 0 1rem;
padding: 1rem;
background: var(--td-bg-color-container);
box-shadow: var(--td-shadow-1);
border-radius: 1rem;
.eyebrow {
color: var(--td-brand-color);
font-size: .75rem;
font-weight: 700;
}
h2 {
margin: .5rem 0;
font-size: 1.25rem;
}
.meta {
display: flex;
align-items: center;
justify-content: space-between;
}
}
.data {
gap: .75rem;
display: grid;
padding: .75rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
.card {
gap: .5rem;
display: flex;
padding: .75rem;
background: var(--td-bg-color-secondarycontainer);
border-radius: .75rem;
flex-direction: column;
span {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
strong {
font-size: 1.25rem;
word-break: break-all;
text-align: center;
}
}
}
.positive {
color: var(--td-success-color);
}
.negative {
color: var(--td-error-color);
}
}
</style>
+394
View File
@@ -0,0 +1,394 @@
<template>
<div class="tui-page-layout tui-navbar recycle-ledger-list">
<t-navbar fixed :z-index="20" title="回收物流水" left-arrow @left-click="$router.back()" />
<master-detail-page v-can="permissionCodes.recycleAccount.read" class="list" :split="isWide" :selected="!!selectedId" :direction="paneDirection" :sub="!!orderPane?.view">
<template #master>
<t-pull-down-refresh
v-model="refreshing"
class="pull-refresh"
:refresh-timeout="30000"
@refresh="reload"
@scrolltolower="loadMore"
>
<div class="filters glass">
<t-input
v-model="keyword"
borderless
clearable
placeholder="搜索客户姓名、拼音或编码"
@enter="reload"
>
<template #suffix-icon>
<t-button
size="extra-small"
theme="primary"
variant="outline"
:content="customerId ? '更换客户' : '选择客户'"
@click.stop="customerVisible = true"
/>
</template>
</t-input>
<t-dropdown-menu class="menus">
<t-dropdown-item
v-model="dateType"
:label="dateLabel"
:options="dateOptions"
@change="selectDate"
/>
<t-dropdown-item
v-model="bizType"
label="流水类型"
:options="typeOptions"
@change="reload"
/>
</t-dropdown-menu>
</div>
<t-cell-group v-if="customerId || dateType === 'custom'" theme="card">
<t-cell v-if="customerId" title="已选择客户" note="清除" arrow @click="clearCustomer" />
<template v-if="dateType === 'custom'">
<t-cell title="开始时间" :note="dateRange[0] || '-'" arrow @click="openDate(false)" />
<t-cell title="结束时间" :note="dateRange[1] || '-'" arrow @click="openDate(true)" />
</template>
</t-cell-group>
<t-cell-group v-if="records.length" class="records empty-cell-title-margin" theme="card">
<t-cell v-for="record in records" :key="record.id" class="item" :arrow="!!record.id" :hover="!!record.id" @click="openRecord(record)" v-entrance-transition="{ step: 30 }">
<template #leftIcon>
<t-image
v-if="getCustomerPhotoURL(record.customer ?? undefined, 64)"
class="avatar"
:src="getCustomerPhotoURL(record.customer ?? undefined, 64)"
:alt="record.customerName || record.customerCode || '客户头像'"
fit="cover"
/>
<div v-else class="avatar fallback" v-text="(record.customerName || record.customerCode || '客').slice(0, 1)" />
</template>
<template #title>
<div class="title">
<span class="actor" v-text="record.customerName || record.customerCode || '未知客户'" />
<strong class="operation" :class="getTypeClass(record.bizType)" v-text="getRecycleLedgerTypeText(record.bizType)" />
<strong class="name clip-text" v-text="record.recycleName || '回收物'" />
</div>
</template>
<template #description>
<div class="description">
<time-label :timestamp="record.createdAt" underline />
<div class="deltas">
<span v-if="!isReservation(record.bizType)">余额 <span class="value" :class="getDeltaClass(record.balanceDelta)" v-text="quantityText(record.balanceDelta, record.recycleUnit)" /></span>
<span v-else>预占 <span class="value" :class="getDeltaClass(record.reservedDelta)" v-text="quantityText(record.reservedDelta, record.recycleUnit)" /></span>
</div>
</div>
<div v-if="record.reason" class="reason" v-text="record.reason" />
</template>
</t-cell>
</t-cell-group>
<center-tips v-else :content="loading ? '正在加载回收物流水' : '暂无回收物流水'" />
<center-tips
v-if="records.length"
:content="loading ? '正在加载' : noMore ? '已经到底了' : '上拉加载更多'"
/>
</t-pull-down-refresh>
</template>
<template #detail>
<sales-order-detail v-if="orderPane" :key="`order-${orderPane.orderId}`" :order-id="orderPane.orderId" />
<recycle-account v-else-if="accountId" :key="`account-${accountId}`" :initial-customer-id="accountId" />
<recycle-ledger-detail v-else :key="`detail-${selectedId}-${detailVersion}`" :record-id="selectedId" />
</template>
<template #sub>
<sales-order-sub-view
v-if="orderPane?.view"
:key="`sub-${orderPane.view}`"
:view="orderPane.view"
:order-id="orderPane.orderId"
@saved="handleOrderSubSaved"
/>
</template>
</master-detail-page>
<customer-selector
v-model="customerId"
v-model:visible="customerVisible"
@change="reload"
/>
<t-popup v-model="dateVisible" placement="bottom">
<t-date-time-picker
v-if="dateVisible"
v-model="dateDraft"
format="YYYY-MM-DD HH:mm"
:mode="['date', 'minute']"
:title="editingEnd ? '结束时间' : '开始时间'"
@cancel="dateVisible = false" @confirm="confirmDate"
/>
</t-popup>
</div>
</template>
<script setup lang="ts">
import { MasterDetailPage, providePane, useMasterDetailPane } from "timi-tdesign-mobile";
import RecycleLedgerDetail from "@/pages/recycle/RecycleLedgerDetail.vue";
import RecycleAccount from "@/pages/recycle/RecycleAccount.vue";
import SalesOrderDetail from "@/pages/salesOrder/SalesOrderDetail.vue";
import SalesOrderSubView from "@/pages/salesOrder/component/SalesOrderSubView.vue";
import { buildOrderPaneView, getOrderPaneRoute, parseOrderPaneView } from "@/pages/salesOrder/component/orderPane";
import type { DropdownValue } from "tdesign-mobile-vue";
import { Time, TimeLabel } from "timi-web";
import RecycleAPI from "@/api/RecycleAPI";
import CustomerSelector from "@/components/CustomerSelector.vue";
import type { RecycleLedger } from "@/types/Recycle";
import { buildPresetDateRange, parseDateTime } from "@/utils/date";
import { DATE_FILTER_OPTIONS as dateOptions, type DateFilterType } from "@/utils/dateFilter";
import { getErrorMessage } from "@/utils/error";
import { getCustomerPhotoURL } from "@/utils/customer";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { getRecycleLedgerTypeText, getRecycleQuantityText } from "@/utils/recycle";
defineOptions({ name: "RecycleLedgerList" });
const route = useRoute();
const customerId = ref(typeof route.query.customerId === "string" ? route.query.customerId : "");
const { selectedId, detailVersion, subView, paneDirection, isWide, openDetail, openSub, close } = useMasterDetailPane({
path: "/product/recycle-payments",
detail: id => {
const order = parseOrderPaneView(subView.value || "");
if (order) return getOrderPaneRoute(order);
if (accountId.value) return `/management/recycle-accounts?customerId=${encodeURIComponent(accountId.value)}`;
const query = new URLSearchParams();
if (customerId.value) query.set("customerId", customerId.value);
const depth = Number(route.query.transitionDepth || route.meta.depth || 0);
query.set("transitionDepth", String(depth + 1));
return `/product/recycle-ledgers/${encodeURIComponent(id)}?${query}`;
}
});
const orderPane = computed(() => parseOrderPaneView(subView.value || ""));
const accountId = computed(() => {
const view = subView.value || "";
return view.startsWith("recycle-account:") ? view.slice("recycle-account:".length) : "";
});
providePane({
close: saved => close(saved),
openSub: view => openSub(orderPane.value && !parseOrderPaneView(view) ? buildOrderPaneView(orderPane.value.orderId, view) : view)
});
watch(orderPane, (next, previous) => {
if (previous?.view && !next?.view) paneDirection.value = "back";
});
function handleOrderSubSaved(kind: string, id: string): void {
const order = orderPane.value;
if (!order || !id) return;
if (kind === "fulfillment-create") openSub(buildOrderPaneView(order.orderId, `fulfillment-detail:${id}`));
if (kind === "recycle-register") openSub(buildOrderPaneView(order.orderId, `recycle-payment-detail:${order.view.split(":")[1] || ""}:${id}`));
}
const customerVisible = ref(false);
const keyword = ref("");
const bizType = ref("ALL");
const dateType = ref<DateFilterType>("all");
const dateRange = ref<[string, string]>(["", ""]);
const dateVisible = ref(false);
const dateDraft = ref("");
const editingEnd = ref(false);
const dateLabel = computed(() => dateOptions.find(item => item.value === dateType.value)?.label || "时间范围");
const typeOptions = [
{ label: "全部类型", value: "ALL" }, ...[
"FULFILLMENT_YIELD",
"FULFILLMENT_REVOKE",
"MANUAL",
"PAYMENT_RESERVE",
"PAYMENT_RELEASE",
"PAYMENT_VERIFY",
"PAYMENT_REVOKE"
].map(value => ({ label: getRecycleLedgerTypeText(value), value }))
];
const records = ref<RecycleLedger[]>([]);
const loading = ref(false);
const refreshing = ref(false);
const noMore = ref(false);
let version = 0;
let index = 0;
function openRecord(record: RecycleLedger): void {
if (record.id) openDetail(record.id);
}
function isReservation(type?: string): boolean {
return type === "PAYMENT_RESERVE" || type === "PAYMENT_RELEASE";
}
function quantityText(value?: number | string, unit?: string): string {
return `${0 < Number(value ?? 0) ? "+" : ""}${getRecycleQuantityText(value ?? 0, unit)}`;
}
function getDeltaClass(value?: number | string): string {
const amount = Number(value ?? 0);
return 0 < amount ? "positive" : amount < 0 ? "negative" : "";
}
function getTypeClass(type?: string): string {
return ({
FULFILLMENT_YIELD: "yield",
FULFILLMENT_REVOKE: "fulfillment-revoke",
MANUAL: "manual",
ADJUST: "manual",
PAYMENT_RESERVE: "reserve",
PAYMENT_RELEASE: "release",
PAYMENT_VERIFY: "verify",
PAYMENT_REVOKE: "payment-revoke"
} as Record<string, string>)[type || ""] || "";
}
async function loadMore(): Promise<void> {
if (loading.value || noMore.value) return;
const token = version;
loading.value = true;
try {
const result = await RecycleAPI.ledgerList({
index, size: 20, customerId: customerId.value || undefined, keyword: keyword.value || undefined,
bizType: bizType.value === "ALL" ? undefined : bizType.value,
beginAt: dateRange.value[0] ? Time.toTimestamp(parseDateTime(dateRange.value[0], false)) : undefined,
endAt: dateRange.value[1] ? Time.toTimestamp(parseDateTime(dateRange.value[1], true)) : undefined
});
if (token !== version) return;
records.value.push(...result.list);
index++;
noMore.value = !(records.value.length < result.total) || !result.list.length;
} catch (error) {
if (token === version) Message.error(getErrorMessage(error, "回收物流水加载失败"));
} finally {
if (token === version) {
loading.value = false;
refreshing.value = false;
}
}
}
async function reload(): Promise<void> {
version++;
index = 0;
records.value = [];
loading.value = false;
noMore.value = false;
await loadMore();
}
async function clearCustomer(): Promise<void> {
customerId.value = "";
await reload();
}
async function selectDate(value: DropdownValue): Promise<void> {
if (Array.isArray(value)) return;
dateType.value = String(value) as DateFilterType;
dateRange.value = dateType.value === "custom" ? ["", ""] : buildPresetDateRange(dateType.value);
await reload();
}
function openDate(end: boolean): void {
editingEnd.value = end;
dateDraft.value = dateRange.value[end ? 1 : 0];
dateVisible.value = true;
}
async function confirmDate(value?: string | number): Promise<void> {
dateVisible.value = false;
const next = String(value || dateDraft.value);
const [begin, end] = editingEnd.value ? [dateRange.value[0], next] : [next, dateRange.value[1]];
if (begin && end && parseDateTime(end, true) < parseDateTime(begin, false)) {
Message.warning("结束时间不能早于开始时间");
return;
}
dateRange.value = [begin, end];
await reload();
}
onMounted(async () => await reload());
</script>
<style scoped lang="less">
.recycle-ledger-list {
.records {
margin: 0;
.item {
padding: .625rem;
min-width: 0;
.avatar {
width: 3.5rem;
height: 3.5rem;
}
.title {
gap: .25rem;
flex: 1;
display: flex;
min-width: 0;
max-width: 100%;
font-size: .75rem;
align-items: center;
white-space: nowrap;
.actor {
flex: 0 0 auto;
color: var(--td-text-color-brand);
}
.operation {
flex: 0 0 auto;
color: var(--operation-color, var(--td-text-color-secondary));
font-weight: 700;
&.yield { --operation-color: #15803d; }
&.fulfillment-revoke { --operation-color: #c2410c; }
&.manual { --operation-color: #2563eb; }
&.reserve { --operation-color: #7c3aed; }
&.release { --operation-color: #0891b2; }
&.verify { --operation-color: #dc2626; }
&.payment-revoke { --operation-color: #4f46e5; }
}
.name {
flex: 0 1 auto;
color: var(--td-text-color-primary);
}
}
.description {
gap: .5rem;
display: flex;
font-size: .75rem;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
.deltas {
gap: .5rem;
display: flex;
flex-wrap: wrap;
align-items: center;
.value { font-size: 1.25rem; }
}
}
.reason {
color: var(--td-text-color-secondary);
font-size: .75rem;
word-break: break-all;
}
}
}
.positive { color: var(--td-success-color); }
.negative { color: var(--td-error-color); }
}
:global(html.theme-dark) .recycle-ledger-list .operation {
&.yield { --operation-color: #86efac; }
&.fulfillment-revoke { --operation-color: #fdba74; }
&.manual { --operation-color: #93c5fd; }
&.reserve { --operation-color: #c4b5fd; }
&.release { --operation-color: #67e8f9; }
&.verify { --operation-color: #fca5a5; }
&.payment-revoke { --operation-color: #a5b4fc; }
}
</style>
@@ -1,6 +1,12 @@
<template> <template>
<div class="tui-page-layout tui-navbar recycle-payment-list"> <div class="tui-page-layout tui-navbar recycle-order-payment-list">
<t-navbar fixed :z-index="20" title="回收流水" left-arrow @left-click="exit"> <t-navbar
fixed
:z-index="20"
title="订单回收流水"
left-arrow
@left-click="exit"
>
<template #right> <template #right>
<t-button <t-button
v-if="canRegister" v-if="canRegister"
@@ -12,13 +18,14 @@
/> />
</template> </template>
</t-navbar> </t-navbar>
<main class="tui-page-content list"> <main class="tui-page-content column scroll list">
<t-pull-down-refresh <t-pull-down-refresh
class="pull-refresh" class="pull-refresh"
v-model="refreshing" v-model="refreshing"
:refresh-timeout="30000" :refresh-timeout="30000"
@refresh="reload" @refresh="reload"
@scrolltolower="loadMore"> @scrolltolower="loadMore"
>
<div class="filters glass"> <div class="filters glass">
<t-input <t-input
class="customer" class="customer"
@@ -59,30 +66,53 @@
/> />
<t-dropdown-item <t-dropdown-item
v-model="status" v-model="status"
label="状态" label="支付状态"
:options="statusOptions" :options="statusOptions"
@change="reload" @change="reload"
/> />
<t-dropdown-item
v-if="customerId && !currentId"
v-model="ledgerType"
label="额度类型"
:options="ledgerTypeOptions"
/>
</t-dropdown-menu> </t-dropdown-menu>
</div> </div>
<t-cell-group v-if="dateType === 'custom'" class="date-summary" theme="card"> <t-cell-group v-if="dateType === 'custom'" class="date-summary" theme="card">
<t-cell title="开始时间" :note="dateRange[0] || '-'" arrow @click="openDate(false)" /> <t-cell title="开始时间" :note="dateRange[0] || '-'" arrow @click="openDate(false)" />
<t-cell title="结束时间" :note="dateRange[1] || '-'" arrow @click="openDate(true)" /> <t-cell title="结束时间" :note="dateRange[1] || '-'" arrow @click="openDate(true)" />
</t-cell-group> </t-cell-group>
<t-cell-group <t-cell-group v-if="exchange" theme="card" v-entrance-transition>
v-if="paymentList.length" <t-cell title="订单号" :note="order?.orderNo || '-'" />
class="empty-cell-title-margin" <t-cell :note="exchange.recycleNameSnapshot || '回收物'">
theme="card" <template #title>
> <t-image v-if="recyclePhotoId" class="recycle-avatar" :src="getAttachmentReadURL(recyclePhotoId, 96)" :alt="exchange.recycleNameSnapshot || '回收物'" fit="cover" />
<span v-else class="recycle-avatar fallback" v-text="(exchange.recycleNameSnapshot || '回').slice(0, 1)" />
</template>
</t-cell>
<t-cell title="总回收量" :note="getRecycleQuantityText(exchange.recycleQuantity, exchange.recycleUnitSnapshot)" />
<t-cell title="剩余回收" :note="getRecycleQuantityText(remaining.toFixed(3), exchange.recycleUnitSnapshot)" />
</t-cell-group>
<t-cell-group v-if="filteredLedgerRecords.length" title="额度流水" theme="card">
<t-cell <t-cell
class="item" v-for="record in filteredLedgerRecords"
v-for="payment in paymentList" :key="record.id"
:key="payment.id" :title="recycleItems.get(record.recycleItemId || '')?.name || '回收物'"
arrow :note="ledgerQuantity(record)"
v-entrance-transition
@click="openDetail(payment)"
> >
<template #leftIcon> <template #description>
<div v-text="getRecycleLedgerTypeText(record.bizType)" />
<div v-if="record.reason" v-text="record.reason" />
<time-label :timestamp="record.createdAt" />
</template>
</t-cell>
</t-cell-group>
<center-tips v-else-if="customerId && !currentId && !ledgerLoading" content="暂无符合条件的额度流水" />
<t-cell v-if="customerId && !currentId && ledgerHasMore" :title="ledgerLoading ? '正在加载额度流水' : '加载更多额度流水'" :arrow="!ledgerLoading" @click="loadMoreLedger" />
<center-tips v-if="customerId && !currentId && ledgerHasMore && (ledgerType !== 'ALL' || dateType !== 'all')" content="筛选仅作用于已加载的额度流水" />
<div v-if="paymentList.length" class="records">
<div v-for="payment in paymentList" :key="payment.id" class="item" v-entrance-transition="{ step: 30 }">
<div class="header">
<t-image <t-image
v-if="getCustomerPhotoURL(payment.customer, 64)" v-if="getCustomerPhotoURL(payment.customer, 64)"
class="avatar" class="avatar"
@@ -91,48 +121,32 @@
fit="cover" fit="cover"
/> />
<div v-else class="avatar fallback" v-text="customerName(payment).slice(0, 1)" /> <div v-else class="avatar fallback" v-text="customerName(payment).slice(0, 1)" />
</template> <div class="main">
<template #title> <div class="customer-status">
<div class="title"> <strong class="customer clip-text" v-text="customerName(payment)" />
<span class="customer clip-text" v-text="customerName(payment)" /> <div class="tags">
<span <t-tag size="small" variant="light" :theme="payment.sourcePaymentId ? 'danger' : 'success'" :content="payment.sourcePaymentId ? '回收冲正' : '回收登记'" />
class="type" <t-tag size="small" variant="light-outline" :content="getRecyclePaymentStatusText(payment.status)" :theme="getRecyclePaymentStatusTheme(payment.status)" />
:class="payment.sourcePaymentId ? 'revoke' : 'receive'"
v-text="payment.sourcePaymentId ? '回收冲正' : '回收登记'"
/>
<t-tag
:content="getRecyclePaymentStatusText(payment.status)"
:theme="getRecyclePaymentStatusTheme(payment.status)"
size="small"
variant="light-outline"
/>
</div>
</template>
<template #description>
<div class="description">
<div class="operator">
<div class="field"><span class="label">发起人</span><span class="text-bold"
v-text="payment.operator?.nick || payment.operator?.name || '未知'" />
</div> </div>
<div v-if="payment.verifierUserId" class="field">
<span
class="label"
v-text="payment.status === 'VERIFIED' ? '核销人' : '处理人'" />
<span
class="text-bold"
v-text="payment.verifier?.nick || payment.verifier?.name || '未知'"
/>
</div>
<time-label :timestamp="payment.occurredAt" underline />
</div> </div>
<div class="quantity"> <div class="record-line">
<strong class="red" v-text="paymentQuantity(payment)" /> <time-label class="time" :timestamp="payment.occurredAt" underline />
<strong class="quantity red" v-text="paymentQuantity(payment)" />
</div> </div>
</div> </div>
</template> </div>
</t-cell> <t-divider />
</t-cell-group> <div class="people-actions">
<center-tips v-else :content="loading ? '正在加载回收流水' : '暂无回收流水'" /> <div class="person"><span class="label">发起人</span><strong v-text="payment.operator?.nick || payment.operator?.name || payment.operatorUserId || '未知'" /></div>
<div v-if="payment.verifierUserId" class="person">
<span class="label" v-text="payment.status === 'VERIFIED' ? '核销人' : '处理人'" />
<strong v-text="payment.verifier?.nick || payment.verifier?.name || payment.verifierUserId || '未知'" />
</div>
<div class="actions"><t-button theme="primary" size="extra-small" content="详情" @click.stop="openDetail(payment)" /></div>
</div>
</div>
</div>
<center-tips v-else :content="loading ? '正在加载回收支付记录' : '暂无回收支付记录'" />
<center-tips <center-tips
v-if="paymentList.length" v-if="paymentList.length"
:content="loading ? '正在加载' : noMore ? '已经到底了' : '上拉加载更多'" :content="loading ? '正在加载' : noMore ? '已经到底了' : '上拉加载更多'"
@@ -165,18 +179,21 @@ import { Time, TimeLabel } from "timi-web";
import { useUserStore } from "timi-web-api"; import { useUserStore } from "timi-web-api";
import CustomerAPI from "@/api/CustomerAPI"; import CustomerAPI from "@/api/CustomerAPI";
import RecycleAPI from "@/api/RecycleAPI"; import RecycleAPI from "@/api/RecycleAPI";
import SalesOrderAPI from "@/api/SalesOrderAPI";
import CustomerSelector from "@/components/CustomerSelector.vue"; import CustomerSelector from "@/components/CustomerSelector.vue";
import type { Customer } from "@/types/Customer"; import type { Customer } from "@/types/Customer";
import type { RecycleExchange, RecyclePayment } from "@/types/Recycle"; import type { SalesOrder } from "@/types/SalesOrder";
import { getAttachmentReadURL } from "@/utils/attachment";
import type { RecycleExchange, RecycleItem, RecycleLedger, RecyclePayment } from "@/types/Recycle";
import { getCustomerPhotoURL } from "@/utils/customer"; import { getCustomerPhotoURL } from "@/utils/customer";
import { buildPresetDateRange, parseDateTime } from "@/utils/date"; import { buildPresetDateRange, parseDateTime } from "@/utils/date";
import { DATE_FILTER_OPTIONS as dateOptions, type DateFilterType } from "@/utils/dateFilter"; import { DATE_FILTER_OPTIONS as dateOptions, type DateFilterType } from "@/utils/dateFilter";
import { getErrorMessage } from "@/utils/error"; import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message"; import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission"; import { permissionCodes } from "@/utils/permission";
import { getRecyclePaymentStatusText, getRecyclePaymentStatusTheme, getRecycleQuantityText } from "@/utils/recycle"; import { getRecycleLedgerTypeText, getRecyclePaymentStatusText, getRecyclePaymentStatusTheme, getRecycleQuantityText } from "@/utils/recycle";
defineOptions({ name: "RecyclePaymentList" }); defineOptions({ name: "RecycleOrderPaymentList" });
const props = withDefaults(defineProps<{ exchangeId?: string }>(), { exchangeId: "" }); const props = withDefaults(defineProps<{ exchangeId?: string }>(), { exchangeId: "" });
const router = useRouter(); const router = useRouter();
const route = useRoute(); const route = useRoute();
@@ -184,8 +201,15 @@ const pane = usePane();
const userStore = useUserStore(); const userStore = useUserStore();
const currentId = computed(() => props.exchangeId || (typeof route.params.id === "string" ? route.params.id : "")); const currentId = computed(() => props.exchangeId || (typeof route.params.id === "string" ? route.params.id : ""));
const exchange = ref<RecycleExchange>(); const exchange = ref<RecycleExchange>();
const order = ref<SalesOrder>();
const recyclePhotoId = computed(() => exchange.value?.recycleItemAttachments?.find(item => item.id && item.mimeType?.startsWith("image/"))?.id || "");
const remaining = ref(0); const remaining = ref(0);
const paymentList = ref<RecyclePayment[]>([]); const paymentList = ref<RecyclePayment[]>([]);
const ledgerRecords = ref<RecycleLedger[]>([]);
const ledgerLoading = ref(false);
const ledgerHasMore = ref(false);
let ledgerIndex = 0;
const recycleItems = ref(new Map<string, RecycleItem>());
const loading = ref(false); const loading = ref(false);
const refreshing = ref(false); const refreshing = ref(false);
const noMore = ref(false); const noMore = ref(false);
@@ -194,6 +218,7 @@ const selectedCustomer = ref<Customer>();
const customerSearchKeyword = ref(""); const customerSearchKeyword = ref("");
const customerSelectorVisible = ref(false); const customerSelectorVisible = ref(false);
const status = ref("ALL"); const status = ref("ALL");
const ledgerType = ref("ALL");
const dateType = ref<DateFilterType>("all"); const dateType = ref<DateFilterType>("all");
const dateRange = ref<[string, string]>(["", ""]); const dateRange = ref<[string, string]>(["", ""]);
const dateVisible = ref(false); const dateVisible = ref(false);
@@ -204,10 +229,68 @@ const statusOptions = [
{ label: "已核销", value: "VERIFIED" }, { label: "已拒绝", value: "REJECTED" }, { label: "已核销", value: "VERIFIED" }, { label: "已拒绝", value: "REJECTED" },
{ label: "已撤销", value: "CANCELLED" }, { label: "已冲正", value: "REVOKED" } { label: "已撤销", value: "CANCELLED" }, { label: "已冲正", value: "REVOKED" }
]; ];
const ledgerTypeOptions = [
{ label: "全部额度类型", value: "ALL" },
...[
"FULFILLMENT_YIELD", "FULFILLMENT_REVOKE", "MANUAL",
"PAYMENT_RESERVE", "PAYMENT_RELEASE", "PAYMENT_VERIFY", "PAYMENT_REVOKE"
].map(value => ({ label: getRecycleLedgerTypeText(value), value }))
];
const dateLabel = computed(() => dateOptions.find(item => item.value === dateType.value)?.label || "时间范围"); const dateLabel = computed(() => dateOptions.find(item => item.value === dateType.value)?.label || "时间范围");
const canRegister = computed(() => !!exchange.value && 0 < remaining.value && userStore.hasPermissions(permissionCodes.fundReceive.create)); const canRegister = computed(() => !!exchange.value && 0 < remaining.value && userStore.hasPermissions(permissionCodes.fundReceive.create));
const filteredLedgerRecords = computed(() => {
if (currentId.value || !customerId.value) return [];
const begin = dateRange.value[0] ? Time.toTimestamp(parseDateTime(dateRange.value[0], false)) : 0;
const end = dateRange.value[1] ? Time.toTimestamp(parseDateTime(dateRange.value[1], true)) : Infinity;
return ledgerRecords.value.filter(item => (ledgerType.value === "ALL" || item.bizType === ledgerType.value
|| (ledgerType.value === "MANUAL" && item.bizType === "ADJUST"))
&& (item.createdAt ? !(item.createdAt < begin) && !(end < item.createdAt) : !dateRange.value[0] && !dateRange.value[1]));
});
let requestVersion = 0; let requestVersion = 0;
function ledgerQuantity(record: RecycleLedger): string {
const item = recycleItems.value.get(record.recycleItemId || "");
const format = (value: number | string | undefined): string => {
const quantity = Number(value ?? 0);
return `${0 < quantity ? "+" : ""}${getRecycleQuantityText(value ?? 0, item?.unitName)}`;
};
return `余额 ${format(record.balanceDelta)},预占 ${format(record.reservedDelta)}`;
}
async function loadLedger(version: number): Promise<void> {
if (currentId.value || !customerId.value) return;
ledgerLoading.value = true;
try {
const [result, items] = await Promise.all([RecycleAPI.accountLedger(customerId.value, 0, 20), RecycleAPI.accountItems()]);
if (version !== requestVersion) return;
ledgerRecords.value = result.list;
ledgerIndex = 1;
ledgerHasMore.value = result.list.length < result.total && 0 < result.list.length;
recycleItems.value = new Map(items.filter(item => item.id).map(item => [item.id!, item]));
} catch (error) {
if (version === requestVersion) Message.error(getErrorMessage(error, "额度流水加载失败"));
} finally {
if (version === requestVersion) ledgerLoading.value = false;
}
}
async function loadMoreLedger(): Promise<void> {
if (ledgerLoading.value || !ledgerHasMore.value || !customerId.value) return;
const version = requestVersion;
ledgerLoading.value = true;
try {
const result = await RecycleAPI.accountLedger(customerId.value, ledgerIndex, 20);
if (version !== requestVersion) return;
ledgerRecords.value.push(...result.list);
ledgerIndex++;
ledgerHasMore.value = ledgerRecords.value.length < result.total && 0 < result.list.length;
} catch (error) {
if (version === requestVersion) Message.error(getErrorMessage(error, "额度流水加载失败"));
} finally {
if (version === requestVersion) ledgerLoading.value = false;
}
}
function exit(): void { function exit(): void {
if (pane) { if (pane) {
pane.close(); pane.close();
@@ -256,10 +339,15 @@ async function reload(): Promise<void> {
requestVersion += 1; requestVersion += 1;
const version = requestVersion; const version = requestVersion;
loading.value = false; loading.value = false;
ledgerLoading.value = false;
paymentList.value = []; paymentList.value = [];
ledgerRecords.value = [];
ledgerHasMore.value = false;
ledgerIndex = 0;
noMore.value = false; noMore.value = false;
if (currentId.value) { if (currentId.value) {
exchange.value = undefined; exchange.value = undefined;
order.value = undefined;
try { try {
const result = await RecycleAPI.detail(currentId.value); const result = await RecycleAPI.detail(currentId.value);
if (version !== requestVersion) return; if (version !== requestVersion) return;
@@ -269,8 +357,12 @@ async function reload(): Promise<void> {
refreshing.value = false; refreshing.value = false;
return; return;
} }
const payments = await RecycleAPI.paymentList(exchange.value.salesOrderId); const [payments, salesOrder] = await Promise.all([
RecycleAPI.paymentList(exchange.value.salesOrderId),
SalesOrderAPI.detail(exchange.value.salesOrderId)
]);
if (version !== requestVersion) return; if (version !== requestVersion) return;
order.value = salesOrder;
const reserved = payments.filter(item => item.status === "PENDING" || (item.status === "VERIFIED" && !item.sourcePaymentId)) const reserved = payments.filter(item => item.status === "PENDING" || (item.status === "VERIFIED" && !item.sourcePaymentId))
.reduce((sum, item) => sum + Number(item.quantity ?? 0), 0); .reduce((sum, item) => sum + Number(item.quantity ?? 0), 0);
remaining.value = Math.max(Number(exchange.value.recycleQuantity ?? 0) - reserved, 0); remaining.value = Math.max(Number(exchange.value.recycleQuantity ?? 0) - reserved, 0);
@@ -282,7 +374,7 @@ async function reload(): Promise<void> {
return; return;
} }
} else exchange.value = undefined; } else exchange.value = undefined;
await loadMore(); await Promise.all([loadMore(), loadLedger(version)]);
} }
async function handleCustomerChange(value: string | string[]): Promise<void> { async function handleCustomerChange(value: string | string[]): Promise<void> {
@@ -380,69 +472,76 @@ onActivated(reload);
watch(currentId, reload); watch(currentId, reload);
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.recycle-payment-list { .recycle-order-payment-list {
.recycle-avatar {
width: 2.5rem;
height: 2.5rem;
border-radius: .5rem;
}
.records {
gap: 1rem;
margin: 0 1rem;
display: flex;
flex-direction: column;
}
.item { .item {
padding: 10px; gap: .5rem;
display: flex;
padding: .625rem;
background: var(--td-bg-color-container);
border-radius: 1rem;
flex-direction: column;
.avatar { .header {
width: 3.5rem; gap: .5rem;
height: 3.5rem; display: flex;
.avatar { width: 3.5rem; height: 3.5rem; }
.main { gap: .5rem; flex: 1; display: flex; min-width: 0; flex-direction: column; }
.customer-status, .record-line { gap: .5rem; display: flex; align-items: center; justify-content: space-between; }
.customer { min-width: 0; }
.tags { gap: .5rem; display: flex; align-items: center; }
.time { color: var(--td-text-color-secondary); font-size: .75rem; }
.quantity { font-size: 1.25rem; white-space: nowrap; }
} }
.title { .people-actions {
gap: .25rem; gap: .75rem;
display: flex; display: flex;
font-size: .75rem;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
.customer { font-weight: 600; } .person {
.type { gap: .25rem;
font-weight: 700;
&.receive { color: #15803d; }
&.revoke { color: #7c3aed; }
}
}
.description {
display: flex;
align-items: start;
justify-content: space-between;
.operator {
color: var(--td-text-color-secondary);
display: flex; display: flex;
min-width: 0;
font-size: .75rem; font-size: .75rem;
line-height: 1.5;
flex-direction: column;
}
.field {
gap: .25rem;
display: inline-flex;
}
.label {
color: var(--td-text-color-placeholder);
}
.quantity {
gap: .25rem;
display: flex;
font-size: 1.25rem;
align-items: baseline; align-items: baseline;
white-space: nowrap;
.label { flex: 0 0 auto; color: var(--td-text-color-secondary); }
strong { overflow: hidden; max-width: 10rem; white-space: nowrap; text-overflow: ellipsis; }
}
.actions {
--td-button-border-radius: .5rem;
display: flex;
justify-content: end;
.t-button { padding-left: 1.5rem; padding-right: 1.5rem; }
} }
} }
} }
} }
:global(html.theme-dark) .recycle-payment-list { :deep(.avatar .t-image__img) {
.type { width: 100%;
&.receive { color: #86efac; } height: 100%;
&.revoke { color: #c4b5fd; } object-fit: cover;
} border-radius: inherit;
} }
:global(html.theme-dark) .recycle-payment-list .fallback { background: #115e59; }
</style> </style>
+280 -167
View File
@@ -7,181 +7,215 @@
left-arrow left-arrow
@left-click="$router.back()" @left-click="$router.back()"
/> />
<main v-can="permissionCodes.salesOrder.read" class="tui-page-content scroll column list"> <master-detail-page
<t-pull-down-refresh v-can="permissionCodes.salesOrder.read"
class="pull-refresh" class="list"
v-model="isRefreshing" :split="isWide"
:refresh-timeout="30000" :selected="!!selectedId"
@refresh="reloadRecords" :direction="paneDirection"
@scrolltolower="loadRecords" :sub="!!subView"
> >
<div class="filters glass"> <template #master>
<t-input <t-pull-down-refresh
class="keyword" class="pull-refresh"
:value="customerDisplayText" v-model="isRefreshing"
readonly :refresh-timeout="30000"
borderless @refresh="reloadRecords"
placeholder="选择或扫码客户" @scrolltolower="loadRecords"
@click="customerSelectorVisible = true" >
> <div class="filters glass">
<template #suffix-icon> <t-input
<div class="actions"> class="keyword"
<t-button :value="customerDisplayText"
v-if="customerId" readonly
shape="circle" borderless
theme="danger" placeholder="选择或扫码客户"
variant="text" @click="customerSelectorVisible = true"
size="extra-small"
aria-label="清除客户选择"
@click.stop="clearCustomer"
>
<t-icon name="close" size="1rem" />
</t-button>
<t-button
size="extra-small"
theme="primary"
variant="outline"
:content="scannerVisible ? '关闭扫码' : '扫码'"
@click.stop="toggleScanner"
/>
</div>
</template>
</t-input>
<t-dropdown-menu class="menus">
<t-dropdown-item
v-model="dateFilterType"
:label="dateFilterLabel"
:options="dateOptions"
@change="selectDateFilter"
/>
<t-dropdown-item
v-model="sourceType"
label="消费来源"
:options="sourceTypeOptions"
@change="reloadRecords"
/>
<t-dropdown-item
v-model="status"
label="消费状态"
:options="statusOptions"
@change="reloadRecords"
/>
</t-dropdown-menu>
</div>
<div class="list-wrap">
<div v-if="scannerVisible" class="scanner-wrap">
<code-scanner
visible
:status-text="scanStatus"
active-text="正在识别客户编码,请将条码或二维码移入取景框。"
@decode="handleDecodedText"
@status-change="handleScanStatusChange"
/>
</div>
<t-cell-group class="summary" theme="card">
<t-cell
v-if="dateFilterType !== 'all'"
title="开始时间"
:note="dateRange[0] || '-'"
arrow
@click="openStartTime"
/>
<t-cell
v-if="dateFilterType !== 'all'"
title="结束时间"
:note="dateRange[1] || '-'"
arrow
@click="openEndTime"
/>
<t-cell title="记录数" :note="`共 ${total} 条`" />
<t-cell title="消费金额合计" :note="`¥${formatPackageAmount(amountTotal)}`" />
</t-cell-group>
<t-cell-group v-if="recordList.length" class="empty-cell-title-margin" theme="card">
<t-cell
class="item"
v-for="item in recordList"
:key="item.id"
:arrow="canOpenSource(item)"
v-entrance-transition="{ step: 30 }"
@click="openSource(item)"
> >
<template #leftIcon> <template #suffix-icon>
<t-image <div class="actions">
v-if="getCustomerPhotoURL(item.customer, 64)" <t-button
:src="getCustomerPhotoURL(item.customer, 64)" v-if="customerId"
:alt="getCustomerText(item)" shape="circle"
fit="cover" theme="danger"
class="avatar" variant="text"
/> size="extra-small"
<div v-else class="avatar fallback" v-text="getCustomerText(item).slice(0, 1)" /> aria-label="清除客户选择"
</template> @click.stop="clearCustomer"
<template #title> >
<div class="title"> <t-icon name="close" size="1rem" />
<span class="customer" v-text="getCustomerText(item)" /> </t-button>
<t-tag <t-button
class="value" size="extra-small"
size="small" theme="primary"
:theme="item.sourceType === 'LEGACY_EVENT' ? 'default' : 'primary'" variant="outline"
variant="light" :content="scannerVisible ? '关闭扫码' : '扫码'"
:content="getRecordTitle(item)" @click.stop="toggleScanner"
/> />
</div> </div>
</template> </template>
<template #description> </t-input>
<div class="description"> <t-dropdown-menu class="menus">
<t-tag <t-dropdown-item
size="small" v-model="dateFilterType"
:theme="item.status === 'ACTIVE' ? 'success' : 'danger'" :label="dateFilterLabel"
variant="light-outline" :options="dateOptions"
:content="getStatusText(item.status)" @change="selectDateFilter"
/>
<t-dropdown-item
v-model="sourceType"
label="消费来源"
:options="sourceTypeOptions"
@change="reloadRecords"
/>
<t-dropdown-item
v-model="status"
label="消费状态"
:options="statusOptions"
@change="reloadRecords"
/>
</t-dropdown-menu>
</div>
<div class="list-wrap">
<div v-if="scannerVisible" class="scanner-wrap">
<code-scanner
visible
:status-text="scanStatus"
active-text="正在识别客户编码,请将条码或二维码移入取景框。"
@decode="handleDecodedText"
@status-change="handleScanStatusChange"
/>
</div>
<t-cell-group class="summary" theme="card">
<t-cell
v-if="dateFilterType !== 'all'"
title="开始时间"
:note="dateRange[0] || '-'"
arrow
@click="openStartTime"
/>
<t-cell
v-if="dateFilterType !== 'all'"
title="结束时间"
:note="dateRange[1] || '-'"
arrow
@click="openEndTime"
/>
<t-cell title="记录数" :note="`共 ${total} 条`" />
<t-cell title="消费金额合计" :note="`¥${formatPackageAmount(amountTotal)}`" />
</t-cell-group>
<t-cell-group v-if="recordList.length" class="empty-cell-title-margin" theme="card">
<t-cell
class="item"
v-for="item in recordList"
:key="item.id"
:arrow="canOpenSource(item)"
v-entrance-transition="{ step: 30 }"
@click="openSource(item)"
>
<template #leftIcon>
<t-image
v-if="getCustomerPhotoURL(item.customer, 64)"
:src="getCustomerPhotoURL(item.customer, 64)"
:alt="getCustomerText(item)"
fit="cover"
class="avatar"
/> />
<time-label class="time" :timestamp="item.effectiveAt" underline /> <div v-else class="avatar fallback" v-text="getCustomerText(item).slice(0, 1)" />
</div> </template>
</template> <template #title>
<template #note> <div class="title">
<strong class="red" v-text="`¥${formatPackageAmount(item.amount)}`" /> <span class="customer" v-text="getCustomerText(item)" />
</template> <t-tag
</t-cell> class="value"
</t-cell-group> size="small"
<center-tips v-else :content="isLoading ? '正在加载消费记录' : '暂无消费记录'" /> :theme="item.sourceType === 'LEGACY_EVENT' ? 'default' : 'primary'"
<center-tips v-if="recordList.length" :content="loadStateText" /> variant="light"
</div> :content="getRecordTitle(item)"
</t-pull-down-refresh> />
<customer-selector </div>
v-model="customerId" </template>
v-model:visible="customerSelectorVisible" <template #description>
:enable-scan="false" <div class="description">
@change="handleCustomerChange" <t-tag
size="small"
:theme="item.status === 'ACTIVE' ? 'success' : 'danger'"
variant="light-outline"
:content="getStatusText(item.status)"
/>
<time-label class="time" :timestamp="item.effectiveAt" underline />
</div>
</template>
<template #note>
<strong class="red" v-text="`¥${formatPackageAmount(item.amount)}`" />
</template>
</t-cell>
</t-cell-group>
<center-tips v-else :content="isLoading ? '正在加载消费记录' : '暂无消费记录'" />
<center-tips v-if="recordList.length" :content="loadStateText" />
</div>
</t-pull-down-refresh>
</template>
<!--
右栏:消费记录点开的是交易订单详情(另一个模块的整页),
直接占用详情槽,消费记录列表保持原位。
-->
<template #detail>
<sales-order-detail
ref="salesOrderDetailRef"
:key="`order-${selectedId}`"
:order-id="selectedId"
/>
</template>
<!--
第三层:订单详情跳到从属页面时,订单退到主栏、右栏换成这一层,
与交易订单列表里「订单详情 + 履约单」的走法一致。
-->
<template #sub>
<sales-order-sub-view
:key="subView"
:view="subView"
:order-id="selectedId"
@refresh="refreshRecycleDetail"
@saved="handleSubSaved"
/>
</template>
</master-detail-page>
<customer-selector
v-model="customerId"
v-model:visible="customerSelectorVisible"
:enable-scan="false"
@change="handleCustomerChange"
/>
<t-popup v-model="startVisible" placement="bottom">
<t-date-time-picker
v-if="startVisible"
v-model="startDraft"
format="YYYY-MM-DD HH:mm"
:mode="['date', 'minute']"
title="开始时间"
:default-value="dateRange[0]"
@cancel="cancelStartTime"
@confirm="confirmStartTime"
/> />
<t-popup v-model="startVisible" placement="bottom"> </t-popup>
<t-date-time-picker <t-popup v-model="endVisible" placement="bottom">
v-if="startVisible" <t-date-time-picker
v-model="startDraft" v-if="endVisible"
format="YYYY-MM-DD HH:mm" v-model="endDraft"
:mode="['date', 'minute']" format="YYYY-MM-DD HH:mm"
title="开始时间" :mode="['date', 'minute']"
:default-value="dateRange[0]" title="结束时间"
@cancel="cancelStartTime" :default-value="dateRange[1]"
@confirm="confirmStartTime" @cancel="cancelEndTime"
/> @confirm="confirmEndTime"
</t-popup> />
<t-popup v-model="endVisible" placement="bottom"> </t-popup>
<t-date-time-picker
v-if="endVisible"
v-model="endDraft"
format="YYYY-MM-DD HH:mm"
:mode="['date', 'minute']"
title="结束时间"
:default-value="dateRange[1]"
@cancel="cancelEndTime"
@confirm="confirmEndTime"
/>
</t-popup>
</main>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile";
import type { DropdownValue } from "tdesign-mobile-vue"; import type { DropdownValue } from "tdesign-mobile-vue";
import { TimeLabel, Time } from "timi-web"; import { TimeLabel, Time } from "timi-web";
import { useUserStore } from "timi-web-api"; import { useUserStore } from "timi-web-api";
@@ -189,6 +223,9 @@ import ConsumptionRecordAPI from "@/api/ConsumptionRecordAPI";
import CustomerAPI from "@/api/CustomerAPI"; import CustomerAPI from "@/api/CustomerAPI";
import CodeScanner from "@/components/CodeScanner.vue"; import CodeScanner from "@/components/CodeScanner.vue";
import CustomerSelector from "@/components/CustomerSelector.vue"; import CustomerSelector from "@/components/CustomerSelector.vue";
import SalesOrderDetail from "@/pages/salesOrder/SalesOrderDetail.vue";
import SalesOrderSubView from "@/pages/salesOrder/component/SalesOrderSubView.vue";
import { getOrderPaneRoute } from "@/pages/salesOrder/component/orderPane";
import type { import type {
ConsumptionRecord, ConsumptionRecord,
ConsumptionRecordPage, ConsumptionRecordPage,
@@ -210,6 +247,63 @@ defineOptions({ name: "ConsumptionRecordList" });
const pageSize = 20; const pageSize = 20;
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
// 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里;右栏渲染订单详情,它自己的子页进第三层
const { selectedId, subView, paneDirection, isWide, openDetail } = useMasterDetailPane({
path: "/product/consumption-records",
detail: detailRoute
});
const salesOrderDetailRef = ref<InstanceType<typeof SalesOrderDetail>>();
/** 转屏变窄时右栏不再渲染,按右栏当前那一层落到整页路由。 */
function detailRoute(id: string): string {
const view = subView.value;
return view ? getOrderPaneRoute({ orderId: id, view }) : `/product/sales-orders/${id}`;
}
/** 子页标识形如 `recycle-rule:698f`,冒号前是类型,后面是参数。 */
const subArg = computed(() => subView.value?.split(":")[1] || "");
// 子页之间是同层替换,反向同步给的是 none,回退到上一层时补成 back
watch(subView, (next, previous) => {
if (previous?.startsWith("fulfillment-detail:") && next === "fulfillments") {
paneDirection.value = "back";
}
if (previous?.startsWith("recycle-payment-detail:") && next?.startsWith("recycle-payments:")) {
paneDirection.value = "back";
}
if (previous?.startsWith("recycle-payment-revoke:") && next?.startsWith("recycle-payment-detail:")) {
paneDirection.value = "back";
}
});
async function refreshRecycleDetail(): Promise<void> {
await salesOrderDetailRef.value?.refreshAfterRecyclePayment();
}
async function handleRecyclePaymentSaved(paymentId?: string): Promise<void> {
const exchangeId = subArg.value;
if (paymentId && exchangeId) {
paneDirection.value = "forward";
subView.value = `recycle-payment-detail:${exchangeId}:${paymentId}`;
}
await refreshRecycleDetail();
}
/** 子页保存完成:新建了履约单或回收支付时,接着打开它刚建出来的详情。 */
async function handleSubSaved(kind: string, id: string): Promise<void> {
if (kind === "fulfillment-create") {
if (id) {
paneDirection.value = "forward";
subView.value = `fulfillment-detail:${id}`;
}
await salesOrderDetailRef.value?.refreshOrder();
return;
}
if (kind === "recycle-register") {
await handleRecyclePaymentSaved(id || undefined);
}
}
const userStore = useUserStore(); const userStore = useUserStore();
const sourceType = ref<ConsumptionRecordSourceType | "ALL">("ALL"); const sourceType = ref<ConsumptionRecordSourceType | "ALL">("ALL");
const status = ref<ConsumptionRecordStatus | "ALL">("ALL"); const status = ref<ConsumptionRecordStatus | "ALL">("ALL");
@@ -444,7 +538,7 @@ async function openSource(record: ConsumptionRecord): Promise<void> {
return; return;
} }
if (record.sourceType === "SALES_ORDER" && record.salesOrderId) { if (record.sourceType === "SALES_ORDER" && record.salesOrderId) {
await router.push({ name: "SalesOrderDetail", params: { id: record.salesOrderId } }); openDetail(record.salesOrderId);
return; return;
} }
if (record.sourceType === "LEGACY_EVENT" && record.sourceId) { if (record.sourceType === "LEGACY_EVENT" && record.sourceId) {
@@ -461,9 +555,28 @@ onMounted(async () => {
<style scoped lang="less"> <style scoped lang="less">
.consumption-record-list { .consumption-record-list {
min-height: 100vh;
padding: var(--tui-nav-height) 0 1rem; padding: var(--tui-nav-height) 0 1rem;
// master 槽里没有 .tui-page-content,库与全局的列表规则不适用,这里补齐
.pull-refresh {
padding-top: 1rem;
:deep(.t-pull-down-refresh__track) {
gap: 1rem;
height: auto;
display: flex;
min-height: 100%;
flex-direction: column;
}
}
.filters {
top: -1rem;
z-index: 10;
margin: -1rem 0 0;
padding: 1rem 1rem 0;
position: sticky;
}
.list-wrap { .list-wrap {
gap: 1rem; gap: 1rem;
@@ -130,6 +130,7 @@ import { TimeLabel, Text } from "timi-web";
import { useUserStore } from "timi-web-api"; import { useUserStore } from "timi-web-api";
import SalesOrderAPI from "@/api/SalesOrderAPI"; import SalesOrderAPI from "@/api/SalesOrderAPI";
import AttachmentSelector from "@/components/attachmentSelector/AttachmentSelector.vue"; import AttachmentSelector from "@/components/attachmentSelector/AttachmentSelector.vue";
import { buildOrderPaneView } from "@/pages/salesOrder/component/orderPane";
import type { PhotoItem } from "@/types/Photo"; import type { PhotoItem } from "@/types/Photo";
import { getAttachmentReadURL } from "@/utils/attachment"; import { getAttachmentReadURL } from "@/utils/attachment";
import { getErrorMessage } from "@/utils/error"; import { getErrorMessage } from "@/utils/error";
@@ -231,6 +232,10 @@ async function toSalesOrder(): Promise<void> {
if (!record.value?.bizId || !canReadSalesOrder.value) { if (!record.value?.bizId || !canReadSalesOrder.value) {
return; return;
} }
// 分栏时订单页叠在右栏里,资金流水列表保持可见
if (pane?.openSub(buildOrderPaneView(record.value.bizId))) {
return;
}
await router.push({ await router.push({
path: `/product/sales-orders/${record.value.bizId}`, path: `/product/sales-orders/${record.value.bizId}`,
query: { transitionDepth: String(getCurrentRouteDepth() + 1) } query: { transitionDepth: String(getCurrentRouteDepth() + 1) }
+74 -3
View File
@@ -13,6 +13,7 @@
:split="isWide" :split="isWide"
:selected="!!selectedId" :selected="!!selectedId"
:direction="paneDirection" :direction="paneDirection"
:sub="!!orderPane?.view"
> >
<template #master> <template #master>
<t-pull-down-refresh <t-pull-down-refresh
@@ -102,12 +103,35 @@
<center-tips :content="loadStateText" /> <center-tips :content="loadStateText" />
</t-pull-down-refresh> </t-pull-down-refresh>
</template> </template>
<!--
右栏两层:资金记录详情,或从它点进的订单详情。订单是另一个模块的整页,
因此直接顶掉详情槽的内容(而不是叠第三层),资金流水列表保持原位。
-->
<template #detail> <template #detail>
<sales-order-detail
v-if="orderPane"
:key="`order-${orderPane.orderId}`"
:order-id="orderPane.orderId"
/>
<fund-record-detail <fund-record-detail
v-else
:key="`detail-${selectedId}`" :key="`detail-${selectedId}`"
:record-id="selectedId" :record-id="selectedId"
/> />
</template> </template>
<!--
只有订单自己的子页才算第三层:订单详情退到主栏,子页占右栏,
与交易订单列表里「订单详情 + 履约单」的走法一致。
-->
<template #sub>
<sales-order-sub-view
v-if="orderPane?.view"
:key="`sub-${orderPane.view}`"
:view="orderPane.view"
:order-id="orderPane.orderId"
@saved="handleOrderSubSaved"
/>
</template>
</master-detail-page> </master-detail-page>
<customer-selector <customer-selector
v-model="customerId" v-model="customerId"
@@ -142,10 +166,13 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile"; import { MasterDetailPage, providePane, useMasterDetailPane } from "timi-tdesign-mobile";
import { type DropdownValue } from "tdesign-mobile-vue"; import { type DropdownValue } from "tdesign-mobile-vue";
import FundRecordDetail from "@/pages/salesOrder/FundRecordDetail.vue"; import FundRecordDetail from "@/pages/salesOrder/FundRecordDetail.vue";
import SalesOrderDetail from "@/pages/salesOrder/SalesOrderDetail.vue";
import FundRecordListCell from "@/pages/salesOrder/component/FundRecordListCell.vue"; import FundRecordListCell from "@/pages/salesOrder/component/FundRecordListCell.vue";
import SalesOrderSubView from "@/pages/salesOrder/component/SalesOrderSubView.vue";
import { buildOrderPaneView, getOrderPaneRoute, parseOrderPaneView } from "@/pages/salesOrder/component/orderPane";
import { Time } from "timi-web"; import { Time } from "timi-web";
import { useUserStore } from "timi-web-api"; import { useUserStore } from "timi-web-api";
import CustomerAPI from "@/api/CustomerAPI"; import CustomerAPI from "@/api/CustomerAPI";
@@ -166,10 +193,54 @@ const route = useRoute();
const router = useRouter(); const router = useRouter();
// 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里;资金流水没有内联编辑视图 // 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里;资金流水没有内联编辑视图
const { selectedId, paneDirection, isWide, openDetail } = useMasterDetailPane({ const { selectedId, subView, paneDirection, isWide, openDetail, openSub, close } = useMasterDetailPane({
path: "/product/fund-records", path: "/product/fund-records",
detail: id => `/product/fund-records/${id}` detail: detailRoute
}); });
/** 右栏叠加的订单页;为空说明右栏还是资金记录详情。 */
const orderPane = computed(() => parseOrderPaneView(subView.value || ""));
// 右栏里既有资金记录详情,也有订单页:给整棵子树换一套"子页标识带订单 id"的上下文,
// 订单详情里的 openSub("payment") 才不会丢掉它叠在哪一单上
providePane({
close: saved => close(saved),
openSub: view => openSub(withOrderPrefix(view))
});
function withOrderPrefix(view: string): string {
const order = orderPane.value;
return order && !parseOrderPaneView(view) ? buildOrderPaneView(order.orderId, view) : view;
}
// 订单子页退回订单详情是同级替换(层级没变),反向同步给的是 none,这里补成 back
watch(orderPane, (next, previous) => {
if (previous?.view && !next?.view) {
paneDirection.value = "back";
}
});
/** 订单子页保存完成:新建了履约单或回收支付,接着打开它刚建出来的详情。 */
async function handleOrderSubSaved(kind: string, id: string): Promise<void> {
const order = orderPane.value;
if (!order || !id) {
return;
}
if (kind === "fulfillment-create") {
openSub(buildOrderPaneView(order.orderId, `fulfillment-detail:${id}`));
return;
}
if (kind === "recycle-register") {
openSub(buildOrderPaneView(order.orderId, `recycle-payment-detail:${order.view.split(":")[1] || ""}:${id}`));
}
}
/** 转屏变窄时右栏不再渲染,按右栏当前那一层落到整页路由。 */
function detailRoute(id: string): string {
const order = parseOrderPaneView(subView.value || "");
return order ? getOrderPaneRoute(order) : `/product/fund-records/${id}`;
}
const userStore = useUserStore(); const userStore = useUserStore();
const recordList = ref<FundRecord[]>([]); const recordList = ref<FundRecord[]>([]);
const operationType = ref(route.query.operationType === "RECEIVE" ? "RECEIVE" : "ALL"); const operationType = ref(route.query.operationType === "RECEIVE" ? "RECEIVE" : "ALL");
+249 -210
View File
@@ -1,216 +1,223 @@
<template> <template>
<t-navbar <div class="tui-page-layout tui-navbar" :class="{ 'in-pane': !!pane, 'wide-page': isWide && !pane }">
fixed <t-navbar
:z-index="20" fixed
title="直接产品下单" :z-index="20"
left-arrow title="直接产品下单"
@left-click="$router.back()" left-arrow
/> @left-click="exit"
<div v-can="permissionCodes.salesOrder.create" class="sales-order-create"> />
<t-form class="form card" label-width="5.25rem" v-entrance-transition> <div v-can="permissionCodes.salesOrder.create" class="tui-page-content scroll sales-order-create">
<t-form-item label="客户" required-mark> <t-form class="form card" label-width="5.25rem" v-entrance-transition>
<t-input <t-form-item label="客户" required-mark>
:model-value="customerDisplayText" <t-input
class="customer" :model-value="customerDisplayText"
readonly class="customer"
borderless readonly
placeholder="选择或扫码客户" borderless
@click="customerSelectorVisible = true" placeholder="选择或扫码客户"
> @click="customerSelectorVisible = true"
<template #suffix-icon>
<div class="actions">
<t-button
theme="primary"
variant="outline"
size="extra-small"
@click.stop="customerSelectorVisible = true"
>选择</t-button>
<t-button theme="primary" size="extra-small" @click.stop="toggleScanner">
<span v-text="scannerVisible ? '关闭扫码' : '扫码'" />
</t-button>
</div>
</template>
</t-input>
</t-form-item>
<div v-if="scannerVisible" class="code-scanner-wrapper">
<code-scanner
visible
:status-text="scanStatus"
active-text="正在识别客户编码,请将条码或二维码移入取景框。"
@decode="handleDecodedText"
@status-change="handleScanStatusChange"
/>
</div>
<customer-profile-card
v-if="customer"
class="customer-profile"
:customer="customer"
v-entrance-transition
/>
<t-form-item label-width="0">
<div class="product-part">
<div class="header">
<strong>购买产品</strong>
<span v-text="`${items.length} 项`" />
</div>
<div class="tips">同一 SKU 单位不能重复</div>
<div class="items">
<div v-for="(item, index) in items" :key="item.clientKey" class="item">
<div class="header">
<span class="no" v-text="String(index + 1).padStart(2, '0')" />
<strong v-text="getItemTitle(item)" />
<t-button theme="danger" variant="text" size="extra-small" @click="removeItem(index)">删除</t-button>
</div>
<product-select-form-item
:model-value="item.skuId ? { skuId: item.skuId, skuUnitId: item.skuUnitId || '' } : undefined"
:selected-product="getProduct(item)"
label="产品"
placeholder="请选择产品"
required-mark
@update:model-value="applyProduct(index, $event)"
/>
<t-form-item v-if="canPriceOverride" label="成交单价">
<t-input
v-model.trim="item.unitPriceText"
type="number"
align="right"
borderless
:placeholder="getItemUnitPricePlaceholder(item)"
/>
<template #help>
<span
v-if="item.skuId && item.unitPriceText"
class="price-tips gray"
v-text="getItemUnitPricePlaceholder(item)"
/>
</template>
</t-form-item>
<t-form-item label="数量" content-align="right">
<t-stepper
v-model="item.quantity"
size="large"
:max="maxQuantity"
:min="getSku(item)?.allowDecimalQuantity ? .001 : 1"
:step="getQuantityStep(item)"
:integer="!getSku(item)?.allowDecimalQuantity"
theme="outline"
/>
</t-form-item>
<t-form-item label="产品备注">
<t-input
:model-value="item.remark ?? ''"
@update:model-value="value => item.remark = String(value).trim()"
borderless placeholder="选填"
/>
</t-form-item>
<div class="price">
<animated-amount
class="red text-bold"
prefix="¥"
empty-text="0.00"
:value="calculateItemAmount(item)"
/>
</div>
</div>
</div>
<t-button
class="add"
type="button"
theme="light"
variant="dashed"
block
@click="addItem"
> >
<template #icon> <template #suffix-icon>
<t-icon name="add" size="1.125rem" /> <div class="actions">
<t-button
theme="primary"
variant="outline"
size="extra-small"
@click.stop="customerSelectorVisible = true"
>选择</t-button>
<t-button theme="primary" size="extra-small" @click.stop="toggleScanner">
<span v-text="scannerVisible ? '关闭扫码' : '扫码'" />
</t-button>
</div>
</template> </template>
<span>继续添加产品</span> </t-input>
</t-button> </t-form-item>
</div> <div v-if="scannerVisible" class="code-scanner-wrapper">
</t-form-item> <code-scanner
<t-form-item label="下单时间" content-align="right"> visible
<date-time-now-picker v-model="purchasedAtText" title="下单时间" /> :status-text="scanStatus"
</t-form-item> active-text="正在识别客户编码,请将条码或二维码移入取景框。"
<t-form-item @decode="handleDecodedText"
v-if="canReceiveImmediately" @status-change="handleScanStatusChange"
class="payment-item"
:class="{ disabled: receiveFullPayment }"
:label="receiveFullPayment ? '收款和核销金额' : '已部分收款和核销'"
label-width="9rem"
content-align="right"
>
<t-input
:model-value="receiveFullPayment ? formatProductAmount(totalAmount || 0) : paymentAmountText"
type="number"
align="right"
borderless
:disabled="receiveFullPayment"
:placeholder="paymentAmountPlaceholder"
@update:model-value="paymentAmountText = String($event)"
/>
</t-form-item>
<t-form-item v-if="canReceiveImmediately" label="已全额收款和核销" content-align="right">
<t-switch
v-model="receiveFullPayment"
size="small"
:disabled="!canReceiveImmediately"
/>
</t-form-item>
<t-form-item v-if="canFulfillImmediately" label="已全部产品履约和核销" content-align="right">
<t-switch
v-model="fulfillAll"
size="small"
:disabled="!canFulfillImmediately || isStockChecking"
/>
</t-form-item>
<t-form-item v-if="canFulfillImmediately" label-width="0">
<div class="stock-tips">
<div class="tips red">全部履约会同步启用全额收款;请先准备充足的库存,任意一步失败都会下单失败。</div>
<product-stock-preview v-if="stockPreviewList.length" :items="stockPreviewList" />
</div>
</t-form-item>
<t-form-item v-if="(paymentVerified && paymentAmount) || (receiveFullPayment && totalAmount)" label-width="0">
<attachment-selector
v-model:items="paymentPhotoItems"
:upload="uploadPhotoList"
title="收款凭证照片(必要)"
/>
</t-form-item>
<t-form-item v-if="fulfillAll" label-width="0">
<attachment-selector
v-model:items="fulfillmentPhotoItems"
:upload="uploadPhotoList"
title="履约凭证照片(必要)"
/>
</t-form-item>
<t-form-item label="订单备注">
<t-textarea v-model="remark" class="textarea" borderless autosize maxlength="500" placeholder="记录本单需要注意的内容" />
</t-form-item>
<div class="photo-part">
<attachment-selector v-model:items="photoItems" :upload="uploadPhotoList" title="订单照片(选填)" />
</div>
</t-form>
<div class="submit-wrap glass-white bg-white">
<div class="total">
<span class="label">订单总价</span>
<div class="price">
<animated-amount
class="red text-bold"
prefix="¥"
empty-text="0.00"
:value="totalAmount"
/> />
</div> </div>
<customer-profile-card
v-if="customer"
class="customer-profile"
:customer="customer"
v-entrance-transition
/>
<t-form-item label-width="0">
<div class="product-part">
<div class="header">
<strong>购买产品</strong>
<span v-text="`${items.length} 项`" />
</div>
<div class="tips">同一 SKU 单位不能重复</div>
<div class="items">
<div
class="item"
v-for="(item, index) in items"
:key="item.clientKey"
v-entrance-transition
>
<div class="header">
<span class="no" v-text="String(index + 1).padStart(2, '0')" />
<strong v-text="getItemTitle(item)" />
<t-button theme="danger" variant="text" size="extra-small" @click="removeItem(index)">删除</t-button>
</div>
<product-select-form-item
:model-value="item.skuId ? { skuId: item.skuId, skuUnitId: item.skuUnitId || '' } : undefined"
:selected-product="getProduct(item)"
label="产品"
placeholder="请选择产品"
required-mark
@update:model-value="applyProduct(index, $event)"
/>
<t-form-item v-if="canPriceOverride" label="成交单价">
<t-input
v-model.trim="item.unitPriceText"
type="number"
align="right"
borderless
:placeholder="getItemUnitPricePlaceholder(item)"
/>
<template #help>
<span
v-if="item.skuId && item.unitPriceText"
class="price-tips gray"
v-text="getItemUnitPricePlaceholder(item)"
/>
</template>
</t-form-item>
<t-form-item label="数量" content-align="right">
<t-stepper
v-model="item.quantity"
size="large"
:max="maxQuantity"
:min="getSku(item)?.allowDecimalQuantity ? .001 : 1"
:step="getQuantityStep(item)"
:integer="!getSku(item)?.allowDecimalQuantity"
theme="outline"
/>
</t-form-item>
<t-form-item label="产品备注">
<t-input
:model-value="item.remark ?? ''"
@update:model-value="value => item.remark = String(value).trim()"
borderless placeholder="选填"
/>
</t-form-item>
<div class="price">
<animated-amount
class="red text-bold"
prefix="¥"
empty-text="0.00"
:value="calculateItemAmount(item)"
/>
</div>
</div>
</div>
<t-button
class="add"
type="button"
theme="light"
variant="dashed"
block
@click="addItem"
>
<template #icon>
<t-icon name="add" size="1.125rem" />
</template>
<span>继续添加产品</span>
</t-button>
</div>
</t-form-item>
<t-form-item label="下单时间" content-align="right">
<date-time-now-picker v-model="purchasedAtText" title="下单时间" />
</t-form-item>
<t-form-item
v-if="canReceiveImmediately"
class="payment-item"
:class="{ disabled: receiveFullPayment }"
:label="receiveFullPayment ? '收款和核销金额' : '已部分收款和核销'"
label-width="9rem"
content-align="right"
>
<t-input
:model-value="receiveFullPayment ? formatProductAmount(totalAmount || 0) : paymentAmountText"
type="number"
align="right"
borderless
:disabled="receiveFullPayment"
:placeholder="paymentAmountPlaceholder"
@update:model-value="paymentAmountText = String($event)"
/>
</t-form-item>
<t-form-item v-if="canReceiveImmediately" label="已全额收款和核销" content-align="right">
<t-switch
v-model="receiveFullPayment"
size="small"
:disabled="!canReceiveImmediately"
/>
</t-form-item>
<t-form-item v-if="canFulfillImmediately" label="已全部产品履约和核销" content-align="right">
<t-switch
v-model="fulfillAll"
size="small"
:disabled="!canFulfillImmediately || isStockChecking"
/>
</t-form-item>
<t-form-item v-if="canFulfillImmediately" label-width="0">
<div class="stock-tips">
<div class="tips red">全部履约会同步启用全额收款;请先准备充足的库存,任意一步失败都会下单失败。</div>
<product-stock-preview v-if="stockPreviewList.length" :items="stockPreviewList" />
</div>
</t-form-item>
<t-form-item v-if="(paymentVerified && paymentAmount) || (receiveFullPayment && totalAmount)" label-width="0">
<attachment-selector
v-model:items="paymentPhotoItems"
:upload="uploadPhotoList"
title="收款凭证照片(必要)"
/>
</t-form-item>
<t-form-item v-if="fulfillAll" label-width="0">
<attachment-selector
v-model:items="fulfillmentPhotoItems"
:upload="uploadPhotoList"
title="履约凭证照片(必要)"
/>
</t-form-item>
<t-form-item label="订单备注">
<t-textarea v-model="remark" class="textarea" borderless autosize maxlength="500" placeholder="记录本单需要注意的内容" />
</t-form-item>
<div class="photo-part">
<attachment-selector v-model:items="photoItems" :upload="uploadPhotoList" title="订单照片(选填)" />
</div>
</t-form>
<div class="submit-wrap tui-fixed-inset glass-white bg-white">
<div class="total">
<span class="label">订单总价</span>
<div class="price">
<animated-amount
class="red text-bold"
prefix="¥"
empty-text="0.00"
:value="totalAmount"
/>
</div>
</div>
<t-button
class="submit"
theme="danger"
:loading="isSaving"
:disabled="isSaving"
@click="save"
>提交订单</t-button>
</div> </div>
<t-button <customer-selector v-model="customerIdList" v-model:visible="customerSelectorVisible" selection-mode="single" :enable-scan="false" @change="loadCustomer" />
class="submit"
theme="danger"
:loading="isSaving"
:disabled="isSaving"
@click="save"
>提交订单</t-button>
</div> </div>
<customer-selector v-model="customerIdList" v-model:visible="customerSelectorVisible" selection-mode="single" :enable-scan="false" @change="loadCustomer" />
</div> </div>
</template> </template>
@@ -218,6 +225,7 @@
import DateTimeNowPicker from "@/components/DateTimeNowPicker.vue"; import DateTimeNowPicker from "@/components/DateTimeNowPicker.vue";
import { type Attachment, useUserStore } from "timi-web-api"; import { type Attachment, useUserStore } from "timi-web-api";
import { AnimatedAmount } from "timi-web"; import { AnimatedAmount } from "timi-web";
import { useLayout, usePane } from "timi-tdesign-mobile";
import { DialogPlugin } from "tdesign-mobile-vue"; import { DialogPlugin } from "tdesign-mobile-vue";
import CustomerAPI from "@/api/CustomerAPI"; import CustomerAPI from "@/api/CustomerAPI";
import ProductAPI from "@/api/ProductAPI"; import ProductAPI from "@/api/ProductAPI";
@@ -246,7 +254,17 @@ import { useSettingStore } from "@/store/settingStore";
type FormItem = Partial<DirectProductOrderItemRequest> & { clientKey: string; productName: string; unitPriceText: string }; type FormItem = Partial<DirectProductOrderItemRequest> & { clientKey: string; productName: string; unitPriceText: string };
defineOptions({ name: "SalesOrderCreate" }); defineOptions({ name: "SalesOrderCreate" });
const emit = defineEmits<{ created: [orderId: string] }>();
const router = useRouter(); const router = useRouter();
const pane = usePane();
const { isWide } = useLayout();
function exit(): void {
if (pane) {
pane.close();
return;
}
void router.back();
}
const settingStore = useSettingStore(); const settingStore = useSettingStore();
const userStore = useUserStore(); const userStore = useUserStore();
const canPriceOverride = computed(() => userStore.hasPermissions(permissionCodes.salesOrder.priceOverride)); const canPriceOverride = computed(() => userStore.hasPermissions(permissionCodes.salesOrder.priceOverride));
@@ -587,6 +605,14 @@ async function submitOrder(): Promise<void> {
emitListDataChanged(listDataEventKeys.salesOrderChanged, result.id); emitListDataChanged(listDataEventKeys.salesOrderChanged, result.id);
emitListDataChanged(listDataEventKeys.productStockChanged); emitListDataChanged(listDataEventKeys.productStockChanged);
Message.success(fulfillAll.value ? "订单、收款及履约已完成" : paymentVerified.value ? "订单及已核销收款已完成" : receiveFullPayment.value ? "订单及全额收款已完成" : "交易订单已创建"); Message.success(fulfillAll.value ? "订单、收款及履约已完成" : paymentVerified.value ? "订单及已核销收款已完成" : receiveFullPayment.value ? "订单及全额收款已完成" : "交易订单已创建");
if (pane) {
if (result.id) {
emit("created", result.id);
} else {
pane.close(true);
}
return;
}
await router.replace(`/product/sales-orders/${result.id}`); await router.replace(`/product/sales-orders/${result.id}`);
} catch (error) { } catch (error) {
const message = getErrorMessage(error, "交易订单创建失败,重试会复用同一请求号"); const message = getErrorMessage(error, "交易订单创建失败,重试会复用同一请求号");
@@ -600,7 +626,7 @@ onMounted(() => {
</script> </script>
<style scoped lang="less"> <style scoped lang="less">
.sales-order-create { .tui-page-layout .sales-order-create {
gap: 1rem; gap: 1rem;
display: flex; display: flex;
padding: calc(var(--tui-nav-height) + 1rem) 0 calc(6.5rem + var(--tui-safe-bottom, 0px)); padding: calc(var(--tui-nav-height) + 1rem) 0 calc(6.5rem + var(--tui-safe-bottom, 0px));
@@ -643,6 +669,7 @@ onMounted(() => {
} }
.product-part { .product-part {
width: 100%;
> .header { > .header {
display: flex; display: flex;
@@ -749,9 +776,9 @@ onMounted(() => {
} }
.submit-wrap { .submit-wrap {
--tui-fixed-gap: 1.5rem;
gap: 1rem; gap: 1rem;
left: 1.5rem;
right: 1.5rem;
border: 1px solid rgba(0, 0, 0, .05); border: 1px solid rgba(0, 0, 0, .05);
bottom: calc(var(--tui-safe-bottom, 0px) + 1rem); bottom: calc(var(--tui-safe-bottom, 0px) + 1rem);
z-index: 12; z-index: 12;
@@ -786,8 +813,20 @@ onMounted(() => {
} }
} }
.tui-page-layout.in-pane .sales-order-create .submit-wrap {
left: 1.5rem !important;
position: absolute;
}
.tui-page-layout.wide-page .sales-order-create .product-part {
.items {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
:global(html.theme-dark) { :global(html.theme-dark) {
.sales-order-create { .tui-page-layout .sales-order-create {
.form { .form {
background: rgba(15, 23, 42, .88); background: rgba(15, 23, 42, .88);
box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32); box-shadow: 0 .75rem 2rem rgba(2, 6, 23, .32);
+12 -3
View File
@@ -546,7 +546,14 @@ async function toRecycleRegister(id: string): Promise<void> {
} }
async function toFundRecords(): Promise<void> { async function toFundRecords(): Promise<void> {
if (order.value?.id) await router.push({ if (!order.value?.id) {
return;
}
// 分栏时本单流水叠在右栏里,订单详情留在旁边,不跳去整页的资金流水列表
if (openSub("fund-records")) {
return;
}
await router.push({
path: "/product/fund-records", path: "/product/fund-records",
query: { query: {
salesOrderId: order.value.id, salesOrderId: order.value.id,
@@ -594,11 +601,13 @@ async function toPayment(): Promise<void> {
} }
async function toRefund(): Promise<void> { async function toRefund(): Promise<void> {
if (order.value?.id) await router.push(`/product/sales-orders/${order.value.id}/refund`); if (!order.value?.id || openSub("refund")) return;
await router.push(`/product/sales-orders/${order.value.id}/refund`);
} }
async function toNoRefund(): Promise<void> { async function toNoRefund(): Promise<void> {
if (order.value?.id) await router.push(`/product/sales-orders/${order.value.id}/no-refund`); if (!order.value?.id || openSub("no-refund")) return;
await router.push(`/product/sales-orders/${order.value.id}/no-refund`);
} }
async function toCancel(): Promise<void> { async function toCancel(): Promise<void> {
+30 -36
View File
@@ -103,7 +103,9 @@
</t-pull-down-refresh> </t-pull-down-refresh>
</template> </template>
<template #detail> <template #detail>
<sales-order-cancel v-if="directAction.kind === 'cancel'" :key="selectedId" :order-id="directAction.id" embedded /> <sales-order-create v-if="selectedId === createPaneId" @created="handleRecycleCreated" />
<package-purchase v-else-if="selectedId === packageCreatePaneId" create-order @created="handleRecycleCreated" />
<sales-order-cancel v-else-if="directAction.kind === 'cancel'" :key="selectedId" :order-id="directAction.id" embedded />
<sales-order-payment v-else-if="directAction.kind === 'payment'" :key="selectedId" :order-id="directAction.id" embedded /> <sales-order-payment v-else-if="directAction.kind === 'payment'" :key="selectedId" :order-id="directAction.id" embedded />
<order-fulfillment-create <order-fulfillment-create
v-else-if="directAction.kind === 'fulfillment-create'" v-else-if="directAction.kind === 'fulfillment-create'"
@@ -125,34 +127,16 @@
</template> </template>
<!-- <!--
第三层:订单详情跳到从属页面时,订单留在主栏、右栏换成这一层。 第三层:订单详情跳到从属页面时,订单留在主栏、右栏换成这一层。
子页标识由详情页的 openSub() 发起,格式 `kind:arg`。 子页标识由详情页的 openSub() 发起,格式 `kind:arg`;换一层就换 :key,交给外层过渡。
--> -->
<template #sub> <template #sub>
<recycle-rule-detail <sales-order-sub-view
v-if="subKind === 'recycle-rule'" :key="subView"
:key="`rule-${subArg}`" :view="subView || ''"
:rule-id="subArg" :order-id="selectedId"
@refresh="refreshRecycleDetail"
@saved="handleSubSaved"
/> />
<order-fulfillment-list
v-else-if="subKind === 'fulfillments'"
key="fulfillments"
:sales-order-id="selectedId"
embedded
/>
<order-fulfillment-detail v-else-if="subKind === 'fulfillment-detail'" :fulfillment-id="subArg" />
<order-fulfillment-create
v-else-if="subKind === 'fulfillment-create'"
key="fulfillment-create"
:sales-order-id="selectedId"
embedded
@saved="handleFulfillmentSaved"
/>
<recycle-payment-list v-else-if="subKind === 'recycle-payments'" :exchange-id="subArg" />
<recycle-payment-detail v-else-if="subKind === 'recycle-payment-detail'" :exchange-id="subArg" :payment-id="subView?.split(':')[2] || ''" @changed="refreshRecycleDetail" />
<recycle-payment-revoke v-else-if="subKind === 'recycle-payment-revoke'" :exchange-id="subArg" :payment-id="subView?.split(':')[2] || ''" @changed="refreshRecycleDetail" />
<recycle-payment-create v-else-if="subKind === 'recycle-register'" :exchange-id="subArg" embedded @saved="handleRecyclePaymentSaved" />
<sales-order-cancel v-else-if="subKind === 'cancel'" :order-id="selectedId" embedded />
<sales-order-payment v-else-if="subKind === 'payment'" :order-id="selectedId" embedded />
</template> </template>
</master-detail-page> </master-detail-page>
@@ -174,17 +158,12 @@
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile"; import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile";
import { Toolkit } from "timi-web"; import { Toolkit } from "timi-web";
import SalesOrderDetail from "@/pages/salesOrder/SalesOrderDetail.vue"; import SalesOrderDetail from "@/pages/salesOrder/SalesOrderDetail.vue";
import SalesOrderCreate from "@/pages/salesOrder/SalesOrderCreate.vue";
import PackagePurchase from "@/pages/package/PackagePurchase.vue";
import RecycleExchangeCreate from "@/pages/recycle/RecycleExchangeCreate.vue"; import RecycleExchangeCreate from "@/pages/recycle/RecycleExchangeCreate.vue";
import RecycleRuleDetail from "@/pages/recycle/RecycleRuleDetail.vue";
import RecyclePaymentList from "@/pages/recycle/RecyclePaymentList.vue";
import RecyclePaymentDetail from "@/pages/recycle/RecyclePaymentDetail.vue";
import RecyclePaymentRevoke from "@/pages/recycle/RecyclePaymentRevoke.vue";
import RecyclePaymentCreate from "@/pages/recycle/RecyclePaymentCreate.vue";
import SalesOrderCancel from "@/pages/salesOrder/SalesOrderCancel.vue"; import SalesOrderCancel from "@/pages/salesOrder/SalesOrderCancel.vue";
import SalesOrderPayment from "@/pages/salesOrder/SalesOrderPayment.vue"; import SalesOrderPayment from "@/pages/salesOrder/SalesOrderPayment.vue";
import OrderFulfillmentCreate from "@/pages/fulfillment/OrderFulfillmentCreate.vue"; import OrderFulfillmentCreate from "@/pages/fulfillment/OrderFulfillmentCreate.vue";
import OrderFulfillmentDetail from "@/pages/fulfillment/OrderFulfillmentDetail.vue";
import OrderFulfillmentList from "@/pages/fulfillment/OrderFulfillmentList.vue";
import { useUserStore } from "timi-web-api"; import { useUserStore } from "timi-web-api";
import { onBeforeRouteLeave } from "vue-router"; import { onBeforeRouteLeave } from "vue-router";
import CustomerAPI from "@/api/CustomerAPI"; import CustomerAPI from "@/api/CustomerAPI";
@@ -193,6 +172,7 @@ import SalesOrderAPI from "@/api/SalesOrderAPI";
import CustomerSelector from "@/components/CustomerSelector.vue"; import CustomerSelector from "@/components/CustomerSelector.vue";
import SalesOrderFilterSummary from "@/pages/salesOrder/component/SalesOrderFilterSummary.vue"; import SalesOrderFilterSummary from "@/pages/salesOrder/component/SalesOrderFilterSummary.vue";
import SalesOrderListCell from "@/pages/salesOrder/component/SalesOrderListCell.vue"; import SalesOrderListCell from "@/pages/salesOrder/component/SalesOrderListCell.vue";
import SalesOrderSubView from "@/pages/salesOrder/component/SalesOrderSubView.vue";
import SalesOrderSummary from "@/pages/salesOrder/component/SalesOrderSummary.vue"; import SalesOrderSummary from "@/pages/salesOrder/component/SalesOrderSummary.vue";
import { useCurrentStoreStore } from "@/store/currentStoreStore"; import { useCurrentStoreStore } from "@/store/currentStoreStore";
import type { GaoPackageConfig } from "@/types/Package"; import type { GaoPackageConfig } from "@/types/Package";
@@ -229,12 +209,16 @@ const route = useRoute();
// 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里;订单没有内联编辑视图 // 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里;订单没有内联编辑视图
const recycleCreatePaneId = "__recycle_create__"; const recycleCreatePaneId = "__recycle_create__";
const createPaneId = "__create__";
const packageCreatePaneId = "__package_create__";
const { selectedId, subView, paneDirection, isWide, openDetail, detailVersion } = useMasterDetailPane({ const { selectedId, subView, paneDirection, isWide, openDetail, detailVersion } = useMasterDetailPane({
path: "/product/sales-orders", path: "/product/sales-orders",
detail: id => { detail: id => {
const [kind, orderId] = id.split(":"); const [kind, orderId] = id.split(":");
if (kind === "cancel" || kind === "payment") return `/product/sales-orders/${orderId}/${kind}`; if (kind === "cancel" || kind === "payment") return `/product/sales-orders/${orderId}/${kind}`;
if (kind === "fulfillment-create") return `/product/order-fulfillments/create?salesOrderId=${encodeURIComponent(orderId)}`; if (kind === "fulfillment-create") return `/product/order-fulfillments/create?salesOrderId=${encodeURIComponent(orderId)}`;
if (id === createPaneId) return "/product/sales-orders/create";
if (id === packageCreatePaneId) return "/product/customer-packages/create";
return id === recycleCreatePaneId return id === recycleCreatePaneId
? "/product/recycle-exchanges/create?source=sales-orders" ? "/product/recycle-exchanges/create?source=sales-orders"
: `/product/sales-orders/${id}`; : `/product/sales-orders/${id}`;
@@ -247,7 +231,6 @@ const directAction = computed(() => {
}); });
/** 子页标识形如 `recycle-rule:698f`,冒号前是类型,后面是参数。 */ /** 子页标识形如 `recycle-rule:698f`,冒号前是类型,后面是参数。 */
const subKind = computed(() => subView.value?.split(":")[0] || "");
const subArg = computed(() => subView.value?.split(":")[1] || ""); const subArg = computed(() => subView.value?.split(":")[1] || "");
watch(subView, (next, previous) => { watch(subView, (next, previous) => {
if (previous?.startsWith("fulfillment-detail:") && next === "fulfillments") { if (previous?.startsWith("fulfillment-detail:") && next === "fulfillments") {
@@ -288,6 +271,17 @@ async function handleFulfillmentSaved(fulfillmentId?: string): Promise<void> {
} }
await salesOrderDetailRef.value?.refreshOrder(); await salesOrderDetailRef.value?.refreshOrder();
} }
/** 子页保存完成:新建了履约单或回收支付时,接着打开它刚建出来的详情。 */
async function handleSubSaved(kind: string, id: string): Promise<void> {
if (kind === "fulfillment-create") {
await handleFulfillmentSaved(id);
return;
}
if (kind === "recycle-register") {
await handleRecyclePaymentSaved(id || undefined);
}
}
const currentStoreStore = useCurrentStoreStore(); const currentStoreStore = useCurrentStoreStore();
const userStore = useUserStore(); const userStore = useUserStore();
const canCreate = computed(() => userStore.hasPermissions(permissionCodes.salesOrder.create)); const canCreate = computed(() => userStore.hasPermissions(permissionCodes.salesOrder.create));
@@ -340,14 +334,14 @@ const actions = computed(() => [
text: "创建产品订单", text: "创建产品订单",
icon: "task", icon: "task",
theme: "primary" as const, theme: "primary" as const,
action: () => router.push("/product/sales-orders/create") action: () => openDetail(createPaneId)
}] : []), }] : []),
...(canCreatePackageOrder.value ? [{ ...(canCreatePackageOrder.value ? [{
key: "create-package-order", key: "create-package-order",
text: "创建套餐订单", text: "创建套餐订单",
icon: "layers", icon: "layers",
theme: "primary" as const, theme: "primary" as const,
action: () => router.push("/product/customer-packages/create") action: () => openDetail(packageCreatePaneId)
}] : []), }] : []),
...(canCreateRecycleOrder.value ? [{ ...(canCreateRecycleOrder.value ? [{
key: "create-recycle-order", key: "create-recycle-order",
+18 -2
View File
@@ -5,7 +5,7 @@
:z-index="20" :z-index="20"
title="确认无需退款" title="确认无需退款"
left-arrow left-arrow
@left-click="$router.back()" @left-click="exit"
> >
<template #right> <template #right>
<t-button <t-button
@@ -62,6 +62,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { useUserStore } from "timi-web-api"; import { useUserStore } from "timi-web-api";
import { usePane } from "timi-tdesign-mobile";
import SalesOrderAPI from "@/api/SalesOrderAPI"; import SalesOrderAPI from "@/api/SalesOrderAPI";
import { getErrorMessage } from "@/utils/error"; import { getErrorMessage } from "@/utils/error";
import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents"; import { emitListDataChanged, listDataEventKeys } from "@/utils/listDataEvents";
@@ -73,8 +74,19 @@ import { getSalesRefundStatusText } from "@/utils/salesOrder";
import type { SalesOrder } from "@/types/SalesOrder"; import type { SalesOrder } from "@/types/SalesOrder";
defineOptions({ name: "SalesOrderNoRefund" }); defineOptions({ name: "SalesOrderNoRefund" });
const props = withDefaults(defineProps<{ orderId?: string; embedded?: boolean }>(), { orderId: "", embedded: false });
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const pane = usePane();
function exit(): void {
if (props.embedded && pane) {
pane.close();
return;
}
router.back();
}
const userStore = useUserStore(); const userStore = useUserStore();
const order = ref<SalesOrder>(); const order = ref<SalesOrder>();
const loading = ref(false); const loading = ref(false);
@@ -104,7 +116,7 @@ function confirmNoRefundReason(value: Array<string | number>): void {
} }
async function loadData(): Promise<void> { async function loadData(): Promise<void> {
const id = String(route.params.id || ""); const id = props.orderId || String(route.params.id || "");
if (!id) return; if (!id) return;
loading.value = true; loading.value = true;
try { try {
@@ -127,6 +139,10 @@ async function save(): Promise<void> {
await SalesOrderAPI.confirmNoRefund({ salesOrderId: order.value.id, reason: reason.value.trim() }); await SalesOrderAPI.confirmNoRefund({ salesOrderId: order.value.id, reason: reason.value.trim() });
emitListDataChanged(listDataEventKeys.salesOrderChanged, order.value.id); emitListDataChanged(listDataEventKeys.salesOrderChanged, order.value.id);
Message.success("已确认无需退款"); Message.success("已确认无需退款");
if (props.embedded && pane) {
pane.close(true);
return;
}
await router.replace(`/product/sales-orders/${order.value.id}`); await router.replace(`/product/sales-orders/${order.value.id}`);
} catch (error) { } catch (error) {
Message.error(getErrorMessage(error, "确认失败,请刷新后重试")); Message.error(getErrorMessage(error, "确认失败,请刷新后重试"));
+18 -2
View File
@@ -5,7 +5,7 @@
:z-index="20" :z-index="20"
title="登记退款" title="登记退款"
left-arrow left-arrow
@left-click="$router.back()" @left-click="exit"
> >
<template #right> <template #right>
<t-button <t-button
@@ -110,6 +110,7 @@ import DateTimeNowPicker from "@/components/DateTimeNowPicker.vue";
import { type Attachment, useUserStore } from "timi-web-api"; import { type Attachment, useUserStore } from "timi-web-api";
import AttachmentSelector from "@/components/attachmentSelector/AttachmentSelector.vue"; import AttachmentSelector from "@/components/attachmentSelector/AttachmentSelector.vue";
import SalesOrderAPI from "@/api/SalesOrderAPI"; import SalesOrderAPI from "@/api/SalesOrderAPI";
import { usePane } from "timi-tdesign-mobile";
import type { PhotoItem } from "@/types/Photo"; import type { PhotoItem } from "@/types/Photo";
import { import {
createPackageRequestNo, createPackageRequestNo,
@@ -127,8 +128,19 @@ import { uploadPhotoList } from "@/utils/photo";
import type { SalesOrder } from "@/types/SalesOrder"; import type { SalesOrder } from "@/types/SalesOrder";
defineOptions({ name: "SalesOrderRefund" }); defineOptions({ name: "SalesOrderRefund" });
const props = withDefaults(defineProps<{ orderId?: string; embedded?: boolean }>(), { orderId: "", embedded: false });
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const pane = usePane();
function exit(): void {
if (props.embedded && pane) {
pane.close();
return;
}
router.back();
}
const userStore = useUserStore(); const userStore = useUserStore();
const order = ref<SalesOrder>(); const order = ref<SalesOrder>();
const loading = ref(false); const loading = ref(false);
@@ -183,7 +195,7 @@ function buildAttachments(): Partial<Attachment>[] {
} }
async function loadData(): Promise<void> { async function loadData(): Promise<void> {
const id = String(route.params.id || ""); const id = props.orderId || String(route.params.id || "");
if (!id) return; if (!id) return;
loading.value = true; loading.value = true;
try { try {
@@ -221,6 +233,10 @@ async function save(): Promise<void> {
}); });
emitListDataChanged(listDataEventKeys.salesOrderChanged, order.value.id); emitListDataChanged(listDataEventKeys.salesOrderChanged, order.value.id);
Message.success("退款登记已提交"); Message.success("退款登记已提交");
if (props.embedded && pane) {
pane.close(true);
return;
}
await router.replace(`/product/sales-orders/${order.value.id}`); await router.replace(`/product/sales-orders/${order.value.id}`);
} catch (error) { } catch (error) {
Message.error(getErrorMessage(error, "退款登记失败,重试会复用同一请求号")); Message.error(getErrorMessage(error, "退款登记失败,重试会复用同一请求号"));
@@ -30,7 +30,7 @@
<t-divider /> <t-divider />
<div class="amounts"> <div class="amounts">
<span>订单总价 <strong v-text="`¥${formatPackageAmount(item.salesOrderAmount)}`" /></span> <span>订单总价 <strong v-text="`¥${formatPackageAmount(item.salesOrderAmount)}`" /></span>
<span>剩余待收 <strong v-text="`¥${formatPackageAmount(item.salesOrderUnpaidAmountSnapshot)}`" /></span> <span>剩余待收(快照) <strong v-text="`¥${formatPackageAmount(item.salesOrderUnpaidAmountSnapshot)}`" /></span>
</div> </div>
<t-divider /> <t-divider />
<div class="people-actions"> <div class="people-actions">
@@ -0,0 +1,134 @@
<template>
<div class="tui-page-layout tui-navbar sales-order-fund-list">
<t-navbar
fixed
:z-index="20"
title="资金流水"
left-arrow
@left-click="exit"
/>
<main v-can="pageAccess" class="tui-page-content list">
<t-pull-down-refresh
class="pull-refresh"
v-model="refreshing"
:refresh-timeout="30000"
@refresh="reload"
@scrolltolower="loadMore"
>
<div v-if="recordList.length" class="records">
<fund-record-list-cell
v-for="item in recordList"
:key="item.id"
:item="item"
@detail="toDetail(item)"
/>
</div>
<center-tips v-else :content="loading ? '正在加载资金流水' : '本单暂无资金流水'" />
<center-tips :content="loadStateText" />
</t-pull-down-refresh>
</main>
</div>
</template>
<script setup lang="ts">
import { usePane } from "timi-tdesign-mobile";
import { useUserStore } from "timi-web-api";
import SalesOrderAPI from "@/api/SalesOrderAPI";
import FundRecordListCell from "@/pages/salesOrder/component/FundRecordListCell.vue";
import type { FundRecord } from "@/types/SalesOrder";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
defineOptions({ name: "SalesOrderFundList" });
const props = withDefaults(defineProps<{
/** 订单 id:只列这条订单产生的资金流水。 */
salesOrderId?: string;
}>(), {
salesOrderId: ""
});
const router = useRouter();
const pane = usePane();
const userStore = useUserStore();
const recordList = ref<FundRecord[]>([]);
const total = ref(0);
const pageIndex = ref(0);
const loading = ref(false);
const refreshing = ref(false);
const noMore = ref(false);
const pageAccess = computed(() => [permissionCodes.fundRecord.read, permissionCodes.fundReceive.create]);
/** 没有流水查看权限、只有收款权限的账号,只能看到自己的收款申请。 */
const isSelfReceiveOnly = computed(() => !userStore.hasPermissions(permissionCodes.fundRecord.read)
&& userStore.hasPermissions(permissionCodes.fundReceive.create));
const loadStateText = computed(() => loading.value ? "正在加载" : noMore.value ? "已经到底了" : "上拉加载更多");
function exit(): void {
if (pane) {
pane.close();
return;
}
void router.back();
}
async function loadMore(): Promise<void> {
if (loading.value || noMore.value) {
return;
}
loading.value = true;
try {
const page = {
index: pageIndex.value,
size: 15,
salesOrderId: props.salesOrderId || undefined
};
const result = isSelfReceiveOnly.value
? await SalesOrderAPI.myReceiveRecordList(page)
: await SalesOrderAPI.fundRecordList(page);
const list = result.list || [];
recordList.value = recordList.value.concat(list);
total.value = result.total || 0;
pageIndex.value += 1;
noMore.value = list.length < 15 || total.value <= recordList.value.length;
} catch (error) {
Message.error(getErrorMessage(error, "资金流水加载失败"));
} finally {
loading.value = false;
}
}
async function reload(): Promise<void> {
if (loading.value) {
return;
}
pageIndex.value = 0;
recordList.value = [];
total.value = 0;
noMore.value = false;
await loadMore();
}
/** 再往下钻一条流水:仍然叠在右栏里,返回回到这份列表。 */
function toDetail(item: FundRecord): void {
if (item.id) {
pane?.openSub(`fund-record:${item.id}`);
}
}
onMounted(loadMore);
watch(() => props.salesOrderId, reload);
</script>
<style scoped lang="less">
.sales-order-fund-list {
.records {
gap: .5rem;
margin: 0 1rem;
display: flex;
flex-direction: column;
}
}
</style>
@@ -301,6 +301,7 @@ function getProductText(item: NonNullable<SalesOrder["itemList"]>[number]): stri
gap: .5rem; gap: .5rem;
flex: 1; flex: 1;
display: flex; display: flex;
min-width: 0;
flex-direction: column; flex-direction: column;
.customer-status { .customer-status {
@@ -318,6 +319,7 @@ function getProductText(item: NonNullable<SalesOrder["itemList"]>[number]): stri
.status { .status {
gap: .25rem; gap: .25rem;
display: flex; display: flex;
flex-shrink: 0;
} }
} }
@@ -0,0 +1,111 @@
<template>
<recycle-rule-detail
v-if="kind === 'recycle-rule'"
:rule-id="arg"
/>
<order-fulfillment-list
v-else-if="kind === 'fulfillments'"
:sales-order-id="orderId"
embedded
/>
<order-fulfillment-detail
v-else-if="kind === 'fulfillment-detail'"
:fulfillment-id="arg"
/>
<order-fulfillment-create
v-else-if="kind === 'fulfillment-create'"
:sales-order-id="orderId"
embedded
@saved="id => emit('saved', kind, id || '')"
/>
<recycle-order-payment-list
v-else-if="kind === 'recycle-payments'"
:exchange-id="arg"
/>
<recycle-payment-detail
v-else-if="kind === 'recycle-payment-detail'"
:exchange-id="arg"
:payment-id="segments[2] || ''"
@changed="emit('refresh')"
/>
<recycle-payment-revoke
v-else-if="kind === 'recycle-payment-revoke'"
:exchange-id="arg"
:payment-id="segments[2] || ''"
@changed="emit('refresh')"
/>
<recycle-payment-create
v-else-if="kind === 'recycle-register'"
:exchange-id="arg"
embedded
@saved="id => emit('saved', kind, id || '')"
/>
<sales-order-cancel
v-else-if="kind === 'cancel'"
:order-id="orderId"
embedded
/>
<sales-order-payment
v-else-if="kind === 'payment'"
:order-id="orderId"
embedded
/>
<sales-order-refund
v-else-if="kind === 'refund'"
:order-id="orderId"
embedded
/>
<sales-order-no-refund
v-else-if="kind === 'no-refund'"
:order-id="orderId"
embedded
/>
<sales-order-fund-list
v-else-if="kind === 'fund-records'"
:sales-order-id="orderId"
/>
<fund-record-detail
v-else-if="kind === 'fund-record'"
:record-id="arg"
/>
</template>
<script setup lang="ts">
import RecycleRuleDetail from "@/pages/recycle/RecycleRuleDetail.vue";
import RecycleOrderPaymentList from "@/pages/recycle/RecycleOrderPaymentList.vue";
import RecyclePaymentDetail from "@/pages/recycle/RecyclePaymentDetail.vue";
import RecyclePaymentRevoke from "@/pages/recycle/RecyclePaymentRevoke.vue";
import RecyclePaymentCreate from "@/pages/recycle/RecyclePaymentCreate.vue";
import OrderFulfillmentList from "@/pages/fulfillment/OrderFulfillmentList.vue";
import OrderFulfillmentDetail from "@/pages/fulfillment/OrderFulfillmentDetail.vue";
import OrderFulfillmentCreate from "@/pages/fulfillment/OrderFulfillmentCreate.vue";
import SalesOrderCancel from "@/pages/salesOrder/SalesOrderCancel.vue";
import SalesOrderPayment from "@/pages/salesOrder/SalesOrderPayment.vue";
import SalesOrderRefund from "@/pages/salesOrder/SalesOrderRefund.vue";
import SalesOrderNoRefund from "@/pages/salesOrder/SalesOrderNoRefund.vue";
import SalesOrderFundList from "@/pages/salesOrder/component/SalesOrderFundList.vue";
import FundRecordDetail from "@/pages/salesOrder/FundRecordDetail.vue";
defineOptions({ name: "SalesOrderSubView" });
const props = withDefaults(defineProps<{
/** 子页标识,形如 `payment`、`fulfillment-detail:698f`。 */
view?: string;
/** 所属订单 id。 */
orderId?: string;
}>(), {
view: "",
orderId: ""
});
const emit = defineEmits<{
/** 子页改了订单数据,宿主应刷新订单详情。 */
refresh: [];
/** 子页保存完成,宿主可据子页类型决定跳到哪一层。 */
saved: [kind: string, id: string];
}>();
const segments = computed(() => props.view.split(":"));
const kind = computed(() => segments.value[0] || "");
const arg = computed(() => segments.value[1] || "");
</script>
@@ -0,0 +1,43 @@
/**
* 右栏内联订单页的标识约定:`sales-order:<订单 id>[:<子页标识>]`。
*
* 资金流水列表这类宿主页把「订单详情及其子页」叠在自己的右栏里,
* 标识借 `useMasterDetailPane` 的 `subView` 传递,宿主负责解析后渲染。
*/
const ORDER_PANE_PREFIX = "sales-order";
/** 拼接右栏订单页标识;`view` 为空表示订单详情本身。 */
export function buildOrderPaneView(orderId: string, view = ""): string {
return view ? `${ORDER_PANE_PREFIX}:${orderId}:${view}` : `${ORDER_PANE_PREFIX}:${orderId}`;
}
/** 解析右栏订单页标识;不是订单页时返回 null。 */
export function parseOrderPaneView(value: string): { orderId: string; view: string } | null {
const [prefix, orderId, ...rest] = value.split(":");
if (prefix !== ORDER_PANE_PREFIX || !orderId) {
return null;
}
return { orderId, view: rest.join(":") };
}
/**
* 右栏订单页对应的整页路由。
*
* 转屏变窄后右栏不再渲染,靠它把用户留在原来看的那一层;
* 没有对应整页路由的子页回落到订单详情。
*/
export function getOrderPaneRoute(pane: { orderId: string; view: string }): string {
const { orderId, view } = pane;
const [kind, arg] = view.split(":");
switch (kind) {
case "payment": return `/product/sales-orders/${orderId}/payment`;
case "cancel": return `/product/sales-orders/${orderId}/cancel`;
case "refund": return `/product/sales-orders/${orderId}/refund`;
case "no-refund": return `/product/sales-orders/${orderId}/no-refund`;
case "fulfillments": return `/product/order-fulfillments?salesOrderId=${encodeURIComponent(orderId)}`;
case "fulfillment-create": return `/product/order-fulfillments/create?salesOrderId=${encodeURIComponent(orderId)}`;
case "fulfillment-detail": return arg ? `/product/order-fulfillments/${arg}` : `/product/sales-orders/${orderId}`;
default: return `/product/sales-orders/${orderId}`;
}
}
+29 -4
View File
@@ -21,19 +21,42 @@
</t-cell> </t-cell>
<t-cell title="背景模糊特效"> <t-cell title="背景模糊特效">
<template #right-icon> <template #right-icon>
<t-switch :model-value="globalUIStore.backdropBlur" @change="value => globalUIStore.setBackdropBlur(value === true)" /> <t-switch
size="small"
:model-value="globalUIStore.backdropBlur"
@change="value => globalUIStore.setBackdropBlur(value === true)"
/>
</template>
</t-cell>
</t-cell-group>
<t-cell-group v-if="isAndroidApp" title="照片" theme="card" v-entrance-transition>
<t-cell title="拍照后存入相册">
<template #right-icon>
<t-switch
size="small"
:model-value="settingStore.albumSave"
@change="value => settingStore.setAlbumSave(value === true)"
/>
</template> </template>
</t-cell> </t-cell>
</t-cell-group> </t-cell-group>
<t-cell-group title="声音" theme="card" v-entrance-transition> <t-cell-group title="声音" theme="card" v-entrance-transition>
<t-cell title="扫码成功"> <t-cell title="扫码成功">
<template #right-icon> <template #right-icon>
<t-switch :model-value="settingStore.sound.scanSuccess" @change="value => handleScanSuccessChange(value === true)" /> <t-switch
size="small"
:model-value="settingStore.sound.scanSuccess"
@change="value => handleScanSuccessChange(value === true)"
/>
</template> </template>
</t-cell> </t-cell>
<t-cell title="登记成功"> <t-cell title="登记成功">
<template #right-icon> <template #right-icon>
<t-switch :model-value="settingStore.sound.registerSuccess" @change="value => handleRegisterSuccessChange(value === true)" /> <t-switch
size="small"
:model-value="settingStore.sound.registerSuccess"
@change="value => handleRegisterSuccessChange(value === true)"
/>
</template> </template>
</t-cell> </t-cell>
<t-cell title="音量"> <t-cell title="音量">
@@ -56,6 +79,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { Capacitor } from "@capacitor/core";
import type { ThemeMode } from "@/store/globalUI"; import type { ThemeMode } from "@/store/globalUI";
import { useGlobalUIStore } from "@/store/globalUI"; import { useGlobalUIStore } from "@/store/globalUI";
import SegmentedSlider from "@/components/SegmentedSlider.vue"; import SegmentedSlider from "@/components/SegmentedSlider.vue";
@@ -67,6 +91,7 @@ defineOptions({
const globalUIStore = useGlobalUIStore(); const globalUIStore = useGlobalUIStore();
const settingStore = useSettingStore(); const settingStore = useSettingStore();
const isAndroidApp = Capacitor.getPlatform() === "android";
// ---------- 主题 ---------- // ---------- 主题 ----------
@@ -137,7 +162,7 @@ async function playSettingSoundPreview(type: "scanSuccess" | "registerSuccess"):
.volume-field { .volume-field {
gap: .5rem; gap: .5rem;
width: 16rem; width: 14rem;
display: flex; display: flex;
align-items: center; align-items: center;
+1 -5
View File
@@ -214,9 +214,6 @@ const updateHint = computed<string>(() => {
// ---------- 更新日志 ---------- // ---------- 更新日志 ----------
/** web 端只展示最近几个版本 */
const WEB_NOTE_LIMIT = 3;
const noteList = ref<AppUpdateNote[]>([]); const noteList = ref<AppUpdateNote[]>([]);
/** 有更新时展示区间日志,已是最新时展示最近几个版本 */ /** 有更新时展示区间日志,已是最新时展示最近几个版本 */
@@ -232,8 +229,7 @@ async function loadNotes(): Promise<void> {
platform: Capacitor.getPlatform(), platform: Capacitor.getPlatform(),
channel: "stable" channel: "stable"
}); });
const list = result?.notes ?? []; noteList.value = result?.notes ?? [];
noteList.value = updateSupported ? list : list.slice(0, WEB_NOTE_LIMIT);
} catch { } catch {
// 日志不是关键路径,失败时安静降级,不弹错误 // 日志不是关键路径,失败时安静降级,不弹错误
noteList.value = []; noteList.value = [];
+24 -51
View File
@@ -1,8 +1,8 @@
<template> <template>
<t-navbar fixed :z-index="20" title="管理" /> <div class="tui-page-layout tui-navbar setting-tab">
<main class="tui-page-content scroll column management-tab"> <t-navbar fixed :z-index="20" title="管理" />
<div class="tab-body"> <main ref="settingTabPage" class="tui-page-content scroll column">
<div class="menus"> <div class="content">
<t-cell-group class="user-card" theme="card" v-entrance-transition> <t-cell-group class="user-card" theme="card" v-entrance-transition>
<t-cell <t-cell
v-if="currentUser" v-if="currentUser"
@@ -42,9 +42,8 @@
</t-cell> </t-cell>
</t-cell-group> </t-cell-group>
<t-cell-group <t-cell-group
v-for="group in visibleMenuGroupList" v-for="(group, index) in visibleMenuGroupList"
:key="group.title" :key="index"
:title="group.title"
theme="card" theme="card"
v-entrance-transition="{ step: 30 }" v-entrance-transition="{ step: 30 }"
> >
@@ -62,13 +61,13 @@
</template> </template>
</t-cell> </t-cell>
</t-cell-group> </t-cell-group>
<footer class="footer">
<p>技术支持:夜雨</p>
<p>Copyright © 2026 imyeyu.com</p>
</footer>
</div> </div>
<footer class="footer"> </main>
<p>技术支持:夜雨</p> </div>
<p>Copyright © 2026 imyeyu.com</p>
</footer>
</div>
</main>
</template> </template>
<script lang="ts"> <script lang="ts">
@@ -92,7 +91,6 @@ type MenuItem = {
type MenuGroup = { type MenuGroup = {
items: MenuItem[]; items: MenuItem[];
title?: string;
}; };
defineOptions({ defineOptions({
@@ -102,11 +100,7 @@ defineOptions({
const router = useRouter(); const router = useRouter();
const route = useRoute(); const route = useRoute();
const userStore = useUserStore(); const userStore = useUserStore();
const settingTabPage = ref<HTMLElement>();
function getSettingTabPage(): HTMLElement | undefined {
return Array.from(document.querySelectorAll<HTMLElement>(".page-transition .page"))
.find(element => !!element.querySelector(".management-tab"));
}
const currentUser = computed(() => userStore.loginUser.user); const currentUser = computed(() => userStore.loginUser.user);
@@ -129,7 +123,6 @@ const visibleMenuGroupList = computed<MenuGroup[]>(() => menuGroupList.value
const menuGroupList = computed<MenuGroup[]>(() => [ const menuGroupList = computed<MenuGroup[]>(() => [
{ {
title: "客户",
items: [ items: [
{ {
icon: "usergroup", icon: "usergroup",
@@ -170,7 +163,6 @@ const menuGroupList = computed<MenuGroup[]>(() => [
] ]
}, },
{ {
title: "登记",
items: [ items: [
{ {
icon: "task", icon: "task",
@@ -193,7 +185,6 @@ const menuGroupList = computed<MenuGroup[]>(() => [
] ]
}, },
{ {
title: "积分",
items: [ items: [
{ {
icon: "git-merge", icon: "git-merge",
@@ -222,7 +213,6 @@ const menuGroupList = computed<MenuGroup[]>(() => [
] ]
}, },
{ {
title: "系统",
items: [ items: [
{ {
icon: "download", icon: "download",
@@ -263,7 +253,6 @@ const menuGroupList = computed<MenuGroup[]>(() => [
] ]
}, },
{ {
title: "其他",
items: [ items: [
{ {
icon: "file-1", icon: "file-1",
@@ -320,11 +309,10 @@ function restoreScrollPosition(): void {
return; return;
} }
const scrollTop = settingTabScrollTop; const scrollTop = settingTabScrollTop;
const settingTabPage = getSettingTabPage(); if (!settingTabPage.value) {
if (!settingTabPage) {
return; return;
} }
settingTabPage.scrollTop = scrollTop; settingTabPage.value.scrollTop = scrollTop;
settingTabScrollTop = undefined; settingTabScrollTop = undefined;
} }
@@ -333,36 +321,21 @@ onMounted(async () => {
await loadCurrentRoleList(); await loadCurrentRoleList();
}); });
onBeforeRouteLeave(() => { onBeforeRouteLeave(() => {
const settingTabPage = getSettingTabPage(); settingTabScrollTop = settingTabPage.value?.scrollTop;
const scrollElement = document.scrollingElement;
settingTabScrollTop = settingTabPage?.scrollTop ?? scrollElement?.scrollTop ?? window.scrollY;
}); });
</script> </script>
<style scoped lang="less"> <style scoped lang="less">
.management-tab { .setting-tab {
gap: .5rem;
// 管理页是一列「账户 + 分组入口」,平板上限宽居中,避免卡片被拉成整屏宽 // 管理页是一列「账户 + 分组入口」,平板上限宽居中,避免卡片被拉成整屏宽
.tab-body { .content {
--tab-body-max: 40rem; gap: 1rem;
width: 100%;
padding: 0 1rem; margin: 0 auto;
}
/**
* 与手机竖屏完全一致的单列堆叠:账户卡 + 每组一张卡片。
* 平板上只是不再拉宽,宽度由 .tab-body 的 max-width 收住。
*/
.menus {
gap: .5rem;
display: flex; display: flex;
max-width: 40rem;
flex-direction: column; flex-direction: column;
// 卡片自带 16px 外边距,间距交给容器
:deep(.t-cell-group--card) {
margin: 0;
}
} }
.user-card { .user-card {
@@ -404,7 +377,8 @@ onBeforeRouteLeave(() => {
} }
:global(html.theme-dark) { :global(html.theme-dark) {
.management-tab {
.setting-tab {
.office { .office {
color: #94a3b8; color: #94a3b8;
} }
@@ -412,7 +386,6 @@ onBeforeRouteLeave(() => {
.footer p { .footer p {
color: #94a3b8; color: #94a3b8;
} }
} }
} }
</style> </style>
+9 -3
View File
@@ -10,10 +10,16 @@ function meta(depth = 3): RouteRecordRaw["meta"] {
export default [ export default [
{ {
path: "/product/recycle-payments", path: "/product/recycle-payments",
name: "RecyclePaymentAll", name: "RecycleLedgerList",
component: () => import("@/pages/recycle/RecyclePaymentList.vue"), component: () => import("@/pages/recycle/RecycleLedgerList.vue"),
meta: meta() meta: meta()
}, },
{
path: "/product/recycle-ledgers/:id",
name: "RecycleLedgerDetail",
component: () => import("@/pages/recycle/RecycleLedgerDetail.vue"),
meta: meta(4)
},
{ {
path: "/product/recycle-exchanges", path: "/product/recycle-exchanges",
name: "RecycleExchangeList", name: "RecycleExchangeList",
@@ -53,7 +59,7 @@ export default [
{ {
path: "/product/recycle-exchanges/:id/payments", path: "/product/recycle-exchanges/:id/payments",
name: "RecyclePaymentList", name: "RecyclePaymentList",
component: () => import("@/pages/recycle/RecyclePaymentList.vue"), component: () => import("@/pages/recycle/RecycleOrderPaymentList.vue"),
meta: meta(5) meta: meta(5)
}, },
{ {
+11
View File
@@ -10,6 +10,7 @@ export interface SoundSetting {
type SoundType = "scanSuccess" | "registerSuccess"; type SoundType = "scanSuccess" | "registerSuccess";
const SOUND_STORAGE_KEY = "gao-customer-h5:sound"; const SOUND_STORAGE_KEY = "gao-customer-h5:sound";
const ALBUM_SAVE_STORAGE_KEY = "gao-customer-h5:album-save";
const soundUrlMap: Record<SoundType, string> = { const soundUrlMap: Record<SoundType, string> = {
scanSuccess: scanSuccessSoundUrl, scanSuccess: scanSuccessSoundUrl,
registerSuccess: registrationSuccessSoundUrl registerSuccess: registrationSuccessSoundUrl
@@ -48,6 +49,8 @@ function readStoredSoundSetting(): SoundSetting {
export const useSettingStore = defineStore("setting", () => { export const useSettingStore = defineStore("setting", () => {
const sound = ref<SoundSetting>(readStoredSoundSetting()); const sound = ref<SoundSetting>(readStoredSoundSetting());
/** 拍照后是否额外存一份到系统相册,默认开启 */
const albumSave = ref(localStorage.getItem(ALBUM_SAVE_STORAGE_KEY) !== "0");
const soundPlayerMap = shallowRef<Record<SoundType, HTMLAudioElement> | null>(null); const soundPlayerMap = shallowRef<Record<SoundType, HTMLAudioElement> | null>(null);
const audioContext = shallowRef<AudioContext | null>(null); const audioContext = shallowRef<AudioContext | null>(null);
const scanSuccessBuffer = shallowRef<AudioBuffer | null>(null); const scanSuccessBuffer = shallowRef<AudioBuffer | null>(null);
@@ -64,6 +67,12 @@ export const useSettingStore = defineStore("setting", () => {
applySoundVolume(); applySoundVolume();
} }
/** 开关相册副本,只影响后续拍摄,已保存的文件不动 */
function setAlbumSave(value: boolean): void {
albumSave.value = value;
localStorage.setItem(ALBUM_SAVE_STORAGE_KEY, value ? "1" : "0");
}
function loadSoundPlayers(): void { function loadSoundPlayers(): void {
if (soundPlayerMap.value) { if (soundPlayerMap.value) {
return; return;
@@ -223,7 +232,9 @@ export const useSettingStore = defineStore("setting", () => {
return { return {
sound, sound,
albumSave,
setSound, setSound,
setAlbumSave,
loadSoundPlayers, loadSoundPlayers,
unlockSoundPlayers, unlockSoundPlayers,
playScanSuccessSound, playScanSuccessSound,
+10
View File
@@ -201,6 +201,11 @@ export type RecycleCustomerAccountPage = {
* `bizType` 决定来源语义:履约产生、人工调整、支付预占与释放、支付核销、冲正返还。 * `bizType` 决定来源语义:履约产生、人工调整、支付预占与释放、支付核销、冲正返还。
*/ */
export type RecycleLedger = { export type RecycleLedger = {
customer?: Customer | null;
customerName?: string;
customerCode?: string;
recycleName?: string;
recycleUnit?: string;
id?: string; id?: string;
accountId?: string; accountId?: string;
storeId?: string; storeId?: string;
@@ -214,6 +219,7 @@ export type RecycleLedger = {
balanceAfter?: number | string; balanceAfter?: number | string;
reservedAfter?: number | string; reservedAfter?: number | string;
operatorUserId?: string | null; operatorUserId?: string | null;
operator?: Partial<User> | null;
reason?: string | null; reason?: string | null;
createdAt?: number; createdAt?: number;
}; };
@@ -280,6 +286,10 @@ export type RecyclePayment = {
/** 服务端回填的回收物名称与单位,仅展示用 */ /** 服务端回填的回收物名称与单位,仅展示用 */
recycleName?: string | null; recycleName?: string | null;
recycleUnit?: string | null; recycleUnit?: string | null;
/** 订单当前成交金额,单位分 */
salesOrderAmount?: number | null;
/** 订单当前剩余待收金额,单位分 */
salesOrderUnpaidAmount?: number | null;
attachmentList?: Attachment[]; attachmentList?: Attachment[];
operator?: Partial<User>; operator?: Partial<User>;
verifier?: Partial<User>; verifier?: Partial<User>;
-18
View File
@@ -1,18 +0,0 @@
declare module "browser-image-compression" {
export interface ImageCompressionOptions {
alwaysKeepResolution?: boolean;
exifOrientation?: number;
fileType?: string;
initialQuality?: number;
libURL?: string;
maxIteration?: number;
maxSizeMB?: number;
maxWidthOrHeight?: number;
onProgress?: (progress: number) => void;
preserveExif?: boolean;
signal?: AbortSignal;
useWebWorker?: boolean;
}
export default function imageCompression(file: File, options: ImageCompressionOptions): Promise<File>;
}
+98 -25
View File
@@ -1,37 +1,46 @@
import imageCompression from "browser-image-compression"; /** 单张照片压缩后的目标体积 */
const TARGET_BYTES = 300 * 1024;
const PHOTO_MAX_SIZE_MB = 300 / 1024; /** 长边上限,超过就等比缩小 */
const PHOTO_MAX_WIDTH_OR_HEIGHT = 1920; const MAX_EDGE = 1920;
/** 质量阶梯:从高往低试,命中目标体积就停 */
const QUALITY_LIST = [.86, .78, .7, .62, .54, .46];
/** 兜底缩放的次数,质量降到最低仍超标时继续缩小尺寸 */
const MAX_SCALE_ATTEMPTS = 3;
/** /**
* 转为真正的 File,避免压缩库返回 Blob 后 FormData 使用默认文件名 blob。 * 压缩上传图片
*/ *
function normalizeUploadImageFile(source: File, compressed: Blob): File { * 用自己的 canvas 实现而不是 browser-image-compression:后者在 Web Worker 里用
if (compressed instanceof File && compressed.name) { * `createImageBitmap` + `OffscreenCanvas` 解码,再把手写 EXIF 的方向标记改成 1。
return compressed; * 一旦 worker 里解出来的位图没有按 EXIF 摆正,存下来的照片就是"倒转 + 大片空白",
} * 而且不可逆。这里用 `<img>` 解码——浏览器会按 EXIF 摆正,`naturalWidth/naturalHeight`
* 也是摆正后的尺寸,所以画到 canvas 上一定是对的。
return new File([compressed], source.name || "upload-image", { *
type: compressed.type || source.type, * @param file 原始文件
lastModified: source.lastModified * @returns 压缩后的文件,非图片或压缩失败时原样返回
});
}
/**
* 压缩上传图片,统一限制到 300 KB。
*/ */
export async function compressUploadImage(file: File): Promise<File> { export async function compressUploadImage(file: File): Promise<File> {
if (!file.type.startsWith("image/")) { if (!file.type.startsWith("image/")) {
return file; return file;
} }
const compressedFile = await imageCompression(file, { try {
maxSizeMB: PHOTO_MAX_SIZE_MB, const image = await loadImage(file);
maxWidthOrHeight: PHOTO_MAX_WIDTH_OR_HEIGHT, const blob = await encodeWithinTarget(image);
useWebWorker: true, if (!blob) {
initialQuality: .86 return file;
}); }
return normalizeUploadImageFile(file, compressedFile); return new File([blob], fileName(file), {
type: "image/jpeg",
lastModified: file.lastModified
});
} catch {
// 压缩是优化项,失败就传原图,不能让上传断掉
return file;
}
} }
/** /**
@@ -44,3 +53,67 @@ export async function compressUploadImageList(fileList: File[]): Promise<File[]>
} }
return result; return result;
} }
/** 解码图片,浏览器会自动应用 EXIF 方向 */
function loadImage(file: File): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(file);
const image = new Image();
image.onload = () => {
URL.revokeObjectURL(url);
resolve(image);
};
image.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error("图片解码失败"));
};
image.src = url;
});
}
/** 逐级降质量、实在不行再降尺寸,直到体积达标 */
async function encodeWithinTarget(image: HTMLImageElement): Promise<Blob | null> {
const width = image.naturalWidth || image.width;
const height = image.naturalHeight || image.height;
let scale = Math.min(1, MAX_EDGE / Math.max(width, height));
let last: Blob | null = null;
for (let attempt = 0; attempt < MAX_SCALE_ATTEMPTS; attempt += 1) {
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.round(width * scale));
canvas.height = Math.max(1, Math.round(height * scale));
const context = canvas.getContext("2d");
if (!context) {
return last;
}
context.drawImage(image, 0, 0, canvas.width, canvas.height);
for (const quality of QUALITY_LIST) {
const blob = await toBlob(canvas, quality);
if (!blob) {
return last;
}
last = blob;
if (blob.size <= TARGET_BYTES) {
return blob;
}
}
// 质量到底还超标,缩小尺寸再来一轮
scale *= .8;
}
return last;
}
/** canvas 转 JPEG,统一走 promise */
function toBlob(canvas: HTMLCanvasElement, quality: number): Promise<Blob | null> {
return new Promise(resolve => canvas.toBlob(blob => resolve(blob), "image/jpeg", quality));
}
/** 保留原文件名,缺省时给一个带时间戳的 */
function fileName(file: File): string {
if (file.name) {
return file.name;
}
return `upload-${Date.now()}.jpg`;
}
+68
View File
@@ -0,0 +1,68 @@
import { Capacitor, registerPlugin } from "@capacitor/core";
interface MediaSaverPlugin {
begin(options: { fileName: string; mimeType: string; mediaType: "image" | "video" }): Promise<{ id: string }>;
append(options: { id: string; data: string }): Promise<void>;
finish(options: { id: string }): Promise<void>;
cancel(options: { id: string }): Promise<void>;
}
const MediaSaver = registerPlugin<MediaSaverPlugin>("MediaSaver");
/** 分块大小,base64 后约 683KB,避免把整个视频一次性塞进桥接调用 */
const CHUNK_SIZE = 512 * 1024;
/** 相册文件名只允许安全字符 */
const SAFE_NAME = /^[\w.-]{1,120}$/;
/** 当前外壳是否具备写相册的能力 */
export function supportsAlbumSave(): boolean {
return Capacitor.isPluginAvailable("MediaSaver");
}
/**
* 把直接拍摄得到的媒体写进系统相册
*
* 写的是 MediaStore 自己的记录,Android 10 起不需要存储权限。
* 失败由调用方决定怎么处理——相册保存是增强能力,绝不能影响上传。
*
* @param file 拍摄产物
* @param mediaType 媒体类型,决定落到 DCIM 还是视频集合
*/
export async function saveToAlbum(file: File, mediaType: "image" | "video"): Promise<void> {
if (!supportsAlbumSave() || !file.size) {
return;
}
const { id } = await MediaSaver.begin({
fileName: buildFileName(file, mediaType),
mimeType: file.type || (mediaType === "video" ? "video/mp4" : "image/jpeg"),
mediaType
});
try {
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
await MediaSaver.append({ id, data: toBase64(chunk) });
}
await MediaSaver.finish({ id });
} catch (error) {
await MediaSaver.cancel({ id }).catch(() => undefined);
throw error;
}
}
/** 生成相册里的显示名,拿不到可用原名时用时间戳兜底 */
function buildFileName(file: File, mediaType: "image" | "video"): string {
const suffix = mediaType === "video" ? "mp4" : "jpg";
const name = file.name && SAFE_NAME.test(file.name) ? file.name : `IMG_${Date.now()}.${suffix}`;
return name.includes(".") ? name : `${name}.${suffix}`;
}
/** ArrayBuffer 转 base64,分段拼接避免超长参数撑爆调用栈 */
function toBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let index = 0; index < bytes.length; index += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return window.btoa(binary);
}
+6 -1
View File
@@ -110,6 +110,8 @@ export function getRecyclePaymentStatusTheme(status?: RecyclePaymentStatus): "su
export function getRecycleLedgerTypeText(bizType?: string): string { export function getRecycleLedgerTypeText(bizType?: string): string {
return ({ return ({
FULFILLMENT_YIELD: "履约产生", FULFILLMENT_YIELD: "履约产生",
FULFILLMENT_REVOKE: "履约冲正",
MANUAL: "人工调整",
ADJUST: "人工调整", ADJUST: "人工调整",
PAYMENT_RESERVE: "支付预占", PAYMENT_RESERVE: "支付预占",
PAYMENT_RELEASE: "释放预占", PAYMENT_RELEASE: "释放预占",
@@ -130,7 +132,10 @@ export function isPaymentVerified(payment?: RecyclePayment): boolean {
/** 拼接「数量 + 单位」,后端 BigDecimal 可能是字符串。 */ /** 拼接「数量 + 单位」,后端 BigDecimal 可能是字符串。 */
export function getRecycleQuantityText(value: number | string | null | undefined, unit?: string | null): string { export function getRecycleQuantityText(value: number | string | null | undefined, unit?: string | null): string {
const quantityText = getPackageQuantityText(value); const text = String(value ?? "").trim();
const negative = text.startsWith("-");
const quantity = getPackageQuantityText(negative ? text.slice(1) : value);
const quantityText = negative && quantity !== "0" ? `-${quantity}` : quantity;
return unit ? `${quantityText} ${unit}` : quantityText; return unit ? `${quantityText} ${unit}` : quantityText;
} }
-330
View File
@@ -1,330 +0,0 @@
const TWA_ORIGIN = "https://gao.imyeyu.com";
const TWA_BRIDGE_TIMEOUT = 10_000;
const MEDIA_CHUNK_SIZE = 64 * 1024;
const LOG_PREFIX = "[TWA 相册]";
type CapturedMediaType = "image" | "video";
interface TwaMessage {
type: string;
id?: string;
index?: number;
data?: string;
error?: string;
version?: number;
}
type TwaResponseHandler = (message: TwaMessage) => void;
let bridgeInitialized = false;
let bridgePort: MessagePort | undefined;
let bridgeWaiterList: Array<(port: MessagePort | undefined) => void> = [];
let transferQueue = Promise.resolve();
const responseHandlerMap = new Map<string, TwaResponseHandler>();
/**
* 初始化 TWA 通信监听。
*
* 普通浏览器不会收到带 MessagePort 的消息,因此初始化失败时不会影响网页功能。
*/
export function initializeTwaBridge(): void {
if (bridgeInitialized || typeof window === "undefined") {
return;
}
bridgeInitialized = true;
window.addEventListener("message", handleWindowMessage);
logInfo("已初始化网页侧通信监听");
}
/**
* 将直接拍摄得到的媒体保存到 Android 系统相册。
*
* 非 TWA 环境会直接返回,不会阻塞原有上传流程。
*/
export function saveCapturedMediaToAlbum(file: File, mediaType: CapturedMediaType): void {
if (!file.size) {
logWarn("跳过相册保存:文件大小为 0", {
fileName: file.name,
mediaType
});
return;
}
initializeTwaBridge();
logInfo("收到相册保存请求", {
fileName: file.name,
fileType: file.type,
fileSize: file.size,
mediaType
});
transferQueue = transferQueue
.then(async () => {
await transferMedia(file, mediaType);
})
.catch(error => {
// 相册保存是增强能力,失败时不能影响媒体上传。
logError("相册保存失败,已忽略并继续原上传流程", error);
});
}
/**
* 根据文件输入框判断是否为直接拍摄,并启动相册保存。
*/
export function saveCapturedFilesFromInput(input: HTMLInputElement, fileList: readonly File[]): void {
if (!input.capture || !fileList.length) {
return;
}
const mediaType: CapturedMediaType = input.accept.toLowerCase().includes("video") ? "video" : "image";
logInfo("识别为直接拍摄媒体", {
accept: input.accept,
capture: input.capture,
fileCount: fileList.length,
mediaType
});
for (const file of fileList) {
saveCapturedMediaToAlbum(file, mediaType);
}
}
function handleWindowMessage(event: MessageEvent): void {
const message = parseMessage(event.data);
if (message?.type !== "twa-bridge-ready") {
return;
}
if (event.origin !== TWA_ORIGIN || !event.ports.length) {
logWarn("忽略无效的 TWA 桥接就绪消息", {
origin: event.origin,
hasMessagePort: event.ports.length > 0
});
return;
}
logInfo("收到 Android 侧桥接就绪消息", {
origin: event.origin,
version: message.version
});
bridgePort = event.ports[0];
bridgePort.onmessage = handlePortMessage;
bridgePort.start();
bridgePort.postMessage(JSON.stringify({
type: "twa-bridge-ready-ack",
version: 1
}));
const waiterList = bridgeWaiterList;
bridgeWaiterList = [];
for (const waiter of waiterList) {
waiter(bridgePort);
}
}
function handlePortMessage(event: MessageEvent): void {
const message = parseMessage(event.data);
if (!message?.id) {
return;
}
responseHandlerMap.get(message.id)?.(message);
}
async function transferMedia(file: File, mediaType: CapturedMediaType): Promise<void> {
const port = await waitForBridgePort();
if (!port) {
logWarn("未连接到 TWA,跳过相册保存", {
fileName: file.name,
mediaType
});
return;
}
const id = createTransferId();
let transferFinished = false;
logInfo("开始传输媒体", {
id,
fileName: file.name,
mediaType,
fileSize: file.size,
chunkSize: MEDIA_CHUNK_SIZE
});
try {
await sendTransferMessage(port, id, {
type: "media-start",
id,
mediaType,
mimeType: file.type || `${mediaType}/*`,
fileName: file.name,
size: file.size
}, "media-started");
let offset = 0;
let index = 0;
while (offset < file.size) {
const chunk = await file.slice(offset, offset + MEDIA_CHUNK_SIZE).arrayBuffer();
if (index === 0 || index % 16 === 0 || offset + chunk.byteLength >= file.size) {
logDebug("发送媒体分块", {
id,
index,
chunkSize: chunk.byteLength,
offset
});
}
await sendTransferMessage(port, id, {
type: "media-chunk",
id,
index,
data: encodeBase64(chunk)
}, "media-chunk-ack", index);
offset += chunk.byteLength;
index++;
}
await sendTransferMessage(port, id, {
type: "media-finish",
id
}, "media-saved");
transferFinished = true;
logInfo("媒体已保存到系统相册", {
id,
fileName: file.name,
fileSize: file.size
});
} finally {
if (!transferFinished) {
logWarn("媒体传输未完成,发送中止请求", { id });
port.postMessage(JSON.stringify({
type: "media-abort",
id
}));
}
}
}
async function sendTransferMessage(
port: MessagePort,
id: string,
message: Record<string, unknown>,
expectedType: string,
expectedIndex?: number
): Promise<void> {
const responsePromise = waitForTransferResponse(id, expectedType, expectedIndex);
logDebug("发送桥接消息", {
id,
type: message.type,
expectedType,
expectedIndex
});
port.postMessage(JSON.stringify(message));
await responsePromise;
}
function waitForBridgePort(): Promise<MessagePort | undefined> {
if (bridgePort) {
return Promise.resolve(bridgePort);
}
return new Promise(resolve => {
let settled = false;
const settle = (port?: MessagePort): void => {
if (settled) {
return;
}
settled = true;
resolve(port);
};
bridgeWaiterList.push(settle);
logDebug("等待 Android 侧桥接就绪");
window.setTimeout(() => {
bridgeWaiterList = bridgeWaiterList.filter(waiter => waiter !== settle);
logWarn("等待 TWA 桥接超时,当前页面不是已建立通道的 TWA,或 Android 来源校验未通过", {
origin: window.location.origin,
displayMode: getDisplayMode(),
userAgent: navigator.userAgent
});
settle();
}, TWA_BRIDGE_TIMEOUT);
});
}
function waitForTransferResponse(id: string, expectedType: string, expectedIndex?: number): Promise<void> {
return new Promise((resolve, reject) => {
const timeout = window.setTimeout(() => {
responseHandlerMap.delete(id);
logError("等待桥接响应超时", new Error(`${expectedType}, id=${id}`));
reject(new Error("TWA 媒体保存响应超时"));
}, 15_000);
responseHandlerMap.set(id, message => {
if (message.type === "media-error") {
window.clearTimeout(timeout);
responseHandlerMap.delete(id);
logError("Android 侧返回媒体错误", new Error(message.error || "TWA 媒体保存失败"));
reject(new Error(message.error || "TWA 媒体保存失败"));
return;
}
if (message.type !== expectedType || (expectedIndex !== undefined && message.index !== expectedIndex)) {
return;
}
window.clearTimeout(timeout);
responseHandlerMap.delete(id);
resolve();
});
});
}
function logInfo(message: string, detail?: unknown): void {
console.warn(LOG_PREFIX, message, detail ?? "");
}
function logDebug(message: string, detail?: unknown): void {
console.warn(LOG_PREFIX, message, detail ?? "");
}
function logWarn(message: string, detail?: unknown): void {
console.warn(LOG_PREFIX, message, detail ?? "");
}
function logError(message: string, error: unknown): void {
console.error(LOG_PREFIX, message, error);
}
function parseMessage(value: unknown): TwaMessage | undefined {
if (typeof value !== "string") {
return undefined;
}
try {
const message = JSON.parse(value) as TwaMessage;
return typeof message.type === "string" ? message : undefined;
} catch {
return undefined;
}
}
function encodeBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let index = 0; index < bytes.length; index += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return window.btoa(binary);
}
function createTransferId(): string {
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
return crypto.randomUUID();
}
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function getDisplayMode(): string {
if (window.matchMedia("(display-mode: standalone)").matches) {
return "standalone";
}
if (window.matchMedia("(display-mode: fullscreen)").matches) {
return "fullscreen";
}
return "browser";
}
-10
View File
@@ -1,10 +0,0 @@
.gradle/
local.properties
**/build/
*.apk
*.aab
*.idsig
*.jks
*.keystore
!gradle/wrapper/gradle-wrapper.jar
-47
View File
@@ -1,47 +0,0 @@
# TWA 构建说明
本目录是 `gao.imyeyu.com` 的 Trusted Web Activity 工程。APK 只包含 Android 启动壳,业务页面始终从 `https://gao.imyeyu.com/` 加载,不把前端 `dist` 打进 APK。
## 构建环境
- JDK 17
- Android SDK
- Bubblewrap CLI 1.25.0
在本机首次使用 Bubblewrap 时执行:
```powershell
pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 doctor
```
## 构建 APK
首次构建正式版本时,先在本目录生成并妥善备份 release keystore:
```powershell
keytool -genkeypair -v -keystore .\android.keystore -alias gao-customer -keyalg RSA -keysize 2048 -validity 10000
```
```powershell
pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 build
```
构建前请准备长期保存的 release keystore,并确认 `twa-manifest.json` 中的 `signingKey` 指向它。当前目录的 `signingKey` 是可提交的相对路径模板;本次验证 APK 使用的是本机调试签名,不能作为正式发布签名。
构建完成后,用 release keystore 的 SHA-256 证书指纹更新 `../public/.well-known/assetlinks.json`,再发布前端 `dist`。TWA 只有在网站的 `/.well-known/assetlinks.json` 与 APK 包名、签名一致时,才会进入无地址栏的全屏模式。
当前 `assetlinks.json` 中登记的是本机调试证书指纹,只能配合本次验证 APK 使用。正式发布前必须替换为 release 证书指纹;如果使用 Google Play,还要把 Play App Signing 证书指纹一并登记。
## TWA 媒体桥接
TWA 通过 `postMessage` 接收网页直接拍摄的照片和视频,Android 10 及以上使用 `MediaStore` 分块写入系统相册,照片保存到“图片/糕店管理”,视频保存到“视频/糕店管理”。普通浏览器和从相册选择的文件不会触发该桥接。
桥接依赖 `assetlinks.json` 中的 `delegate_permission/common.use_as_origin` 关系。发布 APK 前必须使用实际 release 签名证书的 SHA-256 指纹更新该文件,否则来源验证失败,桥接不会启用。
## 前端发布顺序
1. 先上传新版本 `dist/assets`。
2. 再上传新的 `index.html`、Manifest 和其他静态文件。
3. 最后检查 `https://gao.imyeyu.com/`、`/manifest.webmanifest` 和 `/.well-known/assetlinks.json`。
`index.html` 不缓存,带哈希的 `/assets/` 长缓存。不要给前端资源增加 Service Worker 缓存,除非同时实现版本更新和回滚,否则会阻止 TWA 获取最新页面。
-213
View File
@@ -1,213 +0,0 @@
/*
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import groovy.xml.MarkupBuilder
plugins {
id 'com.android.application'
}
def twaManifest = [
applicationId: 'com.imyeyu.gao.customer',
hostName: 'gao.imyeyu.com', // The domain being opened in the TWA.
launchUrl: '/', // The start path for the TWA. Must be relative to the domain.
name: '糕店客户管理', // The application name.
launcherName: '糕店管理', // The name shown on the Android Launcher.
themeColor: '#FFFFFF', // The color used for the status bar.
themeColorDark: '#000000', // The color used for the dark status bar.
navigationColor: '#000000', // The color used for the navigation bar.
navigationColorDark: '#000000', // The color used for the dark navbar.
navigationDividerColor: '#000000', // The navbar divider color.
navigationDividerColorDark: '#000000', // The dark navbar divider color.
backgroundColor: '#FFFFFF', // The color used for the splash screen background.
enableNotifications: false, // Set to true to enable notification delegation.
// Every shortcut must include the following fields:
// - name: String that will show up in the shortcut.
// - short_name: Shorter string used if |name| is too long.
// - url: Absolute path of the URL to launch the app with (e.g '/create').
// - icon: Name of the resource in the drawable folder to use as an icon.
shortcuts: [],
// The duration of fade out animation in milliseconds to be played when removing splash screen.
splashScreenFadeOutDuration: 300,
generatorApp: 'bubblewrap-cli', // Application that generated the Android Project
// The fallback strategy for when Trusted Web Activity is not available. Possible values are
// 'customtabs' and 'webview'.
fallbackType: 'customtabs',
enableSiteSettingsShortcut: 'true',
orientation: 'portrait',
]
android {
compileSdkVersion 36
namespace "com.imyeyu.gao.customer"
defaultConfig {
applicationId "com.imyeyu.gao.customer"
minSdkVersion 21
targetSdkVersion 36
versionCode 1
versionName "1"
// The name for the application
resValue "string", "appName", twaManifest.name
// The name for the application on the Android Launcher
resValue "string", "launcherName", twaManifest.launcherName
// The URL that will be used when launching the TWA from the Android Launcher
def launchUrl = "https://" + twaManifest.hostName + twaManifest.launchUrl
resValue "string", "launchUrl", launchUrl
// The URL the Web Manifest for the Progressive Web App that the TWA points to. This
// is used by Chrome OS and Meta Quest to open the Web version of the PWA instead of
// the TWA, as it will probably give a better user experience for non-mobile devices.
resValue "string", "webManifestUrl", 'https://gao.imyeyu.com/manifest.webmanifest'
// This is used by Meta Quest.
resValue "string", "fullScopeUrl", 'https://gao.imyeyu.com/'
// The hostname is used when building the intent-filter, so the TWA is able to
// handle Intents to open host url of the application.
resValue "string", "hostName", twaManifest.hostName
// This attribute sets the status bar color for the TWA. It can be either set here or in
// `res/values/colors.xml`. Setting in both places is an error and the app will not
// compile. If not set, the status bar color defaults to #FFFFFF - white.
resValue "color", "colorPrimary", twaManifest.themeColor
// This attribute sets the dark status bar color for the TWA. It can be either set here or in
// `res/values/colors.xml`. Setting in both places is an error and the app will not
// compile. If not set, the status bar color defaults to #000000 - white.
resValue "color", "colorPrimaryDark", twaManifest.themeColorDark
// This attribute sets the navigation bar color for the TWA. It can be either set here or
// in `res/values/colors.xml`. Setting in both places is an error and the app will not
// compile. If not set, the navigation bar color defaults to #FFFFFF - white.
resValue "color", "navigationColor", twaManifest.navigationColor
// This attribute sets the dark navigation bar color for the TWA. It can be either set here
// or in `res/values/colors.xml`. Setting in both places is an error and the app will not
// compile. If not set, the navigation bar color defaults to #000000 - black.
resValue "color", "navigationColorDark", twaManifest.navigationColorDark
// This attribute sets the navbar divider color for the TWA. It can be either
// set here or in `res/values/colors.xml`. Setting in both places is an error and the app
// will not compile. If not set, the divider color defaults to #00000000 - transparent.
resValue "color", "navigationDividerColor", twaManifest.navigationDividerColor
// This attribute sets the dark navbar divider color for the TWA. It can be either
// set here or in `res/values/colors.xml`. Setting in both places is an error and the
//app will not compile. If not set, the divider color defaults to #000000 - black.
resValue "color", "navigationDividerColorDark", twaManifest.navigationDividerColorDark
// Sets the color for the background used for the splash screen when launching the
// Trusted Web Activity.
resValue "color", "backgroundColor", twaManifest.backgroundColor
// Defines a provider authority for the Splash Screen
resValue "string", "providerAuthority", twaManifest.applicationId + '.fileprovider'
// The enableNotification resource is used to enable or disable the
// TrustedWebActivityService, by changing the android:enabled and android:exported
// attributes
resValue "bool", "enableNotification", twaManifest.enableNotifications.toString()
twaManifest.shortcuts.eachWithIndex { shortcut, index ->
resValue "string", "shortcut_name_$index", "$shortcut.name"
resValue "string", "shortcut_short_name_$index", "$shortcut.short_name"
}
// The splashScreenFadeOutDuration resource is used to set the duration of fade out animation in milliseconds
// to be played when removing splash screen. The default is 0 (no animation).
resValue "integer", "splashScreenFadeOutDuration", twaManifest.splashScreenFadeOutDuration.toString()
resValue "string", "generatorApp", twaManifest.generatorApp
resValue "string", "fallbackType", twaManifest.fallbackType
resValue "bool", "enableSiteSettingsShortcut", twaManifest.enableSiteSettingsShortcut
resValue "string", "orientation", twaManifest.orientation
}
buildTypes {
release {
minifyEnabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lintOptions {
checkReleaseBuilds false
}
}
task generateShorcutsFile {
assert twaManifest.shortcuts.size() < 5, "You can have at most 4 shortcuts."
twaManifest.shortcuts.eachWithIndex { s, i ->
assert s.name != null, 'Missing `name` in shortcut #' + i
assert s.short_name != null, 'Missing `short_name` in shortcut #' + i
assert s.url != null, 'Missing `icon` in shortcut #' + i
assert s.icon != null, 'Missing `url` in shortcut #' + i
}
def shortcutsFile = new File("$projectDir/src/main/res/xml", "shortcuts.xml")
def xmlWriter = new StringWriter()
def xmlMarkup = new MarkupBuilder(new IndentPrinter(xmlWriter, " ", true))
xmlMarkup
.'shortcuts'('xmlns:android': 'http://schemas.android.com/apk/res/android') {
twaManifest.shortcuts.eachWithIndex { s, i ->
'shortcut'(
'android:shortcutId': 'shortcut' + i,
'android:enabled': 'true',
'android:icon': '@drawable/' + s.icon,
'android:shortcutShortLabel': '@string/shortcut_short_name_' + i,
'android:shortcutLongLabel': '@string/shortcut_name_' + i) {
'intent'(
'android:action': 'android.intent.action.MAIN',
'android:targetPackage': twaManifest.applicationId,
'android:targetClass': twaManifest.applicationId + '.LauncherActivity',
'android:data': s.url)
'categories'('android:name': 'android.intent.category.LAUNCHER')
}
}
}
shortcutsFile.text = xmlWriter.toString() + '\n'
}
preBuild.dependsOn(generateShorcutsFile)
repositories {
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.google.androidbrowserhelper:androidbrowserhelper:2.6.2'
}
-196
View File
@@ -1,196 +0,0 @@
<!--
Copyright 2019 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- The "package" attribute is rewritten by the Gradle build with the value of applicationId.
It is still required here, as it is used to derive paths, for instance when referring
to an Activity by ".MyActivity" instead of the full name. If more Activities are added to the
application, the package attribute will need to reflect the correct path in order to use
the abbreviated format. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.imyeyu.gao.customer">
<application
android:name="Application"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/appName"
android:manageSpaceActivity="com.google.androidbrowserhelper.trusted.ManageDataLauncherActivity"
android:supportsRtl="true"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<meta-data
android:name="asset_statements"
android:resource="@string/assetStatements" />
<meta-data
android:name="web_manifest_url"
android:value="@string/webManifestUrl" />
<meta-data
android:name="twa_generator"
android:value="@string/generatorApp" />
<activity android:name="com.google.androidbrowserhelper.trusted.ManageDataLauncherActivity"
android:exported="false"
android:enabled="true"
android:excludeFromRecents="true">
<meta-data
android:name="android.support.customtabs.trusted.MANAGE_SPACE_URL"
android:value="@string/launchUrl" />
<intent-filter>
<action android:name="android.intent.action.APPLICATION_PREFERENCES" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="LauncherActivity"
android:alwaysRetainTaskState="true"
android:label="@string/launcherName"
android:exported="true">
<meta-data android:name="android.support.customtabs.trusted.DEFAULT_URL"
android:value="@string/launchUrl" />
<meta-data
android:name="android.support.customtabs.trusted.STATUS_BAR_COLOR"
android:resource="@color/colorPrimary" />
<meta-data
android:name="android.support.customtabs.trusted.STATUS_BAR_COLOR_DARK"
android:resource="@color/colorPrimaryDark" />
<meta-data
android:name="android.support.customtabs.trusted.NAVIGATION_BAR_COLOR"
android:resource="@color/navigationColor" />
<meta-data
android:name="android.support.customtabs.trusted.NAVIGATION_BAR_COLOR_DARK"
android:resource="@color/navigationColorDark" />
<meta-data
android:name="androix.browser.trusted.NAVIGATION_BAR_DIVIDER_COLOR"
android:resource="@color/navigationDividerColor" />
<meta-data
android:name="androix.browser.trusted.NAVIGATION_BAR_DIVIDER_COLOR_DARK"
android:resource="@color/navigationDividerColorDark" />
<meta-data android:name="android.support.customtabs.trusted.SPLASH_IMAGE_DRAWABLE"
android:resource="@drawable/splash"/>
<meta-data android:name="android.support.customtabs.trusted.SPLASH_SCREEN_BACKGROUND_COLOR"
android:resource="@color/backgroundColor"/>
<meta-data android:name="android.support.customtabs.trusted.SPLASH_SCREEN_FADE_OUT_DURATION"
android:value="@integer/splashScreenFadeOutDuration"/>
<meta-data android:name="android.support.customtabs.trusted.FILE_PROVIDER_AUTHORITY"
android:value="@string/providerAuthority"/>
<meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts" />
<meta-data android:name="android.support.customtabs.trusted.FALLBACK_STRATEGY"
android:value="@string/fallbackType" />
<meta-data android:name="android.support.customtabs.trusted.SCREEN_ORIENTATION"
android:value="@string/orientation"/>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="https"
android:host="@string/hostName"
/>
</intent-filter>
</activity>
<activity android:name="com.google.androidbrowserhelper.trusted.FocusActivity" />
<activity android:name="com.google.androidbrowserhelper.trusted.WebViewFallbackActivity"
android:configChanges="orientation|screenSize" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="@string/providerAuthority"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
<service
android:name="androidx.browser.customtabs.PostMessageService"
android:exported="true" />
<service
android:name=".DelegationService"
android:enabled="@bool/enableNotification"
android:exported="@bool/enableNotification">
<intent-filter>
<action android:name="android.support.customtabs.trusted.TRUSTED_WEB_ACTIVITY_SERVICE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
</application>
</manifest>
@@ -1,29 +0,0 @@
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.imyeyu.gao.customer;
public class Application extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
}
}
@@ -1,14 +0,0 @@
package com.imyeyu.gao.customer;
public class DelegationService extends
com.google.androidbrowserhelper.trusted.DelegationService {
@Override
public void onCreate() {
super.onCreate();
}
}
@@ -1,322 +0,0 @@
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.imyeyu.gao.customer;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import org.json.JSONObject;
import java.lang.reflect.Field;
import androidx.annotation.Nullable;
import androidx.browser.customtabs.CustomTabsCallback;
import androidx.browser.customtabs.CustomTabsService;
import androidx.browser.customtabs.CustomTabsSession;
import com.google.androidbrowserhelper.trusted.QualityEnforcer;
import com.google.androidbrowserhelper.trusted.TwaLauncher;
public class LauncherActivity
extends com.google.androidbrowserhelper.trusted.LauncherActivity {
private static final String TAG = "GaoTwaBridge";
private static final Uri WEB_ORIGIN = Uri.parse("https://gao.imyeyu.com");
private static final long CHANNEL_RETRY_DELAY_MILLIS = 500L;
private static final int MAX_CHANNEL_ATTEMPTS = 20;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private final CustomTabsCallback bridgeCallback = new BridgeCallback();
private TwaMediaStoreBridge mediaStoreBridge;
private CustomTabsSession postMessageSession;
private boolean originValidationRequested;
private boolean originValidated;
private boolean postMessageChannelRequested;
private boolean postMessageChannelReady;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mediaStoreBridge = new TwaMediaStoreBridge(this);
Log.i(TAG, "TWA Activity 已创建,开始初始化媒体相册桥接");
// Setting an orientation crashes the app due to the transparent background on Android 8.0
// Oreo and below. We only set the orientation on Oreo and above. This only affects the
// splash screen and Chrome will still respect the orientation.
// See https://github.com/GoogleChromeLabs/bubblewrap/issues/496 for details.
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
@Override
protected Uri getLaunchingUrl() {
// Get the original launch Url.
Uri uri = super.getLaunchingUrl();
return uri;
}
@Override
protected CustomTabsCallback getCustomTabsCallback() {
return bridgeCallback;
}
@Override
protected void onDestroy() {
Log.i(TAG, "TWA Activity 销毁,清理未完成的媒体传输");
if (mediaStoreBridge != null) {
mediaStoreBridge.abortAll();
}
mainHandler.removeCallbacksAndMessages(null);
super.onDestroy();
}
private void scheduleChannelRequest(int attempt) {
if (attempt >= MAX_CHANNEL_ATTEMPTS || postMessageChannelReady) {
return;
}
mainHandler.postDelayed(() -> requestPostMessageChannel(attempt), CHANNEL_RETRY_DELAY_MILLIS);
}
private void requestPostMessageChannel(int attempt) {
if (isFinishing() || postMessageChannelReady) {
return;
}
CustomTabsSession session = getCustomTabsSession();
if (session == null) {
Log.w(TAG, "请求 PostMessage 通道失败:当前没有可用的 CustomTabsSession,attempt=" + attempt);
scheduleChannelRequest(attempt + 1);
return;
}
postMessageSession = session;
if (!originValidationRequested) {
originValidationRequested = true;
Log.i(TAG, "开始验证 TWA 来源关系:" + WEB_ORIGIN);
session.validateRelationship(CustomTabsService.RELATION_USE_AS_ORIGIN, WEB_ORIGIN, null);
return;
}
if (!originValidated || postMessageChannelRequested) {
return;
}
postMessageChannelRequested = true;
boolean requested = session.requestPostMessageChannel(WEB_ORIGIN, WEB_ORIGIN, new Bundle());
Log.i(TAG, "请求 PostMessage 通道,结果=" + requested);
if (!requested) {
postMessageChannelRequested = false;
scheduleChannelRequest(attempt + 1);
}
}
/**
* 当前 Bubblewrap 生成的 Android Browser Helper 版本没有公开 TWA 会话访问器,
* 这里按字段类型读取会话,不依赖混淆后的私有字段名称。
*/
@Nullable
private CustomTabsSession getCustomTabsSession() {
try {
Object twaLauncher = findFieldValue(this, TwaLauncher.class);
if (twaLauncher == null) {
Log.w(TAG, "未找到 TwaLauncher 实例");
return null;
}
CustomTabsSession session = (CustomTabsSession) findFieldValue(twaLauncher, CustomTabsSession.class);
if (session == null) {
Log.w(TAG, "未找到 CustomTabsSession 实例");
}
return session;
} catch (ReflectiveOperationException | RuntimeException exception) {
Log.w(TAG, "读取 TWA 会话失败", exception);
return null;
}
}
@Nullable
private static Object findFieldValue(Object target, Class<?> fieldType) throws IllegalAccessException {
Class<?> currentClass = target.getClass();
while (currentClass != null) {
for (Field field : currentClass.getDeclaredFields()) {
if (!fieldType.isAssignableFrom(field.getType())) {
continue;
}
field.setAccessible(true);
return field.get(target);
}
currentClass = currentClass.getSuperclass();
}
return null;
}
private void handleBridgeMessage(String message) {
if (mediaStoreBridge == null || !postMessageChannelReady) {
Log.w(TAG, "忽略媒体消息:桥接尚未就绪");
return;
}
try {
JSONObject payload = new JSONObject(message);
String type = payload.optString("type");
String id = payload.optString("id");
Log.d(TAG, "收到网页桥接消息,type=" + type + ", id=" + id);
if ("twa-bridge-ready-ack".equals(type)) {
Log.i(TAG, "网页已确认 TWA 桥接就绪");
return;
}
if (id.length() == 0) {
return;
}
if ("media-start".equals(type)) {
String error = mediaStoreBridge.start(
id,
payload.optString("mimeType"),
payload.optString("fileName"),
payload.optLong("size", -1L)
);
Log.i(TAG, "开始保存媒体,id=" + id + ", mimeType=" + payload.optString("mimeType")
+ ", fileName=" + payload.optString("fileName") + ", size=" + payload.optLong("size", -1L)
+ ", result=" + (error == null ? "success" : error));
postBridgeResponse(error == null ? "media-started" : "media-error", id, null, error);
return;
}
if ("media-chunk".equals(type)) {
int index = payload.optInt("index", -1);
if (index < 0) {
mediaStoreBridge.abort(id);
postBridgeResponse("media-error", id, null, "媒体分块编号无效");
return;
}
byte[] chunk = Base64.decode(payload.optString("data"), Base64.NO_WRAP);
String error = mediaStoreBridge.append(id, index, chunk);
if (error != null || index == 0 || index % 16 == 0) {
Log.d(TAG, "写入媒体分块,id=" + id + ", index=" + index + ", bytes=" + chunk.length
+ ", result=" + (error == null ? "success" : error));
}
postBridgeResponse(error == null ? "media-chunk-ack" : "media-error", id, index, error);
return;
}
if ("media-finish".equals(type)) {
String error = mediaStoreBridge.finish(id);
Log.i(TAG, "完成保存媒体,id=" + id + ", result=" + (error == null ? "success" : error));
postBridgeResponse(error == null ? "media-saved" : "media-error", id, null, error);
return;
}
if ("media-abort".equals(type)) {
Log.w(TAG, "网页主动中止媒体保存,id=" + id);
mediaStoreBridge.abort(id);
}
} catch (Exception exception) {
Log.e(TAG, "解析 TWA 媒体消息失败,原始消息长度=" + message.length(), exception);
}
}
private void postBridgeResponse(String type, String id, @Nullable Integer index, @Nullable String error) {
JSONObject response = new JSONObject();
try {
response.put("type", type);
response.put("id", id);
if (index != null) {
response.put("index", index);
}
if (error != null) {
response.put("error", error);
}
} catch (Exception exception) {
return;
}
mainHandler.post(() -> {
if (!postMessageChannelReady || postMessageSession == null) {
return;
}
int result = postMessageSession.postMessage(response.toString(), null);
Log.d(TAG, "发送桥接响应,type=" + type + ", id=" + id + ", result=" + result);
});
}
private final class BridgeCallback extends QualityEnforcer {
@Override
public void onNavigationEvent(int navigationEvent, @Nullable Bundle extras) {
super.onNavigationEvent(navigationEvent, extras);
Log.d(TAG, "TWA 导航事件=" + navigationEvent);
if (navigationEvent == NAVIGATION_FINISHED) {
scheduleChannelRequest(0);
}
}
@Override
public void onRelationshipValidationResult(
int relation,
@Nullable Uri requestedOrigin,
boolean result,
@Nullable Bundle extras
) {
super.onRelationshipValidationResult(relation, requestedOrigin, result, extras);
if (relation != CustomTabsService.RELATION_USE_AS_ORIGIN || !WEB_ORIGIN.equals(requestedOrigin)) {
return;
}
originValidated = result;
Log.i(TAG, "TWA 来源验证结果=" + result + ", origin=" + requestedOrigin);
if (result) {
scheduleChannelRequest(0);
} else {
Log.w(TAG, "TWA 来源验证失败,请检查 assetlinks.json");
}
}
@Override
public void onMessageChannelReady(@Nullable Bundle extras) {
super.onMessageChannelReady(extras);
postMessageChannelReady = true;
Log.i(TAG, "PostMessage 通道已就绪");
postMessageSession = getCustomTabsSession();
if (postMessageSession == null) {
Log.e(TAG, "PostMessage 通道已就绪,但无法获取 CustomTabsSession");
return;
}
JSONObject readyMessage = new JSONObject();
try {
readyMessage.put("type", "twa-bridge-ready");
readyMessage.put("version", 1);
} catch (Exception exception) {
return;
}
int result = postMessageSession.postMessage(readyMessage.toString(), null);
Log.i(TAG, "发送 TWA 桥接就绪消息,result=" + result);
}
@Override
public void onPostMessage(String message, @Nullable Bundle extras) {
super.onPostMessage(message, extras);
handleBridgeMessage(message);
}
}
}
@@ -1,249 +0,0 @@
/*
* Copyright (c) 2026 imyeyu.com
*
* MIT License
*/
package com.imyeyu.gao.customer;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import androidx.annotation.Nullable;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* 将 TWA 传来的媒体分块写入 Android 系统相册。
*/
final class TwaMediaStoreBridge {
private static final String TAG = "GaoTwaMediaStore";
private static final long MAX_MEDIA_SIZE = 512L * 1024L * 1024L;
private static final int BUFFER_SIZE = 64 * 1024;
private final ContentResolver contentResolver;
private final Map<String, PendingMedia> pendingMediaMap = new HashMap<>();
TwaMediaStoreBridge(Context context) {
contentResolver = context.getContentResolver();
}
synchronized String start(
String id,
String mimeType,
String fileName,
long expectedSize
) {
Log.i(TAG, "准备创建相册媒体,id=" + id + ", mimeType=" + mimeType + ", fileName=" + fileName
+ ", expectedSize=" + expectedSize + ", sdk=" + Build.VERSION.SDK_INT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
Log.w(TAG, "Android 版本低于 10,无法无权限写入相册");
return "Android 10 以下系统不支持无权限写入系统相册";
}
if (id.length() == 0 || id.length() > 128) {
return "媒体标识无效";
}
if (pendingMediaMap.containsKey(id)) {
return "媒体传输已存在";
}
if (expectedSize <= 0 || expectedSize > MAX_MEDIA_SIZE) {
return "媒体文件大小超出限制";
}
String normalizedMimeType = normalizeMimeType(mimeType);
if (normalizedMimeType == null) {
return "只支持照片和视频";
}
Uri mediaUri = null;
try {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, buildDisplayName(fileName, normalizedMimeType));
values.put(MediaStore.MediaColumns.MIME_TYPE, normalizedMimeType);
values.put(MediaStore.MediaColumns.RELATIVE_PATH, buildRelativePath(normalizedMimeType));
values.put(MediaStore.MediaColumns.IS_PENDING, 1);
mediaUri = contentResolver.insert(getCollectionUri(normalizedMimeType), values);
if (mediaUri == null) {
Log.e(TAG, "MediaStore insert 返回空 Uri,id=" + id);
return "创建相册媒体失败";
}
OutputStream outputStream = contentResolver.openOutputStream(mediaUri);
if (outputStream == null) {
deleteQuietly(mediaUri);
Log.e(TAG, "无法打开 MediaStore 输出流,id=" + id + ", uri=" + mediaUri);
return "打开相册媒体失败";
}
pendingMediaMap.put(id, new PendingMedia(mediaUri, outputStream, expectedSize));
Log.i(TAG, "相册媒体创建成功,id=" + id + ", uri=" + mediaUri + ", path="
+ buildRelativePath(normalizedMimeType));
return null;
} catch (Exception exception) {
if (mediaUri != null) {
deleteQuietly(mediaUri);
}
Log.e(TAG, "创建相册媒体异常,id=" + id, exception);
return "创建相册媒体失败";
}
}
synchronized String append(String id, int index, byte[] chunk) {
PendingMedia pendingMedia = pendingMediaMap.get(id);
if (pendingMedia == null) {
return "媒体传输不存在";
}
if (index != pendingMedia.nextChunkIndex) {
abort(id);
return "媒体分块顺序错误";
}
if (chunk.length == 0 || pendingMedia.receivedSize + chunk.length > pendingMedia.expectedSize) {
abort(id);
return "媒体分块大小错误";
}
try {
pendingMedia.outputStream.write(chunk);
pendingMedia.outputStream.flush();
pendingMedia.receivedSize += chunk.length;
pendingMedia.nextChunkIndex++;
return null;
} catch (IOException exception) {
abort(id);
Log.e(TAG, "写入相册媒体异常,id=" + id + ", index=" + index, exception);
return "写入相册媒体失败";
}
}
synchronized String finish(String id) {
PendingMedia pendingMedia = pendingMediaMap.remove(id);
if (pendingMedia == null) {
return "媒体传输不存在";
}
if (pendingMedia.receivedSize != pendingMedia.expectedSize) {
closeQuietly(pendingMedia.outputStream);
deleteQuietly(pendingMedia.mediaUri);
Log.e(TAG, "媒体内容不完整,id=" + id + ", received=" + pendingMedia.receivedSize
+ ", expected=" + pendingMedia.expectedSize);
return "媒体内容不完整";
}
try {
pendingMedia.outputStream.flush();
pendingMedia.outputStream.close();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.IS_PENDING, 0);
if (contentResolver.update(pendingMedia.mediaUri, values, null, null) != 1) {
deleteQuietly(pendingMedia.mediaUri);
Log.e(TAG, "发布相册媒体失败,MediaStore update 返回 0,id=" + id);
return "发布相册媒体失败";
}
Log.i(TAG, "相册媒体发布成功,id=" + id + ", uri=" + pendingMedia.mediaUri
+ ", bytes=" + pendingMedia.receivedSize);
return null;
} catch (Exception exception) {
closeQuietly(pendingMedia.outputStream);
deleteQuietly(pendingMedia.mediaUri);
Log.e(TAG, "保存相册媒体异常,id=" + id, exception);
return "保存相册媒体失败";
}
}
synchronized void abort(String id) {
PendingMedia pendingMedia = pendingMediaMap.remove(id);
if (pendingMedia == null) {
return;
}
closeQuietly(pendingMedia.outputStream);
deleteQuietly(pendingMedia.mediaUri);
Log.w(TAG, "已清理中止的相册媒体,id=" + id + ", uri=" + pendingMedia.mediaUri);
}
synchronized void abortAll() {
for (PendingMedia pendingMedia : pendingMediaMap.values()) {
closeQuietly(pendingMedia.outputStream);
deleteQuietly(pendingMedia.mediaUri);
}
pendingMediaMap.clear();
Log.i(TAG, "已清理全部未完成的相册媒体");
}
@Nullable
private static String normalizeMimeType(String mimeType) {
String normalizedMimeType = mimeType == null ? "" : mimeType.trim().toLowerCase(Locale.ROOT);
if (normalizedMimeType.startsWith("image/")) {
return normalizedMimeType.equals("image/*") ? "image/jpeg" : normalizedMimeType;
}
if (normalizedMimeType.startsWith("video/")) {
return normalizedMimeType.equals("video/*") ? "video/mp4" : normalizedMimeType;
}
return null;
}
private static Uri getCollectionUri(String mimeType) {
if (mimeType.startsWith("video/")) {
return MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
}
return MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
}
private static String buildRelativePath(String mimeType) {
if (mimeType.startsWith("video/")) {
return Environment.DIRECTORY_MOVIES + "/糕店管理";
}
return Environment.DIRECTORY_PICTURES + "/糕店管理";
}
private static String buildDisplayName(String fileName, String mimeType) {
String safeFileName = fileName == null ? "" : fileName
.replaceAll("[^A-Za-z0-9._-]", "_")
.replaceAll("^\\.+$", "");
if (safeFileName.length() == 0) {
safeFileName = "capture-" + System.currentTimeMillis();
}
if (safeFileName.lastIndexOf('.') < 0) {
safeFileName += mimeType.startsWith("video/") ? ".mp4" : ".jpg";
}
return safeFileName;
}
private void deleteQuietly(Uri uri) {
try {
contentResolver.delete(uri, null, null);
} catch (Exception ignored) {
// 相册清理失败时不能覆盖原始错误。
}
}
private static void closeQuietly(OutputStream outputStream) {
try {
outputStream.close();
} catch (IOException ignored) {
// 关闭失败时继续清理媒体记录。
}
}
private static final class PendingMedia {
private final Uri mediaUri;
private final OutputStream outputStream;
private final long expectedSize;
private long receivedSize;
private int nextChunkIndex;
private PendingMedia(Uri mediaUri, OutputStream outputStream, long expectedSize) {
this.mediaUri = mediaUri;
this.outputStream = new BufferedOutputStream(outputStream, BUFFER_SIZE);
this.expectedSize = expectedSize;
}
}
}
@@ -1,25 +0,0 @@
<!--
Copyright 2020 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:inset="2dp">
<aapt:attr name="android:drawable">
<shape android:shape="oval">
<solid android:color="@color/shortcut_background" />
<size android:width="44dp" android:height="44dp" />
</shape>
</aapt:attr>
</inset>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Some files were not shown because too many files have changed in this diff Show More