37 Commits
Author SHA1 Message Date
timi 7073de06a0 Merge pull request 'v1.5.0' (#12) from dev into master
Reviewed-on: #12
2026-11-17 15:57:16 +00:00
Timi 59e519b549 v1.5.0
Build / build (pull_request) Successful in 49s
Deploy / deploy (pull_request) Successful in 48s
Release / release (pull_request) Successful in 48s
2026-11-17 23:56:43 +08:00
Timi cbfcd69408 feat(system): support app internal update apk 2026-11-17 23:56:43 +08:00
Timi 9f7f260f3e ci(release): auto create tag and release for gitea when deploy succeed 2026-11-17 23:56:43 +08:00
Timi 2816ec1f4b Merge branch 'fix/pending-bundle' into dev 2026-11-17 16:14:13 +08:00
Timi 44ff5c3733 Merge branch 'chore/android-env' into dev 2026-11-17 16:14:13 +08:00
Timi 02a41663a1 fix(update): 别让坏包卡住更新入口
- restorePending 只认 success / pending 的包:插件把失败包也列在 list() 里,
  之前会被当成「已下载待应用」,每次启动就弹窗
- apply 失败时删除该包并清空待应用状态,不再卡在「已下载,重启生效」
- 版本更新页在应用失败后提示原因,用户可以直接重新检查更新
2026-11-17 16:07:43 +08:00
Timi bac3a15cbe chore(android): 构建脚本拆分开发与生产两套环境
- 新增 scripts/android-sync.ps1:dev 注入局域网接口地址,prod 清掉 VITE_API_BASE_URL 走 .env.production
- 新增 android:sync:dev / android:sync:prod,android:sync 保留为 prod 别名
- android-open.ps1 改为复用 android:sync:dev,不再自己拼环境变量
- NATIVE_UPGRADE.md 补充「打壳前必须 sync:prod」与产物核对项
2026-11-17 14:51:00 +08:00
timi 2fb5e93262 Merge pull request 'v1.4.0' (#11) from release/1.4.0 into master
Reviewed-on: #11
2026-11-17 04:13:53 +00:00
Timi f3689a2ccc Merge remote-tracking branch 'origin/master' into release/1.4.0
Build / build (pull_request) Successful in 50s
Deploy / deploy (pull_request) Successful in 49s
Release / release (pull_request) Successful in 50s
# Conflicts:
#	CHANGELOG.md
#	package.json
2026-11-17 12:07:40 +08:00
timi f2432b2b24 Merge pull request 'v1.3.2' (#10) from release/1.3.2 into master
Reviewed-on: #10
2026-11-17 03:55:51 +00:00
Timi 8c346a81c3 feat(update): support download apk package
Build / build (pull_request) Successful in 48s
Deploy / deploy (pull_request) Successful in 48s
Release / release (pull_request) Successful in 49s
2026-11-17 11:54:00 +08:00
Timi e60a5d0ea9 chore: 安卓调试脚本改用局域网地址 2026-11-17 00:34:22 +08:00
Timi 525ae6e0ab chore: 准备 1.4.0 发版与新版外壳
- package.json 升到 1.4.0,对齐 CHANGELOG 与发版 PR 标题
- 外壳 versionCode 1 -> 2、versionName 1.0.0 -> 1.0.1(MainActivity 改了原生层)
2026-11-17 00:33:57 +08:00
Timi 5b22554970 fix(UI): not full screen on apk 2026-11-16 20:34:37 +08:00
Timi 208fdde290 feat(customer): support birthdate followup reminder 2026-11-16 16:23:23 +08:00
Timi 553de63cc7 refactor(UI): fund record list cell 2026-11-15 17:35:04 +08:00
Timi 6b7346f029 fix(UI): back root page for rail bar on tablet 2026-11-14 17:05:54 +08:00
Timi 0910d8dc40 feat(product): no modification base unit 2026-11-14 16:32:07 +08:00
Timi f5565aeda4 fix(recycle): required mark for recycle 2026-11-14 15:34:08 +08:00
Timi d9cebc4d66 style(product): popup style for stock calendar 2026-11-14 15:31:20 +08:00
Timi a69497d556 fix(system): recent update log 2026-11-14 15:07:05 +08:00
timi 611656e6cf Merge pull request 'v1.3.1' (#9) from dev into master
Reviewed-on: #9
2026-11-13 17:12:54 +00:00
Timi f2b36013fe v1.3.1
Build / build (pull_request) Successful in 47s
Deploy / deploy (pull_request) Successful in 48s
Release / release (pull_request) Successful in 49s
2026-11-14 01:11:16 +08:00
Timi 0b18550534 feat(recycle): add customer recycle list 2026-11-14 01:05:46 +08:00
Timi bff1d747e0 feat(product): summary and change unit for stock popup 2026-11-14 00:15:27 +08:00
Timi e0434a76c4 style(product): lighter color for in/out stock calendar 2026-11-14 00:00:26 +08:00
Timi 1f5c80cd7d feat(recycle): add customer recycle amount for create order 2026-11-13 21:14:26 +08:00
Timi 0f0e783ad9 style(recycle): fix select recycle rule popup height 2026-11-13 19:25:02 +08:00
Timi fee05df8e4 fix(order): recycle amount for order detail hero 2026-11-13 19:21:57 +08:00
Timi e97f47475c feat(recycle): support quick fulfillment for recycle order 2026-11-13 19:06:09 +08:00
Timi dbde331b8a fix(recycle): recycle photo for rule list 2026-11-13 16:59:44 +08:00
Timi 288114103f style(system): remove percent value for downloading button 2026-11-13 16:52:22 +08:00
Timi af1c95c8dd fix(system): app update notify 2026-11-13 16:50:16 +08:00
Timi 3e2e8ece49 style(system): agreement 2026-11-13 15:11:53 +08:00
Timi 7cb4836b40 feat(system): app update log 2026-11-13 15:05:20 +08:00
Timi 04ad331e8d feat(user agreement): show on not read when trigger login/register 2026-11-13 12:16:33 +08:00
75 changed files with 3119 additions and 1113 deletions
+166 -1
View File
@@ -51,6 +51,89 @@ jobs:
echo "publish=false" >> $GITHUB_OUTPUT echo "publish=false" >> $GITHUB_OUTPUT
fi fi
# 从 CHANGELOG.md 提取当前版本的说明,落到 release-note.txt
# 用文件而不是 step output 传递:note 是多行文本,多行 output 在各版本 runner 上行为不一致
- name: Resolve release note
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
if [ ! -f CHANGELOG.md ]; then
echo "WARN: 缺少 CHANGELOG.md,本次发布不带变更说明"
: > release-note.txt
exit 0
fi
node --input-type=module <<'NODE'
import fs from "node:fs";
const version = process.env.VERSION;
const heading = "## v" + version;
const lines = fs.readFileSync("CHANGELOG.md", "utf8").split(/\r?\n/);
const start = lines.findIndex(line => line.trim() === heading);
if (start < 0) {
console.error("WARN: CHANGELOG.md 中没有 " + heading + ",本次发布不带变更说明");
fs.writeFileSync("release-note.txt", "");
process.exit(0);
}
const LIMIT = 480;
const picked = [];
let inComment = false;
for (let i = start + 1; i < lines.length; i += 1) {
const raw = lines[i];
if (/^##\s/.test(raw)) {
break;
}
// 跳过 HTML 注释,避免注释内容占掉长度
if (inComment) {
if (raw.includes("-->")) {
inComment = false;
}
continue;
}
if (raw.includes("<!--")) {
if (!raw.includes("-->")) {
inComment = true;
}
continue;
}
if (raw.trim() === "") {
// 连续空行压成一个,只用于分隔段落
if (picked.length > 0 && picked[picked.length - 1] !== "") {
picked.push("");
}
continue;
}
// 去掉行尾空白,保留行首缩进(嵌套列表)
picked.push(raw.replace(/\s+$/, ""));
}
while (picked.length > 0 && picked[picked.length - 1] === "") {
picked.pop();
}
if (picked.length === 0) {
console.error("WARN: " + heading + " 下没有内容,本次发布不带变更说明");
}
// 按行累积到上限,不切半行,避免出现断句
const kept = [];
let total = 0;
for (const line of picked) {
const length = Array.from(line).length + (kept.length > 0 ? 1 : 0);
if (LIMIT < total + length) {
console.error("WARN: 内容超过 " + LIMIT + " 字,截断到第 " + kept.length + " 行");
break;
}
kept.push(line);
total += length;
}
// 尖括号转义:note 最终走 v-html 渲染,不能让 CHANGELOG 里的 HTML 被执行
const note = kept.join("\n").replace(/</g, "&lt;");
fs.writeFileSync("release-note.txt", note);
console.log("变更说明(" + Array.from(note).length + " 字):\n" + (note === "" ? "(空)" : note));
NODE
- name: Configure nexus auth - name: Configure nexus auth
env: env:
NEXUS_USERNAME: ${{ secrets.NEXUS_USERNAME }} NEXUS_USERNAME: ${{ secrets.NEXUS_USERNAME }}
@@ -149,13 +232,17 @@ jobs:
ARTIFACT_SIZE: ${{ steps.bundle.outputs.size }} ARTIFACT_SIZE: ${{ steps.bundle.outputs.size }}
SHA256: ${{ steps.bundle.outputs.sha256 }} SHA256: ${{ steps.bundle.outputs.sha256 }}
ATTACHMENT_ID: ${{ steps.upload.outputs.attachment_id }} ATTACHMENT_ID: ${{ steps.upload.outputs.attachment_id }}
NOTE_FILE: release-note.txt
run: | run: |
if [ -z "$PRODUCT_ID" ]; then if [ -z "$PRODUCT_ID" ]; then
echo "FAIL: 缺少 vars.APP_PRODUCT_ID" echo "FAIL: 缺少 vars.APP_PRODUCT_ID"
exit 1 exit 1
fi fi
payload=$(node -e " payload=$(node -e "
const fs = require('fs');
const minCode = Number(process.env.MIN_VERSION_CODE || '1'); const minCode = Number(process.env.MIN_VERSION_CODE || '1');
const noteFile = process.env.NOTE_FILE || 'release-note.txt';
const note = fs.existsSync(noteFile) ? fs.readFileSync(noteFile, 'utf8') : '';
process.stdout.write(JSON.stringify({ process.stdout.write(JSON.stringify({
productId: process.env.PRODUCT_ID, productId: process.env.PRODUCT_ID,
kind: 'BUNDLE', kind: 'BUNDLE',
@@ -164,7 +251,7 @@ jobs:
attachmentId: process.env.ATTACHMENT_ID, attachmentId: process.env.ATTACHMENT_ID,
artifactSize: Number(process.env.ARTIFACT_SIZE), artifactSize: Number(process.env.ARTIFACT_SIZE),
sha256: process.env.SHA256, sha256: process.env.SHA256,
note: 'CI 构建 ${{ github.sha }}'.slice(0, 500) note
})); }));
") ")
response=$(curl -sS -X POST "$API_BASE_URL/app/release/create" \ response=$(curl -sS -X POST "$API_BASE_URL/app/release/create" \
@@ -198,6 +285,77 @@ jobs:
-H "Token: $API_TOKEN" -H "Token: $API_TOKEN"
echo "OK: 已发布到 stable" echo "OK: 已发布到 stable"
# 打 tag 的时机是「上线成功」而不是「PR 合并」:草稿发布和失败发布都不该留下版本标记。
# Gitea 建 release 会顺带创建 tag,所以不需要单独 git push refs/tags。
- name: Tag release
if: ${{ steps.version.outputs.publish == 'true' }}
env:
GITEA_TOKEN: ${{ secrets.RUNNER_TOKEN }}
GITEA_SERVER_URL: ${{ github.server_url }}
GITEA_INTERNAL_URL: ${{ vars.TIMI_GITEA_INTERNAL_URL }}
GITEA_REPOSITORY: ${{ github.repository }}
VERSION: ${{ steps.version.outputs.version }}
TARGET: ${{ github.sha }}
NOTE_FILE: release-note.txt
MAX_RETRIES: 3
RETRY_DELAY: 10
run: |
if [ -z "$GITEA_TOKEN" ]; then
echo "FAIL: 缺少 secrets.RUNNER_TOKEN,无法创建 tag"
exit 1
fi
if [ -n "$GITEA_INTERNAL_URL" ]; then
api_base_url="$GITEA_INTERNAL_URL"
else
api_base_url="$GITEA_SERVER_URL"
fi
api_url="$api_base_url/api/v1/repos/$GITEA_REPOSITORY/releases"
# 用 node 拼 payload:release note 是多行 markdown,手拼 JSON 会炸
payload=$(node -e "
const fs = require('fs');
const file = process.env.NOTE_FILE;
const note = file && fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
process.stdout.write(JSON.stringify({
tag_name: 'v' + process.env.VERSION,
name: 'v' + process.env.VERSION,
target_commitish: process.env.TARGET,
draft: false,
prerelease: false,
body: note
}));
")
attempt=1
while [ $attempt -le $MAX_RETRIES ]; do
echo "[Create release] 第 $attempt/$MAX_RETRIES 次"
http_code=$(curl -sS -o /tmp/release.json -w "%{http_code}" -X POST "$api_url" \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/json" \
--connect-timeout 30 \
--max-time 60 \
-d "$payload" 2>/dev/null) || http_code="000"
echo "HTTP Status: $http_code"
# 409 表示 tag 与 release 已存在(重跑流水线时的正常情况)
if [ "$http_code" = "201" ] || [ "$http_code" = "409" ]; then
echo "OK: v$VERSION 的 tag 与 release 已就绪"
head -c 400 /tmp/release.json
echo
exit 0
fi
if [ $attempt -lt $MAX_RETRIES ]; then
echo "重试中,${RETRY_DELAY}s 后继续"
sleep $RETRY_DELAY
fi
attempt=$((attempt + 1))
done
echo "FAIL: 创建 tag / release 失败(接口或 token 权限问题)"
exit 1
- name: Summary - name: Summary
run: | run: |
if [ "${{ steps.version.outputs.publish }}" = "true" ]; then if [ "${{ steps.version.outputs.publish }}" = "true" ]; then
@@ -207,6 +365,13 @@ jobs:
echo "需要上线时调用 /app/release/publish?releaseId=${{ steps.create.outputs.release_id }}" echo "需要上线时调用 /app/release/publish?releaseId=${{ steps.create.outputs.release_id }}"
fi fi
echo "-----" echo "-----"
echo "变更说明(写入 App 更新日志):"
if [ -s release-note.txt ]; then
cat release-note.txt
else
echo "(空)CHANGELOG.md 中没有 v${{ steps.version.outputs.version }} 一节,本次发布不带更新说明"
fi
echo "-----"
echo "热更兼容最低原生版本:${{ vars.APP_MIN_VERSION_CODE }}" echo "热更兼容最低原生版本:${{ vars.APP_MIN_VERSION_CODE }}"
echo "只有原生壳升级(增删原生插件)时才需要提高这个值,纯 JS 改动不用管" echo "只有原生壳升级(增删原生插件)时才需要提高这个值,纯 JS 改动不用管"
echo "本次产物大小:${{ steps.bundle.outputs.size }} 字节" echo "本次产物大小:${{ steps.bundle.outputs.size }} 字节"
+2
View File
@@ -131,6 +131,8 @@ dist
dist-ssr dist-ssr
coverage coverage
*.local *.local
# CI 从 CHANGELOG.md 提取的中间产物,发版 job 内生成
release-note.txt
# ---> WorkBuddy 本地工作目录 # ---> WorkBuddy 本地工作目录
# 内含 AI 工作记忆与每日日志:写明本机绝对路径与调试上下文,且每次会话都在追加, # 内含 AI 工作记忆与每日日志:写明本机绝对路径与调试上下文,且每次会话都在追加,
+71
View File
@@ -0,0 +1,71 @@
# 更新日志
<!--
本文件用于 App 内的「版本更新」展示。
CI 规则(.gitea/workflows/release.yml):
1. 按 `## v<版本号>` 精确匹配 package.json 里的 version,例如 `## v1.3.0`
2. 提取该节的全部内容(到下一个 `## ` 为止),写入 app_release.note
3. 最多 480 字,超出按整行截断,不切半句;缺失该节时不阻断发版,只打印警告
写作约定:
1. 只写用户能感知的变化:新增功能、行为变更、影响使用的修复。
重构、依赖升级、CI 调整、内部样式整理不用写
2. 推荐用 `- ` 列表,一条一行。也支持段落、`###` 小标题、加粗,
前端按 markdown 渲染;HTML 标签会被转义成文本显示
3. 整节控制在 480 字以内,超出部分会被丢掉
4. 面向店员,不写文件路径、组件名、接口名
5. 已发布的段落不可修改:note 是发版瞬间的快照,改文件不会影响线上,
需要更正请发补丁版本
-->
## v1.5.0
### 调整
- 应用内可以直接下载并安装新版本,不再跳转浏览器;系统提示时请允许本应用安装未知应用
- 新版本安装完成后登录状态和数据都会保留
## v1.4.0
### 新增
- 自动生成客户生日跟进提醒。在启用功能,配置负责人且客户保存了出生日期时,系统将会在生日前 7 天生成跟进提醒
### 调整
- 现在产生库存流水、订单的产品 SKU 不再允许修改基础单位
- 平板横屏下左侧导航可点击回到根页面
### 修复
- APK 端无法显示更新日志
- APK 端没有完全全屏(仍然避让状态栏)
- 部分页面样式
## v1.3.2
### 调整
- 应用内支持下载并安装新的安装包,按提示覆盖安装即可,账号和已有数据都会保留
## v1.3.1
### 新增
- 系统更新日志
- 回收兑换单支持快速履约
- 新增回收兑换单时,选择了客户、回收物后显示客户可用额度
- 库存日历的流水增加汇总,支持切换单位
- 客户回收物列表
### 调整
- 更新提醒不再是按钮,而是通知栏
- 回收兑换单的详情不再显示无意义的金额
### 修复
- 兑换模板列表没有显示兑换物照片
- 登录/注册页在平板模式下用户协议窗口过小
- 部分页面样式
+35 -3
View File
@@ -40,7 +40,15 @@ grep versionCode android/app/build.gradle
- 增删插件后执行 `pnpm exec cap sync android` - 增删插件后执行 `pnpm exec cap sync android`
- 确认 `capacitor.config.ts` 无遗漏 - 确认 `capacitor.config.ts` 无遗漏
- 本地 `pnpm run android:apk` 打一个包,装机自测 - **打壳前先 `pnpm run android:sync:prod` 重建资源**:它用 `.env.production` 构建并会清掉
残留的 `VITE_API_BASE_URL`。真机调试用的 `android:sync:dev`(或 `android:open`)会把局域网地址
写进 `dist` 和 `android/app/src/main/assets/public`,直接拿去打包就会打出一个连内网的正式包
- 打完核对:`aapt2 dump badging` 的 versionCode、`apksigner verify --print-certs` 的证书,
以及解包 grep 接口地址(内网地址必须为 0 次)
- 用 Android Studio 打包,**签名必须与线上包一致**:线上 1.0.0 用的是
`twa/android.keystore`(alias `gao-customer`,证书 `CN=yeyu` / SHA-256 `3E:9C:CC:8A:…`)。
签名不一致时系统会拒绝覆盖安装,老用户只能卸载重装
- `pnpm run android:apk` 走的是 `assembleDebug`,签的是本机 debug key,**不能用于发版**
### 3. 提高 CI 的兼容基线 ### 3. 提高 CI 的兼容基线
@@ -52,14 +60,38 @@ APP_MIN_VERSION_CODE = <第 1 步的新 versionCode>
**这一步最容易漏**。漏了不会报错,只会在老壳用户那里悄悄出问题。 **这一步最容易漏**。漏了不会报错,只会在老壳用户那里悄悄出问题。
注意顺序:一旦抬高,此后创建的 BUNDLE 记录都会带上新的下限,老壳再也拿不到。
要给老壳发过渡补丁包,必须**先发补丁、再抬基线**。
### 4. 发布原生包 ### 4. 发布原生包
用同一个 versionCode 发一条 `kind = NATIVE` 的发布记录并上线。老壳用户打开 App 会收到强制更新提示,装完才有新壳。 用同一个 versionCode 发一条 `kind = NATIVE` 的发布记录并上线。通道是单指针,这条记录一上线,
热更就停止下发——老壳拿到的 `check` 响应会带 `shell: true` 和安装包地址,新壳因为
`versionCode` 已达标则什么都不下发。所以新壳装完后必须把通道切回最新的 BUNDLE 记录。
### 客户端怎么升级外壳
外壳是 APK,热更(JS)改不了它,所以升级动作分两步:
1. 服务端在 `check` 响应里带 `shell: true`(`AppUpdateCheckResponse.shell`),客户端据此走安装包分支。
**这个字段不能叫 `kind`**:Capgo 插件把 `kind` 当作错误响应标记。
2. 客户端把安装包地址交给系统浏览器(`location.assign`)——Capacitor 对非同源地址走
`Bridge.launchIntent`,用 `ACTION_VIEW` 外抛。下载和安装由浏览器发起,应用不需要
`REQUEST_INSTALL_PACKAGES`,所以 1.0.0 老壳也能用。
要做到「App 内下载、直接拉起安装器」才需要原生改动:`REQUEST_INSTALL_PACKAGES` 权限 +
FileProvider + `ACTION_VIEW` 指向本地 APK,那是下一个壳的事。
### 5. 验证 ### 5. 验证
```bash ```bash
# 老壳应被拦住(version_code 填上一版的 code) # 通道指向 NATIVE 时:老壳应拿到安装包,新壳应无更新
curl -X POST <API>/app/update/check \
-H "Content-Type: application/json" \
-d '{"platform":"android","app_id":"com.imyeyu.gao.customer","version_name":"<当前版本>","version_code":"<旧 code>","device_id":"test"}'
# 期望:shell = true,url 指向 APK
# 通道切回 BUNDLE 后:低于 minVersionCode 的老壳应被拦住
curl -X POST <API>/app/update/check \ curl -X POST <API>/app/update/check \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{"platform":"android","app_id":"com.imyeyu.gao.customer","version_name":"<当前版本>","version_code":"<旧 code>","device_id":"test"}' -d '{"platform":"android","app_id":"com.imyeyu.gao.customer","version_name":"<当前版本>","version_code":"<旧 code>","device_id":"test"}'
+2 -2
View File
@@ -7,8 +7,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 1 versionCode 3
versionName "1.0.0" versionName "1.1.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.
+1
View File
@@ -38,6 +38,7 @@
<!-- Permissions --> <!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<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" />
</manifest> </manifest>
@@ -1,15 +1,29 @@
package com.imyeyu.gao.customer; package com.imyeyu.gao.customer;
import android.content.pm.ApplicationInfo; import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings; import android.webkit.WebSettings;
import androidx.activity.OnBackPressedCallback; import androidx.activity.OnBackPressedCallback;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import com.getcapacitor.BridgeActivity; import com.getcapacitor.BridgeActivity;
import com.imyeyu.gao.customer.shellupdater.ShellUpdaterPlugin;
import java.util.Locale;
public class MainActivity extends BridgeActivity { public class MainActivity extends BridgeActivity {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
registerPlugin(ShellUpdaterPlugin.class);
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
applyEdgeToEdge();
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override @Override
public void handleOnBackPressed() { public void handleOnBackPressed() {
@@ -26,4 +40,67 @@ public class MainActivity extends BridgeActivity {
getBridge().getWebView().getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); getBridge().getWebView().getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
} }
} }
/**
* 让窗口真正 edge-to-edge,安全区由 Web 侧按 --tui-safe-* 补齐。
*
* 这里必须自己接管 insets:Capacitor 8 的 SystemBars 只认 WebView 内核版本
* (getWebViewMajorVersion() >= 140 才认为内核能自己处理安全区,见 SystemBars.java),
* 低内核机型上它会一边给 DecorView 加状态栏高度的 padding 把 WebView 缩回去,
* 一边又把真实的安全区注入成 CSS 变量,结果顶部被让了两次。
* 这个监听器在 Bridge 初始化之后注册,直接覆盖掉它:padding 归零、变量照旧注入。
*/
private void applyEdgeToEdge() {
Window window = getWindow();
WindowCompat.setDecorFitsSystemWindows(window, false);
window.setStatusBarColor(Color.TRANSPARENT);
window.setNavigationBarColor(Color.TRANSPARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
WindowManager.LayoutParams attributes = window.getAttributes();
attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
window.setAttributes(attributes);
}
View decorView = window.getDecorView();
ViewCompat.setOnApplyWindowInsetsListener(decorView, (view, windowInsets) -> {
view.setPadding(0, 0, 0, 0);
Insets systemBars = windowInsets.getInsets(
WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout()
);
boolean keyboardVisible = windowInsets.isVisible(WindowInsetsCompat.Type.ime());
injectSafeArea(systemBars, keyboardVisible);
return windowInsets;
});
ViewCompat.requestApplyInsets(decorView);
}
/**
* 把系统栏尺寸折算成 CSS 像素后写进 html 的 CSS 变量。
*
* 键盘弹出时底部归零,否则 Web 侧的安全区会和键盘顶起来的区域叠加。
*/
private void injectSafeArea(Insets systemBars, boolean keyboardVisible) {
if (getBridge() == null || getBridge().getWebView() == null) {
return;
}
float density = getResources().getDisplayMetrics().density;
int top = Math.round(systemBars.top / density);
int right = Math.round(systemBars.right / density);
int bottom = Math.round((keyboardVisible ? 0 : systemBars.bottom) / density);
int left = Math.round(systemBars.left / density);
String script = String.format(
Locale.US,
"document.documentElement.style.setProperty('--safe-area-inset-top','%dpx');" +
"document.documentElement.style.setProperty('--safe-area-inset-right','%dpx');" +
"document.documentElement.style.setProperty('--safe-area-inset-bottom','%dpx');" +
"document.documentElement.style.setProperty('--safe-area-inset-left','%dpx');",
top,
right,
bottom,
left
);
getBridge().getWebView().evaluateJavascript(script, null);
}
} }
@@ -0,0 +1,151 @@
package com.imyeyu.gao.customer.shellupdater;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.core.content.FileProvider;
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.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
/// 应用外壳下载与安装
@CapacitorPlugin(name = "ShellUpdater")
public class ShellUpdaterPlugin extends Plugin {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final AtomicBoolean downloading = new AtomicBoolean(false);
private File directory;
private boolean awaitingSettings;
@Override
public void load() {
directory = new File(getContext().getCacheDir(), "shell-updates");
executor.execute(() -> {
File[] files = directory.listFiles();
if (files == null) return;
// 只清 6 小时前的残留:安装期间进程可能被杀后重启,立刻删除会让安装器读不到文件
long cutoff = System.currentTimeMillis() - 6 * 60 * 60 * 1000L;
for (File file : files) {
if (file.isFile() && file.lastModified() < cutoff) file.delete();
}
});
}
/// 检查安装未知应用权限
@PluginMethod
public void canInstall(PluginCall call) {
JSObject result = new JSObject();
result.put("allowed", Build.VERSION.SDK_INT < Build.VERSION_CODES.O || getContext().getPackageManager().canRequestPackageInstalls());
call.resolve(result);
}
/// 打开本应用的安装权限设置
@PluginMethod
public void openInstallSettings(PluginCall call) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getContext().getPackageName()));
awaitingSettings = true;
getActivity().startActivity(intent);
}
call.resolve();
} catch (Exception e) {
call.reject("无法打开安装权限设置", e);
}
}
/// 下载并校验安装包,然后打开系统安装器
@PluginMethod
public void downloadAndInstall(PluginCall call) {
String url = call.getString("url");
String sha256 = call.getString("sha256");
String fileName = call.getString("fileName");
if (url == null || sha256 == null || !sha256.matches("(?i)[0-9a-f]{64}") || fileName == null || !fileName.matches("[a-zA-Z0-9._-]+\\.apk")) {
call.reject("安装包参数无效");
return;
}
if (!downloading.compareAndSet(false, true)) {
call.reject("安装包正在下载");
return;
}
executor.execute(() -> download(call, url, sha256, fileName));
}
private void download(PluginCall call, String address, String expected, String fileName) {
File file = new File(directory, fileName);
HttpURLConnection connection = null;
try {
if (!directory.exists() && !directory.mkdirs()) throw new Exception("无法创建下载目录");
URL url = new URL(address);
if (!"https".equalsIgnoreCase(url.getProtocol()) && !"http".equalsIgnoreCase(url.getProtocol())) throw new Exception("下载地址无效");
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(15000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) throw new Exception("安装包下载失败");
long total = connection.getContentLengthLong();
long received = 0;
MessageDigest digest = MessageDigest.getInstance("SHA-256");
try (InputStream input = connection.getInputStream(); FileOutputStream output = new FileOutputStream(file)) {
byte[] buffer = new byte[32768];
int size;
while ((size = input.read(buffer)) != -1) {
output.write(buffer, 0, size);
digest.update(buffer, 0, size);
received += size;
JSObject progress = new JSObject();
progress.put("received", received);
progress.put("total", total);
progress.put("percent", 0 < total ? (int) Math.min(100, received * 100 / total) : 0);
notifyListeners("downloadProgress", progress);
}
}
StringBuilder actual = new StringBuilder();
for (byte b : digest.digest()) actual.append(String.format(Locale.ROOT, "%02x", b & 255));
if (!actual.toString().equalsIgnoreCase(expected)) throw new Exception("安装包校验失败");
Uri uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getActivity().runOnUiThread(() -> {
try {
getActivity().startActivity(intent);
call.resolve();
} catch (Exception e) {
call.reject("无法打开系统安装器", e);
}
});
} catch (Exception e) {
file.delete();
call.reject("安装包下载或校验失败", e);
} finally {
if (connection != null) connection.disconnect();
downloading.set(false);
}
}
@Override
protected void handleOnResume() {
if (awaitingSettings) {
awaitingSettings = false;
notifyListeners("resume", new JSObject());
}
}
@Override
protected void handleOnDestroy() {
executor.shutdown();
}
}
-1
View File
@@ -45,7 +45,6 @@ declare module 'vue' {
SegmentedSlider: typeof import('./src/components/SegmentedSlider.vue')['default'] SegmentedSlider: typeof import('./src/components/SegmentedSlider.vue')['default']
StoreRemoveDialog: typeof import('./src/components/StoreRemoveDialog.vue')['default'] StoreRemoveDialog: typeof import('./src/components/StoreRemoveDialog.vue')['default']
TagSelector: typeof import('./src/components/TagSelector.vue')['default'] TagSelector: typeof import('./src/components/TagSelector.vue')['default']
TAvatar: typeof import('tdesign-mobile-vue')['Avatar']
TBadge: typeof import('tdesign-mobile-vue')['Badge'] TBadge: typeof import('tdesign-mobile-vue')['Badge']
TButton: typeof import('tdesign-mobile-vue')['Button'] TButton: typeof import('tdesign-mobile-vue')['Button']
TCalendar: typeof import('tdesign-mobile-vue')['Calendar'] TCalendar: typeof import('tdesign-mobile-vue')['Calendar']
+6 -4
View File
@@ -1,7 +1,7 @@
{ {
"name": "gao-customer-h5", "name": "gao-customer-h5",
"private": true, "private": true,
"version": "1.3.0", "version": "1.5.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite --host", "dev": "vite --host",
@@ -14,9 +14,11 @@
"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",
"type-check:publish": "vue-tsc -p tsconfig.publish.json --noEmit", "type-check:publish": "vue-tsc -p tsconfig.publish.json --noEmit",
"android:sync": "pnpm run build && cap sync android", "android:sync:dev": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-sync.ps1 -Mode dev",
"android:sync:prod": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-sync.ps1 -Mode 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 && cd android && gradlew.bat assembleDebug" "android:apk": "pnpm run android:sync:prod && cd android && gradlew.bat assembleDebug"
}, },
"dependencies": { "dependencies": {
"@capacitor/android": "^8", "@capacitor/android": "^8",
@@ -30,7 +32,7 @@
"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.1.1", "timi-tdesign-mobile": "^1.3.1",
"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 -5
View File
@@ -47,8 +47,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.1.1 specifier: ^1.3.1
version: 1.1.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.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-ts: timi-ts:
specifier: ^1.0.0 specifier: ^1.0.0
version: 1.0.0 version: 1.0.0
@@ -2748,8 +2748,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.1.1: timi-tdesign-mobile@1.3.1:
resolution: {integrity: sha512-aR6SKu8zVbaqHRJHRtria3amvp9UKS6jTT99FNei38ZrP1sJDBsvCoQmWi0xzUD3F/wkGnSECWWrJQToqso6PQ==} resolution: {integrity: sha512-6hz7MSqseCUyyJzRiyQjymMDfSZ3kJrFP6J5DxHpE1pJ8xeByCzKgELS4CnO4187mqPEx46TtF03qB9XS4Mpuw==}
engines: {node: '>=20.0.0'} engines: {node: '>=20.0.0'}
peerDependencies: peerDependencies:
vue: ^3.5.0 vue: ^3.5.0
@@ -5849,7 +5849,7 @@ snapshots:
dependencies: dependencies:
readable-stream: 3.6.2 readable-stream: 3.6.2
timi-tdesign-mobile@1.1.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.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)):
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))
+2 -8
View File
@@ -1,13 +1,7 @@
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
$env:VITE_API_BASE_URL = if ($env:ANDROID_API_BASE_URL) { # 真机调试固定用开发环境构建,环境变量与构建流程统一收在 android-sync.ps1
$env:ANDROID_API_BASE_URL & pnpm run android:sync:dev
} else {
"http://10.0.2.2:18091"
}
Write-Host "Android 调试接口地址:$env:VITE_API_BASE_URL"
& pnpm run android:sync
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& pnpm exec cap open android & pnpm exec cap open android
+26
View File
@@ -0,0 +1,26 @@
param(
[ValidateSet("dev", "prod")]
[string]$Mode = "prod"
)
$ErrorActionPreference = "Stop"
if ($Mode -eq "dev") {
# 调试包打局域网后端:真机访问不到 localhost,模拟器才用 10.0.2.2
$env:VITE_API_BASE_URL = if ($env:ANDROID_API_BASE_URL) {
$env:ANDROID_API_BASE_URL
} else {
"http://192.168.11.14:18091"
}
Write-Host "接口地址(开发):$env:VITE_API_BASE_URL"
} else {
# 生产包只能用 .env.production,父进程残留的同名变量会覆盖文件配置,先清掉
Remove-Item Env:VITE_API_BASE_URL -ErrorAction SilentlyContinue
Write-Host "接口地址(生产):取 .env.production"
}
& pnpm run build
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& pnpm exec cap sync android
exit $LASTEXITCODE
+23 -3
View File
@@ -3,21 +3,38 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { Capacitor, SystemBars, SystemBarsStyle } from "@capacitor/core";
import { useGlobalUIStore } from "@/store/globalUI"; import { useGlobalUIStore } from "@/store/globalUI";
import { useSettingStore } from "@/store/settingStore"; import { useSettingStore } from "@/store/settingStore";
const globalUIStore = useGlobalUIStore(); const globalUIStore = useGlobalUIStore();
const settingStore = useSettingStore(); const settingStore = useSettingStore();
const darkMediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const prefersDark = ref(darkMediaQuery.matches);
const resolvedThemeMode = computed(() => { const resolvedThemeMode = computed<"light" | "dark">(() => {
if (globalUIStore.themeMode === "system") { if (globalUIStore.themeMode === "system") {
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); return prefersDark.value ? "dark" : "light";
return mediaQuery.matches ? "dark" : "light";
} }
return globalUIStore.themeMode; return globalUIStore.themeMode;
}); });
async function syncSystemBars(themeMode: "light" | "dark"): Promise<void> {
if (!Capacitor.isNativePlatform()) {
return;
}
await SystemBars.setStyle({
// DARK 表示深色系统栏配浅色图标,所以深色主题要用它
style: themeMode === "dark" ? SystemBarsStyle.Dark : SystemBarsStyle.Light
});
}
function handleSystemThemeChange(event: MediaQueryListEvent): void {
prefersDark.value = event.matches;
}
async function unlockSoundOnUserGesture(): Promise<void> { async function unlockSoundOnUserGesture(): Promise<void> {
await settingStore.unlockSoundPlayers(); await settingStore.unlockSoundPlayers();
} }
@@ -28,6 +45,7 @@ watch(
const rootElement = document.documentElement; const rootElement = document.documentElement;
rootElement.classList.toggle("theme-dark", themeMode === "dark"); rootElement.classList.toggle("theme-dark", themeMode === "dark");
rootElement.dataset.theme = themeMode; rootElement.dataset.theme = themeMode;
void syncSystemBars(themeMode).catch(() => undefined);
}, },
{ immediate: true } { immediate: true }
); );
@@ -54,10 +72,12 @@ watch(
onMounted(() => { onMounted(() => {
settingStore.loadSoundPlayers(); settingStore.loadSoundPlayers();
darkMediaQuery.addEventListener("change", handleSystemThemeChange);
window.addEventListener("pointerdown", unlockSoundOnUserGesture, { once: true }); window.addEventListener("pointerdown", unlockSoundOnUserGesture, { once: true });
}); });
onUnmounted(() => { onUnmounted(() => {
darkMediaQuery.removeEventListener("change", handleSystemThemeChange);
window.removeEventListener("pointerdown", unlockSoundOnUserGesture); window.removeEventListener("pointerdown", unlockSoundOnUserGesture);
}); });
</script> </script>
+31
View File
@@ -0,0 +1,31 @@
import { axios } from "timi-web-api";
import type { AppUpdateNotesQuery, AppUpdateNotesResult } from "@/types/AppUpdate";
const URI = "/app/update";
/**
* 查询更新日志
*
* 区间为「当前版本 → 通道当前版本」,与灰度无关,免登录态
*
* @param query 查询参数,versionName 传当前运行的 Web 包版本
* @returns 变更说明列表,按版本号从新到旧
*/
async function notes(query: AppUpdateNotesQuery): Promise<AppUpdateNotesResult> {
const { appId, versionName, versionCode, platform, channel } = query;
// 后端按 Capgo 插件的上报协议接收下划线字段,只在这一层转换
/* eslint-disable camelcase */
const payload = {
app_id: appId,
version_name: versionName,
version_code: versionCode,
platform,
channel
};
/* eslint-enable camelcase */
return await axios.post(`${URI}/notes`, payload);
}
export default {
notes
};
+15
View File
@@ -3,6 +3,7 @@ import type {
OrderTransaction, OrderTransaction,
RecycleAccount, RecycleAccount,
RecycleAccountAdjustRequest, RecycleAccountAdjustRequest,
RecycleCustomerAccountPage,
RecycleExchange, RecycleExchange,
RecycleExchangeCreateRequest, RecycleExchangeCreateRequest,
RecycleExchangeDetail, RecycleExchangeDetail,
@@ -117,6 +118,18 @@ async function accountList(customerId: string): Promise<RecycleAccount[]> {
}); });
} }
/** 按客户分页查询有余额的回收物及全门店汇总。 */
async function accountCustomers(offset: number, limit: number, recycleItemId?: string, keyword?: string, customerIds?: string[]): Promise<RecycleCustomerAccountPage> {
return await axios.post(`${ACCOUNT_URI}/customers`, undefined, {
params: { storeId: getCurrentStoreId() || undefined, offset, limit, recycleItemId: recycleItemId || undefined, keyword: keyword || undefined, customerIds: customerIds?.length ? customerIds.join(",") : undefined }
});
}
/** 获取额度查询可用的回收物选项。 */
async function accountItems(): Promise<RecycleItem[]> {
return await axios.post(`${ACCOUNT_URI}/items`, undefined, { params: { storeId: getCurrentStoreId() || undefined } });
}
/** 额度流水,服务端当前最多返回 100 条。 */ /** 额度流水,服务端当前最多返回 100 条。 */
async function accountLedger(customerId: string): Promise<RecycleLedger[]> { async function accountLedger(customerId: string): Promise<RecycleLedger[]> {
return await axios.post(`${ACCOUNT_URI}/ledger`, undefined, { return await axios.post(`${ACCOUNT_URI}/ledger`, undefined, {
@@ -244,6 +257,8 @@ export default {
create, create,
detail, detail,
accountList, accountList,
accountCustomers,
accountItems,
accountLedger, accountLedger,
accountAdjust, accountAdjust,
yieldList, yieldList,
+56
View File
@@ -0,0 +1,56 @@
import { axios } from "timi-web-api";
/** 门店配置项。 */
export type StoreSetting = {
bizType?: string;
bizId?: string;
code?: string;
description?: string;
value?: string;
valueType?: string;
valueArgs?: unknown;
};
/** 门店配置保存项。 */
export type StoreSettingPayload = {
code: string;
value: string;
};
const BASE_URI = "/gao/store/setting";
/** 客户生日提醒开关。 */
export const BIRTHDAY_REMINDER_ENABLED = "CUSTOMER_BIRTHDAY_REMINDER_ENABLED";
/** 客户生日提醒负责人。 */
export const BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID = "CUSTOMER_BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID";
/**
* 门店配置接口
*
* 门店由后端按登录用户所属门店决定,前端不传 storeId
*/
const StoreSettingAPI = {
/**
* 查询当前门店配置
*
* @param codeList 配置代码列表,为空返回全部
* @returns 配置代码与配置的映射
*/
async map(codeList?: string[]): Promise<Record<string, StoreSetting>> {
return await axios.post(`${BASE_URI}/map`, codeList ?? []);
},
/**
* 保存当前门店配置
*
* 合并写入,未提交的配置项保留
*
* @param settingList 配置列表
*/
async update(settingList: StoreSettingPayload[]): Promise<void> {
await axios.post(`${BASE_URI}/update`, settingList);
}
};
export default StoreSettingAPI;
+1 -1
View File
@@ -119,7 +119,7 @@ html.theme-dark body {
min-height: 0; min-height: 0;
overflow-x: hidden; overflow-x: hidden;
overflow-y: auto; overflow-y: auto;
padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 1rem); padding-bottom: calc(var(--tui-safe-bottom, 0px) + 1rem);
-webkit-overflow-scrolling: touch; -webkit-overflow-scrolling: touch;
.t-pull-down-refresh__track { .t-pull-down-refresh__track {
+1 -1
View File
@@ -361,7 +361,7 @@ onUnmounted(() => {
flex: 1; flex: 1;
overflow: auto; overflow: auto;
min-height: 0; min-height: 0;
padding-bottom: env(safe-area-inset-bottom, 0); padding-bottom: var(--tui-safe-bottom, 0px);
} }
} }
+2 -2
View File
@@ -313,7 +313,7 @@ function toDateValue(date: Date): number {
.day-record-panel, .day-record-panel,
.filter-popup { .filter-popup {
gap: .875rem; gap: .875rem;
padding: 1rem 0 calc(1rem + env(safe-area-inset-bottom, 0)) 0; padding: 1rem 0 calc(1rem + var(--tui-safe-bottom, 0px)) 0;
display: flex; display: flex;
background: #f5f5f8; background: #f5f5f8;
border-radius: 1rem 1rem 0 0; border-radius: 1rem 1rem 0 0;
@@ -344,7 +344,7 @@ function toDateValue(date: Date): number {
} }
.filter-popup { .filter-popup {
padding: 1rem 1rem calc(1rem + env(safe-area-inset-bottom, 0)) 1rem; padding: 1rem 1rem calc(1rem + var(--tui-safe-bottom, 0px)) 1rem;
.popup-head, .popup-head,
.popup-body { .popup-body {
@@ -311,7 +311,7 @@ function updateSelectedSkuIdList(value: string[]): void {
flex: 1; flex: 1;
min-height: 0; min-height: 0;
overflow-y: auto; overflow-y: auto;
padding-bottom: env(safe-area-inset-bottom, 0); padding-bottom: var(--tui-safe-bottom, 0px);
.selector { .selector {
border-radius: 0; border-radius: 0;
+90 -11
View File
@@ -6,11 +6,30 @@ import { ref } from "vue";
/** 自动更新的存储键 */ /** 自动更新的存储键 */
export const AUTO_UPDATE_KEY = "app.autoUpdate"; export const AUTO_UPDATE_KEY = "app.autoUpdate";
/** Capacitor appId,与 capacitor.config.ts 保持一致 */
export const APP_ID = "com.imyeyu.gao.customer";
/**
* 服务端下发的更新信息
*
* 在插件协议基础上增加更新说明与外壳字段,插件会原样透传:
* note 是更新说明,shell 标记产物为安装包(外壳),mandatory 标记强制更新
*/
export type UpdateInfo = LatestVersion & {
note?: string;
shell?: boolean;
mandatory?: boolean;
shellUrl?: string;
shellVersion?: string;
shellChecksum?: string;
shellMandatory?: boolean;
};
// 模块级状态,页面与启动逻辑共享同一份 // 模块级状态,页面与启动逻辑共享同一份
const supported = Capacitor.isNativePlatform(); const supported = Capacitor.isNativePlatform();
const currentVersion = ref(""); const currentVersion = ref("");
const nativeVersion = ref(""); const nativeVersion = ref("");
const latest = ref<LatestVersion | null>(null); const latest = ref<UpdateInfo | null>(null);
const checking = ref(false); const checking = ref(false);
const downloading = ref(false); const downloading = ref(false);
const percent = ref(0); const percent = ref(0);
@@ -34,7 +53,7 @@ async function loadCurrent(): Promise<void> {
} }
/** 查询服务端最新版本 */ /** 查询服务端最新版本 */
async function check(): Promise<LatestVersion | null> { async function check(): Promise<UpdateInfo | null> {
if (!supported) { if (!supported) {
error.value = "仅在 App 内可用"; error.value = "仅在 App 内可用";
return null; return null;
@@ -42,9 +61,18 @@ async function check(): Promise<LatestVersion | null> {
checking.value = true; checking.value = true;
error.value = ""; error.value = "";
try { try {
const result = await CapacitorUpdater.getLatest(); const result: UpdateInfo = await CapacitorUpdater.getLatest();
latest.value = result; // 新协议的独立外壳地址优先,统一转换为页面已有的外壳更新格式
return result; const target: UpdateInfo = result.shellUrl ? {
...result,
url: result.shellUrl,
version: result.shellVersion ?? result.version,
checksum: result.shellChecksum,
mandatory: result.shellMandatory,
shell: true
} : result;
latest.value = target;
return target;
} catch (e) { } catch (e) {
error.value = e instanceof Error ? e.message : "检查更新失败"; error.value = e instanceof Error ? e.message : "检查更新失败";
return null; return null;
@@ -53,10 +81,34 @@ async function check(): Promise<LatestVersion | null> {
} }
} }
/** 是否发现新版本 */ /** 是否发现新版本(外壳更新不看版本号,只认服务端下发的地址) */
function hasUpdate(): boolean { function hasUpdate(): boolean {
const target = latest.value; const target = latest.value;
return Boolean(target?.url) && target?.version !== currentVersion.value; if (!target?.url) {
return false;
}
return Boolean(target.shell) || target.version !== currentVersion.value;
}
/** 是否为外壳更新,只能下载安装包覆盖安装,热更装不进去 */
function isShellUpdate(): boolean {
const target = latest.value;
return Boolean(target?.shell && target?.url);
}
/**
* 把安装包交给系统浏览器下载
*
* Capacitor 对非同源地址走 Bridge.launchIntent,用 ACTION_VIEW 外抛给浏览器,
* 安装动作由浏览器和系统安装器发起,应用自身不需要安装权限,所以老壳也能用
*/
function openShellDownload(): void {
const target = latest.value;
if (!target?.url) {
error.value = "没有可下载的版本";
return;
}
window.location.assign(target.url);
} }
/** 下载最新版本,只落盘不激活 */ /** 下载最新版本,只落盘不激活 */
@@ -66,6 +118,10 @@ async function download(): Promise<BundleInfo | null> {
error.value = "没有可下载的版本"; error.value = "没有可下载的版本";
return null; return null;
} }
if (target.shell) {
error.value = "外壳更新需要下载安装包";
return null;
}
downloading.value = true; downloading.value = true;
percent.value = 0; percent.value = 0;
error.value = ""; error.value = "";
@@ -92,7 +148,20 @@ async function download(): Promise<BundleInfo | null> {
/** 立即应用并重启 */ /** 立即应用并重启 */
async function apply(bundle: BundleInfo): Promise<void> { async function apply(bundle: BundleInfo): Promise<void> {
await CapacitorUpdater.set({ id: bundle.id }); error.value = "";
try {
await CapacitorUpdater.set({ id: bundle.id });
} catch (e) {
// 包目录已被清理或本身就是坏的(例如把安装包当热更包下下来),
// set 会报 id 不存在。不清理的话每次启动都卡在「已下载,重启生效」
try {
await CapacitorUpdater.delete({ id: bundle.id });
} catch {
// 包可能已经被插件清理
}
ready.value = null;
error.value = e instanceof Error ? e.message : "更新失败";
}
} }
/** 排队到下次启动应用 */ /** 排队到下次启动应用 */
@@ -100,6 +169,9 @@ async function defer(bundle: BundleInfo): Promise<void> {
await CapacitorUpdater.next({ id: bundle.id }); await CapacitorUpdater.next({ id: bundle.id });
} }
/** 可以应用的包状态:剩下的都是删除中或下载失败的残骸,set 会报 id 不存在 */
const USABLE_STATUS: Array<BundleInfo["status"]> = ["success", "pending"];
/** 查找已下载但尚未应用的版本 */ /** 查找已下载但尚未应用的版本 */
async function restorePending(): Promise<void> { async function restorePending(): Promise<void> {
if (!supported) { if (!supported) {
@@ -109,7 +181,7 @@ async function restorePending(): Promise<void> {
const [current, list] = await Promise.all([CapacitorUpdater.current(), CapacitorUpdater.list()]); const [current, list] = await Promise.all([CapacitorUpdater.current(), CapacitorUpdater.list()]);
const currentId = current.bundle?.id; const currentId = current.bundle?.id;
const pending = list.bundles const pending = list.bundles
.filter(bundle => bundle.id !== currentId) .filter(bundle => bundle.id !== currentId && USABLE_STATUS.includes(bundle.status))
.sort((a, b) => Date.parse(b.downloaded) - Date.parse(a.downloaded))[0]; .sort((a, b) => Date.parse(b.downloaded) - Date.parse(a.downloaded))[0];
ready.value = pending ?? null; ready.value = pending ?? null;
} catch { } catch {
@@ -137,6 +209,8 @@ export function useAppUpdate() {
loadCurrent, loadCurrent,
check, check,
hasUpdate, hasUpdate,
isShellUpdate,
openShellDownload,
download, download,
apply, apply,
defer, defer,
@@ -179,6 +253,7 @@ function promptUpdate(bundle: BundleInfo): void {
* *
* 检查每次启动都做;是否静默下载取决于自动更新开关 * 检查每次启动都做;是否静默下载取决于自动更新开关
* 下载完成后弹窗让用户选择立即重启还是稍后 * 下载完成后弹窗让用户选择立即重启还是稍后
* 外壳更新优先处理:热更包是 JS,装不进旧壳
*/ */
export async function runAutoUpdate(): Promise<void> { export async function runAutoUpdate(): Promise<void> {
if (!supported) { if (!supported) {
@@ -193,10 +268,14 @@ export async function runAutoUpdate(): Promise<void> {
return; return;
} }
const result = await check(); const result = await check();
if (!result?.url || result.version === currentVersion.value) { // 外壳更新不弹窗,入口统一在「版本更新」页
if (result?.shell) {
return; return;
} }
if (!isAutoUpdateEnabled()) { if (!result?.url) {
return;
}
if (result.version === currentVersion.value || !isAutoUpdateEnabled()) {
return; return;
} }
await download(); await download();
+132
View File
@@ -0,0 +1,132 @@
import { Capacitor, registerPlugin, type PluginListenerHandle } from "@capacitor/core";
import { DialogPlugin } from "tdesign-mobile-vue";
import type { Ref } from "vue";
import type { UpdateInfo } from "@/composables/useAppUpdate";
interface ShellUpdaterPlugin {
canInstall(): Promise<{ allowed: boolean }>;
openInstallSettings(): Promise<void>;
downloadAndInstall(options: { url: string; sha256: string; fileName: string }): Promise<void>;
addListener(eventName: "downloadProgress", listener: (progress: { percent: number; received: number; total: number }) => void): Promise<PluginListenerHandle>;
addListener(eventName: "resume", listener: () => void): Promise<PluginListenerHandle>;
}
const ShellUpdater = registerPlugin<ShellUpdaterPlugin>("ShellUpdater");
/** 管理更新页的外壳安装和授权流程 */
export function useShellUpdate(latest: Ref<UpdateInfo | null>) {
const downloading = ref(false);
const percent = ref(0);
const error = ref("");
let waitingForSettings = false;
let resumeListener: PluginListenerHandle | undefined;
let disposed = false;
/** 下载并交给系统安装器 */
async function install(): Promise<void> {
const target = latest.value;
if (!target?.url || !target.checksum) {
error.value = "缺少安装包地址或校验值";
return;
}
downloading.value = true;
percent.value = 0;
error.value = "";
let listener: PluginListenerHandle | undefined;
try {
listener = await ShellUpdater.addListener("downloadProgress", progress => {
percent.value = progress.percent;
});
await ShellUpdater.downloadAndInstall({
url: target.url,
sha256: target.checksum,
fileName: `app-${target.version}.apk`
});
} catch (e) {
error.value = e instanceof Error ? e.message : "安装包下载失败";
} finally {
if (listener) {
await listener.remove();
}
downloading.value = false;
}
}
/** 从授权页返回后只检查一次 */
async function handleResume(): Promise<void> {
if (!waitingForSettings) {
return;
}
waitingForSettings = false;
try {
const result = await ShellUpdater.canInstall();
if (result.allowed) {
await install();
} else {
error.value = "未获得安装权限,可重试或使用浏览器下载";
}
} catch (e) {
error.value = e instanceof Error ? e.message : "检查安装权限失败";
}
}
/** 检查权限,旧壳交给浏览器下载 */
async function start(): Promise<void> {
error.value = "";
if (!Capacitor.isPluginAvailable("ShellUpdater")) {
if (latest.value?.url) {
window.location.assign(latest.value.url);
}
return;
}
try {
const result = await ShellUpdater.canInstall();
if (result.allowed) {
await install();
return;
}
const dialog = DialogPlugin.confirm({
title: "需要安装权限",
content: "请允许此应用安装未知应用,返回后将继续下载并安装。",
cancelBtn: "稍后",
confirmBtn: "去设置",
onCancel() {
dialog.destroy();
},
async onConfirm() {
dialog.destroy();
waitingForSettings = true;
try {
await ShellUpdater.openInstallSettings();
} catch (e) {
waitingForSettings = false;
error.value = e instanceof Error ? e.message : "无法打开安装权限设置";
}
}
});
} catch (e) {
error.value = e instanceof Error ? e.message : "检查安装权限失败";
}
}
onMounted(async () => {
if (!Capacitor.isPluginAvailable("ShellUpdater")) {
return;
}
const listener = await ShellUpdater.addListener("resume", () => { void handleResume(); });
if (disposed) {
await listener.remove();
} else {
resumeListener = listener;
}
});
onUnmounted(async () => {
disposed = true;
waitingForSettings = false;
if (resumeListener) {
await resumeListener.remove();
}
});
return { downloading, percent, error, start };
}
+11 -2
View File
@@ -7,6 +7,7 @@
tab-bar-float tab-bar-float
:hide-nav="!tabBarStore.isShowing" :hide-nav="!tabBarStore.isShowing"
@change="onChangeTab" @change="onChangeTab"
@rail-click="onRailClick"
> >
<template #rail-extra> <template #rail-extra>
<t-button <t-button
@@ -174,11 +175,19 @@ function resolveVisibleTabValue(path: string): string {
function onChangeTab(value: string | number): void { function onChangeTab(value: string | number): void {
const path = String(value); const path = String(value);
if (resolveTabValue(route.path) === path) { if ((railVisible.value ? route.path : resolveTabValue(route.path)) === path) {
return; return;
} }
router.push(path); void router.push(path);
}
/** 再次点击已激活的侧栏导航时返回栏目根页面。 */
function onRailClick(value: string | number): void {
const path = String(value);
if (path === tabVal.value && route.path !== path) {
void router.push(path);
}
} }
// ---------- Tab 边距 ---------- // ---------- Tab 边距 ----------
@@ -275,7 +275,7 @@ watch(() => props.sessionKey, async () => {
.ai-conversation-list { .ai-conversation-list {
width: min(70vw, 24rem); width: min(70vw, 24rem);
height: 100vh; height: 100vh;
padding: calc(var(--tui-nav-height) + .5rem) 0 calc(1rem + env(safe-area-inset-bottom, 0px)); padding: calc(var(--tui-nav-height) + .5rem) 0 calc(1rem + var(--tui-safe-bottom, 0px));
display: flex; display: flex;
overflow: auto; overflow: auto;
position: relative; position: relative;
+185
View File
@@ -0,0 +1,185 @@
<template>
<div class="tui-page-layout tui-navbar customer-recycle-list">
<t-navbar fixed :z-index="20" title="客户回收物" left-arrow @left-click="$router.back()" />
<main v-can="permissionCodes.recycleAccount.read" class="tui-page-content scroll column">
<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.trim="keyword" type="search" borderless clearable placeholder="搜索客户姓名、拼音、编码">
<template #suffix-icon>
<t-button size="extra-small" theme="primary" variant="outline" :content="customerIds.length ? `已选 ${customerIds.length} 人` : '选择客户'" @click.stop="customerVisible = true" />
</template>
</t-input>
<t-dropdown-menu ref="filterMenuRef" class="menus">
<t-dropdown-item :label="selectedName" :options="[]" @open="openItemPicker" />
</t-dropdown-menu>
</div>
<t-cell-group theme="card">
<t-cell title="汇总">
<template v-if="selectedId" #note>
<t-button size="extra-small" variant="outline" content="清除" @click="clearItem" />
</template>
<template #description>
<div class="tags">
<t-tag v-for="item in displayedTotals" :key="item.recycleItemId" theme="primary"
variant="light"
:content="accountText(item)" />
<span v-if="!displayedTotals.length" v-text="loading ? '正在加载' : '暂无回收物'" />
</div>
</template>
</t-cell>
</t-cell-group>
<t-cell-group v-if="items.length" theme="card" class="fix-last-cell-line">
<customer-cell v-for="row in items" :key="row.customer.id" :customer="row.customer" arrow hover
@click="openCustomer(row.customer)">
<template #description>
<div class="tags">
<t-tag v-for="account in row.accounts" :key="account.recycleItemId" theme="primary"
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} 位客户` : '上拉加载更多'" />
</t-pull-down-refresh>
</main>
<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" />
</div>
</template>
<script setup lang="ts">
import RecycleAPI from "@/api/RecycleAPI";
import RecycleItemPickerPopup from "@/pages/recycle/components/RecycleItemPickerPopup.vue";
import CustomerSelector from "@/components/CustomerSelector.vue";
import type { Customer } from "@/types/Customer";
import type { RecycleAccount, RecycleCustomerAccountPage, RecycleItem } from "@/types/Recycle";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
import { permissionCodes } from "@/utils/permission";
import { getRecycleQuantityText } from "@/utils/recycle";
defineOptions({ name: "CustomerRecycleList" });
const router = useRouter();
const items = ref<RecycleCustomerAccountPage["list"]>([]);
const totals = ref<RecycleAccount[]>([]);
const selectedId = ref("");
const selectedItem = ref<RecycleItem>();
const filterVisible = ref(false);
const customerIds = ref<string[]>([]);
const customerVisible = ref(false);
const filterMenuRef = ref<{ collapseMenu: () => void }>();
const keyword = ref("");
let searchTimer: ReturnType<typeof setTimeout> | undefined;
const loading = ref(false);
const refreshing = ref(false);
const noMore = ref(false);
const total = ref(0);
let version = 0;
const selectedName = computed(() => selectedItem.value?.name || "全部回收物");
const displayedTotals = computed(() => selectedId.value ? totals.value.filter(item => item.recycleItemId === selectedId.value) : totals.value);
function accountText(account: RecycleAccount): string {
return `${account.recycleName || "未命名回收物"} ${getRecycleQuantityText(account.balance, account.recycleUnit)}`;
}
async function fetchPage(reset: boolean): Promise<void> {
if (!reset && (loading.value || noMore.value)) return;
const token = reset ? ++version : version;
const offset = reset ? 0 : items.value.length;
if (reset) {
items.value = [];
noMore.value = false;
}
loading.value = true;
try {
const result = await RecycleAPI.accountCustomers(offset, 20, selectedId.value, keyword.value, customerIds.value);
if (token !== version) return;
items.value = reset ? result.list : [...items.value, ...result.list];
totals.value = result.totals;
total.value = result.total;
noMore.value = result.list.length < 20 || !(items.value.length < total.value);
} catch (error) {
if (token === version) Message.error(getErrorMessage(error, "客户回收物加载失败"));
} finally {
if (token === version) {
loading.value = false;
refreshing.value = false;
}
}
}
async function reload(): Promise<void> {
await fetchPage(true);
}
async function loadMore(): Promise<void> {
await fetchPage(false);
}
async function openItemPicker(): Promise<void> {
filterVisible.value = true;
await nextTick();
filterMenuRef.value?.collapseMenu();
}
async function updateItem(id: string): Promise<void> {
if (selectedId.value === id) return;
selectedId.value = id;
if (searchTimer) clearTimeout(searchTimer);
await reload();
}
async function selectItem(item: RecycleItem): Promise<void> {
selectedItem.value = item;
await updateItem(item.id || "");
}
async function clearItem(): Promise<void> {
selectedItem.value = undefined;
await updateItem("");
}
watch(customerIds, async () => {
if (searchTimer) clearTimeout(searchTimer);
await reload();
});
watch(keyword, () => {
version++;
if (searchTimer) clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
void reload();
}, 300);
});
onUnmounted(() => {
if (searchTimer) clearTimeout(searchTimer);
});
async function openCustomer(customer: Customer): Promise<void> {
if (customer.id) await router.push({ name: "RecycleAccount", query: { customerId: customer.id } });
}
let wasDeactivated = false;
onMounted(reload);
onDeactivated(() => { wasDeactivated = true; });
onActivated(async () => {
if (!wasDeactivated) return;
wasDeactivated = false;
await reload();
});
</script>
<style scoped lang="less">
.customer-recycle-list {
.tags {
gap: .375rem;
display: flex;
padding: .25rem 0;
flex-wrap: wrap;
}
}
</style>
@@ -0,0 +1,169 @@
<template>
<div class="tui-page-layout tui-navbar birthday-reminder-setting">
<t-navbar
fixed
:z-index="20"
title="生日提醒设置"
left-arrow
@left-click="exit()"
>
<template #right>
<t-button
theme="primary"
variant="text"
size="small"
content="保存"
:loading="isSaving"
:disabled="isLoading"
@click="save"
/>
</template>
</t-navbar>
<main v-can="corePermissionCodes.setting.update" class="tui-page-content scroll column">
<t-cell-group theme="card">
<t-cell title="启用生日提醒" description="提前 7 天生成客户生日跟进提醒">
<template #rightIcon>
<t-switch v-model="formModel.enabled" :disabled="isLoading || isSaving" />
</template>
</t-cell>
<t-cell
title="跟进负责人"
:note="responsibleName"
arrow
@click="responsibleSelectorVisible = true"
/>
</t-cell-group>
<div class="tips red">
启用后每天 7:00 提前 7 天生成客户生日提醒,站内信与短信在生日当天 8:00 发给负责人。农历生日按农历月日计算。
</div>
</main>
<managed-user-selector
v-model="formModel.responsibleUserId"
v-model:visible="responsibleSelectorVisible"
title="选择生日提醒负责人"
:store-id="currentStoreStore.currentStoreId"
@change="handleResponsibleSelected"
/>
</div>
</template>
<script setup lang="ts">
import { useExpandToMaster, usePane } from "timi-tdesign-mobile";
import ManagedUserSelector from "@/pages/followUpReminder/component/ManagedUserSelector.vue";
import StoreSettingAPI, {
BIRTHDAY_REMINDER_ENABLED,
BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID
} from "@/api/StoreSettingAPI";
import ManagedUserAPI from "@/api/ManagedUserAPI";
import { Message } from "@/utils/message";
import { getErrorMessage } from "@/utils/error";
import { corePermissionCodes } from "@/utils/permission";
import { useCurrentStoreStore } from "@/store/currentStoreStore";
import type { ManagedUser } from "@/types/ManagedUser";
defineOptions({
name: "BirthdayReminderSetting"
});
const router = useRouter();
const pane = usePane();
useExpandToMaster({
path: "/management/customer-follow-up-reminders",
id: () => "__birthday_setting__"
});
const currentStoreStore = useCurrentStoreStore();
const isLoading = ref(false);
const isSaving = ref(false);
const responsibleSelectorVisible = ref(false);
const responsibleName = ref("未选择");
const formModel = reactive({
enabled: false,
responsibleUserId: ""
});
function exit(): void {
if (pane) {
pane.close();
return;
}
router.back();
}
async function load(): Promise<void> {
isLoading.value = true;
try {
const settingMap = await StoreSettingAPI.map([
BIRTHDAY_REMINDER_ENABLED,
BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID
]);
formModel.enabled = settingMap[BIRTHDAY_REMINDER_ENABLED]?.value === "true";
const responsibleUserId = settingMap[BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID]?.value || "";
formModel.responsibleUserId = responsibleUserId;
responsibleName.value = responsibleUserId ? "加载中…" : "未选择";
if (responsibleUserId) {
await fillResponsibleName(responsibleUserId);
}
} catch (error) {
Message.error(getErrorMessage(error, "生日提醒设置加载失败"));
} finally {
isLoading.value = false;
}
}
async function fillResponsibleName(userId: string): Promise<void> {
try {
const storeId = currentStoreStore.currentStoreId || undefined;
const result = await ManagedUserAPI.list({
index: 0,
size: 1,
equalsExample: { userId, storeId }
}, { storeId });
const managedUser = result.list?.[0];
responsibleName.value = managedUser ? getManagedUserName(managedUser) : "负责人已不在本门店";
} catch {
responsibleName.value = "未知负责人";
}
}
function getManagedUserName(item: ManagedUser): string {
return item.user?.nick || item.user?.name || item.userId || "未命名负责人";
}
function handleResponsibleSelected(user: ManagedUser): void {
formModel.responsibleUserId = user.userId || "";
responsibleName.value = getManagedUserName(user);
}
async function save(): Promise<void> {
if (formModel.enabled && !formModel.responsibleUserId) {
Message.warning("启用生日提醒前请先选择跟进负责人");
return;
}
isSaving.value = true;
try {
await StoreSettingAPI.update([
{ code: BIRTHDAY_REMINDER_ENABLED, value: formModel.enabled ? "true" : "false" },
{ code: BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID, value: formModel.responsibleUserId }
]);
Message.success("已保存");
exit();
} catch (error) {
Message.error(getErrorMessage(error, "保存失败"));
} finally {
isSaving.value = false;
}
}
onMounted(load);
</script>
<style scoped lang="less">
.birthday-reminder-setting {
.tips {
font-size: .875rem;
padding: 0 1rem 0 2rem;
}
}
</style>
@@ -54,8 +54,8 @@
<t-tag <t-tag
size="small" size="small"
variant="outline" variant="outline"
:theme="internalNotifyStatus ? getNotifyStatusTheme(internalNotifyStatus.status) : 'primary'" :theme="internalNotifyStatus ? getNotifyStatusTheme(internalNotifyStatus.status) : (isNotifyPending ? 'warning' : 'primary')"
:content="internalNotifyStatus ? getNotifyStatusText(internalNotifyStatus.status) : '已配置'" :content="internalNotifyStatus ? getNotifyStatusText(internalNotifyStatus.status) : (isNotifyPending ? '待发送' : '已配置')"
/> />
</template> </template>
</t-cell> </t-cell>
@@ -162,6 +162,8 @@ const isLoading = ref(false);
const isCompleting = ref(false); const isCompleting = ref(false);
const isDeleting = ref(false); const isDeleting = ref(false);
const internalNotifyStatus = ref<NotifyDetail>(); const internalNotifyStatus = ref<NotifyDetail>();
// 站内通知在提醒时间之后才对接收人可见,未到时间时后端按未发送处理
const isNotifyPending = computed(() => Boolean(detail.value?.remindAt && Time.now() < detail.value.remindAt));
let loadToken = 0; let loadToken = 0;
const canUpdate = computed(() => detail.value?.status === "PENDING" const canUpdate = computed(() => detail.value?.status === "PENDING"
@@ -258,6 +260,10 @@ async function loadInternalNotifyStatus(item: FollowUpReminder, token: number):
if (!item.internalNotifyDetailId || !userStore.hasPermissions(corePermissionCodes.notify.read)) { if (!item.internalNotifyDetailId || !userStore.hasPermissions(corePermissionCodes.notify.read)) {
return; return;
} }
// 未到提醒时间时后端按未发送处理,直接跳过避免必然失败的请求
if (item.remindAt && Time.now() < item.remindAt) {
return;
}
try { try {
const result = await NotifyAPI.internalDetail(item.internalNotifyDetailId); const result = await NotifyAPI.internalDetail(item.internalNotifyDetailId);
if (token === loadToken) { if (token === loadToken) {
@@ -166,8 +166,10 @@ const route = useRoute();
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
/** 内联到主从分栏时由列表页传入,优先于路由参数 */ /** 内联到主从分栏时由列表页传入,优先于路由参数 */
reminderId?: string; reminderId?: string;
customerId?: string;
}>(), { }>(), {
reminderId: "" reminderId: "",
customerId: ""
}); });
/** 非空说明当前被内联在右栏里,退出走 close 而不是路由 */ /** 非空说明当前被内联在右栏里,退出走 close 而不是路由 */
@@ -177,8 +179,8 @@ const routeId = computed(() => props.reminderId || String(route.params.id || "")
// 竖屏整页编辑转横屏:回到分栏,并用 view=edit 让列表页把右栏还原成编辑 // 竖屏整页编辑转横屏:回到分栏,并用 view=edit 让列表页把右栏还原成编辑
useExpandToMaster({ useExpandToMaster({
path: "/management/customer-follow-up-reminders", path: "/management/customer-follow-up-reminders",
id: () => routeId.value, id: () => routeId.value || "__create__",
query: { view: "edit" } query: { view: "edit", ...(route.query.customerId ? { customerId: String(route.query.customerId) } : {}) }
}); });
/** 退出编辑:分栏时交回列表页,整页时回路由 */ /** 退出编辑:分栏时交回列表页,整页时回路由 */
@@ -199,7 +201,7 @@ const routeNavBarTitle = computed(() => {
return "编辑跟进提醒"; return "编辑跟进提醒";
default: default:
// 内联在右栏时路由仍是列表页,标题不能只看 route.name // 内联在右栏时路由仍是列表页,标题不能只看 route.name
return pane ? "编辑跟进提醒" : ""; return pane ? (routeId.value ? "编辑跟进提醒" : "新增跟进提醒") : "";
} }
}); });
const router = useRouter(); const router = useRouter();
@@ -510,7 +512,7 @@ async function loadForm(): Promise<void> {
await loadStoreScope(); await loadStoreScope();
if (!routeId.value) { if (!routeId.value) {
formModel.notifyChannelList = ["INTERNAL"]; formModel.notifyChannelList = ["INTERNAL"];
const queryCustomerId = String(route.query.customerId || ""); const queryCustomerId = String(props.customerId || route.query.customerId || "");
if (queryCustomerId) { if (queryCustomerId) {
await handleCustomerChange(queryCustomerId); await handleCustomerChange(queryCustomerId);
} }
@@ -8,14 +8,7 @@
@left-click="$router.back()" @left-click="$router.back()"
> >
<template #right> <template #right>
<t-button <navbar-actions :actions="actionList" />
v-if="canCreate"
theme="primary"
variant="text"
size="small"
content="新增"
@click="toCreate"
/>
</template> </template>
</t-navbar> </t-navbar>
<master-detail-page <master-detail-page
@@ -80,93 +73,30 @@
<t-cell v-if="dateFilterType !== 'all'" title="提醒时间" :note="dateFilterLabel" /> <t-cell v-if="dateFilterType !== 'all'" title="提醒时间" :note="dateFilterLabel" />
<t-cell v-if="selectedResponsibleId" title="负责人" :note="selectedResponsibleName" /> <t-cell v-if="selectedResponsibleId" title="负责人" :note="selectedResponsibleName" />
</t-cell-group> </t-cell-group>
<t-cell-group v-if="pageResult.list.length" class="items fix-last-cell-line empty-cell-title-margin" theme="card"> <div v-if="pageResult.list.length" class="items">
<t-swipe-cell <follow-up-reminder-list-cell
v-for="(item, index) in pageResult.list" v-for="(item, index) in pageResult.list"
:key="item.id || index" :key="item.id || index"
class="item" v-entrance-transition="{ step: 30 }"
> :item="item"
<t-cell :can-complete="canComplete"
v-entrance-transition="{ step: 30 }" :can-delete="canDelete"
class="cell" @complete="item.status = 'COMPLETED'"
arrow @delete="removeFromList(item)"
@click="toDetail(item)" @detail="toDetail(item)"
> />
<template #leftIcon> </div>
<t-image
v-if="getCustomerPhotoURL(item.customer, 64)"
:src="getCustomerPhotoURL(item.customer, 64)"
:alt="getCustomerName(item)"
fit="cover"
class="avatar"
/>
<div v-else class="avatar fallback" v-text="getCustomerName(item).slice(0, 1)" />
</template>
<template #title>
<div class="title">
<div class="name-channel">
<span class="text-bold" v-text="getCustomerName(item)" />
<t-tag
v-if="item.notifyChannelList?.includes('INTERNAL')"
size="small"
theme="primary"
variant="outline"
content="站内信"
/>
<t-tag
v-if="item.notifyChannelList?.includes('SMS')"
size="small"
theme="warning"
variant="outline"
content="短信"
/>
</div>
<t-tag size="small" :theme="getStatusTheme(item.status)" :content="getStatusText(item.status)" />
</div>
</template>
<template #description>
<div class="description">
<div class="content clip-text" v-text="getContentSummary(item.content)" />
<div class="time-responsible">
<span
class="remind-time"
:class="getReminderTimeClass(item)"
v-text="getReminderTimeText(item.remindAt)"
/>
<span v-text="`负责人:${getResponsibleName(item)}`" />
</div>
</div>
</template>
</t-cell>
<template #right>
<div class="swipe-actions">
<t-button
v-if="canComplete && item.status === 'PENDING'"
class="complete swipe-cell-button"
variant="text"
:loading="operatingId === item.id && operatingType === 'complete'"
@click.stop="confirmComplete(item)"
>完成</t-button>
<t-button
v-if="canDelete"
class="delete swipe-cell-button"
variant="text"
:loading="operatingId === item.id && operatingType === 'delete'"
@click.stop="confirmDelete(item)"
>删除</t-button>
</div>
</template>
</t-swipe-cell>
</t-cell-group>
<center-tips :content="isLoading ? '正在加载提醒' : pageResult.list.length ? (isNoMore ? '已经到底了' : '上拉加载更多') : '暂无跟进提醒'" /> <center-tips :content="isLoading ? '正在加载提醒' : pageResult.list.length ? (isNoMore ? '已经到底了' : '上拉加载更多') : '暂无跟进提醒'" />
</div> </div>
</t-pull-down-refresh> </t-pull-down-refresh>
</template> </template>
<template #detail> <template #detail>
<birthday-reminder-setting v-if="selectedId === birthdayPaneId" />
<follow-up-reminder-edit <follow-up-reminder-edit
v-if="editing" v-else-if="editing || selectedId === createPaneId"
:key="`edit-${selectedId}`" :key="`edit-${selectedId}`"
:reminder-id="selectedId" :reminder-id="selectedId === createPaneId ? '' : selectedId"
:customer-id="selectedCustomerId"
/> />
<follow-up-reminder-detail <follow-up-reminder-detail
v-else v-else
@@ -176,50 +106,50 @@
/> />
</template> </template>
</master-detail-page> </master-detail-page>
<customer-selector
<customer-selector v-model="selectedCustomerId"
v-model="selectedCustomerId" v-model:visible="customerSelectorVisible"
v-model:visible="customerSelectorVisible" :initial-keyword="customerSearchKeyword"
:initial-keyword="customerSearchKeyword" :store-id="currentStoreStore.currentStoreId"
:store-id="currentStoreStore.currentStoreId" :enable-scan="true"
:enable-scan="true" @change="handleCustomerSelected"
@change="handleCustomerSelected" />
<managed-user-selector
v-model="selectedResponsibleId"
v-model:visible="responsibleSelectorVisible"
:store-id="currentStoreStore.currentStoreId"
@change="handleResponsibleSelected"
/>
<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="提醒开始时间"
@cancel="startVisible = false"
@confirm="confirmStart"
/> />
<managed-user-selector </t-popup>
v-model="selectedResponsibleId" <t-popup v-model="endVisible" placement="bottom">
v-model:visible="responsibleSelectorVisible" <t-date-time-picker
:store-id="currentStoreStore.currentStoreId" v-if="endVisible"
@change="handleResponsibleSelected" v-model="endDraft"
format="YYYY-MM-DD HH:mm"
:mode="['date', 'minute']"
title="提醒结束时间"
@cancel="endVisible = false"
@confirm="confirmEnd"
/> />
<t-popup v-model="startVisible" placement="bottom"> </t-popup>
<t-date-time-picker
v-if="startVisible"
v-model="startDraft"
format="YYYY-MM-DD HH:mm"
:mode="['date', 'minute']"
title="提醒开始时间"
@cancel="startVisible = false"
@confirm="confirmStart"
/>
</t-popup>
<t-popup v-model="endVisible" placement="bottom">
<t-date-time-picker
v-if="endVisible"
v-model="endDraft"
format="YYYY-MM-DD HH:mm"
:mode="['date', 'minute']"
title="提醒结束时间"
@cancel="endVisible = false"
@confirm="confirmEnd"
/>
</t-popup>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile"; import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile";
import { DialogPlugin, type DropdownValue } from "tdesign-mobile-vue"; import { type DropdownValue } from "tdesign-mobile-vue";
import FollowUpReminderListCell from "@/pages/followUpReminder/component/FollowUpReminderListCell.vue";
import BirthdayReminderSetting from "@/pages/followUpReminder/BirthdayReminderSetting.vue";
import FollowUpReminderDetail from "@/pages/followUpReminder/FollowUpReminderDetail.vue"; import FollowUpReminderDetail from "@/pages/followUpReminder/FollowUpReminderDetail.vue";
import FollowUpReminderEdit from "@/pages/followUpReminder/FollowUpReminderEdit.vue"; import FollowUpReminderEdit from "@/pages/followUpReminder/FollowUpReminderEdit.vue";
import { Time } from "timi-web"; import { Time } from "timi-web";
@@ -229,13 +159,14 @@ import { getErrorMessage } from "@/utils/error";
import FollowUpReminderAPI from "@/api/FollowUpReminderAPI"; import FollowUpReminderAPI from "@/api/FollowUpReminderAPI";
import CustomerAPI from "@/api/CustomerAPI"; import CustomerAPI from "@/api/CustomerAPI";
import CustomerSelector from "@/components/CustomerSelector.vue"; import CustomerSelector from "@/components/CustomerSelector.vue";
import NavbarActions from "@/components/NavbarActions.vue";
import ManagedUserSelector from "@/pages/followUpReminder/component/ManagedUserSelector.vue"; import ManagedUserSelector from "@/pages/followUpReminder/component/ManagedUserSelector.vue";
import type { NavbarAction } from "@/types/NavbarAction.ts";
import { useCurrentStoreStore } from "@/store/currentStoreStore"; import { useCurrentStoreStore } from "@/store/currentStoreStore";
import type { ManagedUser } from "@/types/ManagedUser"; import type { ManagedUser } from "@/types/ManagedUser";
import type { FollowUpReminder, FollowUpReminderPage, FollowUpReminderStatus } from "@/types/FollowUpReminder"; import type { FollowUpReminder, FollowUpReminderPage, FollowUpReminderStatus } from "@/types/FollowUpReminder";
import { getCustomerPhotoURL } from "@/utils/customer";
import { parseDateTime } from "@/utils/date"; import { parseDateTime } from "@/utils/date";
import { gaoRoleCodes, permissionCodes } from "@/utils/permission"; import { corePermissionCodes, gaoRoleCodes, permissionCodes } from "@/utils/permission";
import type { Customer } from "@/types/Customer"; import type { Customer } from "@/types/Customer";
@@ -248,12 +179,21 @@ defineOptions({
const router = useRouter(); const router = useRouter();
const route = useRoute(); const route = useRoute();
const createPaneId = "__create__";
const birthdayPaneId = "__birthday_setting__";
// 选中项、编辑态、切换方向、关闭逻辑、转屏、query 同步都在这里 // 选中项、编辑态、切换方向、关闭逻辑、转屏、query 同步都在这里
const { selectedId, editing, detailVersion, paneDirection, isWide, openDetail, openEdit } = const { selectedId, editing, detailVersion, paneDirection, isWide, openDetail, openEdit } =
useMasterDetailPane({ useMasterDetailPane({
path: "/management/customer-follow-up-reminders", path: "/management/customer-follow-up-reminders",
detail: id => `/management/customer-follow-up-reminders/${id}`, detail: id => id === birthdayPaneId
edit: id => `/management/customer-follow-up-reminders/${id}/edit` ? "/management/customer-birthday-reminder-setting"
: id === createPaneId
? `/management/customer-follow-up-reminders/create${selectedCustomerId.value ? `?customerId=${encodeURIComponent(selectedCustomerId.value)}` : ""}`
: `/management/customer-follow-up-reminders/${id}`,
edit: id => id === createPaneId
? `/management/customer-follow-up-reminders/create${selectedCustomerId.value ? `?customerId=${encodeURIComponent(selectedCustomerId.value)}` : ""}`
: `/management/customer-follow-up-reminders/${id}/edit`
}); });
const userStore = useUserStore(); const userStore = useUserStore();
const currentStoreStore = useCurrentStoreStore(); const currentStoreStore = useCurrentStoreStore();
@@ -262,6 +202,7 @@ const isGlobalManager = computed(() => userStore.hasRoles(gaoRoleCodes.globalMan
const canCreate = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.create)); const canCreate = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.create));
const canComplete = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.complete)); const canComplete = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.complete));
const canDelete = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.delete)); const canDelete = computed(() => userStore.hasPermissions(permissionCodes.customerFollowUpReminder.delete));
const canStoreSetting = computed(() => userStore.hasPermissions(corePermissionCodes.setting.update));
// ---------- 筛选 ---------- // ---------- 筛选 ----------
@@ -520,139 +461,71 @@ async function loadStoreScope(): Promise<void> {
// ---------- 展示 ---------- // ---------- 展示 ----------
function getCustomerName(item: FollowUpReminder): string {
return item.customer?.name || item.customer?.code || item.customerId || "未命名客户";
}
function getManagedUserName(item: ManagedUser): string { function getManagedUserName(item: ManagedUser): string {
return item.user?.nick || item.user?.name || item.userId || "未命名负责人"; return item.user?.nick || item.user?.name || item.userId || "未命名负责人";
} }
function getResponsibleName(item: FollowUpReminder): string {
return item.responsibleUser?.nick || item.responsibleUser?.name || item.responsibleUserId || "未命名负责人";
}
function getReminderTimeText(remindAt?: number): string {
return remindAt ? Time.toDateTime(remindAt) : "-";
}
function getReminderTimeClass(item: FollowUpReminder): "near" | "soon" | "later" | "normal" {
if (item.status === "COMPLETED" || !item.remindAt) {
return "normal";
}
const distance = item.remindAt - Time.now();
if (distance < 24 * 60 * 60 * 1000) {
return "near";
}
if (distance < 3 * 24 * 60 * 60 * 1000) {
return "soon";
}
return "later";
}
function getContentSummary(content?: string): string {
const text = content?.trim() || "未填写跟进内容";
return 60 < text.length ? `${text.slice(0, 60)}...` : text;
}
function getStatusText(status?: FollowUpReminderStatus): string {
return status === "COMPLETED" ? "已完成" : "待完成";
}
function getStatusTheme(status?: FollowUpReminderStatus): "success" | "warning" {
return status === "COMPLETED" ? "success" : "warning";
}
// ---------- 操作 ---------- // ---------- 操作 ----------
const operatingId = ref(""); function removeFromList(item: FollowUpReminder): void {
const operatingType = ref<"complete" | "delete">(); pageResult.list = pageResult.list.filter(current => current.id !== item.id);
pageResult.total = Math.max(0, pageResult.total - 1);
function confirmComplete(item: FollowUpReminder): void {
if (!item.id || !canComplete.value || item.status !== "PENDING" || operatingId.value) {
return;
}
const dialog = DialogPlugin.confirm({
title: "完成跟进提醒",
content: "完成后不能重新打开,确定完成此跟进提醒吗?",
cancelBtn: "取消",
confirmBtn: "完成",
onCancel() {
dialog.destroy();
},
onConfirm: async () => {
dialog.destroy();
await complete(item.id || "");
}
});
}
async function complete(id: string): Promise<void> {
operatingId.value = id;
operatingType.value = "complete";
try {
await FollowUpReminderAPI.complete(id);
const item = pageResult.list.find(current => current.id === id);
if (item) {
item.status = "COMPLETED";
}
Message.success("跟进提醒已完成");
} catch (error) {
Message.error(getErrorMessage(error, "跟进提醒完成失败"));
} finally {
operatingId.value = "";
operatingType.value = undefined;
}
}
function confirmDelete(item: FollowUpReminder): void {
if (!item.id || !canDelete.value || operatingId.value) {
return;
}
const dialog = DialogPlugin.confirm({
title: "删除跟进提醒",
content: "删除后列表中将不再显示,确定删除这条跟进提醒吗?",
cancelBtn: "取消",
confirmBtn: "删除",
onCancel() {
dialog.destroy();
},
onConfirm: async () => {
dialog.destroy();
await remove(item.id || "");
}
});
}
async function remove(id: string): Promise<void> {
operatingId.value = id;
operatingType.value = "delete";
try {
await FollowUpReminderAPI.remove(id);
pageResult.list = pageResult.list.filter(item => item.id !== id);
pageResult.total = Math.max(0, pageResult.total - 1);
Message.success("跟进提醒已删除");
} catch (error) {
Message.error(getErrorMessage(error, "跟进提醒删除失败"));
} finally {
operatingId.value = "";
operatingType.value = undefined;
}
} }
// ---------- 导航和生命周期 ---------- // ---------- 导航和生命周期 ----------
async function toCreate(): Promise<void> { async function toCreate(): Promise<void> {
if (isWide.value) {
openDetail(createPaneId);
return;
}
await router.push({ await router.push({
name: "CustomerFollowUpReminderCreate", name: "CustomerFollowUpReminderCreate",
query: selectedCustomerId.value ? { customerId: selectedCustomerId.value } : undefined query: selectedCustomerId.value ? { customerId: selectedCustomerId.value } : undefined
}); });
} }
async function toBirthdaySetting(): Promise<void> {
if (isWide.value) {
openDetail(birthdayPaneId);
return;
}
await router.push({ name: "CustomerBirthdayReminderSetting" });
}
const actionList = computed<NavbarAction[]>(() => {
const list: NavbarAction[] = [];
if (canCreate.value) {
list.push({
action: toCreate,
theme: "primary",
icon: "add",
key: "create",
text: "新增"
});
}
if (canStoreSetting.value) {
list.push({
action: toBirthdaySetting,
theme: "primary",
icon: "setting",
key: "birthday-setting",
text: "生日提醒设置"
});
}
return list;
});
async function toDetail(item: FollowUpReminder): Promise<void> { async function toDetail(item: FollowUpReminder): Promise<void> {
openDetail(item.id || ""); openDetail(item.id || "");
} }
watch([selectedId, detailVersion], async ([id, version], [previousId, previousVersion]) => {
if ((!id && previousId) || version !== previousVersion) {
await refresh();
}
});
onMounted(async () => { onMounted(async () => {
try { try {
@@ -714,107 +587,14 @@ watch(() => route.query.customerId, async value => {
} }
.items { .items {
gap: .5rem;
margin: 0 1rem;
display: flex;
flex-direction: column;
.item { }
.cell {
padding: 10px;
min-width: 0;
:deep(.t-cell__title),
:deep(.t-cell__title-text) {
min-width: 0;
overflow: hidden;
}
.avatar {
width: 3.5rem;
height: 3.5rem;
}
.title {
gap: .5rem;
width: 100%;
display: flex;
min-width: 0;
font-size: .875rem;
align-items: center;
justify-content: space-between;
.name-channel {
gap: .5rem;
display: flex;
min-width: 0;
overflow: hidden;
align-items: center;
> .text-bold {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
}
.description {
font-size: .75rem;
width: 100%;
min-width: 0;
max-width: 100%;
overflow: hidden;
line-height: 1.25;
.remind-time {
font-weight: 600;
&.near {
color: var(--td-error-color);
}
&.soon {
color: var(--td-warning-color);
}
&.later {
color: var(--td-success-color);
}
}
.content {
color: var(--td-text-color-secondary);
width: 100%;
min-width: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.time-responsible {
display: flex;
justify-content: space-between;
}
}
}
}
.swipe-actions {
--td-button-border-radius: 0;
.complete {
color: #fff;
background: var(--td-success-color);
}
.delete {
color: #fff;
background: var(--td-error-color);
}
}
} }
} }
}
:global(html.theme-dark) { :global(html.theme-dark) {
.follow-up-reminder-list { .follow-up-reminder-list {
@@ -823,17 +603,12 @@ watch(() => route.query.customerId, async value => {
} }
.summary, .summary {
.items .item,
.items .cell {
color: #e2e8f0; color: #e2e8f0;
background: rgba(30, 41, 59, .9); background: rgba(30, 41, 59, .9);
border-color: rgba(148, 163, 184, .16); border-color: rgba(148, 163, 184, .16);
} }
.description .content {
color: #94a3b8;
}
} }
} }
@@ -0,0 +1,295 @@
<template>
<div class="item">
<div class="header">
<t-image v-if="getCustomerPhotoURL(item.customer, 64)" :src="getCustomerPhotoURL(item.customer, 64)"
:alt="customerName" fit="cover" class="avatar" />
<div v-else class="avatar fallback" v-text="customerName.slice(0, 1)" />
<div class="main">
<div class="customer-status">
<strong class="customer clip-text" v-text="customerName" />
<div class="tags">
<t-tag
v-if="item.metadata?.bizType === 'BIRTHDAY'"
size="small"
theme="success"
variant="outline"
content="生日"
/>
<t-tag
v-if="item.source === 'SYSTEM'"
size="small"
theme="warning"
variant="outline"
content="系统"
/>
<t-tag
size="small"
variant="light-outline"
:theme="item.status === 'COMPLETED' ? 'success' : 'warning'"
:content="item.status === 'COMPLETED' ? '已完成' : '待完成'"
/>
</div>
</div>
<div class="record-line">
<span
class="time"
:class="timeClass"
v-text="item.remindAt ? Time.toDateTime(item.remindAt) : '-'"
/>
<div class="tags">
<t-tag
v-if="item.notifyChannelList?.includes('INTERNAL')"
size="small"
theme="primary"
variant="outline"
content="站内信"
/>
<t-tag
v-if="item.notifyChannelList?.includes('SMS')"
size="small"
theme="warning"
variant="outline"
content="短信"
/>
</div>
</div>
</div>
</div>
<t-divider />
<div class="content" v-text="item.content?.trim() || '未填写跟进内容'" />
<t-divider />
<div class="people-actions">
<div class="person"><span class="label">负责人</span><strong v-text="responsibleName" /></div>
<div class="actions">
<t-button
v-if="canDelete"
theme="danger"
variant="text"
size="extra-small"
content="删除"
:loading="operating === 'delete'"
:disabled="!!operating"
@click.stop="confirmDelete"
/>
<t-button
v-if="canComplete && item.status === 'PENDING'"
theme="primary"
variant="outline"
size="extra-small"
content="完成"
:loading="operating === 'complete'"
:disabled="!!operating"
@click.stop="confirmComplete"
/>
<t-button theme="primary" size="extra-small" content="详情" @click.stop="emit('detail')" />
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { Time } from "timi-web";
import { DialogPlugin } from "tdesign-mobile-vue";
import FollowUpReminderAPI from "@/api/FollowUpReminderAPI";
import { Message } from "@/utils/message";
import { getErrorMessage } from "@/utils/error";
import type { FollowUpReminder } from "@/types/FollowUpReminder";
import { getCustomerPhotoURL } from "@/utils/customer";
defineOptions({ name: "FollowUpReminderListCell" });
const props = defineProps<{
item: FollowUpReminder;
canComplete: boolean;
canDelete: boolean;
}>();
const emit = defineEmits<{ detail: []; complete: []; delete: [] }>();
const operating = ref<"complete" | "delete">();
const customerName = computed(() => props.item.customer?.name || props.item.customer?.code || props.item.customerId || "未命名客户");
const responsibleName = computed(() => props.item.responsibleUser?.nick || props.item.responsibleUser?.name || props.item.responsibleUserId || "未命名负责人");
const timeClass = computed(() => {
if (props.item.status === "COMPLETED" || !props.item.remindAt) return "normal";
const distance = props.item.remindAt - Time.now();
if (distance < 24 * 60 * 60 * 1000) return "near";
if (distance < 3 * 24 * 60 * 60 * 1000) return "soon";
return "later";
});
function confirmComplete(): void {
if (!props.item.id || !props.canComplete || props.item.status !== "PENDING" || operating.value) return;
const dialog = DialogPlugin.confirm({
title: "完成跟进提醒",
content: "完成后不能重新打开,确定完成此跟进提醒吗?",
cancelBtn: "取消",
confirmBtn: "完成",
onCancel() { dialog.destroy(); },
onConfirm: async () => {
dialog.destroy();
await operate("complete");
}
});
}
function confirmDelete(): void {
if (!props.item.id || !props.canDelete || operating.value) return;
const dialog = DialogPlugin.confirm({
title: "删除跟进提醒",
content: "删除后列表中将不再显示,确定删除这条跟进提醒吗?",
cancelBtn: "取消",
confirmBtn: "删除",
onCancel() { dialog.destroy(); },
onConfirm: async () => {
dialog.destroy();
await operate("delete");
}
});
}
async function operate(action: "complete" | "delete"): Promise<void> {
const id = props.item.id;
if (!id || operating.value) return;
operating.value = action;
try {
if (action === "complete") {
await FollowUpReminderAPI.complete(id);
Message.success("跟进提醒已完成");
emit("complete");
} else {
await FollowUpReminderAPI.remove(id);
Message.success("跟进提醒已删除");
emit("delete");
}
} catch (error) {
Message.error(getErrorMessage(error, action === "complete" ? "跟进提醒完成失败" : "跟进提醒删除失败"));
} finally {
operating.value = undefined;
}
}
</script>
<style scoped lang="less">
.item {
gap: .5rem;
padding: .625rem;
display: flex;
background: var(--td-bg-color-container);
flex-direction: column;
border-radius: 1rem;
.header {
gap: .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;
}
.record-line {
.time {
font-size: .875rem;
&.near {
color: var(--td-error-color);
}
&.soon {
color: var(--td-warning-color);
}
&.later {
color: var(--td-success-color);
}
}
.tags {
flex-wrap: wrap;
justify-content: flex-end;
}
}
}
.content {
width: 100%;
min-width: 0;
overflow: hidden;
font-size: .75rem;
white-space: nowrap;
text-overflow: ellipsis;
}
.people-actions {
gap: .75rem;
display: flex;
align-items: center;
justify-content: space-between;
.person {
gap: .25rem;
display: flex;
min-width: 0;
font-size: .75rem;
align-items: baseline;
.label {
color: var(--td-text-color-secondary);
flex: 0 0 auto;
}
strong {
max-width: 10rem;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.actions {
--td-button-border-radius: .5rem;
gap: .5rem;
display: flex;
justify-content: end;
}
}
}
:deep(.avatar .t-image__img) {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: inherit;
}
:global(html.theme-dark) .item .fallback {
background: #115e59;
}
</style>
@@ -33,7 +33,7 @@
<strong v-if="order.orderType === 'PACKAGE'" class="package-name" v-text="order.packageName || '未命名套餐'" /> <strong v-if="order.orderType === 'PACKAGE'" class="package-name" v-text="order.packageName || '未命名套餐'" />
</div> </div>
</div> </div>
<span class="red text-bold keep-text" v-text="`¥${formatPackageAmount(order.saleAmount)}`" /> <span v-if="order.orderType !== 'RECYCLE'" class="red text-bold keep-text" v-text="`¥${formatPackageAmount(order.saleAmount)}`" />
</div> </div>
</template> </template>
<template #description> <template #description>
@@ -53,7 +53,18 @@
/> />
</div> </div>
</div> </div>
<div class="row payment"> <div v-if="order.orderType === 'RECYCLE'" class="row payment">
<span class="label">回收物</span>
<div class="tags">
<t-tag
size="small"
theme="primary"
variant="light"
:content="`${order.recycleItemName || '回收物'}:已核销 ${order.recycleVerifiedQuantity ?? 0} / 应回收 ${order.recycleRequiredQuantity ?? 0} ${order.recycleUnit || ''}`"
/>
</div>
</div>
<div v-else class="row payment">
<span class="label">收款</span> <span class="label">收款</span>
<div class="tags"> <div class="tags">
<t-tag <t-tag
+1 -1
View File
@@ -528,7 +528,7 @@ onMounted(async () => {
.package-config-edit { .package-config-edit {
gap: 1rem; gap: 1rem;
display: flex; display: flex;
padding: 0 0 calc(1rem + env(safe-area-inset-bottom, 0)); padding: 0 0 calc(1rem + var(--tui-safe-bottom, 0px));
flex-direction: column; flex-direction: column;
.form { .form {
+1 -1
View File
@@ -280,7 +280,7 @@ onMounted(async () => {
.bottom-actions { .bottom-actions {
left: 1rem; left: 1rem;
right: 1rem; right: 1rem;
bottom: calc(.75rem + env(safe-area-inset-bottom, 0)); bottom: calc(.75rem + var(--tui-safe-bottom, 0px));
position: fixed; position: fixed;
.t-button { .t-button {
+1 -1
View File
@@ -554,7 +554,7 @@ onUnmounted(() => {
right: 1rem; right: 1rem;
gap: .75rem; gap: .75rem;
z-index: 20; z-index: 20;
bottom: calc(.75rem + env(safe-area-inset-bottom, 0)); bottom: calc(.75rem + var(--tui-safe-bottom, 0px));
display: flex; display: flex;
position: fixed; position: fixed;
+1 -1
View File
@@ -616,7 +616,7 @@ onMounted(async () => {
<style scoped lang="less"> <style scoped lang="less">
.point-rule-edit { .point-rule-edit {
padding: 0 0 calc(1rem + env(safe-area-inset-bottom, 0)); padding: 0 0 calc(1rem + var(--tui-safe-bottom, 0px));
.form { .form {
gap: 1rem; gap: 1rem;
+32 -26
View File
@@ -202,7 +202,6 @@
<product-sku-unit-batch-editor <product-sku-unit-batch-editor
v-model="batchUnitEditorVisible" v-model="batchUnitEditorVisible"
v-model:unit-list="batchUnitList" v-model:unit-list="batchUnitList"
v-model:base-unit-migration-ratio-text="batchBaseUnitMigrationRatioText"
:product-type="form.productType" :product-type="form.productType"
:sku-count="form.skuList.length" :sku-count="form.skuList.length"
@apply="applyBatchUnitTemplate" @apply="applyBatchUnitTemplate"
@@ -348,7 +347,6 @@ const unitEditorVisible = ref(false);
const editingSku = ref<SkuForm>(); const editingSku = ref<SkuForm>();
const batchUnitEditorVisible = ref(false); const batchUnitEditorVisible = ref(false);
const batchUnitList = ref<UnitForm[]>([]); const batchUnitList = ref<UnitForm[]>([]);
const batchBaseUnitMigrationRatioText = ref("");
const removedSkuKeySet = new Set<string>(); const removedSkuKeySet = new Set<string>();
const removedSkuMap = new Map<string, SkuForm>(); const removedSkuMap = new Map<string, SkuForm>();
@@ -389,7 +387,6 @@ function createSku(sku?: Partial<ProductSku>): SkuForm {
minStockQuantityText: sku?.minStockQuantity === null || sku?.minStockQuantity === undefined ? "" : String(sku.minStockQuantity), minStockQuantityText: sku?.minStockQuantity === null || sku?.minStockQuantity === undefined ? "" : String(sku.minStockQuantity),
unitList: sourceUnitList.length ? sourceUnitList.map(unit => createUnit(unit)) : [createUnit({ isBase: true, baseQuantityPerUnit: "1" })], unitList: sourceUnitList.length ? sourceUnitList.map(unit => createUnit(unit)) : [createUnit({ isBase: true, baseQuantityPerUnit: "1" })],
originalBaseUnitId, originalBaseUnitId,
baseUnitMigrationRatioText: "",
photoItemList photoItemList
}; };
} }
@@ -473,7 +470,6 @@ function openBatchUnitEditor(): void {
return; return;
} }
batchUnitList.value = sourceSku.unitList.map(unit => ({ ...unit, id: undefined, skuId: undefined, clientKey: window.crypto.randomUUID() })); batchUnitList.value = sourceSku.unitList.map(unit => ({ ...unit, id: undefined, skuId: undefined, clientKey: window.crypto.randomUUID() }));
batchBaseUnitMigrationRatioText.value = "";
batchUnitEditorVisible.value = true; batchUnitEditorVisible.value = true;
} }
@@ -483,10 +479,15 @@ function closeBatchUnitEditor(): void {
function applyBatchUnitTemplate(): void { function applyBatchUnitTemplate(): void {
const templateList = batchUnitList.value; const templateList = batchUnitList.value;
for (const sku of form.skuList) {
const conflict = getBatchUnitConflict(sku, templateList);
if (conflict) {
Message.warning(conflict);
return;
}
}
form.skuList.forEach(sku => { form.skuList.forEach(sku => {
const oldUnitList = sku.unitList; const oldUnitMap = new Map(sku.unitList.filter(unit => !!unit.id).map(unit => [unit.name.trim(), unit]));
const oldUnitMap = new Map(oldUnitList.filter(unit => !!unit.id).map(unit => [unit.name.trim(), unit]));
const oldBaseUnit = oldUnitList.find(unit => unit.isBase);
sku.unitList = templateList.map((unit, unitIndex) => ({ sku.unitList = templateList.map((unit, unitIndex) => ({
...unit, ...unit,
id: oldUnitMap.get(unit.name.trim())?.id, id: oldUnitMap.get(unit.name.trim())?.id,
@@ -494,14 +495,31 @@ function applyBatchUnitTemplate(): void {
clientKey: window.crypto.randomUUID(), clientKey: window.crypto.randomUUID(),
sort: unitIndex sort: unitIndex
})); }));
const newBaseUnit = sku.unitList.find(unit => unit.isBase);
if (oldBaseUnit?.id && newBaseUnit && oldBaseUnit.id !== newBaseUnit.id) {
sku.baseUnitMigrationRatioText = batchBaseUnitMigrationRatioText.value;
}
}); });
Message.success(`已为 ${form.skuList.length} 个 SKU 统一配置销售单位`); Message.success(`已为 ${form.skuList.length} 个 SKU 统一配置销售单位`);
} }
/// 校验批量模板与已保存 SKU 的冲突,返回冲突提示;无冲突返回 undefined
function getBatchUnitConflict(sku: SkuForm, templateList: UnitForm[]): string | undefined {
if (sku.unitEditable === true) {
return undefined;
}
const skuLabel = sku.name || sku.specSummary || "默认 SKU";
const oldBaseUnit = sku.unitList.find(unit => unit.isBase);
const templateBaseUnit = templateList.find(unit => unit.isBase);
if (oldBaseUnit?.id && templateBaseUnit?.name.trim() !== oldBaseUnit.name.trim()) {
return `「${skuLabel}」的基础单位为 ${oldBaseUnit.name},该 SKU 已产生业务记录,不能更换基础单位`;
}
const oldUnitMap = new Map(sku.unitList.filter(unit => !!unit.id).map(unit => [unit.name.trim(), unit]));
for (const unit of templateList) {
const existing = oldUnitMap.get(unit.name.trim());
if (existing && Number(existing.baseQuantityPerUnit) !== Number(unit.baseQuantityPerUnit)) {
return `「${skuLabel}」的「${existing.name.trim()}」是已保存单位,换算数量不能修改`;
}
}
return undefined;
}
function removeSku(index: number): void { function removeSku(index: number): void {
const sku = form.skuList[index]; const sku = form.skuList[index];
if (!sku) { if (!sku) {
@@ -969,13 +987,8 @@ function validate(): boolean {
return false; return false;
} }
const selectedBaseUnit = sku.unitList.find(unit => unit.isBase); const selectedBaseUnit = sku.unitList.find(unit => unit.isBase);
const isBaseUnitChanged = !!sku.originalBaseUnitId && selectedBaseUnit?.id !== sku.originalBaseUnitId; if (sku.originalBaseUnitId && selectedBaseUnit?.id !== sku.originalBaseUnitId && sku.unitEditable !== true) {
if (isBaseUnitChanged && !/^\d+(?:\.\d{1,6})?$/.test(sku.baseUnitMigrationRatioText.trim())) { Message.warning("SKU 已产生业务记录,不能更换基础单位,如需调整请新建 SKU");
Message.warning("切换基础单位时,请填写有效的新旧基础单位换算比例,最多六位小数");
return false;
}
if (isBaseUnitChanged && !(0 < Number(sku.baseUnitMigrationRatioText))) {
Message.warning("新旧基础单位换算比例必须大于 0");
return false; return false;
} }
} }
@@ -1007,14 +1020,7 @@ function buildSkuPayload(sku: SkuForm, index: number): ProductSku {
allowPurchase: form.productType === "SERVICE" ? false : !!unit.allowPurchase, allowPurchase: form.productType === "SERVICE" ? false : !!unit.allowPurchase,
allowSale: !!unit.allowSale, allowSale: !!unit.allowSale,
sort: unitIndex sort: unitIndex
})), }))
baseUnitMigrationRequest: sku.id && sku.originalBaseUnitId && sku.unitList.find(unit => unit.isBase)?.id !== sku.originalBaseUnitId
? {
targetUnitId: sku.unitList.find(unit => unit.isBase)?.id,
targetUnitName: sku.unitList.find(unit => unit.isBase)?.name.trim(),
oldToNewBaseRatio: sku.baseUnitMigrationRatioText.trim()
}
: undefined
}; };
} }
@@ -468,7 +468,7 @@ watch(resolveId, async (id, previousId) => {
} }
.revoke-popup { .revoke-popup {
padding: .5rem 1rem calc(1rem + env(safe-area-inset-bottom, 0)); padding: .5rem 1rem calc(1rem + var(--tui-safe-bottom, 0px));
.tip { .tip {
margin: 0 0 .75rem; margin: 0 0 .75rem;
@@ -179,7 +179,7 @@ function setSkuStatus(value: boolean | string | number): void {
} }
.sku-popup { .sku-popup {
padding: 1rem 0 calc(1rem + env(safe-area-inset-bottom, 0px)); padding: 1rem 0 calc(1rem + var(--tui-safe-bottom, 0px));
max-height: 100%; max-height: 100%;
overflow-y: auto; overflow-y: auto;
@@ -14,9 +14,6 @@
<div class="editor-context"> <div class="editor-context">
<strong>批量配置销售单位</strong> <strong>批量配置销售单位</strong>
<span v-text="`以下单位将应用到全部 ${props.skuCount} 个 SKU 明细`" /> <span v-text="`以下单位将应用到全部 ${props.skuCount} 个 SKU 明细`" />
<t-form-item label="基础单位换算比例" help="切换已有 SKU 的基础单位时填写:1 个旧基础单位等于多少个新基础单位;最多六位小数">
<t-input v-model.trim="baseUnitMigrationRatioText" type="number" align="right" borderless placeholder="无需切换时留空" />
</t-form-item>
</div> </div>
<div class="unit-list"> <div class="unit-list">
@@ -29,7 +26,7 @@
<t-form-item label="单位名称" required-mark> <t-form-item label="单位名称" required-mark>
<t-input v-model.trim="unit.name" borderless maxlength="32" placeholder="如 件、盒、箱" /> <t-input v-model.trim="unit.name" borderless maxlength="32" placeholder="如 件、盒、箱" />
</t-form-item> </t-form-item>
<t-form-item label="基础单位" content-align="right"> <t-form-item label="基础单位" content-align="right" help="已产生业务记录的 SKU 沿用原基础单位">
<t-switch v-model="unit.isBase" size="small" :disabled="unitList.length === 1" @change="setBaseUnit(unitIndex)" /> <t-switch v-model="unit.isBase" size="small" :disabled="unitList.length === 1" @change="setBaseUnit(unitIndex)" />
</t-form-item> </t-form-item>
<t-form-item label="换算数量" help="1 个当前单位对应的基础单位数量" required-mark> <t-form-item label="换算数量" help="1 个当前单位对应的基础单位数量" required-mark>
@@ -74,7 +71,6 @@ const props = defineProps<{
}>(); }>();
const unitList = defineModel<ProductSkuUnitForm[]>("unitList", { required: true }); const unitList = defineModel<ProductSkuUnitForm[]>("unitList", { required: true });
const baseUnitMigrationRatioText = defineModel<string>("baseUnitMigrationRatioText", { default: "" });
const emit = defineEmits<{ const emit = defineEmits<{
"update:modelValue": [value: boolean]; "update:modelValue": [value: boolean];
apply: []; apply: [];
@@ -145,7 +141,7 @@ function setBaseUnit(index: number): void {
.batch-editor { .batch-editor {
max-height: 100%; max-height: 100%;
overflow-y: auto; overflow-y: auto;
padding: 1rem 0 calc(1rem + env(safe-area-inset-bottom, 0px)); padding: 1rem 0 calc(1rem + var(--tui-safe-bottom, 0px));
.editor-context { .editor-context {
gap: .25rem; gap: .25rem;
@@ -35,14 +35,11 @@
<t-form-item label="单位名称" required-mark> <t-form-item label="单位名称" required-mark>
<t-input v-model.trim="unit.name" borderless maxlength="32" placeholder="如 件、盒、箱" /> <t-input v-model.trim="unit.name" borderless maxlength="32" placeholder="如 件、盒、箱" />
</t-form-item> </t-form-item>
<t-form-item label="基础单位" content-align="right"> <t-form-item label="基础单位" content-align="right" :help="canChangeBaseUnit ? undefined : 'SKU 已产生业务记录,基础单位不可更换'">
<t-switch v-model="unit.isBase" size="small" :disabled="sku.unitList.length === 1" @change="setBaseUnit(unitIndex)" /> <t-switch v-model="unit.isBase" size="small" :disabled="!canChangeBaseUnit || sku.unitList.length === 1" @change="setBaseUnit(unitIndex)" />
</t-form-item> </t-form-item>
<t-form-item v-if="isBaseUnitMigrationRequired" label="新旧基础单位比例" help="填写 1 个旧基础单位等于多少个新基础单位;最多六位小数" required-mark> <t-form-item label="换算数量" :help="isUnitConversionLocked(unit) ? '已保存单位的换算关系不可修改' : '1 个当前单位对应的基础单位数量'" required-mark>
<t-input v-model.trim="sku.baseUnitMigrationRatioText" type="number" align="right" borderless placeholder="例如 30" /> <t-input v-model.trim="unit.baseQuantityPerUnit" type="number" align="right" borderless :disabled="isUnitConversionLocked(unit)" placeholder="1" />
</t-form-item>
<t-form-item label="换算数量" help="1 个当前单位对应的基础单位数量" required-mark>
<t-input v-model.trim="unit.baseQuantityPerUnit" type="number" align="right" borderless :disabled="unit.isBase" placeholder="1" />
</t-form-item> </t-form-item>
<t-form-item label="售价(元)"> <t-form-item label="售价(元)">
<t-input v-model.trim="unit.salePriceText" type="number" align="right" borderless placeholder="选填" /> <t-input v-model.trim="unit.salePriceText" type="number" align="right" borderless placeholder="选填" />
@@ -93,12 +90,16 @@ const visible = computed({
set: value => handleVisibleChange(value) set: value => handleVisibleChange(value)
}); });
const unitEditorZIndex = 12100; const unitEditorZIndex = 12100;
const isBaseUnitMigrationRequired = computed(() => { /// 新建 SKU 可自由选择基础单位,已保存的 SKU 仅在未产生业务记录时允许调整
if (!sku.value?.originalBaseUnitId) { const canChangeBaseUnit = computed(() => !sku.value?.id || sku.value?.unitEditable === true);
return false;
/// 基础单位与不可编辑单位的换算数量不可修改
function isUnitConversionLocked(unit: ProductSkuUnitForm): boolean {
if (unit.isBase) {
return true;
} }
return sku.value.unitList.find(unit => unit.isBase)?.id !== sku.value.originalBaseUnitId; return !!sku.value?.id && !!unit.id && sku.value?.unitEditable !== true;
}); }
function handleVisibleChange(value: boolean): void { function handleVisibleChange(value: boolean): void {
emit("update:modelValue", value); emit("update:modelValue", value);
@@ -142,6 +143,10 @@ function removeUnit(index: number): void {
return; return;
} }
const unit = sku.value.unitList[index]; const unit = sku.value.unitList[index];
if (unit?.isBase && sku.value.id && sku.value.unitEditable !== true) {
Message.warning("SKU 已产生业务记录,不能移除基础单位");
return;
}
if (unit?.id) { if (unit?.id) {
Message.info("已移除单位将在保存时由后端检查引用后处理"); Message.info("已移除单位将在保存时由后端检查引用后处理");
} }
@@ -169,7 +174,7 @@ function setBaseUnit(index: number): void {
.product-sku-unit-editor { .product-sku-unit-editor {
gap: .75rem; gap: .75rem;
display: flex; display: flex;
padding: .5rem 1rem calc(1rem + env(safe-area-inset-bottom, 0px)); padding: .5rem 1rem calc(1rem + var(--tui-safe-bottom, 0px));
max-height: 100%; max-height: 100%;
overflow-y: auto; overflow-y: auto;
flex-direction: column; flex-direction: column;
@@ -36,10 +36,16 @@
</template> </template>
<template #day="{ day }"> <template #day="{ day }">
<template v-if="selection"> <template v-if="selection">
<span v-if="daily(day)?.inQuantity" class="quantity in" <span
v-text="formatQuantity(daily(day)?.inQuantity)" /> v-if="daily(day)?.inQuantity"
<span v-if="daily(day)?.outQuantity" class="quantity out" class="quantity in"
v-text="formatQuantity(daily(day)?.outQuantity)" /> v-text="formatQuantity(daily(day)?.inQuantity)"
/>
<span
v-if="daily(day)?.outQuantity"
class="quantity out"
v-text="formatQuantity(daily(day)?.outQuantity)"
/>
</template> </template>
<span class="movement-bar" :style="movementStyle(day)" /> <span class="movement-bar" :style="movementStyle(day)" />
</template> </template>
@@ -51,82 +57,36 @@
v-model:visible="selectorVisible" v-model:visible="selectorVisible"
@select="selectProduct" @select="selectProduct"
/> />
<bottom-popup <product-stock-calendar-records-popup
v-model="visible" ref="recordsPopup"
:title="`${selectedDate} 库存流水`" v-model:unit-index="unitIndex"
left-button-text="关闭" :store-id="storeId"
@left-button-click="visible = false" :selection="selection"
> :summary="selectedSummary"
<div class="records"> :summary-loading="loading"
<template v-if="canReadRecords"> @date-change="selectedDate = $event"
<div class="directions"> />
<t-segmented block :value="direction" :options="directionOptions" @change="changeDirection" />
</div>
<div class="record-list">
<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">
<template #leftIcon>
<t-image v-if="getCustomerPhotoURL(record.customer, 64)" :src="getCustomerPhotoURL(record.customer, 64)"
:alt="getCustomerText(record)" fit="cover" class="avatar" />
<div v-else-if="record.customer" class="avatar fallback" v-text="getCustomerText(record).slice(0, 1)" />
<t-image v-else-if="record.operator" :src="getOperatorAvatar(record)" :alt="getOperatorText(record)" fit="cover" class="avatar" />
<span v-else class="icon" :class="getDeltaClass(record.onHandDelta)"><t-icon name="history" size="1.25rem" /></span>
</template>
<template #title>
<div class="record-title">
<span v-if="record.customer" class="actor" v-text="getCustomerText(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="product-name" v-text="record.productNameSnapshot || '未命名产品'" />
<t-tag v-if="record.skuNameSnapshot && record.productNameSnapshot !== record.skuNameSnapshot"
size="small" :content="record.skuNameSnapshot" />
<span v-if="record.quantity !== undefined && record.quantity !== null && record.quantity !== ''"
class="record-quantity" v-text="`${getProductQuantityText(record.quantity)} ${record.unitSnapshot || ''}`" />
</div>
</template>
<template #description>
<div class="description">
<time-label :timestamp="record.occurredAt" underline />
<div><span class="delta" :class="getDeltaClass(record.onHandDelta)" v-text="getDeltaText(record.onHandDelta)" /></div>
</div>
</template>
</t-cell>
</t-cell-group>
<t-empty v-else-if="!recordsLoading" description="当天暂无流水" />
<t-button v-if="!noMore" block variant="text" :loading="recordsLoading" @click="loadRecords">加载更多
</t-button>
</div>
</template>
<t-empty v-else description="暂无库存流水查看权限" />
</div>
</bottom-popup>
</section> </section>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile"; import { useUserStore } from "timi-web-api";
import { TimeLabel } from "timi-web";
import { UserAPI, useUserStore } from "timi-web-api";
import GaoProductChartAPI from "@/api/GaoProductChartAPI"; import GaoProductChartAPI from "@/api/GaoProductChartAPI";
import GaoProductSkuChartAPI from "@/api/GaoProductSkuChartAPI"; import GaoProductSkuChartAPI from "@/api/GaoProductSkuChartAPI";
import ProductAPI from "@/api/ProductAPI";
import StoreChartAPI from "@/api/StoreChartAPI"; import StoreChartAPI from "@/api/StoreChartAPI";
import MonthCalendar from "@/components/monthCalendar/MonthCalendar.vue"; import MonthCalendar from "@/components/monthCalendar/MonthCalendar.vue";
import ProductSelectPopup from "@/components/productSelector/ProductSelectPopup.vue"; import ProductSelectPopup from "@/components/productSelector/ProductSelectPopup.vue";
import ProductStockCalendarRecordsPopup from "@/pages/product/component/ProductStockCalendarRecordsPopup.vue";
import { buildMonthCalendarDays, type MonthCalendarDay } from "@/components/monthCalendar/monthCalendar"; import { buildMonthCalendarDays, 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 } from "@/types/Product";
import type { ProductSkuSelectionValue } from "@/types/ProductSkuSelection"; import type { ProductSkuSelectionValue } from "@/types/ProductSkuSelection";
import { getProductQuantityText, getStockOperationText } from "@/utils/product";
import { buildFallbackAvatar } from "@/utils/avatar";
import { permissionCodes } from "@/utils/permission"; import { permissionCodes } from "@/utils/permission";
import { getErrorMessage } from "@/utils/error"; import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message"; import { Message } from "@/utils/message";
import { getCustomerPhotoURL } from "@/utils/customer";
const props = defineProps<{ storeId: string }>(); const props = defineProps<{ storeId: string }>();
const userStore = useUserStore(); const userStore = useUserStore();
const canReadRecords = computed(() => userStore.hasPermissions(permissionCodes.productStock.read));
const canReadProducts = computed(() => userStore.hasPermissions(permissionCodes.product.read)); const canReadProducts = computed(() => userStore.hasPermissions(permissionCodes.product.read));
const selectorVisible = ref(false); const selectorVisible = ref(false);
const selectedProductSku = ref<ProductSkuSelectionValue>(); const selectedProductSku = ref<ProductSkuSelectionValue>();
@@ -145,32 +105,6 @@ const unitIndex = ref(0);
const units = computed(() => selection.value?.sku.unitList || []); const units = computed(() => selection.value?.sku.unitList || []);
const currentUnit = computed(() => units.value[unitIndex.value]); const currentUnit = computed(() => units.value[unitIndex.value]);
function getCustomerText(record: StockRecord): string {
return record.customer?.name || record.customer?.code || "未知客户";
}
function getOperatorText(record: StockRecord): string {
return record.operator?.nick || record.operator?.name || "未知操作人";
}
function getOperatorAvatar(record: StockRecord): string {
return UserAPI.getAvatarURL(record.operator) || buildFallbackAvatar(getOperatorText(record), "#0f766e");
}
function getOperationClass(type?: string): string {
return ({
INITIAL_IN: "initial-in", MANUAL_IN: "manual-in", MANUAL_OUT: "manual-out", MANUAL_REVOKE: "manual-revoke",
ORDER_RESERVE: "order-reserve", ORDER_RELEASE: "order-release", ORDER_OUT: "order-out", ORDER_REVOKE: "order-revoke",
ORDER_RETURN_IN: "return-in", POINT_REDEMPTION_OUT: "manual-out", POINT_REDEMPTION_RETURN_IN: "return-in",
STOCKTAKE_GAIN: "stocktake-gain", STOCKTAKE_LOSS: "stocktake-loss"
} as Record<string, string>)[type || ""] || "unknown";
}
function getDeltaClass(value?: number | string): string {
const amount = Number(value || 0);
return 0 < amount ? "positive" : amount < 0 ? "negative" : "gray";
}
function getDeltaText(value?: number | string): string {
const amount = Number(value || 0);
return `${0 < amount ? "+" : amount < 0 ? "-" : ""}${getProductQuantityText(String(value || "0").replace(/^-/, ""))}`;
}
function nextUnit(): void { function nextUnit(): void {
unitIndex.value = (unitIndex.value + 1) % units.value.length; unitIndex.value = (unitIndex.value + 1) % units.value.length;
} }
@@ -186,7 +120,7 @@ function movementStyle(day: MonthCalendarDay): Record<string, string> {
const outgoing = Math.abs(Number(item?.outQuantity) || 0); const outgoing = Math.abs(Number(item?.outQuantity) || 0);
if (!incoming && !outgoing) return { background: "var(--td-component-stroke)" }; if (!incoming && !outgoing) return { background: "var(--td-component-stroke)" };
const percentage = incoming / (incoming + outgoing) * 100; const percentage = incoming / (incoming + outgoing) * 100;
return { background: `linear-gradient(90deg, var(--tui-green) ${percentage}%, var(--tui-red) ${percentage}%)` }; return { background: `linear-gradient(90deg, var(--td-success-color-4) ${percentage}%, var(--td-error-color-4) ${percentage}%)` };
} }
function selectProduct(value: ProductSelection): void { function selectProduct(value: ProductSelection): void {
@@ -246,72 +180,14 @@ watch([month, () => props.storeId, skuId], async () => {
} }
}, { immediate: true }); }, { immediate: true });
const visible = ref(false); const recordsPopup = ref<InstanceType<typeof ProductStockCalendarRecordsPopup>>();
const selectedDate = ref(""); const selectedDate = ref("");
const selectedStart = ref(0); const selectedSummary = computed(() => stats.value.find(item => item.dateValue === Number(selectedDate.value.replaceAll("-", ""))));
const direction = ref<StockRecordDirection>("IN");
const directionOptions = [{ label: "入库", value: "IN" }, { label: "出库", value: "OUT" }];
async function changeDirection(event: { value: string | number }): Promise<void> {
if (event.value === "IN" || event.value === "OUT") await selectDirection(event.value);
}
const records = ref<StockRecord[]>([]);
const recordsLoading = ref(false);
const noMore = ref(false);
let page = 0;
let recordToken = 0;
async function openDay(day: MonthCalendarDay): Promise<void> { async function openDay(day: MonthCalendarDay): Promise<void> {
const [year, monthNumber, dateNumber] = day.dateText.split("-").map(Number); await recordsPopup.value?.openDay(day);
const date = new Date(year, monthNumber - 1, dateNumber);
selectedStart.value = date.getTime();
selectedDate.value = day.dateText;
visible.value = true;
if (canReadRecords.value) await selectDirection("IN");
} }
async function selectDirection(value: StockRecordDirection): Promise<void> {
direction.value = value;
recordToken++;
records.value = [];
page = 0;
noMore.value = false;
recordsLoading.value = false;
await loadRecords();
}
async function loadRecords(): Promise<void> {
if (recordsLoading.value || noMore.value) return;
const token = ++recordToken;
recordsLoading.value = true;
try {
const start = new Date(selectedStart.value);
const endAt = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 1).getTime() - 1;
const result = await ProductAPI.recordList({
storeId: props.storeId,
productId: selection.value?.product.id || undefined,
skuId: skuId.value || undefined,
beginAt: selectedStart.value,
endAt,
direction: direction.value,
index: page,
size: 15
});
if (token !== recordToken) return;
const list = result.list || [];
records.value.push(...list);
page++;
noMore.value = list.length < 15 || !(records.value.length < (result.total || 0));
} catch (error) {
if (token === recordToken) Message.error(getErrorMessage(error, "库存流水加载失败"));
} finally {
if (token === recordToken) recordsLoading.value = false;
}
}
watch([() => props.storeId, skuId], () => {
visible.value = false;
recordToken++;
});
watch(() => props.storeId, () => { watch(() => props.storeId, () => {
selectorVisible.value = false; selectorVisible.value = false;
clearSelection(); clearSelection();
@@ -363,76 +239,4 @@ watch(() => props.storeId, () => {
} }
.records {
height: 60vh;
display: flex;
min-height: 0;
flex-direction: column;
.directions {
padding: .75rem;
min-width: 0;
flex-shrink: 0;
}
.record-list {
overflow-x: hidden;
overflow-y: auto;
min-width: 0;
min-height: 0;
flex: 1;
}
.avatar {
width: 3.5rem;
height: 3.5rem;
}
.list { margin: 0; }
.item { padding: .625rem; min-width: 0; }
.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; }
.record-title {
gap: .25rem;
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, .record-quantity { flex: 0 0 auto; }
.operation {
color: var(--operation-color, var(--td-text-color-secondary));
&.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; }
&.return-in { --operation-color: #15803d; }
&.stocktake-gain { --operation-color: #0f766e; }
&.stocktake-loss { --operation-color: #a16207; }
}
.product-name { overflow: hidden; flex: 0 1 auto; text-overflow: ellipsis; }
.record-quantity { color: var(--td-text-color-secondary); }
}
.description { gap: .5rem; display: flex; font-size: .75rem; align-items: center; justify-content: space-between; }
.delta { font-size: 1.25rem; }
.positive { color: var(--td-success-color); }
.negative { color: var(--td-error-color); }
}
:global(html.theme-dark) .records .operation {
&.initial-in { --operation-color: #93c5fd; }
&.manual-in, &.return-in { --operation-color: #86efac; }
&.manual-out { --operation-color: #fdba74; }
&.manual-revoke { --operation-color: #fda4af; }
&.order-reserve { --operation-color: #c4b5fd; }
&.order-release { --operation-color: #67e8f9; }
&.order-out { --operation-color: #fca5a5; }
&.order-revoke { --operation-color: #a5b4fc; }
&.stocktake-gain { --operation-color: #5eead4; }
&.stocktake-loss { --operation-color: #fcd34d; }
}
</style> </style>
@@ -0,0 +1,454 @@
<template>
<bottom-popup
v-model="visible"
:title="`${selectedDate} 库存流水`"
height="80vh"
left-button-text="关闭"
right-button-text=""
@left-button-click="visible = false"
>
<div v-if="canReadRecords" class="records">
<div class="filters glass-header">
<div v-if="selection" class="summary">
<span v-if="summaryLoading">汇总加载中</span>
<span
v-else
:class="direction === 'IN' ? 'in' : 'out'"
v-text="`合计 ${formatQuantity(direction === 'IN' ? summary?.inQuantity : summary?.outQuantity)} ${currentUnit?.name || ''}`"
/>
<t-button
v-if="1 < units.length"
size="extra-small"
variant="outline"
:content="`单位:${currentUnit?.name}`"
@click="nextUnit"
/>
</div>
<t-segmented :value="direction" :options="directionOptions" @change="changeDirection" />
</div>
<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">
<template #leftIcon>
<t-image
v-if="getCustomerPhotoURL(record.customer, 64)"
:src="getCustomerPhotoURL(record.customer, 64)"
:alt="getCustomerText(record)"
fit="cover"
class="avatar"
/>
<div
v-else-if="record.customer"
class="avatar fallback"
v-text="getCustomerText(record).slice(0, 1)"
/>
<t-image
v-else-if="record.operator"
:src="getOperatorAvatar(record)"
:alt="getOperatorText(record)"
fit="cover"
class="avatar"
/>
<span
v-else
class="icon"
:class="getDeltaClass(record.onHandDelta)"
>
<t-icon name="history" size="1.25rem" />
</span>
</template>
<template #title>
<div class="title">
<span v-if="record.customer" class="actor" v-text="getCustomerText(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="product-name" v-text="record.productNameSnapshot || '未命名产品'" />
<t-tag
v-if="record.skuNameSnapshot && record.productNameSnapshot !== record.skuNameSnapshot"
size="small"
:content="record.skuNameSnapshot"
/>
<span
v-if="record.quantity !== undefined && record.quantity !== null && record.quantity !== ''"
class="record-quantity"
v-text="`${getProductQuantityText(record.quantity)} ${record.unitSnapshot || ''}`"
/>
</div>
</template>
<template #description>
<div class="description">
<time-label :timestamp="record.occurredAt" underline />
<div>
<span
class="delta"
:class="getDeltaClass(record.onHandDelta)"
v-text="getDeltaText(record.onHandDelta)"
/>
</div>
</div>
</template>
</t-cell>
</t-cell-group>
<t-empty v-else-if="!recordsLoading" description="当天暂无流水" />
<t-button v-if="!noMore" block variant="text" :loading="recordsLoading" @click="loadRecords">
加载更多
</t-button>
</div>
<t-empty v-else description="暂无库存流水查看权限" />
</bottom-popup>
</template>
<script setup lang="ts">
import { BottomPopup } from "timi-tdesign-mobile";
import { TimeLabel } from "timi-web";
import { UserAPI, useUserStore } from "timi-web-api";
import ProductAPI from "@/api/ProductAPI";
import type { MonthCalendarDay } from "@/components/monthCalendar/monthCalendar";
import type { GaoProductStockMovementDailyStatView } from "@/types/GaoChart";
import type { ProductSelection, StockRecord, StockRecordDirection } from "@/types/Product";
import { getProductQuantityText, getStockOperationText } from "@/utils/product";
import { buildFallbackAvatar } from "@/utils/avatar";
import { permissionCodes } from "@/utils/permission";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
import { getCustomerPhotoURL } from "@/utils/customer";
const props = defineProps<{ storeId: string; selection?: ProductSelection; summary?: GaoProductStockMovementDailyStatView; summaryLoading: boolean }>();
const emit = defineEmits<{ "date-change": [date: string] }>();
const unitIndex = defineModel<number>("unitIndex", { required: true });
const userStore = useUserStore();
const canReadRecords = computed(() => userStore.hasPermissions(permissionCodes.productStock.read));
const skuId = computed(() => props.selection?.sku.id || "");
const units = computed(() => props.selection?.sku.unitList || []);
const currentUnit = computed(() => units.value[unitIndex.value]);
function nextUnit(): void {
unitIndex.value = (unitIndex.value + 1) % units.value.length;
}
function formatQuantity(value: number | string | undefined): string {
const ratio = Number(currentUnit.value?.baseQuantityPerUnit) || 1;
return String(Number((Number(value || 0) / ratio).toFixed(4)));
}
function getCustomerText(record: StockRecord): string {
return record.customer?.name || record.customer?.code || "未知客户";
}
function getOperatorText(record: StockRecord): string {
return record.operator?.nick || record.operator?.name || "未知操作人";
}
function getOperatorAvatar(record: StockRecord): string {
return UserAPI.getAvatarURL(record.operator) || buildFallbackAvatar(getOperatorText(record), "#0f766e");
}
function getOperationClass(type?: string): string {
return ({
INITIAL_IN: "initial-in",
MANUAL_IN: "manual-in",
MANUAL_OUT: "manual-out",
MANUAL_REVOKE: "manual-revoke",
ORDER_RESERVE: "order-reserve",
ORDER_RELEASE: "order-release",
ORDER_OUT: "order-out",
ORDER_REVOKE: "order-revoke",
ORDER_RETURN_IN: "return-in",
POINT_REDEMPTION_OUT: "manual-out",
POINT_REDEMPTION_RETURN_IN: "return-in",
STOCKTAKE_GAIN: "stocktake-gain",
STOCKTAKE_LOSS: "stocktake-loss"
} as Record<string, string>)[type || ""] || "unknown";
}
function getDeltaClass(value?: number | string): string {
const amount = Number(value || 0);
return 0 < amount ? "positive" : amount < 0 ? "negative" : "gray";
}
function getDeltaText(value?: number | string): string {
const amount = Number(value || 0);
const quantity = String(value || "0").replace(/^-/, "");
const text = props.selection ? `${formatQuantity(quantity)} ${currentUnit.value?.name || ""}` : getProductQuantityText(quantity);
return `${0 < amount ? "+" : amount < 0 ? "-" : ""}${text}`;
}
const visible = ref(false);
const selectedDate = ref("");
const selectedStart = ref(0);
const direction = ref<StockRecordDirection>("IN");
const directionOptions = [{ label: "入库", value: "IN" }, { label: "出库", value: "OUT" }];
async function changeDirection(event: { value: string | number }): Promise<void> {
if (event.value === "IN" || event.value === "OUT") await selectDirection(event.value);
}
const records = ref<StockRecord[]>([]);
const recordsLoading = ref(false);
const noMore = ref(false);
let page = 0;
let recordToken = 0;
async function openDay(day: MonthCalendarDay): Promise<void> {
const [year, monthNumber, dateNumber] = day.dateText.split("-").map(Number);
const date = new Date(year, monthNumber - 1, dateNumber);
selectedStart.value = date.getTime();
selectedDate.value = day.dateText;
emit("date-change", day.dateText);
visible.value = true;
if (canReadRecords.value) await selectDirection("IN");
}
async function selectDirection(value: StockRecordDirection): Promise<void> {
direction.value = value;
recordToken++;
records.value = [];
page = 0;
noMore.value = false;
recordsLoading.value = false;
await loadRecords();
}
async function loadRecords(): Promise<void> {
if (recordsLoading.value || noMore.value) return;
const token = ++recordToken;
recordsLoading.value = true;
try {
const start = new Date(selectedStart.value);
const endAt = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 1).getTime() - 1;
const result = await ProductAPI.recordList({
storeId: props.storeId,
productId: props.selection?.product.id || undefined,
skuId: skuId.value || undefined,
beginAt: selectedStart.value,
endAt,
direction: direction.value,
index: page,
size: 15
});
if (token !== recordToken) return;
const list = result.list || [];
records.value.push(...list);
page++;
noMore.value = list.length < 15 || !(records.value.length < (result.total || 0));
} catch (error) {
if (token === recordToken) Message.error(getErrorMessage(error, "库存流水加载失败"));
} finally {
if (token === recordToken) recordsLoading.value = false;
}
}
watch([() => props.storeId, skuId], () => {
visible.value = false;
recordToken++;
});
defineExpose({ openDay });
</script>
<style scoped lang="less">
.records {
height: 100%;
overflow-y: auto;
.filters {
gap: .5rem;
top: 0;
display: flex;
padding: .75rem;
z-index: 1;
position: sticky;
min-width: 0;
flex-shrink: 0;
align-items: center;
justify-content: end;
.summary {
gap: .75rem;
display: flex;
min-width: 0;
font-size: .875rem;
align-items: center;
white-space: nowrap;
.in {
color: var(--td-success-color);
}
.out {
color: var(--td-error-color);
}
}
}
.list {
margin: 0;
.item {
padding: .625rem;
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;
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, .record-quantity {
flex: 0 0 auto;
}
.operation {
color: var(--operation-color, var(--td-text-color-secondary));
&.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;
}
&.return-in {
--operation-color: #15803d;
}
&.stocktake-gain {
--operation-color: #0f766e;
}
&.stocktake-loss {
--operation-color: #a16207;
}
}
.product-name {
overflow: hidden;
flex: 0 1 auto;
text-overflow: ellipsis;
}
.record-quantity {
color: var(--td-text-color-secondary);
}
}
.description {
gap: .5rem;
display: flex;
font-size: .75rem;
align-items: center;
justify-content: space-between;
}
.delta {
font-size: 1.25rem;
}
.positive {
color: var(--td-success-color);
}
.negative {
color: var(--td-error-color);
}
}
}
}
:global(html.theme-dark) .records .operation {
&.initial-in {
--operation-color: #93c5fd;
}
&.manual-in, &.return-in {
--operation-color: #86efac;
}
&.manual-out {
--operation-color: #fdba74;
}
&.manual-revoke {
--operation-color: #fda4af;
}
&.order-reserve {
--operation-color: #c4b5fd;
}
&.order-release {
--operation-color: #67e8f9;
}
&.order-out {
--operation-color: #fca5a5;
}
&.order-revoke {
--operation-color: #a5b4fc;
}
&.stocktake-gain {
--operation-color: #5eead4;
}
&.stocktake-loss {
--operation-color: #fcd34d;
}
}
</style>
@@ -232,7 +232,7 @@ watch(() => [visible.value, props.operation] as const, ([isVisible]) => {
<style scoped lang="less"> <style scoped lang="less">
.operation-popup { .operation-popup {
padding-bottom: calc(1rem + env(safe-area-inset-bottom, 0)); padding-bottom: calc(1rem + var(--tui-safe-bottom, 0px));
.form { .form {
margin: 0; margin: 0;
+68 -8
View File
@@ -20,9 +20,6 @@
</t-navbar> </t-navbar>
<main class="tui-page-content scroll column" v-can="permissionCodes.salesOrder.create"> <main class="tui-page-content scroll column" v-can="permissionCodes.salesOrder.create">
<t-form class="form card" label-width="7rem" v-entrance-transition> <t-form class="form card" label-width="7rem" v-entrance-transition>
<t-form-item label-width="0">
<span>兑换单会生成一张交易订单,商品按订单履约分批领取。回收物支付独立核销,不产生资金流水,也不支持与现金混付。</span>
</t-form-item>
<t-form-item label="兑换模板" arrow content-align="right" @click="openRulePicker"> <t-form-item label="兑换模板" arrow content-align="right" @click="openRulePicker">
<div class="template"> <div class="template">
<span v-text="ruleDisplayText" /> <span v-text="ruleDisplayText" />
@@ -35,7 +32,14 @@
<span v-text="customerName || '请选择'" /> <span v-text="customerName || '请选择'" />
</t-form-item> </t-form-item>
<customer-profile-card v-if="customer" class="customer-profile" :customer="customer" /> <customer-profile-card v-if="customer" class="customer-profile" :customer="customer" />
<t-form-item v-if="canAdjust" label="回收物" arrow content-align="right" @click="itemPickerVisible = true"> <t-form-item
v-if="canAdjust"
label="回收物"
arrow
content-align="right"
required-mark
@click="itemPickerVisible = true"
>
<span v-text="recycleItemName || '请选择'" /> <span v-text="recycleItemName || '请选择'" />
</t-form-item> </t-form-item>
<t-form-item label="回收数量" required-mark content-align="right"> <t-form-item label="回收数量" required-mark content-align="right">
@@ -54,6 +58,14 @@
<t-tag :content="recycleUnitName || '单位'" /> <t-tag :content="recycleUnitName || '单位'" />
</div> </div>
</t-form-item> </t-form-item>
<t-form-item
v-if="customerId && recycleItemId"
label="客户回收物数量"
label-width="9rem"
content-align="right"
>
<span :class="customerRecycleClass" v-text="customerRecycleText" />
</t-form-item>
<t-form-item v-if="selectedRule" label="兑换份数" required-mark content-align="right"> <t-form-item v-if="selectedRule" label="兑换份数" required-mark content-align="right">
<t-stepper v-model="multiple" size="large" :min="1" :max="9999" :step="1" integer theme="outline" /> <t-stepper v-model="multiple" size="large" :min="1" :max="9999" :step="1" integer theme="outline" />
</t-form-item> </t-form-item>
@@ -149,7 +161,7 @@
<bottom-popup <bottom-popup
v-model="ruleVisible" v-model="ruleVisible"
title="选择兑换模板" title="选择兑换模板"
max-height="70vh" height="70vh"
right-button-text="" right-button-text=""
@left-button-click="ruleVisible = false" @left-button-click="ruleVisible = false"
> >
@@ -162,7 +174,13 @@
@click="selectRule(item)" @click="selectRule(item)"
> >
<template #leftIcon> <template #leftIcon>
<t-image v-if="getRulePhotoId(item)" class="avatar" :src="getAttachmentReadURL(getRulePhotoId(item), 96)" :alt="item.recycleName || '回收物'" fit="cover" /> <t-image
v-if="getRulePhotoId(item)"
class="avatar"
:src="getAttachmentReadURL(getRulePhotoId(item), 96)"
:alt="item.recycleName || '回收物'"
fit="cover"
/>
<div v-else class="avatar fallback" v-text="(item.recycleName || '回').slice(0, 1)" /> <div v-else class="avatar fallback" v-text="(item.recycleName || '回').slice(0, 1)" />
</template> </template>
<template #title> <template #title>
@@ -224,8 +242,13 @@ import { Message } from "@/utils/message";
import { comparePackageQuantity, normalizePackageQuantity, toPackageBaseQuantity } from "@/utils/package"; import { comparePackageQuantity, normalizePackageQuantity, toPackageBaseQuantity } from "@/utils/package";
import { permissionCodes } from "@/utils/permission"; import { permissionCodes } from "@/utils/permission";
import { getProductPhotoURL, getProductQuantityStep, getProductSkuSnapshotText } from "@/utils/product"; import { getProductPhotoURL, getProductQuantityStep, getProductSkuSnapshotText } from "@/utils/product";
import { buildProductStockPreview, getProductStockShortageMessage, mergeProductStockRequirements, type ProductStockPreviewItem } from "@/utils/productStock"; import {
import { getRecycleQuantityText, multiplyRecycleQuantity } from "@/utils/recycle"; buildProductStockPreview,
getProductStockShortageMessage,
mergeProductStockRequirements,
type ProductStockPreviewItem
} from "@/utils/productStock";
import { getRecycleAvailable, getRecycleQuantityText, multiplyRecycleQuantity } from "@/utils/recycle";
import { uploadPhotoList } from "@/utils/photo"; import { uploadPhotoList } from "@/utils/photo";
defineOptions({ name: "RecycleExchangeCreate" }); defineOptions({ name: "RecycleExchangeCreate" });
@@ -367,6 +390,36 @@ const recycleItemList = ref<RecycleItem[]>([]);
const recycleItemId = ref(""); const recycleItemId = ref("");
const selectedRecycleItem = ref<RecycleItem>(); const selectedRecycleItem = ref<RecycleItem>();
const recycleQuantityText = ref(""); const recycleQuantityText = ref("");
const customerRecycleText = ref("正在加载");
const customerRecycleAvailable = ref<string>();
const customerRecycleClass = computed(() => {
const required = normalizePackageQuantity(recycleQuantityText.value || "0");
if (customerRecycleAvailable.value === undefined || required === undefined) return "";
return comparePackageQuantity(customerRecycleAvailable.value, required) < 0 ? "insufficient" : "sufficient";
});
watch([customerId, recycleItemId], async ([customer, item], _previous, onCleanup) => {
let active = true;
onCleanup(() => { active = false; });
customerRecycleAvailable.value = undefined;
if (!customer || !item) return;
if (!userStore.hasPermissions(permissionCodes.recycleAccount.read)) {
customerRecycleText.value = "无权限查看";
return;
}
customerRecycleText.value = "正在加载";
try {
const accounts = await RecycleAPI.accountList(customer);
if (!active) return;
const account = accounts.find(value => value.recycleItemId === item);
customerRecycleAvailable.value = getRecycleAvailable(account).toFixed(3);
customerRecycleText.value = `可用 ${getRecycleQuantityText(customerRecycleAvailable.value, recycleUnitName.value)}`;
} catch (error) {
if (!active) return;
customerRecycleText.value = "加载失败";
Message.error(getErrorMessage(error, "客户回收物数量加载失败"));
}
}, { immediate: true });
async function loadRecycleItems(): Promise<void> { async function loadRecycleItems(): Promise<void> {
itemLoading.value = true; itemLoading.value = true;
@@ -776,6 +829,13 @@ onMounted(async () => {
} }
.recycle-exchange-create { .recycle-exchange-create {
.sufficient {
color: var(--td-success-color);
}
.insufficient {
color: var(--td-warning-color);
}
.form { .form {
+14 -2
View File
@@ -28,7 +28,7 @@
> >
<div class="filters glass"> <div class="filters glass">
<t-input <t-input
v-model.trim="keyword" v-model="keyword"
class="keyword" class="keyword"
type="search" type="search"
borderless borderless
@@ -53,7 +53,14 @@
@click="toEdit(item)" @click="toEdit(item)"
> >
<template #left-icon> <template #left-icon>
<div class="avatar fallback" v-text="(getRecycleItemName(item) || '模').slice(0, 1)" /> <t-image
v-if="coverId(item)"
class="avatar"
:src="getAttachmentReadURL(coverId(item), 96)"
:alt="getRecycleItemName(item)"
fit="cover"
/>
<div v-else class="avatar fallback" v-text="(getRecycleItemName(item) || '模').slice(0, 1)" />
</template> </template>
<template #title> <template #title>
<span class="clip-text" v-text="getRecycleItemName(item) || '未命名回收物'" /> <span class="clip-text" v-text="getRecycleItemName(item) || '未命名回收物'" />
@@ -115,6 +122,7 @@ import RecycleRuleDetail from "@/pages/recycle/RecycleRuleDetail.vue";
import RecycleRuleEdit from "@/pages/recycle/RecycleRuleEdit.vue"; import RecycleRuleEdit from "@/pages/recycle/RecycleRuleEdit.vue";
import type { NavbarAction } from "@/types/NavbarAction"; import type { NavbarAction } from "@/types/NavbarAction";
import type { RecycleExchangeRule, RecycleRuleItem } from "@/types/Recycle"; import type { RecycleExchangeRule, RecycleRuleItem } from "@/types/Recycle";
import { getAttachmentReadURL } from "@/utils/attachment";
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";
@@ -157,6 +165,10 @@ function getRecycleItemName(rule: RecycleExchangeRule): string {
return rule.recycleName || ""; return rule.recycleName || "";
} }
function coverId(rule: RecycleExchangeRule): string {
return rule.recycleItemAttachments?.find(attachment => attachment.id && attachment.mimeType?.startsWith("image/"))?.id || "";
}
function getRuleItemList(rule: RecycleExchangeRule): RecycleRuleItem[] { function getRuleItemList(rule: RecycleExchangeRule): RecycleRuleItem[] {
return rule.itemList || []; return rule.itemList || [];
} }
@@ -2,7 +2,7 @@
<bottom-popup <bottom-popup
v-model="visible" v-model="visible"
:title="props.title" :title="props.title"
height="60vh" height="70vh"
right-button-text="" right-button-text=""
:z-index="12100" :z-index="12100"
:overlay-props="{ zIndex: 12099 }" :overlay-props="{ zIndex: 12099 }"
@@ -56,6 +56,7 @@ const props = withDefaults(defineProps<{
title?: string; title?: string;
manage?: boolean; manage?: boolean;
showStatus?: boolean; showStatus?: boolean;
accountItems?: boolean;
selectedId?: string; selectedId?: string;
items?: RecycleItem[]; items?: RecycleItem[];
loading?: boolean; loading?: boolean;
@@ -65,6 +66,7 @@ const props = withDefaults(defineProps<{
title: "选择回收物", title: "选择回收物",
manage: false, manage: false,
showStatus: false, showStatus: false,
accountItems: false,
selectedId: "", selectedId: "",
loading: false, loading: false,
emptyText: "暂无回收物" emptyText: "暂无回收物"
@@ -86,6 +88,10 @@ async function load(): Promise<void> {
if (internalLoading.value) return; if (internalLoading.value) return;
internalLoading.value = true; internalLoading.value = true;
try { try {
if (props.accountItems) {
loadedItems.value = await RecycleAPI.accountItems();
return;
}
const result: RecycleItem[] = []; const result: RecycleItem[] = [];
let offset = 0; let offset = 0;
let total = 0; let total = 0;
+14 -213
View File
@@ -89,71 +89,15 @@
@click="openEndTime" @click="openEndTime"
/> />
</t-cell-group> </t-cell-group>
<t-cell-group v-if="recordList.length" class="empty-cell-title-margin" theme="card"> <div v-if="recordList.length" class="records">
<t-cell <fund-record-list-cell
class="item"
v-for="item in recordList" v-for="item in recordList"
:key="item.id" :key="item.id"
arrow
v-entrance-transition="{ step: 30 }" v-entrance-transition="{ step: 30 }"
@click="toDetail(item)" :item="item"
> @detail="toDetail(item)"
<template #leftIcon> />
<t-image </div>
v-if="getCustomerPhotoURL(item.customer, 64)"
:src="getCustomerPhotoURL(item.customer, 64)"
:alt="getCustomerText(item)"
fit="cover"
class="avatar"
/>
<div v-else class="avatar fallback" v-text="getCustomerText(item).slice(0, 1)" />
</template>
<template #title>
<div class="title">
<span class="customer clip-text" v-text="getCustomerText(item)" />
<span class="type" :class="getOperationClass(item.operationType)" v-text="getFundOperationText(item.operationType)" />
<t-tag
size="small"
:content="getRecordStatusText(item)"
variant="light-outline"
:theme="getRecordStatusTheme(item)"
/>
</div>
</template>
<template #description>
<div class="description">
<div class="operator">
<div class="field">
<span class="label">发起人</span>
<span class="text-bold" v-text="getOperatorText(item)" />
</div>
<div v-if="item.verifier" class="field">
<span class="label">核销人</span>
<span class="text-bold" v-text="getVerifierText(item)" />
</div>
<time-label :timestamp="item.occurredAt" underline />
</div>
<div class="amounts">
<div class="order-amount">
<span class="label">订单总价</span>
<span>¥</span>
<span v-text="formatPackageAmount(item.salesOrderAmount)" />
</div>
<div class="unpaid-amount">
<span class="label">剩余待收</span>
<span>¥</span>
<span v-text="formatPackageAmount(item.salesOrderUnpaidAmountSnapshot)" />
</div>
<div class="record-amount">
<span class="label">流水金额</span>
<span class="red">¥</span>
<span class="value red" v-text="formatPackageAmount(item.amount)" />
</div>
</div>
</div>
</template>
</t-cell>
</t-cell-group>
<center-tips v-else :content="loading ? '正在加载资金流水' : '暂无资金流水'" /> <center-tips v-else :content="loading ? '正在加载资金流水' : '暂无资金流水'" />
<center-tips :content="loadStateText" /> <center-tips :content="loadStateText" />
</t-pull-down-refresh> </t-pull-down-refresh>
@@ -201,7 +145,8 @@
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile"; import { MasterDetailPage, 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 { TimeLabel, Time } from "timi-web"; import FundRecordListCell from "@/pages/salesOrder/component/FundRecordListCell.vue";
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";
import SalesOrderAPI from "@/api/SalesOrderAPI"; import SalesOrderAPI from "@/api/SalesOrderAPI";
@@ -210,11 +155,8 @@ import type { FundOperationType, FundRecord, FundRecordStatus } from "@/types/Sa
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 { formatPackageAmount } from "@/utils/package";
import { getFundOperationText, getFundStatusText } from "@/utils/salesOrder";
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 type { Customer } from "@/types/Customer"; import type { Customer } from "@/types/Customer";
@@ -475,39 +417,6 @@ function buildUnixRange(): [number | undefined, number | undefined] {
]; ];
} }
function getOperatorText(item: FundRecord): string {
return item.operator?.nick || item.operator?.name || item.operatorUserId || "未知";
}
function getVerifierText(item: FundRecord): string {
return item.verifier?.nick || item.verifier?.name || item.verifierUserId || "未核销";
}
function getCustomerText(item: FundRecord): string {
return item.customer?.name || item.customer?.code || item.customerId || "未知客户";
}
function getOperationClass(type?: FundOperationType): string {
return ({
RECEIVE: "receive",
REFUND: "refund",
CONFIRM_NO_REFUND: "confirm-no-refund",
REVOKE: "revoke"
} as Record<string, string>)[type || ""] || "unknown";
}
function getStatusTheme(statusValue?: FundRecordStatus): "success" | "warning" | "danger" | "default" {
return statusValue === "VERIFIED" ? "success" : statusValue === "PENDING" ? "warning" : statusValue === "REJECTED" ? "danger" : "default";
}
function getRecordStatusText(item: FundRecord): string {
return item.revokeRecordId ? "已被冲正" : getFundStatusText(item.status);
}
function getRecordStatusTheme(item: FundRecord): "success" | "warning" | "danger" | "default" {
return item.revokeRecordId ? "danger" : getStatusTheme(item.status);
}
async function toDetail(item: FundRecord): Promise<void> { async function toDetail(item: FundRecord): Promise<void> {
openDetail(item.id || ""); openDetail(item.id || "");
} }
@@ -530,121 +439,13 @@ onMounted(async () => {
.sales-order-record-list { .sales-order-record-list {
padding: var(--tui-nav-height) 0 1rem; padding: var(--tui-nav-height) 0 1rem;
.records {
.item { gap: .5rem;
margin: .75rem;
.avatar { display: flex;
width: 3.5rem; flex-direction: column;
height: 3.5rem;
}
.title {
gap: .25rem;
display: flex;
font-size: .75rem;
align-items: center;
justify-content: space-between;
.customer {
font-weight: 600;
}
.type {
font-weight: 700;
&.receive {
color: #15803d;
}
&.refund {
color: #dc2626;
}
&.confirm-no-refund {
color: #2563eb;
}
&.revoke {
color: #7c3aed;
}
}
}
.description {
display: flex;
align-items: start;
justify-content: space-between;
.operator {
gap: 0;
color: var(--td-text-color-secondary);
display: flex;
font-size: .75rem;
flex-wrap: wrap;
line-height: 1.5;
flex-direction: column;
.field {
gap: .25rem;
display: inline-flex;
}
.label {
color: var(--td-text-color-placeholder);
}
}
.amounts {
display: flex;
font-size: .75rem;
line-height: 1.5;
align-items: end;
flex-direction: column;
.label {
color: var(--td-text-color-placeholder);
}
.order-amount,
.unpaid-amount,
.record-amount {
display: flex;
align-items: baseline;
white-space: nowrap;
}
}
}
}
}
:deep(.sales-order-record-list .avatar .t-image__img) {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: inherit;
}
:global(html.theme-dark) .sales-order-record-list {
.fallback {
background: #115e59;
} }
.operation-type {
&.receive {
color: #86efac;
}
&.refund {
color: #fca5a5;
}
&.confirm-no-refund {
color: #93c5fd;
}
&.revoke {
color: #c4b5fd;
}
}
} }
</style> </style>
+3 -3
View File
@@ -603,7 +603,7 @@ onMounted(() => {
.sales-order-create { .sales-order-create {
gap: 1rem; gap: 1rem;
display: flex; display: flex;
padding: calc(var(--tui-nav-height) + 1rem) 0 calc(6.5rem + env(safe-area-inset-bottom, 0)); padding: calc(var(--tui-nav-height) + 1rem) 0 calc(6.5rem + var(--tui-safe-bottom, 0px));
flex-direction: column; flex-direction: column;
.form { .form {
@@ -753,10 +753,10 @@ onMounted(() => {
left: 1.5rem; left: 1.5rem;
right: 1.5rem; right: 1.5rem;
border: 1px solid rgba(0, 0, 0, .05); border: 1px solid rgba(0, 0, 0, .05);
bottom: calc(env(safe-area-inset-bottom, 0) + 1rem); bottom: calc(var(--tui-safe-bottom, 0px) + 1rem);
z-index: 12; z-index: 12;
display: flex; display: flex;
padding: .5rem 1rem calc(.5rem + env(safe-area-inset-bottom, 0)) 1rem; padding: .5rem 1rem calc(.5rem + var(--tui-safe-bottom, 0px)) 1rem;
position: fixed; position: fixed;
align-items: center; align-items: center;
border-radius: 1.75rem; border-radius: 1.75rem;
+21 -2
View File
@@ -27,7 +27,20 @@
<h1 class="no selectable" v-text="order.orderNo" /> <h1 class="no selectable" v-text="order.orderNo" />
<div class="meta"> <div class="meta">
<time-label class="time" :timestamp="order.purchasedAt" underline /> <time-label class="time" :timestamp="order.purchasedAt" underline />
<div class="amount red text-bold"> <div v-if="order.orderType === 'RECYCLE'" class="amount red text-bold">
<t-tag
class="recycle"
size="small"
theme="primary"
variant="light-outline"
:content="order.recycleItemName || '未命名回收物'"
/>
<strong class="value">
<span class="word-space" v-text="order.recycleRequiredQuantity ?? '-'" />
<span v-text="order.recycleUnit || ''" />
</strong>
</div>
<div v-else class="amount red text-bold">
<span>¥</span> <span>¥</span>
<strong class="value" v-text="formatPackageAmount(order.saleAmount)" /> <strong class="value" v-text="formatPackageAmount(order.saleAmount)" />
</div> </div>
@@ -120,7 +133,6 @@
class="red" class="red"
v-text="`¥${formatPackageAmount(item.lineAmount)}`" v-text="`¥${formatPackageAmount(item.lineAmount)}`"
/> />
<t-tag v-else size="small" content="套餐权益" />
<product-sku-tags <product-sku-tags
:product-name="item.productNameSnapshot" :product-name="item.productNameSnapshot"
:snapshot="item.skuSpecSnapshot" :snapshot="item.skuSpecSnapshot"
@@ -667,10 +679,17 @@ watch(() => [props.orderId, route.params.id], loadData);
} }
.amount { .amount {
gap: .25rem;
display: flex;
align-items: baseline;
.value { .value {
font-size: 1.5rem; font-size: 1.5rem;
} }
.recycle {
transform: translateY(-.25rem);
}
} }
} }
} }
@@ -0,0 +1,199 @@
<template>
<div class="item">
<div class="header">
<t-image v-if="getCustomerPhotoURL(item.customer, 64)" :src="getCustomerPhotoURL(item.customer, 64)"
:alt="getCustomerText(item)" fit="cover" class="avatar" />
<div v-else class="avatar fallback" v-text="getCustomerText(item).slice(0, 1)" />
<div class="main">
<div class="customer-status">
<strong class="customer clip-text" v-text="getCustomerText(item)" />
<div class="tags">
<t-tag
size="small"
variant="light"
:theme="item.operationType === 'RECEIVE' ? 'success' : item.operationType === 'REFUND' ? 'danger' : 'default'"
:content="getFundOperationText(item.operationType)"
/>
<t-tag size="small" :content="getRecordStatusText(item)" variant="light-outline"
:theme="getRecordStatusTheme(item)" />
</div>
</div>
<div class="record-line">
<time-label class="time" :timestamp="item.occurredAt" underline />
<div class="amount">
<span class="red">¥</span>
<strong class="value red" v-text="formatPackageAmount(item.amount)" />
</div>
</div>
</div>
</div>
<t-divider />
<div class="amounts">
<span>订单总价 <strong v-text="`¥${formatPackageAmount(item.salesOrderAmount)}`" /></span>
<span>剩余待收 <strong v-text="`¥${formatPackageAmount(item.salesOrderUnpaidAmountSnapshot)}`" /></span>
</div>
<t-divider />
<div class="people-actions">
<div class="person"><span class="label">发起人</span><strong v-text="getOperatorText(item)" /></div>
<div v-if="item.verifier" class="person"><span class="label">核销人</span><strong
v-text="getVerifierText(item)" /></div>
<div class="actions">
<t-button theme="primary" size="extra-small" content="详情" @click.stop="emit('detail')" />
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { TimeLabel } from "timi-web";
import type { FundRecord, FundRecordStatus } from "@/types/SalesOrder";
import { getCustomerPhotoURL } from "@/utils/customer";
import { formatPackageAmount } from "@/utils/package";
import { getFundOperationText, getFundStatusText } from "@/utils/salesOrder";
defineOptions({ name: "FundRecordListCell" });
defineProps<{ item: FundRecord }>();
const emit = defineEmits<{ detail: [] }>();
function getOperatorText(item: FundRecord): string {
return item.operator?.nick || item.operator?.name || item.operatorUserId || "未知";
}
function getVerifierText(item: FundRecord): string {
return item.verifier?.nick || item.verifier?.name || item.verifierUserId || "未核销";
}
function getCustomerText(item: FundRecord): string {
return item.customer?.name || item.customer?.code || item.customerId || "未知客户";
}
function getStatusTheme(statusValue?: FundRecordStatus): "success" | "warning" | "danger" | "default" {
return statusValue === "VERIFIED" ? "success" : statusValue === "PENDING" ? "warning" : statusValue === "REJECTED" ? "danger" : "default";
}
function getRecordStatusText(item: FundRecord): string {
return item.revokeRecordId ? "已被冲正" : getFundStatusText(item.status);
}
function getRecordStatusTheme(item: FundRecord): "success" | "warning" | "danger" | "default" {
return item.revokeRecordId ? "danger" : getStatusTheme(item.status);
}
</script>
<style scoped lang="less">
.item {
gap: .5rem;
padding: .625rem;
display: flex;
background: var(--td-bg-color-container);
flex-direction: column;
border-radius: 1rem;
.header {
gap: .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;
}
.record-line {
.time {
color: var(--td-text-color-secondary);
font-size: .75rem;
}
.amount {
.value {
font-size: 1.25rem;
}
}
}
}
.amounts {
gap: 1rem;
display: flex;
font-size: .75rem;
flex-wrap: wrap;
}
.people-actions {
gap: .75rem;
display: flex;
align-items: center;
justify-content: space-between;
.person {
gap: .25rem;
display: flex;
min-width: 0;
font-size: .75rem;
align-items: baseline;
.label {
color: var(--td-text-color-secondary);
flex: 0 0 auto;
}
strong {
max-width: 10rem;
overflow: hidden;
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;
}
}
}
}
:deep(.avatar .t-image__img) {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: inherit;
}
:global(html.theme-dark) .item .fallback {
background: #115e59;
}
</style>
+79 -58
View File
@@ -1,5 +1,5 @@
<template> <template>
<div class="tui-page-layout tui-navbar"> <div class="tui-page-layout tui-navbar about">
<t-navbar <t-navbar
fixed fixed
:z-index="20" :z-index="20"
@@ -7,47 +7,65 @@
left-arrow left-arrow
@left-click="$router.back()" @left-click="$router.back()"
/> />
<main class="tui-page-content scroll column"> <master-detail-page
<div class="about-page"> class="list"
<section class="brand" v-entrance-transition> :split="isWide"
<logo @click="handleLogoClick" /> :selected="!!selectedId"
<h1 v-text="appName" /> :direction="paneDirection"
<p v-text="`版本 ${displayVersion}`" /> >
<p v-text="appDescription" /> <template #master>
</section> <div class="about-page tui-page-content column">
<t-cell-group v-if="agreementItemList.length" theme="card" v-entrance-transition> <section class="brand" v-entrance-transition>
<t-cell <logo @click="handleLogoClick" />
v-for="item in agreementItemList" <h1 v-text="appName" />
:key="item.id" <p class="version" v-text="`版本 ${displayVersion}`" />
:title="item.title" <p class="description" v-text="appDescription" />
arrow </section>
hover <t-cell-group
@click="openAgreement(item)" v-if="agreementItemList.length"
theme="card"
v-entrance-transition
> >
<template #leftIcon> <t-cell
<t-icon :name="item.icon" size="1.75rem" /> v-for="item in agreementItemList"
</template> :key="item.id"
</t-cell> :title="item.title"
</t-cell-group> arrow
<t-empty hover
v-else @click="openAgreement(item)"
:description="isLoading ? '正在加载协议配置' : '暂无可用协议'" >
<template #leftIcon>
<t-icon :name="item.icon" size="1.75rem" />
</template>
</t-cell>
</t-cell-group>
<t-empty
v-else
:description="isLoading ? '正在加载协议配置' : '暂无可用协议'"
/>
<t-cell-group theme="card" v-entrance-transition>
<t-cell title="版本更新" arrow hover @click="openDetail('update')">
<template #leftIcon>
<t-icon name="download" size="1.75rem" />
</template>
</t-cell>
</t-cell-group>
<footer class="footer" v-entrance-transition>
<p>技术支持:夜雨</p>
<p>联系技术:imyeyu@qq.com</p>
<p>短信服务支持:广州易保网络科技有限公司</p>
<p>Copyright © 2026 imyeyu.com</p>
</footer>
</div>
</template>
<template #detail>
<app-update v-if="selectedId === 'update'" />
<agreement
v-else-if="selectedId?.startsWith('agreement:')"
:article-id="selectedId.slice(10)"
/> />
<t-cell-group v-if="updateSupported" theme="card" v-entrance-transition> </template>
<t-cell title="版本更新" arrow hover @click="router.push({ name: 'AppUpdate' })"> </master-detail-page>
<template #leftIcon>
<t-icon name="download" size="1.75rem" />
</template>
</t-cell>
</t-cell-group>
<footer class="footer" v-entrance-transition>
<p>技术支持:夜雨</p>
<p>联系技术:imyeyu@qq.com</p>
<p>短信服务支持:广州易保网络科技有限公司</p>
<p>Copyright © 2026 imyeyu.com</p>
</footer>
</div>
</main>
</div> </div>
</template> </template>
@@ -55,6 +73,9 @@
import { version } from "../../../package.json"; import { version } from "../../../package.json";
import { useAppUpdate } from "@/composables/useAppUpdate"; import { useAppUpdate } from "@/composables/useAppUpdate";
import { SettingAPI } from "timi-web-api"; import { SettingAPI } from "timi-web-api";
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile";
import Agreement from "@/pages/setting/Agreement.vue";
import AppUpdate from "@/pages/setting/AppUpdate.vue";
import Logo from "@/pages/user/component/Logo.vue"; import Logo from "@/pages/user/component/Logo.vue";
import { getErrorMessage } from "@/utils/error"; import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message"; import { Message } from "@/utils/message";
@@ -71,9 +92,12 @@ defineOptions({
}); });
const appName = "糕店客户管理"; const appName = "糕店客户管理";
const appDescription = "面向门店的客户、登记、积分与经营管理工具"; const appDescription = "融合客户服务、门店经营与 AI 智能助手的一体化管理平台";
const router = useRouter(); const { selectedId, paneDirection, isWide, openDetail } = useMasterDetailPane({
const { supported: updateSupported, currentVersion, loadCurrent } = useAppUpdate(); path: "/management/about",
detail: id => id === "update" ? "/management/about/update" : `/management/about/agreement/${encodeURIComponent(id.slice(10))}`
});
const { currentVersion, loadCurrent } = useAppUpdate();
const displayVersion = computed(() => currentVersion.value && currentVersion.value !== "builtin" ? currentVersion.value : version); const displayVersion = computed(() => currentVersion.value && currentVersion.value !== "builtin" ? currentVersion.value : version);
const agreementItemList = ref<AgreementItem[]>([]); const agreementItemList = ref<AgreementItem[]>([]);
@@ -81,13 +105,8 @@ const isLoading = ref(false);
const handleLogoClick = createVConsoleClickHandler(toggleVConsole); const handleLogoClick = createVConsoleClickHandler(toggleVConsole);
async function openAgreement(item: AgreementItem): Promise<void> { function openAgreement(item: AgreementItem): void {
await router.push({ openDetail(`agreement:${item.id}`);
name: "Agreement",
params: {
id: item.id
}
});
} }
function normalizeAgreementItem(value: unknown): AgreementItem | undefined { function normalizeAgreementItem(value: unknown): AgreementItem | undefined {
@@ -145,10 +164,6 @@ onMounted(async () => {
<style scoped lang="less"> <style scoped lang="less">
.about-page { .about-page {
gap: 1rem;
display: flex;
padding: 0 0 5rem;
flex-direction: column;
.brand { .brand {
padding: 1rem; padding: 1rem;
@@ -159,22 +174,28 @@ onMounted(async () => {
} }
h1 { h1 {
margin: .875rem 0 .5rem;
color: #0f172a; color: #0f172a;
margin: .875rem 0 .5rem;
font-size: 1.5rem; font-size: 1.5rem;
font-weight: 700; font-weight: 700;
} }
p { p {
margin: 0;
color: #52607a; color: #52607a;
margin: 0;
}
.version {
font-size: .875rem; font-size: .875rem;
line-height: 1.7; }
.description {
font-size: .75rem;
} }
} }
.footer { .footer {
padding: 1.25rem 1rem calc(1rem + env(safe-area-inset-bottom, 0)); padding: 1.25rem 1rem calc(1rem + var(--tui-safe-bottom, 0px));
text-align: center; text-align: center;
p { p {
+38 -46
View File
@@ -1,41 +1,40 @@
<template> <template>
<div class="tui-page-layout tui-navbar"> <div class="tui-page-layout tui-navbar agreement">
<t-navbar <t-navbar
fixed fixed
:z-index="20" :z-index="20"
:title="routeNavBarTitle" :title="routeNavBarTitle"
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 bg-white">
<div class="agreement-page"> <template v-if="article">
<template v-if="article"> <header class="header" v-entrance-transition>
<header class="header" v-entrance-transition> <h3 v-text="article.title || '协议'" />
<h3 v-text="article.title || '协议'" /> <markdown-view
<markdown-view v-if="article.description"
v-if="article.description" class="description"
class="description" :content="article.description"
:content="article.description"
/>
</header>
<article-view
:article="article"
empty-text="暂无协议正文"
:resolve-attachment-url="resolveAttachmentUrl"
/> />
</template> </header>
<t-empty <article-view
v-else :article="article"
:description="isLoading ? '正在加载协议' : '协议不存在'" empty-text="暂无协议正文"
:resolve-attachment-url="resolveAttachmentUrl"
v-entrance-transition
/> />
</div> </template>
<t-empty
v-else
:description="isLoading ? '正在加载协议' : '协议不存在'"
/>
</main> </main>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { type Article, ArticleAPI, AttachmentAPI } from "timi-web-api"; import { type Article, ArticleAPI, AttachmentAPI } from "timi-web-api";
import { ArticleView } from "timi-tdesign-mobile"; import { ArticleView, usePane } from "timi-tdesign-mobile";
import { MarkdownView } from "timi-web"; import { MarkdownView } from "timi-web";
import { getErrorMessage } from "@/utils/error"; import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message"; import { Message } from "@/utils/message";
@@ -45,6 +44,17 @@ defineOptions({
}); });
const route = useRoute(); const route = useRoute();
const router = useRouter();
const pane = usePane();
const props = defineProps<{ articleId?: string }>();
function goBack(): void {
if (pane) {
pane.close();
return;
}
router.back();
}
const routeNavBarTitle = computed(() => { const routeNavBarTitle = computed(() => {
switch (route.name) { switch (route.name) {
@@ -57,7 +67,7 @@ const routeNavBarTitle = computed(() => {
case "OpenSourceAgreement": case "OpenSourceAgreement":
return "开源软件协议"; return "开源软件协议";
default: default:
return ""; return "协议";
} }
}); });
const article = ref<Article>(); const article = ref<Article>();
@@ -72,7 +82,7 @@ async function loadArticle(): Promise<void> {
const requestToken = loadToken + 1; const requestToken = loadToken + 1;
loadToken = requestToken; loadToken = requestToken;
article.value = undefined; article.value = undefined;
const articleId = String(route.params.id || "").trim(); const articleId = String(props.articleId || route.params.id || "").trim();
if (!articleId) { if (!articleId) {
return; return;
} }
@@ -93,30 +103,26 @@ async function loadArticle(): Promise<void> {
} }
} }
watch(() => route.params.id, async () => { watch(() => props.articleId || route.params.id, async () => {
await loadArticle(); await loadArticle();
}, { immediate: true }); }, { immediate: true });
</script> </script>
<style scoped lang="less"> <style scoped lang="less">
.agreement-page { .agreement {
padding: 0 0 1rem 0;
.header { .header {
padding: .5rem 1rem; padding: 0 1rem;
h3 { h3 {
color: #0f172a; color: #0f172a;
margin: 0; margin: 0;
text-align: center; text-align: center;
line-height: 1.4;
} }
.description { .description {
color: #52607a; color: #52607a;
font-size: .875rem; font-size: .875rem;
margin-top: .5rem;
line-height: 1.7;
} }
} }
@@ -124,18 +130,4 @@ watch(() => route.params.id, async () => {
border: none; border: none;
} }
} }
:global(html.theme-dark) {
.agreement-page {
.header {
h1 {
color: #e2e8f0;
}
.description {
color: #94a3b8;
}
}
}
}
</style> </style>
+186 -17
View File
@@ -1,11 +1,16 @@
<template> <template>
<div class="tui-page-layout tui-navbar"> <div class="tui-page-layout tui-navbar app-update">
<t-navbar fixed :z-index="20" title="版本更新" left-arrow @left-click="$router.back()" /> <t-navbar
fixed
:z-index="20"
title="版本更新"
left-arrow
@left-click="goBack"
/>
<main class="tui-page-content scroll column"> <main class="tui-page-content scroll column">
<center-tips v-if="!updateSupported" content="仅在 App 内可用" /> <t-cell-group v-if="updateSupported" theme="card" v-entrance-transition>
<t-cell-group v-if="updateSupported" title="版本更新" theme="card" v-entrance-transition>
<t-cell title="外壳版本" :note="nativeVersion || '—'" /> <t-cell title="外壳版本" :note="nativeVersion || '—'" />
<t-cell title="系统版本" :note="currentVersion || '—'" /> <t-cell title="系统版本" :note="displayVersion" />
<t-cell v-if="latestVersionText" title="最新版本" :note="latestVersionText" /> <t-cell v-if="latestVersionText" title="最新版本" :note="latestVersionText" />
<t-cell title="自动更新"> <t-cell title="自动更新">
<template #right-icon> <template #right-icon>
@@ -13,6 +18,9 @@
</template> </template>
</t-cell> </t-cell>
</t-cell-group> </t-cell-group>
<t-cell-group v-else theme="card" v-entrance-transition>
<t-cell title="系统版本" :note="displayVersion" />
</t-cell-group>
<div v-if="updateSupported" class="update-panel" v-entrance-transition> <div v-if="updateSupported" class="update-panel" v-entrance-transition>
<center-tips v-if="updateHint"><span v-text="updateHint" /></center-tips> <center-tips v-if="updateHint"><span v-text="updateHint" /></center-tips>
<t-button <t-button
@@ -25,6 +33,20 @@
> >
检查更新 检查更新
</t-button> </t-button>
<template v-else-if="updateStage === 'shell-error'">
<center-tips><span v-text="shellError" /></center-tips>
<t-button class="cell-button" theme="primary" size="large" @click="handleShellDownload">重试</t-button>
<t-button class="cell-button" size="large" @click="openShellDownload">用浏览器下载</t-button>
</template>
<t-button
v-else-if="updateStage === 'shell'"
class="cell-button"
theme="primary"
size="large"
@click="handleShellDownload"
>
下载安装包
</t-button>
<t-button <t-button
v-else-if="updateStage === 'download'" v-else-if="updateStage === 'download'"
class="cell-button" class="cell-button"
@@ -35,10 +57,14 @@
下载更新 下载更新
</t-button> </t-button>
<template v-else-if="updateStage === 'downloading'"> <template v-else-if="updateStage === 'downloading'">
<t-progress class="progress" stroke-width=".5rem" :percentage="percent" /> <t-progress class="progress" stroke-width=".5rem" :percentage="shellDownloading ? shellPercent : percent" />
<t-button class="cell-button" theme="primary" size="large" disabled> <t-button
<span v-text="`下载中 ${percent}%`" /> class="cell-button"
</t-button> theme="primary"
size="large"
disabled
content="正在下载.."
/>
</template> </template>
<t-button <t-button
v-else-if="updateStage === 'apply'" v-else-if="updateStage === 'apply'"
@@ -50,18 +76,72 @@
现在更新 现在更新
</t-button> </t-button>
</div> </div>
<section v-if="noteList.length" class="versions">
<h2 class="title" v-text="noteTitle" />
<timeline>
<timeline-item
class="version"
v-for="item in noteList"
:key="item.version"
v-entrance-transition
>
<template #label>
<div class="label">
<t-tag
size="small"
theme="primary"
variant="light-outline"
:content="item.version"
/>
<time-label class="time" :timestamp="item.publishedAt" />
</div>
</template>
<markdown-view class="content bg-white" :content="item.note" />
</timeline-item>
<timeline-item v-entrance-transition>
<template #label>
<div class="label">
<t-tag
size="small"
theme="primary"
variant="light-outline"
content="..."
/>
</div>
</template>
</timeline-item>
</timeline>
</section>
</main> </main>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { setAutoUpdate, useAppUpdate } from "@/composables/useAppUpdate"; import { version } from "../../../package.json";
import { Capacitor } from "@capacitor/core";
import { Timeline, TimelineItem, usePane } from "timi-tdesign-mobile";
import { MarkdownView, TimeLabel } from "timi-web";
import AppUpdateAPI from "@/api/AppUpdateAPI";
import { APP_ID, setAutoUpdate, useAppUpdate } from "@/composables/useAppUpdate";
import { useShellUpdate } from "@/composables/useShellUpdate";
import type { AppUpdateNote } from "@/types/AppUpdate";
import { Message } from "@/utils/message"; import { Message } from "@/utils/message";
defineOptions({ defineOptions({
name: "AppUpdate" name: "AppUpdate"
}); });
const router = useRouter();
const pane = usePane();
function goBack(): void {
if (pane) {
pane.close();
return;
}
router.back();
}
// ---------- 版本更新 ---------- // ---------- 版本更新 ----------
const { const {
@@ -78,19 +158,31 @@ const {
loadCurrent, loadCurrent,
check, check,
hasUpdate, hasUpdate,
isShellUpdate,
openShellDownload,
download, download,
apply, apply,
restorePending restorePending
} = useAppUpdate(); } = useAppUpdate();
const { downloading: shellDownloading, percent: shellPercent, error: shellError, start: startShellUpdate } = useShellUpdate(latest);
/** 系统版本:原生端优先取热更包版本,未热更过或 web 端回落到构建版本 */
const displayVersion = computed<string>(
() => (currentVersion.value && currentVersion.value !== "builtin" ? currentVersion.value : version)
);
/** 有更新时展示目标版本号 */ /** 有更新时展示目标版本号 */
const latestVersionText = computed<string>(() => (hasUpdate() ? `v${latest.value?.version ?? ""}` : "")); const latestVersionText = computed<string>(() => (hasUpdate() ? `v${latest.value?.version ?? ""}` : ""));
/** 当前所处的更新阶段 */ /** 当前所处的更新阶段 */
const updateStage = computed<"check" | "download" | "downloading" | "apply">(() => { const updateStage = computed<"check" | "shell" | "shell-error" | "download" | "downloading" | "apply">(() => {
if (downloading.value) { if (downloading.value || shellDownloading.value) {
return "downloading"; return "downloading";
} }
if (isShellUpdate()) {
return shellError.value ? "shell-error" : "shell";
}
if (ready.value) { if (ready.value) {
return "apply"; return "apply";
} }
@@ -105,6 +197,9 @@ const updateHint = computed<string>(() => {
if (!updateSupported) { if (!updateSupported) {
return "仅在 App 内可用"; return "仅在 App 内可用";
} }
if (isShellUpdate()) {
return `发现新版本 v${latest.value?.version ?? ""},需要下载安装包覆盖安装`;
}
if (ready.value) { if (ready.value) {
return `v${ready.value.version} 已下载,点击下方按钮重启生效`; return `v${ready.value.version} 已下载,点击下方按钮重启生效`;
} }
@@ -117,11 +212,44 @@ const updateHint = computed<string>(() => {
return ""; return "";
}); });
// ---------- 更新日志 ----------
/** web 端只展示最近几个版本 */
const WEB_NOTE_LIMIT = 3;
const noteList = ref<AppUpdateNote[]>([]);
/** 有更新时展示区间日志,已是最新时展示最近几个版本 */
const noteTitle = computed<string>(() => (hasUpdate() ? "更新内容" : "最近更新"));
/** 查询当前版本到通道最新版本之间的变更说明 */
async function loadNotes(): Promise<void> {
try {
const result = await AppUpdateAPI.notes({
appId: APP_ID,
// web 端没有热更包版本,从内置包开始算,后端会返回通道的完整历史
versionName: updateSupported ? currentVersion.value || "builtin" : "builtin",
platform: Capacitor.getPlatform(),
channel: "stable"
});
const list = result?.notes ?? [];
noteList.value = updateSupported ? list : list.slice(0, WEB_NOTE_LIMIT);
} catch {
// 日志不是关键路径,失败时安静降级,不弹错误
noteList.value = [];
}
}
// ---------- 生命周期 ----------
onMounted(async () => { onMounted(async () => {
await loadCurrent(); await loadCurrent();
await restorePending(); await restorePending();
await loadNotes();
}); });
// ---------- 交互 ----------
function handleAutoUpdateChange(value: boolean | string | number): void { function handleAutoUpdateChange(value: boolean | string | number): void {
setAutoUpdate(value === true); setAutoUpdate(value === true);
} }
@@ -135,6 +263,13 @@ async function handleCheck(): Promise<void> {
if (!hasUpdate()) { if (!hasUpdate()) {
Message.info("已是最新版本"); Message.info("已是最新版本");
} }
// 检查后目标版本可能变化,重查一次日志
await loadNotes();
}
/** 外壳更新:优先使用原生安装能力 */
async function handleShellDownload(): Promise<void> {
await startShellUpdate();
} }
async function handleDownload(): Promise<void> { async function handleDownload(): Promise<void> {
@@ -152,18 +287,52 @@ async function handleApply(): Promise<void> {
return; return;
} }
await apply(bundle); await apply(bundle);
// 应用成功会直接重启,走到这里说明包是坏的,已经清理掉,提示后可以重新检查
if (updateError.value) {
Message.error(`更新失败:${updateError.value}`);
}
} }
</script> </script>
<style scoped lang="less"> <style scoped lang="less">
.update-panel { .app-update {
gap: .75rem;
display: flex;
flex-direction: column;
.progress { .progress {
margin: 0 1rem; margin: 0 1rem;
} }
.versions {
gap: .5rem;
display: flex;
padding: .25rem 1rem 1rem;
flex-direction: column;
.title {
color: var(--td-text-color-secondary);
margin: .5rem .25rem 0;
font-size: .8125rem;
font-weight: 500;
}
.version {
.label {
gap: .5rem;
display: flex;
align-items: center;
.time {
font-size: .875rem;
}
}
.content {
padding: .5rem;
font-size: .875rem;
margin-top: .5rem;
border-radius: 1rem;
}
}
}
} }
</style> </style>
+1 -1
View File
@@ -265,7 +265,7 @@ watch(() => [props.diaryId, route.params.id], () => {
<style scoped lang="less"> <style scoped lang="less">
.store-diary-detail { .store-diary-detail {
padding: 0 0 calc(1rem + env(safe-area-inset-bottom, 0)); padding: 0 0 calc(1rem + var(--tui-safe-bottom, 0px));
.header { .header {
margin: 0 1rem; margin: 0 1rem;
+1 -1
View File
@@ -262,7 +262,7 @@ async function removeStore(id: string): Promise<void> {
<style scoped lang="less"> <style scoped lang="less">
.store-edit { .store-edit {
gap: 1rem; gap: 1rem;
padding: 0 0 calc(1rem + env(safe-area-inset-bottom, 0)) 0; padding: 0 0 calc(1rem + var(--tui-safe-bottom, 0px)) 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
-3
View File
@@ -7,7 +7,6 @@
title="客户" title="客户"
> >
<template #right> <template #right>
<app-update-button />
<navbar-notify-button /> <navbar-notify-button />
</template> </template>
</t-navbar> </t-navbar>
@@ -32,7 +31,6 @@
<store-overview ref="storeOverviewRef" compact /> <store-overview ref="storeOverviewRef" compact />
</template> </template>
<template #right-actions> <template #right-actions>
<app-update-button />
<navbar-notify-button /> <navbar-notify-button />
</template> </template>
<template #right> <template #right>
@@ -55,7 +53,6 @@ import { useLayout } from "timi-tdesign-mobile";
import PendingNoticeBar from "./component/PendingNoticeBar.vue"; import PendingNoticeBar from "./component/PendingNoticeBar.vue";
import CustomerEntryPanel from "./component/CustomerEntryPanel.vue"; import CustomerEntryPanel from "./component/CustomerEntryPanel.vue";
import NavbarNotifyButton from "./component/NavbarNotifyButton.vue"; import NavbarNotifyButton from "./component/NavbarNotifyButton.vue";
import AppUpdateButton from "./component/AppUpdateButton.vue";
import StoreOverview from "./component/StoreOverview.vue"; import StoreOverview from "./component/StoreOverview.vue";
import TabSplitView from "./component/TabSplitView.vue"; import TabSplitView from "./component/TabSplitView.vue";
import { permissionCodes } from "@/utils/permission"; import { permissionCodes } from "@/utils/permission";
+7 -1
View File
@@ -149,6 +149,12 @@ const menuGroupList = computed<MenuGroup[]>(() => [
title: "客户邀请关系", title: "客户邀请关系",
visible: userStore.hasPermissions(permissionCodes.customer.read) visible: userStore.hasPermissions(permissionCodes.customer.read)
}, },
{
icon: "layers",
path: "/management/customer-recycle-accounts",
title: "客户回收物",
visible: userStore.hasPermissions(permissionCodes.recycleAccount.read)
},
{ {
icon: "chart-combo", icon: "chart-combo",
path: "/management/customer-data-charts", path: "/management/customer-data-charts",
@@ -385,7 +391,7 @@ onBeforeRouteLeave(() => {
} }
.footer { .footer {
padding: 1.25rem 1rem calc(1rem + env(safe-area-inset-bottom, 0)); padding: 1.25rem 1rem calc(1rem + var(--tui-safe-bottom, 0px));
text-align: center; text-align: center;
p { p {
@@ -1,32 +0,0 @@
<template>
<t-button
v-if="visible"
aria-label="有新版本"
@click="router.push('/management/settings')"
theme="default"
shape="square"
variant="text"
size="small"
>
<t-badge dot :offset="[-4, 4]">
<t-icon name="download" size="1.25rem" />
</t-badge>
</t-button>
</template>
<script setup lang="ts">
import { useAppUpdate } from "@/composables/useAppUpdate";
defineOptions({
name: "AppUpdateButton"
});
const router = useRouter();
const { supported, latest, autoUpdate, hasUpdate } = useAppUpdate();
// 只在有更新且未开启自动更新时出现,开启自动更新后由启动弹窗负责提醒
const visible = computed(() => {
void latest.value;
return supported && hasUpdate() && !autoUpdate.value;
});
</script>
+36 -6
View File
@@ -1,13 +1,14 @@
<template> <template>
<t-notice-bar <t-notice-bar
v-if="noticeContent.length" v-if="noticeList.length"
:key="noticeContent.join(',')" :key="noticeContent.join(',')"
class="pending-notice" class="pending-notice"
theme="warning" theme="warning"
:visible="true" :visible="true"
direction="vertical" direction="vertical"
:interval="4000"
:content="1 < noticeContent.length ? noticeContent : noticeContent[0]" :content="1 < noticeContent.length ? noticeContent : noticeContent[0]"
@change="currentIndex = $event" @change="handleChange"
@click="openNotice" @click="openNotice"
> >
<template #suffix-icon> <template #suffix-icon>
@@ -17,17 +18,42 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { useAppUpdate } from "@/composables/useAppUpdate";
import { usePendingNoticeStore } from "@/store/pendingNoticeStore"; import { usePendingNoticeStore } from "@/store/pendingNoticeStore";
const pendingNoticeStore = usePendingNoticeStore(); const pendingNoticeStore = usePendingNoticeStore();
const router = useRouter(); const router = useRouter();
const currentIndex = ref(0); const { supported, latest, autoUpdate, hasUpdate, isShellUpdate } = useAppUpdate();
const noticeContent = computed(() => pendingNoticeStore.pendingNoticeList.map(notice => notice.content)); const noticeList = computed(() => {
const notices = [...pendingNoticeStore.pendingNoticeList];
if (supported && hasUpdate() && latest.value) {
// 外壳更新不会自动下载,自动更新开着也必须提示;热更开着开关就不提示了
const shell = isShellUpdate();
if (shell || !autoUpdate.value) {
notices.push({
content: shell
? `需要安装新版本 v${latest.value.version},点击前往更新`
: `有可用新版本 v${latest.value.version} 更新`,
name: "AppUpdate",
query: {}
});
}
}
return notices;
});
const noticeContent = computed(() => noticeList.value.map(notice => notice.content));
let currentIndex = 0;
watch(noticeContent, () => { currentIndex.value = 0; }); watch(noticeContent, () => {
currentIndex = 0;
});
function handleChange(index: number): void {
currentIndex = index;
}
async function openNotice(): Promise<void> { async function openNotice(): Promise<void> {
const notice = pendingNoticeStore.pendingNoticeList[currentIndex.value]; const notice = noticeList.value[currentIndex];
if (notice) { if (notice) {
await router.push({ name: notice.name, query: notice.query }); await router.push({ name: notice.name, query: notice.query });
} }
@@ -38,6 +64,10 @@ async function openNotice(): Promise<void> {
.pending-notice { .pending-notice {
margin-top: -1rem; margin-top: -1rem;
:deep(.t-swiper__container) {
transition-duration: .5s !important;
}
:deep(.t-swiper-nav__dots) { :deep(.t-swiper-nav__dots) {
display: none; display: none;
} }
+21 -7
View File
@@ -49,8 +49,8 @@
/> />
</div> </div>
</t-form> </t-form>
<user-agreement v-model="hasAgreed" /> <user-agreement ref="agreementRef" v-model="hasAgreed" @agree="resumeRegister" @reject="cancelRegister" />
<t-button class="submit" theme="primary" size="medium" :loading="isSubmitting" :disabled="isExpired || isSubmitting || !hasAgreed" @click="register">注册并登录</t-button> <t-button class="submit" theme="primary" size="medium" :loading="isSubmitting" :disabled="isExpired || isSubmitting" @click="register">注册并登录</t-button>
</section> </section>
</div> </div>
</template> </template>
@@ -78,6 +78,19 @@ const expireAt = ref(0);
const invalidMessage = ref("邀请码无效或已过期,请联系邀请人重新生成。"); const invalidMessage = ref("邀请码无效或已过期,请联系邀请人重新生成。");
const isSubmitting = ref(false); const isSubmitting = ref(false);
const hasAgreed = ref(false); const hasAgreed = ref(false);
const agreementRef = ref<InstanceType<typeof UserAgreement> | null>(null);
let pendingRegister = false;
async function resumeRegister(): Promise<void> {
if (!pendingRegister) return;
pendingRegister = false;
await nextTick();
await register();
}
function cancelRegister(): void {
pendingRegister = false;
}
const captchaRef = ref<CaptchaExpose | null>(null); const captchaRef = ref<CaptchaExpose | null>(null);
const formModel = reactive({ const formModel = reactive({
phoneNo: "", phoneNo: "",
@@ -196,11 +209,12 @@ async function sendSms(): Promise<void> {
} }
async function register(): Promise<void> { async function register(): Promise<void> {
if (isSubmitting.value || !hasAgreed.value || isExpired.value || !validateForm()) { if (!hasAgreed.value) {
if (!hasAgreed.value) { pendingRegister = true;
Message.warning("请先阅读并同意用户协议"); await agreementRef.value?.open();
return; return;
} }
if (isSubmitting.value || isExpired.value || !validateForm()) {
if (isExpired.value) { if (isExpired.value) {
Message.warning("邀请码已失效,请联系邀请人重新生成"); Message.warning("邀请码已失效,请联系邀请人重新生成");
} }
+23 -3
View File
@@ -11,9 +11,9 @@
:options="loginTypeOptions" :options="loginTypeOptions"
v-entrance-transition v-entrance-transition
/> />
<password-login v-if="loginType === 'password'" class="form card" :agreement-accepted="hasAgreed" /> <password-login v-if="loginType === 'password'" class="form card" :agreement-accepted="hasAgreed" @request-agreement="requestAgreement" />
<sms-login v-else class="form card" :agreement-accepted="hasAgreed" /> <sms-login v-else class="form card" :agreement-accepted="hasAgreed" @request-agreement="requestAgreement" />
<user-agreement v-model="hasAgreed" /> <user-agreement ref="agreementRef" v-model="hasAgreed" @agree="resumeLogin" @reject="cancelLogin" />
</section> </section>
</div> </div>
</template> </template>
@@ -33,6 +33,26 @@ type LoginType = "password" | "sms";
const loginType = ref<LoginType>("password"); const loginType = ref<LoginType>("password");
const hasAgreed = ref(false); const hasAgreed = ref(false);
const agreementRef = ref<InstanceType<typeof UserAgreement> | null>(null);
let pendingLogin: (() => Promise<void>) | undefined;
async function requestAgreement(resume: () => Promise<void>): Promise<void> {
pendingLogin = resume;
await agreementRef.value?.open();
}
async function resumeLogin(): Promise<void> {
const resume = pendingLogin;
pendingLogin = undefined;
await nextTick();
await resume?.();
}
function cancelLogin(): void {
pendingLogin = undefined;
}
watch(loginType, cancelLogin);
const loginTypeOptions = [ const loginTypeOptions = [
{ value: "password" as LoginType, label: "密码登录" }, { value: "password" as LoginType, label: "密码登录" },
{ value: "sms" as LoginType, label: "短信登录" } { value: "sms" as LoginType, label: "短信登录" }
+1 -1
View File
@@ -244,7 +244,7 @@ onMounted(() => {
<style scoped lang="less"> <style scoped lang="less">
.profile-page { .profile-page {
gap: 1rem; gap: 1rem;
padding: 0 0 calc(1rem + env(safe-area-inset-bottom, 0)) 0; padding: 0 0 calc(1rem + var(--tui-safe-bottom, 0px)) 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
+7 -5
View File
@@ -13,7 +13,7 @@
<captcha class="captcha" ref="captchaRef" :width="120" :height="40" :request="CommonAPI.captcha" /> <captcha class="captcha" ref="captchaRef" :width="120" :height="40" :request="CommonAPI.captcha" />
</div> </div>
<div class="exec"> <div class="exec">
<t-button theme="primary" class="button" type="submit" :loading="isSubmitting" :disabled="isSubmitting || !props.agreementAccepted">登录</t-button> <t-button theme="primary" class="button" type="submit" :loading="isSubmitting" :disabled="isSubmitting">登录</t-button>
</div> </div>
</t-form> </t-form>
</template> </template>
@@ -45,6 +45,8 @@ const props = withDefaults(defineProps<{
agreementAccepted: false agreementAccepted: false
}); });
const emit = defineEmits<{ "request-agreement": [resume: () => Promise<void>] }>();
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const userStore = useUserStore(); const userStore = useUserStore();
@@ -62,10 +64,6 @@ function getRedirectPath(): string {
} }
function validateForm(): boolean { function validateForm(): boolean {
if (!props.agreementAccepted) {
Message.warning("请先阅读并同意用户协议");
return false;
}
if (!formModel.user || !formModel.password || !formModel.captcha || !captchaRef.value?.captchaId) { if (!formModel.user || !formModel.password || !formModel.captcha || !captchaRef.value?.captchaId) {
Message.warning("请输入账号、密码和验证码"); Message.warning("请输入账号、密码和验证码");
return false; return false;
@@ -74,6 +72,10 @@ function validateForm(): boolean {
} }
async function login(): Promise<void> { async function login(): Promise<void> {
if (!props.agreementAccepted) {
emit("request-agreement", login);
return;
}
if (isSubmitting.value || !validateForm()) { if (isSubmitting.value || !validateForm()) {
return; return;
} }
+7 -5
View File
@@ -24,7 +24,7 @@
/> />
</div> </div>
<div class="exec"> <div class="exec">
<t-button theme="primary" class="button" type="submit" :loading="isSubmitting" :disabled="isSubmitting || !props.agreementAccepted">登录</t-button> <t-button theme="primary" class="button" type="submit" :loading="isSubmitting" :disabled="isSubmitting">登录</t-button>
</div> </div>
</t-form> </t-form>
</template> </template>
@@ -57,6 +57,8 @@ const props = withDefaults(defineProps<{
agreementAccepted: false agreementAccepted: false
}); });
const emit = defineEmits<{ "request-agreement": [resume: () => Promise<void>] }>();
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const userStore = useUserStore(); const userStore = useUserStore();
@@ -142,10 +144,6 @@ async function sendSms(): Promise<void> {
} }
function validateForm(): boolean { function validateForm(): boolean {
if (!props.agreementAccepted) {
Message.warning("请先阅读并同意用户协议");
return false;
}
if (!/^1\d{10}$/.test(formModel.mobilePhone)) { if (!/^1\d{10}$/.test(formModel.mobilePhone)) {
Message.warning("请输入正确的 11 位手机号"); Message.warning("请输入正确的 11 位手机号");
return false; return false;
@@ -158,6 +156,10 @@ function validateForm(): boolean {
} }
async function login(): Promise<void> { async function login(): Promise<void> {
if (!props.agreementAccepted) {
emit("request-agreement", login);
return;
}
if (isSubmitting.value || !validateForm()) { if (isSubmitting.value || !validateForm()) {
return; return;
} }
+54 -17
View File
@@ -38,7 +38,7 @@
:label="item.title" :label="item.title"
lazy lazy
> >
<div class="agreement-item"> <div class="panel">
<t-loading v-if="item.loading" class="loading" text="正在加载协议" /> <t-loading v-if="item.loading" class="loading" text="正在加载协议" />
<article-view <article-view
v-else-if="item.article" v-else-if="item.article"
@@ -84,6 +84,8 @@ const props = withDefaults(defineProps<{
const emit = defineEmits<{ const emit = defineEmits<{
"update:modelValue": [value: boolean]; "update:modelValue": [value: boolean];
agree: [];
reject: [];
}>(); }>();
const dialogVisible = ref(false); const dialogVisible = ref(false);
@@ -133,6 +135,10 @@ async function handleCheckboxChange(checked: boolean): Promise<void> {
return; return;
} }
await open();
}
async function open(): Promise<void> {
emit("update:modelValue", false); emit("update:modelValue", false);
dialogVisible.value = true; dialogVisible.value = true;
activeAgreementId.value = ""; activeAgreementId.value = "";
@@ -188,12 +194,16 @@ function resolveAttachmentUrl(attachmentId: string): string {
return AttachmentAPI.getReadURL(attachmentId); return AttachmentAPI.getReadURL(attachmentId);
} }
defineExpose({ open });
function rejectAgreement(): void { function rejectAgreement(): void {
emit("update:modelValue", false); emit("update:modelValue", false);
emit("reject");
} }
function agreeAgreement(): void { function agreeAgreement(): void {
emit("update:modelValue", true); emit("update:modelValue", true);
emit("agree");
} }
</script> </script>
@@ -219,22 +229,15 @@ function agreeAgreement(): void {
:global(.user-agreement-dialog.t-dialog .t-dialog__body) { :global(.user-agreement-dialog.t-dialog .t-dialog__body) {
flex: 1 1 auto; flex: 1 1 auto;
min-height: 0;
display: flex; display: flex;
overflow: hidden; overflow: hidden;
min-height: 0;
text-align: unset;
} }
:global(.user-agreement-dialog.t-dialog .t-dialog__body-text) { :global(.user-agreement-dialog.t-dialog .t-dialog__body-text) {
width: 100%; width: 100%;
flex: 1 1 auto; min-width: 0;
min-height: 0;
display: flex;
}
:global(.user-agreement-dialog.t-dialog .t-dialog__footer) {
--td-spacer-1: 0;
--td-button-border-radius: 1rem;
padding: 10px;
} }
.dialog-content { .dialog-content {
@@ -242,6 +245,7 @@ function agreeAgreement(): void {
gap: .5rem; gap: .5rem;
width: 100%; width: 100%;
min-width: 0;
height: 100%; height: 100%;
flex: 1 1 auto; flex: 1 1 auto;
display: flex; display: flex;
@@ -251,12 +255,17 @@ function agreeAgreement(): void {
.tabs { .tabs {
--td-tab-item-height: 2rem; --td-tab-item-height: 2rem;
width: 100%;
flex: 1 1 auto; flex: 1 1 auto;
min-height: 0; width: 100%;
min-width: 0;
display: flex; display: flex;
flex-direction: column;
overflow: hidden; overflow: hidden;
min-height: 0;
flex-direction: column;
:deep(.t-tabs__nav) {
border-bottom: 1px solid var(--td-component-border);
}
:deep(.t-tabs__content) { :deep(.t-tabs__content) {
flex: 1 1 auto; flex: 1 1 auto;
@@ -269,10 +278,13 @@ function agreeAgreement(): void {
padding: 0 .5rem; padding: 0 .5rem;
font-size: .75rem; font-size: .75rem;
} }
:deep(.t-tabs__item--active) {
font-weight: unset;
}
} }
.agreement-item { .panel {
padding-top: 1rem;
.loading { .loading {
padding: 1.5rem 0; padding: 1.5rem 0;
@@ -301,6 +313,31 @@ function agreeAgreement(): void {
} }
} }
@media (orientation: landscape) and (min-width: 48rem) {
:global(.user-agreement-dialog.t-dialog) {
--td-dialog-width: min(80vw, 48rem);
}
.user-agreement-dialog {
:global(.user-agreement-dialog.t-dialog .t-dialog__content) {
height: min(76vh, 36rem);
max-height: min(76vh, 36rem);
}
.dialog-content {
.tips {
br {
display: none;
}
span + span::before {
content: ",";
}
}
}
}
}
:global(html.theme-dark) { :global(html.theme-dark) {
.user-agreement { .user-agreement {
.checkbox { .checkbox {
@@ -310,7 +347,7 @@ function agreeAgreement(): void {
.user-agreement-dialog { .user-agreement-dialog {
.dialog-content { .dialog-content {
.hint { .tips {
color: #94a3b8; color: #94a3b8;
} }
@@ -23,6 +23,17 @@ const followUpReminderRoutes: RouteRecordRaw[] = [
darkBodyBackground: "#10161f" darkBodyBackground: "#10161f"
} }
}, },
{
path: "/management/customer-birthday-reminder-setting",
name: "CustomerBirthdayReminderSetting",
component: () => import("@/pages/followUpReminder/BirthdayReminderSetting.vue"),
meta: {
depth: 4,
tabBarVisible: false,
bodyBackground: "#F5F5F8",
darkBodyBackground: "#10161f"
}
},
{ {
path: "/management/customer-follow-up-reminders/:id", path: "/management/customer-follow-up-reminders/:id",
name: "CustomerFollowUpReminderDetail", name: "CustomerFollowUpReminderDetail",
+6
View File
@@ -76,6 +76,12 @@ export default [
}, },
meta: meta(4) meta: meta(4)
}, },
{
path: "/management/customer-recycle-accounts",
name: "CustomerRecycleList",
component: () => import("@/pages/customer/CustomerRecycleList.vue"),
meta: meta()
},
{ {
path: "/management/recycle-accounts", path: "/management/recycle-accounts",
name: "RecycleAccount", name: "RecycleAccount",
+35
View File
@@ -0,0 +1,35 @@
/**
* 更新日志查询参数
*
* 内部用驼峰,下划线协议字段在 API 层转换,避免业务代码出现 snake_case
*/
export type AppUpdateNotesQuery = {
/** 产品标识,与 capacitor.config.ts 的 appId 一致 */
appId: string;
/** 当前运行的 Web 包版本,内置包为 builtin */
versionName?: string;
/** 当前原生 versionCode */
versionCode?: string;
/** 平台 */
platform?: string;
/** 通道代码 */
channel?: string;
};
/** 单条版本变更说明 */
export type AppUpdateNote = {
/** 版本号 */
version: string;
/** 变更说明,markdown 原文 */
note: string;
/** 首次发布时间,回滚上线的版本可能为空 */
publishedAt?: number;
};
/** 更新日志响应 */
export type AppUpdateNotesResult = {
/** 通道当前版本号,为空表示没有可展示的版本 */
version?: string;
/** 变更说明,按版本号从新到旧 */
notes: AppUpdateNote[];
};
+19
View File
@@ -4,9 +4,24 @@ import type { Customer } from "@/types/Customer";
/** 客户跟进提醒业务状态。 */ /** 客户跟进提醒业务状态。 */
export type FollowUpReminderStatus = "PENDING" | "COMPLETED"; export type FollowUpReminderStatus = "PENDING" | "COMPLETED";
/** 客户跟进提醒来源。 */
export type FollowUpReminderSource = "MANUAL" | "SYSTEM";
/** 客户跟进提醒通知方式。 */ /** 客户跟进提醒通知方式。 */
export type FollowUpReminderNotifyChannel = "INTERNAL" | "SMS"; export type FollowUpReminderNotifyChannel = "INTERNAL" | "SMS";
/** 系统创建提醒的扩展信息快照。 */
export type FollowUpReminderMetadata = {
/** 业务类型,BIRTHDAY 为客户生日提醒 */
bizType?: string;
/** 生日对应的公历日期 */
birthdaySolar?: string;
/** 生日对应的农历月日,仅农历生日有值 */
birthdayLunar?: string;
/** true 为闰月,仅农历生日有值 */
leapMonth?: boolean;
};
/** 跟进提醒附件请求项。 */ /** 跟进提醒附件请求项。 */
export type FollowUpReminderAttachment = Partial<Attachment> & { export type FollowUpReminderAttachment = Partial<Attachment> & {
name?: string; name?: string;
@@ -21,6 +36,10 @@ export type FollowUpReminder = {
content?: string; content?: string;
remindAt?: number; remindAt?: number;
status?: FollowUpReminderStatus; status?: FollowUpReminderStatus;
source?: FollowUpReminderSource;
/** 系统创建的幂等键,手动创建为空 */
sourceKey?: string;
metadata?: FollowUpReminderMetadata;
internalNotifyEnabled?: boolean; internalNotifyEnabled?: boolean;
smsNotifyEnabled?: boolean; smsNotifyEnabled?: boolean;
internalNotifyDetailId?: string; internalNotifyDetailId?: string;
+5 -1
View File
@@ -105,7 +105,11 @@ export type QuickFulfillmentSourceOrderItem = {
export type QuickFulfillmentSourceOrder = { export type QuickFulfillmentSourceOrder = {
id: string; id: string;
orderNo?: string; orderNo?: string;
orderType?: "PACKAGE" | "DIRECT_PRODUCT"; orderType?: "PACKAGE" | "DIRECT_PRODUCT" | "RECYCLE";
recycleItemName?: string | null;
recycleUnit?: string | null;
recycleRequiredQuantity?: number | string | null;
recycleVerifiedQuantity?: number | string | null;
paymentStatus?: GaoSalesPaymentStatus; paymentStatus?: GaoSalesPaymentStatus;
packageName?: string; packageName?: string;
saleAmount?: number | null; saleAmount?: number | null;
+2 -7
View File
@@ -55,12 +55,6 @@ export type ProductSkuUnit = {
sort?: number; sort?: number;
} & Model; } & Model;
export type ProductSkuBaseUnitMigrationRequest = {
targetUnitId?: string;
targetUnitName?: string;
oldToNewBaseRatio: number | string;
};
export type ProductSku = { export type ProductSku = {
storeId?: string; storeId?: string;
productId?: string; productId?: string;
@@ -77,7 +71,8 @@ export type ProductSku = {
updatedBy?: string; updatedBy?: string;
specValueIdList?: string[]; specValueIdList?: string[];
unitList?: ProductSkuUnit[]; unitList?: ProductSkuUnit[];
baseUnitMigrationRequest?: ProductSkuBaseUnitMigrationRequest; /** true 为允许修改基础单位与单位换算系数,SKU 产生业务记录或库存后为 false */
unitEditable?: boolean;
attachmentList?: Attachment[]; attachmentList?: Attachment[];
} & Model; } & Model;
+1 -1
View File
@@ -25,8 +25,8 @@ export type ProductSkuForm = Omit<ProductSku, "unitList"> & {
unitList: ProductSkuUnitForm[]; unitList: ProductSkuUnitForm[];
minStockQuantityText: string; minStockQuantityText: string;
photoItemList: PhotoItem[]; photoItemList: PhotoItem[];
/** 已保存 SKU 的基础单位 ID,用于锁定基础单位不可变更 */
originalBaseUnitId?: string; originalBaseUnitId?: string;
baseUnitMigrationRatioText: string;
}; };
export type ProductForm = Omit<Product, "specList" | "skuList"> & { export type ProductForm = Omit<Product, "specList" | "skuList"> & {
+7
View File
@@ -188,6 +188,13 @@ export type RecycleAccount = {
updatedAt?: number; updatedAt?: number;
}; };
/** 客户回收物分页与按回收物分组的余额汇总。 */
export type RecycleCustomerAccountPage = {
list: { customer: Customer; accounts: RecycleAccount[] }[];
total: number;
totals: RecycleAccount[];
};
/** /**
* 额度流水。 * 额度流水。
* *
+4
View File
@@ -188,6 +188,10 @@ export const corePermissionCodes = {
read: "CORE:NOTIFY:READ", read: "CORE:NOTIFY:READ",
delete: "CORE:NOTIFY:DELETE", delete: "CORE:NOTIFY:DELETE",
cancel: "CORE:NOTIFY:CANCEL" cancel: "CORE:NOTIFY:CANCEL"
},
setting: {
read: "CORE:SETTING:READ",
update: "CORE:SETTING:UPDATE"
} }
} as const; } as const;